Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 int i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0 }
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag, 1);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 1;
217 optreset = 1;
219 if (Vflag) {
220 got_version_print_str();
221 return 0;
224 if (argc <= 0)
225 usage(hflag, hflag ? 0 : 1);
227 signal(SIGINT, catch_sigint);
228 signal(SIGPIPE, catch_sigpipe);
230 for (i = 0; i < nitems(got_commands); i++) {
231 const struct got_error *error;
233 cmd = &got_commands[i];
235 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
236 strcmp(cmd->cmd_alias, argv[0]) != 0)
237 continue;
239 if (hflag)
240 got_commands[i].cmd_usage();
242 error = got_commands[i].cmd_main(argc, argv);
243 if (error && error->code != GOT_ERR_CANCELLED &&
244 error->code != GOT_ERR_PRIVSEP_EXIT &&
245 !(sigpipe_received &&
246 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
247 !(sigint_received &&
248 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
249 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
250 return 1;
253 return 0;
256 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
257 list_commands(stderr);
258 return 1;
261 __dead static void
262 usage(int hflag, int status)
264 FILE *fp = (status == 0) ? stdout : stderr;
266 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
267 getprogname());
268 if (hflag)
269 list_commands(fp);
270 exit(status);
273 static const struct got_error *
274 get_editor(char **abspath)
276 const struct got_error *err = NULL;
277 const char *editor;
279 *abspath = NULL;
281 editor = getenv("VISUAL");
282 if (editor == NULL)
283 editor = getenv("EDITOR");
285 if (editor) {
286 err = got_path_find_prog(abspath, editor);
287 if (err)
288 return err;
291 if (*abspath == NULL) {
292 *abspath = strdup("/bin/ed");
293 if (*abspath == NULL)
294 return got_error_from_errno("strdup");
297 return NULL;
300 static const struct got_error *
301 apply_unveil(const char *repo_path, int repo_read_only,
302 const char *worktree_path)
304 const struct got_error *err;
306 #ifdef PROFILE
307 if (unveil("gmon.out", "rwc") != 0)
308 return got_error_from_errno2("unveil", "gmon.out");
309 #endif
310 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
311 return got_error_from_errno2("unveil", repo_path);
313 if (worktree_path && unveil(worktree_path, "rwc") != 0)
314 return got_error_from_errno2("unveil", worktree_path);
316 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
317 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
319 err = got_privsep_unveil_exec_helpers();
320 if (err != NULL)
321 return err;
323 if (unveil(NULL, NULL) != 0)
324 return got_error_from_errno("unveil");
326 return NULL;
329 __dead static void
330 usage_init(void)
332 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
333 exit(1);
336 static const struct got_error *
337 cmd_init(int argc, char *argv[])
339 const struct got_error *error = NULL;
340 char *repo_path = NULL;
341 int ch;
343 while ((ch = getopt(argc, argv, "")) != -1) {
344 switch (ch) {
345 default:
346 usage_init();
347 /* NOTREACHED */
351 argc -= optind;
352 argv += optind;
354 #ifndef PROFILE
355 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
356 err(1, "pledge");
357 #endif
358 if (argc != 1)
359 usage_init();
361 repo_path = strdup(argv[0]);
362 if (repo_path == NULL)
363 return got_error_from_errno("strdup");
365 got_path_strip_trailing_slashes(repo_path);
367 error = got_path_mkdir(repo_path);
368 if (error &&
369 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
370 goto done;
372 error = apply_unveil(repo_path, 0, NULL);
373 if (error)
374 goto done;
376 error = got_repo_init(repo_path);
377 done:
378 free(repo_path);
379 return error;
382 __dead static void
383 usage_import(void)
385 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
386 "[-r repository-path] [-I pattern] path\n", getprogname());
387 exit(1);
390 int
391 spawn_editor(const char *editor, const char *file)
393 pid_t pid;
394 sig_t sighup, sigint, sigquit;
395 int st = -1;
397 sighup = signal(SIGHUP, SIG_IGN);
398 sigint = signal(SIGINT, SIG_IGN);
399 sigquit = signal(SIGQUIT, SIG_IGN);
401 switch (pid = fork()) {
402 case -1:
403 goto doneediting;
404 case 0:
405 execl(editor, editor, file, (char *)NULL);
406 _exit(127);
409 while (waitpid(pid, &st, 0) == -1)
410 if (errno != EINTR)
411 break;
413 doneediting:
414 (void)signal(SIGHUP, sighup);
415 (void)signal(SIGINT, sigint);
416 (void)signal(SIGQUIT, sigquit);
418 if (!WIFEXITED(st)) {
419 errno = EINTR;
420 return -1;
423 return WEXITSTATUS(st);
426 static const struct got_error *
427 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
428 const char *initial_content, size_t initial_content_len)
430 const struct got_error *err = NULL;
431 char *line = NULL;
432 size_t linesize = 0;
433 ssize_t linelen;
434 struct stat st, st2;
435 FILE *fp = NULL;
436 size_t len, logmsg_len;
437 char *initial_content_stripped = NULL, *buf = NULL, *s;
439 *logmsg = NULL;
441 if (stat(logmsg_path, &st) == -1)
442 return got_error_from_errno2("stat", logmsg_path);
444 if (spawn_editor(editor, logmsg_path) == -1)
445 return got_error_from_errno("failed spawning editor");
447 if (stat(logmsg_path, &st2) == -1)
448 return got_error_from_errno("stat");
450 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
451 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
452 "no changes made to commit message, aborting");
454 /*
455 * Set up a stripped version of the initial content without comments
456 * and blank lines. We need this in order to check if the message
457 * has in fact been edited.
458 */
459 initial_content_stripped = malloc(initial_content_len + 1);
460 if (initial_content_stripped == NULL)
461 return got_error_from_errno("malloc");
462 initial_content_stripped[0] = '\0';
464 buf = strdup(initial_content);
465 if (buf == NULL) {
466 err = got_error_from_errno("strdup");
467 goto done;
469 s = buf;
470 len = 0;
471 while ((line = strsep(&s, "\n")) != NULL) {
472 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
473 continue; /* remove comments and leading empty lines */
474 len = strlcat(initial_content_stripped, line,
475 initial_content_len + 1);
476 if (len >= initial_content_len + 1) {
477 err = got_error(GOT_ERR_NO_SPACE);
478 goto done;
481 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
482 initial_content_stripped[len - 1] = '\0';
483 len--;
486 logmsg_len = st2.st_size;
487 *logmsg = malloc(logmsg_len + 1);
488 if (*logmsg == NULL)
489 return got_error_from_errno("malloc");
490 (*logmsg)[0] = '\0';
492 fp = fopen(logmsg_path, "r");
493 if (fp == NULL) {
494 err = got_error_from_errno("fopen");
495 goto done;
498 len = 0;
499 while ((linelen = getline(&line, &linesize, fp)) != -1) {
500 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
501 continue; /* remove comments and leading empty lines */
502 len = strlcat(*logmsg, line, logmsg_len + 1);
503 if (len >= logmsg_len + 1) {
504 err = got_error(GOT_ERR_NO_SPACE);
505 goto done;
508 free(line);
509 if (ferror(fp)) {
510 err = got_ferror(fp, GOT_ERR_IO);
511 goto done;
513 while (len > 0 && (*logmsg)[len - 1] == '\n') {
514 (*logmsg)[len - 1] = '\0';
515 len--;
518 if (len == 0) {
519 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
520 "commit message cannot be empty, aborting");
521 goto done;
523 if (strcmp(*logmsg, initial_content_stripped) == 0)
524 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
525 "no changes made to commit message, aborting");
526 done:
527 free(initial_content_stripped);
528 free(buf);
529 if (fp && fclose(fp) == EOF && err == NULL)
530 err = got_error_from_errno("fclose");
531 if (err) {
532 free(*logmsg);
533 *logmsg = NULL;
535 return err;
538 static const struct got_error *
539 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
540 const char *path_dir, const char *branch_name)
542 char *initial_content = NULL;
543 const struct got_error *err = NULL;
544 int initial_content_len;
545 int fd = -1;
547 initial_content_len = asprintf(&initial_content,
548 "\n# %s to be imported to branch %s\n", path_dir,
549 branch_name);
550 if (initial_content_len == -1)
551 return got_error_from_errno("asprintf");
553 err = got_opentemp_named_fd(logmsg_path, &fd,
554 GOT_TMPDIR_STR "/got-importmsg");
555 if (err)
556 goto done;
558 if (write(fd, initial_content, initial_content_len) == -1) {
559 err = got_error_from_errno2("write", *logmsg_path);
560 goto done;
563 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
564 initial_content_len);
565 done:
566 if (fd != -1 && close(fd) == -1 && err == NULL)
567 err = got_error_from_errno2("close", *logmsg_path);
568 free(initial_content);
569 if (err) {
570 free(*logmsg_path);
571 *logmsg_path = NULL;
573 return err;
576 static const struct got_error *
577 import_progress(void *arg, const char *path)
579 printf("A %s\n", path);
580 return NULL;
583 static const struct got_error *
584 get_author(char **author, struct got_repository *repo,
585 struct got_worktree *worktree)
587 const struct got_error *err = NULL;
588 const char *got_author = NULL, *name, *email;
589 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
591 *author = NULL;
593 if (worktree)
594 worktree_conf = got_worktree_get_gotconfig(worktree);
595 repo_conf = got_repo_get_gotconfig(repo);
597 /*
598 * Priority of potential author information sources, from most
599 * significant to least significant:
600 * 1) work tree's .got/got.conf file
601 * 2) repository's got.conf file
602 * 3) repository's git config file
603 * 4) environment variables
604 * 5) global git config files (in user's home directory or /etc)
605 */
607 if (worktree_conf)
608 got_author = got_gotconfig_get_author(worktree_conf);
609 if (got_author == NULL)
610 got_author = got_gotconfig_get_author(repo_conf);
611 if (got_author == NULL) {
612 name = got_repo_get_gitconfig_author_name(repo);
613 email = got_repo_get_gitconfig_author_email(repo);
614 if (name && email) {
615 if (asprintf(author, "%s <%s>", name, email) == -1)
616 return got_error_from_errno("asprintf");
617 return NULL;
620 got_author = getenv("GOT_AUTHOR");
621 if (got_author == NULL) {
622 name = got_repo_get_global_gitconfig_author_name(repo);
623 email = got_repo_get_global_gitconfig_author_email(
624 repo);
625 if (name && email) {
626 if (asprintf(author, "%s <%s>", name, email)
627 == -1)
628 return got_error_from_errno("asprintf");
629 return NULL;
631 /* TODO: Look up user in password database? */
632 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
636 *author = strdup(got_author);
637 if (*author == NULL)
638 return got_error_from_errno("strdup");
640 /*
641 * Really dumb email address check; we're only doing this to
642 * avoid git's object parser breaking on commits we create.
643 */
644 while (*got_author && *got_author != '<')
645 got_author++;
646 if (*got_author != '<') {
647 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
648 goto done;
650 while (*got_author && *got_author != '@')
651 got_author++;
652 if (*got_author != '@') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '>')
657 got_author++;
658 if (*got_author != '>')
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 done:
661 if (err) {
662 free(*author);
663 *author = NULL;
665 return err;
668 static const struct got_error *
669 get_gitconfig_path(char **gitconfig_path)
671 const char *homedir = getenv("HOME");
673 *gitconfig_path = NULL;
674 if (homedir) {
675 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
676 return got_error_from_errno("asprintf");
679 return NULL;
682 static const struct got_error *
683 cmd_import(int argc, char *argv[])
685 const struct got_error *error = NULL;
686 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
687 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
688 const char *branch_name = "main";
689 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
690 struct got_repository *repo = NULL;
691 struct got_reference *branch_ref = NULL, *head_ref = NULL;
692 struct got_object_id *new_commit_id = NULL;
693 int ch;
694 struct got_pathlist_head ignores;
695 struct got_pathlist_entry *pe;
696 int preserve_logmsg = 0;
698 TAILQ_INIT(&ignores);
700 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
701 switch (ch) {
702 case 'b':
703 branch_name = optarg;
704 break;
705 case 'm':
706 logmsg = strdup(optarg);
707 if (logmsg == NULL) {
708 error = got_error_from_errno("strdup");
709 goto done;
711 break;
712 case 'r':
713 repo_path = realpath(optarg, NULL);
714 if (repo_path == NULL) {
715 error = got_error_from_errno2("realpath",
716 optarg);
717 goto done;
719 break;
720 case 'I':
721 if (optarg[0] == '\0')
722 break;
723 error = got_pathlist_insert(&pe, &ignores, optarg,
724 NULL);
725 if (error)
726 goto done;
727 break;
728 default:
729 usage_import();
730 /* NOTREACHED */
734 argc -= optind;
735 argv += optind;
737 #ifndef PROFILE
738 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
739 "unveil",
740 NULL) == -1)
741 err(1, "pledge");
742 #endif
743 if (argc != 1)
744 usage_import();
746 if (repo_path == NULL) {
747 repo_path = getcwd(NULL, 0);
748 if (repo_path == NULL)
749 return got_error_from_errno("getcwd");
751 got_path_strip_trailing_slashes(repo_path);
752 error = get_gitconfig_path(&gitconfig_path);
753 if (error)
754 goto done;
755 error = got_repo_open(&repo, repo_path, gitconfig_path);
756 if (error)
757 goto done;
759 error = get_author(&author, repo, NULL);
760 if (error)
761 return error;
763 /*
764 * Don't let the user create a branch name with a leading '-'.
765 * While technically a valid reference name, this case is usually
766 * an unintended typo.
767 */
768 if (branch_name[0] == '-')
769 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
772 error = got_error_from_errno("asprintf");
773 goto done;
776 error = got_ref_open(&branch_ref, repo, refname, 0);
777 if (error) {
778 if (error->code != GOT_ERR_NOT_REF)
779 goto done;
780 } else {
781 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
782 "import target branch already exists");
783 goto done;
786 path_dir = realpath(argv[0], NULL);
787 if (path_dir == NULL) {
788 error = got_error_from_errno2("realpath", argv[0]);
789 goto done;
791 got_path_strip_trailing_slashes(path_dir);
793 /*
794 * unveil(2) traverses exec(2); if an editor is used we have
795 * to apply unveil after the log message has been written.
796 */
797 if (logmsg == NULL || strlen(logmsg) == 0) {
798 error = get_editor(&editor);
799 if (error)
800 goto done;
801 free(logmsg);
802 error = collect_import_msg(&logmsg, &logmsg_path, editor,
803 path_dir, refname);
804 if (error) {
805 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
806 logmsg_path != NULL)
807 preserve_logmsg = 1;
808 goto done;
812 if (unveil(path_dir, "r") != 0) {
813 error = got_error_from_errno2("unveil", path_dir);
814 if (logmsg_path)
815 preserve_logmsg = 1;
816 goto done;
819 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
820 if (error) {
821 if (logmsg_path)
822 preserve_logmsg = 1;
823 goto done;
826 error = got_repo_import(&new_commit_id, path_dir, logmsg,
827 author, &ignores, repo, import_progress, NULL);
828 if (error) {
829 if (logmsg_path)
830 preserve_logmsg = 1;
831 goto done;
834 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
835 if (error) {
836 if (logmsg_path)
837 preserve_logmsg = 1;
838 goto done;
841 error = got_ref_write(branch_ref, repo);
842 if (error) {
843 if (logmsg_path)
844 preserve_logmsg = 1;
845 goto done;
848 error = got_object_id_str(&id_str, new_commit_id);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
856 if (error) {
857 if (error->code != GOT_ERR_NOT_REF) {
858 if (logmsg_path)
859 preserve_logmsg = 1;
860 goto done;
863 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
864 branch_ref);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_write(head_ref, repo);
872 if (error) {
873 if (logmsg_path)
874 preserve_logmsg = 1;
875 goto done;
879 printf("Created branch %s with commit %s\n",
880 got_ref_get_name(branch_ref), id_str);
881 done:
882 if (preserve_logmsg) {
883 fprintf(stderr, "%s: log message preserved in %s\n",
884 getprogname(), logmsg_path);
885 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
886 error = got_error_from_errno2("unlink", logmsg_path);
887 free(logmsg);
888 free(logmsg_path);
889 free(repo_path);
890 free(editor);
891 free(refname);
892 free(new_commit_id);
893 free(id_str);
894 free(author);
895 free(gitconfig_path);
896 if (branch_ref)
897 got_ref_close(branch_ref);
898 if (head_ref)
899 got_ref_close(head_ref);
900 return error;
903 __dead static void
904 usage_clone(void)
906 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
907 "[-R reference] repository-url [directory]\n", getprogname());
908 exit(1);
911 struct got_fetch_progress_arg {
912 char last_scaled_size[FMT_SCALED_STRSIZE];
913 int last_p_indexed;
914 int last_p_resolved;
915 int verbosity;
917 struct got_repository *repo;
919 int create_configs;
920 int configs_created;
921 struct {
922 struct got_pathlist_head *symrefs;
923 struct got_pathlist_head *wanted_branches;
924 const char *proto;
925 const char *host;
926 const char *port;
927 const char *remote_repo_path;
928 const char *git_url;
929 int fetch_all_branches;
930 int mirror_references;
931 } config_info;
932 };
934 /* XXX forward declaration */
935 static const struct got_error *
936 create_config_files(const char *proto, const char *host, const char *port,
937 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
938 int mirror_references, struct got_pathlist_head *symrefs,
939 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
941 static const struct got_error *
942 fetch_progress(void *arg, const char *message, off_t packfile_size,
943 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
945 const struct got_error *err = NULL;
946 struct got_fetch_progress_arg *a = arg;
947 char scaled_size[FMT_SCALED_STRSIZE];
948 int p_indexed, p_resolved;
949 int print_size = 0, print_indexed = 0, print_resolved = 0;
951 /*
952 * In order to allow a failed clone to be resumed with 'got fetch'
953 * we try to create configuration files as soon as possible.
954 * Once the server has sent information about its default branch
955 * we have all required information.
956 */
957 if (a->create_configs && !a->configs_created &&
958 !TAILQ_EMPTY(a->config_info.symrefs)) {
959 err = create_config_files(a->config_info.proto,
960 a->config_info.host, a->config_info.port,
961 a->config_info.remote_repo_path,
962 a->config_info.git_url,
963 a->config_info.fetch_all_branches,
964 a->config_info.mirror_references,
965 a->config_info.symrefs,
966 a->config_info.wanted_branches, a->repo);
967 if (err)
968 return err;
969 a->configs_created = 1;
972 if (a->verbosity < 0)
973 return NULL;
975 if (message && message[0] != '\0') {
976 printf("\rserver: %s", message);
977 fflush(stdout);
978 return NULL;
981 if (packfile_size > 0 || nobj_indexed > 0) {
982 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
983 (a->last_scaled_size[0] == '\0' ||
984 strcmp(scaled_size, a->last_scaled_size)) != 0) {
985 print_size = 1;
986 if (strlcpy(a->last_scaled_size, scaled_size,
987 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
988 return got_error(GOT_ERR_NO_SPACE);
990 if (nobj_indexed > 0) {
991 p_indexed = (nobj_indexed * 100) / nobj_total;
992 if (p_indexed != a->last_p_indexed) {
993 a->last_p_indexed = p_indexed;
994 print_indexed = 1;
995 print_size = 1;
998 if (nobj_resolved > 0) {
999 p_resolved = (nobj_resolved * 100) /
1000 (nobj_total - nobj_loose);
1001 if (p_resolved != a->last_p_resolved) {
1002 a->last_p_resolved = p_resolved;
1003 print_resolved = 1;
1004 print_indexed = 1;
1005 print_size = 1;
1010 if (print_size || print_indexed || print_resolved)
1011 printf("\r");
1012 if (print_size)
1013 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1014 if (print_indexed)
1015 printf("; indexing %d%%", p_indexed);
1016 if (print_resolved)
1017 printf("; resolving deltas %d%%", p_resolved);
1018 if (print_size || print_indexed || print_resolved)
1019 fflush(stdout);
1021 return NULL;
1024 static const struct got_error *
1025 create_symref(const char *refname, struct got_reference *target_ref,
1026 int verbosity, struct got_repository *repo)
1028 const struct got_error *err;
1029 struct got_reference *head_symref;
1031 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1032 if (err)
1033 return err;
1035 err = got_ref_write(head_symref, repo);
1036 if (err == NULL && verbosity > 0) {
1037 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1038 got_ref_get_name(target_ref));
1040 got_ref_close(head_symref);
1041 return err;
1044 static const struct got_error *
1045 list_remote_refs(struct got_pathlist_head *symrefs,
1046 struct got_pathlist_head *refs)
1048 const struct got_error *err;
1049 struct got_pathlist_entry *pe;
1051 TAILQ_FOREACH(pe, symrefs, entry) {
1052 const char *refname = pe->path;
1053 const char *targetref = pe->data;
1055 printf("%s: %s\n", refname, targetref);
1058 TAILQ_FOREACH(pe, refs, entry) {
1059 const char *refname = pe->path;
1060 struct got_object_id *id = pe->data;
1061 char *id_str;
1063 err = got_object_id_str(&id_str, id);
1064 if (err)
1065 return err;
1066 printf("%s: %s\n", refname, id_str);
1067 free(id_str);
1070 return NULL;
1073 static const struct got_error *
1074 create_ref(const char *refname, struct got_object_id *id,
1075 int verbosity, struct got_repository *repo)
1077 const struct got_error *err = NULL;
1078 struct got_reference *ref;
1079 char *id_str;
1081 err = got_object_id_str(&id_str, id);
1082 if (err)
1083 return err;
1085 err = got_ref_alloc(&ref, refname, id);
1086 if (err)
1087 goto done;
1089 err = got_ref_write(ref, repo);
1090 got_ref_close(ref);
1092 if (err == NULL && verbosity >= 0)
1093 printf("Created reference %s: %s\n", refname, id_str);
1094 done:
1095 free(id_str);
1096 return err;
1099 static int
1100 match_wanted_ref(const char *refname, const char *wanted_ref)
1102 if (strncmp(refname, "refs/", 5) != 0)
1103 return 0;
1104 refname += 5;
1107 * Prevent fetching of references that won't make any
1108 * sense outside of the remote repository's context.
1110 if (strncmp(refname, "got/", 4) == 0)
1111 return 0;
1112 if (strncmp(refname, "remotes/", 8) == 0)
1113 return 0;
1115 if (strncmp(wanted_ref, "refs/", 5) == 0)
1116 wanted_ref += 5;
1118 /* Allow prefix match. */
1119 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1120 return 1;
1122 /* Allow exact match. */
1123 return (strcmp(refname, wanted_ref) == 0);
1126 static int
1127 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1129 struct got_pathlist_entry *pe;
1131 TAILQ_FOREACH(pe, wanted_refs, entry) {
1132 if (match_wanted_ref(refname, pe->path))
1133 return 1;
1136 return 0;
1139 static const struct got_error *
1140 create_wanted_ref(const char *refname, struct got_object_id *id,
1141 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1143 const struct got_error *err;
1144 char *remote_refname;
1146 if (strncmp("refs/", refname, 5) == 0)
1147 refname += 5;
1149 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1150 remote_repo_name, refname) == -1)
1151 return got_error_from_errno("asprintf");
1153 err = create_ref(remote_refname, id, verbosity, repo);
1154 free(remote_refname);
1155 return err;
1158 static const struct got_error *
1159 create_gotconfig(const char *proto, const char *host, const char *port,
1160 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1161 struct got_repository *repo)
1163 const struct got_error *err = NULL;
1164 char *gotconfig_path = NULL;
1165 char *gotconfig = NULL;
1166 FILE *gotconfig_file = NULL;
1167 ssize_t n;
1169 /* Create got.conf(5). */
1170 gotconfig_path = got_repo_get_path_gotconfig(repo);
1171 if (gotconfig_path == NULL) {
1172 err = got_error_from_errno("got_repo_get_path_gotconfig");
1173 goto done;
1175 gotconfig_file = fopen(gotconfig_path, "a");
1176 if (gotconfig_file == NULL) {
1177 err = got_error_from_errno2("fopen", gotconfig_path);
1178 goto done;
1180 if (asprintf(&gotconfig,
1181 "remote \"%s\" {\n"
1182 "\tserver %s\n"
1183 "\tprotocol %s\n"
1184 "%s%s%s"
1185 "\trepository \"%s\"\n"
1186 "%s"
1187 "}\n",
1188 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1189 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1190 remote_repo_path,
1191 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1196 if (n != strlen(gotconfig)) {
1197 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1198 goto done;
1201 done:
1202 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1203 err = got_error_from_errno2("fclose", gotconfig_path);
1204 free(gotconfig_path);
1205 return err;
1208 static const struct got_error *
1209 create_gitconfig(const char *git_url, const char *default_branch,
1210 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1212 const struct got_error *err = NULL;
1213 char *gitconfig_path = NULL;
1214 char *gitconfig = NULL;
1215 FILE *gitconfig_file = NULL;
1216 ssize_t n;
1218 /* Create a config file Git can understand. */
1219 gitconfig_path = got_repo_get_path_gitconfig(repo);
1220 if (gitconfig_path == NULL) {
1221 err = got_error_from_errno("got_repo_get_path_gitconfig");
1222 goto done;
1224 gitconfig_file = fopen(gitconfig_path, "a");
1225 if (gitconfig_file == NULL) {
1226 err = got_error_from_errno2("fopen", gitconfig_path);
1227 goto done;
1229 if (mirror_references) {
1230 if (asprintf(&gitconfig,
1231 "[remote \"%s\"]\n"
1232 "\turl = %s\n"
1233 "\tfetch = +refs/*:refs/*\n"
1234 "\tmirror = true\n",
1235 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1236 err = got_error_from_errno("asprintf");
1237 goto done;
1239 } else if (fetch_all_branches) {
1240 if (asprintf(&gitconfig,
1241 "[remote \"%s\"]\n"
1242 "\turl = %s\n"
1243 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1244 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1245 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1246 err = got_error_from_errno("asprintf");
1247 goto done;
1249 } else {
1250 const char *branchname;
1253 * If the server specified a default branch, use just that one.
1254 * Otherwise fall back to fetching all branches on next fetch.
1256 if (default_branch) {
1257 branchname = default_branch;
1258 if (strncmp(branchname, "refs/heads/", 11) == 0)
1259 branchname += 11;
1260 } else
1261 branchname = "*"; /* fall back to all branches */
1262 if (asprintf(&gitconfig,
1263 "[remote \"%s\"]\n"
1264 "\turl = %s\n"
1265 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1266 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1267 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1268 branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1273 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1274 if (n != strlen(gitconfig)) {
1275 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1276 goto done;
1278 done:
1279 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1280 err = got_error_from_errno2("fclose", gitconfig_path);
1281 free(gitconfig_path);
1282 return err;
1285 static const struct got_error *
1286 create_config_files(const char *proto, const char *host, const char *port,
1287 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1288 int mirror_references, struct got_pathlist_head *symrefs,
1289 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1291 const struct got_error *err = NULL;
1292 const char *default_branch = NULL;
1293 struct got_pathlist_entry *pe;
1296 * If we asked for a set of wanted branches then use the first
1297 * one of those.
1299 if (!TAILQ_EMPTY(wanted_branches)) {
1300 pe = TAILQ_FIRST(wanted_branches);
1301 default_branch = pe->path;
1302 } else {
1303 /* First HEAD ref listed by server is the default branch. */
1304 TAILQ_FOREACH(pe, symrefs, entry) {
1305 const char *refname = pe->path;
1306 const char *target = pe->data;
1308 if (strcmp(refname, GOT_REF_HEAD) != 0)
1309 continue;
1311 default_branch = target;
1312 break;
1316 /* Create got.conf(5). */
1317 err = create_gotconfig(proto, host, port, remote_repo_path,
1318 fetch_all_branches, mirror_references, repo);
1319 if (err)
1320 return err;
1322 /* Create a config file Git can understand. */
1323 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1324 mirror_references, repo);
1327 static const struct got_error *
1328 cmd_clone(int argc, char *argv[])
1330 const struct got_error *error = NULL;
1331 const char *uri, *dirname;
1332 char *proto, *host, *port, *repo_name, *server_path;
1333 char *default_destdir = NULL, *id_str = NULL;
1334 const char *repo_path;
1335 struct got_repository *repo = NULL;
1336 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1337 struct got_pathlist_entry *pe;
1338 struct got_object_id *pack_hash = NULL;
1339 int ch, fetchfd = -1, fetchstatus;
1340 pid_t fetchpid = -1;
1341 struct got_fetch_progress_arg fpa;
1342 char *git_url = NULL;
1343 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1344 int list_refs_only = 0;
1346 TAILQ_INIT(&refs);
1347 TAILQ_INIT(&symrefs);
1348 TAILQ_INIT(&wanted_branches);
1349 TAILQ_INIT(&wanted_refs);
1351 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1352 switch (ch) {
1353 case 'a':
1354 fetch_all_branches = 1;
1355 break;
1356 case 'b':
1357 error = got_pathlist_append(&wanted_branches,
1358 optarg, NULL);
1359 if (error)
1360 return error;
1361 break;
1362 case 'l':
1363 list_refs_only = 1;
1364 break;
1365 case 'm':
1366 mirror_references = 1;
1367 break;
1368 case 'v':
1369 if (verbosity < 0)
1370 verbosity = 0;
1371 else if (verbosity < 3)
1372 verbosity++;
1373 break;
1374 case 'q':
1375 verbosity = -1;
1376 break;
1377 case 'R':
1378 error = got_pathlist_append(&wanted_refs,
1379 optarg, NULL);
1380 if (error)
1381 return error;
1382 break;
1383 default:
1384 usage_clone();
1385 break;
1388 argc -= optind;
1389 argv += optind;
1391 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1392 errx(1, "-a and -b options are mutually exclusive");
1393 if (list_refs_only) {
1394 if (!TAILQ_EMPTY(&wanted_branches))
1395 errx(1, "-l and -b options are mutually exclusive");
1396 if (fetch_all_branches)
1397 errx(1, "-l and -a options are mutually exclusive");
1398 if (mirror_references)
1399 errx(1, "-l and -m options are mutually exclusive");
1400 if (verbosity == -1)
1401 errx(1, "-l and -q options are mutually exclusive");
1402 if (!TAILQ_EMPTY(&wanted_refs))
1403 errx(1, "-l and -R options are mutually exclusive");
1406 uri = argv[0];
1408 if (argc == 1)
1409 dirname = NULL;
1410 else if (argc == 2)
1411 dirname = argv[1];
1412 else
1413 usage_clone();
1415 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1416 &repo_name, uri);
1417 if (error)
1418 goto done;
1420 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1421 host, port ? ":" : "", port ? port : "",
1422 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1423 error = got_error_from_errno("asprintf");
1424 goto done;
1427 if (strcmp(proto, "git") == 0) {
1428 #ifndef PROFILE
1429 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1430 "sendfd dns inet unveil", NULL) == -1)
1431 err(1, "pledge");
1432 #endif
1433 } else if (strcmp(proto, "git+ssh") == 0 ||
1434 strcmp(proto, "ssh") == 0) {
1435 #ifndef PROFILE
1436 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1437 "sendfd unveil", NULL) == -1)
1438 err(1, "pledge");
1439 #endif
1440 } else if (strcmp(proto, "http") == 0 ||
1441 strcmp(proto, "git+http") == 0) {
1442 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1443 goto done;
1444 } else {
1445 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1446 goto done;
1448 if (dirname == NULL) {
1449 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1450 error = got_error_from_errno("asprintf");
1451 goto done;
1453 repo_path = default_destdir;
1454 } else
1455 repo_path = dirname;
1457 if (!list_refs_only) {
1458 error = got_path_mkdir(repo_path);
1459 if (error &&
1460 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1461 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1462 goto done;
1463 if (!got_path_dir_is_empty(repo_path)) {
1464 error = got_error_path(repo_path,
1465 GOT_ERR_DIR_NOT_EMPTY);
1466 goto done;
1470 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1471 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1472 error = got_error_from_errno2("unveil",
1473 GOT_FETCH_PATH_SSH);
1474 goto done;
1477 error = apply_unveil(repo_path, 0, NULL);
1478 if (error)
1479 goto done;
1481 if (verbosity >= 0)
1482 printf("Connecting to %s%s%s\n", host,
1483 port ? ":" : "", port ? port : "");
1485 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1486 server_path, verbosity);
1487 if (error)
1488 goto done;
1490 if (!list_refs_only) {
1491 error = got_repo_init(repo_path);
1492 if (error)
1493 goto done;
1494 error = got_repo_open(&repo, repo_path, NULL);
1495 if (error)
1496 goto done;
1499 fpa.last_scaled_size[0] = '\0';
1500 fpa.last_p_indexed = -1;
1501 fpa.last_p_resolved = -1;
1502 fpa.verbosity = verbosity;
1503 fpa.create_configs = 1;
1504 fpa.configs_created = 0;
1505 fpa.repo = repo;
1506 fpa.config_info.symrefs = &symrefs;
1507 fpa.config_info.wanted_branches = &wanted_branches;
1508 fpa.config_info.proto = proto;
1509 fpa.config_info.host = host;
1510 fpa.config_info.port = port;
1511 fpa.config_info.remote_repo_path = server_path;
1512 fpa.config_info.git_url = git_url;
1513 fpa.config_info.fetch_all_branches = fetch_all_branches;
1514 fpa.config_info.mirror_references = mirror_references;
1515 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1516 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1517 fetch_all_branches, &wanted_branches, &wanted_refs,
1518 list_refs_only, verbosity, fetchfd, repo,
1519 fetch_progress, &fpa);
1520 if (error)
1521 goto done;
1523 if (list_refs_only) {
1524 error = list_remote_refs(&symrefs, &refs);
1525 goto done;
1528 error = got_object_id_str(&id_str, pack_hash);
1529 if (error)
1530 goto done;
1531 if (verbosity >= 0)
1532 printf("\nFetched %s.pack\n", id_str);
1533 free(id_str);
1535 /* Set up references provided with the pack file. */
1536 TAILQ_FOREACH(pe, &refs, entry) {
1537 const char *refname = pe->path;
1538 struct got_object_id *id = pe->data;
1539 char *remote_refname;
1541 if (is_wanted_ref(&wanted_refs, refname) &&
1542 !mirror_references) {
1543 error = create_wanted_ref(refname, id,
1544 GOT_FETCH_DEFAULT_REMOTE_NAME,
1545 verbosity - 1, repo);
1546 if (error)
1547 goto done;
1548 continue;
1551 error = create_ref(refname, id, verbosity - 1, repo);
1552 if (error)
1553 goto done;
1555 if (mirror_references)
1556 continue;
1558 if (strncmp("refs/heads/", refname, 11) != 0)
1559 continue;
1561 if (asprintf(&remote_refname,
1562 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1563 refname + 11) == -1) {
1564 error = got_error_from_errno("asprintf");
1565 goto done;
1567 error = create_ref(remote_refname, id, verbosity - 1, repo);
1568 free(remote_refname);
1569 if (error)
1570 goto done;
1573 /* Set the HEAD reference if the server provided one. */
1574 TAILQ_FOREACH(pe, &symrefs, entry) {
1575 struct got_reference *target_ref;
1576 const char *refname = pe->path;
1577 const char *target = pe->data;
1578 char *remote_refname = NULL, *remote_target = NULL;
1580 if (strcmp(refname, GOT_REF_HEAD) != 0)
1581 continue;
1583 error = got_ref_open(&target_ref, repo, target, 0);
1584 if (error) {
1585 if (error->code == GOT_ERR_NOT_REF) {
1586 error = NULL;
1587 continue;
1589 goto done;
1592 error = create_symref(refname, target_ref, verbosity, repo);
1593 got_ref_close(target_ref);
1594 if (error)
1595 goto done;
1597 if (mirror_references)
1598 continue;
1600 if (strncmp("refs/heads/", target, 11) != 0)
1601 continue;
1603 if (asprintf(&remote_refname,
1604 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1605 refname) == -1) {
1606 error = got_error_from_errno("asprintf");
1607 goto done;
1609 if (asprintf(&remote_target,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 target + 11) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 free(remote_refname);
1614 goto done;
1616 error = got_ref_open(&target_ref, repo, remote_target, 0);
1617 if (error) {
1618 free(remote_refname);
1619 free(remote_target);
1620 if (error->code == GOT_ERR_NOT_REF) {
1621 error = NULL;
1622 continue;
1624 goto done;
1626 error = create_symref(remote_refname, target_ref,
1627 verbosity - 1, repo);
1628 free(remote_refname);
1629 free(remote_target);
1630 got_ref_close(target_ref);
1631 if (error)
1632 goto done;
1634 if (pe == NULL) {
1636 * We failed to set the HEAD reference. If we asked for
1637 * a set of wanted branches use the first of one of those
1638 * which could be fetched instead.
1640 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1641 const char *target = pe->path;
1642 struct got_reference *target_ref;
1644 error = got_ref_open(&target_ref, repo, target, 0);
1645 if (error) {
1646 if (error->code == GOT_ERR_NOT_REF) {
1647 error = NULL;
1648 continue;
1650 goto done;
1653 error = create_symref(GOT_REF_HEAD, target_ref,
1654 verbosity, repo);
1655 got_ref_close(target_ref);
1656 if (error)
1657 goto done;
1658 break;
1662 if (verbosity >= 0)
1663 printf("Created %s repository '%s'\n",
1664 mirror_references ? "mirrored" : "cloned", repo_path);
1665 done:
1666 if (fetchpid > 0) {
1667 if (kill(fetchpid, SIGTERM) == -1)
1668 error = got_error_from_errno("kill");
1669 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1670 error = got_error_from_errno("waitpid");
1672 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1673 error = got_error_from_errno("close");
1674 if (repo)
1675 got_repo_close(repo);
1676 TAILQ_FOREACH(pe, &refs, entry) {
1677 free((void *)pe->path);
1678 free(pe->data);
1680 got_pathlist_free(&refs);
1681 TAILQ_FOREACH(pe, &symrefs, entry) {
1682 free((void *)pe->path);
1683 free(pe->data);
1685 got_pathlist_free(&symrefs);
1686 got_pathlist_free(&wanted_branches);
1687 got_pathlist_free(&wanted_refs);
1688 free(pack_hash);
1689 free(proto);
1690 free(host);
1691 free(port);
1692 free(server_path);
1693 free(repo_name);
1694 free(default_destdir);
1695 free(git_url);
1696 return error;
1699 static const struct got_error *
1700 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1701 int replace_tags, int verbosity, struct got_repository *repo)
1703 const struct got_error *err = NULL;
1704 char *new_id_str = NULL;
1705 struct got_object_id *old_id = NULL;
1707 err = got_object_id_str(&new_id_str, new_id);
1708 if (err)
1709 goto done;
1711 if (!replace_tags &&
1712 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1713 err = got_ref_resolve(&old_id, repo, ref);
1714 if (err)
1715 goto done;
1716 if (got_object_id_cmp(old_id, new_id) == 0)
1717 goto done;
1718 if (verbosity >= 0) {
1719 printf("Rejecting update of existing tag %s: %s\n",
1720 got_ref_get_name(ref), new_id_str);
1722 goto done;
1725 if (got_ref_is_symbolic(ref)) {
1726 if (verbosity >= 0) {
1727 printf("Replacing reference %s: %s\n",
1728 got_ref_get_name(ref),
1729 got_ref_get_symref_target(ref));
1731 err = got_ref_change_symref_to_ref(ref, new_id);
1732 if (err)
1733 goto done;
1734 err = got_ref_write(ref, repo);
1735 if (err)
1736 goto done;
1737 } else {
1738 err = got_ref_resolve(&old_id, repo, ref);
1739 if (err)
1740 goto done;
1741 if (got_object_id_cmp(old_id, new_id) == 0)
1742 goto done;
1744 err = got_ref_change_ref(ref, new_id);
1745 if (err)
1746 goto done;
1747 err = got_ref_write(ref, repo);
1748 if (err)
1749 goto done;
1752 if (verbosity >= 0)
1753 printf("Updated %s: %s\n", got_ref_get_name(ref),
1754 new_id_str);
1755 done:
1756 free(old_id);
1757 free(new_id_str);
1758 return err;
1761 static const struct got_error *
1762 update_symref(const char *refname, struct got_reference *target_ref,
1763 int verbosity, struct got_repository *repo)
1765 const struct got_error *err = NULL, *unlock_err;
1766 struct got_reference *symref;
1767 int symref_is_locked = 0;
1769 err = got_ref_open(&symref, repo, refname, 1);
1770 if (err) {
1771 if (err->code != GOT_ERR_NOT_REF)
1772 return err;
1773 err = got_ref_alloc_symref(&symref, refname, target_ref);
1774 if (err)
1775 goto done;
1777 err = got_ref_write(symref, repo);
1778 if (err)
1779 goto done;
1781 if (verbosity >= 0)
1782 printf("Created reference %s: %s\n",
1783 got_ref_get_name(symref),
1784 got_ref_get_symref_target(symref));
1785 } else {
1786 symref_is_locked = 1;
1788 if (strcmp(got_ref_get_symref_target(symref),
1789 got_ref_get_name(target_ref)) == 0)
1790 goto done;
1792 err = got_ref_change_symref(symref,
1793 got_ref_get_name(target_ref));
1794 if (err)
1795 goto done;
1797 err = got_ref_write(symref, repo);
1798 if (err)
1799 goto done;
1801 if (verbosity >= 0)
1802 printf("Updated %s: %s\n", got_ref_get_name(symref),
1803 got_ref_get_symref_target(symref));
1806 done:
1807 if (symref_is_locked) {
1808 unlock_err = got_ref_unlock(symref);
1809 if (unlock_err && err == NULL)
1810 err = unlock_err;
1812 got_ref_close(symref);
1813 return err;
1816 __dead static void
1817 usage_fetch(void)
1819 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1820 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1821 "[remote-repository-name]\n",
1822 getprogname());
1823 exit(1);
1826 static const struct got_error *
1827 delete_missing_ref(struct got_reference *ref,
1828 int verbosity, struct got_repository *repo)
1830 const struct got_error *err = NULL;
1831 struct got_object_id *id = NULL;
1832 char *id_str = NULL;
1834 if (got_ref_is_symbolic(ref)) {
1835 err = got_ref_delete(ref, repo);
1836 if (err)
1837 return err;
1838 if (verbosity >= 0) {
1839 printf("Deleted reference %s: %s\n",
1840 got_ref_get_name(ref),
1841 got_ref_get_symref_target(ref));
1843 } else {
1844 err = got_ref_resolve(&id, repo, ref);
1845 if (err)
1846 return err;
1847 err = got_object_id_str(&id_str, id);
1848 if (err)
1849 goto done;
1851 err = got_ref_delete(ref, repo);
1852 if (err)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Deleted reference %s: %s\n",
1856 got_ref_get_name(ref), id_str);
1859 done:
1860 free(id);
1861 free(id_str);
1862 return NULL;
1865 static const struct got_error *
1866 delete_missing_refs(struct got_pathlist_head *their_refs,
1867 struct got_pathlist_head *their_symrefs,
1868 const struct got_remote_repo *remote,
1869 int verbosity, struct got_repository *repo)
1871 const struct got_error *err = NULL, *unlock_err;
1872 struct got_reflist_head my_refs;
1873 struct got_reflist_entry *re;
1874 struct got_pathlist_entry *pe;
1875 char *remote_namespace = NULL;
1876 char *local_refname = NULL;
1878 SIMPLEQ_INIT(&my_refs);
1880 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1881 == -1)
1882 return got_error_from_errno("asprintf");
1884 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1885 if (err)
1886 goto done;
1888 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1889 const char *refname = got_ref_get_name(re->ref);
1891 if (!remote->mirror_references) {
1892 if (strncmp(refname, remote_namespace,
1893 strlen(remote_namespace)) == 0) {
1894 if (strcmp(refname + strlen(remote_namespace),
1895 GOT_REF_HEAD) == 0)
1896 continue;
1897 if (asprintf(&local_refname, "refs/heads/%s",
1898 refname + strlen(remote_namespace)) == -1) {
1899 err = got_error_from_errno("asprintf");
1900 goto done;
1902 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1903 continue;
1906 TAILQ_FOREACH(pe, their_refs, entry) {
1907 if (strcmp(local_refname, pe->path) == 0)
1908 break;
1910 if (pe != NULL)
1911 continue;
1913 TAILQ_FOREACH(pe, their_symrefs, entry) {
1914 if (strcmp(local_refname, pe->path) == 0)
1915 break;
1917 if (pe != NULL)
1918 continue;
1920 err = delete_missing_ref(re->ref, verbosity, repo);
1921 if (err)
1922 break;
1924 if (local_refname) {
1925 struct got_reference *ref;
1926 err = got_ref_open(&ref, repo, local_refname, 1);
1927 if (err) {
1928 if (err->code != GOT_ERR_NOT_REF)
1929 break;
1930 free(local_refname);
1931 local_refname = NULL;
1932 continue;
1934 err = delete_missing_ref(ref, verbosity, repo);
1935 if (err)
1936 break;
1937 unlock_err = got_ref_unlock(ref);
1938 got_ref_close(ref);
1939 if (unlock_err && err == NULL) {
1940 err = unlock_err;
1941 break;
1944 free(local_refname);
1945 local_refname = NULL;
1948 done:
1949 free(remote_namespace);
1950 free(local_refname);
1951 return err;
1954 static const struct got_error *
1955 update_wanted_ref(const char *refname, struct got_object_id *id,
1956 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1958 const struct got_error *err, *unlock_err;
1959 char *remote_refname;
1960 struct got_reference *ref;
1962 if (strncmp("refs/", refname, 5) == 0)
1963 refname += 5;
1965 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1966 remote_repo_name, refname) == -1)
1967 return got_error_from_errno("asprintf");
1969 err = got_ref_open(&ref, repo, remote_refname, 1);
1970 if (err) {
1971 if (err->code != GOT_ERR_NOT_REF)
1972 goto done;
1973 err = create_ref(remote_refname, id, verbosity, repo);
1974 } else {
1975 err = update_ref(ref, id, 0, verbosity, repo);
1976 unlock_err = got_ref_unlock(ref);
1977 if (unlock_err && err == NULL)
1978 err = unlock_err;
1979 got_ref_close(ref);
1981 done:
1982 free(remote_refname);
1983 return err;
1986 static const struct got_error *
1987 cmd_fetch(int argc, char *argv[])
1989 const struct got_error *error = NULL, *unlock_err;
1990 char *cwd = NULL, *repo_path = NULL;
1991 const char *remote_name;
1992 char *proto = NULL, *host = NULL, *port = NULL;
1993 char *repo_name = NULL, *server_path = NULL;
1994 const struct got_remote_repo *remotes, *remote = NULL;
1995 int nremotes;
1996 char *id_str = NULL;
1997 struct got_repository *repo = NULL;
1998 struct got_worktree *worktree = NULL;
1999 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2000 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2001 struct got_pathlist_entry *pe;
2002 struct got_object_id *pack_hash = NULL;
2003 int i, ch, fetchfd = -1, fetchstatus;
2004 pid_t fetchpid = -1;
2005 struct got_fetch_progress_arg fpa;
2006 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2007 int delete_refs = 0, replace_tags = 0;
2009 TAILQ_INIT(&refs);
2010 TAILQ_INIT(&symrefs);
2011 TAILQ_INIT(&wanted_branches);
2012 TAILQ_INIT(&wanted_refs);
2014 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2015 switch (ch) {
2016 case 'a':
2017 fetch_all_branches = 1;
2018 break;
2019 case 'b':
2020 error = got_pathlist_append(&wanted_branches,
2021 optarg, NULL);
2022 if (error)
2023 return error;
2024 break;
2025 case 'd':
2026 delete_refs = 1;
2027 break;
2028 case 'l':
2029 list_refs_only = 1;
2030 break;
2031 case 'r':
2032 repo_path = realpath(optarg, NULL);
2033 if (repo_path == NULL)
2034 return got_error_from_errno2("realpath",
2035 optarg);
2036 got_path_strip_trailing_slashes(repo_path);
2037 break;
2038 case 't':
2039 replace_tags = 1;
2040 break;
2041 case 'v':
2042 if (verbosity < 0)
2043 verbosity = 0;
2044 else if (verbosity < 3)
2045 verbosity++;
2046 break;
2047 case 'q':
2048 verbosity = -1;
2049 break;
2050 case 'R':
2051 error = got_pathlist_append(&wanted_refs,
2052 optarg, NULL);
2053 if (error)
2054 return error;
2055 break;
2056 default:
2057 usage_fetch();
2058 break;
2061 argc -= optind;
2062 argv += optind;
2064 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2065 errx(1, "-a and -b options are mutually exclusive");
2066 if (list_refs_only) {
2067 if (!TAILQ_EMPTY(&wanted_branches))
2068 errx(1, "-l and -b options are mutually exclusive");
2069 if (fetch_all_branches)
2070 errx(1, "-l and -a options are mutually exclusive");
2071 if (delete_refs)
2072 errx(1, "-l and -d options are mutually exclusive");
2073 if (verbosity == -1)
2074 errx(1, "-l and -q options are mutually exclusive");
2077 if (argc == 0)
2078 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2079 else if (argc == 1)
2080 remote_name = argv[0];
2081 else
2082 usage_fetch();
2084 cwd = getcwd(NULL, 0);
2085 if (cwd == NULL) {
2086 error = got_error_from_errno("getcwd");
2087 goto done;
2090 if (repo_path == NULL) {
2091 error = got_worktree_open(&worktree, cwd);
2092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2093 goto done;
2094 else
2095 error = NULL;
2096 if (worktree) {
2097 repo_path =
2098 strdup(got_worktree_get_repo_path(worktree));
2099 if (repo_path == NULL)
2100 error = got_error_from_errno("strdup");
2101 if (error)
2102 goto done;
2103 } else {
2104 repo_path = strdup(cwd);
2105 if (repo_path == NULL) {
2106 error = got_error_from_errno("strdup");
2107 goto done;
2112 error = got_repo_open(&repo, repo_path, NULL);
2113 if (error)
2114 goto done;
2116 if (worktree) {
2117 worktree_conf = got_worktree_get_gotconfig(worktree);
2118 if (worktree_conf) {
2119 got_gotconfig_get_remotes(&nremotes, &remotes,
2120 worktree_conf);
2121 for (i = 0; i < nremotes; i++) {
2122 remote = &remotes[i];
2123 if (strcmp(remote->name, remote_name) == 0)
2124 break;
2128 if (remote == NULL) {
2129 repo_conf = got_repo_get_gotconfig(repo);
2130 if (repo_conf) {
2131 got_gotconfig_get_remotes(&nremotes, &remotes,
2132 repo_conf);
2133 for (i = 0; i < nremotes; i++) {
2134 remote = &remotes[i];
2135 if (strcmp(remote->name, remote_name) == 0)
2136 break;
2140 if (remote == NULL) {
2141 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2142 for (i = 0; i < nremotes; i++) {
2143 remote = &remotes[i];
2144 if (strcmp(remote->name, remote_name) == 0)
2145 break;
2148 if (remote == NULL) {
2149 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2150 goto done;
2153 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2154 for (i = 0; i < remote->nbranches; i++) {
2155 got_pathlist_append(&wanted_branches,
2156 remote->branches[i], NULL);
2161 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2162 &repo_name, remote->url);
2163 if (error)
2164 goto done;
2166 if (strcmp(proto, "git") == 0) {
2167 #ifndef PROFILE
2168 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2169 "sendfd dns inet unveil", NULL) == -1)
2170 err(1, "pledge");
2171 #endif
2172 } else if (strcmp(proto, "git+ssh") == 0 ||
2173 strcmp(proto, "ssh") == 0) {
2174 #ifndef PROFILE
2175 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2176 "sendfd unveil", NULL) == -1)
2177 err(1, "pledge");
2178 #endif
2179 } else if (strcmp(proto, "http") == 0 ||
2180 strcmp(proto, "git+http") == 0) {
2181 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2182 goto done;
2183 } else {
2184 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2185 goto done;
2188 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2189 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2190 error = got_error_from_errno2("unveil",
2191 GOT_FETCH_PATH_SSH);
2192 goto done;
2195 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2196 if (error)
2197 goto done;
2199 if (verbosity >= 0)
2200 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2201 port ? ":" : "", port ? port : "");
2203 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2204 server_path, verbosity);
2205 if (error)
2206 goto done;
2208 fpa.last_scaled_size[0] = '\0';
2209 fpa.last_p_indexed = -1;
2210 fpa.last_p_resolved = -1;
2211 fpa.verbosity = verbosity;
2212 fpa.repo = repo;
2213 fpa.create_configs = 0;
2214 fpa.configs_created = 0;
2215 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2216 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2217 remote->mirror_references, fetch_all_branches, &wanted_branches,
2218 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2219 fetch_progress, &fpa);
2220 if (error)
2221 goto done;
2223 if (list_refs_only) {
2224 error = list_remote_refs(&symrefs, &refs);
2225 goto done;
2228 if (pack_hash == NULL) {
2229 if (verbosity >= 0)
2230 printf("Already up-to-date\n");
2231 } else if (verbosity >= 0) {
2232 error = got_object_id_str(&id_str, pack_hash);
2233 if (error)
2234 goto done;
2235 printf("\nFetched %s.pack\n", id_str);
2236 free(id_str);
2237 id_str = NULL;
2240 /* Update references provided with the pack file. */
2241 TAILQ_FOREACH(pe, &refs, entry) {
2242 const char *refname = pe->path;
2243 struct got_object_id *id = pe->data;
2244 struct got_reference *ref;
2245 char *remote_refname;
2247 if (is_wanted_ref(&wanted_refs, refname) &&
2248 !remote->mirror_references) {
2249 error = update_wanted_ref(refname, id,
2250 remote->name, verbosity, repo);
2251 if (error)
2252 goto done;
2253 continue;
2256 if (remote->mirror_references ||
2257 strncmp("refs/tags/", refname, 10) == 0) {
2258 error = got_ref_open(&ref, repo, refname, 1);
2259 if (error) {
2260 if (error->code != GOT_ERR_NOT_REF)
2261 goto done;
2262 error = create_ref(refname, id, verbosity,
2263 repo);
2264 if (error)
2265 goto done;
2266 } else {
2267 error = update_ref(ref, id, replace_tags,
2268 verbosity, repo);
2269 unlock_err = got_ref_unlock(ref);
2270 if (unlock_err && error == NULL)
2271 error = unlock_err;
2272 got_ref_close(ref);
2273 if (error)
2274 goto done;
2276 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2277 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2278 remote_name, refname + 11) == -1) {
2279 error = got_error_from_errno("asprintf");
2280 goto done;
2283 error = got_ref_open(&ref, repo, remote_refname, 1);
2284 if (error) {
2285 if (error->code != GOT_ERR_NOT_REF)
2286 goto done;
2287 error = create_ref(remote_refname, id,
2288 verbosity, repo);
2289 if (error)
2290 goto done;
2291 } else {
2292 error = update_ref(ref, id, replace_tags,
2293 verbosity, repo);
2294 unlock_err = got_ref_unlock(ref);
2295 if (unlock_err && error == NULL)
2296 error = unlock_err;
2297 got_ref_close(ref);
2298 if (error)
2299 goto done;
2302 /* Also create a local branch if none exists yet. */
2303 error = got_ref_open(&ref, repo, refname, 1);
2304 if (error) {
2305 if (error->code != GOT_ERR_NOT_REF)
2306 goto done;
2307 error = create_ref(refname, id, verbosity,
2308 repo);
2309 if (error)
2310 goto done;
2311 } else {
2312 unlock_err = got_ref_unlock(ref);
2313 if (unlock_err && error == NULL)
2314 error = unlock_err;
2315 got_ref_close(ref);
2319 if (delete_refs) {
2320 error = delete_missing_refs(&refs, &symrefs, remote,
2321 verbosity, repo);
2322 if (error)
2323 goto done;
2326 if (!remote->mirror_references) {
2327 /* Update remote HEAD reference if the server provided one. */
2328 TAILQ_FOREACH(pe, &symrefs, entry) {
2329 struct got_reference *target_ref;
2330 const char *refname = pe->path;
2331 const char *target = pe->data;
2332 char *remote_refname = NULL, *remote_target = NULL;
2334 if (strcmp(refname, GOT_REF_HEAD) != 0)
2335 continue;
2337 if (strncmp("refs/heads/", target, 11) != 0)
2338 continue;
2340 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2341 remote->name, refname) == -1) {
2342 error = got_error_from_errno("asprintf");
2343 goto done;
2345 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2346 remote->name, target + 11) == -1) {
2347 error = got_error_from_errno("asprintf");
2348 free(remote_refname);
2349 goto done;
2352 error = got_ref_open(&target_ref, repo, remote_target,
2353 0);
2354 if (error) {
2355 free(remote_refname);
2356 free(remote_target);
2357 if (error->code == GOT_ERR_NOT_REF) {
2358 error = NULL;
2359 continue;
2361 goto done;
2363 error = update_symref(remote_refname, target_ref,
2364 verbosity, repo);
2365 free(remote_refname);
2366 free(remote_target);
2367 got_ref_close(target_ref);
2368 if (error)
2369 goto done;
2372 done:
2373 if (fetchpid > 0) {
2374 if (kill(fetchpid, SIGTERM) == -1)
2375 error = got_error_from_errno("kill");
2376 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2377 error = got_error_from_errno("waitpid");
2379 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2380 error = got_error_from_errno("close");
2381 if (repo)
2382 got_repo_close(repo);
2383 if (worktree)
2384 got_worktree_close(worktree);
2385 TAILQ_FOREACH(pe, &refs, entry) {
2386 free((void *)pe->path);
2387 free(pe->data);
2389 got_pathlist_free(&refs);
2390 TAILQ_FOREACH(pe, &symrefs, entry) {
2391 free((void *)pe->path);
2392 free(pe->data);
2394 got_pathlist_free(&symrefs);
2395 got_pathlist_free(&wanted_branches);
2396 got_pathlist_free(&wanted_refs);
2397 free(id_str);
2398 free(cwd);
2399 free(repo_path);
2400 free(pack_hash);
2401 free(proto);
2402 free(host);
2403 free(port);
2404 free(server_path);
2405 free(repo_name);
2406 return error;
2410 __dead static void
2411 usage_checkout(void)
2413 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2414 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2415 exit(1);
2418 static void
2419 show_worktree_base_ref_warning(void)
2421 fprintf(stderr, "%s: warning: could not create a reference "
2422 "to the work tree's base commit; the commit could be "
2423 "garbage-collected by Git; making the repository "
2424 "writable and running 'got update' will prevent this\n",
2425 getprogname());
2428 struct got_checkout_progress_arg {
2429 const char *worktree_path;
2430 int had_base_commit_ref_error;
2433 static const struct got_error *
2434 checkout_progress(void *arg, unsigned char status, const char *path)
2436 struct got_checkout_progress_arg *a = arg;
2438 /* Base commit bump happens silently. */
2439 if (status == GOT_STATUS_BUMP_BASE)
2440 return NULL;
2442 if (status == GOT_STATUS_BASE_REF_ERR) {
2443 a->had_base_commit_ref_error = 1;
2444 return NULL;
2447 while (path[0] == '/')
2448 path++;
2450 printf("%c %s/%s\n", status, a->worktree_path, path);
2451 return NULL;
2454 static const struct got_error *
2455 check_cancelled(void *arg)
2457 if (sigint_received || sigpipe_received)
2458 return got_error(GOT_ERR_CANCELLED);
2459 return NULL;
2462 static const struct got_error *
2463 check_linear_ancestry(struct got_object_id *commit_id,
2464 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2465 struct got_repository *repo)
2467 const struct got_error *err = NULL;
2468 struct got_object_id *yca_id;
2470 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2471 commit_id, base_commit_id, repo, check_cancelled, NULL);
2472 if (err)
2473 return err;
2475 if (yca_id == NULL)
2476 return got_error(GOT_ERR_ANCESTRY);
2479 * Require a straight line of history between the target commit
2480 * and the work tree's base commit.
2482 * Non-linear situations such as this require a rebase:
2484 * (commit) D F (base_commit)
2485 * \ /
2486 * C E
2487 * \ /
2488 * B (yca)
2489 * |
2490 * A
2492 * 'got update' only handles linear cases:
2493 * Update forwards in time: A (base/yca) - B - C - D (commit)
2494 * Update backwards in time: D (base) - C - B - A (commit/yca)
2496 if (allow_forwards_in_time_only) {
2497 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2498 return got_error(GOT_ERR_ANCESTRY);
2499 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2500 got_object_id_cmp(base_commit_id, yca_id) != 0)
2501 return got_error(GOT_ERR_ANCESTRY);
2503 free(yca_id);
2504 return NULL;
2507 static const struct got_error *
2508 check_same_branch(struct got_object_id *commit_id,
2509 struct got_reference *head_ref, struct got_object_id *yca_id,
2510 struct got_repository *repo)
2512 const struct got_error *err = NULL;
2513 struct got_commit_graph *graph = NULL;
2514 struct got_object_id *head_commit_id = NULL;
2515 int is_same_branch = 0;
2517 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2518 if (err)
2519 goto done;
2521 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2522 is_same_branch = 1;
2523 goto done;
2525 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2526 is_same_branch = 1;
2527 goto done;
2530 err = got_commit_graph_open(&graph, "/", 1);
2531 if (err)
2532 goto done;
2534 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2535 check_cancelled, NULL);
2536 if (err)
2537 goto done;
2539 for (;;) {
2540 struct got_object_id *id;
2541 err = got_commit_graph_iter_next(&id, graph, repo,
2542 check_cancelled, NULL);
2543 if (err) {
2544 if (err->code == GOT_ERR_ITER_COMPLETED)
2545 err = NULL;
2546 break;
2549 if (id) {
2550 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2551 break;
2552 if (got_object_id_cmp(id, commit_id) == 0) {
2553 is_same_branch = 1;
2554 break;
2558 done:
2559 if (graph)
2560 got_commit_graph_close(graph);
2561 free(head_commit_id);
2562 if (!err && !is_same_branch)
2563 err = got_error(GOT_ERR_ANCESTRY);
2564 return err;
2567 static const struct got_error *
2568 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2570 static char msg[512];
2571 const char *branch_name;
2573 if (got_ref_is_symbolic(ref))
2574 branch_name = got_ref_get_symref_target(ref);
2575 else
2576 branch_name = got_ref_get_name(ref);
2578 if (strncmp("refs/heads/", branch_name, 11) == 0)
2579 branch_name += 11;
2581 snprintf(msg, sizeof(msg),
2582 "target commit is not contained in branch '%s'; "
2583 "the branch to use must be specified with -b; "
2584 "if necessary a new branch can be created for "
2585 "this commit with 'got branch -c %s BRANCH_NAME'",
2586 branch_name, commit_id_str);
2588 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2591 static const struct got_error *
2592 cmd_checkout(int argc, char *argv[])
2594 const struct got_error *error = NULL;
2595 struct got_repository *repo = NULL;
2596 struct got_reference *head_ref = NULL;
2597 struct got_worktree *worktree = NULL;
2598 char *repo_path = NULL;
2599 char *worktree_path = NULL;
2600 const char *path_prefix = "";
2601 const char *branch_name = GOT_REF_HEAD;
2602 char *commit_id_str = NULL;
2603 char *cwd = NULL, *path = NULL;
2604 int ch, same_path_prefix, allow_nonempty = 0;
2605 struct got_pathlist_head paths;
2606 struct got_checkout_progress_arg cpa;
2608 TAILQ_INIT(&paths);
2610 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2611 switch (ch) {
2612 case 'b':
2613 branch_name = optarg;
2614 break;
2615 case 'c':
2616 commit_id_str = strdup(optarg);
2617 if (commit_id_str == NULL)
2618 return got_error_from_errno("strdup");
2619 break;
2620 case 'E':
2621 allow_nonempty = 1;
2622 break;
2623 case 'p':
2624 path_prefix = optarg;
2625 break;
2626 default:
2627 usage_checkout();
2628 /* NOTREACHED */
2632 argc -= optind;
2633 argv += optind;
2635 #ifndef PROFILE
2636 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2637 "unveil", NULL) == -1)
2638 err(1, "pledge");
2639 #endif
2640 if (argc == 1) {
2641 char *base, *dotgit;
2642 repo_path = realpath(argv[0], NULL);
2643 if (repo_path == NULL)
2644 return got_error_from_errno2("realpath", argv[0]);
2645 cwd = getcwd(NULL, 0);
2646 if (cwd == NULL) {
2647 error = got_error_from_errno("getcwd");
2648 goto done;
2650 if (path_prefix[0])
2651 path = strdup(path_prefix);
2652 else
2653 path = strdup(repo_path);
2654 if (path == NULL) {
2655 error = got_error_from_errno("strdup");
2656 goto done;
2658 base = basename(path);
2659 if (base == NULL) {
2660 error = got_error_from_errno2("basename", path);
2661 goto done;
2663 dotgit = strstr(base, ".git");
2664 if (dotgit)
2665 *dotgit = '\0';
2666 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2667 error = got_error_from_errno("asprintf");
2668 goto done;
2670 } else if (argc == 2) {
2671 repo_path = realpath(argv[0], NULL);
2672 if (repo_path == NULL) {
2673 error = got_error_from_errno2("realpath", argv[0]);
2674 goto done;
2676 worktree_path = realpath(argv[1], NULL);
2677 if (worktree_path == NULL) {
2678 if (errno != ENOENT) {
2679 error = got_error_from_errno2("realpath",
2680 argv[1]);
2681 goto done;
2683 worktree_path = strdup(argv[1]);
2684 if (worktree_path == NULL) {
2685 error = got_error_from_errno("strdup");
2686 goto done;
2689 } else
2690 usage_checkout();
2692 got_path_strip_trailing_slashes(repo_path);
2693 got_path_strip_trailing_slashes(worktree_path);
2695 error = got_repo_open(&repo, repo_path, NULL);
2696 if (error != NULL)
2697 goto done;
2699 /* Pre-create work tree path for unveil(2) */
2700 error = got_path_mkdir(worktree_path);
2701 if (error) {
2702 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2703 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2704 goto done;
2705 if (!allow_nonempty &&
2706 !got_path_dir_is_empty(worktree_path)) {
2707 error = got_error_path(worktree_path,
2708 GOT_ERR_DIR_NOT_EMPTY);
2709 goto done;
2713 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2714 if (error)
2715 goto done;
2717 error = got_ref_open(&head_ref, repo, branch_name, 0);
2718 if (error != NULL)
2719 goto done;
2721 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2722 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2723 goto done;
2725 error = got_worktree_open(&worktree, worktree_path);
2726 if (error != NULL)
2727 goto done;
2729 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2730 path_prefix);
2731 if (error != NULL)
2732 goto done;
2733 if (!same_path_prefix) {
2734 error = got_error(GOT_ERR_PATH_PREFIX);
2735 goto done;
2738 if (commit_id_str) {
2739 struct got_object_id *commit_id;
2740 error = got_repo_match_object_id(&commit_id, NULL,
2741 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2742 if (error)
2743 goto done;
2744 error = check_linear_ancestry(commit_id,
2745 got_worktree_get_base_commit_id(worktree), 0, repo);
2746 if (error != NULL) {
2747 free(commit_id);
2748 if (error->code == GOT_ERR_ANCESTRY) {
2749 error = checkout_ancestry_error(
2750 head_ref, commit_id_str);
2752 goto done;
2754 error = check_same_branch(commit_id, head_ref, NULL, repo);
2755 if (error) {
2756 if (error->code == GOT_ERR_ANCESTRY) {
2757 error = checkout_ancestry_error(
2758 head_ref, commit_id_str);
2760 goto done;
2762 error = got_worktree_set_base_commit_id(worktree, repo,
2763 commit_id);
2764 free(commit_id);
2765 if (error)
2766 goto done;
2769 error = got_pathlist_append(&paths, "", NULL);
2770 if (error)
2771 goto done;
2772 cpa.worktree_path = worktree_path;
2773 cpa.had_base_commit_ref_error = 0;
2774 error = got_worktree_checkout_files(worktree, &paths, repo,
2775 checkout_progress, &cpa, check_cancelled, NULL);
2776 if (error != NULL)
2777 goto done;
2779 printf("Now shut up and hack\n");
2780 if (cpa.had_base_commit_ref_error)
2781 show_worktree_base_ref_warning();
2782 done:
2783 got_pathlist_free(&paths);
2784 free(commit_id_str);
2785 free(repo_path);
2786 free(worktree_path);
2787 free(cwd);
2788 free(path);
2789 return error;
2792 struct got_update_progress_arg {
2793 int did_something;
2794 int conflicts;
2795 int obstructed;
2796 int not_updated;
2799 void
2800 print_update_progress_stats(struct got_update_progress_arg *upa)
2802 if (!upa->did_something)
2803 return;
2805 if (upa->conflicts > 0)
2806 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2807 if (upa->obstructed > 0)
2808 printf("File paths obstructed by a non-regular file: %d\n",
2809 upa->obstructed);
2810 if (upa->not_updated > 0)
2811 printf("Files not updated because of existing merge "
2812 "conflicts: %d\n", upa->not_updated);
2815 __dead static void
2816 usage_update(void)
2818 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2819 getprogname());
2820 exit(1);
2823 static const struct got_error *
2824 update_progress(void *arg, unsigned char status, const char *path)
2826 struct got_update_progress_arg *upa = arg;
2828 if (status == GOT_STATUS_EXISTS ||
2829 status == GOT_STATUS_BASE_REF_ERR)
2830 return NULL;
2832 upa->did_something = 1;
2834 /* Base commit bump happens silently. */
2835 if (status == GOT_STATUS_BUMP_BASE)
2836 return NULL;
2838 if (status == GOT_STATUS_CONFLICT)
2839 upa->conflicts++;
2840 if (status == GOT_STATUS_OBSTRUCTED)
2841 upa->obstructed++;
2842 if (status == GOT_STATUS_CANNOT_UPDATE)
2843 upa->not_updated++;
2845 while (path[0] == '/')
2846 path++;
2847 printf("%c %s\n", status, path);
2848 return NULL;
2851 static const struct got_error *
2852 switch_head_ref(struct got_reference *head_ref,
2853 struct got_object_id *commit_id, struct got_worktree *worktree,
2854 struct got_repository *repo)
2856 const struct got_error *err = NULL;
2857 char *base_id_str;
2858 int ref_has_moved = 0;
2860 /* Trivial case: switching between two different references. */
2861 if (strcmp(got_ref_get_name(head_ref),
2862 got_worktree_get_head_ref_name(worktree)) != 0) {
2863 printf("Switching work tree from %s to %s\n",
2864 got_worktree_get_head_ref_name(worktree),
2865 got_ref_get_name(head_ref));
2866 return got_worktree_set_head_ref(worktree, head_ref);
2869 err = check_linear_ancestry(commit_id,
2870 got_worktree_get_base_commit_id(worktree), 0, repo);
2871 if (err) {
2872 if (err->code != GOT_ERR_ANCESTRY)
2873 return err;
2874 ref_has_moved = 1;
2876 if (!ref_has_moved)
2877 return NULL;
2879 /* Switching to a rebased branch with the same reference name. */
2880 err = got_object_id_str(&base_id_str,
2881 got_worktree_get_base_commit_id(worktree));
2882 if (err)
2883 return err;
2884 printf("Reference %s now points at a different branch\n",
2885 got_worktree_get_head_ref_name(worktree));
2886 printf("Switching work tree from %s to %s\n", base_id_str,
2887 got_worktree_get_head_ref_name(worktree));
2888 return NULL;
2891 static const struct got_error *
2892 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2894 const struct got_error *err;
2895 int in_progress;
2897 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2898 if (err)
2899 return err;
2900 if (in_progress)
2901 return got_error(GOT_ERR_REBASING);
2903 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2904 if (err)
2905 return err;
2906 if (in_progress)
2907 return got_error(GOT_ERR_HISTEDIT_BUSY);
2909 return NULL;
2912 static const struct got_error *
2913 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2914 char *argv[], struct got_worktree *worktree)
2916 const struct got_error *err = NULL;
2917 char *path;
2918 int i;
2920 if (argc == 0) {
2921 path = strdup("");
2922 if (path == NULL)
2923 return got_error_from_errno("strdup");
2924 return got_pathlist_append(paths, path, NULL);
2927 for (i = 0; i < argc; i++) {
2928 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2929 if (err)
2930 break;
2931 err = got_pathlist_append(paths, path, NULL);
2932 if (err) {
2933 free(path);
2934 break;
2938 return err;
2941 static const struct got_error *
2942 wrap_not_worktree_error(const struct got_error *orig_err,
2943 const char *cmdname, const char *path)
2945 const struct got_error *err;
2946 struct got_repository *repo;
2947 static char msg[512];
2949 err = got_repo_open(&repo, path, NULL);
2950 if (err)
2951 return orig_err;
2953 snprintf(msg, sizeof(msg),
2954 "'got %s' needs a work tree in addition to a git repository\n"
2955 "Work trees can be checked out from this Git repository with "
2956 "'got checkout'.\n"
2957 "The got(1) manual page contains more information.", cmdname);
2958 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2959 got_repo_close(repo);
2960 return err;
2963 static const struct got_error *
2964 cmd_update(int argc, char *argv[])
2966 const struct got_error *error = NULL;
2967 struct got_repository *repo = NULL;
2968 struct got_worktree *worktree = NULL;
2969 char *worktree_path = NULL;
2970 struct got_object_id *commit_id = NULL;
2971 char *commit_id_str = NULL;
2972 const char *branch_name = NULL;
2973 struct got_reference *head_ref = NULL;
2974 struct got_pathlist_head paths;
2975 struct got_pathlist_entry *pe;
2976 int ch;
2977 struct got_update_progress_arg upa;
2979 TAILQ_INIT(&paths);
2981 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2982 switch (ch) {
2983 case 'b':
2984 branch_name = optarg;
2985 break;
2986 case 'c':
2987 commit_id_str = strdup(optarg);
2988 if (commit_id_str == NULL)
2989 return got_error_from_errno("strdup");
2990 break;
2991 default:
2992 usage_update();
2993 /* NOTREACHED */
2997 argc -= optind;
2998 argv += optind;
3000 #ifndef PROFILE
3001 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3002 "unveil", NULL) == -1)
3003 err(1, "pledge");
3004 #endif
3005 worktree_path = getcwd(NULL, 0);
3006 if (worktree_path == NULL) {
3007 error = got_error_from_errno("getcwd");
3008 goto done;
3010 error = got_worktree_open(&worktree, worktree_path);
3011 if (error) {
3012 if (error->code == GOT_ERR_NOT_WORKTREE)
3013 error = wrap_not_worktree_error(error, "update",
3014 worktree_path);
3015 goto done;
3018 error = check_rebase_or_histedit_in_progress(worktree);
3019 if (error)
3020 goto done;
3022 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3023 NULL);
3024 if (error != NULL)
3025 goto done;
3027 error = apply_unveil(got_repo_get_path(repo), 0,
3028 got_worktree_get_root_path(worktree));
3029 if (error)
3030 goto done;
3032 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3033 if (error)
3034 goto done;
3036 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3037 got_worktree_get_head_ref_name(worktree), 0);
3038 if (error != NULL)
3039 goto done;
3040 if (commit_id_str == NULL) {
3041 error = got_ref_resolve(&commit_id, repo, head_ref);
3042 if (error != NULL)
3043 goto done;
3044 error = got_object_id_str(&commit_id_str, commit_id);
3045 if (error != NULL)
3046 goto done;
3047 } else {
3048 error = got_repo_match_object_id(&commit_id, NULL,
3049 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3050 free(commit_id_str);
3051 commit_id_str = NULL;
3052 if (error)
3053 goto done;
3054 error = got_object_id_str(&commit_id_str, commit_id);
3055 if (error)
3056 goto done;
3059 if (branch_name) {
3060 struct got_object_id *head_commit_id;
3061 TAILQ_FOREACH(pe, &paths, entry) {
3062 if (pe->path_len == 0)
3063 continue;
3064 error = got_error_msg(GOT_ERR_BAD_PATH,
3065 "switching between branches requires that "
3066 "the entire work tree gets updated");
3067 goto done;
3069 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3070 if (error)
3071 goto done;
3072 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3073 repo);
3074 free(head_commit_id);
3075 if (error != NULL)
3076 goto done;
3077 error = check_same_branch(commit_id, head_ref, NULL, repo);
3078 if (error)
3079 goto done;
3080 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3081 if (error)
3082 goto done;
3083 } else {
3084 error = check_linear_ancestry(commit_id,
3085 got_worktree_get_base_commit_id(worktree), 0, repo);
3086 if (error != NULL) {
3087 if (error->code == GOT_ERR_ANCESTRY)
3088 error = got_error(GOT_ERR_BRANCH_MOVED);
3089 goto done;
3091 error = check_same_branch(commit_id, head_ref, NULL, repo);
3092 if (error)
3093 goto done;
3096 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3097 commit_id) != 0) {
3098 error = got_worktree_set_base_commit_id(worktree, repo,
3099 commit_id);
3100 if (error)
3101 goto done;
3104 memset(&upa, 0, sizeof(upa));
3105 error = got_worktree_checkout_files(worktree, &paths, repo,
3106 update_progress, &upa, check_cancelled, NULL);
3107 if (error != NULL)
3108 goto done;
3110 if (upa.did_something)
3111 printf("Updated to commit %s\n", commit_id_str);
3112 else
3113 printf("Already up-to-date\n");
3114 print_update_progress_stats(&upa);
3115 done:
3116 free(worktree_path);
3117 TAILQ_FOREACH(pe, &paths, entry)
3118 free((char *)pe->path);
3119 got_pathlist_free(&paths);
3120 free(commit_id);
3121 free(commit_id_str);
3122 return error;
3125 static const struct got_error *
3126 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3127 const char *path, int diff_context, int ignore_whitespace,
3128 struct got_repository *repo)
3130 const struct got_error *err = NULL;
3131 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3133 if (blob_id1) {
3134 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3135 if (err)
3136 goto done;
3139 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3140 if (err)
3141 goto done;
3143 while (path[0] == '/')
3144 path++;
3145 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3146 ignore_whitespace, stdout);
3147 done:
3148 if (blob1)
3149 got_object_blob_close(blob1);
3150 got_object_blob_close(blob2);
3151 return err;
3154 static const struct got_error *
3155 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3156 const char *path, int diff_context, int ignore_whitespace,
3157 struct got_repository *repo)
3159 const struct got_error *err = NULL;
3160 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3161 struct got_diff_blob_output_unidiff_arg arg;
3163 if (tree_id1) {
3164 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3165 if (err)
3166 goto done;
3169 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3170 if (err)
3171 goto done;
3173 arg.diff_context = diff_context;
3174 arg.ignore_whitespace = ignore_whitespace;
3175 arg.outfile = stdout;
3176 while (path[0] == '/')
3177 path++;
3178 err = got_diff_tree(tree1, tree2, path, path, repo,
3179 got_diff_blob_output_unidiff, &arg, 1);
3180 done:
3181 if (tree1)
3182 got_object_tree_close(tree1);
3183 if (tree2)
3184 got_object_tree_close(tree2);
3185 return err;
3188 static const struct got_error *
3189 get_changed_paths(struct got_pathlist_head *paths,
3190 struct got_commit_object *commit, struct got_repository *repo)
3192 const struct got_error *err = NULL;
3193 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3194 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3195 struct got_object_qid *qid;
3197 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3198 if (qid != NULL) {
3199 struct got_commit_object *pcommit;
3200 err = got_object_open_as_commit(&pcommit, repo,
3201 qid->id);
3202 if (err)
3203 return err;
3205 tree_id1 = got_object_commit_get_tree_id(pcommit);
3206 got_object_commit_close(pcommit);
3210 if (tree_id1) {
3211 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3212 if (err)
3213 goto done;
3216 tree_id2 = got_object_commit_get_tree_id(commit);
3217 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3218 if (err)
3219 goto done;
3221 err = got_diff_tree(tree1, tree2, "", "", repo,
3222 got_diff_tree_collect_changed_paths, paths, 0);
3223 done:
3224 if (tree1)
3225 got_object_tree_close(tree1);
3226 if (tree2)
3227 got_object_tree_close(tree2);
3228 return err;
3231 static const struct got_error *
3232 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3233 const char *path, int diff_context, struct got_repository *repo)
3235 const struct got_error *err = NULL;
3236 struct got_commit_object *pcommit = NULL;
3237 char *id_str1 = NULL, *id_str2 = NULL;
3238 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3239 struct got_object_qid *qid;
3241 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3242 if (qid != NULL) {
3243 err = got_object_open_as_commit(&pcommit, repo,
3244 qid->id);
3245 if (err)
3246 return err;
3249 if (path && path[0] != '\0') {
3250 int obj_type;
3251 err = got_object_id_by_path(&obj_id2, repo, id, path);
3252 if (err)
3253 goto done;
3254 err = got_object_id_str(&id_str2, obj_id2);
3255 if (err) {
3256 free(obj_id2);
3257 goto done;
3259 if (pcommit) {
3260 err = got_object_id_by_path(&obj_id1, repo,
3261 qid->id, path);
3262 if (err) {
3263 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3264 free(obj_id2);
3265 goto done;
3267 } else {
3268 err = got_object_id_str(&id_str1, obj_id1);
3269 if (err) {
3270 free(obj_id2);
3271 goto done;
3275 err = got_object_get_type(&obj_type, repo, obj_id2);
3276 if (err) {
3277 free(obj_id2);
3278 goto done;
3280 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3281 switch (obj_type) {
3282 case GOT_OBJ_TYPE_BLOB:
3283 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3284 0, repo);
3285 break;
3286 case GOT_OBJ_TYPE_TREE:
3287 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3288 0, repo);
3289 break;
3290 default:
3291 err = got_error(GOT_ERR_OBJ_TYPE);
3292 break;
3294 free(obj_id1);
3295 free(obj_id2);
3296 } else {
3297 obj_id2 = got_object_commit_get_tree_id(commit);
3298 err = got_object_id_str(&id_str2, obj_id2);
3299 if (err)
3300 goto done;
3301 obj_id1 = got_object_commit_get_tree_id(pcommit);
3302 err = got_object_id_str(&id_str1, obj_id1);
3303 if (err)
3304 goto done;
3305 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3306 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3308 done:
3309 free(id_str1);
3310 free(id_str2);
3311 if (pcommit)
3312 got_object_commit_close(pcommit);
3313 return err;
3316 static char *
3317 get_datestr(time_t *time, char *datebuf)
3319 struct tm mytm, *tm;
3320 char *p, *s;
3322 tm = gmtime_r(time, &mytm);
3323 if (tm == NULL)
3324 return NULL;
3325 s = asctime_r(tm, datebuf);
3326 if (s == NULL)
3327 return NULL;
3328 p = strchr(s, '\n');
3329 if (p)
3330 *p = '\0';
3331 return s;
3334 static const struct got_error *
3335 match_logmsg(int *have_match, struct got_object_id *id,
3336 struct got_commit_object *commit, regex_t *regex)
3338 const struct got_error *err = NULL;
3339 regmatch_t regmatch;
3340 char *id_str = NULL, *logmsg = NULL;
3342 *have_match = 0;
3344 err = got_object_id_str(&id_str, id);
3345 if (err)
3346 return err;
3348 err = got_object_commit_get_logmsg(&logmsg, commit);
3349 if (err)
3350 goto done;
3352 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3353 *have_match = 1;
3354 done:
3355 free(id_str);
3356 free(logmsg);
3357 return err;
3360 static void
3361 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3362 regex_t *regex)
3364 regmatch_t regmatch;
3365 struct got_pathlist_entry *pe;
3367 *have_match = 0;
3369 TAILQ_FOREACH(pe, changed_paths, entry) {
3370 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3371 *have_match = 1;
3372 break;
3377 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3379 static const struct got_error *
3380 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3381 struct got_repository *repo, const char *path,
3382 struct got_pathlist_head *changed_paths, int show_patch,
3383 int diff_context, struct got_reflist_head *refs)
3385 const struct got_error *err = NULL;
3386 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3387 char datebuf[26];
3388 time_t committer_time;
3389 const char *author, *committer;
3390 char *refs_str = NULL;
3391 struct got_reflist_entry *re;
3393 SIMPLEQ_FOREACH(re, refs, entry) {
3394 char *s;
3395 const char *name;
3396 struct got_tag_object *tag = NULL;
3397 struct got_object_id *ref_id;
3398 int cmp;
3400 name = got_ref_get_name(re->ref);
3401 if (strcmp(name, GOT_REF_HEAD) == 0)
3402 continue;
3403 if (strncmp(name, "refs/", 5) == 0)
3404 name += 5;
3405 if (strncmp(name, "got/", 4) == 0)
3406 continue;
3407 if (strncmp(name, "heads/", 6) == 0)
3408 name += 6;
3409 if (strncmp(name, "remotes/", 8) == 0) {
3410 name += 8;
3411 s = strstr(name, "/" GOT_REF_HEAD);
3412 if (s != NULL && s[strlen(s)] == '\0')
3413 continue;
3415 err = got_ref_resolve(&ref_id, repo, re->ref);
3416 if (err)
3417 return err;
3418 if (strncmp(name, "tags/", 5) == 0) {
3419 err = got_object_open_as_tag(&tag, repo, ref_id);
3420 if (err) {
3421 if (err->code != GOT_ERR_OBJ_TYPE) {
3422 free(ref_id);
3423 return err;
3425 /* Ref points at something other than a tag. */
3426 err = NULL;
3427 tag = NULL;
3430 cmp = got_object_id_cmp(tag ?
3431 got_object_tag_get_object_id(tag) : ref_id, id);
3432 free(ref_id);
3433 if (tag)
3434 got_object_tag_close(tag);
3435 if (cmp != 0)
3436 continue;
3437 s = refs_str;
3438 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3439 name) == -1) {
3440 err = got_error_from_errno("asprintf");
3441 free(s);
3442 return err;
3444 free(s);
3446 err = got_object_id_str(&id_str, id);
3447 if (err)
3448 return err;
3450 printf(GOT_COMMIT_SEP_STR);
3451 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3452 refs_str ? refs_str : "", refs_str ? ")" : "");
3453 free(id_str);
3454 id_str = NULL;
3455 free(refs_str);
3456 refs_str = NULL;
3457 printf("from: %s\n", got_object_commit_get_author(commit));
3458 committer_time = got_object_commit_get_committer_time(commit);
3459 datestr = get_datestr(&committer_time, datebuf);
3460 if (datestr)
3461 printf("date: %s UTC\n", datestr);
3462 author = got_object_commit_get_author(commit);
3463 committer = got_object_commit_get_committer(commit);
3464 if (strcmp(author, committer) != 0)
3465 printf("via: %s\n", committer);
3466 if (got_object_commit_get_nparents(commit) > 1) {
3467 const struct got_object_id_queue *parent_ids;
3468 struct got_object_qid *qid;
3469 int n = 1;
3470 parent_ids = got_object_commit_get_parent_ids(commit);
3471 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3472 err = got_object_id_str(&id_str, qid->id);
3473 if (err)
3474 return err;
3475 printf("parent %d: %s\n", n++, id_str);
3476 free(id_str);
3480 err = got_object_commit_get_logmsg(&logmsg0, commit);
3481 if (err)
3482 return err;
3484 logmsg = logmsg0;
3485 do {
3486 line = strsep(&logmsg, "\n");
3487 if (line)
3488 printf(" %s\n", line);
3489 } while (line);
3490 free(logmsg0);
3492 if (changed_paths) {
3493 struct got_pathlist_entry *pe;
3494 TAILQ_FOREACH(pe, changed_paths, entry) {
3495 struct got_diff_changed_path *cp = pe->data;
3496 printf(" %c %s\n", cp->status, pe->path);
3498 printf("\n");
3500 if (show_patch) {
3501 err = print_patch(commit, id, path, diff_context, repo);
3502 if (err == 0)
3503 printf("\n");
3506 if (fflush(stdout) != 0 && err == NULL)
3507 err = got_error_from_errno("fflush");
3508 return err;
3511 static const struct got_error *
3512 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3513 struct got_repository *repo, const char *path, int show_changed_paths,
3514 int show_patch, const char *search_pattern, int diff_context, int limit,
3515 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3517 const struct got_error *err;
3518 struct got_commit_graph *graph;
3519 regex_t regex;
3520 int have_match;
3521 struct got_object_id_queue reversed_commits;
3522 struct got_object_qid *qid;
3523 struct got_commit_object *commit;
3524 struct got_pathlist_head changed_paths;
3525 struct got_pathlist_entry *pe;
3527 SIMPLEQ_INIT(&reversed_commits);
3528 TAILQ_INIT(&changed_paths);
3530 if (search_pattern && regcomp(&regex, search_pattern,
3531 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3532 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3534 err = got_commit_graph_open(&graph, path, !log_branches);
3535 if (err)
3536 return err;
3537 err = got_commit_graph_iter_start(graph, root_id, repo,
3538 check_cancelled, NULL);
3539 if (err)
3540 goto done;
3541 for (;;) {
3542 struct got_object_id *id;
3544 if (sigint_received || sigpipe_received)
3545 break;
3547 err = got_commit_graph_iter_next(&id, graph, repo,
3548 check_cancelled, NULL);
3549 if (err) {
3550 if (err->code == GOT_ERR_ITER_COMPLETED)
3551 err = NULL;
3552 break;
3554 if (id == NULL)
3555 break;
3557 err = got_object_open_as_commit(&commit, repo, id);
3558 if (err)
3559 break;
3561 if (show_changed_paths && !reverse_display_order) {
3562 err = get_changed_paths(&changed_paths, commit, repo);
3563 if (err)
3564 break;
3567 if (search_pattern) {
3568 err = match_logmsg(&have_match, id, commit, &regex);
3569 if (err) {
3570 got_object_commit_close(commit);
3571 break;
3573 if (have_match == 0 && show_changed_paths)
3574 match_changed_paths(&have_match,
3575 &changed_paths, &regex);
3576 if (have_match == 0) {
3577 got_object_commit_close(commit);
3578 TAILQ_FOREACH(pe, &changed_paths, entry) {
3579 free((char *)pe->path);
3580 free(pe->data);
3582 got_pathlist_free(&changed_paths);
3583 continue;
3587 if (reverse_display_order) {
3588 err = got_object_qid_alloc(&qid, id);
3589 if (err)
3590 break;
3591 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3592 got_object_commit_close(commit);
3593 } else {
3594 err = print_commit(commit, id, repo, path,
3595 show_changed_paths ? &changed_paths : NULL,
3596 show_patch, diff_context, refs);
3597 got_object_commit_close(commit);
3598 if (err)
3599 break;
3601 if ((limit && --limit == 0) ||
3602 (end_id && got_object_id_cmp(id, end_id) == 0))
3603 break;
3605 TAILQ_FOREACH(pe, &changed_paths, entry) {
3606 free((char *)pe->path);
3607 free(pe->data);
3609 got_pathlist_free(&changed_paths);
3611 if (reverse_display_order) {
3612 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3613 err = got_object_open_as_commit(&commit, repo, qid->id);
3614 if (err)
3615 break;
3616 if (show_changed_paths) {
3617 err = get_changed_paths(&changed_paths,
3618 commit, repo);
3619 if (err)
3620 break;
3622 err = print_commit(commit, qid->id, repo, path,
3623 show_changed_paths ? &changed_paths : NULL,
3624 show_patch, diff_context, refs);
3625 got_object_commit_close(commit);
3626 if (err)
3627 break;
3628 TAILQ_FOREACH(pe, &changed_paths, entry) {
3629 free((char *)pe->path);
3630 free(pe->data);
3632 got_pathlist_free(&changed_paths);
3635 done:
3636 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3637 qid = SIMPLEQ_FIRST(&reversed_commits);
3638 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3639 got_object_qid_free(qid);
3641 TAILQ_FOREACH(pe, &changed_paths, entry) {
3642 free((char *)pe->path);
3643 free(pe->data);
3645 got_pathlist_free(&changed_paths);
3646 if (search_pattern)
3647 regfree(&regex);
3648 got_commit_graph_close(graph);
3649 return err;
3652 __dead static void
3653 usage_log(void)
3655 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3656 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3657 "[-R] [path]\n", getprogname());
3658 exit(1);
3661 static int
3662 get_default_log_limit(void)
3664 const char *got_default_log_limit;
3665 long long n;
3666 const char *errstr;
3668 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3669 if (got_default_log_limit == NULL)
3670 return 0;
3671 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3672 if (errstr != NULL)
3673 return 0;
3674 return n;
3677 static const struct got_error *
3678 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3679 struct got_repository *repo)
3681 const struct got_error *err = NULL;
3682 struct got_reference *ref;
3684 *id = NULL;
3686 err = got_ref_open(&ref, repo, commit_arg, 0);
3687 if (err == NULL) {
3688 int obj_type;
3689 err = got_ref_resolve(id, repo, ref);
3690 got_ref_close(ref);
3691 if (err)
3692 return err;
3693 err = got_object_get_type(&obj_type, repo, *id);
3694 if (err)
3695 return err;
3696 if (obj_type == GOT_OBJ_TYPE_TAG) {
3697 struct got_tag_object *tag;
3698 err = got_object_open_as_tag(&tag, repo, *id);
3699 if (err)
3700 return err;
3701 if (got_object_tag_get_object_type(tag) !=
3702 GOT_OBJ_TYPE_COMMIT) {
3703 got_object_tag_close(tag);
3704 return got_error(GOT_ERR_OBJ_TYPE);
3706 free(*id);
3707 *id = got_object_id_dup(
3708 got_object_tag_get_object_id(tag));
3709 if (*id == NULL)
3710 err = got_error_from_errno(
3711 "got_object_id_dup");
3712 got_object_tag_close(tag);
3713 if (err)
3714 return err;
3715 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3716 return got_error(GOT_ERR_OBJ_TYPE);
3717 } else {
3718 err = got_repo_match_object_id_prefix(id, commit_arg,
3719 GOT_OBJ_TYPE_COMMIT, repo);
3722 return err;
3725 static const struct got_error *
3726 cmd_log(int argc, char *argv[])
3728 const struct got_error *error;
3729 struct got_repository *repo = NULL;
3730 struct got_worktree *worktree = NULL;
3731 struct got_object_id *start_id = NULL, *end_id = NULL;
3732 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3733 const char *start_commit = NULL, *end_commit = NULL;
3734 const char *search_pattern = NULL;
3735 int diff_context = -1, ch;
3736 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3737 int reverse_display_order = 0;
3738 const char *errstr;
3739 struct got_reflist_head refs;
3741 SIMPLEQ_INIT(&refs);
3743 #ifndef PROFILE
3744 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3745 NULL)
3746 == -1)
3747 err(1, "pledge");
3748 #endif
3750 limit = get_default_log_limit();
3752 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3753 switch (ch) {
3754 case 'p':
3755 show_patch = 1;
3756 break;
3757 case 'P':
3758 show_changed_paths = 1;
3759 break;
3760 case 'c':
3761 start_commit = optarg;
3762 break;
3763 case 'C':
3764 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3765 &errstr);
3766 if (errstr != NULL)
3767 err(1, "-C option %s", errstr);
3768 break;
3769 case 'l':
3770 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3771 if (errstr != NULL)
3772 err(1, "-l option %s", errstr);
3773 break;
3774 case 'b':
3775 log_branches = 1;
3776 break;
3777 case 'r':
3778 repo_path = realpath(optarg, NULL);
3779 if (repo_path == NULL)
3780 return got_error_from_errno2("realpath",
3781 optarg);
3782 got_path_strip_trailing_slashes(repo_path);
3783 break;
3784 case 'R':
3785 reverse_display_order = 1;
3786 break;
3787 case 's':
3788 search_pattern = optarg;
3789 break;
3790 case 'x':
3791 end_commit = optarg;
3792 break;
3793 default:
3794 usage_log();
3795 /* NOTREACHED */
3799 argc -= optind;
3800 argv += optind;
3802 if (diff_context == -1)
3803 diff_context = 3;
3804 else if (!show_patch)
3805 errx(1, "-C requires -p");
3807 cwd = getcwd(NULL, 0);
3808 if (cwd == NULL) {
3809 error = got_error_from_errno("getcwd");
3810 goto done;
3813 if (repo_path == NULL) {
3814 error = got_worktree_open(&worktree, cwd);
3815 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3816 goto done;
3817 error = NULL;
3820 if (argc == 0) {
3821 path = strdup("");
3822 if (path == NULL) {
3823 error = got_error_from_errno("strdup");
3824 goto done;
3826 } else if (argc == 1) {
3827 if (worktree) {
3828 error = got_worktree_resolve_path(&path, worktree,
3829 argv[0]);
3830 if (error)
3831 goto done;
3832 } else {
3833 path = strdup(argv[0]);
3834 if (path == NULL) {
3835 error = got_error_from_errno("strdup");
3836 goto done;
3839 } else
3840 usage_log();
3842 if (repo_path == NULL) {
3843 repo_path = worktree ?
3844 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3846 if (repo_path == NULL) {
3847 error = got_error_from_errno("strdup");
3848 goto done;
3851 error = got_repo_open(&repo, repo_path, NULL);
3852 if (error != NULL)
3853 goto done;
3855 error = apply_unveil(got_repo_get_path(repo), 1,
3856 worktree ? got_worktree_get_root_path(worktree) : NULL);
3857 if (error)
3858 goto done;
3860 if (start_commit == NULL) {
3861 struct got_reference *head_ref;
3862 struct got_commit_object *commit = NULL;
3863 error = got_ref_open(&head_ref, repo,
3864 worktree ? got_worktree_get_head_ref_name(worktree)
3865 : GOT_REF_HEAD, 0);
3866 if (error != NULL)
3867 goto done;
3868 error = got_ref_resolve(&start_id, repo, head_ref);
3869 got_ref_close(head_ref);
3870 if (error != NULL)
3871 goto done;
3872 error = got_object_open_as_commit(&commit, repo,
3873 start_id);
3874 if (error != NULL)
3875 goto done;
3876 got_object_commit_close(commit);
3877 } else {
3878 error = resolve_commit_arg(&start_id, start_commit, repo);
3879 if (error != NULL)
3880 goto done;
3882 if (end_commit != NULL) {
3883 error = resolve_commit_arg(&end_id, end_commit, repo);
3884 if (error != NULL)
3885 goto done;
3888 if (worktree) {
3889 const char *prefix = got_worktree_get_path_prefix(worktree);
3890 char *p;
3891 if (asprintf(&p, "%s%s%s", prefix,
3892 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3893 error = got_error_from_errno("asprintf");
3894 goto done;
3896 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3897 free(p);
3898 } else
3899 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3900 if (error != NULL)
3901 goto done;
3902 if (in_repo_path) {
3903 free(path);
3904 path = in_repo_path;
3907 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3908 if (error)
3909 goto done;
3911 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3912 show_patch, search_pattern, diff_context, limit, log_branches,
3913 reverse_display_order, &refs);
3914 done:
3915 free(path);
3916 free(repo_path);
3917 free(cwd);
3918 if (worktree)
3919 got_worktree_close(worktree);
3920 if (repo) {
3921 const struct got_error *repo_error;
3922 repo_error = got_repo_close(repo);
3923 if (error == NULL)
3924 error = repo_error;
3926 got_ref_list_free(&refs);
3927 return error;
3930 __dead static void
3931 usage_diff(void)
3933 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3934 "[-w] [object1 object2 | path]\n", getprogname());
3935 exit(1);
3938 struct print_diff_arg {
3939 struct got_repository *repo;
3940 struct got_worktree *worktree;
3941 int diff_context;
3942 const char *id_str;
3943 int header_shown;
3944 int diff_staged;
3945 int ignore_whitespace;
3949 * Create a file which contains the target path of a symlink so we can feed
3950 * it as content to the diff engine.
3952 static const struct got_error *
3953 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3954 const char *abspath)
3956 const struct got_error *err = NULL;
3957 char target_path[PATH_MAX];
3958 ssize_t target_len, outlen;
3960 *fd = -1;
3962 if (dirfd != -1) {
3963 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3964 if (target_len == -1)
3965 return got_error_from_errno2("readlinkat", abspath);
3966 } else {
3967 target_len = readlink(abspath, target_path, PATH_MAX);
3968 if (target_len == -1)
3969 return got_error_from_errno2("readlink", abspath);
3972 *fd = got_opentempfd();
3973 if (*fd == -1)
3974 return got_error_from_errno("got_opentempfd");
3976 outlen = write(*fd, target_path, target_len);
3977 if (outlen == -1) {
3978 err = got_error_from_errno("got_opentempfd");
3979 goto done;
3982 if (lseek(*fd, 0, SEEK_SET) == -1) {
3983 err = got_error_from_errno2("lseek", abspath);
3984 goto done;
3986 done:
3987 if (err) {
3988 close(*fd);
3989 *fd = -1;
3991 return err;
3994 static const struct got_error *
3995 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3996 const char *path, struct got_object_id *blob_id,
3997 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3998 int dirfd, const char *de_name)
4000 struct print_diff_arg *a = arg;
4001 const struct got_error *err = NULL;
4002 struct got_blob_object *blob1 = NULL;
4003 int fd = -1;
4004 FILE *f2 = NULL;
4005 char *abspath = NULL, *label1 = NULL;
4006 struct stat sb;
4008 if (a->diff_staged) {
4009 if (staged_status != GOT_STATUS_MODIFY &&
4010 staged_status != GOT_STATUS_ADD &&
4011 staged_status != GOT_STATUS_DELETE)
4012 return NULL;
4013 } else {
4014 if (staged_status == GOT_STATUS_DELETE)
4015 return NULL;
4016 if (status == GOT_STATUS_NONEXISTENT)
4017 return got_error_set_errno(ENOENT, path);
4018 if (status != GOT_STATUS_MODIFY &&
4019 status != GOT_STATUS_ADD &&
4020 status != GOT_STATUS_DELETE &&
4021 status != GOT_STATUS_CONFLICT)
4022 return NULL;
4025 if (!a->header_shown) {
4026 printf("diff %s %s%s\n", a->id_str,
4027 got_worktree_get_root_path(a->worktree),
4028 a->diff_staged ? " (staged changes)" : "");
4029 a->header_shown = 1;
4032 if (a->diff_staged) {
4033 const char *label1 = NULL, *label2 = NULL;
4034 switch (staged_status) {
4035 case GOT_STATUS_MODIFY:
4036 label1 = path;
4037 label2 = path;
4038 break;
4039 case GOT_STATUS_ADD:
4040 label2 = path;
4041 break;
4042 case GOT_STATUS_DELETE:
4043 label1 = path;
4044 break;
4045 default:
4046 return got_error(GOT_ERR_FILE_STATUS);
4048 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4049 label1, label2, a->diff_context, a->ignore_whitespace,
4050 a->repo, stdout);
4053 if (staged_status == GOT_STATUS_ADD ||
4054 staged_status == GOT_STATUS_MODIFY) {
4055 char *id_str;
4056 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4057 8192);
4058 if (err)
4059 goto done;
4060 err = got_object_id_str(&id_str, staged_blob_id);
4061 if (err)
4062 goto done;
4063 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4064 err = got_error_from_errno("asprintf");
4065 free(id_str);
4066 goto done;
4068 free(id_str);
4069 } else if (status != GOT_STATUS_ADD) {
4070 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4071 if (err)
4072 goto done;
4075 if (status != GOT_STATUS_DELETE) {
4076 if (asprintf(&abspath, "%s/%s",
4077 got_worktree_get_root_path(a->worktree), path) == -1) {
4078 err = got_error_from_errno("asprintf");
4079 goto done;
4082 if (dirfd != -1) {
4083 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4084 if (fd == -1) {
4085 if (errno != ELOOP) {
4086 err = got_error_from_errno2("openat",
4087 abspath);
4088 goto done;
4090 err = get_symlink_target_file(&fd, dirfd,
4091 de_name, abspath);
4092 if (err)
4093 goto done;
4095 } else {
4096 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4097 if (fd == -1) {
4098 if (errno != ELOOP) {
4099 err = got_error_from_errno2("open",
4100 abspath);
4101 goto done;
4103 err = get_symlink_target_file(&fd, dirfd,
4104 de_name, abspath);
4105 if (err)
4106 goto done;
4109 if (fstat(fd, &sb) == -1) {
4110 err = got_error_from_errno2("fstat", abspath);
4111 goto done;
4113 f2 = fdopen(fd, "r");
4114 if (f2 == NULL) {
4115 err = got_error_from_errno2("fdopen", abspath);
4116 goto done;
4118 fd = -1;
4119 } else
4120 sb.st_size = 0;
4122 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4123 a->diff_context, a->ignore_whitespace, stdout);
4124 done:
4125 if (blob1)
4126 got_object_blob_close(blob1);
4127 if (f2 && fclose(f2) == EOF && err == NULL)
4128 err = got_error_from_errno("fclose");
4129 if (fd != -1 && close(fd) == -1 && err == NULL)
4130 err = got_error_from_errno("close");
4131 free(abspath);
4132 return err;
4135 static const struct got_error *
4136 cmd_diff(int argc, char *argv[])
4138 const struct got_error *error;
4139 struct got_repository *repo = NULL;
4140 struct got_worktree *worktree = NULL;
4141 char *cwd = NULL, *repo_path = NULL;
4142 struct got_object_id *id1 = NULL, *id2 = NULL;
4143 const char *id_str1 = NULL, *id_str2 = NULL;
4144 char *label1 = NULL, *label2 = NULL;
4145 int type1, type2;
4146 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4147 const char *errstr;
4148 char *path = NULL;
4150 #ifndef PROFILE
4151 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4152 NULL) == -1)
4153 err(1, "pledge");
4154 #endif
4156 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4157 switch (ch) {
4158 case 'C':
4159 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4160 &errstr);
4161 if (errstr != NULL)
4162 err(1, "-C option %s", errstr);
4163 break;
4164 case 'r':
4165 repo_path = realpath(optarg, NULL);
4166 if (repo_path == NULL)
4167 return got_error_from_errno2("realpath",
4168 optarg);
4169 got_path_strip_trailing_slashes(repo_path);
4170 break;
4171 case 's':
4172 diff_staged = 1;
4173 break;
4174 case 'w':
4175 ignore_whitespace = 1;
4176 break;
4177 default:
4178 usage_diff();
4179 /* NOTREACHED */
4183 argc -= optind;
4184 argv += optind;
4186 cwd = getcwd(NULL, 0);
4187 if (cwd == NULL) {
4188 error = got_error_from_errno("getcwd");
4189 goto done;
4191 if (argc <= 1) {
4192 if (repo_path)
4193 errx(1,
4194 "-r option can't be used when diffing a work tree");
4195 error = got_worktree_open(&worktree, cwd);
4196 if (error) {
4197 if (error->code == GOT_ERR_NOT_WORKTREE)
4198 error = wrap_not_worktree_error(error, "diff",
4199 cwd);
4200 goto done;
4202 repo_path = strdup(got_worktree_get_repo_path(worktree));
4203 if (repo_path == NULL) {
4204 error = got_error_from_errno("strdup");
4205 goto done;
4207 if (argc == 1) {
4208 error = got_worktree_resolve_path(&path, worktree,
4209 argv[0]);
4210 if (error)
4211 goto done;
4212 } else {
4213 path = strdup("");
4214 if (path == NULL) {
4215 error = got_error_from_errno("strdup");
4216 goto done;
4219 } else if (argc == 2) {
4220 if (diff_staged)
4221 errx(1, "-s option can't be used when diffing "
4222 "objects in repository");
4223 id_str1 = argv[0];
4224 id_str2 = argv[1];
4225 if (repo_path == NULL) {
4226 error = got_worktree_open(&worktree, cwd);
4227 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4228 goto done;
4229 if (worktree) {
4230 repo_path = strdup(
4231 got_worktree_get_repo_path(worktree));
4232 if (repo_path == NULL) {
4233 error = got_error_from_errno("strdup");
4234 goto done;
4236 } else {
4237 repo_path = strdup(cwd);
4238 if (repo_path == NULL) {
4239 error = got_error_from_errno("strdup");
4240 goto done;
4244 } else
4245 usage_diff();
4247 error = got_repo_open(&repo, repo_path, NULL);
4248 free(repo_path);
4249 if (error != NULL)
4250 goto done;
4252 error = apply_unveil(got_repo_get_path(repo), 1,
4253 worktree ? got_worktree_get_root_path(worktree) : NULL);
4254 if (error)
4255 goto done;
4257 if (argc <= 1) {
4258 struct print_diff_arg arg;
4259 struct got_pathlist_head paths;
4260 char *id_str;
4262 TAILQ_INIT(&paths);
4264 error = got_object_id_str(&id_str,
4265 got_worktree_get_base_commit_id(worktree));
4266 if (error)
4267 goto done;
4268 arg.repo = repo;
4269 arg.worktree = worktree;
4270 arg.diff_context = diff_context;
4271 arg.id_str = id_str;
4272 arg.header_shown = 0;
4273 arg.diff_staged = diff_staged;
4274 arg.ignore_whitespace = ignore_whitespace;
4276 error = got_pathlist_append(&paths, path, NULL);
4277 if (error)
4278 goto done;
4280 error = got_worktree_status(worktree, &paths, repo, print_diff,
4281 &arg, check_cancelled, NULL);
4282 free(id_str);
4283 got_pathlist_free(&paths);
4284 goto done;
4287 error = got_repo_match_object_id(&id1, &label1, id_str1,
4288 GOT_OBJ_TYPE_ANY, 1, repo);
4289 if (error)
4290 goto done;
4292 error = got_repo_match_object_id(&id2, &label2, id_str2,
4293 GOT_OBJ_TYPE_ANY, 1, repo);
4294 if (error)
4295 goto done;
4297 error = got_object_get_type(&type1, repo, id1);
4298 if (error)
4299 goto done;
4301 error = got_object_get_type(&type2, repo, id2);
4302 if (error)
4303 goto done;
4305 if (type1 != type2) {
4306 error = got_error(GOT_ERR_OBJ_TYPE);
4307 goto done;
4310 switch (type1) {
4311 case GOT_OBJ_TYPE_BLOB:
4312 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4313 diff_context, ignore_whitespace, repo, stdout);
4314 break;
4315 case GOT_OBJ_TYPE_TREE:
4316 error = got_diff_objects_as_trees(id1, id2, "", "",
4317 diff_context, ignore_whitespace, repo, stdout);
4318 break;
4319 case GOT_OBJ_TYPE_COMMIT:
4320 printf("diff %s %s\n", label1, label2);
4321 error = got_diff_objects_as_commits(id1, id2, diff_context,
4322 ignore_whitespace, repo, stdout);
4323 break;
4324 default:
4325 error = got_error(GOT_ERR_OBJ_TYPE);
4327 done:
4328 free(label1);
4329 free(label2);
4330 free(id1);
4331 free(id2);
4332 free(path);
4333 if (worktree)
4334 got_worktree_close(worktree);
4335 if (repo) {
4336 const struct got_error *repo_error;
4337 repo_error = got_repo_close(repo);
4338 if (error == NULL)
4339 error = repo_error;
4341 return error;
4344 __dead static void
4345 usage_blame(void)
4347 fprintf(stderr,
4348 "usage: %s blame [-c commit] [-r repository-path] path\n",
4349 getprogname());
4350 exit(1);
4353 struct blame_line {
4354 int annotated;
4355 char *id_str;
4356 char *committer;
4357 char datebuf[11]; /* YYYY-MM-DD + NUL */
4360 struct blame_cb_args {
4361 struct blame_line *lines;
4362 int nlines;
4363 int nlines_prec;
4364 int lineno_cur;
4365 off_t *line_offsets;
4366 FILE *f;
4367 struct got_repository *repo;
4370 static const struct got_error *
4371 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4373 const struct got_error *err = NULL;
4374 struct blame_cb_args *a = arg;
4375 struct blame_line *bline;
4376 char *line = NULL;
4377 size_t linesize = 0;
4378 struct got_commit_object *commit = NULL;
4379 off_t offset;
4380 struct tm tm;
4381 time_t committer_time;
4383 if (nlines != a->nlines ||
4384 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4385 return got_error(GOT_ERR_RANGE);
4387 if (sigint_received)
4388 return got_error(GOT_ERR_ITER_COMPLETED);
4390 if (lineno == -1)
4391 return NULL; /* no change in this commit */
4393 /* Annotate this line. */
4394 bline = &a->lines[lineno - 1];
4395 if (bline->annotated)
4396 return NULL;
4397 err = got_object_id_str(&bline->id_str, id);
4398 if (err)
4399 return err;
4401 err = got_object_open_as_commit(&commit, a->repo, id);
4402 if (err)
4403 goto done;
4405 bline->committer = strdup(got_object_commit_get_committer(commit));
4406 if (bline->committer == NULL) {
4407 err = got_error_from_errno("strdup");
4408 goto done;
4411 committer_time = got_object_commit_get_committer_time(commit);
4412 if (localtime_r(&committer_time, &tm) == NULL)
4413 return got_error_from_errno("localtime_r");
4414 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4415 &tm) >= sizeof(bline->datebuf)) {
4416 err = got_error(GOT_ERR_NO_SPACE);
4417 goto done;
4419 bline->annotated = 1;
4421 /* Print lines annotated so far. */
4422 bline = &a->lines[a->lineno_cur - 1];
4423 if (!bline->annotated)
4424 goto done;
4426 offset = a->line_offsets[a->lineno_cur - 1];
4427 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4428 err = got_error_from_errno("fseeko");
4429 goto done;
4432 while (bline->annotated) {
4433 char *smallerthan, *at, *nl, *committer;
4434 size_t len;
4436 if (getline(&line, &linesize, a->f) == -1) {
4437 if (ferror(a->f))
4438 err = got_error_from_errno("getline");
4439 break;
4442 committer = bline->committer;
4443 smallerthan = strchr(committer, '<');
4444 if (smallerthan && smallerthan[1] != '\0')
4445 committer = smallerthan + 1;
4446 at = strchr(committer, '@');
4447 if (at)
4448 *at = '\0';
4449 len = strlen(committer);
4450 if (len >= 9)
4451 committer[8] = '\0';
4453 nl = strchr(line, '\n');
4454 if (nl)
4455 *nl = '\0';
4456 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4457 bline->id_str, bline->datebuf, committer, line);
4459 a->lineno_cur++;
4460 bline = &a->lines[a->lineno_cur - 1];
4462 done:
4463 if (commit)
4464 got_object_commit_close(commit);
4465 free(line);
4466 return err;
4469 static const struct got_error *
4470 cmd_blame(int argc, char *argv[])
4472 const struct got_error *error;
4473 struct got_repository *repo = NULL;
4474 struct got_worktree *worktree = NULL;
4475 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4476 char *link_target = NULL;
4477 struct got_object_id *obj_id = NULL;
4478 struct got_object_id *commit_id = NULL;
4479 struct got_blob_object *blob = NULL;
4480 char *commit_id_str = NULL;
4481 struct blame_cb_args bca;
4482 int ch, obj_type, i;
4483 size_t filesize;
4485 memset(&bca, 0, sizeof(bca));
4487 #ifndef PROFILE
4488 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4489 NULL) == -1)
4490 err(1, "pledge");
4491 #endif
4493 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4494 switch (ch) {
4495 case 'c':
4496 commit_id_str = optarg;
4497 break;
4498 case 'r':
4499 repo_path = realpath(optarg, NULL);
4500 if (repo_path == NULL)
4501 return got_error_from_errno2("realpath",
4502 optarg);
4503 got_path_strip_trailing_slashes(repo_path);
4504 break;
4505 default:
4506 usage_blame();
4507 /* NOTREACHED */
4511 argc -= optind;
4512 argv += optind;
4514 if (argc == 1)
4515 path = argv[0];
4516 else
4517 usage_blame();
4519 cwd = getcwd(NULL, 0);
4520 if (cwd == NULL) {
4521 error = got_error_from_errno("getcwd");
4522 goto done;
4524 if (repo_path == NULL) {
4525 error = got_worktree_open(&worktree, cwd);
4526 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4527 goto done;
4528 else
4529 error = NULL;
4530 if (worktree) {
4531 repo_path =
4532 strdup(got_worktree_get_repo_path(worktree));
4533 if (repo_path == NULL) {
4534 error = got_error_from_errno("strdup");
4535 if (error)
4536 goto done;
4538 } else {
4539 repo_path = strdup(cwd);
4540 if (repo_path == NULL) {
4541 error = got_error_from_errno("strdup");
4542 goto done;
4547 error = got_repo_open(&repo, repo_path, NULL);
4548 if (error != NULL)
4549 goto done;
4551 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4552 if (error)
4553 goto done;
4555 if (worktree) {
4556 const char *prefix = got_worktree_get_path_prefix(worktree);
4557 char *p, *worktree_subdir = cwd +
4558 strlen(got_worktree_get_root_path(worktree));
4559 if (asprintf(&p, "%s%s%s%s%s",
4560 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4561 worktree_subdir, worktree_subdir[0] ? "/" : "",
4562 path) == -1) {
4563 error = got_error_from_errno("asprintf");
4564 goto done;
4566 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4567 free(p);
4568 } else {
4569 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4571 if (error)
4572 goto done;
4574 if (commit_id_str == NULL) {
4575 struct got_reference *head_ref;
4576 error = got_ref_open(&head_ref, repo, worktree ?
4577 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4578 if (error != NULL)
4579 goto done;
4580 error = got_ref_resolve(&commit_id, repo, head_ref);
4581 got_ref_close(head_ref);
4582 if (error != NULL)
4583 goto done;
4584 } else {
4585 error = got_repo_match_object_id(&commit_id, NULL,
4586 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4587 if (error)
4588 goto done;
4591 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4592 commit_id, repo);
4593 if (error)
4594 goto done;
4596 error = got_object_id_by_path(&obj_id, repo, commit_id,
4597 link_target ? link_target : in_repo_path);
4598 if (error)
4599 goto done;
4601 error = got_object_get_type(&obj_type, repo, obj_id);
4602 if (error)
4603 goto done;
4605 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4606 error = got_error_path(link_target ? link_target : in_repo_path,
4607 GOT_ERR_OBJ_TYPE);
4608 goto done;
4611 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4612 if (error)
4613 goto done;
4614 bca.f = got_opentemp();
4615 if (bca.f == NULL) {
4616 error = got_error_from_errno("got_opentemp");
4617 goto done;
4619 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4620 &bca.line_offsets, bca.f, blob);
4621 if (error || bca.nlines == 0)
4622 goto done;
4624 /* Don't include \n at EOF in the blame line count. */
4625 if (bca.line_offsets[bca.nlines - 1] == filesize)
4626 bca.nlines--;
4628 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4629 if (bca.lines == NULL) {
4630 error = got_error_from_errno("calloc");
4631 goto done;
4633 bca.lineno_cur = 1;
4634 bca.nlines_prec = 0;
4635 i = bca.nlines;
4636 while (i > 0) {
4637 i /= 10;
4638 bca.nlines_prec++;
4640 bca.repo = repo;
4642 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4643 repo, blame_cb, &bca, check_cancelled, NULL);
4644 done:
4645 free(in_repo_path);
4646 free(link_target);
4647 free(repo_path);
4648 free(cwd);
4649 free(commit_id);
4650 free(obj_id);
4651 if (blob)
4652 got_object_blob_close(blob);
4653 if (worktree)
4654 got_worktree_close(worktree);
4655 if (repo) {
4656 const struct got_error *repo_error;
4657 repo_error = got_repo_close(repo);
4658 if (error == NULL)
4659 error = repo_error;
4661 if (bca.lines) {
4662 for (i = 0; i < bca.nlines; i++) {
4663 struct blame_line *bline = &bca.lines[i];
4664 free(bline->id_str);
4665 free(bline->committer);
4667 free(bca.lines);
4669 free(bca.line_offsets);
4670 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4671 error = got_error_from_errno("fclose");
4672 return error;
4675 __dead static void
4676 usage_tree(void)
4678 fprintf(stderr,
4679 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4680 getprogname());
4681 exit(1);
4684 static const struct got_error *
4685 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4686 const char *root_path, struct got_repository *repo)
4688 const struct got_error *err = NULL;
4689 int is_root_path = (strcmp(path, root_path) == 0);
4690 const char *modestr = "";
4691 mode_t mode = got_tree_entry_get_mode(te);
4692 char *link_target = NULL;
4694 path += strlen(root_path);
4695 while (path[0] == '/')
4696 path++;
4698 if (got_object_tree_entry_is_submodule(te))
4699 modestr = "$";
4700 else if (S_ISLNK(mode)) {
4701 int i;
4703 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4704 if (err)
4705 return err;
4706 for (i = 0; i < strlen(link_target); i++) {
4707 if (!isprint((unsigned char)link_target[i]))
4708 link_target[i] = '?';
4711 modestr = "@";
4713 else if (S_ISDIR(mode))
4714 modestr = "/";
4715 else if (mode & S_IXUSR)
4716 modestr = "*";
4718 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4719 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4720 link_target ? " -> ": "", link_target ? link_target : "");
4722 free(link_target);
4723 return NULL;
4726 static const struct got_error *
4727 print_tree(const char *path, struct got_object_id *commit_id,
4728 int show_ids, int recurse, const char *root_path,
4729 struct got_repository *repo)
4731 const struct got_error *err = NULL;
4732 struct got_object_id *tree_id = NULL;
4733 struct got_tree_object *tree = NULL;
4734 int nentries, i;
4736 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4737 if (err)
4738 goto done;
4740 err = got_object_open_as_tree(&tree, repo, tree_id);
4741 if (err)
4742 goto done;
4743 nentries = got_object_tree_get_nentries(tree);
4744 for (i = 0; i < nentries; i++) {
4745 struct got_tree_entry *te;
4746 char *id = NULL;
4748 if (sigint_received || sigpipe_received)
4749 break;
4751 te = got_object_tree_get_entry(tree, i);
4752 if (show_ids) {
4753 char *id_str;
4754 err = got_object_id_str(&id_str,
4755 got_tree_entry_get_id(te));
4756 if (err)
4757 goto done;
4758 if (asprintf(&id, "%s ", id_str) == -1) {
4759 err = got_error_from_errno("asprintf");
4760 free(id_str);
4761 goto done;
4763 free(id_str);
4765 err = print_entry(te, id, path, root_path, repo);
4766 free(id);
4767 if (err)
4768 goto done;
4770 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4771 char *child_path;
4772 if (asprintf(&child_path, "%s%s%s", path,
4773 path[0] == '/' && path[1] == '\0' ? "" : "/",
4774 got_tree_entry_get_name(te)) == -1) {
4775 err = got_error_from_errno("asprintf");
4776 goto done;
4778 err = print_tree(child_path, commit_id, show_ids, 1,
4779 root_path, repo);
4780 free(child_path);
4781 if (err)
4782 goto done;
4785 done:
4786 if (tree)
4787 got_object_tree_close(tree);
4788 free(tree_id);
4789 return err;
4792 static const struct got_error *
4793 cmd_tree(int argc, char *argv[])
4795 const struct got_error *error;
4796 struct got_repository *repo = NULL;
4797 struct got_worktree *worktree = NULL;
4798 const char *path, *refname = NULL;
4799 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4800 struct got_object_id *commit_id = NULL;
4801 char *commit_id_str = NULL;
4802 int show_ids = 0, recurse = 0;
4803 int ch;
4805 #ifndef PROFILE
4806 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4807 NULL) == -1)
4808 err(1, "pledge");
4809 #endif
4811 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4812 switch (ch) {
4813 case 'c':
4814 commit_id_str = optarg;
4815 break;
4816 case 'r':
4817 repo_path = realpath(optarg, NULL);
4818 if (repo_path == NULL)
4819 return got_error_from_errno2("realpath",
4820 optarg);
4821 got_path_strip_trailing_slashes(repo_path);
4822 break;
4823 case 'i':
4824 show_ids = 1;
4825 break;
4826 case 'R':
4827 recurse = 1;
4828 break;
4829 default:
4830 usage_tree();
4831 /* NOTREACHED */
4835 argc -= optind;
4836 argv += optind;
4838 if (argc == 1)
4839 path = argv[0];
4840 else if (argc > 1)
4841 usage_tree();
4842 else
4843 path = NULL;
4845 cwd = getcwd(NULL, 0);
4846 if (cwd == NULL) {
4847 error = got_error_from_errno("getcwd");
4848 goto done;
4850 if (repo_path == NULL) {
4851 error = got_worktree_open(&worktree, cwd);
4852 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4853 goto done;
4854 else
4855 error = NULL;
4856 if (worktree) {
4857 repo_path =
4858 strdup(got_worktree_get_repo_path(worktree));
4859 if (repo_path == NULL)
4860 error = got_error_from_errno("strdup");
4861 if (error)
4862 goto done;
4863 } else {
4864 repo_path = strdup(cwd);
4865 if (repo_path == NULL) {
4866 error = got_error_from_errno("strdup");
4867 goto done;
4872 error = got_repo_open(&repo, repo_path, NULL);
4873 if (error != NULL)
4874 goto done;
4876 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4877 if (error)
4878 goto done;
4880 if (path == NULL) {
4881 if (worktree) {
4882 char *p, *worktree_subdir = cwd +
4883 strlen(got_worktree_get_root_path(worktree));
4884 if (asprintf(&p, "%s/%s",
4885 got_worktree_get_path_prefix(worktree),
4886 worktree_subdir) == -1) {
4887 error = got_error_from_errno("asprintf");
4888 goto done;
4890 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4891 free(p);
4892 if (error)
4893 goto done;
4894 } else
4895 path = "/";
4897 if (in_repo_path == NULL) {
4898 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4899 if (error != NULL)
4900 goto done;
4903 if (commit_id_str == NULL) {
4904 struct got_reference *head_ref;
4905 if (worktree)
4906 refname = got_worktree_get_head_ref_name(worktree);
4907 else
4908 refname = GOT_REF_HEAD;
4909 error = got_ref_open(&head_ref, repo, refname, 0);
4910 if (error != NULL)
4911 goto done;
4912 error = got_ref_resolve(&commit_id, repo, head_ref);
4913 got_ref_close(head_ref);
4914 if (error != NULL)
4915 goto done;
4916 } else {
4917 error = got_repo_match_object_id(&commit_id, NULL,
4918 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4919 if (error)
4920 goto done;
4923 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4924 in_repo_path, repo);
4925 done:
4926 free(in_repo_path);
4927 free(repo_path);
4928 free(cwd);
4929 free(commit_id);
4930 if (worktree)
4931 got_worktree_close(worktree);
4932 if (repo) {
4933 const struct got_error *repo_error;
4934 repo_error = got_repo_close(repo);
4935 if (error == NULL)
4936 error = repo_error;
4938 return error;
4941 __dead static void
4942 usage_status(void)
4944 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4945 getprogname());
4946 exit(1);
4949 static const struct got_error *
4950 print_status(void *arg, unsigned char status, unsigned char staged_status,
4951 const char *path, struct got_object_id *blob_id,
4952 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4953 int dirfd, const char *de_name)
4955 if (status == staged_status && (status == GOT_STATUS_DELETE))
4956 status = GOT_STATUS_NO_CHANGE;
4957 if (arg) {
4958 char *status_codes = arg;
4959 size_t ncodes = strlen(status_codes);
4960 int i;
4961 for (i = 0; i < ncodes ; i++) {
4962 if (status == status_codes[i] ||
4963 staged_status == status_codes[i])
4964 break;
4966 if (i == ncodes)
4967 return NULL;
4969 printf("%c%c %s\n", status, staged_status, path);
4970 return NULL;
4973 static const struct got_error *
4974 cmd_status(int argc, char *argv[])
4976 const struct got_error *error = NULL;
4977 struct got_repository *repo = NULL;
4978 struct got_worktree *worktree = NULL;
4979 char *cwd = NULL, *status_codes = NULL;;
4980 struct got_pathlist_head paths;
4981 struct got_pathlist_entry *pe;
4982 int ch, i;
4984 TAILQ_INIT(&paths);
4986 while ((ch = getopt(argc, argv, "s:")) != -1) {
4987 switch (ch) {
4988 case 's':
4989 for (i = 0; i < strlen(optarg); i++) {
4990 switch (optarg[i]) {
4991 case GOT_STATUS_MODIFY:
4992 case GOT_STATUS_ADD:
4993 case GOT_STATUS_DELETE:
4994 case GOT_STATUS_CONFLICT:
4995 case GOT_STATUS_MISSING:
4996 case GOT_STATUS_OBSTRUCTED:
4997 case GOT_STATUS_UNVERSIONED:
4998 case GOT_STATUS_MODE_CHANGE:
4999 case GOT_STATUS_NONEXISTENT:
5000 break;
5001 default:
5002 errx(1, "invalid status code '%c'",
5003 optarg[i]);
5006 status_codes = optarg;
5007 break;
5008 default:
5009 usage_status();
5010 /* NOTREACHED */
5014 argc -= optind;
5015 argv += optind;
5017 #ifndef PROFILE
5018 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5019 NULL) == -1)
5020 err(1, "pledge");
5021 #endif
5022 cwd = getcwd(NULL, 0);
5023 if (cwd == NULL) {
5024 error = got_error_from_errno("getcwd");
5025 goto done;
5028 error = got_worktree_open(&worktree, cwd);
5029 if (error) {
5030 if (error->code == GOT_ERR_NOT_WORKTREE)
5031 error = wrap_not_worktree_error(error, "status", cwd);
5032 goto done;
5035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5036 NULL);
5037 if (error != NULL)
5038 goto done;
5040 error = apply_unveil(got_repo_get_path(repo), 1,
5041 got_worktree_get_root_path(worktree));
5042 if (error)
5043 goto done;
5045 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5046 if (error)
5047 goto done;
5049 error = got_worktree_status(worktree, &paths, repo, print_status,
5050 status_codes, check_cancelled, NULL);
5051 done:
5052 TAILQ_FOREACH(pe, &paths, entry)
5053 free((char *)pe->path);
5054 got_pathlist_free(&paths);
5055 free(cwd);
5056 return error;
5059 __dead static void
5060 usage_ref(void)
5062 fprintf(stderr,
5063 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5064 "[-d] [name]\n",
5065 getprogname());
5066 exit(1);
5069 static const struct got_error *
5070 list_refs(struct got_repository *repo, const char *refname)
5072 static const struct got_error *err = NULL;
5073 struct got_reflist_head refs;
5074 struct got_reflist_entry *re;
5076 SIMPLEQ_INIT(&refs);
5077 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5078 if (err)
5079 return err;
5081 SIMPLEQ_FOREACH(re, &refs, entry) {
5082 char *refstr;
5083 refstr = got_ref_to_str(re->ref);
5084 if (refstr == NULL)
5085 return got_error_from_errno("got_ref_to_str");
5086 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5087 free(refstr);
5090 got_ref_list_free(&refs);
5091 return NULL;
5094 static const struct got_error *
5095 delete_ref(struct got_repository *repo, const char *refname)
5097 const struct got_error *err = NULL;
5098 struct got_reference *ref;
5100 err = got_ref_open(&ref, repo, refname, 0);
5101 if (err)
5102 return err;
5104 err = got_ref_delete(ref, repo);
5105 got_ref_close(ref);
5106 return err;
5109 static const struct got_error *
5110 add_ref(struct got_repository *repo, const char *refname, const char *target)
5112 const struct got_error *err = NULL;
5113 struct got_object_id *id;
5114 struct got_reference *ref = NULL;
5117 * Don't let the user create a reference name with a leading '-'.
5118 * While technically a valid reference name, this case is usually
5119 * an unintended typo.
5121 if (refname[0] == '-')
5122 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5124 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5125 repo);
5126 if (err) {
5127 struct got_reference *target_ref;
5129 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5130 return err;
5131 err = got_ref_open(&target_ref, repo, target, 0);
5132 if (err)
5133 return err;
5134 err = got_ref_resolve(&id, repo, target_ref);
5135 got_ref_close(target_ref);
5136 if (err)
5137 return err;
5140 err = got_ref_alloc(&ref, refname, id);
5141 if (err)
5142 goto done;
5144 err = got_ref_write(ref, repo);
5145 done:
5146 if (ref)
5147 got_ref_close(ref);
5148 free(id);
5149 return err;
5152 static const struct got_error *
5153 add_symref(struct got_repository *repo, const char *refname, const char *target)
5155 const struct got_error *err = NULL;
5156 struct got_reference *ref = NULL;
5157 struct got_reference *target_ref = NULL;
5160 * Don't let the user create a reference name with a leading '-'.
5161 * While technically a valid reference name, this case is usually
5162 * an unintended typo.
5164 if (refname[0] == '-')
5165 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5167 err = got_ref_open(&target_ref, repo, target, 0);
5168 if (err)
5169 return err;
5171 err = got_ref_alloc_symref(&ref, refname, target_ref);
5172 if (err)
5173 goto done;
5175 err = got_ref_write(ref, repo);
5176 done:
5177 if (target_ref)
5178 got_ref_close(target_ref);
5179 if (ref)
5180 got_ref_close(ref);
5181 return err;
5184 static const struct got_error *
5185 cmd_ref(int argc, char *argv[])
5187 const struct got_error *error = NULL;
5188 struct got_repository *repo = NULL;
5189 struct got_worktree *worktree = NULL;
5190 char *cwd = NULL, *repo_path = NULL;
5191 int ch, do_list = 0, do_delete = 0;
5192 const char *obj_arg = NULL, *symref_target= NULL;
5193 char *refname = NULL;
5195 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5196 switch (ch) {
5197 case 'c':
5198 obj_arg = optarg;
5199 break;
5200 case 'd':
5201 do_delete = 1;
5202 break;
5203 case 'r':
5204 repo_path = realpath(optarg, NULL);
5205 if (repo_path == NULL)
5206 return got_error_from_errno2("realpath",
5207 optarg);
5208 got_path_strip_trailing_slashes(repo_path);
5209 break;
5210 case 'l':
5211 do_list = 1;
5212 break;
5213 case 's':
5214 symref_target = optarg;
5215 break;
5216 default:
5217 usage_ref();
5218 /* NOTREACHED */
5222 if (obj_arg && do_list)
5223 errx(1, "-c and -l options are mutually exclusive");
5224 if (obj_arg && do_delete)
5225 errx(1, "-c and -d options are mutually exclusive");
5226 if (obj_arg && symref_target)
5227 errx(1, "-c and -s options are mutually exclusive");
5228 if (symref_target && do_delete)
5229 errx(1, "-s and -d options are mutually exclusive");
5230 if (symref_target && do_list)
5231 errx(1, "-s and -l options are mutually exclusive");
5232 if (do_delete && do_list)
5233 errx(1, "-d and -l options are mutually exclusive");
5235 argc -= optind;
5236 argv += optind;
5238 if (do_list) {
5239 if (argc != 0 && argc != 1)
5240 usage_ref();
5241 if (argc == 1) {
5242 refname = strdup(argv[0]);
5243 if (refname == NULL) {
5244 error = got_error_from_errno("strdup");
5245 goto done;
5248 } else {
5249 if (argc != 1)
5250 usage_ref();
5251 refname = strdup(argv[0]);
5252 if (refname == NULL) {
5253 error = got_error_from_errno("strdup");
5254 goto done;
5258 if (refname)
5259 got_path_strip_trailing_slashes(refname);
5261 #ifndef PROFILE
5262 if (do_list) {
5263 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5264 NULL) == -1)
5265 err(1, "pledge");
5266 } else {
5267 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5268 "sendfd unveil", NULL) == -1)
5269 err(1, "pledge");
5271 #endif
5272 cwd = getcwd(NULL, 0);
5273 if (cwd == NULL) {
5274 error = got_error_from_errno("getcwd");
5275 goto done;
5278 if (repo_path == NULL) {
5279 error = got_worktree_open(&worktree, cwd);
5280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5281 goto done;
5282 else
5283 error = NULL;
5284 if (worktree) {
5285 repo_path =
5286 strdup(got_worktree_get_repo_path(worktree));
5287 if (repo_path == NULL)
5288 error = got_error_from_errno("strdup");
5289 if (error)
5290 goto done;
5291 } else {
5292 repo_path = strdup(cwd);
5293 if (repo_path == NULL) {
5294 error = got_error_from_errno("strdup");
5295 goto done;
5300 error = got_repo_open(&repo, repo_path, NULL);
5301 if (error != NULL)
5302 goto done;
5304 error = apply_unveil(got_repo_get_path(repo), do_list,
5305 worktree ? got_worktree_get_root_path(worktree) : NULL);
5306 if (error)
5307 goto done;
5309 if (do_list)
5310 error = list_refs(repo, refname);
5311 else if (do_delete)
5312 error = delete_ref(repo, refname);
5313 else if (symref_target)
5314 error = add_symref(repo, refname, symref_target);
5315 else {
5316 if (obj_arg == NULL)
5317 usage_ref();
5318 error = add_ref(repo, refname, obj_arg);
5320 done:
5321 free(refname);
5322 if (repo)
5323 got_repo_close(repo);
5324 if (worktree)
5325 got_worktree_close(worktree);
5326 free(cwd);
5327 free(repo_path);
5328 return error;
5331 __dead static void
5332 usage_branch(void)
5334 fprintf(stderr,
5335 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5336 "[name]\n", getprogname());
5337 exit(1);
5340 static const struct got_error *
5341 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5342 struct got_reference *ref)
5344 const struct got_error *err = NULL;
5345 const char *refname, *marker = " ";
5346 char *refstr;
5348 refname = got_ref_get_name(ref);
5349 if (worktree && strcmp(refname,
5350 got_worktree_get_head_ref_name(worktree)) == 0) {
5351 struct got_object_id *id = NULL;
5353 err = got_ref_resolve(&id, repo, ref);
5354 if (err)
5355 return err;
5356 if (got_object_id_cmp(id,
5357 got_worktree_get_base_commit_id(worktree)) == 0)
5358 marker = "* ";
5359 else
5360 marker = "~ ";
5361 free(id);
5364 if (strncmp(refname, "refs/heads/", 11) == 0)
5365 refname += 11;
5366 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5367 refname += 18;
5369 refstr = got_ref_to_str(ref);
5370 if (refstr == NULL)
5371 return got_error_from_errno("got_ref_to_str");
5373 printf("%s%s: %s\n", marker, refname, refstr);
5374 free(refstr);
5375 return NULL;
5378 static const struct got_error *
5379 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5381 const char *refname;
5383 if (worktree == NULL)
5384 return got_error(GOT_ERR_NOT_WORKTREE);
5386 refname = got_worktree_get_head_ref_name(worktree);
5388 if (strncmp(refname, "refs/heads/", 11) == 0)
5389 refname += 11;
5390 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5391 refname += 18;
5393 printf("%s\n", refname);
5395 return NULL;
5398 static const struct got_error *
5399 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5401 static const struct got_error *err = NULL;
5402 struct got_reflist_head refs;
5403 struct got_reflist_entry *re;
5404 struct got_reference *temp_ref = NULL;
5405 int rebase_in_progress, histedit_in_progress;
5407 SIMPLEQ_INIT(&refs);
5409 if (worktree) {
5410 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5411 worktree);
5412 if (err)
5413 return err;
5415 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5416 worktree);
5417 if (err)
5418 return err;
5420 if (rebase_in_progress || histedit_in_progress) {
5421 err = got_ref_open(&temp_ref, repo,
5422 got_worktree_get_head_ref_name(worktree), 0);
5423 if (err)
5424 return err;
5425 list_branch(repo, worktree, temp_ref);
5426 got_ref_close(temp_ref);
5430 err = got_ref_list(&refs, repo, "refs/heads",
5431 got_ref_cmp_by_name, NULL);
5432 if (err)
5433 return err;
5435 SIMPLEQ_FOREACH(re, &refs, entry)
5436 list_branch(repo, worktree, re->ref);
5438 got_ref_list_free(&refs);
5439 return NULL;
5442 static const struct got_error *
5443 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5444 const char *branch_name)
5446 const struct got_error *err = NULL;
5447 struct got_reference *ref = NULL;
5448 char *refname;
5450 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5451 return got_error_from_errno("asprintf");
5453 err = got_ref_open(&ref, repo, refname, 0);
5454 if (err)
5455 goto done;
5457 if (worktree &&
5458 strcmp(got_worktree_get_head_ref_name(worktree),
5459 got_ref_get_name(ref)) == 0) {
5460 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5461 "will not delete this work tree's current branch");
5462 goto done;
5465 err = got_ref_delete(ref, repo);
5466 done:
5467 if (ref)
5468 got_ref_close(ref);
5469 free(refname);
5470 return err;
5473 static const struct got_error *
5474 add_branch(struct got_repository *repo, const char *branch_name,
5475 struct got_object_id *base_commit_id)
5477 const struct got_error *err = NULL;
5478 struct got_reference *ref = NULL;
5479 char *base_refname = NULL, *refname = NULL;
5482 * Don't let the user create a branch name with a leading '-'.
5483 * While technically a valid reference name, this case is usually
5484 * an unintended typo.
5486 if (branch_name[0] == '-')
5487 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5489 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5490 err = got_error_from_errno("asprintf");
5491 goto done;
5494 err = got_ref_open(&ref, repo, refname, 0);
5495 if (err == NULL) {
5496 err = got_error(GOT_ERR_BRANCH_EXISTS);
5497 goto done;
5498 } else if (err->code != GOT_ERR_NOT_REF)
5499 goto done;
5501 err = got_ref_alloc(&ref, refname, base_commit_id);
5502 if (err)
5503 goto done;
5505 err = got_ref_write(ref, repo);
5506 done:
5507 if (ref)
5508 got_ref_close(ref);
5509 free(base_refname);
5510 free(refname);
5511 return err;
5514 static const struct got_error *
5515 cmd_branch(int argc, char *argv[])
5517 const struct got_error *error = NULL;
5518 struct got_repository *repo = NULL;
5519 struct got_worktree *worktree = NULL;
5520 char *cwd = NULL, *repo_path = NULL;
5521 int ch, do_list = 0, do_show = 0, do_update = 1;
5522 const char *delref = NULL, *commit_id_arg = NULL;
5523 struct got_reference *ref = NULL;
5524 struct got_pathlist_head paths;
5525 struct got_pathlist_entry *pe;
5526 struct got_object_id *commit_id = NULL;
5527 char *commit_id_str = NULL;
5529 TAILQ_INIT(&paths);
5531 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5532 switch (ch) {
5533 case 'c':
5534 commit_id_arg = optarg;
5535 break;
5536 case 'd':
5537 delref = optarg;
5538 break;
5539 case 'r':
5540 repo_path = realpath(optarg, NULL);
5541 if (repo_path == NULL)
5542 return got_error_from_errno2("realpath",
5543 optarg);
5544 got_path_strip_trailing_slashes(repo_path);
5545 break;
5546 case 'l':
5547 do_list = 1;
5548 break;
5549 case 'n':
5550 do_update = 0;
5551 break;
5552 default:
5553 usage_branch();
5554 /* NOTREACHED */
5558 if (do_list && delref)
5559 errx(1, "-l and -d options are mutually exclusive");
5561 argc -= optind;
5562 argv += optind;
5564 if (!do_list && !delref && argc == 0)
5565 do_show = 1;
5567 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5568 errx(1, "-c option can only be used when creating a branch");
5570 if (do_list || delref) {
5571 if (argc > 0)
5572 usage_branch();
5573 } else if (!do_show && argc != 1)
5574 usage_branch();
5576 #ifndef PROFILE
5577 if (do_list || do_show) {
5578 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5579 NULL) == -1)
5580 err(1, "pledge");
5581 } else {
5582 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5583 "sendfd unveil", NULL) == -1)
5584 err(1, "pledge");
5586 #endif
5587 cwd = getcwd(NULL, 0);
5588 if (cwd == NULL) {
5589 error = got_error_from_errno("getcwd");
5590 goto done;
5593 if (repo_path == NULL) {
5594 error = got_worktree_open(&worktree, cwd);
5595 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5596 goto done;
5597 else
5598 error = NULL;
5599 if (worktree) {
5600 repo_path =
5601 strdup(got_worktree_get_repo_path(worktree));
5602 if (repo_path == NULL)
5603 error = got_error_from_errno("strdup");
5604 if (error)
5605 goto done;
5606 } else {
5607 repo_path = strdup(cwd);
5608 if (repo_path == NULL) {
5609 error = got_error_from_errno("strdup");
5610 goto done;
5615 error = got_repo_open(&repo, repo_path, NULL);
5616 if (error != NULL)
5617 goto done;
5619 error = apply_unveil(got_repo_get_path(repo), do_list,
5620 worktree ? got_worktree_get_root_path(worktree) : NULL);
5621 if (error)
5622 goto done;
5624 if (do_show)
5625 error = show_current_branch(repo, worktree);
5626 else if (do_list)
5627 error = list_branches(repo, worktree);
5628 else if (delref)
5629 error = delete_branch(repo, worktree, delref);
5630 else {
5631 if (commit_id_arg == NULL)
5632 commit_id_arg = worktree ?
5633 got_worktree_get_head_ref_name(worktree) :
5634 GOT_REF_HEAD;
5635 error = got_repo_match_object_id(&commit_id, NULL,
5636 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5637 if (error)
5638 goto done;
5639 error = add_branch(repo, argv[0], commit_id);
5640 if (error)
5641 goto done;
5642 if (worktree && do_update) {
5643 struct got_update_progress_arg upa;
5644 char *branch_refname = NULL;
5646 error = got_object_id_str(&commit_id_str, commit_id);
5647 if (error)
5648 goto done;
5649 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5650 worktree);
5651 if (error)
5652 goto done;
5653 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5654 == -1) {
5655 error = got_error_from_errno("asprintf");
5656 goto done;
5658 error = got_ref_open(&ref, repo, branch_refname, 0);
5659 free(branch_refname);
5660 if (error)
5661 goto done;
5662 error = switch_head_ref(ref, commit_id, worktree,
5663 repo);
5664 if (error)
5665 goto done;
5666 error = got_worktree_set_base_commit_id(worktree, repo,
5667 commit_id);
5668 if (error)
5669 goto done;
5670 memset(&upa, 0, sizeof(upa));
5671 error = got_worktree_checkout_files(worktree, &paths,
5672 repo, update_progress, &upa, check_cancelled,
5673 NULL);
5674 if (error)
5675 goto done;
5676 if (upa.did_something)
5677 printf("Updated to commit %s\n", commit_id_str);
5678 print_update_progress_stats(&upa);
5681 done:
5682 if (ref)
5683 got_ref_close(ref);
5684 if (repo)
5685 got_repo_close(repo);
5686 if (worktree)
5687 got_worktree_close(worktree);
5688 free(cwd);
5689 free(repo_path);
5690 free(commit_id);
5691 free(commit_id_str);
5692 TAILQ_FOREACH(pe, &paths, entry)
5693 free((char *)pe->path);
5694 got_pathlist_free(&paths);
5695 return error;
5699 __dead static void
5700 usage_tag(void)
5702 fprintf(stderr,
5703 "usage: %s tag [-c commit] [-r repository] [-l] "
5704 "[-m message] name\n", getprogname());
5705 exit(1);
5708 #if 0
5709 static const struct got_error *
5710 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5712 const struct got_error *err = NULL;
5713 struct got_reflist_entry *re, *se, *new;
5714 struct got_object_id *re_id, *se_id;
5715 struct got_tag_object *re_tag, *se_tag;
5716 time_t re_time, se_time;
5718 SIMPLEQ_FOREACH(re, tags, entry) {
5719 se = SIMPLEQ_FIRST(sorted);
5720 if (se == NULL) {
5721 err = got_reflist_entry_dup(&new, re);
5722 if (err)
5723 return err;
5724 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5725 continue;
5726 } else {
5727 err = got_ref_resolve(&re_id, repo, re->ref);
5728 if (err)
5729 break;
5730 err = got_object_open_as_tag(&re_tag, repo, re_id);
5731 free(re_id);
5732 if (err)
5733 break;
5734 re_time = got_object_tag_get_tagger_time(re_tag);
5735 got_object_tag_close(re_tag);
5738 while (se) {
5739 err = got_ref_resolve(&se_id, repo, re->ref);
5740 if (err)
5741 break;
5742 err = got_object_open_as_tag(&se_tag, repo, se_id);
5743 free(se_id);
5744 if (err)
5745 break;
5746 se_time = got_object_tag_get_tagger_time(se_tag);
5747 got_object_tag_close(se_tag);
5749 if (se_time > re_time) {
5750 err = got_reflist_entry_dup(&new, re);
5751 if (err)
5752 return err;
5753 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5754 break;
5756 se = SIMPLEQ_NEXT(se, entry);
5757 continue;
5760 done:
5761 return err;
5763 #endif
5765 static const struct got_error *
5766 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5768 static const struct got_error *err = NULL;
5769 struct got_reflist_head refs;
5770 struct got_reflist_entry *re;
5772 SIMPLEQ_INIT(&refs);
5774 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5775 if (err)
5776 return err;
5778 SIMPLEQ_FOREACH(re, &refs, entry) {
5779 const char *refname;
5780 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5781 char datebuf[26];
5782 const char *tagger;
5783 time_t tagger_time;
5784 struct got_object_id *id;
5785 struct got_tag_object *tag;
5786 struct got_commit_object *commit = NULL;
5788 refname = got_ref_get_name(re->ref);
5789 if (strncmp(refname, "refs/tags/", 10) != 0)
5790 continue;
5791 refname += 10;
5792 refstr = got_ref_to_str(re->ref);
5793 if (refstr == NULL) {
5794 err = got_error_from_errno("got_ref_to_str");
5795 break;
5797 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5798 free(refstr);
5800 err = got_ref_resolve(&id, repo, re->ref);
5801 if (err)
5802 break;
5803 err = got_object_open_as_tag(&tag, repo, id);
5804 if (err) {
5805 if (err->code != GOT_ERR_OBJ_TYPE) {
5806 free(id);
5807 break;
5809 /* "lightweight" tag */
5810 err = got_object_open_as_commit(&commit, repo, id);
5811 if (err) {
5812 free(id);
5813 break;
5815 tagger = got_object_commit_get_committer(commit);
5816 tagger_time =
5817 got_object_commit_get_committer_time(commit);
5818 err = got_object_id_str(&id_str, id);
5819 free(id);
5820 if (err)
5821 break;
5822 } else {
5823 free(id);
5824 tagger = got_object_tag_get_tagger(tag);
5825 tagger_time = got_object_tag_get_tagger_time(tag);
5826 err = got_object_id_str(&id_str,
5827 got_object_tag_get_object_id(tag));
5828 if (err)
5829 break;
5831 printf("from: %s\n", tagger);
5832 datestr = get_datestr(&tagger_time, datebuf);
5833 if (datestr)
5834 printf("date: %s UTC\n", datestr);
5835 if (commit)
5836 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5837 else {
5838 switch (got_object_tag_get_object_type(tag)) {
5839 case GOT_OBJ_TYPE_BLOB:
5840 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5841 id_str);
5842 break;
5843 case GOT_OBJ_TYPE_TREE:
5844 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5845 id_str);
5846 break;
5847 case GOT_OBJ_TYPE_COMMIT:
5848 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5849 id_str);
5850 break;
5851 case GOT_OBJ_TYPE_TAG:
5852 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5853 id_str);
5854 break;
5855 default:
5856 break;
5859 free(id_str);
5860 if (commit) {
5861 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5862 if (err)
5863 break;
5864 got_object_commit_close(commit);
5865 } else {
5866 tagmsg0 = strdup(got_object_tag_get_message(tag));
5867 got_object_tag_close(tag);
5868 if (tagmsg0 == NULL) {
5869 err = got_error_from_errno("strdup");
5870 break;
5874 tagmsg = tagmsg0;
5875 do {
5876 line = strsep(&tagmsg, "\n");
5877 if (line)
5878 printf(" %s\n", line);
5879 } while (line);
5880 free(tagmsg0);
5883 got_ref_list_free(&refs);
5884 return NULL;
5887 static const struct got_error *
5888 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5889 const char *tag_name, const char *repo_path)
5891 const struct got_error *err = NULL;
5892 char *template = NULL, *initial_content = NULL;
5893 char *editor = NULL;
5894 int initial_content_len;
5895 int fd = -1;
5897 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5898 err = got_error_from_errno("asprintf");
5899 goto done;
5902 initial_content_len = asprintf(&initial_content,
5903 "\n# tagging commit %s as %s\n",
5904 commit_id_str, tag_name);
5905 if (initial_content_len == -1) {
5906 err = got_error_from_errno("asprintf");
5907 goto done;
5910 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5911 if (err)
5912 goto done;
5914 if (write(fd, initial_content, initial_content_len) == -1) {
5915 err = got_error_from_errno2("write", *tagmsg_path);
5916 goto done;
5919 err = get_editor(&editor);
5920 if (err)
5921 goto done;
5922 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5923 initial_content_len);
5924 done:
5925 free(initial_content);
5926 free(template);
5927 free(editor);
5929 if (fd != -1 && close(fd) == -1 && err == NULL)
5930 err = got_error_from_errno2("close", *tagmsg_path);
5932 /* Editor is done; we can now apply unveil(2) */
5933 if (err == NULL)
5934 err = apply_unveil(repo_path, 0, NULL);
5935 if (err) {
5936 free(*tagmsg);
5937 *tagmsg = NULL;
5939 return err;
5942 static const struct got_error *
5943 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5944 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5946 const struct got_error *err = NULL;
5947 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5948 char *label = NULL, *commit_id_str = NULL;
5949 struct got_reference *ref = NULL;
5950 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5951 char *tagmsg_path = NULL, *tag_id_str = NULL;
5952 int preserve_tagmsg = 0;
5955 * Don't let the user create a tag name with a leading '-'.
5956 * While technically a valid reference name, this case is usually
5957 * an unintended typo.
5959 if (tag_name[0] == '-')
5960 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5962 err = get_author(&tagger, repo, worktree);
5963 if (err)
5964 return err;
5966 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5967 GOT_OBJ_TYPE_COMMIT, 1, repo);
5968 if (err)
5969 goto done;
5971 err = got_object_id_str(&commit_id_str, commit_id);
5972 if (err)
5973 goto done;
5975 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5976 refname = strdup(tag_name);
5977 if (refname == NULL) {
5978 err = got_error_from_errno("strdup");
5979 goto done;
5981 tag_name += 10;
5982 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5983 err = got_error_from_errno("asprintf");
5984 goto done;
5987 err = got_ref_open(&ref, repo, refname, 0);
5988 if (err == NULL) {
5989 err = got_error(GOT_ERR_TAG_EXISTS);
5990 goto done;
5991 } else if (err->code != GOT_ERR_NOT_REF)
5992 goto done;
5994 if (tagmsg_arg == NULL) {
5995 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5996 tag_name, got_repo_get_path(repo));
5997 if (err) {
5998 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5999 tagmsg_path != NULL)
6000 preserve_tagmsg = 1;
6001 goto done;
6005 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6006 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6007 if (err) {
6008 if (tagmsg_path)
6009 preserve_tagmsg = 1;
6010 goto done;
6013 err = got_ref_alloc(&ref, refname, tag_id);
6014 if (err) {
6015 if (tagmsg_path)
6016 preserve_tagmsg = 1;
6017 goto done;
6020 err = got_ref_write(ref, repo);
6021 if (err) {
6022 if (tagmsg_path)
6023 preserve_tagmsg = 1;
6024 goto done;
6027 err = got_object_id_str(&tag_id_str, tag_id);
6028 if (err) {
6029 if (tagmsg_path)
6030 preserve_tagmsg = 1;
6031 goto done;
6033 printf("Created tag %s\n", tag_id_str);
6034 done:
6035 if (preserve_tagmsg) {
6036 fprintf(stderr, "%s: tag message preserved in %s\n",
6037 getprogname(), tagmsg_path);
6038 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6039 err = got_error_from_errno2("unlink", tagmsg_path);
6040 free(tag_id_str);
6041 if (ref)
6042 got_ref_close(ref);
6043 free(commit_id);
6044 free(commit_id_str);
6045 free(refname);
6046 free(tagmsg);
6047 free(tagmsg_path);
6048 free(tagger);
6049 return err;
6052 static const struct got_error *
6053 cmd_tag(int argc, char *argv[])
6055 const struct got_error *error = NULL;
6056 struct got_repository *repo = NULL;
6057 struct got_worktree *worktree = NULL;
6058 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6059 char *gitconfig_path = NULL;
6060 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6061 int ch, do_list = 0;
6063 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6064 switch (ch) {
6065 case 'c':
6066 commit_id_arg = optarg;
6067 break;
6068 case 'm':
6069 tagmsg = optarg;
6070 break;
6071 case 'r':
6072 repo_path = realpath(optarg, NULL);
6073 if (repo_path == NULL)
6074 return got_error_from_errno2("realpath",
6075 optarg);
6076 got_path_strip_trailing_slashes(repo_path);
6077 break;
6078 case 'l':
6079 do_list = 1;
6080 break;
6081 default:
6082 usage_tag();
6083 /* NOTREACHED */
6087 argc -= optind;
6088 argv += optind;
6090 if (do_list) {
6091 if (commit_id_arg != NULL)
6092 errx(1,
6093 "-c option can only be used when creating a tag");
6094 if (tagmsg)
6095 errx(1, "-l and -m options are mutually exclusive");
6096 if (argc > 0)
6097 usage_tag();
6098 } else if (argc != 1)
6099 usage_tag();
6101 tag_name = argv[0];
6103 #ifndef PROFILE
6104 if (do_list) {
6105 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6106 NULL) == -1)
6107 err(1, "pledge");
6108 } else {
6109 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6110 "sendfd unveil", NULL) == -1)
6111 err(1, "pledge");
6113 #endif
6114 cwd = getcwd(NULL, 0);
6115 if (cwd == NULL) {
6116 error = got_error_from_errno("getcwd");
6117 goto done;
6120 if (repo_path == NULL) {
6121 error = got_worktree_open(&worktree, cwd);
6122 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6123 goto done;
6124 else
6125 error = NULL;
6126 if (worktree) {
6127 repo_path =
6128 strdup(got_worktree_get_repo_path(worktree));
6129 if (repo_path == NULL)
6130 error = got_error_from_errno("strdup");
6131 if (error)
6132 goto done;
6133 } else {
6134 repo_path = strdup(cwd);
6135 if (repo_path == NULL) {
6136 error = got_error_from_errno("strdup");
6137 goto done;
6142 if (do_list) {
6143 error = got_repo_open(&repo, repo_path, NULL);
6144 if (error != NULL)
6145 goto done;
6146 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6147 if (error)
6148 goto done;
6149 error = list_tags(repo, worktree);
6150 } else {
6151 error = get_gitconfig_path(&gitconfig_path);
6152 if (error)
6153 goto done;
6154 error = got_repo_open(&repo, repo_path, gitconfig_path);
6155 if (error != NULL)
6156 goto done;
6158 if (tagmsg) {
6159 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6160 if (error)
6161 goto done;
6164 if (commit_id_arg == NULL) {
6165 struct got_reference *head_ref;
6166 struct got_object_id *commit_id;
6167 error = got_ref_open(&head_ref, repo,
6168 worktree ? got_worktree_get_head_ref_name(worktree)
6169 : GOT_REF_HEAD, 0);
6170 if (error)
6171 goto done;
6172 error = got_ref_resolve(&commit_id, repo, head_ref);
6173 got_ref_close(head_ref);
6174 if (error)
6175 goto done;
6176 error = got_object_id_str(&commit_id_str, commit_id);
6177 free(commit_id);
6178 if (error)
6179 goto done;
6182 error = add_tag(repo, worktree, tag_name,
6183 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6185 done:
6186 if (repo)
6187 got_repo_close(repo);
6188 if (worktree)
6189 got_worktree_close(worktree);
6190 free(cwd);
6191 free(repo_path);
6192 free(gitconfig_path);
6193 free(commit_id_str);
6194 return error;
6197 __dead static void
6198 usage_add(void)
6200 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6201 getprogname());
6202 exit(1);
6205 static const struct got_error *
6206 add_progress(void *arg, unsigned char status, const char *path)
6208 while (path[0] == '/')
6209 path++;
6210 printf("%c %s\n", status, path);
6211 return NULL;
6214 static const struct got_error *
6215 cmd_add(int argc, char *argv[])
6217 const struct got_error *error = NULL;
6218 struct got_repository *repo = NULL;
6219 struct got_worktree *worktree = NULL;
6220 char *cwd = NULL;
6221 struct got_pathlist_head paths;
6222 struct got_pathlist_entry *pe;
6223 int ch, can_recurse = 0, no_ignores = 0;
6225 TAILQ_INIT(&paths);
6227 while ((ch = getopt(argc, argv, "IR")) != -1) {
6228 switch (ch) {
6229 case 'I':
6230 no_ignores = 1;
6231 break;
6232 case 'R':
6233 can_recurse = 1;
6234 break;
6235 default:
6236 usage_add();
6237 /* NOTREACHED */
6241 argc -= optind;
6242 argv += optind;
6244 #ifndef PROFILE
6245 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6246 NULL) == -1)
6247 err(1, "pledge");
6248 #endif
6249 if (argc < 1)
6250 usage_add();
6252 cwd = getcwd(NULL, 0);
6253 if (cwd == NULL) {
6254 error = got_error_from_errno("getcwd");
6255 goto done;
6258 error = got_worktree_open(&worktree, cwd);
6259 if (error) {
6260 if (error->code == GOT_ERR_NOT_WORKTREE)
6261 error = wrap_not_worktree_error(error, "add", cwd);
6262 goto done;
6265 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6266 NULL);
6267 if (error != NULL)
6268 goto done;
6270 error = apply_unveil(got_repo_get_path(repo), 1,
6271 got_worktree_get_root_path(worktree));
6272 if (error)
6273 goto done;
6275 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6276 if (error)
6277 goto done;
6279 if (!can_recurse && no_ignores) {
6280 error = got_error_msg(GOT_ERR_BAD_PATH,
6281 "disregarding ignores requires -R option");
6282 goto done;
6286 if (!can_recurse) {
6287 char *ondisk_path;
6288 struct stat sb;
6289 TAILQ_FOREACH(pe, &paths, entry) {
6290 if (asprintf(&ondisk_path, "%s/%s",
6291 got_worktree_get_root_path(worktree),
6292 pe->path) == -1) {
6293 error = got_error_from_errno("asprintf");
6294 goto done;
6296 if (lstat(ondisk_path, &sb) == -1) {
6297 if (errno == ENOENT) {
6298 free(ondisk_path);
6299 continue;
6301 error = got_error_from_errno2("lstat",
6302 ondisk_path);
6303 free(ondisk_path);
6304 goto done;
6306 free(ondisk_path);
6307 if (S_ISDIR(sb.st_mode)) {
6308 error = got_error_msg(GOT_ERR_BAD_PATH,
6309 "adding directories requires -R option");
6310 goto done;
6315 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6316 NULL, repo, no_ignores);
6317 done:
6318 if (repo)
6319 got_repo_close(repo);
6320 if (worktree)
6321 got_worktree_close(worktree);
6322 TAILQ_FOREACH(pe, &paths, entry)
6323 free((char *)pe->path);
6324 got_pathlist_free(&paths);
6325 free(cwd);
6326 return error;
6329 __dead static void
6330 usage_remove(void)
6332 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6333 "path ...\n", getprogname());
6334 exit(1);
6337 static const struct got_error *
6338 print_remove_status(void *arg, unsigned char status,
6339 unsigned char staged_status, const char *path)
6341 while (path[0] == '/')
6342 path++;
6343 if (status == GOT_STATUS_NONEXISTENT)
6344 return NULL;
6345 if (status == staged_status && (status == GOT_STATUS_DELETE))
6346 status = GOT_STATUS_NO_CHANGE;
6347 printf("%c%c %s\n", status, staged_status, path);
6348 return NULL;
6351 static const struct got_error *
6352 cmd_remove(int argc, char *argv[])
6354 const struct got_error *error = NULL;
6355 struct got_worktree *worktree = NULL;
6356 struct got_repository *repo = NULL;
6357 const char *status_codes = NULL;
6358 char *cwd = NULL;
6359 struct got_pathlist_head paths;
6360 struct got_pathlist_entry *pe;
6361 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6363 TAILQ_INIT(&paths);
6365 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6366 switch (ch) {
6367 case 'f':
6368 delete_local_mods = 1;
6369 break;
6370 case 'k':
6371 keep_on_disk = 1;
6372 break;
6373 case 'R':
6374 can_recurse = 1;
6375 break;
6376 case 's':
6377 for (i = 0; i < strlen(optarg); i++) {
6378 switch (optarg[i]) {
6379 case GOT_STATUS_MODIFY:
6380 delete_local_mods = 1;
6381 break;
6382 case GOT_STATUS_MISSING:
6383 break;
6384 default:
6385 errx(1, "invalid status code '%c'",
6386 optarg[i]);
6389 status_codes = optarg;
6390 break;
6391 default:
6392 usage_remove();
6393 /* NOTREACHED */
6397 argc -= optind;
6398 argv += optind;
6400 #ifndef PROFILE
6401 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6402 NULL) == -1)
6403 err(1, "pledge");
6404 #endif
6405 if (argc < 1)
6406 usage_remove();
6408 cwd = getcwd(NULL, 0);
6409 if (cwd == NULL) {
6410 error = got_error_from_errno("getcwd");
6411 goto done;
6413 error = got_worktree_open(&worktree, cwd);
6414 if (error) {
6415 if (error->code == GOT_ERR_NOT_WORKTREE)
6416 error = wrap_not_worktree_error(error, "remove", cwd);
6417 goto done;
6420 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6421 NULL);
6422 if (error)
6423 goto done;
6425 error = apply_unveil(got_repo_get_path(repo), 1,
6426 got_worktree_get_root_path(worktree));
6427 if (error)
6428 goto done;
6430 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6431 if (error)
6432 goto done;
6434 if (!can_recurse) {
6435 char *ondisk_path;
6436 struct stat sb;
6437 TAILQ_FOREACH(pe, &paths, entry) {
6438 if (asprintf(&ondisk_path, "%s/%s",
6439 got_worktree_get_root_path(worktree),
6440 pe->path) == -1) {
6441 error = got_error_from_errno("asprintf");
6442 goto done;
6444 if (lstat(ondisk_path, &sb) == -1) {
6445 if (errno == ENOENT) {
6446 free(ondisk_path);
6447 continue;
6449 error = got_error_from_errno2("lstat",
6450 ondisk_path);
6451 free(ondisk_path);
6452 goto done;
6454 free(ondisk_path);
6455 if (S_ISDIR(sb.st_mode)) {
6456 error = got_error_msg(GOT_ERR_BAD_PATH,
6457 "removing directories requires -R option");
6458 goto done;
6463 error = got_worktree_schedule_delete(worktree, &paths,
6464 delete_local_mods, status_codes, print_remove_status, NULL,
6465 repo, keep_on_disk);
6466 done:
6467 if (repo)
6468 got_repo_close(repo);
6469 if (worktree)
6470 got_worktree_close(worktree);
6471 TAILQ_FOREACH(pe, &paths, entry)
6472 free((char *)pe->path);
6473 got_pathlist_free(&paths);
6474 free(cwd);
6475 return error;
6478 __dead static void
6479 usage_revert(void)
6481 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6482 "path ...\n", getprogname());
6483 exit(1);
6486 static const struct got_error *
6487 revert_progress(void *arg, unsigned char status, const char *path)
6489 if (status == GOT_STATUS_UNVERSIONED)
6490 return NULL;
6492 while (path[0] == '/')
6493 path++;
6494 printf("%c %s\n", status, path);
6495 return NULL;
6498 struct choose_patch_arg {
6499 FILE *patch_script_file;
6500 const char *action;
6503 static const struct got_error *
6504 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6505 int nchanges, const char *action)
6507 char *line = NULL;
6508 size_t linesize = 0;
6509 ssize_t linelen;
6511 switch (status) {
6512 case GOT_STATUS_ADD:
6513 printf("A %s\n%s this addition? [y/n] ", path, action);
6514 break;
6515 case GOT_STATUS_DELETE:
6516 printf("D %s\n%s this deletion? [y/n] ", path, action);
6517 break;
6518 case GOT_STATUS_MODIFY:
6519 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6520 return got_error_from_errno("fseek");
6521 printf(GOT_COMMIT_SEP_STR);
6522 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6523 printf("%s", line);
6524 if (ferror(patch_file))
6525 return got_error_from_errno("getline");
6526 printf(GOT_COMMIT_SEP_STR);
6527 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6528 path, n, nchanges, action);
6529 break;
6530 default:
6531 return got_error_path(path, GOT_ERR_FILE_STATUS);
6534 return NULL;
6537 static const struct got_error *
6538 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6539 FILE *patch_file, int n, int nchanges)
6541 const struct got_error *err = NULL;
6542 char *line = NULL;
6543 size_t linesize = 0;
6544 ssize_t linelen;
6545 int resp = ' ';
6546 struct choose_patch_arg *a = arg;
6548 *choice = GOT_PATCH_CHOICE_NONE;
6550 if (a->patch_script_file) {
6551 char *nl;
6552 err = show_change(status, path, patch_file, n, nchanges,
6553 a->action);
6554 if (err)
6555 return err;
6556 linelen = getline(&line, &linesize, a->patch_script_file);
6557 if (linelen == -1) {
6558 if (ferror(a->patch_script_file))
6559 return got_error_from_errno("getline");
6560 return NULL;
6562 nl = strchr(line, '\n');
6563 if (nl)
6564 *nl = '\0';
6565 if (strcmp(line, "y") == 0) {
6566 *choice = GOT_PATCH_CHOICE_YES;
6567 printf("y\n");
6568 } else if (strcmp(line, "n") == 0) {
6569 *choice = GOT_PATCH_CHOICE_NO;
6570 printf("n\n");
6571 } else if (strcmp(line, "q") == 0 &&
6572 status == GOT_STATUS_MODIFY) {
6573 *choice = GOT_PATCH_CHOICE_QUIT;
6574 printf("q\n");
6575 } else
6576 printf("invalid response '%s'\n", line);
6577 free(line);
6578 return NULL;
6581 while (resp != 'y' && resp != 'n' && resp != 'q') {
6582 err = show_change(status, path, patch_file, n, nchanges,
6583 a->action);
6584 if (err)
6585 return err;
6586 resp = getchar();
6587 if (resp == '\n')
6588 resp = getchar();
6589 if (status == GOT_STATUS_MODIFY) {
6590 if (resp != 'y' && resp != 'n' && resp != 'q') {
6591 printf("invalid response '%c'\n", resp);
6592 resp = ' ';
6594 } else if (resp != 'y' && resp != 'n') {
6595 printf("invalid response '%c'\n", resp);
6596 resp = ' ';
6600 if (resp == 'y')
6601 *choice = GOT_PATCH_CHOICE_YES;
6602 else if (resp == 'n')
6603 *choice = GOT_PATCH_CHOICE_NO;
6604 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6605 *choice = GOT_PATCH_CHOICE_QUIT;
6607 return NULL;
6611 static const struct got_error *
6612 cmd_revert(int argc, char *argv[])
6614 const struct got_error *error = NULL;
6615 struct got_worktree *worktree = NULL;
6616 struct got_repository *repo = NULL;
6617 char *cwd = NULL, *path = NULL;
6618 struct got_pathlist_head paths;
6619 struct got_pathlist_entry *pe;
6620 int ch, can_recurse = 0, pflag = 0;
6621 FILE *patch_script_file = NULL;
6622 const char *patch_script_path = NULL;
6623 struct choose_patch_arg cpa;
6625 TAILQ_INIT(&paths);
6627 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6628 switch (ch) {
6629 case 'p':
6630 pflag = 1;
6631 break;
6632 case 'F':
6633 patch_script_path = optarg;
6634 break;
6635 case 'R':
6636 can_recurse = 1;
6637 break;
6638 default:
6639 usage_revert();
6640 /* NOTREACHED */
6644 argc -= optind;
6645 argv += optind;
6647 #ifndef PROFILE
6648 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6649 "unveil", NULL) == -1)
6650 err(1, "pledge");
6651 #endif
6652 if (argc < 1)
6653 usage_revert();
6654 if (patch_script_path && !pflag)
6655 errx(1, "-F option can only be used together with -p option");
6657 cwd = getcwd(NULL, 0);
6658 if (cwd == NULL) {
6659 error = got_error_from_errno("getcwd");
6660 goto done;
6662 error = got_worktree_open(&worktree, cwd);
6663 if (error) {
6664 if (error->code == GOT_ERR_NOT_WORKTREE)
6665 error = wrap_not_worktree_error(error, "revert", cwd);
6666 goto done;
6669 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6670 NULL);
6671 if (error != NULL)
6672 goto done;
6674 if (patch_script_path) {
6675 patch_script_file = fopen(patch_script_path, "r");
6676 if (patch_script_file == NULL) {
6677 error = got_error_from_errno2("fopen",
6678 patch_script_path);
6679 goto done;
6682 error = apply_unveil(got_repo_get_path(repo), 1,
6683 got_worktree_get_root_path(worktree));
6684 if (error)
6685 goto done;
6687 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6688 if (error)
6689 goto done;
6691 if (!can_recurse) {
6692 char *ondisk_path;
6693 struct stat sb;
6694 TAILQ_FOREACH(pe, &paths, entry) {
6695 if (asprintf(&ondisk_path, "%s/%s",
6696 got_worktree_get_root_path(worktree),
6697 pe->path) == -1) {
6698 error = got_error_from_errno("asprintf");
6699 goto done;
6701 if (lstat(ondisk_path, &sb) == -1) {
6702 if (errno == ENOENT) {
6703 free(ondisk_path);
6704 continue;
6706 error = got_error_from_errno2("lstat",
6707 ondisk_path);
6708 free(ondisk_path);
6709 goto done;
6711 free(ondisk_path);
6712 if (S_ISDIR(sb.st_mode)) {
6713 error = got_error_msg(GOT_ERR_BAD_PATH,
6714 "reverting directories requires -R option");
6715 goto done;
6720 cpa.patch_script_file = patch_script_file;
6721 cpa.action = "revert";
6722 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6723 pflag ? choose_patch : NULL, &cpa, repo);
6724 done:
6725 if (patch_script_file && fclose(patch_script_file) == EOF &&
6726 error == NULL)
6727 error = got_error_from_errno2("fclose", patch_script_path);
6728 if (repo)
6729 got_repo_close(repo);
6730 if (worktree)
6731 got_worktree_close(worktree);
6732 free(path);
6733 free(cwd);
6734 return error;
6737 __dead static void
6738 usage_commit(void)
6740 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6741 getprogname());
6742 exit(1);
6745 struct collect_commit_logmsg_arg {
6746 const char *cmdline_log;
6747 const char *editor;
6748 const char *worktree_path;
6749 const char *branch_name;
6750 const char *repo_path;
6751 char *logmsg_path;
6755 static const struct got_error *
6756 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6757 void *arg)
6759 char *initial_content = NULL;
6760 struct got_pathlist_entry *pe;
6761 const struct got_error *err = NULL;
6762 char *template = NULL;
6763 struct collect_commit_logmsg_arg *a = arg;
6764 int initial_content_len;
6765 int fd = -1;
6766 size_t len;
6768 /* if a message was specified on the command line, just use it */
6769 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6770 len = strlen(a->cmdline_log) + 1;
6771 *logmsg = malloc(len + 1);
6772 if (*logmsg == NULL)
6773 return got_error_from_errno("malloc");
6774 strlcpy(*logmsg, a->cmdline_log, len);
6775 return NULL;
6778 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6779 return got_error_from_errno("asprintf");
6781 initial_content_len = asprintf(&initial_content,
6782 "\n# changes to be committed on branch %s:\n",
6783 a->branch_name);
6784 if (initial_content_len == -1)
6785 return got_error_from_errno("asprintf");
6787 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6788 if (err)
6789 goto done;
6791 if (write(fd, initial_content, initial_content_len) == -1) {
6792 err = got_error_from_errno2("write", a->logmsg_path);
6793 goto done;
6796 TAILQ_FOREACH(pe, commitable_paths, entry) {
6797 struct got_commitable *ct = pe->data;
6798 dprintf(fd, "# %c %s\n",
6799 got_commitable_get_status(ct),
6800 got_commitable_get_path(ct));
6803 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6804 initial_content_len);
6805 done:
6806 free(initial_content);
6807 free(template);
6809 if (fd != -1 && close(fd) == -1 && err == NULL)
6810 err = got_error_from_errno2("close", a->logmsg_path);
6812 /* Editor is done; we can now apply unveil(2) */
6813 if (err == NULL)
6814 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6815 if (err) {
6816 free(*logmsg);
6817 *logmsg = NULL;
6819 return err;
6822 static const struct got_error *
6823 cmd_commit(int argc, char *argv[])
6825 const struct got_error *error = NULL;
6826 struct got_worktree *worktree = NULL;
6827 struct got_repository *repo = NULL;
6828 char *cwd = NULL, *id_str = NULL;
6829 struct got_object_id *id = NULL;
6830 const char *logmsg = NULL;
6831 struct collect_commit_logmsg_arg cl_arg;
6832 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6833 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6834 int allow_bad_symlinks = 0;
6835 struct got_pathlist_head paths;
6837 TAILQ_INIT(&paths);
6838 cl_arg.logmsg_path = NULL;
6840 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6841 switch (ch) {
6842 case 'm':
6843 logmsg = optarg;
6844 break;
6845 case 'S':
6846 allow_bad_symlinks = 1;
6847 break;
6848 default:
6849 usage_commit();
6850 /* NOTREACHED */
6854 argc -= optind;
6855 argv += optind;
6857 #ifndef PROFILE
6858 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6859 "unveil", NULL) == -1)
6860 err(1, "pledge");
6861 #endif
6862 cwd = getcwd(NULL, 0);
6863 if (cwd == NULL) {
6864 error = got_error_from_errno("getcwd");
6865 goto done;
6867 error = got_worktree_open(&worktree, cwd);
6868 if (error) {
6869 if (error->code == GOT_ERR_NOT_WORKTREE)
6870 error = wrap_not_worktree_error(error, "commit", cwd);
6871 goto done;
6874 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6875 if (error)
6876 goto done;
6877 if (rebase_in_progress) {
6878 error = got_error(GOT_ERR_REBASING);
6879 goto done;
6882 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6883 worktree);
6884 if (error)
6885 goto done;
6887 error = get_gitconfig_path(&gitconfig_path);
6888 if (error)
6889 goto done;
6890 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6891 gitconfig_path);
6892 if (error != NULL)
6893 goto done;
6895 error = get_author(&author, repo, worktree);
6896 if (error)
6897 return error;
6900 * unveil(2) traverses exec(2); if an editor is used we have
6901 * to apply unveil after the log message has been written.
6903 if (logmsg == NULL || strlen(logmsg) == 0)
6904 error = get_editor(&editor);
6905 else
6906 error = apply_unveil(got_repo_get_path(repo), 0,
6907 got_worktree_get_root_path(worktree));
6908 if (error)
6909 goto done;
6911 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6912 if (error)
6913 goto done;
6915 cl_arg.editor = editor;
6916 cl_arg.cmdline_log = logmsg;
6917 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6918 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6919 if (!histedit_in_progress) {
6920 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6921 error = got_error(GOT_ERR_COMMIT_BRANCH);
6922 goto done;
6924 cl_arg.branch_name += 11;
6926 cl_arg.repo_path = got_repo_get_path(repo);
6927 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6928 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6929 print_status, NULL, repo);
6930 if (error) {
6931 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6932 cl_arg.logmsg_path != NULL)
6933 preserve_logmsg = 1;
6934 goto done;
6937 error = got_object_id_str(&id_str, id);
6938 if (error)
6939 goto done;
6940 printf("Created commit %s\n", id_str);
6941 done:
6942 if (preserve_logmsg) {
6943 fprintf(stderr, "%s: log message preserved in %s\n",
6944 getprogname(), cl_arg.logmsg_path);
6945 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6946 error == NULL)
6947 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6948 free(cl_arg.logmsg_path);
6949 if (repo)
6950 got_repo_close(repo);
6951 if (worktree)
6952 got_worktree_close(worktree);
6953 free(cwd);
6954 free(id_str);
6955 free(gitconfig_path);
6956 free(editor);
6957 free(author);
6958 return error;
6961 __dead static void
6962 usage_cherrypick(void)
6964 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6965 exit(1);
6968 static const struct got_error *
6969 cmd_cherrypick(int argc, char *argv[])
6971 const struct got_error *error = NULL;
6972 struct got_worktree *worktree = NULL;
6973 struct got_repository *repo = NULL;
6974 char *cwd = NULL, *commit_id_str = NULL;
6975 struct got_object_id *commit_id = NULL;
6976 struct got_commit_object *commit = NULL;
6977 struct got_object_qid *pid;
6978 struct got_reference *head_ref = NULL;
6979 int ch;
6980 struct got_update_progress_arg upa;
6982 while ((ch = getopt(argc, argv, "")) != -1) {
6983 switch (ch) {
6984 default:
6985 usage_cherrypick();
6986 /* NOTREACHED */
6990 argc -= optind;
6991 argv += optind;
6993 #ifndef PROFILE
6994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6995 "unveil", NULL) == -1)
6996 err(1, "pledge");
6997 #endif
6998 if (argc != 1)
6999 usage_cherrypick();
7001 cwd = getcwd(NULL, 0);
7002 if (cwd == NULL) {
7003 error = got_error_from_errno("getcwd");
7004 goto done;
7006 error = got_worktree_open(&worktree, cwd);
7007 if (error) {
7008 if (error->code == GOT_ERR_NOT_WORKTREE)
7009 error = wrap_not_worktree_error(error, "cherrypick",
7010 cwd);
7011 goto done;
7014 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7015 NULL);
7016 if (error != NULL)
7017 goto done;
7019 error = apply_unveil(got_repo_get_path(repo), 0,
7020 got_worktree_get_root_path(worktree));
7021 if (error)
7022 goto done;
7024 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7025 GOT_OBJ_TYPE_COMMIT, repo);
7026 if (error != NULL) {
7027 struct got_reference *ref;
7028 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7029 goto done;
7030 error = got_ref_open(&ref, repo, argv[0], 0);
7031 if (error != NULL)
7032 goto done;
7033 error = got_ref_resolve(&commit_id, repo, ref);
7034 got_ref_close(ref);
7035 if (error != NULL)
7036 goto done;
7038 error = got_object_id_str(&commit_id_str, commit_id);
7039 if (error)
7040 goto done;
7042 error = got_ref_open(&head_ref, repo,
7043 got_worktree_get_head_ref_name(worktree), 0);
7044 if (error != NULL)
7045 goto done;
7047 error = check_same_branch(commit_id, head_ref, NULL, repo);
7048 if (error) {
7049 if (error->code != GOT_ERR_ANCESTRY)
7050 goto done;
7051 error = NULL;
7052 } else {
7053 error = got_error(GOT_ERR_SAME_BRANCH);
7054 goto done;
7057 error = got_object_open_as_commit(&commit, repo, commit_id);
7058 if (error)
7059 goto done;
7060 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7061 memset(&upa, 0, sizeof(upa));
7062 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7063 commit_id, repo, update_progress, &upa, check_cancelled,
7064 NULL);
7065 if (error != NULL)
7066 goto done;
7068 if (upa.did_something)
7069 printf("Merged commit %s\n", commit_id_str);
7070 print_update_progress_stats(&upa);
7071 done:
7072 if (commit)
7073 got_object_commit_close(commit);
7074 free(commit_id_str);
7075 if (head_ref)
7076 got_ref_close(head_ref);
7077 if (worktree)
7078 got_worktree_close(worktree);
7079 if (repo)
7080 got_repo_close(repo);
7081 return error;
7084 __dead static void
7085 usage_backout(void)
7087 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7088 exit(1);
7091 static const struct got_error *
7092 cmd_backout(int argc, char *argv[])
7094 const struct got_error *error = NULL;
7095 struct got_worktree *worktree = NULL;
7096 struct got_repository *repo = NULL;
7097 char *cwd = NULL, *commit_id_str = NULL;
7098 struct got_object_id *commit_id = NULL;
7099 struct got_commit_object *commit = NULL;
7100 struct got_object_qid *pid;
7101 struct got_reference *head_ref = NULL;
7102 int ch;
7103 struct got_update_progress_arg upa;
7105 while ((ch = getopt(argc, argv, "")) != -1) {
7106 switch (ch) {
7107 default:
7108 usage_backout();
7109 /* NOTREACHED */
7113 argc -= optind;
7114 argv += optind;
7116 #ifndef PROFILE
7117 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7118 "unveil", NULL) == -1)
7119 err(1, "pledge");
7120 #endif
7121 if (argc != 1)
7122 usage_backout();
7124 cwd = getcwd(NULL, 0);
7125 if (cwd == NULL) {
7126 error = got_error_from_errno("getcwd");
7127 goto done;
7129 error = got_worktree_open(&worktree, cwd);
7130 if (error) {
7131 if (error->code == GOT_ERR_NOT_WORKTREE)
7132 error = wrap_not_worktree_error(error, "backout", cwd);
7133 goto done;
7136 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7137 NULL);
7138 if (error != NULL)
7139 goto done;
7141 error = apply_unveil(got_repo_get_path(repo), 0,
7142 got_worktree_get_root_path(worktree));
7143 if (error)
7144 goto done;
7146 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7147 GOT_OBJ_TYPE_COMMIT, repo);
7148 if (error != NULL) {
7149 struct got_reference *ref;
7150 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7151 goto done;
7152 error = got_ref_open(&ref, repo, argv[0], 0);
7153 if (error != NULL)
7154 goto done;
7155 error = got_ref_resolve(&commit_id, repo, ref);
7156 got_ref_close(ref);
7157 if (error != NULL)
7158 goto done;
7160 error = got_object_id_str(&commit_id_str, commit_id);
7161 if (error)
7162 goto done;
7164 error = got_ref_open(&head_ref, repo,
7165 got_worktree_get_head_ref_name(worktree), 0);
7166 if (error != NULL)
7167 goto done;
7169 error = check_same_branch(commit_id, head_ref, NULL, repo);
7170 if (error)
7171 goto done;
7173 error = got_object_open_as_commit(&commit, repo, commit_id);
7174 if (error)
7175 goto done;
7176 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7177 if (pid == NULL) {
7178 error = got_error(GOT_ERR_ROOT_COMMIT);
7179 goto done;
7182 memset(&upa, 0, sizeof(upa));
7183 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7184 update_progress, &upa, check_cancelled, NULL);
7185 if (error != NULL)
7186 goto done;
7188 if (upa.did_something)
7189 printf("Backed out commit %s\n", commit_id_str);
7190 print_update_progress_stats(&upa);
7191 done:
7192 if (commit)
7193 got_object_commit_close(commit);
7194 free(commit_id_str);
7195 if (head_ref)
7196 got_ref_close(head_ref);
7197 if (worktree)
7198 got_worktree_close(worktree);
7199 if (repo)
7200 got_repo_close(repo);
7201 return error;
7204 __dead static void
7205 usage_rebase(void)
7207 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7208 getprogname());
7209 exit(1);
7212 void
7213 trim_logmsg(char *logmsg, int limit)
7215 char *nl;
7216 size_t len;
7218 len = strlen(logmsg);
7219 if (len > limit)
7220 len = limit;
7221 logmsg[len] = '\0';
7222 nl = strchr(logmsg, '\n');
7223 if (nl)
7224 *nl = '\0';
7227 static const struct got_error *
7228 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7230 const struct got_error *err;
7231 char *logmsg0 = NULL;
7232 const char *s;
7234 err = got_object_commit_get_logmsg(&logmsg0, commit);
7235 if (err)
7236 return err;
7238 s = logmsg0;
7239 while (isspace((unsigned char)s[0]))
7240 s++;
7242 *logmsg = strdup(s);
7243 if (*logmsg == NULL) {
7244 err = got_error_from_errno("strdup");
7245 goto done;
7248 trim_logmsg(*logmsg, limit);
7249 done:
7250 free(logmsg0);
7251 return err;
7254 static const struct got_error *
7255 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7257 const struct got_error *err;
7258 struct got_commit_object *commit = NULL;
7259 char *id_str = NULL, *logmsg = NULL;
7261 err = got_object_open_as_commit(&commit, repo, id);
7262 if (err)
7263 return err;
7265 err = got_object_id_str(&id_str, id);
7266 if (err)
7267 goto done;
7269 id_str[12] = '\0';
7271 err = get_short_logmsg(&logmsg, 42, commit);
7272 if (err)
7273 goto done;
7275 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7276 done:
7277 free(id_str);
7278 got_object_commit_close(commit);
7279 free(logmsg);
7280 return err;
7283 static const struct got_error *
7284 show_rebase_progress(struct got_commit_object *commit,
7285 struct got_object_id *old_id, struct got_object_id *new_id)
7287 const struct got_error *err;
7288 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7290 err = got_object_id_str(&old_id_str, old_id);
7291 if (err)
7292 goto done;
7294 if (new_id) {
7295 err = got_object_id_str(&new_id_str, new_id);
7296 if (err)
7297 goto done;
7300 old_id_str[12] = '\0';
7301 if (new_id_str)
7302 new_id_str[12] = '\0';
7304 err = get_short_logmsg(&logmsg, 42, commit);
7305 if (err)
7306 goto done;
7308 printf("%s -> %s: %s\n", old_id_str,
7309 new_id_str ? new_id_str : "no-op change", logmsg);
7310 done:
7311 free(old_id_str);
7312 free(new_id_str);
7313 free(logmsg);
7314 return err;
7317 static const struct got_error *
7318 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7319 struct got_reference *branch, struct got_reference *new_base_branch,
7320 struct got_reference *tmp_branch, struct got_repository *repo)
7322 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7323 return got_worktree_rebase_complete(worktree, fileindex,
7324 new_base_branch, tmp_branch, branch, repo);
7327 static const struct got_error *
7328 rebase_commit(struct got_pathlist_head *merged_paths,
7329 struct got_worktree *worktree, struct got_fileindex *fileindex,
7330 struct got_reference *tmp_branch,
7331 struct got_object_id *commit_id, struct got_repository *repo)
7333 const struct got_error *error;
7334 struct got_commit_object *commit;
7335 struct got_object_id *new_commit_id;
7337 error = got_object_open_as_commit(&commit, repo, commit_id);
7338 if (error)
7339 return error;
7341 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7342 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7343 if (error) {
7344 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7345 goto done;
7346 error = show_rebase_progress(commit, commit_id, NULL);
7347 } else {
7348 error = show_rebase_progress(commit, commit_id, new_commit_id);
7349 free(new_commit_id);
7351 done:
7352 got_object_commit_close(commit);
7353 return error;
7356 struct check_path_prefix_arg {
7357 const char *path_prefix;
7358 size_t len;
7359 int errcode;
7362 static const struct got_error *
7363 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7364 struct got_blob_object *blob2, struct got_object_id *id1,
7365 struct got_object_id *id2, const char *path1, const char *path2,
7366 mode_t mode1, mode_t mode2, struct got_repository *repo)
7368 struct check_path_prefix_arg *a = arg;
7370 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7371 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7372 return got_error(a->errcode);
7374 return NULL;
7377 static const struct got_error *
7378 check_path_prefix(struct got_object_id *parent_id,
7379 struct got_object_id *commit_id, const char *path_prefix,
7380 int errcode, struct got_repository *repo)
7382 const struct got_error *err;
7383 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7384 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7385 struct check_path_prefix_arg cpp_arg;
7387 if (got_path_is_root_dir(path_prefix))
7388 return NULL;
7390 err = got_object_open_as_commit(&commit, repo, commit_id);
7391 if (err)
7392 goto done;
7394 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7395 if (err)
7396 goto done;
7398 err = got_object_open_as_tree(&tree1, repo,
7399 got_object_commit_get_tree_id(parent_commit));
7400 if (err)
7401 goto done;
7403 err = got_object_open_as_tree(&tree2, repo,
7404 got_object_commit_get_tree_id(commit));
7405 if (err)
7406 goto done;
7408 cpp_arg.path_prefix = path_prefix;
7409 while (cpp_arg.path_prefix[0] == '/')
7410 cpp_arg.path_prefix++;
7411 cpp_arg.len = strlen(cpp_arg.path_prefix);
7412 cpp_arg.errcode = errcode;
7413 err = got_diff_tree(tree1, tree2, "", "", repo,
7414 check_path_prefix_in_diff, &cpp_arg, 0);
7415 done:
7416 if (tree1)
7417 got_object_tree_close(tree1);
7418 if (tree2)
7419 got_object_tree_close(tree2);
7420 if (commit)
7421 got_object_commit_close(commit);
7422 if (parent_commit)
7423 got_object_commit_close(parent_commit);
7424 return err;
7427 static const struct got_error *
7428 collect_commits(struct got_object_id_queue *commits,
7429 struct got_object_id *initial_commit_id,
7430 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7431 const char *path_prefix, int path_prefix_errcode,
7432 struct got_repository *repo)
7434 const struct got_error *err = NULL;
7435 struct got_commit_graph *graph = NULL;
7436 struct got_object_id *parent_id = NULL;
7437 struct got_object_qid *qid;
7438 struct got_object_id *commit_id = initial_commit_id;
7440 err = got_commit_graph_open(&graph, "/", 1);
7441 if (err)
7442 return err;
7444 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7445 check_cancelled, NULL);
7446 if (err)
7447 goto done;
7448 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7449 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7450 check_cancelled, NULL);
7451 if (err) {
7452 if (err->code == GOT_ERR_ITER_COMPLETED) {
7453 err = got_error_msg(GOT_ERR_ANCESTRY,
7454 "ran out of commits to rebase before "
7455 "youngest common ancestor commit has "
7456 "been reached?!?");
7458 goto done;
7459 } else {
7460 err = check_path_prefix(parent_id, commit_id,
7461 path_prefix, path_prefix_errcode, repo);
7462 if (err)
7463 goto done;
7465 err = got_object_qid_alloc(&qid, commit_id);
7466 if (err)
7467 goto done;
7468 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7469 commit_id = parent_id;
7472 done:
7473 got_commit_graph_close(graph);
7474 return err;
7477 static const struct got_error *
7478 cmd_rebase(int argc, char *argv[])
7480 const struct got_error *error = NULL;
7481 struct got_worktree *worktree = NULL;
7482 struct got_repository *repo = NULL;
7483 struct got_fileindex *fileindex = NULL;
7484 char *cwd = NULL;
7485 struct got_reference *branch = NULL;
7486 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7487 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7488 struct got_object_id *resume_commit_id = NULL;
7489 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7490 struct got_commit_object *commit = NULL;
7491 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7492 int histedit_in_progress = 0;
7493 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7494 struct got_object_id_queue commits;
7495 struct got_pathlist_head merged_paths;
7496 const struct got_object_id_queue *parent_ids;
7497 struct got_object_qid *qid, *pid;
7499 SIMPLEQ_INIT(&commits);
7500 TAILQ_INIT(&merged_paths);
7502 while ((ch = getopt(argc, argv, "ac")) != -1) {
7503 switch (ch) {
7504 case 'a':
7505 abort_rebase = 1;
7506 break;
7507 case 'c':
7508 continue_rebase = 1;
7509 break;
7510 default:
7511 usage_rebase();
7512 /* NOTREACHED */
7516 argc -= optind;
7517 argv += optind;
7519 #ifndef PROFILE
7520 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7521 "unveil", NULL) == -1)
7522 err(1, "pledge");
7523 #endif
7524 if (abort_rebase && continue_rebase)
7525 usage_rebase();
7526 else if (abort_rebase || continue_rebase) {
7527 if (argc != 0)
7528 usage_rebase();
7529 } else if (argc != 1)
7530 usage_rebase();
7532 cwd = getcwd(NULL, 0);
7533 if (cwd == NULL) {
7534 error = got_error_from_errno("getcwd");
7535 goto done;
7537 error = got_worktree_open(&worktree, cwd);
7538 if (error) {
7539 if (error->code == GOT_ERR_NOT_WORKTREE)
7540 error = wrap_not_worktree_error(error, "rebase", cwd);
7541 goto done;
7544 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7545 NULL);
7546 if (error != NULL)
7547 goto done;
7549 error = apply_unveil(got_repo_get_path(repo), 0,
7550 got_worktree_get_root_path(worktree));
7551 if (error)
7552 goto done;
7554 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7555 worktree);
7556 if (error)
7557 goto done;
7558 if (histedit_in_progress) {
7559 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7560 goto done;
7563 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7564 if (error)
7565 goto done;
7567 if (abort_rebase) {
7568 struct got_update_progress_arg upa;
7569 if (!rebase_in_progress) {
7570 error = got_error(GOT_ERR_NOT_REBASING);
7571 goto done;
7573 error = got_worktree_rebase_continue(&resume_commit_id,
7574 &new_base_branch, &tmp_branch, &branch, &fileindex,
7575 worktree, repo);
7576 if (error)
7577 goto done;
7578 printf("Switching work tree to %s\n",
7579 got_ref_get_symref_target(new_base_branch));
7580 memset(&upa, 0, sizeof(upa));
7581 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7582 new_base_branch, update_progress, &upa);
7583 if (error)
7584 goto done;
7585 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7586 print_update_progress_stats(&upa);
7587 goto done; /* nothing else to do */
7590 if (continue_rebase) {
7591 if (!rebase_in_progress) {
7592 error = got_error(GOT_ERR_NOT_REBASING);
7593 goto done;
7595 error = got_worktree_rebase_continue(&resume_commit_id,
7596 &new_base_branch, &tmp_branch, &branch, &fileindex,
7597 worktree, repo);
7598 if (error)
7599 goto done;
7601 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7602 resume_commit_id, repo);
7603 if (error)
7604 goto done;
7606 yca_id = got_object_id_dup(resume_commit_id);
7607 if (yca_id == NULL) {
7608 error = got_error_from_errno("got_object_id_dup");
7609 goto done;
7611 } else {
7612 error = got_ref_open(&branch, repo, argv[0], 0);
7613 if (error != NULL)
7614 goto done;
7617 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7618 if (error)
7619 goto done;
7621 if (!continue_rebase) {
7622 struct got_object_id *base_commit_id;
7624 base_commit_id = got_worktree_get_base_commit_id(worktree);
7625 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7626 base_commit_id, branch_head_commit_id, repo,
7627 check_cancelled, NULL);
7628 if (error)
7629 goto done;
7630 if (yca_id == NULL) {
7631 error = got_error_msg(GOT_ERR_ANCESTRY,
7632 "specified branch shares no common ancestry "
7633 "with work tree's branch");
7634 goto done;
7637 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7638 if (error) {
7639 if (error->code != GOT_ERR_ANCESTRY)
7640 goto done;
7641 error = NULL;
7642 } else {
7643 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7644 "specified branch resolves to a commit which "
7645 "is already contained in work tree's branch");
7646 goto done;
7648 error = got_worktree_rebase_prepare(&new_base_branch,
7649 &tmp_branch, &fileindex, worktree, branch, repo);
7650 if (error)
7651 goto done;
7654 commit_id = branch_head_commit_id;
7655 error = got_object_open_as_commit(&commit, repo, commit_id);
7656 if (error)
7657 goto done;
7659 parent_ids = got_object_commit_get_parent_ids(commit);
7660 pid = SIMPLEQ_FIRST(parent_ids);
7661 if (pid == NULL) {
7662 if (!continue_rebase) {
7663 struct got_update_progress_arg upa;
7664 memset(&upa, 0, sizeof(upa));
7665 error = got_worktree_rebase_abort(worktree, fileindex,
7666 repo, new_base_branch, update_progress, &upa);
7667 if (error)
7668 goto done;
7669 printf("Rebase of %s aborted\n",
7670 got_ref_get_name(branch));
7671 print_update_progress_stats(&upa);
7674 error = got_error(GOT_ERR_EMPTY_REBASE);
7675 goto done;
7677 error = collect_commits(&commits, commit_id, pid->id,
7678 yca_id, got_worktree_get_path_prefix(worktree),
7679 GOT_ERR_REBASE_PATH, repo);
7680 got_object_commit_close(commit);
7681 commit = NULL;
7682 if (error)
7683 goto done;
7685 if (SIMPLEQ_EMPTY(&commits)) {
7686 if (continue_rebase) {
7687 error = rebase_complete(worktree, fileindex,
7688 branch, new_base_branch, tmp_branch, repo);
7689 goto done;
7690 } else {
7691 /* Fast-forward the reference of the branch. */
7692 struct got_object_id *new_head_commit_id;
7693 char *id_str;
7694 error = got_ref_resolve(&new_head_commit_id, repo,
7695 new_base_branch);
7696 if (error)
7697 goto done;
7698 error = got_object_id_str(&id_str, new_head_commit_id);
7699 printf("Forwarding %s to commit %s\n",
7700 got_ref_get_name(branch), id_str);
7701 free(id_str);
7702 error = got_ref_change_ref(branch,
7703 new_head_commit_id);
7704 if (error)
7705 goto done;
7709 pid = NULL;
7710 SIMPLEQ_FOREACH(qid, &commits, entry) {
7711 struct got_update_progress_arg upa;
7713 commit_id = qid->id;
7714 parent_id = pid ? pid->id : yca_id;
7715 pid = qid;
7717 memset(&upa, 0, sizeof(upa));
7718 error = got_worktree_rebase_merge_files(&merged_paths,
7719 worktree, fileindex, parent_id, commit_id, repo,
7720 update_progress, &upa, check_cancelled, NULL);
7721 if (error)
7722 goto done;
7724 print_update_progress_stats(&upa);
7725 if (upa.conflicts > 0)
7726 rebase_status = GOT_STATUS_CONFLICT;
7728 if (rebase_status == GOT_STATUS_CONFLICT) {
7729 error = show_rebase_merge_conflict(qid->id, repo);
7730 if (error)
7731 goto done;
7732 got_worktree_rebase_pathlist_free(&merged_paths);
7733 break;
7736 error = rebase_commit(&merged_paths, worktree, fileindex,
7737 tmp_branch, commit_id, repo);
7738 got_worktree_rebase_pathlist_free(&merged_paths);
7739 if (error)
7740 goto done;
7743 if (rebase_status == GOT_STATUS_CONFLICT) {
7744 error = got_worktree_rebase_postpone(worktree, fileindex);
7745 if (error)
7746 goto done;
7747 error = got_error_msg(GOT_ERR_CONFLICTS,
7748 "conflicts must be resolved before rebasing can continue");
7749 } else
7750 error = rebase_complete(worktree, fileindex, branch,
7751 new_base_branch, tmp_branch, repo);
7752 done:
7753 got_object_id_queue_free(&commits);
7754 free(branch_head_commit_id);
7755 free(resume_commit_id);
7756 free(yca_id);
7757 if (commit)
7758 got_object_commit_close(commit);
7759 if (branch)
7760 got_ref_close(branch);
7761 if (new_base_branch)
7762 got_ref_close(new_base_branch);
7763 if (tmp_branch)
7764 got_ref_close(tmp_branch);
7765 if (worktree)
7766 got_worktree_close(worktree);
7767 if (repo)
7768 got_repo_close(repo);
7769 return error;
7772 __dead static void
7773 usage_histedit(void)
7775 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7776 getprogname());
7777 exit(1);
7780 #define GOT_HISTEDIT_PICK 'p'
7781 #define GOT_HISTEDIT_EDIT 'e'
7782 #define GOT_HISTEDIT_FOLD 'f'
7783 #define GOT_HISTEDIT_DROP 'd'
7784 #define GOT_HISTEDIT_MESG 'm'
7786 static struct got_histedit_cmd {
7787 unsigned char code;
7788 const char *name;
7789 const char *desc;
7790 } got_histedit_cmds[] = {
7791 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7792 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7793 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7794 "be used" },
7795 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7796 { GOT_HISTEDIT_MESG, "mesg",
7797 "single-line log message for commit above (open editor if empty)" },
7800 struct got_histedit_list_entry {
7801 TAILQ_ENTRY(got_histedit_list_entry) entry;
7802 struct got_object_id *commit_id;
7803 const struct got_histedit_cmd *cmd;
7804 char *logmsg;
7806 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7808 static const struct got_error *
7809 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7810 FILE *f, struct got_repository *repo)
7812 const struct got_error *err = NULL;
7813 char *logmsg = NULL, *id_str = NULL;
7814 struct got_commit_object *commit = NULL;
7815 int n;
7817 err = got_object_open_as_commit(&commit, repo, commit_id);
7818 if (err)
7819 goto done;
7821 err = get_short_logmsg(&logmsg, 34, commit);
7822 if (err)
7823 goto done;
7825 err = got_object_id_str(&id_str, commit_id);
7826 if (err)
7827 goto done;
7829 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7830 if (n < 0)
7831 err = got_ferror(f, GOT_ERR_IO);
7832 done:
7833 if (commit)
7834 got_object_commit_close(commit);
7835 free(id_str);
7836 free(logmsg);
7837 return err;
7840 static const struct got_error *
7841 histedit_write_commit_list(struct got_object_id_queue *commits,
7842 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7844 const struct got_error *err = NULL;
7845 struct got_object_qid *qid;
7847 if (SIMPLEQ_EMPTY(commits))
7848 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7850 SIMPLEQ_FOREACH(qid, commits, entry) {
7851 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7852 f, repo);
7853 if (err)
7854 break;
7855 if (edit_logmsg_only) {
7856 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7857 if (n < 0) {
7858 err = got_ferror(f, GOT_ERR_IO);
7859 break;
7864 return err;
7867 static const struct got_error *
7868 write_cmd_list(FILE *f, const char *branch_name,
7869 struct got_object_id_queue *commits)
7871 const struct got_error *err = NULL;
7872 int n, i;
7873 char *id_str;
7874 struct got_object_qid *qid;
7876 qid = SIMPLEQ_FIRST(commits);
7877 err = got_object_id_str(&id_str, qid->id);
7878 if (err)
7879 return err;
7881 n = fprintf(f,
7882 "# Editing the history of branch '%s' starting at\n"
7883 "# commit %s\n"
7884 "# Commits will be processed in order from top to "
7885 "bottom of this file.\n", branch_name, id_str);
7886 if (n < 0) {
7887 err = got_ferror(f, GOT_ERR_IO);
7888 goto done;
7891 n = fprintf(f, "# Available histedit commands:\n");
7892 if (n < 0) {
7893 err = got_ferror(f, GOT_ERR_IO);
7894 goto done;
7897 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7898 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7899 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7900 cmd->desc);
7901 if (n < 0) {
7902 err = got_ferror(f, GOT_ERR_IO);
7903 break;
7906 done:
7907 free(id_str);
7908 return err;
7911 static const struct got_error *
7912 histedit_syntax_error(int lineno)
7914 static char msg[42];
7915 int ret;
7917 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7918 lineno);
7919 if (ret == -1 || ret >= sizeof(msg))
7920 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7922 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7925 static const struct got_error *
7926 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7927 char *logmsg, struct got_repository *repo)
7929 const struct got_error *err;
7930 struct got_commit_object *folded_commit = NULL;
7931 char *id_str, *folded_logmsg = NULL;
7933 err = got_object_id_str(&id_str, hle->commit_id);
7934 if (err)
7935 return err;
7937 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7938 if (err)
7939 goto done;
7941 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7942 if (err)
7943 goto done;
7944 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7945 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7946 folded_logmsg) == -1) {
7947 err = got_error_from_errno("asprintf");
7949 done:
7950 if (folded_commit)
7951 got_object_commit_close(folded_commit);
7952 free(id_str);
7953 free(folded_logmsg);
7954 return err;
7957 static struct got_histedit_list_entry *
7958 get_folded_commits(struct got_histedit_list_entry *hle)
7960 struct got_histedit_list_entry *prev, *folded = NULL;
7962 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7963 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7964 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7965 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7966 folded = prev;
7967 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7970 return folded;
7973 static const struct got_error *
7974 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7975 struct got_repository *repo)
7977 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7978 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7979 const struct got_error *err = NULL;
7980 struct got_commit_object *commit = NULL;
7981 int logmsg_len;
7982 int fd;
7983 struct got_histedit_list_entry *folded = NULL;
7985 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7986 if (err)
7987 return err;
7989 folded = get_folded_commits(hle);
7990 if (folded) {
7991 while (folded != hle) {
7992 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7993 folded = TAILQ_NEXT(folded, entry);
7994 continue;
7996 err = append_folded_commit_msg(&new_msg, folded,
7997 logmsg, repo);
7998 if (err)
7999 goto done;
8000 free(logmsg);
8001 logmsg = new_msg;
8002 folded = TAILQ_NEXT(folded, entry);
8006 err = got_object_id_str(&id_str, hle->commit_id);
8007 if (err)
8008 goto done;
8009 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8010 if (err)
8011 goto done;
8012 logmsg_len = asprintf(&new_msg,
8013 "%s\n# original log message of commit %s: %s",
8014 logmsg ? logmsg : "", id_str, orig_logmsg);
8015 if (logmsg_len == -1) {
8016 err = got_error_from_errno("asprintf");
8017 goto done;
8019 free(logmsg);
8020 logmsg = new_msg;
8022 err = got_object_id_str(&id_str, hle->commit_id);
8023 if (err)
8024 goto done;
8026 err = got_opentemp_named_fd(&logmsg_path, &fd,
8027 GOT_TMPDIR_STR "/got-logmsg");
8028 if (err)
8029 goto done;
8031 write(fd, logmsg, logmsg_len);
8032 close(fd);
8034 err = get_editor(&editor);
8035 if (err)
8036 goto done;
8038 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8039 logmsg_len);
8040 if (err) {
8041 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8042 goto done;
8043 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8045 done:
8046 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8047 err = got_error_from_errno2("unlink", logmsg_path);
8048 free(logmsg_path);
8049 free(logmsg);
8050 free(orig_logmsg);
8051 free(editor);
8052 if (commit)
8053 got_object_commit_close(commit);
8054 return err;
8057 static const struct got_error *
8058 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8059 FILE *f, struct got_repository *repo)
8061 const struct got_error *err = NULL;
8062 char *line = NULL, *p, *end;
8063 size_t size;
8064 ssize_t len;
8065 int lineno = 0, i;
8066 const struct got_histedit_cmd *cmd;
8067 struct got_object_id *commit_id = NULL;
8068 struct got_histedit_list_entry *hle = NULL;
8070 for (;;) {
8071 len = getline(&line, &size, f);
8072 if (len == -1) {
8073 const struct got_error *getline_err;
8074 if (feof(f))
8075 break;
8076 getline_err = got_error_from_errno("getline");
8077 err = got_ferror(f, getline_err->code);
8078 break;
8080 lineno++;
8081 p = line;
8082 while (isspace((unsigned char)p[0]))
8083 p++;
8084 if (p[0] == '#' || p[0] == '\0') {
8085 free(line);
8086 line = NULL;
8087 continue;
8089 cmd = NULL;
8090 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8091 cmd = &got_histedit_cmds[i];
8092 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8093 isspace((unsigned char)p[strlen(cmd->name)])) {
8094 p += strlen(cmd->name);
8095 break;
8097 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8098 p++;
8099 break;
8102 if (i == nitems(got_histedit_cmds)) {
8103 err = histedit_syntax_error(lineno);
8104 break;
8106 while (isspace((unsigned char)p[0]))
8107 p++;
8108 if (cmd->code == GOT_HISTEDIT_MESG) {
8109 if (hle == NULL || hle->logmsg != NULL) {
8110 err = got_error(GOT_ERR_HISTEDIT_CMD);
8111 break;
8113 if (p[0] == '\0') {
8114 err = histedit_edit_logmsg(hle, repo);
8115 if (err)
8116 break;
8117 } else {
8118 hle->logmsg = strdup(p);
8119 if (hle->logmsg == NULL) {
8120 err = got_error_from_errno("strdup");
8121 break;
8124 free(line);
8125 line = NULL;
8126 continue;
8127 } else {
8128 end = p;
8129 while (end[0] && !isspace((unsigned char)end[0]))
8130 end++;
8131 *end = '\0';
8133 err = got_object_resolve_id_str(&commit_id, repo, p);
8134 if (err) {
8135 /* override error code */
8136 err = histedit_syntax_error(lineno);
8137 break;
8140 hle = malloc(sizeof(*hle));
8141 if (hle == NULL) {
8142 err = got_error_from_errno("malloc");
8143 break;
8145 hle->cmd = cmd;
8146 hle->commit_id = commit_id;
8147 hle->logmsg = NULL;
8148 commit_id = NULL;
8149 free(line);
8150 line = NULL;
8151 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8154 free(line);
8155 free(commit_id);
8156 return err;
8159 static const struct got_error *
8160 histedit_check_script(struct got_histedit_list *histedit_cmds,
8161 struct got_object_id_queue *commits, struct got_repository *repo)
8163 const struct got_error *err = NULL;
8164 struct got_object_qid *qid;
8165 struct got_histedit_list_entry *hle;
8166 static char msg[92];
8167 char *id_str;
8169 if (TAILQ_EMPTY(histedit_cmds))
8170 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8171 "histedit script contains no commands");
8172 if (SIMPLEQ_EMPTY(commits))
8173 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8175 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8176 struct got_histedit_list_entry *hle2;
8177 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8178 if (hle == hle2)
8179 continue;
8180 if (got_object_id_cmp(hle->commit_id,
8181 hle2->commit_id) != 0)
8182 continue;
8183 err = got_object_id_str(&id_str, hle->commit_id);
8184 if (err)
8185 return err;
8186 snprintf(msg, sizeof(msg), "commit %s is listed "
8187 "more than once in histedit script", id_str);
8188 free(id_str);
8189 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8193 SIMPLEQ_FOREACH(qid, commits, entry) {
8194 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8195 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8196 break;
8198 if (hle == NULL) {
8199 err = got_object_id_str(&id_str, qid->id);
8200 if (err)
8201 return err;
8202 snprintf(msg, sizeof(msg),
8203 "commit %s missing from histedit script", id_str);
8204 free(id_str);
8205 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8209 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8210 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8211 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8212 "last commit in histedit script cannot be folded");
8214 return NULL;
8217 static const struct got_error *
8218 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8219 const char *path, struct got_object_id_queue *commits,
8220 struct got_repository *repo)
8222 const struct got_error *err = NULL;
8223 char *editor;
8224 FILE *f = NULL;
8226 err = get_editor(&editor);
8227 if (err)
8228 return err;
8230 if (spawn_editor(editor, path) == -1) {
8231 err = got_error_from_errno("failed spawning editor");
8232 goto done;
8235 f = fopen(path, "r");
8236 if (f == NULL) {
8237 err = got_error_from_errno("fopen");
8238 goto done;
8240 err = histedit_parse_list(histedit_cmds, f, repo);
8241 if (err)
8242 goto done;
8244 err = histedit_check_script(histedit_cmds, commits, repo);
8245 done:
8246 if (f && fclose(f) != 0 && err == NULL)
8247 err = got_error_from_errno("fclose");
8248 free(editor);
8249 return err;
8252 static const struct got_error *
8253 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8254 struct got_object_id_queue *, const char *, const char *,
8255 struct got_repository *);
8257 static const struct got_error *
8258 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8259 struct got_object_id_queue *commits, const char *branch_name,
8260 int edit_logmsg_only, struct got_repository *repo)
8262 const struct got_error *err;
8263 FILE *f = NULL;
8264 char *path = NULL;
8266 err = got_opentemp_named(&path, &f, "got-histedit");
8267 if (err)
8268 return err;
8270 err = write_cmd_list(f, branch_name, commits);
8271 if (err)
8272 goto done;
8274 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8275 if (err)
8276 goto done;
8278 if (edit_logmsg_only) {
8279 rewind(f);
8280 err = histedit_parse_list(histedit_cmds, f, repo);
8281 } else {
8282 if (fclose(f) != 0) {
8283 err = got_error_from_errno("fclose");
8284 goto done;
8286 f = NULL;
8287 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8288 if (err) {
8289 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8290 err->code != GOT_ERR_HISTEDIT_CMD)
8291 goto done;
8292 err = histedit_edit_list_retry(histedit_cmds, err,
8293 commits, path, branch_name, repo);
8296 done:
8297 if (f && fclose(f) != 0 && err == NULL)
8298 err = got_error_from_errno("fclose");
8299 if (path && unlink(path) != 0 && err == NULL)
8300 err = got_error_from_errno2("unlink", path);
8301 free(path);
8302 return err;
8305 static const struct got_error *
8306 histedit_save_list(struct got_histedit_list *histedit_cmds,
8307 struct got_worktree *worktree, struct got_repository *repo)
8309 const struct got_error *err = NULL;
8310 char *path = NULL;
8311 FILE *f = NULL;
8312 struct got_histedit_list_entry *hle;
8313 struct got_commit_object *commit = NULL;
8315 err = got_worktree_get_histedit_script_path(&path, worktree);
8316 if (err)
8317 return err;
8319 f = fopen(path, "w");
8320 if (f == NULL) {
8321 err = got_error_from_errno2("fopen", path);
8322 goto done;
8324 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8325 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8326 repo);
8327 if (err)
8328 break;
8330 if (hle->logmsg) {
8331 int n = fprintf(f, "%c %s\n",
8332 GOT_HISTEDIT_MESG, hle->logmsg);
8333 if (n < 0) {
8334 err = got_ferror(f, GOT_ERR_IO);
8335 break;
8339 done:
8340 if (f && fclose(f) != 0 && err == NULL)
8341 err = got_error_from_errno("fclose");
8342 free(path);
8343 if (commit)
8344 got_object_commit_close(commit);
8345 return err;
8348 void
8349 histedit_free_list(struct got_histedit_list *histedit_cmds)
8351 struct got_histedit_list_entry *hle;
8353 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8354 TAILQ_REMOVE(histedit_cmds, hle, entry);
8355 free(hle);
8359 static const struct got_error *
8360 histedit_load_list(struct got_histedit_list *histedit_cmds,
8361 const char *path, struct got_repository *repo)
8363 const struct got_error *err = NULL;
8364 FILE *f = NULL;
8366 f = fopen(path, "r");
8367 if (f == NULL) {
8368 err = got_error_from_errno2("fopen", path);
8369 goto done;
8372 err = histedit_parse_list(histedit_cmds, f, repo);
8373 done:
8374 if (f && fclose(f) != 0 && err == NULL)
8375 err = got_error_from_errno("fclose");
8376 return err;
8379 static const struct got_error *
8380 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8381 const struct got_error *edit_err, struct got_object_id_queue *commits,
8382 const char *path, const char *branch_name, struct got_repository *repo)
8384 const struct got_error *err = NULL, *prev_err = edit_err;
8385 int resp = ' ';
8387 while (resp != 'c' && resp != 'r' && resp != 'a') {
8388 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8389 "or (a)bort: ", getprogname(), prev_err->msg);
8390 resp = getchar();
8391 if (resp == '\n')
8392 resp = getchar();
8393 if (resp == 'c') {
8394 histedit_free_list(histedit_cmds);
8395 err = histedit_run_editor(histedit_cmds, path, commits,
8396 repo);
8397 if (err) {
8398 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8399 err->code != GOT_ERR_HISTEDIT_CMD)
8400 break;
8401 prev_err = err;
8402 resp = ' ';
8403 continue;
8405 break;
8406 } else if (resp == 'r') {
8407 histedit_free_list(histedit_cmds);
8408 err = histedit_edit_script(histedit_cmds,
8409 commits, branch_name, 0, repo);
8410 if (err) {
8411 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8412 err->code != GOT_ERR_HISTEDIT_CMD)
8413 break;
8414 prev_err = err;
8415 resp = ' ';
8416 continue;
8418 break;
8419 } else if (resp == 'a') {
8420 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8421 break;
8422 } else
8423 printf("invalid response '%c'\n", resp);
8426 return err;
8429 static const struct got_error *
8430 histedit_complete(struct got_worktree *worktree,
8431 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8432 struct got_reference *branch, struct got_repository *repo)
8434 printf("Switching work tree to %s\n",
8435 got_ref_get_symref_target(branch));
8436 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8437 branch, repo);
8440 static const struct got_error *
8441 show_histedit_progress(struct got_commit_object *commit,
8442 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8444 const struct got_error *err;
8445 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8447 err = got_object_id_str(&old_id_str, hle->commit_id);
8448 if (err)
8449 goto done;
8451 if (new_id) {
8452 err = got_object_id_str(&new_id_str, new_id);
8453 if (err)
8454 goto done;
8457 old_id_str[12] = '\0';
8458 if (new_id_str)
8459 new_id_str[12] = '\0';
8461 if (hle->logmsg) {
8462 logmsg = strdup(hle->logmsg);
8463 if (logmsg == NULL) {
8464 err = got_error_from_errno("strdup");
8465 goto done;
8467 trim_logmsg(logmsg, 42);
8468 } else {
8469 err = get_short_logmsg(&logmsg, 42, commit);
8470 if (err)
8471 goto done;
8474 switch (hle->cmd->code) {
8475 case GOT_HISTEDIT_PICK:
8476 case GOT_HISTEDIT_EDIT:
8477 printf("%s -> %s: %s\n", old_id_str,
8478 new_id_str ? new_id_str : "no-op change", logmsg);
8479 break;
8480 case GOT_HISTEDIT_DROP:
8481 case GOT_HISTEDIT_FOLD:
8482 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8483 logmsg);
8484 break;
8485 default:
8486 break;
8488 done:
8489 free(old_id_str);
8490 free(new_id_str);
8491 return err;
8494 static const struct got_error *
8495 histedit_commit(struct got_pathlist_head *merged_paths,
8496 struct got_worktree *worktree, struct got_fileindex *fileindex,
8497 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8498 struct got_repository *repo)
8500 const struct got_error *err;
8501 struct got_commit_object *commit;
8502 struct got_object_id *new_commit_id;
8504 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8505 && hle->logmsg == NULL) {
8506 err = histedit_edit_logmsg(hle, repo);
8507 if (err)
8508 return err;
8511 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8512 if (err)
8513 return err;
8515 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8516 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8517 hle->logmsg, repo);
8518 if (err) {
8519 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8520 goto done;
8521 err = show_histedit_progress(commit, hle, NULL);
8522 } else {
8523 err = show_histedit_progress(commit, hle, new_commit_id);
8524 free(new_commit_id);
8526 done:
8527 got_object_commit_close(commit);
8528 return err;
8531 static const struct got_error *
8532 histedit_skip_commit(struct got_histedit_list_entry *hle,
8533 struct got_worktree *worktree, struct got_repository *repo)
8535 const struct got_error *error;
8536 struct got_commit_object *commit;
8538 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8539 repo);
8540 if (error)
8541 return error;
8543 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8544 if (error)
8545 return error;
8547 error = show_histedit_progress(commit, hle, NULL);
8548 got_object_commit_close(commit);
8549 return error;
8552 static const struct got_error *
8553 check_local_changes(void *arg, unsigned char status,
8554 unsigned char staged_status, const char *path,
8555 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8556 struct got_object_id *commit_id, int dirfd, const char *de_name)
8558 int *have_local_changes = arg;
8560 switch (status) {
8561 case GOT_STATUS_ADD:
8562 case GOT_STATUS_DELETE:
8563 case GOT_STATUS_MODIFY:
8564 case GOT_STATUS_CONFLICT:
8565 *have_local_changes = 1;
8566 return got_error(GOT_ERR_CANCELLED);
8567 default:
8568 break;
8571 switch (staged_status) {
8572 case GOT_STATUS_ADD:
8573 case GOT_STATUS_DELETE:
8574 case GOT_STATUS_MODIFY:
8575 *have_local_changes = 1;
8576 return got_error(GOT_ERR_CANCELLED);
8577 default:
8578 break;
8581 return NULL;
8584 static const struct got_error *
8585 cmd_histedit(int argc, char *argv[])
8587 const struct got_error *error = NULL;
8588 struct got_worktree *worktree = NULL;
8589 struct got_fileindex *fileindex = NULL;
8590 struct got_repository *repo = NULL;
8591 char *cwd = NULL;
8592 struct got_reference *branch = NULL;
8593 struct got_reference *tmp_branch = NULL;
8594 struct got_object_id *resume_commit_id = NULL;
8595 struct got_object_id *base_commit_id = NULL;
8596 struct got_object_id *head_commit_id = NULL;
8597 struct got_commit_object *commit = NULL;
8598 int ch, rebase_in_progress = 0;
8599 struct got_update_progress_arg upa;
8600 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8601 int edit_logmsg_only = 0;
8602 const char *edit_script_path = NULL;
8603 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8604 struct got_object_id_queue commits;
8605 struct got_pathlist_head merged_paths;
8606 const struct got_object_id_queue *parent_ids;
8607 struct got_object_qid *pid;
8608 struct got_histedit_list histedit_cmds;
8609 struct got_histedit_list_entry *hle;
8611 SIMPLEQ_INIT(&commits);
8612 TAILQ_INIT(&histedit_cmds);
8613 TAILQ_INIT(&merged_paths);
8614 memset(&upa, 0, sizeof(upa));
8616 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8617 switch (ch) {
8618 case 'a':
8619 abort_edit = 1;
8620 break;
8621 case 'c':
8622 continue_edit = 1;
8623 break;
8624 case 'F':
8625 edit_script_path = optarg;
8626 break;
8627 case 'm':
8628 edit_logmsg_only = 1;
8629 break;
8630 default:
8631 usage_histedit();
8632 /* NOTREACHED */
8636 argc -= optind;
8637 argv += optind;
8639 #ifndef PROFILE
8640 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8641 "unveil", NULL) == -1)
8642 err(1, "pledge");
8643 #endif
8644 if (abort_edit && continue_edit)
8645 errx(1, "histedit's -a and -c options are mutually exclusive");
8646 if (edit_script_path && edit_logmsg_only)
8647 errx(1, "histedit's -F and -m options are mutually exclusive");
8648 if (abort_edit && edit_logmsg_only)
8649 errx(1, "histedit's -a and -m options are mutually exclusive");
8650 if (continue_edit && edit_logmsg_only)
8651 errx(1, "histedit's -c and -m options are mutually exclusive");
8652 if (argc != 0)
8653 usage_histedit();
8656 * This command cannot apply unveil(2) in all cases because the
8657 * user may choose to run an editor to edit the histedit script
8658 * and to edit individual commit log messages.
8659 * unveil(2) traverses exec(2); if an editor is used we have to
8660 * apply unveil after edit script and log messages have been written.
8661 * XXX TODO: Make use of unveil(2) where possible.
8664 cwd = getcwd(NULL, 0);
8665 if (cwd == NULL) {
8666 error = got_error_from_errno("getcwd");
8667 goto done;
8669 error = got_worktree_open(&worktree, cwd);
8670 if (error) {
8671 if (error->code == GOT_ERR_NOT_WORKTREE)
8672 error = wrap_not_worktree_error(error, "histedit", cwd);
8673 goto done;
8676 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8677 NULL);
8678 if (error != NULL)
8679 goto done;
8681 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8682 if (error)
8683 goto done;
8684 if (rebase_in_progress) {
8685 error = got_error(GOT_ERR_REBASING);
8686 goto done;
8689 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8690 if (error)
8691 goto done;
8693 if (edit_in_progress && edit_logmsg_only) {
8694 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8695 "histedit operation is in progress in this "
8696 "work tree and must be continued or aborted "
8697 "before the -m option can be used");
8698 goto done;
8701 if (edit_in_progress && abort_edit) {
8702 error = got_worktree_histedit_continue(&resume_commit_id,
8703 &tmp_branch, &branch, &base_commit_id, &fileindex,
8704 worktree, repo);
8705 if (error)
8706 goto done;
8707 printf("Switching work tree to %s\n",
8708 got_ref_get_symref_target(branch));
8709 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8710 branch, base_commit_id, update_progress, &upa);
8711 if (error)
8712 goto done;
8713 printf("Histedit of %s aborted\n",
8714 got_ref_get_symref_target(branch));
8715 print_update_progress_stats(&upa);
8716 goto done; /* nothing else to do */
8717 } else if (abort_edit) {
8718 error = got_error(GOT_ERR_NOT_HISTEDIT);
8719 goto done;
8722 if (continue_edit) {
8723 char *path;
8725 if (!edit_in_progress) {
8726 error = got_error(GOT_ERR_NOT_HISTEDIT);
8727 goto done;
8730 error = got_worktree_get_histedit_script_path(&path, worktree);
8731 if (error)
8732 goto done;
8734 error = histedit_load_list(&histedit_cmds, path, repo);
8735 free(path);
8736 if (error)
8737 goto done;
8739 error = got_worktree_histedit_continue(&resume_commit_id,
8740 &tmp_branch, &branch, &base_commit_id, &fileindex,
8741 worktree, repo);
8742 if (error)
8743 goto done;
8745 error = got_ref_resolve(&head_commit_id, repo, branch);
8746 if (error)
8747 goto done;
8749 error = got_object_open_as_commit(&commit, repo,
8750 head_commit_id);
8751 if (error)
8752 goto done;
8753 parent_ids = got_object_commit_get_parent_ids(commit);
8754 pid = SIMPLEQ_FIRST(parent_ids);
8755 if (pid == NULL) {
8756 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8757 goto done;
8759 error = collect_commits(&commits, head_commit_id, pid->id,
8760 base_commit_id, got_worktree_get_path_prefix(worktree),
8761 GOT_ERR_HISTEDIT_PATH, repo);
8762 got_object_commit_close(commit);
8763 commit = NULL;
8764 if (error)
8765 goto done;
8766 } else {
8767 if (edit_in_progress) {
8768 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8769 goto done;
8772 error = got_ref_open(&branch, repo,
8773 got_worktree_get_head_ref_name(worktree), 0);
8774 if (error != NULL)
8775 goto done;
8777 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8778 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8779 "will not edit commit history of a branch outside "
8780 "the \"refs/heads/\" reference namespace");
8781 goto done;
8784 error = got_ref_resolve(&head_commit_id, repo, branch);
8785 got_ref_close(branch);
8786 branch = NULL;
8787 if (error)
8788 goto done;
8790 error = got_object_open_as_commit(&commit, repo,
8791 head_commit_id);
8792 if (error)
8793 goto done;
8794 parent_ids = got_object_commit_get_parent_ids(commit);
8795 pid = SIMPLEQ_FIRST(parent_ids);
8796 if (pid == NULL) {
8797 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8798 goto done;
8800 error = collect_commits(&commits, head_commit_id, pid->id,
8801 got_worktree_get_base_commit_id(worktree),
8802 got_worktree_get_path_prefix(worktree),
8803 GOT_ERR_HISTEDIT_PATH, repo);
8804 got_object_commit_close(commit);
8805 commit = NULL;
8806 if (error)
8807 goto done;
8809 if (SIMPLEQ_EMPTY(&commits)) {
8810 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8811 goto done;
8814 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8815 &base_commit_id, &fileindex, worktree, repo);
8816 if (error)
8817 goto done;
8819 if (edit_script_path) {
8820 error = histedit_load_list(&histedit_cmds,
8821 edit_script_path, repo);
8822 if (error) {
8823 got_worktree_histedit_abort(worktree, fileindex,
8824 repo, branch, base_commit_id,
8825 update_progress, &upa);
8826 print_update_progress_stats(&upa);
8827 goto done;
8829 } else {
8830 const char *branch_name;
8831 branch_name = got_ref_get_symref_target(branch);
8832 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8833 branch_name += 11;
8834 error = histedit_edit_script(&histedit_cmds, &commits,
8835 branch_name, edit_logmsg_only, repo);
8836 if (error) {
8837 got_worktree_histedit_abort(worktree, fileindex,
8838 repo, branch, base_commit_id,
8839 update_progress, &upa);
8840 print_update_progress_stats(&upa);
8841 goto done;
8846 error = histedit_save_list(&histedit_cmds, worktree,
8847 repo);
8848 if (error) {
8849 got_worktree_histedit_abort(worktree, fileindex,
8850 repo, branch, base_commit_id,
8851 update_progress, &upa);
8852 print_update_progress_stats(&upa);
8853 goto done;
8858 error = histedit_check_script(&histedit_cmds, &commits, repo);
8859 if (error)
8860 goto done;
8862 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8863 if (resume_commit_id) {
8864 if (got_object_id_cmp(hle->commit_id,
8865 resume_commit_id) != 0)
8866 continue;
8868 resume_commit_id = NULL;
8869 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8870 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8871 error = histedit_skip_commit(hle, worktree,
8872 repo);
8873 if (error)
8874 goto done;
8875 } else {
8876 struct got_pathlist_head paths;
8877 int have_changes = 0;
8879 TAILQ_INIT(&paths);
8880 error = got_pathlist_append(&paths, "", NULL);
8881 if (error)
8882 goto done;
8883 error = got_worktree_status(worktree, &paths,
8884 repo, check_local_changes, &have_changes,
8885 check_cancelled, NULL);
8886 got_pathlist_free(&paths);
8887 if (error) {
8888 if (error->code != GOT_ERR_CANCELLED)
8889 goto done;
8890 if (sigint_received || sigpipe_received)
8891 goto done;
8893 if (have_changes) {
8894 error = histedit_commit(NULL, worktree,
8895 fileindex, tmp_branch, hle, repo);
8896 if (error)
8897 goto done;
8898 } else {
8899 error = got_object_open_as_commit(
8900 &commit, repo, hle->commit_id);
8901 if (error)
8902 goto done;
8903 error = show_histedit_progress(commit,
8904 hle, NULL);
8905 got_object_commit_close(commit);
8906 commit = NULL;
8907 if (error)
8908 goto done;
8911 continue;
8914 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8915 error = histedit_skip_commit(hle, worktree, repo);
8916 if (error)
8917 goto done;
8918 continue;
8921 error = got_object_open_as_commit(&commit, repo,
8922 hle->commit_id);
8923 if (error)
8924 goto done;
8925 parent_ids = got_object_commit_get_parent_ids(commit);
8926 pid = SIMPLEQ_FIRST(parent_ids);
8928 error = got_worktree_histedit_merge_files(&merged_paths,
8929 worktree, fileindex, pid->id, hle->commit_id, repo,
8930 update_progress, &upa, check_cancelled, NULL);
8931 if (error)
8932 goto done;
8933 got_object_commit_close(commit);
8934 commit = NULL;
8936 print_update_progress_stats(&upa);
8937 if (upa.conflicts > 0)
8938 rebase_status = GOT_STATUS_CONFLICT;
8940 if (rebase_status == GOT_STATUS_CONFLICT) {
8941 error = show_rebase_merge_conflict(hle->commit_id,
8942 repo);
8943 if (error)
8944 goto done;
8945 got_worktree_rebase_pathlist_free(&merged_paths);
8946 break;
8949 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8950 char *id_str;
8951 error = got_object_id_str(&id_str, hle->commit_id);
8952 if (error)
8953 goto done;
8954 printf("Stopping histedit for amending commit %s\n",
8955 id_str);
8956 free(id_str);
8957 got_worktree_rebase_pathlist_free(&merged_paths);
8958 error = got_worktree_histedit_postpone(worktree,
8959 fileindex);
8960 goto done;
8963 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8964 error = histedit_skip_commit(hle, worktree, repo);
8965 if (error)
8966 goto done;
8967 continue;
8970 error = histedit_commit(&merged_paths, worktree, fileindex,
8971 tmp_branch, hle, repo);
8972 got_worktree_rebase_pathlist_free(&merged_paths);
8973 if (error)
8974 goto done;
8977 if (rebase_status == GOT_STATUS_CONFLICT) {
8978 error = got_worktree_histedit_postpone(worktree, fileindex);
8979 if (error)
8980 goto done;
8981 error = got_error_msg(GOT_ERR_CONFLICTS,
8982 "conflicts must be resolved before histedit can continue");
8983 } else
8984 error = histedit_complete(worktree, fileindex, tmp_branch,
8985 branch, repo);
8986 done:
8987 got_object_id_queue_free(&commits);
8988 histedit_free_list(&histedit_cmds);
8989 free(head_commit_id);
8990 free(base_commit_id);
8991 free(resume_commit_id);
8992 if (commit)
8993 got_object_commit_close(commit);
8994 if (branch)
8995 got_ref_close(branch);
8996 if (tmp_branch)
8997 got_ref_close(tmp_branch);
8998 if (worktree)
8999 got_worktree_close(worktree);
9000 if (repo)
9001 got_repo_close(repo);
9002 return error;
9005 __dead static void
9006 usage_integrate(void)
9008 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9009 exit(1);
9012 static const struct got_error *
9013 cmd_integrate(int argc, char *argv[])
9015 const struct got_error *error = NULL;
9016 struct got_repository *repo = NULL;
9017 struct got_worktree *worktree = NULL;
9018 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9019 const char *branch_arg = NULL;
9020 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9021 struct got_fileindex *fileindex = NULL;
9022 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9023 int ch;
9024 struct got_update_progress_arg upa;
9026 while ((ch = getopt(argc, argv, "")) != -1) {
9027 switch (ch) {
9028 default:
9029 usage_integrate();
9030 /* NOTREACHED */
9034 argc -= optind;
9035 argv += optind;
9037 if (argc != 1)
9038 usage_integrate();
9039 branch_arg = argv[0];
9040 #ifndef PROFILE
9041 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9042 "unveil", NULL) == -1)
9043 err(1, "pledge");
9044 #endif
9045 cwd = getcwd(NULL, 0);
9046 if (cwd == NULL) {
9047 error = got_error_from_errno("getcwd");
9048 goto done;
9051 error = got_worktree_open(&worktree, cwd);
9052 if (error) {
9053 if (error->code == GOT_ERR_NOT_WORKTREE)
9054 error = wrap_not_worktree_error(error, "integrate",
9055 cwd);
9056 goto done;
9059 error = check_rebase_or_histedit_in_progress(worktree);
9060 if (error)
9061 goto done;
9063 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9064 NULL);
9065 if (error != NULL)
9066 goto done;
9068 error = apply_unveil(got_repo_get_path(repo), 0,
9069 got_worktree_get_root_path(worktree));
9070 if (error)
9071 goto done;
9073 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9074 error = got_error_from_errno("asprintf");
9075 goto done;
9078 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9079 &base_branch_ref, worktree, refname, repo);
9080 if (error)
9081 goto done;
9083 refname = strdup(got_ref_get_name(branch_ref));
9084 if (refname == NULL) {
9085 error = got_error_from_errno("strdup");
9086 got_worktree_integrate_abort(worktree, fileindex, repo,
9087 branch_ref, base_branch_ref);
9088 goto done;
9090 base_refname = strdup(got_ref_get_name(base_branch_ref));
9091 if (base_refname == NULL) {
9092 error = got_error_from_errno("strdup");
9093 got_worktree_integrate_abort(worktree, fileindex, repo,
9094 branch_ref, base_branch_ref);
9095 goto done;
9098 error = got_ref_resolve(&commit_id, repo, branch_ref);
9099 if (error)
9100 goto done;
9102 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9103 if (error)
9104 goto done;
9106 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9107 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9108 "specified branch has already been integrated");
9109 got_worktree_integrate_abort(worktree, fileindex, repo,
9110 branch_ref, base_branch_ref);
9111 goto done;
9114 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9115 if (error) {
9116 if (error->code == GOT_ERR_ANCESTRY)
9117 error = got_error(GOT_ERR_REBASE_REQUIRED);
9118 got_worktree_integrate_abort(worktree, fileindex, repo,
9119 branch_ref, base_branch_ref);
9120 goto done;
9123 memset(&upa, 0, sizeof(upa));
9124 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9125 branch_ref, base_branch_ref, update_progress, &upa,
9126 check_cancelled, NULL);
9127 if (error)
9128 goto done;
9130 printf("Integrated %s into %s\n", refname, base_refname);
9131 print_update_progress_stats(&upa);
9132 done:
9133 if (repo)
9134 got_repo_close(repo);
9135 if (worktree)
9136 got_worktree_close(worktree);
9137 free(cwd);
9138 free(base_commit_id);
9139 free(commit_id);
9140 free(refname);
9141 free(base_refname);
9142 return error;
9145 __dead static void
9146 usage_stage(void)
9148 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9149 "[-S] [file-path ...]\n",
9150 getprogname());
9151 exit(1);
9154 static const struct got_error *
9155 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9156 const char *path, struct got_object_id *blob_id,
9157 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9158 int dirfd, const char *de_name)
9160 const struct got_error *err = NULL;
9161 char *id_str = NULL;
9163 if (staged_status != GOT_STATUS_ADD &&
9164 staged_status != GOT_STATUS_MODIFY &&
9165 staged_status != GOT_STATUS_DELETE)
9166 return NULL;
9168 if (staged_status == GOT_STATUS_ADD ||
9169 staged_status == GOT_STATUS_MODIFY)
9170 err = got_object_id_str(&id_str, staged_blob_id);
9171 else
9172 err = got_object_id_str(&id_str, blob_id);
9173 if (err)
9174 return err;
9176 printf("%s %c %s\n", id_str, staged_status, path);
9177 free(id_str);
9178 return NULL;
9181 static const struct got_error *
9182 cmd_stage(int argc, char *argv[])
9184 const struct got_error *error = NULL;
9185 struct got_repository *repo = NULL;
9186 struct got_worktree *worktree = NULL;
9187 char *cwd = NULL;
9188 struct got_pathlist_head paths;
9189 struct got_pathlist_entry *pe;
9190 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9191 FILE *patch_script_file = NULL;
9192 const char *patch_script_path = NULL;
9193 struct choose_patch_arg cpa;
9195 TAILQ_INIT(&paths);
9197 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9198 switch (ch) {
9199 case 'l':
9200 list_stage = 1;
9201 break;
9202 case 'p':
9203 pflag = 1;
9204 break;
9205 case 'F':
9206 patch_script_path = optarg;
9207 break;
9208 case 'S':
9209 allow_bad_symlinks = 1;
9210 break;
9211 default:
9212 usage_stage();
9213 /* NOTREACHED */
9217 argc -= optind;
9218 argv += optind;
9220 #ifndef PROFILE
9221 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9222 "unveil", NULL) == -1)
9223 err(1, "pledge");
9224 #endif
9225 if (list_stage && (pflag || patch_script_path))
9226 errx(1, "-l option cannot be used with other options");
9227 if (patch_script_path && !pflag)
9228 errx(1, "-F option can only be used together with -p option");
9230 cwd = getcwd(NULL, 0);
9231 if (cwd == NULL) {
9232 error = got_error_from_errno("getcwd");
9233 goto done;
9236 error = got_worktree_open(&worktree, cwd);
9237 if (error) {
9238 if (error->code == GOT_ERR_NOT_WORKTREE)
9239 error = wrap_not_worktree_error(error, "stage", cwd);
9240 goto done;
9243 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9244 NULL);
9245 if (error != NULL)
9246 goto done;
9248 if (patch_script_path) {
9249 patch_script_file = fopen(patch_script_path, "r");
9250 if (patch_script_file == NULL) {
9251 error = got_error_from_errno2("fopen",
9252 patch_script_path);
9253 goto done;
9256 error = apply_unveil(got_repo_get_path(repo), 0,
9257 got_worktree_get_root_path(worktree));
9258 if (error)
9259 goto done;
9261 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9262 if (error)
9263 goto done;
9265 if (list_stage)
9266 error = got_worktree_status(worktree, &paths, repo,
9267 print_stage, NULL, check_cancelled, NULL);
9268 else {
9269 cpa.patch_script_file = patch_script_file;
9270 cpa.action = "stage";
9271 error = got_worktree_stage(worktree, &paths,
9272 pflag ? NULL : print_status, NULL,
9273 pflag ? choose_patch : NULL, &cpa,
9274 allow_bad_symlinks, repo);
9276 done:
9277 if (patch_script_file && fclose(patch_script_file) == EOF &&
9278 error == NULL)
9279 error = got_error_from_errno2("fclose", patch_script_path);
9280 if (repo)
9281 got_repo_close(repo);
9282 if (worktree)
9283 got_worktree_close(worktree);
9284 TAILQ_FOREACH(pe, &paths, entry)
9285 free((char *)pe->path);
9286 got_pathlist_free(&paths);
9287 free(cwd);
9288 return error;
9291 __dead static void
9292 usage_unstage(void)
9294 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9295 "[file-path ...]\n",
9296 getprogname());
9297 exit(1);
9301 static const struct got_error *
9302 cmd_unstage(int argc, char *argv[])
9304 const struct got_error *error = NULL;
9305 struct got_repository *repo = NULL;
9306 struct got_worktree *worktree = NULL;
9307 char *cwd = NULL;
9308 struct got_pathlist_head paths;
9309 struct got_pathlist_entry *pe;
9310 int ch, pflag = 0;
9311 struct got_update_progress_arg upa;
9312 FILE *patch_script_file = NULL;
9313 const char *patch_script_path = NULL;
9314 struct choose_patch_arg cpa;
9316 TAILQ_INIT(&paths);
9318 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9319 switch (ch) {
9320 case 'p':
9321 pflag = 1;
9322 break;
9323 case 'F':
9324 patch_script_path = optarg;
9325 break;
9326 default:
9327 usage_unstage();
9328 /* NOTREACHED */
9332 argc -= optind;
9333 argv += optind;
9335 #ifndef PROFILE
9336 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9337 "unveil", NULL) == -1)
9338 err(1, "pledge");
9339 #endif
9340 if (patch_script_path && !pflag)
9341 errx(1, "-F option can only be used together with -p option");
9343 cwd = getcwd(NULL, 0);
9344 if (cwd == NULL) {
9345 error = got_error_from_errno("getcwd");
9346 goto done;
9349 error = got_worktree_open(&worktree, cwd);
9350 if (error) {
9351 if (error->code == GOT_ERR_NOT_WORKTREE)
9352 error = wrap_not_worktree_error(error, "unstage", cwd);
9353 goto done;
9356 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9357 NULL);
9358 if (error != NULL)
9359 goto done;
9361 if (patch_script_path) {
9362 patch_script_file = fopen(patch_script_path, "r");
9363 if (patch_script_file == NULL) {
9364 error = got_error_from_errno2("fopen",
9365 patch_script_path);
9366 goto done;
9370 error = apply_unveil(got_repo_get_path(repo), 0,
9371 got_worktree_get_root_path(worktree));
9372 if (error)
9373 goto done;
9375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9376 if (error)
9377 goto done;
9379 cpa.patch_script_file = patch_script_file;
9380 cpa.action = "unstage";
9381 memset(&upa, 0, sizeof(upa));
9382 error = got_worktree_unstage(worktree, &paths, update_progress,
9383 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9384 if (!error)
9385 print_update_progress_stats(&upa);
9386 done:
9387 if (patch_script_file && fclose(patch_script_file) == EOF &&
9388 error == NULL)
9389 error = got_error_from_errno2("fclose", patch_script_path);
9390 if (repo)
9391 got_repo_close(repo);
9392 if (worktree)
9393 got_worktree_close(worktree);
9394 TAILQ_FOREACH(pe, &paths, entry)
9395 free((char *)pe->path);
9396 got_pathlist_free(&paths);
9397 free(cwd);
9398 return error;
9401 __dead static void
9402 usage_cat(void)
9404 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9405 "arg1 [arg2 ...]\n", getprogname());
9406 exit(1);
9409 static const struct got_error *
9410 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9412 const struct got_error *err;
9413 struct got_blob_object *blob;
9415 err = got_object_open_as_blob(&blob, repo, id, 8192);
9416 if (err)
9417 return err;
9419 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9420 got_object_blob_close(blob);
9421 return err;
9424 static const struct got_error *
9425 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9427 const struct got_error *err;
9428 struct got_tree_object *tree;
9429 int nentries, i;
9431 err = got_object_open_as_tree(&tree, repo, id);
9432 if (err)
9433 return err;
9435 nentries = got_object_tree_get_nentries(tree);
9436 for (i = 0; i < nentries; i++) {
9437 struct got_tree_entry *te;
9438 char *id_str;
9439 if (sigint_received || sigpipe_received)
9440 break;
9441 te = got_object_tree_get_entry(tree, i);
9442 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9443 if (err)
9444 break;
9445 fprintf(outfile, "%s %.7o %s\n", id_str,
9446 got_tree_entry_get_mode(te),
9447 got_tree_entry_get_name(te));
9448 free(id_str);
9451 got_object_tree_close(tree);
9452 return err;
9455 static const struct got_error *
9456 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9458 const struct got_error *err;
9459 struct got_commit_object *commit;
9460 const struct got_object_id_queue *parent_ids;
9461 struct got_object_qid *pid;
9462 char *id_str = NULL;
9463 const char *logmsg = NULL;
9465 err = got_object_open_as_commit(&commit, repo, id);
9466 if (err)
9467 return err;
9469 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9470 if (err)
9471 goto done;
9473 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9474 parent_ids = got_object_commit_get_parent_ids(commit);
9475 fprintf(outfile, "numparents %d\n",
9476 got_object_commit_get_nparents(commit));
9477 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9478 char *pid_str;
9479 err = got_object_id_str(&pid_str, pid->id);
9480 if (err)
9481 goto done;
9482 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9483 free(pid_str);
9485 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9486 got_object_commit_get_author(commit),
9487 (long long)got_object_commit_get_author_time(commit));
9489 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9490 got_object_commit_get_author(commit),
9491 (long long)got_object_commit_get_committer_time(commit));
9493 logmsg = got_object_commit_get_logmsg_raw(commit);
9494 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9495 fprintf(outfile, "%s", logmsg);
9496 done:
9497 free(id_str);
9498 got_object_commit_close(commit);
9499 return err;
9502 static const struct got_error *
9503 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9505 const struct got_error *err;
9506 struct got_tag_object *tag;
9507 char *id_str = NULL;
9508 const char *tagmsg = NULL;
9510 err = got_object_open_as_tag(&tag, repo, id);
9511 if (err)
9512 return err;
9514 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9515 if (err)
9516 goto done;
9518 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9520 switch (got_object_tag_get_object_type(tag)) {
9521 case GOT_OBJ_TYPE_BLOB:
9522 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9523 GOT_OBJ_LABEL_BLOB);
9524 break;
9525 case GOT_OBJ_TYPE_TREE:
9526 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9527 GOT_OBJ_LABEL_TREE);
9528 break;
9529 case GOT_OBJ_TYPE_COMMIT:
9530 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9531 GOT_OBJ_LABEL_COMMIT);
9532 break;
9533 case GOT_OBJ_TYPE_TAG:
9534 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9535 GOT_OBJ_LABEL_TAG);
9536 break;
9537 default:
9538 break;
9541 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9542 got_object_tag_get_name(tag));
9544 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9545 got_object_tag_get_tagger(tag),
9546 (long long)got_object_tag_get_tagger_time(tag));
9548 tagmsg = got_object_tag_get_message(tag);
9549 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9550 fprintf(outfile, "%s", tagmsg);
9551 done:
9552 free(id_str);
9553 got_object_tag_close(tag);
9554 return err;
9557 static const struct got_error *
9558 cmd_cat(int argc, char *argv[])
9560 const struct got_error *error;
9561 struct got_repository *repo = NULL;
9562 struct got_worktree *worktree = NULL;
9563 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9564 const char *commit_id_str = NULL;
9565 struct got_object_id *id = NULL, *commit_id = NULL;
9566 int ch, obj_type, i, force_path = 0;
9568 #ifndef PROFILE
9569 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9570 NULL) == -1)
9571 err(1, "pledge");
9572 #endif
9574 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9575 switch (ch) {
9576 case 'c':
9577 commit_id_str = optarg;
9578 break;
9579 case 'r':
9580 repo_path = realpath(optarg, NULL);
9581 if (repo_path == NULL)
9582 return got_error_from_errno2("realpath",
9583 optarg);
9584 got_path_strip_trailing_slashes(repo_path);
9585 break;
9586 case 'P':
9587 force_path = 1;
9588 break;
9589 default:
9590 usage_cat();
9591 /* NOTREACHED */
9595 argc -= optind;
9596 argv += optind;
9598 cwd = getcwd(NULL, 0);
9599 if (cwd == NULL) {
9600 error = got_error_from_errno("getcwd");
9601 goto done;
9603 error = got_worktree_open(&worktree, cwd);
9604 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9605 goto done;
9606 if (worktree) {
9607 if (repo_path == NULL) {
9608 repo_path = strdup(
9609 got_worktree_get_repo_path(worktree));
9610 if (repo_path == NULL) {
9611 error = got_error_from_errno("strdup");
9612 goto done;
9617 if (repo_path == NULL) {
9618 repo_path = getcwd(NULL, 0);
9619 if (repo_path == NULL)
9620 return got_error_from_errno("getcwd");
9623 error = got_repo_open(&repo, repo_path, NULL);
9624 free(repo_path);
9625 if (error != NULL)
9626 goto done;
9628 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9629 if (error)
9630 goto done;
9632 if (commit_id_str == NULL)
9633 commit_id_str = GOT_REF_HEAD;
9634 error = got_repo_match_object_id(&commit_id, NULL,
9635 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9636 if (error)
9637 goto done;
9639 for (i = 0; i < argc; i++) {
9640 if (force_path) {
9641 error = got_object_id_by_path(&id, repo, commit_id,
9642 argv[i]);
9643 if (error)
9644 break;
9645 } else {
9646 error = got_repo_match_object_id(&id, &label, argv[i],
9647 GOT_OBJ_TYPE_ANY, 0, repo);
9648 if (error) {
9649 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9650 error->code != GOT_ERR_NOT_REF)
9651 break;
9652 error = got_object_id_by_path(&id, repo,
9653 commit_id, argv[i]);
9654 if (error)
9655 break;
9659 error = got_object_get_type(&obj_type, repo, id);
9660 if (error)
9661 break;
9663 switch (obj_type) {
9664 case GOT_OBJ_TYPE_BLOB:
9665 error = cat_blob(id, repo, stdout);
9666 break;
9667 case GOT_OBJ_TYPE_TREE:
9668 error = cat_tree(id, repo, stdout);
9669 break;
9670 case GOT_OBJ_TYPE_COMMIT:
9671 error = cat_commit(id, repo, stdout);
9672 break;
9673 case GOT_OBJ_TYPE_TAG:
9674 error = cat_tag(id, repo, stdout);
9675 break;
9676 default:
9677 error = got_error(GOT_ERR_OBJ_TYPE);
9678 break;
9680 if (error)
9681 break;
9682 free(label);
9683 label = NULL;
9684 free(id);
9685 id = NULL;
9687 done:
9688 free(label);
9689 free(id);
9690 free(commit_id);
9691 if (worktree)
9692 got_worktree_close(worktree);
9693 if (repo) {
9694 const struct got_error *repo_error;
9695 repo_error = got_repo_close(repo);
9696 if (error == NULL)
9697 error = repo_error;
9699 return error;
9702 __dead static void
9703 usage_info(void)
9705 fprintf(stderr, "usage: %s info [path ...]\n",
9706 getprogname());
9707 exit(1);
9710 static const struct got_error *
9711 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9712 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9713 struct got_object_id *commit_id)
9715 const struct got_error *err = NULL;
9716 char *id_str = NULL;
9717 char datebuf[128];
9718 struct tm mytm, *tm;
9719 struct got_pathlist_head *paths = arg;
9720 struct got_pathlist_entry *pe;
9723 * Clear error indication from any of the path arguments which
9724 * would cause this file index entry to be displayed.
9726 TAILQ_FOREACH(pe, paths, entry) {
9727 if (got_path_cmp(path, pe->path, strlen(path),
9728 pe->path_len) == 0 ||
9729 got_path_is_child(path, pe->path, pe->path_len))
9730 pe->data = NULL; /* no error */
9733 printf(GOT_COMMIT_SEP_STR);
9734 if (S_ISLNK(mode))
9735 printf("symlink: %s\n", path);
9736 else if (S_ISREG(mode)) {
9737 printf("file: %s\n", path);
9738 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9739 } else if (S_ISDIR(mode))
9740 printf("directory: %s\n", path);
9741 else
9742 printf("something: %s\n", path);
9744 tm = localtime_r(&mtime, &mytm);
9745 if (tm == NULL)
9746 return NULL;
9747 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9748 return got_error(GOT_ERR_NO_SPACE);
9749 printf("timestamp: %s\n", datebuf);
9751 if (blob_id) {
9752 err = got_object_id_str(&id_str, blob_id);
9753 if (err)
9754 return err;
9755 printf("based on blob: %s\n", id_str);
9756 free(id_str);
9759 if (staged_blob_id) {
9760 err = got_object_id_str(&id_str, staged_blob_id);
9761 if (err)
9762 return err;
9763 printf("based on staged blob: %s\n", id_str);
9764 free(id_str);
9767 if (commit_id) {
9768 err = got_object_id_str(&id_str, commit_id);
9769 if (err)
9770 return err;
9771 printf("based on commit: %s\n", id_str);
9772 free(id_str);
9775 return NULL;
9778 static const struct got_error *
9779 cmd_info(int argc, char *argv[])
9781 const struct got_error *error = NULL;
9782 struct got_worktree *worktree = NULL;
9783 char *cwd = NULL, *id_str = NULL;
9784 struct got_pathlist_head paths;
9785 struct got_pathlist_entry *pe;
9786 char *uuidstr = NULL;
9787 int ch, show_files = 0;
9789 TAILQ_INIT(&paths);
9791 while ((ch = getopt(argc, argv, "")) != -1) {
9792 switch (ch) {
9793 default:
9794 usage_info();
9795 /* NOTREACHED */
9799 argc -= optind;
9800 argv += optind;
9802 #ifndef PROFILE
9803 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9804 NULL) == -1)
9805 err(1, "pledge");
9806 #endif
9807 cwd = getcwd(NULL, 0);
9808 if (cwd == NULL) {
9809 error = got_error_from_errno("getcwd");
9810 goto done;
9813 error = got_worktree_open(&worktree, cwd);
9814 if (error) {
9815 if (error->code == GOT_ERR_NOT_WORKTREE)
9816 error = wrap_not_worktree_error(error, "status", cwd);
9817 goto done;
9820 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9821 if (error)
9822 goto done;
9824 if (argc >= 1) {
9825 error = get_worktree_paths_from_argv(&paths, argc, argv,
9826 worktree);
9827 if (error)
9828 goto done;
9829 show_files = 1;
9832 error = got_object_id_str(&id_str,
9833 got_worktree_get_base_commit_id(worktree));
9834 if (error)
9835 goto done;
9837 error = got_worktree_get_uuid(&uuidstr, worktree);
9838 if (error)
9839 goto done;
9841 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9842 printf("work tree base commit: %s\n", id_str);
9843 printf("work tree path prefix: %s\n",
9844 got_worktree_get_path_prefix(worktree));
9845 printf("work tree branch reference: %s\n",
9846 got_worktree_get_head_ref_name(worktree));
9847 printf("work tree UUID: %s\n", uuidstr);
9848 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9850 if (show_files) {
9851 struct got_pathlist_entry *pe;
9852 TAILQ_FOREACH(pe, &paths, entry) {
9853 if (pe->path_len == 0)
9854 continue;
9856 * Assume this path will fail. This will be corrected
9857 * in print_path_info() in case the path does suceeed.
9859 pe->data = (void *)got_error_path(pe->path,
9860 GOT_ERR_BAD_PATH);
9862 error = got_worktree_path_info(worktree, &paths,
9863 print_path_info, &paths, check_cancelled, NULL);
9864 if (error)
9865 goto done;
9866 TAILQ_FOREACH(pe, &paths, entry) {
9867 if (pe->data != NULL) {
9868 error = pe->data; /* bad path */
9869 break;
9873 done:
9874 TAILQ_FOREACH(pe, &paths, entry)
9875 free((char *)pe->path);
9876 got_pathlist_free(&paths);
9877 free(cwd);
9878 free(id_str);
9879 free(uuidstr);
9880 return error;