Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
862 };
864 static const struct got_error *
865 fetch_progress(void *arg, const char *message, off_t packfile_size,
866 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
868 struct got_fetch_progress_arg *a = arg;
869 char scaled_size[FMT_SCALED_STRSIZE];
870 int p_indexed, p_resolved;
871 int print_size = 0, print_indexed = 0, print_resolved = 0;
873 if (a->verbosity < 0)
874 return NULL;
876 if (message && message[0] != '\0') {
877 printf("\rserver: %s", message);
878 fflush(stdout);
879 return NULL;
882 if (packfile_size > 0 || nobj_indexed > 0) {
883 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
884 (a->last_scaled_size[0] == '\0' ||
885 strcmp(scaled_size, a->last_scaled_size)) != 0) {
886 print_size = 1;
887 if (strlcpy(a->last_scaled_size, scaled_size,
888 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
889 return got_error(GOT_ERR_NO_SPACE);
891 if (nobj_indexed > 0) {
892 p_indexed = (nobj_indexed * 100) / nobj_total;
893 if (p_indexed != a->last_p_indexed) {
894 a->last_p_indexed = p_indexed;
895 print_indexed = 1;
896 print_size = 1;
899 if (nobj_resolved > 0) {
900 p_resolved = (nobj_resolved * 100) /
901 (nobj_total - nobj_loose);
902 if (p_resolved != a->last_p_resolved) {
903 a->last_p_resolved = p_resolved;
904 print_resolved = 1;
905 print_indexed = 1;
906 print_size = 1;
911 if (print_size || print_indexed || print_resolved)
912 printf("\r");
913 if (print_size)
914 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
915 if (print_indexed)
916 printf("; indexing %d%%", p_indexed);
917 if (print_resolved)
918 printf("; resolving deltas %d%%", p_resolved);
919 if (print_size || print_indexed || print_resolved)
920 fflush(stdout);
922 return NULL;
925 static const struct got_error *
926 create_symref(const char *refname, struct got_reference *target_ref,
927 int verbosity, struct got_repository *repo)
929 const struct got_error *err;
930 struct got_reference *head_symref;
932 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
933 if (err)
934 return err;
936 err = got_ref_write(head_symref, repo);
937 got_ref_close(head_symref);
938 if (err == NULL && verbosity > 0) {
939 printf("Created reference %s: %s\n", GOT_REF_HEAD,
940 got_ref_get_name(target_ref));
942 return err;
945 static const struct got_error *
946 list_remote_refs(struct got_pathlist_head *symrefs,
947 struct got_pathlist_head *refs)
949 const struct got_error *err;
950 struct got_pathlist_entry *pe;
952 TAILQ_FOREACH(pe, symrefs, entry) {
953 const char *refname = pe->path;
954 const char *targetref = pe->data;
956 printf("%s: %s\n", refname, targetref);
959 TAILQ_FOREACH(pe, refs, entry) {
960 const char *refname = pe->path;
961 struct got_object_id *id = pe->data;
962 char *id_str;
964 err = got_object_id_str(&id_str, id);
965 if (err)
966 return err;
967 printf("%s: %s\n", refname, id_str);
968 free(id_str);
971 return NULL;
974 static const struct got_error *
975 create_ref(const char *refname, struct got_object_id *id,
976 int verbosity, struct got_repository *repo)
978 const struct got_error *err = NULL;
979 struct got_reference *ref;
980 char *id_str;
982 err = got_object_id_str(&id_str, id);
983 if (err)
984 return err;
986 err = got_ref_alloc(&ref, refname, id);
987 if (err)
988 goto done;
990 err = got_ref_write(ref, repo);
991 got_ref_close(ref);
993 if (err == NULL && verbosity >= 0)
994 printf("Created reference %s: %s\n", refname, id_str);
995 done:
996 free(id_str);
997 return err;
1000 static int
1001 match_wanted_ref(const char *refname, const char *wanted_ref)
1003 if (strncmp(refname, "refs/", 5) != 0)
1004 return 0;
1005 refname += 5;
1008 * Prevent fetching of references that won't make any
1009 * sense outside of the remote repository's context.
1011 if (strncmp(refname, "got/", 4) == 0)
1012 return 0;
1013 if (strncmp(refname, "remotes/", 8) == 0)
1014 return 0;
1016 if (strncmp(wanted_ref, "refs/", 5) == 0)
1017 wanted_ref += 5;
1019 /* Allow prefix match. */
1020 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1021 return 1;
1023 /* Allow exact match. */
1024 return (strcmp(refname, wanted_ref) == 0);
1027 static int
1028 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1030 struct got_pathlist_entry *pe;
1032 TAILQ_FOREACH(pe, wanted_refs, entry) {
1033 if (match_wanted_ref(refname, pe->path))
1034 return 1;
1037 return 0;
1040 static const struct got_error *
1041 create_wanted_ref(const char *refname, struct got_object_id *id,
1042 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 char *remote_refname;
1047 if (strncmp("refs/", refname, 5) == 0)
1048 refname += 5;
1050 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1051 remote_repo_name, refname) == -1)
1052 return got_error_from_errno("asprintf");
1054 err = create_ref(remote_refname, id, verbosity, repo);
1055 free(remote_refname);
1056 return err;
1059 static const struct got_error *
1060 cmd_clone(int argc, char *argv[])
1062 const struct got_error *error = NULL;
1063 const char *uri, *dirname;
1064 char *proto, *host, *port, *repo_name, *server_path;
1065 char *default_destdir = NULL, *id_str = NULL;
1066 const char *repo_path;
1067 struct got_repository *repo = NULL;
1068 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1069 struct got_pathlist_entry *pe;
1070 struct got_object_id *pack_hash = NULL;
1071 int ch, fetchfd = -1, fetchstatus;
1072 pid_t fetchpid = -1;
1073 struct got_fetch_progress_arg fpa;
1074 char *git_url = NULL;
1075 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1076 char *gitconfig = NULL, *gotconfig = NULL;
1077 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1078 ssize_t n;
1079 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1080 int list_refs_only = 0;
1081 struct got_reference *head_symref = NULL;
1083 TAILQ_INIT(&refs);
1084 TAILQ_INIT(&symrefs);
1085 TAILQ_INIT(&wanted_branches);
1086 TAILQ_INIT(&wanted_refs);
1088 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1089 switch (ch) {
1090 case 'a':
1091 fetch_all_branches = 1;
1092 break;
1093 case 'b':
1094 error = got_pathlist_append(&wanted_branches,
1095 optarg, NULL);
1096 if (error)
1097 return error;
1098 break;
1099 case 'l':
1100 list_refs_only = 1;
1101 break;
1102 case 'm':
1103 mirror_references = 1;
1104 break;
1105 case 'v':
1106 if (verbosity < 0)
1107 verbosity = 0;
1108 else if (verbosity < 3)
1109 verbosity++;
1110 break;
1111 case 'q':
1112 verbosity = -1;
1113 break;
1114 case 'R':
1115 error = got_pathlist_append(&wanted_refs,
1116 optarg, NULL);
1117 if (error)
1118 return error;
1119 break;
1120 default:
1121 usage_clone();
1122 break;
1125 argc -= optind;
1126 argv += optind;
1128 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1129 errx(1, "-a and -b options are mutually exclusive");
1130 if (list_refs_only) {
1131 if (!TAILQ_EMPTY(&wanted_branches))
1132 errx(1, "-l and -b options are mutually exclusive");
1133 if (fetch_all_branches)
1134 errx(1, "-l and -a options are mutually exclusive");
1135 if (mirror_references)
1136 errx(1, "-l and -m options are mutually exclusive");
1137 if (verbosity == -1)
1138 errx(1, "-l and -q options are mutually exclusive");
1139 if (!TAILQ_EMPTY(&wanted_refs))
1140 errx(1, "-l and -R options are mutually exclusive");
1143 uri = argv[0];
1145 if (argc == 1)
1146 dirname = NULL;
1147 else if (argc == 2)
1148 dirname = argv[1];
1149 else
1150 usage_clone();
1152 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1153 &repo_name, uri);
1154 if (error)
1155 goto done;
1157 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1158 host, port ? ":" : "", port ? port : "",
1159 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1160 error = got_error_from_errno("asprintf");
1161 goto done;
1164 if (strcmp(proto, "git") == 0) {
1165 #ifndef PROFILE
1166 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1167 "sendfd dns inet unveil", NULL) == -1)
1168 err(1, "pledge");
1169 #endif
1170 } else if (strcmp(proto, "git+ssh") == 0 ||
1171 strcmp(proto, "ssh") == 0) {
1172 #ifndef PROFILE
1173 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1174 "sendfd unveil", NULL) == -1)
1175 err(1, "pledge");
1176 #endif
1177 } else if (strcmp(proto, "http") == 0 ||
1178 strcmp(proto, "git+http") == 0) {
1179 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1180 goto done;
1181 } else {
1182 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1183 goto done;
1185 if (dirname == NULL) {
1186 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1187 error = got_error_from_errno("asprintf");
1188 goto done;
1190 repo_path = default_destdir;
1191 } else
1192 repo_path = dirname;
1194 if (!list_refs_only) {
1195 error = got_path_mkdir(repo_path);
1196 if (error)
1197 goto done;
1199 error = got_repo_init(repo_path);
1200 if (error)
1201 goto done;
1202 error = got_repo_open(&repo, repo_path, NULL);
1203 if (error)
1204 goto done;
1207 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1208 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1209 error = got_error_from_errno2("unveil",
1210 GOT_FETCH_PATH_SSH);
1211 goto done;
1214 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1215 if (error)
1216 goto done;
1218 if (verbosity >= 0)
1219 printf("Connecting to %s%s%s\n", host,
1220 port ? ":" : "", port ? port : "");
1222 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1223 server_path, verbosity);
1224 if (error)
1225 goto done;
1227 fpa.last_scaled_size[0] = '\0';
1228 fpa.last_p_indexed = -1;
1229 fpa.last_p_resolved = -1;
1230 fpa.verbosity = verbosity;
1231 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1232 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1233 fetch_all_branches, &wanted_branches, &wanted_refs,
1234 list_refs_only, verbosity, fetchfd, repo,
1235 fetch_progress, &fpa);
1236 if (error)
1237 goto done;
1239 if (list_refs_only) {
1240 error = list_remote_refs(&symrefs, &refs);
1241 goto done;
1244 error = got_object_id_str(&id_str, pack_hash);
1245 if (error)
1246 goto done;
1247 if (verbosity >= 0)
1248 printf("\nFetched %s.pack\n", id_str);
1249 free(id_str);
1251 /* Set up references provided with the pack file. */
1252 TAILQ_FOREACH(pe, &refs, entry) {
1253 const char *refname = pe->path;
1254 struct got_object_id *id = pe->data;
1255 char *remote_refname;
1257 if (is_wanted_ref(&wanted_refs, refname) &&
1258 !mirror_references) {
1259 error = create_wanted_ref(refname, id,
1260 GOT_FETCH_DEFAULT_REMOTE_NAME,
1261 verbosity - 1, repo);
1262 if (error)
1263 goto done;
1264 continue;
1267 error = create_ref(refname, id, verbosity - 1, repo);
1268 if (error)
1269 goto done;
1271 if (mirror_references)
1272 continue;
1274 if (strncmp("refs/heads/", refname, 11) != 0)
1275 continue;
1277 if (asprintf(&remote_refname,
1278 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1279 refname + 11) == -1) {
1280 error = got_error_from_errno("asprintf");
1281 goto done;
1283 error = create_ref(remote_refname, id, verbosity - 1, repo);
1284 free(remote_refname);
1285 if (error)
1286 goto done;
1289 /* Set the HEAD reference if the server provided one. */
1290 TAILQ_FOREACH(pe, &symrefs, entry) {
1291 struct got_reference *target_ref;
1292 const char *refname = pe->path;
1293 const char *target = pe->data;
1294 char *remote_refname = NULL, *remote_target = NULL;
1296 if (strcmp(refname, GOT_REF_HEAD) != 0)
1297 continue;
1299 error = got_ref_open(&target_ref, repo, target, 0);
1300 if (error) {
1301 if (error->code == GOT_ERR_NOT_REF) {
1302 error = NULL;
1303 continue;
1305 goto done;
1308 error = create_symref(refname, target_ref, verbosity, repo);
1309 got_ref_close(target_ref);
1310 if (error)
1311 goto done;
1313 if (mirror_references)
1314 continue;
1316 if (strncmp("refs/heads/", target, 11) != 0)
1317 continue;
1319 if (asprintf(&remote_refname,
1320 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1321 refname) == -1) {
1322 error = got_error_from_errno("asprintf");
1323 goto done;
1325 if (asprintf(&remote_target,
1326 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1327 target + 11) == -1) {
1328 error = got_error_from_errno("asprintf");
1329 free(remote_refname);
1330 goto done;
1332 error = got_ref_open(&target_ref, repo, remote_target, 0);
1333 if (error) {
1334 free(remote_refname);
1335 free(remote_target);
1336 if (error->code == GOT_ERR_NOT_REF) {
1337 error = NULL;
1338 continue;
1340 goto done;
1342 error = create_symref(remote_refname, target_ref,
1343 verbosity - 1, repo);
1344 free(remote_refname);
1345 free(remote_target);
1346 got_ref_close(target_ref);
1347 if (error)
1348 goto done;
1350 if (pe == NULL) {
1352 * We failed to set the HEAD reference. If we asked for
1353 * a set of wanted branches use the first of one of those
1354 * which could be fetched instead.
1356 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1357 const char *target = pe->path;
1358 struct got_reference *target_ref;
1360 error = got_ref_open(&target_ref, repo, target, 0);
1361 if (error) {
1362 if (error->code == GOT_ERR_NOT_REF) {
1363 error = NULL;
1364 continue;
1366 goto done;
1369 error = create_symref(GOT_REF_HEAD, target_ref,
1370 verbosity, repo);
1371 got_ref_close(target_ref);
1372 if (error)
1373 goto done;
1374 break;
1378 /* Create got.conf(5). */
1379 gotconfig_path = got_repo_get_path_gotconfig(repo);
1380 if (gotconfig_path == NULL) {
1381 error = got_error_from_errno("got_repo_get_path_gotconfig");
1382 goto done;
1384 gotconfig_file = fopen(gotconfig_path, "a");
1385 if (gotconfig_file == NULL) {
1386 error = got_error_from_errno2("fopen", gotconfig_path);
1387 goto done;
1389 got_path_strip_trailing_slashes(server_path);
1390 if (asprintf(&gotconfig,
1391 "remote \"%s\" {\n"
1392 "\tserver %s\n"
1393 "\tprotocol %s\n"
1394 "%s%s%s"
1395 "\trepository \"%s\"\n"
1396 "%s"
1397 "}\n",
1398 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1399 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1400 server_path,
1401 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1402 error = got_error_from_errno("asprintf");
1403 goto done;
1405 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1406 if (n != strlen(gotconfig)) {
1407 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1408 goto done;
1411 /* Create a config file Git can understand. */
1412 gitconfig_path = got_repo_get_path_gitconfig(repo);
1413 if (gitconfig_path == NULL) {
1414 error = got_error_from_errno("got_repo_get_path_gitconfig");
1415 goto done;
1417 gitconfig_file = fopen(gitconfig_path, "a");
1418 if (gitconfig_file == NULL) {
1419 error = got_error_from_errno2("fopen", gitconfig_path);
1420 goto done;
1422 if (mirror_references) {
1423 if (asprintf(&gitconfig,
1424 "[remote \"%s\"]\n"
1425 "\turl = %s\n"
1426 "\tfetch = +refs/*:refs/*\n"
1427 "\tmirror = true\n",
1428 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1429 error = got_error_from_errno("asprintf");
1430 goto done;
1432 } else if (fetch_all_branches) {
1433 if (asprintf(&gitconfig,
1434 "[remote \"%s\"]\n"
1435 "\turl = %s\n"
1436 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1437 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1438 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1439 error = got_error_from_errno("asprintf");
1440 goto done;
1442 } else {
1443 const char *branchname;
1446 * If the server specified a default branch, use just that one.
1447 * Otherwise fall back to fetching all branches on next fetch.
1449 if (head_symref) {
1450 branchname = got_ref_get_symref_target(head_symref);
1451 if (strncmp(branchname, "refs/heads/", 11) == 0)
1452 branchname += 11;
1453 } else
1454 branchname = "*"; /* fall back to all branches */
1455 if (asprintf(&gitconfig,
1456 "[remote \"%s\"]\n"
1457 "\turl = %s\n"
1458 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1459 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1460 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 branchname) == -1) {
1462 error = got_error_from_errno("asprintf");
1463 goto done;
1466 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1467 if (n != strlen(gitconfig)) {
1468 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1469 goto done;
1472 if (verbosity >= 0)
1473 printf("Created %s repository '%s'\n",
1474 mirror_references ? "mirrored" : "cloned", repo_path);
1475 done:
1476 if (fetchpid > 0) {
1477 if (kill(fetchpid, SIGTERM) == -1)
1478 error = got_error_from_errno("kill");
1479 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1480 error = got_error_from_errno("waitpid");
1482 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1483 error = got_error_from_errno("close");
1484 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1485 error = got_error_from_errno("fclose");
1486 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1487 error = got_error_from_errno("fclose");
1488 if (repo)
1489 got_repo_close(repo);
1490 if (head_symref)
1491 got_ref_close(head_symref);
1492 TAILQ_FOREACH(pe, &refs, entry) {
1493 free((void *)pe->path);
1494 free(pe->data);
1496 got_pathlist_free(&refs);
1497 TAILQ_FOREACH(pe, &symrefs, entry) {
1498 free((void *)pe->path);
1499 free(pe->data);
1501 got_pathlist_free(&symrefs);
1502 got_pathlist_free(&wanted_branches);
1503 got_pathlist_free(&wanted_refs);
1504 free(pack_hash);
1505 free(proto);
1506 free(host);
1507 free(port);
1508 free(server_path);
1509 free(repo_name);
1510 free(default_destdir);
1511 free(gotconfig);
1512 free(gitconfig);
1513 free(gotconfig_path);
1514 free(gitconfig_path);
1515 free(git_url);
1516 return error;
1519 static const struct got_error *
1520 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1521 int replace_tags, int verbosity, struct got_repository *repo)
1523 const struct got_error *err = NULL;
1524 char *new_id_str = NULL;
1525 struct got_object_id *old_id = NULL;
1527 err = got_object_id_str(&new_id_str, new_id);
1528 if (err)
1529 goto done;
1531 if (!replace_tags &&
1532 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1533 err = got_ref_resolve(&old_id, repo, ref);
1534 if (err)
1535 goto done;
1536 if (got_object_id_cmp(old_id, new_id) == 0)
1537 goto done;
1538 if (verbosity >= 0) {
1539 printf("Rejecting update of existing tag %s: %s\n",
1540 got_ref_get_name(ref), new_id_str);
1542 goto done;
1545 if (got_ref_is_symbolic(ref)) {
1546 if (verbosity >= 0) {
1547 printf("Replacing reference %s: %s\n",
1548 got_ref_get_name(ref),
1549 got_ref_get_symref_target(ref));
1551 err = got_ref_change_symref_to_ref(ref, new_id);
1552 if (err)
1553 goto done;
1554 err = got_ref_write(ref, repo);
1555 if (err)
1556 goto done;
1557 } else {
1558 err = got_ref_resolve(&old_id, repo, ref);
1559 if (err)
1560 goto done;
1561 if (got_object_id_cmp(old_id, new_id) == 0)
1562 goto done;
1564 err = got_ref_change_ref(ref, new_id);
1565 if (err)
1566 goto done;
1567 err = got_ref_write(ref, repo);
1568 if (err)
1569 goto done;
1572 if (verbosity >= 0)
1573 printf("Updated %s: %s\n", got_ref_get_name(ref),
1574 new_id_str);
1575 done:
1576 free(old_id);
1577 free(new_id_str);
1578 return err;
1581 static const struct got_error *
1582 update_symref(const char *refname, struct got_reference *target_ref,
1583 int verbosity, struct got_repository *repo)
1585 const struct got_error *err = NULL, *unlock_err;
1586 struct got_reference *symref;
1587 int symref_is_locked = 0;
1589 err = got_ref_open(&symref, repo, refname, 1);
1590 if (err) {
1591 if (err->code != GOT_ERR_NOT_REF)
1592 return err;
1593 err = got_ref_alloc_symref(&symref, refname, target_ref);
1594 if (err)
1595 goto done;
1597 err = got_ref_write(symref, repo);
1598 if (err)
1599 goto done;
1601 if (verbosity >= 0)
1602 printf("Created reference %s: %s\n",
1603 got_ref_get_name(symref),
1604 got_ref_get_symref_target(symref));
1605 } else {
1606 symref_is_locked = 1;
1608 if (strcmp(got_ref_get_symref_target(symref),
1609 got_ref_get_name(target_ref)) == 0)
1610 goto done;
1612 err = got_ref_change_symref(symref,
1613 got_ref_get_name(target_ref));
1614 if (err)
1615 goto done;
1617 err = got_ref_write(symref, repo);
1618 if (err)
1619 goto done;
1621 if (verbosity >= 0)
1622 printf("Updated %s: %s\n", got_ref_get_name(symref),
1623 got_ref_get_symref_target(symref));
1626 done:
1627 if (symref_is_locked) {
1628 unlock_err = got_ref_unlock(symref);
1629 if (unlock_err && err == NULL)
1630 err = unlock_err;
1632 got_ref_close(symref);
1633 return err;
1636 __dead static void
1637 usage_fetch(void)
1639 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1640 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1641 "[remote-repository-name]\n",
1642 getprogname());
1643 exit(1);
1646 static const struct got_error *
1647 delete_missing_ref(struct got_reference *ref,
1648 int verbosity, struct got_repository *repo)
1650 const struct got_error *err = NULL;
1651 struct got_object_id *id = NULL;
1652 char *id_str = NULL;
1654 if (got_ref_is_symbolic(ref)) {
1655 err = got_ref_delete(ref, repo);
1656 if (err)
1657 return err;
1658 if (verbosity >= 0) {
1659 printf("Deleted reference %s: %s\n",
1660 got_ref_get_name(ref),
1661 got_ref_get_symref_target(ref));
1663 } else {
1664 err = got_ref_resolve(&id, repo, ref);
1665 if (err)
1666 return err;
1667 err = got_object_id_str(&id_str, id);
1668 if (err)
1669 goto done;
1671 err = got_ref_delete(ref, repo);
1672 if (err)
1673 goto done;
1674 if (verbosity >= 0) {
1675 printf("Deleted reference %s: %s\n",
1676 got_ref_get_name(ref), id_str);
1679 done:
1680 free(id);
1681 free(id_str);
1682 return NULL;
1685 static const struct got_error *
1686 delete_missing_refs(struct got_pathlist_head *their_refs,
1687 struct got_pathlist_head *their_symrefs,
1688 const struct got_remote_repo *remote,
1689 int verbosity, struct got_repository *repo)
1691 const struct got_error *err = NULL, *unlock_err;
1692 struct got_reflist_head my_refs;
1693 struct got_reflist_entry *re;
1694 struct got_pathlist_entry *pe;
1695 char *remote_namespace = NULL;
1696 char *local_refname = NULL;
1698 SIMPLEQ_INIT(&my_refs);
1700 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1701 == -1)
1702 return got_error_from_errno("asprintf");
1704 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1705 if (err)
1706 goto done;
1708 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1709 const char *refname = got_ref_get_name(re->ref);
1711 if (!remote->mirror_references) {
1712 if (strncmp(refname, remote_namespace,
1713 strlen(remote_namespace)) == 0) {
1714 if (strcmp(refname + strlen(remote_namespace),
1715 GOT_REF_HEAD) == 0)
1716 continue;
1717 if (asprintf(&local_refname, "refs/heads/%s",
1718 refname + strlen(remote_namespace)) == -1) {
1719 err = got_error_from_errno("asprintf");
1720 goto done;
1722 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1723 continue;
1726 TAILQ_FOREACH(pe, their_refs, entry) {
1727 if (strcmp(local_refname, pe->path) == 0)
1728 break;
1730 if (pe != NULL)
1731 continue;
1733 TAILQ_FOREACH(pe, their_symrefs, entry) {
1734 if (strcmp(local_refname, pe->path) == 0)
1735 break;
1737 if (pe != NULL)
1738 continue;
1740 err = delete_missing_ref(re->ref, verbosity, repo);
1741 if (err)
1742 break;
1744 if (local_refname) {
1745 struct got_reference *ref;
1746 err = got_ref_open(&ref, repo, local_refname, 1);
1747 if (err) {
1748 if (err->code != GOT_ERR_NOT_REF)
1749 break;
1750 free(local_refname);
1751 local_refname = NULL;
1752 continue;
1754 err = delete_missing_ref(ref, verbosity, repo);
1755 if (err)
1756 break;
1757 unlock_err = got_ref_unlock(ref);
1758 got_ref_close(ref);
1759 if (unlock_err && err == NULL) {
1760 err = unlock_err;
1761 break;
1764 free(local_refname);
1765 local_refname = NULL;
1768 done:
1769 free(remote_namespace);
1770 free(local_refname);
1771 return err;
1774 static const struct got_error *
1775 update_wanted_ref(const char *refname, struct got_object_id *id,
1776 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1778 const struct got_error *err, *unlock_err;
1779 char *remote_refname;
1780 struct got_reference *ref;
1782 if (strncmp("refs/", refname, 5) == 0)
1783 refname += 5;
1785 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1786 remote_repo_name, refname) == -1)
1787 return got_error_from_errno("asprintf");
1789 err = got_ref_open(&ref, repo, remote_refname, 1);
1790 if (err) {
1791 if (err->code != GOT_ERR_NOT_REF)
1792 goto done;
1793 err = create_ref(remote_refname, id, verbosity, repo);
1794 } else {
1795 err = update_ref(ref, id, 0, verbosity, repo);
1796 unlock_err = got_ref_unlock(ref);
1797 if (unlock_err && err == NULL)
1798 err = unlock_err;
1799 got_ref_close(ref);
1801 done:
1802 free(remote_refname);
1803 return err;
1806 static const struct got_error *
1807 cmd_fetch(int argc, char *argv[])
1809 const struct got_error *error = NULL, *unlock_err;
1810 char *cwd = NULL, *repo_path = NULL;
1811 const char *remote_name;
1812 char *proto = NULL, *host = NULL, *port = NULL;
1813 char *repo_name = NULL, *server_path = NULL;
1814 const struct got_remote_repo *remotes, *remote = NULL;
1815 int nremotes;
1816 char *id_str = NULL;
1817 struct got_repository *repo = NULL;
1818 struct got_worktree *worktree = NULL;
1819 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1820 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1821 struct got_pathlist_entry *pe;
1822 struct got_object_id *pack_hash = NULL;
1823 int i, ch, fetchfd = -1, fetchstatus;
1824 pid_t fetchpid = -1;
1825 struct got_fetch_progress_arg fpa;
1826 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1827 int delete_refs = 0, replace_tags = 0;
1829 TAILQ_INIT(&refs);
1830 TAILQ_INIT(&symrefs);
1831 TAILQ_INIT(&wanted_branches);
1832 TAILQ_INIT(&wanted_refs);
1834 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1835 switch (ch) {
1836 case 'a':
1837 fetch_all_branches = 1;
1838 break;
1839 case 'b':
1840 error = got_pathlist_append(&wanted_branches,
1841 optarg, NULL);
1842 if (error)
1843 return error;
1844 break;
1845 case 'd':
1846 delete_refs = 1;
1847 break;
1848 case 'l':
1849 list_refs_only = 1;
1850 break;
1851 case 'r':
1852 repo_path = realpath(optarg, NULL);
1853 if (repo_path == NULL)
1854 return got_error_from_errno2("realpath",
1855 optarg);
1856 got_path_strip_trailing_slashes(repo_path);
1857 break;
1858 case 't':
1859 replace_tags = 1;
1860 break;
1861 case 'v':
1862 if (verbosity < 0)
1863 verbosity = 0;
1864 else if (verbosity < 3)
1865 verbosity++;
1866 break;
1867 case 'q':
1868 verbosity = -1;
1869 break;
1870 case 'R':
1871 error = got_pathlist_append(&wanted_refs,
1872 optarg, NULL);
1873 if (error)
1874 return error;
1875 break;
1876 default:
1877 usage_fetch();
1878 break;
1881 argc -= optind;
1882 argv += optind;
1884 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1885 errx(1, "-a and -b options are mutually exclusive");
1886 if (list_refs_only) {
1887 if (!TAILQ_EMPTY(&wanted_branches))
1888 errx(1, "-l and -b options are mutually exclusive");
1889 if (fetch_all_branches)
1890 errx(1, "-l and -a options are mutually exclusive");
1891 if (delete_refs)
1892 errx(1, "-l and -d options are mutually exclusive");
1893 if (verbosity == -1)
1894 errx(1, "-l and -q options are mutually exclusive");
1897 if (argc == 0)
1898 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1899 else if (argc == 1)
1900 remote_name = argv[0];
1901 else
1902 usage_fetch();
1904 cwd = getcwd(NULL, 0);
1905 if (cwd == NULL) {
1906 error = got_error_from_errno("getcwd");
1907 goto done;
1910 if (repo_path == NULL) {
1911 error = got_worktree_open(&worktree, cwd);
1912 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1913 goto done;
1914 else
1915 error = NULL;
1916 if (worktree) {
1917 repo_path =
1918 strdup(got_worktree_get_repo_path(worktree));
1919 if (repo_path == NULL)
1920 error = got_error_from_errno("strdup");
1921 if (error)
1922 goto done;
1923 } else {
1924 repo_path = strdup(cwd);
1925 if (repo_path == NULL) {
1926 error = got_error_from_errno("strdup");
1927 goto done;
1932 error = got_repo_open(&repo, repo_path, NULL);
1933 if (error)
1934 goto done;
1936 if (worktree) {
1937 worktree_conf = got_worktree_get_gotconfig(worktree);
1938 if (worktree_conf) {
1939 got_gotconfig_get_remotes(&nremotes, &remotes,
1940 worktree_conf);
1941 for (i = 0; i < nremotes; i++) {
1942 remote = &remotes[i];
1943 if (strcmp(remote->name, remote_name) == 0)
1944 break;
1948 if (remote == NULL) {
1949 repo_conf = got_repo_get_gotconfig(repo);
1950 if (repo_conf) {
1951 got_gotconfig_get_remotes(&nremotes, &remotes,
1952 repo_conf);
1953 for (i = 0; i < nremotes; i++) {
1954 remote = &remotes[i];
1955 if (strcmp(remote->name, remote_name) == 0)
1956 break;
1960 if (remote == NULL) {
1961 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1962 for (i = 0; i < nremotes; i++) {
1963 remote = &remotes[i];
1964 if (strcmp(remote->name, remote_name) == 0)
1965 break;
1968 if (remote == NULL) {
1969 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1970 goto done;
1973 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1974 &repo_name, remote->url);
1975 if (error)
1976 goto done;
1978 if (strcmp(proto, "git") == 0) {
1979 #ifndef PROFILE
1980 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1981 "sendfd dns inet unveil", NULL) == -1)
1982 err(1, "pledge");
1983 #endif
1984 } else if (strcmp(proto, "git+ssh") == 0 ||
1985 strcmp(proto, "ssh") == 0) {
1986 #ifndef PROFILE
1987 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1988 "sendfd unveil", NULL) == -1)
1989 err(1, "pledge");
1990 #endif
1991 } else if (strcmp(proto, "http") == 0 ||
1992 strcmp(proto, "git+http") == 0) {
1993 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1994 goto done;
1995 } else {
1996 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1997 goto done;
2000 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2001 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2002 error = got_error_from_errno2("unveil",
2003 GOT_FETCH_PATH_SSH);
2004 goto done;
2007 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2008 if (error)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2013 port ? ":" : "", port ? port : "");
2015 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2016 server_path, verbosity);
2017 if (error)
2018 goto done;
2020 fpa.last_scaled_size[0] = '\0';
2021 fpa.last_p_indexed = -1;
2022 fpa.last_p_resolved = -1;
2023 fpa.verbosity = verbosity;
2024 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2025 remote->mirror_references, fetch_all_branches, &wanted_branches,
2026 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2027 fetch_progress, &fpa);
2028 if (error)
2029 goto done;
2031 if (list_refs_only) {
2032 error = list_remote_refs(&symrefs, &refs);
2033 goto done;
2036 if (pack_hash == NULL) {
2037 if (verbosity >= 0)
2038 printf("Already up-to-date\n");
2039 } else if (verbosity >= 0) {
2040 error = got_object_id_str(&id_str, pack_hash);
2041 if (error)
2042 goto done;
2043 printf("\nFetched %s.pack\n", id_str);
2044 free(id_str);
2045 id_str = NULL;
2048 /* Update references provided with the pack file. */
2049 TAILQ_FOREACH(pe, &refs, entry) {
2050 const char *refname = pe->path;
2051 struct got_object_id *id = pe->data;
2052 struct got_reference *ref;
2053 char *remote_refname;
2055 if (is_wanted_ref(&wanted_refs, refname) &&
2056 !remote->mirror_references) {
2057 error = update_wanted_ref(refname, id,
2058 remote->name, verbosity, repo);
2059 if (error)
2060 goto done;
2061 continue;
2064 if (remote->mirror_references ||
2065 strncmp("refs/tags/", refname, 10) == 0) {
2066 error = got_ref_open(&ref, repo, refname, 1);
2067 if (error) {
2068 if (error->code != GOT_ERR_NOT_REF)
2069 goto done;
2070 error = create_ref(refname, id, verbosity,
2071 repo);
2072 if (error)
2073 goto done;
2074 } else {
2075 error = update_ref(ref, id, replace_tags,
2076 verbosity, repo);
2077 unlock_err = got_ref_unlock(ref);
2078 if (unlock_err && error == NULL)
2079 error = unlock_err;
2080 got_ref_close(ref);
2081 if (error)
2082 goto done;
2084 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2085 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2086 remote_name, refname + 11) == -1) {
2087 error = got_error_from_errno("asprintf");
2088 goto done;
2091 error = got_ref_open(&ref, repo, remote_refname, 1);
2092 if (error) {
2093 if (error->code != GOT_ERR_NOT_REF)
2094 goto done;
2095 error = create_ref(remote_refname, id,
2096 verbosity, repo);
2097 if (error)
2098 goto done;
2099 } else {
2100 error = update_ref(ref, id, replace_tags,
2101 verbosity, repo);
2102 unlock_err = got_ref_unlock(ref);
2103 if (unlock_err && error == NULL)
2104 error = unlock_err;
2105 got_ref_close(ref);
2106 if (error)
2107 goto done;
2110 /* Also create a local branch if none exists yet. */
2111 error = got_ref_open(&ref, repo, refname, 1);
2112 if (error) {
2113 if (error->code != GOT_ERR_NOT_REF)
2114 goto done;
2115 error = create_ref(refname, id, verbosity,
2116 repo);
2117 if (error)
2118 goto done;
2119 } else {
2120 unlock_err = got_ref_unlock(ref);
2121 if (unlock_err && error == NULL)
2122 error = unlock_err;
2123 got_ref_close(ref);
2127 if (delete_refs) {
2128 error = delete_missing_refs(&refs, &symrefs, remote,
2129 verbosity, repo);
2130 if (error)
2131 goto done;
2134 if (!remote->mirror_references) {
2135 /* Update remote HEAD reference if the server provided one. */
2136 TAILQ_FOREACH(pe, &symrefs, entry) {
2137 struct got_reference *target_ref;
2138 const char *refname = pe->path;
2139 const char *target = pe->data;
2140 char *remote_refname = NULL, *remote_target = NULL;
2142 if (strcmp(refname, GOT_REF_HEAD) != 0)
2143 continue;
2145 if (strncmp("refs/heads/", target, 11) != 0)
2146 continue;
2148 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2149 remote->name, refname) == -1) {
2150 error = got_error_from_errno("asprintf");
2151 goto done;
2153 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2154 remote->name, target + 11) == -1) {
2155 error = got_error_from_errno("asprintf");
2156 free(remote_refname);
2157 goto done;
2160 error = got_ref_open(&target_ref, repo, remote_target,
2161 0);
2162 if (error) {
2163 free(remote_refname);
2164 free(remote_target);
2165 if (error->code == GOT_ERR_NOT_REF) {
2166 error = NULL;
2167 continue;
2169 goto done;
2171 error = update_symref(remote_refname, target_ref,
2172 verbosity, repo);
2173 free(remote_refname);
2174 free(remote_target);
2175 got_ref_close(target_ref);
2176 if (error)
2177 goto done;
2180 done:
2181 if (fetchpid > 0) {
2182 if (kill(fetchpid, SIGTERM) == -1)
2183 error = got_error_from_errno("kill");
2184 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2185 error = got_error_from_errno("waitpid");
2187 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2188 error = got_error_from_errno("close");
2189 if (repo)
2190 got_repo_close(repo);
2191 if (worktree)
2192 got_worktree_close(worktree);
2193 TAILQ_FOREACH(pe, &refs, entry) {
2194 free((void *)pe->path);
2195 free(pe->data);
2197 got_pathlist_free(&refs);
2198 TAILQ_FOREACH(pe, &symrefs, entry) {
2199 free((void *)pe->path);
2200 free(pe->data);
2202 got_pathlist_free(&symrefs);
2203 got_pathlist_free(&wanted_branches);
2204 got_pathlist_free(&wanted_refs);
2205 free(id_str);
2206 free(cwd);
2207 free(repo_path);
2208 free(pack_hash);
2209 free(proto);
2210 free(host);
2211 free(port);
2212 free(server_path);
2213 free(repo_name);
2214 return error;
2218 __dead static void
2219 usage_checkout(void)
2221 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2222 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2223 exit(1);
2226 static void
2227 show_worktree_base_ref_warning(void)
2229 fprintf(stderr, "%s: warning: could not create a reference "
2230 "to the work tree's base commit; the commit could be "
2231 "garbage-collected by Git; making the repository "
2232 "writable and running 'got update' will prevent this\n",
2233 getprogname());
2236 struct got_checkout_progress_arg {
2237 const char *worktree_path;
2238 int had_base_commit_ref_error;
2241 static const struct got_error *
2242 checkout_progress(void *arg, unsigned char status, const char *path)
2244 struct got_checkout_progress_arg *a = arg;
2246 /* Base commit bump happens silently. */
2247 if (status == GOT_STATUS_BUMP_BASE)
2248 return NULL;
2250 if (status == GOT_STATUS_BASE_REF_ERR) {
2251 a->had_base_commit_ref_error = 1;
2252 return NULL;
2255 while (path[0] == '/')
2256 path++;
2258 printf("%c %s/%s\n", status, a->worktree_path, path);
2259 return NULL;
2262 static const struct got_error *
2263 check_cancelled(void *arg)
2265 if (sigint_received || sigpipe_received)
2266 return got_error(GOT_ERR_CANCELLED);
2267 return NULL;
2270 static const struct got_error *
2271 check_linear_ancestry(struct got_object_id *commit_id,
2272 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2273 struct got_repository *repo)
2275 const struct got_error *err = NULL;
2276 struct got_object_id *yca_id;
2278 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2279 commit_id, base_commit_id, repo, check_cancelled, NULL);
2280 if (err)
2281 return err;
2283 if (yca_id == NULL)
2284 return got_error(GOT_ERR_ANCESTRY);
2287 * Require a straight line of history between the target commit
2288 * and the work tree's base commit.
2290 * Non-linear situations such as this require a rebase:
2292 * (commit) D F (base_commit)
2293 * \ /
2294 * C E
2295 * \ /
2296 * B (yca)
2297 * |
2298 * A
2300 * 'got update' only handles linear cases:
2301 * Update forwards in time: A (base/yca) - B - C - D (commit)
2302 * Update backwards in time: D (base) - C - B - A (commit/yca)
2304 if (allow_forwards_in_time_only) {
2305 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2306 return got_error(GOT_ERR_ANCESTRY);
2307 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2308 got_object_id_cmp(base_commit_id, yca_id) != 0)
2309 return got_error(GOT_ERR_ANCESTRY);
2311 free(yca_id);
2312 return NULL;
2315 static const struct got_error *
2316 check_same_branch(struct got_object_id *commit_id,
2317 struct got_reference *head_ref, struct got_object_id *yca_id,
2318 struct got_repository *repo)
2320 const struct got_error *err = NULL;
2321 struct got_commit_graph *graph = NULL;
2322 struct got_object_id *head_commit_id = NULL;
2323 int is_same_branch = 0;
2325 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2326 if (err)
2327 goto done;
2329 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2330 is_same_branch = 1;
2331 goto done;
2333 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2334 is_same_branch = 1;
2335 goto done;
2338 err = got_commit_graph_open(&graph, "/", 1);
2339 if (err)
2340 goto done;
2342 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2343 check_cancelled, NULL);
2344 if (err)
2345 goto done;
2347 for (;;) {
2348 struct got_object_id *id;
2349 err = got_commit_graph_iter_next(&id, graph, repo,
2350 check_cancelled, NULL);
2351 if (err) {
2352 if (err->code == GOT_ERR_ITER_COMPLETED)
2353 err = NULL;
2354 break;
2357 if (id) {
2358 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2359 break;
2360 if (got_object_id_cmp(id, commit_id) == 0) {
2361 is_same_branch = 1;
2362 break;
2366 done:
2367 if (graph)
2368 got_commit_graph_close(graph);
2369 free(head_commit_id);
2370 if (!err && !is_same_branch)
2371 err = got_error(GOT_ERR_ANCESTRY);
2372 return err;
2375 static const struct got_error *
2376 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2378 static char msg[512];
2379 const char *branch_name;
2381 if (got_ref_is_symbolic(ref))
2382 branch_name = got_ref_get_symref_target(ref);
2383 else
2384 branch_name = got_ref_get_name(ref);
2386 if (strncmp("refs/heads/", branch_name, 11) == 0)
2387 branch_name += 11;
2389 snprintf(msg, sizeof(msg),
2390 "target commit is not contained in branch '%s'; "
2391 "the branch to use must be specified with -b; "
2392 "if necessary a new branch can be created for "
2393 "this commit with 'got branch -c %s BRANCH_NAME'",
2394 branch_name, commit_id_str);
2396 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2399 static const struct got_error *
2400 cmd_checkout(int argc, char *argv[])
2402 const struct got_error *error = NULL;
2403 struct got_repository *repo = NULL;
2404 struct got_reference *head_ref = NULL;
2405 struct got_worktree *worktree = NULL;
2406 char *repo_path = NULL;
2407 char *worktree_path = NULL;
2408 const char *path_prefix = "";
2409 const char *branch_name = GOT_REF_HEAD;
2410 char *commit_id_str = NULL;
2411 int ch, same_path_prefix, allow_nonempty = 0;
2412 struct got_pathlist_head paths;
2413 struct got_checkout_progress_arg cpa;
2415 TAILQ_INIT(&paths);
2417 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2418 switch (ch) {
2419 case 'b':
2420 branch_name = optarg;
2421 break;
2422 case 'c':
2423 commit_id_str = strdup(optarg);
2424 if (commit_id_str == NULL)
2425 return got_error_from_errno("strdup");
2426 break;
2427 case 'E':
2428 allow_nonempty = 1;
2429 break;
2430 case 'p':
2431 path_prefix = optarg;
2432 break;
2433 default:
2434 usage_checkout();
2435 /* NOTREACHED */
2439 argc -= optind;
2440 argv += optind;
2442 #ifndef PROFILE
2443 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2444 "unveil", NULL) == -1)
2445 err(1, "pledge");
2446 #endif
2447 if (argc == 1) {
2448 char *cwd, *base, *dotgit;
2449 repo_path = realpath(argv[0], NULL);
2450 if (repo_path == NULL)
2451 return got_error_from_errno2("realpath", argv[0]);
2452 cwd = getcwd(NULL, 0);
2453 if (cwd == NULL) {
2454 error = got_error_from_errno("getcwd");
2455 goto done;
2457 if (path_prefix[0]) {
2458 base = basename(path_prefix);
2459 if (base == NULL) {
2460 error = got_error_from_errno2("basename",
2461 path_prefix);
2462 goto done;
2464 } else {
2465 base = basename(repo_path);
2466 if (base == NULL) {
2467 error = got_error_from_errno2("basename",
2468 repo_path);
2469 goto done;
2472 dotgit = strstr(base, ".git");
2473 if (dotgit)
2474 *dotgit = '\0';
2475 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2476 error = got_error_from_errno("asprintf");
2477 free(cwd);
2478 goto done;
2480 free(cwd);
2481 } else if (argc == 2) {
2482 repo_path = realpath(argv[0], NULL);
2483 if (repo_path == NULL) {
2484 error = got_error_from_errno2("realpath", argv[0]);
2485 goto done;
2487 worktree_path = realpath(argv[1], NULL);
2488 if (worktree_path == NULL) {
2489 if (errno != ENOENT) {
2490 error = got_error_from_errno2("realpath",
2491 argv[1]);
2492 goto done;
2494 worktree_path = strdup(argv[1]);
2495 if (worktree_path == NULL) {
2496 error = got_error_from_errno("strdup");
2497 goto done;
2500 } else
2501 usage_checkout();
2503 got_path_strip_trailing_slashes(repo_path);
2504 got_path_strip_trailing_slashes(worktree_path);
2506 error = got_repo_open(&repo, repo_path, NULL);
2507 if (error != NULL)
2508 goto done;
2510 /* Pre-create work tree path for unveil(2) */
2511 error = got_path_mkdir(worktree_path);
2512 if (error) {
2513 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2514 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2515 goto done;
2516 if (!allow_nonempty &&
2517 !got_path_dir_is_empty(worktree_path)) {
2518 error = got_error_path(worktree_path,
2519 GOT_ERR_DIR_NOT_EMPTY);
2520 goto done;
2524 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2525 if (error)
2526 goto done;
2528 error = got_ref_open(&head_ref, repo, branch_name, 0);
2529 if (error != NULL)
2530 goto done;
2532 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2533 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2534 goto done;
2536 error = got_worktree_open(&worktree, worktree_path);
2537 if (error != NULL)
2538 goto done;
2540 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2541 path_prefix);
2542 if (error != NULL)
2543 goto done;
2544 if (!same_path_prefix) {
2545 error = got_error(GOT_ERR_PATH_PREFIX);
2546 goto done;
2549 if (commit_id_str) {
2550 struct got_object_id *commit_id;
2551 error = got_repo_match_object_id(&commit_id, NULL,
2552 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2553 if (error)
2554 goto done;
2555 error = check_linear_ancestry(commit_id,
2556 got_worktree_get_base_commit_id(worktree), 0, repo);
2557 if (error != NULL) {
2558 free(commit_id);
2559 if (error->code == GOT_ERR_ANCESTRY) {
2560 error = checkout_ancestry_error(
2561 head_ref, commit_id_str);
2563 goto done;
2565 error = check_same_branch(commit_id, head_ref, NULL, repo);
2566 if (error) {
2567 if (error->code == GOT_ERR_ANCESTRY) {
2568 error = checkout_ancestry_error(
2569 head_ref, commit_id_str);
2571 goto done;
2573 error = got_worktree_set_base_commit_id(worktree, repo,
2574 commit_id);
2575 free(commit_id);
2576 if (error)
2577 goto done;
2580 error = got_pathlist_append(&paths, "", NULL);
2581 if (error)
2582 goto done;
2583 cpa.worktree_path = worktree_path;
2584 cpa.had_base_commit_ref_error = 0;
2585 error = got_worktree_checkout_files(worktree, &paths, repo,
2586 checkout_progress, &cpa, check_cancelled, NULL);
2587 if (error != NULL)
2588 goto done;
2590 printf("Now shut up and hack\n");
2591 if (cpa.had_base_commit_ref_error)
2592 show_worktree_base_ref_warning();
2593 done:
2594 got_pathlist_free(&paths);
2595 free(commit_id_str);
2596 free(repo_path);
2597 free(worktree_path);
2598 return error;
2601 struct got_update_progress_arg {
2602 int did_something;
2603 int conflicts;
2604 int obstructed;
2605 int not_updated;
2608 void
2609 print_update_progress_stats(struct got_update_progress_arg *upa)
2611 if (!upa->did_something)
2612 return;
2614 if (upa->conflicts > 0)
2615 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2616 if (upa->obstructed > 0)
2617 printf("File paths obstructed by a non-regular file: %d\n",
2618 upa->obstructed);
2619 if (upa->not_updated > 0)
2620 printf("Files not updated because of existing merge "
2621 "conflicts: %d\n", upa->not_updated);
2624 __dead static void
2625 usage_update(void)
2627 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2628 getprogname());
2629 exit(1);
2632 static const struct got_error *
2633 update_progress(void *arg, unsigned char status, const char *path)
2635 struct got_update_progress_arg *upa = arg;
2637 if (status == GOT_STATUS_EXISTS ||
2638 status == GOT_STATUS_BASE_REF_ERR)
2639 return NULL;
2641 upa->did_something = 1;
2643 /* Base commit bump happens silently. */
2644 if (status == GOT_STATUS_BUMP_BASE)
2645 return NULL;
2647 if (status == GOT_STATUS_CONFLICT)
2648 upa->conflicts++;
2649 if (status == GOT_STATUS_OBSTRUCTED)
2650 upa->obstructed++;
2651 if (status == GOT_STATUS_CANNOT_UPDATE)
2652 upa->not_updated++;
2654 while (path[0] == '/')
2655 path++;
2656 printf("%c %s\n", status, path);
2657 return NULL;
2660 static const struct got_error *
2661 switch_head_ref(struct got_reference *head_ref,
2662 struct got_object_id *commit_id, struct got_worktree *worktree,
2663 struct got_repository *repo)
2665 const struct got_error *err = NULL;
2666 char *base_id_str;
2667 int ref_has_moved = 0;
2669 /* Trivial case: switching between two different references. */
2670 if (strcmp(got_ref_get_name(head_ref),
2671 got_worktree_get_head_ref_name(worktree)) != 0) {
2672 printf("Switching work tree from %s to %s\n",
2673 got_worktree_get_head_ref_name(worktree),
2674 got_ref_get_name(head_ref));
2675 return got_worktree_set_head_ref(worktree, head_ref);
2678 err = check_linear_ancestry(commit_id,
2679 got_worktree_get_base_commit_id(worktree), 0, repo);
2680 if (err) {
2681 if (err->code != GOT_ERR_ANCESTRY)
2682 return err;
2683 ref_has_moved = 1;
2685 if (!ref_has_moved)
2686 return NULL;
2688 /* Switching to a rebased branch with the same reference name. */
2689 err = got_object_id_str(&base_id_str,
2690 got_worktree_get_base_commit_id(worktree));
2691 if (err)
2692 return err;
2693 printf("Reference %s now points at a different branch\n",
2694 got_worktree_get_head_ref_name(worktree));
2695 printf("Switching work tree from %s to %s\n", base_id_str,
2696 got_worktree_get_head_ref_name(worktree));
2697 return NULL;
2700 static const struct got_error *
2701 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2703 const struct got_error *err;
2704 int in_progress;
2706 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2707 if (err)
2708 return err;
2709 if (in_progress)
2710 return got_error(GOT_ERR_REBASING);
2712 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2713 if (err)
2714 return err;
2715 if (in_progress)
2716 return got_error(GOT_ERR_HISTEDIT_BUSY);
2718 return NULL;
2721 static const struct got_error *
2722 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2723 char *argv[], struct got_worktree *worktree)
2725 const struct got_error *err = NULL;
2726 char *path;
2727 int i;
2729 if (argc == 0) {
2730 path = strdup("");
2731 if (path == NULL)
2732 return got_error_from_errno("strdup");
2733 return got_pathlist_append(paths, path, NULL);
2736 for (i = 0; i < argc; i++) {
2737 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2738 if (err)
2739 break;
2740 err = got_pathlist_append(paths, path, NULL);
2741 if (err) {
2742 free(path);
2743 break;
2747 return err;
2750 static const struct got_error *
2751 wrap_not_worktree_error(const struct got_error *orig_err,
2752 const char *cmdname, const char *path)
2754 const struct got_error *err;
2755 struct got_repository *repo;
2756 static char msg[512];
2758 err = got_repo_open(&repo, path, NULL);
2759 if (err)
2760 return orig_err;
2762 snprintf(msg, sizeof(msg),
2763 "'got %s' needs a work tree in addition to a git repository\n"
2764 "Work trees can be checked out from this Git repository with "
2765 "'got checkout'.\n"
2766 "The got(1) manual page contains more information.", cmdname);
2767 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2768 got_repo_close(repo);
2769 return err;
2772 static const struct got_error *
2773 cmd_update(int argc, char *argv[])
2775 const struct got_error *error = NULL;
2776 struct got_repository *repo = NULL;
2777 struct got_worktree *worktree = NULL;
2778 char *worktree_path = NULL;
2779 struct got_object_id *commit_id = NULL;
2780 char *commit_id_str = NULL;
2781 const char *branch_name = NULL;
2782 struct got_reference *head_ref = NULL;
2783 struct got_pathlist_head paths;
2784 struct got_pathlist_entry *pe;
2785 int ch;
2786 struct got_update_progress_arg upa;
2788 TAILQ_INIT(&paths);
2790 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2791 switch (ch) {
2792 case 'b':
2793 branch_name = optarg;
2794 break;
2795 case 'c':
2796 commit_id_str = strdup(optarg);
2797 if (commit_id_str == NULL)
2798 return got_error_from_errno("strdup");
2799 break;
2800 default:
2801 usage_update();
2802 /* NOTREACHED */
2806 argc -= optind;
2807 argv += optind;
2809 #ifndef PROFILE
2810 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2811 "unveil", NULL) == -1)
2812 err(1, "pledge");
2813 #endif
2814 worktree_path = getcwd(NULL, 0);
2815 if (worktree_path == NULL) {
2816 error = got_error_from_errno("getcwd");
2817 goto done;
2819 error = got_worktree_open(&worktree, worktree_path);
2820 if (error) {
2821 if (error->code == GOT_ERR_NOT_WORKTREE)
2822 error = wrap_not_worktree_error(error, "update",
2823 worktree_path);
2824 goto done;
2827 error = check_rebase_or_histedit_in_progress(worktree);
2828 if (error)
2829 goto done;
2831 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2832 NULL);
2833 if (error != NULL)
2834 goto done;
2836 error = apply_unveil(got_repo_get_path(repo), 0,
2837 got_worktree_get_root_path(worktree));
2838 if (error)
2839 goto done;
2841 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2842 if (error)
2843 goto done;
2845 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2846 got_worktree_get_head_ref_name(worktree), 0);
2847 if (error != NULL)
2848 goto done;
2849 if (commit_id_str == NULL) {
2850 error = got_ref_resolve(&commit_id, repo, head_ref);
2851 if (error != NULL)
2852 goto done;
2853 error = got_object_id_str(&commit_id_str, commit_id);
2854 if (error != NULL)
2855 goto done;
2856 } else {
2857 error = got_repo_match_object_id(&commit_id, NULL,
2858 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2859 free(commit_id_str);
2860 commit_id_str = NULL;
2861 if (error)
2862 goto done;
2863 error = got_object_id_str(&commit_id_str, commit_id);
2864 if (error)
2865 goto done;
2868 if (branch_name) {
2869 struct got_object_id *head_commit_id;
2870 TAILQ_FOREACH(pe, &paths, entry) {
2871 if (pe->path_len == 0)
2872 continue;
2873 error = got_error_msg(GOT_ERR_BAD_PATH,
2874 "switching between branches requires that "
2875 "the entire work tree gets updated");
2876 goto done;
2878 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2879 if (error)
2880 goto done;
2881 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2882 repo);
2883 free(head_commit_id);
2884 if (error != NULL)
2885 goto done;
2886 error = check_same_branch(commit_id, head_ref, NULL, repo);
2887 if (error)
2888 goto done;
2889 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2890 if (error)
2891 goto done;
2892 } else {
2893 error = check_linear_ancestry(commit_id,
2894 got_worktree_get_base_commit_id(worktree), 0, repo);
2895 if (error != NULL) {
2896 if (error->code == GOT_ERR_ANCESTRY)
2897 error = got_error(GOT_ERR_BRANCH_MOVED);
2898 goto done;
2900 error = check_same_branch(commit_id, head_ref, NULL, repo);
2901 if (error)
2902 goto done;
2905 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2906 commit_id) != 0) {
2907 error = got_worktree_set_base_commit_id(worktree, repo,
2908 commit_id);
2909 if (error)
2910 goto done;
2913 memset(&upa, 0, sizeof(upa));
2914 error = got_worktree_checkout_files(worktree, &paths, repo,
2915 update_progress, &upa, check_cancelled, NULL);
2916 if (error != NULL)
2917 goto done;
2919 if (upa.did_something)
2920 printf("Updated to commit %s\n", commit_id_str);
2921 else
2922 printf("Already up-to-date\n");
2923 print_update_progress_stats(&upa);
2924 done:
2925 free(worktree_path);
2926 TAILQ_FOREACH(pe, &paths, entry)
2927 free((char *)pe->path);
2928 got_pathlist_free(&paths);
2929 free(commit_id);
2930 free(commit_id_str);
2931 return error;
2934 static const struct got_error *
2935 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2936 const char *path, int diff_context, int ignore_whitespace,
2937 struct got_repository *repo)
2939 const struct got_error *err = NULL;
2940 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2942 if (blob_id1) {
2943 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2944 if (err)
2945 goto done;
2948 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2949 if (err)
2950 goto done;
2952 while (path[0] == '/')
2953 path++;
2954 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2955 ignore_whitespace, stdout);
2956 done:
2957 if (blob1)
2958 got_object_blob_close(blob1);
2959 got_object_blob_close(blob2);
2960 return err;
2963 static const struct got_error *
2964 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2965 const char *path, int diff_context, int ignore_whitespace,
2966 struct got_repository *repo)
2968 const struct got_error *err = NULL;
2969 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2970 struct got_diff_blob_output_unidiff_arg arg;
2972 if (tree_id1) {
2973 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2974 if (err)
2975 goto done;
2978 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2979 if (err)
2980 goto done;
2982 arg.diff_context = diff_context;
2983 arg.ignore_whitespace = ignore_whitespace;
2984 arg.outfile = stdout;
2985 while (path[0] == '/')
2986 path++;
2987 err = got_diff_tree(tree1, tree2, path, path, repo,
2988 got_diff_blob_output_unidiff, &arg, 1);
2989 done:
2990 if (tree1)
2991 got_object_tree_close(tree1);
2992 if (tree2)
2993 got_object_tree_close(tree2);
2994 return err;
2997 static const struct got_error *
2998 get_changed_paths(struct got_pathlist_head *paths,
2999 struct got_commit_object *commit, struct got_repository *repo)
3001 const struct got_error *err = NULL;
3002 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3003 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3004 struct got_object_qid *qid;
3006 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3007 if (qid != NULL) {
3008 struct got_commit_object *pcommit;
3009 err = got_object_open_as_commit(&pcommit, repo,
3010 qid->id);
3011 if (err)
3012 return err;
3014 tree_id1 = got_object_commit_get_tree_id(pcommit);
3015 got_object_commit_close(pcommit);
3019 if (tree_id1) {
3020 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3021 if (err)
3022 goto done;
3025 tree_id2 = got_object_commit_get_tree_id(commit);
3026 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3027 if (err)
3028 goto done;
3030 err = got_diff_tree(tree1, tree2, "", "", repo,
3031 got_diff_tree_collect_changed_paths, paths, 0);
3032 done:
3033 if (tree1)
3034 got_object_tree_close(tree1);
3035 if (tree2)
3036 got_object_tree_close(tree2);
3037 return err;
3040 static const struct got_error *
3041 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3042 const char *path, int diff_context, struct got_repository *repo)
3044 const struct got_error *err = NULL;
3045 struct got_commit_object *pcommit = NULL;
3046 char *id_str1 = NULL, *id_str2 = NULL;
3047 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3048 struct got_object_qid *qid;
3050 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3051 if (qid != NULL) {
3052 err = got_object_open_as_commit(&pcommit, repo,
3053 qid->id);
3054 if (err)
3055 return err;
3058 if (path && path[0] != '\0') {
3059 int obj_type;
3060 err = got_object_id_by_path(&obj_id2, repo, id, path);
3061 if (err)
3062 goto done;
3063 err = got_object_id_str(&id_str2, obj_id2);
3064 if (err) {
3065 free(obj_id2);
3066 goto done;
3068 if (pcommit) {
3069 err = got_object_id_by_path(&obj_id1, repo,
3070 qid->id, path);
3071 if (err) {
3072 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3073 free(obj_id2);
3074 goto done;
3076 } else {
3077 err = got_object_id_str(&id_str1, obj_id1);
3078 if (err) {
3079 free(obj_id2);
3080 goto done;
3084 err = got_object_get_type(&obj_type, repo, obj_id2);
3085 if (err) {
3086 free(obj_id2);
3087 goto done;
3089 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3090 switch (obj_type) {
3091 case GOT_OBJ_TYPE_BLOB:
3092 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3093 0, repo);
3094 break;
3095 case GOT_OBJ_TYPE_TREE:
3096 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3097 0, repo);
3098 break;
3099 default:
3100 err = got_error(GOT_ERR_OBJ_TYPE);
3101 break;
3103 free(obj_id1);
3104 free(obj_id2);
3105 } else {
3106 obj_id2 = got_object_commit_get_tree_id(commit);
3107 err = got_object_id_str(&id_str2, obj_id2);
3108 if (err)
3109 goto done;
3110 obj_id1 = got_object_commit_get_tree_id(pcommit);
3111 err = got_object_id_str(&id_str1, obj_id1);
3112 if (err)
3113 goto done;
3114 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3115 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3117 done:
3118 free(id_str1);
3119 free(id_str2);
3120 if (pcommit)
3121 got_object_commit_close(pcommit);
3122 return err;
3125 static char *
3126 get_datestr(time_t *time, char *datebuf)
3128 struct tm mytm, *tm;
3129 char *p, *s;
3131 tm = gmtime_r(time, &mytm);
3132 if (tm == NULL)
3133 return NULL;
3134 s = asctime_r(tm, datebuf);
3135 if (s == NULL)
3136 return NULL;
3137 p = strchr(s, '\n');
3138 if (p)
3139 *p = '\0';
3140 return s;
3143 static const struct got_error *
3144 match_logmsg(int *have_match, struct got_object_id *id,
3145 struct got_commit_object *commit, regex_t *regex)
3147 const struct got_error *err = NULL;
3148 regmatch_t regmatch;
3149 char *id_str = NULL, *logmsg = NULL;
3151 *have_match = 0;
3153 err = got_object_id_str(&id_str, id);
3154 if (err)
3155 return err;
3157 err = got_object_commit_get_logmsg(&logmsg, commit);
3158 if (err)
3159 goto done;
3161 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3162 *have_match = 1;
3163 done:
3164 free(id_str);
3165 free(logmsg);
3166 return err;
3169 static void
3170 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3171 regex_t *regex)
3173 regmatch_t regmatch;
3174 struct got_pathlist_entry *pe;
3176 *have_match = 0;
3178 TAILQ_FOREACH(pe, changed_paths, entry) {
3179 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3180 *have_match = 1;
3181 break;
3186 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3188 static const struct got_error *
3189 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3190 struct got_repository *repo, const char *path,
3191 struct got_pathlist_head *changed_paths, int show_patch,
3192 int diff_context, struct got_reflist_head *refs)
3194 const struct got_error *err = NULL;
3195 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3196 char datebuf[26];
3197 time_t committer_time;
3198 const char *author, *committer;
3199 char *refs_str = NULL;
3200 struct got_reflist_entry *re;
3202 SIMPLEQ_FOREACH(re, refs, entry) {
3203 char *s;
3204 const char *name;
3205 struct got_tag_object *tag = NULL;
3206 int cmp;
3208 name = got_ref_get_name(re->ref);
3209 if (strcmp(name, GOT_REF_HEAD) == 0)
3210 continue;
3211 if (strncmp(name, "refs/", 5) == 0)
3212 name += 5;
3213 if (strncmp(name, "got/", 4) == 0)
3214 continue;
3215 if (strncmp(name, "heads/", 6) == 0)
3216 name += 6;
3217 if (strncmp(name, "remotes/", 8) == 0) {
3218 name += 8;
3219 s = strstr(name, "/" GOT_REF_HEAD);
3220 if (s != NULL && s[strlen(s)] == '\0')
3221 continue;
3223 if (strncmp(name, "tags/", 5) == 0) {
3224 err = got_object_open_as_tag(&tag, repo, re->id);
3225 if (err) {
3226 if (err->code != GOT_ERR_OBJ_TYPE)
3227 return err;
3228 /* Ref points at something other than a tag. */
3229 err = NULL;
3230 tag = NULL;
3233 cmp = got_object_id_cmp(tag ?
3234 got_object_tag_get_object_id(tag) : re->id, id);
3235 if (tag)
3236 got_object_tag_close(tag);
3237 if (cmp != 0)
3238 continue;
3239 s = refs_str;
3240 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3241 name) == -1) {
3242 err = got_error_from_errno("asprintf");
3243 free(s);
3244 return err;
3246 free(s);
3248 err = got_object_id_str(&id_str, id);
3249 if (err)
3250 return err;
3252 printf(GOT_COMMIT_SEP_STR);
3253 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3254 refs_str ? refs_str : "", refs_str ? ")" : "");
3255 free(id_str);
3256 id_str = NULL;
3257 free(refs_str);
3258 refs_str = NULL;
3259 printf("from: %s\n", got_object_commit_get_author(commit));
3260 committer_time = got_object_commit_get_committer_time(commit);
3261 datestr = get_datestr(&committer_time, datebuf);
3262 if (datestr)
3263 printf("date: %s UTC\n", datestr);
3264 author = got_object_commit_get_author(commit);
3265 committer = got_object_commit_get_committer(commit);
3266 if (strcmp(author, committer) != 0)
3267 printf("via: %s\n", committer);
3268 if (got_object_commit_get_nparents(commit) > 1) {
3269 const struct got_object_id_queue *parent_ids;
3270 struct got_object_qid *qid;
3271 int n = 1;
3272 parent_ids = got_object_commit_get_parent_ids(commit);
3273 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3274 err = got_object_id_str(&id_str, qid->id);
3275 if (err)
3276 return err;
3277 printf("parent %d: %s\n", n++, id_str);
3278 free(id_str);
3282 err = got_object_commit_get_logmsg(&logmsg0, commit);
3283 if (err)
3284 return err;
3286 logmsg = logmsg0;
3287 do {
3288 line = strsep(&logmsg, "\n");
3289 if (line)
3290 printf(" %s\n", line);
3291 } while (line);
3292 free(logmsg0);
3294 if (changed_paths) {
3295 struct got_pathlist_entry *pe;
3296 TAILQ_FOREACH(pe, changed_paths, entry) {
3297 struct got_diff_changed_path *cp = pe->data;
3298 printf(" %c %s\n", cp->status, pe->path);
3300 printf("\n");
3302 if (show_patch) {
3303 err = print_patch(commit, id, path, diff_context, repo);
3304 if (err == 0)
3305 printf("\n");
3308 if (fflush(stdout) != 0 && err == NULL)
3309 err = got_error_from_errno("fflush");
3310 return err;
3313 static const struct got_error *
3314 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3315 struct got_repository *repo, const char *path, int show_changed_paths,
3316 int show_patch, const char *search_pattern, int diff_context, int limit,
3317 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3319 const struct got_error *err;
3320 struct got_commit_graph *graph;
3321 regex_t regex;
3322 int have_match;
3323 struct got_object_id_queue reversed_commits;
3324 struct got_object_qid *qid;
3325 struct got_commit_object *commit;
3326 struct got_pathlist_head changed_paths;
3327 struct got_pathlist_entry *pe;
3329 SIMPLEQ_INIT(&reversed_commits);
3330 TAILQ_INIT(&changed_paths);
3332 if (search_pattern && regcomp(&regex, search_pattern,
3333 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3334 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3336 err = got_commit_graph_open(&graph, path, !log_branches);
3337 if (err)
3338 return err;
3339 err = got_commit_graph_iter_start(graph, root_id, repo,
3340 check_cancelled, NULL);
3341 if (err)
3342 goto done;
3343 for (;;) {
3344 struct got_object_id *id;
3346 if (sigint_received || sigpipe_received)
3347 break;
3349 err = got_commit_graph_iter_next(&id, graph, repo,
3350 check_cancelled, NULL);
3351 if (err) {
3352 if (err->code == GOT_ERR_ITER_COMPLETED)
3353 err = NULL;
3354 break;
3356 if (id == NULL)
3357 break;
3359 err = got_object_open_as_commit(&commit, repo, id);
3360 if (err)
3361 break;
3363 if (show_changed_paths && !reverse_display_order) {
3364 err = get_changed_paths(&changed_paths, commit, repo);
3365 if (err)
3366 break;
3369 if (search_pattern) {
3370 err = match_logmsg(&have_match, id, commit, &regex);
3371 if (err) {
3372 got_object_commit_close(commit);
3373 break;
3375 if (have_match == 0 && show_changed_paths)
3376 match_changed_paths(&have_match,
3377 &changed_paths, &regex);
3378 if (have_match == 0) {
3379 got_object_commit_close(commit);
3380 TAILQ_FOREACH(pe, &changed_paths, entry) {
3381 free((char *)pe->path);
3382 free(pe->data);
3384 got_pathlist_free(&changed_paths);
3385 continue;
3389 if (reverse_display_order) {
3390 err = got_object_qid_alloc(&qid, id);
3391 if (err)
3392 break;
3393 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3394 got_object_commit_close(commit);
3395 } else {
3396 err = print_commit(commit, id, repo, path,
3397 show_changed_paths ? &changed_paths : NULL,
3398 show_patch, diff_context, refs);
3399 got_object_commit_close(commit);
3400 if (err)
3401 break;
3403 if ((limit && --limit == 0) ||
3404 (end_id && got_object_id_cmp(id, end_id) == 0))
3405 break;
3407 TAILQ_FOREACH(pe, &changed_paths, entry) {
3408 free((char *)pe->path);
3409 free(pe->data);
3411 got_pathlist_free(&changed_paths);
3413 if (reverse_display_order) {
3414 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3415 err = got_object_open_as_commit(&commit, repo, qid->id);
3416 if (err)
3417 break;
3418 if (show_changed_paths) {
3419 err = get_changed_paths(&changed_paths,
3420 commit, repo);
3421 if (err)
3422 break;
3424 err = print_commit(commit, qid->id, repo, path,
3425 show_changed_paths ? &changed_paths : NULL,
3426 show_patch, diff_context, refs);
3427 got_object_commit_close(commit);
3428 if (err)
3429 break;
3430 TAILQ_FOREACH(pe, &changed_paths, entry) {
3431 free((char *)pe->path);
3432 free(pe->data);
3434 got_pathlist_free(&changed_paths);
3437 done:
3438 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3439 qid = SIMPLEQ_FIRST(&reversed_commits);
3440 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3441 got_object_qid_free(qid);
3443 TAILQ_FOREACH(pe, &changed_paths, entry) {
3444 free((char *)pe->path);
3445 free(pe->data);
3447 got_pathlist_free(&changed_paths);
3448 if (search_pattern)
3449 regfree(&regex);
3450 got_commit_graph_close(graph);
3451 return err;
3454 __dead static void
3455 usage_log(void)
3457 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3458 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3459 "[-R] [path]\n", getprogname());
3460 exit(1);
3463 static int
3464 get_default_log_limit(void)
3466 const char *got_default_log_limit;
3467 long long n;
3468 const char *errstr;
3470 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3471 if (got_default_log_limit == NULL)
3472 return 0;
3473 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3474 if (errstr != NULL)
3475 return 0;
3476 return n;
3479 static const struct got_error *
3480 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3481 struct got_repository *repo)
3483 const struct got_error *err = NULL;
3484 struct got_reference *ref;
3486 *id = NULL;
3488 err = got_ref_open(&ref, repo, commit_arg, 0);
3489 if (err == NULL) {
3490 int obj_type;
3491 err = got_ref_resolve(id, repo, ref);
3492 got_ref_close(ref);
3493 if (err)
3494 return err;
3495 err = got_object_get_type(&obj_type, repo, *id);
3496 if (err)
3497 return err;
3498 if (obj_type == GOT_OBJ_TYPE_TAG) {
3499 struct got_tag_object *tag;
3500 err = got_object_open_as_tag(&tag, repo, *id);
3501 if (err)
3502 return err;
3503 if (got_object_tag_get_object_type(tag) !=
3504 GOT_OBJ_TYPE_COMMIT) {
3505 got_object_tag_close(tag);
3506 return got_error(GOT_ERR_OBJ_TYPE);
3508 free(*id);
3509 *id = got_object_id_dup(
3510 got_object_tag_get_object_id(tag));
3511 if (*id == NULL)
3512 err = got_error_from_errno(
3513 "got_object_id_dup");
3514 got_object_tag_close(tag);
3515 if (err)
3516 return err;
3517 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3518 return got_error(GOT_ERR_OBJ_TYPE);
3519 } else {
3520 err = got_repo_match_object_id_prefix(id, commit_arg,
3521 GOT_OBJ_TYPE_COMMIT, repo);
3524 return err;
3527 static const struct got_error *
3528 cmd_log(int argc, char *argv[])
3530 const struct got_error *error;
3531 struct got_repository *repo = NULL;
3532 struct got_worktree *worktree = NULL;
3533 struct got_object_id *start_id = NULL, *end_id = NULL;
3534 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3535 const char *start_commit = NULL, *end_commit = NULL;
3536 const char *search_pattern = NULL;
3537 int diff_context = -1, ch;
3538 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3539 int reverse_display_order = 0;
3540 const char *errstr;
3541 struct got_reflist_head refs;
3543 SIMPLEQ_INIT(&refs);
3545 #ifndef PROFILE
3546 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3547 NULL)
3548 == -1)
3549 err(1, "pledge");
3550 #endif
3552 limit = get_default_log_limit();
3554 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3555 switch (ch) {
3556 case 'p':
3557 show_patch = 1;
3558 break;
3559 case 'P':
3560 show_changed_paths = 1;
3561 break;
3562 case 'c':
3563 start_commit = optarg;
3564 break;
3565 case 'C':
3566 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3567 &errstr);
3568 if (errstr != NULL)
3569 err(1, "-C option %s", errstr);
3570 break;
3571 case 'l':
3572 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3573 if (errstr != NULL)
3574 err(1, "-l option %s", errstr);
3575 break;
3576 case 'b':
3577 log_branches = 1;
3578 break;
3579 case 'r':
3580 repo_path = realpath(optarg, NULL);
3581 if (repo_path == NULL)
3582 return got_error_from_errno2("realpath",
3583 optarg);
3584 got_path_strip_trailing_slashes(repo_path);
3585 break;
3586 case 'R':
3587 reverse_display_order = 1;
3588 break;
3589 case 's':
3590 search_pattern = optarg;
3591 break;
3592 case 'x':
3593 end_commit = optarg;
3594 break;
3595 default:
3596 usage_log();
3597 /* NOTREACHED */
3601 argc -= optind;
3602 argv += optind;
3604 if (diff_context == -1)
3605 diff_context = 3;
3606 else if (!show_patch)
3607 errx(1, "-C reguires -p");
3609 cwd = getcwd(NULL, 0);
3610 if (cwd == NULL) {
3611 error = got_error_from_errno("getcwd");
3612 goto done;
3615 if (repo_path == NULL) {
3616 error = got_worktree_open(&worktree, cwd);
3617 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3618 goto done;
3619 error = NULL;
3622 if (argc == 0) {
3623 path = strdup("");
3624 if (path == NULL) {
3625 error = got_error_from_errno("strdup");
3626 goto done;
3628 } else if (argc == 1) {
3629 if (worktree) {
3630 error = got_worktree_resolve_path(&path, worktree,
3631 argv[0]);
3632 if (error)
3633 goto done;
3634 } else {
3635 path = strdup(argv[0]);
3636 if (path == NULL) {
3637 error = got_error_from_errno("strdup");
3638 goto done;
3641 } else
3642 usage_log();
3644 if (repo_path == NULL) {
3645 repo_path = worktree ?
3646 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3648 if (repo_path == NULL) {
3649 error = got_error_from_errno("strdup");
3650 goto done;
3653 error = got_repo_open(&repo, repo_path, NULL);
3654 if (error != NULL)
3655 goto done;
3657 error = apply_unveil(got_repo_get_path(repo), 1,
3658 worktree ? got_worktree_get_root_path(worktree) : NULL);
3659 if (error)
3660 goto done;
3662 if (start_commit == NULL) {
3663 struct got_reference *head_ref;
3664 struct got_commit_object *commit = NULL;
3665 error = got_ref_open(&head_ref, repo,
3666 worktree ? got_worktree_get_head_ref_name(worktree)
3667 : GOT_REF_HEAD, 0);
3668 if (error != NULL)
3669 goto done;
3670 error = got_ref_resolve(&start_id, repo, head_ref);
3671 got_ref_close(head_ref);
3672 if (error != NULL)
3673 goto done;
3674 error = got_object_open_as_commit(&commit, repo,
3675 start_id);
3676 if (error != NULL)
3677 goto done;
3678 got_object_commit_close(commit);
3679 } else {
3680 error = resolve_commit_arg(&start_id, start_commit, repo);
3681 if (error != NULL)
3682 goto done;
3684 if (end_commit != NULL) {
3685 error = resolve_commit_arg(&end_id, end_commit, repo);
3686 if (error != NULL)
3687 goto done;
3690 if (worktree) {
3691 const char *prefix = got_worktree_get_path_prefix(worktree);
3692 char *p;
3693 if (asprintf(&p, "%s%s%s", prefix,
3694 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3695 error = got_error_from_errno("asprintf");
3696 goto done;
3698 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3699 free(p);
3700 } else
3701 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3702 if (error != NULL)
3703 goto done;
3704 if (in_repo_path) {
3705 free(path);
3706 path = in_repo_path;
3709 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3710 if (error)
3711 goto done;
3713 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3714 show_patch, search_pattern, diff_context, limit, log_branches,
3715 reverse_display_order, &refs);
3716 done:
3717 free(path);
3718 free(repo_path);
3719 free(cwd);
3720 if (worktree)
3721 got_worktree_close(worktree);
3722 if (repo) {
3723 const struct got_error *repo_error;
3724 repo_error = got_repo_close(repo);
3725 if (error == NULL)
3726 error = repo_error;
3728 got_ref_list_free(&refs);
3729 return error;
3732 __dead static void
3733 usage_diff(void)
3735 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3736 "[-w] [object1 object2 | path]\n", getprogname());
3737 exit(1);
3740 struct print_diff_arg {
3741 struct got_repository *repo;
3742 struct got_worktree *worktree;
3743 int diff_context;
3744 const char *id_str;
3745 int header_shown;
3746 int diff_staged;
3747 int ignore_whitespace;
3751 * Create a file which contains the target path of a symlink so we can feed
3752 * it as content to the diff engine.
3754 static const struct got_error *
3755 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3756 const char *abspath)
3758 const struct got_error *err = NULL;
3759 char target_path[PATH_MAX];
3760 ssize_t target_len, outlen;
3762 *fd = -1;
3764 if (dirfd != -1) {
3765 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3766 if (target_len == -1)
3767 return got_error_from_errno2("readlinkat", abspath);
3768 } else {
3769 target_len = readlink(abspath, target_path, PATH_MAX);
3770 if (target_len == -1)
3771 return got_error_from_errno2("readlink", abspath);
3774 *fd = got_opentempfd();
3775 if (*fd == -1)
3776 return got_error_from_errno("got_opentempfd");
3778 outlen = write(*fd, target_path, target_len);
3779 if (outlen == -1) {
3780 err = got_error_from_errno("got_opentempfd");
3781 goto done;
3784 if (lseek(*fd, 0, SEEK_SET) == -1) {
3785 err = got_error_from_errno2("lseek", abspath);
3786 goto done;
3788 done:
3789 if (err) {
3790 close(*fd);
3791 *fd = -1;
3793 return err;
3796 static const struct got_error *
3797 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3798 const char *path, struct got_object_id *blob_id,
3799 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3800 int dirfd, const char *de_name)
3802 struct print_diff_arg *a = arg;
3803 const struct got_error *err = NULL;
3804 struct got_blob_object *blob1 = NULL;
3805 int fd = -1;
3806 FILE *f2 = NULL;
3807 char *abspath = NULL, *label1 = NULL;
3808 struct stat sb;
3810 if (a->diff_staged) {
3811 if (staged_status != GOT_STATUS_MODIFY &&
3812 staged_status != GOT_STATUS_ADD &&
3813 staged_status != GOT_STATUS_DELETE)
3814 return NULL;
3815 } else {
3816 if (staged_status == GOT_STATUS_DELETE)
3817 return NULL;
3818 if (status == GOT_STATUS_NONEXISTENT)
3819 return got_error_set_errno(ENOENT, path);
3820 if (status != GOT_STATUS_MODIFY &&
3821 status != GOT_STATUS_ADD &&
3822 status != GOT_STATUS_DELETE &&
3823 status != GOT_STATUS_CONFLICT)
3824 return NULL;
3827 if (!a->header_shown) {
3828 printf("diff %s %s%s\n", a->id_str,
3829 got_worktree_get_root_path(a->worktree),
3830 a->diff_staged ? " (staged changes)" : "");
3831 a->header_shown = 1;
3834 if (a->diff_staged) {
3835 const char *label1 = NULL, *label2 = NULL;
3836 switch (staged_status) {
3837 case GOT_STATUS_MODIFY:
3838 label1 = path;
3839 label2 = path;
3840 break;
3841 case GOT_STATUS_ADD:
3842 label2 = path;
3843 break;
3844 case GOT_STATUS_DELETE:
3845 label1 = path;
3846 break;
3847 default:
3848 return got_error(GOT_ERR_FILE_STATUS);
3850 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3851 label1, label2, a->diff_context, a->ignore_whitespace,
3852 a->repo, stdout);
3855 if (staged_status == GOT_STATUS_ADD ||
3856 staged_status == GOT_STATUS_MODIFY) {
3857 char *id_str;
3858 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3859 8192);
3860 if (err)
3861 goto done;
3862 err = got_object_id_str(&id_str, staged_blob_id);
3863 if (err)
3864 goto done;
3865 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3866 err = got_error_from_errno("asprintf");
3867 free(id_str);
3868 goto done;
3870 free(id_str);
3871 } else if (status != GOT_STATUS_ADD) {
3872 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3873 if (err)
3874 goto done;
3877 if (status != GOT_STATUS_DELETE) {
3878 if (asprintf(&abspath, "%s/%s",
3879 got_worktree_get_root_path(a->worktree), path) == -1) {
3880 err = got_error_from_errno("asprintf");
3881 goto done;
3884 if (dirfd != -1) {
3885 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3886 if (fd == -1) {
3887 if (errno != ELOOP) {
3888 err = got_error_from_errno2("openat",
3889 abspath);
3890 goto done;
3892 err = get_symlink_target_file(&fd, dirfd,
3893 de_name, abspath);
3894 if (err)
3895 goto done;
3897 } else {
3898 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3899 if (fd == -1) {
3900 if (errno != ELOOP) {
3901 err = got_error_from_errno2("open",
3902 abspath);
3903 goto done;
3905 err = get_symlink_target_file(&fd, dirfd,
3906 de_name, abspath);
3907 if (err)
3908 goto done;
3911 if (fstat(fd, &sb) == -1) {
3912 err = got_error_from_errno2("fstat", abspath);
3913 goto done;
3915 f2 = fdopen(fd, "r");
3916 if (f2 == NULL) {
3917 err = got_error_from_errno2("fdopen", abspath);
3918 goto done;
3920 fd = -1;
3921 } else
3922 sb.st_size = 0;
3924 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3925 a->diff_context, a->ignore_whitespace, stdout);
3926 done:
3927 if (blob1)
3928 got_object_blob_close(blob1);
3929 if (f2 && fclose(f2) == EOF && err == NULL)
3930 err = got_error_from_errno("fclose");
3931 if (fd != -1 && close(fd) == -1 && err == NULL)
3932 err = got_error_from_errno("close");
3933 free(abspath);
3934 return err;
3937 static const struct got_error *
3938 cmd_diff(int argc, char *argv[])
3940 const struct got_error *error;
3941 struct got_repository *repo = NULL;
3942 struct got_worktree *worktree = NULL;
3943 char *cwd = NULL, *repo_path = NULL;
3944 struct got_object_id *id1 = NULL, *id2 = NULL;
3945 const char *id_str1 = NULL, *id_str2 = NULL;
3946 char *label1 = NULL, *label2 = NULL;
3947 int type1, type2;
3948 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3949 const char *errstr;
3950 char *path = NULL;
3952 #ifndef PROFILE
3953 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3954 NULL) == -1)
3955 err(1, "pledge");
3956 #endif
3958 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3959 switch (ch) {
3960 case 'C':
3961 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3962 &errstr);
3963 if (errstr != NULL)
3964 err(1, "-C option %s", errstr);
3965 break;
3966 case 'r':
3967 repo_path = realpath(optarg, NULL);
3968 if (repo_path == NULL)
3969 return got_error_from_errno2("realpath",
3970 optarg);
3971 got_path_strip_trailing_slashes(repo_path);
3972 break;
3973 case 's':
3974 diff_staged = 1;
3975 break;
3976 case 'w':
3977 ignore_whitespace = 1;
3978 break;
3979 default:
3980 usage_diff();
3981 /* NOTREACHED */
3985 argc -= optind;
3986 argv += optind;
3988 cwd = getcwd(NULL, 0);
3989 if (cwd == NULL) {
3990 error = got_error_from_errno("getcwd");
3991 goto done;
3993 if (argc <= 1) {
3994 if (repo_path)
3995 errx(1,
3996 "-r option can't be used when diffing a work tree");
3997 error = got_worktree_open(&worktree, cwd);
3998 if (error) {
3999 if (error->code == GOT_ERR_NOT_WORKTREE)
4000 error = wrap_not_worktree_error(error, "diff",
4001 cwd);
4002 goto done;
4004 repo_path = strdup(got_worktree_get_repo_path(worktree));
4005 if (repo_path == NULL) {
4006 error = got_error_from_errno("strdup");
4007 goto done;
4009 if (argc == 1) {
4010 error = got_worktree_resolve_path(&path, worktree,
4011 argv[0]);
4012 if (error)
4013 goto done;
4014 } else {
4015 path = strdup("");
4016 if (path == NULL) {
4017 error = got_error_from_errno("strdup");
4018 goto done;
4021 } else if (argc == 2) {
4022 if (diff_staged)
4023 errx(1, "-s option can't be used when diffing "
4024 "objects in repository");
4025 id_str1 = argv[0];
4026 id_str2 = argv[1];
4027 if (repo_path == NULL) {
4028 error = got_worktree_open(&worktree, cwd);
4029 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4030 goto done;
4031 if (worktree) {
4032 repo_path = strdup(
4033 got_worktree_get_repo_path(worktree));
4034 if (repo_path == NULL) {
4035 error = got_error_from_errno("strdup");
4036 goto done;
4038 } else {
4039 repo_path = strdup(cwd);
4040 if (repo_path == NULL) {
4041 error = got_error_from_errno("strdup");
4042 goto done;
4046 } else
4047 usage_diff();
4049 error = got_repo_open(&repo, repo_path, NULL);
4050 free(repo_path);
4051 if (error != NULL)
4052 goto done;
4054 error = apply_unveil(got_repo_get_path(repo), 1,
4055 worktree ? got_worktree_get_root_path(worktree) : NULL);
4056 if (error)
4057 goto done;
4059 if (argc <= 1) {
4060 struct print_diff_arg arg;
4061 struct got_pathlist_head paths;
4062 char *id_str;
4064 TAILQ_INIT(&paths);
4066 error = got_object_id_str(&id_str,
4067 got_worktree_get_base_commit_id(worktree));
4068 if (error)
4069 goto done;
4070 arg.repo = repo;
4071 arg.worktree = worktree;
4072 arg.diff_context = diff_context;
4073 arg.id_str = id_str;
4074 arg.header_shown = 0;
4075 arg.diff_staged = diff_staged;
4076 arg.ignore_whitespace = ignore_whitespace;
4078 error = got_pathlist_append(&paths, path, NULL);
4079 if (error)
4080 goto done;
4082 error = got_worktree_status(worktree, &paths, repo, print_diff,
4083 &arg, check_cancelled, NULL);
4084 free(id_str);
4085 got_pathlist_free(&paths);
4086 goto done;
4089 error = got_repo_match_object_id(&id1, &label1, id_str1,
4090 GOT_OBJ_TYPE_ANY, 1, repo);
4091 if (error)
4092 goto done;
4094 error = got_repo_match_object_id(&id2, &label2, id_str2,
4095 GOT_OBJ_TYPE_ANY, 1, repo);
4096 if (error)
4097 goto done;
4099 error = got_object_get_type(&type1, repo, id1);
4100 if (error)
4101 goto done;
4103 error = got_object_get_type(&type2, repo, id2);
4104 if (error)
4105 goto done;
4107 if (type1 != type2) {
4108 error = got_error(GOT_ERR_OBJ_TYPE);
4109 goto done;
4112 switch (type1) {
4113 case GOT_OBJ_TYPE_BLOB:
4114 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4115 diff_context, ignore_whitespace, repo, stdout);
4116 break;
4117 case GOT_OBJ_TYPE_TREE:
4118 error = got_diff_objects_as_trees(id1, id2, "", "",
4119 diff_context, ignore_whitespace, repo, stdout);
4120 break;
4121 case GOT_OBJ_TYPE_COMMIT:
4122 printf("diff %s %s\n", label1, label2);
4123 error = got_diff_objects_as_commits(id1, id2, diff_context,
4124 ignore_whitespace, repo, stdout);
4125 break;
4126 default:
4127 error = got_error(GOT_ERR_OBJ_TYPE);
4129 done:
4130 free(label1);
4131 free(label2);
4132 free(id1);
4133 free(id2);
4134 free(path);
4135 if (worktree)
4136 got_worktree_close(worktree);
4137 if (repo) {
4138 const struct got_error *repo_error;
4139 repo_error = got_repo_close(repo);
4140 if (error == NULL)
4141 error = repo_error;
4143 return error;
4146 __dead static void
4147 usage_blame(void)
4149 fprintf(stderr,
4150 "usage: %s blame [-c commit] [-r repository-path] path\n",
4151 getprogname());
4152 exit(1);
4155 struct blame_line {
4156 int annotated;
4157 char *id_str;
4158 char *committer;
4159 char datebuf[11]; /* YYYY-MM-DD + NUL */
4162 struct blame_cb_args {
4163 struct blame_line *lines;
4164 int nlines;
4165 int nlines_prec;
4166 int lineno_cur;
4167 off_t *line_offsets;
4168 FILE *f;
4169 struct got_repository *repo;
4172 static const struct got_error *
4173 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4175 const struct got_error *err = NULL;
4176 struct blame_cb_args *a = arg;
4177 struct blame_line *bline;
4178 char *line = NULL;
4179 size_t linesize = 0;
4180 struct got_commit_object *commit = NULL;
4181 off_t offset;
4182 struct tm tm;
4183 time_t committer_time;
4185 if (nlines != a->nlines ||
4186 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4187 return got_error(GOT_ERR_RANGE);
4189 if (sigint_received)
4190 return got_error(GOT_ERR_ITER_COMPLETED);
4192 if (lineno == -1)
4193 return NULL; /* no change in this commit */
4195 /* Annotate this line. */
4196 bline = &a->lines[lineno - 1];
4197 if (bline->annotated)
4198 return NULL;
4199 err = got_object_id_str(&bline->id_str, id);
4200 if (err)
4201 return err;
4203 err = got_object_open_as_commit(&commit, a->repo, id);
4204 if (err)
4205 goto done;
4207 bline->committer = strdup(got_object_commit_get_committer(commit));
4208 if (bline->committer == NULL) {
4209 err = got_error_from_errno("strdup");
4210 goto done;
4213 committer_time = got_object_commit_get_committer_time(commit);
4214 if (localtime_r(&committer_time, &tm) == NULL)
4215 return got_error_from_errno("localtime_r");
4216 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4217 &tm) >= sizeof(bline->datebuf)) {
4218 err = got_error(GOT_ERR_NO_SPACE);
4219 goto done;
4221 bline->annotated = 1;
4223 /* Print lines annotated so far. */
4224 bline = &a->lines[a->lineno_cur - 1];
4225 if (!bline->annotated)
4226 goto done;
4228 offset = a->line_offsets[a->lineno_cur - 1];
4229 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4230 err = got_error_from_errno("fseeko");
4231 goto done;
4234 while (bline->annotated) {
4235 char *smallerthan, *at, *nl, *committer;
4236 size_t len;
4238 if (getline(&line, &linesize, a->f) == -1) {
4239 if (ferror(a->f))
4240 err = got_error_from_errno("getline");
4241 break;
4244 committer = bline->committer;
4245 smallerthan = strchr(committer, '<');
4246 if (smallerthan && smallerthan[1] != '\0')
4247 committer = smallerthan + 1;
4248 at = strchr(committer, '@');
4249 if (at)
4250 *at = '\0';
4251 len = strlen(committer);
4252 if (len >= 9)
4253 committer[8] = '\0';
4255 nl = strchr(line, '\n');
4256 if (nl)
4257 *nl = '\0';
4258 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4259 bline->id_str, bline->datebuf, committer, line);
4261 a->lineno_cur++;
4262 bline = &a->lines[a->lineno_cur - 1];
4264 done:
4265 if (commit)
4266 got_object_commit_close(commit);
4267 free(line);
4268 return err;
4271 static const struct got_error *
4272 cmd_blame(int argc, char *argv[])
4274 const struct got_error *error;
4275 struct got_repository *repo = NULL;
4276 struct got_worktree *worktree = NULL;
4277 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4278 char *link_target = NULL;
4279 struct got_object_id *obj_id = NULL;
4280 struct got_object_id *commit_id = NULL;
4281 struct got_blob_object *blob = NULL;
4282 char *commit_id_str = NULL;
4283 struct blame_cb_args bca;
4284 int ch, obj_type, i;
4285 size_t filesize;
4287 memset(&bca, 0, sizeof(bca));
4289 #ifndef PROFILE
4290 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4291 NULL) == -1)
4292 err(1, "pledge");
4293 #endif
4295 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4296 switch (ch) {
4297 case 'c':
4298 commit_id_str = optarg;
4299 break;
4300 case 'r':
4301 repo_path = realpath(optarg, NULL);
4302 if (repo_path == NULL)
4303 return got_error_from_errno2("realpath",
4304 optarg);
4305 got_path_strip_trailing_slashes(repo_path);
4306 break;
4307 default:
4308 usage_blame();
4309 /* NOTREACHED */
4313 argc -= optind;
4314 argv += optind;
4316 if (argc == 1)
4317 path = argv[0];
4318 else
4319 usage_blame();
4321 cwd = getcwd(NULL, 0);
4322 if (cwd == NULL) {
4323 error = got_error_from_errno("getcwd");
4324 goto done;
4326 if (repo_path == NULL) {
4327 error = got_worktree_open(&worktree, cwd);
4328 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4329 goto done;
4330 else
4331 error = NULL;
4332 if (worktree) {
4333 repo_path =
4334 strdup(got_worktree_get_repo_path(worktree));
4335 if (repo_path == NULL) {
4336 error = got_error_from_errno("strdup");
4337 if (error)
4338 goto done;
4340 } else {
4341 repo_path = strdup(cwd);
4342 if (repo_path == NULL) {
4343 error = got_error_from_errno("strdup");
4344 goto done;
4349 error = got_repo_open(&repo, repo_path, NULL);
4350 if (error != NULL)
4351 goto done;
4353 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4354 if (error)
4355 goto done;
4357 if (worktree) {
4358 const char *prefix = got_worktree_get_path_prefix(worktree);
4359 char *p, *worktree_subdir = cwd +
4360 strlen(got_worktree_get_root_path(worktree));
4361 if (asprintf(&p, "%s%s%s%s%s",
4362 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4363 worktree_subdir, worktree_subdir[0] ? "/" : "",
4364 path) == -1) {
4365 error = got_error_from_errno("asprintf");
4366 goto done;
4368 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4369 free(p);
4370 } else {
4371 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4373 if (error)
4374 goto done;
4376 if (commit_id_str == NULL) {
4377 struct got_reference *head_ref;
4378 error = got_ref_open(&head_ref, repo, worktree ?
4379 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4380 if (error != NULL)
4381 goto done;
4382 error = got_ref_resolve(&commit_id, repo, head_ref);
4383 got_ref_close(head_ref);
4384 if (error != NULL)
4385 goto done;
4386 } else {
4387 error = got_repo_match_object_id(&commit_id, NULL,
4388 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4389 if (error)
4390 goto done;
4393 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4394 commit_id, repo);
4395 if (error)
4396 goto done;
4398 error = got_object_id_by_path(&obj_id, repo, commit_id,
4399 link_target ? link_target : in_repo_path);
4400 if (error)
4401 goto done;
4403 error = got_object_get_type(&obj_type, repo, obj_id);
4404 if (error)
4405 goto done;
4407 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4408 error = got_error_path(link_target ? link_target : in_repo_path,
4409 GOT_ERR_OBJ_TYPE);
4410 goto done;
4413 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4414 if (error)
4415 goto done;
4416 bca.f = got_opentemp();
4417 if (bca.f == NULL) {
4418 error = got_error_from_errno("got_opentemp");
4419 goto done;
4421 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4422 &bca.line_offsets, bca.f, blob);
4423 if (error || bca.nlines == 0)
4424 goto done;
4426 /* Don't include \n at EOF in the blame line count. */
4427 if (bca.line_offsets[bca.nlines - 1] == filesize)
4428 bca.nlines--;
4430 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4431 if (bca.lines == NULL) {
4432 error = got_error_from_errno("calloc");
4433 goto done;
4435 bca.lineno_cur = 1;
4436 bca.nlines_prec = 0;
4437 i = bca.nlines;
4438 while (i > 0) {
4439 i /= 10;
4440 bca.nlines_prec++;
4442 bca.repo = repo;
4444 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4445 repo, blame_cb, &bca, check_cancelled, NULL);
4446 done:
4447 free(in_repo_path);
4448 free(link_target);
4449 free(repo_path);
4450 free(cwd);
4451 free(commit_id);
4452 free(obj_id);
4453 if (blob)
4454 got_object_blob_close(blob);
4455 if (worktree)
4456 got_worktree_close(worktree);
4457 if (repo) {
4458 const struct got_error *repo_error;
4459 repo_error = got_repo_close(repo);
4460 if (error == NULL)
4461 error = repo_error;
4463 if (bca.lines) {
4464 for (i = 0; i < bca.nlines; i++) {
4465 struct blame_line *bline = &bca.lines[i];
4466 free(bline->id_str);
4467 free(bline->committer);
4469 free(bca.lines);
4471 free(bca.line_offsets);
4472 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4473 error = got_error_from_errno("fclose");
4474 return error;
4477 __dead static void
4478 usage_tree(void)
4480 fprintf(stderr,
4481 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4482 getprogname());
4483 exit(1);
4486 static const struct got_error *
4487 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4488 const char *root_path, struct got_repository *repo)
4490 const struct got_error *err = NULL;
4491 int is_root_path = (strcmp(path, root_path) == 0);
4492 const char *modestr = "";
4493 mode_t mode = got_tree_entry_get_mode(te);
4494 char *link_target = NULL;
4496 path += strlen(root_path);
4497 while (path[0] == '/')
4498 path++;
4500 if (got_object_tree_entry_is_submodule(te))
4501 modestr = "$";
4502 else if (S_ISLNK(mode)) {
4503 int i;
4505 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4506 if (err)
4507 return err;
4508 for (i = 0; i < strlen(link_target); i++) {
4509 if (!isprint((unsigned char)link_target[i]))
4510 link_target[i] = '?';
4513 modestr = "@";
4515 else if (S_ISDIR(mode))
4516 modestr = "/";
4517 else if (mode & S_IXUSR)
4518 modestr = "*";
4520 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4521 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4522 link_target ? " -> ": "", link_target ? link_target : "");
4524 free(link_target);
4525 return NULL;
4528 static const struct got_error *
4529 print_tree(const char *path, struct got_object_id *commit_id,
4530 int show_ids, int recurse, const char *root_path,
4531 struct got_repository *repo)
4533 const struct got_error *err = NULL;
4534 struct got_object_id *tree_id = NULL;
4535 struct got_tree_object *tree = NULL;
4536 int nentries, i;
4538 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4539 if (err)
4540 goto done;
4542 err = got_object_open_as_tree(&tree, repo, tree_id);
4543 if (err)
4544 goto done;
4545 nentries = got_object_tree_get_nentries(tree);
4546 for (i = 0; i < nentries; i++) {
4547 struct got_tree_entry *te;
4548 char *id = NULL;
4550 if (sigint_received || sigpipe_received)
4551 break;
4553 te = got_object_tree_get_entry(tree, i);
4554 if (show_ids) {
4555 char *id_str;
4556 err = got_object_id_str(&id_str,
4557 got_tree_entry_get_id(te));
4558 if (err)
4559 goto done;
4560 if (asprintf(&id, "%s ", id_str) == -1) {
4561 err = got_error_from_errno("asprintf");
4562 free(id_str);
4563 goto done;
4565 free(id_str);
4567 err = print_entry(te, id, path, root_path, repo);
4568 free(id);
4569 if (err)
4570 goto done;
4572 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4573 char *child_path;
4574 if (asprintf(&child_path, "%s%s%s", path,
4575 path[0] == '/' && path[1] == '\0' ? "" : "/",
4576 got_tree_entry_get_name(te)) == -1) {
4577 err = got_error_from_errno("asprintf");
4578 goto done;
4580 err = print_tree(child_path, commit_id, show_ids, 1,
4581 root_path, repo);
4582 free(child_path);
4583 if (err)
4584 goto done;
4587 done:
4588 if (tree)
4589 got_object_tree_close(tree);
4590 free(tree_id);
4591 return err;
4594 static const struct got_error *
4595 cmd_tree(int argc, char *argv[])
4597 const struct got_error *error;
4598 struct got_repository *repo = NULL;
4599 struct got_worktree *worktree = NULL;
4600 const char *path, *refname = NULL;
4601 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4602 struct got_object_id *commit_id = NULL;
4603 char *commit_id_str = NULL;
4604 int show_ids = 0, recurse = 0;
4605 int ch;
4607 #ifndef PROFILE
4608 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4609 NULL) == -1)
4610 err(1, "pledge");
4611 #endif
4613 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4614 switch (ch) {
4615 case 'c':
4616 commit_id_str = optarg;
4617 break;
4618 case 'r':
4619 repo_path = realpath(optarg, NULL);
4620 if (repo_path == NULL)
4621 return got_error_from_errno2("realpath",
4622 optarg);
4623 got_path_strip_trailing_slashes(repo_path);
4624 break;
4625 case 'i':
4626 show_ids = 1;
4627 break;
4628 case 'R':
4629 recurse = 1;
4630 break;
4631 default:
4632 usage_tree();
4633 /* NOTREACHED */
4637 argc -= optind;
4638 argv += optind;
4640 if (argc == 1)
4641 path = argv[0];
4642 else if (argc > 1)
4643 usage_tree();
4644 else
4645 path = NULL;
4647 cwd = getcwd(NULL, 0);
4648 if (cwd == NULL) {
4649 error = got_error_from_errno("getcwd");
4650 goto done;
4652 if (repo_path == NULL) {
4653 error = got_worktree_open(&worktree, cwd);
4654 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4655 goto done;
4656 else
4657 error = NULL;
4658 if (worktree) {
4659 repo_path =
4660 strdup(got_worktree_get_repo_path(worktree));
4661 if (repo_path == NULL)
4662 error = got_error_from_errno("strdup");
4663 if (error)
4664 goto done;
4665 } else {
4666 repo_path = strdup(cwd);
4667 if (repo_path == NULL) {
4668 error = got_error_from_errno("strdup");
4669 goto done;
4674 error = got_repo_open(&repo, repo_path, NULL);
4675 if (error != NULL)
4676 goto done;
4678 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4679 if (error)
4680 goto done;
4682 if (path == NULL) {
4683 if (worktree) {
4684 char *p, *worktree_subdir = cwd +
4685 strlen(got_worktree_get_root_path(worktree));
4686 if (asprintf(&p, "%s/%s",
4687 got_worktree_get_path_prefix(worktree),
4688 worktree_subdir) == -1) {
4689 error = got_error_from_errno("asprintf");
4690 goto done;
4692 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4693 free(p);
4694 if (error)
4695 goto done;
4696 } else
4697 path = "/";
4699 if (in_repo_path == NULL) {
4700 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4701 if (error != NULL)
4702 goto done;
4705 if (commit_id_str == NULL) {
4706 struct got_reference *head_ref;
4707 if (worktree)
4708 refname = got_worktree_get_head_ref_name(worktree);
4709 else
4710 refname = GOT_REF_HEAD;
4711 error = got_ref_open(&head_ref, repo, refname, 0);
4712 if (error != NULL)
4713 goto done;
4714 error = got_ref_resolve(&commit_id, repo, head_ref);
4715 got_ref_close(head_ref);
4716 if (error != NULL)
4717 goto done;
4718 } else {
4719 error = got_repo_match_object_id(&commit_id, NULL,
4720 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4721 if (error)
4722 goto done;
4725 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4726 in_repo_path, repo);
4727 done:
4728 free(in_repo_path);
4729 free(repo_path);
4730 free(cwd);
4731 free(commit_id);
4732 if (worktree)
4733 got_worktree_close(worktree);
4734 if (repo) {
4735 const struct got_error *repo_error;
4736 repo_error = got_repo_close(repo);
4737 if (error == NULL)
4738 error = repo_error;
4740 return error;
4743 __dead static void
4744 usage_status(void)
4746 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4747 getprogname());
4748 exit(1);
4751 static const struct got_error *
4752 print_status(void *arg, unsigned char status, unsigned char staged_status,
4753 const char *path, struct got_object_id *blob_id,
4754 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4755 int dirfd, const char *de_name)
4757 if (status == staged_status && (status == GOT_STATUS_DELETE))
4758 status = GOT_STATUS_NO_CHANGE;
4759 if (arg) {
4760 char *status_codes = arg;
4761 size_t ncodes = strlen(status_codes);
4762 int i;
4763 for (i = 0; i < ncodes ; i++) {
4764 if (status == status_codes[i] ||
4765 staged_status == status_codes[i])
4766 break;
4768 if (i == ncodes)
4769 return NULL;
4771 printf("%c%c %s\n", status, staged_status, path);
4772 return NULL;
4775 static const struct got_error *
4776 cmd_status(int argc, char *argv[])
4778 const struct got_error *error = NULL;
4779 struct got_repository *repo = NULL;
4780 struct got_worktree *worktree = NULL;
4781 char *cwd = NULL, *status_codes = NULL;;
4782 struct got_pathlist_head paths;
4783 struct got_pathlist_entry *pe;
4784 int ch, i;
4786 TAILQ_INIT(&paths);
4788 while ((ch = getopt(argc, argv, "s:")) != -1) {
4789 switch (ch) {
4790 case 's':
4791 for (i = 0; i < strlen(optarg); i++) {
4792 switch (optarg[i]) {
4793 case GOT_STATUS_MODIFY:
4794 case GOT_STATUS_ADD:
4795 case GOT_STATUS_DELETE:
4796 case GOT_STATUS_CONFLICT:
4797 case GOT_STATUS_MISSING:
4798 case GOT_STATUS_OBSTRUCTED:
4799 case GOT_STATUS_UNVERSIONED:
4800 case GOT_STATUS_MODE_CHANGE:
4801 case GOT_STATUS_NONEXISTENT:
4802 break;
4803 default:
4804 errx(1, "invalid status code '%c'",
4805 optarg[i]);
4808 status_codes = optarg;
4809 break;
4810 default:
4811 usage_status();
4812 /* NOTREACHED */
4816 argc -= optind;
4817 argv += optind;
4819 #ifndef PROFILE
4820 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4821 NULL) == -1)
4822 err(1, "pledge");
4823 #endif
4824 cwd = getcwd(NULL, 0);
4825 if (cwd == NULL) {
4826 error = got_error_from_errno("getcwd");
4827 goto done;
4830 error = got_worktree_open(&worktree, cwd);
4831 if (error) {
4832 if (error->code == GOT_ERR_NOT_WORKTREE)
4833 error = wrap_not_worktree_error(error, "status", cwd);
4834 goto done;
4837 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4838 NULL);
4839 if (error != NULL)
4840 goto done;
4842 error = apply_unveil(got_repo_get_path(repo), 1,
4843 got_worktree_get_root_path(worktree));
4844 if (error)
4845 goto done;
4847 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4848 if (error)
4849 goto done;
4851 error = got_worktree_status(worktree, &paths, repo, print_status,
4852 status_codes, check_cancelled, NULL);
4853 done:
4854 TAILQ_FOREACH(pe, &paths, entry)
4855 free((char *)pe->path);
4856 got_pathlist_free(&paths);
4857 free(cwd);
4858 return error;
4861 __dead static void
4862 usage_ref(void)
4864 fprintf(stderr,
4865 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4866 "[-d] [name]\n",
4867 getprogname());
4868 exit(1);
4871 static const struct got_error *
4872 list_refs(struct got_repository *repo, const char *refname)
4874 static const struct got_error *err = NULL;
4875 struct got_reflist_head refs;
4876 struct got_reflist_entry *re;
4878 SIMPLEQ_INIT(&refs);
4879 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4880 if (err)
4881 return err;
4883 SIMPLEQ_FOREACH(re, &refs, entry) {
4884 char *refstr;
4885 refstr = got_ref_to_str(re->ref);
4886 if (refstr == NULL)
4887 return got_error_from_errno("got_ref_to_str");
4888 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4889 free(refstr);
4892 got_ref_list_free(&refs);
4893 return NULL;
4896 static const struct got_error *
4897 delete_ref(struct got_repository *repo, const char *refname)
4899 const struct got_error *err = NULL;
4900 struct got_reference *ref;
4902 err = got_ref_open(&ref, repo, refname, 0);
4903 if (err)
4904 return err;
4906 err = got_ref_delete(ref, repo);
4907 got_ref_close(ref);
4908 return err;
4911 static const struct got_error *
4912 add_ref(struct got_repository *repo, const char *refname, const char *target)
4914 const struct got_error *err = NULL;
4915 struct got_object_id *id;
4916 struct got_reference *ref = NULL;
4919 * Don't let the user create a reference name with a leading '-'.
4920 * While technically a valid reference name, this case is usually
4921 * an unintended typo.
4923 if (refname[0] == '-')
4924 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4926 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4927 repo);
4928 if (err) {
4929 struct got_reference *target_ref;
4931 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4932 return err;
4933 err = got_ref_open(&target_ref, repo, target, 0);
4934 if (err)
4935 return err;
4936 err = got_ref_resolve(&id, repo, target_ref);
4937 got_ref_close(target_ref);
4938 if (err)
4939 return err;
4942 err = got_ref_alloc(&ref, refname, id);
4943 if (err)
4944 goto done;
4946 err = got_ref_write(ref, repo);
4947 done:
4948 if (ref)
4949 got_ref_close(ref);
4950 free(id);
4951 return err;
4954 static const struct got_error *
4955 add_symref(struct got_repository *repo, const char *refname, const char *target)
4957 const struct got_error *err = NULL;
4958 struct got_reference *ref = NULL;
4959 struct got_reference *target_ref = NULL;
4962 * Don't let the user create a reference name with a leading '-'.
4963 * While technically a valid reference name, this case is usually
4964 * an unintended typo.
4966 if (refname[0] == '-')
4967 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4969 err = got_ref_open(&target_ref, repo, target, 0);
4970 if (err)
4971 return err;
4973 err = got_ref_alloc_symref(&ref, refname, target_ref);
4974 if (err)
4975 goto done;
4977 err = got_ref_write(ref, repo);
4978 done:
4979 if (target_ref)
4980 got_ref_close(target_ref);
4981 if (ref)
4982 got_ref_close(ref);
4983 return err;
4986 static const struct got_error *
4987 cmd_ref(int argc, char *argv[])
4989 const struct got_error *error = NULL;
4990 struct got_repository *repo = NULL;
4991 struct got_worktree *worktree = NULL;
4992 char *cwd = NULL, *repo_path = NULL;
4993 int ch, do_list = 0, do_delete = 0;
4994 const char *obj_arg = NULL, *symref_target= NULL;
4995 char *refname = NULL;
4997 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4998 switch (ch) {
4999 case 'c':
5000 obj_arg = optarg;
5001 break;
5002 case 'd':
5003 do_delete = 1;
5004 break;
5005 case 'r':
5006 repo_path = realpath(optarg, NULL);
5007 if (repo_path == NULL)
5008 return got_error_from_errno2("realpath",
5009 optarg);
5010 got_path_strip_trailing_slashes(repo_path);
5011 break;
5012 case 'l':
5013 do_list = 1;
5014 break;
5015 case 's':
5016 symref_target = optarg;
5017 break;
5018 default:
5019 usage_ref();
5020 /* NOTREACHED */
5024 if (obj_arg && do_list)
5025 errx(1, "-c and -l options are mutually exclusive");
5026 if (obj_arg && do_delete)
5027 errx(1, "-c and -d options are mutually exclusive");
5028 if (obj_arg && symref_target)
5029 errx(1, "-c and -s options are mutually exclusive");
5030 if (symref_target && do_delete)
5031 errx(1, "-s and -d options are mutually exclusive");
5032 if (symref_target && do_list)
5033 errx(1, "-s and -l options are mutually exclusive");
5034 if (do_delete && do_list)
5035 errx(1, "-d and -l options are mutually exclusive");
5037 argc -= optind;
5038 argv += optind;
5040 if (do_list) {
5041 if (argc != 0 && argc != 1)
5042 usage_ref();
5043 if (argc == 1) {
5044 refname = strdup(argv[0]);
5045 if (refname == NULL) {
5046 error = got_error_from_errno("strdup");
5047 goto done;
5050 } else {
5051 if (argc != 1)
5052 usage_ref();
5053 refname = strdup(argv[0]);
5054 if (refname == NULL) {
5055 error = got_error_from_errno("strdup");
5056 goto done;
5060 if (refname)
5061 got_path_strip_trailing_slashes(refname);
5063 #ifndef PROFILE
5064 if (do_list) {
5065 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5066 NULL) == -1)
5067 err(1, "pledge");
5068 } else {
5069 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5070 "sendfd unveil", NULL) == -1)
5071 err(1, "pledge");
5073 #endif
5074 cwd = getcwd(NULL, 0);
5075 if (cwd == NULL) {
5076 error = got_error_from_errno("getcwd");
5077 goto done;
5080 if (repo_path == NULL) {
5081 error = got_worktree_open(&worktree, cwd);
5082 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5083 goto done;
5084 else
5085 error = NULL;
5086 if (worktree) {
5087 repo_path =
5088 strdup(got_worktree_get_repo_path(worktree));
5089 if (repo_path == NULL)
5090 error = got_error_from_errno("strdup");
5091 if (error)
5092 goto done;
5093 } else {
5094 repo_path = strdup(cwd);
5095 if (repo_path == NULL) {
5096 error = got_error_from_errno("strdup");
5097 goto done;
5102 error = got_repo_open(&repo, repo_path, NULL);
5103 if (error != NULL)
5104 goto done;
5106 error = apply_unveil(got_repo_get_path(repo), do_list,
5107 worktree ? got_worktree_get_root_path(worktree) : NULL);
5108 if (error)
5109 goto done;
5111 if (do_list)
5112 error = list_refs(repo, refname);
5113 else if (do_delete)
5114 error = delete_ref(repo, refname);
5115 else if (symref_target)
5116 error = add_symref(repo, refname, symref_target);
5117 else {
5118 if (obj_arg == NULL)
5119 usage_ref();
5120 error = add_ref(repo, refname, obj_arg);
5122 done:
5123 free(refname);
5124 if (repo)
5125 got_repo_close(repo);
5126 if (worktree)
5127 got_worktree_close(worktree);
5128 free(cwd);
5129 free(repo_path);
5130 return error;
5133 __dead static void
5134 usage_branch(void)
5136 fprintf(stderr,
5137 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5138 "[name]\n", getprogname());
5139 exit(1);
5142 static const struct got_error *
5143 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5144 struct got_reference *ref)
5146 const struct got_error *err = NULL;
5147 const char *refname, *marker = " ";
5148 char *refstr;
5150 refname = got_ref_get_name(ref);
5151 if (worktree && strcmp(refname,
5152 got_worktree_get_head_ref_name(worktree)) == 0) {
5153 struct got_object_id *id = NULL;
5155 err = got_ref_resolve(&id, repo, ref);
5156 if (err)
5157 return err;
5158 if (got_object_id_cmp(id,
5159 got_worktree_get_base_commit_id(worktree)) == 0)
5160 marker = "* ";
5161 else
5162 marker = "~ ";
5163 free(id);
5166 if (strncmp(refname, "refs/heads/", 11) == 0)
5167 refname += 11;
5168 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5169 refname += 18;
5171 refstr = got_ref_to_str(ref);
5172 if (refstr == NULL)
5173 return got_error_from_errno("got_ref_to_str");
5175 printf("%s%s: %s\n", marker, refname, refstr);
5176 free(refstr);
5177 return NULL;
5180 static const struct got_error *
5181 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5183 const char *refname;
5185 if (worktree == NULL)
5186 return got_error(GOT_ERR_NOT_WORKTREE);
5188 refname = got_worktree_get_head_ref_name(worktree);
5190 if (strncmp(refname, "refs/heads/", 11) == 0)
5191 refname += 11;
5192 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5193 refname += 18;
5195 printf("%s\n", refname);
5197 return NULL;
5200 static const struct got_error *
5201 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5203 static const struct got_error *err = NULL;
5204 struct got_reflist_head refs;
5205 struct got_reflist_entry *re;
5206 struct got_reference *temp_ref = NULL;
5207 int rebase_in_progress, histedit_in_progress;
5209 SIMPLEQ_INIT(&refs);
5211 if (worktree) {
5212 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5213 worktree);
5214 if (err)
5215 return err;
5217 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5218 worktree);
5219 if (err)
5220 return err;
5222 if (rebase_in_progress || histedit_in_progress) {
5223 err = got_ref_open(&temp_ref, repo,
5224 got_worktree_get_head_ref_name(worktree), 0);
5225 if (err)
5226 return err;
5227 list_branch(repo, worktree, temp_ref);
5228 got_ref_close(temp_ref);
5232 err = got_ref_list(&refs, repo, "refs/heads",
5233 got_ref_cmp_by_name, NULL);
5234 if (err)
5235 return err;
5237 SIMPLEQ_FOREACH(re, &refs, entry)
5238 list_branch(repo, worktree, re->ref);
5240 got_ref_list_free(&refs);
5241 return NULL;
5244 static const struct got_error *
5245 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5246 const char *branch_name)
5248 const struct got_error *err = NULL;
5249 struct got_reference *ref = NULL;
5250 char *refname;
5252 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5253 return got_error_from_errno("asprintf");
5255 err = got_ref_open(&ref, repo, refname, 0);
5256 if (err)
5257 goto done;
5259 if (worktree &&
5260 strcmp(got_worktree_get_head_ref_name(worktree),
5261 got_ref_get_name(ref)) == 0) {
5262 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5263 "will not delete this work tree's current branch");
5264 goto done;
5267 err = got_ref_delete(ref, repo);
5268 done:
5269 if (ref)
5270 got_ref_close(ref);
5271 free(refname);
5272 return err;
5275 static const struct got_error *
5276 add_branch(struct got_repository *repo, const char *branch_name,
5277 struct got_object_id *base_commit_id)
5279 const struct got_error *err = NULL;
5280 struct got_reference *ref = NULL;
5281 char *base_refname = NULL, *refname = NULL;
5284 * Don't let the user create a branch name with a leading '-'.
5285 * While technically a valid reference name, this case is usually
5286 * an unintended typo.
5288 if (branch_name[0] == '-')
5289 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5291 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5292 err = got_error_from_errno("asprintf");
5293 goto done;
5296 err = got_ref_open(&ref, repo, refname, 0);
5297 if (err == NULL) {
5298 err = got_error(GOT_ERR_BRANCH_EXISTS);
5299 goto done;
5300 } else if (err->code != GOT_ERR_NOT_REF)
5301 goto done;
5303 err = got_ref_alloc(&ref, refname, base_commit_id);
5304 if (err)
5305 goto done;
5307 err = got_ref_write(ref, repo);
5308 done:
5309 if (ref)
5310 got_ref_close(ref);
5311 free(base_refname);
5312 free(refname);
5313 return err;
5316 static const struct got_error *
5317 cmd_branch(int argc, char *argv[])
5319 const struct got_error *error = NULL;
5320 struct got_repository *repo = NULL;
5321 struct got_worktree *worktree = NULL;
5322 char *cwd = NULL, *repo_path = NULL;
5323 int ch, do_list = 0, do_show = 0, do_update = 1;
5324 const char *delref = NULL, *commit_id_arg = NULL;
5325 struct got_reference *ref = NULL;
5326 struct got_pathlist_head paths;
5327 struct got_pathlist_entry *pe;
5328 struct got_object_id *commit_id = NULL;
5329 char *commit_id_str = NULL;
5331 TAILQ_INIT(&paths);
5333 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5334 switch (ch) {
5335 case 'c':
5336 commit_id_arg = optarg;
5337 break;
5338 case 'd':
5339 delref = optarg;
5340 break;
5341 case 'r':
5342 repo_path = realpath(optarg, NULL);
5343 if (repo_path == NULL)
5344 return got_error_from_errno2("realpath",
5345 optarg);
5346 got_path_strip_trailing_slashes(repo_path);
5347 break;
5348 case 'l':
5349 do_list = 1;
5350 break;
5351 case 'n':
5352 do_update = 0;
5353 break;
5354 default:
5355 usage_branch();
5356 /* NOTREACHED */
5360 if (do_list && delref)
5361 errx(1, "-l and -d options are mutually exclusive");
5363 argc -= optind;
5364 argv += optind;
5366 if (!do_list && !delref && argc == 0)
5367 do_show = 1;
5369 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5370 errx(1, "-c option can only be used when creating a branch");
5372 if (do_list || delref) {
5373 if (argc > 0)
5374 usage_branch();
5375 } else if (!do_show && argc != 1)
5376 usage_branch();
5378 #ifndef PROFILE
5379 if (do_list || do_show) {
5380 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5381 NULL) == -1)
5382 err(1, "pledge");
5383 } else {
5384 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5385 "sendfd unveil", NULL) == -1)
5386 err(1, "pledge");
5388 #endif
5389 cwd = getcwd(NULL, 0);
5390 if (cwd == NULL) {
5391 error = got_error_from_errno("getcwd");
5392 goto done;
5395 if (repo_path == NULL) {
5396 error = got_worktree_open(&worktree, cwd);
5397 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5398 goto done;
5399 else
5400 error = NULL;
5401 if (worktree) {
5402 repo_path =
5403 strdup(got_worktree_get_repo_path(worktree));
5404 if (repo_path == NULL)
5405 error = got_error_from_errno("strdup");
5406 if (error)
5407 goto done;
5408 } else {
5409 repo_path = strdup(cwd);
5410 if (repo_path == NULL) {
5411 error = got_error_from_errno("strdup");
5412 goto done;
5417 error = got_repo_open(&repo, repo_path, NULL);
5418 if (error != NULL)
5419 goto done;
5421 error = apply_unveil(got_repo_get_path(repo), do_list,
5422 worktree ? got_worktree_get_root_path(worktree) : NULL);
5423 if (error)
5424 goto done;
5426 if (do_show)
5427 error = show_current_branch(repo, worktree);
5428 else if (do_list)
5429 error = list_branches(repo, worktree);
5430 else if (delref)
5431 error = delete_branch(repo, worktree, delref);
5432 else {
5433 if (commit_id_arg == NULL)
5434 commit_id_arg = worktree ?
5435 got_worktree_get_head_ref_name(worktree) :
5436 GOT_REF_HEAD;
5437 error = got_repo_match_object_id(&commit_id, NULL,
5438 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5439 if (error)
5440 goto done;
5441 error = add_branch(repo, argv[0], commit_id);
5442 if (error)
5443 goto done;
5444 if (worktree && do_update) {
5445 struct got_update_progress_arg upa;
5446 char *branch_refname = NULL;
5448 error = got_object_id_str(&commit_id_str, commit_id);
5449 if (error)
5450 goto done;
5451 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5452 worktree);
5453 if (error)
5454 goto done;
5455 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5456 == -1) {
5457 error = got_error_from_errno("asprintf");
5458 goto done;
5460 error = got_ref_open(&ref, repo, branch_refname, 0);
5461 free(branch_refname);
5462 if (error)
5463 goto done;
5464 error = switch_head_ref(ref, commit_id, worktree,
5465 repo);
5466 if (error)
5467 goto done;
5468 error = got_worktree_set_base_commit_id(worktree, repo,
5469 commit_id);
5470 if (error)
5471 goto done;
5472 memset(&upa, 0, sizeof(upa));
5473 error = got_worktree_checkout_files(worktree, &paths,
5474 repo, update_progress, &upa, check_cancelled,
5475 NULL);
5476 if (error)
5477 goto done;
5478 if (upa.did_something)
5479 printf("Updated to commit %s\n", commit_id_str);
5480 print_update_progress_stats(&upa);
5483 done:
5484 if (ref)
5485 got_ref_close(ref);
5486 if (repo)
5487 got_repo_close(repo);
5488 if (worktree)
5489 got_worktree_close(worktree);
5490 free(cwd);
5491 free(repo_path);
5492 free(commit_id);
5493 free(commit_id_str);
5494 TAILQ_FOREACH(pe, &paths, entry)
5495 free((char *)pe->path);
5496 got_pathlist_free(&paths);
5497 return error;
5501 __dead static void
5502 usage_tag(void)
5504 fprintf(stderr,
5505 "usage: %s tag [-c commit] [-r repository] [-l] "
5506 "[-m message] name\n", getprogname());
5507 exit(1);
5510 #if 0
5511 static const struct got_error *
5512 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5514 const struct got_error *err = NULL;
5515 struct got_reflist_entry *re, *se, *new;
5516 struct got_object_id *re_id, *se_id;
5517 struct got_tag_object *re_tag, *se_tag;
5518 time_t re_time, se_time;
5520 SIMPLEQ_FOREACH(re, tags, entry) {
5521 se = SIMPLEQ_FIRST(sorted);
5522 if (se == NULL) {
5523 err = got_reflist_entry_dup(&new, re);
5524 if (err)
5525 return err;
5526 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5527 continue;
5528 } else {
5529 err = got_ref_resolve(&re_id, repo, re->ref);
5530 if (err)
5531 break;
5532 err = got_object_open_as_tag(&re_tag, repo, re_id);
5533 free(re_id);
5534 if (err)
5535 break;
5536 re_time = got_object_tag_get_tagger_time(re_tag);
5537 got_object_tag_close(re_tag);
5540 while (se) {
5541 err = got_ref_resolve(&se_id, repo, re->ref);
5542 if (err)
5543 break;
5544 err = got_object_open_as_tag(&se_tag, repo, se_id);
5545 free(se_id);
5546 if (err)
5547 break;
5548 se_time = got_object_tag_get_tagger_time(se_tag);
5549 got_object_tag_close(se_tag);
5551 if (se_time > re_time) {
5552 err = got_reflist_entry_dup(&new, re);
5553 if (err)
5554 return err;
5555 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5556 break;
5558 se = SIMPLEQ_NEXT(se, entry);
5559 continue;
5562 done:
5563 return err;
5565 #endif
5567 static const struct got_error *
5568 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5570 static const struct got_error *err = NULL;
5571 struct got_reflist_head refs;
5572 struct got_reflist_entry *re;
5574 SIMPLEQ_INIT(&refs);
5576 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5577 if (err)
5578 return err;
5580 SIMPLEQ_FOREACH(re, &refs, entry) {
5581 const char *refname;
5582 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5583 char datebuf[26];
5584 const char *tagger;
5585 time_t tagger_time;
5586 struct got_object_id *id;
5587 struct got_tag_object *tag;
5588 struct got_commit_object *commit = NULL;
5590 refname = got_ref_get_name(re->ref);
5591 if (strncmp(refname, "refs/tags/", 10) != 0)
5592 continue;
5593 refname += 10;
5594 refstr = got_ref_to_str(re->ref);
5595 if (refstr == NULL) {
5596 err = got_error_from_errno("got_ref_to_str");
5597 break;
5599 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5600 free(refstr);
5602 err = got_ref_resolve(&id, repo, re->ref);
5603 if (err)
5604 break;
5605 err = got_object_open_as_tag(&tag, repo, id);
5606 if (err) {
5607 if (err->code != GOT_ERR_OBJ_TYPE) {
5608 free(id);
5609 break;
5611 /* "lightweight" tag */
5612 err = got_object_open_as_commit(&commit, repo, id);
5613 if (err) {
5614 free(id);
5615 break;
5617 tagger = got_object_commit_get_committer(commit);
5618 tagger_time =
5619 got_object_commit_get_committer_time(commit);
5620 err = got_object_id_str(&id_str, id);
5621 free(id);
5622 if (err)
5623 break;
5624 } else {
5625 free(id);
5626 tagger = got_object_tag_get_tagger(tag);
5627 tagger_time = got_object_tag_get_tagger_time(tag);
5628 err = got_object_id_str(&id_str,
5629 got_object_tag_get_object_id(tag));
5630 if (err)
5631 break;
5633 printf("from: %s\n", tagger);
5634 datestr = get_datestr(&tagger_time, datebuf);
5635 if (datestr)
5636 printf("date: %s UTC\n", datestr);
5637 if (commit)
5638 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5639 else {
5640 switch (got_object_tag_get_object_type(tag)) {
5641 case GOT_OBJ_TYPE_BLOB:
5642 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5643 id_str);
5644 break;
5645 case GOT_OBJ_TYPE_TREE:
5646 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5647 id_str);
5648 break;
5649 case GOT_OBJ_TYPE_COMMIT:
5650 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5651 id_str);
5652 break;
5653 case GOT_OBJ_TYPE_TAG:
5654 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5655 id_str);
5656 break;
5657 default:
5658 break;
5661 free(id_str);
5662 if (commit) {
5663 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5664 if (err)
5665 break;
5666 got_object_commit_close(commit);
5667 } else {
5668 tagmsg0 = strdup(got_object_tag_get_message(tag));
5669 got_object_tag_close(tag);
5670 if (tagmsg0 == NULL) {
5671 err = got_error_from_errno("strdup");
5672 break;
5676 tagmsg = tagmsg0;
5677 do {
5678 line = strsep(&tagmsg, "\n");
5679 if (line)
5680 printf(" %s\n", line);
5681 } while (line);
5682 free(tagmsg0);
5685 got_ref_list_free(&refs);
5686 return NULL;
5689 static const struct got_error *
5690 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5691 const char *tag_name, const char *repo_path)
5693 const struct got_error *err = NULL;
5694 char *template = NULL, *initial_content = NULL;
5695 char *editor = NULL;
5696 int initial_content_len;
5697 int fd = -1;
5699 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5700 err = got_error_from_errno("asprintf");
5701 goto done;
5704 initial_content_len = asprintf(&initial_content,
5705 "\n# tagging commit %s as %s\n",
5706 commit_id_str, tag_name);
5707 if (initial_content_len == -1) {
5708 err = got_error_from_errno("asprintf");
5709 goto done;
5712 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5713 if (err)
5714 goto done;
5716 if (write(fd, initial_content, initial_content_len) == -1) {
5717 err = got_error_from_errno2("write", *tagmsg_path);
5718 goto done;
5721 err = get_editor(&editor);
5722 if (err)
5723 goto done;
5724 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5725 done:
5726 free(initial_content);
5727 free(template);
5728 free(editor);
5730 if (fd != -1 && close(fd) == -1 && err == NULL)
5731 err = got_error_from_errno2("close", *tagmsg_path);
5733 /* Editor is done; we can now apply unveil(2) */
5734 if (err == NULL)
5735 err = apply_unveil(repo_path, 0, NULL);
5736 if (err) {
5737 free(*tagmsg);
5738 *tagmsg = NULL;
5740 return err;
5743 static const struct got_error *
5744 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5745 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5747 const struct got_error *err = NULL;
5748 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5749 char *label = NULL, *commit_id_str = NULL;
5750 struct got_reference *ref = NULL;
5751 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5752 char *tagmsg_path = NULL, *tag_id_str = NULL;
5753 int preserve_tagmsg = 0;
5756 * Don't let the user create a tag name with a leading '-'.
5757 * While technically a valid reference name, this case is usually
5758 * an unintended typo.
5760 if (tag_name[0] == '-')
5761 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5763 err = get_author(&tagger, repo, worktree);
5764 if (err)
5765 return err;
5767 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5768 GOT_OBJ_TYPE_COMMIT, 1, repo);
5769 if (err)
5770 goto done;
5772 err = got_object_id_str(&commit_id_str, commit_id);
5773 if (err)
5774 goto done;
5776 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5777 refname = strdup(tag_name);
5778 if (refname == NULL) {
5779 err = got_error_from_errno("strdup");
5780 goto done;
5782 tag_name += 10;
5783 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5784 err = got_error_from_errno("asprintf");
5785 goto done;
5788 err = got_ref_open(&ref, repo, refname, 0);
5789 if (err == NULL) {
5790 err = got_error(GOT_ERR_TAG_EXISTS);
5791 goto done;
5792 } else if (err->code != GOT_ERR_NOT_REF)
5793 goto done;
5795 if (tagmsg_arg == NULL) {
5796 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5797 tag_name, got_repo_get_path(repo));
5798 if (err) {
5799 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5800 tagmsg_path != NULL)
5801 preserve_tagmsg = 1;
5802 goto done;
5806 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5807 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5808 if (err) {
5809 if (tagmsg_path)
5810 preserve_tagmsg = 1;
5811 goto done;
5814 err = got_ref_alloc(&ref, refname, tag_id);
5815 if (err) {
5816 if (tagmsg_path)
5817 preserve_tagmsg = 1;
5818 goto done;
5821 err = got_ref_write(ref, repo);
5822 if (err) {
5823 if (tagmsg_path)
5824 preserve_tagmsg = 1;
5825 goto done;
5828 err = got_object_id_str(&tag_id_str, tag_id);
5829 if (err) {
5830 if (tagmsg_path)
5831 preserve_tagmsg = 1;
5832 goto done;
5834 printf("Created tag %s\n", tag_id_str);
5835 done:
5836 if (preserve_tagmsg) {
5837 fprintf(stderr, "%s: tag message preserved in %s\n",
5838 getprogname(), tagmsg_path);
5839 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5840 err = got_error_from_errno2("unlink", tagmsg_path);
5841 free(tag_id_str);
5842 if (ref)
5843 got_ref_close(ref);
5844 free(commit_id);
5845 free(commit_id_str);
5846 free(refname);
5847 free(tagmsg);
5848 free(tagmsg_path);
5849 free(tagger);
5850 return err;
5853 static const struct got_error *
5854 cmd_tag(int argc, char *argv[])
5856 const struct got_error *error = NULL;
5857 struct got_repository *repo = NULL;
5858 struct got_worktree *worktree = NULL;
5859 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5860 char *gitconfig_path = NULL;
5861 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5862 int ch, do_list = 0;
5864 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5865 switch (ch) {
5866 case 'c':
5867 commit_id_arg = optarg;
5868 break;
5869 case 'm':
5870 tagmsg = optarg;
5871 break;
5872 case 'r':
5873 repo_path = realpath(optarg, NULL);
5874 if (repo_path == NULL)
5875 return got_error_from_errno2("realpath",
5876 optarg);
5877 got_path_strip_trailing_slashes(repo_path);
5878 break;
5879 case 'l':
5880 do_list = 1;
5881 break;
5882 default:
5883 usage_tag();
5884 /* NOTREACHED */
5888 argc -= optind;
5889 argv += optind;
5891 if (do_list) {
5892 if (commit_id_arg != NULL)
5893 errx(1,
5894 "-c option can only be used when creating a tag");
5895 if (tagmsg)
5896 errx(1, "-l and -m options are mutually exclusive");
5897 if (argc > 0)
5898 usage_tag();
5899 } else if (argc != 1)
5900 usage_tag();
5902 tag_name = argv[0];
5904 #ifndef PROFILE
5905 if (do_list) {
5906 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5907 NULL) == -1)
5908 err(1, "pledge");
5909 } else {
5910 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5911 "sendfd unveil", NULL) == -1)
5912 err(1, "pledge");
5914 #endif
5915 cwd = getcwd(NULL, 0);
5916 if (cwd == NULL) {
5917 error = got_error_from_errno("getcwd");
5918 goto done;
5921 if (repo_path == NULL) {
5922 error = got_worktree_open(&worktree, cwd);
5923 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5924 goto done;
5925 else
5926 error = NULL;
5927 if (worktree) {
5928 repo_path =
5929 strdup(got_worktree_get_repo_path(worktree));
5930 if (repo_path == NULL)
5931 error = got_error_from_errno("strdup");
5932 if (error)
5933 goto done;
5934 } else {
5935 repo_path = strdup(cwd);
5936 if (repo_path == NULL) {
5937 error = got_error_from_errno("strdup");
5938 goto done;
5943 if (do_list) {
5944 error = got_repo_open(&repo, repo_path, NULL);
5945 if (error != NULL)
5946 goto done;
5947 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5948 if (error)
5949 goto done;
5950 error = list_tags(repo, worktree);
5951 } else {
5952 error = get_gitconfig_path(&gitconfig_path);
5953 if (error)
5954 goto done;
5955 error = got_repo_open(&repo, repo_path, gitconfig_path);
5956 if (error != NULL)
5957 goto done;
5959 if (tagmsg) {
5960 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5961 if (error)
5962 goto done;
5965 if (commit_id_arg == NULL) {
5966 struct got_reference *head_ref;
5967 struct got_object_id *commit_id;
5968 error = got_ref_open(&head_ref, repo,
5969 worktree ? got_worktree_get_head_ref_name(worktree)
5970 : GOT_REF_HEAD, 0);
5971 if (error)
5972 goto done;
5973 error = got_ref_resolve(&commit_id, repo, head_ref);
5974 got_ref_close(head_ref);
5975 if (error)
5976 goto done;
5977 error = got_object_id_str(&commit_id_str, commit_id);
5978 free(commit_id);
5979 if (error)
5980 goto done;
5983 error = add_tag(repo, worktree, tag_name,
5984 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5986 done:
5987 if (repo)
5988 got_repo_close(repo);
5989 if (worktree)
5990 got_worktree_close(worktree);
5991 free(cwd);
5992 free(repo_path);
5993 free(gitconfig_path);
5994 free(commit_id_str);
5995 return error;
5998 __dead static void
5999 usage_add(void)
6001 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6002 getprogname());
6003 exit(1);
6006 static const struct got_error *
6007 add_progress(void *arg, unsigned char status, const char *path)
6009 while (path[0] == '/')
6010 path++;
6011 printf("%c %s\n", status, path);
6012 return NULL;
6015 static const struct got_error *
6016 cmd_add(int argc, char *argv[])
6018 const struct got_error *error = NULL;
6019 struct got_repository *repo = NULL;
6020 struct got_worktree *worktree = NULL;
6021 char *cwd = NULL;
6022 struct got_pathlist_head paths;
6023 struct got_pathlist_entry *pe;
6024 int ch, can_recurse = 0, no_ignores = 0;
6026 TAILQ_INIT(&paths);
6028 while ((ch = getopt(argc, argv, "IR")) != -1) {
6029 switch (ch) {
6030 case 'I':
6031 no_ignores = 1;
6032 break;
6033 case 'R':
6034 can_recurse = 1;
6035 break;
6036 default:
6037 usage_add();
6038 /* NOTREACHED */
6042 argc -= optind;
6043 argv += optind;
6045 #ifndef PROFILE
6046 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6047 NULL) == -1)
6048 err(1, "pledge");
6049 #endif
6050 if (argc < 1)
6051 usage_add();
6053 cwd = getcwd(NULL, 0);
6054 if (cwd == NULL) {
6055 error = got_error_from_errno("getcwd");
6056 goto done;
6059 error = got_worktree_open(&worktree, cwd);
6060 if (error) {
6061 if (error->code == GOT_ERR_NOT_WORKTREE)
6062 error = wrap_not_worktree_error(error, "add", cwd);
6063 goto done;
6066 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6067 NULL);
6068 if (error != NULL)
6069 goto done;
6071 error = apply_unveil(got_repo_get_path(repo), 1,
6072 got_worktree_get_root_path(worktree));
6073 if (error)
6074 goto done;
6076 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6077 if (error)
6078 goto done;
6080 if (!can_recurse && no_ignores) {
6081 error = got_error_msg(GOT_ERR_BAD_PATH,
6082 "disregarding ignores requires -R option");
6083 goto done;
6087 if (!can_recurse) {
6088 char *ondisk_path;
6089 struct stat sb;
6090 TAILQ_FOREACH(pe, &paths, entry) {
6091 if (asprintf(&ondisk_path, "%s/%s",
6092 got_worktree_get_root_path(worktree),
6093 pe->path) == -1) {
6094 error = got_error_from_errno("asprintf");
6095 goto done;
6097 if (lstat(ondisk_path, &sb) == -1) {
6098 if (errno == ENOENT) {
6099 free(ondisk_path);
6100 continue;
6102 error = got_error_from_errno2("lstat",
6103 ondisk_path);
6104 free(ondisk_path);
6105 goto done;
6107 free(ondisk_path);
6108 if (S_ISDIR(sb.st_mode)) {
6109 error = got_error_msg(GOT_ERR_BAD_PATH,
6110 "adding directories requires -R option");
6111 goto done;
6116 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6117 NULL, repo, no_ignores);
6118 done:
6119 if (repo)
6120 got_repo_close(repo);
6121 if (worktree)
6122 got_worktree_close(worktree);
6123 TAILQ_FOREACH(pe, &paths, entry)
6124 free((char *)pe->path);
6125 got_pathlist_free(&paths);
6126 free(cwd);
6127 return error;
6130 __dead static void
6131 usage_remove(void)
6133 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6134 "path ...\n", getprogname());
6135 exit(1);
6138 static const struct got_error *
6139 print_remove_status(void *arg, unsigned char status,
6140 unsigned char staged_status, const char *path)
6142 while (path[0] == '/')
6143 path++;
6144 if (status == GOT_STATUS_NONEXISTENT)
6145 return NULL;
6146 if (status == staged_status && (status == GOT_STATUS_DELETE))
6147 status = GOT_STATUS_NO_CHANGE;
6148 printf("%c%c %s\n", status, staged_status, path);
6149 return NULL;
6152 static const struct got_error *
6153 cmd_remove(int argc, char *argv[])
6155 const struct got_error *error = NULL;
6156 struct got_worktree *worktree = NULL;
6157 struct got_repository *repo = NULL;
6158 const char *status_codes = NULL;
6159 char *cwd = NULL;
6160 struct got_pathlist_head paths;
6161 struct got_pathlist_entry *pe;
6162 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6164 TAILQ_INIT(&paths);
6166 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6167 switch (ch) {
6168 case 'f':
6169 delete_local_mods = 1;
6170 break;
6171 case 'k':
6172 keep_on_disk = 1;
6173 break;
6174 case 'R':
6175 can_recurse = 1;
6176 break;
6177 case 's':
6178 for (i = 0; i < strlen(optarg); i++) {
6179 switch (optarg[i]) {
6180 case GOT_STATUS_MODIFY:
6181 delete_local_mods = 1;
6182 break;
6183 case GOT_STATUS_MISSING:
6184 break;
6185 default:
6186 errx(1, "invalid status code '%c'",
6187 optarg[i]);
6190 status_codes = optarg;
6191 break;
6192 default:
6193 usage_remove();
6194 /* NOTREACHED */
6198 argc -= optind;
6199 argv += optind;
6201 #ifndef PROFILE
6202 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6203 NULL) == -1)
6204 err(1, "pledge");
6205 #endif
6206 if (argc < 1)
6207 usage_remove();
6209 cwd = getcwd(NULL, 0);
6210 if (cwd == NULL) {
6211 error = got_error_from_errno("getcwd");
6212 goto done;
6214 error = got_worktree_open(&worktree, cwd);
6215 if (error) {
6216 if (error->code == GOT_ERR_NOT_WORKTREE)
6217 error = wrap_not_worktree_error(error, "remove", cwd);
6218 goto done;
6221 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6222 NULL);
6223 if (error)
6224 goto done;
6226 error = apply_unveil(got_repo_get_path(repo), 1,
6227 got_worktree_get_root_path(worktree));
6228 if (error)
6229 goto done;
6231 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6232 if (error)
6233 goto done;
6235 if (!can_recurse) {
6236 char *ondisk_path;
6237 struct stat sb;
6238 TAILQ_FOREACH(pe, &paths, entry) {
6239 if (asprintf(&ondisk_path, "%s/%s",
6240 got_worktree_get_root_path(worktree),
6241 pe->path) == -1) {
6242 error = got_error_from_errno("asprintf");
6243 goto done;
6245 if (lstat(ondisk_path, &sb) == -1) {
6246 if (errno == ENOENT) {
6247 free(ondisk_path);
6248 continue;
6250 error = got_error_from_errno2("lstat",
6251 ondisk_path);
6252 free(ondisk_path);
6253 goto done;
6255 free(ondisk_path);
6256 if (S_ISDIR(sb.st_mode)) {
6257 error = got_error_msg(GOT_ERR_BAD_PATH,
6258 "removing directories requires -R option");
6259 goto done;
6264 error = got_worktree_schedule_delete(worktree, &paths,
6265 delete_local_mods, status_codes, print_remove_status, NULL,
6266 repo, keep_on_disk);
6267 done:
6268 if (repo)
6269 got_repo_close(repo);
6270 if (worktree)
6271 got_worktree_close(worktree);
6272 TAILQ_FOREACH(pe, &paths, entry)
6273 free((char *)pe->path);
6274 got_pathlist_free(&paths);
6275 free(cwd);
6276 return error;
6279 __dead static void
6280 usage_revert(void)
6282 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6283 "path ...\n", getprogname());
6284 exit(1);
6287 static const struct got_error *
6288 revert_progress(void *arg, unsigned char status, const char *path)
6290 if (status == GOT_STATUS_UNVERSIONED)
6291 return NULL;
6293 while (path[0] == '/')
6294 path++;
6295 printf("%c %s\n", status, path);
6296 return NULL;
6299 struct choose_patch_arg {
6300 FILE *patch_script_file;
6301 const char *action;
6304 static const struct got_error *
6305 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6306 int nchanges, const char *action)
6308 char *line = NULL;
6309 size_t linesize = 0;
6310 ssize_t linelen;
6312 switch (status) {
6313 case GOT_STATUS_ADD:
6314 printf("A %s\n%s this addition? [y/n] ", path, action);
6315 break;
6316 case GOT_STATUS_DELETE:
6317 printf("D %s\n%s this deletion? [y/n] ", path, action);
6318 break;
6319 case GOT_STATUS_MODIFY:
6320 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6321 return got_error_from_errno("fseek");
6322 printf(GOT_COMMIT_SEP_STR);
6323 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6324 printf("%s", line);
6325 if (ferror(patch_file))
6326 return got_error_from_errno("getline");
6327 printf(GOT_COMMIT_SEP_STR);
6328 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6329 path, n, nchanges, action);
6330 break;
6331 default:
6332 return got_error_path(path, GOT_ERR_FILE_STATUS);
6335 return NULL;
6338 static const struct got_error *
6339 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6340 FILE *patch_file, int n, int nchanges)
6342 const struct got_error *err = NULL;
6343 char *line = NULL;
6344 size_t linesize = 0;
6345 ssize_t linelen;
6346 int resp = ' ';
6347 struct choose_patch_arg *a = arg;
6349 *choice = GOT_PATCH_CHOICE_NONE;
6351 if (a->patch_script_file) {
6352 char *nl;
6353 err = show_change(status, path, patch_file, n, nchanges,
6354 a->action);
6355 if (err)
6356 return err;
6357 linelen = getline(&line, &linesize, a->patch_script_file);
6358 if (linelen == -1) {
6359 if (ferror(a->patch_script_file))
6360 return got_error_from_errno("getline");
6361 return NULL;
6363 nl = strchr(line, '\n');
6364 if (nl)
6365 *nl = '\0';
6366 if (strcmp(line, "y") == 0) {
6367 *choice = GOT_PATCH_CHOICE_YES;
6368 printf("y\n");
6369 } else if (strcmp(line, "n") == 0) {
6370 *choice = GOT_PATCH_CHOICE_NO;
6371 printf("n\n");
6372 } else if (strcmp(line, "q") == 0 &&
6373 status == GOT_STATUS_MODIFY) {
6374 *choice = GOT_PATCH_CHOICE_QUIT;
6375 printf("q\n");
6376 } else
6377 printf("invalid response '%s'\n", line);
6378 free(line);
6379 return NULL;
6382 while (resp != 'y' && resp != 'n' && resp != 'q') {
6383 err = show_change(status, path, patch_file, n, nchanges,
6384 a->action);
6385 if (err)
6386 return err;
6387 resp = getchar();
6388 if (resp == '\n')
6389 resp = getchar();
6390 if (status == GOT_STATUS_MODIFY) {
6391 if (resp != 'y' && resp != 'n' && resp != 'q') {
6392 printf("invalid response '%c'\n", resp);
6393 resp = ' ';
6395 } else if (resp != 'y' && resp != 'n') {
6396 printf("invalid response '%c'\n", resp);
6397 resp = ' ';
6401 if (resp == 'y')
6402 *choice = GOT_PATCH_CHOICE_YES;
6403 else if (resp == 'n')
6404 *choice = GOT_PATCH_CHOICE_NO;
6405 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6406 *choice = GOT_PATCH_CHOICE_QUIT;
6408 return NULL;
6412 static const struct got_error *
6413 cmd_revert(int argc, char *argv[])
6415 const struct got_error *error = NULL;
6416 struct got_worktree *worktree = NULL;
6417 struct got_repository *repo = NULL;
6418 char *cwd = NULL, *path = NULL;
6419 struct got_pathlist_head paths;
6420 struct got_pathlist_entry *pe;
6421 int ch, can_recurse = 0, pflag = 0;
6422 FILE *patch_script_file = NULL;
6423 const char *patch_script_path = NULL;
6424 struct choose_patch_arg cpa;
6426 TAILQ_INIT(&paths);
6428 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6429 switch (ch) {
6430 case 'p':
6431 pflag = 1;
6432 break;
6433 case 'F':
6434 patch_script_path = optarg;
6435 break;
6436 case 'R':
6437 can_recurse = 1;
6438 break;
6439 default:
6440 usage_revert();
6441 /* NOTREACHED */
6445 argc -= optind;
6446 argv += optind;
6448 #ifndef PROFILE
6449 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6450 "unveil", NULL) == -1)
6451 err(1, "pledge");
6452 #endif
6453 if (argc < 1)
6454 usage_revert();
6455 if (patch_script_path && !pflag)
6456 errx(1, "-F option can only be used together with -p option");
6458 cwd = getcwd(NULL, 0);
6459 if (cwd == NULL) {
6460 error = got_error_from_errno("getcwd");
6461 goto done;
6463 error = got_worktree_open(&worktree, cwd);
6464 if (error) {
6465 if (error->code == GOT_ERR_NOT_WORKTREE)
6466 error = wrap_not_worktree_error(error, "revert", cwd);
6467 goto done;
6470 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6471 NULL);
6472 if (error != NULL)
6473 goto done;
6475 if (patch_script_path) {
6476 patch_script_file = fopen(patch_script_path, "r");
6477 if (patch_script_file == NULL) {
6478 error = got_error_from_errno2("fopen",
6479 patch_script_path);
6480 goto done;
6483 error = apply_unveil(got_repo_get_path(repo), 1,
6484 got_worktree_get_root_path(worktree));
6485 if (error)
6486 goto done;
6488 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6489 if (error)
6490 goto done;
6492 if (!can_recurse) {
6493 char *ondisk_path;
6494 struct stat sb;
6495 TAILQ_FOREACH(pe, &paths, entry) {
6496 if (asprintf(&ondisk_path, "%s/%s",
6497 got_worktree_get_root_path(worktree),
6498 pe->path) == -1) {
6499 error = got_error_from_errno("asprintf");
6500 goto done;
6502 if (lstat(ondisk_path, &sb) == -1) {
6503 if (errno == ENOENT) {
6504 free(ondisk_path);
6505 continue;
6507 error = got_error_from_errno2("lstat",
6508 ondisk_path);
6509 free(ondisk_path);
6510 goto done;
6512 free(ondisk_path);
6513 if (S_ISDIR(sb.st_mode)) {
6514 error = got_error_msg(GOT_ERR_BAD_PATH,
6515 "reverting directories requires -R option");
6516 goto done;
6521 cpa.patch_script_file = patch_script_file;
6522 cpa.action = "revert";
6523 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6524 pflag ? choose_patch : NULL, &cpa, repo);
6525 done:
6526 if (patch_script_file && fclose(patch_script_file) == EOF &&
6527 error == NULL)
6528 error = got_error_from_errno2("fclose", patch_script_path);
6529 if (repo)
6530 got_repo_close(repo);
6531 if (worktree)
6532 got_worktree_close(worktree);
6533 free(path);
6534 free(cwd);
6535 return error;
6538 __dead static void
6539 usage_commit(void)
6541 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6542 getprogname());
6543 exit(1);
6546 struct collect_commit_logmsg_arg {
6547 const char *cmdline_log;
6548 const char *editor;
6549 const char *worktree_path;
6550 const char *branch_name;
6551 const char *repo_path;
6552 char *logmsg_path;
6556 static const struct got_error *
6557 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6558 void *arg)
6560 char *initial_content = NULL;
6561 struct got_pathlist_entry *pe;
6562 const struct got_error *err = NULL;
6563 char *template = NULL;
6564 struct collect_commit_logmsg_arg *a = arg;
6565 int initial_content_len;
6566 int fd = -1;
6567 size_t len;
6569 /* if a message was specified on the command line, just use it */
6570 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6571 len = strlen(a->cmdline_log) + 1;
6572 *logmsg = malloc(len + 1);
6573 if (*logmsg == NULL)
6574 return got_error_from_errno("malloc");
6575 strlcpy(*logmsg, a->cmdline_log, len);
6576 return NULL;
6579 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6580 return got_error_from_errno("asprintf");
6582 initial_content_len = asprintf(&initial_content,
6583 "\n# changes to be committed on branch %s:\n",
6584 a->branch_name);
6585 if (initial_content_len == -1)
6586 return got_error_from_errno("asprintf");
6588 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6589 if (err)
6590 goto done;
6592 if (write(fd, initial_content, initial_content_len) == -1) {
6593 err = got_error_from_errno2("write", a->logmsg_path);
6594 goto done;
6597 TAILQ_FOREACH(pe, commitable_paths, entry) {
6598 struct got_commitable *ct = pe->data;
6599 dprintf(fd, "# %c %s\n",
6600 got_commitable_get_status(ct),
6601 got_commitable_get_path(ct));
6604 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6605 done:
6606 free(initial_content);
6607 free(template);
6609 if (fd != -1 && close(fd) == -1 && err == NULL)
6610 err = got_error_from_errno2("close", a->logmsg_path);
6612 /* Editor is done; we can now apply unveil(2) */
6613 if (err == NULL)
6614 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6615 if (err) {
6616 free(*logmsg);
6617 *logmsg = NULL;
6619 return err;
6622 static const struct got_error *
6623 cmd_commit(int argc, char *argv[])
6625 const struct got_error *error = NULL;
6626 struct got_worktree *worktree = NULL;
6627 struct got_repository *repo = NULL;
6628 char *cwd = NULL, *id_str = NULL;
6629 struct got_object_id *id = NULL;
6630 const char *logmsg = NULL;
6631 struct collect_commit_logmsg_arg cl_arg;
6632 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6633 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6634 int allow_bad_symlinks = 0;
6635 struct got_pathlist_head paths;
6637 TAILQ_INIT(&paths);
6638 cl_arg.logmsg_path = NULL;
6640 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6641 switch (ch) {
6642 case 'm':
6643 logmsg = optarg;
6644 break;
6645 case 'S':
6646 allow_bad_symlinks = 1;
6647 break;
6648 default:
6649 usage_commit();
6650 /* NOTREACHED */
6654 argc -= optind;
6655 argv += optind;
6657 #ifndef PROFILE
6658 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6659 "unveil", NULL) == -1)
6660 err(1, "pledge");
6661 #endif
6662 cwd = getcwd(NULL, 0);
6663 if (cwd == NULL) {
6664 error = got_error_from_errno("getcwd");
6665 goto done;
6667 error = got_worktree_open(&worktree, cwd);
6668 if (error) {
6669 if (error->code == GOT_ERR_NOT_WORKTREE)
6670 error = wrap_not_worktree_error(error, "commit", cwd);
6671 goto done;
6674 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6675 if (error)
6676 goto done;
6677 if (rebase_in_progress) {
6678 error = got_error(GOT_ERR_REBASING);
6679 goto done;
6682 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6683 worktree);
6684 if (error)
6685 goto done;
6687 error = get_gitconfig_path(&gitconfig_path);
6688 if (error)
6689 goto done;
6690 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6691 gitconfig_path);
6692 if (error != NULL)
6693 goto done;
6695 error = get_author(&author, repo, worktree);
6696 if (error)
6697 return error;
6700 * unveil(2) traverses exec(2); if an editor is used we have
6701 * to apply unveil after the log message has been written.
6703 if (logmsg == NULL || strlen(logmsg) == 0)
6704 error = get_editor(&editor);
6705 else
6706 error = apply_unveil(got_repo_get_path(repo), 0,
6707 got_worktree_get_root_path(worktree));
6708 if (error)
6709 goto done;
6711 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6712 if (error)
6713 goto done;
6715 cl_arg.editor = editor;
6716 cl_arg.cmdline_log = logmsg;
6717 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6718 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6719 if (!histedit_in_progress) {
6720 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6721 error = got_error(GOT_ERR_COMMIT_BRANCH);
6722 goto done;
6724 cl_arg.branch_name += 11;
6726 cl_arg.repo_path = got_repo_get_path(repo);
6727 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6728 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6729 print_status, NULL, repo);
6730 if (error) {
6731 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6732 cl_arg.logmsg_path != NULL)
6733 preserve_logmsg = 1;
6734 goto done;
6737 error = got_object_id_str(&id_str, id);
6738 if (error)
6739 goto done;
6740 printf("Created commit %s\n", id_str);
6741 done:
6742 if (preserve_logmsg) {
6743 fprintf(stderr, "%s: log message preserved in %s\n",
6744 getprogname(), cl_arg.logmsg_path);
6745 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6746 error == NULL)
6747 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6748 free(cl_arg.logmsg_path);
6749 if (repo)
6750 got_repo_close(repo);
6751 if (worktree)
6752 got_worktree_close(worktree);
6753 free(cwd);
6754 free(id_str);
6755 free(gitconfig_path);
6756 free(editor);
6757 free(author);
6758 return error;
6761 __dead static void
6762 usage_cherrypick(void)
6764 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6765 exit(1);
6768 static const struct got_error *
6769 cmd_cherrypick(int argc, char *argv[])
6771 const struct got_error *error = NULL;
6772 struct got_worktree *worktree = NULL;
6773 struct got_repository *repo = NULL;
6774 char *cwd = NULL, *commit_id_str = NULL;
6775 struct got_object_id *commit_id = NULL;
6776 struct got_commit_object *commit = NULL;
6777 struct got_object_qid *pid;
6778 struct got_reference *head_ref = NULL;
6779 int ch;
6780 struct got_update_progress_arg upa;
6782 while ((ch = getopt(argc, argv, "")) != -1) {
6783 switch (ch) {
6784 default:
6785 usage_cherrypick();
6786 /* NOTREACHED */
6790 argc -= optind;
6791 argv += optind;
6793 #ifndef PROFILE
6794 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6795 "unveil", NULL) == -1)
6796 err(1, "pledge");
6797 #endif
6798 if (argc != 1)
6799 usage_cherrypick();
6801 cwd = getcwd(NULL, 0);
6802 if (cwd == NULL) {
6803 error = got_error_from_errno("getcwd");
6804 goto done;
6806 error = got_worktree_open(&worktree, cwd);
6807 if (error) {
6808 if (error->code == GOT_ERR_NOT_WORKTREE)
6809 error = wrap_not_worktree_error(error, "cherrypick",
6810 cwd);
6811 goto done;
6814 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6815 NULL);
6816 if (error != NULL)
6817 goto done;
6819 error = apply_unveil(got_repo_get_path(repo), 0,
6820 got_worktree_get_root_path(worktree));
6821 if (error)
6822 goto done;
6824 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6825 GOT_OBJ_TYPE_COMMIT, repo);
6826 if (error != NULL) {
6827 struct got_reference *ref;
6828 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6829 goto done;
6830 error = got_ref_open(&ref, repo, argv[0], 0);
6831 if (error != NULL)
6832 goto done;
6833 error = got_ref_resolve(&commit_id, repo, ref);
6834 got_ref_close(ref);
6835 if (error != NULL)
6836 goto done;
6838 error = got_object_id_str(&commit_id_str, commit_id);
6839 if (error)
6840 goto done;
6842 error = got_ref_open(&head_ref, repo,
6843 got_worktree_get_head_ref_name(worktree), 0);
6844 if (error != NULL)
6845 goto done;
6847 error = check_same_branch(commit_id, head_ref, NULL, repo);
6848 if (error) {
6849 if (error->code != GOT_ERR_ANCESTRY)
6850 goto done;
6851 error = NULL;
6852 } else {
6853 error = got_error(GOT_ERR_SAME_BRANCH);
6854 goto done;
6857 error = got_object_open_as_commit(&commit, repo, commit_id);
6858 if (error)
6859 goto done;
6860 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6861 memset(&upa, 0, sizeof(upa));
6862 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6863 commit_id, repo, update_progress, &upa, check_cancelled,
6864 NULL);
6865 if (error != NULL)
6866 goto done;
6868 if (upa.did_something)
6869 printf("Merged commit %s\n", commit_id_str);
6870 print_update_progress_stats(&upa);
6871 done:
6872 if (commit)
6873 got_object_commit_close(commit);
6874 free(commit_id_str);
6875 if (head_ref)
6876 got_ref_close(head_ref);
6877 if (worktree)
6878 got_worktree_close(worktree);
6879 if (repo)
6880 got_repo_close(repo);
6881 return error;
6884 __dead static void
6885 usage_backout(void)
6887 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6888 exit(1);
6891 static const struct got_error *
6892 cmd_backout(int argc, char *argv[])
6894 const struct got_error *error = NULL;
6895 struct got_worktree *worktree = NULL;
6896 struct got_repository *repo = NULL;
6897 char *cwd = NULL, *commit_id_str = NULL;
6898 struct got_object_id *commit_id = NULL;
6899 struct got_commit_object *commit = NULL;
6900 struct got_object_qid *pid;
6901 struct got_reference *head_ref = NULL;
6902 int ch;
6903 struct got_update_progress_arg upa;
6905 while ((ch = getopt(argc, argv, "")) != -1) {
6906 switch (ch) {
6907 default:
6908 usage_backout();
6909 /* NOTREACHED */
6913 argc -= optind;
6914 argv += optind;
6916 #ifndef PROFILE
6917 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6918 "unveil", NULL) == -1)
6919 err(1, "pledge");
6920 #endif
6921 if (argc != 1)
6922 usage_backout();
6924 cwd = getcwd(NULL, 0);
6925 if (cwd == NULL) {
6926 error = got_error_from_errno("getcwd");
6927 goto done;
6929 error = got_worktree_open(&worktree, cwd);
6930 if (error) {
6931 if (error->code == GOT_ERR_NOT_WORKTREE)
6932 error = wrap_not_worktree_error(error, "backout", cwd);
6933 goto done;
6936 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6937 NULL);
6938 if (error != NULL)
6939 goto done;
6941 error = apply_unveil(got_repo_get_path(repo), 0,
6942 got_worktree_get_root_path(worktree));
6943 if (error)
6944 goto done;
6946 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6947 GOT_OBJ_TYPE_COMMIT, repo);
6948 if (error != NULL) {
6949 struct got_reference *ref;
6950 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6951 goto done;
6952 error = got_ref_open(&ref, repo, argv[0], 0);
6953 if (error != NULL)
6954 goto done;
6955 error = got_ref_resolve(&commit_id, repo, ref);
6956 got_ref_close(ref);
6957 if (error != NULL)
6958 goto done;
6960 error = got_object_id_str(&commit_id_str, commit_id);
6961 if (error)
6962 goto done;
6964 error = got_ref_open(&head_ref, repo,
6965 got_worktree_get_head_ref_name(worktree), 0);
6966 if (error != NULL)
6967 goto done;
6969 error = check_same_branch(commit_id, head_ref, NULL, repo);
6970 if (error)
6971 goto done;
6973 error = got_object_open_as_commit(&commit, repo, commit_id);
6974 if (error)
6975 goto done;
6976 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6977 if (pid == NULL) {
6978 error = got_error(GOT_ERR_ROOT_COMMIT);
6979 goto done;
6982 memset(&upa, 0, sizeof(upa));
6983 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6984 update_progress, &upa, check_cancelled, NULL);
6985 if (error != NULL)
6986 goto done;
6988 if (upa.did_something)
6989 printf("Backed out commit %s\n", commit_id_str);
6990 print_update_progress_stats(&upa);
6991 done:
6992 if (commit)
6993 got_object_commit_close(commit);
6994 free(commit_id_str);
6995 if (head_ref)
6996 got_ref_close(head_ref);
6997 if (worktree)
6998 got_worktree_close(worktree);
6999 if (repo)
7000 got_repo_close(repo);
7001 return error;
7004 __dead static void
7005 usage_rebase(void)
7007 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7008 getprogname());
7009 exit(1);
7012 void
7013 trim_logmsg(char *logmsg, int limit)
7015 char *nl;
7016 size_t len;
7018 len = strlen(logmsg);
7019 if (len > limit)
7020 len = limit;
7021 logmsg[len] = '\0';
7022 nl = strchr(logmsg, '\n');
7023 if (nl)
7024 *nl = '\0';
7027 static const struct got_error *
7028 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7030 const struct got_error *err;
7031 char *logmsg0 = NULL;
7032 const char *s;
7034 err = got_object_commit_get_logmsg(&logmsg0, commit);
7035 if (err)
7036 return err;
7038 s = logmsg0;
7039 while (isspace((unsigned char)s[0]))
7040 s++;
7042 *logmsg = strdup(s);
7043 if (*logmsg == NULL) {
7044 err = got_error_from_errno("strdup");
7045 goto done;
7048 trim_logmsg(*logmsg, limit);
7049 done:
7050 free(logmsg0);
7051 return err;
7054 static const struct got_error *
7055 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7057 const struct got_error *err;
7058 struct got_commit_object *commit = NULL;
7059 char *id_str = NULL, *logmsg = NULL;
7061 err = got_object_open_as_commit(&commit, repo, id);
7062 if (err)
7063 return err;
7065 err = got_object_id_str(&id_str, id);
7066 if (err)
7067 goto done;
7069 id_str[12] = '\0';
7071 err = get_short_logmsg(&logmsg, 42, commit);
7072 if (err)
7073 goto done;
7075 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7076 done:
7077 free(id_str);
7078 got_object_commit_close(commit);
7079 free(logmsg);
7080 return err;
7083 static const struct got_error *
7084 show_rebase_progress(struct got_commit_object *commit,
7085 struct got_object_id *old_id, struct got_object_id *new_id)
7087 const struct got_error *err;
7088 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7090 err = got_object_id_str(&old_id_str, old_id);
7091 if (err)
7092 goto done;
7094 if (new_id) {
7095 err = got_object_id_str(&new_id_str, new_id);
7096 if (err)
7097 goto done;
7100 old_id_str[12] = '\0';
7101 if (new_id_str)
7102 new_id_str[12] = '\0';
7104 err = get_short_logmsg(&logmsg, 42, commit);
7105 if (err)
7106 goto done;
7108 printf("%s -> %s: %s\n", old_id_str,
7109 new_id_str ? new_id_str : "no-op change", logmsg);
7110 done:
7111 free(old_id_str);
7112 free(new_id_str);
7113 free(logmsg);
7114 return err;
7117 static const struct got_error *
7118 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7119 struct got_reference *branch, struct got_reference *new_base_branch,
7120 struct got_reference *tmp_branch, struct got_repository *repo)
7122 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7123 return got_worktree_rebase_complete(worktree, fileindex,
7124 new_base_branch, tmp_branch, branch, repo);
7127 static const struct got_error *
7128 rebase_commit(struct got_pathlist_head *merged_paths,
7129 struct got_worktree *worktree, struct got_fileindex *fileindex,
7130 struct got_reference *tmp_branch,
7131 struct got_object_id *commit_id, struct got_repository *repo)
7133 const struct got_error *error;
7134 struct got_commit_object *commit;
7135 struct got_object_id *new_commit_id;
7137 error = got_object_open_as_commit(&commit, repo, commit_id);
7138 if (error)
7139 return error;
7141 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7142 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7143 if (error) {
7144 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7145 goto done;
7146 error = show_rebase_progress(commit, commit_id, NULL);
7147 } else {
7148 error = show_rebase_progress(commit, commit_id, new_commit_id);
7149 free(new_commit_id);
7151 done:
7152 got_object_commit_close(commit);
7153 return error;
7156 struct check_path_prefix_arg {
7157 const char *path_prefix;
7158 size_t len;
7159 int errcode;
7162 static const struct got_error *
7163 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7164 struct got_blob_object *blob2, struct got_object_id *id1,
7165 struct got_object_id *id2, const char *path1, const char *path2,
7166 mode_t mode1, mode_t mode2, struct got_repository *repo)
7168 struct check_path_prefix_arg *a = arg;
7170 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7171 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7172 return got_error(a->errcode);
7174 return NULL;
7177 static const struct got_error *
7178 check_path_prefix(struct got_object_id *parent_id,
7179 struct got_object_id *commit_id, const char *path_prefix,
7180 int errcode, struct got_repository *repo)
7182 const struct got_error *err;
7183 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7184 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7185 struct check_path_prefix_arg cpp_arg;
7187 if (got_path_is_root_dir(path_prefix))
7188 return NULL;
7190 err = got_object_open_as_commit(&commit, repo, commit_id);
7191 if (err)
7192 goto done;
7194 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7195 if (err)
7196 goto done;
7198 err = got_object_open_as_tree(&tree1, repo,
7199 got_object_commit_get_tree_id(parent_commit));
7200 if (err)
7201 goto done;
7203 err = got_object_open_as_tree(&tree2, repo,
7204 got_object_commit_get_tree_id(commit));
7205 if (err)
7206 goto done;
7208 cpp_arg.path_prefix = path_prefix;
7209 while (cpp_arg.path_prefix[0] == '/')
7210 cpp_arg.path_prefix++;
7211 cpp_arg.len = strlen(cpp_arg.path_prefix);
7212 cpp_arg.errcode = errcode;
7213 err = got_diff_tree(tree1, tree2, "", "", repo,
7214 check_path_prefix_in_diff, &cpp_arg, 0);
7215 done:
7216 if (tree1)
7217 got_object_tree_close(tree1);
7218 if (tree2)
7219 got_object_tree_close(tree2);
7220 if (commit)
7221 got_object_commit_close(commit);
7222 if (parent_commit)
7223 got_object_commit_close(parent_commit);
7224 return err;
7227 static const struct got_error *
7228 collect_commits(struct got_object_id_queue *commits,
7229 struct got_object_id *initial_commit_id,
7230 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7231 const char *path_prefix, int path_prefix_errcode,
7232 struct got_repository *repo)
7234 const struct got_error *err = NULL;
7235 struct got_commit_graph *graph = NULL;
7236 struct got_object_id *parent_id = NULL;
7237 struct got_object_qid *qid;
7238 struct got_object_id *commit_id = initial_commit_id;
7240 err = got_commit_graph_open(&graph, "/", 1);
7241 if (err)
7242 return err;
7244 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7245 check_cancelled, NULL);
7246 if (err)
7247 goto done;
7248 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7249 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7250 check_cancelled, NULL);
7251 if (err) {
7252 if (err->code == GOT_ERR_ITER_COMPLETED) {
7253 err = got_error_msg(GOT_ERR_ANCESTRY,
7254 "ran out of commits to rebase before "
7255 "youngest common ancestor commit has "
7256 "been reached?!?");
7258 goto done;
7259 } else {
7260 err = check_path_prefix(parent_id, commit_id,
7261 path_prefix, path_prefix_errcode, repo);
7262 if (err)
7263 goto done;
7265 err = got_object_qid_alloc(&qid, commit_id);
7266 if (err)
7267 goto done;
7268 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7269 commit_id = parent_id;
7272 done:
7273 got_commit_graph_close(graph);
7274 return err;
7277 static const struct got_error *
7278 cmd_rebase(int argc, char *argv[])
7280 const struct got_error *error = NULL;
7281 struct got_worktree *worktree = NULL;
7282 struct got_repository *repo = NULL;
7283 struct got_fileindex *fileindex = NULL;
7284 char *cwd = NULL;
7285 struct got_reference *branch = NULL;
7286 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7287 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7288 struct got_object_id *resume_commit_id = NULL;
7289 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7290 struct got_commit_object *commit = NULL;
7291 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7292 int histedit_in_progress = 0;
7293 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7294 struct got_object_id_queue commits;
7295 struct got_pathlist_head merged_paths;
7296 const struct got_object_id_queue *parent_ids;
7297 struct got_object_qid *qid, *pid;
7299 SIMPLEQ_INIT(&commits);
7300 TAILQ_INIT(&merged_paths);
7302 while ((ch = getopt(argc, argv, "ac")) != -1) {
7303 switch (ch) {
7304 case 'a':
7305 abort_rebase = 1;
7306 break;
7307 case 'c':
7308 continue_rebase = 1;
7309 break;
7310 default:
7311 usage_rebase();
7312 /* NOTREACHED */
7316 argc -= optind;
7317 argv += optind;
7319 #ifndef PROFILE
7320 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7321 "unveil", NULL) == -1)
7322 err(1, "pledge");
7323 #endif
7324 if (abort_rebase && continue_rebase)
7325 usage_rebase();
7326 else if (abort_rebase || continue_rebase) {
7327 if (argc != 0)
7328 usage_rebase();
7329 } else if (argc != 1)
7330 usage_rebase();
7332 cwd = getcwd(NULL, 0);
7333 if (cwd == NULL) {
7334 error = got_error_from_errno("getcwd");
7335 goto done;
7337 error = got_worktree_open(&worktree, cwd);
7338 if (error) {
7339 if (error->code == GOT_ERR_NOT_WORKTREE)
7340 error = wrap_not_worktree_error(error, "rebase", cwd);
7341 goto done;
7344 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7345 NULL);
7346 if (error != NULL)
7347 goto done;
7349 error = apply_unveil(got_repo_get_path(repo), 0,
7350 got_worktree_get_root_path(worktree));
7351 if (error)
7352 goto done;
7354 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7355 worktree);
7356 if (error)
7357 goto done;
7358 if (histedit_in_progress) {
7359 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7360 goto done;
7363 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7364 if (error)
7365 goto done;
7367 if (abort_rebase) {
7368 struct got_update_progress_arg upa;
7369 if (!rebase_in_progress) {
7370 error = got_error(GOT_ERR_NOT_REBASING);
7371 goto done;
7373 error = got_worktree_rebase_continue(&resume_commit_id,
7374 &new_base_branch, &tmp_branch, &branch, &fileindex,
7375 worktree, repo);
7376 if (error)
7377 goto done;
7378 printf("Switching work tree to %s\n",
7379 got_ref_get_symref_target(new_base_branch));
7380 memset(&upa, 0, sizeof(upa));
7381 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7382 new_base_branch, update_progress, &upa);
7383 if (error)
7384 goto done;
7385 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7386 print_update_progress_stats(&upa);
7387 goto done; /* nothing else to do */
7390 if (continue_rebase) {
7391 if (!rebase_in_progress) {
7392 error = got_error(GOT_ERR_NOT_REBASING);
7393 goto done;
7395 error = got_worktree_rebase_continue(&resume_commit_id,
7396 &new_base_branch, &tmp_branch, &branch, &fileindex,
7397 worktree, repo);
7398 if (error)
7399 goto done;
7401 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7402 resume_commit_id, repo);
7403 if (error)
7404 goto done;
7406 yca_id = got_object_id_dup(resume_commit_id);
7407 if (yca_id == NULL) {
7408 error = got_error_from_errno("got_object_id_dup");
7409 goto done;
7411 } else {
7412 error = got_ref_open(&branch, repo, argv[0], 0);
7413 if (error != NULL)
7414 goto done;
7417 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7418 if (error)
7419 goto done;
7421 if (!continue_rebase) {
7422 struct got_object_id *base_commit_id;
7424 base_commit_id = got_worktree_get_base_commit_id(worktree);
7425 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7426 base_commit_id, branch_head_commit_id, repo,
7427 check_cancelled, NULL);
7428 if (error)
7429 goto done;
7430 if (yca_id == NULL) {
7431 error = got_error_msg(GOT_ERR_ANCESTRY,
7432 "specified branch shares no common ancestry "
7433 "with work tree's branch");
7434 goto done;
7437 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7438 if (error) {
7439 if (error->code != GOT_ERR_ANCESTRY)
7440 goto done;
7441 error = NULL;
7442 } else {
7443 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7444 "specified branch resolves to a commit which "
7445 "is already contained in work tree's branch");
7446 goto done;
7448 error = got_worktree_rebase_prepare(&new_base_branch,
7449 &tmp_branch, &fileindex, worktree, branch, repo);
7450 if (error)
7451 goto done;
7454 commit_id = branch_head_commit_id;
7455 error = got_object_open_as_commit(&commit, repo, commit_id);
7456 if (error)
7457 goto done;
7459 parent_ids = got_object_commit_get_parent_ids(commit);
7460 pid = SIMPLEQ_FIRST(parent_ids);
7461 if (pid == NULL) {
7462 if (!continue_rebase) {
7463 struct got_update_progress_arg upa;
7464 memset(&upa, 0, sizeof(upa));
7465 error = got_worktree_rebase_abort(worktree, fileindex,
7466 repo, new_base_branch, update_progress, &upa);
7467 if (error)
7468 goto done;
7469 printf("Rebase of %s aborted\n",
7470 got_ref_get_name(branch));
7471 print_update_progress_stats(&upa);
7474 error = got_error(GOT_ERR_EMPTY_REBASE);
7475 goto done;
7477 error = collect_commits(&commits, commit_id, pid->id,
7478 yca_id, got_worktree_get_path_prefix(worktree),
7479 GOT_ERR_REBASE_PATH, repo);
7480 got_object_commit_close(commit);
7481 commit = NULL;
7482 if (error)
7483 goto done;
7485 if (SIMPLEQ_EMPTY(&commits)) {
7486 if (continue_rebase) {
7487 error = rebase_complete(worktree, fileindex,
7488 branch, new_base_branch, tmp_branch, repo);
7489 goto done;
7490 } else {
7491 /* Fast-forward the reference of the branch. */
7492 struct got_object_id *new_head_commit_id;
7493 char *id_str;
7494 error = got_ref_resolve(&new_head_commit_id, repo,
7495 new_base_branch);
7496 if (error)
7497 goto done;
7498 error = got_object_id_str(&id_str, new_head_commit_id);
7499 printf("Forwarding %s to commit %s\n",
7500 got_ref_get_name(branch), id_str);
7501 free(id_str);
7502 error = got_ref_change_ref(branch,
7503 new_head_commit_id);
7504 if (error)
7505 goto done;
7509 pid = NULL;
7510 SIMPLEQ_FOREACH(qid, &commits, entry) {
7511 struct got_update_progress_arg upa;
7513 commit_id = qid->id;
7514 parent_id = pid ? pid->id : yca_id;
7515 pid = qid;
7517 memset(&upa, 0, sizeof(upa));
7518 error = got_worktree_rebase_merge_files(&merged_paths,
7519 worktree, fileindex, parent_id, commit_id, repo,
7520 update_progress, &upa, check_cancelled, NULL);
7521 if (error)
7522 goto done;
7524 print_update_progress_stats(&upa);
7525 if (upa.conflicts > 0)
7526 rebase_status = GOT_STATUS_CONFLICT;
7528 if (rebase_status == GOT_STATUS_CONFLICT) {
7529 error = show_rebase_merge_conflict(qid->id, repo);
7530 if (error)
7531 goto done;
7532 got_worktree_rebase_pathlist_free(&merged_paths);
7533 break;
7536 error = rebase_commit(&merged_paths, worktree, fileindex,
7537 tmp_branch, commit_id, repo);
7538 got_worktree_rebase_pathlist_free(&merged_paths);
7539 if (error)
7540 goto done;
7543 if (rebase_status == GOT_STATUS_CONFLICT) {
7544 error = got_worktree_rebase_postpone(worktree, fileindex);
7545 if (error)
7546 goto done;
7547 error = got_error_msg(GOT_ERR_CONFLICTS,
7548 "conflicts must be resolved before rebasing can continue");
7549 } else
7550 error = rebase_complete(worktree, fileindex, branch,
7551 new_base_branch, tmp_branch, repo);
7552 done:
7553 got_object_id_queue_free(&commits);
7554 free(branch_head_commit_id);
7555 free(resume_commit_id);
7556 free(yca_id);
7557 if (commit)
7558 got_object_commit_close(commit);
7559 if (branch)
7560 got_ref_close(branch);
7561 if (new_base_branch)
7562 got_ref_close(new_base_branch);
7563 if (tmp_branch)
7564 got_ref_close(tmp_branch);
7565 if (worktree)
7566 got_worktree_close(worktree);
7567 if (repo)
7568 got_repo_close(repo);
7569 return error;
7572 __dead static void
7573 usage_histedit(void)
7575 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7576 getprogname());
7577 exit(1);
7580 #define GOT_HISTEDIT_PICK 'p'
7581 #define GOT_HISTEDIT_EDIT 'e'
7582 #define GOT_HISTEDIT_FOLD 'f'
7583 #define GOT_HISTEDIT_DROP 'd'
7584 #define GOT_HISTEDIT_MESG 'm'
7586 static struct got_histedit_cmd {
7587 unsigned char code;
7588 const char *name;
7589 const char *desc;
7590 } got_histedit_cmds[] = {
7591 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7592 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7593 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7594 "be used" },
7595 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7596 { GOT_HISTEDIT_MESG, "mesg",
7597 "single-line log message for commit above (open editor if empty)" },
7600 struct got_histedit_list_entry {
7601 TAILQ_ENTRY(got_histedit_list_entry) entry;
7602 struct got_object_id *commit_id;
7603 const struct got_histedit_cmd *cmd;
7604 char *logmsg;
7606 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7608 static const struct got_error *
7609 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7610 FILE *f, struct got_repository *repo)
7612 const struct got_error *err = NULL;
7613 char *logmsg = NULL, *id_str = NULL;
7614 struct got_commit_object *commit = NULL;
7615 int n;
7617 err = got_object_open_as_commit(&commit, repo, commit_id);
7618 if (err)
7619 goto done;
7621 err = get_short_logmsg(&logmsg, 34, commit);
7622 if (err)
7623 goto done;
7625 err = got_object_id_str(&id_str, commit_id);
7626 if (err)
7627 goto done;
7629 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7630 if (n < 0)
7631 err = got_ferror(f, GOT_ERR_IO);
7632 done:
7633 if (commit)
7634 got_object_commit_close(commit);
7635 free(id_str);
7636 free(logmsg);
7637 return err;
7640 static const struct got_error *
7641 histedit_write_commit_list(struct got_object_id_queue *commits,
7642 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7644 const struct got_error *err = NULL;
7645 struct got_object_qid *qid;
7647 if (SIMPLEQ_EMPTY(commits))
7648 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7650 SIMPLEQ_FOREACH(qid, commits, entry) {
7651 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7652 f, repo);
7653 if (err)
7654 break;
7655 if (edit_logmsg_only) {
7656 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7657 if (n < 0) {
7658 err = got_ferror(f, GOT_ERR_IO);
7659 break;
7664 return err;
7667 static const struct got_error *
7668 write_cmd_list(FILE *f, const char *branch_name,
7669 struct got_object_id_queue *commits)
7671 const struct got_error *err = NULL;
7672 int n, i;
7673 char *id_str;
7674 struct got_object_qid *qid;
7676 qid = SIMPLEQ_FIRST(commits);
7677 err = got_object_id_str(&id_str, qid->id);
7678 if (err)
7679 return err;
7681 n = fprintf(f,
7682 "# Editing the history of branch '%s' starting at\n"
7683 "# commit %s\n"
7684 "# Commits will be processed in order from top to "
7685 "bottom of this file.\n", branch_name, id_str);
7686 if (n < 0) {
7687 err = got_ferror(f, GOT_ERR_IO);
7688 goto done;
7691 n = fprintf(f, "# Available histedit commands:\n");
7692 if (n < 0) {
7693 err = got_ferror(f, GOT_ERR_IO);
7694 goto done;
7697 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7698 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7699 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7700 cmd->desc);
7701 if (n < 0) {
7702 err = got_ferror(f, GOT_ERR_IO);
7703 break;
7706 done:
7707 free(id_str);
7708 return err;
7711 static const struct got_error *
7712 histedit_syntax_error(int lineno)
7714 static char msg[42];
7715 int ret;
7717 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7718 lineno);
7719 if (ret == -1 || ret >= sizeof(msg))
7720 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7722 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7725 static const struct got_error *
7726 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7727 char *logmsg, struct got_repository *repo)
7729 const struct got_error *err;
7730 struct got_commit_object *folded_commit = NULL;
7731 char *id_str, *folded_logmsg = NULL;
7733 err = got_object_id_str(&id_str, hle->commit_id);
7734 if (err)
7735 return err;
7737 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7738 if (err)
7739 goto done;
7741 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7742 if (err)
7743 goto done;
7744 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7745 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7746 folded_logmsg) == -1) {
7747 err = got_error_from_errno("asprintf");
7749 done:
7750 if (folded_commit)
7751 got_object_commit_close(folded_commit);
7752 free(id_str);
7753 free(folded_logmsg);
7754 return err;
7757 static struct got_histedit_list_entry *
7758 get_folded_commits(struct got_histedit_list_entry *hle)
7760 struct got_histedit_list_entry *prev, *folded = NULL;
7762 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7763 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7764 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7765 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7766 folded = prev;
7767 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7770 return folded;
7773 static const struct got_error *
7774 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7775 struct got_repository *repo)
7777 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7778 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7779 const struct got_error *err = NULL;
7780 struct got_commit_object *commit = NULL;
7781 int logmsg_len;
7782 int fd;
7783 struct got_histedit_list_entry *folded = NULL;
7785 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7786 if (err)
7787 return err;
7789 folded = get_folded_commits(hle);
7790 if (folded) {
7791 while (folded != hle) {
7792 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7793 folded = TAILQ_NEXT(folded, entry);
7794 continue;
7796 err = append_folded_commit_msg(&new_msg, folded,
7797 logmsg, repo);
7798 if (err)
7799 goto done;
7800 free(logmsg);
7801 logmsg = new_msg;
7802 folded = TAILQ_NEXT(folded, entry);
7806 err = got_object_id_str(&id_str, hle->commit_id);
7807 if (err)
7808 goto done;
7809 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7810 if (err)
7811 goto done;
7812 logmsg_len = asprintf(&new_msg,
7813 "%s\n# original log message of commit %s: %s",
7814 logmsg ? logmsg : "", id_str, orig_logmsg);
7815 if (logmsg_len == -1) {
7816 err = got_error_from_errno("asprintf");
7817 goto done;
7819 free(logmsg);
7820 logmsg = new_msg;
7822 err = got_object_id_str(&id_str, hle->commit_id);
7823 if (err)
7824 goto done;
7826 err = got_opentemp_named_fd(&logmsg_path, &fd,
7827 GOT_TMPDIR_STR "/got-logmsg");
7828 if (err)
7829 goto done;
7831 write(fd, logmsg, logmsg_len);
7832 close(fd);
7834 err = get_editor(&editor);
7835 if (err)
7836 goto done;
7838 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7839 if (err) {
7840 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7841 goto done;
7842 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7844 done:
7845 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7846 err = got_error_from_errno2("unlink", logmsg_path);
7847 free(logmsg_path);
7848 free(logmsg);
7849 free(orig_logmsg);
7850 free(editor);
7851 if (commit)
7852 got_object_commit_close(commit);
7853 return err;
7856 static const struct got_error *
7857 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7858 FILE *f, struct got_repository *repo)
7860 const struct got_error *err = NULL;
7861 char *line = NULL, *p, *end;
7862 size_t size;
7863 ssize_t len;
7864 int lineno = 0, i;
7865 const struct got_histedit_cmd *cmd;
7866 struct got_object_id *commit_id = NULL;
7867 struct got_histedit_list_entry *hle = NULL;
7869 for (;;) {
7870 len = getline(&line, &size, f);
7871 if (len == -1) {
7872 const struct got_error *getline_err;
7873 if (feof(f))
7874 break;
7875 getline_err = got_error_from_errno("getline");
7876 err = got_ferror(f, getline_err->code);
7877 break;
7879 lineno++;
7880 p = line;
7881 while (isspace((unsigned char)p[0]))
7882 p++;
7883 if (p[0] == '#' || p[0] == '\0') {
7884 free(line);
7885 line = NULL;
7886 continue;
7888 cmd = NULL;
7889 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7890 cmd = &got_histedit_cmds[i];
7891 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7892 isspace((unsigned char)p[strlen(cmd->name)])) {
7893 p += strlen(cmd->name);
7894 break;
7896 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7897 p++;
7898 break;
7901 if (i == nitems(got_histedit_cmds)) {
7902 err = histedit_syntax_error(lineno);
7903 break;
7905 while (isspace((unsigned char)p[0]))
7906 p++;
7907 if (cmd->code == GOT_HISTEDIT_MESG) {
7908 if (hle == NULL || hle->logmsg != NULL) {
7909 err = got_error(GOT_ERR_HISTEDIT_CMD);
7910 break;
7912 if (p[0] == '\0') {
7913 err = histedit_edit_logmsg(hle, repo);
7914 if (err)
7915 break;
7916 } else {
7917 hle->logmsg = strdup(p);
7918 if (hle->logmsg == NULL) {
7919 err = got_error_from_errno("strdup");
7920 break;
7923 free(line);
7924 line = NULL;
7925 continue;
7926 } else {
7927 end = p;
7928 while (end[0] && !isspace((unsigned char)end[0]))
7929 end++;
7930 *end = '\0';
7932 err = got_object_resolve_id_str(&commit_id, repo, p);
7933 if (err) {
7934 /* override error code */
7935 err = histedit_syntax_error(lineno);
7936 break;
7939 hle = malloc(sizeof(*hle));
7940 if (hle == NULL) {
7941 err = got_error_from_errno("malloc");
7942 break;
7944 hle->cmd = cmd;
7945 hle->commit_id = commit_id;
7946 hle->logmsg = NULL;
7947 commit_id = NULL;
7948 free(line);
7949 line = NULL;
7950 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7953 free(line);
7954 free(commit_id);
7955 return err;
7958 static const struct got_error *
7959 histedit_check_script(struct got_histedit_list *histedit_cmds,
7960 struct got_object_id_queue *commits, struct got_repository *repo)
7962 const struct got_error *err = NULL;
7963 struct got_object_qid *qid;
7964 struct got_histedit_list_entry *hle;
7965 static char msg[92];
7966 char *id_str;
7968 if (TAILQ_EMPTY(histedit_cmds))
7969 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7970 "histedit script contains no commands");
7971 if (SIMPLEQ_EMPTY(commits))
7972 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7974 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7975 struct got_histedit_list_entry *hle2;
7976 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7977 if (hle == hle2)
7978 continue;
7979 if (got_object_id_cmp(hle->commit_id,
7980 hle2->commit_id) != 0)
7981 continue;
7982 err = got_object_id_str(&id_str, hle->commit_id);
7983 if (err)
7984 return err;
7985 snprintf(msg, sizeof(msg), "commit %s is listed "
7986 "more than once in histedit script", id_str);
7987 free(id_str);
7988 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7992 SIMPLEQ_FOREACH(qid, commits, entry) {
7993 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7994 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7995 break;
7997 if (hle == NULL) {
7998 err = got_object_id_str(&id_str, qid->id);
7999 if (err)
8000 return err;
8001 snprintf(msg, sizeof(msg),
8002 "commit %s missing from histedit script", id_str);
8003 free(id_str);
8004 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8008 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8009 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8010 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8011 "last commit in histedit script cannot be folded");
8013 return NULL;
8016 static const struct got_error *
8017 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8018 const char *path, struct got_object_id_queue *commits,
8019 struct got_repository *repo)
8021 const struct got_error *err = NULL;
8022 char *editor;
8023 FILE *f = NULL;
8025 err = get_editor(&editor);
8026 if (err)
8027 return err;
8029 if (spawn_editor(editor, path) == -1) {
8030 err = got_error_from_errno("failed spawning editor");
8031 goto done;
8034 f = fopen(path, "r");
8035 if (f == NULL) {
8036 err = got_error_from_errno("fopen");
8037 goto done;
8039 err = histedit_parse_list(histedit_cmds, f, repo);
8040 if (err)
8041 goto done;
8043 err = histedit_check_script(histedit_cmds, commits, repo);
8044 done:
8045 if (f && fclose(f) != 0 && err == NULL)
8046 err = got_error_from_errno("fclose");
8047 free(editor);
8048 return err;
8051 static const struct got_error *
8052 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8053 struct got_object_id_queue *, const char *, const char *,
8054 struct got_repository *);
8056 static const struct got_error *
8057 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8058 struct got_object_id_queue *commits, const char *branch_name,
8059 int edit_logmsg_only, struct got_repository *repo)
8061 const struct got_error *err;
8062 FILE *f = NULL;
8063 char *path = NULL;
8065 err = got_opentemp_named(&path, &f, "got-histedit");
8066 if (err)
8067 return err;
8069 err = write_cmd_list(f, branch_name, commits);
8070 if (err)
8071 goto done;
8073 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8074 if (err)
8075 goto done;
8077 if (edit_logmsg_only) {
8078 rewind(f);
8079 err = histedit_parse_list(histedit_cmds, f, repo);
8080 } else {
8081 if (fclose(f) != 0) {
8082 err = got_error_from_errno("fclose");
8083 goto done;
8085 f = NULL;
8086 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8087 if (err) {
8088 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8089 err->code != GOT_ERR_HISTEDIT_CMD)
8090 goto done;
8091 err = histedit_edit_list_retry(histedit_cmds, err,
8092 commits, path, branch_name, repo);
8095 done:
8096 if (f && fclose(f) != 0 && err == NULL)
8097 err = got_error_from_errno("fclose");
8098 if (path && unlink(path) != 0 && err == NULL)
8099 err = got_error_from_errno2("unlink", path);
8100 free(path);
8101 return err;
8104 static const struct got_error *
8105 histedit_save_list(struct got_histedit_list *histedit_cmds,
8106 struct got_worktree *worktree, struct got_repository *repo)
8108 const struct got_error *err = NULL;
8109 char *path = NULL;
8110 FILE *f = NULL;
8111 struct got_histedit_list_entry *hle;
8112 struct got_commit_object *commit = NULL;
8114 err = got_worktree_get_histedit_script_path(&path, worktree);
8115 if (err)
8116 return err;
8118 f = fopen(path, "w");
8119 if (f == NULL) {
8120 err = got_error_from_errno2("fopen", path);
8121 goto done;
8123 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8124 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8125 repo);
8126 if (err)
8127 break;
8129 if (hle->logmsg) {
8130 int n = fprintf(f, "%c %s\n",
8131 GOT_HISTEDIT_MESG, hle->logmsg);
8132 if (n < 0) {
8133 err = got_ferror(f, GOT_ERR_IO);
8134 break;
8138 done:
8139 if (f && fclose(f) != 0 && err == NULL)
8140 err = got_error_from_errno("fclose");
8141 free(path);
8142 if (commit)
8143 got_object_commit_close(commit);
8144 return err;
8147 void
8148 histedit_free_list(struct got_histedit_list *histedit_cmds)
8150 struct got_histedit_list_entry *hle;
8152 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8153 TAILQ_REMOVE(histedit_cmds, hle, entry);
8154 free(hle);
8158 static const struct got_error *
8159 histedit_load_list(struct got_histedit_list *histedit_cmds,
8160 const char *path, struct got_repository *repo)
8162 const struct got_error *err = NULL;
8163 FILE *f = NULL;
8165 f = fopen(path, "r");
8166 if (f == NULL) {
8167 err = got_error_from_errno2("fopen", path);
8168 goto done;
8171 err = histedit_parse_list(histedit_cmds, f, repo);
8172 done:
8173 if (f && fclose(f) != 0 && err == NULL)
8174 err = got_error_from_errno("fclose");
8175 return err;
8178 static const struct got_error *
8179 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8180 const struct got_error *edit_err, struct got_object_id_queue *commits,
8181 const char *path, const char *branch_name, struct got_repository *repo)
8183 const struct got_error *err = NULL, *prev_err = edit_err;
8184 int resp = ' ';
8186 while (resp != 'c' && resp != 'r' && resp != 'a') {
8187 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8188 "or (a)bort: ", getprogname(), prev_err->msg);
8189 resp = getchar();
8190 if (resp == '\n')
8191 resp = getchar();
8192 if (resp == 'c') {
8193 histedit_free_list(histedit_cmds);
8194 err = histedit_run_editor(histedit_cmds, path, commits,
8195 repo);
8196 if (err) {
8197 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8198 err->code != GOT_ERR_HISTEDIT_CMD)
8199 break;
8200 prev_err = err;
8201 resp = ' ';
8202 continue;
8204 break;
8205 } else if (resp == 'r') {
8206 histedit_free_list(histedit_cmds);
8207 err = histedit_edit_script(histedit_cmds,
8208 commits, branch_name, 0, repo);
8209 if (err) {
8210 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8211 err->code != GOT_ERR_HISTEDIT_CMD)
8212 break;
8213 prev_err = err;
8214 resp = ' ';
8215 continue;
8217 break;
8218 } else if (resp == 'a') {
8219 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8220 break;
8221 } else
8222 printf("invalid response '%c'\n", resp);
8225 return err;
8228 static const struct got_error *
8229 histedit_complete(struct got_worktree *worktree,
8230 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8231 struct got_reference *branch, struct got_repository *repo)
8233 printf("Switching work tree to %s\n",
8234 got_ref_get_symref_target(branch));
8235 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8236 branch, repo);
8239 static const struct got_error *
8240 show_histedit_progress(struct got_commit_object *commit,
8241 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8243 const struct got_error *err;
8244 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8246 err = got_object_id_str(&old_id_str, hle->commit_id);
8247 if (err)
8248 goto done;
8250 if (new_id) {
8251 err = got_object_id_str(&new_id_str, new_id);
8252 if (err)
8253 goto done;
8256 old_id_str[12] = '\0';
8257 if (new_id_str)
8258 new_id_str[12] = '\0';
8260 if (hle->logmsg) {
8261 logmsg = strdup(hle->logmsg);
8262 if (logmsg == NULL) {
8263 err = got_error_from_errno("strdup");
8264 goto done;
8266 trim_logmsg(logmsg, 42);
8267 } else {
8268 err = get_short_logmsg(&logmsg, 42, commit);
8269 if (err)
8270 goto done;
8273 switch (hle->cmd->code) {
8274 case GOT_HISTEDIT_PICK:
8275 case GOT_HISTEDIT_EDIT:
8276 printf("%s -> %s: %s\n", old_id_str,
8277 new_id_str ? new_id_str : "no-op change", logmsg);
8278 break;
8279 case GOT_HISTEDIT_DROP:
8280 case GOT_HISTEDIT_FOLD:
8281 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8282 logmsg);
8283 break;
8284 default:
8285 break;
8287 done:
8288 free(old_id_str);
8289 free(new_id_str);
8290 return err;
8293 static const struct got_error *
8294 histedit_commit(struct got_pathlist_head *merged_paths,
8295 struct got_worktree *worktree, struct got_fileindex *fileindex,
8296 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8297 struct got_repository *repo)
8299 const struct got_error *err;
8300 struct got_commit_object *commit;
8301 struct got_object_id *new_commit_id;
8303 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8304 && hle->logmsg == NULL) {
8305 err = histedit_edit_logmsg(hle, repo);
8306 if (err)
8307 return err;
8310 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8311 if (err)
8312 return err;
8314 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8315 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8316 hle->logmsg, repo);
8317 if (err) {
8318 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8319 goto done;
8320 err = show_histedit_progress(commit, hle, NULL);
8321 } else {
8322 err = show_histedit_progress(commit, hle, new_commit_id);
8323 free(new_commit_id);
8325 done:
8326 got_object_commit_close(commit);
8327 return err;
8330 static const struct got_error *
8331 histedit_skip_commit(struct got_histedit_list_entry *hle,
8332 struct got_worktree *worktree, struct got_repository *repo)
8334 const struct got_error *error;
8335 struct got_commit_object *commit;
8337 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8338 repo);
8339 if (error)
8340 return error;
8342 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8343 if (error)
8344 return error;
8346 error = show_histedit_progress(commit, hle, NULL);
8347 got_object_commit_close(commit);
8348 return error;
8351 static const struct got_error *
8352 check_local_changes(void *arg, unsigned char status,
8353 unsigned char staged_status, const char *path,
8354 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8355 struct got_object_id *commit_id, int dirfd, const char *de_name)
8357 int *have_local_changes = arg;
8359 switch (status) {
8360 case GOT_STATUS_ADD:
8361 case GOT_STATUS_DELETE:
8362 case GOT_STATUS_MODIFY:
8363 case GOT_STATUS_CONFLICT:
8364 *have_local_changes = 1;
8365 return got_error(GOT_ERR_CANCELLED);
8366 default:
8367 break;
8370 switch (staged_status) {
8371 case GOT_STATUS_ADD:
8372 case GOT_STATUS_DELETE:
8373 case GOT_STATUS_MODIFY:
8374 *have_local_changes = 1;
8375 return got_error(GOT_ERR_CANCELLED);
8376 default:
8377 break;
8380 return NULL;
8383 static const struct got_error *
8384 cmd_histedit(int argc, char *argv[])
8386 const struct got_error *error = NULL;
8387 struct got_worktree *worktree = NULL;
8388 struct got_fileindex *fileindex = NULL;
8389 struct got_repository *repo = NULL;
8390 char *cwd = NULL;
8391 struct got_reference *branch = NULL;
8392 struct got_reference *tmp_branch = NULL;
8393 struct got_object_id *resume_commit_id = NULL;
8394 struct got_object_id *base_commit_id = NULL;
8395 struct got_object_id *head_commit_id = NULL;
8396 struct got_commit_object *commit = NULL;
8397 int ch, rebase_in_progress = 0;
8398 struct got_update_progress_arg upa;
8399 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8400 int edit_logmsg_only = 0;
8401 const char *edit_script_path = NULL;
8402 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8403 struct got_object_id_queue commits;
8404 struct got_pathlist_head merged_paths;
8405 const struct got_object_id_queue *parent_ids;
8406 struct got_object_qid *pid;
8407 struct got_histedit_list histedit_cmds;
8408 struct got_histedit_list_entry *hle;
8410 SIMPLEQ_INIT(&commits);
8411 TAILQ_INIT(&histedit_cmds);
8412 TAILQ_INIT(&merged_paths);
8413 memset(&upa, 0, sizeof(upa));
8415 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8416 switch (ch) {
8417 case 'a':
8418 abort_edit = 1;
8419 break;
8420 case 'c':
8421 continue_edit = 1;
8422 break;
8423 case 'F':
8424 edit_script_path = optarg;
8425 break;
8426 case 'm':
8427 edit_logmsg_only = 1;
8428 break;
8429 default:
8430 usage_histedit();
8431 /* NOTREACHED */
8435 argc -= optind;
8436 argv += optind;
8438 #ifndef PROFILE
8439 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8440 "unveil", NULL) == -1)
8441 err(1, "pledge");
8442 #endif
8443 if (abort_edit && continue_edit)
8444 errx(1, "histedit's -a and -c options are mutually exclusive");
8445 if (edit_script_path && edit_logmsg_only)
8446 errx(1, "histedit's -F and -m options are mutually exclusive");
8447 if (abort_edit && edit_logmsg_only)
8448 errx(1, "histedit's -a and -m options are mutually exclusive");
8449 if (continue_edit && edit_logmsg_only)
8450 errx(1, "histedit's -c and -m options are mutually exclusive");
8451 if (argc != 0)
8452 usage_histedit();
8455 * This command cannot apply unveil(2) in all cases because the
8456 * user may choose to run an editor to edit the histedit script
8457 * and to edit individual commit log messages.
8458 * unveil(2) traverses exec(2); if an editor is used we have to
8459 * apply unveil after edit script and log messages have been written.
8460 * XXX TODO: Make use of unveil(2) where possible.
8463 cwd = getcwd(NULL, 0);
8464 if (cwd == NULL) {
8465 error = got_error_from_errno("getcwd");
8466 goto done;
8468 error = got_worktree_open(&worktree, cwd);
8469 if (error) {
8470 if (error->code == GOT_ERR_NOT_WORKTREE)
8471 error = wrap_not_worktree_error(error, "histedit", cwd);
8472 goto done;
8475 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8476 NULL);
8477 if (error != NULL)
8478 goto done;
8480 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8481 if (error)
8482 goto done;
8483 if (rebase_in_progress) {
8484 error = got_error(GOT_ERR_REBASING);
8485 goto done;
8488 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8489 if (error)
8490 goto done;
8492 if (edit_in_progress && edit_logmsg_only) {
8493 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8494 "histedit operation is in progress in this "
8495 "work tree and must be continued or aborted "
8496 "before the -m option can be used");
8497 goto done;
8500 if (edit_in_progress && abort_edit) {
8501 error = got_worktree_histedit_continue(&resume_commit_id,
8502 &tmp_branch, &branch, &base_commit_id, &fileindex,
8503 worktree, repo);
8504 if (error)
8505 goto done;
8506 printf("Switching work tree to %s\n",
8507 got_ref_get_symref_target(branch));
8508 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8509 branch, base_commit_id, update_progress, &upa);
8510 if (error)
8511 goto done;
8512 printf("Histedit of %s aborted\n",
8513 got_ref_get_symref_target(branch));
8514 print_update_progress_stats(&upa);
8515 goto done; /* nothing else to do */
8516 } else if (abort_edit) {
8517 error = got_error(GOT_ERR_NOT_HISTEDIT);
8518 goto done;
8521 if (continue_edit) {
8522 char *path;
8524 if (!edit_in_progress) {
8525 error = got_error(GOT_ERR_NOT_HISTEDIT);
8526 goto done;
8529 error = got_worktree_get_histedit_script_path(&path, worktree);
8530 if (error)
8531 goto done;
8533 error = histedit_load_list(&histedit_cmds, path, repo);
8534 free(path);
8535 if (error)
8536 goto done;
8538 error = got_worktree_histedit_continue(&resume_commit_id,
8539 &tmp_branch, &branch, &base_commit_id, &fileindex,
8540 worktree, repo);
8541 if (error)
8542 goto done;
8544 error = got_ref_resolve(&head_commit_id, repo, branch);
8545 if (error)
8546 goto done;
8548 error = got_object_open_as_commit(&commit, repo,
8549 head_commit_id);
8550 if (error)
8551 goto done;
8552 parent_ids = got_object_commit_get_parent_ids(commit);
8553 pid = SIMPLEQ_FIRST(parent_ids);
8554 if (pid == NULL) {
8555 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8556 goto done;
8558 error = collect_commits(&commits, head_commit_id, pid->id,
8559 base_commit_id, got_worktree_get_path_prefix(worktree),
8560 GOT_ERR_HISTEDIT_PATH, repo);
8561 got_object_commit_close(commit);
8562 commit = NULL;
8563 if (error)
8564 goto done;
8565 } else {
8566 if (edit_in_progress) {
8567 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8568 goto done;
8571 error = got_ref_open(&branch, repo,
8572 got_worktree_get_head_ref_name(worktree), 0);
8573 if (error != NULL)
8574 goto done;
8576 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8577 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8578 "will not edit commit history of a branch outside "
8579 "the \"refs/heads/\" reference namespace");
8580 goto done;
8583 error = got_ref_resolve(&head_commit_id, repo, branch);
8584 got_ref_close(branch);
8585 branch = NULL;
8586 if (error)
8587 goto done;
8589 error = got_object_open_as_commit(&commit, repo,
8590 head_commit_id);
8591 if (error)
8592 goto done;
8593 parent_ids = got_object_commit_get_parent_ids(commit);
8594 pid = SIMPLEQ_FIRST(parent_ids);
8595 if (pid == NULL) {
8596 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8597 goto done;
8599 error = collect_commits(&commits, head_commit_id, pid->id,
8600 got_worktree_get_base_commit_id(worktree),
8601 got_worktree_get_path_prefix(worktree),
8602 GOT_ERR_HISTEDIT_PATH, repo);
8603 got_object_commit_close(commit);
8604 commit = NULL;
8605 if (error)
8606 goto done;
8608 if (SIMPLEQ_EMPTY(&commits)) {
8609 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8610 goto done;
8613 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8614 &base_commit_id, &fileindex, worktree, repo);
8615 if (error)
8616 goto done;
8618 if (edit_script_path) {
8619 error = histedit_load_list(&histedit_cmds,
8620 edit_script_path, repo);
8621 if (error) {
8622 got_worktree_histedit_abort(worktree, fileindex,
8623 repo, branch, base_commit_id,
8624 update_progress, &upa);
8625 print_update_progress_stats(&upa);
8626 goto done;
8628 } else {
8629 const char *branch_name;
8630 branch_name = got_ref_get_symref_target(branch);
8631 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8632 branch_name += 11;
8633 error = histedit_edit_script(&histedit_cmds, &commits,
8634 branch_name, edit_logmsg_only, repo);
8635 if (error) {
8636 got_worktree_histedit_abort(worktree, fileindex,
8637 repo, branch, base_commit_id,
8638 update_progress, &upa);
8639 print_update_progress_stats(&upa);
8640 goto done;
8645 error = histedit_save_list(&histedit_cmds, worktree,
8646 repo);
8647 if (error) {
8648 got_worktree_histedit_abort(worktree, fileindex,
8649 repo, branch, base_commit_id,
8650 update_progress, &upa);
8651 print_update_progress_stats(&upa);
8652 goto done;
8657 error = histedit_check_script(&histedit_cmds, &commits, repo);
8658 if (error)
8659 goto done;
8661 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8662 if (resume_commit_id) {
8663 if (got_object_id_cmp(hle->commit_id,
8664 resume_commit_id) != 0)
8665 continue;
8667 resume_commit_id = NULL;
8668 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8669 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8670 error = histedit_skip_commit(hle, worktree,
8671 repo);
8672 if (error)
8673 goto done;
8674 } else {
8675 struct got_pathlist_head paths;
8676 int have_changes = 0;
8678 TAILQ_INIT(&paths);
8679 error = got_pathlist_append(&paths, "", NULL);
8680 if (error)
8681 goto done;
8682 error = got_worktree_status(worktree, &paths,
8683 repo, check_local_changes, &have_changes,
8684 check_cancelled, NULL);
8685 got_pathlist_free(&paths);
8686 if (error) {
8687 if (error->code != GOT_ERR_CANCELLED)
8688 goto done;
8689 if (sigint_received || sigpipe_received)
8690 goto done;
8692 if (have_changes) {
8693 error = histedit_commit(NULL, worktree,
8694 fileindex, tmp_branch, hle, repo);
8695 if (error)
8696 goto done;
8697 } else {
8698 error = got_object_open_as_commit(
8699 &commit, repo, hle->commit_id);
8700 if (error)
8701 goto done;
8702 error = show_histedit_progress(commit,
8703 hle, NULL);
8704 got_object_commit_close(commit);
8705 commit = NULL;
8706 if (error)
8707 goto done;
8710 continue;
8713 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8714 error = histedit_skip_commit(hle, worktree, repo);
8715 if (error)
8716 goto done;
8717 continue;
8720 error = got_object_open_as_commit(&commit, repo,
8721 hle->commit_id);
8722 if (error)
8723 goto done;
8724 parent_ids = got_object_commit_get_parent_ids(commit);
8725 pid = SIMPLEQ_FIRST(parent_ids);
8727 error = got_worktree_histedit_merge_files(&merged_paths,
8728 worktree, fileindex, pid->id, hle->commit_id, repo,
8729 update_progress, &upa, check_cancelled, NULL);
8730 if (error)
8731 goto done;
8732 got_object_commit_close(commit);
8733 commit = NULL;
8735 print_update_progress_stats(&upa);
8736 if (upa.conflicts > 0)
8737 rebase_status = GOT_STATUS_CONFLICT;
8739 if (rebase_status == GOT_STATUS_CONFLICT) {
8740 error = show_rebase_merge_conflict(hle->commit_id,
8741 repo);
8742 if (error)
8743 goto done;
8744 got_worktree_rebase_pathlist_free(&merged_paths);
8745 break;
8748 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8749 char *id_str;
8750 error = got_object_id_str(&id_str, hle->commit_id);
8751 if (error)
8752 goto done;
8753 printf("Stopping histedit for amending commit %s\n",
8754 id_str);
8755 free(id_str);
8756 got_worktree_rebase_pathlist_free(&merged_paths);
8757 error = got_worktree_histedit_postpone(worktree,
8758 fileindex);
8759 goto done;
8762 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8763 error = histedit_skip_commit(hle, worktree, repo);
8764 if (error)
8765 goto done;
8766 continue;
8769 error = histedit_commit(&merged_paths, worktree, fileindex,
8770 tmp_branch, hle, repo);
8771 got_worktree_rebase_pathlist_free(&merged_paths);
8772 if (error)
8773 goto done;
8776 if (rebase_status == GOT_STATUS_CONFLICT) {
8777 error = got_worktree_histedit_postpone(worktree, fileindex);
8778 if (error)
8779 goto done;
8780 error = got_error_msg(GOT_ERR_CONFLICTS,
8781 "conflicts must be resolved before histedit can continue");
8782 } else
8783 error = histedit_complete(worktree, fileindex, tmp_branch,
8784 branch, repo);
8785 done:
8786 got_object_id_queue_free(&commits);
8787 histedit_free_list(&histedit_cmds);
8788 free(head_commit_id);
8789 free(base_commit_id);
8790 free(resume_commit_id);
8791 if (commit)
8792 got_object_commit_close(commit);
8793 if (branch)
8794 got_ref_close(branch);
8795 if (tmp_branch)
8796 got_ref_close(tmp_branch);
8797 if (worktree)
8798 got_worktree_close(worktree);
8799 if (repo)
8800 got_repo_close(repo);
8801 return error;
8804 __dead static void
8805 usage_integrate(void)
8807 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8808 exit(1);
8811 static const struct got_error *
8812 cmd_integrate(int argc, char *argv[])
8814 const struct got_error *error = NULL;
8815 struct got_repository *repo = NULL;
8816 struct got_worktree *worktree = NULL;
8817 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8818 const char *branch_arg = NULL;
8819 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8820 struct got_fileindex *fileindex = NULL;
8821 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8822 int ch;
8823 struct got_update_progress_arg upa;
8825 while ((ch = getopt(argc, argv, "")) != -1) {
8826 switch (ch) {
8827 default:
8828 usage_integrate();
8829 /* NOTREACHED */
8833 argc -= optind;
8834 argv += optind;
8836 if (argc != 1)
8837 usage_integrate();
8838 branch_arg = argv[0];
8840 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8841 "unveil", NULL) == -1)
8842 err(1, "pledge");
8844 cwd = getcwd(NULL, 0);
8845 if (cwd == NULL) {
8846 error = got_error_from_errno("getcwd");
8847 goto done;
8850 error = got_worktree_open(&worktree, cwd);
8851 if (error) {
8852 if (error->code == GOT_ERR_NOT_WORKTREE)
8853 error = wrap_not_worktree_error(error, "integrate",
8854 cwd);
8855 goto done;
8858 error = check_rebase_or_histedit_in_progress(worktree);
8859 if (error)
8860 goto done;
8862 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8863 NULL);
8864 if (error != NULL)
8865 goto done;
8867 error = apply_unveil(got_repo_get_path(repo), 0,
8868 got_worktree_get_root_path(worktree));
8869 if (error)
8870 goto done;
8872 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8873 error = got_error_from_errno("asprintf");
8874 goto done;
8877 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8878 &base_branch_ref, worktree, refname, repo);
8879 if (error)
8880 goto done;
8882 refname = strdup(got_ref_get_name(branch_ref));
8883 if (refname == NULL) {
8884 error = got_error_from_errno("strdup");
8885 got_worktree_integrate_abort(worktree, fileindex, repo,
8886 branch_ref, base_branch_ref);
8887 goto done;
8889 base_refname = strdup(got_ref_get_name(base_branch_ref));
8890 if (base_refname == NULL) {
8891 error = got_error_from_errno("strdup");
8892 got_worktree_integrate_abort(worktree, fileindex, repo,
8893 branch_ref, base_branch_ref);
8894 goto done;
8897 error = got_ref_resolve(&commit_id, repo, branch_ref);
8898 if (error)
8899 goto done;
8901 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8902 if (error)
8903 goto done;
8905 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8906 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8907 "specified branch has already been integrated");
8908 got_worktree_integrate_abort(worktree, fileindex, repo,
8909 branch_ref, base_branch_ref);
8910 goto done;
8913 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8914 if (error) {
8915 if (error->code == GOT_ERR_ANCESTRY)
8916 error = got_error(GOT_ERR_REBASE_REQUIRED);
8917 got_worktree_integrate_abort(worktree, fileindex, repo,
8918 branch_ref, base_branch_ref);
8919 goto done;
8922 memset(&upa, 0, sizeof(upa));
8923 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8924 branch_ref, base_branch_ref, update_progress, &upa,
8925 check_cancelled, NULL);
8926 if (error)
8927 goto done;
8929 printf("Integrated %s into %s\n", refname, base_refname);
8930 print_update_progress_stats(&upa);
8931 done:
8932 if (repo)
8933 got_repo_close(repo);
8934 if (worktree)
8935 got_worktree_close(worktree);
8936 free(cwd);
8937 free(base_commit_id);
8938 free(commit_id);
8939 free(refname);
8940 free(base_refname);
8941 return error;
8944 __dead static void
8945 usage_stage(void)
8947 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8948 "[-S] [file-path ...]\n",
8949 getprogname());
8950 exit(1);
8953 static const struct got_error *
8954 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8955 const char *path, struct got_object_id *blob_id,
8956 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8957 int dirfd, const char *de_name)
8959 const struct got_error *err = NULL;
8960 char *id_str = NULL;
8962 if (staged_status != GOT_STATUS_ADD &&
8963 staged_status != GOT_STATUS_MODIFY &&
8964 staged_status != GOT_STATUS_DELETE)
8965 return NULL;
8967 if (staged_status == GOT_STATUS_ADD ||
8968 staged_status == GOT_STATUS_MODIFY)
8969 err = got_object_id_str(&id_str, staged_blob_id);
8970 else
8971 err = got_object_id_str(&id_str, blob_id);
8972 if (err)
8973 return err;
8975 printf("%s %c %s\n", id_str, staged_status, path);
8976 free(id_str);
8977 return NULL;
8980 static const struct got_error *
8981 cmd_stage(int argc, char *argv[])
8983 const struct got_error *error = NULL;
8984 struct got_repository *repo = NULL;
8985 struct got_worktree *worktree = NULL;
8986 char *cwd = NULL;
8987 struct got_pathlist_head paths;
8988 struct got_pathlist_entry *pe;
8989 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8990 FILE *patch_script_file = NULL;
8991 const char *patch_script_path = NULL;
8992 struct choose_patch_arg cpa;
8994 TAILQ_INIT(&paths);
8996 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
8997 switch (ch) {
8998 case 'l':
8999 list_stage = 1;
9000 break;
9001 case 'p':
9002 pflag = 1;
9003 break;
9004 case 'F':
9005 patch_script_path = optarg;
9006 break;
9007 case 'S':
9008 allow_bad_symlinks = 1;
9009 break;
9010 default:
9011 usage_stage();
9012 /* NOTREACHED */
9016 argc -= optind;
9017 argv += optind;
9019 #ifndef PROFILE
9020 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9021 "unveil", NULL) == -1)
9022 err(1, "pledge");
9023 #endif
9024 if (list_stage && (pflag || patch_script_path))
9025 errx(1, "-l option cannot be used with other options");
9026 if (patch_script_path && !pflag)
9027 errx(1, "-F option can only be used together with -p option");
9029 cwd = getcwd(NULL, 0);
9030 if (cwd == NULL) {
9031 error = got_error_from_errno("getcwd");
9032 goto done;
9035 error = got_worktree_open(&worktree, cwd);
9036 if (error) {
9037 if (error->code == GOT_ERR_NOT_WORKTREE)
9038 error = wrap_not_worktree_error(error, "stage", cwd);
9039 goto done;
9042 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9043 NULL);
9044 if (error != NULL)
9045 goto done;
9047 if (patch_script_path) {
9048 patch_script_file = fopen(patch_script_path, "r");
9049 if (patch_script_file == NULL) {
9050 error = got_error_from_errno2("fopen",
9051 patch_script_path);
9052 goto done;
9055 error = apply_unveil(got_repo_get_path(repo), 0,
9056 got_worktree_get_root_path(worktree));
9057 if (error)
9058 goto done;
9060 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9061 if (error)
9062 goto done;
9064 if (list_stage)
9065 error = got_worktree_status(worktree, &paths, repo,
9066 print_stage, NULL, check_cancelled, NULL);
9067 else {
9068 cpa.patch_script_file = patch_script_file;
9069 cpa.action = "stage";
9070 error = got_worktree_stage(worktree, &paths,
9071 pflag ? NULL : print_status, NULL,
9072 pflag ? choose_patch : NULL, &cpa,
9073 allow_bad_symlinks, repo);
9075 done:
9076 if (patch_script_file && fclose(patch_script_file) == EOF &&
9077 error == NULL)
9078 error = got_error_from_errno2("fclose", patch_script_path);
9079 if (repo)
9080 got_repo_close(repo);
9081 if (worktree)
9082 got_worktree_close(worktree);
9083 TAILQ_FOREACH(pe, &paths, entry)
9084 free((char *)pe->path);
9085 got_pathlist_free(&paths);
9086 free(cwd);
9087 return error;
9090 __dead static void
9091 usage_unstage(void)
9093 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9094 "[file-path ...]\n",
9095 getprogname());
9096 exit(1);
9100 static const struct got_error *
9101 cmd_unstage(int argc, char *argv[])
9103 const struct got_error *error = NULL;
9104 struct got_repository *repo = NULL;
9105 struct got_worktree *worktree = NULL;
9106 char *cwd = NULL;
9107 struct got_pathlist_head paths;
9108 struct got_pathlist_entry *pe;
9109 int ch, pflag = 0;
9110 struct got_update_progress_arg upa;
9111 FILE *patch_script_file = NULL;
9112 const char *patch_script_path = NULL;
9113 struct choose_patch_arg cpa;
9115 TAILQ_INIT(&paths);
9117 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9118 switch (ch) {
9119 case 'p':
9120 pflag = 1;
9121 break;
9122 case 'F':
9123 patch_script_path = optarg;
9124 break;
9125 default:
9126 usage_unstage();
9127 /* NOTREACHED */
9131 argc -= optind;
9132 argv += optind;
9134 #ifndef PROFILE
9135 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9136 "unveil", NULL) == -1)
9137 err(1, "pledge");
9138 #endif
9139 if (patch_script_path && !pflag)
9140 errx(1, "-F option can only be used together with -p option");
9142 cwd = getcwd(NULL, 0);
9143 if (cwd == NULL) {
9144 error = got_error_from_errno("getcwd");
9145 goto done;
9148 error = got_worktree_open(&worktree, cwd);
9149 if (error) {
9150 if (error->code == GOT_ERR_NOT_WORKTREE)
9151 error = wrap_not_worktree_error(error, "unstage", cwd);
9152 goto done;
9155 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9156 NULL);
9157 if (error != NULL)
9158 goto done;
9160 if (patch_script_path) {
9161 patch_script_file = fopen(patch_script_path, "r");
9162 if (patch_script_file == NULL) {
9163 error = got_error_from_errno2("fopen",
9164 patch_script_path);
9165 goto done;
9169 error = apply_unveil(got_repo_get_path(repo), 0,
9170 got_worktree_get_root_path(worktree));
9171 if (error)
9172 goto done;
9174 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9175 if (error)
9176 goto done;
9178 cpa.patch_script_file = patch_script_file;
9179 cpa.action = "unstage";
9180 memset(&upa, 0, sizeof(upa));
9181 error = got_worktree_unstage(worktree, &paths, update_progress,
9182 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9183 if (!error)
9184 print_update_progress_stats(&upa);
9185 done:
9186 if (patch_script_file && fclose(patch_script_file) == EOF &&
9187 error == NULL)
9188 error = got_error_from_errno2("fclose", patch_script_path);
9189 if (repo)
9190 got_repo_close(repo);
9191 if (worktree)
9192 got_worktree_close(worktree);
9193 TAILQ_FOREACH(pe, &paths, entry)
9194 free((char *)pe->path);
9195 got_pathlist_free(&paths);
9196 free(cwd);
9197 return error;
9200 __dead static void
9201 usage_cat(void)
9203 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9204 "arg1 [arg2 ...]\n", getprogname());
9205 exit(1);
9208 static const struct got_error *
9209 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9211 const struct got_error *err;
9212 struct got_blob_object *blob;
9214 err = got_object_open_as_blob(&blob, repo, id, 8192);
9215 if (err)
9216 return err;
9218 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9219 got_object_blob_close(blob);
9220 return err;
9223 static const struct got_error *
9224 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9226 const struct got_error *err;
9227 struct got_tree_object *tree;
9228 int nentries, i;
9230 err = got_object_open_as_tree(&tree, repo, id);
9231 if (err)
9232 return err;
9234 nentries = got_object_tree_get_nentries(tree);
9235 for (i = 0; i < nentries; i++) {
9236 struct got_tree_entry *te;
9237 char *id_str;
9238 if (sigint_received || sigpipe_received)
9239 break;
9240 te = got_object_tree_get_entry(tree, i);
9241 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9242 if (err)
9243 break;
9244 fprintf(outfile, "%s %.7o %s\n", id_str,
9245 got_tree_entry_get_mode(te),
9246 got_tree_entry_get_name(te));
9247 free(id_str);
9250 got_object_tree_close(tree);
9251 return err;
9254 static const struct got_error *
9255 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9257 const struct got_error *err;
9258 struct got_commit_object *commit;
9259 const struct got_object_id_queue *parent_ids;
9260 struct got_object_qid *pid;
9261 char *id_str = NULL;
9262 const char *logmsg = NULL;
9264 err = got_object_open_as_commit(&commit, repo, id);
9265 if (err)
9266 return err;
9268 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9269 if (err)
9270 goto done;
9272 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9273 parent_ids = got_object_commit_get_parent_ids(commit);
9274 fprintf(outfile, "numparents %d\n",
9275 got_object_commit_get_nparents(commit));
9276 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9277 char *pid_str;
9278 err = got_object_id_str(&pid_str, pid->id);
9279 if (err)
9280 goto done;
9281 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9282 free(pid_str);
9284 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9285 got_object_commit_get_author(commit),
9286 got_object_commit_get_author_time(commit));
9288 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9289 got_object_commit_get_author(commit),
9290 got_object_commit_get_committer_time(commit));
9292 logmsg = got_object_commit_get_logmsg_raw(commit);
9293 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9294 fprintf(outfile, "%s", logmsg);
9295 done:
9296 free(id_str);
9297 got_object_commit_close(commit);
9298 return err;
9301 static const struct got_error *
9302 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9304 const struct got_error *err;
9305 struct got_tag_object *tag;
9306 char *id_str = NULL;
9307 const char *tagmsg = NULL;
9309 err = got_object_open_as_tag(&tag, repo, id);
9310 if (err)
9311 return err;
9313 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9314 if (err)
9315 goto done;
9317 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9319 switch (got_object_tag_get_object_type(tag)) {
9320 case GOT_OBJ_TYPE_BLOB:
9321 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9322 GOT_OBJ_LABEL_BLOB);
9323 break;
9324 case GOT_OBJ_TYPE_TREE:
9325 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9326 GOT_OBJ_LABEL_TREE);
9327 break;
9328 case GOT_OBJ_TYPE_COMMIT:
9329 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9330 GOT_OBJ_LABEL_COMMIT);
9331 break;
9332 case GOT_OBJ_TYPE_TAG:
9333 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9334 GOT_OBJ_LABEL_TAG);
9335 break;
9336 default:
9337 break;
9340 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9341 got_object_tag_get_name(tag));
9343 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9344 got_object_tag_get_tagger(tag),
9345 got_object_tag_get_tagger_time(tag));
9347 tagmsg = got_object_tag_get_message(tag);
9348 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9349 fprintf(outfile, "%s", tagmsg);
9350 done:
9351 free(id_str);
9352 got_object_tag_close(tag);
9353 return err;
9356 static const struct got_error *
9357 cmd_cat(int argc, char *argv[])
9359 const struct got_error *error;
9360 struct got_repository *repo = NULL;
9361 struct got_worktree *worktree = NULL;
9362 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9363 const char *commit_id_str = NULL;
9364 struct got_object_id *id = NULL, *commit_id = NULL;
9365 int ch, obj_type, i, force_path = 0;
9367 #ifndef PROFILE
9368 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9369 NULL) == -1)
9370 err(1, "pledge");
9371 #endif
9373 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9374 switch (ch) {
9375 case 'c':
9376 commit_id_str = optarg;
9377 break;
9378 case 'r':
9379 repo_path = realpath(optarg, NULL);
9380 if (repo_path == NULL)
9381 return got_error_from_errno2("realpath",
9382 optarg);
9383 got_path_strip_trailing_slashes(repo_path);
9384 break;
9385 case 'P':
9386 force_path = 1;
9387 break;
9388 default:
9389 usage_cat();
9390 /* NOTREACHED */
9394 argc -= optind;
9395 argv += optind;
9397 cwd = getcwd(NULL, 0);
9398 if (cwd == NULL) {
9399 error = got_error_from_errno("getcwd");
9400 goto done;
9402 error = got_worktree_open(&worktree, cwd);
9403 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9404 goto done;
9405 if (worktree) {
9406 if (repo_path == NULL) {
9407 repo_path = strdup(
9408 got_worktree_get_repo_path(worktree));
9409 if (repo_path == NULL) {
9410 error = got_error_from_errno("strdup");
9411 goto done;
9416 if (repo_path == NULL) {
9417 repo_path = getcwd(NULL, 0);
9418 if (repo_path == NULL)
9419 return got_error_from_errno("getcwd");
9422 error = got_repo_open(&repo, repo_path, NULL);
9423 free(repo_path);
9424 if (error != NULL)
9425 goto done;
9427 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9428 if (error)
9429 goto done;
9431 if (commit_id_str == NULL)
9432 commit_id_str = GOT_REF_HEAD;
9433 error = got_repo_match_object_id(&commit_id, NULL,
9434 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9435 if (error)
9436 goto done;
9438 for (i = 0; i < argc; i++) {
9439 if (force_path) {
9440 error = got_object_id_by_path(&id, repo, commit_id,
9441 argv[i]);
9442 if (error)
9443 break;
9444 } else {
9445 error = got_repo_match_object_id(&id, &label, argv[i],
9446 GOT_OBJ_TYPE_ANY, 0, repo);
9447 if (error) {
9448 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9449 error->code != GOT_ERR_NOT_REF)
9450 break;
9451 error = got_object_id_by_path(&id, repo,
9452 commit_id, argv[i]);
9453 if (error)
9454 break;
9458 error = got_object_get_type(&obj_type, repo, id);
9459 if (error)
9460 break;
9462 switch (obj_type) {
9463 case GOT_OBJ_TYPE_BLOB:
9464 error = cat_blob(id, repo, stdout);
9465 break;
9466 case GOT_OBJ_TYPE_TREE:
9467 error = cat_tree(id, repo, stdout);
9468 break;
9469 case GOT_OBJ_TYPE_COMMIT:
9470 error = cat_commit(id, repo, stdout);
9471 break;
9472 case GOT_OBJ_TYPE_TAG:
9473 error = cat_tag(id, repo, stdout);
9474 break;
9475 default:
9476 error = got_error(GOT_ERR_OBJ_TYPE);
9477 break;
9479 if (error)
9480 break;
9481 free(label);
9482 label = NULL;
9483 free(id);
9484 id = NULL;
9486 done:
9487 free(label);
9488 free(id);
9489 free(commit_id);
9490 if (worktree)
9491 got_worktree_close(worktree);
9492 if (repo) {
9493 const struct got_error *repo_error;
9494 repo_error = got_repo_close(repo);
9495 if (error == NULL)
9496 error = repo_error;
9498 return error;
9501 __dead static void
9502 usage_info(void)
9504 fprintf(stderr, "usage: %s info [path ...]\n",
9505 getprogname());
9506 exit(1);
9509 static const struct got_error *
9510 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9511 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9512 struct got_object_id *commit_id)
9514 const struct got_error *err = NULL;
9515 char *id_str = NULL;
9516 char datebuf[128];
9517 struct tm mytm, *tm;
9518 struct got_pathlist_head *paths = arg;
9519 struct got_pathlist_entry *pe;
9522 * Clear error indication from any of the path arguments which
9523 * would cause this file index entry to be displayed.
9525 TAILQ_FOREACH(pe, paths, entry) {
9526 if (got_path_cmp(path, pe->path, strlen(path),
9527 pe->path_len) == 0 ||
9528 got_path_is_child(path, pe->path, pe->path_len))
9529 pe->data = NULL; /* no error */
9532 printf(GOT_COMMIT_SEP_STR);
9533 if (S_ISLNK(mode))
9534 printf("symlink: %s\n", path);
9535 else if (S_ISREG(mode)) {
9536 printf("file: %s\n", path);
9537 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9538 } else if (S_ISDIR(mode))
9539 printf("directory: %s\n", path);
9540 else
9541 printf("something: %s\n", path);
9543 tm = localtime_r(&mtime, &mytm);
9544 if (tm == NULL)
9545 return NULL;
9546 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9547 return got_error(GOT_ERR_NO_SPACE);
9548 printf("timestamp: %s\n", datebuf);
9550 if (blob_id) {
9551 err = got_object_id_str(&id_str, blob_id);
9552 if (err)
9553 return err;
9554 printf("based on blob: %s\n", id_str);
9555 free(id_str);
9558 if (staged_blob_id) {
9559 err = got_object_id_str(&id_str, staged_blob_id);
9560 if (err)
9561 return err;
9562 printf("based on staged blob: %s\n", id_str);
9563 free(id_str);
9566 if (commit_id) {
9567 err = got_object_id_str(&id_str, commit_id);
9568 if (err)
9569 return err;
9570 printf("based on commit: %s\n", id_str);
9571 free(id_str);
9574 return NULL;
9577 static const struct got_error *
9578 cmd_info(int argc, char *argv[])
9580 const struct got_error *error = NULL;
9581 struct got_worktree *worktree = NULL;
9582 char *cwd = NULL, *id_str = NULL;
9583 struct got_pathlist_head paths;
9584 struct got_pathlist_entry *pe;
9585 char *uuidstr = NULL;
9586 int ch, show_files = 0;
9588 TAILQ_INIT(&paths);
9590 while ((ch = getopt(argc, argv, "")) != -1) {
9591 switch (ch) {
9592 default:
9593 usage_info();
9594 /* NOTREACHED */
9598 argc -= optind;
9599 argv += optind;
9601 #ifndef PROFILE
9602 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9603 NULL) == -1)
9604 err(1, "pledge");
9605 #endif
9606 cwd = getcwd(NULL, 0);
9607 if (cwd == NULL) {
9608 error = got_error_from_errno("getcwd");
9609 goto done;
9612 error = got_worktree_open(&worktree, cwd);
9613 if (error) {
9614 if (error->code == GOT_ERR_NOT_WORKTREE)
9615 error = wrap_not_worktree_error(error, "status", cwd);
9616 goto done;
9619 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9620 if (error)
9621 goto done;
9623 if (argc >= 1) {
9624 error = get_worktree_paths_from_argv(&paths, argc, argv,
9625 worktree);
9626 if (error)
9627 goto done;
9628 show_files = 1;
9631 error = got_object_id_str(&id_str,
9632 got_worktree_get_base_commit_id(worktree));
9633 if (error)
9634 goto done;
9636 error = got_worktree_get_uuid(&uuidstr, worktree);
9637 if (error)
9638 goto done;
9640 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9641 printf("work tree base commit: %s\n", id_str);
9642 printf("work tree path prefix: %s\n",
9643 got_worktree_get_path_prefix(worktree));
9644 printf("work tree branch reference: %s\n",
9645 got_worktree_get_head_ref_name(worktree));
9646 printf("work tree UUID: %s\n", uuidstr);
9647 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9649 if (show_files) {
9650 struct got_pathlist_entry *pe;
9651 TAILQ_FOREACH(pe, &paths, entry) {
9652 if (pe->path_len == 0)
9653 continue;
9655 * Assume this path will fail. This will be corrected
9656 * in print_path_info() in case the path does suceeed.
9658 pe->data = (void *)got_error_path(pe->path,
9659 GOT_ERR_BAD_PATH);
9661 error = got_worktree_path_info(worktree, &paths,
9662 print_path_info, &paths, check_cancelled, NULL);
9663 if (error)
9664 goto done;
9665 TAILQ_FOREACH(pe, &paths, entry) {
9666 if (pe->data != NULL) {
9667 error = pe->data; /* bad path */
9668 break;
9672 done:
9673 TAILQ_FOREACH(pe, &paths, entry)
9674 free((char *)pe->path);
9675 got_pathlist_free(&paths);
9676 free(cwd);
9677 free(id_str);
9678 free(uuidstr);
9679 return error;