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 if (strcmp(remotes[i].name, remote_name) == 0) {
2123 remote = &remotes[i];
2124 break;
2129 if (remote == NULL) {
2130 repo_conf = got_repo_get_gotconfig(repo);
2131 if (repo_conf) {
2132 got_gotconfig_get_remotes(&nremotes, &remotes,
2133 repo_conf);
2134 for (i = 0; i < nremotes; i++) {
2135 if (strcmp(remotes[i].name, remote_name) == 0) {
2136 remote = &remotes[i];
2137 break;
2142 if (remote == NULL) {
2143 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2144 for (i = 0; i < nremotes; i++) {
2145 if (strcmp(remotes[i].name, remote_name) == 0) {
2146 remote = &remotes[i];
2147 break;
2151 if (remote == NULL) {
2152 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2153 goto done;
2156 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2157 for (i = 0; i < remote->nbranches; i++) {
2158 got_pathlist_append(&wanted_branches,
2159 remote->branches[i], NULL);
2164 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2165 &repo_name, remote->url);
2166 if (error)
2167 goto done;
2169 if (strcmp(proto, "git") == 0) {
2170 #ifndef PROFILE
2171 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2172 "sendfd dns inet unveil", NULL) == -1)
2173 err(1, "pledge");
2174 #endif
2175 } else if (strcmp(proto, "git+ssh") == 0 ||
2176 strcmp(proto, "ssh") == 0) {
2177 #ifndef PROFILE
2178 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2179 "sendfd unveil", NULL) == -1)
2180 err(1, "pledge");
2181 #endif
2182 } else if (strcmp(proto, "http") == 0 ||
2183 strcmp(proto, "git+http") == 0) {
2184 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2185 goto done;
2186 } else {
2187 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2188 goto done;
2191 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2192 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2193 error = got_error_from_errno2("unveil",
2194 GOT_FETCH_PATH_SSH);
2195 goto done;
2198 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2199 if (error)
2200 goto done;
2202 if (verbosity >= 0)
2203 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2204 port ? ":" : "", port ? port : "");
2206 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2207 server_path, verbosity);
2208 if (error)
2209 goto done;
2211 fpa.last_scaled_size[0] = '\0';
2212 fpa.last_p_indexed = -1;
2213 fpa.last_p_resolved = -1;
2214 fpa.verbosity = verbosity;
2215 fpa.repo = repo;
2216 fpa.create_configs = 0;
2217 fpa.configs_created = 0;
2218 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2219 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2220 remote->mirror_references, fetch_all_branches, &wanted_branches,
2221 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2222 fetch_progress, &fpa);
2223 if (error)
2224 goto done;
2226 if (list_refs_only) {
2227 error = list_remote_refs(&symrefs, &refs);
2228 goto done;
2231 if (pack_hash == NULL) {
2232 if (verbosity >= 0)
2233 printf("Already up-to-date\n");
2234 } else if (verbosity >= 0) {
2235 error = got_object_id_str(&id_str, pack_hash);
2236 if (error)
2237 goto done;
2238 printf("\nFetched %s.pack\n", id_str);
2239 free(id_str);
2240 id_str = NULL;
2243 /* Update references provided with the pack file. */
2244 TAILQ_FOREACH(pe, &refs, entry) {
2245 const char *refname = pe->path;
2246 struct got_object_id *id = pe->data;
2247 struct got_reference *ref;
2248 char *remote_refname;
2250 if (is_wanted_ref(&wanted_refs, refname) &&
2251 !remote->mirror_references) {
2252 error = update_wanted_ref(refname, id,
2253 remote->name, verbosity, repo);
2254 if (error)
2255 goto done;
2256 continue;
2259 if (remote->mirror_references ||
2260 strncmp("refs/tags/", refname, 10) == 0) {
2261 error = got_ref_open(&ref, repo, refname, 1);
2262 if (error) {
2263 if (error->code != GOT_ERR_NOT_REF)
2264 goto done;
2265 error = create_ref(refname, id, verbosity,
2266 repo);
2267 if (error)
2268 goto done;
2269 } else {
2270 error = update_ref(ref, id, replace_tags,
2271 verbosity, repo);
2272 unlock_err = got_ref_unlock(ref);
2273 if (unlock_err && error == NULL)
2274 error = unlock_err;
2275 got_ref_close(ref);
2276 if (error)
2277 goto done;
2279 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2280 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2281 remote_name, refname + 11) == -1) {
2282 error = got_error_from_errno("asprintf");
2283 goto done;
2286 error = got_ref_open(&ref, repo, remote_refname, 1);
2287 if (error) {
2288 if (error->code != GOT_ERR_NOT_REF)
2289 goto done;
2290 error = create_ref(remote_refname, id,
2291 verbosity, repo);
2292 if (error)
2293 goto done;
2294 } else {
2295 error = update_ref(ref, id, replace_tags,
2296 verbosity, repo);
2297 unlock_err = got_ref_unlock(ref);
2298 if (unlock_err && error == NULL)
2299 error = unlock_err;
2300 got_ref_close(ref);
2301 if (error)
2302 goto done;
2305 /* Also create a local branch if none exists yet. */
2306 error = got_ref_open(&ref, repo, refname, 1);
2307 if (error) {
2308 if (error->code != GOT_ERR_NOT_REF)
2309 goto done;
2310 error = create_ref(refname, id, verbosity,
2311 repo);
2312 if (error)
2313 goto done;
2314 } else {
2315 unlock_err = got_ref_unlock(ref);
2316 if (unlock_err && error == NULL)
2317 error = unlock_err;
2318 got_ref_close(ref);
2322 if (delete_refs) {
2323 error = delete_missing_refs(&refs, &symrefs, remote,
2324 verbosity, repo);
2325 if (error)
2326 goto done;
2329 if (!remote->mirror_references) {
2330 /* Update remote HEAD reference if the server provided one. */
2331 TAILQ_FOREACH(pe, &symrefs, entry) {
2332 struct got_reference *target_ref;
2333 const char *refname = pe->path;
2334 const char *target = pe->data;
2335 char *remote_refname = NULL, *remote_target = NULL;
2337 if (strcmp(refname, GOT_REF_HEAD) != 0)
2338 continue;
2340 if (strncmp("refs/heads/", target, 11) != 0)
2341 continue;
2343 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2344 remote->name, refname) == -1) {
2345 error = got_error_from_errno("asprintf");
2346 goto done;
2348 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2349 remote->name, target + 11) == -1) {
2350 error = got_error_from_errno("asprintf");
2351 free(remote_refname);
2352 goto done;
2355 error = got_ref_open(&target_ref, repo, remote_target,
2356 0);
2357 if (error) {
2358 free(remote_refname);
2359 free(remote_target);
2360 if (error->code == GOT_ERR_NOT_REF) {
2361 error = NULL;
2362 continue;
2364 goto done;
2366 error = update_symref(remote_refname, target_ref,
2367 verbosity, repo);
2368 free(remote_refname);
2369 free(remote_target);
2370 got_ref_close(target_ref);
2371 if (error)
2372 goto done;
2375 done:
2376 if (fetchpid > 0) {
2377 if (kill(fetchpid, SIGTERM) == -1)
2378 error = got_error_from_errno("kill");
2379 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2380 error = got_error_from_errno("waitpid");
2382 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2383 error = got_error_from_errno("close");
2384 if (repo)
2385 got_repo_close(repo);
2386 if (worktree)
2387 got_worktree_close(worktree);
2388 TAILQ_FOREACH(pe, &refs, entry) {
2389 free((void *)pe->path);
2390 free(pe->data);
2392 got_pathlist_free(&refs);
2393 TAILQ_FOREACH(pe, &symrefs, entry) {
2394 free((void *)pe->path);
2395 free(pe->data);
2397 got_pathlist_free(&symrefs);
2398 got_pathlist_free(&wanted_branches);
2399 got_pathlist_free(&wanted_refs);
2400 free(id_str);
2401 free(cwd);
2402 free(repo_path);
2403 free(pack_hash);
2404 free(proto);
2405 free(host);
2406 free(port);
2407 free(server_path);
2408 free(repo_name);
2409 return error;
2413 __dead static void
2414 usage_checkout(void)
2416 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2417 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2418 exit(1);
2421 static void
2422 show_worktree_base_ref_warning(void)
2424 fprintf(stderr, "%s: warning: could not create a reference "
2425 "to the work tree's base commit; the commit could be "
2426 "garbage-collected by Git; making the repository "
2427 "writable and running 'got update' will prevent this\n",
2428 getprogname());
2431 struct got_checkout_progress_arg {
2432 const char *worktree_path;
2433 int had_base_commit_ref_error;
2436 static const struct got_error *
2437 checkout_progress(void *arg, unsigned char status, const char *path)
2439 struct got_checkout_progress_arg *a = arg;
2441 /* Base commit bump happens silently. */
2442 if (status == GOT_STATUS_BUMP_BASE)
2443 return NULL;
2445 if (status == GOT_STATUS_BASE_REF_ERR) {
2446 a->had_base_commit_ref_error = 1;
2447 return NULL;
2450 while (path[0] == '/')
2451 path++;
2453 printf("%c %s/%s\n", status, a->worktree_path, path);
2454 return NULL;
2457 static const struct got_error *
2458 check_cancelled(void *arg)
2460 if (sigint_received || sigpipe_received)
2461 return got_error(GOT_ERR_CANCELLED);
2462 return NULL;
2465 static const struct got_error *
2466 check_linear_ancestry(struct got_object_id *commit_id,
2467 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2468 struct got_repository *repo)
2470 const struct got_error *err = NULL;
2471 struct got_object_id *yca_id;
2473 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2474 commit_id, base_commit_id, repo, check_cancelled, NULL);
2475 if (err)
2476 return err;
2478 if (yca_id == NULL)
2479 return got_error(GOT_ERR_ANCESTRY);
2482 * Require a straight line of history between the target commit
2483 * and the work tree's base commit.
2485 * Non-linear situations such as this require a rebase:
2487 * (commit) D F (base_commit)
2488 * \ /
2489 * C E
2490 * \ /
2491 * B (yca)
2492 * |
2493 * A
2495 * 'got update' only handles linear cases:
2496 * Update forwards in time: A (base/yca) - B - C - D (commit)
2497 * Update backwards in time: D (base) - C - B - A (commit/yca)
2499 if (allow_forwards_in_time_only) {
2500 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2501 return got_error(GOT_ERR_ANCESTRY);
2502 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2503 got_object_id_cmp(base_commit_id, yca_id) != 0)
2504 return got_error(GOT_ERR_ANCESTRY);
2506 free(yca_id);
2507 return NULL;
2510 static const struct got_error *
2511 check_same_branch(struct got_object_id *commit_id,
2512 struct got_reference *head_ref, struct got_object_id *yca_id,
2513 struct got_repository *repo)
2515 const struct got_error *err = NULL;
2516 struct got_commit_graph *graph = NULL;
2517 struct got_object_id *head_commit_id = NULL;
2518 int is_same_branch = 0;
2520 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2521 if (err)
2522 goto done;
2524 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2525 is_same_branch = 1;
2526 goto done;
2528 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2529 is_same_branch = 1;
2530 goto done;
2533 err = got_commit_graph_open(&graph, "/", 1);
2534 if (err)
2535 goto done;
2537 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2538 check_cancelled, NULL);
2539 if (err)
2540 goto done;
2542 for (;;) {
2543 struct got_object_id *id;
2544 err = got_commit_graph_iter_next(&id, graph, repo,
2545 check_cancelled, NULL);
2546 if (err) {
2547 if (err->code == GOT_ERR_ITER_COMPLETED)
2548 err = NULL;
2549 break;
2552 if (id) {
2553 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2554 break;
2555 if (got_object_id_cmp(id, commit_id) == 0) {
2556 is_same_branch = 1;
2557 break;
2561 done:
2562 if (graph)
2563 got_commit_graph_close(graph);
2564 free(head_commit_id);
2565 if (!err && !is_same_branch)
2566 err = got_error(GOT_ERR_ANCESTRY);
2567 return err;
2570 static const struct got_error *
2571 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2573 static char msg[512];
2574 const char *branch_name;
2576 if (got_ref_is_symbolic(ref))
2577 branch_name = got_ref_get_symref_target(ref);
2578 else
2579 branch_name = got_ref_get_name(ref);
2581 if (strncmp("refs/heads/", branch_name, 11) == 0)
2582 branch_name += 11;
2584 snprintf(msg, sizeof(msg),
2585 "target commit is not contained in branch '%s'; "
2586 "the branch to use must be specified with -b; "
2587 "if necessary a new branch can be created for "
2588 "this commit with 'got branch -c %s BRANCH_NAME'",
2589 branch_name, commit_id_str);
2591 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2594 static const struct got_error *
2595 cmd_checkout(int argc, char *argv[])
2597 const struct got_error *error = NULL;
2598 struct got_repository *repo = NULL;
2599 struct got_reference *head_ref = NULL;
2600 struct got_worktree *worktree = NULL;
2601 char *repo_path = NULL;
2602 char *worktree_path = NULL;
2603 const char *path_prefix = "";
2604 const char *branch_name = GOT_REF_HEAD;
2605 char *commit_id_str = NULL;
2606 char *cwd = NULL;
2607 int ch, same_path_prefix, allow_nonempty = 0;
2608 struct got_pathlist_head paths;
2609 struct got_checkout_progress_arg cpa;
2611 TAILQ_INIT(&paths);
2613 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2614 switch (ch) {
2615 case 'b':
2616 branch_name = optarg;
2617 break;
2618 case 'c':
2619 commit_id_str = strdup(optarg);
2620 if (commit_id_str == NULL)
2621 return got_error_from_errno("strdup");
2622 break;
2623 case 'E':
2624 allow_nonempty = 1;
2625 break;
2626 case 'p':
2627 path_prefix = optarg;
2628 break;
2629 default:
2630 usage_checkout();
2631 /* NOTREACHED */
2635 argc -= optind;
2636 argv += optind;
2638 #ifndef PROFILE
2639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2640 "unveil", NULL) == -1)
2641 err(1, "pledge");
2642 #endif
2643 if (argc == 1) {
2644 char *base, *dotgit;
2645 const char *path;
2646 repo_path = realpath(argv[0], NULL);
2647 if (repo_path == NULL)
2648 return got_error_from_errno2("realpath", argv[0]);
2649 cwd = getcwd(NULL, 0);
2650 if (cwd == NULL) {
2651 error = got_error_from_errno("getcwd");
2652 goto done;
2654 if (path_prefix[0])
2655 path = path_prefix;
2656 else
2657 path = repo_path;
2658 error = got_path_basename(&base, path);
2659 if (error)
2660 goto done;
2661 dotgit = strstr(base, ".git");
2662 if (dotgit)
2663 *dotgit = '\0';
2664 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2665 error = got_error_from_errno("asprintf");
2666 free(base);
2667 goto done;
2669 free(base);
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 return error;
2791 struct got_update_progress_arg {
2792 int did_something;
2793 int conflicts;
2794 int obstructed;
2795 int not_updated;
2798 void
2799 print_update_progress_stats(struct got_update_progress_arg *upa)
2801 if (!upa->did_something)
2802 return;
2804 if (upa->conflicts > 0)
2805 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2806 if (upa->obstructed > 0)
2807 printf("File paths obstructed by a non-regular file: %d\n",
2808 upa->obstructed);
2809 if (upa->not_updated > 0)
2810 printf("Files not updated because of existing merge "
2811 "conflicts: %d\n", upa->not_updated);
2814 __dead static void
2815 usage_update(void)
2817 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2818 getprogname());
2819 exit(1);
2822 static const struct got_error *
2823 update_progress(void *arg, unsigned char status, const char *path)
2825 struct got_update_progress_arg *upa = arg;
2827 if (status == GOT_STATUS_EXISTS ||
2828 status == GOT_STATUS_BASE_REF_ERR)
2829 return NULL;
2831 upa->did_something = 1;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_CONFLICT)
2838 upa->conflicts++;
2839 if (status == GOT_STATUS_OBSTRUCTED)
2840 upa->obstructed++;
2841 if (status == GOT_STATUS_CANNOT_UPDATE)
2842 upa->not_updated++;
2844 while (path[0] == '/')
2845 path++;
2846 printf("%c %s\n", status, path);
2847 return NULL;
2850 static const struct got_error *
2851 switch_head_ref(struct got_reference *head_ref,
2852 struct got_object_id *commit_id, struct got_worktree *worktree,
2853 struct got_repository *repo)
2855 const struct got_error *err = NULL;
2856 char *base_id_str;
2857 int ref_has_moved = 0;
2859 /* Trivial case: switching between two different references. */
2860 if (strcmp(got_ref_get_name(head_ref),
2861 got_worktree_get_head_ref_name(worktree)) != 0) {
2862 printf("Switching work tree from %s to %s\n",
2863 got_worktree_get_head_ref_name(worktree),
2864 got_ref_get_name(head_ref));
2865 return got_worktree_set_head_ref(worktree, head_ref);
2868 err = check_linear_ancestry(commit_id,
2869 got_worktree_get_base_commit_id(worktree), 0, repo);
2870 if (err) {
2871 if (err->code != GOT_ERR_ANCESTRY)
2872 return err;
2873 ref_has_moved = 1;
2875 if (!ref_has_moved)
2876 return NULL;
2878 /* Switching to a rebased branch with the same reference name. */
2879 err = got_object_id_str(&base_id_str,
2880 got_worktree_get_base_commit_id(worktree));
2881 if (err)
2882 return err;
2883 printf("Reference %s now points at a different branch\n",
2884 got_worktree_get_head_ref_name(worktree));
2885 printf("Switching work tree from %s to %s\n", base_id_str,
2886 got_worktree_get_head_ref_name(worktree));
2887 return NULL;
2890 static const struct got_error *
2891 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2893 const struct got_error *err;
2894 int in_progress;
2896 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2897 if (err)
2898 return err;
2899 if (in_progress)
2900 return got_error(GOT_ERR_REBASING);
2902 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2903 if (err)
2904 return err;
2905 if (in_progress)
2906 return got_error(GOT_ERR_HISTEDIT_BUSY);
2908 return NULL;
2911 static const struct got_error *
2912 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2913 char *argv[], struct got_worktree *worktree)
2915 const struct got_error *err = NULL;
2916 char *path;
2917 int i;
2919 if (argc == 0) {
2920 path = strdup("");
2921 if (path == NULL)
2922 return got_error_from_errno("strdup");
2923 return got_pathlist_append(paths, path, NULL);
2926 for (i = 0; i < argc; i++) {
2927 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2928 if (err)
2929 break;
2930 err = got_pathlist_append(paths, path, NULL);
2931 if (err) {
2932 free(path);
2933 break;
2937 return err;
2940 static const struct got_error *
2941 wrap_not_worktree_error(const struct got_error *orig_err,
2942 const char *cmdname, const char *path)
2944 const struct got_error *err;
2945 struct got_repository *repo;
2946 static char msg[512];
2948 err = got_repo_open(&repo, path, NULL);
2949 if (err)
2950 return orig_err;
2952 snprintf(msg, sizeof(msg),
2953 "'got %s' needs a work tree in addition to a git repository\n"
2954 "Work trees can be checked out from this Git repository with "
2955 "'got checkout'.\n"
2956 "The got(1) manual page contains more information.", cmdname);
2957 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2958 got_repo_close(repo);
2959 return err;
2962 static const struct got_error *
2963 cmd_update(int argc, char *argv[])
2965 const struct got_error *error = NULL;
2966 struct got_repository *repo = NULL;
2967 struct got_worktree *worktree = NULL;
2968 char *worktree_path = NULL;
2969 struct got_object_id *commit_id = NULL;
2970 char *commit_id_str = NULL;
2971 const char *branch_name = NULL;
2972 struct got_reference *head_ref = NULL;
2973 struct got_pathlist_head paths;
2974 struct got_pathlist_entry *pe;
2975 int ch;
2976 struct got_update_progress_arg upa;
2978 TAILQ_INIT(&paths);
2980 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2981 switch (ch) {
2982 case 'b':
2983 branch_name = optarg;
2984 break;
2985 case 'c':
2986 commit_id_str = strdup(optarg);
2987 if (commit_id_str == NULL)
2988 return got_error_from_errno("strdup");
2989 break;
2990 default:
2991 usage_update();
2992 /* NOTREACHED */
2996 argc -= optind;
2997 argv += optind;
2999 #ifndef PROFILE
3000 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3001 "unveil", NULL) == -1)
3002 err(1, "pledge");
3003 #endif
3004 worktree_path = getcwd(NULL, 0);
3005 if (worktree_path == NULL) {
3006 error = got_error_from_errno("getcwd");
3007 goto done;
3009 error = got_worktree_open(&worktree, worktree_path);
3010 if (error) {
3011 if (error->code == GOT_ERR_NOT_WORKTREE)
3012 error = wrap_not_worktree_error(error, "update",
3013 worktree_path);
3014 goto done;
3017 error = check_rebase_or_histedit_in_progress(worktree);
3018 if (error)
3019 goto done;
3021 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3022 NULL);
3023 if (error != NULL)
3024 goto done;
3026 error = apply_unveil(got_repo_get_path(repo), 0,
3027 got_worktree_get_root_path(worktree));
3028 if (error)
3029 goto done;
3031 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3032 if (error)
3033 goto done;
3035 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3036 got_worktree_get_head_ref_name(worktree), 0);
3037 if (error != NULL)
3038 goto done;
3039 if (commit_id_str == NULL) {
3040 error = got_ref_resolve(&commit_id, repo, head_ref);
3041 if (error != NULL)
3042 goto done;
3043 error = got_object_id_str(&commit_id_str, commit_id);
3044 if (error != NULL)
3045 goto done;
3046 } else {
3047 error = got_repo_match_object_id(&commit_id, NULL,
3048 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3049 free(commit_id_str);
3050 commit_id_str = NULL;
3051 if (error)
3052 goto done;
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3058 if (branch_name) {
3059 struct got_object_id *head_commit_id;
3060 TAILQ_FOREACH(pe, &paths, entry) {
3061 if (pe->path_len == 0)
3062 continue;
3063 error = got_error_msg(GOT_ERR_BAD_PATH,
3064 "switching between branches requires that "
3065 "the entire work tree gets updated");
3066 goto done;
3068 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3069 if (error)
3070 goto done;
3071 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3072 repo);
3073 free(head_commit_id);
3074 if (error != NULL)
3075 goto done;
3076 error = check_same_branch(commit_id, head_ref, NULL, repo);
3077 if (error)
3078 goto done;
3079 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3080 if (error)
3081 goto done;
3082 } else {
3083 error = check_linear_ancestry(commit_id,
3084 got_worktree_get_base_commit_id(worktree), 0, repo);
3085 if (error != NULL) {
3086 if (error->code == GOT_ERR_ANCESTRY)
3087 error = got_error(GOT_ERR_BRANCH_MOVED);
3088 goto done;
3090 error = check_same_branch(commit_id, head_ref, NULL, repo);
3091 if (error)
3092 goto done;
3095 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3096 commit_id) != 0) {
3097 error = got_worktree_set_base_commit_id(worktree, repo,
3098 commit_id);
3099 if (error)
3100 goto done;
3103 memset(&upa, 0, sizeof(upa));
3104 error = got_worktree_checkout_files(worktree, &paths, repo,
3105 update_progress, &upa, check_cancelled, NULL);
3106 if (error != NULL)
3107 goto done;
3109 if (upa.did_something)
3110 printf("Updated to commit %s\n", commit_id_str);
3111 else
3112 printf("Already up-to-date\n");
3113 print_update_progress_stats(&upa);
3114 done:
3115 free(worktree_path);
3116 TAILQ_FOREACH(pe, &paths, entry)
3117 free((char *)pe->path);
3118 got_pathlist_free(&paths);
3119 free(commit_id);
3120 free(commit_id_str);
3121 return error;
3124 static const struct got_error *
3125 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3126 const char *path, int diff_context, int ignore_whitespace,
3127 struct got_repository *repo)
3129 const struct got_error *err = NULL;
3130 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3132 if (blob_id1) {
3133 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3134 if (err)
3135 goto done;
3138 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3139 if (err)
3140 goto done;
3142 while (path[0] == '/')
3143 path++;
3144 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3145 ignore_whitespace, stdout);
3146 done:
3147 if (blob1)
3148 got_object_blob_close(blob1);
3149 got_object_blob_close(blob2);
3150 return err;
3153 static const struct got_error *
3154 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3155 const char *path, int diff_context, int ignore_whitespace,
3156 struct got_repository *repo)
3158 const struct got_error *err = NULL;
3159 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3160 struct got_diff_blob_output_unidiff_arg arg;
3162 if (tree_id1) {
3163 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3164 if (err)
3165 goto done;
3168 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3169 if (err)
3170 goto done;
3172 arg.diff_context = diff_context;
3173 arg.ignore_whitespace = ignore_whitespace;
3174 arg.outfile = stdout;
3175 while (path[0] == '/')
3176 path++;
3177 err = got_diff_tree(tree1, tree2, path, path, repo,
3178 got_diff_blob_output_unidiff, &arg, 1);
3179 done:
3180 if (tree1)
3181 got_object_tree_close(tree1);
3182 if (tree2)
3183 got_object_tree_close(tree2);
3184 return err;
3187 static const struct got_error *
3188 get_changed_paths(struct got_pathlist_head *paths,
3189 struct got_commit_object *commit, struct got_repository *repo)
3191 const struct got_error *err = NULL;
3192 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3193 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3194 struct got_object_qid *qid;
3196 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3197 if (qid != NULL) {
3198 struct got_commit_object *pcommit;
3199 err = got_object_open_as_commit(&pcommit, repo,
3200 qid->id);
3201 if (err)
3202 return err;
3204 tree_id1 = got_object_commit_get_tree_id(pcommit);
3205 got_object_commit_close(pcommit);
3209 if (tree_id1) {
3210 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3211 if (err)
3212 goto done;
3215 tree_id2 = got_object_commit_get_tree_id(commit);
3216 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3217 if (err)
3218 goto done;
3220 err = got_diff_tree(tree1, tree2, "", "", repo,
3221 got_diff_tree_collect_changed_paths, paths, 0);
3222 done:
3223 if (tree1)
3224 got_object_tree_close(tree1);
3225 if (tree2)
3226 got_object_tree_close(tree2);
3227 return err;
3230 static const struct got_error *
3231 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3232 const char *path, int diff_context, struct got_repository *repo)
3234 const struct got_error *err = NULL;
3235 struct got_commit_object *pcommit = NULL;
3236 char *id_str1 = NULL, *id_str2 = NULL;
3237 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3238 struct got_object_qid *qid;
3240 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3241 if (qid != NULL) {
3242 err = got_object_open_as_commit(&pcommit, repo,
3243 qid->id);
3244 if (err)
3245 return err;
3248 if (path && path[0] != '\0') {
3249 int obj_type;
3250 err = got_object_id_by_path(&obj_id2, repo, id, path);
3251 if (err)
3252 goto done;
3253 err = got_object_id_str(&id_str2, obj_id2);
3254 if (err) {
3255 free(obj_id2);
3256 goto done;
3258 if (pcommit) {
3259 err = got_object_id_by_path(&obj_id1, repo,
3260 qid->id, path);
3261 if (err) {
3262 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3263 free(obj_id2);
3264 goto done;
3266 } else {
3267 err = got_object_id_str(&id_str1, obj_id1);
3268 if (err) {
3269 free(obj_id2);
3270 goto done;
3274 err = got_object_get_type(&obj_type, repo, obj_id2);
3275 if (err) {
3276 free(obj_id2);
3277 goto done;
3279 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3280 switch (obj_type) {
3281 case GOT_OBJ_TYPE_BLOB:
3282 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3283 0, repo);
3284 break;
3285 case GOT_OBJ_TYPE_TREE:
3286 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3287 0, repo);
3288 break;
3289 default:
3290 err = got_error(GOT_ERR_OBJ_TYPE);
3291 break;
3293 free(obj_id1);
3294 free(obj_id2);
3295 } else {
3296 obj_id2 = got_object_commit_get_tree_id(commit);
3297 err = got_object_id_str(&id_str2, obj_id2);
3298 if (err)
3299 goto done;
3300 obj_id1 = got_object_commit_get_tree_id(pcommit);
3301 err = got_object_id_str(&id_str1, obj_id1);
3302 if (err)
3303 goto done;
3304 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3305 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3307 done:
3308 free(id_str1);
3309 free(id_str2);
3310 if (pcommit)
3311 got_object_commit_close(pcommit);
3312 return err;
3315 static char *
3316 get_datestr(time_t *time, char *datebuf)
3318 struct tm mytm, *tm;
3319 char *p, *s;
3321 tm = gmtime_r(time, &mytm);
3322 if (tm == NULL)
3323 return NULL;
3324 s = asctime_r(tm, datebuf);
3325 if (s == NULL)
3326 return NULL;
3327 p = strchr(s, '\n');
3328 if (p)
3329 *p = '\0';
3330 return s;
3333 static const struct got_error *
3334 match_logmsg(int *have_match, struct got_object_id *id,
3335 struct got_commit_object *commit, regex_t *regex)
3337 const struct got_error *err = NULL;
3338 regmatch_t regmatch;
3339 char *id_str = NULL, *logmsg = NULL;
3341 *have_match = 0;
3343 err = got_object_id_str(&id_str, id);
3344 if (err)
3345 return err;
3347 err = got_object_commit_get_logmsg(&logmsg, commit);
3348 if (err)
3349 goto done;
3351 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3352 *have_match = 1;
3353 done:
3354 free(id_str);
3355 free(logmsg);
3356 return err;
3359 static void
3360 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3361 regex_t *regex)
3363 regmatch_t regmatch;
3364 struct got_pathlist_entry *pe;
3366 *have_match = 0;
3368 TAILQ_FOREACH(pe, changed_paths, entry) {
3369 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3370 *have_match = 1;
3371 break;
3376 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3378 static const struct got_error *
3379 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3380 struct got_repository *repo, const char *path,
3381 struct got_pathlist_head *changed_paths, int show_patch,
3382 int diff_context, struct got_reflist_head *refs)
3384 const struct got_error *err = NULL;
3385 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3386 char datebuf[26];
3387 time_t committer_time;
3388 const char *author, *committer;
3389 char *refs_str = NULL;
3390 struct got_reflist_entry *re;
3392 SIMPLEQ_FOREACH(re, refs, entry) {
3393 char *s;
3394 const char *name;
3395 struct got_tag_object *tag = NULL;
3396 struct got_object_id *ref_id;
3397 int cmp;
3399 name = got_ref_get_name(re->ref);
3400 if (strcmp(name, GOT_REF_HEAD) == 0)
3401 continue;
3402 if (strncmp(name, "refs/", 5) == 0)
3403 name += 5;
3404 if (strncmp(name, "got/", 4) == 0)
3405 continue;
3406 if (strncmp(name, "heads/", 6) == 0)
3407 name += 6;
3408 if (strncmp(name, "remotes/", 8) == 0) {
3409 name += 8;
3410 s = strstr(name, "/" GOT_REF_HEAD);
3411 if (s != NULL && s[strlen(s)] == '\0')
3412 continue;
3414 err = got_ref_resolve(&ref_id, repo, re->ref);
3415 if (err)
3416 return err;
3417 if (strncmp(name, "tags/", 5) == 0) {
3418 err = got_object_open_as_tag(&tag, repo, ref_id);
3419 if (err) {
3420 if (err->code != GOT_ERR_OBJ_TYPE) {
3421 free(ref_id);
3422 return err;
3424 /* Ref points at something other than a tag. */
3425 err = NULL;
3426 tag = NULL;
3429 cmp = got_object_id_cmp(tag ?
3430 got_object_tag_get_object_id(tag) : ref_id, id);
3431 free(ref_id);
3432 if (tag)
3433 got_object_tag_close(tag);
3434 if (cmp != 0)
3435 continue;
3436 s = refs_str;
3437 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3438 name) == -1) {
3439 err = got_error_from_errno("asprintf");
3440 free(s);
3441 return err;
3443 free(s);
3445 err = got_object_id_str(&id_str, id);
3446 if (err)
3447 return err;
3449 printf(GOT_COMMIT_SEP_STR);
3450 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3451 refs_str ? refs_str : "", refs_str ? ")" : "");
3452 free(id_str);
3453 id_str = NULL;
3454 free(refs_str);
3455 refs_str = NULL;
3456 printf("from: %s\n", got_object_commit_get_author(commit));
3457 committer_time = got_object_commit_get_committer_time(commit);
3458 datestr = get_datestr(&committer_time, datebuf);
3459 if (datestr)
3460 printf("date: %s UTC\n", datestr);
3461 author = got_object_commit_get_author(commit);
3462 committer = got_object_commit_get_committer(commit);
3463 if (strcmp(author, committer) != 0)
3464 printf("via: %s\n", committer);
3465 if (got_object_commit_get_nparents(commit) > 1) {
3466 const struct got_object_id_queue *parent_ids;
3467 struct got_object_qid *qid;
3468 int n = 1;
3469 parent_ids = got_object_commit_get_parent_ids(commit);
3470 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3471 err = got_object_id_str(&id_str, qid->id);
3472 if (err)
3473 return err;
3474 printf("parent %d: %s\n", n++, id_str);
3475 free(id_str);
3479 err = got_object_commit_get_logmsg(&logmsg0, commit);
3480 if (err)
3481 return err;
3483 logmsg = logmsg0;
3484 do {
3485 line = strsep(&logmsg, "\n");
3486 if (line)
3487 printf(" %s\n", line);
3488 } while (line);
3489 free(logmsg0);
3491 if (changed_paths) {
3492 struct got_pathlist_entry *pe;
3493 TAILQ_FOREACH(pe, changed_paths, entry) {
3494 struct got_diff_changed_path *cp = pe->data;
3495 printf(" %c %s\n", cp->status, pe->path);
3497 printf("\n");
3499 if (show_patch) {
3500 err = print_patch(commit, id, path, diff_context, repo);
3501 if (err == 0)
3502 printf("\n");
3505 if (fflush(stdout) != 0 && err == NULL)
3506 err = got_error_from_errno("fflush");
3507 return err;
3510 static const struct got_error *
3511 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3512 struct got_repository *repo, const char *path, int show_changed_paths,
3513 int show_patch, const char *search_pattern, int diff_context, int limit,
3514 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3516 const struct got_error *err;
3517 struct got_commit_graph *graph;
3518 regex_t regex;
3519 int have_match;
3520 struct got_object_id_queue reversed_commits;
3521 struct got_object_qid *qid;
3522 struct got_commit_object *commit;
3523 struct got_pathlist_head changed_paths;
3524 struct got_pathlist_entry *pe;
3526 SIMPLEQ_INIT(&reversed_commits);
3527 TAILQ_INIT(&changed_paths);
3529 if (search_pattern && regcomp(&regex, search_pattern,
3530 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3531 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3533 err = got_commit_graph_open(&graph, path, !log_branches);
3534 if (err)
3535 return err;
3536 err = got_commit_graph_iter_start(graph, root_id, repo,
3537 check_cancelled, NULL);
3538 if (err)
3539 goto done;
3540 for (;;) {
3541 struct got_object_id *id;
3543 if (sigint_received || sigpipe_received)
3544 break;
3546 err = got_commit_graph_iter_next(&id, graph, repo,
3547 check_cancelled, NULL);
3548 if (err) {
3549 if (err->code == GOT_ERR_ITER_COMPLETED)
3550 err = NULL;
3551 break;
3553 if (id == NULL)
3554 break;
3556 err = got_object_open_as_commit(&commit, repo, id);
3557 if (err)
3558 break;
3560 if (show_changed_paths && !reverse_display_order) {
3561 err = get_changed_paths(&changed_paths, commit, repo);
3562 if (err)
3563 break;
3566 if (search_pattern) {
3567 err = match_logmsg(&have_match, id, commit, &regex);
3568 if (err) {
3569 got_object_commit_close(commit);
3570 break;
3572 if (have_match == 0 && show_changed_paths)
3573 match_changed_paths(&have_match,
3574 &changed_paths, &regex);
3575 if (have_match == 0) {
3576 got_object_commit_close(commit);
3577 TAILQ_FOREACH(pe, &changed_paths, entry) {
3578 free((char *)pe->path);
3579 free(pe->data);
3581 got_pathlist_free(&changed_paths);
3582 continue;
3586 if (reverse_display_order) {
3587 err = got_object_qid_alloc(&qid, id);
3588 if (err)
3589 break;
3590 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3591 got_object_commit_close(commit);
3592 } else {
3593 err = print_commit(commit, id, repo, path,
3594 show_changed_paths ? &changed_paths : NULL,
3595 show_patch, diff_context, refs);
3596 got_object_commit_close(commit);
3597 if (err)
3598 break;
3600 if ((limit && --limit == 0) ||
3601 (end_id && got_object_id_cmp(id, end_id) == 0))
3602 break;
3604 TAILQ_FOREACH(pe, &changed_paths, entry) {
3605 free((char *)pe->path);
3606 free(pe->data);
3608 got_pathlist_free(&changed_paths);
3610 if (reverse_display_order) {
3611 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3612 err = got_object_open_as_commit(&commit, repo, qid->id);
3613 if (err)
3614 break;
3615 if (show_changed_paths) {
3616 err = get_changed_paths(&changed_paths,
3617 commit, repo);
3618 if (err)
3619 break;
3621 err = print_commit(commit, qid->id, repo, path,
3622 show_changed_paths ? &changed_paths : NULL,
3623 show_patch, diff_context, refs);
3624 got_object_commit_close(commit);
3625 if (err)
3626 break;
3627 TAILQ_FOREACH(pe, &changed_paths, entry) {
3628 free((char *)pe->path);
3629 free(pe->data);
3631 got_pathlist_free(&changed_paths);
3634 done:
3635 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3636 qid = SIMPLEQ_FIRST(&reversed_commits);
3637 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3638 got_object_qid_free(qid);
3640 TAILQ_FOREACH(pe, &changed_paths, entry) {
3641 free((char *)pe->path);
3642 free(pe->data);
3644 got_pathlist_free(&changed_paths);
3645 if (search_pattern)
3646 regfree(&regex);
3647 got_commit_graph_close(graph);
3648 return err;
3651 __dead static void
3652 usage_log(void)
3654 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3655 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3656 "[-R] [path]\n", getprogname());
3657 exit(1);
3660 static int
3661 get_default_log_limit(void)
3663 const char *got_default_log_limit;
3664 long long n;
3665 const char *errstr;
3667 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3668 if (got_default_log_limit == NULL)
3669 return 0;
3670 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3671 if (errstr != NULL)
3672 return 0;
3673 return n;
3676 static const struct got_error *
3677 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3678 struct got_repository *repo)
3680 const struct got_error *err = NULL;
3681 struct got_reference *ref;
3683 *id = NULL;
3685 err = got_ref_open(&ref, repo, commit_arg, 0);
3686 if (err == NULL) {
3687 int obj_type;
3688 err = got_ref_resolve(id, repo, ref);
3689 got_ref_close(ref);
3690 if (err)
3691 return err;
3692 err = got_object_get_type(&obj_type, repo, *id);
3693 if (err)
3694 return err;
3695 if (obj_type == GOT_OBJ_TYPE_TAG) {
3696 struct got_tag_object *tag;
3697 err = got_object_open_as_tag(&tag, repo, *id);
3698 if (err)
3699 return err;
3700 if (got_object_tag_get_object_type(tag) !=
3701 GOT_OBJ_TYPE_COMMIT) {
3702 got_object_tag_close(tag);
3703 return got_error(GOT_ERR_OBJ_TYPE);
3705 free(*id);
3706 *id = got_object_id_dup(
3707 got_object_tag_get_object_id(tag));
3708 if (*id == NULL)
3709 err = got_error_from_errno(
3710 "got_object_id_dup");
3711 got_object_tag_close(tag);
3712 if (err)
3713 return err;
3714 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3715 return got_error(GOT_ERR_OBJ_TYPE);
3716 } else {
3717 err = got_repo_match_object_id_prefix(id, commit_arg,
3718 GOT_OBJ_TYPE_COMMIT, repo);
3721 return err;
3724 static const struct got_error *
3725 cmd_log(int argc, char *argv[])
3727 const struct got_error *error;
3728 struct got_repository *repo = NULL;
3729 struct got_worktree *worktree = NULL;
3730 struct got_object_id *start_id = NULL, *end_id = NULL;
3731 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3732 const char *start_commit = NULL, *end_commit = NULL;
3733 const char *search_pattern = NULL;
3734 int diff_context = -1, ch;
3735 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3736 int reverse_display_order = 0;
3737 const char *errstr;
3738 struct got_reflist_head refs;
3740 SIMPLEQ_INIT(&refs);
3742 #ifndef PROFILE
3743 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3744 NULL)
3745 == -1)
3746 err(1, "pledge");
3747 #endif
3749 limit = get_default_log_limit();
3751 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3752 switch (ch) {
3753 case 'p':
3754 show_patch = 1;
3755 break;
3756 case 'P':
3757 show_changed_paths = 1;
3758 break;
3759 case 'c':
3760 start_commit = optarg;
3761 break;
3762 case 'C':
3763 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3764 &errstr);
3765 if (errstr != NULL)
3766 err(1, "-C option %s", errstr);
3767 break;
3768 case 'l':
3769 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3770 if (errstr != NULL)
3771 err(1, "-l option %s", errstr);
3772 break;
3773 case 'b':
3774 log_branches = 1;
3775 break;
3776 case 'r':
3777 repo_path = realpath(optarg, NULL);
3778 if (repo_path == NULL)
3779 return got_error_from_errno2("realpath",
3780 optarg);
3781 got_path_strip_trailing_slashes(repo_path);
3782 break;
3783 case 'R':
3784 reverse_display_order = 1;
3785 break;
3786 case 's':
3787 search_pattern = optarg;
3788 break;
3789 case 'x':
3790 end_commit = optarg;
3791 break;
3792 default:
3793 usage_log();
3794 /* NOTREACHED */
3798 argc -= optind;
3799 argv += optind;
3801 if (diff_context == -1)
3802 diff_context = 3;
3803 else if (!show_patch)
3804 errx(1, "-C requires -p");
3806 cwd = getcwd(NULL, 0);
3807 if (cwd == NULL) {
3808 error = got_error_from_errno("getcwd");
3809 goto done;
3812 if (repo_path == NULL) {
3813 error = got_worktree_open(&worktree, cwd);
3814 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3815 goto done;
3816 error = NULL;
3819 if (argc == 1) {
3820 if (worktree) {
3821 error = got_worktree_resolve_path(&path, worktree,
3822 argv[0]);
3823 if (error)
3824 goto done;
3825 } else {
3826 path = strdup(argv[0]);
3827 if (path == NULL) {
3828 error = got_error_from_errno("strdup");
3829 goto done;
3832 } else if (argc != 0)
3833 usage_log();
3835 if (repo_path == NULL) {
3836 repo_path = worktree ?
3837 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3839 if (repo_path == NULL) {
3840 error = got_error_from_errno("strdup");
3841 goto done;
3844 error = got_repo_open(&repo, repo_path, NULL);
3845 if (error != NULL)
3846 goto done;
3848 error = apply_unveil(got_repo_get_path(repo), 1,
3849 worktree ? got_worktree_get_root_path(worktree) : NULL);
3850 if (error)
3851 goto done;
3853 if (start_commit == NULL) {
3854 struct got_reference *head_ref;
3855 struct got_commit_object *commit = NULL;
3856 error = got_ref_open(&head_ref, repo,
3857 worktree ? got_worktree_get_head_ref_name(worktree)
3858 : GOT_REF_HEAD, 0);
3859 if (error != NULL)
3860 goto done;
3861 error = got_ref_resolve(&start_id, repo, head_ref);
3862 got_ref_close(head_ref);
3863 if (error != NULL)
3864 goto done;
3865 error = got_object_open_as_commit(&commit, repo,
3866 start_id);
3867 if (error != NULL)
3868 goto done;
3869 got_object_commit_close(commit);
3870 } else {
3871 error = resolve_commit_arg(&start_id, start_commit, repo);
3872 if (error != NULL)
3873 goto done;
3875 if (end_commit != NULL) {
3876 error = resolve_commit_arg(&end_id, end_commit, repo);
3877 if (error != NULL)
3878 goto done;
3881 if (worktree) {
3883 * If a path was specified on the command line it was resolved
3884 * to a path in the work tree above. Prepend the work tree's
3885 * path prefix to obtain the corresponding in-repository path.
3887 if (path) {
3888 const char *prefix;
3889 prefix = got_worktree_get_path_prefix(worktree);
3890 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3891 (path[0] != '\0') ? "/" : "", path) == -1) {
3892 error = got_error_from_errno("asprintf");
3893 goto done;
3896 } else
3897 error = got_repo_map_path(&in_repo_path, repo,
3898 path ? path : "", 1);
3899 if (error != NULL)
3900 goto done;
3901 if (in_repo_path) {
3902 free(path);
3903 path = in_repo_path;
3906 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3907 if (error)
3908 goto done;
3910 error = print_commits(start_id, end_id, repo, path ? path : "",
3911 show_changed_paths, show_patch, search_pattern, diff_context,
3912 limit, log_branches, reverse_display_order, &refs);
3913 done:
3914 free(path);
3915 free(repo_path);
3916 free(cwd);
3917 if (worktree)
3918 got_worktree_close(worktree);
3919 if (repo) {
3920 const struct got_error *repo_error;
3921 repo_error = got_repo_close(repo);
3922 if (error == NULL)
3923 error = repo_error;
3925 got_ref_list_free(&refs);
3926 return error;
3929 __dead static void
3930 usage_diff(void)
3932 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3933 "[-w] [object1 object2 | path]\n", getprogname());
3934 exit(1);
3937 struct print_diff_arg {
3938 struct got_repository *repo;
3939 struct got_worktree *worktree;
3940 int diff_context;
3941 const char *id_str;
3942 int header_shown;
3943 int diff_staged;
3944 int ignore_whitespace;
3948 * Create a file which contains the target path of a symlink so we can feed
3949 * it as content to the diff engine.
3951 static const struct got_error *
3952 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3953 const char *abspath)
3955 const struct got_error *err = NULL;
3956 char target_path[PATH_MAX];
3957 ssize_t target_len, outlen;
3959 *fd = -1;
3961 if (dirfd != -1) {
3962 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3963 if (target_len == -1)
3964 return got_error_from_errno2("readlinkat", abspath);
3965 } else {
3966 target_len = readlink(abspath, target_path, PATH_MAX);
3967 if (target_len == -1)
3968 return got_error_from_errno2("readlink", abspath);
3971 *fd = got_opentempfd();
3972 if (*fd == -1)
3973 return got_error_from_errno("got_opentempfd");
3975 outlen = write(*fd, target_path, target_len);
3976 if (outlen == -1) {
3977 err = got_error_from_errno("got_opentempfd");
3978 goto done;
3981 if (lseek(*fd, 0, SEEK_SET) == -1) {
3982 err = got_error_from_errno2("lseek", abspath);
3983 goto done;
3985 done:
3986 if (err) {
3987 close(*fd);
3988 *fd = -1;
3990 return err;
3993 static const struct got_error *
3994 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3995 const char *path, struct got_object_id *blob_id,
3996 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3997 int dirfd, const char *de_name)
3999 struct print_diff_arg *a = arg;
4000 const struct got_error *err = NULL;
4001 struct got_blob_object *blob1 = NULL;
4002 int fd = -1;
4003 FILE *f2 = NULL;
4004 char *abspath = NULL, *label1 = NULL;
4005 struct stat sb;
4007 if (a->diff_staged) {
4008 if (staged_status != GOT_STATUS_MODIFY &&
4009 staged_status != GOT_STATUS_ADD &&
4010 staged_status != GOT_STATUS_DELETE)
4011 return NULL;
4012 } else {
4013 if (staged_status == GOT_STATUS_DELETE)
4014 return NULL;
4015 if (status == GOT_STATUS_NONEXISTENT)
4016 return got_error_set_errno(ENOENT, path);
4017 if (status != GOT_STATUS_MODIFY &&
4018 status != GOT_STATUS_ADD &&
4019 status != GOT_STATUS_DELETE &&
4020 status != GOT_STATUS_CONFLICT)
4021 return NULL;
4024 if (!a->header_shown) {
4025 printf("diff %s %s%s\n", a->id_str,
4026 got_worktree_get_root_path(a->worktree),
4027 a->diff_staged ? " (staged changes)" : "");
4028 a->header_shown = 1;
4031 if (a->diff_staged) {
4032 const char *label1 = NULL, *label2 = NULL;
4033 switch (staged_status) {
4034 case GOT_STATUS_MODIFY:
4035 label1 = path;
4036 label2 = path;
4037 break;
4038 case GOT_STATUS_ADD:
4039 label2 = path;
4040 break;
4041 case GOT_STATUS_DELETE:
4042 label1 = path;
4043 break;
4044 default:
4045 return got_error(GOT_ERR_FILE_STATUS);
4047 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4048 label1, label2, a->diff_context, a->ignore_whitespace,
4049 a->repo, stdout);
4052 if (staged_status == GOT_STATUS_ADD ||
4053 staged_status == GOT_STATUS_MODIFY) {
4054 char *id_str;
4055 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4056 8192);
4057 if (err)
4058 goto done;
4059 err = got_object_id_str(&id_str, staged_blob_id);
4060 if (err)
4061 goto done;
4062 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4063 err = got_error_from_errno("asprintf");
4064 free(id_str);
4065 goto done;
4067 free(id_str);
4068 } else if (status != GOT_STATUS_ADD) {
4069 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4070 if (err)
4071 goto done;
4074 if (status != GOT_STATUS_DELETE) {
4075 if (asprintf(&abspath, "%s/%s",
4076 got_worktree_get_root_path(a->worktree), path) == -1) {
4077 err = got_error_from_errno("asprintf");
4078 goto done;
4081 if (dirfd != -1) {
4082 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4083 if (fd == -1) {
4084 if (errno != ELOOP) {
4085 err = got_error_from_errno2("openat",
4086 abspath);
4087 goto done;
4089 err = get_symlink_target_file(&fd, dirfd,
4090 de_name, abspath);
4091 if (err)
4092 goto done;
4094 } else {
4095 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4096 if (fd == -1) {
4097 if (errno != ELOOP) {
4098 err = got_error_from_errno2("open",
4099 abspath);
4100 goto done;
4102 err = get_symlink_target_file(&fd, dirfd,
4103 de_name, abspath);
4104 if (err)
4105 goto done;
4108 if (fstat(fd, &sb) == -1) {
4109 err = got_error_from_errno2("fstat", abspath);
4110 goto done;
4112 f2 = fdopen(fd, "r");
4113 if (f2 == NULL) {
4114 err = got_error_from_errno2("fdopen", abspath);
4115 goto done;
4117 fd = -1;
4118 } else
4119 sb.st_size = 0;
4121 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4122 a->diff_context, a->ignore_whitespace, stdout);
4123 done:
4124 if (blob1)
4125 got_object_blob_close(blob1);
4126 if (f2 && fclose(f2) == EOF && err == NULL)
4127 err = got_error_from_errno("fclose");
4128 if (fd != -1 && close(fd) == -1 && err == NULL)
4129 err = got_error_from_errno("close");
4130 free(abspath);
4131 return err;
4134 static const struct got_error *
4135 cmd_diff(int argc, char *argv[])
4137 const struct got_error *error;
4138 struct got_repository *repo = NULL;
4139 struct got_worktree *worktree = NULL;
4140 char *cwd = NULL, *repo_path = NULL;
4141 struct got_object_id *id1 = NULL, *id2 = NULL;
4142 const char *id_str1 = NULL, *id_str2 = NULL;
4143 char *label1 = NULL, *label2 = NULL;
4144 int type1, type2;
4145 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4146 const char *errstr;
4147 char *path = NULL;
4149 #ifndef PROFILE
4150 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4151 NULL) == -1)
4152 err(1, "pledge");
4153 #endif
4155 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4156 switch (ch) {
4157 case 'C':
4158 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4159 &errstr);
4160 if (errstr != NULL)
4161 err(1, "-C option %s", errstr);
4162 break;
4163 case 'r':
4164 repo_path = realpath(optarg, NULL);
4165 if (repo_path == NULL)
4166 return got_error_from_errno2("realpath",
4167 optarg);
4168 got_path_strip_trailing_slashes(repo_path);
4169 break;
4170 case 's':
4171 diff_staged = 1;
4172 break;
4173 case 'w':
4174 ignore_whitespace = 1;
4175 break;
4176 default:
4177 usage_diff();
4178 /* NOTREACHED */
4182 argc -= optind;
4183 argv += optind;
4185 cwd = getcwd(NULL, 0);
4186 if (cwd == NULL) {
4187 error = got_error_from_errno("getcwd");
4188 goto done;
4190 if (argc <= 1) {
4191 if (repo_path)
4192 errx(1,
4193 "-r option can't be used when diffing a work tree");
4194 error = got_worktree_open(&worktree, cwd);
4195 if (error) {
4196 if (error->code == GOT_ERR_NOT_WORKTREE)
4197 error = wrap_not_worktree_error(error, "diff",
4198 cwd);
4199 goto done;
4201 repo_path = strdup(got_worktree_get_repo_path(worktree));
4202 if (repo_path == NULL) {
4203 error = got_error_from_errno("strdup");
4204 goto done;
4206 if (argc == 1) {
4207 error = got_worktree_resolve_path(&path, worktree,
4208 argv[0]);
4209 if (error)
4210 goto done;
4211 } else {
4212 path = strdup("");
4213 if (path == NULL) {
4214 error = got_error_from_errno("strdup");
4215 goto done;
4218 } else if (argc == 2) {
4219 if (diff_staged)
4220 errx(1, "-s option can't be used when diffing "
4221 "objects in repository");
4222 id_str1 = argv[0];
4223 id_str2 = argv[1];
4224 if (repo_path == NULL) {
4225 error = got_worktree_open(&worktree, cwd);
4226 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4227 goto done;
4228 if (worktree) {
4229 repo_path = strdup(
4230 got_worktree_get_repo_path(worktree));
4231 if (repo_path == NULL) {
4232 error = got_error_from_errno("strdup");
4233 goto done;
4235 } else {
4236 repo_path = strdup(cwd);
4237 if (repo_path == NULL) {
4238 error = got_error_from_errno("strdup");
4239 goto done;
4243 } else
4244 usage_diff();
4246 error = got_repo_open(&repo, repo_path, NULL);
4247 free(repo_path);
4248 if (error != NULL)
4249 goto done;
4251 error = apply_unveil(got_repo_get_path(repo), 1,
4252 worktree ? got_worktree_get_root_path(worktree) : NULL);
4253 if (error)
4254 goto done;
4256 if (argc <= 1) {
4257 struct print_diff_arg arg;
4258 struct got_pathlist_head paths;
4259 char *id_str;
4261 TAILQ_INIT(&paths);
4263 error = got_object_id_str(&id_str,
4264 got_worktree_get_base_commit_id(worktree));
4265 if (error)
4266 goto done;
4267 arg.repo = repo;
4268 arg.worktree = worktree;
4269 arg.diff_context = diff_context;
4270 arg.id_str = id_str;
4271 arg.header_shown = 0;
4272 arg.diff_staged = diff_staged;
4273 arg.ignore_whitespace = ignore_whitespace;
4275 error = got_pathlist_append(&paths, path, NULL);
4276 if (error)
4277 goto done;
4279 error = got_worktree_status(worktree, &paths, repo, print_diff,
4280 &arg, check_cancelled, NULL);
4281 free(id_str);
4282 got_pathlist_free(&paths);
4283 goto done;
4286 error = got_repo_match_object_id(&id1, &label1, id_str1,
4287 GOT_OBJ_TYPE_ANY, 1, repo);
4288 if (error)
4289 goto done;
4291 error = got_repo_match_object_id(&id2, &label2, id_str2,
4292 GOT_OBJ_TYPE_ANY, 1, repo);
4293 if (error)
4294 goto done;
4296 error = got_object_get_type(&type1, repo, id1);
4297 if (error)
4298 goto done;
4300 error = got_object_get_type(&type2, repo, id2);
4301 if (error)
4302 goto done;
4304 if (type1 != type2) {
4305 error = got_error(GOT_ERR_OBJ_TYPE);
4306 goto done;
4309 switch (type1) {
4310 case GOT_OBJ_TYPE_BLOB:
4311 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4312 diff_context, ignore_whitespace, repo, stdout);
4313 break;
4314 case GOT_OBJ_TYPE_TREE:
4315 error = got_diff_objects_as_trees(id1, id2, "", "",
4316 diff_context, ignore_whitespace, repo, stdout);
4317 break;
4318 case GOT_OBJ_TYPE_COMMIT:
4319 printf("diff %s %s\n", label1, label2);
4320 error = got_diff_objects_as_commits(id1, id2, diff_context,
4321 ignore_whitespace, repo, stdout);
4322 break;
4323 default:
4324 error = got_error(GOT_ERR_OBJ_TYPE);
4326 done:
4327 free(label1);
4328 free(label2);
4329 free(id1);
4330 free(id2);
4331 free(path);
4332 if (worktree)
4333 got_worktree_close(worktree);
4334 if (repo) {
4335 const struct got_error *repo_error;
4336 repo_error = got_repo_close(repo);
4337 if (error == NULL)
4338 error = repo_error;
4340 return error;
4343 __dead static void
4344 usage_blame(void)
4346 fprintf(stderr,
4347 "usage: %s blame [-c commit] [-r repository-path] path\n",
4348 getprogname());
4349 exit(1);
4352 struct blame_line {
4353 int annotated;
4354 char *id_str;
4355 char *committer;
4356 char datebuf[11]; /* YYYY-MM-DD + NUL */
4359 struct blame_cb_args {
4360 struct blame_line *lines;
4361 int nlines;
4362 int nlines_prec;
4363 int lineno_cur;
4364 off_t *line_offsets;
4365 FILE *f;
4366 struct got_repository *repo;
4369 static const struct got_error *
4370 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4372 const struct got_error *err = NULL;
4373 struct blame_cb_args *a = arg;
4374 struct blame_line *bline;
4375 char *line = NULL;
4376 size_t linesize = 0;
4377 struct got_commit_object *commit = NULL;
4378 off_t offset;
4379 struct tm tm;
4380 time_t committer_time;
4382 if (nlines != a->nlines ||
4383 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4384 return got_error(GOT_ERR_RANGE);
4386 if (sigint_received)
4387 return got_error(GOT_ERR_ITER_COMPLETED);
4389 if (lineno == -1)
4390 return NULL; /* no change in this commit */
4392 /* Annotate this line. */
4393 bline = &a->lines[lineno - 1];
4394 if (bline->annotated)
4395 return NULL;
4396 err = got_object_id_str(&bline->id_str, id);
4397 if (err)
4398 return err;
4400 err = got_object_open_as_commit(&commit, a->repo, id);
4401 if (err)
4402 goto done;
4404 bline->committer = strdup(got_object_commit_get_committer(commit));
4405 if (bline->committer == NULL) {
4406 err = got_error_from_errno("strdup");
4407 goto done;
4410 committer_time = got_object_commit_get_committer_time(commit);
4411 if (localtime_r(&committer_time, &tm) == NULL)
4412 return got_error_from_errno("localtime_r");
4413 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4414 &tm) >= sizeof(bline->datebuf)) {
4415 err = got_error(GOT_ERR_NO_SPACE);
4416 goto done;
4418 bline->annotated = 1;
4420 /* Print lines annotated so far. */
4421 bline = &a->lines[a->lineno_cur - 1];
4422 if (!bline->annotated)
4423 goto done;
4425 offset = a->line_offsets[a->lineno_cur - 1];
4426 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4427 err = got_error_from_errno("fseeko");
4428 goto done;
4431 while (bline->annotated) {
4432 char *smallerthan, *at, *nl, *committer;
4433 size_t len;
4435 if (getline(&line, &linesize, a->f) == -1) {
4436 if (ferror(a->f))
4437 err = got_error_from_errno("getline");
4438 break;
4441 committer = bline->committer;
4442 smallerthan = strchr(committer, '<');
4443 if (smallerthan && smallerthan[1] != '\0')
4444 committer = smallerthan + 1;
4445 at = strchr(committer, '@');
4446 if (at)
4447 *at = '\0';
4448 len = strlen(committer);
4449 if (len >= 9)
4450 committer[8] = '\0';
4452 nl = strchr(line, '\n');
4453 if (nl)
4454 *nl = '\0';
4455 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4456 bline->id_str, bline->datebuf, committer, line);
4458 a->lineno_cur++;
4459 bline = &a->lines[a->lineno_cur - 1];
4461 done:
4462 if (commit)
4463 got_object_commit_close(commit);
4464 free(line);
4465 return err;
4468 static const struct got_error *
4469 cmd_blame(int argc, char *argv[])
4471 const struct got_error *error;
4472 struct got_repository *repo = NULL;
4473 struct got_worktree *worktree = NULL;
4474 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4475 char *link_target = NULL;
4476 struct got_object_id *obj_id = NULL;
4477 struct got_object_id *commit_id = NULL;
4478 struct got_blob_object *blob = NULL;
4479 char *commit_id_str = NULL;
4480 struct blame_cb_args bca;
4481 int ch, obj_type, i;
4482 size_t filesize;
4484 memset(&bca, 0, sizeof(bca));
4486 #ifndef PROFILE
4487 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4488 NULL) == -1)
4489 err(1, "pledge");
4490 #endif
4492 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4493 switch (ch) {
4494 case 'c':
4495 commit_id_str = optarg;
4496 break;
4497 case 'r':
4498 repo_path = realpath(optarg, NULL);
4499 if (repo_path == NULL)
4500 return got_error_from_errno2("realpath",
4501 optarg);
4502 got_path_strip_trailing_slashes(repo_path);
4503 break;
4504 default:
4505 usage_blame();
4506 /* NOTREACHED */
4510 argc -= optind;
4511 argv += optind;
4513 if (argc == 1)
4514 path = argv[0];
4515 else
4516 usage_blame();
4518 cwd = getcwd(NULL, 0);
4519 if (cwd == NULL) {
4520 error = got_error_from_errno("getcwd");
4521 goto done;
4523 if (repo_path == NULL) {
4524 error = got_worktree_open(&worktree, cwd);
4525 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4526 goto done;
4527 else
4528 error = NULL;
4529 if (worktree) {
4530 repo_path =
4531 strdup(got_worktree_get_repo_path(worktree));
4532 if (repo_path == NULL) {
4533 error = got_error_from_errno("strdup");
4534 if (error)
4535 goto done;
4537 } else {
4538 repo_path = strdup(cwd);
4539 if (repo_path == NULL) {
4540 error = got_error_from_errno("strdup");
4541 goto done;
4546 error = got_repo_open(&repo, repo_path, NULL);
4547 if (error != NULL)
4548 goto done;
4550 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4551 if (error)
4552 goto done;
4554 if (worktree) {
4555 const char *prefix = got_worktree_get_path_prefix(worktree);
4556 char *p, *worktree_subdir = cwd +
4557 strlen(got_worktree_get_root_path(worktree));
4558 if (asprintf(&p, "%s%s%s%s%s",
4559 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4560 worktree_subdir, worktree_subdir[0] ? "/" : "",
4561 path) == -1) {
4562 error = got_error_from_errno("asprintf");
4563 goto done;
4565 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4566 free(p);
4567 } else {
4568 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4570 if (error)
4571 goto done;
4573 if (commit_id_str == NULL) {
4574 struct got_reference *head_ref;
4575 error = got_ref_open(&head_ref, repo, worktree ?
4576 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4577 if (error != NULL)
4578 goto done;
4579 error = got_ref_resolve(&commit_id, repo, head_ref);
4580 got_ref_close(head_ref);
4581 if (error != NULL)
4582 goto done;
4583 } else {
4584 error = got_repo_match_object_id(&commit_id, NULL,
4585 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4586 if (error)
4587 goto done;
4590 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4591 commit_id, repo);
4592 if (error)
4593 goto done;
4595 error = got_object_id_by_path(&obj_id, repo, commit_id,
4596 link_target ? link_target : in_repo_path);
4597 if (error)
4598 goto done;
4600 error = got_object_get_type(&obj_type, repo, obj_id);
4601 if (error)
4602 goto done;
4604 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4605 error = got_error_path(link_target ? link_target : in_repo_path,
4606 GOT_ERR_OBJ_TYPE);
4607 goto done;
4610 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4611 if (error)
4612 goto done;
4613 bca.f = got_opentemp();
4614 if (bca.f == NULL) {
4615 error = got_error_from_errno("got_opentemp");
4616 goto done;
4618 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4619 &bca.line_offsets, bca.f, blob);
4620 if (error || bca.nlines == 0)
4621 goto done;
4623 /* Don't include \n at EOF in the blame line count. */
4624 if (bca.line_offsets[bca.nlines - 1] == filesize)
4625 bca.nlines--;
4627 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4628 if (bca.lines == NULL) {
4629 error = got_error_from_errno("calloc");
4630 goto done;
4632 bca.lineno_cur = 1;
4633 bca.nlines_prec = 0;
4634 i = bca.nlines;
4635 while (i > 0) {
4636 i /= 10;
4637 bca.nlines_prec++;
4639 bca.repo = repo;
4641 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4642 repo, blame_cb, &bca, check_cancelled, NULL);
4643 done:
4644 free(in_repo_path);
4645 free(link_target);
4646 free(repo_path);
4647 free(cwd);
4648 free(commit_id);
4649 free(obj_id);
4650 if (blob)
4651 got_object_blob_close(blob);
4652 if (worktree)
4653 got_worktree_close(worktree);
4654 if (repo) {
4655 const struct got_error *repo_error;
4656 repo_error = got_repo_close(repo);
4657 if (error == NULL)
4658 error = repo_error;
4660 if (bca.lines) {
4661 for (i = 0; i < bca.nlines; i++) {
4662 struct blame_line *bline = &bca.lines[i];
4663 free(bline->id_str);
4664 free(bline->committer);
4666 free(bca.lines);
4668 free(bca.line_offsets);
4669 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4670 error = got_error_from_errno("fclose");
4671 return error;
4674 __dead static void
4675 usage_tree(void)
4677 fprintf(stderr,
4678 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4679 getprogname());
4680 exit(1);
4683 static const struct got_error *
4684 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4685 const char *root_path, struct got_repository *repo)
4687 const struct got_error *err = NULL;
4688 int is_root_path = (strcmp(path, root_path) == 0);
4689 const char *modestr = "";
4690 mode_t mode = got_tree_entry_get_mode(te);
4691 char *link_target = NULL;
4693 path += strlen(root_path);
4694 while (path[0] == '/')
4695 path++;
4697 if (got_object_tree_entry_is_submodule(te))
4698 modestr = "$";
4699 else if (S_ISLNK(mode)) {
4700 int i;
4702 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4703 if (err)
4704 return err;
4705 for (i = 0; i < strlen(link_target); i++) {
4706 if (!isprint((unsigned char)link_target[i]))
4707 link_target[i] = '?';
4710 modestr = "@";
4712 else if (S_ISDIR(mode))
4713 modestr = "/";
4714 else if (mode & S_IXUSR)
4715 modestr = "*";
4717 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4718 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4719 link_target ? " -> ": "", link_target ? link_target : "");
4721 free(link_target);
4722 return NULL;
4725 static const struct got_error *
4726 print_tree(const char *path, struct got_object_id *commit_id,
4727 int show_ids, int recurse, const char *root_path,
4728 struct got_repository *repo)
4730 const struct got_error *err = NULL;
4731 struct got_object_id *tree_id = NULL;
4732 struct got_tree_object *tree = NULL;
4733 int nentries, i;
4735 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4736 if (err)
4737 goto done;
4739 err = got_object_open_as_tree(&tree, repo, tree_id);
4740 if (err)
4741 goto done;
4742 nentries = got_object_tree_get_nentries(tree);
4743 for (i = 0; i < nentries; i++) {
4744 struct got_tree_entry *te;
4745 char *id = NULL;
4747 if (sigint_received || sigpipe_received)
4748 break;
4750 te = got_object_tree_get_entry(tree, i);
4751 if (show_ids) {
4752 char *id_str;
4753 err = got_object_id_str(&id_str,
4754 got_tree_entry_get_id(te));
4755 if (err)
4756 goto done;
4757 if (asprintf(&id, "%s ", id_str) == -1) {
4758 err = got_error_from_errno("asprintf");
4759 free(id_str);
4760 goto done;
4762 free(id_str);
4764 err = print_entry(te, id, path, root_path, repo);
4765 free(id);
4766 if (err)
4767 goto done;
4769 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4770 char *child_path;
4771 if (asprintf(&child_path, "%s%s%s", path,
4772 path[0] == '/' && path[1] == '\0' ? "" : "/",
4773 got_tree_entry_get_name(te)) == -1) {
4774 err = got_error_from_errno("asprintf");
4775 goto done;
4777 err = print_tree(child_path, commit_id, show_ids, 1,
4778 root_path, repo);
4779 free(child_path);
4780 if (err)
4781 goto done;
4784 done:
4785 if (tree)
4786 got_object_tree_close(tree);
4787 free(tree_id);
4788 return err;
4791 static const struct got_error *
4792 cmd_tree(int argc, char *argv[])
4794 const struct got_error *error;
4795 struct got_repository *repo = NULL;
4796 struct got_worktree *worktree = NULL;
4797 const char *path, *refname = NULL;
4798 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4799 struct got_object_id *commit_id = NULL;
4800 char *commit_id_str = NULL;
4801 int show_ids = 0, recurse = 0;
4802 int ch;
4804 #ifndef PROFILE
4805 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4806 NULL) == -1)
4807 err(1, "pledge");
4808 #endif
4810 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4811 switch (ch) {
4812 case 'c':
4813 commit_id_str = optarg;
4814 break;
4815 case 'r':
4816 repo_path = realpath(optarg, NULL);
4817 if (repo_path == NULL)
4818 return got_error_from_errno2("realpath",
4819 optarg);
4820 got_path_strip_trailing_slashes(repo_path);
4821 break;
4822 case 'i':
4823 show_ids = 1;
4824 break;
4825 case 'R':
4826 recurse = 1;
4827 break;
4828 default:
4829 usage_tree();
4830 /* NOTREACHED */
4834 argc -= optind;
4835 argv += optind;
4837 if (argc == 1)
4838 path = argv[0];
4839 else if (argc > 1)
4840 usage_tree();
4841 else
4842 path = NULL;
4844 cwd = getcwd(NULL, 0);
4845 if (cwd == NULL) {
4846 error = got_error_from_errno("getcwd");
4847 goto done;
4849 if (repo_path == NULL) {
4850 error = got_worktree_open(&worktree, cwd);
4851 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4852 goto done;
4853 else
4854 error = NULL;
4855 if (worktree) {
4856 repo_path =
4857 strdup(got_worktree_get_repo_path(worktree));
4858 if (repo_path == NULL)
4859 error = got_error_from_errno("strdup");
4860 if (error)
4861 goto done;
4862 } else {
4863 repo_path = strdup(cwd);
4864 if (repo_path == NULL) {
4865 error = got_error_from_errno("strdup");
4866 goto done;
4871 error = got_repo_open(&repo, repo_path, NULL);
4872 if (error != NULL)
4873 goto done;
4875 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4876 if (error)
4877 goto done;
4879 if (path == NULL) {
4880 if (worktree) {
4881 char *p, *worktree_subdir = cwd +
4882 strlen(got_worktree_get_root_path(worktree));
4883 if (asprintf(&p, "%s/%s",
4884 got_worktree_get_path_prefix(worktree),
4885 worktree_subdir) == -1) {
4886 error = got_error_from_errno("asprintf");
4887 goto done;
4889 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4890 free(p);
4891 if (error)
4892 goto done;
4893 } else
4894 path = "/";
4896 if (in_repo_path == NULL) {
4897 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4898 if (error != NULL)
4899 goto done;
4902 if (commit_id_str == NULL) {
4903 struct got_reference *head_ref;
4904 if (worktree)
4905 refname = got_worktree_get_head_ref_name(worktree);
4906 else
4907 refname = GOT_REF_HEAD;
4908 error = got_ref_open(&head_ref, repo, refname, 0);
4909 if (error != NULL)
4910 goto done;
4911 error = got_ref_resolve(&commit_id, repo, head_ref);
4912 got_ref_close(head_ref);
4913 if (error != NULL)
4914 goto done;
4915 } else {
4916 error = got_repo_match_object_id(&commit_id, NULL,
4917 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4918 if (error)
4919 goto done;
4922 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4923 in_repo_path, repo);
4924 done:
4925 free(in_repo_path);
4926 free(repo_path);
4927 free(cwd);
4928 free(commit_id);
4929 if (worktree)
4930 got_worktree_close(worktree);
4931 if (repo) {
4932 const struct got_error *repo_error;
4933 repo_error = got_repo_close(repo);
4934 if (error == NULL)
4935 error = repo_error;
4937 return error;
4940 __dead static void
4941 usage_status(void)
4943 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4944 getprogname());
4945 exit(1);
4948 static const struct got_error *
4949 print_status(void *arg, unsigned char status, unsigned char staged_status,
4950 const char *path, struct got_object_id *blob_id,
4951 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4952 int dirfd, const char *de_name)
4954 if (status == staged_status && (status == GOT_STATUS_DELETE))
4955 status = GOT_STATUS_NO_CHANGE;
4956 if (arg) {
4957 char *status_codes = arg;
4958 size_t ncodes = strlen(status_codes);
4959 int i;
4960 for (i = 0; i < ncodes ; i++) {
4961 if (status == status_codes[i] ||
4962 staged_status == status_codes[i])
4963 break;
4965 if (i == ncodes)
4966 return NULL;
4968 printf("%c%c %s\n", status, staged_status, path);
4969 return NULL;
4972 static const struct got_error *
4973 cmd_status(int argc, char *argv[])
4975 const struct got_error *error = NULL;
4976 struct got_repository *repo = NULL;
4977 struct got_worktree *worktree = NULL;
4978 char *cwd = NULL, *status_codes = NULL;;
4979 struct got_pathlist_head paths;
4980 struct got_pathlist_entry *pe;
4981 int ch, i;
4983 TAILQ_INIT(&paths);
4985 while ((ch = getopt(argc, argv, "s:")) != -1) {
4986 switch (ch) {
4987 case 's':
4988 for (i = 0; i < strlen(optarg); i++) {
4989 switch (optarg[i]) {
4990 case GOT_STATUS_MODIFY:
4991 case GOT_STATUS_ADD:
4992 case GOT_STATUS_DELETE:
4993 case GOT_STATUS_CONFLICT:
4994 case GOT_STATUS_MISSING:
4995 case GOT_STATUS_OBSTRUCTED:
4996 case GOT_STATUS_UNVERSIONED:
4997 case GOT_STATUS_MODE_CHANGE:
4998 case GOT_STATUS_NONEXISTENT:
4999 break;
5000 default:
5001 errx(1, "invalid status code '%c'",
5002 optarg[i]);
5005 status_codes = optarg;
5006 break;
5007 default:
5008 usage_status();
5009 /* NOTREACHED */
5013 argc -= optind;
5014 argv += optind;
5016 #ifndef PROFILE
5017 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5018 NULL) == -1)
5019 err(1, "pledge");
5020 #endif
5021 cwd = getcwd(NULL, 0);
5022 if (cwd == NULL) {
5023 error = got_error_from_errno("getcwd");
5024 goto done;
5027 error = got_worktree_open(&worktree, cwd);
5028 if (error) {
5029 if (error->code == GOT_ERR_NOT_WORKTREE)
5030 error = wrap_not_worktree_error(error, "status", cwd);
5031 goto done;
5034 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5035 NULL);
5036 if (error != NULL)
5037 goto done;
5039 error = apply_unveil(got_repo_get_path(repo), 1,
5040 got_worktree_get_root_path(worktree));
5041 if (error)
5042 goto done;
5044 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5045 if (error)
5046 goto done;
5048 error = got_worktree_status(worktree, &paths, repo, print_status,
5049 status_codes, check_cancelled, NULL);
5050 done:
5051 TAILQ_FOREACH(pe, &paths, entry)
5052 free((char *)pe->path);
5053 got_pathlist_free(&paths);
5054 free(cwd);
5055 return error;
5058 __dead static void
5059 usage_ref(void)
5061 fprintf(stderr,
5062 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5063 "[-d] [name]\n",
5064 getprogname());
5065 exit(1);
5068 static const struct got_error *
5069 list_refs(struct got_repository *repo, const char *refname)
5071 static const struct got_error *err = NULL;
5072 struct got_reflist_head refs;
5073 struct got_reflist_entry *re;
5075 SIMPLEQ_INIT(&refs);
5076 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5077 if (err)
5078 return err;
5080 SIMPLEQ_FOREACH(re, &refs, entry) {
5081 char *refstr;
5082 refstr = got_ref_to_str(re->ref);
5083 if (refstr == NULL)
5084 return got_error_from_errno("got_ref_to_str");
5085 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5086 free(refstr);
5089 got_ref_list_free(&refs);
5090 return NULL;
5093 static const struct got_error *
5094 delete_ref(struct got_repository *repo, const char *refname)
5096 const struct got_error *err = NULL;
5097 struct got_reference *ref;
5099 err = got_ref_open(&ref, repo, refname, 0);
5100 if (err)
5101 return err;
5103 err = got_ref_delete(ref, repo);
5104 got_ref_close(ref);
5105 return err;
5108 static const struct got_error *
5109 add_ref(struct got_repository *repo, const char *refname, const char *target)
5111 const struct got_error *err = NULL;
5112 struct got_object_id *id;
5113 struct got_reference *ref = NULL;
5116 * Don't let the user create a reference name with a leading '-'.
5117 * While technically a valid reference name, this case is usually
5118 * an unintended typo.
5120 if (refname[0] == '-')
5121 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5123 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5124 repo);
5125 if (err) {
5126 struct got_reference *target_ref;
5128 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5129 return err;
5130 err = got_ref_open(&target_ref, repo, target, 0);
5131 if (err)
5132 return err;
5133 err = got_ref_resolve(&id, repo, target_ref);
5134 got_ref_close(target_ref);
5135 if (err)
5136 return err;
5139 err = got_ref_alloc(&ref, refname, id);
5140 if (err)
5141 goto done;
5143 err = got_ref_write(ref, repo);
5144 done:
5145 if (ref)
5146 got_ref_close(ref);
5147 free(id);
5148 return err;
5151 static const struct got_error *
5152 add_symref(struct got_repository *repo, const char *refname, const char *target)
5154 const struct got_error *err = NULL;
5155 struct got_reference *ref = NULL;
5156 struct got_reference *target_ref = NULL;
5159 * Don't let the user create a reference name with a leading '-'.
5160 * While technically a valid reference name, this case is usually
5161 * an unintended typo.
5163 if (refname[0] == '-')
5164 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5166 err = got_ref_open(&target_ref, repo, target, 0);
5167 if (err)
5168 return err;
5170 err = got_ref_alloc_symref(&ref, refname, target_ref);
5171 if (err)
5172 goto done;
5174 err = got_ref_write(ref, repo);
5175 done:
5176 if (target_ref)
5177 got_ref_close(target_ref);
5178 if (ref)
5179 got_ref_close(ref);
5180 return err;
5183 static const struct got_error *
5184 cmd_ref(int argc, char *argv[])
5186 const struct got_error *error = NULL;
5187 struct got_repository *repo = NULL;
5188 struct got_worktree *worktree = NULL;
5189 char *cwd = NULL, *repo_path = NULL;
5190 int ch, do_list = 0, do_delete = 0;
5191 const char *obj_arg = NULL, *symref_target= NULL;
5192 char *refname = NULL;
5194 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5195 switch (ch) {
5196 case 'c':
5197 obj_arg = optarg;
5198 break;
5199 case 'd':
5200 do_delete = 1;
5201 break;
5202 case 'r':
5203 repo_path = realpath(optarg, NULL);
5204 if (repo_path == NULL)
5205 return got_error_from_errno2("realpath",
5206 optarg);
5207 got_path_strip_trailing_slashes(repo_path);
5208 break;
5209 case 'l':
5210 do_list = 1;
5211 break;
5212 case 's':
5213 symref_target = optarg;
5214 break;
5215 default:
5216 usage_ref();
5217 /* NOTREACHED */
5221 if (obj_arg && do_list)
5222 errx(1, "-c and -l options are mutually exclusive");
5223 if (obj_arg && do_delete)
5224 errx(1, "-c and -d options are mutually exclusive");
5225 if (obj_arg && symref_target)
5226 errx(1, "-c and -s options are mutually exclusive");
5227 if (symref_target && do_delete)
5228 errx(1, "-s and -d options are mutually exclusive");
5229 if (symref_target && do_list)
5230 errx(1, "-s and -l options are mutually exclusive");
5231 if (do_delete && do_list)
5232 errx(1, "-d and -l options are mutually exclusive");
5234 argc -= optind;
5235 argv += optind;
5237 if (do_list) {
5238 if (argc != 0 && argc != 1)
5239 usage_ref();
5240 if (argc == 1) {
5241 refname = strdup(argv[0]);
5242 if (refname == NULL) {
5243 error = got_error_from_errno("strdup");
5244 goto done;
5247 } else {
5248 if (argc != 1)
5249 usage_ref();
5250 refname = strdup(argv[0]);
5251 if (refname == NULL) {
5252 error = got_error_from_errno("strdup");
5253 goto done;
5257 if (refname)
5258 got_path_strip_trailing_slashes(refname);
5260 #ifndef PROFILE
5261 if (do_list) {
5262 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5263 NULL) == -1)
5264 err(1, "pledge");
5265 } else {
5266 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5267 "sendfd unveil", NULL) == -1)
5268 err(1, "pledge");
5270 #endif
5271 cwd = getcwd(NULL, 0);
5272 if (cwd == NULL) {
5273 error = got_error_from_errno("getcwd");
5274 goto done;
5277 if (repo_path == NULL) {
5278 error = got_worktree_open(&worktree, cwd);
5279 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5280 goto done;
5281 else
5282 error = NULL;
5283 if (worktree) {
5284 repo_path =
5285 strdup(got_worktree_get_repo_path(worktree));
5286 if (repo_path == NULL)
5287 error = got_error_from_errno("strdup");
5288 if (error)
5289 goto done;
5290 } else {
5291 repo_path = strdup(cwd);
5292 if (repo_path == NULL) {
5293 error = got_error_from_errno("strdup");
5294 goto done;
5299 error = got_repo_open(&repo, repo_path, NULL);
5300 if (error != NULL)
5301 goto done;
5303 error = apply_unveil(got_repo_get_path(repo), do_list,
5304 worktree ? got_worktree_get_root_path(worktree) : NULL);
5305 if (error)
5306 goto done;
5308 if (do_list)
5309 error = list_refs(repo, refname);
5310 else if (do_delete)
5311 error = delete_ref(repo, refname);
5312 else if (symref_target)
5313 error = add_symref(repo, refname, symref_target);
5314 else {
5315 if (obj_arg == NULL)
5316 usage_ref();
5317 error = add_ref(repo, refname, obj_arg);
5319 done:
5320 free(refname);
5321 if (repo)
5322 got_repo_close(repo);
5323 if (worktree)
5324 got_worktree_close(worktree);
5325 free(cwd);
5326 free(repo_path);
5327 return error;
5330 __dead static void
5331 usage_branch(void)
5333 fprintf(stderr,
5334 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5335 "[name]\n", getprogname());
5336 exit(1);
5339 static const struct got_error *
5340 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5341 struct got_reference *ref)
5343 const struct got_error *err = NULL;
5344 const char *refname, *marker = " ";
5345 char *refstr;
5347 refname = got_ref_get_name(ref);
5348 if (worktree && strcmp(refname,
5349 got_worktree_get_head_ref_name(worktree)) == 0) {
5350 struct got_object_id *id = NULL;
5352 err = got_ref_resolve(&id, repo, ref);
5353 if (err)
5354 return err;
5355 if (got_object_id_cmp(id,
5356 got_worktree_get_base_commit_id(worktree)) == 0)
5357 marker = "* ";
5358 else
5359 marker = "~ ";
5360 free(id);
5363 if (strncmp(refname, "refs/heads/", 11) == 0)
5364 refname += 11;
5365 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5366 refname += 18;
5368 refstr = got_ref_to_str(ref);
5369 if (refstr == NULL)
5370 return got_error_from_errno("got_ref_to_str");
5372 printf("%s%s: %s\n", marker, refname, refstr);
5373 free(refstr);
5374 return NULL;
5377 static const struct got_error *
5378 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5380 const char *refname;
5382 if (worktree == NULL)
5383 return got_error(GOT_ERR_NOT_WORKTREE);
5385 refname = got_worktree_get_head_ref_name(worktree);
5387 if (strncmp(refname, "refs/heads/", 11) == 0)
5388 refname += 11;
5389 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5390 refname += 18;
5392 printf("%s\n", refname);
5394 return NULL;
5397 static const struct got_error *
5398 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5400 static const struct got_error *err = NULL;
5401 struct got_reflist_head refs;
5402 struct got_reflist_entry *re;
5403 struct got_reference *temp_ref = NULL;
5404 int rebase_in_progress, histedit_in_progress;
5406 SIMPLEQ_INIT(&refs);
5408 if (worktree) {
5409 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5410 worktree);
5411 if (err)
5412 return err;
5414 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5415 worktree);
5416 if (err)
5417 return err;
5419 if (rebase_in_progress || histedit_in_progress) {
5420 err = got_ref_open(&temp_ref, repo,
5421 got_worktree_get_head_ref_name(worktree), 0);
5422 if (err)
5423 return err;
5424 list_branch(repo, worktree, temp_ref);
5425 got_ref_close(temp_ref);
5429 err = got_ref_list(&refs, repo, "refs/heads",
5430 got_ref_cmp_by_name, NULL);
5431 if (err)
5432 return err;
5434 SIMPLEQ_FOREACH(re, &refs, entry)
5435 list_branch(repo, worktree, re->ref);
5437 got_ref_list_free(&refs);
5438 return NULL;
5441 static const struct got_error *
5442 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5443 const char *branch_name)
5445 const struct got_error *err = NULL;
5446 struct got_reference *ref = NULL;
5447 char *refname;
5449 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5450 return got_error_from_errno("asprintf");
5452 err = got_ref_open(&ref, repo, refname, 0);
5453 if (err)
5454 goto done;
5456 if (worktree &&
5457 strcmp(got_worktree_get_head_ref_name(worktree),
5458 got_ref_get_name(ref)) == 0) {
5459 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5460 "will not delete this work tree's current branch");
5461 goto done;
5464 err = got_ref_delete(ref, repo);
5465 done:
5466 if (ref)
5467 got_ref_close(ref);
5468 free(refname);
5469 return err;
5472 static const struct got_error *
5473 add_branch(struct got_repository *repo, const char *branch_name,
5474 struct got_object_id *base_commit_id)
5476 const struct got_error *err = NULL;
5477 struct got_reference *ref = NULL;
5478 char *base_refname = NULL, *refname = NULL;
5481 * Don't let the user create a branch name with a leading '-'.
5482 * While technically a valid reference name, this case is usually
5483 * an unintended typo.
5485 if (branch_name[0] == '-')
5486 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5488 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5489 err = got_error_from_errno("asprintf");
5490 goto done;
5493 err = got_ref_open(&ref, repo, refname, 0);
5494 if (err == NULL) {
5495 err = got_error(GOT_ERR_BRANCH_EXISTS);
5496 goto done;
5497 } else if (err->code != GOT_ERR_NOT_REF)
5498 goto done;
5500 err = got_ref_alloc(&ref, refname, base_commit_id);
5501 if (err)
5502 goto done;
5504 err = got_ref_write(ref, repo);
5505 done:
5506 if (ref)
5507 got_ref_close(ref);
5508 free(base_refname);
5509 free(refname);
5510 return err;
5513 static const struct got_error *
5514 cmd_branch(int argc, char *argv[])
5516 const struct got_error *error = NULL;
5517 struct got_repository *repo = NULL;
5518 struct got_worktree *worktree = NULL;
5519 char *cwd = NULL, *repo_path = NULL;
5520 int ch, do_list = 0, do_show = 0, do_update = 1;
5521 const char *delref = NULL, *commit_id_arg = NULL;
5522 struct got_reference *ref = NULL;
5523 struct got_pathlist_head paths;
5524 struct got_pathlist_entry *pe;
5525 struct got_object_id *commit_id = NULL;
5526 char *commit_id_str = NULL;
5528 TAILQ_INIT(&paths);
5530 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5531 switch (ch) {
5532 case 'c':
5533 commit_id_arg = optarg;
5534 break;
5535 case 'd':
5536 delref = optarg;
5537 break;
5538 case 'r':
5539 repo_path = realpath(optarg, NULL);
5540 if (repo_path == NULL)
5541 return got_error_from_errno2("realpath",
5542 optarg);
5543 got_path_strip_trailing_slashes(repo_path);
5544 break;
5545 case 'l':
5546 do_list = 1;
5547 break;
5548 case 'n':
5549 do_update = 0;
5550 break;
5551 default:
5552 usage_branch();
5553 /* NOTREACHED */
5557 if (do_list && delref)
5558 errx(1, "-l and -d options are mutually exclusive");
5560 argc -= optind;
5561 argv += optind;
5563 if (!do_list && !delref && argc == 0)
5564 do_show = 1;
5566 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5567 errx(1, "-c option can only be used when creating a branch");
5569 if (do_list || delref) {
5570 if (argc > 0)
5571 usage_branch();
5572 } else if (!do_show && argc != 1)
5573 usage_branch();
5575 #ifndef PROFILE
5576 if (do_list || do_show) {
5577 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5578 NULL) == -1)
5579 err(1, "pledge");
5580 } else {
5581 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5582 "sendfd unveil", NULL) == -1)
5583 err(1, "pledge");
5585 #endif
5586 cwd = getcwd(NULL, 0);
5587 if (cwd == NULL) {
5588 error = got_error_from_errno("getcwd");
5589 goto done;
5592 if (repo_path == NULL) {
5593 error = got_worktree_open(&worktree, cwd);
5594 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5595 goto done;
5596 else
5597 error = NULL;
5598 if (worktree) {
5599 repo_path =
5600 strdup(got_worktree_get_repo_path(worktree));
5601 if (repo_path == NULL)
5602 error = got_error_from_errno("strdup");
5603 if (error)
5604 goto done;
5605 } else {
5606 repo_path = strdup(cwd);
5607 if (repo_path == NULL) {
5608 error = got_error_from_errno("strdup");
5609 goto done;
5614 error = got_repo_open(&repo, repo_path, NULL);
5615 if (error != NULL)
5616 goto done;
5618 error = apply_unveil(got_repo_get_path(repo), do_list,
5619 worktree ? got_worktree_get_root_path(worktree) : NULL);
5620 if (error)
5621 goto done;
5623 if (do_show)
5624 error = show_current_branch(repo, worktree);
5625 else if (do_list)
5626 error = list_branches(repo, worktree);
5627 else if (delref)
5628 error = delete_branch(repo, worktree, delref);
5629 else {
5630 if (commit_id_arg == NULL)
5631 commit_id_arg = worktree ?
5632 got_worktree_get_head_ref_name(worktree) :
5633 GOT_REF_HEAD;
5634 error = got_repo_match_object_id(&commit_id, NULL,
5635 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5636 if (error)
5637 goto done;
5638 error = add_branch(repo, argv[0], commit_id);
5639 if (error)
5640 goto done;
5641 if (worktree && do_update) {
5642 struct got_update_progress_arg upa;
5643 char *branch_refname = NULL;
5645 error = got_object_id_str(&commit_id_str, commit_id);
5646 if (error)
5647 goto done;
5648 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5649 worktree);
5650 if (error)
5651 goto done;
5652 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5653 == -1) {
5654 error = got_error_from_errno("asprintf");
5655 goto done;
5657 error = got_ref_open(&ref, repo, branch_refname, 0);
5658 free(branch_refname);
5659 if (error)
5660 goto done;
5661 error = switch_head_ref(ref, commit_id, worktree,
5662 repo);
5663 if (error)
5664 goto done;
5665 error = got_worktree_set_base_commit_id(worktree, repo,
5666 commit_id);
5667 if (error)
5668 goto done;
5669 memset(&upa, 0, sizeof(upa));
5670 error = got_worktree_checkout_files(worktree, &paths,
5671 repo, update_progress, &upa, check_cancelled,
5672 NULL);
5673 if (error)
5674 goto done;
5675 if (upa.did_something)
5676 printf("Updated to commit %s\n", commit_id_str);
5677 print_update_progress_stats(&upa);
5680 done:
5681 if (ref)
5682 got_ref_close(ref);
5683 if (repo)
5684 got_repo_close(repo);
5685 if (worktree)
5686 got_worktree_close(worktree);
5687 free(cwd);
5688 free(repo_path);
5689 free(commit_id);
5690 free(commit_id_str);
5691 TAILQ_FOREACH(pe, &paths, entry)
5692 free((char *)pe->path);
5693 got_pathlist_free(&paths);
5694 return error;
5698 __dead static void
5699 usage_tag(void)
5701 fprintf(stderr,
5702 "usage: %s tag [-c commit] [-r repository] [-l] "
5703 "[-m message] name\n", getprogname());
5704 exit(1);
5707 #if 0
5708 static const struct got_error *
5709 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5711 const struct got_error *err = NULL;
5712 struct got_reflist_entry *re, *se, *new;
5713 struct got_object_id *re_id, *se_id;
5714 struct got_tag_object *re_tag, *se_tag;
5715 time_t re_time, se_time;
5717 SIMPLEQ_FOREACH(re, tags, entry) {
5718 se = SIMPLEQ_FIRST(sorted);
5719 if (se == NULL) {
5720 err = got_reflist_entry_dup(&new, re);
5721 if (err)
5722 return err;
5723 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5724 continue;
5725 } else {
5726 err = got_ref_resolve(&re_id, repo, re->ref);
5727 if (err)
5728 break;
5729 err = got_object_open_as_tag(&re_tag, repo, re_id);
5730 free(re_id);
5731 if (err)
5732 break;
5733 re_time = got_object_tag_get_tagger_time(re_tag);
5734 got_object_tag_close(re_tag);
5737 while (se) {
5738 err = got_ref_resolve(&se_id, repo, re->ref);
5739 if (err)
5740 break;
5741 err = got_object_open_as_tag(&se_tag, repo, se_id);
5742 free(se_id);
5743 if (err)
5744 break;
5745 se_time = got_object_tag_get_tagger_time(se_tag);
5746 got_object_tag_close(se_tag);
5748 if (se_time > re_time) {
5749 err = got_reflist_entry_dup(&new, re);
5750 if (err)
5751 return err;
5752 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5753 break;
5755 se = SIMPLEQ_NEXT(se, entry);
5756 continue;
5759 done:
5760 return err;
5762 #endif
5764 static const struct got_error *
5765 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5767 static const struct got_error *err = NULL;
5768 struct got_reflist_head refs;
5769 struct got_reflist_entry *re;
5771 SIMPLEQ_INIT(&refs);
5773 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5774 if (err)
5775 return err;
5777 SIMPLEQ_FOREACH(re, &refs, entry) {
5778 const char *refname;
5779 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5780 char datebuf[26];
5781 const char *tagger;
5782 time_t tagger_time;
5783 struct got_object_id *id;
5784 struct got_tag_object *tag;
5785 struct got_commit_object *commit = NULL;
5787 refname = got_ref_get_name(re->ref);
5788 if (strncmp(refname, "refs/tags/", 10) != 0)
5789 continue;
5790 refname += 10;
5791 refstr = got_ref_to_str(re->ref);
5792 if (refstr == NULL) {
5793 err = got_error_from_errno("got_ref_to_str");
5794 break;
5796 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5797 free(refstr);
5799 err = got_ref_resolve(&id, repo, re->ref);
5800 if (err)
5801 break;
5802 err = got_object_open_as_tag(&tag, repo, id);
5803 if (err) {
5804 if (err->code != GOT_ERR_OBJ_TYPE) {
5805 free(id);
5806 break;
5808 /* "lightweight" tag */
5809 err = got_object_open_as_commit(&commit, repo, id);
5810 if (err) {
5811 free(id);
5812 break;
5814 tagger = got_object_commit_get_committer(commit);
5815 tagger_time =
5816 got_object_commit_get_committer_time(commit);
5817 err = got_object_id_str(&id_str, id);
5818 free(id);
5819 if (err)
5820 break;
5821 } else {
5822 free(id);
5823 tagger = got_object_tag_get_tagger(tag);
5824 tagger_time = got_object_tag_get_tagger_time(tag);
5825 err = got_object_id_str(&id_str,
5826 got_object_tag_get_object_id(tag));
5827 if (err)
5828 break;
5830 printf("from: %s\n", tagger);
5831 datestr = get_datestr(&tagger_time, datebuf);
5832 if (datestr)
5833 printf("date: %s UTC\n", datestr);
5834 if (commit)
5835 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5836 else {
5837 switch (got_object_tag_get_object_type(tag)) {
5838 case GOT_OBJ_TYPE_BLOB:
5839 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5840 id_str);
5841 break;
5842 case GOT_OBJ_TYPE_TREE:
5843 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5844 id_str);
5845 break;
5846 case GOT_OBJ_TYPE_COMMIT:
5847 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5848 id_str);
5849 break;
5850 case GOT_OBJ_TYPE_TAG:
5851 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5852 id_str);
5853 break;
5854 default:
5855 break;
5858 free(id_str);
5859 if (commit) {
5860 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5861 if (err)
5862 break;
5863 got_object_commit_close(commit);
5864 } else {
5865 tagmsg0 = strdup(got_object_tag_get_message(tag));
5866 got_object_tag_close(tag);
5867 if (tagmsg0 == NULL) {
5868 err = got_error_from_errno("strdup");
5869 break;
5873 tagmsg = tagmsg0;
5874 do {
5875 line = strsep(&tagmsg, "\n");
5876 if (line)
5877 printf(" %s\n", line);
5878 } while (line);
5879 free(tagmsg0);
5882 got_ref_list_free(&refs);
5883 return NULL;
5886 static const struct got_error *
5887 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5888 const char *tag_name, const char *repo_path)
5890 const struct got_error *err = NULL;
5891 char *template = NULL, *initial_content = NULL;
5892 char *editor = NULL;
5893 int initial_content_len;
5894 int fd = -1;
5896 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5897 err = got_error_from_errno("asprintf");
5898 goto done;
5901 initial_content_len = asprintf(&initial_content,
5902 "\n# tagging commit %s as %s\n",
5903 commit_id_str, tag_name);
5904 if (initial_content_len == -1) {
5905 err = got_error_from_errno("asprintf");
5906 goto done;
5909 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5910 if (err)
5911 goto done;
5913 if (write(fd, initial_content, initial_content_len) == -1) {
5914 err = got_error_from_errno2("write", *tagmsg_path);
5915 goto done;
5918 err = get_editor(&editor);
5919 if (err)
5920 goto done;
5921 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5922 initial_content_len);
5923 done:
5924 free(initial_content);
5925 free(template);
5926 free(editor);
5928 if (fd != -1 && close(fd) == -1 && err == NULL)
5929 err = got_error_from_errno2("close", *tagmsg_path);
5931 /* Editor is done; we can now apply unveil(2) */
5932 if (err == NULL)
5933 err = apply_unveil(repo_path, 0, NULL);
5934 if (err) {
5935 free(*tagmsg);
5936 *tagmsg = NULL;
5938 return err;
5941 static const struct got_error *
5942 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5943 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5945 const struct got_error *err = NULL;
5946 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5947 char *label = NULL, *commit_id_str = NULL;
5948 struct got_reference *ref = NULL;
5949 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5950 char *tagmsg_path = NULL, *tag_id_str = NULL;
5951 int preserve_tagmsg = 0;
5954 * Don't let the user create a tag name with a leading '-'.
5955 * While technically a valid reference name, this case is usually
5956 * an unintended typo.
5958 if (tag_name[0] == '-')
5959 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5961 err = get_author(&tagger, repo, worktree);
5962 if (err)
5963 return err;
5965 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5966 GOT_OBJ_TYPE_COMMIT, 1, repo);
5967 if (err)
5968 goto done;
5970 err = got_object_id_str(&commit_id_str, commit_id);
5971 if (err)
5972 goto done;
5974 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5975 refname = strdup(tag_name);
5976 if (refname == NULL) {
5977 err = got_error_from_errno("strdup");
5978 goto done;
5980 tag_name += 10;
5981 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5982 err = got_error_from_errno("asprintf");
5983 goto done;
5986 err = got_ref_open(&ref, repo, refname, 0);
5987 if (err == NULL) {
5988 err = got_error(GOT_ERR_TAG_EXISTS);
5989 goto done;
5990 } else if (err->code != GOT_ERR_NOT_REF)
5991 goto done;
5993 if (tagmsg_arg == NULL) {
5994 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5995 tag_name, got_repo_get_path(repo));
5996 if (err) {
5997 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5998 tagmsg_path != NULL)
5999 preserve_tagmsg = 1;
6000 goto done;
6004 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6005 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6006 if (err) {
6007 if (tagmsg_path)
6008 preserve_tagmsg = 1;
6009 goto done;
6012 err = got_ref_alloc(&ref, refname, tag_id);
6013 if (err) {
6014 if (tagmsg_path)
6015 preserve_tagmsg = 1;
6016 goto done;
6019 err = got_ref_write(ref, repo);
6020 if (err) {
6021 if (tagmsg_path)
6022 preserve_tagmsg = 1;
6023 goto done;
6026 err = got_object_id_str(&tag_id_str, tag_id);
6027 if (err) {
6028 if (tagmsg_path)
6029 preserve_tagmsg = 1;
6030 goto done;
6032 printf("Created tag %s\n", tag_id_str);
6033 done:
6034 if (preserve_tagmsg) {
6035 fprintf(stderr, "%s: tag message preserved in %s\n",
6036 getprogname(), tagmsg_path);
6037 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6038 err = got_error_from_errno2("unlink", tagmsg_path);
6039 free(tag_id_str);
6040 if (ref)
6041 got_ref_close(ref);
6042 free(commit_id);
6043 free(commit_id_str);
6044 free(refname);
6045 free(tagmsg);
6046 free(tagmsg_path);
6047 free(tagger);
6048 return err;
6051 static const struct got_error *
6052 cmd_tag(int argc, char *argv[])
6054 const struct got_error *error = NULL;
6055 struct got_repository *repo = NULL;
6056 struct got_worktree *worktree = NULL;
6057 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6058 char *gitconfig_path = NULL;
6059 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6060 int ch, do_list = 0;
6062 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6063 switch (ch) {
6064 case 'c':
6065 commit_id_arg = optarg;
6066 break;
6067 case 'm':
6068 tagmsg = optarg;
6069 break;
6070 case 'r':
6071 repo_path = realpath(optarg, NULL);
6072 if (repo_path == NULL)
6073 return got_error_from_errno2("realpath",
6074 optarg);
6075 got_path_strip_trailing_slashes(repo_path);
6076 break;
6077 case 'l':
6078 do_list = 1;
6079 break;
6080 default:
6081 usage_tag();
6082 /* NOTREACHED */
6086 argc -= optind;
6087 argv += optind;
6089 if (do_list) {
6090 if (commit_id_arg != NULL)
6091 errx(1,
6092 "-c option can only be used when creating a tag");
6093 if (tagmsg)
6094 errx(1, "-l and -m options are mutually exclusive");
6095 if (argc > 0)
6096 usage_tag();
6097 } else if (argc != 1)
6098 usage_tag();
6100 tag_name = argv[0];
6102 #ifndef PROFILE
6103 if (do_list) {
6104 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6105 NULL) == -1)
6106 err(1, "pledge");
6107 } else {
6108 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6109 "sendfd unveil", NULL) == -1)
6110 err(1, "pledge");
6112 #endif
6113 cwd = getcwd(NULL, 0);
6114 if (cwd == NULL) {
6115 error = got_error_from_errno("getcwd");
6116 goto done;
6119 if (repo_path == NULL) {
6120 error = got_worktree_open(&worktree, cwd);
6121 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6122 goto done;
6123 else
6124 error = NULL;
6125 if (worktree) {
6126 repo_path =
6127 strdup(got_worktree_get_repo_path(worktree));
6128 if (repo_path == NULL)
6129 error = got_error_from_errno("strdup");
6130 if (error)
6131 goto done;
6132 } else {
6133 repo_path = strdup(cwd);
6134 if (repo_path == NULL) {
6135 error = got_error_from_errno("strdup");
6136 goto done;
6141 if (do_list) {
6142 error = got_repo_open(&repo, repo_path, NULL);
6143 if (error != NULL)
6144 goto done;
6145 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6146 if (error)
6147 goto done;
6148 error = list_tags(repo, worktree);
6149 } else {
6150 error = get_gitconfig_path(&gitconfig_path);
6151 if (error)
6152 goto done;
6153 error = got_repo_open(&repo, repo_path, gitconfig_path);
6154 if (error != NULL)
6155 goto done;
6157 if (tagmsg) {
6158 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6159 if (error)
6160 goto done;
6163 if (commit_id_arg == NULL) {
6164 struct got_reference *head_ref;
6165 struct got_object_id *commit_id;
6166 error = got_ref_open(&head_ref, repo,
6167 worktree ? got_worktree_get_head_ref_name(worktree)
6168 : GOT_REF_HEAD, 0);
6169 if (error)
6170 goto done;
6171 error = got_ref_resolve(&commit_id, repo, head_ref);
6172 got_ref_close(head_ref);
6173 if (error)
6174 goto done;
6175 error = got_object_id_str(&commit_id_str, commit_id);
6176 free(commit_id);
6177 if (error)
6178 goto done;
6181 error = add_tag(repo, worktree, tag_name,
6182 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6184 done:
6185 if (repo)
6186 got_repo_close(repo);
6187 if (worktree)
6188 got_worktree_close(worktree);
6189 free(cwd);
6190 free(repo_path);
6191 free(gitconfig_path);
6192 free(commit_id_str);
6193 return error;
6196 __dead static void
6197 usage_add(void)
6199 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6200 getprogname());
6201 exit(1);
6204 static const struct got_error *
6205 add_progress(void *arg, unsigned char status, const char *path)
6207 while (path[0] == '/')
6208 path++;
6209 printf("%c %s\n", status, path);
6210 return NULL;
6213 static const struct got_error *
6214 cmd_add(int argc, char *argv[])
6216 const struct got_error *error = NULL;
6217 struct got_repository *repo = NULL;
6218 struct got_worktree *worktree = NULL;
6219 char *cwd = NULL;
6220 struct got_pathlist_head paths;
6221 struct got_pathlist_entry *pe;
6222 int ch, can_recurse = 0, no_ignores = 0;
6224 TAILQ_INIT(&paths);
6226 while ((ch = getopt(argc, argv, "IR")) != -1) {
6227 switch (ch) {
6228 case 'I':
6229 no_ignores = 1;
6230 break;
6231 case 'R':
6232 can_recurse = 1;
6233 break;
6234 default:
6235 usage_add();
6236 /* NOTREACHED */
6240 argc -= optind;
6241 argv += optind;
6243 #ifndef PROFILE
6244 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6245 NULL) == -1)
6246 err(1, "pledge");
6247 #endif
6248 if (argc < 1)
6249 usage_add();
6251 cwd = getcwd(NULL, 0);
6252 if (cwd == NULL) {
6253 error = got_error_from_errno("getcwd");
6254 goto done;
6257 error = got_worktree_open(&worktree, cwd);
6258 if (error) {
6259 if (error->code == GOT_ERR_NOT_WORKTREE)
6260 error = wrap_not_worktree_error(error, "add", cwd);
6261 goto done;
6264 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6265 NULL);
6266 if (error != NULL)
6267 goto done;
6269 error = apply_unveil(got_repo_get_path(repo), 1,
6270 got_worktree_get_root_path(worktree));
6271 if (error)
6272 goto done;
6274 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6275 if (error)
6276 goto done;
6278 if (!can_recurse && no_ignores) {
6279 error = got_error_msg(GOT_ERR_BAD_PATH,
6280 "disregarding ignores requires -R option");
6281 goto done;
6285 if (!can_recurse) {
6286 char *ondisk_path;
6287 struct stat sb;
6288 TAILQ_FOREACH(pe, &paths, entry) {
6289 if (asprintf(&ondisk_path, "%s/%s",
6290 got_worktree_get_root_path(worktree),
6291 pe->path) == -1) {
6292 error = got_error_from_errno("asprintf");
6293 goto done;
6295 if (lstat(ondisk_path, &sb) == -1) {
6296 if (errno == ENOENT) {
6297 free(ondisk_path);
6298 continue;
6300 error = got_error_from_errno2("lstat",
6301 ondisk_path);
6302 free(ondisk_path);
6303 goto done;
6305 free(ondisk_path);
6306 if (S_ISDIR(sb.st_mode)) {
6307 error = got_error_msg(GOT_ERR_BAD_PATH,
6308 "adding directories requires -R option");
6309 goto done;
6314 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6315 NULL, repo, no_ignores);
6316 done:
6317 if (repo)
6318 got_repo_close(repo);
6319 if (worktree)
6320 got_worktree_close(worktree);
6321 TAILQ_FOREACH(pe, &paths, entry)
6322 free((char *)pe->path);
6323 got_pathlist_free(&paths);
6324 free(cwd);
6325 return error;
6328 __dead static void
6329 usage_remove(void)
6331 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6332 "path ...\n", getprogname());
6333 exit(1);
6336 static const struct got_error *
6337 print_remove_status(void *arg, unsigned char status,
6338 unsigned char staged_status, const char *path)
6340 while (path[0] == '/')
6341 path++;
6342 if (status == GOT_STATUS_NONEXISTENT)
6343 return NULL;
6344 if (status == staged_status && (status == GOT_STATUS_DELETE))
6345 status = GOT_STATUS_NO_CHANGE;
6346 printf("%c%c %s\n", status, staged_status, path);
6347 return NULL;
6350 static const struct got_error *
6351 cmd_remove(int argc, char *argv[])
6353 const struct got_error *error = NULL;
6354 struct got_worktree *worktree = NULL;
6355 struct got_repository *repo = NULL;
6356 const char *status_codes = NULL;
6357 char *cwd = NULL;
6358 struct got_pathlist_head paths;
6359 struct got_pathlist_entry *pe;
6360 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6362 TAILQ_INIT(&paths);
6364 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6365 switch (ch) {
6366 case 'f':
6367 delete_local_mods = 1;
6368 break;
6369 case 'k':
6370 keep_on_disk = 1;
6371 break;
6372 case 'R':
6373 can_recurse = 1;
6374 break;
6375 case 's':
6376 for (i = 0; i < strlen(optarg); i++) {
6377 switch (optarg[i]) {
6378 case GOT_STATUS_MODIFY:
6379 delete_local_mods = 1;
6380 break;
6381 case GOT_STATUS_MISSING:
6382 break;
6383 default:
6384 errx(1, "invalid status code '%c'",
6385 optarg[i]);
6388 status_codes = optarg;
6389 break;
6390 default:
6391 usage_remove();
6392 /* NOTREACHED */
6396 argc -= optind;
6397 argv += optind;
6399 #ifndef PROFILE
6400 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6401 NULL) == -1)
6402 err(1, "pledge");
6403 #endif
6404 if (argc < 1)
6405 usage_remove();
6407 cwd = getcwd(NULL, 0);
6408 if (cwd == NULL) {
6409 error = got_error_from_errno("getcwd");
6410 goto done;
6412 error = got_worktree_open(&worktree, cwd);
6413 if (error) {
6414 if (error->code == GOT_ERR_NOT_WORKTREE)
6415 error = wrap_not_worktree_error(error, "remove", cwd);
6416 goto done;
6419 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6420 NULL);
6421 if (error)
6422 goto done;
6424 error = apply_unveil(got_repo_get_path(repo), 1,
6425 got_worktree_get_root_path(worktree));
6426 if (error)
6427 goto done;
6429 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6430 if (error)
6431 goto done;
6433 if (!can_recurse) {
6434 char *ondisk_path;
6435 struct stat sb;
6436 TAILQ_FOREACH(pe, &paths, entry) {
6437 if (asprintf(&ondisk_path, "%s/%s",
6438 got_worktree_get_root_path(worktree),
6439 pe->path) == -1) {
6440 error = got_error_from_errno("asprintf");
6441 goto done;
6443 if (lstat(ondisk_path, &sb) == -1) {
6444 if (errno == ENOENT) {
6445 free(ondisk_path);
6446 continue;
6448 error = got_error_from_errno2("lstat",
6449 ondisk_path);
6450 free(ondisk_path);
6451 goto done;
6453 free(ondisk_path);
6454 if (S_ISDIR(sb.st_mode)) {
6455 error = got_error_msg(GOT_ERR_BAD_PATH,
6456 "removing directories requires -R option");
6457 goto done;
6462 error = got_worktree_schedule_delete(worktree, &paths,
6463 delete_local_mods, status_codes, print_remove_status, NULL,
6464 repo, keep_on_disk);
6465 done:
6466 if (repo)
6467 got_repo_close(repo);
6468 if (worktree)
6469 got_worktree_close(worktree);
6470 TAILQ_FOREACH(pe, &paths, entry)
6471 free((char *)pe->path);
6472 got_pathlist_free(&paths);
6473 free(cwd);
6474 return error;
6477 __dead static void
6478 usage_revert(void)
6480 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6481 "path ...\n", getprogname());
6482 exit(1);
6485 static const struct got_error *
6486 revert_progress(void *arg, unsigned char status, const char *path)
6488 if (status == GOT_STATUS_UNVERSIONED)
6489 return NULL;
6491 while (path[0] == '/')
6492 path++;
6493 printf("%c %s\n", status, path);
6494 return NULL;
6497 struct choose_patch_arg {
6498 FILE *patch_script_file;
6499 const char *action;
6502 static const struct got_error *
6503 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6504 int nchanges, const char *action)
6506 char *line = NULL;
6507 size_t linesize = 0;
6508 ssize_t linelen;
6510 switch (status) {
6511 case GOT_STATUS_ADD:
6512 printf("A %s\n%s this addition? [y/n] ", path, action);
6513 break;
6514 case GOT_STATUS_DELETE:
6515 printf("D %s\n%s this deletion? [y/n] ", path, action);
6516 break;
6517 case GOT_STATUS_MODIFY:
6518 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6519 return got_error_from_errno("fseek");
6520 printf(GOT_COMMIT_SEP_STR);
6521 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6522 printf("%s", line);
6523 if (ferror(patch_file))
6524 return got_error_from_errno("getline");
6525 printf(GOT_COMMIT_SEP_STR);
6526 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6527 path, n, nchanges, action);
6528 break;
6529 default:
6530 return got_error_path(path, GOT_ERR_FILE_STATUS);
6533 return NULL;
6536 static const struct got_error *
6537 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6538 FILE *patch_file, int n, int nchanges)
6540 const struct got_error *err = NULL;
6541 char *line = NULL;
6542 size_t linesize = 0;
6543 ssize_t linelen;
6544 int resp = ' ';
6545 struct choose_patch_arg *a = arg;
6547 *choice = GOT_PATCH_CHOICE_NONE;
6549 if (a->patch_script_file) {
6550 char *nl;
6551 err = show_change(status, path, patch_file, n, nchanges,
6552 a->action);
6553 if (err)
6554 return err;
6555 linelen = getline(&line, &linesize, a->patch_script_file);
6556 if (linelen == -1) {
6557 if (ferror(a->patch_script_file))
6558 return got_error_from_errno("getline");
6559 return NULL;
6561 nl = strchr(line, '\n');
6562 if (nl)
6563 *nl = '\0';
6564 if (strcmp(line, "y") == 0) {
6565 *choice = GOT_PATCH_CHOICE_YES;
6566 printf("y\n");
6567 } else if (strcmp(line, "n") == 0) {
6568 *choice = GOT_PATCH_CHOICE_NO;
6569 printf("n\n");
6570 } else if (strcmp(line, "q") == 0 &&
6571 status == GOT_STATUS_MODIFY) {
6572 *choice = GOT_PATCH_CHOICE_QUIT;
6573 printf("q\n");
6574 } else
6575 printf("invalid response '%s'\n", line);
6576 free(line);
6577 return NULL;
6580 while (resp != 'y' && resp != 'n' && resp != 'q') {
6581 err = show_change(status, path, patch_file, n, nchanges,
6582 a->action);
6583 if (err)
6584 return err;
6585 resp = getchar();
6586 if (resp == '\n')
6587 resp = getchar();
6588 if (status == GOT_STATUS_MODIFY) {
6589 if (resp != 'y' && resp != 'n' && resp != 'q') {
6590 printf("invalid response '%c'\n", resp);
6591 resp = ' ';
6593 } else if (resp != 'y' && resp != 'n') {
6594 printf("invalid response '%c'\n", resp);
6595 resp = ' ';
6599 if (resp == 'y')
6600 *choice = GOT_PATCH_CHOICE_YES;
6601 else if (resp == 'n')
6602 *choice = GOT_PATCH_CHOICE_NO;
6603 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6604 *choice = GOT_PATCH_CHOICE_QUIT;
6606 return NULL;
6610 static const struct got_error *
6611 cmd_revert(int argc, char *argv[])
6613 const struct got_error *error = NULL;
6614 struct got_worktree *worktree = NULL;
6615 struct got_repository *repo = NULL;
6616 char *cwd = NULL, *path = NULL;
6617 struct got_pathlist_head paths;
6618 struct got_pathlist_entry *pe;
6619 int ch, can_recurse = 0, pflag = 0;
6620 FILE *patch_script_file = NULL;
6621 const char *patch_script_path = NULL;
6622 struct choose_patch_arg cpa;
6624 TAILQ_INIT(&paths);
6626 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6627 switch (ch) {
6628 case 'p':
6629 pflag = 1;
6630 break;
6631 case 'F':
6632 patch_script_path = optarg;
6633 break;
6634 case 'R':
6635 can_recurse = 1;
6636 break;
6637 default:
6638 usage_revert();
6639 /* NOTREACHED */
6643 argc -= optind;
6644 argv += optind;
6646 #ifndef PROFILE
6647 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6648 "unveil", NULL) == -1)
6649 err(1, "pledge");
6650 #endif
6651 if (argc < 1)
6652 usage_revert();
6653 if (patch_script_path && !pflag)
6654 errx(1, "-F option can only be used together with -p option");
6656 cwd = getcwd(NULL, 0);
6657 if (cwd == NULL) {
6658 error = got_error_from_errno("getcwd");
6659 goto done;
6661 error = got_worktree_open(&worktree, cwd);
6662 if (error) {
6663 if (error->code == GOT_ERR_NOT_WORKTREE)
6664 error = wrap_not_worktree_error(error, "revert", cwd);
6665 goto done;
6668 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6669 NULL);
6670 if (error != NULL)
6671 goto done;
6673 if (patch_script_path) {
6674 patch_script_file = fopen(patch_script_path, "r");
6675 if (patch_script_file == NULL) {
6676 error = got_error_from_errno2("fopen",
6677 patch_script_path);
6678 goto done;
6681 error = apply_unveil(got_repo_get_path(repo), 1,
6682 got_worktree_get_root_path(worktree));
6683 if (error)
6684 goto done;
6686 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6687 if (error)
6688 goto done;
6690 if (!can_recurse) {
6691 char *ondisk_path;
6692 struct stat sb;
6693 TAILQ_FOREACH(pe, &paths, entry) {
6694 if (asprintf(&ondisk_path, "%s/%s",
6695 got_worktree_get_root_path(worktree),
6696 pe->path) == -1) {
6697 error = got_error_from_errno("asprintf");
6698 goto done;
6700 if (lstat(ondisk_path, &sb) == -1) {
6701 if (errno == ENOENT) {
6702 free(ondisk_path);
6703 continue;
6705 error = got_error_from_errno2("lstat",
6706 ondisk_path);
6707 free(ondisk_path);
6708 goto done;
6710 free(ondisk_path);
6711 if (S_ISDIR(sb.st_mode)) {
6712 error = got_error_msg(GOT_ERR_BAD_PATH,
6713 "reverting directories requires -R option");
6714 goto done;
6719 cpa.patch_script_file = patch_script_file;
6720 cpa.action = "revert";
6721 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6722 pflag ? choose_patch : NULL, &cpa, repo);
6723 done:
6724 if (patch_script_file && fclose(patch_script_file) == EOF &&
6725 error == NULL)
6726 error = got_error_from_errno2("fclose", patch_script_path);
6727 if (repo)
6728 got_repo_close(repo);
6729 if (worktree)
6730 got_worktree_close(worktree);
6731 free(path);
6732 free(cwd);
6733 return error;
6736 __dead static void
6737 usage_commit(void)
6739 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6740 getprogname());
6741 exit(1);
6744 struct collect_commit_logmsg_arg {
6745 const char *cmdline_log;
6746 const char *editor;
6747 const char *worktree_path;
6748 const char *branch_name;
6749 const char *repo_path;
6750 char *logmsg_path;
6754 static const struct got_error *
6755 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6756 void *arg)
6758 char *initial_content = NULL;
6759 struct got_pathlist_entry *pe;
6760 const struct got_error *err = NULL;
6761 char *template = NULL;
6762 struct collect_commit_logmsg_arg *a = arg;
6763 int initial_content_len;
6764 int fd = -1;
6765 size_t len;
6767 /* if a message was specified on the command line, just use it */
6768 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6769 len = strlen(a->cmdline_log) + 1;
6770 *logmsg = malloc(len + 1);
6771 if (*logmsg == NULL)
6772 return got_error_from_errno("malloc");
6773 strlcpy(*logmsg, a->cmdline_log, len);
6774 return NULL;
6777 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6778 return got_error_from_errno("asprintf");
6780 initial_content_len = asprintf(&initial_content,
6781 "\n# changes to be committed on branch %s:\n",
6782 a->branch_name);
6783 if (initial_content_len == -1)
6784 return got_error_from_errno("asprintf");
6786 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6787 if (err)
6788 goto done;
6790 if (write(fd, initial_content, initial_content_len) == -1) {
6791 err = got_error_from_errno2("write", a->logmsg_path);
6792 goto done;
6795 TAILQ_FOREACH(pe, commitable_paths, entry) {
6796 struct got_commitable *ct = pe->data;
6797 dprintf(fd, "# %c %s\n",
6798 got_commitable_get_status(ct),
6799 got_commitable_get_path(ct));
6802 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6803 initial_content_len);
6804 done:
6805 free(initial_content);
6806 free(template);
6808 if (fd != -1 && close(fd) == -1 && err == NULL)
6809 err = got_error_from_errno2("close", a->logmsg_path);
6811 /* Editor is done; we can now apply unveil(2) */
6812 if (err == NULL)
6813 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6814 if (err) {
6815 free(*logmsg);
6816 *logmsg = NULL;
6818 return err;
6821 static const struct got_error *
6822 cmd_commit(int argc, char *argv[])
6824 const struct got_error *error = NULL;
6825 struct got_worktree *worktree = NULL;
6826 struct got_repository *repo = NULL;
6827 char *cwd = NULL, *id_str = NULL;
6828 struct got_object_id *id = NULL;
6829 const char *logmsg = NULL;
6830 struct collect_commit_logmsg_arg cl_arg;
6831 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6832 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6833 int allow_bad_symlinks = 0;
6834 struct got_pathlist_head paths;
6836 TAILQ_INIT(&paths);
6837 cl_arg.logmsg_path = NULL;
6839 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6840 switch (ch) {
6841 case 'm':
6842 logmsg = optarg;
6843 break;
6844 case 'S':
6845 allow_bad_symlinks = 1;
6846 break;
6847 default:
6848 usage_commit();
6849 /* NOTREACHED */
6853 argc -= optind;
6854 argv += optind;
6856 #ifndef PROFILE
6857 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6858 "unveil", NULL) == -1)
6859 err(1, "pledge");
6860 #endif
6861 cwd = getcwd(NULL, 0);
6862 if (cwd == NULL) {
6863 error = got_error_from_errno("getcwd");
6864 goto done;
6866 error = got_worktree_open(&worktree, cwd);
6867 if (error) {
6868 if (error->code == GOT_ERR_NOT_WORKTREE)
6869 error = wrap_not_worktree_error(error, "commit", cwd);
6870 goto done;
6873 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6874 if (error)
6875 goto done;
6876 if (rebase_in_progress) {
6877 error = got_error(GOT_ERR_REBASING);
6878 goto done;
6881 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6882 worktree);
6883 if (error)
6884 goto done;
6886 error = get_gitconfig_path(&gitconfig_path);
6887 if (error)
6888 goto done;
6889 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6890 gitconfig_path);
6891 if (error != NULL)
6892 goto done;
6894 error = get_author(&author, repo, worktree);
6895 if (error)
6896 return error;
6899 * unveil(2) traverses exec(2); if an editor is used we have
6900 * to apply unveil after the log message has been written.
6902 if (logmsg == NULL || strlen(logmsg) == 0)
6903 error = get_editor(&editor);
6904 else
6905 error = apply_unveil(got_repo_get_path(repo), 0,
6906 got_worktree_get_root_path(worktree));
6907 if (error)
6908 goto done;
6910 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6911 if (error)
6912 goto done;
6914 cl_arg.editor = editor;
6915 cl_arg.cmdline_log = logmsg;
6916 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6917 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6918 if (!histedit_in_progress) {
6919 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6920 error = got_error(GOT_ERR_COMMIT_BRANCH);
6921 goto done;
6923 cl_arg.branch_name += 11;
6925 cl_arg.repo_path = got_repo_get_path(repo);
6926 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6927 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6928 print_status, NULL, repo);
6929 if (error) {
6930 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6931 cl_arg.logmsg_path != NULL)
6932 preserve_logmsg = 1;
6933 goto done;
6936 error = got_object_id_str(&id_str, id);
6937 if (error)
6938 goto done;
6939 printf("Created commit %s\n", id_str);
6940 done:
6941 if (preserve_logmsg) {
6942 fprintf(stderr, "%s: log message preserved in %s\n",
6943 getprogname(), cl_arg.logmsg_path);
6944 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6945 error == NULL)
6946 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6947 free(cl_arg.logmsg_path);
6948 if (repo)
6949 got_repo_close(repo);
6950 if (worktree)
6951 got_worktree_close(worktree);
6952 free(cwd);
6953 free(id_str);
6954 free(gitconfig_path);
6955 free(editor);
6956 free(author);
6957 return error;
6960 __dead static void
6961 usage_cherrypick(void)
6963 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6964 exit(1);
6967 static const struct got_error *
6968 cmd_cherrypick(int argc, char *argv[])
6970 const struct got_error *error = NULL;
6971 struct got_worktree *worktree = NULL;
6972 struct got_repository *repo = NULL;
6973 char *cwd = NULL, *commit_id_str = NULL;
6974 struct got_object_id *commit_id = NULL;
6975 struct got_commit_object *commit = NULL;
6976 struct got_object_qid *pid;
6977 struct got_reference *head_ref = NULL;
6978 int ch;
6979 struct got_update_progress_arg upa;
6981 while ((ch = getopt(argc, argv, "")) != -1) {
6982 switch (ch) {
6983 default:
6984 usage_cherrypick();
6985 /* NOTREACHED */
6989 argc -= optind;
6990 argv += optind;
6992 #ifndef PROFILE
6993 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6994 "unveil", NULL) == -1)
6995 err(1, "pledge");
6996 #endif
6997 if (argc != 1)
6998 usage_cherrypick();
7000 cwd = getcwd(NULL, 0);
7001 if (cwd == NULL) {
7002 error = got_error_from_errno("getcwd");
7003 goto done;
7005 error = got_worktree_open(&worktree, cwd);
7006 if (error) {
7007 if (error->code == GOT_ERR_NOT_WORKTREE)
7008 error = wrap_not_worktree_error(error, "cherrypick",
7009 cwd);
7010 goto done;
7013 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7014 NULL);
7015 if (error != NULL)
7016 goto done;
7018 error = apply_unveil(got_repo_get_path(repo), 0,
7019 got_worktree_get_root_path(worktree));
7020 if (error)
7021 goto done;
7023 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7024 GOT_OBJ_TYPE_COMMIT, repo);
7025 if (error != NULL) {
7026 struct got_reference *ref;
7027 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7028 goto done;
7029 error = got_ref_open(&ref, repo, argv[0], 0);
7030 if (error != NULL)
7031 goto done;
7032 error = got_ref_resolve(&commit_id, repo, ref);
7033 got_ref_close(ref);
7034 if (error != NULL)
7035 goto done;
7037 error = got_object_id_str(&commit_id_str, commit_id);
7038 if (error)
7039 goto done;
7041 error = got_ref_open(&head_ref, repo,
7042 got_worktree_get_head_ref_name(worktree), 0);
7043 if (error != NULL)
7044 goto done;
7046 error = check_same_branch(commit_id, head_ref, NULL, repo);
7047 if (error) {
7048 if (error->code != GOT_ERR_ANCESTRY)
7049 goto done;
7050 error = NULL;
7051 } else {
7052 error = got_error(GOT_ERR_SAME_BRANCH);
7053 goto done;
7056 error = got_object_open_as_commit(&commit, repo, commit_id);
7057 if (error)
7058 goto done;
7059 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7060 memset(&upa, 0, sizeof(upa));
7061 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7062 commit_id, repo, update_progress, &upa, check_cancelled,
7063 NULL);
7064 if (error != NULL)
7065 goto done;
7067 if (upa.did_something)
7068 printf("Merged commit %s\n", commit_id_str);
7069 print_update_progress_stats(&upa);
7070 done:
7071 if (commit)
7072 got_object_commit_close(commit);
7073 free(commit_id_str);
7074 if (head_ref)
7075 got_ref_close(head_ref);
7076 if (worktree)
7077 got_worktree_close(worktree);
7078 if (repo)
7079 got_repo_close(repo);
7080 return error;
7083 __dead static void
7084 usage_backout(void)
7086 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7087 exit(1);
7090 static const struct got_error *
7091 cmd_backout(int argc, char *argv[])
7093 const struct got_error *error = NULL;
7094 struct got_worktree *worktree = NULL;
7095 struct got_repository *repo = NULL;
7096 char *cwd = NULL, *commit_id_str = NULL;
7097 struct got_object_id *commit_id = NULL;
7098 struct got_commit_object *commit = NULL;
7099 struct got_object_qid *pid;
7100 struct got_reference *head_ref = NULL;
7101 int ch;
7102 struct got_update_progress_arg upa;
7104 while ((ch = getopt(argc, argv, "")) != -1) {
7105 switch (ch) {
7106 default:
7107 usage_backout();
7108 /* NOTREACHED */
7112 argc -= optind;
7113 argv += optind;
7115 #ifndef PROFILE
7116 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7117 "unveil", NULL) == -1)
7118 err(1, "pledge");
7119 #endif
7120 if (argc != 1)
7121 usage_backout();
7123 cwd = getcwd(NULL, 0);
7124 if (cwd == NULL) {
7125 error = got_error_from_errno("getcwd");
7126 goto done;
7128 error = got_worktree_open(&worktree, cwd);
7129 if (error) {
7130 if (error->code == GOT_ERR_NOT_WORKTREE)
7131 error = wrap_not_worktree_error(error, "backout", cwd);
7132 goto done;
7135 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7136 NULL);
7137 if (error != NULL)
7138 goto done;
7140 error = apply_unveil(got_repo_get_path(repo), 0,
7141 got_worktree_get_root_path(worktree));
7142 if (error)
7143 goto done;
7145 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7146 GOT_OBJ_TYPE_COMMIT, repo);
7147 if (error != NULL) {
7148 struct got_reference *ref;
7149 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7150 goto done;
7151 error = got_ref_open(&ref, repo, argv[0], 0);
7152 if (error != NULL)
7153 goto done;
7154 error = got_ref_resolve(&commit_id, repo, ref);
7155 got_ref_close(ref);
7156 if (error != NULL)
7157 goto done;
7159 error = got_object_id_str(&commit_id_str, commit_id);
7160 if (error)
7161 goto done;
7163 error = got_ref_open(&head_ref, repo,
7164 got_worktree_get_head_ref_name(worktree), 0);
7165 if (error != NULL)
7166 goto done;
7168 error = check_same_branch(commit_id, head_ref, NULL, repo);
7169 if (error)
7170 goto done;
7172 error = got_object_open_as_commit(&commit, repo, commit_id);
7173 if (error)
7174 goto done;
7175 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7176 if (pid == NULL) {
7177 error = got_error(GOT_ERR_ROOT_COMMIT);
7178 goto done;
7181 memset(&upa, 0, sizeof(upa));
7182 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7183 update_progress, &upa, check_cancelled, NULL);
7184 if (error != NULL)
7185 goto done;
7187 if (upa.did_something)
7188 printf("Backed out commit %s\n", commit_id_str);
7189 print_update_progress_stats(&upa);
7190 done:
7191 if (commit)
7192 got_object_commit_close(commit);
7193 free(commit_id_str);
7194 if (head_ref)
7195 got_ref_close(head_ref);
7196 if (worktree)
7197 got_worktree_close(worktree);
7198 if (repo)
7199 got_repo_close(repo);
7200 return error;
7203 __dead static void
7204 usage_rebase(void)
7206 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7207 getprogname());
7208 exit(1);
7211 void
7212 trim_logmsg(char *logmsg, int limit)
7214 char *nl;
7215 size_t len;
7217 len = strlen(logmsg);
7218 if (len > limit)
7219 len = limit;
7220 logmsg[len] = '\0';
7221 nl = strchr(logmsg, '\n');
7222 if (nl)
7223 *nl = '\0';
7226 static const struct got_error *
7227 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7229 const struct got_error *err;
7230 char *logmsg0 = NULL;
7231 const char *s;
7233 err = got_object_commit_get_logmsg(&logmsg0, commit);
7234 if (err)
7235 return err;
7237 s = logmsg0;
7238 while (isspace((unsigned char)s[0]))
7239 s++;
7241 *logmsg = strdup(s);
7242 if (*logmsg == NULL) {
7243 err = got_error_from_errno("strdup");
7244 goto done;
7247 trim_logmsg(*logmsg, limit);
7248 done:
7249 free(logmsg0);
7250 return err;
7253 static const struct got_error *
7254 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7256 const struct got_error *err;
7257 struct got_commit_object *commit = NULL;
7258 char *id_str = NULL, *logmsg = NULL;
7260 err = got_object_open_as_commit(&commit, repo, id);
7261 if (err)
7262 return err;
7264 err = got_object_id_str(&id_str, id);
7265 if (err)
7266 goto done;
7268 id_str[12] = '\0';
7270 err = get_short_logmsg(&logmsg, 42, commit);
7271 if (err)
7272 goto done;
7274 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7275 done:
7276 free(id_str);
7277 got_object_commit_close(commit);
7278 free(logmsg);
7279 return err;
7282 static const struct got_error *
7283 show_rebase_progress(struct got_commit_object *commit,
7284 struct got_object_id *old_id, struct got_object_id *new_id)
7286 const struct got_error *err;
7287 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7289 err = got_object_id_str(&old_id_str, old_id);
7290 if (err)
7291 goto done;
7293 if (new_id) {
7294 err = got_object_id_str(&new_id_str, new_id);
7295 if (err)
7296 goto done;
7299 old_id_str[12] = '\0';
7300 if (new_id_str)
7301 new_id_str[12] = '\0';
7303 err = get_short_logmsg(&logmsg, 42, commit);
7304 if (err)
7305 goto done;
7307 printf("%s -> %s: %s\n", old_id_str,
7308 new_id_str ? new_id_str : "no-op change", logmsg);
7309 done:
7310 free(old_id_str);
7311 free(new_id_str);
7312 free(logmsg);
7313 return err;
7316 static const struct got_error *
7317 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7318 struct got_reference *branch, struct got_reference *new_base_branch,
7319 struct got_reference *tmp_branch, struct got_repository *repo)
7321 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7322 return got_worktree_rebase_complete(worktree, fileindex,
7323 new_base_branch, tmp_branch, branch, repo);
7326 static const struct got_error *
7327 rebase_commit(struct got_pathlist_head *merged_paths,
7328 struct got_worktree *worktree, struct got_fileindex *fileindex,
7329 struct got_reference *tmp_branch,
7330 struct got_object_id *commit_id, struct got_repository *repo)
7332 const struct got_error *error;
7333 struct got_commit_object *commit;
7334 struct got_object_id *new_commit_id;
7336 error = got_object_open_as_commit(&commit, repo, commit_id);
7337 if (error)
7338 return error;
7340 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7341 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7342 if (error) {
7343 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7344 goto done;
7345 error = show_rebase_progress(commit, commit_id, NULL);
7346 } else {
7347 error = show_rebase_progress(commit, commit_id, new_commit_id);
7348 free(new_commit_id);
7350 done:
7351 got_object_commit_close(commit);
7352 return error;
7355 struct check_path_prefix_arg {
7356 const char *path_prefix;
7357 size_t len;
7358 int errcode;
7361 static const struct got_error *
7362 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7363 struct got_blob_object *blob2, struct got_object_id *id1,
7364 struct got_object_id *id2, const char *path1, const char *path2,
7365 mode_t mode1, mode_t mode2, struct got_repository *repo)
7367 struct check_path_prefix_arg *a = arg;
7369 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7370 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7371 return got_error(a->errcode);
7373 return NULL;
7376 static const struct got_error *
7377 check_path_prefix(struct got_object_id *parent_id,
7378 struct got_object_id *commit_id, const char *path_prefix,
7379 int errcode, struct got_repository *repo)
7381 const struct got_error *err;
7382 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7383 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7384 struct check_path_prefix_arg cpp_arg;
7386 if (got_path_is_root_dir(path_prefix))
7387 return NULL;
7389 err = got_object_open_as_commit(&commit, repo, commit_id);
7390 if (err)
7391 goto done;
7393 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7394 if (err)
7395 goto done;
7397 err = got_object_open_as_tree(&tree1, repo,
7398 got_object_commit_get_tree_id(parent_commit));
7399 if (err)
7400 goto done;
7402 err = got_object_open_as_tree(&tree2, repo,
7403 got_object_commit_get_tree_id(commit));
7404 if (err)
7405 goto done;
7407 cpp_arg.path_prefix = path_prefix;
7408 while (cpp_arg.path_prefix[0] == '/')
7409 cpp_arg.path_prefix++;
7410 cpp_arg.len = strlen(cpp_arg.path_prefix);
7411 cpp_arg.errcode = errcode;
7412 err = got_diff_tree(tree1, tree2, "", "", repo,
7413 check_path_prefix_in_diff, &cpp_arg, 0);
7414 done:
7415 if (tree1)
7416 got_object_tree_close(tree1);
7417 if (tree2)
7418 got_object_tree_close(tree2);
7419 if (commit)
7420 got_object_commit_close(commit);
7421 if (parent_commit)
7422 got_object_commit_close(parent_commit);
7423 return err;
7426 static const struct got_error *
7427 collect_commits(struct got_object_id_queue *commits,
7428 struct got_object_id *initial_commit_id,
7429 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7430 const char *path_prefix, int path_prefix_errcode,
7431 struct got_repository *repo)
7433 const struct got_error *err = NULL;
7434 struct got_commit_graph *graph = NULL;
7435 struct got_object_id *parent_id = NULL;
7436 struct got_object_qid *qid;
7437 struct got_object_id *commit_id = initial_commit_id;
7439 err = got_commit_graph_open(&graph, "/", 1);
7440 if (err)
7441 return err;
7443 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7444 check_cancelled, NULL);
7445 if (err)
7446 goto done;
7447 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7448 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7449 check_cancelled, NULL);
7450 if (err) {
7451 if (err->code == GOT_ERR_ITER_COMPLETED) {
7452 err = got_error_msg(GOT_ERR_ANCESTRY,
7453 "ran out of commits to rebase before "
7454 "youngest common ancestor commit has "
7455 "been reached?!?");
7457 goto done;
7458 } else {
7459 err = check_path_prefix(parent_id, commit_id,
7460 path_prefix, path_prefix_errcode, repo);
7461 if (err)
7462 goto done;
7464 err = got_object_qid_alloc(&qid, commit_id);
7465 if (err)
7466 goto done;
7467 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7468 commit_id = parent_id;
7471 done:
7472 got_commit_graph_close(graph);
7473 return err;
7476 static const struct got_error *
7477 cmd_rebase(int argc, char *argv[])
7479 const struct got_error *error = NULL;
7480 struct got_worktree *worktree = NULL;
7481 struct got_repository *repo = NULL;
7482 struct got_fileindex *fileindex = NULL;
7483 char *cwd = NULL;
7484 struct got_reference *branch = NULL;
7485 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7486 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7487 struct got_object_id *resume_commit_id = NULL;
7488 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7489 struct got_commit_object *commit = NULL;
7490 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7491 int histedit_in_progress = 0;
7492 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7493 struct got_object_id_queue commits;
7494 struct got_pathlist_head merged_paths;
7495 const struct got_object_id_queue *parent_ids;
7496 struct got_object_qid *qid, *pid;
7498 SIMPLEQ_INIT(&commits);
7499 TAILQ_INIT(&merged_paths);
7501 while ((ch = getopt(argc, argv, "ac")) != -1) {
7502 switch (ch) {
7503 case 'a':
7504 abort_rebase = 1;
7505 break;
7506 case 'c':
7507 continue_rebase = 1;
7508 break;
7509 default:
7510 usage_rebase();
7511 /* NOTREACHED */
7515 argc -= optind;
7516 argv += optind;
7518 #ifndef PROFILE
7519 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7520 "unveil", NULL) == -1)
7521 err(1, "pledge");
7522 #endif
7523 if (abort_rebase && continue_rebase)
7524 usage_rebase();
7525 else if (abort_rebase || continue_rebase) {
7526 if (argc != 0)
7527 usage_rebase();
7528 } else if (argc != 1)
7529 usage_rebase();
7531 cwd = getcwd(NULL, 0);
7532 if (cwd == NULL) {
7533 error = got_error_from_errno("getcwd");
7534 goto done;
7536 error = got_worktree_open(&worktree, cwd);
7537 if (error) {
7538 if (error->code == GOT_ERR_NOT_WORKTREE)
7539 error = wrap_not_worktree_error(error, "rebase", cwd);
7540 goto done;
7543 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7544 NULL);
7545 if (error != NULL)
7546 goto done;
7548 error = apply_unveil(got_repo_get_path(repo), 0,
7549 got_worktree_get_root_path(worktree));
7550 if (error)
7551 goto done;
7553 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7554 worktree);
7555 if (error)
7556 goto done;
7557 if (histedit_in_progress) {
7558 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7559 goto done;
7562 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7563 if (error)
7564 goto done;
7566 if (abort_rebase) {
7567 struct got_update_progress_arg upa;
7568 if (!rebase_in_progress) {
7569 error = got_error(GOT_ERR_NOT_REBASING);
7570 goto done;
7572 error = got_worktree_rebase_continue(&resume_commit_id,
7573 &new_base_branch, &tmp_branch, &branch, &fileindex,
7574 worktree, repo);
7575 if (error)
7576 goto done;
7577 printf("Switching work tree to %s\n",
7578 got_ref_get_symref_target(new_base_branch));
7579 memset(&upa, 0, sizeof(upa));
7580 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7581 new_base_branch, update_progress, &upa);
7582 if (error)
7583 goto done;
7584 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7585 print_update_progress_stats(&upa);
7586 goto done; /* nothing else to do */
7589 if (continue_rebase) {
7590 if (!rebase_in_progress) {
7591 error = got_error(GOT_ERR_NOT_REBASING);
7592 goto done;
7594 error = got_worktree_rebase_continue(&resume_commit_id,
7595 &new_base_branch, &tmp_branch, &branch, &fileindex,
7596 worktree, repo);
7597 if (error)
7598 goto done;
7600 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7601 resume_commit_id, repo);
7602 if (error)
7603 goto done;
7605 yca_id = got_object_id_dup(resume_commit_id);
7606 if (yca_id == NULL) {
7607 error = got_error_from_errno("got_object_id_dup");
7608 goto done;
7610 } else {
7611 error = got_ref_open(&branch, repo, argv[0], 0);
7612 if (error != NULL)
7613 goto done;
7616 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7617 if (error)
7618 goto done;
7620 if (!continue_rebase) {
7621 struct got_object_id *base_commit_id;
7623 base_commit_id = got_worktree_get_base_commit_id(worktree);
7624 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7625 base_commit_id, branch_head_commit_id, repo,
7626 check_cancelled, NULL);
7627 if (error)
7628 goto done;
7629 if (yca_id == NULL) {
7630 error = got_error_msg(GOT_ERR_ANCESTRY,
7631 "specified branch shares no common ancestry "
7632 "with work tree's branch");
7633 goto done;
7636 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7637 if (error) {
7638 if (error->code != GOT_ERR_ANCESTRY)
7639 goto done;
7640 error = NULL;
7641 } else {
7642 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7643 "specified branch resolves to a commit which "
7644 "is already contained in work tree's branch");
7645 goto done;
7647 error = got_worktree_rebase_prepare(&new_base_branch,
7648 &tmp_branch, &fileindex, worktree, branch, repo);
7649 if (error)
7650 goto done;
7653 commit_id = branch_head_commit_id;
7654 error = got_object_open_as_commit(&commit, repo, commit_id);
7655 if (error)
7656 goto done;
7658 parent_ids = got_object_commit_get_parent_ids(commit);
7659 pid = SIMPLEQ_FIRST(parent_ids);
7660 if (pid == NULL) {
7661 if (!continue_rebase) {
7662 struct got_update_progress_arg upa;
7663 memset(&upa, 0, sizeof(upa));
7664 error = got_worktree_rebase_abort(worktree, fileindex,
7665 repo, new_base_branch, update_progress, &upa);
7666 if (error)
7667 goto done;
7668 printf("Rebase of %s aborted\n",
7669 got_ref_get_name(branch));
7670 print_update_progress_stats(&upa);
7673 error = got_error(GOT_ERR_EMPTY_REBASE);
7674 goto done;
7676 error = collect_commits(&commits, commit_id, pid->id,
7677 yca_id, got_worktree_get_path_prefix(worktree),
7678 GOT_ERR_REBASE_PATH, repo);
7679 got_object_commit_close(commit);
7680 commit = NULL;
7681 if (error)
7682 goto done;
7684 if (SIMPLEQ_EMPTY(&commits)) {
7685 if (continue_rebase) {
7686 error = rebase_complete(worktree, fileindex,
7687 branch, new_base_branch, tmp_branch, repo);
7688 goto done;
7689 } else {
7690 /* Fast-forward the reference of the branch. */
7691 struct got_object_id *new_head_commit_id;
7692 char *id_str;
7693 error = got_ref_resolve(&new_head_commit_id, repo,
7694 new_base_branch);
7695 if (error)
7696 goto done;
7697 error = got_object_id_str(&id_str, new_head_commit_id);
7698 printf("Forwarding %s to commit %s\n",
7699 got_ref_get_name(branch), id_str);
7700 free(id_str);
7701 error = got_ref_change_ref(branch,
7702 new_head_commit_id);
7703 if (error)
7704 goto done;
7708 pid = NULL;
7709 SIMPLEQ_FOREACH(qid, &commits, entry) {
7710 struct got_update_progress_arg upa;
7712 commit_id = qid->id;
7713 parent_id = pid ? pid->id : yca_id;
7714 pid = qid;
7716 memset(&upa, 0, sizeof(upa));
7717 error = got_worktree_rebase_merge_files(&merged_paths,
7718 worktree, fileindex, parent_id, commit_id, repo,
7719 update_progress, &upa, check_cancelled, NULL);
7720 if (error)
7721 goto done;
7723 print_update_progress_stats(&upa);
7724 if (upa.conflicts > 0)
7725 rebase_status = GOT_STATUS_CONFLICT;
7727 if (rebase_status == GOT_STATUS_CONFLICT) {
7728 error = show_rebase_merge_conflict(qid->id, repo);
7729 if (error)
7730 goto done;
7731 got_worktree_rebase_pathlist_free(&merged_paths);
7732 break;
7735 error = rebase_commit(&merged_paths, worktree, fileindex,
7736 tmp_branch, commit_id, repo);
7737 got_worktree_rebase_pathlist_free(&merged_paths);
7738 if (error)
7739 goto done;
7742 if (rebase_status == GOT_STATUS_CONFLICT) {
7743 error = got_worktree_rebase_postpone(worktree, fileindex);
7744 if (error)
7745 goto done;
7746 error = got_error_msg(GOT_ERR_CONFLICTS,
7747 "conflicts must be resolved before rebasing can continue");
7748 } else
7749 error = rebase_complete(worktree, fileindex, branch,
7750 new_base_branch, tmp_branch, repo);
7751 done:
7752 got_object_id_queue_free(&commits);
7753 free(branch_head_commit_id);
7754 free(resume_commit_id);
7755 free(yca_id);
7756 if (commit)
7757 got_object_commit_close(commit);
7758 if (branch)
7759 got_ref_close(branch);
7760 if (new_base_branch)
7761 got_ref_close(new_base_branch);
7762 if (tmp_branch)
7763 got_ref_close(tmp_branch);
7764 if (worktree)
7765 got_worktree_close(worktree);
7766 if (repo)
7767 got_repo_close(repo);
7768 return error;
7771 __dead static void
7772 usage_histedit(void)
7774 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7775 getprogname());
7776 exit(1);
7779 #define GOT_HISTEDIT_PICK 'p'
7780 #define GOT_HISTEDIT_EDIT 'e'
7781 #define GOT_HISTEDIT_FOLD 'f'
7782 #define GOT_HISTEDIT_DROP 'd'
7783 #define GOT_HISTEDIT_MESG 'm'
7785 static struct got_histedit_cmd {
7786 unsigned char code;
7787 const char *name;
7788 const char *desc;
7789 } got_histedit_cmds[] = {
7790 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7791 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7792 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7793 "be used" },
7794 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7795 { GOT_HISTEDIT_MESG, "mesg",
7796 "single-line log message for commit above (open editor if empty)" },
7799 struct got_histedit_list_entry {
7800 TAILQ_ENTRY(got_histedit_list_entry) entry;
7801 struct got_object_id *commit_id;
7802 const struct got_histedit_cmd *cmd;
7803 char *logmsg;
7805 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7807 static const struct got_error *
7808 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7809 FILE *f, struct got_repository *repo)
7811 const struct got_error *err = NULL;
7812 char *logmsg = NULL, *id_str = NULL;
7813 struct got_commit_object *commit = NULL;
7814 int n;
7816 err = got_object_open_as_commit(&commit, repo, commit_id);
7817 if (err)
7818 goto done;
7820 err = get_short_logmsg(&logmsg, 34, commit);
7821 if (err)
7822 goto done;
7824 err = got_object_id_str(&id_str, commit_id);
7825 if (err)
7826 goto done;
7828 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7829 if (n < 0)
7830 err = got_ferror(f, GOT_ERR_IO);
7831 done:
7832 if (commit)
7833 got_object_commit_close(commit);
7834 free(id_str);
7835 free(logmsg);
7836 return err;
7839 static const struct got_error *
7840 histedit_write_commit_list(struct got_object_id_queue *commits,
7841 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7843 const struct got_error *err = NULL;
7844 struct got_object_qid *qid;
7846 if (SIMPLEQ_EMPTY(commits))
7847 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7849 SIMPLEQ_FOREACH(qid, commits, entry) {
7850 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7851 f, repo);
7852 if (err)
7853 break;
7854 if (edit_logmsg_only) {
7855 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7856 if (n < 0) {
7857 err = got_ferror(f, GOT_ERR_IO);
7858 break;
7863 return err;
7866 static const struct got_error *
7867 write_cmd_list(FILE *f, const char *branch_name,
7868 struct got_object_id_queue *commits)
7870 const struct got_error *err = NULL;
7871 int n, i;
7872 char *id_str;
7873 struct got_object_qid *qid;
7875 qid = SIMPLEQ_FIRST(commits);
7876 err = got_object_id_str(&id_str, qid->id);
7877 if (err)
7878 return err;
7880 n = fprintf(f,
7881 "# Editing the history of branch '%s' starting at\n"
7882 "# commit %s\n"
7883 "# Commits will be processed in order from top to "
7884 "bottom of this file.\n", branch_name, id_str);
7885 if (n < 0) {
7886 err = got_ferror(f, GOT_ERR_IO);
7887 goto done;
7890 n = fprintf(f, "# Available histedit commands:\n");
7891 if (n < 0) {
7892 err = got_ferror(f, GOT_ERR_IO);
7893 goto done;
7896 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7897 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7898 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7899 cmd->desc);
7900 if (n < 0) {
7901 err = got_ferror(f, GOT_ERR_IO);
7902 break;
7905 done:
7906 free(id_str);
7907 return err;
7910 static const struct got_error *
7911 histedit_syntax_error(int lineno)
7913 static char msg[42];
7914 int ret;
7916 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7917 lineno);
7918 if (ret == -1 || ret >= sizeof(msg))
7919 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7921 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7924 static const struct got_error *
7925 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7926 char *logmsg, struct got_repository *repo)
7928 const struct got_error *err;
7929 struct got_commit_object *folded_commit = NULL;
7930 char *id_str, *folded_logmsg = NULL;
7932 err = got_object_id_str(&id_str, hle->commit_id);
7933 if (err)
7934 return err;
7936 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7937 if (err)
7938 goto done;
7940 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7941 if (err)
7942 goto done;
7943 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7944 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7945 folded_logmsg) == -1) {
7946 err = got_error_from_errno("asprintf");
7948 done:
7949 if (folded_commit)
7950 got_object_commit_close(folded_commit);
7951 free(id_str);
7952 free(folded_logmsg);
7953 return err;
7956 static struct got_histedit_list_entry *
7957 get_folded_commits(struct got_histedit_list_entry *hle)
7959 struct got_histedit_list_entry *prev, *folded = NULL;
7961 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7962 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7963 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7964 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7965 folded = prev;
7966 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7969 return folded;
7972 static const struct got_error *
7973 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7974 struct got_repository *repo)
7976 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7977 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7978 const struct got_error *err = NULL;
7979 struct got_commit_object *commit = NULL;
7980 int logmsg_len;
7981 int fd;
7982 struct got_histedit_list_entry *folded = NULL;
7984 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7985 if (err)
7986 return err;
7988 folded = get_folded_commits(hle);
7989 if (folded) {
7990 while (folded != hle) {
7991 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7992 folded = TAILQ_NEXT(folded, entry);
7993 continue;
7995 err = append_folded_commit_msg(&new_msg, folded,
7996 logmsg, repo);
7997 if (err)
7998 goto done;
7999 free(logmsg);
8000 logmsg = new_msg;
8001 folded = TAILQ_NEXT(folded, entry);
8005 err = got_object_id_str(&id_str, hle->commit_id);
8006 if (err)
8007 goto done;
8008 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8009 if (err)
8010 goto done;
8011 logmsg_len = asprintf(&new_msg,
8012 "%s\n# original log message of commit %s: %s",
8013 logmsg ? logmsg : "", id_str, orig_logmsg);
8014 if (logmsg_len == -1) {
8015 err = got_error_from_errno("asprintf");
8016 goto done;
8018 free(logmsg);
8019 logmsg = new_msg;
8021 err = got_object_id_str(&id_str, hle->commit_id);
8022 if (err)
8023 goto done;
8025 err = got_opentemp_named_fd(&logmsg_path, &fd,
8026 GOT_TMPDIR_STR "/got-logmsg");
8027 if (err)
8028 goto done;
8030 write(fd, logmsg, logmsg_len);
8031 close(fd);
8033 err = get_editor(&editor);
8034 if (err)
8035 goto done;
8037 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8038 logmsg_len);
8039 if (err) {
8040 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8041 goto done;
8042 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8044 done:
8045 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8046 err = got_error_from_errno2("unlink", logmsg_path);
8047 free(logmsg_path);
8048 free(logmsg);
8049 free(orig_logmsg);
8050 free(editor);
8051 if (commit)
8052 got_object_commit_close(commit);
8053 return err;
8056 static const struct got_error *
8057 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8058 FILE *f, struct got_repository *repo)
8060 const struct got_error *err = NULL;
8061 char *line = NULL, *p, *end;
8062 size_t size;
8063 ssize_t len;
8064 int lineno = 0, i;
8065 const struct got_histedit_cmd *cmd;
8066 struct got_object_id *commit_id = NULL;
8067 struct got_histedit_list_entry *hle = NULL;
8069 for (;;) {
8070 len = getline(&line, &size, f);
8071 if (len == -1) {
8072 const struct got_error *getline_err;
8073 if (feof(f))
8074 break;
8075 getline_err = got_error_from_errno("getline");
8076 err = got_ferror(f, getline_err->code);
8077 break;
8079 lineno++;
8080 p = line;
8081 while (isspace((unsigned char)p[0]))
8082 p++;
8083 if (p[0] == '#' || p[0] == '\0') {
8084 free(line);
8085 line = NULL;
8086 continue;
8088 cmd = NULL;
8089 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8090 cmd = &got_histedit_cmds[i];
8091 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8092 isspace((unsigned char)p[strlen(cmd->name)])) {
8093 p += strlen(cmd->name);
8094 break;
8096 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8097 p++;
8098 break;
8101 if (i == nitems(got_histedit_cmds)) {
8102 err = histedit_syntax_error(lineno);
8103 break;
8105 while (isspace((unsigned char)p[0]))
8106 p++;
8107 if (cmd->code == GOT_HISTEDIT_MESG) {
8108 if (hle == NULL || hle->logmsg != NULL) {
8109 err = got_error(GOT_ERR_HISTEDIT_CMD);
8110 break;
8112 if (p[0] == '\0') {
8113 err = histedit_edit_logmsg(hle, repo);
8114 if (err)
8115 break;
8116 } else {
8117 hle->logmsg = strdup(p);
8118 if (hle->logmsg == NULL) {
8119 err = got_error_from_errno("strdup");
8120 break;
8123 free(line);
8124 line = NULL;
8125 continue;
8126 } else {
8127 end = p;
8128 while (end[0] && !isspace((unsigned char)end[0]))
8129 end++;
8130 *end = '\0';
8132 err = got_object_resolve_id_str(&commit_id, repo, p);
8133 if (err) {
8134 /* override error code */
8135 err = histedit_syntax_error(lineno);
8136 break;
8139 hle = malloc(sizeof(*hle));
8140 if (hle == NULL) {
8141 err = got_error_from_errno("malloc");
8142 break;
8144 hle->cmd = cmd;
8145 hle->commit_id = commit_id;
8146 hle->logmsg = NULL;
8147 commit_id = NULL;
8148 free(line);
8149 line = NULL;
8150 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8153 free(line);
8154 free(commit_id);
8155 return err;
8158 static const struct got_error *
8159 histedit_check_script(struct got_histedit_list *histedit_cmds,
8160 struct got_object_id_queue *commits, struct got_repository *repo)
8162 const struct got_error *err = NULL;
8163 struct got_object_qid *qid;
8164 struct got_histedit_list_entry *hle;
8165 static char msg[92];
8166 char *id_str;
8168 if (TAILQ_EMPTY(histedit_cmds))
8169 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8170 "histedit script contains no commands");
8171 if (SIMPLEQ_EMPTY(commits))
8172 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8174 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8175 struct got_histedit_list_entry *hle2;
8176 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8177 if (hle == hle2)
8178 continue;
8179 if (got_object_id_cmp(hle->commit_id,
8180 hle2->commit_id) != 0)
8181 continue;
8182 err = got_object_id_str(&id_str, hle->commit_id);
8183 if (err)
8184 return err;
8185 snprintf(msg, sizeof(msg), "commit %s is listed "
8186 "more than once in histedit script", id_str);
8187 free(id_str);
8188 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8192 SIMPLEQ_FOREACH(qid, commits, entry) {
8193 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8194 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8195 break;
8197 if (hle == NULL) {
8198 err = got_object_id_str(&id_str, qid->id);
8199 if (err)
8200 return err;
8201 snprintf(msg, sizeof(msg),
8202 "commit %s missing from histedit script", id_str);
8203 free(id_str);
8204 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8208 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8209 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8210 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8211 "last commit in histedit script cannot be folded");
8213 return NULL;
8216 static const struct got_error *
8217 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8218 const char *path, struct got_object_id_queue *commits,
8219 struct got_repository *repo)
8221 const struct got_error *err = NULL;
8222 char *editor;
8223 FILE *f = NULL;
8225 err = get_editor(&editor);
8226 if (err)
8227 return err;
8229 if (spawn_editor(editor, path) == -1) {
8230 err = got_error_from_errno("failed spawning editor");
8231 goto done;
8234 f = fopen(path, "r");
8235 if (f == NULL) {
8236 err = got_error_from_errno("fopen");
8237 goto done;
8239 err = histedit_parse_list(histedit_cmds, f, repo);
8240 if (err)
8241 goto done;
8243 err = histedit_check_script(histedit_cmds, commits, repo);
8244 done:
8245 if (f && fclose(f) != 0 && err == NULL)
8246 err = got_error_from_errno("fclose");
8247 free(editor);
8248 return err;
8251 static const struct got_error *
8252 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8253 struct got_object_id_queue *, const char *, const char *,
8254 struct got_repository *);
8256 static const struct got_error *
8257 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8258 struct got_object_id_queue *commits, const char *branch_name,
8259 int edit_logmsg_only, struct got_repository *repo)
8261 const struct got_error *err;
8262 FILE *f = NULL;
8263 char *path = NULL;
8265 err = got_opentemp_named(&path, &f, "got-histedit");
8266 if (err)
8267 return err;
8269 err = write_cmd_list(f, branch_name, commits);
8270 if (err)
8271 goto done;
8273 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8274 if (err)
8275 goto done;
8277 if (edit_logmsg_only) {
8278 rewind(f);
8279 err = histedit_parse_list(histedit_cmds, f, repo);
8280 } else {
8281 if (fclose(f) != 0) {
8282 err = got_error_from_errno("fclose");
8283 goto done;
8285 f = NULL;
8286 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8287 if (err) {
8288 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8289 err->code != GOT_ERR_HISTEDIT_CMD)
8290 goto done;
8291 err = histedit_edit_list_retry(histedit_cmds, err,
8292 commits, path, branch_name, repo);
8295 done:
8296 if (f && fclose(f) != 0 && err == NULL)
8297 err = got_error_from_errno("fclose");
8298 if (path && unlink(path) != 0 && err == NULL)
8299 err = got_error_from_errno2("unlink", path);
8300 free(path);
8301 return err;
8304 static const struct got_error *
8305 histedit_save_list(struct got_histedit_list *histedit_cmds,
8306 struct got_worktree *worktree, struct got_repository *repo)
8308 const struct got_error *err = NULL;
8309 char *path = NULL;
8310 FILE *f = NULL;
8311 struct got_histedit_list_entry *hle;
8312 struct got_commit_object *commit = NULL;
8314 err = got_worktree_get_histedit_script_path(&path, worktree);
8315 if (err)
8316 return err;
8318 f = fopen(path, "w");
8319 if (f == NULL) {
8320 err = got_error_from_errno2("fopen", path);
8321 goto done;
8323 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8324 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8325 repo);
8326 if (err)
8327 break;
8329 if (hle->logmsg) {
8330 int n = fprintf(f, "%c %s\n",
8331 GOT_HISTEDIT_MESG, hle->logmsg);
8332 if (n < 0) {
8333 err = got_ferror(f, GOT_ERR_IO);
8334 break;
8338 done:
8339 if (f && fclose(f) != 0 && err == NULL)
8340 err = got_error_from_errno("fclose");
8341 free(path);
8342 if (commit)
8343 got_object_commit_close(commit);
8344 return err;
8347 void
8348 histedit_free_list(struct got_histedit_list *histedit_cmds)
8350 struct got_histedit_list_entry *hle;
8352 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8353 TAILQ_REMOVE(histedit_cmds, hle, entry);
8354 free(hle);
8358 static const struct got_error *
8359 histedit_load_list(struct got_histedit_list *histedit_cmds,
8360 const char *path, struct got_repository *repo)
8362 const struct got_error *err = NULL;
8363 FILE *f = NULL;
8365 f = fopen(path, "r");
8366 if (f == NULL) {
8367 err = got_error_from_errno2("fopen", path);
8368 goto done;
8371 err = histedit_parse_list(histedit_cmds, f, repo);
8372 done:
8373 if (f && fclose(f) != 0 && err == NULL)
8374 err = got_error_from_errno("fclose");
8375 return err;
8378 static const struct got_error *
8379 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8380 const struct got_error *edit_err, struct got_object_id_queue *commits,
8381 const char *path, const char *branch_name, struct got_repository *repo)
8383 const struct got_error *err = NULL, *prev_err = edit_err;
8384 int resp = ' ';
8386 while (resp != 'c' && resp != 'r' && resp != 'a') {
8387 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8388 "or (a)bort: ", getprogname(), prev_err->msg);
8389 resp = getchar();
8390 if (resp == '\n')
8391 resp = getchar();
8392 if (resp == 'c') {
8393 histedit_free_list(histedit_cmds);
8394 err = histedit_run_editor(histedit_cmds, path, commits,
8395 repo);
8396 if (err) {
8397 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8398 err->code != GOT_ERR_HISTEDIT_CMD)
8399 break;
8400 prev_err = err;
8401 resp = ' ';
8402 continue;
8404 break;
8405 } else if (resp == 'r') {
8406 histedit_free_list(histedit_cmds);
8407 err = histedit_edit_script(histedit_cmds,
8408 commits, branch_name, 0, repo);
8409 if (err) {
8410 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8411 err->code != GOT_ERR_HISTEDIT_CMD)
8412 break;
8413 prev_err = err;
8414 resp = ' ';
8415 continue;
8417 break;
8418 } else if (resp == 'a') {
8419 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8420 break;
8421 } else
8422 printf("invalid response '%c'\n", resp);
8425 return err;
8428 static const struct got_error *
8429 histedit_complete(struct got_worktree *worktree,
8430 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8431 struct got_reference *branch, struct got_repository *repo)
8433 printf("Switching work tree to %s\n",
8434 got_ref_get_symref_target(branch));
8435 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8436 branch, repo);
8439 static const struct got_error *
8440 show_histedit_progress(struct got_commit_object *commit,
8441 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8443 const struct got_error *err;
8444 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8446 err = got_object_id_str(&old_id_str, hle->commit_id);
8447 if (err)
8448 goto done;
8450 if (new_id) {
8451 err = got_object_id_str(&new_id_str, new_id);
8452 if (err)
8453 goto done;
8456 old_id_str[12] = '\0';
8457 if (new_id_str)
8458 new_id_str[12] = '\0';
8460 if (hle->logmsg) {
8461 logmsg = strdup(hle->logmsg);
8462 if (logmsg == NULL) {
8463 err = got_error_from_errno("strdup");
8464 goto done;
8466 trim_logmsg(logmsg, 42);
8467 } else {
8468 err = get_short_logmsg(&logmsg, 42, commit);
8469 if (err)
8470 goto done;
8473 switch (hle->cmd->code) {
8474 case GOT_HISTEDIT_PICK:
8475 case GOT_HISTEDIT_EDIT:
8476 printf("%s -> %s: %s\n", old_id_str,
8477 new_id_str ? new_id_str : "no-op change", logmsg);
8478 break;
8479 case GOT_HISTEDIT_DROP:
8480 case GOT_HISTEDIT_FOLD:
8481 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8482 logmsg);
8483 break;
8484 default:
8485 break;
8487 done:
8488 free(old_id_str);
8489 free(new_id_str);
8490 return err;
8493 static const struct got_error *
8494 histedit_commit(struct got_pathlist_head *merged_paths,
8495 struct got_worktree *worktree, struct got_fileindex *fileindex,
8496 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8497 struct got_repository *repo)
8499 const struct got_error *err;
8500 struct got_commit_object *commit;
8501 struct got_object_id *new_commit_id;
8503 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8504 && hle->logmsg == NULL) {
8505 err = histedit_edit_logmsg(hle, repo);
8506 if (err)
8507 return err;
8510 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8511 if (err)
8512 return err;
8514 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8515 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8516 hle->logmsg, repo);
8517 if (err) {
8518 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8519 goto done;
8520 err = show_histedit_progress(commit, hle, NULL);
8521 } else {
8522 err = show_histedit_progress(commit, hle, new_commit_id);
8523 free(new_commit_id);
8525 done:
8526 got_object_commit_close(commit);
8527 return err;
8530 static const struct got_error *
8531 histedit_skip_commit(struct got_histedit_list_entry *hle,
8532 struct got_worktree *worktree, struct got_repository *repo)
8534 const struct got_error *error;
8535 struct got_commit_object *commit;
8537 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8538 repo);
8539 if (error)
8540 return error;
8542 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8543 if (error)
8544 return error;
8546 error = show_histedit_progress(commit, hle, NULL);
8547 got_object_commit_close(commit);
8548 return error;
8551 static const struct got_error *
8552 check_local_changes(void *arg, unsigned char status,
8553 unsigned char staged_status, const char *path,
8554 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8555 struct got_object_id *commit_id, int dirfd, const char *de_name)
8557 int *have_local_changes = arg;
8559 switch (status) {
8560 case GOT_STATUS_ADD:
8561 case GOT_STATUS_DELETE:
8562 case GOT_STATUS_MODIFY:
8563 case GOT_STATUS_CONFLICT:
8564 *have_local_changes = 1;
8565 return got_error(GOT_ERR_CANCELLED);
8566 default:
8567 break;
8570 switch (staged_status) {
8571 case GOT_STATUS_ADD:
8572 case GOT_STATUS_DELETE:
8573 case GOT_STATUS_MODIFY:
8574 *have_local_changes = 1;
8575 return got_error(GOT_ERR_CANCELLED);
8576 default:
8577 break;
8580 return NULL;
8583 static const struct got_error *
8584 cmd_histedit(int argc, char *argv[])
8586 const struct got_error *error = NULL;
8587 struct got_worktree *worktree = NULL;
8588 struct got_fileindex *fileindex = NULL;
8589 struct got_repository *repo = NULL;
8590 char *cwd = NULL;
8591 struct got_reference *branch = NULL;
8592 struct got_reference *tmp_branch = NULL;
8593 struct got_object_id *resume_commit_id = NULL;
8594 struct got_object_id *base_commit_id = NULL;
8595 struct got_object_id *head_commit_id = NULL;
8596 struct got_commit_object *commit = NULL;
8597 int ch, rebase_in_progress = 0;
8598 struct got_update_progress_arg upa;
8599 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8600 int edit_logmsg_only = 0;
8601 const char *edit_script_path = NULL;
8602 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8603 struct got_object_id_queue commits;
8604 struct got_pathlist_head merged_paths;
8605 const struct got_object_id_queue *parent_ids;
8606 struct got_object_qid *pid;
8607 struct got_histedit_list histedit_cmds;
8608 struct got_histedit_list_entry *hle;
8610 SIMPLEQ_INIT(&commits);
8611 TAILQ_INIT(&histedit_cmds);
8612 TAILQ_INIT(&merged_paths);
8613 memset(&upa, 0, sizeof(upa));
8615 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8616 switch (ch) {
8617 case 'a':
8618 abort_edit = 1;
8619 break;
8620 case 'c':
8621 continue_edit = 1;
8622 break;
8623 case 'F':
8624 edit_script_path = optarg;
8625 break;
8626 case 'm':
8627 edit_logmsg_only = 1;
8628 break;
8629 default:
8630 usage_histedit();
8631 /* NOTREACHED */
8635 argc -= optind;
8636 argv += optind;
8638 #ifndef PROFILE
8639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8640 "unveil", NULL) == -1)
8641 err(1, "pledge");
8642 #endif
8643 if (abort_edit && continue_edit)
8644 errx(1, "histedit's -a and -c options are mutually exclusive");
8645 if (edit_script_path && edit_logmsg_only)
8646 errx(1, "histedit's -F and -m options are mutually exclusive");
8647 if (abort_edit && edit_logmsg_only)
8648 errx(1, "histedit's -a and -m options are mutually exclusive");
8649 if (continue_edit && edit_logmsg_only)
8650 errx(1, "histedit's -c and -m options are mutually exclusive");
8651 if (argc != 0)
8652 usage_histedit();
8655 * This command cannot apply unveil(2) in all cases because the
8656 * user may choose to run an editor to edit the histedit script
8657 * and to edit individual commit log messages.
8658 * unveil(2) traverses exec(2); if an editor is used we have to
8659 * apply unveil after edit script and log messages have been written.
8660 * XXX TODO: Make use of unveil(2) where possible.
8663 cwd = getcwd(NULL, 0);
8664 if (cwd == NULL) {
8665 error = got_error_from_errno("getcwd");
8666 goto done;
8668 error = got_worktree_open(&worktree, cwd);
8669 if (error) {
8670 if (error->code == GOT_ERR_NOT_WORKTREE)
8671 error = wrap_not_worktree_error(error, "histedit", cwd);
8672 goto done;
8675 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8676 NULL);
8677 if (error != NULL)
8678 goto done;
8680 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8681 if (error)
8682 goto done;
8683 if (rebase_in_progress) {
8684 error = got_error(GOT_ERR_REBASING);
8685 goto done;
8688 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8689 if (error)
8690 goto done;
8692 if (edit_in_progress && edit_logmsg_only) {
8693 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8694 "histedit operation is in progress in this "
8695 "work tree and must be continued or aborted "
8696 "before the -m option can be used");
8697 goto done;
8700 if (edit_in_progress && abort_edit) {
8701 error = got_worktree_histedit_continue(&resume_commit_id,
8702 &tmp_branch, &branch, &base_commit_id, &fileindex,
8703 worktree, repo);
8704 if (error)
8705 goto done;
8706 printf("Switching work tree to %s\n",
8707 got_ref_get_symref_target(branch));
8708 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8709 branch, base_commit_id, update_progress, &upa);
8710 if (error)
8711 goto done;
8712 printf("Histedit of %s aborted\n",
8713 got_ref_get_symref_target(branch));
8714 print_update_progress_stats(&upa);
8715 goto done; /* nothing else to do */
8716 } else if (abort_edit) {
8717 error = got_error(GOT_ERR_NOT_HISTEDIT);
8718 goto done;
8721 if (continue_edit) {
8722 char *path;
8724 if (!edit_in_progress) {
8725 error = got_error(GOT_ERR_NOT_HISTEDIT);
8726 goto done;
8729 error = got_worktree_get_histedit_script_path(&path, worktree);
8730 if (error)
8731 goto done;
8733 error = histedit_load_list(&histedit_cmds, path, repo);
8734 free(path);
8735 if (error)
8736 goto done;
8738 error = got_worktree_histedit_continue(&resume_commit_id,
8739 &tmp_branch, &branch, &base_commit_id, &fileindex,
8740 worktree, repo);
8741 if (error)
8742 goto done;
8744 error = got_ref_resolve(&head_commit_id, repo, branch);
8745 if (error)
8746 goto done;
8748 error = got_object_open_as_commit(&commit, repo,
8749 head_commit_id);
8750 if (error)
8751 goto done;
8752 parent_ids = got_object_commit_get_parent_ids(commit);
8753 pid = SIMPLEQ_FIRST(parent_ids);
8754 if (pid == NULL) {
8755 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8756 goto done;
8758 error = collect_commits(&commits, head_commit_id, pid->id,
8759 base_commit_id, got_worktree_get_path_prefix(worktree),
8760 GOT_ERR_HISTEDIT_PATH, repo);
8761 got_object_commit_close(commit);
8762 commit = NULL;
8763 if (error)
8764 goto done;
8765 } else {
8766 if (edit_in_progress) {
8767 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8768 goto done;
8771 error = got_ref_open(&branch, repo,
8772 got_worktree_get_head_ref_name(worktree), 0);
8773 if (error != NULL)
8774 goto done;
8776 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8777 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8778 "will not edit commit history of a branch outside "
8779 "the \"refs/heads/\" reference namespace");
8780 goto done;
8783 error = got_ref_resolve(&head_commit_id, repo, branch);
8784 got_ref_close(branch);
8785 branch = NULL;
8786 if (error)
8787 goto done;
8789 error = got_object_open_as_commit(&commit, repo,
8790 head_commit_id);
8791 if (error)
8792 goto done;
8793 parent_ids = got_object_commit_get_parent_ids(commit);
8794 pid = SIMPLEQ_FIRST(parent_ids);
8795 if (pid == NULL) {
8796 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8797 goto done;
8799 error = collect_commits(&commits, head_commit_id, pid->id,
8800 got_worktree_get_base_commit_id(worktree),
8801 got_worktree_get_path_prefix(worktree),
8802 GOT_ERR_HISTEDIT_PATH, repo);
8803 got_object_commit_close(commit);
8804 commit = NULL;
8805 if (error)
8806 goto done;
8808 if (SIMPLEQ_EMPTY(&commits)) {
8809 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8810 goto done;
8813 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8814 &base_commit_id, &fileindex, worktree, repo);
8815 if (error)
8816 goto done;
8818 if (edit_script_path) {
8819 error = histedit_load_list(&histedit_cmds,
8820 edit_script_path, repo);
8821 if (error) {
8822 got_worktree_histedit_abort(worktree, fileindex,
8823 repo, branch, base_commit_id,
8824 update_progress, &upa);
8825 print_update_progress_stats(&upa);
8826 goto done;
8828 } else {
8829 const char *branch_name;
8830 branch_name = got_ref_get_symref_target(branch);
8831 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8832 branch_name += 11;
8833 error = histedit_edit_script(&histedit_cmds, &commits,
8834 branch_name, edit_logmsg_only, repo);
8835 if (error) {
8836 got_worktree_histedit_abort(worktree, fileindex,
8837 repo, branch, base_commit_id,
8838 update_progress, &upa);
8839 print_update_progress_stats(&upa);
8840 goto done;
8845 error = histedit_save_list(&histedit_cmds, worktree,
8846 repo);
8847 if (error) {
8848 got_worktree_histedit_abort(worktree, fileindex,
8849 repo, branch, base_commit_id,
8850 update_progress, &upa);
8851 print_update_progress_stats(&upa);
8852 goto done;
8857 error = histedit_check_script(&histedit_cmds, &commits, repo);
8858 if (error)
8859 goto done;
8861 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8862 if (resume_commit_id) {
8863 if (got_object_id_cmp(hle->commit_id,
8864 resume_commit_id) != 0)
8865 continue;
8867 resume_commit_id = NULL;
8868 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8869 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8870 error = histedit_skip_commit(hle, worktree,
8871 repo);
8872 if (error)
8873 goto done;
8874 } else {
8875 struct got_pathlist_head paths;
8876 int have_changes = 0;
8878 TAILQ_INIT(&paths);
8879 error = got_pathlist_append(&paths, "", NULL);
8880 if (error)
8881 goto done;
8882 error = got_worktree_status(worktree, &paths,
8883 repo, check_local_changes, &have_changes,
8884 check_cancelled, NULL);
8885 got_pathlist_free(&paths);
8886 if (error) {
8887 if (error->code != GOT_ERR_CANCELLED)
8888 goto done;
8889 if (sigint_received || sigpipe_received)
8890 goto done;
8892 if (have_changes) {
8893 error = histedit_commit(NULL, worktree,
8894 fileindex, tmp_branch, hle, repo);
8895 if (error)
8896 goto done;
8897 } else {
8898 error = got_object_open_as_commit(
8899 &commit, repo, hle->commit_id);
8900 if (error)
8901 goto done;
8902 error = show_histedit_progress(commit,
8903 hle, NULL);
8904 got_object_commit_close(commit);
8905 commit = NULL;
8906 if (error)
8907 goto done;
8910 continue;
8913 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8914 error = histedit_skip_commit(hle, worktree, repo);
8915 if (error)
8916 goto done;
8917 continue;
8920 error = got_object_open_as_commit(&commit, repo,
8921 hle->commit_id);
8922 if (error)
8923 goto done;
8924 parent_ids = got_object_commit_get_parent_ids(commit);
8925 pid = SIMPLEQ_FIRST(parent_ids);
8927 error = got_worktree_histedit_merge_files(&merged_paths,
8928 worktree, fileindex, pid->id, hle->commit_id, repo,
8929 update_progress, &upa, check_cancelled, NULL);
8930 if (error)
8931 goto done;
8932 got_object_commit_close(commit);
8933 commit = NULL;
8935 print_update_progress_stats(&upa);
8936 if (upa.conflicts > 0)
8937 rebase_status = GOT_STATUS_CONFLICT;
8939 if (rebase_status == GOT_STATUS_CONFLICT) {
8940 error = show_rebase_merge_conflict(hle->commit_id,
8941 repo);
8942 if (error)
8943 goto done;
8944 got_worktree_rebase_pathlist_free(&merged_paths);
8945 break;
8948 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8949 char *id_str;
8950 error = got_object_id_str(&id_str, hle->commit_id);
8951 if (error)
8952 goto done;
8953 printf("Stopping histedit for amending commit %s\n",
8954 id_str);
8955 free(id_str);
8956 got_worktree_rebase_pathlist_free(&merged_paths);
8957 error = got_worktree_histedit_postpone(worktree,
8958 fileindex);
8959 goto done;
8962 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8963 error = histedit_skip_commit(hle, worktree, repo);
8964 if (error)
8965 goto done;
8966 continue;
8969 error = histedit_commit(&merged_paths, worktree, fileindex,
8970 tmp_branch, hle, repo);
8971 got_worktree_rebase_pathlist_free(&merged_paths);
8972 if (error)
8973 goto done;
8976 if (rebase_status == GOT_STATUS_CONFLICT) {
8977 error = got_worktree_histedit_postpone(worktree, fileindex);
8978 if (error)
8979 goto done;
8980 error = got_error_msg(GOT_ERR_CONFLICTS,
8981 "conflicts must be resolved before histedit can continue");
8982 } else
8983 error = histedit_complete(worktree, fileindex, tmp_branch,
8984 branch, repo);
8985 done:
8986 got_object_id_queue_free(&commits);
8987 histedit_free_list(&histedit_cmds);
8988 free(head_commit_id);
8989 free(base_commit_id);
8990 free(resume_commit_id);
8991 if (commit)
8992 got_object_commit_close(commit);
8993 if (branch)
8994 got_ref_close(branch);
8995 if (tmp_branch)
8996 got_ref_close(tmp_branch);
8997 if (worktree)
8998 got_worktree_close(worktree);
8999 if (repo)
9000 got_repo_close(repo);
9001 return error;
9004 __dead static void
9005 usage_integrate(void)
9007 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9008 exit(1);
9011 static const struct got_error *
9012 cmd_integrate(int argc, char *argv[])
9014 const struct got_error *error = NULL;
9015 struct got_repository *repo = NULL;
9016 struct got_worktree *worktree = NULL;
9017 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9018 const char *branch_arg = NULL;
9019 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9020 struct got_fileindex *fileindex = NULL;
9021 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9022 int ch;
9023 struct got_update_progress_arg upa;
9025 while ((ch = getopt(argc, argv, "")) != -1) {
9026 switch (ch) {
9027 default:
9028 usage_integrate();
9029 /* NOTREACHED */
9033 argc -= optind;
9034 argv += optind;
9036 if (argc != 1)
9037 usage_integrate();
9038 branch_arg = argv[0];
9039 #ifndef PROFILE
9040 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9041 "unveil", NULL) == -1)
9042 err(1, "pledge");
9043 #endif
9044 cwd = getcwd(NULL, 0);
9045 if (cwd == NULL) {
9046 error = got_error_from_errno("getcwd");
9047 goto done;
9050 error = got_worktree_open(&worktree, cwd);
9051 if (error) {
9052 if (error->code == GOT_ERR_NOT_WORKTREE)
9053 error = wrap_not_worktree_error(error, "integrate",
9054 cwd);
9055 goto done;
9058 error = check_rebase_or_histedit_in_progress(worktree);
9059 if (error)
9060 goto done;
9062 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9063 NULL);
9064 if (error != NULL)
9065 goto done;
9067 error = apply_unveil(got_repo_get_path(repo), 0,
9068 got_worktree_get_root_path(worktree));
9069 if (error)
9070 goto done;
9072 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9073 error = got_error_from_errno("asprintf");
9074 goto done;
9077 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9078 &base_branch_ref, worktree, refname, repo);
9079 if (error)
9080 goto done;
9082 refname = strdup(got_ref_get_name(branch_ref));
9083 if (refname == NULL) {
9084 error = got_error_from_errno("strdup");
9085 got_worktree_integrate_abort(worktree, fileindex, repo,
9086 branch_ref, base_branch_ref);
9087 goto done;
9089 base_refname = strdup(got_ref_get_name(base_branch_ref));
9090 if (base_refname == NULL) {
9091 error = got_error_from_errno("strdup");
9092 got_worktree_integrate_abort(worktree, fileindex, repo,
9093 branch_ref, base_branch_ref);
9094 goto done;
9097 error = got_ref_resolve(&commit_id, repo, branch_ref);
9098 if (error)
9099 goto done;
9101 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9102 if (error)
9103 goto done;
9105 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9106 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9107 "specified branch has already been integrated");
9108 got_worktree_integrate_abort(worktree, fileindex, repo,
9109 branch_ref, base_branch_ref);
9110 goto done;
9113 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9114 if (error) {
9115 if (error->code == GOT_ERR_ANCESTRY)
9116 error = got_error(GOT_ERR_REBASE_REQUIRED);
9117 got_worktree_integrate_abort(worktree, fileindex, repo,
9118 branch_ref, base_branch_ref);
9119 goto done;
9122 memset(&upa, 0, sizeof(upa));
9123 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9124 branch_ref, base_branch_ref, update_progress, &upa,
9125 check_cancelled, NULL);
9126 if (error)
9127 goto done;
9129 printf("Integrated %s into %s\n", refname, base_refname);
9130 print_update_progress_stats(&upa);
9131 done:
9132 if (repo)
9133 got_repo_close(repo);
9134 if (worktree)
9135 got_worktree_close(worktree);
9136 free(cwd);
9137 free(base_commit_id);
9138 free(commit_id);
9139 free(refname);
9140 free(base_refname);
9141 return error;
9144 __dead static void
9145 usage_stage(void)
9147 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9148 "[-S] [file-path ...]\n",
9149 getprogname());
9150 exit(1);
9153 static const struct got_error *
9154 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9155 const char *path, struct got_object_id *blob_id,
9156 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9157 int dirfd, const char *de_name)
9159 const struct got_error *err = NULL;
9160 char *id_str = NULL;
9162 if (staged_status != GOT_STATUS_ADD &&
9163 staged_status != GOT_STATUS_MODIFY &&
9164 staged_status != GOT_STATUS_DELETE)
9165 return NULL;
9167 if (staged_status == GOT_STATUS_ADD ||
9168 staged_status == GOT_STATUS_MODIFY)
9169 err = got_object_id_str(&id_str, staged_blob_id);
9170 else
9171 err = got_object_id_str(&id_str, blob_id);
9172 if (err)
9173 return err;
9175 printf("%s %c %s\n", id_str, staged_status, path);
9176 free(id_str);
9177 return NULL;
9180 static const struct got_error *
9181 cmd_stage(int argc, char *argv[])
9183 const struct got_error *error = NULL;
9184 struct got_repository *repo = NULL;
9185 struct got_worktree *worktree = NULL;
9186 char *cwd = NULL;
9187 struct got_pathlist_head paths;
9188 struct got_pathlist_entry *pe;
9189 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9190 FILE *patch_script_file = NULL;
9191 const char *patch_script_path = NULL;
9192 struct choose_patch_arg cpa;
9194 TAILQ_INIT(&paths);
9196 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9197 switch (ch) {
9198 case 'l':
9199 list_stage = 1;
9200 break;
9201 case 'p':
9202 pflag = 1;
9203 break;
9204 case 'F':
9205 patch_script_path = optarg;
9206 break;
9207 case 'S':
9208 allow_bad_symlinks = 1;
9209 break;
9210 default:
9211 usage_stage();
9212 /* NOTREACHED */
9216 argc -= optind;
9217 argv += optind;
9219 #ifndef PROFILE
9220 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9221 "unveil", NULL) == -1)
9222 err(1, "pledge");
9223 #endif
9224 if (list_stage && (pflag || patch_script_path))
9225 errx(1, "-l option cannot be used with other options");
9226 if (patch_script_path && !pflag)
9227 errx(1, "-F option can only be used together with -p option");
9229 cwd = getcwd(NULL, 0);
9230 if (cwd == NULL) {
9231 error = got_error_from_errno("getcwd");
9232 goto done;
9235 error = got_worktree_open(&worktree, cwd);
9236 if (error) {
9237 if (error->code == GOT_ERR_NOT_WORKTREE)
9238 error = wrap_not_worktree_error(error, "stage", cwd);
9239 goto done;
9242 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9243 NULL);
9244 if (error != NULL)
9245 goto done;
9247 if (patch_script_path) {
9248 patch_script_file = fopen(patch_script_path, "r");
9249 if (patch_script_file == NULL) {
9250 error = got_error_from_errno2("fopen",
9251 patch_script_path);
9252 goto done;
9255 error = apply_unveil(got_repo_get_path(repo), 0,
9256 got_worktree_get_root_path(worktree));
9257 if (error)
9258 goto done;
9260 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9261 if (error)
9262 goto done;
9264 if (list_stage)
9265 error = got_worktree_status(worktree, &paths, repo,
9266 print_stage, NULL, check_cancelled, NULL);
9267 else {
9268 cpa.patch_script_file = patch_script_file;
9269 cpa.action = "stage";
9270 error = got_worktree_stage(worktree, &paths,
9271 pflag ? NULL : print_status, NULL,
9272 pflag ? choose_patch : NULL, &cpa,
9273 allow_bad_symlinks, repo);
9275 done:
9276 if (patch_script_file && fclose(patch_script_file) == EOF &&
9277 error == NULL)
9278 error = got_error_from_errno2("fclose", patch_script_path);
9279 if (repo)
9280 got_repo_close(repo);
9281 if (worktree)
9282 got_worktree_close(worktree);
9283 TAILQ_FOREACH(pe, &paths, entry)
9284 free((char *)pe->path);
9285 got_pathlist_free(&paths);
9286 free(cwd);
9287 return error;
9290 __dead static void
9291 usage_unstage(void)
9293 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9294 "[file-path ...]\n",
9295 getprogname());
9296 exit(1);
9300 static const struct got_error *
9301 cmd_unstage(int argc, char *argv[])
9303 const struct got_error *error = NULL;
9304 struct got_repository *repo = NULL;
9305 struct got_worktree *worktree = NULL;
9306 char *cwd = NULL;
9307 struct got_pathlist_head paths;
9308 struct got_pathlist_entry *pe;
9309 int ch, pflag = 0;
9310 struct got_update_progress_arg upa;
9311 FILE *patch_script_file = NULL;
9312 const char *patch_script_path = NULL;
9313 struct choose_patch_arg cpa;
9315 TAILQ_INIT(&paths);
9317 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9318 switch (ch) {
9319 case 'p':
9320 pflag = 1;
9321 break;
9322 case 'F':
9323 patch_script_path = optarg;
9324 break;
9325 default:
9326 usage_unstage();
9327 /* NOTREACHED */
9331 argc -= optind;
9332 argv += optind;
9334 #ifndef PROFILE
9335 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9336 "unveil", NULL) == -1)
9337 err(1, "pledge");
9338 #endif
9339 if (patch_script_path && !pflag)
9340 errx(1, "-F option can only be used together with -p option");
9342 cwd = getcwd(NULL, 0);
9343 if (cwd == NULL) {
9344 error = got_error_from_errno("getcwd");
9345 goto done;
9348 error = got_worktree_open(&worktree, cwd);
9349 if (error) {
9350 if (error->code == GOT_ERR_NOT_WORKTREE)
9351 error = wrap_not_worktree_error(error, "unstage", cwd);
9352 goto done;
9355 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9356 NULL);
9357 if (error != NULL)
9358 goto done;
9360 if (patch_script_path) {
9361 patch_script_file = fopen(patch_script_path, "r");
9362 if (patch_script_file == NULL) {
9363 error = got_error_from_errno2("fopen",
9364 patch_script_path);
9365 goto done;
9369 error = apply_unveil(got_repo_get_path(repo), 0,
9370 got_worktree_get_root_path(worktree));
9371 if (error)
9372 goto done;
9374 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9375 if (error)
9376 goto done;
9378 cpa.patch_script_file = patch_script_file;
9379 cpa.action = "unstage";
9380 memset(&upa, 0, sizeof(upa));
9381 error = got_worktree_unstage(worktree, &paths, update_progress,
9382 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9383 if (!error)
9384 print_update_progress_stats(&upa);
9385 done:
9386 if (patch_script_file && fclose(patch_script_file) == EOF &&
9387 error == NULL)
9388 error = got_error_from_errno2("fclose", patch_script_path);
9389 if (repo)
9390 got_repo_close(repo);
9391 if (worktree)
9392 got_worktree_close(worktree);
9393 TAILQ_FOREACH(pe, &paths, entry)
9394 free((char *)pe->path);
9395 got_pathlist_free(&paths);
9396 free(cwd);
9397 return error;
9400 __dead static void
9401 usage_cat(void)
9403 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9404 "arg1 [arg2 ...]\n", getprogname());
9405 exit(1);
9408 static const struct got_error *
9409 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9411 const struct got_error *err;
9412 struct got_blob_object *blob;
9414 err = got_object_open_as_blob(&blob, repo, id, 8192);
9415 if (err)
9416 return err;
9418 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9419 got_object_blob_close(blob);
9420 return err;
9423 static const struct got_error *
9424 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9426 const struct got_error *err;
9427 struct got_tree_object *tree;
9428 int nentries, i;
9430 err = got_object_open_as_tree(&tree, repo, id);
9431 if (err)
9432 return err;
9434 nentries = got_object_tree_get_nentries(tree);
9435 for (i = 0; i < nentries; i++) {
9436 struct got_tree_entry *te;
9437 char *id_str;
9438 if (sigint_received || sigpipe_received)
9439 break;
9440 te = got_object_tree_get_entry(tree, i);
9441 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9442 if (err)
9443 break;
9444 fprintf(outfile, "%s %.7o %s\n", id_str,
9445 got_tree_entry_get_mode(te),
9446 got_tree_entry_get_name(te));
9447 free(id_str);
9450 got_object_tree_close(tree);
9451 return err;
9454 static const struct got_error *
9455 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9457 const struct got_error *err;
9458 struct got_commit_object *commit;
9459 const struct got_object_id_queue *parent_ids;
9460 struct got_object_qid *pid;
9461 char *id_str = NULL;
9462 const char *logmsg = NULL;
9464 err = got_object_open_as_commit(&commit, repo, id);
9465 if (err)
9466 return err;
9468 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9469 if (err)
9470 goto done;
9472 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9473 parent_ids = got_object_commit_get_parent_ids(commit);
9474 fprintf(outfile, "numparents %d\n",
9475 got_object_commit_get_nparents(commit));
9476 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9477 char *pid_str;
9478 err = got_object_id_str(&pid_str, pid->id);
9479 if (err)
9480 goto done;
9481 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9482 free(pid_str);
9484 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9485 got_object_commit_get_author(commit),
9486 (long long)got_object_commit_get_author_time(commit));
9488 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9489 got_object_commit_get_author(commit),
9490 (long long)got_object_commit_get_committer_time(commit));
9492 logmsg = got_object_commit_get_logmsg_raw(commit);
9493 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9494 fprintf(outfile, "%s", logmsg);
9495 done:
9496 free(id_str);
9497 got_object_commit_close(commit);
9498 return err;
9501 static const struct got_error *
9502 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9504 const struct got_error *err;
9505 struct got_tag_object *tag;
9506 char *id_str = NULL;
9507 const char *tagmsg = NULL;
9509 err = got_object_open_as_tag(&tag, repo, id);
9510 if (err)
9511 return err;
9513 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9514 if (err)
9515 goto done;
9517 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9519 switch (got_object_tag_get_object_type(tag)) {
9520 case GOT_OBJ_TYPE_BLOB:
9521 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9522 GOT_OBJ_LABEL_BLOB);
9523 break;
9524 case GOT_OBJ_TYPE_TREE:
9525 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9526 GOT_OBJ_LABEL_TREE);
9527 break;
9528 case GOT_OBJ_TYPE_COMMIT:
9529 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9530 GOT_OBJ_LABEL_COMMIT);
9531 break;
9532 case GOT_OBJ_TYPE_TAG:
9533 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9534 GOT_OBJ_LABEL_TAG);
9535 break;
9536 default:
9537 break;
9540 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9541 got_object_tag_get_name(tag));
9543 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9544 got_object_tag_get_tagger(tag),
9545 (long long)got_object_tag_get_tagger_time(tag));
9547 tagmsg = got_object_tag_get_message(tag);
9548 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9549 fprintf(outfile, "%s", tagmsg);
9550 done:
9551 free(id_str);
9552 got_object_tag_close(tag);
9553 return err;
9556 static const struct got_error *
9557 cmd_cat(int argc, char *argv[])
9559 const struct got_error *error;
9560 struct got_repository *repo = NULL;
9561 struct got_worktree *worktree = NULL;
9562 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9563 const char *commit_id_str = NULL;
9564 struct got_object_id *id = NULL, *commit_id = NULL;
9565 int ch, obj_type, i, force_path = 0;
9567 #ifndef PROFILE
9568 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9569 NULL) == -1)
9570 err(1, "pledge");
9571 #endif
9573 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9574 switch (ch) {
9575 case 'c':
9576 commit_id_str = optarg;
9577 break;
9578 case 'r':
9579 repo_path = realpath(optarg, NULL);
9580 if (repo_path == NULL)
9581 return got_error_from_errno2("realpath",
9582 optarg);
9583 got_path_strip_trailing_slashes(repo_path);
9584 break;
9585 case 'P':
9586 force_path = 1;
9587 break;
9588 default:
9589 usage_cat();
9590 /* NOTREACHED */
9594 argc -= optind;
9595 argv += optind;
9597 cwd = getcwd(NULL, 0);
9598 if (cwd == NULL) {
9599 error = got_error_from_errno("getcwd");
9600 goto done;
9602 error = got_worktree_open(&worktree, cwd);
9603 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9604 goto done;
9605 if (worktree) {
9606 if (repo_path == NULL) {
9607 repo_path = strdup(
9608 got_worktree_get_repo_path(worktree));
9609 if (repo_path == NULL) {
9610 error = got_error_from_errno("strdup");
9611 goto done;
9616 if (repo_path == NULL) {
9617 repo_path = getcwd(NULL, 0);
9618 if (repo_path == NULL)
9619 return got_error_from_errno("getcwd");
9622 error = got_repo_open(&repo, repo_path, NULL);
9623 free(repo_path);
9624 if (error != NULL)
9625 goto done;
9627 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9628 if (error)
9629 goto done;
9631 if (commit_id_str == NULL)
9632 commit_id_str = GOT_REF_HEAD;
9633 error = got_repo_match_object_id(&commit_id, NULL,
9634 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9635 if (error)
9636 goto done;
9638 for (i = 0; i < argc; i++) {
9639 if (force_path) {
9640 error = got_object_id_by_path(&id, repo, commit_id,
9641 argv[i]);
9642 if (error)
9643 break;
9644 } else {
9645 error = got_repo_match_object_id(&id, &label, argv[i],
9646 GOT_OBJ_TYPE_ANY, 0, repo);
9647 if (error) {
9648 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9649 error->code != GOT_ERR_NOT_REF)
9650 break;
9651 error = got_object_id_by_path(&id, repo,
9652 commit_id, argv[i]);
9653 if (error)
9654 break;
9658 error = got_object_get_type(&obj_type, repo, id);
9659 if (error)
9660 break;
9662 switch (obj_type) {
9663 case GOT_OBJ_TYPE_BLOB:
9664 error = cat_blob(id, repo, stdout);
9665 break;
9666 case GOT_OBJ_TYPE_TREE:
9667 error = cat_tree(id, repo, stdout);
9668 break;
9669 case GOT_OBJ_TYPE_COMMIT:
9670 error = cat_commit(id, repo, stdout);
9671 break;
9672 case GOT_OBJ_TYPE_TAG:
9673 error = cat_tag(id, repo, stdout);
9674 break;
9675 default:
9676 error = got_error(GOT_ERR_OBJ_TYPE);
9677 break;
9679 if (error)
9680 break;
9681 free(label);
9682 label = NULL;
9683 free(id);
9684 id = NULL;
9686 done:
9687 free(label);
9688 free(id);
9689 free(commit_id);
9690 if (worktree)
9691 got_worktree_close(worktree);
9692 if (repo) {
9693 const struct got_error *repo_error;
9694 repo_error = got_repo_close(repo);
9695 if (error == NULL)
9696 error = repo_error;
9698 return error;
9701 __dead static void
9702 usage_info(void)
9704 fprintf(stderr, "usage: %s info [path ...]\n",
9705 getprogname());
9706 exit(1);
9709 static const struct got_error *
9710 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9711 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9712 struct got_object_id *commit_id)
9714 const struct got_error *err = NULL;
9715 char *id_str = NULL;
9716 char datebuf[128];
9717 struct tm mytm, *tm;
9718 struct got_pathlist_head *paths = arg;
9719 struct got_pathlist_entry *pe;
9722 * Clear error indication from any of the path arguments which
9723 * would cause this file index entry to be displayed.
9725 TAILQ_FOREACH(pe, paths, entry) {
9726 if (got_path_cmp(path, pe->path, strlen(path),
9727 pe->path_len) == 0 ||
9728 got_path_is_child(path, pe->path, pe->path_len))
9729 pe->data = NULL; /* no error */
9732 printf(GOT_COMMIT_SEP_STR);
9733 if (S_ISLNK(mode))
9734 printf("symlink: %s\n", path);
9735 else if (S_ISREG(mode)) {
9736 printf("file: %s\n", path);
9737 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9738 } else if (S_ISDIR(mode))
9739 printf("directory: %s\n", path);
9740 else
9741 printf("something: %s\n", path);
9743 tm = localtime_r(&mtime, &mytm);
9744 if (tm == NULL)
9745 return NULL;
9746 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9747 return got_error(GOT_ERR_NO_SPACE);
9748 printf("timestamp: %s\n", datebuf);
9750 if (blob_id) {
9751 err = got_object_id_str(&id_str, blob_id);
9752 if (err)
9753 return err;
9754 printf("based on blob: %s\n", id_str);
9755 free(id_str);
9758 if (staged_blob_id) {
9759 err = got_object_id_str(&id_str, staged_blob_id);
9760 if (err)
9761 return err;
9762 printf("based on staged blob: %s\n", id_str);
9763 free(id_str);
9766 if (commit_id) {
9767 err = got_object_id_str(&id_str, commit_id);
9768 if (err)
9769 return err;
9770 printf("based on commit: %s\n", id_str);
9771 free(id_str);
9774 return NULL;
9777 static const struct got_error *
9778 cmd_info(int argc, char *argv[])
9780 const struct got_error *error = NULL;
9781 struct got_worktree *worktree = NULL;
9782 char *cwd = NULL, *id_str = NULL;
9783 struct got_pathlist_head paths;
9784 struct got_pathlist_entry *pe;
9785 char *uuidstr = NULL;
9786 int ch, show_files = 0;
9788 TAILQ_INIT(&paths);
9790 while ((ch = getopt(argc, argv, "")) != -1) {
9791 switch (ch) {
9792 default:
9793 usage_info();
9794 /* NOTREACHED */
9798 argc -= optind;
9799 argv += optind;
9801 #ifndef PROFILE
9802 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9803 NULL) == -1)
9804 err(1, "pledge");
9805 #endif
9806 cwd = getcwd(NULL, 0);
9807 if (cwd == NULL) {
9808 error = got_error_from_errno("getcwd");
9809 goto done;
9812 error = got_worktree_open(&worktree, cwd);
9813 if (error) {
9814 if (error->code == GOT_ERR_NOT_WORKTREE)
9815 error = wrap_not_worktree_error(error, "status", cwd);
9816 goto done;
9819 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9820 if (error)
9821 goto done;
9823 if (argc >= 1) {
9824 error = get_worktree_paths_from_argv(&paths, argc, argv,
9825 worktree);
9826 if (error)
9827 goto done;
9828 show_files = 1;
9831 error = got_object_id_str(&id_str,
9832 got_worktree_get_base_commit_id(worktree));
9833 if (error)
9834 goto done;
9836 error = got_worktree_get_uuid(&uuidstr, worktree);
9837 if (error)
9838 goto done;
9840 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9841 printf("work tree base commit: %s\n", id_str);
9842 printf("work tree path prefix: %s\n",
9843 got_worktree_get_path_prefix(worktree));
9844 printf("work tree branch reference: %s\n",
9845 got_worktree_get_head_ref_name(worktree));
9846 printf("work tree UUID: %s\n", uuidstr);
9847 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9849 if (show_files) {
9850 struct got_pathlist_entry *pe;
9851 TAILQ_FOREACH(pe, &paths, entry) {
9852 if (pe->path_len == 0)
9853 continue;
9855 * Assume this path will fail. This will be corrected
9856 * in print_path_info() in case the path does suceeed.
9858 pe->data = (void *)got_error_path(pe->path,
9859 GOT_ERR_BAD_PATH);
9861 error = got_worktree_path_info(worktree, &paths,
9862 print_path_info, &paths, check_cancelled, NULL);
9863 if (error)
9864 goto done;
9865 TAILQ_FOREACH(pe, &paths, entry) {
9866 if (pe->data != NULL) {
9867 error = pe->data; /* bad path */
9868 break;
9872 done:
9873 TAILQ_FOREACH(pe, &paths, entry)
9874 free((char *)pe->path);
9875 got_pathlist_free(&paths);
9876 free(cwd);
9877 free(id_str);
9878 free(uuidstr);
9879 return error;