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"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
112 __dead static void usage_info(void);
114 static const struct got_error* cmd_init(int, char *[]);
115 static const struct got_error* cmd_import(int, char *[]);
116 static const struct got_error* cmd_clone(int, char *[]);
117 static const struct got_error* cmd_fetch(int, char *[]);
118 static const struct got_error* cmd_checkout(int, char *[]);
119 static const struct got_error* cmd_update(int, char *[]);
120 static const struct got_error* cmd_log(int, char *[]);
121 static const struct got_error* cmd_diff(int, char *[]);
122 static const struct got_error* cmd_blame(int, char *[]);
123 static const struct got_error* cmd_tree(int, char *[]);
124 static const struct got_error* cmd_status(int, char *[]);
125 static const struct got_error* cmd_ref(int, char *[]);
126 static const struct got_error* cmd_branch(int, char *[]);
127 static const struct got_error* cmd_tag(int, char *[]);
128 static const struct got_error* cmd_add(int, char *[]);
129 static const struct got_error* cmd_remove(int, char *[]);
130 static const struct got_error* cmd_revert(int, char *[]);
131 static const struct got_error* cmd_commit(int, char *[]);
132 static const struct got_error* cmd_cherrypick(int, char *[]);
133 static const struct got_error* cmd_backout(int, char *[]);
134 static const struct got_error* cmd_rebase(int, char *[]);
135 static const struct got_error* cmd_histedit(int, char *[]);
136 static const struct got_error* cmd_integrate(int, char *[]);
137 static const struct got_error* cmd_stage(int, char *[]);
138 static const struct got_error* cmd_unstage(int, char *[]);
139 static const struct got_error* cmd_cat(int, char *[]);
140 static const struct got_error* cmd_info(int, char *[]);
142 static struct got_cmd got_commands[] = {
143 { "init", cmd_init, usage_init, "" },
144 { "import", cmd_import, usage_import, "im" },
145 { "clone", cmd_clone, usage_clone, "cl" },
146 { "fetch", cmd_fetch, usage_fetch, "fe" },
147 { "checkout", cmd_checkout, usage_checkout, "co" },
148 { "update", cmd_update, usage_update, "up" },
149 { "log", cmd_log, usage_log, "" },
150 { "diff", cmd_diff, usage_diff, "di" },
151 { "blame", cmd_blame, usage_blame, "bl" },
152 { "tree", cmd_tree, usage_tree, "tr" },
153 { "status", cmd_status, usage_status, "st" },
154 { "ref", cmd_ref, usage_ref, "" },
155 { "branch", cmd_branch, usage_branch, "br" },
156 { "tag", cmd_tag, usage_tag, "" },
157 { "add", cmd_add, usage_add, "" },
158 { "remove", cmd_remove, usage_remove, "rm" },
159 { "revert", cmd_revert, usage_revert, "rv" },
160 { "commit", cmd_commit, usage_commit, "ci" },
161 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
162 { "backout", cmd_backout, usage_backout, "bo" },
163 { "rebase", cmd_rebase, usage_rebase, "rb" },
164 { "histedit", cmd_histedit, usage_histedit, "he" },
165 { "integrate", cmd_integrate, usage_integrate,"ig" },
166 { "stage", cmd_stage, usage_stage, "sg" },
167 { "unstage", cmd_unstage, usage_unstage, "ug" },
168 { "cat", cmd_cat, usage_cat, "" },
169 { "info", cmd_info, usage_info, "" },
170 };
172 static void
173 list_commands(void)
175 int i;
177 fprintf(stderr, "commands:");
178 for (i = 0; i < nitems(got_commands); i++) {
179 struct got_cmd *cmd = &got_commands[i];
180 fprintf(stderr, " %s", cmd->cmd_name);
182 fputc('\n', stderr);
185 int
186 main(int argc, char *argv[])
188 struct got_cmd *cmd;
189 unsigned int i;
190 int ch;
191 int hflag = 0, Vflag = 0;
192 static struct option longopts[] = {
193 { "version", no_argument, NULL, 'V' },
194 { NULL, 0, NULL, 0}
195 };
197 setlocale(LC_CTYPE, "");
199 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
200 switch (ch) {
201 case 'h':
202 hflag = 1;
203 break;
204 case 'V':
205 Vflag = 1;
206 break;
207 default:
208 usage(hflag);
209 /* NOTREACHED */
213 argc -= optind;
214 argv += optind;
215 optind = 0;
217 if (Vflag) {
218 got_version_print_str();
219 return 1;
222 if (argc <= 0)
223 usage(hflag);
225 signal(SIGINT, catch_sigint);
226 signal(SIGPIPE, catch_sigpipe);
228 for (i = 0; i < nitems(got_commands); i++) {
229 const struct got_error *error;
231 cmd = &got_commands[i];
233 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
234 strcmp(cmd->cmd_alias, argv[0]) != 0)
235 continue;
237 if (hflag)
238 got_commands[i].cmd_usage();
240 error = got_commands[i].cmd_main(argc, argv);
241 if (error && error->code != GOT_ERR_CANCELLED &&
242 error->code != GOT_ERR_PRIVSEP_EXIT &&
243 !(sigpipe_received &&
244 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
245 !(sigint_received &&
246 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
247 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
248 return 1;
251 return 0;
254 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
255 list_commands();
256 return 1;
259 __dead static void
260 usage(int hflag)
262 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
263 getprogname());
264 if (hflag)
265 list_commands();
266 exit(1);
269 static const struct got_error *
270 get_editor(char **abspath)
272 const struct got_error *err = NULL;
273 const char *editor;
275 *abspath = NULL;
277 editor = getenv("VISUAL");
278 if (editor == NULL)
279 editor = getenv("EDITOR");
281 if (editor) {
282 err = got_path_find_prog(abspath, editor);
283 if (err)
284 return err;
287 if (*abspath == NULL) {
288 *abspath = strdup("/bin/ed");
289 if (*abspath == NULL)
290 return got_error_from_errno("strdup");
293 return NULL;
296 static const struct got_error *
297 apply_unveil(const char *repo_path, int repo_read_only,
298 const char *worktree_path)
300 const struct got_error *err;
302 #ifdef PROFILE
303 if (unveil("gmon.out", "rwc") != 0)
304 return got_error_from_errno2("unveil", "gmon.out");
305 #endif
306 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
307 return got_error_from_errno2("unveil", repo_path);
309 if (worktree_path && unveil(worktree_path, "rwc") != 0)
310 return got_error_from_errno2("unveil", worktree_path);
312 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
313 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
315 err = got_privsep_unveil_exec_helpers();
316 if (err != NULL)
317 return err;
319 if (unveil(NULL, NULL) != 0)
320 return got_error_from_errno("unveil");
322 return NULL;
325 __dead static void
326 usage_init(void)
328 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
329 exit(1);
332 static const struct got_error *
333 cmd_init(int argc, char *argv[])
335 const struct got_error *error = NULL;
336 char *repo_path = NULL;
337 int ch;
339 while ((ch = getopt(argc, argv, "")) != -1) {
340 switch (ch) {
341 default:
342 usage_init();
343 /* NOTREACHED */
347 argc -= optind;
348 argv += optind;
350 #ifndef PROFILE
351 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
352 err(1, "pledge");
353 #endif
354 if (argc != 1)
355 usage_init();
357 repo_path = strdup(argv[0]);
358 if (repo_path == NULL)
359 return got_error_from_errno("strdup");
361 got_path_strip_trailing_slashes(repo_path);
363 error = got_path_mkdir(repo_path);
364 if (error &&
365 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
366 goto done;
368 error = apply_unveil(repo_path, 0, NULL);
369 if (error)
370 goto done;
372 error = got_repo_init(repo_path);
373 done:
374 free(repo_path);
375 return error;
378 __dead static void
379 usage_import(void)
381 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
382 "[-r repository-path] [-I pattern] path\n", getprogname());
383 exit(1);
386 int
387 spawn_editor(const char *editor, const char *file)
389 pid_t pid;
390 sig_t sighup, sigint, sigquit;
391 int st = -1;
393 sighup = signal(SIGHUP, SIG_IGN);
394 sigint = signal(SIGINT, SIG_IGN);
395 sigquit = signal(SIGQUIT, SIG_IGN);
397 switch (pid = fork()) {
398 case -1:
399 goto doneediting;
400 case 0:
401 execl(editor, editor, file, (char *)NULL);
402 _exit(127);
405 while (waitpid(pid, &st, 0) == -1)
406 if (errno != EINTR)
407 break;
409 doneediting:
410 (void)signal(SIGHUP, sighup);
411 (void)signal(SIGINT, sigint);
412 (void)signal(SIGQUIT, sigquit);
414 if (!WIFEXITED(st)) {
415 errno = EINTR;
416 return -1;
419 return WEXITSTATUS(st);
422 static const struct got_error *
423 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
424 const char *initial_content)
426 const struct got_error *err = NULL;
427 char buf[1024];
428 struct stat st, st2;
429 FILE *fp;
430 int content_changed = 0;
431 size_t len;
433 *logmsg = NULL;
435 if (stat(logmsg_path, &st) == -1)
436 return got_error_from_errno2("stat", logmsg_path);
438 if (spawn_editor(editor, logmsg_path) == -1)
439 return got_error_from_errno("failed spawning editor");
441 if (stat(logmsg_path, &st2) == -1)
442 return got_error_from_errno("stat");
444 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
445 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
446 "no changes made to commit message, aborting");
448 *logmsg = malloc(st2.st_size + 1);
449 if (*logmsg == NULL)
450 return got_error_from_errno("malloc");
451 (*logmsg)[0] = '\0';
452 len = 0;
454 fp = fopen(logmsg_path, "r");
455 if (fp == NULL) {
456 err = got_error_from_errno("fopen");
457 goto done;
459 while (fgets(buf, sizeof(buf), fp) != NULL) {
460 if (!content_changed && strcmp(buf, initial_content) != 0)
461 content_changed = 1;
462 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
463 continue; /* remove comments and leading empty lines */
464 len = strlcat(*logmsg, buf, st2.st_size);
466 fclose(fp);
468 while (len > 0 && (*logmsg)[len - 1] == '\n') {
469 (*logmsg)[len - 1] = '\0';
470 len--;
473 if (len == 0 || !content_changed)
474 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
475 "commit message cannot be empty, aborting");
476 done:
477 if (err) {
478 free(*logmsg);
479 *logmsg = NULL;
481 return err;
484 static const struct got_error *
485 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
486 const char *path_dir, const char *branch_name)
488 char *initial_content = NULL;
489 const struct got_error *err = NULL;
490 int fd;
492 if (asprintf(&initial_content,
493 "\n# %s to be imported to branch %s\n", path_dir,
494 branch_name) == -1)
495 return got_error_from_errno("asprintf");
497 err = got_opentemp_named_fd(logmsg_path, &fd,
498 GOT_TMPDIR_STR "/got-importmsg");
499 if (err)
500 goto done;
502 dprintf(fd, initial_content);
503 close(fd);
505 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
506 done:
507 free(initial_content);
508 return err;
511 static const struct got_error *
512 import_progress(void *arg, const char *path)
514 printf("A %s\n", path);
515 return NULL;
518 static const struct got_error *
519 get_author(char **author, struct got_repository *repo)
521 const struct got_error *err = NULL;
522 const char *got_author, *name, *email;
524 *author = NULL;
526 got_author = got_repo_get_gotconfig_author(repo);
527 if (got_author == NULL) {
528 name = got_repo_get_gitconfig_author_name(repo);
529 email = got_repo_get_gitconfig_author_email(repo);
530 if (name && email) {
531 if (asprintf(author, "%s <%s>", name, email) == -1)
532 return got_error_from_errno("asprintf");
533 return NULL;
536 got_author = getenv("GOT_AUTHOR");
537 if (got_author == NULL) {
538 name = got_repo_get_global_gitconfig_author_name(repo);
539 email = got_repo_get_global_gitconfig_author_email(
540 repo);
541 if (name && email) {
542 if (asprintf(author, "%s <%s>", name, email)
543 == -1)
544 return got_error_from_errno("asprintf");
545 return NULL;
547 /* TODO: Look up user in password database? */
548 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
552 *author = strdup(got_author);
553 if (*author == NULL)
554 return got_error_from_errno("strdup");
556 /*
557 * Really dumb email address check; we're only doing this to
558 * avoid git's object parser breaking on commits we create.
559 */
560 while (*got_author && *got_author != '<')
561 got_author++;
562 if (*got_author != '<') {
563 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
564 goto done;
566 while (*got_author && *got_author != '@')
567 got_author++;
568 if (*got_author != '@') {
569 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
570 goto done;
572 while (*got_author && *got_author != '>')
573 got_author++;
574 if (*got_author != '>')
575 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
576 done:
577 if (err) {
578 free(*author);
579 *author = NULL;
581 return err;
584 static const struct got_error *
585 get_gitconfig_path(char **gitconfig_path)
587 const char *homedir = getenv("HOME");
589 *gitconfig_path = NULL;
590 if (homedir) {
591 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
592 return got_error_from_errno("asprintf");
595 return NULL;
598 static const struct got_error *
599 cmd_import(int argc, char *argv[])
601 const struct got_error *error = NULL;
602 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
603 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
604 const char *branch_name = "main";
605 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
606 struct got_repository *repo = NULL;
607 struct got_reference *branch_ref = NULL, *head_ref = NULL;
608 struct got_object_id *new_commit_id = NULL;
609 int ch;
610 struct got_pathlist_head ignores;
611 struct got_pathlist_entry *pe;
612 int preserve_logmsg = 0;
614 TAILQ_INIT(&ignores);
616 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
617 switch (ch) {
618 case 'b':
619 branch_name = optarg;
620 break;
621 case 'm':
622 logmsg = strdup(optarg);
623 if (logmsg == NULL) {
624 error = got_error_from_errno("strdup");
625 goto done;
627 break;
628 case 'r':
629 repo_path = realpath(optarg, NULL);
630 if (repo_path == NULL) {
631 error = got_error_from_errno2("realpath",
632 optarg);
633 goto done;
635 break;
636 case 'I':
637 if (optarg[0] == '\0')
638 break;
639 error = got_pathlist_insert(&pe, &ignores, optarg,
640 NULL);
641 if (error)
642 goto done;
643 break;
644 default:
645 usage_import();
646 /* NOTREACHED */
650 argc -= optind;
651 argv += optind;
653 #ifndef PROFILE
654 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
655 "unveil",
656 NULL) == -1)
657 err(1, "pledge");
658 #endif
659 if (argc != 1)
660 usage_import();
662 if (repo_path == NULL) {
663 repo_path = getcwd(NULL, 0);
664 if (repo_path == NULL)
665 return got_error_from_errno("getcwd");
667 got_path_strip_trailing_slashes(repo_path);
668 error = get_gitconfig_path(&gitconfig_path);
669 if (error)
670 goto done;
671 error = got_repo_open(&repo, repo_path, gitconfig_path);
672 if (error)
673 goto done;
675 error = get_author(&author, repo);
676 if (error)
677 return error;
679 /*
680 * Don't let the user create a branch name with a leading '-'.
681 * While technically a valid reference name, this case is usually
682 * an unintended typo.
683 */
684 if (branch_name[0] == '-')
685 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
687 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
688 error = got_error_from_errno("asprintf");
689 goto done;
692 error = got_ref_open(&branch_ref, repo, refname, 0);
693 if (error) {
694 if (error->code != GOT_ERR_NOT_REF)
695 goto done;
696 } else {
697 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
698 "import target branch already exists");
699 goto done;
702 path_dir = realpath(argv[0], NULL);
703 if (path_dir == NULL) {
704 error = got_error_from_errno2("realpath", argv[0]);
705 goto done;
707 got_path_strip_trailing_slashes(path_dir);
709 /*
710 * unveil(2) traverses exec(2); if an editor is used we have
711 * to apply unveil after the log message has been written.
712 */
713 if (logmsg == NULL || strlen(logmsg) == 0) {
714 error = get_editor(&editor);
715 if (error)
716 goto done;
717 free(logmsg);
718 error = collect_import_msg(&logmsg, &logmsg_path, editor,
719 path_dir, refname);
720 if (error) {
721 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
722 logmsg_path != NULL)
723 preserve_logmsg = 1;
724 goto done;
728 if (unveil(path_dir, "r") != 0) {
729 error = got_error_from_errno2("unveil", path_dir);
730 if (logmsg_path)
731 preserve_logmsg = 1;
732 goto done;
735 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_repo_import(&new_commit_id, path_dir, logmsg,
743 author, &ignores, repo, import_progress, NULL);
744 if (error) {
745 if (logmsg_path)
746 preserve_logmsg = 1;
747 goto done;
750 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
751 if (error) {
752 if (logmsg_path)
753 preserve_logmsg = 1;
754 goto done;
757 error = got_ref_write(branch_ref, repo);
758 if (error) {
759 if (logmsg_path)
760 preserve_logmsg = 1;
761 goto done;
764 error = got_object_id_str(&id_str, new_commit_id);
765 if (error) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
772 if (error) {
773 if (error->code != GOT_ERR_NOT_REF) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
780 branch_ref);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(head_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
795 printf("Created branch %s with commit %s\n",
796 got_ref_get_name(branch_ref), id_str);
797 done:
798 if (preserve_logmsg) {
799 fprintf(stderr, "%s: log message preserved in %s\n",
800 getprogname(), logmsg_path);
801 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
802 error = got_error_from_errno2("unlink", logmsg_path);
803 free(logmsg);
804 free(logmsg_path);
805 free(repo_path);
806 free(editor);
807 free(refname);
808 free(new_commit_id);
809 free(id_str);
810 free(author);
811 free(gitconfig_path);
812 if (branch_ref)
813 got_ref_close(branch_ref);
814 if (head_ref)
815 got_ref_close(head_ref);
816 return error;
819 __dead static void
820 usage_clone(void)
822 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
823 "[-R reference] repository-url [directory]\n", getprogname());
824 exit(1);
827 struct got_fetch_progress_arg {
828 char last_scaled_size[FMT_SCALED_STRSIZE];
829 int last_p_indexed;
830 int last_p_resolved;
831 int verbosity;
832 };
834 static const struct got_error *
835 fetch_progress(void *arg, const char *message, off_t packfile_size,
836 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
838 struct got_fetch_progress_arg *a = arg;
839 char scaled_size[FMT_SCALED_STRSIZE];
840 int p_indexed, p_resolved;
841 int print_size = 0, print_indexed = 0, print_resolved = 0;
843 if (a->verbosity < 0)
844 return NULL;
846 if (message && message[0] != '\0') {
847 printf("\rserver: %s", message);
848 fflush(stdout);
849 return NULL;
852 if (packfile_size > 0 || nobj_indexed > 0) {
853 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
854 (a->last_scaled_size[0] == '\0' ||
855 strcmp(scaled_size, a->last_scaled_size)) != 0) {
856 print_size = 1;
857 if (strlcpy(a->last_scaled_size, scaled_size,
858 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
859 return got_error(GOT_ERR_NO_SPACE);
861 if (nobj_indexed > 0) {
862 p_indexed = (nobj_indexed * 100) / nobj_total;
863 if (p_indexed != a->last_p_indexed) {
864 a->last_p_indexed = p_indexed;
865 print_indexed = 1;
866 print_size = 1;
869 if (nobj_resolved > 0) {
870 p_resolved = (nobj_resolved * 100) /
871 (nobj_total - nobj_loose);
872 if (p_resolved != a->last_p_resolved) {
873 a->last_p_resolved = p_resolved;
874 print_resolved = 1;
875 print_indexed = 1;
876 print_size = 1;
881 if (print_size || print_indexed || print_resolved)
882 printf("\r");
883 if (print_size)
884 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
885 if (print_indexed)
886 printf("; indexing %d%%", p_indexed);
887 if (print_resolved)
888 printf("; resolving deltas %d%%", p_resolved);
889 if (print_size || print_indexed || print_resolved)
890 fflush(stdout);
892 return NULL;
895 static const struct got_error *
896 create_symref(const char *refname, struct got_reference *target_ref,
897 int verbosity, struct got_repository *repo)
899 const struct got_error *err;
900 struct got_reference *head_symref;
902 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
903 if (err)
904 return err;
906 err = got_ref_write(head_symref, repo);
907 got_ref_close(head_symref);
908 if (err == NULL && verbosity > 0) {
909 printf("Created reference %s: %s\n", GOT_REF_HEAD,
910 got_ref_get_name(target_ref));
912 return err;
915 static const struct got_error *
916 list_remote_refs(struct got_pathlist_head *symrefs,
917 struct got_pathlist_head *refs)
919 const struct got_error *err;
920 struct got_pathlist_entry *pe;
922 TAILQ_FOREACH(pe, symrefs, entry) {
923 const char *refname = pe->path;
924 const char *targetref = pe->data;
926 printf("%s: %s\n", refname, targetref);
929 TAILQ_FOREACH(pe, refs, entry) {
930 const char *refname = pe->path;
931 struct got_object_id *id = pe->data;
932 char *id_str;
934 err = got_object_id_str(&id_str, id);
935 if (err)
936 return err;
937 printf("%s: %s\n", refname, id_str);
938 free(id_str);
941 return NULL;
944 static const struct got_error *
945 create_ref(const char *refname, struct got_object_id *id,
946 int verbosity, struct got_repository *repo)
948 const struct got_error *err = NULL;
949 struct got_reference *ref;
950 char *id_str;
952 err = got_object_id_str(&id_str, id);
953 if (err)
954 return err;
956 err = got_ref_alloc(&ref, refname, id);
957 if (err)
958 goto done;
960 err = got_ref_write(ref, repo);
961 got_ref_close(ref);
963 if (err == NULL && verbosity >= 0)
964 printf("Created reference %s: %s\n", refname, id_str);
965 done:
966 free(id_str);
967 return err;
970 static int
971 match_wanted_ref(const char *refname, const char *wanted_ref)
973 if (strncmp(refname, "refs/", 5) != 0)
974 return 0;
975 refname += 5;
977 /*
978 * Prevent fetching of references that won't make any
979 * sense outside of the remote repository's context.
980 */
981 if (strncmp(refname, "got/", 4) == 0)
982 return 0;
983 if (strncmp(refname, "remotes/", 8) == 0)
984 return 0;
986 if (strncmp(wanted_ref, "refs/", 5) == 0)
987 wanted_ref += 5;
989 /* Allow prefix match. */
990 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
991 return 1;
993 /* Allow exact match. */
994 return (strcmp(refname, wanted_ref) == 0);
997 static int
998 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1000 struct got_pathlist_entry *pe;
1002 TAILQ_FOREACH(pe, wanted_refs, entry) {
1003 if (match_wanted_ref(refname, pe->path))
1004 return 1;
1007 return 0;
1010 static const struct got_error *
1011 create_wanted_ref(const char *refname, struct got_object_id *id,
1012 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1014 const struct got_error *err;
1015 char *remote_refname;
1017 if (strncmp("refs/", refname, 5) == 0)
1018 refname += 5;
1020 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1021 remote_repo_name, refname) == -1)
1022 return got_error_from_errno("asprintf");
1024 err = create_ref(remote_refname, id, verbosity, repo);
1025 free(remote_refname);
1026 return err;
1029 static const struct got_error *
1030 cmd_clone(int argc, char *argv[])
1032 const struct got_error *error = NULL;
1033 const char *uri, *dirname;
1034 char *proto, *host, *port, *repo_name, *server_path;
1035 char *default_destdir = NULL, *id_str = NULL;
1036 const char *repo_path;
1037 struct got_repository *repo = NULL;
1038 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1039 struct got_pathlist_entry *pe;
1040 struct got_object_id *pack_hash = NULL;
1041 int ch, fetchfd = -1, fetchstatus;
1042 pid_t fetchpid = -1;
1043 struct got_fetch_progress_arg fpa;
1044 char *git_url = NULL;
1045 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1046 char *gitconfig = NULL, *gotconfig = NULL;
1047 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1048 ssize_t n;
1049 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1050 int list_refs_only = 0;
1051 struct got_reference *head_symref = NULL;
1053 TAILQ_INIT(&refs);
1054 TAILQ_INIT(&symrefs);
1055 TAILQ_INIT(&wanted_branches);
1056 TAILQ_INIT(&wanted_refs);
1058 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1059 switch (ch) {
1060 case 'a':
1061 fetch_all_branches = 1;
1062 break;
1063 case 'b':
1064 error = got_pathlist_append(&wanted_branches,
1065 optarg, NULL);
1066 if (error)
1067 return error;
1068 break;
1069 case 'l':
1070 list_refs_only = 1;
1071 break;
1072 case 'm':
1073 mirror_references = 1;
1074 break;
1075 case 'v':
1076 if (verbosity < 0)
1077 verbosity = 0;
1078 else if (verbosity < 3)
1079 verbosity++;
1080 break;
1081 case 'q':
1082 verbosity = -1;
1083 break;
1084 case 'R':
1085 error = got_pathlist_append(&wanted_refs,
1086 optarg, NULL);
1087 if (error)
1088 return error;
1089 break;
1090 default:
1091 usage_clone();
1092 break;
1095 argc -= optind;
1096 argv += optind;
1098 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1099 errx(1, "-a and -b options are mutually exclusive");
1100 if (list_refs_only) {
1101 if (!TAILQ_EMPTY(&wanted_branches))
1102 errx(1, "-l and -b options are mutually exclusive");
1103 if (fetch_all_branches)
1104 errx(1, "-l and -a options are mutually exclusive");
1105 if (mirror_references)
1106 errx(1, "-l and -m options are mutually exclusive");
1107 if (verbosity == -1)
1108 errx(1, "-l and -q options are mutually exclusive");
1109 if (!TAILQ_EMPTY(&wanted_refs))
1110 errx(1, "-l and -R options are mutually exclusive");
1113 uri = argv[0];
1115 if (argc == 1)
1116 dirname = NULL;
1117 else if (argc == 2)
1118 dirname = argv[1];
1119 else
1120 usage_clone();
1122 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1123 &repo_name, uri);
1124 if (error)
1125 goto done;
1127 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1128 host, port ? ":" : "", port ? port : "",
1129 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1130 error = got_error_from_errno("asprintf");
1131 goto done;
1134 if (strcmp(proto, "git") == 0) {
1135 #ifndef PROFILE
1136 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1137 "sendfd dns inet unveil", NULL) == -1)
1138 err(1, "pledge");
1139 #endif
1140 } else if (strcmp(proto, "git+ssh") == 0 ||
1141 strcmp(proto, "ssh") == 0) {
1142 #ifndef PROFILE
1143 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1144 "sendfd unveil", NULL) == -1)
1145 err(1, "pledge");
1146 #endif
1147 } else if (strcmp(proto, "http") == 0 ||
1148 strcmp(proto, "git+http") == 0) {
1149 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1150 goto done;
1151 } else {
1152 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1153 goto done;
1155 if (dirname == NULL) {
1156 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1157 error = got_error_from_errno("asprintf");
1158 goto done;
1160 repo_path = default_destdir;
1161 } else
1162 repo_path = dirname;
1164 if (!list_refs_only) {
1165 error = got_path_mkdir(repo_path);
1166 if (error)
1167 goto done;
1169 error = got_repo_init(repo_path);
1170 if (error)
1171 goto done;
1172 error = got_repo_open(&repo, repo_path, NULL);
1173 if (error)
1174 goto done;
1177 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1178 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1179 error = got_error_from_errno2("unveil",
1180 GOT_FETCH_PATH_SSH);
1181 goto done;
1184 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1185 if (error)
1186 goto done;
1188 if (verbosity >= 0)
1189 printf("Connecting to %s%s%s\n", host,
1190 port ? ":" : "", port ? port : "");
1192 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1193 server_path, verbosity);
1194 if (error)
1195 goto done;
1197 fpa.last_scaled_size[0] = '\0';
1198 fpa.last_p_indexed = -1;
1199 fpa.last_p_resolved = -1;
1200 fpa.verbosity = verbosity;
1201 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1202 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1203 fetch_all_branches, &wanted_branches, &wanted_refs,
1204 list_refs_only, verbosity, fetchfd, repo,
1205 fetch_progress, &fpa);
1206 if (error)
1207 goto done;
1209 if (list_refs_only) {
1210 error = list_remote_refs(&symrefs, &refs);
1211 goto done;
1214 error = got_object_id_str(&id_str, pack_hash);
1215 if (error)
1216 goto done;
1217 if (verbosity >= 0)
1218 printf("\nFetched %s.pack\n", id_str);
1219 free(id_str);
1221 /* Set up references provided with the pack file. */
1222 TAILQ_FOREACH(pe, &refs, entry) {
1223 const char *refname = pe->path;
1224 struct got_object_id *id = pe->data;
1225 char *remote_refname;
1227 if (is_wanted_ref(&wanted_refs, refname) &&
1228 !mirror_references) {
1229 error = create_wanted_ref(refname, id,
1230 GOT_FETCH_DEFAULT_REMOTE_NAME,
1231 verbosity - 1, repo);
1232 if (error)
1233 goto done;
1234 continue;
1237 error = create_ref(refname, id, verbosity - 1, repo);
1238 if (error)
1239 goto done;
1241 if (mirror_references)
1242 continue;
1244 if (strncmp("refs/heads/", refname, 11) != 0)
1245 continue;
1247 if (asprintf(&remote_refname,
1248 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1249 refname + 11) == -1) {
1250 error = got_error_from_errno("asprintf");
1251 goto done;
1253 error = create_ref(remote_refname, id, verbosity - 1, repo);
1254 free(remote_refname);
1255 if (error)
1256 goto done;
1259 /* Set the HEAD reference if the server provided one. */
1260 TAILQ_FOREACH(pe, &symrefs, entry) {
1261 struct got_reference *target_ref;
1262 const char *refname = pe->path;
1263 const char *target = pe->data;
1264 char *remote_refname = NULL, *remote_target = NULL;
1266 if (strcmp(refname, GOT_REF_HEAD) != 0)
1267 continue;
1269 error = got_ref_open(&target_ref, repo, target, 0);
1270 if (error) {
1271 if (error->code == GOT_ERR_NOT_REF) {
1272 error = NULL;
1273 continue;
1275 goto done;
1278 error = create_symref(refname, target_ref, verbosity, repo);
1279 got_ref_close(target_ref);
1280 if (error)
1281 goto done;
1283 if (mirror_references)
1284 continue;
1286 if (strncmp("refs/heads/", target, 11) != 0)
1287 continue;
1289 if (asprintf(&remote_refname,
1290 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1291 refname) == -1) {
1292 error = got_error_from_errno("asprintf");
1293 goto done;
1295 if (asprintf(&remote_target,
1296 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1297 target + 11) == -1) {
1298 error = got_error_from_errno("asprintf");
1299 free(remote_refname);
1300 goto done;
1302 error = got_ref_open(&target_ref, repo, remote_target, 0);
1303 if (error) {
1304 free(remote_refname);
1305 free(remote_target);
1306 if (error->code == GOT_ERR_NOT_REF) {
1307 error = NULL;
1308 continue;
1310 goto done;
1312 error = create_symref(remote_refname, target_ref,
1313 verbosity - 1, repo);
1314 free(remote_refname);
1315 free(remote_target);
1316 got_ref_close(target_ref);
1317 if (error)
1318 goto done;
1320 if (pe == NULL) {
1322 * We failed to set the HEAD reference. If we asked for
1323 * a set of wanted branches use the first of one of those
1324 * which could be fetched instead.
1326 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1327 const char *target = pe->path;
1328 struct got_reference *target_ref;
1330 error = got_ref_open(&target_ref, repo, target, 0);
1331 if (error) {
1332 if (error->code == GOT_ERR_NOT_REF) {
1333 error = NULL;
1334 continue;
1336 goto done;
1339 error = create_symref(GOT_REF_HEAD, target_ref,
1340 verbosity, repo);
1341 got_ref_close(target_ref);
1342 if (error)
1343 goto done;
1344 break;
1348 /* Create got.conf(5). */
1349 gotconfig_path = got_repo_get_path_gotconfig(repo);
1350 if (gotconfig_path == NULL) {
1351 error = got_error_from_errno("got_repo_get_path_gotconfig");
1352 goto done;
1354 gotconfig_file = fopen(gotconfig_path, "a");
1355 if (gotconfig_file == NULL) {
1356 error = got_error_from_errno2("fopen", gotconfig_path);
1357 goto done;
1359 got_path_strip_trailing_slashes(server_path);
1360 if (asprintf(&gotconfig,
1361 "remote \"%s\" {\n"
1362 "\tserver %s\n"
1363 "\tprotocol %s\n"
1364 "%s%s%s"
1365 "\trepository \"%s\"\n"
1366 "%s"
1367 "}\n",
1368 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1369 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1370 server_path,
1371 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1372 error = got_error_from_errno("asprintf");
1373 goto done;
1375 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1376 if (n != strlen(gotconfig)) {
1377 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1378 goto done;
1381 /* Create a config file Git can understand. */
1382 gitconfig_path = got_repo_get_path_gitconfig(repo);
1383 if (gitconfig_path == NULL) {
1384 error = got_error_from_errno("got_repo_get_path_gitconfig");
1385 goto done;
1387 gitconfig_file = fopen(gitconfig_path, "a");
1388 if (gitconfig_file == NULL) {
1389 error = got_error_from_errno2("fopen", gitconfig_path);
1390 goto done;
1392 if (mirror_references) {
1393 if (asprintf(&gitconfig,
1394 "[remote \"%s\"]\n"
1395 "\turl = %s\n"
1396 "\tfetch = +refs/*:refs/*\n"
1397 "\tmirror = true\n",
1398 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1399 error = got_error_from_errno("asprintf");
1400 goto done;
1402 } else if (fetch_all_branches) {
1403 if (asprintf(&gitconfig,
1404 "[remote \"%s\"]\n"
1405 "\turl = %s\n"
1406 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1407 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1408 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1409 error = got_error_from_errno("asprintf");
1410 goto done;
1412 } else {
1413 const char *branchname;
1416 * If the server specified a default branch, use just that one.
1417 * Otherwise fall back to fetching all branches on next fetch.
1419 if (head_symref) {
1420 branchname = got_ref_get_symref_target(head_symref);
1421 if (strncmp(branchname, "refs/heads/", 11) == 0)
1422 branchname += 11;
1423 } else
1424 branchname = "*"; /* fall back to all branches */
1425 if (asprintf(&gitconfig,
1426 "[remote \"%s\"]\n"
1427 "\turl = %s\n"
1428 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1429 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1430 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1431 branchname) == -1) {
1432 error = got_error_from_errno("asprintf");
1433 goto done;
1436 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1437 if (n != strlen(gitconfig)) {
1438 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1439 goto done;
1442 if (verbosity >= 0)
1443 printf("Created %s repository '%s'\n",
1444 mirror_references ? "mirrored" : "cloned", repo_path);
1445 done:
1446 if (fetchpid > 0) {
1447 if (kill(fetchpid, SIGTERM) == -1)
1448 error = got_error_from_errno("kill");
1449 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1450 error = got_error_from_errno("waitpid");
1452 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1453 error = got_error_from_errno("close");
1454 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1455 error = got_error_from_errno("fclose");
1456 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1457 error = got_error_from_errno("fclose");
1458 if (repo)
1459 got_repo_close(repo);
1460 if (head_symref)
1461 got_ref_close(head_symref);
1462 TAILQ_FOREACH(pe, &refs, entry) {
1463 free((void *)pe->path);
1464 free(pe->data);
1466 got_pathlist_free(&refs);
1467 TAILQ_FOREACH(pe, &symrefs, entry) {
1468 free((void *)pe->path);
1469 free(pe->data);
1471 got_pathlist_free(&symrefs);
1472 got_pathlist_free(&wanted_branches);
1473 got_pathlist_free(&wanted_refs);
1474 free(pack_hash);
1475 free(proto);
1476 free(host);
1477 free(port);
1478 free(server_path);
1479 free(repo_name);
1480 free(default_destdir);
1481 free(gotconfig);
1482 free(gitconfig);
1483 free(gotconfig_path);
1484 free(gitconfig_path);
1485 free(git_url);
1486 return error;
1489 static const struct got_error *
1490 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1491 int replace_tags, int verbosity, struct got_repository *repo)
1493 const struct got_error *err = NULL;
1494 char *new_id_str = NULL;
1495 struct got_object_id *old_id = NULL;
1497 err = got_object_id_str(&new_id_str, new_id);
1498 if (err)
1499 goto done;
1501 if (!replace_tags &&
1502 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1503 err = got_ref_resolve(&old_id, repo, ref);
1504 if (err)
1505 goto done;
1506 if (got_object_id_cmp(old_id, new_id) == 0)
1507 goto done;
1508 if (verbosity >= 0) {
1509 printf("Rejecting update of existing tag %s: %s\n",
1510 got_ref_get_name(ref), new_id_str);
1512 goto done;
1515 if (got_ref_is_symbolic(ref)) {
1516 if (verbosity >= 0) {
1517 printf("Replacing reference %s: %s\n",
1518 got_ref_get_name(ref),
1519 got_ref_get_symref_target(ref));
1521 err = got_ref_change_symref_to_ref(ref, new_id);
1522 if (err)
1523 goto done;
1524 err = got_ref_write(ref, repo);
1525 if (err)
1526 goto done;
1527 } else {
1528 err = got_ref_resolve(&old_id, repo, ref);
1529 if (err)
1530 goto done;
1531 if (got_object_id_cmp(old_id, new_id) == 0)
1532 goto done;
1534 err = got_ref_change_ref(ref, new_id);
1535 if (err)
1536 goto done;
1537 err = got_ref_write(ref, repo);
1538 if (err)
1539 goto done;
1542 if (verbosity >= 0)
1543 printf("Updated %s: %s\n", got_ref_get_name(ref),
1544 new_id_str);
1545 done:
1546 free(old_id);
1547 free(new_id_str);
1548 return err;
1551 static const struct got_error *
1552 update_symref(const char *refname, struct got_reference *target_ref,
1553 int verbosity, struct got_repository *repo)
1555 const struct got_error *err = NULL, *unlock_err;
1556 struct got_reference *symref;
1557 int symref_is_locked = 0;
1559 err = got_ref_open(&symref, repo, refname, 1);
1560 if (err) {
1561 if (err->code != GOT_ERR_NOT_REF)
1562 return err;
1563 err = got_ref_alloc_symref(&symref, refname, target_ref);
1564 if (err)
1565 goto done;
1567 err = got_ref_write(symref, repo);
1568 if (err)
1569 goto done;
1571 if (verbosity >= 0)
1572 printf("Created reference %s: %s\n",
1573 got_ref_get_name(symref),
1574 got_ref_get_symref_target(symref));
1575 } else {
1576 symref_is_locked = 1;
1578 if (strcmp(got_ref_get_symref_target(symref),
1579 got_ref_get_name(target_ref)) == 0)
1580 goto done;
1582 err = got_ref_change_symref(symref,
1583 got_ref_get_name(target_ref));
1584 if (err)
1585 goto done;
1587 err = got_ref_write(symref, repo);
1588 if (err)
1589 goto done;
1591 if (verbosity >= 0)
1592 printf("Updated %s: %s\n", got_ref_get_name(symref),
1593 got_ref_get_symref_target(symref));
1596 done:
1597 if (symref_is_locked) {
1598 unlock_err = got_ref_unlock(symref);
1599 if (unlock_err && err == NULL)
1600 err = unlock_err;
1602 got_ref_close(symref);
1603 return err;
1606 __dead static void
1607 usage_fetch(void)
1609 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1610 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1611 "[remote-repository-name]\n",
1612 getprogname());
1613 exit(1);
1616 static const struct got_error *
1617 delete_missing_ref(struct got_reference *ref,
1618 int verbosity, struct got_repository *repo)
1620 const struct got_error *err = NULL;
1621 struct got_object_id *id = NULL;
1622 char *id_str = NULL;
1624 if (got_ref_is_symbolic(ref)) {
1625 err = got_ref_delete(ref, repo);
1626 if (err)
1627 return err;
1628 if (verbosity >= 0) {
1629 printf("Deleted reference %s: %s\n",
1630 got_ref_get_name(ref),
1631 got_ref_get_symref_target(ref));
1633 } else {
1634 err = got_ref_resolve(&id, repo, ref);
1635 if (err)
1636 return err;
1637 err = got_object_id_str(&id_str, id);
1638 if (err)
1639 goto done;
1641 err = got_ref_delete(ref, repo);
1642 if (err)
1643 goto done;
1644 if (verbosity >= 0) {
1645 printf("Deleted reference %s: %s\n",
1646 got_ref_get_name(ref), id_str);
1649 done:
1650 free(id);
1651 free(id_str);
1652 return NULL;
1655 static const struct got_error *
1656 delete_missing_refs(struct got_pathlist_head *their_refs,
1657 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1658 int verbosity, struct got_repository *repo)
1660 const struct got_error *err = NULL, *unlock_err;
1661 struct got_reflist_head my_refs;
1662 struct got_reflist_entry *re;
1663 struct got_pathlist_entry *pe;
1664 char *remote_namespace = NULL;
1665 char *local_refname = NULL;
1667 SIMPLEQ_INIT(&my_refs);
1669 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1670 == -1)
1671 return got_error_from_errno("asprintf");
1673 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1674 if (err)
1675 goto done;
1677 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1678 const char *refname = got_ref_get_name(re->ref);
1680 if (!remote->mirror_references) {
1681 if (strncmp(refname, remote_namespace,
1682 strlen(remote_namespace)) == 0) {
1683 if (strcmp(refname + strlen(remote_namespace),
1684 GOT_REF_HEAD) == 0)
1685 continue;
1686 if (asprintf(&local_refname, "refs/heads/%s",
1687 refname + strlen(remote_namespace)) == -1) {
1688 err = got_error_from_errno("asprintf");
1689 goto done;
1691 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1692 continue;
1695 TAILQ_FOREACH(pe, their_refs, entry) {
1696 if (strcmp(local_refname, pe->path) == 0)
1697 break;
1699 if (pe != NULL)
1700 continue;
1702 TAILQ_FOREACH(pe, their_symrefs, entry) {
1703 if (strcmp(local_refname, pe->path) == 0)
1704 break;
1706 if (pe != NULL)
1707 continue;
1709 err = delete_missing_ref(re->ref, verbosity, repo);
1710 if (err)
1711 break;
1713 if (local_refname) {
1714 struct got_reference *ref;
1715 err = got_ref_open(&ref, repo, local_refname, 1);
1716 if (err) {
1717 if (err->code != GOT_ERR_NOT_REF)
1718 break;
1719 free(local_refname);
1720 local_refname = NULL;
1721 continue;
1723 err = delete_missing_ref(ref, verbosity, repo);
1724 if (err)
1725 break;
1726 unlock_err = got_ref_unlock(ref);
1727 got_ref_close(ref);
1728 if (unlock_err && err == NULL) {
1729 err = unlock_err;
1730 break;
1733 free(local_refname);
1734 local_refname = NULL;
1737 done:
1738 free(remote_namespace);
1739 free(local_refname);
1740 return err;
1743 static const struct got_error *
1744 update_wanted_ref(const char *refname, struct got_object_id *id,
1745 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1747 const struct got_error *err, *unlock_err;
1748 char *remote_refname;
1749 struct got_reference *ref;
1751 if (strncmp("refs/", refname, 5) == 0)
1752 refname += 5;
1754 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1755 remote_repo_name, refname) == -1)
1756 return got_error_from_errno("asprintf");
1758 err = got_ref_open(&ref, repo, remote_refname, 1);
1759 if (err) {
1760 if (err->code != GOT_ERR_NOT_REF)
1761 goto done;
1762 err = create_ref(remote_refname, id, verbosity, repo);
1763 } else {
1764 err = update_ref(ref, id, 0, verbosity, repo);
1765 unlock_err = got_ref_unlock(ref);
1766 if (unlock_err && err == NULL)
1767 err = unlock_err;
1768 got_ref_close(ref);
1770 done:
1771 free(remote_refname);
1772 return err;
1775 static const struct got_error *
1776 cmd_fetch(int argc, char *argv[])
1778 const struct got_error *error = NULL, *unlock_err;
1779 char *cwd = NULL, *repo_path = NULL;
1780 const char *remote_name;
1781 char *proto = NULL, *host = NULL, *port = NULL;
1782 char *repo_name = NULL, *server_path = NULL;
1783 struct got_remote_repo *remotes, *remote = NULL;
1784 int nremotes;
1785 char *id_str = NULL;
1786 struct got_repository *repo = NULL;
1787 struct got_worktree *worktree = NULL;
1788 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1789 struct got_pathlist_entry *pe;
1790 struct got_object_id *pack_hash = NULL;
1791 int i, ch, fetchfd = -1, fetchstatus;
1792 pid_t fetchpid = -1;
1793 struct got_fetch_progress_arg fpa;
1794 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1795 int delete_refs = 0, replace_tags = 0;
1797 TAILQ_INIT(&refs);
1798 TAILQ_INIT(&symrefs);
1799 TAILQ_INIT(&wanted_branches);
1800 TAILQ_INIT(&wanted_refs);
1802 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1803 switch (ch) {
1804 case 'a':
1805 fetch_all_branches = 1;
1806 break;
1807 case 'b':
1808 error = got_pathlist_append(&wanted_branches,
1809 optarg, NULL);
1810 if (error)
1811 return error;
1812 break;
1813 case 'd':
1814 delete_refs = 1;
1815 break;
1816 case 'l':
1817 list_refs_only = 1;
1818 break;
1819 case 'r':
1820 repo_path = realpath(optarg, NULL);
1821 if (repo_path == NULL)
1822 return got_error_from_errno2("realpath",
1823 optarg);
1824 got_path_strip_trailing_slashes(repo_path);
1825 break;
1826 case 't':
1827 replace_tags = 1;
1828 break;
1829 case 'v':
1830 if (verbosity < 0)
1831 verbosity = 0;
1832 else if (verbosity < 3)
1833 verbosity++;
1834 break;
1835 case 'q':
1836 verbosity = -1;
1837 break;
1838 case 'R':
1839 error = got_pathlist_append(&wanted_refs,
1840 optarg, NULL);
1841 if (error)
1842 return error;
1843 break;
1844 default:
1845 usage_fetch();
1846 break;
1849 argc -= optind;
1850 argv += optind;
1852 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1853 errx(1, "-a and -b options are mutually exclusive");
1854 if (list_refs_only) {
1855 if (!TAILQ_EMPTY(&wanted_branches))
1856 errx(1, "-l and -b options are mutually exclusive");
1857 if (fetch_all_branches)
1858 errx(1, "-l and -a options are mutually exclusive");
1859 if (delete_refs)
1860 errx(1, "-l and -d options are mutually exclusive");
1861 if (verbosity == -1)
1862 errx(1, "-l and -q options are mutually exclusive");
1865 if (argc == 0)
1866 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1867 else if (argc == 1)
1868 remote_name = argv[0];
1869 else
1870 usage_fetch();
1872 cwd = getcwd(NULL, 0);
1873 if (cwd == NULL) {
1874 error = got_error_from_errno("getcwd");
1875 goto done;
1878 if (repo_path == NULL) {
1879 error = got_worktree_open(&worktree, cwd);
1880 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1881 goto done;
1882 else
1883 error = NULL;
1884 if (worktree) {
1885 repo_path =
1886 strdup(got_worktree_get_repo_path(worktree));
1887 if (repo_path == NULL)
1888 error = got_error_from_errno("strdup");
1889 if (error)
1890 goto done;
1891 } else {
1892 repo_path = strdup(cwd);
1893 if (repo_path == NULL) {
1894 error = got_error_from_errno("strdup");
1895 goto done;
1900 error = got_repo_open(&repo, repo_path, NULL);
1901 if (error)
1902 goto done;
1904 got_repo_get_gotconfig_remotes(&nremotes, &remotes, repo);
1905 for (i = 0; i < nremotes; i++) {
1906 remote = &remotes[i];
1907 if (strcmp(remote->name, remote_name) == 0)
1908 break;
1910 if (i == nremotes) {
1911 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1912 for (i = 0; i < nremotes; i++) {
1913 remote = &remotes[i];
1914 if (strcmp(remote->name, remote_name) == 0)
1915 break;
1917 if (i == nremotes) {
1918 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1919 goto done;
1923 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1924 &repo_name, remote->url);
1925 if (error)
1926 goto done;
1928 if (strcmp(proto, "git") == 0) {
1929 #ifndef PROFILE
1930 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1931 "sendfd dns inet unveil", NULL) == -1)
1932 err(1, "pledge");
1933 #endif
1934 } else if (strcmp(proto, "git+ssh") == 0 ||
1935 strcmp(proto, "ssh") == 0) {
1936 #ifndef PROFILE
1937 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1938 "sendfd unveil", NULL) == -1)
1939 err(1, "pledge");
1940 #endif
1941 } else if (strcmp(proto, "http") == 0 ||
1942 strcmp(proto, "git+http") == 0) {
1943 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1944 goto done;
1945 } else {
1946 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1947 goto done;
1950 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1951 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1952 error = got_error_from_errno2("unveil",
1953 GOT_FETCH_PATH_SSH);
1954 goto done;
1957 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1958 if (error)
1959 goto done;
1961 if (verbosity >= 0)
1962 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
1963 port ? ":" : "", port ? port : "");
1965 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1966 server_path, verbosity);
1967 if (error)
1968 goto done;
1970 fpa.last_scaled_size[0] = '\0';
1971 fpa.last_p_indexed = -1;
1972 fpa.last_p_resolved = -1;
1973 fpa.verbosity = verbosity;
1974 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1975 remote->mirror_references, fetch_all_branches, &wanted_branches,
1976 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1977 fetch_progress, &fpa);
1978 if (error)
1979 goto done;
1981 if (list_refs_only) {
1982 error = list_remote_refs(&symrefs, &refs);
1983 goto done;
1986 if (pack_hash == NULL) {
1987 if (verbosity >= 0)
1988 printf("Already up-to-date\n");
1989 } else if (verbosity >= 0) {
1990 error = got_object_id_str(&id_str, pack_hash);
1991 if (error)
1992 goto done;
1993 printf("\nFetched %s.pack\n", id_str);
1994 free(id_str);
1995 id_str = NULL;
1998 /* Update references provided with the pack file. */
1999 TAILQ_FOREACH(pe, &refs, entry) {
2000 const char *refname = pe->path;
2001 struct got_object_id *id = pe->data;
2002 struct got_reference *ref;
2003 char *remote_refname;
2005 if (is_wanted_ref(&wanted_refs, refname) &&
2006 !remote->mirror_references) {
2007 error = update_wanted_ref(refname, id,
2008 remote->name, verbosity, repo);
2009 if (error)
2010 goto done;
2011 continue;
2014 if (remote->mirror_references ||
2015 strncmp("refs/tags/", refname, 10) == 0) {
2016 error = got_ref_open(&ref, repo, refname, 1);
2017 if (error) {
2018 if (error->code != GOT_ERR_NOT_REF)
2019 goto done;
2020 error = create_ref(refname, id, verbosity,
2021 repo);
2022 if (error)
2023 goto done;
2024 } else {
2025 error = update_ref(ref, id, replace_tags,
2026 verbosity, repo);
2027 unlock_err = got_ref_unlock(ref);
2028 if (unlock_err && error == NULL)
2029 error = unlock_err;
2030 got_ref_close(ref);
2031 if (error)
2032 goto done;
2034 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2035 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2036 remote_name, refname + 11) == -1) {
2037 error = got_error_from_errno("asprintf");
2038 goto done;
2041 error = got_ref_open(&ref, repo, remote_refname, 1);
2042 if (error) {
2043 if (error->code != GOT_ERR_NOT_REF)
2044 goto done;
2045 error = create_ref(remote_refname, id,
2046 verbosity, repo);
2047 if (error)
2048 goto done;
2049 } else {
2050 error = update_ref(ref, id, replace_tags,
2051 verbosity, repo);
2052 unlock_err = got_ref_unlock(ref);
2053 if (unlock_err && error == NULL)
2054 error = unlock_err;
2055 got_ref_close(ref);
2056 if (error)
2057 goto done;
2060 /* Also create a local branch if none exists yet. */
2061 error = got_ref_open(&ref, repo, refname, 1);
2062 if (error) {
2063 if (error->code != GOT_ERR_NOT_REF)
2064 goto done;
2065 error = create_ref(refname, id, verbosity,
2066 repo);
2067 if (error)
2068 goto done;
2069 } else {
2070 unlock_err = got_ref_unlock(ref);
2071 if (unlock_err && error == NULL)
2072 error = unlock_err;
2073 got_ref_close(ref);
2077 if (delete_refs) {
2078 error = delete_missing_refs(&refs, &symrefs, remote,
2079 verbosity, repo);
2080 if (error)
2081 goto done;
2084 if (!remote->mirror_references) {
2085 /* Update remote HEAD reference if the server provided one. */
2086 TAILQ_FOREACH(pe, &symrefs, entry) {
2087 struct got_reference *target_ref;
2088 const char *refname = pe->path;
2089 const char *target = pe->data;
2090 char *remote_refname = NULL, *remote_target = NULL;
2092 if (strcmp(refname, GOT_REF_HEAD) != 0)
2093 continue;
2095 if (strncmp("refs/heads/", target, 11) != 0)
2096 continue;
2098 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2099 remote->name, refname) == -1) {
2100 error = got_error_from_errno("asprintf");
2101 goto done;
2103 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2104 remote->name, target + 11) == -1) {
2105 error = got_error_from_errno("asprintf");
2106 free(remote_refname);
2107 goto done;
2110 error = got_ref_open(&target_ref, repo, remote_target,
2111 0);
2112 if (error) {
2113 free(remote_refname);
2114 free(remote_target);
2115 if (error->code == GOT_ERR_NOT_REF) {
2116 error = NULL;
2117 continue;
2119 goto done;
2121 error = update_symref(remote_refname, target_ref,
2122 verbosity, repo);
2123 free(remote_refname);
2124 free(remote_target);
2125 got_ref_close(target_ref);
2126 if (error)
2127 goto done;
2130 done:
2131 if (fetchpid > 0) {
2132 if (kill(fetchpid, SIGTERM) == -1)
2133 error = got_error_from_errno("kill");
2134 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2135 error = got_error_from_errno("waitpid");
2137 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2138 error = got_error_from_errno("close");
2139 if (repo)
2140 got_repo_close(repo);
2141 if (worktree)
2142 got_worktree_close(worktree);
2143 TAILQ_FOREACH(pe, &refs, entry) {
2144 free((void *)pe->path);
2145 free(pe->data);
2147 got_pathlist_free(&refs);
2148 TAILQ_FOREACH(pe, &symrefs, entry) {
2149 free((void *)pe->path);
2150 free(pe->data);
2152 got_pathlist_free(&symrefs);
2153 got_pathlist_free(&wanted_branches);
2154 got_pathlist_free(&wanted_refs);
2155 free(id_str);
2156 free(cwd);
2157 free(repo_path);
2158 free(pack_hash);
2159 free(proto);
2160 free(host);
2161 free(port);
2162 free(server_path);
2163 free(repo_name);
2164 return error;
2168 __dead static void
2169 usage_checkout(void)
2171 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2172 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2173 exit(1);
2176 static void
2177 show_worktree_base_ref_warning(void)
2179 fprintf(stderr, "%s: warning: could not create a reference "
2180 "to the work tree's base commit; the commit could be "
2181 "garbage-collected by Git; making the repository "
2182 "writable and running 'got update' will prevent this\n",
2183 getprogname());
2186 struct got_checkout_progress_arg {
2187 const char *worktree_path;
2188 int had_base_commit_ref_error;
2191 static const struct got_error *
2192 checkout_progress(void *arg, unsigned char status, const char *path)
2194 struct got_checkout_progress_arg *a = arg;
2196 /* Base commit bump happens silently. */
2197 if (status == GOT_STATUS_BUMP_BASE)
2198 return NULL;
2200 if (status == GOT_STATUS_BASE_REF_ERR) {
2201 a->had_base_commit_ref_error = 1;
2202 return NULL;
2205 while (path[0] == '/')
2206 path++;
2208 printf("%c %s/%s\n", status, a->worktree_path, path);
2209 return NULL;
2212 static const struct got_error *
2213 check_cancelled(void *arg)
2215 if (sigint_received || sigpipe_received)
2216 return got_error(GOT_ERR_CANCELLED);
2217 return NULL;
2220 static const struct got_error *
2221 check_linear_ancestry(struct got_object_id *commit_id,
2222 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2223 struct got_repository *repo)
2225 const struct got_error *err = NULL;
2226 struct got_object_id *yca_id;
2228 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2229 commit_id, base_commit_id, repo, check_cancelled, NULL);
2230 if (err)
2231 return err;
2233 if (yca_id == NULL)
2234 return got_error(GOT_ERR_ANCESTRY);
2237 * Require a straight line of history between the target commit
2238 * and the work tree's base commit.
2240 * Non-linear situations such as this require a rebase:
2242 * (commit) D F (base_commit)
2243 * \ /
2244 * C E
2245 * \ /
2246 * B (yca)
2247 * |
2248 * A
2250 * 'got update' only handles linear cases:
2251 * Update forwards in time: A (base/yca) - B - C - D (commit)
2252 * Update backwards in time: D (base) - C - B - A (commit/yca)
2254 if (allow_forwards_in_time_only) {
2255 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2256 return got_error(GOT_ERR_ANCESTRY);
2257 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2258 got_object_id_cmp(base_commit_id, yca_id) != 0)
2259 return got_error(GOT_ERR_ANCESTRY);
2261 free(yca_id);
2262 return NULL;
2265 static const struct got_error *
2266 check_same_branch(struct got_object_id *commit_id,
2267 struct got_reference *head_ref, struct got_object_id *yca_id,
2268 struct got_repository *repo)
2270 const struct got_error *err = NULL;
2271 struct got_commit_graph *graph = NULL;
2272 struct got_object_id *head_commit_id = NULL;
2273 int is_same_branch = 0;
2275 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2276 if (err)
2277 goto done;
2279 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2280 is_same_branch = 1;
2281 goto done;
2283 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2284 is_same_branch = 1;
2285 goto done;
2288 err = got_commit_graph_open(&graph, "/", 1);
2289 if (err)
2290 goto done;
2292 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2293 check_cancelled, NULL);
2294 if (err)
2295 goto done;
2297 for (;;) {
2298 struct got_object_id *id;
2299 err = got_commit_graph_iter_next(&id, graph, repo,
2300 check_cancelled, NULL);
2301 if (err) {
2302 if (err->code == GOT_ERR_ITER_COMPLETED)
2303 err = NULL;
2304 break;
2307 if (id) {
2308 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2309 break;
2310 if (got_object_id_cmp(id, commit_id) == 0) {
2311 is_same_branch = 1;
2312 break;
2316 done:
2317 if (graph)
2318 got_commit_graph_close(graph);
2319 free(head_commit_id);
2320 if (!err && !is_same_branch)
2321 err = got_error(GOT_ERR_ANCESTRY);
2322 return err;
2325 static const struct got_error *
2326 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2328 static char msg[512];
2329 const char *branch_name;
2331 if (got_ref_is_symbolic(ref))
2332 branch_name = got_ref_get_symref_target(ref);
2333 else
2334 branch_name = got_ref_get_name(ref);
2336 if (strncmp("refs/heads/", branch_name, 11) == 0)
2337 branch_name += 11;
2339 snprintf(msg, sizeof(msg),
2340 "target commit is not contained in branch '%s'; "
2341 "the branch to use must be specified with -b; "
2342 "if necessary a new branch can be created for "
2343 "this commit with 'got branch -c %s BRANCH_NAME'",
2344 branch_name, commit_id_str);
2346 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2349 static const struct got_error *
2350 cmd_checkout(int argc, char *argv[])
2352 const struct got_error *error = NULL;
2353 struct got_repository *repo = NULL;
2354 struct got_reference *head_ref = NULL;
2355 struct got_worktree *worktree = NULL;
2356 char *repo_path = NULL;
2357 char *worktree_path = NULL;
2358 const char *path_prefix = "";
2359 const char *branch_name = GOT_REF_HEAD;
2360 char *commit_id_str = NULL;
2361 int ch, same_path_prefix, allow_nonempty = 0;
2362 struct got_pathlist_head paths;
2363 struct got_checkout_progress_arg cpa;
2365 TAILQ_INIT(&paths);
2367 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2368 switch (ch) {
2369 case 'b':
2370 branch_name = optarg;
2371 break;
2372 case 'c':
2373 commit_id_str = strdup(optarg);
2374 if (commit_id_str == NULL)
2375 return got_error_from_errno("strdup");
2376 break;
2377 case 'E':
2378 allow_nonempty = 1;
2379 break;
2380 case 'p':
2381 path_prefix = optarg;
2382 break;
2383 default:
2384 usage_checkout();
2385 /* NOTREACHED */
2389 argc -= optind;
2390 argv += optind;
2392 #ifndef PROFILE
2393 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2394 "unveil", NULL) == -1)
2395 err(1, "pledge");
2396 #endif
2397 if (argc == 1) {
2398 char *cwd, *base, *dotgit;
2399 repo_path = realpath(argv[0], NULL);
2400 if (repo_path == NULL)
2401 return got_error_from_errno2("realpath", argv[0]);
2402 cwd = getcwd(NULL, 0);
2403 if (cwd == NULL) {
2404 error = got_error_from_errno("getcwd");
2405 goto done;
2407 if (path_prefix[0]) {
2408 base = basename(path_prefix);
2409 if (base == NULL) {
2410 error = got_error_from_errno2("basename",
2411 path_prefix);
2412 goto done;
2414 } else {
2415 base = basename(repo_path);
2416 if (base == NULL) {
2417 error = got_error_from_errno2("basename",
2418 repo_path);
2419 goto done;
2422 dotgit = strstr(base, ".git");
2423 if (dotgit)
2424 *dotgit = '\0';
2425 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2426 error = got_error_from_errno("asprintf");
2427 free(cwd);
2428 goto done;
2430 free(cwd);
2431 } else if (argc == 2) {
2432 repo_path = realpath(argv[0], NULL);
2433 if (repo_path == NULL) {
2434 error = got_error_from_errno2("realpath", argv[0]);
2435 goto done;
2437 worktree_path = realpath(argv[1], NULL);
2438 if (worktree_path == NULL) {
2439 if (errno != ENOENT) {
2440 error = got_error_from_errno2("realpath",
2441 argv[1]);
2442 goto done;
2444 worktree_path = strdup(argv[1]);
2445 if (worktree_path == NULL) {
2446 error = got_error_from_errno("strdup");
2447 goto done;
2450 } else
2451 usage_checkout();
2453 got_path_strip_trailing_slashes(repo_path);
2454 got_path_strip_trailing_slashes(worktree_path);
2456 error = got_repo_open(&repo, repo_path, NULL);
2457 if (error != NULL)
2458 goto done;
2460 /* Pre-create work tree path for unveil(2) */
2461 error = got_path_mkdir(worktree_path);
2462 if (error) {
2463 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2464 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2465 goto done;
2466 if (!allow_nonempty &&
2467 !got_path_dir_is_empty(worktree_path)) {
2468 error = got_error_path(worktree_path,
2469 GOT_ERR_DIR_NOT_EMPTY);
2470 goto done;
2474 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2475 if (error)
2476 goto done;
2478 error = got_ref_open(&head_ref, repo, branch_name, 0);
2479 if (error != NULL)
2480 goto done;
2482 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2483 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2484 goto done;
2486 error = got_worktree_open(&worktree, worktree_path);
2487 if (error != NULL)
2488 goto done;
2490 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2491 path_prefix);
2492 if (error != NULL)
2493 goto done;
2494 if (!same_path_prefix) {
2495 error = got_error(GOT_ERR_PATH_PREFIX);
2496 goto done;
2499 if (commit_id_str) {
2500 struct got_object_id *commit_id;
2501 error = got_repo_match_object_id(&commit_id, NULL,
2502 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2503 if (error)
2504 goto done;
2505 error = check_linear_ancestry(commit_id,
2506 got_worktree_get_base_commit_id(worktree), 0, repo);
2507 if (error != NULL) {
2508 free(commit_id);
2509 if (error->code == GOT_ERR_ANCESTRY) {
2510 error = checkout_ancestry_error(
2511 head_ref, commit_id_str);
2513 goto done;
2515 error = check_same_branch(commit_id, head_ref, NULL, repo);
2516 if (error) {
2517 if (error->code == GOT_ERR_ANCESTRY) {
2518 error = checkout_ancestry_error(
2519 head_ref, commit_id_str);
2521 goto done;
2523 error = got_worktree_set_base_commit_id(worktree, repo,
2524 commit_id);
2525 free(commit_id);
2526 if (error)
2527 goto done;
2530 error = got_pathlist_append(&paths, "", NULL);
2531 if (error)
2532 goto done;
2533 cpa.worktree_path = worktree_path;
2534 cpa.had_base_commit_ref_error = 0;
2535 error = got_worktree_checkout_files(worktree, &paths, repo,
2536 checkout_progress, &cpa, check_cancelled, NULL);
2537 if (error != NULL)
2538 goto done;
2540 printf("Now shut up and hack\n");
2541 if (cpa.had_base_commit_ref_error)
2542 show_worktree_base_ref_warning();
2543 done:
2544 got_pathlist_free(&paths);
2545 free(commit_id_str);
2546 free(repo_path);
2547 free(worktree_path);
2548 return error;
2551 struct got_update_progress_arg {
2552 int did_something;
2553 int conflicts;
2554 int obstructed;
2555 int not_updated;
2558 void
2559 print_update_progress_stats(struct got_update_progress_arg *upa)
2561 if (!upa->did_something)
2562 return;
2564 if (upa->conflicts > 0)
2565 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2566 if (upa->obstructed > 0)
2567 printf("File paths obstructed by a non-regular file: %d\n",
2568 upa->obstructed);
2569 if (upa->not_updated > 0)
2570 printf("Files not updated because of existing merge "
2571 "conflicts: %d\n", upa->not_updated);
2574 __dead static void
2575 usage_update(void)
2577 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2578 getprogname());
2579 exit(1);
2582 static const struct got_error *
2583 update_progress(void *arg, unsigned char status, const char *path)
2585 struct got_update_progress_arg *upa = arg;
2587 if (status == GOT_STATUS_EXISTS ||
2588 status == GOT_STATUS_BASE_REF_ERR)
2589 return NULL;
2591 upa->did_something = 1;
2593 /* Base commit bump happens silently. */
2594 if (status == GOT_STATUS_BUMP_BASE)
2595 return NULL;
2597 if (status == GOT_STATUS_CONFLICT)
2598 upa->conflicts++;
2599 if (status == GOT_STATUS_OBSTRUCTED)
2600 upa->obstructed++;
2601 if (status == GOT_STATUS_CANNOT_UPDATE)
2602 upa->not_updated++;
2604 while (path[0] == '/')
2605 path++;
2606 printf("%c %s\n", status, path);
2607 return NULL;
2610 static const struct got_error *
2611 switch_head_ref(struct got_reference *head_ref,
2612 struct got_object_id *commit_id, struct got_worktree *worktree,
2613 struct got_repository *repo)
2615 const struct got_error *err = NULL;
2616 char *base_id_str;
2617 int ref_has_moved = 0;
2619 /* Trivial case: switching between two different references. */
2620 if (strcmp(got_ref_get_name(head_ref),
2621 got_worktree_get_head_ref_name(worktree)) != 0) {
2622 printf("Switching work tree from %s to %s\n",
2623 got_worktree_get_head_ref_name(worktree),
2624 got_ref_get_name(head_ref));
2625 return got_worktree_set_head_ref(worktree, head_ref);
2628 err = check_linear_ancestry(commit_id,
2629 got_worktree_get_base_commit_id(worktree), 0, repo);
2630 if (err) {
2631 if (err->code != GOT_ERR_ANCESTRY)
2632 return err;
2633 ref_has_moved = 1;
2635 if (!ref_has_moved)
2636 return NULL;
2638 /* Switching to a rebased branch with the same reference name. */
2639 err = got_object_id_str(&base_id_str,
2640 got_worktree_get_base_commit_id(worktree));
2641 if (err)
2642 return err;
2643 printf("Reference %s now points at a different branch\n",
2644 got_worktree_get_head_ref_name(worktree));
2645 printf("Switching work tree from %s to %s\n", base_id_str,
2646 got_worktree_get_head_ref_name(worktree));
2647 return NULL;
2650 static const struct got_error *
2651 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2653 const struct got_error *err;
2654 int in_progress;
2656 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2657 if (err)
2658 return err;
2659 if (in_progress)
2660 return got_error(GOT_ERR_REBASING);
2662 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2663 if (err)
2664 return err;
2665 if (in_progress)
2666 return got_error(GOT_ERR_HISTEDIT_BUSY);
2668 return NULL;
2671 static const struct got_error *
2672 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2673 char *argv[], struct got_worktree *worktree)
2675 const struct got_error *err = NULL;
2676 char *path;
2677 int i;
2679 if (argc == 0) {
2680 path = strdup("");
2681 if (path == NULL)
2682 return got_error_from_errno("strdup");
2683 return got_pathlist_append(paths, path, NULL);
2686 for (i = 0; i < argc; i++) {
2687 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2688 if (err)
2689 break;
2690 err = got_pathlist_append(paths, path, NULL);
2691 if (err) {
2692 free(path);
2693 break;
2697 return err;
2700 static const struct got_error *
2701 wrap_not_worktree_error(const struct got_error *orig_err,
2702 const char *cmdname, const char *path)
2704 const struct got_error *err;
2705 struct got_repository *repo;
2706 static char msg[512];
2708 err = got_repo_open(&repo, path, NULL);
2709 if (err)
2710 return orig_err;
2712 snprintf(msg, sizeof(msg),
2713 "'got %s' needs a work tree in addition to a git repository\n"
2714 "Work trees can be checked out from this Git repository with "
2715 "'got checkout'.\n"
2716 "The got(1) manual page contains more information.", cmdname);
2717 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2718 got_repo_close(repo);
2719 return err;
2722 static const struct got_error *
2723 cmd_update(int argc, char *argv[])
2725 const struct got_error *error = NULL;
2726 struct got_repository *repo = NULL;
2727 struct got_worktree *worktree = NULL;
2728 char *worktree_path = NULL;
2729 struct got_object_id *commit_id = NULL;
2730 char *commit_id_str = NULL;
2731 const char *branch_name = NULL;
2732 struct got_reference *head_ref = NULL;
2733 struct got_pathlist_head paths;
2734 struct got_pathlist_entry *pe;
2735 int ch;
2736 struct got_update_progress_arg upa;
2738 TAILQ_INIT(&paths);
2740 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2741 switch (ch) {
2742 case 'b':
2743 branch_name = optarg;
2744 break;
2745 case 'c':
2746 commit_id_str = strdup(optarg);
2747 if (commit_id_str == NULL)
2748 return got_error_from_errno("strdup");
2749 break;
2750 default:
2751 usage_update();
2752 /* NOTREACHED */
2756 argc -= optind;
2757 argv += optind;
2759 #ifndef PROFILE
2760 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2761 "unveil", NULL) == -1)
2762 err(1, "pledge");
2763 #endif
2764 worktree_path = getcwd(NULL, 0);
2765 if (worktree_path == NULL) {
2766 error = got_error_from_errno("getcwd");
2767 goto done;
2769 error = got_worktree_open(&worktree, worktree_path);
2770 if (error) {
2771 if (error->code == GOT_ERR_NOT_WORKTREE)
2772 error = wrap_not_worktree_error(error, "update",
2773 worktree_path);
2774 goto done;
2777 error = check_rebase_or_histedit_in_progress(worktree);
2778 if (error)
2779 goto done;
2781 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2782 NULL);
2783 if (error != NULL)
2784 goto done;
2786 error = apply_unveil(got_repo_get_path(repo), 0,
2787 got_worktree_get_root_path(worktree));
2788 if (error)
2789 goto done;
2791 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2792 if (error)
2793 goto done;
2795 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2796 got_worktree_get_head_ref_name(worktree), 0);
2797 if (error != NULL)
2798 goto done;
2799 if (commit_id_str == NULL) {
2800 error = got_ref_resolve(&commit_id, repo, head_ref);
2801 if (error != NULL)
2802 goto done;
2803 error = got_object_id_str(&commit_id_str, commit_id);
2804 if (error != NULL)
2805 goto done;
2806 } else {
2807 error = got_repo_match_object_id(&commit_id, NULL,
2808 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2809 free(commit_id_str);
2810 commit_id_str = NULL;
2811 if (error)
2812 goto done;
2813 error = got_object_id_str(&commit_id_str, commit_id);
2814 if (error)
2815 goto done;
2818 if (branch_name) {
2819 struct got_object_id *head_commit_id;
2820 TAILQ_FOREACH(pe, &paths, entry) {
2821 if (pe->path_len == 0)
2822 continue;
2823 error = got_error_msg(GOT_ERR_BAD_PATH,
2824 "switching between branches requires that "
2825 "the entire work tree gets updated");
2826 goto done;
2828 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2829 if (error)
2830 goto done;
2831 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2832 repo);
2833 free(head_commit_id);
2834 if (error != NULL)
2835 goto done;
2836 error = check_same_branch(commit_id, head_ref, NULL, repo);
2837 if (error)
2838 goto done;
2839 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2840 if (error)
2841 goto done;
2842 } else {
2843 error = check_linear_ancestry(commit_id,
2844 got_worktree_get_base_commit_id(worktree), 0, repo);
2845 if (error != NULL) {
2846 if (error->code == GOT_ERR_ANCESTRY)
2847 error = got_error(GOT_ERR_BRANCH_MOVED);
2848 goto done;
2850 error = check_same_branch(commit_id, head_ref, NULL, repo);
2851 if (error)
2852 goto done;
2855 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2856 commit_id) != 0) {
2857 error = got_worktree_set_base_commit_id(worktree, repo,
2858 commit_id);
2859 if (error)
2860 goto done;
2863 memset(&upa, 0, sizeof(upa));
2864 error = got_worktree_checkout_files(worktree, &paths, repo,
2865 update_progress, &upa, check_cancelled, NULL);
2866 if (error != NULL)
2867 goto done;
2869 if (upa.did_something)
2870 printf("Updated to commit %s\n", commit_id_str);
2871 else
2872 printf("Already up-to-date\n");
2873 print_update_progress_stats(&upa);
2874 done:
2875 free(worktree_path);
2876 TAILQ_FOREACH(pe, &paths, entry)
2877 free((char *)pe->path);
2878 got_pathlist_free(&paths);
2879 free(commit_id);
2880 free(commit_id_str);
2881 return error;
2884 static const struct got_error *
2885 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2886 const char *path, int diff_context, int ignore_whitespace,
2887 struct got_repository *repo)
2889 const struct got_error *err = NULL;
2890 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2892 if (blob_id1) {
2893 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2894 if (err)
2895 goto done;
2898 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2899 if (err)
2900 goto done;
2902 while (path[0] == '/')
2903 path++;
2904 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2905 ignore_whitespace, stdout);
2906 done:
2907 if (blob1)
2908 got_object_blob_close(blob1);
2909 got_object_blob_close(blob2);
2910 return err;
2913 static const struct got_error *
2914 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2915 const char *path, int diff_context, int ignore_whitespace,
2916 struct got_repository *repo)
2918 const struct got_error *err = NULL;
2919 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2920 struct got_diff_blob_output_unidiff_arg arg;
2922 if (tree_id1) {
2923 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2924 if (err)
2925 goto done;
2928 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2929 if (err)
2930 goto done;
2932 arg.diff_context = diff_context;
2933 arg.ignore_whitespace = ignore_whitespace;
2934 arg.outfile = stdout;
2935 while (path[0] == '/')
2936 path++;
2937 err = got_diff_tree(tree1, tree2, path, path, repo,
2938 got_diff_blob_output_unidiff, &arg, 1);
2939 done:
2940 if (tree1)
2941 got_object_tree_close(tree1);
2942 if (tree2)
2943 got_object_tree_close(tree2);
2944 return err;
2947 static const struct got_error *
2948 get_changed_paths(struct got_pathlist_head *paths,
2949 struct got_commit_object *commit, struct got_repository *repo)
2951 const struct got_error *err = NULL;
2952 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
2953 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2954 struct got_object_qid *qid;
2956 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2957 if (qid != NULL) {
2958 struct got_commit_object *pcommit;
2959 err = got_object_open_as_commit(&pcommit, repo,
2960 qid->id);
2961 if (err)
2962 return err;
2964 tree_id1 = got_object_commit_get_tree_id(pcommit);
2965 got_object_commit_close(pcommit);
2969 if (tree_id1) {
2970 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2971 if (err)
2972 goto done;
2975 tree_id2 = got_object_commit_get_tree_id(commit);
2976 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2977 if (err)
2978 goto done;
2980 err = got_diff_tree(tree1, tree2, "", "", repo,
2981 got_diff_tree_collect_changed_paths, paths, 0);
2982 done:
2983 if (tree1)
2984 got_object_tree_close(tree1);
2985 if (tree2)
2986 got_object_tree_close(tree2);
2987 return err;
2990 static const struct got_error *
2991 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2992 const char *path, int diff_context, struct got_repository *repo)
2994 const struct got_error *err = NULL;
2995 struct got_commit_object *pcommit = NULL;
2996 char *id_str1 = NULL, *id_str2 = NULL;
2997 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2998 struct got_object_qid *qid;
3000 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3001 if (qid != NULL) {
3002 err = got_object_open_as_commit(&pcommit, repo,
3003 qid->id);
3004 if (err)
3005 return err;
3008 if (path && path[0] != '\0') {
3009 int obj_type;
3010 err = got_object_id_by_path(&obj_id2, repo, id, path);
3011 if (err)
3012 goto done;
3013 err = got_object_id_str(&id_str2, obj_id2);
3014 if (err) {
3015 free(obj_id2);
3016 goto done;
3018 if (pcommit) {
3019 err = got_object_id_by_path(&obj_id1, repo,
3020 qid->id, path);
3021 if (err) {
3022 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3023 free(obj_id2);
3024 goto done;
3026 } else {
3027 err = got_object_id_str(&id_str1, obj_id1);
3028 if (err) {
3029 free(obj_id2);
3030 goto done;
3034 err = got_object_get_type(&obj_type, repo, obj_id2);
3035 if (err) {
3036 free(obj_id2);
3037 goto done;
3039 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3040 switch (obj_type) {
3041 case GOT_OBJ_TYPE_BLOB:
3042 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3043 0, repo);
3044 break;
3045 case GOT_OBJ_TYPE_TREE:
3046 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3047 0, repo);
3048 break;
3049 default:
3050 err = got_error(GOT_ERR_OBJ_TYPE);
3051 break;
3053 free(obj_id1);
3054 free(obj_id2);
3055 } else {
3056 obj_id2 = got_object_commit_get_tree_id(commit);
3057 err = got_object_id_str(&id_str2, obj_id2);
3058 if (err)
3059 goto done;
3060 obj_id1 = got_object_commit_get_tree_id(pcommit);
3061 err = got_object_id_str(&id_str1, obj_id1);
3062 if (err)
3063 goto done;
3064 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3065 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3067 done:
3068 free(id_str1);
3069 free(id_str2);
3070 if (pcommit)
3071 got_object_commit_close(pcommit);
3072 return err;
3075 static char *
3076 get_datestr(time_t *time, char *datebuf)
3078 struct tm mytm, *tm;
3079 char *p, *s;
3081 tm = gmtime_r(time, &mytm);
3082 if (tm == NULL)
3083 return NULL;
3084 s = asctime_r(tm, datebuf);
3085 if (s == NULL)
3086 return NULL;
3087 p = strchr(s, '\n');
3088 if (p)
3089 *p = '\0';
3090 return s;
3093 static const struct got_error *
3094 match_logmsg(int *have_match, struct got_object_id *id,
3095 struct got_commit_object *commit, regex_t *regex)
3097 const struct got_error *err = NULL;
3098 regmatch_t regmatch;
3099 char *id_str = NULL, *logmsg = NULL;
3101 *have_match = 0;
3103 err = got_object_id_str(&id_str, id);
3104 if (err)
3105 return err;
3107 err = got_object_commit_get_logmsg(&logmsg, commit);
3108 if (err)
3109 goto done;
3111 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3112 *have_match = 1;
3113 done:
3114 free(id_str);
3115 free(logmsg);
3116 return err;
3119 static void
3120 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3121 regex_t *regex)
3123 regmatch_t regmatch;
3124 struct got_pathlist_entry *pe;
3126 *have_match = 0;
3128 TAILQ_FOREACH(pe, changed_paths, entry) {
3129 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3130 *have_match = 1;
3131 break;
3136 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3138 static const struct got_error *
3139 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3140 struct got_repository *repo, const char *path,
3141 struct got_pathlist_head *changed_paths, int show_patch,
3142 int diff_context, struct got_reflist_head *refs)
3144 const struct got_error *err = NULL;
3145 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3146 char datebuf[26];
3147 time_t committer_time;
3148 const char *author, *committer;
3149 char *refs_str = NULL;
3150 struct got_reflist_entry *re;
3152 SIMPLEQ_FOREACH(re, refs, entry) {
3153 char *s;
3154 const char *name;
3155 struct got_tag_object *tag = NULL;
3156 int cmp;
3158 name = got_ref_get_name(re->ref);
3159 if (strcmp(name, GOT_REF_HEAD) == 0)
3160 continue;
3161 if (strncmp(name, "refs/", 5) == 0)
3162 name += 5;
3163 if (strncmp(name, "got/", 4) == 0)
3164 continue;
3165 if (strncmp(name, "heads/", 6) == 0)
3166 name += 6;
3167 if (strncmp(name, "remotes/", 8) == 0) {
3168 name += 8;
3169 s = strstr(name, "/" GOT_REF_HEAD);
3170 if (s != NULL && s[strlen(s)] == '\0')
3171 continue;
3173 if (strncmp(name, "tags/", 5) == 0) {
3174 err = got_object_open_as_tag(&tag, repo, re->id);
3175 if (err) {
3176 if (err->code != GOT_ERR_OBJ_TYPE)
3177 return err;
3178 /* Ref points at something other than a tag. */
3179 err = NULL;
3180 tag = NULL;
3183 cmp = got_object_id_cmp(tag ?
3184 got_object_tag_get_object_id(tag) : re->id, id);
3185 if (tag)
3186 got_object_tag_close(tag);
3187 if (cmp != 0)
3188 continue;
3189 s = refs_str;
3190 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3191 name) == -1) {
3192 err = got_error_from_errno("asprintf");
3193 free(s);
3194 return err;
3196 free(s);
3198 err = got_object_id_str(&id_str, id);
3199 if (err)
3200 return err;
3202 printf(GOT_COMMIT_SEP_STR);
3203 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3204 refs_str ? refs_str : "", refs_str ? ")" : "");
3205 free(id_str);
3206 id_str = NULL;
3207 free(refs_str);
3208 refs_str = NULL;
3209 printf("from: %s\n", got_object_commit_get_author(commit));
3210 committer_time = got_object_commit_get_committer_time(commit);
3211 datestr = get_datestr(&committer_time, datebuf);
3212 if (datestr)
3213 printf("date: %s UTC\n", datestr);
3214 author = got_object_commit_get_author(commit);
3215 committer = got_object_commit_get_committer(commit);
3216 if (strcmp(author, committer) != 0)
3217 printf("via: %s\n", committer);
3218 if (got_object_commit_get_nparents(commit) > 1) {
3219 const struct got_object_id_queue *parent_ids;
3220 struct got_object_qid *qid;
3221 int n = 1;
3222 parent_ids = got_object_commit_get_parent_ids(commit);
3223 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3224 err = got_object_id_str(&id_str, qid->id);
3225 if (err)
3226 return err;
3227 printf("parent %d: %s\n", n++, id_str);
3228 free(id_str);
3232 err = got_object_commit_get_logmsg(&logmsg0, commit);
3233 if (err)
3234 return err;
3236 logmsg = logmsg0;
3237 do {
3238 line = strsep(&logmsg, "\n");
3239 if (line)
3240 printf(" %s\n", line);
3241 } while (line);
3242 free(logmsg0);
3244 if (changed_paths) {
3245 struct got_pathlist_entry *pe;
3246 TAILQ_FOREACH(pe, changed_paths, entry) {
3247 struct got_diff_changed_path *cp = pe->data;
3248 printf(" %c %s\n", cp->status, pe->path);
3250 printf("\n");
3252 if (show_patch) {
3253 err = print_patch(commit, id, path, diff_context, repo);
3254 if (err == 0)
3255 printf("\n");
3258 if (fflush(stdout) != 0 && err == NULL)
3259 err = got_error_from_errno("fflush");
3260 return err;
3263 static const struct got_error *
3264 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3265 struct got_repository *repo, const char *path, int show_changed_paths,
3266 int show_patch, const char *search_pattern, int diff_context, int limit,
3267 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3269 const struct got_error *err;
3270 struct got_commit_graph *graph;
3271 regex_t regex;
3272 int have_match;
3273 struct got_object_id_queue reversed_commits;
3274 struct got_object_qid *qid;
3275 struct got_commit_object *commit;
3276 struct got_pathlist_head changed_paths;
3277 struct got_pathlist_entry *pe;
3279 SIMPLEQ_INIT(&reversed_commits);
3280 TAILQ_INIT(&changed_paths);
3282 if (search_pattern && regcomp(&regex, search_pattern,
3283 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3284 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3286 err = got_commit_graph_open(&graph, path, !log_branches);
3287 if (err)
3288 return err;
3289 err = got_commit_graph_iter_start(graph, root_id, repo,
3290 check_cancelled, NULL);
3291 if (err)
3292 goto done;
3293 for (;;) {
3294 struct got_object_id *id;
3296 if (sigint_received || sigpipe_received)
3297 break;
3299 err = got_commit_graph_iter_next(&id, graph, repo,
3300 check_cancelled, NULL);
3301 if (err) {
3302 if (err->code == GOT_ERR_ITER_COMPLETED)
3303 err = NULL;
3304 break;
3306 if (id == NULL)
3307 break;
3309 err = got_object_open_as_commit(&commit, repo, id);
3310 if (err)
3311 break;
3313 if (show_changed_paths && !reverse_display_order) {
3314 err = get_changed_paths(&changed_paths, commit, repo);
3315 if (err)
3316 break;
3319 if (search_pattern) {
3320 err = match_logmsg(&have_match, id, commit, &regex);
3321 if (err) {
3322 got_object_commit_close(commit);
3323 break;
3325 if (have_match == 0 && show_changed_paths)
3326 match_changed_paths(&have_match,
3327 &changed_paths, &regex);
3328 if (have_match == 0) {
3329 got_object_commit_close(commit);
3330 TAILQ_FOREACH(pe, &changed_paths, entry) {
3331 free((char *)pe->path);
3332 free(pe->data);
3334 got_pathlist_free(&changed_paths);
3335 continue;
3339 if (reverse_display_order) {
3340 err = got_object_qid_alloc(&qid, id);
3341 if (err)
3342 break;
3343 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3344 got_object_commit_close(commit);
3345 } else {
3346 err = print_commit(commit, id, repo, path,
3347 show_changed_paths ? &changed_paths : NULL,
3348 show_patch, diff_context, refs);
3349 got_object_commit_close(commit);
3350 if (err)
3351 break;
3353 if ((limit && --limit == 0) ||
3354 (end_id && got_object_id_cmp(id, end_id) == 0))
3355 break;
3357 TAILQ_FOREACH(pe, &changed_paths, entry) {
3358 free((char *)pe->path);
3359 free(pe->data);
3361 got_pathlist_free(&changed_paths);
3363 if (reverse_display_order) {
3364 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3365 err = got_object_open_as_commit(&commit, repo, qid->id);
3366 if (err)
3367 break;
3368 if (show_changed_paths) {
3369 err = get_changed_paths(&changed_paths,
3370 commit, repo);
3371 if (err)
3372 break;
3374 err = print_commit(commit, qid->id, repo, path,
3375 show_changed_paths ? &changed_paths : NULL,
3376 show_patch, diff_context, refs);
3377 got_object_commit_close(commit);
3378 if (err)
3379 break;
3380 TAILQ_FOREACH(pe, &changed_paths, entry) {
3381 free((char *)pe->path);
3382 free(pe->data);
3384 got_pathlist_free(&changed_paths);
3387 done:
3388 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3389 qid = SIMPLEQ_FIRST(&reversed_commits);
3390 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3391 got_object_qid_free(qid);
3393 TAILQ_FOREACH(pe, &changed_paths, entry) {
3394 free((char *)pe->path);
3395 free(pe->data);
3397 got_pathlist_free(&changed_paths);
3398 if (search_pattern)
3399 regfree(&regex);
3400 got_commit_graph_close(graph);
3401 return err;
3404 __dead static void
3405 usage_log(void)
3407 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3408 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3409 "[-R] [path]\n", getprogname());
3410 exit(1);
3413 static int
3414 get_default_log_limit(void)
3416 const char *got_default_log_limit;
3417 long long n;
3418 const char *errstr;
3420 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3421 if (got_default_log_limit == NULL)
3422 return 0;
3423 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3424 if (errstr != NULL)
3425 return 0;
3426 return n;
3429 static const struct got_error *
3430 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3431 struct got_repository *repo)
3433 const struct got_error *err = NULL;
3434 struct got_reference *ref;
3436 *id = NULL;
3438 err = got_ref_open(&ref, repo, commit_arg, 0);
3439 if (err == NULL) {
3440 int obj_type;
3441 err = got_ref_resolve(id, repo, ref);
3442 got_ref_close(ref);
3443 if (err)
3444 return err;
3445 err = got_object_get_type(&obj_type, repo, *id);
3446 if (err)
3447 return err;
3448 if (obj_type == GOT_OBJ_TYPE_TAG) {
3449 struct got_tag_object *tag;
3450 err = got_object_open_as_tag(&tag, repo, *id);
3451 if (err)
3452 return err;
3453 if (got_object_tag_get_object_type(tag) !=
3454 GOT_OBJ_TYPE_COMMIT) {
3455 got_object_tag_close(tag);
3456 return got_error(GOT_ERR_OBJ_TYPE);
3458 free(*id);
3459 *id = got_object_id_dup(
3460 got_object_tag_get_object_id(tag));
3461 if (*id == NULL)
3462 err = got_error_from_errno(
3463 "got_object_id_dup");
3464 got_object_tag_close(tag);
3465 if (err)
3466 return err;
3467 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3468 return got_error(GOT_ERR_OBJ_TYPE);
3469 } else {
3470 err = got_repo_match_object_id_prefix(id, commit_arg,
3471 GOT_OBJ_TYPE_COMMIT, repo);
3474 return err;
3477 static const struct got_error *
3478 cmd_log(int argc, char *argv[])
3480 const struct got_error *error;
3481 struct got_repository *repo = NULL;
3482 struct got_worktree *worktree = NULL;
3483 struct got_object_id *start_id = NULL, *end_id = NULL;
3484 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3485 const char *start_commit = NULL, *end_commit = NULL;
3486 const char *search_pattern = NULL;
3487 int diff_context = -1, ch;
3488 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3489 int reverse_display_order = 0;
3490 const char *errstr;
3491 struct got_reflist_head refs;
3493 SIMPLEQ_INIT(&refs);
3495 #ifndef PROFILE
3496 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3497 NULL)
3498 == -1)
3499 err(1, "pledge");
3500 #endif
3502 limit = get_default_log_limit();
3504 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3505 switch (ch) {
3506 case 'p':
3507 show_patch = 1;
3508 break;
3509 case 'P':
3510 show_changed_paths = 1;
3511 break;
3512 case 'c':
3513 start_commit = optarg;
3514 break;
3515 case 'C':
3516 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3517 &errstr);
3518 if (errstr != NULL)
3519 err(1, "-C option %s", errstr);
3520 break;
3521 case 'l':
3522 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3523 if (errstr != NULL)
3524 err(1, "-l option %s", errstr);
3525 break;
3526 case 'b':
3527 log_branches = 1;
3528 break;
3529 case 'r':
3530 repo_path = realpath(optarg, NULL);
3531 if (repo_path == NULL)
3532 return got_error_from_errno2("realpath",
3533 optarg);
3534 got_path_strip_trailing_slashes(repo_path);
3535 break;
3536 case 'R':
3537 reverse_display_order = 1;
3538 break;
3539 case 's':
3540 search_pattern = optarg;
3541 break;
3542 case 'x':
3543 end_commit = optarg;
3544 break;
3545 default:
3546 usage_log();
3547 /* NOTREACHED */
3551 argc -= optind;
3552 argv += optind;
3554 if (diff_context == -1)
3555 diff_context = 3;
3556 else if (!show_patch)
3557 errx(1, "-C reguires -p");
3559 cwd = getcwd(NULL, 0);
3560 if (cwd == NULL) {
3561 error = got_error_from_errno("getcwd");
3562 goto done;
3565 if (repo_path == NULL) {
3566 error = got_worktree_open(&worktree, cwd);
3567 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3568 goto done;
3569 error = NULL;
3572 if (argc == 0) {
3573 path = strdup("");
3574 if (path == NULL) {
3575 error = got_error_from_errno("strdup");
3576 goto done;
3578 } else if (argc == 1) {
3579 if (worktree) {
3580 error = got_worktree_resolve_path(&path, worktree,
3581 argv[0]);
3582 if (error)
3583 goto done;
3584 } else {
3585 path = strdup(argv[0]);
3586 if (path == NULL) {
3587 error = got_error_from_errno("strdup");
3588 goto done;
3591 } else
3592 usage_log();
3594 if (repo_path == NULL) {
3595 repo_path = worktree ?
3596 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3598 if (repo_path == NULL) {
3599 error = got_error_from_errno("strdup");
3600 goto done;
3603 error = got_repo_open(&repo, repo_path, NULL);
3604 if (error != NULL)
3605 goto done;
3607 error = apply_unveil(got_repo_get_path(repo), 1,
3608 worktree ? got_worktree_get_root_path(worktree) : NULL);
3609 if (error)
3610 goto done;
3612 if (start_commit == NULL) {
3613 struct got_reference *head_ref;
3614 struct got_commit_object *commit = NULL;
3615 error = got_ref_open(&head_ref, repo,
3616 worktree ? got_worktree_get_head_ref_name(worktree)
3617 : GOT_REF_HEAD, 0);
3618 if (error != NULL)
3619 goto done;
3620 error = got_ref_resolve(&start_id, repo, head_ref);
3621 got_ref_close(head_ref);
3622 if (error != NULL)
3623 goto done;
3624 error = got_object_open_as_commit(&commit, repo,
3625 start_id);
3626 if (error != NULL)
3627 goto done;
3628 got_object_commit_close(commit);
3629 } else {
3630 error = resolve_commit_arg(&start_id, start_commit, repo);
3631 if (error != NULL)
3632 goto done;
3634 if (end_commit != NULL) {
3635 error = resolve_commit_arg(&end_id, end_commit, repo);
3636 if (error != NULL)
3637 goto done;
3640 if (worktree) {
3641 const char *prefix = got_worktree_get_path_prefix(worktree);
3642 char *p;
3643 if (asprintf(&p, "%s%s%s", prefix,
3644 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3645 error = got_error_from_errno("asprintf");
3646 goto done;
3648 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3649 free(p);
3650 } else
3651 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3652 if (error != NULL)
3653 goto done;
3654 if (in_repo_path) {
3655 free(path);
3656 path = in_repo_path;
3659 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3660 if (error)
3661 goto done;
3663 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3664 show_patch, search_pattern, diff_context, limit, log_branches,
3665 reverse_display_order, &refs);
3666 done:
3667 free(path);
3668 free(repo_path);
3669 free(cwd);
3670 if (worktree)
3671 got_worktree_close(worktree);
3672 if (repo) {
3673 const struct got_error *repo_error;
3674 repo_error = got_repo_close(repo);
3675 if (error == NULL)
3676 error = repo_error;
3678 got_ref_list_free(&refs);
3679 return error;
3682 __dead static void
3683 usage_diff(void)
3685 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3686 "[-w] [object1 object2 | path]\n", getprogname());
3687 exit(1);
3690 struct print_diff_arg {
3691 struct got_repository *repo;
3692 struct got_worktree *worktree;
3693 int diff_context;
3694 const char *id_str;
3695 int header_shown;
3696 int diff_staged;
3697 int ignore_whitespace;
3701 * Create a file which contains the target path of a symlink so we can feed
3702 * it as content to the diff engine.
3704 static const struct got_error *
3705 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3706 const char *abspath)
3708 const struct got_error *err = NULL;
3709 char target_path[PATH_MAX];
3710 ssize_t target_len, outlen;
3712 *fd = -1;
3714 if (dirfd != -1) {
3715 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3716 if (target_len == -1)
3717 return got_error_from_errno2("readlinkat", abspath);
3718 } else {
3719 target_len = readlink(abspath, target_path, PATH_MAX);
3720 if (target_len == -1)
3721 return got_error_from_errno2("readlink", abspath);
3724 *fd = got_opentempfd();
3725 if (*fd == -1)
3726 return got_error_from_errno("got_opentempfd");
3728 outlen = write(*fd, target_path, target_len);
3729 if (outlen == -1) {
3730 err = got_error_from_errno("got_opentempfd");
3731 goto done;
3734 if (lseek(*fd, 0, SEEK_SET) == -1) {
3735 err = got_error_from_errno2("lseek", abspath);
3736 goto done;
3738 done:
3739 if (err) {
3740 close(*fd);
3741 *fd = -1;
3743 return err;
3746 static const struct got_error *
3747 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3748 const char *path, struct got_object_id *blob_id,
3749 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3750 int dirfd, const char *de_name)
3752 struct print_diff_arg *a = arg;
3753 const struct got_error *err = NULL;
3754 struct got_blob_object *blob1 = NULL;
3755 int fd = -1;
3756 FILE *f2 = NULL;
3757 char *abspath = NULL, *label1 = NULL;
3758 struct stat sb;
3760 if (a->diff_staged) {
3761 if (staged_status != GOT_STATUS_MODIFY &&
3762 staged_status != GOT_STATUS_ADD &&
3763 staged_status != GOT_STATUS_DELETE)
3764 return NULL;
3765 } else {
3766 if (staged_status == GOT_STATUS_DELETE)
3767 return NULL;
3768 if (status == GOT_STATUS_NONEXISTENT)
3769 return got_error_set_errno(ENOENT, path);
3770 if (status != GOT_STATUS_MODIFY &&
3771 status != GOT_STATUS_ADD &&
3772 status != GOT_STATUS_DELETE &&
3773 status != GOT_STATUS_CONFLICT)
3774 return NULL;
3777 if (!a->header_shown) {
3778 printf("diff %s %s%s\n", a->id_str,
3779 got_worktree_get_root_path(a->worktree),
3780 a->diff_staged ? " (staged changes)" : "");
3781 a->header_shown = 1;
3784 if (a->diff_staged) {
3785 const char *label1 = NULL, *label2 = NULL;
3786 switch (staged_status) {
3787 case GOT_STATUS_MODIFY:
3788 label1 = path;
3789 label2 = path;
3790 break;
3791 case GOT_STATUS_ADD:
3792 label2 = path;
3793 break;
3794 case GOT_STATUS_DELETE:
3795 label1 = path;
3796 break;
3797 default:
3798 return got_error(GOT_ERR_FILE_STATUS);
3800 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3801 label1, label2, a->diff_context, a->ignore_whitespace,
3802 a->repo, stdout);
3805 if (staged_status == GOT_STATUS_ADD ||
3806 staged_status == GOT_STATUS_MODIFY) {
3807 char *id_str;
3808 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3809 8192);
3810 if (err)
3811 goto done;
3812 err = got_object_id_str(&id_str, staged_blob_id);
3813 if (err)
3814 goto done;
3815 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3816 err = got_error_from_errno("asprintf");
3817 free(id_str);
3818 goto done;
3820 free(id_str);
3821 } else if (status != GOT_STATUS_ADD) {
3822 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3823 if (err)
3824 goto done;
3827 if (status != GOT_STATUS_DELETE) {
3828 if (asprintf(&abspath, "%s/%s",
3829 got_worktree_get_root_path(a->worktree), path) == -1) {
3830 err = got_error_from_errno("asprintf");
3831 goto done;
3834 if (dirfd != -1) {
3835 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3836 if (fd == -1) {
3837 if (errno != ELOOP) {
3838 err = got_error_from_errno2("openat",
3839 abspath);
3840 goto done;
3842 err = get_symlink_target_file(&fd, dirfd,
3843 de_name, abspath);
3844 if (err)
3845 goto done;
3847 } else {
3848 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3849 if (fd == -1) {
3850 if (errno != ELOOP) {
3851 err = got_error_from_errno2("open",
3852 abspath);
3853 goto done;
3855 err = get_symlink_target_file(&fd, dirfd,
3856 de_name, abspath);
3857 if (err)
3858 goto done;
3861 if (fstat(fd, &sb) == -1) {
3862 err = got_error_from_errno2("fstat", abspath);
3863 goto done;
3865 f2 = fdopen(fd, "r");
3866 if (f2 == NULL) {
3867 err = got_error_from_errno2("fdopen", abspath);
3868 goto done;
3870 fd = -1;
3871 } else
3872 sb.st_size = 0;
3874 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3875 a->diff_context, a->ignore_whitespace, stdout);
3876 done:
3877 if (blob1)
3878 got_object_blob_close(blob1);
3879 if (f2 && fclose(f2) == EOF && err == NULL)
3880 err = got_error_from_errno("fclose");
3881 if (fd != -1 && close(fd) == -1 && err == NULL)
3882 err = got_error_from_errno("close");
3883 free(abspath);
3884 return err;
3887 static const struct got_error *
3888 cmd_diff(int argc, char *argv[])
3890 const struct got_error *error;
3891 struct got_repository *repo = NULL;
3892 struct got_worktree *worktree = NULL;
3893 char *cwd = NULL, *repo_path = NULL;
3894 struct got_object_id *id1 = NULL, *id2 = NULL;
3895 const char *id_str1 = NULL, *id_str2 = NULL;
3896 char *label1 = NULL, *label2 = NULL;
3897 int type1, type2;
3898 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3899 const char *errstr;
3900 char *path = NULL;
3902 #ifndef PROFILE
3903 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3904 NULL) == -1)
3905 err(1, "pledge");
3906 #endif
3908 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3909 switch (ch) {
3910 case 'C':
3911 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3912 &errstr);
3913 if (errstr != NULL)
3914 err(1, "-C option %s", errstr);
3915 break;
3916 case 'r':
3917 repo_path = realpath(optarg, NULL);
3918 if (repo_path == NULL)
3919 return got_error_from_errno2("realpath",
3920 optarg);
3921 got_path_strip_trailing_slashes(repo_path);
3922 break;
3923 case 's':
3924 diff_staged = 1;
3925 break;
3926 case 'w':
3927 ignore_whitespace = 1;
3928 break;
3929 default:
3930 usage_diff();
3931 /* NOTREACHED */
3935 argc -= optind;
3936 argv += optind;
3938 cwd = getcwd(NULL, 0);
3939 if (cwd == NULL) {
3940 error = got_error_from_errno("getcwd");
3941 goto done;
3943 if (argc <= 1) {
3944 if (repo_path)
3945 errx(1,
3946 "-r option can't be used when diffing a work tree");
3947 error = got_worktree_open(&worktree, cwd);
3948 if (error) {
3949 if (error->code == GOT_ERR_NOT_WORKTREE)
3950 error = wrap_not_worktree_error(error, "diff",
3951 cwd);
3952 goto done;
3954 repo_path = strdup(got_worktree_get_repo_path(worktree));
3955 if (repo_path == NULL) {
3956 error = got_error_from_errno("strdup");
3957 goto done;
3959 if (argc == 1) {
3960 error = got_worktree_resolve_path(&path, worktree,
3961 argv[0]);
3962 if (error)
3963 goto done;
3964 } else {
3965 path = strdup("");
3966 if (path == NULL) {
3967 error = got_error_from_errno("strdup");
3968 goto done;
3971 } else if (argc == 2) {
3972 if (diff_staged)
3973 errx(1, "-s option can't be used when diffing "
3974 "objects in repository");
3975 id_str1 = argv[0];
3976 id_str2 = argv[1];
3977 if (repo_path == NULL) {
3978 error = got_worktree_open(&worktree, cwd);
3979 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3980 goto done;
3981 if (worktree) {
3982 repo_path = strdup(
3983 got_worktree_get_repo_path(worktree));
3984 if (repo_path == NULL) {
3985 error = got_error_from_errno("strdup");
3986 goto done;
3988 } else {
3989 repo_path = strdup(cwd);
3990 if (repo_path == NULL) {
3991 error = got_error_from_errno("strdup");
3992 goto done;
3996 } else
3997 usage_diff();
3999 error = got_repo_open(&repo, repo_path, NULL);
4000 free(repo_path);
4001 if (error != NULL)
4002 goto done;
4004 error = apply_unveil(got_repo_get_path(repo), 1,
4005 worktree ? got_worktree_get_root_path(worktree) : NULL);
4006 if (error)
4007 goto done;
4009 if (argc <= 1) {
4010 struct print_diff_arg arg;
4011 struct got_pathlist_head paths;
4012 char *id_str;
4014 TAILQ_INIT(&paths);
4016 error = got_object_id_str(&id_str,
4017 got_worktree_get_base_commit_id(worktree));
4018 if (error)
4019 goto done;
4020 arg.repo = repo;
4021 arg.worktree = worktree;
4022 arg.diff_context = diff_context;
4023 arg.id_str = id_str;
4024 arg.header_shown = 0;
4025 arg.diff_staged = diff_staged;
4026 arg.ignore_whitespace = ignore_whitespace;
4028 error = got_pathlist_append(&paths, path, NULL);
4029 if (error)
4030 goto done;
4032 error = got_worktree_status(worktree, &paths, repo, print_diff,
4033 &arg, check_cancelled, NULL);
4034 free(id_str);
4035 got_pathlist_free(&paths);
4036 goto done;
4039 error = got_repo_match_object_id(&id1, &label1, id_str1,
4040 GOT_OBJ_TYPE_ANY, 1, repo);
4041 if (error)
4042 goto done;
4044 error = got_repo_match_object_id(&id2, &label2, id_str2,
4045 GOT_OBJ_TYPE_ANY, 1, repo);
4046 if (error)
4047 goto done;
4049 error = got_object_get_type(&type1, repo, id1);
4050 if (error)
4051 goto done;
4053 error = got_object_get_type(&type2, repo, id2);
4054 if (error)
4055 goto done;
4057 if (type1 != type2) {
4058 error = got_error(GOT_ERR_OBJ_TYPE);
4059 goto done;
4062 switch (type1) {
4063 case GOT_OBJ_TYPE_BLOB:
4064 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4065 diff_context, ignore_whitespace, repo, stdout);
4066 break;
4067 case GOT_OBJ_TYPE_TREE:
4068 error = got_diff_objects_as_trees(id1, id2, "", "",
4069 diff_context, ignore_whitespace, repo, stdout);
4070 break;
4071 case GOT_OBJ_TYPE_COMMIT:
4072 printf("diff %s %s\n", label1, label2);
4073 error = got_diff_objects_as_commits(id1, id2, diff_context,
4074 ignore_whitespace, repo, stdout);
4075 break;
4076 default:
4077 error = got_error(GOT_ERR_OBJ_TYPE);
4079 done:
4080 free(label1);
4081 free(label2);
4082 free(id1);
4083 free(id2);
4084 free(path);
4085 if (worktree)
4086 got_worktree_close(worktree);
4087 if (repo) {
4088 const struct got_error *repo_error;
4089 repo_error = got_repo_close(repo);
4090 if (error == NULL)
4091 error = repo_error;
4093 return error;
4096 __dead static void
4097 usage_blame(void)
4099 fprintf(stderr,
4100 "usage: %s blame [-c commit] [-r repository-path] path\n",
4101 getprogname());
4102 exit(1);
4105 struct blame_line {
4106 int annotated;
4107 char *id_str;
4108 char *committer;
4109 char datebuf[11]; /* YYYY-MM-DD + NUL */
4112 struct blame_cb_args {
4113 struct blame_line *lines;
4114 int nlines;
4115 int nlines_prec;
4116 int lineno_cur;
4117 off_t *line_offsets;
4118 FILE *f;
4119 struct got_repository *repo;
4122 static const struct got_error *
4123 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4125 const struct got_error *err = NULL;
4126 struct blame_cb_args *a = arg;
4127 struct blame_line *bline;
4128 char *line = NULL;
4129 size_t linesize = 0;
4130 struct got_commit_object *commit = NULL;
4131 off_t offset;
4132 struct tm tm;
4133 time_t committer_time;
4135 if (nlines != a->nlines ||
4136 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4137 return got_error(GOT_ERR_RANGE);
4139 if (sigint_received)
4140 return got_error(GOT_ERR_ITER_COMPLETED);
4142 if (lineno == -1)
4143 return NULL; /* no change in this commit */
4145 /* Annotate this line. */
4146 bline = &a->lines[lineno - 1];
4147 if (bline->annotated)
4148 return NULL;
4149 err = got_object_id_str(&bline->id_str, id);
4150 if (err)
4151 return err;
4153 err = got_object_open_as_commit(&commit, a->repo, id);
4154 if (err)
4155 goto done;
4157 bline->committer = strdup(got_object_commit_get_committer(commit));
4158 if (bline->committer == NULL) {
4159 err = got_error_from_errno("strdup");
4160 goto done;
4163 committer_time = got_object_commit_get_committer_time(commit);
4164 if (localtime_r(&committer_time, &tm) == NULL)
4165 return got_error_from_errno("localtime_r");
4166 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4167 &tm) >= sizeof(bline->datebuf)) {
4168 err = got_error(GOT_ERR_NO_SPACE);
4169 goto done;
4171 bline->annotated = 1;
4173 /* Print lines annotated so far. */
4174 bline = &a->lines[a->lineno_cur - 1];
4175 if (!bline->annotated)
4176 goto done;
4178 offset = a->line_offsets[a->lineno_cur - 1];
4179 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4180 err = got_error_from_errno("fseeko");
4181 goto done;
4184 while (bline->annotated) {
4185 char *smallerthan, *at, *nl, *committer;
4186 size_t len;
4188 if (getline(&line, &linesize, a->f) == -1) {
4189 if (ferror(a->f))
4190 err = got_error_from_errno("getline");
4191 break;
4194 committer = bline->committer;
4195 smallerthan = strchr(committer, '<');
4196 if (smallerthan && smallerthan[1] != '\0')
4197 committer = smallerthan + 1;
4198 at = strchr(committer, '@');
4199 if (at)
4200 *at = '\0';
4201 len = strlen(committer);
4202 if (len >= 9)
4203 committer[8] = '\0';
4205 nl = strchr(line, '\n');
4206 if (nl)
4207 *nl = '\0';
4208 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4209 bline->id_str, bline->datebuf, committer, line);
4211 a->lineno_cur++;
4212 bline = &a->lines[a->lineno_cur - 1];
4214 done:
4215 if (commit)
4216 got_object_commit_close(commit);
4217 free(line);
4218 return err;
4221 static const struct got_error *
4222 cmd_blame(int argc, char *argv[])
4224 const struct got_error *error;
4225 struct got_repository *repo = NULL;
4226 struct got_worktree *worktree = NULL;
4227 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4228 char *link_target = NULL;
4229 struct got_object_id *obj_id = NULL;
4230 struct got_object_id *commit_id = NULL;
4231 struct got_blob_object *blob = NULL;
4232 char *commit_id_str = NULL;
4233 struct blame_cb_args bca;
4234 int ch, obj_type, i;
4235 size_t filesize;
4237 memset(&bca, 0, sizeof(bca));
4239 #ifndef PROFILE
4240 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4241 NULL) == -1)
4242 err(1, "pledge");
4243 #endif
4245 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4246 switch (ch) {
4247 case 'c':
4248 commit_id_str = optarg;
4249 break;
4250 case 'r':
4251 repo_path = realpath(optarg, NULL);
4252 if (repo_path == NULL)
4253 return got_error_from_errno2("realpath",
4254 optarg);
4255 got_path_strip_trailing_slashes(repo_path);
4256 break;
4257 default:
4258 usage_blame();
4259 /* NOTREACHED */
4263 argc -= optind;
4264 argv += optind;
4266 if (argc == 1)
4267 path = argv[0];
4268 else
4269 usage_blame();
4271 cwd = getcwd(NULL, 0);
4272 if (cwd == NULL) {
4273 error = got_error_from_errno("getcwd");
4274 goto done;
4276 if (repo_path == NULL) {
4277 error = got_worktree_open(&worktree, cwd);
4278 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4279 goto done;
4280 else
4281 error = NULL;
4282 if (worktree) {
4283 repo_path =
4284 strdup(got_worktree_get_repo_path(worktree));
4285 if (repo_path == NULL) {
4286 error = got_error_from_errno("strdup");
4287 if (error)
4288 goto done;
4290 } else {
4291 repo_path = strdup(cwd);
4292 if (repo_path == NULL) {
4293 error = got_error_from_errno("strdup");
4294 goto done;
4299 error = got_repo_open(&repo, repo_path, NULL);
4300 if (error != NULL)
4301 goto done;
4303 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4304 if (error)
4305 goto done;
4307 if (worktree) {
4308 const char *prefix = got_worktree_get_path_prefix(worktree);
4309 char *p, *worktree_subdir = cwd +
4310 strlen(got_worktree_get_root_path(worktree));
4311 if (asprintf(&p, "%s%s%s%s%s",
4312 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4313 worktree_subdir, worktree_subdir[0] ? "/" : "",
4314 path) == -1) {
4315 error = got_error_from_errno("asprintf");
4316 goto done;
4318 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4319 free(p);
4320 } else {
4321 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4323 if (error)
4324 goto done;
4326 if (commit_id_str == NULL) {
4327 struct got_reference *head_ref;
4328 error = got_ref_open(&head_ref, repo, worktree ?
4329 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4330 if (error != NULL)
4331 goto done;
4332 error = got_ref_resolve(&commit_id, repo, head_ref);
4333 got_ref_close(head_ref);
4334 if (error != NULL)
4335 goto done;
4336 } else {
4337 error = got_repo_match_object_id(&commit_id, NULL,
4338 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4339 if (error)
4340 goto done;
4343 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4344 commit_id, repo);
4345 if (error)
4346 goto done;
4348 error = got_object_id_by_path(&obj_id, repo, commit_id,
4349 link_target ? link_target : in_repo_path);
4350 if (error)
4351 goto done;
4353 error = got_object_get_type(&obj_type, repo, obj_id);
4354 if (error)
4355 goto done;
4357 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4358 error = got_error_path(link_target ? link_target : in_repo_path,
4359 GOT_ERR_OBJ_TYPE);
4360 goto done;
4363 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4364 if (error)
4365 goto done;
4366 bca.f = got_opentemp();
4367 if (bca.f == NULL) {
4368 error = got_error_from_errno("got_opentemp");
4369 goto done;
4371 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4372 &bca.line_offsets, bca.f, blob);
4373 if (error || bca.nlines == 0)
4374 goto done;
4376 /* Don't include \n at EOF in the blame line count. */
4377 if (bca.line_offsets[bca.nlines - 1] == filesize)
4378 bca.nlines--;
4380 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4381 if (bca.lines == NULL) {
4382 error = got_error_from_errno("calloc");
4383 goto done;
4385 bca.lineno_cur = 1;
4386 bca.nlines_prec = 0;
4387 i = bca.nlines;
4388 while (i > 0) {
4389 i /= 10;
4390 bca.nlines_prec++;
4392 bca.repo = repo;
4394 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4395 repo, blame_cb, &bca, check_cancelled, NULL);
4396 done:
4397 free(in_repo_path);
4398 free(link_target);
4399 free(repo_path);
4400 free(cwd);
4401 free(commit_id);
4402 free(obj_id);
4403 if (blob)
4404 got_object_blob_close(blob);
4405 if (worktree)
4406 got_worktree_close(worktree);
4407 if (repo) {
4408 const struct got_error *repo_error;
4409 repo_error = got_repo_close(repo);
4410 if (error == NULL)
4411 error = repo_error;
4413 if (bca.lines) {
4414 for (i = 0; i < bca.nlines; i++) {
4415 struct blame_line *bline = &bca.lines[i];
4416 free(bline->id_str);
4417 free(bline->committer);
4419 free(bca.lines);
4421 free(bca.line_offsets);
4422 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4423 error = got_error_from_errno("fclose");
4424 return error;
4427 __dead static void
4428 usage_tree(void)
4430 fprintf(stderr,
4431 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4432 getprogname());
4433 exit(1);
4436 static const struct got_error *
4437 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4438 const char *root_path, struct got_repository *repo)
4440 const struct got_error *err = NULL;
4441 int is_root_path = (strcmp(path, root_path) == 0);
4442 const char *modestr = "";
4443 mode_t mode = got_tree_entry_get_mode(te);
4444 char *link_target = NULL;
4446 path += strlen(root_path);
4447 while (path[0] == '/')
4448 path++;
4450 if (got_object_tree_entry_is_submodule(te))
4451 modestr = "$";
4452 else if (S_ISLNK(mode)) {
4453 int i;
4455 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4456 if (err)
4457 return err;
4458 for (i = 0; i < strlen(link_target); i++) {
4459 if (!isprint((unsigned char)link_target[i]))
4460 link_target[i] = '?';
4463 modestr = "@";
4465 else if (S_ISDIR(mode))
4466 modestr = "/";
4467 else if (mode & S_IXUSR)
4468 modestr = "*";
4470 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4471 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4472 link_target ? " -> ": "", link_target ? link_target : "");
4474 free(link_target);
4475 return NULL;
4478 static const struct got_error *
4479 print_tree(const char *path, struct got_object_id *commit_id,
4480 int show_ids, int recurse, const char *root_path,
4481 struct got_repository *repo)
4483 const struct got_error *err = NULL;
4484 struct got_object_id *tree_id = NULL;
4485 struct got_tree_object *tree = NULL;
4486 int nentries, i;
4488 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4489 if (err)
4490 goto done;
4492 err = got_object_open_as_tree(&tree, repo, tree_id);
4493 if (err)
4494 goto done;
4495 nentries = got_object_tree_get_nentries(tree);
4496 for (i = 0; i < nentries; i++) {
4497 struct got_tree_entry *te;
4498 char *id = NULL;
4500 if (sigint_received || sigpipe_received)
4501 break;
4503 te = got_object_tree_get_entry(tree, i);
4504 if (show_ids) {
4505 char *id_str;
4506 err = got_object_id_str(&id_str,
4507 got_tree_entry_get_id(te));
4508 if (err)
4509 goto done;
4510 if (asprintf(&id, "%s ", id_str) == -1) {
4511 err = got_error_from_errno("asprintf");
4512 free(id_str);
4513 goto done;
4515 free(id_str);
4517 err = print_entry(te, id, path, root_path, repo);
4518 free(id);
4519 if (err)
4520 goto done;
4522 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4523 char *child_path;
4524 if (asprintf(&child_path, "%s%s%s", path,
4525 path[0] == '/' && path[1] == '\0' ? "" : "/",
4526 got_tree_entry_get_name(te)) == -1) {
4527 err = got_error_from_errno("asprintf");
4528 goto done;
4530 err = print_tree(child_path, commit_id, show_ids, 1,
4531 root_path, repo);
4532 free(child_path);
4533 if (err)
4534 goto done;
4537 done:
4538 if (tree)
4539 got_object_tree_close(tree);
4540 free(tree_id);
4541 return err;
4544 static const struct got_error *
4545 cmd_tree(int argc, char *argv[])
4547 const struct got_error *error;
4548 struct got_repository *repo = NULL;
4549 struct got_worktree *worktree = NULL;
4550 const char *path, *refname = NULL;
4551 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4552 struct got_object_id *commit_id = NULL;
4553 char *commit_id_str = NULL;
4554 int show_ids = 0, recurse = 0;
4555 int ch;
4557 #ifndef PROFILE
4558 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4559 NULL) == -1)
4560 err(1, "pledge");
4561 #endif
4563 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4564 switch (ch) {
4565 case 'c':
4566 commit_id_str = optarg;
4567 break;
4568 case 'r':
4569 repo_path = realpath(optarg, NULL);
4570 if (repo_path == NULL)
4571 return got_error_from_errno2("realpath",
4572 optarg);
4573 got_path_strip_trailing_slashes(repo_path);
4574 break;
4575 case 'i':
4576 show_ids = 1;
4577 break;
4578 case 'R':
4579 recurse = 1;
4580 break;
4581 default:
4582 usage_tree();
4583 /* NOTREACHED */
4587 argc -= optind;
4588 argv += optind;
4590 if (argc == 1)
4591 path = argv[0];
4592 else if (argc > 1)
4593 usage_tree();
4594 else
4595 path = NULL;
4597 cwd = getcwd(NULL, 0);
4598 if (cwd == NULL) {
4599 error = got_error_from_errno("getcwd");
4600 goto done;
4602 if (repo_path == NULL) {
4603 error = got_worktree_open(&worktree, cwd);
4604 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4605 goto done;
4606 else
4607 error = NULL;
4608 if (worktree) {
4609 repo_path =
4610 strdup(got_worktree_get_repo_path(worktree));
4611 if (repo_path == NULL)
4612 error = got_error_from_errno("strdup");
4613 if (error)
4614 goto done;
4615 } else {
4616 repo_path = strdup(cwd);
4617 if (repo_path == NULL) {
4618 error = got_error_from_errno("strdup");
4619 goto done;
4624 error = got_repo_open(&repo, repo_path, NULL);
4625 if (error != NULL)
4626 goto done;
4628 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4629 if (error)
4630 goto done;
4632 if (path == NULL) {
4633 if (worktree) {
4634 char *p, *worktree_subdir = cwd +
4635 strlen(got_worktree_get_root_path(worktree));
4636 if (asprintf(&p, "%s/%s",
4637 got_worktree_get_path_prefix(worktree),
4638 worktree_subdir) == -1) {
4639 error = got_error_from_errno("asprintf");
4640 goto done;
4642 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4643 free(p);
4644 if (error)
4645 goto done;
4646 } else
4647 path = "/";
4649 if (in_repo_path == NULL) {
4650 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4651 if (error != NULL)
4652 goto done;
4655 if (commit_id_str == NULL) {
4656 struct got_reference *head_ref;
4657 if (worktree)
4658 refname = got_worktree_get_head_ref_name(worktree);
4659 else
4660 refname = GOT_REF_HEAD;
4661 error = got_ref_open(&head_ref, repo, refname, 0);
4662 if (error != NULL)
4663 goto done;
4664 error = got_ref_resolve(&commit_id, repo, head_ref);
4665 got_ref_close(head_ref);
4666 if (error != NULL)
4667 goto done;
4668 } else {
4669 error = got_repo_match_object_id(&commit_id, NULL,
4670 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4671 if (error)
4672 goto done;
4675 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4676 in_repo_path, repo);
4677 done:
4678 free(in_repo_path);
4679 free(repo_path);
4680 free(cwd);
4681 free(commit_id);
4682 if (worktree)
4683 got_worktree_close(worktree);
4684 if (repo) {
4685 const struct got_error *repo_error;
4686 repo_error = got_repo_close(repo);
4687 if (error == NULL)
4688 error = repo_error;
4690 return error;
4693 __dead static void
4694 usage_status(void)
4696 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4697 getprogname());
4698 exit(1);
4701 static const struct got_error *
4702 print_status(void *arg, unsigned char status, unsigned char staged_status,
4703 const char *path, struct got_object_id *blob_id,
4704 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4705 int dirfd, const char *de_name)
4707 if (status == staged_status && (status == GOT_STATUS_DELETE))
4708 status = GOT_STATUS_NO_CHANGE;
4709 if (arg) {
4710 char *status_codes = arg;
4711 size_t ncodes = strlen(status_codes);
4712 int i;
4713 for (i = 0; i < ncodes ; i++) {
4714 if (status == status_codes[i] ||
4715 staged_status == status_codes[i])
4716 break;
4718 if (i == ncodes)
4719 return NULL;
4721 printf("%c%c %s\n", status, staged_status, path);
4722 return NULL;
4725 static const struct got_error *
4726 cmd_status(int argc, char *argv[])
4728 const struct got_error *error = NULL;
4729 struct got_repository *repo = NULL;
4730 struct got_worktree *worktree = NULL;
4731 char *cwd = NULL, *status_codes = NULL;;
4732 struct got_pathlist_head paths;
4733 struct got_pathlist_entry *pe;
4734 int ch, i;
4736 TAILQ_INIT(&paths);
4738 while ((ch = getopt(argc, argv, "s:")) != -1) {
4739 switch (ch) {
4740 case 's':
4741 for (i = 0; i < strlen(optarg); i++) {
4742 switch (optarg[i]) {
4743 case GOT_STATUS_MODIFY:
4744 case GOT_STATUS_ADD:
4745 case GOT_STATUS_DELETE:
4746 case GOT_STATUS_CONFLICT:
4747 case GOT_STATUS_MISSING:
4748 case GOT_STATUS_OBSTRUCTED:
4749 case GOT_STATUS_UNVERSIONED:
4750 case GOT_STATUS_MODE_CHANGE:
4751 case GOT_STATUS_NONEXISTENT:
4752 break;
4753 default:
4754 errx(1, "invalid status code '%c'",
4755 optarg[i]);
4758 status_codes = optarg;
4759 break;
4760 default:
4761 usage_status();
4762 /* NOTREACHED */
4766 argc -= optind;
4767 argv += optind;
4769 #ifndef PROFILE
4770 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4771 NULL) == -1)
4772 err(1, "pledge");
4773 #endif
4774 cwd = getcwd(NULL, 0);
4775 if (cwd == NULL) {
4776 error = got_error_from_errno("getcwd");
4777 goto done;
4780 error = got_worktree_open(&worktree, cwd);
4781 if (error) {
4782 if (error->code == GOT_ERR_NOT_WORKTREE)
4783 error = wrap_not_worktree_error(error, "status", cwd);
4784 goto done;
4787 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4788 NULL);
4789 if (error != NULL)
4790 goto done;
4792 error = apply_unveil(got_repo_get_path(repo), 1,
4793 got_worktree_get_root_path(worktree));
4794 if (error)
4795 goto done;
4797 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4798 if (error)
4799 goto done;
4801 error = got_worktree_status(worktree, &paths, repo, print_status,
4802 status_codes, check_cancelled, NULL);
4803 done:
4804 TAILQ_FOREACH(pe, &paths, entry)
4805 free((char *)pe->path);
4806 got_pathlist_free(&paths);
4807 free(cwd);
4808 return error;
4811 __dead static void
4812 usage_ref(void)
4814 fprintf(stderr,
4815 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4816 "[-d] [name]\n",
4817 getprogname());
4818 exit(1);
4821 static const struct got_error *
4822 list_refs(struct got_repository *repo, const char *refname)
4824 static const struct got_error *err = NULL;
4825 struct got_reflist_head refs;
4826 struct got_reflist_entry *re;
4828 SIMPLEQ_INIT(&refs);
4829 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4830 if (err)
4831 return err;
4833 SIMPLEQ_FOREACH(re, &refs, entry) {
4834 char *refstr;
4835 refstr = got_ref_to_str(re->ref);
4836 if (refstr == NULL)
4837 return got_error_from_errno("got_ref_to_str");
4838 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4839 free(refstr);
4842 got_ref_list_free(&refs);
4843 return NULL;
4846 static const struct got_error *
4847 delete_ref(struct got_repository *repo, const char *refname)
4849 const struct got_error *err = NULL;
4850 struct got_reference *ref;
4852 err = got_ref_open(&ref, repo, refname, 0);
4853 if (err)
4854 return err;
4856 err = got_ref_delete(ref, repo);
4857 got_ref_close(ref);
4858 return err;
4861 static const struct got_error *
4862 add_ref(struct got_repository *repo, const char *refname, const char *target)
4864 const struct got_error *err = NULL;
4865 struct got_object_id *id;
4866 struct got_reference *ref = NULL;
4869 * Don't let the user create a reference name with a leading '-'.
4870 * While technically a valid reference name, this case is usually
4871 * an unintended typo.
4873 if (refname[0] == '-')
4874 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4876 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4877 repo);
4878 if (err) {
4879 struct got_reference *target_ref;
4881 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4882 return err;
4883 err = got_ref_open(&target_ref, repo, target, 0);
4884 if (err)
4885 return err;
4886 err = got_ref_resolve(&id, repo, target_ref);
4887 got_ref_close(target_ref);
4888 if (err)
4889 return err;
4892 err = got_ref_alloc(&ref, refname, id);
4893 if (err)
4894 goto done;
4896 err = got_ref_write(ref, repo);
4897 done:
4898 if (ref)
4899 got_ref_close(ref);
4900 free(id);
4901 return err;
4904 static const struct got_error *
4905 add_symref(struct got_repository *repo, const char *refname, const char *target)
4907 const struct got_error *err = NULL;
4908 struct got_reference *ref = NULL;
4909 struct got_reference *target_ref = NULL;
4912 * Don't let the user create a reference name with a leading '-'.
4913 * While technically a valid reference name, this case is usually
4914 * an unintended typo.
4916 if (refname[0] == '-')
4917 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4919 err = got_ref_open(&target_ref, repo, target, 0);
4920 if (err)
4921 return err;
4923 err = got_ref_alloc_symref(&ref, refname, target_ref);
4924 if (err)
4925 goto done;
4927 err = got_ref_write(ref, repo);
4928 done:
4929 if (target_ref)
4930 got_ref_close(target_ref);
4931 if (ref)
4932 got_ref_close(ref);
4933 return err;
4936 static const struct got_error *
4937 cmd_ref(int argc, char *argv[])
4939 const struct got_error *error = NULL;
4940 struct got_repository *repo = NULL;
4941 struct got_worktree *worktree = NULL;
4942 char *cwd = NULL, *repo_path = NULL;
4943 int ch, do_list = 0, do_delete = 0;
4944 const char *obj_arg = NULL, *symref_target= NULL;
4945 char *refname = NULL;
4947 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4948 switch (ch) {
4949 case 'c':
4950 obj_arg = optarg;
4951 break;
4952 case 'd':
4953 do_delete = 1;
4954 break;
4955 case 'r':
4956 repo_path = realpath(optarg, NULL);
4957 if (repo_path == NULL)
4958 return got_error_from_errno2("realpath",
4959 optarg);
4960 got_path_strip_trailing_slashes(repo_path);
4961 break;
4962 case 'l':
4963 do_list = 1;
4964 break;
4965 case 's':
4966 symref_target = optarg;
4967 break;
4968 default:
4969 usage_ref();
4970 /* NOTREACHED */
4974 if (obj_arg && do_list)
4975 errx(1, "-c and -l options are mutually exclusive");
4976 if (obj_arg && do_delete)
4977 errx(1, "-c and -d options are mutually exclusive");
4978 if (obj_arg && symref_target)
4979 errx(1, "-c and -s options are mutually exclusive");
4980 if (symref_target && do_delete)
4981 errx(1, "-s and -d options are mutually exclusive");
4982 if (symref_target && do_list)
4983 errx(1, "-s and -l options are mutually exclusive");
4984 if (do_delete && do_list)
4985 errx(1, "-d and -l options are mutually exclusive");
4987 argc -= optind;
4988 argv += optind;
4990 if (do_list) {
4991 if (argc != 0 && argc != 1)
4992 usage_ref();
4993 if (argc == 1) {
4994 refname = strdup(argv[0]);
4995 if (refname == NULL) {
4996 error = got_error_from_errno("strdup");
4997 goto done;
5000 } else {
5001 if (argc != 1)
5002 usage_ref();
5003 refname = strdup(argv[0]);
5004 if (refname == NULL) {
5005 error = got_error_from_errno("strdup");
5006 goto done;
5010 if (refname)
5011 got_path_strip_trailing_slashes(refname);
5013 #ifndef PROFILE
5014 if (do_list) {
5015 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5016 NULL) == -1)
5017 err(1, "pledge");
5018 } else {
5019 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5020 "sendfd unveil", NULL) == -1)
5021 err(1, "pledge");
5023 #endif
5024 cwd = getcwd(NULL, 0);
5025 if (cwd == NULL) {
5026 error = got_error_from_errno("getcwd");
5027 goto done;
5030 if (repo_path == NULL) {
5031 error = got_worktree_open(&worktree, cwd);
5032 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5033 goto done;
5034 else
5035 error = NULL;
5036 if (worktree) {
5037 repo_path =
5038 strdup(got_worktree_get_repo_path(worktree));
5039 if (repo_path == NULL)
5040 error = got_error_from_errno("strdup");
5041 if (error)
5042 goto done;
5043 } else {
5044 repo_path = strdup(cwd);
5045 if (repo_path == NULL) {
5046 error = got_error_from_errno("strdup");
5047 goto done;
5052 error = got_repo_open(&repo, repo_path, NULL);
5053 if (error != NULL)
5054 goto done;
5056 error = apply_unveil(got_repo_get_path(repo), do_list,
5057 worktree ? got_worktree_get_root_path(worktree) : NULL);
5058 if (error)
5059 goto done;
5061 if (do_list)
5062 error = list_refs(repo, refname);
5063 else if (do_delete)
5064 error = delete_ref(repo, refname);
5065 else if (symref_target)
5066 error = add_symref(repo, refname, symref_target);
5067 else {
5068 if (obj_arg == NULL)
5069 usage_ref();
5070 error = add_ref(repo, refname, obj_arg);
5072 done:
5073 free(refname);
5074 if (repo)
5075 got_repo_close(repo);
5076 if (worktree)
5077 got_worktree_close(worktree);
5078 free(cwd);
5079 free(repo_path);
5080 return error;
5083 __dead static void
5084 usage_branch(void)
5086 fprintf(stderr,
5087 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5088 "[name]\n", getprogname());
5089 exit(1);
5092 static const struct got_error *
5093 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5094 struct got_reference *ref)
5096 const struct got_error *err = NULL;
5097 const char *refname, *marker = " ";
5098 char *refstr;
5100 refname = got_ref_get_name(ref);
5101 if (worktree && strcmp(refname,
5102 got_worktree_get_head_ref_name(worktree)) == 0) {
5103 struct got_object_id *id = NULL;
5105 err = got_ref_resolve(&id, repo, ref);
5106 if (err)
5107 return err;
5108 if (got_object_id_cmp(id,
5109 got_worktree_get_base_commit_id(worktree)) == 0)
5110 marker = "* ";
5111 else
5112 marker = "~ ";
5113 free(id);
5116 if (strncmp(refname, "refs/heads/", 11) == 0)
5117 refname += 11;
5118 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5119 refname += 18;
5121 refstr = got_ref_to_str(ref);
5122 if (refstr == NULL)
5123 return got_error_from_errno("got_ref_to_str");
5125 printf("%s%s: %s\n", marker, refname, refstr);
5126 free(refstr);
5127 return NULL;
5130 static const struct got_error *
5131 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5133 const char *refname;
5135 if (worktree == NULL)
5136 return got_error(GOT_ERR_NOT_WORKTREE);
5138 refname = got_worktree_get_head_ref_name(worktree);
5140 if (strncmp(refname, "refs/heads/", 11) == 0)
5141 refname += 11;
5142 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5143 refname += 18;
5145 printf("%s\n", refname);
5147 return NULL;
5150 static const struct got_error *
5151 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5153 static const struct got_error *err = NULL;
5154 struct got_reflist_head refs;
5155 struct got_reflist_entry *re;
5156 struct got_reference *temp_ref = NULL;
5157 int rebase_in_progress, histedit_in_progress;
5159 SIMPLEQ_INIT(&refs);
5161 if (worktree) {
5162 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5163 worktree);
5164 if (err)
5165 return err;
5167 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5168 worktree);
5169 if (err)
5170 return err;
5172 if (rebase_in_progress || histedit_in_progress) {
5173 err = got_ref_open(&temp_ref, repo,
5174 got_worktree_get_head_ref_name(worktree), 0);
5175 if (err)
5176 return err;
5177 list_branch(repo, worktree, temp_ref);
5178 got_ref_close(temp_ref);
5182 err = got_ref_list(&refs, repo, "refs/heads",
5183 got_ref_cmp_by_name, NULL);
5184 if (err)
5185 return err;
5187 SIMPLEQ_FOREACH(re, &refs, entry)
5188 list_branch(repo, worktree, re->ref);
5190 got_ref_list_free(&refs);
5191 return NULL;
5194 static const struct got_error *
5195 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5196 const char *branch_name)
5198 const struct got_error *err = NULL;
5199 struct got_reference *ref = NULL;
5200 char *refname;
5202 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5203 return got_error_from_errno("asprintf");
5205 err = got_ref_open(&ref, repo, refname, 0);
5206 if (err)
5207 goto done;
5209 if (worktree &&
5210 strcmp(got_worktree_get_head_ref_name(worktree),
5211 got_ref_get_name(ref)) == 0) {
5212 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5213 "will not delete this work tree's current branch");
5214 goto done;
5217 err = got_ref_delete(ref, repo);
5218 done:
5219 if (ref)
5220 got_ref_close(ref);
5221 free(refname);
5222 return err;
5225 static const struct got_error *
5226 add_branch(struct got_repository *repo, const char *branch_name,
5227 struct got_object_id *base_commit_id)
5229 const struct got_error *err = NULL;
5230 struct got_reference *ref = NULL;
5231 char *base_refname = NULL, *refname = NULL;
5234 * Don't let the user create a branch name with a leading '-'.
5235 * While technically a valid reference name, this case is usually
5236 * an unintended typo.
5238 if (branch_name[0] == '-')
5239 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5241 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5242 err = got_error_from_errno("asprintf");
5243 goto done;
5246 err = got_ref_open(&ref, repo, refname, 0);
5247 if (err == NULL) {
5248 err = got_error(GOT_ERR_BRANCH_EXISTS);
5249 goto done;
5250 } else if (err->code != GOT_ERR_NOT_REF)
5251 goto done;
5253 err = got_ref_alloc(&ref, refname, base_commit_id);
5254 if (err)
5255 goto done;
5257 err = got_ref_write(ref, repo);
5258 done:
5259 if (ref)
5260 got_ref_close(ref);
5261 free(base_refname);
5262 free(refname);
5263 return err;
5266 static const struct got_error *
5267 cmd_branch(int argc, char *argv[])
5269 const struct got_error *error = NULL;
5270 struct got_repository *repo = NULL;
5271 struct got_worktree *worktree = NULL;
5272 char *cwd = NULL, *repo_path = NULL;
5273 int ch, do_list = 0, do_show = 0, do_update = 1;
5274 const char *delref = NULL, *commit_id_arg = NULL;
5275 struct got_reference *ref = NULL;
5276 struct got_pathlist_head paths;
5277 struct got_pathlist_entry *pe;
5278 struct got_object_id *commit_id = NULL;
5279 char *commit_id_str = NULL;
5281 TAILQ_INIT(&paths);
5283 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5284 switch (ch) {
5285 case 'c':
5286 commit_id_arg = optarg;
5287 break;
5288 case 'd':
5289 delref = optarg;
5290 break;
5291 case 'r':
5292 repo_path = realpath(optarg, NULL);
5293 if (repo_path == NULL)
5294 return got_error_from_errno2("realpath",
5295 optarg);
5296 got_path_strip_trailing_slashes(repo_path);
5297 break;
5298 case 'l':
5299 do_list = 1;
5300 break;
5301 case 'n':
5302 do_update = 0;
5303 break;
5304 default:
5305 usage_branch();
5306 /* NOTREACHED */
5310 if (do_list && delref)
5311 errx(1, "-l and -d options are mutually exclusive");
5313 argc -= optind;
5314 argv += optind;
5316 if (!do_list && !delref && argc == 0)
5317 do_show = 1;
5319 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5320 errx(1, "-c option can only be used when creating a branch");
5322 if (do_list || delref) {
5323 if (argc > 0)
5324 usage_branch();
5325 } else if (!do_show && argc != 1)
5326 usage_branch();
5328 #ifndef PROFILE
5329 if (do_list || do_show) {
5330 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5331 NULL) == -1)
5332 err(1, "pledge");
5333 } else {
5334 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5335 "sendfd unveil", NULL) == -1)
5336 err(1, "pledge");
5338 #endif
5339 cwd = getcwd(NULL, 0);
5340 if (cwd == NULL) {
5341 error = got_error_from_errno("getcwd");
5342 goto done;
5345 if (repo_path == NULL) {
5346 error = got_worktree_open(&worktree, cwd);
5347 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5348 goto done;
5349 else
5350 error = NULL;
5351 if (worktree) {
5352 repo_path =
5353 strdup(got_worktree_get_repo_path(worktree));
5354 if (repo_path == NULL)
5355 error = got_error_from_errno("strdup");
5356 if (error)
5357 goto done;
5358 } else {
5359 repo_path = strdup(cwd);
5360 if (repo_path == NULL) {
5361 error = got_error_from_errno("strdup");
5362 goto done;
5367 error = got_repo_open(&repo, repo_path, NULL);
5368 if (error != NULL)
5369 goto done;
5371 error = apply_unveil(got_repo_get_path(repo), do_list,
5372 worktree ? got_worktree_get_root_path(worktree) : NULL);
5373 if (error)
5374 goto done;
5376 if (do_show)
5377 error = show_current_branch(repo, worktree);
5378 else if (do_list)
5379 error = list_branches(repo, worktree);
5380 else if (delref)
5381 error = delete_branch(repo, worktree, delref);
5382 else {
5383 if (commit_id_arg == NULL)
5384 commit_id_arg = worktree ?
5385 got_worktree_get_head_ref_name(worktree) :
5386 GOT_REF_HEAD;
5387 error = got_repo_match_object_id(&commit_id, NULL,
5388 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5389 if (error)
5390 goto done;
5391 error = add_branch(repo, argv[0], commit_id);
5392 if (error)
5393 goto done;
5394 if (worktree && do_update) {
5395 struct got_update_progress_arg upa;
5396 char *branch_refname = NULL;
5398 error = got_object_id_str(&commit_id_str, commit_id);
5399 if (error)
5400 goto done;
5401 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5402 worktree);
5403 if (error)
5404 goto done;
5405 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5406 == -1) {
5407 error = got_error_from_errno("asprintf");
5408 goto done;
5410 error = got_ref_open(&ref, repo, branch_refname, 0);
5411 free(branch_refname);
5412 if (error)
5413 goto done;
5414 error = switch_head_ref(ref, commit_id, worktree,
5415 repo);
5416 if (error)
5417 goto done;
5418 error = got_worktree_set_base_commit_id(worktree, repo,
5419 commit_id);
5420 if (error)
5421 goto done;
5422 memset(&upa, 0, sizeof(upa));
5423 error = got_worktree_checkout_files(worktree, &paths,
5424 repo, update_progress, &upa, check_cancelled,
5425 NULL);
5426 if (error)
5427 goto done;
5428 if (upa.did_something)
5429 printf("Updated to commit %s\n", commit_id_str);
5430 print_update_progress_stats(&upa);
5433 done:
5434 if (ref)
5435 got_ref_close(ref);
5436 if (repo)
5437 got_repo_close(repo);
5438 if (worktree)
5439 got_worktree_close(worktree);
5440 free(cwd);
5441 free(repo_path);
5442 free(commit_id);
5443 free(commit_id_str);
5444 TAILQ_FOREACH(pe, &paths, entry)
5445 free((char *)pe->path);
5446 got_pathlist_free(&paths);
5447 return error;
5451 __dead static void
5452 usage_tag(void)
5454 fprintf(stderr,
5455 "usage: %s tag [-c commit] [-r repository] [-l] "
5456 "[-m message] name\n", getprogname());
5457 exit(1);
5460 #if 0
5461 static const struct got_error *
5462 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5464 const struct got_error *err = NULL;
5465 struct got_reflist_entry *re, *se, *new;
5466 struct got_object_id *re_id, *se_id;
5467 struct got_tag_object *re_tag, *se_tag;
5468 time_t re_time, se_time;
5470 SIMPLEQ_FOREACH(re, tags, entry) {
5471 se = SIMPLEQ_FIRST(sorted);
5472 if (se == NULL) {
5473 err = got_reflist_entry_dup(&new, re);
5474 if (err)
5475 return err;
5476 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5477 continue;
5478 } else {
5479 err = got_ref_resolve(&re_id, repo, re->ref);
5480 if (err)
5481 break;
5482 err = got_object_open_as_tag(&re_tag, repo, re_id);
5483 free(re_id);
5484 if (err)
5485 break;
5486 re_time = got_object_tag_get_tagger_time(re_tag);
5487 got_object_tag_close(re_tag);
5490 while (se) {
5491 err = got_ref_resolve(&se_id, repo, re->ref);
5492 if (err)
5493 break;
5494 err = got_object_open_as_tag(&se_tag, repo, se_id);
5495 free(se_id);
5496 if (err)
5497 break;
5498 se_time = got_object_tag_get_tagger_time(se_tag);
5499 got_object_tag_close(se_tag);
5501 if (se_time > re_time) {
5502 err = got_reflist_entry_dup(&new, re);
5503 if (err)
5504 return err;
5505 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5506 break;
5508 se = SIMPLEQ_NEXT(se, entry);
5509 continue;
5512 done:
5513 return err;
5515 #endif
5517 static const struct got_error *
5518 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5520 static const struct got_error *err = NULL;
5521 struct got_reflist_head refs;
5522 struct got_reflist_entry *re;
5524 SIMPLEQ_INIT(&refs);
5526 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5527 if (err)
5528 return err;
5530 SIMPLEQ_FOREACH(re, &refs, entry) {
5531 const char *refname;
5532 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5533 char datebuf[26];
5534 const char *tagger;
5535 time_t tagger_time;
5536 struct got_object_id *id;
5537 struct got_tag_object *tag;
5538 struct got_commit_object *commit = NULL;
5540 refname = got_ref_get_name(re->ref);
5541 if (strncmp(refname, "refs/tags/", 10) != 0)
5542 continue;
5543 refname += 10;
5544 refstr = got_ref_to_str(re->ref);
5545 if (refstr == NULL) {
5546 err = got_error_from_errno("got_ref_to_str");
5547 break;
5549 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5550 free(refstr);
5552 err = got_ref_resolve(&id, repo, re->ref);
5553 if (err)
5554 break;
5555 err = got_object_open_as_tag(&tag, repo, id);
5556 if (err) {
5557 if (err->code != GOT_ERR_OBJ_TYPE) {
5558 free(id);
5559 break;
5561 /* "lightweight" tag */
5562 err = got_object_open_as_commit(&commit, repo, id);
5563 if (err) {
5564 free(id);
5565 break;
5567 tagger = got_object_commit_get_committer(commit);
5568 tagger_time =
5569 got_object_commit_get_committer_time(commit);
5570 err = got_object_id_str(&id_str, id);
5571 free(id);
5572 if (err)
5573 break;
5574 } else {
5575 free(id);
5576 tagger = got_object_tag_get_tagger(tag);
5577 tagger_time = got_object_tag_get_tagger_time(tag);
5578 err = got_object_id_str(&id_str,
5579 got_object_tag_get_object_id(tag));
5580 if (err)
5581 break;
5583 printf("from: %s\n", tagger);
5584 datestr = get_datestr(&tagger_time, datebuf);
5585 if (datestr)
5586 printf("date: %s UTC\n", datestr);
5587 if (commit)
5588 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5589 else {
5590 switch (got_object_tag_get_object_type(tag)) {
5591 case GOT_OBJ_TYPE_BLOB:
5592 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5593 id_str);
5594 break;
5595 case GOT_OBJ_TYPE_TREE:
5596 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5597 id_str);
5598 break;
5599 case GOT_OBJ_TYPE_COMMIT:
5600 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5601 id_str);
5602 break;
5603 case GOT_OBJ_TYPE_TAG:
5604 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5605 id_str);
5606 break;
5607 default:
5608 break;
5611 free(id_str);
5612 if (commit) {
5613 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5614 if (err)
5615 break;
5616 got_object_commit_close(commit);
5617 } else {
5618 tagmsg0 = strdup(got_object_tag_get_message(tag));
5619 got_object_tag_close(tag);
5620 if (tagmsg0 == NULL) {
5621 err = got_error_from_errno("strdup");
5622 break;
5626 tagmsg = tagmsg0;
5627 do {
5628 line = strsep(&tagmsg, "\n");
5629 if (line)
5630 printf(" %s\n", line);
5631 } while (line);
5632 free(tagmsg0);
5635 got_ref_list_free(&refs);
5636 return NULL;
5639 static const struct got_error *
5640 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5641 const char *tag_name, const char *repo_path)
5643 const struct got_error *err = NULL;
5644 char *template = NULL, *initial_content = NULL;
5645 char *editor = NULL;
5646 int fd = -1;
5648 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5649 err = got_error_from_errno("asprintf");
5650 goto done;
5653 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5654 commit_id_str, tag_name) == -1) {
5655 err = got_error_from_errno("asprintf");
5656 goto done;
5659 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5660 if (err)
5661 goto done;
5663 dprintf(fd, initial_content);
5664 close(fd);
5666 err = get_editor(&editor);
5667 if (err)
5668 goto done;
5669 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5670 done:
5671 free(initial_content);
5672 free(template);
5673 free(editor);
5675 /* Editor is done; we can now apply unveil(2) */
5676 if (err == NULL) {
5677 err = apply_unveil(repo_path, 0, NULL);
5678 if (err) {
5679 free(*tagmsg);
5680 *tagmsg = NULL;
5683 return err;
5686 static const struct got_error *
5687 add_tag(struct got_repository *repo, const char *tag_name,
5688 const char *commit_arg, const char *tagmsg_arg)
5690 const struct got_error *err = NULL;
5691 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5692 char *label = NULL, *commit_id_str = NULL;
5693 struct got_reference *ref = NULL;
5694 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5695 char *tagmsg_path = NULL, *tag_id_str = NULL;
5696 int preserve_tagmsg = 0;
5699 * Don't let the user create a tag name with a leading '-'.
5700 * While technically a valid reference name, this case is usually
5701 * an unintended typo.
5703 if (tag_name[0] == '-')
5704 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5706 err = get_author(&tagger, repo);
5707 if (err)
5708 return err;
5710 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5711 GOT_OBJ_TYPE_COMMIT, 1, repo);
5712 if (err)
5713 goto done;
5715 err = got_object_id_str(&commit_id_str, commit_id);
5716 if (err)
5717 goto done;
5719 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5720 refname = strdup(tag_name);
5721 if (refname == NULL) {
5722 err = got_error_from_errno("strdup");
5723 goto done;
5725 tag_name += 10;
5726 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5727 err = got_error_from_errno("asprintf");
5728 goto done;
5731 err = got_ref_open(&ref, repo, refname, 0);
5732 if (err == NULL) {
5733 err = got_error(GOT_ERR_TAG_EXISTS);
5734 goto done;
5735 } else if (err->code != GOT_ERR_NOT_REF)
5736 goto done;
5738 if (tagmsg_arg == NULL) {
5739 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5740 tag_name, got_repo_get_path(repo));
5741 if (err) {
5742 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5743 tagmsg_path != NULL)
5744 preserve_tagmsg = 1;
5745 goto done;
5749 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5750 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5751 if (err) {
5752 if (tagmsg_path)
5753 preserve_tagmsg = 1;
5754 goto done;
5757 err = got_ref_alloc(&ref, refname, tag_id);
5758 if (err) {
5759 if (tagmsg_path)
5760 preserve_tagmsg = 1;
5761 goto done;
5764 err = got_ref_write(ref, repo);
5765 if (err) {
5766 if (tagmsg_path)
5767 preserve_tagmsg = 1;
5768 goto done;
5771 err = got_object_id_str(&tag_id_str, tag_id);
5772 if (err) {
5773 if (tagmsg_path)
5774 preserve_tagmsg = 1;
5775 goto done;
5777 printf("Created tag %s\n", tag_id_str);
5778 done:
5779 if (preserve_tagmsg) {
5780 fprintf(stderr, "%s: tag message preserved in %s\n",
5781 getprogname(), tagmsg_path);
5782 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5783 err = got_error_from_errno2("unlink", tagmsg_path);
5784 free(tag_id_str);
5785 if (ref)
5786 got_ref_close(ref);
5787 free(commit_id);
5788 free(commit_id_str);
5789 free(refname);
5790 free(tagmsg);
5791 free(tagmsg_path);
5792 free(tagger);
5793 return err;
5796 static const struct got_error *
5797 cmd_tag(int argc, char *argv[])
5799 const struct got_error *error = NULL;
5800 struct got_repository *repo = NULL;
5801 struct got_worktree *worktree = NULL;
5802 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5803 char *gitconfig_path = NULL;
5804 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5805 int ch, do_list = 0;
5807 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5808 switch (ch) {
5809 case 'c':
5810 commit_id_arg = optarg;
5811 break;
5812 case 'm':
5813 tagmsg = optarg;
5814 break;
5815 case 'r':
5816 repo_path = realpath(optarg, NULL);
5817 if (repo_path == NULL)
5818 return got_error_from_errno2("realpath",
5819 optarg);
5820 got_path_strip_trailing_slashes(repo_path);
5821 break;
5822 case 'l':
5823 do_list = 1;
5824 break;
5825 default:
5826 usage_tag();
5827 /* NOTREACHED */
5831 argc -= optind;
5832 argv += optind;
5834 if (do_list) {
5835 if (commit_id_arg != NULL)
5836 errx(1,
5837 "-c option can only be used when creating a tag");
5838 if (tagmsg)
5839 errx(1, "-l and -m options are mutually exclusive");
5840 if (argc > 0)
5841 usage_tag();
5842 } else if (argc != 1)
5843 usage_tag();
5845 tag_name = argv[0];
5847 #ifndef PROFILE
5848 if (do_list) {
5849 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5850 NULL) == -1)
5851 err(1, "pledge");
5852 } else {
5853 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5854 "sendfd unveil", NULL) == -1)
5855 err(1, "pledge");
5857 #endif
5858 cwd = getcwd(NULL, 0);
5859 if (cwd == NULL) {
5860 error = got_error_from_errno("getcwd");
5861 goto done;
5864 if (repo_path == NULL) {
5865 error = got_worktree_open(&worktree, cwd);
5866 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5867 goto done;
5868 else
5869 error = NULL;
5870 if (worktree) {
5871 repo_path =
5872 strdup(got_worktree_get_repo_path(worktree));
5873 if (repo_path == NULL)
5874 error = got_error_from_errno("strdup");
5875 if (error)
5876 goto done;
5877 } else {
5878 repo_path = strdup(cwd);
5879 if (repo_path == NULL) {
5880 error = got_error_from_errno("strdup");
5881 goto done;
5886 if (do_list) {
5887 error = got_repo_open(&repo, repo_path, NULL);
5888 if (error != NULL)
5889 goto done;
5890 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5891 if (error)
5892 goto done;
5893 error = list_tags(repo, worktree);
5894 } else {
5895 error = get_gitconfig_path(&gitconfig_path);
5896 if (error)
5897 goto done;
5898 error = got_repo_open(&repo, repo_path, gitconfig_path);
5899 if (error != NULL)
5900 goto done;
5902 if (tagmsg) {
5903 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5904 if (error)
5905 goto done;
5908 if (commit_id_arg == NULL) {
5909 struct got_reference *head_ref;
5910 struct got_object_id *commit_id;
5911 error = got_ref_open(&head_ref, repo,
5912 worktree ? got_worktree_get_head_ref_name(worktree)
5913 : GOT_REF_HEAD, 0);
5914 if (error)
5915 goto done;
5916 error = got_ref_resolve(&commit_id, repo, head_ref);
5917 got_ref_close(head_ref);
5918 if (error)
5919 goto done;
5920 error = got_object_id_str(&commit_id_str, commit_id);
5921 free(commit_id);
5922 if (error)
5923 goto done;
5926 error = add_tag(repo, tag_name,
5927 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5929 done:
5930 if (repo)
5931 got_repo_close(repo);
5932 if (worktree)
5933 got_worktree_close(worktree);
5934 free(cwd);
5935 free(repo_path);
5936 free(gitconfig_path);
5937 free(commit_id_str);
5938 return error;
5941 __dead static void
5942 usage_add(void)
5944 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5945 getprogname());
5946 exit(1);
5949 static const struct got_error *
5950 add_progress(void *arg, unsigned char status, const char *path)
5952 while (path[0] == '/')
5953 path++;
5954 printf("%c %s\n", status, path);
5955 return NULL;
5958 static const struct got_error *
5959 cmd_add(int argc, char *argv[])
5961 const struct got_error *error = NULL;
5962 struct got_repository *repo = NULL;
5963 struct got_worktree *worktree = NULL;
5964 char *cwd = NULL;
5965 struct got_pathlist_head paths;
5966 struct got_pathlist_entry *pe;
5967 int ch, can_recurse = 0, no_ignores = 0;
5969 TAILQ_INIT(&paths);
5971 while ((ch = getopt(argc, argv, "IR")) != -1) {
5972 switch (ch) {
5973 case 'I':
5974 no_ignores = 1;
5975 break;
5976 case 'R':
5977 can_recurse = 1;
5978 break;
5979 default:
5980 usage_add();
5981 /* NOTREACHED */
5985 argc -= optind;
5986 argv += optind;
5988 #ifndef PROFILE
5989 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5990 NULL) == -1)
5991 err(1, "pledge");
5992 #endif
5993 if (argc < 1)
5994 usage_add();
5996 cwd = getcwd(NULL, 0);
5997 if (cwd == NULL) {
5998 error = got_error_from_errno("getcwd");
5999 goto done;
6002 error = got_worktree_open(&worktree, cwd);
6003 if (error) {
6004 if (error->code == GOT_ERR_NOT_WORKTREE)
6005 error = wrap_not_worktree_error(error, "add", cwd);
6006 goto done;
6009 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6010 NULL);
6011 if (error != NULL)
6012 goto done;
6014 error = apply_unveil(got_repo_get_path(repo), 1,
6015 got_worktree_get_root_path(worktree));
6016 if (error)
6017 goto done;
6019 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6020 if (error)
6021 goto done;
6023 if (!can_recurse && no_ignores) {
6024 error = got_error_msg(GOT_ERR_BAD_PATH,
6025 "disregarding ignores requires -R option");
6026 goto done;
6030 if (!can_recurse) {
6031 char *ondisk_path;
6032 struct stat sb;
6033 TAILQ_FOREACH(pe, &paths, entry) {
6034 if (asprintf(&ondisk_path, "%s/%s",
6035 got_worktree_get_root_path(worktree),
6036 pe->path) == -1) {
6037 error = got_error_from_errno("asprintf");
6038 goto done;
6040 if (lstat(ondisk_path, &sb) == -1) {
6041 if (errno == ENOENT) {
6042 free(ondisk_path);
6043 continue;
6045 error = got_error_from_errno2("lstat",
6046 ondisk_path);
6047 free(ondisk_path);
6048 goto done;
6050 free(ondisk_path);
6051 if (S_ISDIR(sb.st_mode)) {
6052 error = got_error_msg(GOT_ERR_BAD_PATH,
6053 "adding directories requires -R option");
6054 goto done;
6059 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6060 NULL, repo, no_ignores);
6061 done:
6062 if (repo)
6063 got_repo_close(repo);
6064 if (worktree)
6065 got_worktree_close(worktree);
6066 TAILQ_FOREACH(pe, &paths, entry)
6067 free((char *)pe->path);
6068 got_pathlist_free(&paths);
6069 free(cwd);
6070 return error;
6073 __dead static void
6074 usage_remove(void)
6076 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6077 "path ...\n", getprogname());
6078 exit(1);
6081 static const struct got_error *
6082 print_remove_status(void *arg, unsigned char status,
6083 unsigned char staged_status, const char *path)
6085 while (path[0] == '/')
6086 path++;
6087 if (status == GOT_STATUS_NONEXISTENT)
6088 return NULL;
6089 if (status == staged_status && (status == GOT_STATUS_DELETE))
6090 status = GOT_STATUS_NO_CHANGE;
6091 printf("%c%c %s\n", status, staged_status, path);
6092 return NULL;
6095 static const struct got_error *
6096 cmd_remove(int argc, char *argv[])
6098 const struct got_error *error = NULL;
6099 struct got_worktree *worktree = NULL;
6100 struct got_repository *repo = NULL;
6101 const char *status_codes = NULL;
6102 char *cwd = NULL;
6103 struct got_pathlist_head paths;
6104 struct got_pathlist_entry *pe;
6105 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6107 TAILQ_INIT(&paths);
6109 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6110 switch (ch) {
6111 case 'f':
6112 delete_local_mods = 1;
6113 break;
6114 case 'k':
6115 keep_on_disk = 1;
6116 break;
6117 case 'R':
6118 can_recurse = 1;
6119 break;
6120 case 's':
6121 for (i = 0; i < strlen(optarg); i++) {
6122 switch (optarg[i]) {
6123 case GOT_STATUS_MODIFY:
6124 delete_local_mods = 1;
6125 break;
6126 case GOT_STATUS_MISSING:
6127 break;
6128 default:
6129 errx(1, "invalid status code '%c'",
6130 optarg[i]);
6133 status_codes = optarg;
6134 break;
6135 default:
6136 usage_remove();
6137 /* NOTREACHED */
6141 argc -= optind;
6142 argv += optind;
6144 #ifndef PROFILE
6145 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6146 NULL) == -1)
6147 err(1, "pledge");
6148 #endif
6149 if (argc < 1)
6150 usage_remove();
6152 cwd = getcwd(NULL, 0);
6153 if (cwd == NULL) {
6154 error = got_error_from_errno("getcwd");
6155 goto done;
6157 error = got_worktree_open(&worktree, cwd);
6158 if (error) {
6159 if (error->code == GOT_ERR_NOT_WORKTREE)
6160 error = wrap_not_worktree_error(error, "remove", cwd);
6161 goto done;
6164 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6165 NULL);
6166 if (error)
6167 goto done;
6169 error = apply_unveil(got_repo_get_path(repo), 1,
6170 got_worktree_get_root_path(worktree));
6171 if (error)
6172 goto done;
6174 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6175 if (error)
6176 goto done;
6178 if (!can_recurse) {
6179 char *ondisk_path;
6180 struct stat sb;
6181 TAILQ_FOREACH(pe, &paths, entry) {
6182 if (asprintf(&ondisk_path, "%s/%s",
6183 got_worktree_get_root_path(worktree),
6184 pe->path) == -1) {
6185 error = got_error_from_errno("asprintf");
6186 goto done;
6188 if (lstat(ondisk_path, &sb) == -1) {
6189 if (errno == ENOENT) {
6190 free(ondisk_path);
6191 continue;
6193 error = got_error_from_errno2("lstat",
6194 ondisk_path);
6195 free(ondisk_path);
6196 goto done;
6198 free(ondisk_path);
6199 if (S_ISDIR(sb.st_mode)) {
6200 error = got_error_msg(GOT_ERR_BAD_PATH,
6201 "removing directories requires -R option");
6202 goto done;
6207 error = got_worktree_schedule_delete(worktree, &paths,
6208 delete_local_mods, status_codes, print_remove_status, NULL,
6209 repo, keep_on_disk);
6210 done:
6211 if (repo)
6212 got_repo_close(repo);
6213 if (worktree)
6214 got_worktree_close(worktree);
6215 TAILQ_FOREACH(pe, &paths, entry)
6216 free((char *)pe->path);
6217 got_pathlist_free(&paths);
6218 free(cwd);
6219 return error;
6222 __dead static void
6223 usage_revert(void)
6225 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6226 "path ...\n", getprogname());
6227 exit(1);
6230 static const struct got_error *
6231 revert_progress(void *arg, unsigned char status, const char *path)
6233 if (status == GOT_STATUS_UNVERSIONED)
6234 return NULL;
6236 while (path[0] == '/')
6237 path++;
6238 printf("%c %s\n", status, path);
6239 return NULL;
6242 struct choose_patch_arg {
6243 FILE *patch_script_file;
6244 const char *action;
6247 static const struct got_error *
6248 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6249 int nchanges, const char *action)
6251 char *line = NULL;
6252 size_t linesize = 0;
6253 ssize_t linelen;
6255 switch (status) {
6256 case GOT_STATUS_ADD:
6257 printf("A %s\n%s this addition? [y/n] ", path, action);
6258 break;
6259 case GOT_STATUS_DELETE:
6260 printf("D %s\n%s this deletion? [y/n] ", path, action);
6261 break;
6262 case GOT_STATUS_MODIFY:
6263 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6264 return got_error_from_errno("fseek");
6265 printf(GOT_COMMIT_SEP_STR);
6266 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6267 printf("%s", line);
6268 if (ferror(patch_file))
6269 return got_error_from_errno("getline");
6270 printf(GOT_COMMIT_SEP_STR);
6271 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6272 path, n, nchanges, action);
6273 break;
6274 default:
6275 return got_error_path(path, GOT_ERR_FILE_STATUS);
6278 return NULL;
6281 static const struct got_error *
6282 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6283 FILE *patch_file, int n, int nchanges)
6285 const struct got_error *err = NULL;
6286 char *line = NULL;
6287 size_t linesize = 0;
6288 ssize_t linelen;
6289 int resp = ' ';
6290 struct choose_patch_arg *a = arg;
6292 *choice = GOT_PATCH_CHOICE_NONE;
6294 if (a->patch_script_file) {
6295 char *nl;
6296 err = show_change(status, path, patch_file, n, nchanges,
6297 a->action);
6298 if (err)
6299 return err;
6300 linelen = getline(&line, &linesize, a->patch_script_file);
6301 if (linelen == -1) {
6302 if (ferror(a->patch_script_file))
6303 return got_error_from_errno("getline");
6304 return NULL;
6306 nl = strchr(line, '\n');
6307 if (nl)
6308 *nl = '\0';
6309 if (strcmp(line, "y") == 0) {
6310 *choice = GOT_PATCH_CHOICE_YES;
6311 printf("y\n");
6312 } else if (strcmp(line, "n") == 0) {
6313 *choice = GOT_PATCH_CHOICE_NO;
6314 printf("n\n");
6315 } else if (strcmp(line, "q") == 0 &&
6316 status == GOT_STATUS_MODIFY) {
6317 *choice = GOT_PATCH_CHOICE_QUIT;
6318 printf("q\n");
6319 } else
6320 printf("invalid response '%s'\n", line);
6321 free(line);
6322 return NULL;
6325 while (resp != 'y' && resp != 'n' && resp != 'q') {
6326 err = show_change(status, path, patch_file, n, nchanges,
6327 a->action);
6328 if (err)
6329 return err;
6330 resp = getchar();
6331 if (resp == '\n')
6332 resp = getchar();
6333 if (status == GOT_STATUS_MODIFY) {
6334 if (resp != 'y' && resp != 'n' && resp != 'q') {
6335 printf("invalid response '%c'\n", resp);
6336 resp = ' ';
6338 } else if (resp != 'y' && resp != 'n') {
6339 printf("invalid response '%c'\n", resp);
6340 resp = ' ';
6344 if (resp == 'y')
6345 *choice = GOT_PATCH_CHOICE_YES;
6346 else if (resp == 'n')
6347 *choice = GOT_PATCH_CHOICE_NO;
6348 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6349 *choice = GOT_PATCH_CHOICE_QUIT;
6351 return NULL;
6355 static const struct got_error *
6356 cmd_revert(int argc, char *argv[])
6358 const struct got_error *error = NULL;
6359 struct got_worktree *worktree = NULL;
6360 struct got_repository *repo = NULL;
6361 char *cwd = NULL, *path = NULL;
6362 struct got_pathlist_head paths;
6363 struct got_pathlist_entry *pe;
6364 int ch, can_recurse = 0, pflag = 0;
6365 FILE *patch_script_file = NULL;
6366 const char *patch_script_path = NULL;
6367 struct choose_patch_arg cpa;
6369 TAILQ_INIT(&paths);
6371 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6372 switch (ch) {
6373 case 'p':
6374 pflag = 1;
6375 break;
6376 case 'F':
6377 patch_script_path = optarg;
6378 break;
6379 case 'R':
6380 can_recurse = 1;
6381 break;
6382 default:
6383 usage_revert();
6384 /* NOTREACHED */
6388 argc -= optind;
6389 argv += optind;
6391 #ifndef PROFILE
6392 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6393 "unveil", NULL) == -1)
6394 err(1, "pledge");
6395 #endif
6396 if (argc < 1)
6397 usage_revert();
6398 if (patch_script_path && !pflag)
6399 errx(1, "-F option can only be used together with -p option");
6401 cwd = getcwd(NULL, 0);
6402 if (cwd == NULL) {
6403 error = got_error_from_errno("getcwd");
6404 goto done;
6406 error = got_worktree_open(&worktree, cwd);
6407 if (error) {
6408 if (error->code == GOT_ERR_NOT_WORKTREE)
6409 error = wrap_not_worktree_error(error, "revert", cwd);
6410 goto done;
6413 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6414 NULL);
6415 if (error != NULL)
6416 goto done;
6418 if (patch_script_path) {
6419 patch_script_file = fopen(patch_script_path, "r");
6420 if (patch_script_file == NULL) {
6421 error = got_error_from_errno2("fopen",
6422 patch_script_path);
6423 goto done;
6426 error = apply_unveil(got_repo_get_path(repo), 1,
6427 got_worktree_get_root_path(worktree));
6428 if (error)
6429 goto done;
6431 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6432 if (error)
6433 goto done;
6435 if (!can_recurse) {
6436 char *ondisk_path;
6437 struct stat sb;
6438 TAILQ_FOREACH(pe, &paths, entry) {
6439 if (asprintf(&ondisk_path, "%s/%s",
6440 got_worktree_get_root_path(worktree),
6441 pe->path) == -1) {
6442 error = got_error_from_errno("asprintf");
6443 goto done;
6445 if (lstat(ondisk_path, &sb) == -1) {
6446 if (errno == ENOENT) {
6447 free(ondisk_path);
6448 continue;
6450 error = got_error_from_errno2("lstat",
6451 ondisk_path);
6452 free(ondisk_path);
6453 goto done;
6455 free(ondisk_path);
6456 if (S_ISDIR(sb.st_mode)) {
6457 error = got_error_msg(GOT_ERR_BAD_PATH,
6458 "reverting directories requires -R option");
6459 goto done;
6464 cpa.patch_script_file = patch_script_file;
6465 cpa.action = "revert";
6466 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6467 pflag ? choose_patch : NULL, &cpa, repo);
6468 done:
6469 if (patch_script_file && fclose(patch_script_file) == EOF &&
6470 error == NULL)
6471 error = got_error_from_errno2("fclose", patch_script_path);
6472 if (repo)
6473 got_repo_close(repo);
6474 if (worktree)
6475 got_worktree_close(worktree);
6476 free(path);
6477 free(cwd);
6478 return error;
6481 __dead static void
6482 usage_commit(void)
6484 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6485 getprogname());
6486 exit(1);
6489 struct collect_commit_logmsg_arg {
6490 const char *cmdline_log;
6491 const char *editor;
6492 const char *worktree_path;
6493 const char *branch_name;
6494 const char *repo_path;
6495 char *logmsg_path;
6499 static const struct got_error *
6500 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6501 void *arg)
6503 char *initial_content = NULL;
6504 struct got_pathlist_entry *pe;
6505 const struct got_error *err = NULL;
6506 char *template = NULL;
6507 struct collect_commit_logmsg_arg *a = arg;
6508 int fd;
6509 size_t len;
6511 /* if a message was specified on the command line, just use it */
6512 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6513 len = strlen(a->cmdline_log) + 1;
6514 *logmsg = malloc(len + 1);
6515 if (*logmsg == NULL)
6516 return got_error_from_errno("malloc");
6517 strlcpy(*logmsg, a->cmdline_log, len);
6518 return NULL;
6521 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6522 return got_error_from_errno("asprintf");
6524 if (asprintf(&initial_content,
6525 "\n# changes to be committed on branch %s:\n",
6526 a->branch_name) == -1)
6527 return got_error_from_errno("asprintf");
6529 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6530 if (err)
6531 goto done;
6533 dprintf(fd, initial_content);
6535 TAILQ_FOREACH(pe, commitable_paths, entry) {
6536 struct got_commitable *ct = pe->data;
6537 dprintf(fd, "# %c %s\n",
6538 got_commitable_get_status(ct),
6539 got_commitable_get_path(ct));
6541 close(fd);
6543 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6544 done:
6545 free(initial_content);
6546 free(template);
6548 /* Editor is done; we can now apply unveil(2) */
6549 if (err == NULL) {
6550 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6551 if (err) {
6552 free(*logmsg);
6553 *logmsg = NULL;
6556 return err;
6559 static const struct got_error *
6560 cmd_commit(int argc, char *argv[])
6562 const struct got_error *error = NULL;
6563 struct got_worktree *worktree = NULL;
6564 struct got_repository *repo = NULL;
6565 char *cwd = NULL, *id_str = NULL;
6566 struct got_object_id *id = NULL;
6567 const char *logmsg = NULL;
6568 struct collect_commit_logmsg_arg cl_arg;
6569 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6570 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6571 int allow_bad_symlinks = 0;
6572 struct got_pathlist_head paths;
6574 TAILQ_INIT(&paths);
6575 cl_arg.logmsg_path = NULL;
6577 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6578 switch (ch) {
6579 case 'm':
6580 logmsg = optarg;
6581 break;
6582 case 'S':
6583 allow_bad_symlinks = 1;
6584 break;
6585 default:
6586 usage_commit();
6587 /* NOTREACHED */
6591 argc -= optind;
6592 argv += optind;
6594 #ifndef PROFILE
6595 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6596 "unveil", NULL) == -1)
6597 err(1, "pledge");
6598 #endif
6599 cwd = getcwd(NULL, 0);
6600 if (cwd == NULL) {
6601 error = got_error_from_errno("getcwd");
6602 goto done;
6604 error = got_worktree_open(&worktree, cwd);
6605 if (error) {
6606 if (error->code == GOT_ERR_NOT_WORKTREE)
6607 error = wrap_not_worktree_error(error, "commit", cwd);
6608 goto done;
6611 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6612 if (error)
6613 goto done;
6614 if (rebase_in_progress) {
6615 error = got_error(GOT_ERR_REBASING);
6616 goto done;
6619 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6620 worktree);
6621 if (error)
6622 goto done;
6624 error = get_gitconfig_path(&gitconfig_path);
6625 if (error)
6626 goto done;
6627 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6628 gitconfig_path);
6629 if (error != NULL)
6630 goto done;
6632 error = get_author(&author, repo);
6633 if (error)
6634 return error;
6637 * unveil(2) traverses exec(2); if an editor is used we have
6638 * to apply unveil after the log message has been written.
6640 if (logmsg == NULL || strlen(logmsg) == 0)
6641 error = get_editor(&editor);
6642 else
6643 error = apply_unveil(got_repo_get_path(repo), 0,
6644 got_worktree_get_root_path(worktree));
6645 if (error)
6646 goto done;
6648 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6649 if (error)
6650 goto done;
6652 cl_arg.editor = editor;
6653 cl_arg.cmdline_log = logmsg;
6654 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6655 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6656 if (!histedit_in_progress) {
6657 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6658 error = got_error(GOT_ERR_COMMIT_BRANCH);
6659 goto done;
6661 cl_arg.branch_name += 11;
6663 cl_arg.repo_path = got_repo_get_path(repo);
6664 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6665 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6666 print_status, NULL, repo);
6667 if (error) {
6668 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6669 cl_arg.logmsg_path != NULL)
6670 preserve_logmsg = 1;
6671 goto done;
6674 error = got_object_id_str(&id_str, id);
6675 if (error)
6676 goto done;
6677 printf("Created commit %s\n", id_str);
6678 done:
6679 if (preserve_logmsg) {
6680 fprintf(stderr, "%s: log message preserved in %s\n",
6681 getprogname(), cl_arg.logmsg_path);
6682 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6683 error == NULL)
6684 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6685 free(cl_arg.logmsg_path);
6686 if (repo)
6687 got_repo_close(repo);
6688 if (worktree)
6689 got_worktree_close(worktree);
6690 free(cwd);
6691 free(id_str);
6692 free(gitconfig_path);
6693 free(editor);
6694 free(author);
6695 return error;
6698 __dead static void
6699 usage_cherrypick(void)
6701 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6702 exit(1);
6705 static const struct got_error *
6706 cmd_cherrypick(int argc, char *argv[])
6708 const struct got_error *error = NULL;
6709 struct got_worktree *worktree = NULL;
6710 struct got_repository *repo = NULL;
6711 char *cwd = NULL, *commit_id_str = NULL;
6712 struct got_object_id *commit_id = NULL;
6713 struct got_commit_object *commit = NULL;
6714 struct got_object_qid *pid;
6715 struct got_reference *head_ref = NULL;
6716 int ch;
6717 struct got_update_progress_arg upa;
6719 while ((ch = getopt(argc, argv, "")) != -1) {
6720 switch (ch) {
6721 default:
6722 usage_cherrypick();
6723 /* NOTREACHED */
6727 argc -= optind;
6728 argv += optind;
6730 #ifndef PROFILE
6731 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6732 "unveil", NULL) == -1)
6733 err(1, "pledge");
6734 #endif
6735 if (argc != 1)
6736 usage_cherrypick();
6738 cwd = getcwd(NULL, 0);
6739 if (cwd == NULL) {
6740 error = got_error_from_errno("getcwd");
6741 goto done;
6743 error = got_worktree_open(&worktree, cwd);
6744 if (error) {
6745 if (error->code == GOT_ERR_NOT_WORKTREE)
6746 error = wrap_not_worktree_error(error, "cherrypick",
6747 cwd);
6748 goto done;
6751 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6752 NULL);
6753 if (error != NULL)
6754 goto done;
6756 error = apply_unveil(got_repo_get_path(repo), 0,
6757 got_worktree_get_root_path(worktree));
6758 if (error)
6759 goto done;
6761 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6762 GOT_OBJ_TYPE_COMMIT, repo);
6763 if (error != NULL) {
6764 struct got_reference *ref;
6765 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6766 goto done;
6767 error = got_ref_open(&ref, repo, argv[0], 0);
6768 if (error != NULL)
6769 goto done;
6770 error = got_ref_resolve(&commit_id, repo, ref);
6771 got_ref_close(ref);
6772 if (error != NULL)
6773 goto done;
6775 error = got_object_id_str(&commit_id_str, commit_id);
6776 if (error)
6777 goto done;
6779 error = got_ref_open(&head_ref, repo,
6780 got_worktree_get_head_ref_name(worktree), 0);
6781 if (error != NULL)
6782 goto done;
6784 error = check_same_branch(commit_id, head_ref, NULL, repo);
6785 if (error) {
6786 if (error->code != GOT_ERR_ANCESTRY)
6787 goto done;
6788 error = NULL;
6789 } else {
6790 error = got_error(GOT_ERR_SAME_BRANCH);
6791 goto done;
6794 error = got_object_open_as_commit(&commit, repo, commit_id);
6795 if (error)
6796 goto done;
6797 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6798 memset(&upa, 0, sizeof(upa));
6799 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6800 commit_id, repo, update_progress, &upa, check_cancelled,
6801 NULL);
6802 if (error != NULL)
6803 goto done;
6805 if (upa.did_something)
6806 printf("Merged commit %s\n", commit_id_str);
6807 print_update_progress_stats(&upa);
6808 done:
6809 if (commit)
6810 got_object_commit_close(commit);
6811 free(commit_id_str);
6812 if (head_ref)
6813 got_ref_close(head_ref);
6814 if (worktree)
6815 got_worktree_close(worktree);
6816 if (repo)
6817 got_repo_close(repo);
6818 return error;
6821 __dead static void
6822 usage_backout(void)
6824 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6825 exit(1);
6828 static const struct got_error *
6829 cmd_backout(int argc, char *argv[])
6831 const struct got_error *error = NULL;
6832 struct got_worktree *worktree = NULL;
6833 struct got_repository *repo = NULL;
6834 char *cwd = NULL, *commit_id_str = NULL;
6835 struct got_object_id *commit_id = NULL;
6836 struct got_commit_object *commit = NULL;
6837 struct got_object_qid *pid;
6838 struct got_reference *head_ref = NULL;
6839 int ch;
6840 struct got_update_progress_arg upa;
6842 while ((ch = getopt(argc, argv, "")) != -1) {
6843 switch (ch) {
6844 default:
6845 usage_backout();
6846 /* NOTREACHED */
6850 argc -= optind;
6851 argv += optind;
6853 #ifndef PROFILE
6854 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6855 "unveil", NULL) == -1)
6856 err(1, "pledge");
6857 #endif
6858 if (argc != 1)
6859 usage_backout();
6861 cwd = getcwd(NULL, 0);
6862 if (cwd == NULL) {
6863 error = got_error_from_errno("getcwd");
6864 goto done;
6866 error = got_worktree_open(&worktree, cwd);
6867 if (error) {
6868 if (error->code == GOT_ERR_NOT_WORKTREE)
6869 error = wrap_not_worktree_error(error, "backout", cwd);
6870 goto done;
6873 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6874 NULL);
6875 if (error != NULL)
6876 goto done;
6878 error = apply_unveil(got_repo_get_path(repo), 0,
6879 got_worktree_get_root_path(worktree));
6880 if (error)
6881 goto done;
6883 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6884 GOT_OBJ_TYPE_COMMIT, repo);
6885 if (error != NULL) {
6886 struct got_reference *ref;
6887 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6888 goto done;
6889 error = got_ref_open(&ref, repo, argv[0], 0);
6890 if (error != NULL)
6891 goto done;
6892 error = got_ref_resolve(&commit_id, repo, ref);
6893 got_ref_close(ref);
6894 if (error != NULL)
6895 goto done;
6897 error = got_object_id_str(&commit_id_str, commit_id);
6898 if (error)
6899 goto done;
6901 error = got_ref_open(&head_ref, repo,
6902 got_worktree_get_head_ref_name(worktree), 0);
6903 if (error != NULL)
6904 goto done;
6906 error = check_same_branch(commit_id, head_ref, NULL, repo);
6907 if (error)
6908 goto done;
6910 error = got_object_open_as_commit(&commit, repo, commit_id);
6911 if (error)
6912 goto done;
6913 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6914 if (pid == NULL) {
6915 error = got_error(GOT_ERR_ROOT_COMMIT);
6916 goto done;
6919 memset(&upa, 0, sizeof(upa));
6920 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6921 update_progress, &upa, check_cancelled, NULL);
6922 if (error != NULL)
6923 goto done;
6925 if (upa.did_something)
6926 printf("Backed out commit %s\n", commit_id_str);
6927 print_update_progress_stats(&upa);
6928 done:
6929 if (commit)
6930 got_object_commit_close(commit);
6931 free(commit_id_str);
6932 if (head_ref)
6933 got_ref_close(head_ref);
6934 if (worktree)
6935 got_worktree_close(worktree);
6936 if (repo)
6937 got_repo_close(repo);
6938 return error;
6941 __dead static void
6942 usage_rebase(void)
6944 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6945 getprogname());
6946 exit(1);
6949 void
6950 trim_logmsg(char *logmsg, int limit)
6952 char *nl;
6953 size_t len;
6955 len = strlen(logmsg);
6956 if (len > limit)
6957 len = limit;
6958 logmsg[len] = '\0';
6959 nl = strchr(logmsg, '\n');
6960 if (nl)
6961 *nl = '\0';
6964 static const struct got_error *
6965 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6967 const struct got_error *err;
6968 char *logmsg0 = NULL;
6969 const char *s;
6971 err = got_object_commit_get_logmsg(&logmsg0, commit);
6972 if (err)
6973 return err;
6975 s = logmsg0;
6976 while (isspace((unsigned char)s[0]))
6977 s++;
6979 *logmsg = strdup(s);
6980 if (*logmsg == NULL) {
6981 err = got_error_from_errno("strdup");
6982 goto done;
6985 trim_logmsg(*logmsg, limit);
6986 done:
6987 free(logmsg0);
6988 return err;
6991 static const struct got_error *
6992 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6994 const struct got_error *err;
6995 struct got_commit_object *commit = NULL;
6996 char *id_str = NULL, *logmsg = NULL;
6998 err = got_object_open_as_commit(&commit, repo, id);
6999 if (err)
7000 return err;
7002 err = got_object_id_str(&id_str, id);
7003 if (err)
7004 goto done;
7006 id_str[12] = '\0';
7008 err = get_short_logmsg(&logmsg, 42, commit);
7009 if (err)
7010 goto done;
7012 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7013 done:
7014 free(id_str);
7015 got_object_commit_close(commit);
7016 free(logmsg);
7017 return err;
7020 static const struct got_error *
7021 show_rebase_progress(struct got_commit_object *commit,
7022 struct got_object_id *old_id, struct got_object_id *new_id)
7024 const struct got_error *err;
7025 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7027 err = got_object_id_str(&old_id_str, old_id);
7028 if (err)
7029 goto done;
7031 if (new_id) {
7032 err = got_object_id_str(&new_id_str, new_id);
7033 if (err)
7034 goto done;
7037 old_id_str[12] = '\0';
7038 if (new_id_str)
7039 new_id_str[12] = '\0';
7041 err = get_short_logmsg(&logmsg, 42, commit);
7042 if (err)
7043 goto done;
7045 printf("%s -> %s: %s\n", old_id_str,
7046 new_id_str ? new_id_str : "no-op change", logmsg);
7047 done:
7048 free(old_id_str);
7049 free(new_id_str);
7050 free(logmsg);
7051 return err;
7054 static const struct got_error *
7055 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7056 struct got_reference *branch, struct got_reference *new_base_branch,
7057 struct got_reference *tmp_branch, struct got_repository *repo)
7059 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7060 return got_worktree_rebase_complete(worktree, fileindex,
7061 new_base_branch, tmp_branch, branch, repo);
7064 static const struct got_error *
7065 rebase_commit(struct got_pathlist_head *merged_paths,
7066 struct got_worktree *worktree, struct got_fileindex *fileindex,
7067 struct got_reference *tmp_branch,
7068 struct got_object_id *commit_id, struct got_repository *repo)
7070 const struct got_error *error;
7071 struct got_commit_object *commit;
7072 struct got_object_id *new_commit_id;
7074 error = got_object_open_as_commit(&commit, repo, commit_id);
7075 if (error)
7076 return error;
7078 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7079 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7080 if (error) {
7081 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7082 goto done;
7083 error = show_rebase_progress(commit, commit_id, NULL);
7084 } else {
7085 error = show_rebase_progress(commit, commit_id, new_commit_id);
7086 free(new_commit_id);
7088 done:
7089 got_object_commit_close(commit);
7090 return error;
7093 struct check_path_prefix_arg {
7094 const char *path_prefix;
7095 size_t len;
7096 int errcode;
7099 static const struct got_error *
7100 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7101 struct got_blob_object *blob2, struct got_object_id *id1,
7102 struct got_object_id *id2, const char *path1, const char *path2,
7103 mode_t mode1, mode_t mode2, struct got_repository *repo)
7105 struct check_path_prefix_arg *a = arg;
7107 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7108 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7109 return got_error(a->errcode);
7111 return NULL;
7114 static const struct got_error *
7115 check_path_prefix(struct got_object_id *parent_id,
7116 struct got_object_id *commit_id, const char *path_prefix,
7117 int errcode, struct got_repository *repo)
7119 const struct got_error *err;
7120 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7121 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7122 struct check_path_prefix_arg cpp_arg;
7124 if (got_path_is_root_dir(path_prefix))
7125 return NULL;
7127 err = got_object_open_as_commit(&commit, repo, commit_id);
7128 if (err)
7129 goto done;
7131 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7132 if (err)
7133 goto done;
7135 err = got_object_open_as_tree(&tree1, repo,
7136 got_object_commit_get_tree_id(parent_commit));
7137 if (err)
7138 goto done;
7140 err = got_object_open_as_tree(&tree2, repo,
7141 got_object_commit_get_tree_id(commit));
7142 if (err)
7143 goto done;
7145 cpp_arg.path_prefix = path_prefix;
7146 while (cpp_arg.path_prefix[0] == '/')
7147 cpp_arg.path_prefix++;
7148 cpp_arg.len = strlen(cpp_arg.path_prefix);
7149 cpp_arg.errcode = errcode;
7150 err = got_diff_tree(tree1, tree2, "", "", repo,
7151 check_path_prefix_in_diff, &cpp_arg, 0);
7152 done:
7153 if (tree1)
7154 got_object_tree_close(tree1);
7155 if (tree2)
7156 got_object_tree_close(tree2);
7157 if (commit)
7158 got_object_commit_close(commit);
7159 if (parent_commit)
7160 got_object_commit_close(parent_commit);
7161 return err;
7164 static const struct got_error *
7165 collect_commits(struct got_object_id_queue *commits,
7166 struct got_object_id *initial_commit_id,
7167 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7168 const char *path_prefix, int path_prefix_errcode,
7169 struct got_repository *repo)
7171 const struct got_error *err = NULL;
7172 struct got_commit_graph *graph = NULL;
7173 struct got_object_id *parent_id = NULL;
7174 struct got_object_qid *qid;
7175 struct got_object_id *commit_id = initial_commit_id;
7177 err = got_commit_graph_open(&graph, "/", 1);
7178 if (err)
7179 return err;
7181 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7182 check_cancelled, NULL);
7183 if (err)
7184 goto done;
7185 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7186 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7187 check_cancelled, NULL);
7188 if (err) {
7189 if (err->code == GOT_ERR_ITER_COMPLETED) {
7190 err = got_error_msg(GOT_ERR_ANCESTRY,
7191 "ran out of commits to rebase before "
7192 "youngest common ancestor commit has "
7193 "been reached?!?");
7195 goto done;
7196 } else {
7197 err = check_path_prefix(parent_id, commit_id,
7198 path_prefix, path_prefix_errcode, repo);
7199 if (err)
7200 goto done;
7202 err = got_object_qid_alloc(&qid, commit_id);
7203 if (err)
7204 goto done;
7205 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7206 commit_id = parent_id;
7209 done:
7210 got_commit_graph_close(graph);
7211 return err;
7214 static const struct got_error *
7215 cmd_rebase(int argc, char *argv[])
7217 const struct got_error *error = NULL;
7218 struct got_worktree *worktree = NULL;
7219 struct got_repository *repo = NULL;
7220 struct got_fileindex *fileindex = NULL;
7221 char *cwd = NULL;
7222 struct got_reference *branch = NULL;
7223 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7224 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7225 struct got_object_id *resume_commit_id = NULL;
7226 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7227 struct got_commit_object *commit = NULL;
7228 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7229 int histedit_in_progress = 0;
7230 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7231 struct got_object_id_queue commits;
7232 struct got_pathlist_head merged_paths;
7233 const struct got_object_id_queue *parent_ids;
7234 struct got_object_qid *qid, *pid;
7236 SIMPLEQ_INIT(&commits);
7237 TAILQ_INIT(&merged_paths);
7239 while ((ch = getopt(argc, argv, "ac")) != -1) {
7240 switch (ch) {
7241 case 'a':
7242 abort_rebase = 1;
7243 break;
7244 case 'c':
7245 continue_rebase = 1;
7246 break;
7247 default:
7248 usage_rebase();
7249 /* NOTREACHED */
7253 argc -= optind;
7254 argv += optind;
7256 #ifndef PROFILE
7257 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7258 "unveil", NULL) == -1)
7259 err(1, "pledge");
7260 #endif
7261 if (abort_rebase && continue_rebase)
7262 usage_rebase();
7263 else if (abort_rebase || continue_rebase) {
7264 if (argc != 0)
7265 usage_rebase();
7266 } else if (argc != 1)
7267 usage_rebase();
7269 cwd = getcwd(NULL, 0);
7270 if (cwd == NULL) {
7271 error = got_error_from_errno("getcwd");
7272 goto done;
7274 error = got_worktree_open(&worktree, cwd);
7275 if (error) {
7276 if (error->code == GOT_ERR_NOT_WORKTREE)
7277 error = wrap_not_worktree_error(error, "rebase", cwd);
7278 goto done;
7281 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7282 NULL);
7283 if (error != NULL)
7284 goto done;
7286 error = apply_unveil(got_repo_get_path(repo), 0,
7287 got_worktree_get_root_path(worktree));
7288 if (error)
7289 goto done;
7291 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7292 worktree);
7293 if (error)
7294 goto done;
7295 if (histedit_in_progress) {
7296 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7297 goto done;
7300 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7301 if (error)
7302 goto done;
7304 if (abort_rebase) {
7305 struct got_update_progress_arg upa;
7306 if (!rebase_in_progress) {
7307 error = got_error(GOT_ERR_NOT_REBASING);
7308 goto done;
7310 error = got_worktree_rebase_continue(&resume_commit_id,
7311 &new_base_branch, &tmp_branch, &branch, &fileindex,
7312 worktree, repo);
7313 if (error)
7314 goto done;
7315 printf("Switching work tree to %s\n",
7316 got_ref_get_symref_target(new_base_branch));
7317 memset(&upa, 0, sizeof(upa));
7318 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7319 new_base_branch, update_progress, &upa);
7320 if (error)
7321 goto done;
7322 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7323 print_update_progress_stats(&upa);
7324 goto done; /* nothing else to do */
7327 if (continue_rebase) {
7328 if (!rebase_in_progress) {
7329 error = got_error(GOT_ERR_NOT_REBASING);
7330 goto done;
7332 error = got_worktree_rebase_continue(&resume_commit_id,
7333 &new_base_branch, &tmp_branch, &branch, &fileindex,
7334 worktree, repo);
7335 if (error)
7336 goto done;
7338 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7339 resume_commit_id, repo);
7340 if (error)
7341 goto done;
7343 yca_id = got_object_id_dup(resume_commit_id);
7344 if (yca_id == NULL) {
7345 error = got_error_from_errno("got_object_id_dup");
7346 goto done;
7348 } else {
7349 error = got_ref_open(&branch, repo, argv[0], 0);
7350 if (error != NULL)
7351 goto done;
7354 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7355 if (error)
7356 goto done;
7358 if (!continue_rebase) {
7359 struct got_object_id *base_commit_id;
7361 base_commit_id = got_worktree_get_base_commit_id(worktree);
7362 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7363 base_commit_id, branch_head_commit_id, repo,
7364 check_cancelled, NULL);
7365 if (error)
7366 goto done;
7367 if (yca_id == NULL) {
7368 error = got_error_msg(GOT_ERR_ANCESTRY,
7369 "specified branch shares no common ancestry "
7370 "with work tree's branch");
7371 goto done;
7374 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7375 if (error) {
7376 if (error->code != GOT_ERR_ANCESTRY)
7377 goto done;
7378 error = NULL;
7379 } else {
7380 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7381 "specified branch resolves to a commit which "
7382 "is already contained in work tree's branch");
7383 goto done;
7385 error = got_worktree_rebase_prepare(&new_base_branch,
7386 &tmp_branch, &fileindex, worktree, branch, repo);
7387 if (error)
7388 goto done;
7391 commit_id = branch_head_commit_id;
7392 error = got_object_open_as_commit(&commit, repo, commit_id);
7393 if (error)
7394 goto done;
7396 parent_ids = got_object_commit_get_parent_ids(commit);
7397 pid = SIMPLEQ_FIRST(parent_ids);
7398 if (pid == NULL) {
7399 if (!continue_rebase) {
7400 struct got_update_progress_arg upa;
7401 memset(&upa, 0, sizeof(upa));
7402 error = got_worktree_rebase_abort(worktree, fileindex,
7403 repo, new_base_branch, update_progress, &upa);
7404 if (error)
7405 goto done;
7406 printf("Rebase of %s aborted\n",
7407 got_ref_get_name(branch));
7408 print_update_progress_stats(&upa);
7411 error = got_error(GOT_ERR_EMPTY_REBASE);
7412 goto done;
7414 error = collect_commits(&commits, commit_id, pid->id,
7415 yca_id, got_worktree_get_path_prefix(worktree),
7416 GOT_ERR_REBASE_PATH, repo);
7417 got_object_commit_close(commit);
7418 commit = NULL;
7419 if (error)
7420 goto done;
7422 if (SIMPLEQ_EMPTY(&commits)) {
7423 if (continue_rebase) {
7424 error = rebase_complete(worktree, fileindex,
7425 branch, new_base_branch, tmp_branch, repo);
7426 goto done;
7427 } else {
7428 /* Fast-forward the reference of the branch. */
7429 struct got_object_id *new_head_commit_id;
7430 char *id_str;
7431 error = got_ref_resolve(&new_head_commit_id, repo,
7432 new_base_branch);
7433 if (error)
7434 goto done;
7435 error = got_object_id_str(&id_str, new_head_commit_id);
7436 printf("Forwarding %s to commit %s\n",
7437 got_ref_get_name(branch), id_str);
7438 free(id_str);
7439 error = got_ref_change_ref(branch,
7440 new_head_commit_id);
7441 if (error)
7442 goto done;
7446 pid = NULL;
7447 SIMPLEQ_FOREACH(qid, &commits, entry) {
7448 struct got_update_progress_arg upa;
7450 commit_id = qid->id;
7451 parent_id = pid ? pid->id : yca_id;
7452 pid = qid;
7454 memset(&upa, 0, sizeof(upa));
7455 error = got_worktree_rebase_merge_files(&merged_paths,
7456 worktree, fileindex, parent_id, commit_id, repo,
7457 update_progress, &upa, check_cancelled, NULL);
7458 if (error)
7459 goto done;
7461 print_update_progress_stats(&upa);
7462 if (upa.conflicts > 0)
7463 rebase_status = GOT_STATUS_CONFLICT;
7465 if (rebase_status == GOT_STATUS_CONFLICT) {
7466 error = show_rebase_merge_conflict(qid->id, repo);
7467 if (error)
7468 goto done;
7469 got_worktree_rebase_pathlist_free(&merged_paths);
7470 break;
7473 error = rebase_commit(&merged_paths, worktree, fileindex,
7474 tmp_branch, commit_id, repo);
7475 got_worktree_rebase_pathlist_free(&merged_paths);
7476 if (error)
7477 goto done;
7480 if (rebase_status == GOT_STATUS_CONFLICT) {
7481 error = got_worktree_rebase_postpone(worktree, fileindex);
7482 if (error)
7483 goto done;
7484 error = got_error_msg(GOT_ERR_CONFLICTS,
7485 "conflicts must be resolved before rebasing can continue");
7486 } else
7487 error = rebase_complete(worktree, fileindex, branch,
7488 new_base_branch, tmp_branch, repo);
7489 done:
7490 got_object_id_queue_free(&commits);
7491 free(branch_head_commit_id);
7492 free(resume_commit_id);
7493 free(yca_id);
7494 if (commit)
7495 got_object_commit_close(commit);
7496 if (branch)
7497 got_ref_close(branch);
7498 if (new_base_branch)
7499 got_ref_close(new_base_branch);
7500 if (tmp_branch)
7501 got_ref_close(tmp_branch);
7502 if (worktree)
7503 got_worktree_close(worktree);
7504 if (repo)
7505 got_repo_close(repo);
7506 return error;
7509 __dead static void
7510 usage_histedit(void)
7512 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7513 getprogname());
7514 exit(1);
7517 #define GOT_HISTEDIT_PICK 'p'
7518 #define GOT_HISTEDIT_EDIT 'e'
7519 #define GOT_HISTEDIT_FOLD 'f'
7520 #define GOT_HISTEDIT_DROP 'd'
7521 #define GOT_HISTEDIT_MESG 'm'
7523 static struct got_histedit_cmd {
7524 unsigned char code;
7525 const char *name;
7526 const char *desc;
7527 } got_histedit_cmds[] = {
7528 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7529 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7530 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7531 "be used" },
7532 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7533 { GOT_HISTEDIT_MESG, "mesg",
7534 "single-line log message for commit above (open editor if empty)" },
7537 struct got_histedit_list_entry {
7538 TAILQ_ENTRY(got_histedit_list_entry) entry;
7539 struct got_object_id *commit_id;
7540 const struct got_histedit_cmd *cmd;
7541 char *logmsg;
7543 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7545 static const struct got_error *
7546 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7547 FILE *f, struct got_repository *repo)
7549 const struct got_error *err = NULL;
7550 char *logmsg = NULL, *id_str = NULL;
7551 struct got_commit_object *commit = NULL;
7552 int n;
7554 err = got_object_open_as_commit(&commit, repo, commit_id);
7555 if (err)
7556 goto done;
7558 err = get_short_logmsg(&logmsg, 34, commit);
7559 if (err)
7560 goto done;
7562 err = got_object_id_str(&id_str, commit_id);
7563 if (err)
7564 goto done;
7566 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7567 if (n < 0)
7568 err = got_ferror(f, GOT_ERR_IO);
7569 done:
7570 if (commit)
7571 got_object_commit_close(commit);
7572 free(id_str);
7573 free(logmsg);
7574 return err;
7577 static const struct got_error *
7578 histedit_write_commit_list(struct got_object_id_queue *commits,
7579 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7581 const struct got_error *err = NULL;
7582 struct got_object_qid *qid;
7584 if (SIMPLEQ_EMPTY(commits))
7585 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7587 SIMPLEQ_FOREACH(qid, commits, entry) {
7588 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7589 f, repo);
7590 if (err)
7591 break;
7592 if (edit_logmsg_only) {
7593 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7594 if (n < 0) {
7595 err = got_ferror(f, GOT_ERR_IO);
7596 break;
7601 return err;
7604 static const struct got_error *
7605 write_cmd_list(FILE *f, const char *branch_name,
7606 struct got_object_id_queue *commits)
7608 const struct got_error *err = NULL;
7609 int n, i;
7610 char *id_str;
7611 struct got_object_qid *qid;
7613 qid = SIMPLEQ_FIRST(commits);
7614 err = got_object_id_str(&id_str, qid->id);
7615 if (err)
7616 return err;
7618 n = fprintf(f,
7619 "# Editing the history of branch '%s' starting at\n"
7620 "# commit %s\n"
7621 "# Commits will be processed in order from top to "
7622 "bottom of this file.\n", branch_name, id_str);
7623 if (n < 0) {
7624 err = got_ferror(f, GOT_ERR_IO);
7625 goto done;
7628 n = fprintf(f, "# Available histedit commands:\n");
7629 if (n < 0) {
7630 err = got_ferror(f, GOT_ERR_IO);
7631 goto done;
7634 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7635 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7636 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7637 cmd->desc);
7638 if (n < 0) {
7639 err = got_ferror(f, GOT_ERR_IO);
7640 break;
7643 done:
7644 free(id_str);
7645 return err;
7648 static const struct got_error *
7649 histedit_syntax_error(int lineno)
7651 static char msg[42];
7652 int ret;
7654 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7655 lineno);
7656 if (ret == -1 || ret >= sizeof(msg))
7657 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7659 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7662 static const struct got_error *
7663 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7664 char *logmsg, struct got_repository *repo)
7666 const struct got_error *err;
7667 struct got_commit_object *folded_commit = NULL;
7668 char *id_str, *folded_logmsg = NULL;
7670 err = got_object_id_str(&id_str, hle->commit_id);
7671 if (err)
7672 return err;
7674 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7675 if (err)
7676 goto done;
7678 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7679 if (err)
7680 goto done;
7681 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7682 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7683 folded_logmsg) == -1) {
7684 err = got_error_from_errno("asprintf");
7686 done:
7687 if (folded_commit)
7688 got_object_commit_close(folded_commit);
7689 free(id_str);
7690 free(folded_logmsg);
7691 return err;
7694 static struct got_histedit_list_entry *
7695 get_folded_commits(struct got_histedit_list_entry *hle)
7697 struct got_histedit_list_entry *prev, *folded = NULL;
7699 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7700 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7701 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7702 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7703 folded = prev;
7704 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7707 return folded;
7710 static const struct got_error *
7711 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7712 struct got_repository *repo)
7714 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7715 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7716 const struct got_error *err = NULL;
7717 struct got_commit_object *commit = NULL;
7718 int fd;
7719 struct got_histedit_list_entry *folded = NULL;
7721 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7722 if (err)
7723 return err;
7725 folded = get_folded_commits(hle);
7726 if (folded) {
7727 while (folded != hle) {
7728 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7729 folded = TAILQ_NEXT(folded, entry);
7730 continue;
7732 err = append_folded_commit_msg(&new_msg, folded,
7733 logmsg, repo);
7734 if (err)
7735 goto done;
7736 free(logmsg);
7737 logmsg = new_msg;
7738 folded = TAILQ_NEXT(folded, entry);
7742 err = got_object_id_str(&id_str, hle->commit_id);
7743 if (err)
7744 goto done;
7745 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7746 if (err)
7747 goto done;
7748 if (asprintf(&new_msg,
7749 "%s\n# original log message of commit %s: %s",
7750 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7751 err = got_error_from_errno("asprintf");
7752 goto done;
7754 free(logmsg);
7755 logmsg = new_msg;
7757 err = got_object_id_str(&id_str, hle->commit_id);
7758 if (err)
7759 goto done;
7761 err = got_opentemp_named_fd(&logmsg_path, &fd,
7762 GOT_TMPDIR_STR "/got-logmsg");
7763 if (err)
7764 goto done;
7766 dprintf(fd, logmsg);
7767 close(fd);
7769 err = get_editor(&editor);
7770 if (err)
7771 goto done;
7773 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7774 if (err) {
7775 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7776 goto done;
7777 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7779 done:
7780 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7781 err = got_error_from_errno2("unlink", logmsg_path);
7782 free(logmsg_path);
7783 free(logmsg);
7784 free(orig_logmsg);
7785 free(editor);
7786 if (commit)
7787 got_object_commit_close(commit);
7788 return err;
7791 static const struct got_error *
7792 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7793 FILE *f, struct got_repository *repo)
7795 const struct got_error *err = NULL;
7796 char *line = NULL, *p, *end;
7797 size_t size;
7798 ssize_t len;
7799 int lineno = 0, i;
7800 const struct got_histedit_cmd *cmd;
7801 struct got_object_id *commit_id = NULL;
7802 struct got_histedit_list_entry *hle = NULL;
7804 for (;;) {
7805 len = getline(&line, &size, f);
7806 if (len == -1) {
7807 const struct got_error *getline_err;
7808 if (feof(f))
7809 break;
7810 getline_err = got_error_from_errno("getline");
7811 err = got_ferror(f, getline_err->code);
7812 break;
7814 lineno++;
7815 p = line;
7816 while (isspace((unsigned char)p[0]))
7817 p++;
7818 if (p[0] == '#' || p[0] == '\0') {
7819 free(line);
7820 line = NULL;
7821 continue;
7823 cmd = NULL;
7824 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7825 cmd = &got_histedit_cmds[i];
7826 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7827 isspace((unsigned char)p[strlen(cmd->name)])) {
7828 p += strlen(cmd->name);
7829 break;
7831 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7832 p++;
7833 break;
7836 if (i == nitems(got_histedit_cmds)) {
7837 err = histedit_syntax_error(lineno);
7838 break;
7840 while (isspace((unsigned char)p[0]))
7841 p++;
7842 if (cmd->code == GOT_HISTEDIT_MESG) {
7843 if (hle == NULL || hle->logmsg != NULL) {
7844 err = got_error(GOT_ERR_HISTEDIT_CMD);
7845 break;
7847 if (p[0] == '\0') {
7848 err = histedit_edit_logmsg(hle, repo);
7849 if (err)
7850 break;
7851 } else {
7852 hle->logmsg = strdup(p);
7853 if (hle->logmsg == NULL) {
7854 err = got_error_from_errno("strdup");
7855 break;
7858 free(line);
7859 line = NULL;
7860 continue;
7861 } else {
7862 end = p;
7863 while (end[0] && !isspace((unsigned char)end[0]))
7864 end++;
7865 *end = '\0';
7867 err = got_object_resolve_id_str(&commit_id, repo, p);
7868 if (err) {
7869 /* override error code */
7870 err = histedit_syntax_error(lineno);
7871 break;
7874 hle = malloc(sizeof(*hle));
7875 if (hle == NULL) {
7876 err = got_error_from_errno("malloc");
7877 break;
7879 hle->cmd = cmd;
7880 hle->commit_id = commit_id;
7881 hle->logmsg = NULL;
7882 commit_id = NULL;
7883 free(line);
7884 line = NULL;
7885 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7888 free(line);
7889 free(commit_id);
7890 return err;
7893 static const struct got_error *
7894 histedit_check_script(struct got_histedit_list *histedit_cmds,
7895 struct got_object_id_queue *commits, struct got_repository *repo)
7897 const struct got_error *err = NULL;
7898 struct got_object_qid *qid;
7899 struct got_histedit_list_entry *hle;
7900 static char msg[92];
7901 char *id_str;
7903 if (TAILQ_EMPTY(histedit_cmds))
7904 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7905 "histedit script contains no commands");
7906 if (SIMPLEQ_EMPTY(commits))
7907 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7909 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7910 struct got_histedit_list_entry *hle2;
7911 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7912 if (hle == hle2)
7913 continue;
7914 if (got_object_id_cmp(hle->commit_id,
7915 hle2->commit_id) != 0)
7916 continue;
7917 err = got_object_id_str(&id_str, hle->commit_id);
7918 if (err)
7919 return err;
7920 snprintf(msg, sizeof(msg), "commit %s is listed "
7921 "more than once in histedit script", id_str);
7922 free(id_str);
7923 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7927 SIMPLEQ_FOREACH(qid, commits, entry) {
7928 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7929 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7930 break;
7932 if (hle == NULL) {
7933 err = got_object_id_str(&id_str, qid->id);
7934 if (err)
7935 return err;
7936 snprintf(msg, sizeof(msg),
7937 "commit %s missing from histedit script", id_str);
7938 free(id_str);
7939 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7943 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7944 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7945 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7946 "last commit in histedit script cannot be folded");
7948 return NULL;
7951 static const struct got_error *
7952 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7953 const char *path, struct got_object_id_queue *commits,
7954 struct got_repository *repo)
7956 const struct got_error *err = NULL;
7957 char *editor;
7958 FILE *f = NULL;
7960 err = get_editor(&editor);
7961 if (err)
7962 return err;
7964 if (spawn_editor(editor, path) == -1) {
7965 err = got_error_from_errno("failed spawning editor");
7966 goto done;
7969 f = fopen(path, "r");
7970 if (f == NULL) {
7971 err = got_error_from_errno("fopen");
7972 goto done;
7974 err = histedit_parse_list(histedit_cmds, f, repo);
7975 if (err)
7976 goto done;
7978 err = histedit_check_script(histedit_cmds, commits, repo);
7979 done:
7980 if (f && fclose(f) != 0 && err == NULL)
7981 err = got_error_from_errno("fclose");
7982 free(editor);
7983 return err;
7986 static const struct got_error *
7987 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7988 struct got_object_id_queue *, const char *, const char *,
7989 struct got_repository *);
7991 static const struct got_error *
7992 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7993 struct got_object_id_queue *commits, const char *branch_name,
7994 int edit_logmsg_only, struct got_repository *repo)
7996 const struct got_error *err;
7997 FILE *f = NULL;
7998 char *path = NULL;
8000 err = got_opentemp_named(&path, &f, "got-histedit");
8001 if (err)
8002 return err;
8004 err = write_cmd_list(f, branch_name, commits);
8005 if (err)
8006 goto done;
8008 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8009 if (err)
8010 goto done;
8012 if (edit_logmsg_only) {
8013 rewind(f);
8014 err = histedit_parse_list(histedit_cmds, f, repo);
8015 } else {
8016 if (fclose(f) != 0) {
8017 err = got_error_from_errno("fclose");
8018 goto done;
8020 f = NULL;
8021 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8022 if (err) {
8023 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8024 err->code != GOT_ERR_HISTEDIT_CMD)
8025 goto done;
8026 err = histedit_edit_list_retry(histedit_cmds, err,
8027 commits, path, branch_name, repo);
8030 done:
8031 if (f && fclose(f) != 0 && err == NULL)
8032 err = got_error_from_errno("fclose");
8033 if (path && unlink(path) != 0 && err == NULL)
8034 err = got_error_from_errno2("unlink", path);
8035 free(path);
8036 return err;
8039 static const struct got_error *
8040 histedit_save_list(struct got_histedit_list *histedit_cmds,
8041 struct got_worktree *worktree, struct got_repository *repo)
8043 const struct got_error *err = NULL;
8044 char *path = NULL;
8045 FILE *f = NULL;
8046 struct got_histedit_list_entry *hle;
8047 struct got_commit_object *commit = NULL;
8049 err = got_worktree_get_histedit_script_path(&path, worktree);
8050 if (err)
8051 return err;
8053 f = fopen(path, "w");
8054 if (f == NULL) {
8055 err = got_error_from_errno2("fopen", path);
8056 goto done;
8058 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8059 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8060 repo);
8061 if (err)
8062 break;
8064 if (hle->logmsg) {
8065 int n = fprintf(f, "%c %s\n",
8066 GOT_HISTEDIT_MESG, hle->logmsg);
8067 if (n < 0) {
8068 err = got_ferror(f, GOT_ERR_IO);
8069 break;
8073 done:
8074 if (f && fclose(f) != 0 && err == NULL)
8075 err = got_error_from_errno("fclose");
8076 free(path);
8077 if (commit)
8078 got_object_commit_close(commit);
8079 return err;
8082 void
8083 histedit_free_list(struct got_histedit_list *histedit_cmds)
8085 struct got_histedit_list_entry *hle;
8087 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8088 TAILQ_REMOVE(histedit_cmds, hle, entry);
8089 free(hle);
8093 static const struct got_error *
8094 histedit_load_list(struct got_histedit_list *histedit_cmds,
8095 const char *path, struct got_repository *repo)
8097 const struct got_error *err = NULL;
8098 FILE *f = NULL;
8100 f = fopen(path, "r");
8101 if (f == NULL) {
8102 err = got_error_from_errno2("fopen", path);
8103 goto done;
8106 err = histedit_parse_list(histedit_cmds, f, repo);
8107 done:
8108 if (f && fclose(f) != 0 && err == NULL)
8109 err = got_error_from_errno("fclose");
8110 return err;
8113 static const struct got_error *
8114 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8115 const struct got_error *edit_err, struct got_object_id_queue *commits,
8116 const char *path, const char *branch_name, struct got_repository *repo)
8118 const struct got_error *err = NULL, *prev_err = edit_err;
8119 int resp = ' ';
8121 while (resp != 'c' && resp != 'r' && resp != 'a') {
8122 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8123 "or (a)bort: ", getprogname(), prev_err->msg);
8124 resp = getchar();
8125 if (resp == '\n')
8126 resp = getchar();
8127 if (resp == 'c') {
8128 histedit_free_list(histedit_cmds);
8129 err = histedit_run_editor(histedit_cmds, path, commits,
8130 repo);
8131 if (err) {
8132 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8133 err->code != GOT_ERR_HISTEDIT_CMD)
8134 break;
8135 prev_err = err;
8136 resp = ' ';
8137 continue;
8139 break;
8140 } else if (resp == 'r') {
8141 histedit_free_list(histedit_cmds);
8142 err = histedit_edit_script(histedit_cmds,
8143 commits, branch_name, 0, repo);
8144 if (err) {
8145 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8146 err->code != GOT_ERR_HISTEDIT_CMD)
8147 break;
8148 prev_err = err;
8149 resp = ' ';
8150 continue;
8152 break;
8153 } else if (resp == 'a') {
8154 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8155 break;
8156 } else
8157 printf("invalid response '%c'\n", resp);
8160 return err;
8163 static const struct got_error *
8164 histedit_complete(struct got_worktree *worktree,
8165 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8166 struct got_reference *branch, struct got_repository *repo)
8168 printf("Switching work tree to %s\n",
8169 got_ref_get_symref_target(branch));
8170 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8171 branch, repo);
8174 static const struct got_error *
8175 show_histedit_progress(struct got_commit_object *commit,
8176 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8178 const struct got_error *err;
8179 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8181 err = got_object_id_str(&old_id_str, hle->commit_id);
8182 if (err)
8183 goto done;
8185 if (new_id) {
8186 err = got_object_id_str(&new_id_str, new_id);
8187 if (err)
8188 goto done;
8191 old_id_str[12] = '\0';
8192 if (new_id_str)
8193 new_id_str[12] = '\0';
8195 if (hle->logmsg) {
8196 logmsg = strdup(hle->logmsg);
8197 if (logmsg == NULL) {
8198 err = got_error_from_errno("strdup");
8199 goto done;
8201 trim_logmsg(logmsg, 42);
8202 } else {
8203 err = get_short_logmsg(&logmsg, 42, commit);
8204 if (err)
8205 goto done;
8208 switch (hle->cmd->code) {
8209 case GOT_HISTEDIT_PICK:
8210 case GOT_HISTEDIT_EDIT:
8211 printf("%s -> %s: %s\n", old_id_str,
8212 new_id_str ? new_id_str : "no-op change", logmsg);
8213 break;
8214 case GOT_HISTEDIT_DROP:
8215 case GOT_HISTEDIT_FOLD:
8216 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8217 logmsg);
8218 break;
8219 default:
8220 break;
8222 done:
8223 free(old_id_str);
8224 free(new_id_str);
8225 return err;
8228 static const struct got_error *
8229 histedit_commit(struct got_pathlist_head *merged_paths,
8230 struct got_worktree *worktree, struct got_fileindex *fileindex,
8231 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8232 struct got_repository *repo)
8234 const struct got_error *err;
8235 struct got_commit_object *commit;
8236 struct got_object_id *new_commit_id;
8238 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8239 && hle->logmsg == NULL) {
8240 err = histedit_edit_logmsg(hle, repo);
8241 if (err)
8242 return err;
8245 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8246 if (err)
8247 return err;
8249 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8250 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8251 hle->logmsg, repo);
8252 if (err) {
8253 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8254 goto done;
8255 err = show_histedit_progress(commit, hle, NULL);
8256 } else {
8257 err = show_histedit_progress(commit, hle, new_commit_id);
8258 free(new_commit_id);
8260 done:
8261 got_object_commit_close(commit);
8262 return err;
8265 static const struct got_error *
8266 histedit_skip_commit(struct got_histedit_list_entry *hle,
8267 struct got_worktree *worktree, struct got_repository *repo)
8269 const struct got_error *error;
8270 struct got_commit_object *commit;
8272 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8273 repo);
8274 if (error)
8275 return error;
8277 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8278 if (error)
8279 return error;
8281 error = show_histedit_progress(commit, hle, NULL);
8282 got_object_commit_close(commit);
8283 return error;
8286 static const struct got_error *
8287 check_local_changes(void *arg, unsigned char status,
8288 unsigned char staged_status, const char *path,
8289 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8290 struct got_object_id *commit_id, int dirfd, const char *de_name)
8292 int *have_local_changes = arg;
8294 switch (status) {
8295 case GOT_STATUS_ADD:
8296 case GOT_STATUS_DELETE:
8297 case GOT_STATUS_MODIFY:
8298 case GOT_STATUS_CONFLICT:
8299 *have_local_changes = 1;
8300 return got_error(GOT_ERR_CANCELLED);
8301 default:
8302 break;
8305 switch (staged_status) {
8306 case GOT_STATUS_ADD:
8307 case GOT_STATUS_DELETE:
8308 case GOT_STATUS_MODIFY:
8309 *have_local_changes = 1;
8310 return got_error(GOT_ERR_CANCELLED);
8311 default:
8312 break;
8315 return NULL;
8318 static const struct got_error *
8319 cmd_histedit(int argc, char *argv[])
8321 const struct got_error *error = NULL;
8322 struct got_worktree *worktree = NULL;
8323 struct got_fileindex *fileindex = NULL;
8324 struct got_repository *repo = NULL;
8325 char *cwd = NULL;
8326 struct got_reference *branch = NULL;
8327 struct got_reference *tmp_branch = NULL;
8328 struct got_object_id *resume_commit_id = NULL;
8329 struct got_object_id *base_commit_id = NULL;
8330 struct got_object_id *head_commit_id = NULL;
8331 struct got_commit_object *commit = NULL;
8332 int ch, rebase_in_progress = 0;
8333 struct got_update_progress_arg upa;
8334 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8335 int edit_logmsg_only = 0;
8336 const char *edit_script_path = NULL;
8337 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8338 struct got_object_id_queue commits;
8339 struct got_pathlist_head merged_paths;
8340 const struct got_object_id_queue *parent_ids;
8341 struct got_object_qid *pid;
8342 struct got_histedit_list histedit_cmds;
8343 struct got_histedit_list_entry *hle;
8345 SIMPLEQ_INIT(&commits);
8346 TAILQ_INIT(&histedit_cmds);
8347 TAILQ_INIT(&merged_paths);
8348 memset(&upa, 0, sizeof(upa));
8350 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8351 switch (ch) {
8352 case 'a':
8353 abort_edit = 1;
8354 break;
8355 case 'c':
8356 continue_edit = 1;
8357 break;
8358 case 'F':
8359 edit_script_path = optarg;
8360 break;
8361 case 'm':
8362 edit_logmsg_only = 1;
8363 break;
8364 default:
8365 usage_histedit();
8366 /* NOTREACHED */
8370 argc -= optind;
8371 argv += optind;
8373 #ifndef PROFILE
8374 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8375 "unveil", NULL) == -1)
8376 err(1, "pledge");
8377 #endif
8378 if (abort_edit && continue_edit)
8379 errx(1, "histedit's -a and -c options are mutually exclusive");
8380 if (edit_script_path && edit_logmsg_only)
8381 errx(1, "histedit's -F and -m options are mutually exclusive");
8382 if (abort_edit && edit_logmsg_only)
8383 errx(1, "histedit's -a and -m options are mutually exclusive");
8384 if (continue_edit && edit_logmsg_only)
8385 errx(1, "histedit's -c and -m options are mutually exclusive");
8386 if (argc != 0)
8387 usage_histedit();
8390 * This command cannot apply unveil(2) in all cases because the
8391 * user may choose to run an editor to edit the histedit script
8392 * and to edit individual commit log messages.
8393 * unveil(2) traverses exec(2); if an editor is used we have to
8394 * apply unveil after edit script and log messages have been written.
8395 * XXX TODO: Make use of unveil(2) where possible.
8398 cwd = getcwd(NULL, 0);
8399 if (cwd == NULL) {
8400 error = got_error_from_errno("getcwd");
8401 goto done;
8403 error = got_worktree_open(&worktree, cwd);
8404 if (error) {
8405 if (error->code == GOT_ERR_NOT_WORKTREE)
8406 error = wrap_not_worktree_error(error, "histedit", cwd);
8407 goto done;
8410 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8411 NULL);
8412 if (error != NULL)
8413 goto done;
8415 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8416 if (error)
8417 goto done;
8418 if (rebase_in_progress) {
8419 error = got_error(GOT_ERR_REBASING);
8420 goto done;
8423 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8424 if (error)
8425 goto done;
8427 if (edit_in_progress && edit_logmsg_only) {
8428 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8429 "histedit operation is in progress in this "
8430 "work tree and must be continued or aborted "
8431 "before the -m option can be used");
8432 goto done;
8435 if (edit_in_progress && abort_edit) {
8436 error = got_worktree_histedit_continue(&resume_commit_id,
8437 &tmp_branch, &branch, &base_commit_id, &fileindex,
8438 worktree, repo);
8439 if (error)
8440 goto done;
8441 printf("Switching work tree to %s\n",
8442 got_ref_get_symref_target(branch));
8443 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8444 branch, base_commit_id, update_progress, &upa);
8445 if (error)
8446 goto done;
8447 printf("Histedit of %s aborted\n",
8448 got_ref_get_symref_target(branch));
8449 print_update_progress_stats(&upa);
8450 goto done; /* nothing else to do */
8451 } else if (abort_edit) {
8452 error = got_error(GOT_ERR_NOT_HISTEDIT);
8453 goto done;
8456 if (continue_edit) {
8457 char *path;
8459 if (!edit_in_progress) {
8460 error = got_error(GOT_ERR_NOT_HISTEDIT);
8461 goto done;
8464 error = got_worktree_get_histedit_script_path(&path, worktree);
8465 if (error)
8466 goto done;
8468 error = histedit_load_list(&histedit_cmds, path, repo);
8469 free(path);
8470 if (error)
8471 goto done;
8473 error = got_worktree_histedit_continue(&resume_commit_id,
8474 &tmp_branch, &branch, &base_commit_id, &fileindex,
8475 worktree, repo);
8476 if (error)
8477 goto done;
8479 error = got_ref_resolve(&head_commit_id, repo, branch);
8480 if (error)
8481 goto done;
8483 error = got_object_open_as_commit(&commit, repo,
8484 head_commit_id);
8485 if (error)
8486 goto done;
8487 parent_ids = got_object_commit_get_parent_ids(commit);
8488 pid = SIMPLEQ_FIRST(parent_ids);
8489 if (pid == NULL) {
8490 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8491 goto done;
8493 error = collect_commits(&commits, head_commit_id, pid->id,
8494 base_commit_id, got_worktree_get_path_prefix(worktree),
8495 GOT_ERR_HISTEDIT_PATH, repo);
8496 got_object_commit_close(commit);
8497 commit = NULL;
8498 if (error)
8499 goto done;
8500 } else {
8501 if (edit_in_progress) {
8502 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8503 goto done;
8506 error = got_ref_open(&branch, repo,
8507 got_worktree_get_head_ref_name(worktree), 0);
8508 if (error != NULL)
8509 goto done;
8511 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8512 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8513 "will not edit commit history of a branch outside "
8514 "the \"refs/heads/\" reference namespace");
8515 goto done;
8518 error = got_ref_resolve(&head_commit_id, repo, branch);
8519 got_ref_close(branch);
8520 branch = NULL;
8521 if (error)
8522 goto done;
8524 error = got_object_open_as_commit(&commit, repo,
8525 head_commit_id);
8526 if (error)
8527 goto done;
8528 parent_ids = got_object_commit_get_parent_ids(commit);
8529 pid = SIMPLEQ_FIRST(parent_ids);
8530 if (pid == NULL) {
8531 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8532 goto done;
8534 error = collect_commits(&commits, head_commit_id, pid->id,
8535 got_worktree_get_base_commit_id(worktree),
8536 got_worktree_get_path_prefix(worktree),
8537 GOT_ERR_HISTEDIT_PATH, repo);
8538 got_object_commit_close(commit);
8539 commit = NULL;
8540 if (error)
8541 goto done;
8543 if (SIMPLEQ_EMPTY(&commits)) {
8544 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8545 goto done;
8548 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8549 &base_commit_id, &fileindex, worktree, repo);
8550 if (error)
8551 goto done;
8553 if (edit_script_path) {
8554 error = histedit_load_list(&histedit_cmds,
8555 edit_script_path, repo);
8556 if (error) {
8557 got_worktree_histedit_abort(worktree, fileindex,
8558 repo, branch, base_commit_id,
8559 update_progress, &upa);
8560 print_update_progress_stats(&upa);
8561 goto done;
8563 } else {
8564 const char *branch_name;
8565 branch_name = got_ref_get_symref_target(branch);
8566 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8567 branch_name += 11;
8568 error = histedit_edit_script(&histedit_cmds, &commits,
8569 branch_name, edit_logmsg_only, repo);
8570 if (error) {
8571 got_worktree_histedit_abort(worktree, fileindex,
8572 repo, branch, base_commit_id,
8573 update_progress, &upa);
8574 print_update_progress_stats(&upa);
8575 goto done;
8580 error = histedit_save_list(&histedit_cmds, worktree,
8581 repo);
8582 if (error) {
8583 got_worktree_histedit_abort(worktree, fileindex,
8584 repo, branch, base_commit_id,
8585 update_progress, &upa);
8586 print_update_progress_stats(&upa);
8587 goto done;
8592 error = histedit_check_script(&histedit_cmds, &commits, repo);
8593 if (error)
8594 goto done;
8596 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8597 if (resume_commit_id) {
8598 if (got_object_id_cmp(hle->commit_id,
8599 resume_commit_id) != 0)
8600 continue;
8602 resume_commit_id = NULL;
8603 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8604 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8605 error = histedit_skip_commit(hle, worktree,
8606 repo);
8607 if (error)
8608 goto done;
8609 } else {
8610 struct got_pathlist_head paths;
8611 int have_changes = 0;
8613 TAILQ_INIT(&paths);
8614 error = got_pathlist_append(&paths, "", NULL);
8615 if (error)
8616 goto done;
8617 error = got_worktree_status(worktree, &paths,
8618 repo, check_local_changes, &have_changes,
8619 check_cancelled, NULL);
8620 got_pathlist_free(&paths);
8621 if (error) {
8622 if (error->code != GOT_ERR_CANCELLED)
8623 goto done;
8624 if (sigint_received || sigpipe_received)
8625 goto done;
8627 if (have_changes) {
8628 error = histedit_commit(NULL, worktree,
8629 fileindex, tmp_branch, hle, repo);
8630 if (error)
8631 goto done;
8632 } else {
8633 error = got_object_open_as_commit(
8634 &commit, repo, hle->commit_id);
8635 if (error)
8636 goto done;
8637 error = show_histedit_progress(commit,
8638 hle, NULL);
8639 got_object_commit_close(commit);
8640 commit = NULL;
8641 if (error)
8642 goto done;
8645 continue;
8648 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8649 error = histedit_skip_commit(hle, worktree, repo);
8650 if (error)
8651 goto done;
8652 continue;
8655 error = got_object_open_as_commit(&commit, repo,
8656 hle->commit_id);
8657 if (error)
8658 goto done;
8659 parent_ids = got_object_commit_get_parent_ids(commit);
8660 pid = SIMPLEQ_FIRST(parent_ids);
8662 error = got_worktree_histedit_merge_files(&merged_paths,
8663 worktree, fileindex, pid->id, hle->commit_id, repo,
8664 update_progress, &upa, check_cancelled, NULL);
8665 if (error)
8666 goto done;
8667 got_object_commit_close(commit);
8668 commit = NULL;
8670 print_update_progress_stats(&upa);
8671 if (upa.conflicts > 0)
8672 rebase_status = GOT_STATUS_CONFLICT;
8674 if (rebase_status == GOT_STATUS_CONFLICT) {
8675 error = show_rebase_merge_conflict(hle->commit_id,
8676 repo);
8677 if (error)
8678 goto done;
8679 got_worktree_rebase_pathlist_free(&merged_paths);
8680 break;
8683 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8684 char *id_str;
8685 error = got_object_id_str(&id_str, hle->commit_id);
8686 if (error)
8687 goto done;
8688 printf("Stopping histedit for amending commit %s\n",
8689 id_str);
8690 free(id_str);
8691 got_worktree_rebase_pathlist_free(&merged_paths);
8692 error = got_worktree_histedit_postpone(worktree,
8693 fileindex);
8694 goto done;
8697 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8698 error = histedit_skip_commit(hle, worktree, repo);
8699 if (error)
8700 goto done;
8701 continue;
8704 error = histedit_commit(&merged_paths, worktree, fileindex,
8705 tmp_branch, hle, repo);
8706 got_worktree_rebase_pathlist_free(&merged_paths);
8707 if (error)
8708 goto done;
8711 if (rebase_status == GOT_STATUS_CONFLICT) {
8712 error = got_worktree_histedit_postpone(worktree, fileindex);
8713 if (error)
8714 goto done;
8715 error = got_error_msg(GOT_ERR_CONFLICTS,
8716 "conflicts must be resolved before histedit can continue");
8717 } else
8718 error = histedit_complete(worktree, fileindex, tmp_branch,
8719 branch, repo);
8720 done:
8721 got_object_id_queue_free(&commits);
8722 histedit_free_list(&histedit_cmds);
8723 free(head_commit_id);
8724 free(base_commit_id);
8725 free(resume_commit_id);
8726 if (commit)
8727 got_object_commit_close(commit);
8728 if (branch)
8729 got_ref_close(branch);
8730 if (tmp_branch)
8731 got_ref_close(tmp_branch);
8732 if (worktree)
8733 got_worktree_close(worktree);
8734 if (repo)
8735 got_repo_close(repo);
8736 return error;
8739 __dead static void
8740 usage_integrate(void)
8742 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8743 exit(1);
8746 static const struct got_error *
8747 cmd_integrate(int argc, char *argv[])
8749 const struct got_error *error = NULL;
8750 struct got_repository *repo = NULL;
8751 struct got_worktree *worktree = NULL;
8752 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8753 const char *branch_arg = NULL;
8754 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8755 struct got_fileindex *fileindex = NULL;
8756 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8757 int ch;
8758 struct got_update_progress_arg upa;
8760 while ((ch = getopt(argc, argv, "")) != -1) {
8761 switch (ch) {
8762 default:
8763 usage_integrate();
8764 /* NOTREACHED */
8768 argc -= optind;
8769 argv += optind;
8771 if (argc != 1)
8772 usage_integrate();
8773 branch_arg = argv[0];
8775 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8776 "unveil", NULL) == -1)
8777 err(1, "pledge");
8779 cwd = getcwd(NULL, 0);
8780 if (cwd == NULL) {
8781 error = got_error_from_errno("getcwd");
8782 goto done;
8785 error = got_worktree_open(&worktree, cwd);
8786 if (error) {
8787 if (error->code == GOT_ERR_NOT_WORKTREE)
8788 error = wrap_not_worktree_error(error, "integrate",
8789 cwd);
8790 goto done;
8793 error = check_rebase_or_histedit_in_progress(worktree);
8794 if (error)
8795 goto done;
8797 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8798 NULL);
8799 if (error != NULL)
8800 goto done;
8802 error = apply_unveil(got_repo_get_path(repo), 0,
8803 got_worktree_get_root_path(worktree));
8804 if (error)
8805 goto done;
8807 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8808 error = got_error_from_errno("asprintf");
8809 goto done;
8812 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8813 &base_branch_ref, worktree, refname, repo);
8814 if (error)
8815 goto done;
8817 refname = strdup(got_ref_get_name(branch_ref));
8818 if (refname == NULL) {
8819 error = got_error_from_errno("strdup");
8820 got_worktree_integrate_abort(worktree, fileindex, repo,
8821 branch_ref, base_branch_ref);
8822 goto done;
8824 base_refname = strdup(got_ref_get_name(base_branch_ref));
8825 if (base_refname == NULL) {
8826 error = got_error_from_errno("strdup");
8827 got_worktree_integrate_abort(worktree, fileindex, repo,
8828 branch_ref, base_branch_ref);
8829 goto done;
8832 error = got_ref_resolve(&commit_id, repo, branch_ref);
8833 if (error)
8834 goto done;
8836 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8837 if (error)
8838 goto done;
8840 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8841 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8842 "specified branch has already been integrated");
8843 got_worktree_integrate_abort(worktree, fileindex, repo,
8844 branch_ref, base_branch_ref);
8845 goto done;
8848 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8849 if (error) {
8850 if (error->code == GOT_ERR_ANCESTRY)
8851 error = got_error(GOT_ERR_REBASE_REQUIRED);
8852 got_worktree_integrate_abort(worktree, fileindex, repo,
8853 branch_ref, base_branch_ref);
8854 goto done;
8857 memset(&upa, 0, sizeof(upa));
8858 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8859 branch_ref, base_branch_ref, update_progress, &upa,
8860 check_cancelled, NULL);
8861 if (error)
8862 goto done;
8864 printf("Integrated %s into %s\n", refname, base_refname);
8865 print_update_progress_stats(&upa);
8866 done:
8867 if (repo)
8868 got_repo_close(repo);
8869 if (worktree)
8870 got_worktree_close(worktree);
8871 free(cwd);
8872 free(base_commit_id);
8873 free(commit_id);
8874 free(refname);
8875 free(base_refname);
8876 return error;
8879 __dead static void
8880 usage_stage(void)
8882 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8883 "[-S] [file-path ...]\n",
8884 getprogname());
8885 exit(1);
8888 static const struct got_error *
8889 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8890 const char *path, struct got_object_id *blob_id,
8891 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8892 int dirfd, const char *de_name)
8894 const struct got_error *err = NULL;
8895 char *id_str = NULL;
8897 if (staged_status != GOT_STATUS_ADD &&
8898 staged_status != GOT_STATUS_MODIFY &&
8899 staged_status != GOT_STATUS_DELETE)
8900 return NULL;
8902 if (staged_status == GOT_STATUS_ADD ||
8903 staged_status == GOT_STATUS_MODIFY)
8904 err = got_object_id_str(&id_str, staged_blob_id);
8905 else
8906 err = got_object_id_str(&id_str, blob_id);
8907 if (err)
8908 return err;
8910 printf("%s %c %s\n", id_str, staged_status, path);
8911 free(id_str);
8912 return NULL;
8915 static const struct got_error *
8916 cmd_stage(int argc, char *argv[])
8918 const struct got_error *error = NULL;
8919 struct got_repository *repo = NULL;
8920 struct got_worktree *worktree = NULL;
8921 char *cwd = NULL;
8922 struct got_pathlist_head paths;
8923 struct got_pathlist_entry *pe;
8924 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8925 FILE *patch_script_file = NULL;
8926 const char *patch_script_path = NULL;
8927 struct choose_patch_arg cpa;
8929 TAILQ_INIT(&paths);
8931 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
8932 switch (ch) {
8933 case 'l':
8934 list_stage = 1;
8935 break;
8936 case 'p':
8937 pflag = 1;
8938 break;
8939 case 'F':
8940 patch_script_path = optarg;
8941 break;
8942 case 'S':
8943 allow_bad_symlinks = 1;
8944 break;
8945 default:
8946 usage_stage();
8947 /* NOTREACHED */
8951 argc -= optind;
8952 argv += optind;
8954 #ifndef PROFILE
8955 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8956 "unveil", NULL) == -1)
8957 err(1, "pledge");
8958 #endif
8959 if (list_stage && (pflag || patch_script_path))
8960 errx(1, "-l option cannot be used with other options");
8961 if (patch_script_path && !pflag)
8962 errx(1, "-F option can only be used together with -p option");
8964 cwd = getcwd(NULL, 0);
8965 if (cwd == NULL) {
8966 error = got_error_from_errno("getcwd");
8967 goto done;
8970 error = got_worktree_open(&worktree, cwd);
8971 if (error) {
8972 if (error->code == GOT_ERR_NOT_WORKTREE)
8973 error = wrap_not_worktree_error(error, "stage", cwd);
8974 goto done;
8977 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8978 NULL);
8979 if (error != NULL)
8980 goto done;
8982 if (patch_script_path) {
8983 patch_script_file = fopen(patch_script_path, "r");
8984 if (patch_script_file == NULL) {
8985 error = got_error_from_errno2("fopen",
8986 patch_script_path);
8987 goto done;
8990 error = apply_unveil(got_repo_get_path(repo), 0,
8991 got_worktree_get_root_path(worktree));
8992 if (error)
8993 goto done;
8995 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8996 if (error)
8997 goto done;
8999 if (list_stage)
9000 error = got_worktree_status(worktree, &paths, repo,
9001 print_stage, NULL, check_cancelled, NULL);
9002 else {
9003 cpa.patch_script_file = patch_script_file;
9004 cpa.action = "stage";
9005 error = got_worktree_stage(worktree, &paths,
9006 pflag ? NULL : print_status, NULL,
9007 pflag ? choose_patch : NULL, &cpa,
9008 allow_bad_symlinks, repo);
9010 done:
9011 if (patch_script_file && fclose(patch_script_file) == EOF &&
9012 error == NULL)
9013 error = got_error_from_errno2("fclose", patch_script_path);
9014 if (repo)
9015 got_repo_close(repo);
9016 if (worktree)
9017 got_worktree_close(worktree);
9018 TAILQ_FOREACH(pe, &paths, entry)
9019 free((char *)pe->path);
9020 got_pathlist_free(&paths);
9021 free(cwd);
9022 return error;
9025 __dead static void
9026 usage_unstage(void)
9028 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9029 "[file-path ...]\n",
9030 getprogname());
9031 exit(1);
9035 static const struct got_error *
9036 cmd_unstage(int argc, char *argv[])
9038 const struct got_error *error = NULL;
9039 struct got_repository *repo = NULL;
9040 struct got_worktree *worktree = NULL;
9041 char *cwd = NULL;
9042 struct got_pathlist_head paths;
9043 struct got_pathlist_entry *pe;
9044 int ch, pflag = 0;
9045 struct got_update_progress_arg upa;
9046 FILE *patch_script_file = NULL;
9047 const char *patch_script_path = NULL;
9048 struct choose_patch_arg cpa;
9050 TAILQ_INIT(&paths);
9052 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9053 switch (ch) {
9054 case 'p':
9055 pflag = 1;
9056 break;
9057 case 'F':
9058 patch_script_path = optarg;
9059 break;
9060 default:
9061 usage_unstage();
9062 /* NOTREACHED */
9066 argc -= optind;
9067 argv += optind;
9069 #ifndef PROFILE
9070 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9071 "unveil", NULL) == -1)
9072 err(1, "pledge");
9073 #endif
9074 if (patch_script_path && !pflag)
9075 errx(1, "-F option can only be used together with -p option");
9077 cwd = getcwd(NULL, 0);
9078 if (cwd == NULL) {
9079 error = got_error_from_errno("getcwd");
9080 goto done;
9083 error = got_worktree_open(&worktree, cwd);
9084 if (error) {
9085 if (error->code == GOT_ERR_NOT_WORKTREE)
9086 error = wrap_not_worktree_error(error, "unstage", cwd);
9087 goto done;
9090 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9091 NULL);
9092 if (error != NULL)
9093 goto done;
9095 if (patch_script_path) {
9096 patch_script_file = fopen(patch_script_path, "r");
9097 if (patch_script_file == NULL) {
9098 error = got_error_from_errno2("fopen",
9099 patch_script_path);
9100 goto done;
9104 error = apply_unveil(got_repo_get_path(repo), 0,
9105 got_worktree_get_root_path(worktree));
9106 if (error)
9107 goto done;
9109 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9110 if (error)
9111 goto done;
9113 cpa.patch_script_file = patch_script_file;
9114 cpa.action = "unstage";
9115 memset(&upa, 0, sizeof(upa));
9116 error = got_worktree_unstage(worktree, &paths, update_progress,
9117 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9118 if (!error)
9119 print_update_progress_stats(&upa);
9120 done:
9121 if (patch_script_file && fclose(patch_script_file) == EOF &&
9122 error == NULL)
9123 error = got_error_from_errno2("fclose", patch_script_path);
9124 if (repo)
9125 got_repo_close(repo);
9126 if (worktree)
9127 got_worktree_close(worktree);
9128 TAILQ_FOREACH(pe, &paths, entry)
9129 free((char *)pe->path);
9130 got_pathlist_free(&paths);
9131 free(cwd);
9132 return error;
9135 __dead static void
9136 usage_cat(void)
9138 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9139 "arg1 [arg2 ...]\n", getprogname());
9140 exit(1);
9143 static const struct got_error *
9144 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9146 const struct got_error *err;
9147 struct got_blob_object *blob;
9149 err = got_object_open_as_blob(&blob, repo, id, 8192);
9150 if (err)
9151 return err;
9153 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9154 got_object_blob_close(blob);
9155 return err;
9158 static const struct got_error *
9159 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9161 const struct got_error *err;
9162 struct got_tree_object *tree;
9163 int nentries, i;
9165 err = got_object_open_as_tree(&tree, repo, id);
9166 if (err)
9167 return err;
9169 nentries = got_object_tree_get_nentries(tree);
9170 for (i = 0; i < nentries; i++) {
9171 struct got_tree_entry *te;
9172 char *id_str;
9173 if (sigint_received || sigpipe_received)
9174 break;
9175 te = got_object_tree_get_entry(tree, i);
9176 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9177 if (err)
9178 break;
9179 fprintf(outfile, "%s %.7o %s\n", id_str,
9180 got_tree_entry_get_mode(te),
9181 got_tree_entry_get_name(te));
9182 free(id_str);
9185 got_object_tree_close(tree);
9186 return err;
9189 static const struct got_error *
9190 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9192 const struct got_error *err;
9193 struct got_commit_object *commit;
9194 const struct got_object_id_queue *parent_ids;
9195 struct got_object_qid *pid;
9196 char *id_str = NULL;
9197 const char *logmsg = NULL;
9199 err = got_object_open_as_commit(&commit, repo, id);
9200 if (err)
9201 return err;
9203 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9204 if (err)
9205 goto done;
9207 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9208 parent_ids = got_object_commit_get_parent_ids(commit);
9209 fprintf(outfile, "numparents %d\n",
9210 got_object_commit_get_nparents(commit));
9211 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9212 char *pid_str;
9213 err = got_object_id_str(&pid_str, pid->id);
9214 if (err)
9215 goto done;
9216 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9217 free(pid_str);
9219 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9220 got_object_commit_get_author(commit),
9221 got_object_commit_get_author_time(commit));
9223 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9224 got_object_commit_get_author(commit),
9225 got_object_commit_get_committer_time(commit));
9227 logmsg = got_object_commit_get_logmsg_raw(commit);
9228 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9229 fprintf(outfile, "%s", logmsg);
9230 done:
9231 free(id_str);
9232 got_object_commit_close(commit);
9233 return err;
9236 static const struct got_error *
9237 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9239 const struct got_error *err;
9240 struct got_tag_object *tag;
9241 char *id_str = NULL;
9242 const char *tagmsg = NULL;
9244 err = got_object_open_as_tag(&tag, repo, id);
9245 if (err)
9246 return err;
9248 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9249 if (err)
9250 goto done;
9252 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9254 switch (got_object_tag_get_object_type(tag)) {
9255 case GOT_OBJ_TYPE_BLOB:
9256 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9257 GOT_OBJ_LABEL_BLOB);
9258 break;
9259 case GOT_OBJ_TYPE_TREE:
9260 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9261 GOT_OBJ_LABEL_TREE);
9262 break;
9263 case GOT_OBJ_TYPE_COMMIT:
9264 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9265 GOT_OBJ_LABEL_COMMIT);
9266 break;
9267 case GOT_OBJ_TYPE_TAG:
9268 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9269 GOT_OBJ_LABEL_TAG);
9270 break;
9271 default:
9272 break;
9275 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9276 got_object_tag_get_name(tag));
9278 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9279 got_object_tag_get_tagger(tag),
9280 got_object_tag_get_tagger_time(tag));
9282 tagmsg = got_object_tag_get_message(tag);
9283 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9284 fprintf(outfile, "%s", tagmsg);
9285 done:
9286 free(id_str);
9287 got_object_tag_close(tag);
9288 return err;
9291 static const struct got_error *
9292 cmd_cat(int argc, char *argv[])
9294 const struct got_error *error;
9295 struct got_repository *repo = NULL;
9296 struct got_worktree *worktree = NULL;
9297 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9298 const char *commit_id_str = NULL;
9299 struct got_object_id *id = NULL, *commit_id = NULL;
9300 int ch, obj_type, i, force_path = 0;
9302 #ifndef PROFILE
9303 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9304 NULL) == -1)
9305 err(1, "pledge");
9306 #endif
9308 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9309 switch (ch) {
9310 case 'c':
9311 commit_id_str = optarg;
9312 break;
9313 case 'r':
9314 repo_path = realpath(optarg, NULL);
9315 if (repo_path == NULL)
9316 return got_error_from_errno2("realpath",
9317 optarg);
9318 got_path_strip_trailing_slashes(repo_path);
9319 break;
9320 case 'P':
9321 force_path = 1;
9322 break;
9323 default:
9324 usage_cat();
9325 /* NOTREACHED */
9329 argc -= optind;
9330 argv += optind;
9332 cwd = getcwd(NULL, 0);
9333 if (cwd == NULL) {
9334 error = got_error_from_errno("getcwd");
9335 goto done;
9337 error = got_worktree_open(&worktree, cwd);
9338 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9339 goto done;
9340 if (worktree) {
9341 if (repo_path == NULL) {
9342 repo_path = strdup(
9343 got_worktree_get_repo_path(worktree));
9344 if (repo_path == NULL) {
9345 error = got_error_from_errno("strdup");
9346 goto done;
9351 if (repo_path == NULL) {
9352 repo_path = getcwd(NULL, 0);
9353 if (repo_path == NULL)
9354 return got_error_from_errno("getcwd");
9357 error = got_repo_open(&repo, repo_path, NULL);
9358 free(repo_path);
9359 if (error != NULL)
9360 goto done;
9362 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9363 if (error)
9364 goto done;
9366 if (commit_id_str == NULL)
9367 commit_id_str = GOT_REF_HEAD;
9368 error = got_repo_match_object_id(&commit_id, NULL,
9369 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9370 if (error)
9371 goto done;
9373 for (i = 0; i < argc; i++) {
9374 if (force_path) {
9375 error = got_object_id_by_path(&id, repo, commit_id,
9376 argv[i]);
9377 if (error)
9378 break;
9379 } else {
9380 error = got_repo_match_object_id(&id, &label, argv[i],
9381 GOT_OBJ_TYPE_ANY, 0, repo);
9382 if (error) {
9383 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9384 error->code != GOT_ERR_NOT_REF)
9385 break;
9386 error = got_object_id_by_path(&id, repo,
9387 commit_id, argv[i]);
9388 if (error)
9389 break;
9393 error = got_object_get_type(&obj_type, repo, id);
9394 if (error)
9395 break;
9397 switch (obj_type) {
9398 case GOT_OBJ_TYPE_BLOB:
9399 error = cat_blob(id, repo, stdout);
9400 break;
9401 case GOT_OBJ_TYPE_TREE:
9402 error = cat_tree(id, repo, stdout);
9403 break;
9404 case GOT_OBJ_TYPE_COMMIT:
9405 error = cat_commit(id, repo, stdout);
9406 break;
9407 case GOT_OBJ_TYPE_TAG:
9408 error = cat_tag(id, repo, stdout);
9409 break;
9410 default:
9411 error = got_error(GOT_ERR_OBJ_TYPE);
9412 break;
9414 if (error)
9415 break;
9416 free(label);
9417 label = NULL;
9418 free(id);
9419 id = NULL;
9421 done:
9422 free(label);
9423 free(id);
9424 free(commit_id);
9425 if (worktree)
9426 got_worktree_close(worktree);
9427 if (repo) {
9428 const struct got_error *repo_error;
9429 repo_error = got_repo_close(repo);
9430 if (error == NULL)
9431 error = repo_error;
9433 return error;
9436 __dead static void
9437 usage_info(void)
9439 fprintf(stderr, "usage: %s info [path ...]\n",
9440 getprogname());
9441 exit(1);
9444 static const struct got_error *
9445 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9446 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9447 struct got_object_id *commit_id)
9449 const struct got_error *err = NULL;
9450 char *id_str = NULL;
9451 char datebuf[128];
9452 struct tm mytm, *tm;
9453 struct got_pathlist_head *paths = arg;
9454 struct got_pathlist_entry *pe;
9457 * Clear error indication from any of the path arguments which
9458 * would cause this file index entry to be displayed.
9460 TAILQ_FOREACH(pe, paths, entry) {
9461 if (got_path_cmp(path, pe->path, strlen(path),
9462 pe->path_len) == 0 ||
9463 got_path_is_child(path, pe->path, pe->path_len))
9464 pe->data = NULL; /* no error */
9467 printf(GOT_COMMIT_SEP_STR);
9468 if (S_ISLNK(mode))
9469 printf("symlink: %s\n", path);
9470 else if (S_ISREG(mode)) {
9471 printf("file: %s\n", path);
9472 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9473 } else if (S_ISDIR(mode))
9474 printf("directory: %s\n", path);
9475 else
9476 printf("something: %s\n", path);
9478 tm = localtime_r(&mtime, &mytm);
9479 if (tm == NULL)
9480 return NULL;
9481 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9482 return got_error(GOT_ERR_NO_SPACE);
9483 printf("timestamp: %s\n", datebuf);
9485 if (blob_id) {
9486 err = got_object_id_str(&id_str, blob_id);
9487 if (err)
9488 return err;
9489 printf("based on blob: %s\n", id_str);
9490 free(id_str);
9493 if (staged_blob_id) {
9494 err = got_object_id_str(&id_str, staged_blob_id);
9495 if (err)
9496 return err;
9497 printf("based on staged blob: %s\n", id_str);
9498 free(id_str);
9501 if (commit_id) {
9502 err = got_object_id_str(&id_str, commit_id);
9503 if (err)
9504 return err;
9505 printf("based on commit: %s\n", id_str);
9506 free(id_str);
9509 return NULL;
9512 static const struct got_error *
9513 cmd_info(int argc, char *argv[])
9515 const struct got_error *error = NULL;
9516 struct got_worktree *worktree = NULL;
9517 char *cwd = NULL, *id_str = NULL;
9518 struct got_pathlist_head paths;
9519 struct got_pathlist_entry *pe;
9520 char *uuidstr = NULL;
9521 int ch, show_files = 0;
9523 TAILQ_INIT(&paths);
9525 while ((ch = getopt(argc, argv, "")) != -1) {
9526 switch (ch) {
9527 default:
9528 usage_info();
9529 /* NOTREACHED */
9533 argc -= optind;
9534 argv += optind;
9536 #ifndef PROFILE
9537 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9538 NULL) == -1)
9539 err(1, "pledge");
9540 #endif
9541 cwd = getcwd(NULL, 0);
9542 if (cwd == NULL) {
9543 error = got_error_from_errno("getcwd");
9544 goto done;
9547 error = got_worktree_open(&worktree, cwd);
9548 if (error) {
9549 if (error->code == GOT_ERR_NOT_WORKTREE)
9550 error = wrap_not_worktree_error(error, "status", cwd);
9551 goto done;
9554 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9555 if (error)
9556 goto done;
9558 if (argc >= 1) {
9559 error = get_worktree_paths_from_argv(&paths, argc, argv,
9560 worktree);
9561 if (error)
9562 goto done;
9563 show_files = 1;
9566 error = got_object_id_str(&id_str,
9567 got_worktree_get_base_commit_id(worktree));
9568 if (error)
9569 goto done;
9571 error = got_worktree_get_uuid(&uuidstr, worktree);
9572 if (error)
9573 goto done;
9575 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9576 printf("work tree base commit: %s\n", id_str);
9577 printf("work tree path prefix: %s\n",
9578 got_worktree_get_path_prefix(worktree));
9579 printf("work tree branch reference: %s\n",
9580 got_worktree_get_head_ref_name(worktree));
9581 printf("work tree UUID: %s\n", uuidstr);
9582 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9584 if (show_files) {
9585 struct got_pathlist_entry *pe;
9586 TAILQ_FOREACH(pe, &paths, entry) {
9587 if (pe->path_len == 0)
9588 continue;
9590 * Assume this path will fail. This will be corrected
9591 * in print_path_info() in case the path does suceeed.
9593 pe->data = (void *)got_error_path(pe->path,
9594 GOT_ERR_BAD_PATH);
9596 error = got_worktree_path_info(worktree, &paths,
9597 print_path_info, &paths, check_cancelled, NULL);
9598 if (error)
9599 goto done;
9600 TAILQ_FOREACH(pe, &paths, entry) {
9601 if (pe->data != NULL) {
9602 error = pe->data; /* bad path */
9603 break;
9607 done:
9608 TAILQ_FOREACH(pe, &paths, entry)
9609 free((char *)pe->path);
9610 got_pathlist_free(&paths);
9611 free(cwd);
9612 free(id_str);
9613 free(uuidstr);
9614 return error;