Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 int i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0 }
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag, 1);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 1;
217 optreset = 1;
219 if (Vflag) {
220 got_version_print_str();
221 return 0;
224 if (argc <= 0)
225 usage(hflag, hflag ? 0 : 1);
227 signal(SIGINT, catch_sigint);
228 signal(SIGPIPE, catch_sigpipe);
230 for (i = 0; i < nitems(got_commands); i++) {
231 const struct got_error *error;
233 cmd = &got_commands[i];
235 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
236 strcmp(cmd->cmd_alias, argv[0]) != 0)
237 continue;
239 if (hflag)
240 got_commands[i].cmd_usage();
242 error = got_commands[i].cmd_main(argc, argv);
243 if (error && error->code != GOT_ERR_CANCELLED &&
244 error->code != GOT_ERR_PRIVSEP_EXIT &&
245 !(sigpipe_received &&
246 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
247 !(sigint_received &&
248 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
249 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
250 return 1;
253 return 0;
256 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
257 list_commands(stderr);
258 return 1;
261 __dead static void
262 usage(int hflag, int status)
264 FILE *fp = (status == 0) ? stdout : stderr;
266 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
267 getprogname());
268 if (hflag)
269 list_commands(fp);
270 exit(status);
273 static const struct got_error *
274 get_editor(char **abspath)
276 const struct got_error *err = NULL;
277 const char *editor;
279 *abspath = NULL;
281 editor = getenv("VISUAL");
282 if (editor == NULL)
283 editor = getenv("EDITOR");
285 if (editor) {
286 err = got_path_find_prog(abspath, editor);
287 if (err)
288 return err;
291 if (*abspath == NULL) {
292 *abspath = strdup("/bin/ed");
293 if (*abspath == NULL)
294 return got_error_from_errno("strdup");
297 return NULL;
300 static const struct got_error *
301 apply_unveil(const char *repo_path, int repo_read_only,
302 const char *worktree_path)
304 const struct got_error *err;
306 #ifdef PROFILE
307 if (unveil("gmon.out", "rwc") != 0)
308 return got_error_from_errno2("unveil", "gmon.out");
309 #endif
310 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
311 return got_error_from_errno2("unveil", repo_path);
313 if (worktree_path && unveil(worktree_path, "rwc") != 0)
314 return got_error_from_errno2("unveil", worktree_path);
316 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
317 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
319 err = got_privsep_unveil_exec_helpers();
320 if (err != NULL)
321 return err;
323 if (unveil(NULL, NULL) != 0)
324 return got_error_from_errno("unveil");
326 return NULL;
329 __dead static void
330 usage_init(void)
332 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
333 exit(1);
336 static const struct got_error *
337 cmd_init(int argc, char *argv[])
339 const struct got_error *error = NULL;
340 char *repo_path = NULL;
341 int ch;
343 while ((ch = getopt(argc, argv, "")) != -1) {
344 switch (ch) {
345 default:
346 usage_init();
347 /* NOTREACHED */
351 argc -= optind;
352 argv += optind;
354 #ifndef PROFILE
355 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
356 err(1, "pledge");
357 #endif
358 if (argc != 1)
359 usage_init();
361 repo_path = strdup(argv[0]);
362 if (repo_path == NULL)
363 return got_error_from_errno("strdup");
365 got_path_strip_trailing_slashes(repo_path);
367 error = got_path_mkdir(repo_path);
368 if (error &&
369 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
370 goto done;
372 error = apply_unveil(repo_path, 0, NULL);
373 if (error)
374 goto done;
376 error = got_repo_init(repo_path);
377 done:
378 free(repo_path);
379 return error;
382 __dead static void
383 usage_import(void)
385 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
386 "[-r repository-path] [-I pattern] path\n", getprogname());
387 exit(1);
390 int
391 spawn_editor(const char *editor, const char *file)
393 pid_t pid;
394 sig_t sighup, sigint, sigquit;
395 int st = -1;
397 sighup = signal(SIGHUP, SIG_IGN);
398 sigint = signal(SIGINT, SIG_IGN);
399 sigquit = signal(SIGQUIT, SIG_IGN);
401 switch (pid = fork()) {
402 case -1:
403 goto doneediting;
404 case 0:
405 execl(editor, editor, file, (char *)NULL);
406 _exit(127);
409 while (waitpid(pid, &st, 0) == -1)
410 if (errno != EINTR)
411 break;
413 doneediting:
414 (void)signal(SIGHUP, sighup);
415 (void)signal(SIGINT, sigint);
416 (void)signal(SIGQUIT, sigquit);
418 if (!WIFEXITED(st)) {
419 errno = EINTR;
420 return -1;
423 return WEXITSTATUS(st);
426 static const struct got_error *
427 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
428 const char *initial_content, size_t initial_content_len)
430 const struct got_error *err = NULL;
431 char *line = NULL;
432 size_t linesize = 0;
433 ssize_t linelen;
434 struct stat st, st2;
435 FILE *fp = NULL;
436 size_t len, logmsg_len;
437 char *initial_content_stripped = NULL, *buf = NULL, *s;
439 *logmsg = NULL;
441 if (stat(logmsg_path, &st) == -1)
442 return got_error_from_errno2("stat", logmsg_path);
444 if (spawn_editor(editor, logmsg_path) == -1)
445 return got_error_from_errno("failed spawning editor");
447 if (stat(logmsg_path, &st2) == -1)
448 return got_error_from_errno("stat");
450 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
451 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
452 "no changes made to commit message, aborting");
454 /*
455 * Set up a stripped version of the initial content without comments
456 * and blank lines. We need this in order to check if the message
457 * has in fact been edited.
458 */
459 initial_content_stripped = malloc(initial_content_len + 1);
460 if (initial_content_stripped == NULL)
461 return got_error_from_errno("malloc");
462 initial_content_stripped[0] = '\0';
464 buf = strdup(initial_content);
465 if (buf == NULL) {
466 err = got_error_from_errno("strdup");
467 goto done;
469 s = buf;
470 len = 0;
471 while ((line = strsep(&s, "\n")) != NULL) {
472 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
473 continue; /* remove comments and leading empty lines */
474 len = strlcat(initial_content_stripped, line,
475 initial_content_len + 1);
476 if (len >= initial_content_len + 1) {
477 err = got_error(GOT_ERR_NO_SPACE);
478 goto done;
481 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
482 initial_content_stripped[len - 1] = '\0';
483 len--;
486 logmsg_len = st2.st_size;
487 *logmsg = malloc(logmsg_len + 1);
488 if (*logmsg == NULL)
489 return got_error_from_errno("malloc");
490 (*logmsg)[0] = '\0';
492 fp = fopen(logmsg_path, "r");
493 if (fp == NULL) {
494 err = got_error_from_errno("fopen");
495 goto done;
498 len = 0;
499 while ((linelen = getline(&line, &linesize, fp)) != -1) {
500 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
501 continue; /* remove comments and leading empty lines */
502 len = strlcat(*logmsg, line, logmsg_len + 1);
503 if (len >= logmsg_len + 1) {
504 err = got_error(GOT_ERR_NO_SPACE);
505 goto done;
508 free(line);
509 if (ferror(fp)) {
510 err = got_ferror(fp, GOT_ERR_IO);
511 goto done;
513 while (len > 0 && (*logmsg)[len - 1] == '\n') {
514 (*logmsg)[len - 1] = '\0';
515 len--;
518 if (len == 0) {
519 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
520 "commit message cannot be empty, aborting");
521 goto done;
523 if (strcmp(*logmsg, initial_content_stripped) == 0)
524 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
525 "no changes made to commit message, aborting");
526 done:
527 free(initial_content_stripped);
528 free(buf);
529 if (fp && fclose(fp) == EOF && err == NULL)
530 err = got_error_from_errno("fclose");
531 if (err) {
532 free(*logmsg);
533 *logmsg = NULL;
535 return err;
538 static const struct got_error *
539 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
540 const char *path_dir, const char *branch_name)
542 char *initial_content = NULL;
543 const struct got_error *err = NULL;
544 int initial_content_len;
545 int fd = -1;
547 initial_content_len = asprintf(&initial_content,
548 "\n# %s to be imported to branch %s\n", path_dir,
549 branch_name);
550 if (initial_content_len == -1)
551 return got_error_from_errno("asprintf");
553 err = got_opentemp_named_fd(logmsg_path, &fd,
554 GOT_TMPDIR_STR "/got-importmsg");
555 if (err)
556 goto done;
558 if (write(fd, initial_content, initial_content_len) == -1) {
559 err = got_error_from_errno2("write", *logmsg_path);
560 goto done;
563 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
564 initial_content_len);
565 done:
566 if (fd != -1 && close(fd) == -1 && err == NULL)
567 err = got_error_from_errno2("close", *logmsg_path);
568 free(initial_content);
569 if (err) {
570 free(*logmsg_path);
571 *logmsg_path = NULL;
573 return err;
576 static const struct got_error *
577 import_progress(void *arg, const char *path)
579 printf("A %s\n", path);
580 return NULL;
583 static const struct got_error *
584 get_author(char **author, struct got_repository *repo,
585 struct got_worktree *worktree)
587 const struct got_error *err = NULL;
588 const char *got_author = NULL, *name, *email;
589 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
591 *author = NULL;
593 if (worktree)
594 worktree_conf = got_worktree_get_gotconfig(worktree);
595 repo_conf = got_repo_get_gotconfig(repo);
597 /*
598 * Priority of potential author information sources, from most
599 * significant to least significant:
600 * 1) work tree's .got/got.conf file
601 * 2) repository's got.conf file
602 * 3) repository's git config file
603 * 4) environment variables
604 * 5) global git config files (in user's home directory or /etc)
605 */
607 if (worktree_conf)
608 got_author = got_gotconfig_get_author(worktree_conf);
609 if (got_author == NULL)
610 got_author = got_gotconfig_get_author(repo_conf);
611 if (got_author == NULL) {
612 name = got_repo_get_gitconfig_author_name(repo);
613 email = got_repo_get_gitconfig_author_email(repo);
614 if (name && email) {
615 if (asprintf(author, "%s <%s>", name, email) == -1)
616 return got_error_from_errno("asprintf");
617 return NULL;
620 got_author = getenv("GOT_AUTHOR");
621 if (got_author == NULL) {
622 name = got_repo_get_global_gitconfig_author_name(repo);
623 email = got_repo_get_global_gitconfig_author_email(
624 repo);
625 if (name && email) {
626 if (asprintf(author, "%s <%s>", name, email)
627 == -1)
628 return got_error_from_errno("asprintf");
629 return NULL;
631 /* TODO: Look up user in password database? */
632 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
636 *author = strdup(got_author);
637 if (*author == NULL)
638 return got_error_from_errno("strdup");
640 /*
641 * Really dumb email address check; we're only doing this to
642 * avoid git's object parser breaking on commits we create.
643 */
644 while (*got_author && *got_author != '<')
645 got_author++;
646 if (*got_author != '<') {
647 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
648 goto done;
650 while (*got_author && *got_author != '@')
651 got_author++;
652 if (*got_author != '@') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '>')
657 got_author++;
658 if (*got_author != '>')
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 done:
661 if (err) {
662 free(*author);
663 *author = NULL;
665 return err;
668 static const struct got_error *
669 get_gitconfig_path(char **gitconfig_path)
671 const char *homedir = getenv("HOME");
673 *gitconfig_path = NULL;
674 if (homedir) {
675 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
676 return got_error_from_errno("asprintf");
679 return NULL;
682 static const struct got_error *
683 cmd_import(int argc, char *argv[])
685 const struct got_error *error = NULL;
686 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
687 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
688 const char *branch_name = "main";
689 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
690 struct got_repository *repo = NULL;
691 struct got_reference *branch_ref = NULL, *head_ref = NULL;
692 struct got_object_id *new_commit_id = NULL;
693 int ch;
694 struct got_pathlist_head ignores;
695 struct got_pathlist_entry *pe;
696 int preserve_logmsg = 0;
698 TAILQ_INIT(&ignores);
700 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
701 switch (ch) {
702 case 'b':
703 branch_name = optarg;
704 break;
705 case 'm':
706 logmsg = strdup(optarg);
707 if (logmsg == NULL) {
708 error = got_error_from_errno("strdup");
709 goto done;
711 break;
712 case 'r':
713 repo_path = realpath(optarg, NULL);
714 if (repo_path == NULL) {
715 error = got_error_from_errno2("realpath",
716 optarg);
717 goto done;
719 break;
720 case 'I':
721 if (optarg[0] == '\0')
722 break;
723 error = got_pathlist_insert(&pe, &ignores, optarg,
724 NULL);
725 if (error)
726 goto done;
727 break;
728 default:
729 usage_import();
730 /* NOTREACHED */
734 argc -= optind;
735 argv += optind;
737 #ifndef PROFILE
738 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
739 "unveil",
740 NULL) == -1)
741 err(1, "pledge");
742 #endif
743 if (argc != 1)
744 usage_import();
746 if (repo_path == NULL) {
747 repo_path = getcwd(NULL, 0);
748 if (repo_path == NULL)
749 return got_error_from_errno("getcwd");
751 got_path_strip_trailing_slashes(repo_path);
752 error = get_gitconfig_path(&gitconfig_path);
753 if (error)
754 goto done;
755 error = got_repo_open(&repo, repo_path, gitconfig_path);
756 if (error)
757 goto done;
759 error = get_author(&author, repo, NULL);
760 if (error)
761 return error;
763 /*
764 * Don't let the user create a branch name with a leading '-'.
765 * While technically a valid reference name, this case is usually
766 * an unintended typo.
767 */
768 if (branch_name[0] == '-')
769 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
772 error = got_error_from_errno("asprintf");
773 goto done;
776 error = got_ref_open(&branch_ref, repo, refname, 0);
777 if (error) {
778 if (error->code != GOT_ERR_NOT_REF)
779 goto done;
780 } else {
781 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
782 "import target branch already exists");
783 goto done;
786 path_dir = realpath(argv[0], NULL);
787 if (path_dir == NULL) {
788 error = got_error_from_errno2("realpath", argv[0]);
789 goto done;
791 got_path_strip_trailing_slashes(path_dir);
793 /*
794 * unveil(2) traverses exec(2); if an editor is used we have
795 * to apply unveil after the log message has been written.
796 */
797 if (logmsg == NULL || strlen(logmsg) == 0) {
798 error = get_editor(&editor);
799 if (error)
800 goto done;
801 free(logmsg);
802 error = collect_import_msg(&logmsg, &logmsg_path, editor,
803 path_dir, refname);
804 if (error) {
805 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
806 logmsg_path != NULL)
807 preserve_logmsg = 1;
808 goto done;
812 if (unveil(path_dir, "r") != 0) {
813 error = got_error_from_errno2("unveil", path_dir);
814 if (logmsg_path)
815 preserve_logmsg = 1;
816 goto done;
819 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
820 if (error) {
821 if (logmsg_path)
822 preserve_logmsg = 1;
823 goto done;
826 error = got_repo_import(&new_commit_id, path_dir, logmsg,
827 author, &ignores, repo, import_progress, NULL);
828 if (error) {
829 if (logmsg_path)
830 preserve_logmsg = 1;
831 goto done;
834 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
835 if (error) {
836 if (logmsg_path)
837 preserve_logmsg = 1;
838 goto done;
841 error = got_ref_write(branch_ref, repo);
842 if (error) {
843 if (logmsg_path)
844 preserve_logmsg = 1;
845 goto done;
848 error = got_object_id_str(&id_str, new_commit_id);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
856 if (error) {
857 if (error->code != GOT_ERR_NOT_REF) {
858 if (logmsg_path)
859 preserve_logmsg = 1;
860 goto done;
863 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
864 branch_ref);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_write(head_ref, repo);
872 if (error) {
873 if (logmsg_path)
874 preserve_logmsg = 1;
875 goto done;
879 printf("Created branch %s with commit %s\n",
880 got_ref_get_name(branch_ref), id_str);
881 done:
882 if (preserve_logmsg) {
883 fprintf(stderr, "%s: log message preserved in %s\n",
884 getprogname(), logmsg_path);
885 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
886 error = got_error_from_errno2("unlink", logmsg_path);
887 free(logmsg);
888 free(logmsg_path);
889 free(repo_path);
890 free(editor);
891 free(refname);
892 free(new_commit_id);
893 free(id_str);
894 free(author);
895 free(gitconfig_path);
896 if (branch_ref)
897 got_ref_close(branch_ref);
898 if (head_ref)
899 got_ref_close(head_ref);
900 return error;
903 __dead static void
904 usage_clone(void)
906 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
907 "[-R reference] repository-url [directory]\n", getprogname());
908 exit(1);
911 struct got_fetch_progress_arg {
912 char last_scaled_size[FMT_SCALED_STRSIZE];
913 int last_p_indexed;
914 int last_p_resolved;
915 int verbosity;
917 struct got_repository *repo;
919 int create_configs;
920 int configs_created;
921 struct {
922 struct got_pathlist_head *symrefs;
923 struct got_pathlist_head *wanted_branches;
924 const char *proto;
925 const char *host;
926 const char *port;
927 const char *remote_repo_path;
928 const char *git_url;
929 int fetch_all_branches;
930 int mirror_references;
931 } config_info;
932 };
934 /* XXX forward declaration */
935 static const struct got_error *
936 create_config_files(const char *proto, const char *host, const char *port,
937 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
938 int mirror_references, struct got_pathlist_head *symrefs,
939 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
941 static const struct got_error *
942 fetch_progress(void *arg, const char *message, off_t packfile_size,
943 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
945 const struct got_error *err = NULL;
946 struct got_fetch_progress_arg *a = arg;
947 char scaled_size[FMT_SCALED_STRSIZE];
948 int p_indexed, p_resolved;
949 int print_size = 0, print_indexed = 0, print_resolved = 0;
951 /*
952 * In order to allow a failed clone to be resumed with 'got fetch'
953 * we try to create configuration files as soon as possible.
954 * Once the server has sent information about its default branch
955 * we have all required information.
956 */
957 if (a->create_configs && !a->configs_created &&
958 !TAILQ_EMPTY(a->config_info.symrefs)) {
959 err = create_config_files(a->config_info.proto,
960 a->config_info.host, a->config_info.port,
961 a->config_info.remote_repo_path,
962 a->config_info.git_url,
963 a->config_info.fetch_all_branches,
964 a->config_info.mirror_references,
965 a->config_info.symrefs,
966 a->config_info.wanted_branches, a->repo);
967 if (err)
968 return err;
969 a->configs_created = 1;
972 if (a->verbosity < 0)
973 return NULL;
975 if (message && message[0] != '\0') {
976 printf("\rserver: %s", message);
977 fflush(stdout);
978 return NULL;
981 if (packfile_size > 0 || nobj_indexed > 0) {
982 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
983 (a->last_scaled_size[0] == '\0' ||
984 strcmp(scaled_size, a->last_scaled_size)) != 0) {
985 print_size = 1;
986 if (strlcpy(a->last_scaled_size, scaled_size,
987 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
988 return got_error(GOT_ERR_NO_SPACE);
990 if (nobj_indexed > 0) {
991 p_indexed = (nobj_indexed * 100) / nobj_total;
992 if (p_indexed != a->last_p_indexed) {
993 a->last_p_indexed = p_indexed;
994 print_indexed = 1;
995 print_size = 1;
998 if (nobj_resolved > 0) {
999 p_resolved = (nobj_resolved * 100) /
1000 (nobj_total - nobj_loose);
1001 if (p_resolved != a->last_p_resolved) {
1002 a->last_p_resolved = p_resolved;
1003 print_resolved = 1;
1004 print_indexed = 1;
1005 print_size = 1;
1010 if (print_size || print_indexed || print_resolved)
1011 printf("\r");
1012 if (print_size)
1013 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1014 if (print_indexed)
1015 printf("; indexing %d%%", p_indexed);
1016 if (print_resolved)
1017 printf("; resolving deltas %d%%", p_resolved);
1018 if (print_size || print_indexed || print_resolved)
1019 fflush(stdout);
1021 return NULL;
1024 static const struct got_error *
1025 create_symref(const char *refname, struct got_reference *target_ref,
1026 int verbosity, struct got_repository *repo)
1028 const struct got_error *err;
1029 struct got_reference *head_symref;
1031 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1032 if (err)
1033 return err;
1035 err = got_ref_write(head_symref, repo);
1036 if (err == NULL && verbosity > 0) {
1037 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1038 got_ref_get_name(target_ref));
1040 got_ref_close(head_symref);
1041 return err;
1044 static const struct got_error *
1045 list_remote_refs(struct got_pathlist_head *symrefs,
1046 struct got_pathlist_head *refs)
1048 const struct got_error *err;
1049 struct got_pathlist_entry *pe;
1051 TAILQ_FOREACH(pe, symrefs, entry) {
1052 const char *refname = pe->path;
1053 const char *targetref = pe->data;
1055 printf("%s: %s\n", refname, targetref);
1058 TAILQ_FOREACH(pe, refs, entry) {
1059 const char *refname = pe->path;
1060 struct got_object_id *id = pe->data;
1061 char *id_str;
1063 err = got_object_id_str(&id_str, id);
1064 if (err)
1065 return err;
1066 printf("%s: %s\n", refname, id_str);
1067 free(id_str);
1070 return NULL;
1073 static const struct got_error *
1074 create_ref(const char *refname, struct got_object_id *id,
1075 int verbosity, struct got_repository *repo)
1077 const struct got_error *err = NULL;
1078 struct got_reference *ref;
1079 char *id_str;
1081 err = got_object_id_str(&id_str, id);
1082 if (err)
1083 return err;
1085 err = got_ref_alloc(&ref, refname, id);
1086 if (err)
1087 goto done;
1089 err = got_ref_write(ref, repo);
1090 got_ref_close(ref);
1092 if (err == NULL && verbosity >= 0)
1093 printf("Created reference %s: %s\n", refname, id_str);
1094 done:
1095 free(id_str);
1096 return err;
1099 static int
1100 match_wanted_ref(const char *refname, const char *wanted_ref)
1102 if (strncmp(refname, "refs/", 5) != 0)
1103 return 0;
1104 refname += 5;
1107 * Prevent fetching of references that won't make any
1108 * sense outside of the remote repository's context.
1110 if (strncmp(refname, "got/", 4) == 0)
1111 return 0;
1112 if (strncmp(refname, "remotes/", 8) == 0)
1113 return 0;
1115 if (strncmp(wanted_ref, "refs/", 5) == 0)
1116 wanted_ref += 5;
1118 /* Allow prefix match. */
1119 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1120 return 1;
1122 /* Allow exact match. */
1123 return (strcmp(refname, wanted_ref) == 0);
1126 static int
1127 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1129 struct got_pathlist_entry *pe;
1131 TAILQ_FOREACH(pe, wanted_refs, entry) {
1132 if (match_wanted_ref(refname, pe->path))
1133 return 1;
1136 return 0;
1139 static const struct got_error *
1140 create_wanted_ref(const char *refname, struct got_object_id *id,
1141 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1143 const struct got_error *err;
1144 char *remote_refname;
1146 if (strncmp("refs/", refname, 5) == 0)
1147 refname += 5;
1149 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1150 remote_repo_name, refname) == -1)
1151 return got_error_from_errno("asprintf");
1153 err = create_ref(remote_refname, id, verbosity, repo);
1154 free(remote_refname);
1155 return err;
1158 static const struct got_error *
1159 create_gotconfig(const char *proto, const char *host, const char *port,
1160 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1161 struct got_repository *repo)
1163 const struct got_error *err = NULL;
1164 char *gotconfig_path = NULL;
1165 char *gotconfig = NULL;
1166 FILE *gotconfig_file = NULL;
1167 ssize_t n;
1169 /* Create got.conf(5). */
1170 gotconfig_path = got_repo_get_path_gotconfig(repo);
1171 if (gotconfig_path == NULL) {
1172 err = got_error_from_errno("got_repo_get_path_gotconfig");
1173 goto done;
1175 gotconfig_file = fopen(gotconfig_path, "a");
1176 if (gotconfig_file == NULL) {
1177 err = got_error_from_errno2("fopen", gotconfig_path);
1178 goto done;
1180 if (asprintf(&gotconfig,
1181 "remote \"%s\" {\n"
1182 "\tserver %s\n"
1183 "\tprotocol %s\n"
1184 "%s%s%s"
1185 "\trepository \"%s\"\n"
1186 "%s"
1187 "}\n",
1188 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1189 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1190 remote_repo_path,
1191 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1196 if (n != strlen(gotconfig)) {
1197 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1198 goto done;
1201 done:
1202 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1203 err = got_error_from_errno2("fclose", gotconfig_path);
1204 free(gotconfig_path);
1205 return err;
1208 static const struct got_error *
1209 create_gitconfig(const char *git_url, const char *default_branch,
1210 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1212 const struct got_error *err = NULL;
1213 char *gitconfig_path = NULL;
1214 char *gitconfig = NULL;
1215 FILE *gitconfig_file = NULL;
1216 ssize_t n;
1218 /* Create a config file Git can understand. */
1219 gitconfig_path = got_repo_get_path_gitconfig(repo);
1220 if (gitconfig_path == NULL) {
1221 err = got_error_from_errno("got_repo_get_path_gitconfig");
1222 goto done;
1224 gitconfig_file = fopen(gitconfig_path, "a");
1225 if (gitconfig_file == NULL) {
1226 err = got_error_from_errno2("fopen", gitconfig_path);
1227 goto done;
1229 if (mirror_references) {
1230 if (asprintf(&gitconfig,
1231 "[remote \"%s\"]\n"
1232 "\turl = %s\n"
1233 "\tfetch = +refs/*:refs/*\n"
1234 "\tmirror = true\n",
1235 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1236 err = got_error_from_errno("asprintf");
1237 goto done;
1239 } else if (fetch_all_branches) {
1240 if (asprintf(&gitconfig,
1241 "[remote \"%s\"]\n"
1242 "\turl = %s\n"
1243 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1244 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1245 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1246 err = got_error_from_errno("asprintf");
1247 goto done;
1249 } else {
1250 const char *branchname;
1253 * If the server specified a default branch, use just that one.
1254 * Otherwise fall back to fetching all branches on next fetch.
1256 if (default_branch) {
1257 branchname = default_branch;
1258 if (strncmp(branchname, "refs/heads/", 11) == 0)
1259 branchname += 11;
1260 } else
1261 branchname = "*"; /* fall back to all branches */
1262 if (asprintf(&gitconfig,
1263 "[remote \"%s\"]\n"
1264 "\turl = %s\n"
1265 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1266 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1267 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1268 branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1273 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1274 if (n != strlen(gitconfig)) {
1275 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1276 goto done;
1278 done:
1279 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1280 err = got_error_from_errno2("fclose", gitconfig_path);
1281 free(gitconfig_path);
1282 return err;
1285 static const struct got_error *
1286 create_config_files(const char *proto, const char *host, const char *port,
1287 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1288 int mirror_references, struct got_pathlist_head *symrefs,
1289 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1291 const struct got_error *err = NULL;
1292 const char *default_branch = NULL;
1293 struct got_pathlist_entry *pe;
1296 * If we asked for a set of wanted branches then use the first
1297 * one of those.
1299 if (!TAILQ_EMPTY(wanted_branches)) {
1300 pe = TAILQ_FIRST(wanted_branches);
1301 default_branch = pe->path;
1302 } else {
1303 /* First HEAD ref listed by server is the default branch. */
1304 TAILQ_FOREACH(pe, symrefs, entry) {
1305 const char *refname = pe->path;
1306 const char *target = pe->data;
1308 if (strcmp(refname, GOT_REF_HEAD) != 0)
1309 continue;
1311 default_branch = target;
1312 break;
1316 /* Create got.conf(5). */
1317 err = create_gotconfig(proto, host, port, remote_repo_path,
1318 fetch_all_branches, mirror_references, repo);
1319 if (err)
1320 return err;
1322 /* Create a config file Git can understand. */
1323 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1324 mirror_references, repo);
1327 static const struct got_error *
1328 cmd_clone(int argc, char *argv[])
1330 const struct got_error *error = NULL;
1331 const char *uri, *dirname;
1332 char *proto, *host, *port, *repo_name, *server_path;
1333 char *default_destdir = NULL, *id_str = NULL;
1334 const char *repo_path;
1335 struct got_repository *repo = NULL;
1336 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1337 struct got_pathlist_entry *pe;
1338 struct got_object_id *pack_hash = NULL;
1339 int ch, fetchfd = -1, fetchstatus;
1340 pid_t fetchpid = -1;
1341 struct got_fetch_progress_arg fpa;
1342 char *git_url = NULL;
1343 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1344 int list_refs_only = 0;
1346 TAILQ_INIT(&refs);
1347 TAILQ_INIT(&symrefs);
1348 TAILQ_INIT(&wanted_branches);
1349 TAILQ_INIT(&wanted_refs);
1351 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1352 switch (ch) {
1353 case 'a':
1354 fetch_all_branches = 1;
1355 break;
1356 case 'b':
1357 error = got_pathlist_append(&wanted_branches,
1358 optarg, NULL);
1359 if (error)
1360 return error;
1361 break;
1362 case 'l':
1363 list_refs_only = 1;
1364 break;
1365 case 'm':
1366 mirror_references = 1;
1367 break;
1368 case 'v':
1369 if (verbosity < 0)
1370 verbosity = 0;
1371 else if (verbosity < 3)
1372 verbosity++;
1373 break;
1374 case 'q':
1375 verbosity = -1;
1376 break;
1377 case 'R':
1378 error = got_pathlist_append(&wanted_refs,
1379 optarg, NULL);
1380 if (error)
1381 return error;
1382 break;
1383 default:
1384 usage_clone();
1385 break;
1388 argc -= optind;
1389 argv += optind;
1391 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1392 errx(1, "-a and -b options are mutually exclusive");
1393 if (list_refs_only) {
1394 if (!TAILQ_EMPTY(&wanted_branches))
1395 errx(1, "-l and -b options are mutually exclusive");
1396 if (fetch_all_branches)
1397 errx(1, "-l and -a options are mutually exclusive");
1398 if (mirror_references)
1399 errx(1, "-l and -m options are mutually exclusive");
1400 if (verbosity == -1)
1401 errx(1, "-l and -q options are mutually exclusive");
1402 if (!TAILQ_EMPTY(&wanted_refs))
1403 errx(1, "-l and -R options are mutually exclusive");
1406 uri = argv[0];
1408 if (argc == 1)
1409 dirname = NULL;
1410 else if (argc == 2)
1411 dirname = argv[1];
1412 else
1413 usage_clone();
1415 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1416 &repo_name, uri);
1417 if (error)
1418 goto done;
1420 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1421 host, port ? ":" : "", port ? port : "",
1422 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1423 error = got_error_from_errno("asprintf");
1424 goto done;
1427 if (strcmp(proto, "git") == 0) {
1428 #ifndef PROFILE
1429 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1430 "sendfd dns inet unveil", NULL) == -1)
1431 err(1, "pledge");
1432 #endif
1433 } else if (strcmp(proto, "git+ssh") == 0 ||
1434 strcmp(proto, "ssh") == 0) {
1435 #ifndef PROFILE
1436 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1437 "sendfd unveil", NULL) == -1)
1438 err(1, "pledge");
1439 #endif
1440 } else if (strcmp(proto, "http") == 0 ||
1441 strcmp(proto, "git+http") == 0) {
1442 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1443 goto done;
1444 } else {
1445 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1446 goto done;
1448 if (dirname == NULL) {
1449 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1450 error = got_error_from_errno("asprintf");
1451 goto done;
1453 repo_path = default_destdir;
1454 } else
1455 repo_path = dirname;
1457 if (!list_refs_only) {
1458 error = got_path_mkdir(repo_path);
1459 if (error &&
1460 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1461 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1462 goto done;
1463 if (!got_path_dir_is_empty(repo_path)) {
1464 error = got_error_path(repo_path,
1465 GOT_ERR_DIR_NOT_EMPTY);
1466 goto done;
1470 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1471 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1472 error = got_error_from_errno2("unveil",
1473 GOT_FETCH_PATH_SSH);
1474 goto done;
1477 error = apply_unveil(repo_path, 0, NULL);
1478 if (error)
1479 goto done;
1481 if (verbosity >= 0)
1482 printf("Connecting to %s%s%s\n", host,
1483 port ? ":" : "", port ? port : "");
1485 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1486 server_path, verbosity);
1487 if (error)
1488 goto done;
1490 if (!list_refs_only) {
1491 error = got_repo_init(repo_path);
1492 if (error)
1493 goto done;
1494 error = got_repo_open(&repo, repo_path, NULL);
1495 if (error)
1496 goto done;
1499 fpa.last_scaled_size[0] = '\0';
1500 fpa.last_p_indexed = -1;
1501 fpa.last_p_resolved = -1;
1502 fpa.verbosity = verbosity;
1503 fpa.create_configs = 1;
1504 fpa.configs_created = 0;
1505 fpa.repo = repo;
1506 fpa.config_info.symrefs = &symrefs;
1507 fpa.config_info.wanted_branches = &wanted_branches;
1508 fpa.config_info.proto = proto;
1509 fpa.config_info.host = host;
1510 fpa.config_info.port = port;
1511 fpa.config_info.remote_repo_path = server_path;
1512 fpa.config_info.git_url = git_url;
1513 fpa.config_info.fetch_all_branches = fetch_all_branches;
1514 fpa.config_info.mirror_references = mirror_references;
1515 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1516 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1517 fetch_all_branches, &wanted_branches, &wanted_refs,
1518 list_refs_only, verbosity, fetchfd, repo,
1519 fetch_progress, &fpa);
1520 if (error)
1521 goto done;
1523 if (list_refs_only) {
1524 error = list_remote_refs(&symrefs, &refs);
1525 goto done;
1528 error = got_object_id_str(&id_str, pack_hash);
1529 if (error)
1530 goto done;
1531 if (verbosity >= 0)
1532 printf("\nFetched %s.pack\n", id_str);
1533 free(id_str);
1535 /* Set up references provided with the pack file. */
1536 TAILQ_FOREACH(pe, &refs, entry) {
1537 const char *refname = pe->path;
1538 struct got_object_id *id = pe->data;
1539 char *remote_refname;
1541 if (is_wanted_ref(&wanted_refs, refname) &&
1542 !mirror_references) {
1543 error = create_wanted_ref(refname, id,
1544 GOT_FETCH_DEFAULT_REMOTE_NAME,
1545 verbosity - 1, repo);
1546 if (error)
1547 goto done;
1548 continue;
1551 error = create_ref(refname, id, verbosity - 1, repo);
1552 if (error)
1553 goto done;
1555 if (mirror_references)
1556 continue;
1558 if (strncmp("refs/heads/", refname, 11) != 0)
1559 continue;
1561 if (asprintf(&remote_refname,
1562 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1563 refname + 11) == -1) {
1564 error = got_error_from_errno("asprintf");
1565 goto done;
1567 error = create_ref(remote_refname, id, verbosity - 1, repo);
1568 free(remote_refname);
1569 if (error)
1570 goto done;
1573 /* Set the HEAD reference if the server provided one. */
1574 TAILQ_FOREACH(pe, &symrefs, entry) {
1575 struct got_reference *target_ref;
1576 const char *refname = pe->path;
1577 const char *target = pe->data;
1578 char *remote_refname = NULL, *remote_target = NULL;
1580 if (strcmp(refname, GOT_REF_HEAD) != 0)
1581 continue;
1583 error = got_ref_open(&target_ref, repo, target, 0);
1584 if (error) {
1585 if (error->code == GOT_ERR_NOT_REF) {
1586 error = NULL;
1587 continue;
1589 goto done;
1592 error = create_symref(refname, target_ref, verbosity, repo);
1593 got_ref_close(target_ref);
1594 if (error)
1595 goto done;
1597 if (mirror_references)
1598 continue;
1600 if (strncmp("refs/heads/", target, 11) != 0)
1601 continue;
1603 if (asprintf(&remote_refname,
1604 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1605 refname) == -1) {
1606 error = got_error_from_errno("asprintf");
1607 goto done;
1609 if (asprintf(&remote_target,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 target + 11) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 free(remote_refname);
1614 goto done;
1616 error = got_ref_open(&target_ref, repo, remote_target, 0);
1617 if (error) {
1618 free(remote_refname);
1619 free(remote_target);
1620 if (error->code == GOT_ERR_NOT_REF) {
1621 error = NULL;
1622 continue;
1624 goto done;
1626 error = create_symref(remote_refname, target_ref,
1627 verbosity - 1, repo);
1628 free(remote_refname);
1629 free(remote_target);
1630 got_ref_close(target_ref);
1631 if (error)
1632 goto done;
1634 if (pe == NULL) {
1636 * We failed to set the HEAD reference. If we asked for
1637 * a set of wanted branches use the first of one of those
1638 * which could be fetched instead.
1640 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1641 const char *target = pe->path;
1642 struct got_reference *target_ref;
1644 error = got_ref_open(&target_ref, repo, target, 0);
1645 if (error) {
1646 if (error->code == GOT_ERR_NOT_REF) {
1647 error = NULL;
1648 continue;
1650 goto done;
1653 error = create_symref(GOT_REF_HEAD, target_ref,
1654 verbosity, repo);
1655 got_ref_close(target_ref);
1656 if (error)
1657 goto done;
1658 break;
1662 if (verbosity >= 0)
1663 printf("Created %s repository '%s'\n",
1664 mirror_references ? "mirrored" : "cloned", repo_path);
1665 done:
1666 if (fetchpid > 0) {
1667 if (kill(fetchpid, SIGTERM) == -1)
1668 error = got_error_from_errno("kill");
1669 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1670 error = got_error_from_errno("waitpid");
1672 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1673 error = got_error_from_errno("close");
1674 if (repo)
1675 got_repo_close(repo);
1676 TAILQ_FOREACH(pe, &refs, entry) {
1677 free((void *)pe->path);
1678 free(pe->data);
1680 got_pathlist_free(&refs);
1681 TAILQ_FOREACH(pe, &symrefs, entry) {
1682 free((void *)pe->path);
1683 free(pe->data);
1685 got_pathlist_free(&symrefs);
1686 got_pathlist_free(&wanted_branches);
1687 got_pathlist_free(&wanted_refs);
1688 free(pack_hash);
1689 free(proto);
1690 free(host);
1691 free(port);
1692 free(server_path);
1693 free(repo_name);
1694 free(default_destdir);
1695 free(git_url);
1696 return error;
1699 static const struct got_error *
1700 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1701 int replace_tags, int verbosity, struct got_repository *repo)
1703 const struct got_error *err = NULL;
1704 char *new_id_str = NULL;
1705 struct got_object_id *old_id = NULL;
1707 err = got_object_id_str(&new_id_str, new_id);
1708 if (err)
1709 goto done;
1711 if (!replace_tags &&
1712 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1713 err = got_ref_resolve(&old_id, repo, ref);
1714 if (err)
1715 goto done;
1716 if (got_object_id_cmp(old_id, new_id) == 0)
1717 goto done;
1718 if (verbosity >= 0) {
1719 printf("Rejecting update of existing tag %s: %s\n",
1720 got_ref_get_name(ref), new_id_str);
1722 goto done;
1725 if (got_ref_is_symbolic(ref)) {
1726 if (verbosity >= 0) {
1727 printf("Replacing reference %s: %s\n",
1728 got_ref_get_name(ref),
1729 got_ref_get_symref_target(ref));
1731 err = got_ref_change_symref_to_ref(ref, new_id);
1732 if (err)
1733 goto done;
1734 err = got_ref_write(ref, repo);
1735 if (err)
1736 goto done;
1737 } else {
1738 err = got_ref_resolve(&old_id, repo, ref);
1739 if (err)
1740 goto done;
1741 if (got_object_id_cmp(old_id, new_id) == 0)
1742 goto done;
1744 err = got_ref_change_ref(ref, new_id);
1745 if (err)
1746 goto done;
1747 err = got_ref_write(ref, repo);
1748 if (err)
1749 goto done;
1752 if (verbosity >= 0)
1753 printf("Updated %s: %s\n", got_ref_get_name(ref),
1754 new_id_str);
1755 done:
1756 free(old_id);
1757 free(new_id_str);
1758 return err;
1761 static const struct got_error *
1762 update_symref(const char *refname, struct got_reference *target_ref,
1763 int verbosity, struct got_repository *repo)
1765 const struct got_error *err = NULL, *unlock_err;
1766 struct got_reference *symref;
1767 int symref_is_locked = 0;
1769 err = got_ref_open(&symref, repo, refname, 1);
1770 if (err) {
1771 if (err->code != GOT_ERR_NOT_REF)
1772 return err;
1773 err = got_ref_alloc_symref(&symref, refname, target_ref);
1774 if (err)
1775 goto done;
1777 err = got_ref_write(symref, repo);
1778 if (err)
1779 goto done;
1781 if (verbosity >= 0)
1782 printf("Created reference %s: %s\n",
1783 got_ref_get_name(symref),
1784 got_ref_get_symref_target(symref));
1785 } else {
1786 symref_is_locked = 1;
1788 if (strcmp(got_ref_get_symref_target(symref),
1789 got_ref_get_name(target_ref)) == 0)
1790 goto done;
1792 err = got_ref_change_symref(symref,
1793 got_ref_get_name(target_ref));
1794 if (err)
1795 goto done;
1797 err = got_ref_write(symref, repo);
1798 if (err)
1799 goto done;
1801 if (verbosity >= 0)
1802 printf("Updated %s: %s\n", got_ref_get_name(symref),
1803 got_ref_get_symref_target(symref));
1806 done:
1807 if (symref_is_locked) {
1808 unlock_err = got_ref_unlock(symref);
1809 if (unlock_err && err == NULL)
1810 err = unlock_err;
1812 got_ref_close(symref);
1813 return err;
1816 __dead static void
1817 usage_fetch(void)
1819 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1820 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1821 "[remote-repository-name]\n",
1822 getprogname());
1823 exit(1);
1826 static const struct got_error *
1827 delete_missing_ref(struct got_reference *ref,
1828 int verbosity, struct got_repository *repo)
1830 const struct got_error *err = NULL;
1831 struct got_object_id *id = NULL;
1832 char *id_str = NULL;
1834 if (got_ref_is_symbolic(ref)) {
1835 err = got_ref_delete(ref, repo);
1836 if (err)
1837 return err;
1838 if (verbosity >= 0) {
1839 printf("Deleted reference %s: %s\n",
1840 got_ref_get_name(ref),
1841 got_ref_get_symref_target(ref));
1843 } else {
1844 err = got_ref_resolve(&id, repo, ref);
1845 if (err)
1846 return err;
1847 err = got_object_id_str(&id_str, id);
1848 if (err)
1849 goto done;
1851 err = got_ref_delete(ref, repo);
1852 if (err)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Deleted reference %s: %s\n",
1856 got_ref_get_name(ref), id_str);
1859 done:
1860 free(id);
1861 free(id_str);
1862 return NULL;
1865 static const struct got_error *
1866 delete_missing_refs(struct got_pathlist_head *their_refs,
1867 struct got_pathlist_head *their_symrefs,
1868 const struct got_remote_repo *remote,
1869 int verbosity, struct got_repository *repo)
1871 const struct got_error *err = NULL, *unlock_err;
1872 struct got_reflist_head my_refs;
1873 struct got_reflist_entry *re;
1874 struct got_pathlist_entry *pe;
1875 char *remote_namespace = NULL;
1876 char *local_refname = NULL;
1878 SIMPLEQ_INIT(&my_refs);
1880 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1881 == -1)
1882 return got_error_from_errno("asprintf");
1884 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1885 if (err)
1886 goto done;
1888 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1889 const char *refname = got_ref_get_name(re->ref);
1891 if (!remote->mirror_references) {
1892 if (strncmp(refname, remote_namespace,
1893 strlen(remote_namespace)) == 0) {
1894 if (strcmp(refname + strlen(remote_namespace),
1895 GOT_REF_HEAD) == 0)
1896 continue;
1897 if (asprintf(&local_refname, "refs/heads/%s",
1898 refname + strlen(remote_namespace)) == -1) {
1899 err = got_error_from_errno("asprintf");
1900 goto done;
1902 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1903 continue;
1906 TAILQ_FOREACH(pe, their_refs, entry) {
1907 if (strcmp(local_refname, pe->path) == 0)
1908 break;
1910 if (pe != NULL)
1911 continue;
1913 TAILQ_FOREACH(pe, their_symrefs, entry) {
1914 if (strcmp(local_refname, pe->path) == 0)
1915 break;
1917 if (pe != NULL)
1918 continue;
1920 err = delete_missing_ref(re->ref, verbosity, repo);
1921 if (err)
1922 break;
1924 if (local_refname) {
1925 struct got_reference *ref;
1926 err = got_ref_open(&ref, repo, local_refname, 1);
1927 if (err) {
1928 if (err->code != GOT_ERR_NOT_REF)
1929 break;
1930 free(local_refname);
1931 local_refname = NULL;
1932 continue;
1934 err = delete_missing_ref(ref, verbosity, repo);
1935 if (err)
1936 break;
1937 unlock_err = got_ref_unlock(ref);
1938 got_ref_close(ref);
1939 if (unlock_err && err == NULL) {
1940 err = unlock_err;
1941 break;
1944 free(local_refname);
1945 local_refname = NULL;
1948 done:
1949 free(remote_namespace);
1950 free(local_refname);
1951 return err;
1954 static const struct got_error *
1955 update_wanted_ref(const char *refname, struct got_object_id *id,
1956 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1958 const struct got_error *err, *unlock_err;
1959 char *remote_refname;
1960 struct got_reference *ref;
1962 if (strncmp("refs/", refname, 5) == 0)
1963 refname += 5;
1965 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1966 remote_repo_name, refname) == -1)
1967 return got_error_from_errno("asprintf");
1969 err = got_ref_open(&ref, repo, remote_refname, 1);
1970 if (err) {
1971 if (err->code != GOT_ERR_NOT_REF)
1972 goto done;
1973 err = create_ref(remote_refname, id, verbosity, repo);
1974 } else {
1975 err = update_ref(ref, id, 0, verbosity, repo);
1976 unlock_err = got_ref_unlock(ref);
1977 if (unlock_err && err == NULL)
1978 err = unlock_err;
1979 got_ref_close(ref);
1981 done:
1982 free(remote_refname);
1983 return err;
1986 static const struct got_error *
1987 cmd_fetch(int argc, char *argv[])
1989 const struct got_error *error = NULL, *unlock_err;
1990 char *cwd = NULL, *repo_path = NULL;
1991 const char *remote_name;
1992 char *proto = NULL, *host = NULL, *port = NULL;
1993 char *repo_name = NULL, *server_path = NULL;
1994 const struct got_remote_repo *remotes, *remote = NULL;
1995 int nremotes;
1996 char *id_str = NULL;
1997 struct got_repository *repo = NULL;
1998 struct got_worktree *worktree = NULL;
1999 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2000 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2001 struct got_pathlist_entry *pe;
2002 struct got_object_id *pack_hash = NULL;
2003 int i, ch, fetchfd = -1, fetchstatus;
2004 pid_t fetchpid = -1;
2005 struct got_fetch_progress_arg fpa;
2006 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2007 int delete_refs = 0, replace_tags = 0;
2009 TAILQ_INIT(&refs);
2010 TAILQ_INIT(&symrefs);
2011 TAILQ_INIT(&wanted_branches);
2012 TAILQ_INIT(&wanted_refs);
2014 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2015 switch (ch) {
2016 case 'a':
2017 fetch_all_branches = 1;
2018 break;
2019 case 'b':
2020 error = got_pathlist_append(&wanted_branches,
2021 optarg, NULL);
2022 if (error)
2023 return error;
2024 break;
2025 case 'd':
2026 delete_refs = 1;
2027 break;
2028 case 'l':
2029 list_refs_only = 1;
2030 break;
2031 case 'r':
2032 repo_path = realpath(optarg, NULL);
2033 if (repo_path == NULL)
2034 return got_error_from_errno2("realpath",
2035 optarg);
2036 got_path_strip_trailing_slashes(repo_path);
2037 break;
2038 case 't':
2039 replace_tags = 1;
2040 break;
2041 case 'v':
2042 if (verbosity < 0)
2043 verbosity = 0;
2044 else if (verbosity < 3)
2045 verbosity++;
2046 break;
2047 case 'q':
2048 verbosity = -1;
2049 break;
2050 case 'R':
2051 error = got_pathlist_append(&wanted_refs,
2052 optarg, NULL);
2053 if (error)
2054 return error;
2055 break;
2056 default:
2057 usage_fetch();
2058 break;
2061 argc -= optind;
2062 argv += optind;
2064 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2065 errx(1, "-a and -b options are mutually exclusive");
2066 if (list_refs_only) {
2067 if (!TAILQ_EMPTY(&wanted_branches))
2068 errx(1, "-l and -b options are mutually exclusive");
2069 if (fetch_all_branches)
2070 errx(1, "-l and -a options are mutually exclusive");
2071 if (delete_refs)
2072 errx(1, "-l and -d options are mutually exclusive");
2073 if (verbosity == -1)
2074 errx(1, "-l and -q options are mutually exclusive");
2077 if (argc == 0)
2078 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2079 else if (argc == 1)
2080 remote_name = argv[0];
2081 else
2082 usage_fetch();
2084 cwd = getcwd(NULL, 0);
2085 if (cwd == NULL) {
2086 error = got_error_from_errno("getcwd");
2087 goto done;
2090 if (repo_path == NULL) {
2091 error = got_worktree_open(&worktree, cwd);
2092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2093 goto done;
2094 else
2095 error = NULL;
2096 if (worktree) {
2097 repo_path =
2098 strdup(got_worktree_get_repo_path(worktree));
2099 if (repo_path == NULL)
2100 error = got_error_from_errno("strdup");
2101 if (error)
2102 goto done;
2103 } else {
2104 repo_path = strdup(cwd);
2105 if (repo_path == NULL) {
2106 error = got_error_from_errno("strdup");
2107 goto done;
2112 error = got_repo_open(&repo, repo_path, NULL);
2113 if (error)
2114 goto done;
2116 if (worktree) {
2117 worktree_conf = got_worktree_get_gotconfig(worktree);
2118 if (worktree_conf) {
2119 got_gotconfig_get_remotes(&nremotes, &remotes,
2120 worktree_conf);
2121 for (i = 0; i < nremotes; i++) {
2122 remote = &remotes[i];
2123 if (strcmp(remote->name, remote_name) == 0)
2124 break;
2128 if (remote == NULL) {
2129 repo_conf = got_repo_get_gotconfig(repo);
2130 if (repo_conf) {
2131 got_gotconfig_get_remotes(&nremotes, &remotes,
2132 repo_conf);
2133 for (i = 0; i < nremotes; i++) {
2134 remote = &remotes[i];
2135 if (strcmp(remote->name, remote_name) == 0)
2136 break;
2140 if (remote == NULL) {
2141 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2142 for (i = 0; i < nremotes; i++) {
2143 remote = &remotes[i];
2144 if (strcmp(remote->name, remote_name) == 0)
2145 break;
2148 if (remote == NULL) {
2149 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2150 goto done;
2153 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2154 for (i = 0; i < remote->nbranches; i++) {
2155 got_pathlist_append(&wanted_branches,
2156 remote->branches[i], NULL);
2161 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2162 &repo_name, remote->url);
2163 if (error)
2164 goto done;
2166 if (strcmp(proto, "git") == 0) {
2167 #ifndef PROFILE
2168 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2169 "sendfd dns inet unveil", NULL) == -1)
2170 err(1, "pledge");
2171 #endif
2172 } else if (strcmp(proto, "git+ssh") == 0 ||
2173 strcmp(proto, "ssh") == 0) {
2174 #ifndef PROFILE
2175 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2176 "sendfd unveil", NULL) == -1)
2177 err(1, "pledge");
2178 #endif
2179 } else if (strcmp(proto, "http") == 0 ||
2180 strcmp(proto, "git+http") == 0) {
2181 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2182 goto done;
2183 } else {
2184 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2185 goto done;
2188 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2189 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2190 error = got_error_from_errno2("unveil",
2191 GOT_FETCH_PATH_SSH);
2192 goto done;
2195 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2196 if (error)
2197 goto done;
2199 if (verbosity >= 0)
2200 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2201 port ? ":" : "", port ? port : "");
2203 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2204 server_path, verbosity);
2205 if (error)
2206 goto done;
2208 fpa.last_scaled_size[0] = '\0';
2209 fpa.last_p_indexed = -1;
2210 fpa.last_p_resolved = -1;
2211 fpa.verbosity = verbosity;
2212 fpa.repo = repo;
2213 fpa.create_configs = 0;
2214 fpa.configs_created = 0;
2215 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2216 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2217 remote->mirror_references, fetch_all_branches, &wanted_branches,
2218 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2219 fetch_progress, &fpa);
2220 if (error)
2221 goto done;
2223 if (list_refs_only) {
2224 error = list_remote_refs(&symrefs, &refs);
2225 goto done;
2228 if (pack_hash == NULL) {
2229 if (verbosity >= 0)
2230 printf("Already up-to-date\n");
2231 } else if (verbosity >= 0) {
2232 error = got_object_id_str(&id_str, pack_hash);
2233 if (error)
2234 goto done;
2235 printf("\nFetched %s.pack\n", id_str);
2236 free(id_str);
2237 id_str = NULL;
2240 /* Update references provided with the pack file. */
2241 TAILQ_FOREACH(pe, &refs, entry) {
2242 const char *refname = pe->path;
2243 struct got_object_id *id = pe->data;
2244 struct got_reference *ref;
2245 char *remote_refname;
2247 if (is_wanted_ref(&wanted_refs, refname) &&
2248 !remote->mirror_references) {
2249 error = update_wanted_ref(refname, id,
2250 remote->name, verbosity, repo);
2251 if (error)
2252 goto done;
2253 continue;
2256 if (remote->mirror_references ||
2257 strncmp("refs/tags/", refname, 10) == 0) {
2258 error = got_ref_open(&ref, repo, refname, 1);
2259 if (error) {
2260 if (error->code != GOT_ERR_NOT_REF)
2261 goto done;
2262 error = create_ref(refname, id, verbosity,
2263 repo);
2264 if (error)
2265 goto done;
2266 } else {
2267 error = update_ref(ref, id, replace_tags,
2268 verbosity, repo);
2269 unlock_err = got_ref_unlock(ref);
2270 if (unlock_err && error == NULL)
2271 error = unlock_err;
2272 got_ref_close(ref);
2273 if (error)
2274 goto done;
2276 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2277 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2278 remote_name, refname + 11) == -1) {
2279 error = got_error_from_errno("asprintf");
2280 goto done;
2283 error = got_ref_open(&ref, repo, remote_refname, 1);
2284 if (error) {
2285 if (error->code != GOT_ERR_NOT_REF)
2286 goto done;
2287 error = create_ref(remote_refname, id,
2288 verbosity, repo);
2289 if (error)
2290 goto done;
2291 } else {
2292 error = update_ref(ref, id, replace_tags,
2293 verbosity, repo);
2294 unlock_err = got_ref_unlock(ref);
2295 if (unlock_err && error == NULL)
2296 error = unlock_err;
2297 got_ref_close(ref);
2298 if (error)
2299 goto done;
2302 /* Also create a local branch if none exists yet. */
2303 error = got_ref_open(&ref, repo, refname, 1);
2304 if (error) {
2305 if (error->code != GOT_ERR_NOT_REF)
2306 goto done;
2307 error = create_ref(refname, id, verbosity,
2308 repo);
2309 if (error)
2310 goto done;
2311 } else {
2312 unlock_err = got_ref_unlock(ref);
2313 if (unlock_err && error == NULL)
2314 error = unlock_err;
2315 got_ref_close(ref);
2319 if (delete_refs) {
2320 error = delete_missing_refs(&refs, &symrefs, remote,
2321 verbosity, repo);
2322 if (error)
2323 goto done;
2326 if (!remote->mirror_references) {
2327 /* Update remote HEAD reference if the server provided one. */
2328 TAILQ_FOREACH(pe, &symrefs, entry) {
2329 struct got_reference *target_ref;
2330 const char *refname = pe->path;
2331 const char *target = pe->data;
2332 char *remote_refname = NULL, *remote_target = NULL;
2334 if (strcmp(refname, GOT_REF_HEAD) != 0)
2335 continue;
2337 if (strncmp("refs/heads/", target, 11) != 0)
2338 continue;
2340 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2341 remote->name, refname) == -1) {
2342 error = got_error_from_errno("asprintf");
2343 goto done;
2345 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2346 remote->name, target + 11) == -1) {
2347 error = got_error_from_errno("asprintf");
2348 free(remote_refname);
2349 goto done;
2352 error = got_ref_open(&target_ref, repo, remote_target,
2353 0);
2354 if (error) {
2355 free(remote_refname);
2356 free(remote_target);
2357 if (error->code == GOT_ERR_NOT_REF) {
2358 error = NULL;
2359 continue;
2361 goto done;
2363 error = update_symref(remote_refname, target_ref,
2364 verbosity, repo);
2365 free(remote_refname);
2366 free(remote_target);
2367 got_ref_close(target_ref);
2368 if (error)
2369 goto done;
2372 done:
2373 if (fetchpid > 0) {
2374 if (kill(fetchpid, SIGTERM) == -1)
2375 error = got_error_from_errno("kill");
2376 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2377 error = got_error_from_errno("waitpid");
2379 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2380 error = got_error_from_errno("close");
2381 if (repo)
2382 got_repo_close(repo);
2383 if (worktree)
2384 got_worktree_close(worktree);
2385 TAILQ_FOREACH(pe, &refs, entry) {
2386 free((void *)pe->path);
2387 free(pe->data);
2389 got_pathlist_free(&refs);
2390 TAILQ_FOREACH(pe, &symrefs, entry) {
2391 free((void *)pe->path);
2392 free(pe->data);
2394 got_pathlist_free(&symrefs);
2395 got_pathlist_free(&wanted_branches);
2396 got_pathlist_free(&wanted_refs);
2397 free(id_str);
2398 free(cwd);
2399 free(repo_path);
2400 free(pack_hash);
2401 free(proto);
2402 free(host);
2403 free(port);
2404 free(server_path);
2405 free(repo_name);
2406 return error;
2410 __dead static void
2411 usage_checkout(void)
2413 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2414 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2415 exit(1);
2418 static void
2419 show_worktree_base_ref_warning(void)
2421 fprintf(stderr, "%s: warning: could not create a reference "
2422 "to the work tree's base commit; the commit could be "
2423 "garbage-collected by Git; making the repository "
2424 "writable and running 'got update' will prevent this\n",
2425 getprogname());
2428 struct got_checkout_progress_arg {
2429 const char *worktree_path;
2430 int had_base_commit_ref_error;
2433 static const struct got_error *
2434 checkout_progress(void *arg, unsigned char status, const char *path)
2436 struct got_checkout_progress_arg *a = arg;
2438 /* Base commit bump happens silently. */
2439 if (status == GOT_STATUS_BUMP_BASE)
2440 return NULL;
2442 if (status == GOT_STATUS_BASE_REF_ERR) {
2443 a->had_base_commit_ref_error = 1;
2444 return NULL;
2447 while (path[0] == '/')
2448 path++;
2450 printf("%c %s/%s\n", status, a->worktree_path, path);
2451 return NULL;
2454 static const struct got_error *
2455 check_cancelled(void *arg)
2457 if (sigint_received || sigpipe_received)
2458 return got_error(GOT_ERR_CANCELLED);
2459 return NULL;
2462 static const struct got_error *
2463 check_linear_ancestry(struct got_object_id *commit_id,
2464 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2465 struct got_repository *repo)
2467 const struct got_error *err = NULL;
2468 struct got_object_id *yca_id;
2470 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2471 commit_id, base_commit_id, repo, check_cancelled, NULL);
2472 if (err)
2473 return err;
2475 if (yca_id == NULL)
2476 return got_error(GOT_ERR_ANCESTRY);
2479 * Require a straight line of history between the target commit
2480 * and the work tree's base commit.
2482 * Non-linear situations such as this require a rebase:
2484 * (commit) D F (base_commit)
2485 * \ /
2486 * C E
2487 * \ /
2488 * B (yca)
2489 * |
2490 * A
2492 * 'got update' only handles linear cases:
2493 * Update forwards in time: A (base/yca) - B - C - D (commit)
2494 * Update backwards in time: D (base) - C - B - A (commit/yca)
2496 if (allow_forwards_in_time_only) {
2497 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2498 return got_error(GOT_ERR_ANCESTRY);
2499 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2500 got_object_id_cmp(base_commit_id, yca_id) != 0)
2501 return got_error(GOT_ERR_ANCESTRY);
2503 free(yca_id);
2504 return NULL;
2507 static const struct got_error *
2508 check_same_branch(struct got_object_id *commit_id,
2509 struct got_reference *head_ref, struct got_object_id *yca_id,
2510 struct got_repository *repo)
2512 const struct got_error *err = NULL;
2513 struct got_commit_graph *graph = NULL;
2514 struct got_object_id *head_commit_id = NULL;
2515 int is_same_branch = 0;
2517 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2518 if (err)
2519 goto done;
2521 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2522 is_same_branch = 1;
2523 goto done;
2525 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2526 is_same_branch = 1;
2527 goto done;
2530 err = got_commit_graph_open(&graph, "/", 1);
2531 if (err)
2532 goto done;
2534 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2535 check_cancelled, NULL);
2536 if (err)
2537 goto done;
2539 for (;;) {
2540 struct got_object_id *id;
2541 err = got_commit_graph_iter_next(&id, graph, repo,
2542 check_cancelled, NULL);
2543 if (err) {
2544 if (err->code == GOT_ERR_ITER_COMPLETED)
2545 err = NULL;
2546 break;
2549 if (id) {
2550 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2551 break;
2552 if (got_object_id_cmp(id, commit_id) == 0) {
2553 is_same_branch = 1;
2554 break;
2558 done:
2559 if (graph)
2560 got_commit_graph_close(graph);
2561 free(head_commit_id);
2562 if (!err && !is_same_branch)
2563 err = got_error(GOT_ERR_ANCESTRY);
2564 return err;
2567 static const struct got_error *
2568 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2570 static char msg[512];
2571 const char *branch_name;
2573 if (got_ref_is_symbolic(ref))
2574 branch_name = got_ref_get_symref_target(ref);
2575 else
2576 branch_name = got_ref_get_name(ref);
2578 if (strncmp("refs/heads/", branch_name, 11) == 0)
2579 branch_name += 11;
2581 snprintf(msg, sizeof(msg),
2582 "target commit is not contained in branch '%s'; "
2583 "the branch to use must be specified with -b; "
2584 "if necessary a new branch can be created for "
2585 "this commit with 'got branch -c %s BRANCH_NAME'",
2586 branch_name, commit_id_str);
2588 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2591 static const struct got_error *
2592 cmd_checkout(int argc, char *argv[])
2594 const struct got_error *error = NULL;
2595 struct got_repository *repo = NULL;
2596 struct got_reference *head_ref = NULL;
2597 struct got_worktree *worktree = NULL;
2598 char *repo_path = NULL;
2599 char *worktree_path = NULL;
2600 const char *path_prefix = "";
2601 const char *branch_name = GOT_REF_HEAD;
2602 char *commit_id_str = NULL;
2603 char *cwd = NULL;
2604 int ch, same_path_prefix, allow_nonempty = 0;
2605 struct got_pathlist_head paths;
2606 struct got_checkout_progress_arg cpa;
2608 TAILQ_INIT(&paths);
2610 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2611 switch (ch) {
2612 case 'b':
2613 branch_name = optarg;
2614 break;
2615 case 'c':
2616 commit_id_str = strdup(optarg);
2617 if (commit_id_str == NULL)
2618 return got_error_from_errno("strdup");
2619 break;
2620 case 'E':
2621 allow_nonempty = 1;
2622 break;
2623 case 'p':
2624 path_prefix = optarg;
2625 break;
2626 default:
2627 usage_checkout();
2628 /* NOTREACHED */
2632 argc -= optind;
2633 argv += optind;
2635 #ifndef PROFILE
2636 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2637 "unveil", NULL) == -1)
2638 err(1, "pledge");
2639 #endif
2640 if (argc == 1) {
2641 char *base, *dotgit;
2642 const char *path;
2643 repo_path = realpath(argv[0], NULL);
2644 if (repo_path == NULL)
2645 return got_error_from_errno2("realpath", argv[0]);
2646 cwd = getcwd(NULL, 0);
2647 if (cwd == NULL) {
2648 error = got_error_from_errno("getcwd");
2649 goto done;
2651 if (path_prefix[0])
2652 path = path_prefix;
2653 else
2654 path = repo_path;
2655 error = got_path_basename(&base, path);
2656 if (error)
2657 goto done;
2658 dotgit = strstr(base, ".git");
2659 if (dotgit)
2660 *dotgit = '\0';
2661 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2662 error = got_error_from_errno("asprintf");
2663 free(base);
2664 goto done;
2666 free(base);
2667 } else if (argc == 2) {
2668 repo_path = realpath(argv[0], NULL);
2669 if (repo_path == NULL) {
2670 error = got_error_from_errno2("realpath", argv[0]);
2671 goto done;
2673 worktree_path = realpath(argv[1], NULL);
2674 if (worktree_path == NULL) {
2675 if (errno != ENOENT) {
2676 error = got_error_from_errno2("realpath",
2677 argv[1]);
2678 goto done;
2680 worktree_path = strdup(argv[1]);
2681 if (worktree_path == NULL) {
2682 error = got_error_from_errno("strdup");
2683 goto done;
2686 } else
2687 usage_checkout();
2689 got_path_strip_trailing_slashes(repo_path);
2690 got_path_strip_trailing_slashes(worktree_path);
2692 error = got_repo_open(&repo, repo_path, NULL);
2693 if (error != NULL)
2694 goto done;
2696 /* Pre-create work tree path for unveil(2) */
2697 error = got_path_mkdir(worktree_path);
2698 if (error) {
2699 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2700 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2701 goto done;
2702 if (!allow_nonempty &&
2703 !got_path_dir_is_empty(worktree_path)) {
2704 error = got_error_path(worktree_path,
2705 GOT_ERR_DIR_NOT_EMPTY);
2706 goto done;
2710 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2711 if (error)
2712 goto done;
2714 error = got_ref_open(&head_ref, repo, branch_name, 0);
2715 if (error != NULL)
2716 goto done;
2718 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2719 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2720 goto done;
2722 error = got_worktree_open(&worktree, worktree_path);
2723 if (error != NULL)
2724 goto done;
2726 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2727 path_prefix);
2728 if (error != NULL)
2729 goto done;
2730 if (!same_path_prefix) {
2731 error = got_error(GOT_ERR_PATH_PREFIX);
2732 goto done;
2735 if (commit_id_str) {
2736 struct got_object_id *commit_id;
2737 error = got_repo_match_object_id(&commit_id, NULL,
2738 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2739 if (error)
2740 goto done;
2741 error = check_linear_ancestry(commit_id,
2742 got_worktree_get_base_commit_id(worktree), 0, repo);
2743 if (error != NULL) {
2744 free(commit_id);
2745 if (error->code == GOT_ERR_ANCESTRY) {
2746 error = checkout_ancestry_error(
2747 head_ref, commit_id_str);
2749 goto done;
2751 error = check_same_branch(commit_id, head_ref, NULL, repo);
2752 if (error) {
2753 if (error->code == GOT_ERR_ANCESTRY) {
2754 error = checkout_ancestry_error(
2755 head_ref, commit_id_str);
2757 goto done;
2759 error = got_worktree_set_base_commit_id(worktree, repo,
2760 commit_id);
2761 free(commit_id);
2762 if (error)
2763 goto done;
2766 error = got_pathlist_append(&paths, "", NULL);
2767 if (error)
2768 goto done;
2769 cpa.worktree_path = worktree_path;
2770 cpa.had_base_commit_ref_error = 0;
2771 error = got_worktree_checkout_files(worktree, &paths, repo,
2772 checkout_progress, &cpa, check_cancelled, NULL);
2773 if (error != NULL)
2774 goto done;
2776 printf("Now shut up and hack\n");
2777 if (cpa.had_base_commit_ref_error)
2778 show_worktree_base_ref_warning();
2779 done:
2780 got_pathlist_free(&paths);
2781 free(commit_id_str);
2782 free(repo_path);
2783 free(worktree_path);
2784 free(cwd);
2785 return error;
2788 struct got_update_progress_arg {
2789 int did_something;
2790 int conflicts;
2791 int obstructed;
2792 int not_updated;
2795 void
2796 print_update_progress_stats(struct got_update_progress_arg *upa)
2798 if (!upa->did_something)
2799 return;
2801 if (upa->conflicts > 0)
2802 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2803 if (upa->obstructed > 0)
2804 printf("File paths obstructed by a non-regular file: %d\n",
2805 upa->obstructed);
2806 if (upa->not_updated > 0)
2807 printf("Files not updated because of existing merge "
2808 "conflicts: %d\n", upa->not_updated);
2811 __dead static void
2812 usage_update(void)
2814 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2815 getprogname());
2816 exit(1);
2819 static const struct got_error *
2820 update_progress(void *arg, unsigned char status, const char *path)
2822 struct got_update_progress_arg *upa = arg;
2824 if (status == GOT_STATUS_EXISTS ||
2825 status == GOT_STATUS_BASE_REF_ERR)
2826 return NULL;
2828 upa->did_something = 1;
2830 /* Base commit bump happens silently. */
2831 if (status == GOT_STATUS_BUMP_BASE)
2832 return NULL;
2834 if (status == GOT_STATUS_CONFLICT)
2835 upa->conflicts++;
2836 if (status == GOT_STATUS_OBSTRUCTED)
2837 upa->obstructed++;
2838 if (status == GOT_STATUS_CANNOT_UPDATE)
2839 upa->not_updated++;
2841 while (path[0] == '/')
2842 path++;
2843 printf("%c %s\n", status, path);
2844 return NULL;
2847 static const struct got_error *
2848 switch_head_ref(struct got_reference *head_ref,
2849 struct got_object_id *commit_id, struct got_worktree *worktree,
2850 struct got_repository *repo)
2852 const struct got_error *err = NULL;
2853 char *base_id_str;
2854 int ref_has_moved = 0;
2856 /* Trivial case: switching between two different references. */
2857 if (strcmp(got_ref_get_name(head_ref),
2858 got_worktree_get_head_ref_name(worktree)) != 0) {
2859 printf("Switching work tree from %s to %s\n",
2860 got_worktree_get_head_ref_name(worktree),
2861 got_ref_get_name(head_ref));
2862 return got_worktree_set_head_ref(worktree, head_ref);
2865 err = check_linear_ancestry(commit_id,
2866 got_worktree_get_base_commit_id(worktree), 0, repo);
2867 if (err) {
2868 if (err->code != GOT_ERR_ANCESTRY)
2869 return err;
2870 ref_has_moved = 1;
2872 if (!ref_has_moved)
2873 return NULL;
2875 /* Switching to a rebased branch with the same reference name. */
2876 err = got_object_id_str(&base_id_str,
2877 got_worktree_get_base_commit_id(worktree));
2878 if (err)
2879 return err;
2880 printf("Reference %s now points at a different branch\n",
2881 got_worktree_get_head_ref_name(worktree));
2882 printf("Switching work tree from %s to %s\n", base_id_str,
2883 got_worktree_get_head_ref_name(worktree));
2884 return NULL;
2887 static const struct got_error *
2888 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2890 const struct got_error *err;
2891 int in_progress;
2893 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2894 if (err)
2895 return err;
2896 if (in_progress)
2897 return got_error(GOT_ERR_REBASING);
2899 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2900 if (err)
2901 return err;
2902 if (in_progress)
2903 return got_error(GOT_ERR_HISTEDIT_BUSY);
2905 return NULL;
2908 static const struct got_error *
2909 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2910 char *argv[], struct got_worktree *worktree)
2912 const struct got_error *err = NULL;
2913 char *path;
2914 int i;
2916 if (argc == 0) {
2917 path = strdup("");
2918 if (path == NULL)
2919 return got_error_from_errno("strdup");
2920 return got_pathlist_append(paths, path, NULL);
2923 for (i = 0; i < argc; i++) {
2924 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2925 if (err)
2926 break;
2927 err = got_pathlist_append(paths, path, NULL);
2928 if (err) {
2929 free(path);
2930 break;
2934 return err;
2937 static const struct got_error *
2938 wrap_not_worktree_error(const struct got_error *orig_err,
2939 const char *cmdname, const char *path)
2941 const struct got_error *err;
2942 struct got_repository *repo;
2943 static char msg[512];
2945 err = got_repo_open(&repo, path, NULL);
2946 if (err)
2947 return orig_err;
2949 snprintf(msg, sizeof(msg),
2950 "'got %s' needs a work tree in addition to a git repository\n"
2951 "Work trees can be checked out from this Git repository with "
2952 "'got checkout'.\n"
2953 "The got(1) manual page contains more information.", cmdname);
2954 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2955 got_repo_close(repo);
2956 return err;
2959 static const struct got_error *
2960 cmd_update(int argc, char *argv[])
2962 const struct got_error *error = NULL;
2963 struct got_repository *repo = NULL;
2964 struct got_worktree *worktree = NULL;
2965 char *worktree_path = NULL;
2966 struct got_object_id *commit_id = NULL;
2967 char *commit_id_str = NULL;
2968 const char *branch_name = NULL;
2969 struct got_reference *head_ref = NULL;
2970 struct got_pathlist_head paths;
2971 struct got_pathlist_entry *pe;
2972 int ch;
2973 struct got_update_progress_arg upa;
2975 TAILQ_INIT(&paths);
2977 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2978 switch (ch) {
2979 case 'b':
2980 branch_name = optarg;
2981 break;
2982 case 'c':
2983 commit_id_str = strdup(optarg);
2984 if (commit_id_str == NULL)
2985 return got_error_from_errno("strdup");
2986 break;
2987 default:
2988 usage_update();
2989 /* NOTREACHED */
2993 argc -= optind;
2994 argv += optind;
2996 #ifndef PROFILE
2997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2998 "unveil", NULL) == -1)
2999 err(1, "pledge");
3000 #endif
3001 worktree_path = getcwd(NULL, 0);
3002 if (worktree_path == NULL) {
3003 error = got_error_from_errno("getcwd");
3004 goto done;
3006 error = got_worktree_open(&worktree, worktree_path);
3007 if (error) {
3008 if (error->code == GOT_ERR_NOT_WORKTREE)
3009 error = wrap_not_worktree_error(error, "update",
3010 worktree_path);
3011 goto done;
3014 error = check_rebase_or_histedit_in_progress(worktree);
3015 if (error)
3016 goto done;
3018 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3019 NULL);
3020 if (error != NULL)
3021 goto done;
3023 error = apply_unveil(got_repo_get_path(repo), 0,
3024 got_worktree_get_root_path(worktree));
3025 if (error)
3026 goto done;
3028 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3029 if (error)
3030 goto done;
3032 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3033 got_worktree_get_head_ref_name(worktree), 0);
3034 if (error != NULL)
3035 goto done;
3036 if (commit_id_str == NULL) {
3037 error = got_ref_resolve(&commit_id, repo, head_ref);
3038 if (error != NULL)
3039 goto done;
3040 error = got_object_id_str(&commit_id_str, commit_id);
3041 if (error != NULL)
3042 goto done;
3043 } else {
3044 error = got_repo_match_object_id(&commit_id, NULL,
3045 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3046 free(commit_id_str);
3047 commit_id_str = NULL;
3048 if (error)
3049 goto done;
3050 error = got_object_id_str(&commit_id_str, commit_id);
3051 if (error)
3052 goto done;
3055 if (branch_name) {
3056 struct got_object_id *head_commit_id;
3057 TAILQ_FOREACH(pe, &paths, entry) {
3058 if (pe->path_len == 0)
3059 continue;
3060 error = got_error_msg(GOT_ERR_BAD_PATH,
3061 "switching between branches requires that "
3062 "the entire work tree gets updated");
3063 goto done;
3065 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3066 if (error)
3067 goto done;
3068 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3069 repo);
3070 free(head_commit_id);
3071 if (error != NULL)
3072 goto done;
3073 error = check_same_branch(commit_id, head_ref, NULL, repo);
3074 if (error)
3075 goto done;
3076 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3077 if (error)
3078 goto done;
3079 } else {
3080 error = check_linear_ancestry(commit_id,
3081 got_worktree_get_base_commit_id(worktree), 0, repo);
3082 if (error != NULL) {
3083 if (error->code == GOT_ERR_ANCESTRY)
3084 error = got_error(GOT_ERR_BRANCH_MOVED);
3085 goto done;
3087 error = check_same_branch(commit_id, head_ref, NULL, repo);
3088 if (error)
3089 goto done;
3092 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3093 commit_id) != 0) {
3094 error = got_worktree_set_base_commit_id(worktree, repo,
3095 commit_id);
3096 if (error)
3097 goto done;
3100 memset(&upa, 0, sizeof(upa));
3101 error = got_worktree_checkout_files(worktree, &paths, repo,
3102 update_progress, &upa, check_cancelled, NULL);
3103 if (error != NULL)
3104 goto done;
3106 if (upa.did_something)
3107 printf("Updated to commit %s\n", commit_id_str);
3108 else
3109 printf("Already up-to-date\n");
3110 print_update_progress_stats(&upa);
3111 done:
3112 free(worktree_path);
3113 TAILQ_FOREACH(pe, &paths, entry)
3114 free((char *)pe->path);
3115 got_pathlist_free(&paths);
3116 free(commit_id);
3117 free(commit_id_str);
3118 return error;
3121 static const struct got_error *
3122 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3123 const char *path, int diff_context, int ignore_whitespace,
3124 struct got_repository *repo)
3126 const struct got_error *err = NULL;
3127 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3129 if (blob_id1) {
3130 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3131 if (err)
3132 goto done;
3135 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3136 if (err)
3137 goto done;
3139 while (path[0] == '/')
3140 path++;
3141 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3142 ignore_whitespace, stdout);
3143 done:
3144 if (blob1)
3145 got_object_blob_close(blob1);
3146 got_object_blob_close(blob2);
3147 return err;
3150 static const struct got_error *
3151 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3152 const char *path, int diff_context, int ignore_whitespace,
3153 struct got_repository *repo)
3155 const struct got_error *err = NULL;
3156 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3157 struct got_diff_blob_output_unidiff_arg arg;
3159 if (tree_id1) {
3160 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3161 if (err)
3162 goto done;
3165 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3166 if (err)
3167 goto done;
3169 arg.diff_context = diff_context;
3170 arg.ignore_whitespace = ignore_whitespace;
3171 arg.outfile = stdout;
3172 while (path[0] == '/')
3173 path++;
3174 err = got_diff_tree(tree1, tree2, path, path, repo,
3175 got_diff_blob_output_unidiff, &arg, 1);
3176 done:
3177 if (tree1)
3178 got_object_tree_close(tree1);
3179 if (tree2)
3180 got_object_tree_close(tree2);
3181 return err;
3184 static const struct got_error *
3185 get_changed_paths(struct got_pathlist_head *paths,
3186 struct got_commit_object *commit, struct got_repository *repo)
3188 const struct got_error *err = NULL;
3189 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3190 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3191 struct got_object_qid *qid;
3193 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3194 if (qid != NULL) {
3195 struct got_commit_object *pcommit;
3196 err = got_object_open_as_commit(&pcommit, repo,
3197 qid->id);
3198 if (err)
3199 return err;
3201 tree_id1 = got_object_commit_get_tree_id(pcommit);
3202 got_object_commit_close(pcommit);
3206 if (tree_id1) {
3207 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3208 if (err)
3209 goto done;
3212 tree_id2 = got_object_commit_get_tree_id(commit);
3213 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3214 if (err)
3215 goto done;
3217 err = got_diff_tree(tree1, tree2, "", "", repo,
3218 got_diff_tree_collect_changed_paths, paths, 0);
3219 done:
3220 if (tree1)
3221 got_object_tree_close(tree1);
3222 if (tree2)
3223 got_object_tree_close(tree2);
3224 return err;
3227 static const struct got_error *
3228 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3229 const char *path, int diff_context, struct got_repository *repo)
3231 const struct got_error *err = NULL;
3232 struct got_commit_object *pcommit = NULL;
3233 char *id_str1 = NULL, *id_str2 = NULL;
3234 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3235 struct got_object_qid *qid;
3237 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3238 if (qid != NULL) {
3239 err = got_object_open_as_commit(&pcommit, repo,
3240 qid->id);
3241 if (err)
3242 return err;
3245 if (path && path[0] != '\0') {
3246 int obj_type;
3247 err = got_object_id_by_path(&obj_id2, repo, id, path);
3248 if (err)
3249 goto done;
3250 err = got_object_id_str(&id_str2, obj_id2);
3251 if (err) {
3252 free(obj_id2);
3253 goto done;
3255 if (pcommit) {
3256 err = got_object_id_by_path(&obj_id1, repo,
3257 qid->id, path);
3258 if (err) {
3259 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3260 free(obj_id2);
3261 goto done;
3263 } else {
3264 err = got_object_id_str(&id_str1, obj_id1);
3265 if (err) {
3266 free(obj_id2);
3267 goto done;
3271 err = got_object_get_type(&obj_type, repo, obj_id2);
3272 if (err) {
3273 free(obj_id2);
3274 goto done;
3276 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3277 switch (obj_type) {
3278 case GOT_OBJ_TYPE_BLOB:
3279 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3280 0, repo);
3281 break;
3282 case GOT_OBJ_TYPE_TREE:
3283 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3284 0, repo);
3285 break;
3286 default:
3287 err = got_error(GOT_ERR_OBJ_TYPE);
3288 break;
3290 free(obj_id1);
3291 free(obj_id2);
3292 } else {
3293 obj_id2 = got_object_commit_get_tree_id(commit);
3294 err = got_object_id_str(&id_str2, obj_id2);
3295 if (err)
3296 goto done;
3297 obj_id1 = got_object_commit_get_tree_id(pcommit);
3298 err = got_object_id_str(&id_str1, obj_id1);
3299 if (err)
3300 goto done;
3301 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3302 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3304 done:
3305 free(id_str1);
3306 free(id_str2);
3307 if (pcommit)
3308 got_object_commit_close(pcommit);
3309 return err;
3312 static char *
3313 get_datestr(time_t *time, char *datebuf)
3315 struct tm mytm, *tm;
3316 char *p, *s;
3318 tm = gmtime_r(time, &mytm);
3319 if (tm == NULL)
3320 return NULL;
3321 s = asctime_r(tm, datebuf);
3322 if (s == NULL)
3323 return NULL;
3324 p = strchr(s, '\n');
3325 if (p)
3326 *p = '\0';
3327 return s;
3330 static const struct got_error *
3331 match_logmsg(int *have_match, struct got_object_id *id,
3332 struct got_commit_object *commit, regex_t *regex)
3334 const struct got_error *err = NULL;
3335 regmatch_t regmatch;
3336 char *id_str = NULL, *logmsg = NULL;
3338 *have_match = 0;
3340 err = got_object_id_str(&id_str, id);
3341 if (err)
3342 return err;
3344 err = got_object_commit_get_logmsg(&logmsg, commit);
3345 if (err)
3346 goto done;
3348 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3349 *have_match = 1;
3350 done:
3351 free(id_str);
3352 free(logmsg);
3353 return err;
3356 static void
3357 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3358 regex_t *regex)
3360 regmatch_t regmatch;
3361 struct got_pathlist_entry *pe;
3363 *have_match = 0;
3365 TAILQ_FOREACH(pe, changed_paths, entry) {
3366 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3367 *have_match = 1;
3368 break;
3373 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3375 static const struct got_error *
3376 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3377 struct got_repository *repo, const char *path,
3378 struct got_pathlist_head *changed_paths, int show_patch,
3379 int diff_context, struct got_reflist_head *refs)
3381 const struct got_error *err = NULL;
3382 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3383 char datebuf[26];
3384 time_t committer_time;
3385 const char *author, *committer;
3386 char *refs_str = NULL;
3387 struct got_reflist_entry *re;
3389 SIMPLEQ_FOREACH(re, refs, entry) {
3390 char *s;
3391 const char *name;
3392 struct got_tag_object *tag = NULL;
3393 struct got_object_id *ref_id;
3394 int cmp;
3396 name = got_ref_get_name(re->ref);
3397 if (strcmp(name, GOT_REF_HEAD) == 0)
3398 continue;
3399 if (strncmp(name, "refs/", 5) == 0)
3400 name += 5;
3401 if (strncmp(name, "got/", 4) == 0)
3402 continue;
3403 if (strncmp(name, "heads/", 6) == 0)
3404 name += 6;
3405 if (strncmp(name, "remotes/", 8) == 0) {
3406 name += 8;
3407 s = strstr(name, "/" GOT_REF_HEAD);
3408 if (s != NULL && s[strlen(s)] == '\0')
3409 continue;
3411 err = got_ref_resolve(&ref_id, repo, re->ref);
3412 if (err)
3413 return err;
3414 if (strncmp(name, "tags/", 5) == 0) {
3415 err = got_object_open_as_tag(&tag, repo, ref_id);
3416 if (err) {
3417 if (err->code != GOT_ERR_OBJ_TYPE) {
3418 free(ref_id);
3419 return err;
3421 /* Ref points at something other than a tag. */
3422 err = NULL;
3423 tag = NULL;
3426 cmp = got_object_id_cmp(tag ?
3427 got_object_tag_get_object_id(tag) : ref_id, id);
3428 free(ref_id);
3429 if (tag)
3430 got_object_tag_close(tag);
3431 if (cmp != 0)
3432 continue;
3433 s = refs_str;
3434 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3435 name) == -1) {
3436 err = got_error_from_errno("asprintf");
3437 free(s);
3438 return err;
3440 free(s);
3442 err = got_object_id_str(&id_str, id);
3443 if (err)
3444 return err;
3446 printf(GOT_COMMIT_SEP_STR);
3447 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3448 refs_str ? refs_str : "", refs_str ? ")" : "");
3449 free(id_str);
3450 id_str = NULL;
3451 free(refs_str);
3452 refs_str = NULL;
3453 printf("from: %s\n", got_object_commit_get_author(commit));
3454 committer_time = got_object_commit_get_committer_time(commit);
3455 datestr = get_datestr(&committer_time, datebuf);
3456 if (datestr)
3457 printf("date: %s UTC\n", datestr);
3458 author = got_object_commit_get_author(commit);
3459 committer = got_object_commit_get_committer(commit);
3460 if (strcmp(author, committer) != 0)
3461 printf("via: %s\n", committer);
3462 if (got_object_commit_get_nparents(commit) > 1) {
3463 const struct got_object_id_queue *parent_ids;
3464 struct got_object_qid *qid;
3465 int n = 1;
3466 parent_ids = got_object_commit_get_parent_ids(commit);
3467 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3468 err = got_object_id_str(&id_str, qid->id);
3469 if (err)
3470 return err;
3471 printf("parent %d: %s\n", n++, id_str);
3472 free(id_str);
3476 err = got_object_commit_get_logmsg(&logmsg0, commit);
3477 if (err)
3478 return err;
3480 logmsg = logmsg0;
3481 do {
3482 line = strsep(&logmsg, "\n");
3483 if (line)
3484 printf(" %s\n", line);
3485 } while (line);
3486 free(logmsg0);
3488 if (changed_paths) {
3489 struct got_pathlist_entry *pe;
3490 TAILQ_FOREACH(pe, changed_paths, entry) {
3491 struct got_diff_changed_path *cp = pe->data;
3492 printf(" %c %s\n", cp->status, pe->path);
3494 printf("\n");
3496 if (show_patch) {
3497 err = print_patch(commit, id, path, diff_context, repo);
3498 if (err == 0)
3499 printf("\n");
3502 if (fflush(stdout) != 0 && err == NULL)
3503 err = got_error_from_errno("fflush");
3504 return err;
3507 static const struct got_error *
3508 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3509 struct got_repository *repo, const char *path, int show_changed_paths,
3510 int show_patch, const char *search_pattern, int diff_context, int limit,
3511 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3513 const struct got_error *err;
3514 struct got_commit_graph *graph;
3515 regex_t regex;
3516 int have_match;
3517 struct got_object_id_queue reversed_commits;
3518 struct got_object_qid *qid;
3519 struct got_commit_object *commit;
3520 struct got_pathlist_head changed_paths;
3521 struct got_pathlist_entry *pe;
3523 SIMPLEQ_INIT(&reversed_commits);
3524 TAILQ_INIT(&changed_paths);
3526 if (search_pattern && regcomp(&regex, search_pattern,
3527 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3528 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3530 err = got_commit_graph_open(&graph, path, !log_branches);
3531 if (err)
3532 return err;
3533 err = got_commit_graph_iter_start(graph, root_id, repo,
3534 check_cancelled, NULL);
3535 if (err)
3536 goto done;
3537 for (;;) {
3538 struct got_object_id *id;
3540 if (sigint_received || sigpipe_received)
3541 break;
3543 err = got_commit_graph_iter_next(&id, graph, repo,
3544 check_cancelled, NULL);
3545 if (err) {
3546 if (err->code == GOT_ERR_ITER_COMPLETED)
3547 err = NULL;
3548 break;
3550 if (id == NULL)
3551 break;
3553 err = got_object_open_as_commit(&commit, repo, id);
3554 if (err)
3555 break;
3557 if (show_changed_paths && !reverse_display_order) {
3558 err = get_changed_paths(&changed_paths, commit, repo);
3559 if (err)
3560 break;
3563 if (search_pattern) {
3564 err = match_logmsg(&have_match, id, commit, &regex);
3565 if (err) {
3566 got_object_commit_close(commit);
3567 break;
3569 if (have_match == 0 && show_changed_paths)
3570 match_changed_paths(&have_match,
3571 &changed_paths, &regex);
3572 if (have_match == 0) {
3573 got_object_commit_close(commit);
3574 TAILQ_FOREACH(pe, &changed_paths, entry) {
3575 free((char *)pe->path);
3576 free(pe->data);
3578 got_pathlist_free(&changed_paths);
3579 continue;
3583 if (reverse_display_order) {
3584 err = got_object_qid_alloc(&qid, id);
3585 if (err)
3586 break;
3587 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3588 got_object_commit_close(commit);
3589 } else {
3590 err = print_commit(commit, id, repo, path,
3591 show_changed_paths ? &changed_paths : NULL,
3592 show_patch, diff_context, refs);
3593 got_object_commit_close(commit);
3594 if (err)
3595 break;
3597 if ((limit && --limit == 0) ||
3598 (end_id && got_object_id_cmp(id, end_id) == 0))
3599 break;
3601 TAILQ_FOREACH(pe, &changed_paths, entry) {
3602 free((char *)pe->path);
3603 free(pe->data);
3605 got_pathlist_free(&changed_paths);
3607 if (reverse_display_order) {
3608 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3609 err = got_object_open_as_commit(&commit, repo, qid->id);
3610 if (err)
3611 break;
3612 if (show_changed_paths) {
3613 err = get_changed_paths(&changed_paths,
3614 commit, repo);
3615 if (err)
3616 break;
3618 err = print_commit(commit, qid->id, repo, path,
3619 show_changed_paths ? &changed_paths : NULL,
3620 show_patch, diff_context, refs);
3621 got_object_commit_close(commit);
3622 if (err)
3623 break;
3624 TAILQ_FOREACH(pe, &changed_paths, entry) {
3625 free((char *)pe->path);
3626 free(pe->data);
3628 got_pathlist_free(&changed_paths);
3631 done:
3632 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3633 qid = SIMPLEQ_FIRST(&reversed_commits);
3634 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3635 got_object_qid_free(qid);
3637 TAILQ_FOREACH(pe, &changed_paths, entry) {
3638 free((char *)pe->path);
3639 free(pe->data);
3641 got_pathlist_free(&changed_paths);
3642 if (search_pattern)
3643 regfree(&regex);
3644 got_commit_graph_close(graph);
3645 return err;
3648 __dead static void
3649 usage_log(void)
3651 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3652 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3653 "[-R] [path]\n", getprogname());
3654 exit(1);
3657 static int
3658 get_default_log_limit(void)
3660 const char *got_default_log_limit;
3661 long long n;
3662 const char *errstr;
3664 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3665 if (got_default_log_limit == NULL)
3666 return 0;
3667 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3668 if (errstr != NULL)
3669 return 0;
3670 return n;
3673 static const struct got_error *
3674 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3675 struct got_repository *repo)
3677 const struct got_error *err = NULL;
3678 struct got_reference *ref;
3680 *id = NULL;
3682 err = got_ref_open(&ref, repo, commit_arg, 0);
3683 if (err == NULL) {
3684 int obj_type;
3685 err = got_ref_resolve(id, repo, ref);
3686 got_ref_close(ref);
3687 if (err)
3688 return err;
3689 err = got_object_get_type(&obj_type, repo, *id);
3690 if (err)
3691 return err;
3692 if (obj_type == GOT_OBJ_TYPE_TAG) {
3693 struct got_tag_object *tag;
3694 err = got_object_open_as_tag(&tag, repo, *id);
3695 if (err)
3696 return err;
3697 if (got_object_tag_get_object_type(tag) !=
3698 GOT_OBJ_TYPE_COMMIT) {
3699 got_object_tag_close(tag);
3700 return got_error(GOT_ERR_OBJ_TYPE);
3702 free(*id);
3703 *id = got_object_id_dup(
3704 got_object_tag_get_object_id(tag));
3705 if (*id == NULL)
3706 err = got_error_from_errno(
3707 "got_object_id_dup");
3708 got_object_tag_close(tag);
3709 if (err)
3710 return err;
3711 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3712 return got_error(GOT_ERR_OBJ_TYPE);
3713 } else {
3714 err = got_repo_match_object_id_prefix(id, commit_arg,
3715 GOT_OBJ_TYPE_COMMIT, repo);
3718 return err;
3721 static const struct got_error *
3722 cmd_log(int argc, char *argv[])
3724 const struct got_error *error;
3725 struct got_repository *repo = NULL;
3726 struct got_worktree *worktree = NULL;
3727 struct got_object_id *start_id = NULL, *end_id = NULL;
3728 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3729 const char *start_commit = NULL, *end_commit = NULL;
3730 const char *search_pattern = NULL;
3731 int diff_context = -1, ch;
3732 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3733 int reverse_display_order = 0;
3734 const char *errstr;
3735 struct got_reflist_head refs;
3737 SIMPLEQ_INIT(&refs);
3739 #ifndef PROFILE
3740 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3741 NULL)
3742 == -1)
3743 err(1, "pledge");
3744 #endif
3746 limit = get_default_log_limit();
3748 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3749 switch (ch) {
3750 case 'p':
3751 show_patch = 1;
3752 break;
3753 case 'P':
3754 show_changed_paths = 1;
3755 break;
3756 case 'c':
3757 start_commit = optarg;
3758 break;
3759 case 'C':
3760 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3761 &errstr);
3762 if (errstr != NULL)
3763 err(1, "-C option %s", errstr);
3764 break;
3765 case 'l':
3766 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3767 if (errstr != NULL)
3768 err(1, "-l option %s", errstr);
3769 break;
3770 case 'b':
3771 log_branches = 1;
3772 break;
3773 case 'r':
3774 repo_path = realpath(optarg, NULL);
3775 if (repo_path == NULL)
3776 return got_error_from_errno2("realpath",
3777 optarg);
3778 got_path_strip_trailing_slashes(repo_path);
3779 break;
3780 case 'R':
3781 reverse_display_order = 1;
3782 break;
3783 case 's':
3784 search_pattern = optarg;
3785 break;
3786 case 'x':
3787 end_commit = optarg;
3788 break;
3789 default:
3790 usage_log();
3791 /* NOTREACHED */
3795 argc -= optind;
3796 argv += optind;
3798 if (diff_context == -1)
3799 diff_context = 3;
3800 else if (!show_patch)
3801 errx(1, "-C requires -p");
3803 cwd = getcwd(NULL, 0);
3804 if (cwd == NULL) {
3805 error = got_error_from_errno("getcwd");
3806 goto done;
3809 if (repo_path == NULL) {
3810 error = got_worktree_open(&worktree, cwd);
3811 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3812 goto done;
3813 error = NULL;
3816 if (argc == 0) {
3817 path = strdup("");
3818 if (path == NULL) {
3819 error = got_error_from_errno("strdup");
3820 goto done;
3822 } else if (argc == 1) {
3823 if (worktree) {
3824 error = got_worktree_resolve_path(&path, worktree,
3825 argv[0]);
3826 if (error)
3827 goto done;
3828 } else {
3829 path = strdup(argv[0]);
3830 if (path == NULL) {
3831 error = got_error_from_errno("strdup");
3832 goto done;
3835 } else
3836 usage_log();
3838 if (repo_path == NULL) {
3839 repo_path = worktree ?
3840 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3842 if (repo_path == NULL) {
3843 error = got_error_from_errno("strdup");
3844 goto done;
3847 error = got_repo_open(&repo, repo_path, NULL);
3848 if (error != NULL)
3849 goto done;
3851 error = apply_unveil(got_repo_get_path(repo), 1,
3852 worktree ? got_worktree_get_root_path(worktree) : NULL);
3853 if (error)
3854 goto done;
3856 if (start_commit == NULL) {
3857 struct got_reference *head_ref;
3858 struct got_commit_object *commit = NULL;
3859 error = got_ref_open(&head_ref, repo,
3860 worktree ? got_worktree_get_head_ref_name(worktree)
3861 : GOT_REF_HEAD, 0);
3862 if (error != NULL)
3863 goto done;
3864 error = got_ref_resolve(&start_id, repo, head_ref);
3865 got_ref_close(head_ref);
3866 if (error != NULL)
3867 goto done;
3868 error = got_object_open_as_commit(&commit, repo,
3869 start_id);
3870 if (error != NULL)
3871 goto done;
3872 got_object_commit_close(commit);
3873 } else {
3874 error = resolve_commit_arg(&start_id, start_commit, repo);
3875 if (error != NULL)
3876 goto done;
3878 if (end_commit != NULL) {
3879 error = resolve_commit_arg(&end_id, end_commit, repo);
3880 if (error != NULL)
3881 goto done;
3884 if (worktree) {
3885 const char *prefix = got_worktree_get_path_prefix(worktree);
3886 char *p;
3887 if (asprintf(&p, "%s%s%s", prefix,
3888 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3889 error = got_error_from_errno("asprintf");
3890 goto done;
3892 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3893 free(p);
3894 } else
3895 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3896 if (error != NULL)
3897 goto done;
3898 if (in_repo_path) {
3899 free(path);
3900 path = in_repo_path;
3903 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3904 if (error)
3905 goto done;
3907 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3908 show_patch, search_pattern, diff_context, limit, log_branches,
3909 reverse_display_order, &refs);
3910 done:
3911 free(path);
3912 free(repo_path);
3913 free(cwd);
3914 if (worktree)
3915 got_worktree_close(worktree);
3916 if (repo) {
3917 const struct got_error *repo_error;
3918 repo_error = got_repo_close(repo);
3919 if (error == NULL)
3920 error = repo_error;
3922 got_ref_list_free(&refs);
3923 return error;
3926 __dead static void
3927 usage_diff(void)
3929 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3930 "[-w] [object1 object2 | path]\n", getprogname());
3931 exit(1);
3934 struct print_diff_arg {
3935 struct got_repository *repo;
3936 struct got_worktree *worktree;
3937 int diff_context;
3938 const char *id_str;
3939 int header_shown;
3940 int diff_staged;
3941 int ignore_whitespace;
3945 * Create a file which contains the target path of a symlink so we can feed
3946 * it as content to the diff engine.
3948 static const struct got_error *
3949 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3950 const char *abspath)
3952 const struct got_error *err = NULL;
3953 char target_path[PATH_MAX];
3954 ssize_t target_len, outlen;
3956 *fd = -1;
3958 if (dirfd != -1) {
3959 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3960 if (target_len == -1)
3961 return got_error_from_errno2("readlinkat", abspath);
3962 } else {
3963 target_len = readlink(abspath, target_path, PATH_MAX);
3964 if (target_len == -1)
3965 return got_error_from_errno2("readlink", abspath);
3968 *fd = got_opentempfd();
3969 if (*fd == -1)
3970 return got_error_from_errno("got_opentempfd");
3972 outlen = write(*fd, target_path, target_len);
3973 if (outlen == -1) {
3974 err = got_error_from_errno("got_opentempfd");
3975 goto done;
3978 if (lseek(*fd, 0, SEEK_SET) == -1) {
3979 err = got_error_from_errno2("lseek", abspath);
3980 goto done;
3982 done:
3983 if (err) {
3984 close(*fd);
3985 *fd = -1;
3987 return err;
3990 static const struct got_error *
3991 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3992 const char *path, struct got_object_id *blob_id,
3993 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3994 int dirfd, const char *de_name)
3996 struct print_diff_arg *a = arg;
3997 const struct got_error *err = NULL;
3998 struct got_blob_object *blob1 = NULL;
3999 int fd = -1;
4000 FILE *f2 = NULL;
4001 char *abspath = NULL, *label1 = NULL;
4002 struct stat sb;
4004 if (a->diff_staged) {
4005 if (staged_status != GOT_STATUS_MODIFY &&
4006 staged_status != GOT_STATUS_ADD &&
4007 staged_status != GOT_STATUS_DELETE)
4008 return NULL;
4009 } else {
4010 if (staged_status == GOT_STATUS_DELETE)
4011 return NULL;
4012 if (status == GOT_STATUS_NONEXISTENT)
4013 return got_error_set_errno(ENOENT, path);
4014 if (status != GOT_STATUS_MODIFY &&
4015 status != GOT_STATUS_ADD &&
4016 status != GOT_STATUS_DELETE &&
4017 status != GOT_STATUS_CONFLICT)
4018 return NULL;
4021 if (!a->header_shown) {
4022 printf("diff %s %s%s\n", a->id_str,
4023 got_worktree_get_root_path(a->worktree),
4024 a->diff_staged ? " (staged changes)" : "");
4025 a->header_shown = 1;
4028 if (a->diff_staged) {
4029 const char *label1 = NULL, *label2 = NULL;
4030 switch (staged_status) {
4031 case GOT_STATUS_MODIFY:
4032 label1 = path;
4033 label2 = path;
4034 break;
4035 case GOT_STATUS_ADD:
4036 label2 = path;
4037 break;
4038 case GOT_STATUS_DELETE:
4039 label1 = path;
4040 break;
4041 default:
4042 return got_error(GOT_ERR_FILE_STATUS);
4044 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4045 label1, label2, a->diff_context, a->ignore_whitespace,
4046 a->repo, stdout);
4049 if (staged_status == GOT_STATUS_ADD ||
4050 staged_status == GOT_STATUS_MODIFY) {
4051 char *id_str;
4052 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4053 8192);
4054 if (err)
4055 goto done;
4056 err = got_object_id_str(&id_str, staged_blob_id);
4057 if (err)
4058 goto done;
4059 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4060 err = got_error_from_errno("asprintf");
4061 free(id_str);
4062 goto done;
4064 free(id_str);
4065 } else if (status != GOT_STATUS_ADD) {
4066 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4067 if (err)
4068 goto done;
4071 if (status != GOT_STATUS_DELETE) {
4072 if (asprintf(&abspath, "%s/%s",
4073 got_worktree_get_root_path(a->worktree), path) == -1) {
4074 err = got_error_from_errno("asprintf");
4075 goto done;
4078 if (dirfd != -1) {
4079 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4080 if (fd == -1) {
4081 if (errno != ELOOP) {
4082 err = got_error_from_errno2("openat",
4083 abspath);
4084 goto done;
4086 err = get_symlink_target_file(&fd, dirfd,
4087 de_name, abspath);
4088 if (err)
4089 goto done;
4091 } else {
4092 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4093 if (fd == -1) {
4094 if (errno != ELOOP) {
4095 err = got_error_from_errno2("open",
4096 abspath);
4097 goto done;
4099 err = get_symlink_target_file(&fd, dirfd,
4100 de_name, abspath);
4101 if (err)
4102 goto done;
4105 if (fstat(fd, &sb) == -1) {
4106 err = got_error_from_errno2("fstat", abspath);
4107 goto done;
4109 f2 = fdopen(fd, "r");
4110 if (f2 == NULL) {
4111 err = got_error_from_errno2("fdopen", abspath);
4112 goto done;
4114 fd = -1;
4115 } else
4116 sb.st_size = 0;
4118 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4119 a->diff_context, a->ignore_whitespace, stdout);
4120 done:
4121 if (blob1)
4122 got_object_blob_close(blob1);
4123 if (f2 && fclose(f2) == EOF && err == NULL)
4124 err = got_error_from_errno("fclose");
4125 if (fd != -1 && close(fd) == -1 && err == NULL)
4126 err = got_error_from_errno("close");
4127 free(abspath);
4128 return err;
4131 static const struct got_error *
4132 cmd_diff(int argc, char *argv[])
4134 const struct got_error *error;
4135 struct got_repository *repo = NULL;
4136 struct got_worktree *worktree = NULL;
4137 char *cwd = NULL, *repo_path = NULL;
4138 struct got_object_id *id1 = NULL, *id2 = NULL;
4139 const char *id_str1 = NULL, *id_str2 = NULL;
4140 char *label1 = NULL, *label2 = NULL;
4141 int type1, type2;
4142 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4143 const char *errstr;
4144 char *path = NULL;
4146 #ifndef PROFILE
4147 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4148 NULL) == -1)
4149 err(1, "pledge");
4150 #endif
4152 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4153 switch (ch) {
4154 case 'C':
4155 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4156 &errstr);
4157 if (errstr != NULL)
4158 err(1, "-C option %s", errstr);
4159 break;
4160 case 'r':
4161 repo_path = realpath(optarg, NULL);
4162 if (repo_path == NULL)
4163 return got_error_from_errno2("realpath",
4164 optarg);
4165 got_path_strip_trailing_slashes(repo_path);
4166 break;
4167 case 's':
4168 diff_staged = 1;
4169 break;
4170 case 'w':
4171 ignore_whitespace = 1;
4172 break;
4173 default:
4174 usage_diff();
4175 /* NOTREACHED */
4179 argc -= optind;
4180 argv += optind;
4182 cwd = getcwd(NULL, 0);
4183 if (cwd == NULL) {
4184 error = got_error_from_errno("getcwd");
4185 goto done;
4187 if (argc <= 1) {
4188 if (repo_path)
4189 errx(1,
4190 "-r option can't be used when diffing a work tree");
4191 error = got_worktree_open(&worktree, cwd);
4192 if (error) {
4193 if (error->code == GOT_ERR_NOT_WORKTREE)
4194 error = wrap_not_worktree_error(error, "diff",
4195 cwd);
4196 goto done;
4198 repo_path = strdup(got_worktree_get_repo_path(worktree));
4199 if (repo_path == NULL) {
4200 error = got_error_from_errno("strdup");
4201 goto done;
4203 if (argc == 1) {
4204 error = got_worktree_resolve_path(&path, worktree,
4205 argv[0]);
4206 if (error)
4207 goto done;
4208 } else {
4209 path = strdup("");
4210 if (path == NULL) {
4211 error = got_error_from_errno("strdup");
4212 goto done;
4215 } else if (argc == 2) {
4216 if (diff_staged)
4217 errx(1, "-s option can't be used when diffing "
4218 "objects in repository");
4219 id_str1 = argv[0];
4220 id_str2 = argv[1];
4221 if (repo_path == NULL) {
4222 error = got_worktree_open(&worktree, cwd);
4223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4224 goto done;
4225 if (worktree) {
4226 repo_path = strdup(
4227 got_worktree_get_repo_path(worktree));
4228 if (repo_path == NULL) {
4229 error = got_error_from_errno("strdup");
4230 goto done;
4232 } else {
4233 repo_path = strdup(cwd);
4234 if (repo_path == NULL) {
4235 error = got_error_from_errno("strdup");
4236 goto done;
4240 } else
4241 usage_diff();
4243 error = got_repo_open(&repo, repo_path, NULL);
4244 free(repo_path);
4245 if (error != NULL)
4246 goto done;
4248 error = apply_unveil(got_repo_get_path(repo), 1,
4249 worktree ? got_worktree_get_root_path(worktree) : NULL);
4250 if (error)
4251 goto done;
4253 if (argc <= 1) {
4254 struct print_diff_arg arg;
4255 struct got_pathlist_head paths;
4256 char *id_str;
4258 TAILQ_INIT(&paths);
4260 error = got_object_id_str(&id_str,
4261 got_worktree_get_base_commit_id(worktree));
4262 if (error)
4263 goto done;
4264 arg.repo = repo;
4265 arg.worktree = worktree;
4266 arg.diff_context = diff_context;
4267 arg.id_str = id_str;
4268 arg.header_shown = 0;
4269 arg.diff_staged = diff_staged;
4270 arg.ignore_whitespace = ignore_whitespace;
4272 error = got_pathlist_append(&paths, path, NULL);
4273 if (error)
4274 goto done;
4276 error = got_worktree_status(worktree, &paths, repo, print_diff,
4277 &arg, check_cancelled, NULL);
4278 free(id_str);
4279 got_pathlist_free(&paths);
4280 goto done;
4283 error = got_repo_match_object_id(&id1, &label1, id_str1,
4284 GOT_OBJ_TYPE_ANY, 1, repo);
4285 if (error)
4286 goto done;
4288 error = got_repo_match_object_id(&id2, &label2, id_str2,
4289 GOT_OBJ_TYPE_ANY, 1, repo);
4290 if (error)
4291 goto done;
4293 error = got_object_get_type(&type1, repo, id1);
4294 if (error)
4295 goto done;
4297 error = got_object_get_type(&type2, repo, id2);
4298 if (error)
4299 goto done;
4301 if (type1 != type2) {
4302 error = got_error(GOT_ERR_OBJ_TYPE);
4303 goto done;
4306 switch (type1) {
4307 case GOT_OBJ_TYPE_BLOB:
4308 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4309 diff_context, ignore_whitespace, repo, stdout);
4310 break;
4311 case GOT_OBJ_TYPE_TREE:
4312 error = got_diff_objects_as_trees(id1, id2, "", "",
4313 diff_context, ignore_whitespace, repo, stdout);
4314 break;
4315 case GOT_OBJ_TYPE_COMMIT:
4316 printf("diff %s %s\n", label1, label2);
4317 error = got_diff_objects_as_commits(id1, id2, diff_context,
4318 ignore_whitespace, repo, stdout);
4319 break;
4320 default:
4321 error = got_error(GOT_ERR_OBJ_TYPE);
4323 done:
4324 free(label1);
4325 free(label2);
4326 free(id1);
4327 free(id2);
4328 free(path);
4329 if (worktree)
4330 got_worktree_close(worktree);
4331 if (repo) {
4332 const struct got_error *repo_error;
4333 repo_error = got_repo_close(repo);
4334 if (error == NULL)
4335 error = repo_error;
4337 return error;
4340 __dead static void
4341 usage_blame(void)
4343 fprintf(stderr,
4344 "usage: %s blame [-c commit] [-r repository-path] path\n",
4345 getprogname());
4346 exit(1);
4349 struct blame_line {
4350 int annotated;
4351 char *id_str;
4352 char *committer;
4353 char datebuf[11]; /* YYYY-MM-DD + NUL */
4356 struct blame_cb_args {
4357 struct blame_line *lines;
4358 int nlines;
4359 int nlines_prec;
4360 int lineno_cur;
4361 off_t *line_offsets;
4362 FILE *f;
4363 struct got_repository *repo;
4366 static const struct got_error *
4367 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4369 const struct got_error *err = NULL;
4370 struct blame_cb_args *a = arg;
4371 struct blame_line *bline;
4372 char *line = NULL;
4373 size_t linesize = 0;
4374 struct got_commit_object *commit = NULL;
4375 off_t offset;
4376 struct tm tm;
4377 time_t committer_time;
4379 if (nlines != a->nlines ||
4380 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4381 return got_error(GOT_ERR_RANGE);
4383 if (sigint_received)
4384 return got_error(GOT_ERR_ITER_COMPLETED);
4386 if (lineno == -1)
4387 return NULL; /* no change in this commit */
4389 /* Annotate this line. */
4390 bline = &a->lines[lineno - 1];
4391 if (bline->annotated)
4392 return NULL;
4393 err = got_object_id_str(&bline->id_str, id);
4394 if (err)
4395 return err;
4397 err = got_object_open_as_commit(&commit, a->repo, id);
4398 if (err)
4399 goto done;
4401 bline->committer = strdup(got_object_commit_get_committer(commit));
4402 if (bline->committer == NULL) {
4403 err = got_error_from_errno("strdup");
4404 goto done;
4407 committer_time = got_object_commit_get_committer_time(commit);
4408 if (localtime_r(&committer_time, &tm) == NULL)
4409 return got_error_from_errno("localtime_r");
4410 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4411 &tm) >= sizeof(bline->datebuf)) {
4412 err = got_error(GOT_ERR_NO_SPACE);
4413 goto done;
4415 bline->annotated = 1;
4417 /* Print lines annotated so far. */
4418 bline = &a->lines[a->lineno_cur - 1];
4419 if (!bline->annotated)
4420 goto done;
4422 offset = a->line_offsets[a->lineno_cur - 1];
4423 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4424 err = got_error_from_errno("fseeko");
4425 goto done;
4428 while (bline->annotated) {
4429 char *smallerthan, *at, *nl, *committer;
4430 size_t len;
4432 if (getline(&line, &linesize, a->f) == -1) {
4433 if (ferror(a->f))
4434 err = got_error_from_errno("getline");
4435 break;
4438 committer = bline->committer;
4439 smallerthan = strchr(committer, '<');
4440 if (smallerthan && smallerthan[1] != '\0')
4441 committer = smallerthan + 1;
4442 at = strchr(committer, '@');
4443 if (at)
4444 *at = '\0';
4445 len = strlen(committer);
4446 if (len >= 9)
4447 committer[8] = '\0';
4449 nl = strchr(line, '\n');
4450 if (nl)
4451 *nl = '\0';
4452 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4453 bline->id_str, bline->datebuf, committer, line);
4455 a->lineno_cur++;
4456 bline = &a->lines[a->lineno_cur - 1];
4458 done:
4459 if (commit)
4460 got_object_commit_close(commit);
4461 free(line);
4462 return err;
4465 static const struct got_error *
4466 cmd_blame(int argc, char *argv[])
4468 const struct got_error *error;
4469 struct got_repository *repo = NULL;
4470 struct got_worktree *worktree = NULL;
4471 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4472 char *link_target = NULL;
4473 struct got_object_id *obj_id = NULL;
4474 struct got_object_id *commit_id = NULL;
4475 struct got_blob_object *blob = NULL;
4476 char *commit_id_str = NULL;
4477 struct blame_cb_args bca;
4478 int ch, obj_type, i;
4479 size_t filesize;
4481 memset(&bca, 0, sizeof(bca));
4483 #ifndef PROFILE
4484 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4485 NULL) == -1)
4486 err(1, "pledge");
4487 #endif
4489 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4490 switch (ch) {
4491 case 'c':
4492 commit_id_str = optarg;
4493 break;
4494 case 'r':
4495 repo_path = realpath(optarg, NULL);
4496 if (repo_path == NULL)
4497 return got_error_from_errno2("realpath",
4498 optarg);
4499 got_path_strip_trailing_slashes(repo_path);
4500 break;
4501 default:
4502 usage_blame();
4503 /* NOTREACHED */
4507 argc -= optind;
4508 argv += optind;
4510 if (argc == 1)
4511 path = argv[0];
4512 else
4513 usage_blame();
4515 cwd = getcwd(NULL, 0);
4516 if (cwd == NULL) {
4517 error = got_error_from_errno("getcwd");
4518 goto done;
4520 if (repo_path == NULL) {
4521 error = got_worktree_open(&worktree, cwd);
4522 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4523 goto done;
4524 else
4525 error = NULL;
4526 if (worktree) {
4527 repo_path =
4528 strdup(got_worktree_get_repo_path(worktree));
4529 if (repo_path == NULL) {
4530 error = got_error_from_errno("strdup");
4531 if (error)
4532 goto done;
4534 } else {
4535 repo_path = strdup(cwd);
4536 if (repo_path == NULL) {
4537 error = got_error_from_errno("strdup");
4538 goto done;
4543 error = got_repo_open(&repo, repo_path, NULL);
4544 if (error != NULL)
4545 goto done;
4547 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4548 if (error)
4549 goto done;
4551 if (worktree) {
4552 const char *prefix = got_worktree_get_path_prefix(worktree);
4553 char *p, *worktree_subdir = cwd +
4554 strlen(got_worktree_get_root_path(worktree));
4555 if (asprintf(&p, "%s%s%s%s%s",
4556 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4557 worktree_subdir, worktree_subdir[0] ? "/" : "",
4558 path) == -1) {
4559 error = got_error_from_errno("asprintf");
4560 goto done;
4562 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4563 free(p);
4564 } else {
4565 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4567 if (error)
4568 goto done;
4570 if (commit_id_str == NULL) {
4571 struct got_reference *head_ref;
4572 error = got_ref_open(&head_ref, repo, worktree ?
4573 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4574 if (error != NULL)
4575 goto done;
4576 error = got_ref_resolve(&commit_id, repo, head_ref);
4577 got_ref_close(head_ref);
4578 if (error != NULL)
4579 goto done;
4580 } else {
4581 error = got_repo_match_object_id(&commit_id, NULL,
4582 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4583 if (error)
4584 goto done;
4587 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4588 commit_id, repo);
4589 if (error)
4590 goto done;
4592 error = got_object_id_by_path(&obj_id, repo, commit_id,
4593 link_target ? link_target : in_repo_path);
4594 if (error)
4595 goto done;
4597 error = got_object_get_type(&obj_type, repo, obj_id);
4598 if (error)
4599 goto done;
4601 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4602 error = got_error_path(link_target ? link_target : in_repo_path,
4603 GOT_ERR_OBJ_TYPE);
4604 goto done;
4607 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4608 if (error)
4609 goto done;
4610 bca.f = got_opentemp();
4611 if (bca.f == NULL) {
4612 error = got_error_from_errno("got_opentemp");
4613 goto done;
4615 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4616 &bca.line_offsets, bca.f, blob);
4617 if (error || bca.nlines == 0)
4618 goto done;
4620 /* Don't include \n at EOF in the blame line count. */
4621 if (bca.line_offsets[bca.nlines - 1] == filesize)
4622 bca.nlines--;
4624 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4625 if (bca.lines == NULL) {
4626 error = got_error_from_errno("calloc");
4627 goto done;
4629 bca.lineno_cur = 1;
4630 bca.nlines_prec = 0;
4631 i = bca.nlines;
4632 while (i > 0) {
4633 i /= 10;
4634 bca.nlines_prec++;
4636 bca.repo = repo;
4638 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4639 repo, blame_cb, &bca, check_cancelled, NULL);
4640 done:
4641 free(in_repo_path);
4642 free(link_target);
4643 free(repo_path);
4644 free(cwd);
4645 free(commit_id);
4646 free(obj_id);
4647 if (blob)
4648 got_object_blob_close(blob);
4649 if (worktree)
4650 got_worktree_close(worktree);
4651 if (repo) {
4652 const struct got_error *repo_error;
4653 repo_error = got_repo_close(repo);
4654 if (error == NULL)
4655 error = repo_error;
4657 if (bca.lines) {
4658 for (i = 0; i < bca.nlines; i++) {
4659 struct blame_line *bline = &bca.lines[i];
4660 free(bline->id_str);
4661 free(bline->committer);
4663 free(bca.lines);
4665 free(bca.line_offsets);
4666 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4667 error = got_error_from_errno("fclose");
4668 return error;
4671 __dead static void
4672 usage_tree(void)
4674 fprintf(stderr,
4675 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4676 getprogname());
4677 exit(1);
4680 static const struct got_error *
4681 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4682 const char *root_path, struct got_repository *repo)
4684 const struct got_error *err = NULL;
4685 int is_root_path = (strcmp(path, root_path) == 0);
4686 const char *modestr = "";
4687 mode_t mode = got_tree_entry_get_mode(te);
4688 char *link_target = NULL;
4690 path += strlen(root_path);
4691 while (path[0] == '/')
4692 path++;
4694 if (got_object_tree_entry_is_submodule(te))
4695 modestr = "$";
4696 else if (S_ISLNK(mode)) {
4697 int i;
4699 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4700 if (err)
4701 return err;
4702 for (i = 0; i < strlen(link_target); i++) {
4703 if (!isprint((unsigned char)link_target[i]))
4704 link_target[i] = '?';
4707 modestr = "@";
4709 else if (S_ISDIR(mode))
4710 modestr = "/";
4711 else if (mode & S_IXUSR)
4712 modestr = "*";
4714 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4715 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4716 link_target ? " -> ": "", link_target ? link_target : "");
4718 free(link_target);
4719 return NULL;
4722 static const struct got_error *
4723 print_tree(const char *path, struct got_object_id *commit_id,
4724 int show_ids, int recurse, const char *root_path,
4725 struct got_repository *repo)
4727 const struct got_error *err = NULL;
4728 struct got_object_id *tree_id = NULL;
4729 struct got_tree_object *tree = NULL;
4730 int nentries, i;
4732 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4733 if (err)
4734 goto done;
4736 err = got_object_open_as_tree(&tree, repo, tree_id);
4737 if (err)
4738 goto done;
4739 nentries = got_object_tree_get_nentries(tree);
4740 for (i = 0; i < nentries; i++) {
4741 struct got_tree_entry *te;
4742 char *id = NULL;
4744 if (sigint_received || sigpipe_received)
4745 break;
4747 te = got_object_tree_get_entry(tree, i);
4748 if (show_ids) {
4749 char *id_str;
4750 err = got_object_id_str(&id_str,
4751 got_tree_entry_get_id(te));
4752 if (err)
4753 goto done;
4754 if (asprintf(&id, "%s ", id_str) == -1) {
4755 err = got_error_from_errno("asprintf");
4756 free(id_str);
4757 goto done;
4759 free(id_str);
4761 err = print_entry(te, id, path, root_path, repo);
4762 free(id);
4763 if (err)
4764 goto done;
4766 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4767 char *child_path;
4768 if (asprintf(&child_path, "%s%s%s", path,
4769 path[0] == '/' && path[1] == '\0' ? "" : "/",
4770 got_tree_entry_get_name(te)) == -1) {
4771 err = got_error_from_errno("asprintf");
4772 goto done;
4774 err = print_tree(child_path, commit_id, show_ids, 1,
4775 root_path, repo);
4776 free(child_path);
4777 if (err)
4778 goto done;
4781 done:
4782 if (tree)
4783 got_object_tree_close(tree);
4784 free(tree_id);
4785 return err;
4788 static const struct got_error *
4789 cmd_tree(int argc, char *argv[])
4791 const struct got_error *error;
4792 struct got_repository *repo = NULL;
4793 struct got_worktree *worktree = NULL;
4794 const char *path, *refname = NULL;
4795 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4796 struct got_object_id *commit_id = NULL;
4797 char *commit_id_str = NULL;
4798 int show_ids = 0, recurse = 0;
4799 int ch;
4801 #ifndef PROFILE
4802 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4803 NULL) == -1)
4804 err(1, "pledge");
4805 #endif
4807 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4808 switch (ch) {
4809 case 'c':
4810 commit_id_str = optarg;
4811 break;
4812 case 'r':
4813 repo_path = realpath(optarg, NULL);
4814 if (repo_path == NULL)
4815 return got_error_from_errno2("realpath",
4816 optarg);
4817 got_path_strip_trailing_slashes(repo_path);
4818 break;
4819 case 'i':
4820 show_ids = 1;
4821 break;
4822 case 'R':
4823 recurse = 1;
4824 break;
4825 default:
4826 usage_tree();
4827 /* NOTREACHED */
4831 argc -= optind;
4832 argv += optind;
4834 if (argc == 1)
4835 path = argv[0];
4836 else if (argc > 1)
4837 usage_tree();
4838 else
4839 path = NULL;
4841 cwd = getcwd(NULL, 0);
4842 if (cwd == NULL) {
4843 error = got_error_from_errno("getcwd");
4844 goto done;
4846 if (repo_path == NULL) {
4847 error = got_worktree_open(&worktree, cwd);
4848 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4849 goto done;
4850 else
4851 error = NULL;
4852 if (worktree) {
4853 repo_path =
4854 strdup(got_worktree_get_repo_path(worktree));
4855 if (repo_path == NULL)
4856 error = got_error_from_errno("strdup");
4857 if (error)
4858 goto done;
4859 } else {
4860 repo_path = strdup(cwd);
4861 if (repo_path == NULL) {
4862 error = got_error_from_errno("strdup");
4863 goto done;
4868 error = got_repo_open(&repo, repo_path, NULL);
4869 if (error != NULL)
4870 goto done;
4872 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4873 if (error)
4874 goto done;
4876 if (path == NULL) {
4877 if (worktree) {
4878 char *p, *worktree_subdir = cwd +
4879 strlen(got_worktree_get_root_path(worktree));
4880 if (asprintf(&p, "%s/%s",
4881 got_worktree_get_path_prefix(worktree),
4882 worktree_subdir) == -1) {
4883 error = got_error_from_errno("asprintf");
4884 goto done;
4886 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4887 free(p);
4888 if (error)
4889 goto done;
4890 } else
4891 path = "/";
4893 if (in_repo_path == NULL) {
4894 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4895 if (error != NULL)
4896 goto done;
4899 if (commit_id_str == NULL) {
4900 struct got_reference *head_ref;
4901 if (worktree)
4902 refname = got_worktree_get_head_ref_name(worktree);
4903 else
4904 refname = GOT_REF_HEAD;
4905 error = got_ref_open(&head_ref, repo, refname, 0);
4906 if (error != NULL)
4907 goto done;
4908 error = got_ref_resolve(&commit_id, repo, head_ref);
4909 got_ref_close(head_ref);
4910 if (error != NULL)
4911 goto done;
4912 } else {
4913 error = got_repo_match_object_id(&commit_id, NULL,
4914 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4915 if (error)
4916 goto done;
4919 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4920 in_repo_path, repo);
4921 done:
4922 free(in_repo_path);
4923 free(repo_path);
4924 free(cwd);
4925 free(commit_id);
4926 if (worktree)
4927 got_worktree_close(worktree);
4928 if (repo) {
4929 const struct got_error *repo_error;
4930 repo_error = got_repo_close(repo);
4931 if (error == NULL)
4932 error = repo_error;
4934 return error;
4937 __dead static void
4938 usage_status(void)
4940 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4941 getprogname());
4942 exit(1);
4945 static const struct got_error *
4946 print_status(void *arg, unsigned char status, unsigned char staged_status,
4947 const char *path, struct got_object_id *blob_id,
4948 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4949 int dirfd, const char *de_name)
4951 if (status == staged_status && (status == GOT_STATUS_DELETE))
4952 status = GOT_STATUS_NO_CHANGE;
4953 if (arg) {
4954 char *status_codes = arg;
4955 size_t ncodes = strlen(status_codes);
4956 int i;
4957 for (i = 0; i < ncodes ; i++) {
4958 if (status == status_codes[i] ||
4959 staged_status == status_codes[i])
4960 break;
4962 if (i == ncodes)
4963 return NULL;
4965 printf("%c%c %s\n", status, staged_status, path);
4966 return NULL;
4969 static const struct got_error *
4970 cmd_status(int argc, char *argv[])
4972 const struct got_error *error = NULL;
4973 struct got_repository *repo = NULL;
4974 struct got_worktree *worktree = NULL;
4975 char *cwd = NULL, *status_codes = NULL;;
4976 struct got_pathlist_head paths;
4977 struct got_pathlist_entry *pe;
4978 int ch, i;
4980 TAILQ_INIT(&paths);
4982 while ((ch = getopt(argc, argv, "s:")) != -1) {
4983 switch (ch) {
4984 case 's':
4985 for (i = 0; i < strlen(optarg); i++) {
4986 switch (optarg[i]) {
4987 case GOT_STATUS_MODIFY:
4988 case GOT_STATUS_ADD:
4989 case GOT_STATUS_DELETE:
4990 case GOT_STATUS_CONFLICT:
4991 case GOT_STATUS_MISSING:
4992 case GOT_STATUS_OBSTRUCTED:
4993 case GOT_STATUS_UNVERSIONED:
4994 case GOT_STATUS_MODE_CHANGE:
4995 case GOT_STATUS_NONEXISTENT:
4996 break;
4997 default:
4998 errx(1, "invalid status code '%c'",
4999 optarg[i]);
5002 status_codes = optarg;
5003 break;
5004 default:
5005 usage_status();
5006 /* NOTREACHED */
5010 argc -= optind;
5011 argv += optind;
5013 #ifndef PROFILE
5014 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5015 NULL) == -1)
5016 err(1, "pledge");
5017 #endif
5018 cwd = getcwd(NULL, 0);
5019 if (cwd == NULL) {
5020 error = got_error_from_errno("getcwd");
5021 goto done;
5024 error = got_worktree_open(&worktree, cwd);
5025 if (error) {
5026 if (error->code == GOT_ERR_NOT_WORKTREE)
5027 error = wrap_not_worktree_error(error, "status", cwd);
5028 goto done;
5031 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5032 NULL);
5033 if (error != NULL)
5034 goto done;
5036 error = apply_unveil(got_repo_get_path(repo), 1,
5037 got_worktree_get_root_path(worktree));
5038 if (error)
5039 goto done;
5041 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5042 if (error)
5043 goto done;
5045 error = got_worktree_status(worktree, &paths, repo, print_status,
5046 status_codes, check_cancelled, NULL);
5047 done:
5048 TAILQ_FOREACH(pe, &paths, entry)
5049 free((char *)pe->path);
5050 got_pathlist_free(&paths);
5051 free(cwd);
5052 return error;
5055 __dead static void
5056 usage_ref(void)
5058 fprintf(stderr,
5059 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5060 "[-d] [name]\n",
5061 getprogname());
5062 exit(1);
5065 static const struct got_error *
5066 list_refs(struct got_repository *repo, const char *refname)
5068 static const struct got_error *err = NULL;
5069 struct got_reflist_head refs;
5070 struct got_reflist_entry *re;
5072 SIMPLEQ_INIT(&refs);
5073 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5074 if (err)
5075 return err;
5077 SIMPLEQ_FOREACH(re, &refs, entry) {
5078 char *refstr;
5079 refstr = got_ref_to_str(re->ref);
5080 if (refstr == NULL)
5081 return got_error_from_errno("got_ref_to_str");
5082 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5083 free(refstr);
5086 got_ref_list_free(&refs);
5087 return NULL;
5090 static const struct got_error *
5091 delete_ref(struct got_repository *repo, const char *refname)
5093 const struct got_error *err = NULL;
5094 struct got_reference *ref;
5096 err = got_ref_open(&ref, repo, refname, 0);
5097 if (err)
5098 return err;
5100 err = got_ref_delete(ref, repo);
5101 got_ref_close(ref);
5102 return err;
5105 static const struct got_error *
5106 add_ref(struct got_repository *repo, const char *refname, const char *target)
5108 const struct got_error *err = NULL;
5109 struct got_object_id *id;
5110 struct got_reference *ref = NULL;
5113 * Don't let the user create a reference name with a leading '-'.
5114 * While technically a valid reference name, this case is usually
5115 * an unintended typo.
5117 if (refname[0] == '-')
5118 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5120 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5121 repo);
5122 if (err) {
5123 struct got_reference *target_ref;
5125 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5126 return err;
5127 err = got_ref_open(&target_ref, repo, target, 0);
5128 if (err)
5129 return err;
5130 err = got_ref_resolve(&id, repo, target_ref);
5131 got_ref_close(target_ref);
5132 if (err)
5133 return err;
5136 err = got_ref_alloc(&ref, refname, id);
5137 if (err)
5138 goto done;
5140 err = got_ref_write(ref, repo);
5141 done:
5142 if (ref)
5143 got_ref_close(ref);
5144 free(id);
5145 return err;
5148 static const struct got_error *
5149 add_symref(struct got_repository *repo, const char *refname, const char *target)
5151 const struct got_error *err = NULL;
5152 struct got_reference *ref = NULL;
5153 struct got_reference *target_ref = NULL;
5156 * Don't let the user create a reference name with a leading '-'.
5157 * While technically a valid reference name, this case is usually
5158 * an unintended typo.
5160 if (refname[0] == '-')
5161 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5163 err = got_ref_open(&target_ref, repo, target, 0);
5164 if (err)
5165 return err;
5167 err = got_ref_alloc_symref(&ref, refname, target_ref);
5168 if (err)
5169 goto done;
5171 err = got_ref_write(ref, repo);
5172 done:
5173 if (target_ref)
5174 got_ref_close(target_ref);
5175 if (ref)
5176 got_ref_close(ref);
5177 return err;
5180 static const struct got_error *
5181 cmd_ref(int argc, char *argv[])
5183 const struct got_error *error = NULL;
5184 struct got_repository *repo = NULL;
5185 struct got_worktree *worktree = NULL;
5186 char *cwd = NULL, *repo_path = NULL;
5187 int ch, do_list = 0, do_delete = 0;
5188 const char *obj_arg = NULL, *symref_target= NULL;
5189 char *refname = NULL;
5191 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5192 switch (ch) {
5193 case 'c':
5194 obj_arg = optarg;
5195 break;
5196 case 'd':
5197 do_delete = 1;
5198 break;
5199 case 'r':
5200 repo_path = realpath(optarg, NULL);
5201 if (repo_path == NULL)
5202 return got_error_from_errno2("realpath",
5203 optarg);
5204 got_path_strip_trailing_slashes(repo_path);
5205 break;
5206 case 'l':
5207 do_list = 1;
5208 break;
5209 case 's':
5210 symref_target = optarg;
5211 break;
5212 default:
5213 usage_ref();
5214 /* NOTREACHED */
5218 if (obj_arg && do_list)
5219 errx(1, "-c and -l options are mutually exclusive");
5220 if (obj_arg && do_delete)
5221 errx(1, "-c and -d options are mutually exclusive");
5222 if (obj_arg && symref_target)
5223 errx(1, "-c and -s options are mutually exclusive");
5224 if (symref_target && do_delete)
5225 errx(1, "-s and -d options are mutually exclusive");
5226 if (symref_target && do_list)
5227 errx(1, "-s and -l options are mutually exclusive");
5228 if (do_delete && do_list)
5229 errx(1, "-d and -l options are mutually exclusive");
5231 argc -= optind;
5232 argv += optind;
5234 if (do_list) {
5235 if (argc != 0 && argc != 1)
5236 usage_ref();
5237 if (argc == 1) {
5238 refname = strdup(argv[0]);
5239 if (refname == NULL) {
5240 error = got_error_from_errno("strdup");
5241 goto done;
5244 } else {
5245 if (argc != 1)
5246 usage_ref();
5247 refname = strdup(argv[0]);
5248 if (refname == NULL) {
5249 error = got_error_from_errno("strdup");
5250 goto done;
5254 if (refname)
5255 got_path_strip_trailing_slashes(refname);
5257 #ifndef PROFILE
5258 if (do_list) {
5259 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5260 NULL) == -1)
5261 err(1, "pledge");
5262 } else {
5263 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5264 "sendfd unveil", NULL) == -1)
5265 err(1, "pledge");
5267 #endif
5268 cwd = getcwd(NULL, 0);
5269 if (cwd == NULL) {
5270 error = got_error_from_errno("getcwd");
5271 goto done;
5274 if (repo_path == NULL) {
5275 error = got_worktree_open(&worktree, cwd);
5276 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5277 goto done;
5278 else
5279 error = NULL;
5280 if (worktree) {
5281 repo_path =
5282 strdup(got_worktree_get_repo_path(worktree));
5283 if (repo_path == NULL)
5284 error = got_error_from_errno("strdup");
5285 if (error)
5286 goto done;
5287 } else {
5288 repo_path = strdup(cwd);
5289 if (repo_path == NULL) {
5290 error = got_error_from_errno("strdup");
5291 goto done;
5296 error = got_repo_open(&repo, repo_path, NULL);
5297 if (error != NULL)
5298 goto done;
5300 error = apply_unveil(got_repo_get_path(repo), do_list,
5301 worktree ? got_worktree_get_root_path(worktree) : NULL);
5302 if (error)
5303 goto done;
5305 if (do_list)
5306 error = list_refs(repo, refname);
5307 else if (do_delete)
5308 error = delete_ref(repo, refname);
5309 else if (symref_target)
5310 error = add_symref(repo, refname, symref_target);
5311 else {
5312 if (obj_arg == NULL)
5313 usage_ref();
5314 error = add_ref(repo, refname, obj_arg);
5316 done:
5317 free(refname);
5318 if (repo)
5319 got_repo_close(repo);
5320 if (worktree)
5321 got_worktree_close(worktree);
5322 free(cwd);
5323 free(repo_path);
5324 return error;
5327 __dead static void
5328 usage_branch(void)
5330 fprintf(stderr,
5331 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5332 "[name]\n", getprogname());
5333 exit(1);
5336 static const struct got_error *
5337 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5338 struct got_reference *ref)
5340 const struct got_error *err = NULL;
5341 const char *refname, *marker = " ";
5342 char *refstr;
5344 refname = got_ref_get_name(ref);
5345 if (worktree && strcmp(refname,
5346 got_worktree_get_head_ref_name(worktree)) == 0) {
5347 struct got_object_id *id = NULL;
5349 err = got_ref_resolve(&id, repo, ref);
5350 if (err)
5351 return err;
5352 if (got_object_id_cmp(id,
5353 got_worktree_get_base_commit_id(worktree)) == 0)
5354 marker = "* ";
5355 else
5356 marker = "~ ";
5357 free(id);
5360 if (strncmp(refname, "refs/heads/", 11) == 0)
5361 refname += 11;
5362 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5363 refname += 18;
5365 refstr = got_ref_to_str(ref);
5366 if (refstr == NULL)
5367 return got_error_from_errno("got_ref_to_str");
5369 printf("%s%s: %s\n", marker, refname, refstr);
5370 free(refstr);
5371 return NULL;
5374 static const struct got_error *
5375 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5377 const char *refname;
5379 if (worktree == NULL)
5380 return got_error(GOT_ERR_NOT_WORKTREE);
5382 refname = got_worktree_get_head_ref_name(worktree);
5384 if (strncmp(refname, "refs/heads/", 11) == 0)
5385 refname += 11;
5386 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5387 refname += 18;
5389 printf("%s\n", refname);
5391 return NULL;
5394 static const struct got_error *
5395 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5397 static const struct got_error *err = NULL;
5398 struct got_reflist_head refs;
5399 struct got_reflist_entry *re;
5400 struct got_reference *temp_ref = NULL;
5401 int rebase_in_progress, histedit_in_progress;
5403 SIMPLEQ_INIT(&refs);
5405 if (worktree) {
5406 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5407 worktree);
5408 if (err)
5409 return err;
5411 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5412 worktree);
5413 if (err)
5414 return err;
5416 if (rebase_in_progress || histedit_in_progress) {
5417 err = got_ref_open(&temp_ref, repo,
5418 got_worktree_get_head_ref_name(worktree), 0);
5419 if (err)
5420 return err;
5421 list_branch(repo, worktree, temp_ref);
5422 got_ref_close(temp_ref);
5426 err = got_ref_list(&refs, repo, "refs/heads",
5427 got_ref_cmp_by_name, NULL);
5428 if (err)
5429 return err;
5431 SIMPLEQ_FOREACH(re, &refs, entry)
5432 list_branch(repo, worktree, re->ref);
5434 got_ref_list_free(&refs);
5435 return NULL;
5438 static const struct got_error *
5439 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5440 const char *branch_name)
5442 const struct got_error *err = NULL;
5443 struct got_reference *ref = NULL;
5444 char *refname;
5446 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5447 return got_error_from_errno("asprintf");
5449 err = got_ref_open(&ref, repo, refname, 0);
5450 if (err)
5451 goto done;
5453 if (worktree &&
5454 strcmp(got_worktree_get_head_ref_name(worktree),
5455 got_ref_get_name(ref)) == 0) {
5456 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5457 "will not delete this work tree's current branch");
5458 goto done;
5461 err = got_ref_delete(ref, repo);
5462 done:
5463 if (ref)
5464 got_ref_close(ref);
5465 free(refname);
5466 return err;
5469 static const struct got_error *
5470 add_branch(struct got_repository *repo, const char *branch_name,
5471 struct got_object_id *base_commit_id)
5473 const struct got_error *err = NULL;
5474 struct got_reference *ref = NULL;
5475 char *base_refname = NULL, *refname = NULL;
5478 * Don't let the user create a branch name with a leading '-'.
5479 * While technically a valid reference name, this case is usually
5480 * an unintended typo.
5482 if (branch_name[0] == '-')
5483 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5485 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5486 err = got_error_from_errno("asprintf");
5487 goto done;
5490 err = got_ref_open(&ref, repo, refname, 0);
5491 if (err == NULL) {
5492 err = got_error(GOT_ERR_BRANCH_EXISTS);
5493 goto done;
5494 } else if (err->code != GOT_ERR_NOT_REF)
5495 goto done;
5497 err = got_ref_alloc(&ref, refname, base_commit_id);
5498 if (err)
5499 goto done;
5501 err = got_ref_write(ref, repo);
5502 done:
5503 if (ref)
5504 got_ref_close(ref);
5505 free(base_refname);
5506 free(refname);
5507 return err;
5510 static const struct got_error *
5511 cmd_branch(int argc, char *argv[])
5513 const struct got_error *error = NULL;
5514 struct got_repository *repo = NULL;
5515 struct got_worktree *worktree = NULL;
5516 char *cwd = NULL, *repo_path = NULL;
5517 int ch, do_list = 0, do_show = 0, do_update = 1;
5518 const char *delref = NULL, *commit_id_arg = NULL;
5519 struct got_reference *ref = NULL;
5520 struct got_pathlist_head paths;
5521 struct got_pathlist_entry *pe;
5522 struct got_object_id *commit_id = NULL;
5523 char *commit_id_str = NULL;
5525 TAILQ_INIT(&paths);
5527 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5528 switch (ch) {
5529 case 'c':
5530 commit_id_arg = optarg;
5531 break;
5532 case 'd':
5533 delref = optarg;
5534 break;
5535 case 'r':
5536 repo_path = realpath(optarg, NULL);
5537 if (repo_path == NULL)
5538 return got_error_from_errno2("realpath",
5539 optarg);
5540 got_path_strip_trailing_slashes(repo_path);
5541 break;
5542 case 'l':
5543 do_list = 1;
5544 break;
5545 case 'n':
5546 do_update = 0;
5547 break;
5548 default:
5549 usage_branch();
5550 /* NOTREACHED */
5554 if (do_list && delref)
5555 errx(1, "-l and -d options are mutually exclusive");
5557 argc -= optind;
5558 argv += optind;
5560 if (!do_list && !delref && argc == 0)
5561 do_show = 1;
5563 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5564 errx(1, "-c option can only be used when creating a branch");
5566 if (do_list || delref) {
5567 if (argc > 0)
5568 usage_branch();
5569 } else if (!do_show && argc != 1)
5570 usage_branch();
5572 #ifndef PROFILE
5573 if (do_list || do_show) {
5574 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5575 NULL) == -1)
5576 err(1, "pledge");
5577 } else {
5578 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5579 "sendfd unveil", NULL) == -1)
5580 err(1, "pledge");
5582 #endif
5583 cwd = getcwd(NULL, 0);
5584 if (cwd == NULL) {
5585 error = got_error_from_errno("getcwd");
5586 goto done;
5589 if (repo_path == NULL) {
5590 error = got_worktree_open(&worktree, cwd);
5591 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5592 goto done;
5593 else
5594 error = NULL;
5595 if (worktree) {
5596 repo_path =
5597 strdup(got_worktree_get_repo_path(worktree));
5598 if (repo_path == NULL)
5599 error = got_error_from_errno("strdup");
5600 if (error)
5601 goto done;
5602 } else {
5603 repo_path = strdup(cwd);
5604 if (repo_path == NULL) {
5605 error = got_error_from_errno("strdup");
5606 goto done;
5611 error = got_repo_open(&repo, repo_path, NULL);
5612 if (error != NULL)
5613 goto done;
5615 error = apply_unveil(got_repo_get_path(repo), do_list,
5616 worktree ? got_worktree_get_root_path(worktree) : NULL);
5617 if (error)
5618 goto done;
5620 if (do_show)
5621 error = show_current_branch(repo, worktree);
5622 else if (do_list)
5623 error = list_branches(repo, worktree);
5624 else if (delref)
5625 error = delete_branch(repo, worktree, delref);
5626 else {
5627 if (commit_id_arg == NULL)
5628 commit_id_arg = worktree ?
5629 got_worktree_get_head_ref_name(worktree) :
5630 GOT_REF_HEAD;
5631 error = got_repo_match_object_id(&commit_id, NULL,
5632 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5633 if (error)
5634 goto done;
5635 error = add_branch(repo, argv[0], commit_id);
5636 if (error)
5637 goto done;
5638 if (worktree && do_update) {
5639 struct got_update_progress_arg upa;
5640 char *branch_refname = NULL;
5642 error = got_object_id_str(&commit_id_str, commit_id);
5643 if (error)
5644 goto done;
5645 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5646 worktree);
5647 if (error)
5648 goto done;
5649 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5650 == -1) {
5651 error = got_error_from_errno("asprintf");
5652 goto done;
5654 error = got_ref_open(&ref, repo, branch_refname, 0);
5655 free(branch_refname);
5656 if (error)
5657 goto done;
5658 error = switch_head_ref(ref, commit_id, worktree,
5659 repo);
5660 if (error)
5661 goto done;
5662 error = got_worktree_set_base_commit_id(worktree, repo,
5663 commit_id);
5664 if (error)
5665 goto done;
5666 memset(&upa, 0, sizeof(upa));
5667 error = got_worktree_checkout_files(worktree, &paths,
5668 repo, update_progress, &upa, check_cancelled,
5669 NULL);
5670 if (error)
5671 goto done;
5672 if (upa.did_something)
5673 printf("Updated to commit %s\n", commit_id_str);
5674 print_update_progress_stats(&upa);
5677 done:
5678 if (ref)
5679 got_ref_close(ref);
5680 if (repo)
5681 got_repo_close(repo);
5682 if (worktree)
5683 got_worktree_close(worktree);
5684 free(cwd);
5685 free(repo_path);
5686 free(commit_id);
5687 free(commit_id_str);
5688 TAILQ_FOREACH(pe, &paths, entry)
5689 free((char *)pe->path);
5690 got_pathlist_free(&paths);
5691 return error;
5695 __dead static void
5696 usage_tag(void)
5698 fprintf(stderr,
5699 "usage: %s tag [-c commit] [-r repository] [-l] "
5700 "[-m message] name\n", getprogname());
5701 exit(1);
5704 #if 0
5705 static const struct got_error *
5706 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5708 const struct got_error *err = NULL;
5709 struct got_reflist_entry *re, *se, *new;
5710 struct got_object_id *re_id, *se_id;
5711 struct got_tag_object *re_tag, *se_tag;
5712 time_t re_time, se_time;
5714 SIMPLEQ_FOREACH(re, tags, entry) {
5715 se = SIMPLEQ_FIRST(sorted);
5716 if (se == NULL) {
5717 err = got_reflist_entry_dup(&new, re);
5718 if (err)
5719 return err;
5720 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5721 continue;
5722 } else {
5723 err = got_ref_resolve(&re_id, repo, re->ref);
5724 if (err)
5725 break;
5726 err = got_object_open_as_tag(&re_tag, repo, re_id);
5727 free(re_id);
5728 if (err)
5729 break;
5730 re_time = got_object_tag_get_tagger_time(re_tag);
5731 got_object_tag_close(re_tag);
5734 while (se) {
5735 err = got_ref_resolve(&se_id, repo, re->ref);
5736 if (err)
5737 break;
5738 err = got_object_open_as_tag(&se_tag, repo, se_id);
5739 free(se_id);
5740 if (err)
5741 break;
5742 se_time = got_object_tag_get_tagger_time(se_tag);
5743 got_object_tag_close(se_tag);
5745 if (se_time > re_time) {
5746 err = got_reflist_entry_dup(&new, re);
5747 if (err)
5748 return err;
5749 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5750 break;
5752 se = SIMPLEQ_NEXT(se, entry);
5753 continue;
5756 done:
5757 return err;
5759 #endif
5761 static const struct got_error *
5762 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5764 static const struct got_error *err = NULL;
5765 struct got_reflist_head refs;
5766 struct got_reflist_entry *re;
5768 SIMPLEQ_INIT(&refs);
5770 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5771 if (err)
5772 return err;
5774 SIMPLEQ_FOREACH(re, &refs, entry) {
5775 const char *refname;
5776 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5777 char datebuf[26];
5778 const char *tagger;
5779 time_t tagger_time;
5780 struct got_object_id *id;
5781 struct got_tag_object *tag;
5782 struct got_commit_object *commit = NULL;
5784 refname = got_ref_get_name(re->ref);
5785 if (strncmp(refname, "refs/tags/", 10) != 0)
5786 continue;
5787 refname += 10;
5788 refstr = got_ref_to_str(re->ref);
5789 if (refstr == NULL) {
5790 err = got_error_from_errno("got_ref_to_str");
5791 break;
5793 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5794 free(refstr);
5796 err = got_ref_resolve(&id, repo, re->ref);
5797 if (err)
5798 break;
5799 err = got_object_open_as_tag(&tag, repo, id);
5800 if (err) {
5801 if (err->code != GOT_ERR_OBJ_TYPE) {
5802 free(id);
5803 break;
5805 /* "lightweight" tag */
5806 err = got_object_open_as_commit(&commit, repo, id);
5807 if (err) {
5808 free(id);
5809 break;
5811 tagger = got_object_commit_get_committer(commit);
5812 tagger_time =
5813 got_object_commit_get_committer_time(commit);
5814 err = got_object_id_str(&id_str, id);
5815 free(id);
5816 if (err)
5817 break;
5818 } else {
5819 free(id);
5820 tagger = got_object_tag_get_tagger(tag);
5821 tagger_time = got_object_tag_get_tagger_time(tag);
5822 err = got_object_id_str(&id_str,
5823 got_object_tag_get_object_id(tag));
5824 if (err)
5825 break;
5827 printf("from: %s\n", tagger);
5828 datestr = get_datestr(&tagger_time, datebuf);
5829 if (datestr)
5830 printf("date: %s UTC\n", datestr);
5831 if (commit)
5832 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5833 else {
5834 switch (got_object_tag_get_object_type(tag)) {
5835 case GOT_OBJ_TYPE_BLOB:
5836 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5837 id_str);
5838 break;
5839 case GOT_OBJ_TYPE_TREE:
5840 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5841 id_str);
5842 break;
5843 case GOT_OBJ_TYPE_COMMIT:
5844 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5845 id_str);
5846 break;
5847 case GOT_OBJ_TYPE_TAG:
5848 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5849 id_str);
5850 break;
5851 default:
5852 break;
5855 free(id_str);
5856 if (commit) {
5857 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5858 if (err)
5859 break;
5860 got_object_commit_close(commit);
5861 } else {
5862 tagmsg0 = strdup(got_object_tag_get_message(tag));
5863 got_object_tag_close(tag);
5864 if (tagmsg0 == NULL) {
5865 err = got_error_from_errno("strdup");
5866 break;
5870 tagmsg = tagmsg0;
5871 do {
5872 line = strsep(&tagmsg, "\n");
5873 if (line)
5874 printf(" %s\n", line);
5875 } while (line);
5876 free(tagmsg0);
5879 got_ref_list_free(&refs);
5880 return NULL;
5883 static const struct got_error *
5884 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5885 const char *tag_name, const char *repo_path)
5887 const struct got_error *err = NULL;
5888 char *template = NULL, *initial_content = NULL;
5889 char *editor = NULL;
5890 int initial_content_len;
5891 int fd = -1;
5893 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5894 err = got_error_from_errno("asprintf");
5895 goto done;
5898 initial_content_len = asprintf(&initial_content,
5899 "\n# tagging commit %s as %s\n",
5900 commit_id_str, tag_name);
5901 if (initial_content_len == -1) {
5902 err = got_error_from_errno("asprintf");
5903 goto done;
5906 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5907 if (err)
5908 goto done;
5910 if (write(fd, initial_content, initial_content_len) == -1) {
5911 err = got_error_from_errno2("write", *tagmsg_path);
5912 goto done;
5915 err = get_editor(&editor);
5916 if (err)
5917 goto done;
5918 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5919 initial_content_len);
5920 done:
5921 free(initial_content);
5922 free(template);
5923 free(editor);
5925 if (fd != -1 && close(fd) == -1 && err == NULL)
5926 err = got_error_from_errno2("close", *tagmsg_path);
5928 /* Editor is done; we can now apply unveil(2) */
5929 if (err == NULL)
5930 err = apply_unveil(repo_path, 0, NULL);
5931 if (err) {
5932 free(*tagmsg);
5933 *tagmsg = NULL;
5935 return err;
5938 static const struct got_error *
5939 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5940 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5942 const struct got_error *err = NULL;
5943 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5944 char *label = NULL, *commit_id_str = NULL;
5945 struct got_reference *ref = NULL;
5946 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5947 char *tagmsg_path = NULL, *tag_id_str = NULL;
5948 int preserve_tagmsg = 0;
5951 * Don't let the user create a tag name with a leading '-'.
5952 * While technically a valid reference name, this case is usually
5953 * an unintended typo.
5955 if (tag_name[0] == '-')
5956 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5958 err = get_author(&tagger, repo, worktree);
5959 if (err)
5960 return err;
5962 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5963 GOT_OBJ_TYPE_COMMIT, 1, repo);
5964 if (err)
5965 goto done;
5967 err = got_object_id_str(&commit_id_str, commit_id);
5968 if (err)
5969 goto done;
5971 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5972 refname = strdup(tag_name);
5973 if (refname == NULL) {
5974 err = got_error_from_errno("strdup");
5975 goto done;
5977 tag_name += 10;
5978 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5979 err = got_error_from_errno("asprintf");
5980 goto done;
5983 err = got_ref_open(&ref, repo, refname, 0);
5984 if (err == NULL) {
5985 err = got_error(GOT_ERR_TAG_EXISTS);
5986 goto done;
5987 } else if (err->code != GOT_ERR_NOT_REF)
5988 goto done;
5990 if (tagmsg_arg == NULL) {
5991 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5992 tag_name, got_repo_get_path(repo));
5993 if (err) {
5994 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5995 tagmsg_path != NULL)
5996 preserve_tagmsg = 1;
5997 goto done;
6001 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6002 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6003 if (err) {
6004 if (tagmsg_path)
6005 preserve_tagmsg = 1;
6006 goto done;
6009 err = got_ref_alloc(&ref, refname, tag_id);
6010 if (err) {
6011 if (tagmsg_path)
6012 preserve_tagmsg = 1;
6013 goto done;
6016 err = got_ref_write(ref, repo);
6017 if (err) {
6018 if (tagmsg_path)
6019 preserve_tagmsg = 1;
6020 goto done;
6023 err = got_object_id_str(&tag_id_str, tag_id);
6024 if (err) {
6025 if (tagmsg_path)
6026 preserve_tagmsg = 1;
6027 goto done;
6029 printf("Created tag %s\n", tag_id_str);
6030 done:
6031 if (preserve_tagmsg) {
6032 fprintf(stderr, "%s: tag message preserved in %s\n",
6033 getprogname(), tagmsg_path);
6034 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6035 err = got_error_from_errno2("unlink", tagmsg_path);
6036 free(tag_id_str);
6037 if (ref)
6038 got_ref_close(ref);
6039 free(commit_id);
6040 free(commit_id_str);
6041 free(refname);
6042 free(tagmsg);
6043 free(tagmsg_path);
6044 free(tagger);
6045 return err;
6048 static const struct got_error *
6049 cmd_tag(int argc, char *argv[])
6051 const struct got_error *error = NULL;
6052 struct got_repository *repo = NULL;
6053 struct got_worktree *worktree = NULL;
6054 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6055 char *gitconfig_path = NULL;
6056 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6057 int ch, do_list = 0;
6059 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6060 switch (ch) {
6061 case 'c':
6062 commit_id_arg = optarg;
6063 break;
6064 case 'm':
6065 tagmsg = optarg;
6066 break;
6067 case 'r':
6068 repo_path = realpath(optarg, NULL);
6069 if (repo_path == NULL)
6070 return got_error_from_errno2("realpath",
6071 optarg);
6072 got_path_strip_trailing_slashes(repo_path);
6073 break;
6074 case 'l':
6075 do_list = 1;
6076 break;
6077 default:
6078 usage_tag();
6079 /* NOTREACHED */
6083 argc -= optind;
6084 argv += optind;
6086 if (do_list) {
6087 if (commit_id_arg != NULL)
6088 errx(1,
6089 "-c option can only be used when creating a tag");
6090 if (tagmsg)
6091 errx(1, "-l and -m options are mutually exclusive");
6092 if (argc > 0)
6093 usage_tag();
6094 } else if (argc != 1)
6095 usage_tag();
6097 tag_name = argv[0];
6099 #ifndef PROFILE
6100 if (do_list) {
6101 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6102 NULL) == -1)
6103 err(1, "pledge");
6104 } else {
6105 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6106 "sendfd unveil", NULL) == -1)
6107 err(1, "pledge");
6109 #endif
6110 cwd = getcwd(NULL, 0);
6111 if (cwd == NULL) {
6112 error = got_error_from_errno("getcwd");
6113 goto done;
6116 if (repo_path == NULL) {
6117 error = got_worktree_open(&worktree, cwd);
6118 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6119 goto done;
6120 else
6121 error = NULL;
6122 if (worktree) {
6123 repo_path =
6124 strdup(got_worktree_get_repo_path(worktree));
6125 if (repo_path == NULL)
6126 error = got_error_from_errno("strdup");
6127 if (error)
6128 goto done;
6129 } else {
6130 repo_path = strdup(cwd);
6131 if (repo_path == NULL) {
6132 error = got_error_from_errno("strdup");
6133 goto done;
6138 if (do_list) {
6139 error = got_repo_open(&repo, repo_path, NULL);
6140 if (error != NULL)
6141 goto done;
6142 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6143 if (error)
6144 goto done;
6145 error = list_tags(repo, worktree);
6146 } else {
6147 error = get_gitconfig_path(&gitconfig_path);
6148 if (error)
6149 goto done;
6150 error = got_repo_open(&repo, repo_path, gitconfig_path);
6151 if (error != NULL)
6152 goto done;
6154 if (tagmsg) {
6155 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6156 if (error)
6157 goto done;
6160 if (commit_id_arg == NULL) {
6161 struct got_reference *head_ref;
6162 struct got_object_id *commit_id;
6163 error = got_ref_open(&head_ref, repo,
6164 worktree ? got_worktree_get_head_ref_name(worktree)
6165 : GOT_REF_HEAD, 0);
6166 if (error)
6167 goto done;
6168 error = got_ref_resolve(&commit_id, repo, head_ref);
6169 got_ref_close(head_ref);
6170 if (error)
6171 goto done;
6172 error = got_object_id_str(&commit_id_str, commit_id);
6173 free(commit_id);
6174 if (error)
6175 goto done;
6178 error = add_tag(repo, worktree, tag_name,
6179 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6181 done:
6182 if (repo)
6183 got_repo_close(repo);
6184 if (worktree)
6185 got_worktree_close(worktree);
6186 free(cwd);
6187 free(repo_path);
6188 free(gitconfig_path);
6189 free(commit_id_str);
6190 return error;
6193 __dead static void
6194 usage_add(void)
6196 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6197 getprogname());
6198 exit(1);
6201 static const struct got_error *
6202 add_progress(void *arg, unsigned char status, const char *path)
6204 while (path[0] == '/')
6205 path++;
6206 printf("%c %s\n", status, path);
6207 return NULL;
6210 static const struct got_error *
6211 cmd_add(int argc, char *argv[])
6213 const struct got_error *error = NULL;
6214 struct got_repository *repo = NULL;
6215 struct got_worktree *worktree = NULL;
6216 char *cwd = NULL;
6217 struct got_pathlist_head paths;
6218 struct got_pathlist_entry *pe;
6219 int ch, can_recurse = 0, no_ignores = 0;
6221 TAILQ_INIT(&paths);
6223 while ((ch = getopt(argc, argv, "IR")) != -1) {
6224 switch (ch) {
6225 case 'I':
6226 no_ignores = 1;
6227 break;
6228 case 'R':
6229 can_recurse = 1;
6230 break;
6231 default:
6232 usage_add();
6233 /* NOTREACHED */
6237 argc -= optind;
6238 argv += optind;
6240 #ifndef PROFILE
6241 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6242 NULL) == -1)
6243 err(1, "pledge");
6244 #endif
6245 if (argc < 1)
6246 usage_add();
6248 cwd = getcwd(NULL, 0);
6249 if (cwd == NULL) {
6250 error = got_error_from_errno("getcwd");
6251 goto done;
6254 error = got_worktree_open(&worktree, cwd);
6255 if (error) {
6256 if (error->code == GOT_ERR_NOT_WORKTREE)
6257 error = wrap_not_worktree_error(error, "add", cwd);
6258 goto done;
6261 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6262 NULL);
6263 if (error != NULL)
6264 goto done;
6266 error = apply_unveil(got_repo_get_path(repo), 1,
6267 got_worktree_get_root_path(worktree));
6268 if (error)
6269 goto done;
6271 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6272 if (error)
6273 goto done;
6275 if (!can_recurse && no_ignores) {
6276 error = got_error_msg(GOT_ERR_BAD_PATH,
6277 "disregarding ignores requires -R option");
6278 goto done;
6282 if (!can_recurse) {
6283 char *ondisk_path;
6284 struct stat sb;
6285 TAILQ_FOREACH(pe, &paths, entry) {
6286 if (asprintf(&ondisk_path, "%s/%s",
6287 got_worktree_get_root_path(worktree),
6288 pe->path) == -1) {
6289 error = got_error_from_errno("asprintf");
6290 goto done;
6292 if (lstat(ondisk_path, &sb) == -1) {
6293 if (errno == ENOENT) {
6294 free(ondisk_path);
6295 continue;
6297 error = got_error_from_errno2("lstat",
6298 ondisk_path);
6299 free(ondisk_path);
6300 goto done;
6302 free(ondisk_path);
6303 if (S_ISDIR(sb.st_mode)) {
6304 error = got_error_msg(GOT_ERR_BAD_PATH,
6305 "adding directories requires -R option");
6306 goto done;
6311 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6312 NULL, repo, no_ignores);
6313 done:
6314 if (repo)
6315 got_repo_close(repo);
6316 if (worktree)
6317 got_worktree_close(worktree);
6318 TAILQ_FOREACH(pe, &paths, entry)
6319 free((char *)pe->path);
6320 got_pathlist_free(&paths);
6321 free(cwd);
6322 return error;
6325 __dead static void
6326 usage_remove(void)
6328 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6329 "path ...\n", getprogname());
6330 exit(1);
6333 static const struct got_error *
6334 print_remove_status(void *arg, unsigned char status,
6335 unsigned char staged_status, const char *path)
6337 while (path[0] == '/')
6338 path++;
6339 if (status == GOT_STATUS_NONEXISTENT)
6340 return NULL;
6341 if (status == staged_status && (status == GOT_STATUS_DELETE))
6342 status = GOT_STATUS_NO_CHANGE;
6343 printf("%c%c %s\n", status, staged_status, path);
6344 return NULL;
6347 static const struct got_error *
6348 cmd_remove(int argc, char *argv[])
6350 const struct got_error *error = NULL;
6351 struct got_worktree *worktree = NULL;
6352 struct got_repository *repo = NULL;
6353 const char *status_codes = NULL;
6354 char *cwd = NULL;
6355 struct got_pathlist_head paths;
6356 struct got_pathlist_entry *pe;
6357 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6359 TAILQ_INIT(&paths);
6361 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6362 switch (ch) {
6363 case 'f':
6364 delete_local_mods = 1;
6365 break;
6366 case 'k':
6367 keep_on_disk = 1;
6368 break;
6369 case 'R':
6370 can_recurse = 1;
6371 break;
6372 case 's':
6373 for (i = 0; i < strlen(optarg); i++) {
6374 switch (optarg[i]) {
6375 case GOT_STATUS_MODIFY:
6376 delete_local_mods = 1;
6377 break;
6378 case GOT_STATUS_MISSING:
6379 break;
6380 default:
6381 errx(1, "invalid status code '%c'",
6382 optarg[i]);
6385 status_codes = optarg;
6386 break;
6387 default:
6388 usage_remove();
6389 /* NOTREACHED */
6393 argc -= optind;
6394 argv += optind;
6396 #ifndef PROFILE
6397 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6398 NULL) == -1)
6399 err(1, "pledge");
6400 #endif
6401 if (argc < 1)
6402 usage_remove();
6404 cwd = getcwd(NULL, 0);
6405 if (cwd == NULL) {
6406 error = got_error_from_errno("getcwd");
6407 goto done;
6409 error = got_worktree_open(&worktree, cwd);
6410 if (error) {
6411 if (error->code == GOT_ERR_NOT_WORKTREE)
6412 error = wrap_not_worktree_error(error, "remove", cwd);
6413 goto done;
6416 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6417 NULL);
6418 if (error)
6419 goto done;
6421 error = apply_unveil(got_repo_get_path(repo), 1,
6422 got_worktree_get_root_path(worktree));
6423 if (error)
6424 goto done;
6426 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6427 if (error)
6428 goto done;
6430 if (!can_recurse) {
6431 char *ondisk_path;
6432 struct stat sb;
6433 TAILQ_FOREACH(pe, &paths, entry) {
6434 if (asprintf(&ondisk_path, "%s/%s",
6435 got_worktree_get_root_path(worktree),
6436 pe->path) == -1) {
6437 error = got_error_from_errno("asprintf");
6438 goto done;
6440 if (lstat(ondisk_path, &sb) == -1) {
6441 if (errno == ENOENT) {
6442 free(ondisk_path);
6443 continue;
6445 error = got_error_from_errno2("lstat",
6446 ondisk_path);
6447 free(ondisk_path);
6448 goto done;
6450 free(ondisk_path);
6451 if (S_ISDIR(sb.st_mode)) {
6452 error = got_error_msg(GOT_ERR_BAD_PATH,
6453 "removing directories requires -R option");
6454 goto done;
6459 error = got_worktree_schedule_delete(worktree, &paths,
6460 delete_local_mods, status_codes, print_remove_status, NULL,
6461 repo, keep_on_disk);
6462 done:
6463 if (repo)
6464 got_repo_close(repo);
6465 if (worktree)
6466 got_worktree_close(worktree);
6467 TAILQ_FOREACH(pe, &paths, entry)
6468 free((char *)pe->path);
6469 got_pathlist_free(&paths);
6470 free(cwd);
6471 return error;
6474 __dead static void
6475 usage_revert(void)
6477 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6478 "path ...\n", getprogname());
6479 exit(1);
6482 static const struct got_error *
6483 revert_progress(void *arg, unsigned char status, const char *path)
6485 if (status == GOT_STATUS_UNVERSIONED)
6486 return NULL;
6488 while (path[0] == '/')
6489 path++;
6490 printf("%c %s\n", status, path);
6491 return NULL;
6494 struct choose_patch_arg {
6495 FILE *patch_script_file;
6496 const char *action;
6499 static const struct got_error *
6500 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6501 int nchanges, const char *action)
6503 char *line = NULL;
6504 size_t linesize = 0;
6505 ssize_t linelen;
6507 switch (status) {
6508 case GOT_STATUS_ADD:
6509 printf("A %s\n%s this addition? [y/n] ", path, action);
6510 break;
6511 case GOT_STATUS_DELETE:
6512 printf("D %s\n%s this deletion? [y/n] ", path, action);
6513 break;
6514 case GOT_STATUS_MODIFY:
6515 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6516 return got_error_from_errno("fseek");
6517 printf(GOT_COMMIT_SEP_STR);
6518 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6519 printf("%s", line);
6520 if (ferror(patch_file))
6521 return got_error_from_errno("getline");
6522 printf(GOT_COMMIT_SEP_STR);
6523 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6524 path, n, nchanges, action);
6525 break;
6526 default:
6527 return got_error_path(path, GOT_ERR_FILE_STATUS);
6530 return NULL;
6533 static const struct got_error *
6534 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6535 FILE *patch_file, int n, int nchanges)
6537 const struct got_error *err = NULL;
6538 char *line = NULL;
6539 size_t linesize = 0;
6540 ssize_t linelen;
6541 int resp = ' ';
6542 struct choose_patch_arg *a = arg;
6544 *choice = GOT_PATCH_CHOICE_NONE;
6546 if (a->patch_script_file) {
6547 char *nl;
6548 err = show_change(status, path, patch_file, n, nchanges,
6549 a->action);
6550 if (err)
6551 return err;
6552 linelen = getline(&line, &linesize, a->patch_script_file);
6553 if (linelen == -1) {
6554 if (ferror(a->patch_script_file))
6555 return got_error_from_errno("getline");
6556 return NULL;
6558 nl = strchr(line, '\n');
6559 if (nl)
6560 *nl = '\0';
6561 if (strcmp(line, "y") == 0) {
6562 *choice = GOT_PATCH_CHOICE_YES;
6563 printf("y\n");
6564 } else if (strcmp(line, "n") == 0) {
6565 *choice = GOT_PATCH_CHOICE_NO;
6566 printf("n\n");
6567 } else if (strcmp(line, "q") == 0 &&
6568 status == GOT_STATUS_MODIFY) {
6569 *choice = GOT_PATCH_CHOICE_QUIT;
6570 printf("q\n");
6571 } else
6572 printf("invalid response '%s'\n", line);
6573 free(line);
6574 return NULL;
6577 while (resp != 'y' && resp != 'n' && resp != 'q') {
6578 err = show_change(status, path, patch_file, n, nchanges,
6579 a->action);
6580 if (err)
6581 return err;
6582 resp = getchar();
6583 if (resp == '\n')
6584 resp = getchar();
6585 if (status == GOT_STATUS_MODIFY) {
6586 if (resp != 'y' && resp != 'n' && resp != 'q') {
6587 printf("invalid response '%c'\n", resp);
6588 resp = ' ';
6590 } else if (resp != 'y' && resp != 'n') {
6591 printf("invalid response '%c'\n", resp);
6592 resp = ' ';
6596 if (resp == 'y')
6597 *choice = GOT_PATCH_CHOICE_YES;
6598 else if (resp == 'n')
6599 *choice = GOT_PATCH_CHOICE_NO;
6600 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6601 *choice = GOT_PATCH_CHOICE_QUIT;
6603 return NULL;
6607 static const struct got_error *
6608 cmd_revert(int argc, char *argv[])
6610 const struct got_error *error = NULL;
6611 struct got_worktree *worktree = NULL;
6612 struct got_repository *repo = NULL;
6613 char *cwd = NULL, *path = NULL;
6614 struct got_pathlist_head paths;
6615 struct got_pathlist_entry *pe;
6616 int ch, can_recurse = 0, pflag = 0;
6617 FILE *patch_script_file = NULL;
6618 const char *patch_script_path = NULL;
6619 struct choose_patch_arg cpa;
6621 TAILQ_INIT(&paths);
6623 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6624 switch (ch) {
6625 case 'p':
6626 pflag = 1;
6627 break;
6628 case 'F':
6629 patch_script_path = optarg;
6630 break;
6631 case 'R':
6632 can_recurse = 1;
6633 break;
6634 default:
6635 usage_revert();
6636 /* NOTREACHED */
6640 argc -= optind;
6641 argv += optind;
6643 #ifndef PROFILE
6644 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6645 "unveil", NULL) == -1)
6646 err(1, "pledge");
6647 #endif
6648 if (argc < 1)
6649 usage_revert();
6650 if (patch_script_path && !pflag)
6651 errx(1, "-F option can only be used together with -p option");
6653 cwd = getcwd(NULL, 0);
6654 if (cwd == NULL) {
6655 error = got_error_from_errno("getcwd");
6656 goto done;
6658 error = got_worktree_open(&worktree, cwd);
6659 if (error) {
6660 if (error->code == GOT_ERR_NOT_WORKTREE)
6661 error = wrap_not_worktree_error(error, "revert", cwd);
6662 goto done;
6665 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6666 NULL);
6667 if (error != NULL)
6668 goto done;
6670 if (patch_script_path) {
6671 patch_script_file = fopen(patch_script_path, "r");
6672 if (patch_script_file == NULL) {
6673 error = got_error_from_errno2("fopen",
6674 patch_script_path);
6675 goto done;
6678 error = apply_unveil(got_repo_get_path(repo), 1,
6679 got_worktree_get_root_path(worktree));
6680 if (error)
6681 goto done;
6683 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6684 if (error)
6685 goto done;
6687 if (!can_recurse) {
6688 char *ondisk_path;
6689 struct stat sb;
6690 TAILQ_FOREACH(pe, &paths, entry) {
6691 if (asprintf(&ondisk_path, "%s/%s",
6692 got_worktree_get_root_path(worktree),
6693 pe->path) == -1) {
6694 error = got_error_from_errno("asprintf");
6695 goto done;
6697 if (lstat(ondisk_path, &sb) == -1) {
6698 if (errno == ENOENT) {
6699 free(ondisk_path);
6700 continue;
6702 error = got_error_from_errno2("lstat",
6703 ondisk_path);
6704 free(ondisk_path);
6705 goto done;
6707 free(ondisk_path);
6708 if (S_ISDIR(sb.st_mode)) {
6709 error = got_error_msg(GOT_ERR_BAD_PATH,
6710 "reverting directories requires -R option");
6711 goto done;
6716 cpa.patch_script_file = patch_script_file;
6717 cpa.action = "revert";
6718 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6719 pflag ? choose_patch : NULL, &cpa, repo);
6720 done:
6721 if (patch_script_file && fclose(patch_script_file) == EOF &&
6722 error == NULL)
6723 error = got_error_from_errno2("fclose", patch_script_path);
6724 if (repo)
6725 got_repo_close(repo);
6726 if (worktree)
6727 got_worktree_close(worktree);
6728 free(path);
6729 free(cwd);
6730 return error;
6733 __dead static void
6734 usage_commit(void)
6736 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6737 getprogname());
6738 exit(1);
6741 struct collect_commit_logmsg_arg {
6742 const char *cmdline_log;
6743 const char *editor;
6744 const char *worktree_path;
6745 const char *branch_name;
6746 const char *repo_path;
6747 char *logmsg_path;
6751 static const struct got_error *
6752 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6753 void *arg)
6755 char *initial_content = NULL;
6756 struct got_pathlist_entry *pe;
6757 const struct got_error *err = NULL;
6758 char *template = NULL;
6759 struct collect_commit_logmsg_arg *a = arg;
6760 int initial_content_len;
6761 int fd = -1;
6762 size_t len;
6764 /* if a message was specified on the command line, just use it */
6765 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6766 len = strlen(a->cmdline_log) + 1;
6767 *logmsg = malloc(len + 1);
6768 if (*logmsg == NULL)
6769 return got_error_from_errno("malloc");
6770 strlcpy(*logmsg, a->cmdline_log, len);
6771 return NULL;
6774 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6775 return got_error_from_errno("asprintf");
6777 initial_content_len = asprintf(&initial_content,
6778 "\n# changes to be committed on branch %s:\n",
6779 a->branch_name);
6780 if (initial_content_len == -1)
6781 return got_error_from_errno("asprintf");
6783 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6784 if (err)
6785 goto done;
6787 if (write(fd, initial_content, initial_content_len) == -1) {
6788 err = got_error_from_errno2("write", a->logmsg_path);
6789 goto done;
6792 TAILQ_FOREACH(pe, commitable_paths, entry) {
6793 struct got_commitable *ct = pe->data;
6794 dprintf(fd, "# %c %s\n",
6795 got_commitable_get_status(ct),
6796 got_commitable_get_path(ct));
6799 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6800 initial_content_len);
6801 done:
6802 free(initial_content);
6803 free(template);
6805 if (fd != -1 && close(fd) == -1 && err == NULL)
6806 err = got_error_from_errno2("close", a->logmsg_path);
6808 /* Editor is done; we can now apply unveil(2) */
6809 if (err == NULL)
6810 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6811 if (err) {
6812 free(*logmsg);
6813 *logmsg = NULL;
6815 return err;
6818 static const struct got_error *
6819 cmd_commit(int argc, char *argv[])
6821 const struct got_error *error = NULL;
6822 struct got_worktree *worktree = NULL;
6823 struct got_repository *repo = NULL;
6824 char *cwd = NULL, *id_str = NULL;
6825 struct got_object_id *id = NULL;
6826 const char *logmsg = NULL;
6827 struct collect_commit_logmsg_arg cl_arg;
6828 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6829 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6830 int allow_bad_symlinks = 0;
6831 struct got_pathlist_head paths;
6833 TAILQ_INIT(&paths);
6834 cl_arg.logmsg_path = NULL;
6836 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6837 switch (ch) {
6838 case 'm':
6839 logmsg = optarg;
6840 break;
6841 case 'S':
6842 allow_bad_symlinks = 1;
6843 break;
6844 default:
6845 usage_commit();
6846 /* NOTREACHED */
6850 argc -= optind;
6851 argv += optind;
6853 #ifndef PROFILE
6854 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6855 "unveil", NULL) == -1)
6856 err(1, "pledge");
6857 #endif
6858 cwd = getcwd(NULL, 0);
6859 if (cwd == NULL) {
6860 error = got_error_from_errno("getcwd");
6861 goto done;
6863 error = got_worktree_open(&worktree, cwd);
6864 if (error) {
6865 if (error->code == GOT_ERR_NOT_WORKTREE)
6866 error = wrap_not_worktree_error(error, "commit", cwd);
6867 goto done;
6870 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6871 if (error)
6872 goto done;
6873 if (rebase_in_progress) {
6874 error = got_error(GOT_ERR_REBASING);
6875 goto done;
6878 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6879 worktree);
6880 if (error)
6881 goto done;
6883 error = get_gitconfig_path(&gitconfig_path);
6884 if (error)
6885 goto done;
6886 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6887 gitconfig_path);
6888 if (error != NULL)
6889 goto done;
6891 error = get_author(&author, repo, worktree);
6892 if (error)
6893 return error;
6896 * unveil(2) traverses exec(2); if an editor is used we have
6897 * to apply unveil after the log message has been written.
6899 if (logmsg == NULL || strlen(logmsg) == 0)
6900 error = get_editor(&editor);
6901 else
6902 error = apply_unveil(got_repo_get_path(repo), 0,
6903 got_worktree_get_root_path(worktree));
6904 if (error)
6905 goto done;
6907 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6908 if (error)
6909 goto done;
6911 cl_arg.editor = editor;
6912 cl_arg.cmdline_log = logmsg;
6913 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6914 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6915 if (!histedit_in_progress) {
6916 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6917 error = got_error(GOT_ERR_COMMIT_BRANCH);
6918 goto done;
6920 cl_arg.branch_name += 11;
6922 cl_arg.repo_path = got_repo_get_path(repo);
6923 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6924 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6925 print_status, NULL, repo);
6926 if (error) {
6927 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6928 cl_arg.logmsg_path != NULL)
6929 preserve_logmsg = 1;
6930 goto done;
6933 error = got_object_id_str(&id_str, id);
6934 if (error)
6935 goto done;
6936 printf("Created commit %s\n", id_str);
6937 done:
6938 if (preserve_logmsg) {
6939 fprintf(stderr, "%s: log message preserved in %s\n",
6940 getprogname(), cl_arg.logmsg_path);
6941 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6942 error == NULL)
6943 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6944 free(cl_arg.logmsg_path);
6945 if (repo)
6946 got_repo_close(repo);
6947 if (worktree)
6948 got_worktree_close(worktree);
6949 free(cwd);
6950 free(id_str);
6951 free(gitconfig_path);
6952 free(editor);
6953 free(author);
6954 return error;
6957 __dead static void
6958 usage_cherrypick(void)
6960 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6961 exit(1);
6964 static const struct got_error *
6965 cmd_cherrypick(int argc, char *argv[])
6967 const struct got_error *error = NULL;
6968 struct got_worktree *worktree = NULL;
6969 struct got_repository *repo = NULL;
6970 char *cwd = NULL, *commit_id_str = NULL;
6971 struct got_object_id *commit_id = NULL;
6972 struct got_commit_object *commit = NULL;
6973 struct got_object_qid *pid;
6974 struct got_reference *head_ref = NULL;
6975 int ch;
6976 struct got_update_progress_arg upa;
6978 while ((ch = getopt(argc, argv, "")) != -1) {
6979 switch (ch) {
6980 default:
6981 usage_cherrypick();
6982 /* NOTREACHED */
6986 argc -= optind;
6987 argv += optind;
6989 #ifndef PROFILE
6990 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6991 "unveil", NULL) == -1)
6992 err(1, "pledge");
6993 #endif
6994 if (argc != 1)
6995 usage_cherrypick();
6997 cwd = getcwd(NULL, 0);
6998 if (cwd == NULL) {
6999 error = got_error_from_errno("getcwd");
7000 goto done;
7002 error = got_worktree_open(&worktree, cwd);
7003 if (error) {
7004 if (error->code == GOT_ERR_NOT_WORKTREE)
7005 error = wrap_not_worktree_error(error, "cherrypick",
7006 cwd);
7007 goto done;
7010 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7011 NULL);
7012 if (error != NULL)
7013 goto done;
7015 error = apply_unveil(got_repo_get_path(repo), 0,
7016 got_worktree_get_root_path(worktree));
7017 if (error)
7018 goto done;
7020 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7021 GOT_OBJ_TYPE_COMMIT, repo);
7022 if (error != NULL) {
7023 struct got_reference *ref;
7024 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7025 goto done;
7026 error = got_ref_open(&ref, repo, argv[0], 0);
7027 if (error != NULL)
7028 goto done;
7029 error = got_ref_resolve(&commit_id, repo, ref);
7030 got_ref_close(ref);
7031 if (error != NULL)
7032 goto done;
7034 error = got_object_id_str(&commit_id_str, commit_id);
7035 if (error)
7036 goto done;
7038 error = got_ref_open(&head_ref, repo,
7039 got_worktree_get_head_ref_name(worktree), 0);
7040 if (error != NULL)
7041 goto done;
7043 error = check_same_branch(commit_id, head_ref, NULL, repo);
7044 if (error) {
7045 if (error->code != GOT_ERR_ANCESTRY)
7046 goto done;
7047 error = NULL;
7048 } else {
7049 error = got_error(GOT_ERR_SAME_BRANCH);
7050 goto done;
7053 error = got_object_open_as_commit(&commit, repo, commit_id);
7054 if (error)
7055 goto done;
7056 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7057 memset(&upa, 0, sizeof(upa));
7058 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7059 commit_id, repo, update_progress, &upa, check_cancelled,
7060 NULL);
7061 if (error != NULL)
7062 goto done;
7064 if (upa.did_something)
7065 printf("Merged commit %s\n", commit_id_str);
7066 print_update_progress_stats(&upa);
7067 done:
7068 if (commit)
7069 got_object_commit_close(commit);
7070 free(commit_id_str);
7071 if (head_ref)
7072 got_ref_close(head_ref);
7073 if (worktree)
7074 got_worktree_close(worktree);
7075 if (repo)
7076 got_repo_close(repo);
7077 return error;
7080 __dead static void
7081 usage_backout(void)
7083 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7084 exit(1);
7087 static const struct got_error *
7088 cmd_backout(int argc, char *argv[])
7090 const struct got_error *error = NULL;
7091 struct got_worktree *worktree = NULL;
7092 struct got_repository *repo = NULL;
7093 char *cwd = NULL, *commit_id_str = NULL;
7094 struct got_object_id *commit_id = NULL;
7095 struct got_commit_object *commit = NULL;
7096 struct got_object_qid *pid;
7097 struct got_reference *head_ref = NULL;
7098 int ch;
7099 struct got_update_progress_arg upa;
7101 while ((ch = getopt(argc, argv, "")) != -1) {
7102 switch (ch) {
7103 default:
7104 usage_backout();
7105 /* NOTREACHED */
7109 argc -= optind;
7110 argv += optind;
7112 #ifndef PROFILE
7113 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7114 "unveil", NULL) == -1)
7115 err(1, "pledge");
7116 #endif
7117 if (argc != 1)
7118 usage_backout();
7120 cwd = getcwd(NULL, 0);
7121 if (cwd == NULL) {
7122 error = got_error_from_errno("getcwd");
7123 goto done;
7125 error = got_worktree_open(&worktree, cwd);
7126 if (error) {
7127 if (error->code == GOT_ERR_NOT_WORKTREE)
7128 error = wrap_not_worktree_error(error, "backout", cwd);
7129 goto done;
7132 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7133 NULL);
7134 if (error != NULL)
7135 goto done;
7137 error = apply_unveil(got_repo_get_path(repo), 0,
7138 got_worktree_get_root_path(worktree));
7139 if (error)
7140 goto done;
7142 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7143 GOT_OBJ_TYPE_COMMIT, repo);
7144 if (error != NULL) {
7145 struct got_reference *ref;
7146 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7147 goto done;
7148 error = got_ref_open(&ref, repo, argv[0], 0);
7149 if (error != NULL)
7150 goto done;
7151 error = got_ref_resolve(&commit_id, repo, ref);
7152 got_ref_close(ref);
7153 if (error != NULL)
7154 goto done;
7156 error = got_object_id_str(&commit_id_str, commit_id);
7157 if (error)
7158 goto done;
7160 error = got_ref_open(&head_ref, repo,
7161 got_worktree_get_head_ref_name(worktree), 0);
7162 if (error != NULL)
7163 goto done;
7165 error = check_same_branch(commit_id, head_ref, NULL, repo);
7166 if (error)
7167 goto done;
7169 error = got_object_open_as_commit(&commit, repo, commit_id);
7170 if (error)
7171 goto done;
7172 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7173 if (pid == NULL) {
7174 error = got_error(GOT_ERR_ROOT_COMMIT);
7175 goto done;
7178 memset(&upa, 0, sizeof(upa));
7179 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7180 update_progress, &upa, check_cancelled, NULL);
7181 if (error != NULL)
7182 goto done;
7184 if (upa.did_something)
7185 printf("Backed out commit %s\n", commit_id_str);
7186 print_update_progress_stats(&upa);
7187 done:
7188 if (commit)
7189 got_object_commit_close(commit);
7190 free(commit_id_str);
7191 if (head_ref)
7192 got_ref_close(head_ref);
7193 if (worktree)
7194 got_worktree_close(worktree);
7195 if (repo)
7196 got_repo_close(repo);
7197 return error;
7200 __dead static void
7201 usage_rebase(void)
7203 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7204 getprogname());
7205 exit(1);
7208 void
7209 trim_logmsg(char *logmsg, int limit)
7211 char *nl;
7212 size_t len;
7214 len = strlen(logmsg);
7215 if (len > limit)
7216 len = limit;
7217 logmsg[len] = '\0';
7218 nl = strchr(logmsg, '\n');
7219 if (nl)
7220 *nl = '\0';
7223 static const struct got_error *
7224 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7226 const struct got_error *err;
7227 char *logmsg0 = NULL;
7228 const char *s;
7230 err = got_object_commit_get_logmsg(&logmsg0, commit);
7231 if (err)
7232 return err;
7234 s = logmsg0;
7235 while (isspace((unsigned char)s[0]))
7236 s++;
7238 *logmsg = strdup(s);
7239 if (*logmsg == NULL) {
7240 err = got_error_from_errno("strdup");
7241 goto done;
7244 trim_logmsg(*logmsg, limit);
7245 done:
7246 free(logmsg0);
7247 return err;
7250 static const struct got_error *
7251 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7253 const struct got_error *err;
7254 struct got_commit_object *commit = NULL;
7255 char *id_str = NULL, *logmsg = NULL;
7257 err = got_object_open_as_commit(&commit, repo, id);
7258 if (err)
7259 return err;
7261 err = got_object_id_str(&id_str, id);
7262 if (err)
7263 goto done;
7265 id_str[12] = '\0';
7267 err = get_short_logmsg(&logmsg, 42, commit);
7268 if (err)
7269 goto done;
7271 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7272 done:
7273 free(id_str);
7274 got_object_commit_close(commit);
7275 free(logmsg);
7276 return err;
7279 static const struct got_error *
7280 show_rebase_progress(struct got_commit_object *commit,
7281 struct got_object_id *old_id, struct got_object_id *new_id)
7283 const struct got_error *err;
7284 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7286 err = got_object_id_str(&old_id_str, old_id);
7287 if (err)
7288 goto done;
7290 if (new_id) {
7291 err = got_object_id_str(&new_id_str, new_id);
7292 if (err)
7293 goto done;
7296 old_id_str[12] = '\0';
7297 if (new_id_str)
7298 new_id_str[12] = '\0';
7300 err = get_short_logmsg(&logmsg, 42, commit);
7301 if (err)
7302 goto done;
7304 printf("%s -> %s: %s\n", old_id_str,
7305 new_id_str ? new_id_str : "no-op change", logmsg);
7306 done:
7307 free(old_id_str);
7308 free(new_id_str);
7309 free(logmsg);
7310 return err;
7313 static const struct got_error *
7314 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7315 struct got_reference *branch, struct got_reference *new_base_branch,
7316 struct got_reference *tmp_branch, struct got_repository *repo)
7318 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7319 return got_worktree_rebase_complete(worktree, fileindex,
7320 new_base_branch, tmp_branch, branch, repo);
7323 static const struct got_error *
7324 rebase_commit(struct got_pathlist_head *merged_paths,
7325 struct got_worktree *worktree, struct got_fileindex *fileindex,
7326 struct got_reference *tmp_branch,
7327 struct got_object_id *commit_id, struct got_repository *repo)
7329 const struct got_error *error;
7330 struct got_commit_object *commit;
7331 struct got_object_id *new_commit_id;
7333 error = got_object_open_as_commit(&commit, repo, commit_id);
7334 if (error)
7335 return error;
7337 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7338 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7339 if (error) {
7340 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7341 goto done;
7342 error = show_rebase_progress(commit, commit_id, NULL);
7343 } else {
7344 error = show_rebase_progress(commit, commit_id, new_commit_id);
7345 free(new_commit_id);
7347 done:
7348 got_object_commit_close(commit);
7349 return error;
7352 struct check_path_prefix_arg {
7353 const char *path_prefix;
7354 size_t len;
7355 int errcode;
7358 static const struct got_error *
7359 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7360 struct got_blob_object *blob2, struct got_object_id *id1,
7361 struct got_object_id *id2, const char *path1, const char *path2,
7362 mode_t mode1, mode_t mode2, struct got_repository *repo)
7364 struct check_path_prefix_arg *a = arg;
7366 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7367 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7368 return got_error(a->errcode);
7370 return NULL;
7373 static const struct got_error *
7374 check_path_prefix(struct got_object_id *parent_id,
7375 struct got_object_id *commit_id, const char *path_prefix,
7376 int errcode, struct got_repository *repo)
7378 const struct got_error *err;
7379 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7380 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7381 struct check_path_prefix_arg cpp_arg;
7383 if (got_path_is_root_dir(path_prefix))
7384 return NULL;
7386 err = got_object_open_as_commit(&commit, repo, commit_id);
7387 if (err)
7388 goto done;
7390 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7391 if (err)
7392 goto done;
7394 err = got_object_open_as_tree(&tree1, repo,
7395 got_object_commit_get_tree_id(parent_commit));
7396 if (err)
7397 goto done;
7399 err = got_object_open_as_tree(&tree2, repo,
7400 got_object_commit_get_tree_id(commit));
7401 if (err)
7402 goto done;
7404 cpp_arg.path_prefix = path_prefix;
7405 while (cpp_arg.path_prefix[0] == '/')
7406 cpp_arg.path_prefix++;
7407 cpp_arg.len = strlen(cpp_arg.path_prefix);
7408 cpp_arg.errcode = errcode;
7409 err = got_diff_tree(tree1, tree2, "", "", repo,
7410 check_path_prefix_in_diff, &cpp_arg, 0);
7411 done:
7412 if (tree1)
7413 got_object_tree_close(tree1);
7414 if (tree2)
7415 got_object_tree_close(tree2);
7416 if (commit)
7417 got_object_commit_close(commit);
7418 if (parent_commit)
7419 got_object_commit_close(parent_commit);
7420 return err;
7423 static const struct got_error *
7424 collect_commits(struct got_object_id_queue *commits,
7425 struct got_object_id *initial_commit_id,
7426 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7427 const char *path_prefix, int path_prefix_errcode,
7428 struct got_repository *repo)
7430 const struct got_error *err = NULL;
7431 struct got_commit_graph *graph = NULL;
7432 struct got_object_id *parent_id = NULL;
7433 struct got_object_qid *qid;
7434 struct got_object_id *commit_id = initial_commit_id;
7436 err = got_commit_graph_open(&graph, "/", 1);
7437 if (err)
7438 return err;
7440 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7441 check_cancelled, NULL);
7442 if (err)
7443 goto done;
7444 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7445 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7446 check_cancelled, NULL);
7447 if (err) {
7448 if (err->code == GOT_ERR_ITER_COMPLETED) {
7449 err = got_error_msg(GOT_ERR_ANCESTRY,
7450 "ran out of commits to rebase before "
7451 "youngest common ancestor commit has "
7452 "been reached?!?");
7454 goto done;
7455 } else {
7456 err = check_path_prefix(parent_id, commit_id,
7457 path_prefix, path_prefix_errcode, repo);
7458 if (err)
7459 goto done;
7461 err = got_object_qid_alloc(&qid, commit_id);
7462 if (err)
7463 goto done;
7464 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7465 commit_id = parent_id;
7468 done:
7469 got_commit_graph_close(graph);
7470 return err;
7473 static const struct got_error *
7474 cmd_rebase(int argc, char *argv[])
7476 const struct got_error *error = NULL;
7477 struct got_worktree *worktree = NULL;
7478 struct got_repository *repo = NULL;
7479 struct got_fileindex *fileindex = NULL;
7480 char *cwd = NULL;
7481 struct got_reference *branch = NULL;
7482 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7483 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7484 struct got_object_id *resume_commit_id = NULL;
7485 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7486 struct got_commit_object *commit = NULL;
7487 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7488 int histedit_in_progress = 0;
7489 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7490 struct got_object_id_queue commits;
7491 struct got_pathlist_head merged_paths;
7492 const struct got_object_id_queue *parent_ids;
7493 struct got_object_qid *qid, *pid;
7495 SIMPLEQ_INIT(&commits);
7496 TAILQ_INIT(&merged_paths);
7498 while ((ch = getopt(argc, argv, "ac")) != -1) {
7499 switch (ch) {
7500 case 'a':
7501 abort_rebase = 1;
7502 break;
7503 case 'c':
7504 continue_rebase = 1;
7505 break;
7506 default:
7507 usage_rebase();
7508 /* NOTREACHED */
7512 argc -= optind;
7513 argv += optind;
7515 #ifndef PROFILE
7516 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7517 "unveil", NULL) == -1)
7518 err(1, "pledge");
7519 #endif
7520 if (abort_rebase && continue_rebase)
7521 usage_rebase();
7522 else if (abort_rebase || continue_rebase) {
7523 if (argc != 0)
7524 usage_rebase();
7525 } else if (argc != 1)
7526 usage_rebase();
7528 cwd = getcwd(NULL, 0);
7529 if (cwd == NULL) {
7530 error = got_error_from_errno("getcwd");
7531 goto done;
7533 error = got_worktree_open(&worktree, cwd);
7534 if (error) {
7535 if (error->code == GOT_ERR_NOT_WORKTREE)
7536 error = wrap_not_worktree_error(error, "rebase", cwd);
7537 goto done;
7540 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7541 NULL);
7542 if (error != NULL)
7543 goto done;
7545 error = apply_unveil(got_repo_get_path(repo), 0,
7546 got_worktree_get_root_path(worktree));
7547 if (error)
7548 goto done;
7550 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7551 worktree);
7552 if (error)
7553 goto done;
7554 if (histedit_in_progress) {
7555 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7556 goto done;
7559 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7560 if (error)
7561 goto done;
7563 if (abort_rebase) {
7564 struct got_update_progress_arg upa;
7565 if (!rebase_in_progress) {
7566 error = got_error(GOT_ERR_NOT_REBASING);
7567 goto done;
7569 error = got_worktree_rebase_continue(&resume_commit_id,
7570 &new_base_branch, &tmp_branch, &branch, &fileindex,
7571 worktree, repo);
7572 if (error)
7573 goto done;
7574 printf("Switching work tree to %s\n",
7575 got_ref_get_symref_target(new_base_branch));
7576 memset(&upa, 0, sizeof(upa));
7577 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7578 new_base_branch, update_progress, &upa);
7579 if (error)
7580 goto done;
7581 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7582 print_update_progress_stats(&upa);
7583 goto done; /* nothing else to do */
7586 if (continue_rebase) {
7587 if (!rebase_in_progress) {
7588 error = got_error(GOT_ERR_NOT_REBASING);
7589 goto done;
7591 error = got_worktree_rebase_continue(&resume_commit_id,
7592 &new_base_branch, &tmp_branch, &branch, &fileindex,
7593 worktree, repo);
7594 if (error)
7595 goto done;
7597 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7598 resume_commit_id, repo);
7599 if (error)
7600 goto done;
7602 yca_id = got_object_id_dup(resume_commit_id);
7603 if (yca_id == NULL) {
7604 error = got_error_from_errno("got_object_id_dup");
7605 goto done;
7607 } else {
7608 error = got_ref_open(&branch, repo, argv[0], 0);
7609 if (error != NULL)
7610 goto done;
7613 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7614 if (error)
7615 goto done;
7617 if (!continue_rebase) {
7618 struct got_object_id *base_commit_id;
7620 base_commit_id = got_worktree_get_base_commit_id(worktree);
7621 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7622 base_commit_id, branch_head_commit_id, repo,
7623 check_cancelled, NULL);
7624 if (error)
7625 goto done;
7626 if (yca_id == NULL) {
7627 error = got_error_msg(GOT_ERR_ANCESTRY,
7628 "specified branch shares no common ancestry "
7629 "with work tree's branch");
7630 goto done;
7633 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7634 if (error) {
7635 if (error->code != GOT_ERR_ANCESTRY)
7636 goto done;
7637 error = NULL;
7638 } else {
7639 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7640 "specified branch resolves to a commit which "
7641 "is already contained in work tree's branch");
7642 goto done;
7644 error = got_worktree_rebase_prepare(&new_base_branch,
7645 &tmp_branch, &fileindex, worktree, branch, repo);
7646 if (error)
7647 goto done;
7650 commit_id = branch_head_commit_id;
7651 error = got_object_open_as_commit(&commit, repo, commit_id);
7652 if (error)
7653 goto done;
7655 parent_ids = got_object_commit_get_parent_ids(commit);
7656 pid = SIMPLEQ_FIRST(parent_ids);
7657 if (pid == NULL) {
7658 if (!continue_rebase) {
7659 struct got_update_progress_arg upa;
7660 memset(&upa, 0, sizeof(upa));
7661 error = got_worktree_rebase_abort(worktree, fileindex,
7662 repo, new_base_branch, update_progress, &upa);
7663 if (error)
7664 goto done;
7665 printf("Rebase of %s aborted\n",
7666 got_ref_get_name(branch));
7667 print_update_progress_stats(&upa);
7670 error = got_error(GOT_ERR_EMPTY_REBASE);
7671 goto done;
7673 error = collect_commits(&commits, commit_id, pid->id,
7674 yca_id, got_worktree_get_path_prefix(worktree),
7675 GOT_ERR_REBASE_PATH, repo);
7676 got_object_commit_close(commit);
7677 commit = NULL;
7678 if (error)
7679 goto done;
7681 if (SIMPLEQ_EMPTY(&commits)) {
7682 if (continue_rebase) {
7683 error = rebase_complete(worktree, fileindex,
7684 branch, new_base_branch, tmp_branch, repo);
7685 goto done;
7686 } else {
7687 /* Fast-forward the reference of the branch. */
7688 struct got_object_id *new_head_commit_id;
7689 char *id_str;
7690 error = got_ref_resolve(&new_head_commit_id, repo,
7691 new_base_branch);
7692 if (error)
7693 goto done;
7694 error = got_object_id_str(&id_str, new_head_commit_id);
7695 printf("Forwarding %s to commit %s\n",
7696 got_ref_get_name(branch), id_str);
7697 free(id_str);
7698 error = got_ref_change_ref(branch,
7699 new_head_commit_id);
7700 if (error)
7701 goto done;
7705 pid = NULL;
7706 SIMPLEQ_FOREACH(qid, &commits, entry) {
7707 struct got_update_progress_arg upa;
7709 commit_id = qid->id;
7710 parent_id = pid ? pid->id : yca_id;
7711 pid = qid;
7713 memset(&upa, 0, sizeof(upa));
7714 error = got_worktree_rebase_merge_files(&merged_paths,
7715 worktree, fileindex, parent_id, commit_id, repo,
7716 update_progress, &upa, check_cancelled, NULL);
7717 if (error)
7718 goto done;
7720 print_update_progress_stats(&upa);
7721 if (upa.conflicts > 0)
7722 rebase_status = GOT_STATUS_CONFLICT;
7724 if (rebase_status == GOT_STATUS_CONFLICT) {
7725 error = show_rebase_merge_conflict(qid->id, repo);
7726 if (error)
7727 goto done;
7728 got_worktree_rebase_pathlist_free(&merged_paths);
7729 break;
7732 error = rebase_commit(&merged_paths, worktree, fileindex,
7733 tmp_branch, commit_id, repo);
7734 got_worktree_rebase_pathlist_free(&merged_paths);
7735 if (error)
7736 goto done;
7739 if (rebase_status == GOT_STATUS_CONFLICT) {
7740 error = got_worktree_rebase_postpone(worktree, fileindex);
7741 if (error)
7742 goto done;
7743 error = got_error_msg(GOT_ERR_CONFLICTS,
7744 "conflicts must be resolved before rebasing can continue");
7745 } else
7746 error = rebase_complete(worktree, fileindex, branch,
7747 new_base_branch, tmp_branch, repo);
7748 done:
7749 got_object_id_queue_free(&commits);
7750 free(branch_head_commit_id);
7751 free(resume_commit_id);
7752 free(yca_id);
7753 if (commit)
7754 got_object_commit_close(commit);
7755 if (branch)
7756 got_ref_close(branch);
7757 if (new_base_branch)
7758 got_ref_close(new_base_branch);
7759 if (tmp_branch)
7760 got_ref_close(tmp_branch);
7761 if (worktree)
7762 got_worktree_close(worktree);
7763 if (repo)
7764 got_repo_close(repo);
7765 return error;
7768 __dead static void
7769 usage_histedit(void)
7771 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7772 getprogname());
7773 exit(1);
7776 #define GOT_HISTEDIT_PICK 'p'
7777 #define GOT_HISTEDIT_EDIT 'e'
7778 #define GOT_HISTEDIT_FOLD 'f'
7779 #define GOT_HISTEDIT_DROP 'd'
7780 #define GOT_HISTEDIT_MESG 'm'
7782 static struct got_histedit_cmd {
7783 unsigned char code;
7784 const char *name;
7785 const char *desc;
7786 } got_histedit_cmds[] = {
7787 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7788 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7789 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7790 "be used" },
7791 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7792 { GOT_HISTEDIT_MESG, "mesg",
7793 "single-line log message for commit above (open editor if empty)" },
7796 struct got_histedit_list_entry {
7797 TAILQ_ENTRY(got_histedit_list_entry) entry;
7798 struct got_object_id *commit_id;
7799 const struct got_histedit_cmd *cmd;
7800 char *logmsg;
7802 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7804 static const struct got_error *
7805 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7806 FILE *f, struct got_repository *repo)
7808 const struct got_error *err = NULL;
7809 char *logmsg = NULL, *id_str = NULL;
7810 struct got_commit_object *commit = NULL;
7811 int n;
7813 err = got_object_open_as_commit(&commit, repo, commit_id);
7814 if (err)
7815 goto done;
7817 err = get_short_logmsg(&logmsg, 34, commit);
7818 if (err)
7819 goto done;
7821 err = got_object_id_str(&id_str, commit_id);
7822 if (err)
7823 goto done;
7825 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7826 if (n < 0)
7827 err = got_ferror(f, GOT_ERR_IO);
7828 done:
7829 if (commit)
7830 got_object_commit_close(commit);
7831 free(id_str);
7832 free(logmsg);
7833 return err;
7836 static const struct got_error *
7837 histedit_write_commit_list(struct got_object_id_queue *commits,
7838 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7840 const struct got_error *err = NULL;
7841 struct got_object_qid *qid;
7843 if (SIMPLEQ_EMPTY(commits))
7844 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7846 SIMPLEQ_FOREACH(qid, commits, entry) {
7847 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7848 f, repo);
7849 if (err)
7850 break;
7851 if (edit_logmsg_only) {
7852 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7853 if (n < 0) {
7854 err = got_ferror(f, GOT_ERR_IO);
7855 break;
7860 return err;
7863 static const struct got_error *
7864 write_cmd_list(FILE *f, const char *branch_name,
7865 struct got_object_id_queue *commits)
7867 const struct got_error *err = NULL;
7868 int n, i;
7869 char *id_str;
7870 struct got_object_qid *qid;
7872 qid = SIMPLEQ_FIRST(commits);
7873 err = got_object_id_str(&id_str, qid->id);
7874 if (err)
7875 return err;
7877 n = fprintf(f,
7878 "# Editing the history of branch '%s' starting at\n"
7879 "# commit %s\n"
7880 "# Commits will be processed in order from top to "
7881 "bottom of this file.\n", branch_name, id_str);
7882 if (n < 0) {
7883 err = got_ferror(f, GOT_ERR_IO);
7884 goto done;
7887 n = fprintf(f, "# Available histedit commands:\n");
7888 if (n < 0) {
7889 err = got_ferror(f, GOT_ERR_IO);
7890 goto done;
7893 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7894 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7895 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7896 cmd->desc);
7897 if (n < 0) {
7898 err = got_ferror(f, GOT_ERR_IO);
7899 break;
7902 done:
7903 free(id_str);
7904 return err;
7907 static const struct got_error *
7908 histedit_syntax_error(int lineno)
7910 static char msg[42];
7911 int ret;
7913 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7914 lineno);
7915 if (ret == -1 || ret >= sizeof(msg))
7916 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7918 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7921 static const struct got_error *
7922 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7923 char *logmsg, struct got_repository *repo)
7925 const struct got_error *err;
7926 struct got_commit_object *folded_commit = NULL;
7927 char *id_str, *folded_logmsg = NULL;
7929 err = got_object_id_str(&id_str, hle->commit_id);
7930 if (err)
7931 return err;
7933 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7934 if (err)
7935 goto done;
7937 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7938 if (err)
7939 goto done;
7940 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7941 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7942 folded_logmsg) == -1) {
7943 err = got_error_from_errno("asprintf");
7945 done:
7946 if (folded_commit)
7947 got_object_commit_close(folded_commit);
7948 free(id_str);
7949 free(folded_logmsg);
7950 return err;
7953 static struct got_histedit_list_entry *
7954 get_folded_commits(struct got_histedit_list_entry *hle)
7956 struct got_histedit_list_entry *prev, *folded = NULL;
7958 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7959 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7960 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7961 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7962 folded = prev;
7963 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7966 return folded;
7969 static const struct got_error *
7970 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7971 struct got_repository *repo)
7973 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7974 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7975 const struct got_error *err = NULL;
7976 struct got_commit_object *commit = NULL;
7977 int logmsg_len;
7978 int fd;
7979 struct got_histedit_list_entry *folded = NULL;
7981 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7982 if (err)
7983 return err;
7985 folded = get_folded_commits(hle);
7986 if (folded) {
7987 while (folded != hle) {
7988 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7989 folded = TAILQ_NEXT(folded, entry);
7990 continue;
7992 err = append_folded_commit_msg(&new_msg, folded,
7993 logmsg, repo);
7994 if (err)
7995 goto done;
7996 free(logmsg);
7997 logmsg = new_msg;
7998 folded = TAILQ_NEXT(folded, entry);
8002 err = got_object_id_str(&id_str, hle->commit_id);
8003 if (err)
8004 goto done;
8005 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8006 if (err)
8007 goto done;
8008 logmsg_len = asprintf(&new_msg,
8009 "%s\n# original log message of commit %s: %s",
8010 logmsg ? logmsg : "", id_str, orig_logmsg);
8011 if (logmsg_len == -1) {
8012 err = got_error_from_errno("asprintf");
8013 goto done;
8015 free(logmsg);
8016 logmsg = new_msg;
8018 err = got_object_id_str(&id_str, hle->commit_id);
8019 if (err)
8020 goto done;
8022 err = got_opentemp_named_fd(&logmsg_path, &fd,
8023 GOT_TMPDIR_STR "/got-logmsg");
8024 if (err)
8025 goto done;
8027 write(fd, logmsg, logmsg_len);
8028 close(fd);
8030 err = get_editor(&editor);
8031 if (err)
8032 goto done;
8034 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8035 logmsg_len);
8036 if (err) {
8037 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8038 goto done;
8039 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8041 done:
8042 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8043 err = got_error_from_errno2("unlink", logmsg_path);
8044 free(logmsg_path);
8045 free(logmsg);
8046 free(orig_logmsg);
8047 free(editor);
8048 if (commit)
8049 got_object_commit_close(commit);
8050 return err;
8053 static const struct got_error *
8054 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8055 FILE *f, struct got_repository *repo)
8057 const struct got_error *err = NULL;
8058 char *line = NULL, *p, *end;
8059 size_t size;
8060 ssize_t len;
8061 int lineno = 0, i;
8062 const struct got_histedit_cmd *cmd;
8063 struct got_object_id *commit_id = NULL;
8064 struct got_histedit_list_entry *hle = NULL;
8066 for (;;) {
8067 len = getline(&line, &size, f);
8068 if (len == -1) {
8069 const struct got_error *getline_err;
8070 if (feof(f))
8071 break;
8072 getline_err = got_error_from_errno("getline");
8073 err = got_ferror(f, getline_err->code);
8074 break;
8076 lineno++;
8077 p = line;
8078 while (isspace((unsigned char)p[0]))
8079 p++;
8080 if (p[0] == '#' || p[0] == '\0') {
8081 free(line);
8082 line = NULL;
8083 continue;
8085 cmd = NULL;
8086 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8087 cmd = &got_histedit_cmds[i];
8088 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8089 isspace((unsigned char)p[strlen(cmd->name)])) {
8090 p += strlen(cmd->name);
8091 break;
8093 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8094 p++;
8095 break;
8098 if (i == nitems(got_histedit_cmds)) {
8099 err = histedit_syntax_error(lineno);
8100 break;
8102 while (isspace((unsigned char)p[0]))
8103 p++;
8104 if (cmd->code == GOT_HISTEDIT_MESG) {
8105 if (hle == NULL || hle->logmsg != NULL) {
8106 err = got_error(GOT_ERR_HISTEDIT_CMD);
8107 break;
8109 if (p[0] == '\0') {
8110 err = histedit_edit_logmsg(hle, repo);
8111 if (err)
8112 break;
8113 } else {
8114 hle->logmsg = strdup(p);
8115 if (hle->logmsg == NULL) {
8116 err = got_error_from_errno("strdup");
8117 break;
8120 free(line);
8121 line = NULL;
8122 continue;
8123 } else {
8124 end = p;
8125 while (end[0] && !isspace((unsigned char)end[0]))
8126 end++;
8127 *end = '\0';
8129 err = got_object_resolve_id_str(&commit_id, repo, p);
8130 if (err) {
8131 /* override error code */
8132 err = histedit_syntax_error(lineno);
8133 break;
8136 hle = malloc(sizeof(*hle));
8137 if (hle == NULL) {
8138 err = got_error_from_errno("malloc");
8139 break;
8141 hle->cmd = cmd;
8142 hle->commit_id = commit_id;
8143 hle->logmsg = NULL;
8144 commit_id = NULL;
8145 free(line);
8146 line = NULL;
8147 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8150 free(line);
8151 free(commit_id);
8152 return err;
8155 static const struct got_error *
8156 histedit_check_script(struct got_histedit_list *histedit_cmds,
8157 struct got_object_id_queue *commits, struct got_repository *repo)
8159 const struct got_error *err = NULL;
8160 struct got_object_qid *qid;
8161 struct got_histedit_list_entry *hle;
8162 static char msg[92];
8163 char *id_str;
8165 if (TAILQ_EMPTY(histedit_cmds))
8166 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8167 "histedit script contains no commands");
8168 if (SIMPLEQ_EMPTY(commits))
8169 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8171 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8172 struct got_histedit_list_entry *hle2;
8173 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8174 if (hle == hle2)
8175 continue;
8176 if (got_object_id_cmp(hle->commit_id,
8177 hle2->commit_id) != 0)
8178 continue;
8179 err = got_object_id_str(&id_str, hle->commit_id);
8180 if (err)
8181 return err;
8182 snprintf(msg, sizeof(msg), "commit %s is listed "
8183 "more than once in histedit script", id_str);
8184 free(id_str);
8185 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8189 SIMPLEQ_FOREACH(qid, commits, entry) {
8190 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8191 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8192 break;
8194 if (hle == NULL) {
8195 err = got_object_id_str(&id_str, qid->id);
8196 if (err)
8197 return err;
8198 snprintf(msg, sizeof(msg),
8199 "commit %s missing from histedit script", id_str);
8200 free(id_str);
8201 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8205 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8206 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8207 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8208 "last commit in histedit script cannot be folded");
8210 return NULL;
8213 static const struct got_error *
8214 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8215 const char *path, struct got_object_id_queue *commits,
8216 struct got_repository *repo)
8218 const struct got_error *err = NULL;
8219 char *editor;
8220 FILE *f = NULL;
8222 err = get_editor(&editor);
8223 if (err)
8224 return err;
8226 if (spawn_editor(editor, path) == -1) {
8227 err = got_error_from_errno("failed spawning editor");
8228 goto done;
8231 f = fopen(path, "r");
8232 if (f == NULL) {
8233 err = got_error_from_errno("fopen");
8234 goto done;
8236 err = histedit_parse_list(histedit_cmds, f, repo);
8237 if (err)
8238 goto done;
8240 err = histedit_check_script(histedit_cmds, commits, repo);
8241 done:
8242 if (f && fclose(f) != 0 && err == NULL)
8243 err = got_error_from_errno("fclose");
8244 free(editor);
8245 return err;
8248 static const struct got_error *
8249 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8250 struct got_object_id_queue *, const char *, const char *,
8251 struct got_repository *);
8253 static const struct got_error *
8254 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8255 struct got_object_id_queue *commits, const char *branch_name,
8256 int edit_logmsg_only, struct got_repository *repo)
8258 const struct got_error *err;
8259 FILE *f = NULL;
8260 char *path = NULL;
8262 err = got_opentemp_named(&path, &f, "got-histedit");
8263 if (err)
8264 return err;
8266 err = write_cmd_list(f, branch_name, commits);
8267 if (err)
8268 goto done;
8270 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8271 if (err)
8272 goto done;
8274 if (edit_logmsg_only) {
8275 rewind(f);
8276 err = histedit_parse_list(histedit_cmds, f, repo);
8277 } else {
8278 if (fclose(f) != 0) {
8279 err = got_error_from_errno("fclose");
8280 goto done;
8282 f = NULL;
8283 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8284 if (err) {
8285 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8286 err->code != GOT_ERR_HISTEDIT_CMD)
8287 goto done;
8288 err = histedit_edit_list_retry(histedit_cmds, err,
8289 commits, path, branch_name, repo);
8292 done:
8293 if (f && fclose(f) != 0 && err == NULL)
8294 err = got_error_from_errno("fclose");
8295 if (path && unlink(path) != 0 && err == NULL)
8296 err = got_error_from_errno2("unlink", path);
8297 free(path);
8298 return err;
8301 static const struct got_error *
8302 histedit_save_list(struct got_histedit_list *histedit_cmds,
8303 struct got_worktree *worktree, struct got_repository *repo)
8305 const struct got_error *err = NULL;
8306 char *path = NULL;
8307 FILE *f = NULL;
8308 struct got_histedit_list_entry *hle;
8309 struct got_commit_object *commit = NULL;
8311 err = got_worktree_get_histedit_script_path(&path, worktree);
8312 if (err)
8313 return err;
8315 f = fopen(path, "w");
8316 if (f == NULL) {
8317 err = got_error_from_errno2("fopen", path);
8318 goto done;
8320 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8321 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8322 repo);
8323 if (err)
8324 break;
8326 if (hle->logmsg) {
8327 int n = fprintf(f, "%c %s\n",
8328 GOT_HISTEDIT_MESG, hle->logmsg);
8329 if (n < 0) {
8330 err = got_ferror(f, GOT_ERR_IO);
8331 break;
8335 done:
8336 if (f && fclose(f) != 0 && err == NULL)
8337 err = got_error_from_errno("fclose");
8338 free(path);
8339 if (commit)
8340 got_object_commit_close(commit);
8341 return err;
8344 void
8345 histedit_free_list(struct got_histedit_list *histedit_cmds)
8347 struct got_histedit_list_entry *hle;
8349 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8350 TAILQ_REMOVE(histedit_cmds, hle, entry);
8351 free(hle);
8355 static const struct got_error *
8356 histedit_load_list(struct got_histedit_list *histedit_cmds,
8357 const char *path, struct got_repository *repo)
8359 const struct got_error *err = NULL;
8360 FILE *f = NULL;
8362 f = fopen(path, "r");
8363 if (f == NULL) {
8364 err = got_error_from_errno2("fopen", path);
8365 goto done;
8368 err = histedit_parse_list(histedit_cmds, f, repo);
8369 done:
8370 if (f && fclose(f) != 0 && err == NULL)
8371 err = got_error_from_errno("fclose");
8372 return err;
8375 static const struct got_error *
8376 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8377 const struct got_error *edit_err, struct got_object_id_queue *commits,
8378 const char *path, const char *branch_name, struct got_repository *repo)
8380 const struct got_error *err = NULL, *prev_err = edit_err;
8381 int resp = ' ';
8383 while (resp != 'c' && resp != 'r' && resp != 'a') {
8384 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8385 "or (a)bort: ", getprogname(), prev_err->msg);
8386 resp = getchar();
8387 if (resp == '\n')
8388 resp = getchar();
8389 if (resp == 'c') {
8390 histedit_free_list(histedit_cmds);
8391 err = histedit_run_editor(histedit_cmds, path, commits,
8392 repo);
8393 if (err) {
8394 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8395 err->code != GOT_ERR_HISTEDIT_CMD)
8396 break;
8397 prev_err = err;
8398 resp = ' ';
8399 continue;
8401 break;
8402 } else if (resp == 'r') {
8403 histedit_free_list(histedit_cmds);
8404 err = histedit_edit_script(histedit_cmds,
8405 commits, branch_name, 0, repo);
8406 if (err) {
8407 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8408 err->code != GOT_ERR_HISTEDIT_CMD)
8409 break;
8410 prev_err = err;
8411 resp = ' ';
8412 continue;
8414 break;
8415 } else if (resp == 'a') {
8416 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8417 break;
8418 } else
8419 printf("invalid response '%c'\n", resp);
8422 return err;
8425 static const struct got_error *
8426 histedit_complete(struct got_worktree *worktree,
8427 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8428 struct got_reference *branch, struct got_repository *repo)
8430 printf("Switching work tree to %s\n",
8431 got_ref_get_symref_target(branch));
8432 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8433 branch, repo);
8436 static const struct got_error *
8437 show_histedit_progress(struct got_commit_object *commit,
8438 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8440 const struct got_error *err;
8441 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8443 err = got_object_id_str(&old_id_str, hle->commit_id);
8444 if (err)
8445 goto done;
8447 if (new_id) {
8448 err = got_object_id_str(&new_id_str, new_id);
8449 if (err)
8450 goto done;
8453 old_id_str[12] = '\0';
8454 if (new_id_str)
8455 new_id_str[12] = '\0';
8457 if (hle->logmsg) {
8458 logmsg = strdup(hle->logmsg);
8459 if (logmsg == NULL) {
8460 err = got_error_from_errno("strdup");
8461 goto done;
8463 trim_logmsg(logmsg, 42);
8464 } else {
8465 err = get_short_logmsg(&logmsg, 42, commit);
8466 if (err)
8467 goto done;
8470 switch (hle->cmd->code) {
8471 case GOT_HISTEDIT_PICK:
8472 case GOT_HISTEDIT_EDIT:
8473 printf("%s -> %s: %s\n", old_id_str,
8474 new_id_str ? new_id_str : "no-op change", logmsg);
8475 break;
8476 case GOT_HISTEDIT_DROP:
8477 case GOT_HISTEDIT_FOLD:
8478 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8479 logmsg);
8480 break;
8481 default:
8482 break;
8484 done:
8485 free(old_id_str);
8486 free(new_id_str);
8487 return err;
8490 static const struct got_error *
8491 histedit_commit(struct got_pathlist_head *merged_paths,
8492 struct got_worktree *worktree, struct got_fileindex *fileindex,
8493 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8494 struct got_repository *repo)
8496 const struct got_error *err;
8497 struct got_commit_object *commit;
8498 struct got_object_id *new_commit_id;
8500 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8501 && hle->logmsg == NULL) {
8502 err = histedit_edit_logmsg(hle, repo);
8503 if (err)
8504 return err;
8507 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8508 if (err)
8509 return err;
8511 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8512 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8513 hle->logmsg, repo);
8514 if (err) {
8515 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8516 goto done;
8517 err = show_histedit_progress(commit, hle, NULL);
8518 } else {
8519 err = show_histedit_progress(commit, hle, new_commit_id);
8520 free(new_commit_id);
8522 done:
8523 got_object_commit_close(commit);
8524 return err;
8527 static const struct got_error *
8528 histedit_skip_commit(struct got_histedit_list_entry *hle,
8529 struct got_worktree *worktree, struct got_repository *repo)
8531 const struct got_error *error;
8532 struct got_commit_object *commit;
8534 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8535 repo);
8536 if (error)
8537 return error;
8539 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8540 if (error)
8541 return error;
8543 error = show_histedit_progress(commit, hle, NULL);
8544 got_object_commit_close(commit);
8545 return error;
8548 static const struct got_error *
8549 check_local_changes(void *arg, unsigned char status,
8550 unsigned char staged_status, const char *path,
8551 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8552 struct got_object_id *commit_id, int dirfd, const char *de_name)
8554 int *have_local_changes = arg;
8556 switch (status) {
8557 case GOT_STATUS_ADD:
8558 case GOT_STATUS_DELETE:
8559 case GOT_STATUS_MODIFY:
8560 case GOT_STATUS_CONFLICT:
8561 *have_local_changes = 1;
8562 return got_error(GOT_ERR_CANCELLED);
8563 default:
8564 break;
8567 switch (staged_status) {
8568 case GOT_STATUS_ADD:
8569 case GOT_STATUS_DELETE:
8570 case GOT_STATUS_MODIFY:
8571 *have_local_changes = 1;
8572 return got_error(GOT_ERR_CANCELLED);
8573 default:
8574 break;
8577 return NULL;
8580 static const struct got_error *
8581 cmd_histedit(int argc, char *argv[])
8583 const struct got_error *error = NULL;
8584 struct got_worktree *worktree = NULL;
8585 struct got_fileindex *fileindex = NULL;
8586 struct got_repository *repo = NULL;
8587 char *cwd = NULL;
8588 struct got_reference *branch = NULL;
8589 struct got_reference *tmp_branch = NULL;
8590 struct got_object_id *resume_commit_id = NULL;
8591 struct got_object_id *base_commit_id = NULL;
8592 struct got_object_id *head_commit_id = NULL;
8593 struct got_commit_object *commit = NULL;
8594 int ch, rebase_in_progress = 0;
8595 struct got_update_progress_arg upa;
8596 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8597 int edit_logmsg_only = 0;
8598 const char *edit_script_path = NULL;
8599 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8600 struct got_object_id_queue commits;
8601 struct got_pathlist_head merged_paths;
8602 const struct got_object_id_queue *parent_ids;
8603 struct got_object_qid *pid;
8604 struct got_histedit_list histedit_cmds;
8605 struct got_histedit_list_entry *hle;
8607 SIMPLEQ_INIT(&commits);
8608 TAILQ_INIT(&histedit_cmds);
8609 TAILQ_INIT(&merged_paths);
8610 memset(&upa, 0, sizeof(upa));
8612 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8613 switch (ch) {
8614 case 'a':
8615 abort_edit = 1;
8616 break;
8617 case 'c':
8618 continue_edit = 1;
8619 break;
8620 case 'F':
8621 edit_script_path = optarg;
8622 break;
8623 case 'm':
8624 edit_logmsg_only = 1;
8625 break;
8626 default:
8627 usage_histedit();
8628 /* NOTREACHED */
8632 argc -= optind;
8633 argv += optind;
8635 #ifndef PROFILE
8636 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8637 "unveil", NULL) == -1)
8638 err(1, "pledge");
8639 #endif
8640 if (abort_edit && continue_edit)
8641 errx(1, "histedit's -a and -c options are mutually exclusive");
8642 if (edit_script_path && edit_logmsg_only)
8643 errx(1, "histedit's -F and -m options are mutually exclusive");
8644 if (abort_edit && edit_logmsg_only)
8645 errx(1, "histedit's -a and -m options are mutually exclusive");
8646 if (continue_edit && edit_logmsg_only)
8647 errx(1, "histedit's -c and -m options are mutually exclusive");
8648 if (argc != 0)
8649 usage_histedit();
8652 * This command cannot apply unveil(2) in all cases because the
8653 * user may choose to run an editor to edit the histedit script
8654 * and to edit individual commit log messages.
8655 * unveil(2) traverses exec(2); if an editor is used we have to
8656 * apply unveil after edit script and log messages have been written.
8657 * XXX TODO: Make use of unveil(2) where possible.
8660 cwd = getcwd(NULL, 0);
8661 if (cwd == NULL) {
8662 error = got_error_from_errno("getcwd");
8663 goto done;
8665 error = got_worktree_open(&worktree, cwd);
8666 if (error) {
8667 if (error->code == GOT_ERR_NOT_WORKTREE)
8668 error = wrap_not_worktree_error(error, "histedit", cwd);
8669 goto done;
8672 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8673 NULL);
8674 if (error != NULL)
8675 goto done;
8677 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8678 if (error)
8679 goto done;
8680 if (rebase_in_progress) {
8681 error = got_error(GOT_ERR_REBASING);
8682 goto done;
8685 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8686 if (error)
8687 goto done;
8689 if (edit_in_progress && edit_logmsg_only) {
8690 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8691 "histedit operation is in progress in this "
8692 "work tree and must be continued or aborted "
8693 "before the -m option can be used");
8694 goto done;
8697 if (edit_in_progress && abort_edit) {
8698 error = got_worktree_histedit_continue(&resume_commit_id,
8699 &tmp_branch, &branch, &base_commit_id, &fileindex,
8700 worktree, repo);
8701 if (error)
8702 goto done;
8703 printf("Switching work tree to %s\n",
8704 got_ref_get_symref_target(branch));
8705 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8706 branch, base_commit_id, update_progress, &upa);
8707 if (error)
8708 goto done;
8709 printf("Histedit of %s aborted\n",
8710 got_ref_get_symref_target(branch));
8711 print_update_progress_stats(&upa);
8712 goto done; /* nothing else to do */
8713 } else if (abort_edit) {
8714 error = got_error(GOT_ERR_NOT_HISTEDIT);
8715 goto done;
8718 if (continue_edit) {
8719 char *path;
8721 if (!edit_in_progress) {
8722 error = got_error(GOT_ERR_NOT_HISTEDIT);
8723 goto done;
8726 error = got_worktree_get_histedit_script_path(&path, worktree);
8727 if (error)
8728 goto done;
8730 error = histedit_load_list(&histedit_cmds, path, repo);
8731 free(path);
8732 if (error)
8733 goto done;
8735 error = got_worktree_histedit_continue(&resume_commit_id,
8736 &tmp_branch, &branch, &base_commit_id, &fileindex,
8737 worktree, repo);
8738 if (error)
8739 goto done;
8741 error = got_ref_resolve(&head_commit_id, repo, branch);
8742 if (error)
8743 goto done;
8745 error = got_object_open_as_commit(&commit, repo,
8746 head_commit_id);
8747 if (error)
8748 goto done;
8749 parent_ids = got_object_commit_get_parent_ids(commit);
8750 pid = SIMPLEQ_FIRST(parent_ids);
8751 if (pid == NULL) {
8752 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8753 goto done;
8755 error = collect_commits(&commits, head_commit_id, pid->id,
8756 base_commit_id, got_worktree_get_path_prefix(worktree),
8757 GOT_ERR_HISTEDIT_PATH, repo);
8758 got_object_commit_close(commit);
8759 commit = NULL;
8760 if (error)
8761 goto done;
8762 } else {
8763 if (edit_in_progress) {
8764 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8765 goto done;
8768 error = got_ref_open(&branch, repo,
8769 got_worktree_get_head_ref_name(worktree), 0);
8770 if (error != NULL)
8771 goto done;
8773 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8774 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8775 "will not edit commit history of a branch outside "
8776 "the \"refs/heads/\" reference namespace");
8777 goto done;
8780 error = got_ref_resolve(&head_commit_id, repo, branch);
8781 got_ref_close(branch);
8782 branch = NULL;
8783 if (error)
8784 goto done;
8786 error = got_object_open_as_commit(&commit, repo,
8787 head_commit_id);
8788 if (error)
8789 goto done;
8790 parent_ids = got_object_commit_get_parent_ids(commit);
8791 pid = SIMPLEQ_FIRST(parent_ids);
8792 if (pid == NULL) {
8793 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8794 goto done;
8796 error = collect_commits(&commits, head_commit_id, pid->id,
8797 got_worktree_get_base_commit_id(worktree),
8798 got_worktree_get_path_prefix(worktree),
8799 GOT_ERR_HISTEDIT_PATH, repo);
8800 got_object_commit_close(commit);
8801 commit = NULL;
8802 if (error)
8803 goto done;
8805 if (SIMPLEQ_EMPTY(&commits)) {
8806 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8807 goto done;
8810 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8811 &base_commit_id, &fileindex, worktree, repo);
8812 if (error)
8813 goto done;
8815 if (edit_script_path) {
8816 error = histedit_load_list(&histedit_cmds,
8817 edit_script_path, repo);
8818 if (error) {
8819 got_worktree_histedit_abort(worktree, fileindex,
8820 repo, branch, base_commit_id,
8821 update_progress, &upa);
8822 print_update_progress_stats(&upa);
8823 goto done;
8825 } else {
8826 const char *branch_name;
8827 branch_name = got_ref_get_symref_target(branch);
8828 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8829 branch_name += 11;
8830 error = histedit_edit_script(&histedit_cmds, &commits,
8831 branch_name, edit_logmsg_only, repo);
8832 if (error) {
8833 got_worktree_histedit_abort(worktree, fileindex,
8834 repo, branch, base_commit_id,
8835 update_progress, &upa);
8836 print_update_progress_stats(&upa);
8837 goto done;
8842 error = histedit_save_list(&histedit_cmds, worktree,
8843 repo);
8844 if (error) {
8845 got_worktree_histedit_abort(worktree, fileindex,
8846 repo, branch, base_commit_id,
8847 update_progress, &upa);
8848 print_update_progress_stats(&upa);
8849 goto done;
8854 error = histedit_check_script(&histedit_cmds, &commits, repo);
8855 if (error)
8856 goto done;
8858 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8859 if (resume_commit_id) {
8860 if (got_object_id_cmp(hle->commit_id,
8861 resume_commit_id) != 0)
8862 continue;
8864 resume_commit_id = NULL;
8865 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8866 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8867 error = histedit_skip_commit(hle, worktree,
8868 repo);
8869 if (error)
8870 goto done;
8871 } else {
8872 struct got_pathlist_head paths;
8873 int have_changes = 0;
8875 TAILQ_INIT(&paths);
8876 error = got_pathlist_append(&paths, "", NULL);
8877 if (error)
8878 goto done;
8879 error = got_worktree_status(worktree, &paths,
8880 repo, check_local_changes, &have_changes,
8881 check_cancelled, NULL);
8882 got_pathlist_free(&paths);
8883 if (error) {
8884 if (error->code != GOT_ERR_CANCELLED)
8885 goto done;
8886 if (sigint_received || sigpipe_received)
8887 goto done;
8889 if (have_changes) {
8890 error = histedit_commit(NULL, worktree,
8891 fileindex, tmp_branch, hle, repo);
8892 if (error)
8893 goto done;
8894 } else {
8895 error = got_object_open_as_commit(
8896 &commit, repo, hle->commit_id);
8897 if (error)
8898 goto done;
8899 error = show_histedit_progress(commit,
8900 hle, NULL);
8901 got_object_commit_close(commit);
8902 commit = NULL;
8903 if (error)
8904 goto done;
8907 continue;
8910 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8911 error = histedit_skip_commit(hle, worktree, repo);
8912 if (error)
8913 goto done;
8914 continue;
8917 error = got_object_open_as_commit(&commit, repo,
8918 hle->commit_id);
8919 if (error)
8920 goto done;
8921 parent_ids = got_object_commit_get_parent_ids(commit);
8922 pid = SIMPLEQ_FIRST(parent_ids);
8924 error = got_worktree_histedit_merge_files(&merged_paths,
8925 worktree, fileindex, pid->id, hle->commit_id, repo,
8926 update_progress, &upa, check_cancelled, NULL);
8927 if (error)
8928 goto done;
8929 got_object_commit_close(commit);
8930 commit = NULL;
8932 print_update_progress_stats(&upa);
8933 if (upa.conflicts > 0)
8934 rebase_status = GOT_STATUS_CONFLICT;
8936 if (rebase_status == GOT_STATUS_CONFLICT) {
8937 error = show_rebase_merge_conflict(hle->commit_id,
8938 repo);
8939 if (error)
8940 goto done;
8941 got_worktree_rebase_pathlist_free(&merged_paths);
8942 break;
8945 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8946 char *id_str;
8947 error = got_object_id_str(&id_str, hle->commit_id);
8948 if (error)
8949 goto done;
8950 printf("Stopping histedit for amending commit %s\n",
8951 id_str);
8952 free(id_str);
8953 got_worktree_rebase_pathlist_free(&merged_paths);
8954 error = got_worktree_histedit_postpone(worktree,
8955 fileindex);
8956 goto done;
8959 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8960 error = histedit_skip_commit(hle, worktree, repo);
8961 if (error)
8962 goto done;
8963 continue;
8966 error = histedit_commit(&merged_paths, worktree, fileindex,
8967 tmp_branch, hle, repo);
8968 got_worktree_rebase_pathlist_free(&merged_paths);
8969 if (error)
8970 goto done;
8973 if (rebase_status == GOT_STATUS_CONFLICT) {
8974 error = got_worktree_histedit_postpone(worktree, fileindex);
8975 if (error)
8976 goto done;
8977 error = got_error_msg(GOT_ERR_CONFLICTS,
8978 "conflicts must be resolved before histedit can continue");
8979 } else
8980 error = histedit_complete(worktree, fileindex, tmp_branch,
8981 branch, repo);
8982 done:
8983 got_object_id_queue_free(&commits);
8984 histedit_free_list(&histedit_cmds);
8985 free(head_commit_id);
8986 free(base_commit_id);
8987 free(resume_commit_id);
8988 if (commit)
8989 got_object_commit_close(commit);
8990 if (branch)
8991 got_ref_close(branch);
8992 if (tmp_branch)
8993 got_ref_close(tmp_branch);
8994 if (worktree)
8995 got_worktree_close(worktree);
8996 if (repo)
8997 got_repo_close(repo);
8998 return error;
9001 __dead static void
9002 usage_integrate(void)
9004 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9005 exit(1);
9008 static const struct got_error *
9009 cmd_integrate(int argc, char *argv[])
9011 const struct got_error *error = NULL;
9012 struct got_repository *repo = NULL;
9013 struct got_worktree *worktree = NULL;
9014 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9015 const char *branch_arg = NULL;
9016 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9017 struct got_fileindex *fileindex = NULL;
9018 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9019 int ch;
9020 struct got_update_progress_arg upa;
9022 while ((ch = getopt(argc, argv, "")) != -1) {
9023 switch (ch) {
9024 default:
9025 usage_integrate();
9026 /* NOTREACHED */
9030 argc -= optind;
9031 argv += optind;
9033 if (argc != 1)
9034 usage_integrate();
9035 branch_arg = argv[0];
9036 #ifndef PROFILE
9037 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9038 "unveil", NULL) == -1)
9039 err(1, "pledge");
9040 #endif
9041 cwd = getcwd(NULL, 0);
9042 if (cwd == NULL) {
9043 error = got_error_from_errno("getcwd");
9044 goto done;
9047 error = got_worktree_open(&worktree, cwd);
9048 if (error) {
9049 if (error->code == GOT_ERR_NOT_WORKTREE)
9050 error = wrap_not_worktree_error(error, "integrate",
9051 cwd);
9052 goto done;
9055 error = check_rebase_or_histedit_in_progress(worktree);
9056 if (error)
9057 goto done;
9059 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9060 NULL);
9061 if (error != NULL)
9062 goto done;
9064 error = apply_unveil(got_repo_get_path(repo), 0,
9065 got_worktree_get_root_path(worktree));
9066 if (error)
9067 goto done;
9069 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9070 error = got_error_from_errno("asprintf");
9071 goto done;
9074 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9075 &base_branch_ref, worktree, refname, repo);
9076 if (error)
9077 goto done;
9079 refname = strdup(got_ref_get_name(branch_ref));
9080 if (refname == NULL) {
9081 error = got_error_from_errno("strdup");
9082 got_worktree_integrate_abort(worktree, fileindex, repo,
9083 branch_ref, base_branch_ref);
9084 goto done;
9086 base_refname = strdup(got_ref_get_name(base_branch_ref));
9087 if (base_refname == NULL) {
9088 error = got_error_from_errno("strdup");
9089 got_worktree_integrate_abort(worktree, fileindex, repo,
9090 branch_ref, base_branch_ref);
9091 goto done;
9094 error = got_ref_resolve(&commit_id, repo, branch_ref);
9095 if (error)
9096 goto done;
9098 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9099 if (error)
9100 goto done;
9102 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9103 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9104 "specified branch has already been integrated");
9105 got_worktree_integrate_abort(worktree, fileindex, repo,
9106 branch_ref, base_branch_ref);
9107 goto done;
9110 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9111 if (error) {
9112 if (error->code == GOT_ERR_ANCESTRY)
9113 error = got_error(GOT_ERR_REBASE_REQUIRED);
9114 got_worktree_integrate_abort(worktree, fileindex, repo,
9115 branch_ref, base_branch_ref);
9116 goto done;
9119 memset(&upa, 0, sizeof(upa));
9120 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9121 branch_ref, base_branch_ref, update_progress, &upa,
9122 check_cancelled, NULL);
9123 if (error)
9124 goto done;
9126 printf("Integrated %s into %s\n", refname, base_refname);
9127 print_update_progress_stats(&upa);
9128 done:
9129 if (repo)
9130 got_repo_close(repo);
9131 if (worktree)
9132 got_worktree_close(worktree);
9133 free(cwd);
9134 free(base_commit_id);
9135 free(commit_id);
9136 free(refname);
9137 free(base_refname);
9138 return error;
9141 __dead static void
9142 usage_stage(void)
9144 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9145 "[-S] [file-path ...]\n",
9146 getprogname());
9147 exit(1);
9150 static const struct got_error *
9151 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9152 const char *path, struct got_object_id *blob_id,
9153 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9154 int dirfd, const char *de_name)
9156 const struct got_error *err = NULL;
9157 char *id_str = NULL;
9159 if (staged_status != GOT_STATUS_ADD &&
9160 staged_status != GOT_STATUS_MODIFY &&
9161 staged_status != GOT_STATUS_DELETE)
9162 return NULL;
9164 if (staged_status == GOT_STATUS_ADD ||
9165 staged_status == GOT_STATUS_MODIFY)
9166 err = got_object_id_str(&id_str, staged_blob_id);
9167 else
9168 err = got_object_id_str(&id_str, blob_id);
9169 if (err)
9170 return err;
9172 printf("%s %c %s\n", id_str, staged_status, path);
9173 free(id_str);
9174 return NULL;
9177 static const struct got_error *
9178 cmd_stage(int argc, char *argv[])
9180 const struct got_error *error = NULL;
9181 struct got_repository *repo = NULL;
9182 struct got_worktree *worktree = NULL;
9183 char *cwd = NULL;
9184 struct got_pathlist_head paths;
9185 struct got_pathlist_entry *pe;
9186 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9187 FILE *patch_script_file = NULL;
9188 const char *patch_script_path = NULL;
9189 struct choose_patch_arg cpa;
9191 TAILQ_INIT(&paths);
9193 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9194 switch (ch) {
9195 case 'l':
9196 list_stage = 1;
9197 break;
9198 case 'p':
9199 pflag = 1;
9200 break;
9201 case 'F':
9202 patch_script_path = optarg;
9203 break;
9204 case 'S':
9205 allow_bad_symlinks = 1;
9206 break;
9207 default:
9208 usage_stage();
9209 /* NOTREACHED */
9213 argc -= optind;
9214 argv += optind;
9216 #ifndef PROFILE
9217 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9218 "unveil", NULL) == -1)
9219 err(1, "pledge");
9220 #endif
9221 if (list_stage && (pflag || patch_script_path))
9222 errx(1, "-l option cannot be used with other options");
9223 if (patch_script_path && !pflag)
9224 errx(1, "-F option can only be used together with -p option");
9226 cwd = getcwd(NULL, 0);
9227 if (cwd == NULL) {
9228 error = got_error_from_errno("getcwd");
9229 goto done;
9232 error = got_worktree_open(&worktree, cwd);
9233 if (error) {
9234 if (error->code == GOT_ERR_NOT_WORKTREE)
9235 error = wrap_not_worktree_error(error, "stage", cwd);
9236 goto done;
9239 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9240 NULL);
9241 if (error != NULL)
9242 goto done;
9244 if (patch_script_path) {
9245 patch_script_file = fopen(patch_script_path, "r");
9246 if (patch_script_file == NULL) {
9247 error = got_error_from_errno2("fopen",
9248 patch_script_path);
9249 goto done;
9252 error = apply_unveil(got_repo_get_path(repo), 0,
9253 got_worktree_get_root_path(worktree));
9254 if (error)
9255 goto done;
9257 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9258 if (error)
9259 goto done;
9261 if (list_stage)
9262 error = got_worktree_status(worktree, &paths, repo,
9263 print_stage, NULL, check_cancelled, NULL);
9264 else {
9265 cpa.patch_script_file = patch_script_file;
9266 cpa.action = "stage";
9267 error = got_worktree_stage(worktree, &paths,
9268 pflag ? NULL : print_status, NULL,
9269 pflag ? choose_patch : NULL, &cpa,
9270 allow_bad_symlinks, repo);
9272 done:
9273 if (patch_script_file && fclose(patch_script_file) == EOF &&
9274 error == NULL)
9275 error = got_error_from_errno2("fclose", patch_script_path);
9276 if (repo)
9277 got_repo_close(repo);
9278 if (worktree)
9279 got_worktree_close(worktree);
9280 TAILQ_FOREACH(pe, &paths, entry)
9281 free((char *)pe->path);
9282 got_pathlist_free(&paths);
9283 free(cwd);
9284 return error;
9287 __dead static void
9288 usage_unstage(void)
9290 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9291 "[file-path ...]\n",
9292 getprogname());
9293 exit(1);
9297 static const struct got_error *
9298 cmd_unstage(int argc, char *argv[])
9300 const struct got_error *error = NULL;
9301 struct got_repository *repo = NULL;
9302 struct got_worktree *worktree = NULL;
9303 char *cwd = NULL;
9304 struct got_pathlist_head paths;
9305 struct got_pathlist_entry *pe;
9306 int ch, pflag = 0;
9307 struct got_update_progress_arg upa;
9308 FILE *patch_script_file = NULL;
9309 const char *patch_script_path = NULL;
9310 struct choose_patch_arg cpa;
9312 TAILQ_INIT(&paths);
9314 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9315 switch (ch) {
9316 case 'p':
9317 pflag = 1;
9318 break;
9319 case 'F':
9320 patch_script_path = optarg;
9321 break;
9322 default:
9323 usage_unstage();
9324 /* NOTREACHED */
9328 argc -= optind;
9329 argv += optind;
9331 #ifndef PROFILE
9332 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9333 "unveil", NULL) == -1)
9334 err(1, "pledge");
9335 #endif
9336 if (patch_script_path && !pflag)
9337 errx(1, "-F option can only be used together with -p option");
9339 cwd = getcwd(NULL, 0);
9340 if (cwd == NULL) {
9341 error = got_error_from_errno("getcwd");
9342 goto done;
9345 error = got_worktree_open(&worktree, cwd);
9346 if (error) {
9347 if (error->code == GOT_ERR_NOT_WORKTREE)
9348 error = wrap_not_worktree_error(error, "unstage", cwd);
9349 goto done;
9352 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9353 NULL);
9354 if (error != NULL)
9355 goto done;
9357 if (patch_script_path) {
9358 patch_script_file = fopen(patch_script_path, "r");
9359 if (patch_script_file == NULL) {
9360 error = got_error_from_errno2("fopen",
9361 patch_script_path);
9362 goto done;
9366 error = apply_unveil(got_repo_get_path(repo), 0,
9367 got_worktree_get_root_path(worktree));
9368 if (error)
9369 goto done;
9371 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9372 if (error)
9373 goto done;
9375 cpa.patch_script_file = patch_script_file;
9376 cpa.action = "unstage";
9377 memset(&upa, 0, sizeof(upa));
9378 error = got_worktree_unstage(worktree, &paths, update_progress,
9379 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9380 if (!error)
9381 print_update_progress_stats(&upa);
9382 done:
9383 if (patch_script_file && fclose(patch_script_file) == EOF &&
9384 error == NULL)
9385 error = got_error_from_errno2("fclose", patch_script_path);
9386 if (repo)
9387 got_repo_close(repo);
9388 if (worktree)
9389 got_worktree_close(worktree);
9390 TAILQ_FOREACH(pe, &paths, entry)
9391 free((char *)pe->path);
9392 got_pathlist_free(&paths);
9393 free(cwd);
9394 return error;
9397 __dead static void
9398 usage_cat(void)
9400 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9401 "arg1 [arg2 ...]\n", getprogname());
9402 exit(1);
9405 static const struct got_error *
9406 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9408 const struct got_error *err;
9409 struct got_blob_object *blob;
9411 err = got_object_open_as_blob(&blob, repo, id, 8192);
9412 if (err)
9413 return err;
9415 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9416 got_object_blob_close(blob);
9417 return err;
9420 static const struct got_error *
9421 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9423 const struct got_error *err;
9424 struct got_tree_object *tree;
9425 int nentries, i;
9427 err = got_object_open_as_tree(&tree, repo, id);
9428 if (err)
9429 return err;
9431 nentries = got_object_tree_get_nentries(tree);
9432 for (i = 0; i < nentries; i++) {
9433 struct got_tree_entry *te;
9434 char *id_str;
9435 if (sigint_received || sigpipe_received)
9436 break;
9437 te = got_object_tree_get_entry(tree, i);
9438 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9439 if (err)
9440 break;
9441 fprintf(outfile, "%s %.7o %s\n", id_str,
9442 got_tree_entry_get_mode(te),
9443 got_tree_entry_get_name(te));
9444 free(id_str);
9447 got_object_tree_close(tree);
9448 return err;
9451 static const struct got_error *
9452 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9454 const struct got_error *err;
9455 struct got_commit_object *commit;
9456 const struct got_object_id_queue *parent_ids;
9457 struct got_object_qid *pid;
9458 char *id_str = NULL;
9459 const char *logmsg = NULL;
9461 err = got_object_open_as_commit(&commit, repo, id);
9462 if (err)
9463 return err;
9465 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9466 if (err)
9467 goto done;
9469 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9470 parent_ids = got_object_commit_get_parent_ids(commit);
9471 fprintf(outfile, "numparents %d\n",
9472 got_object_commit_get_nparents(commit));
9473 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9474 char *pid_str;
9475 err = got_object_id_str(&pid_str, pid->id);
9476 if (err)
9477 goto done;
9478 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9479 free(pid_str);
9481 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9482 got_object_commit_get_author(commit),
9483 (long long)got_object_commit_get_author_time(commit));
9485 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9486 got_object_commit_get_author(commit),
9487 (long long)got_object_commit_get_committer_time(commit));
9489 logmsg = got_object_commit_get_logmsg_raw(commit);
9490 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9491 fprintf(outfile, "%s", logmsg);
9492 done:
9493 free(id_str);
9494 got_object_commit_close(commit);
9495 return err;
9498 static const struct got_error *
9499 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9501 const struct got_error *err;
9502 struct got_tag_object *tag;
9503 char *id_str = NULL;
9504 const char *tagmsg = NULL;
9506 err = got_object_open_as_tag(&tag, repo, id);
9507 if (err)
9508 return err;
9510 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9511 if (err)
9512 goto done;
9514 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9516 switch (got_object_tag_get_object_type(tag)) {
9517 case GOT_OBJ_TYPE_BLOB:
9518 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9519 GOT_OBJ_LABEL_BLOB);
9520 break;
9521 case GOT_OBJ_TYPE_TREE:
9522 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9523 GOT_OBJ_LABEL_TREE);
9524 break;
9525 case GOT_OBJ_TYPE_COMMIT:
9526 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9527 GOT_OBJ_LABEL_COMMIT);
9528 break;
9529 case GOT_OBJ_TYPE_TAG:
9530 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9531 GOT_OBJ_LABEL_TAG);
9532 break;
9533 default:
9534 break;
9537 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9538 got_object_tag_get_name(tag));
9540 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9541 got_object_tag_get_tagger(tag),
9542 (long long)got_object_tag_get_tagger_time(tag));
9544 tagmsg = got_object_tag_get_message(tag);
9545 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9546 fprintf(outfile, "%s", tagmsg);
9547 done:
9548 free(id_str);
9549 got_object_tag_close(tag);
9550 return err;
9553 static const struct got_error *
9554 cmd_cat(int argc, char *argv[])
9556 const struct got_error *error;
9557 struct got_repository *repo = NULL;
9558 struct got_worktree *worktree = NULL;
9559 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9560 const char *commit_id_str = NULL;
9561 struct got_object_id *id = NULL, *commit_id = NULL;
9562 int ch, obj_type, i, force_path = 0;
9564 #ifndef PROFILE
9565 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9566 NULL) == -1)
9567 err(1, "pledge");
9568 #endif
9570 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9571 switch (ch) {
9572 case 'c':
9573 commit_id_str = optarg;
9574 break;
9575 case 'r':
9576 repo_path = realpath(optarg, NULL);
9577 if (repo_path == NULL)
9578 return got_error_from_errno2("realpath",
9579 optarg);
9580 got_path_strip_trailing_slashes(repo_path);
9581 break;
9582 case 'P':
9583 force_path = 1;
9584 break;
9585 default:
9586 usage_cat();
9587 /* NOTREACHED */
9591 argc -= optind;
9592 argv += optind;
9594 cwd = getcwd(NULL, 0);
9595 if (cwd == NULL) {
9596 error = got_error_from_errno("getcwd");
9597 goto done;
9599 error = got_worktree_open(&worktree, cwd);
9600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9601 goto done;
9602 if (worktree) {
9603 if (repo_path == NULL) {
9604 repo_path = strdup(
9605 got_worktree_get_repo_path(worktree));
9606 if (repo_path == NULL) {
9607 error = got_error_from_errno("strdup");
9608 goto done;
9613 if (repo_path == NULL) {
9614 repo_path = getcwd(NULL, 0);
9615 if (repo_path == NULL)
9616 return got_error_from_errno("getcwd");
9619 error = got_repo_open(&repo, repo_path, NULL);
9620 free(repo_path);
9621 if (error != NULL)
9622 goto done;
9624 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9625 if (error)
9626 goto done;
9628 if (commit_id_str == NULL)
9629 commit_id_str = GOT_REF_HEAD;
9630 error = got_repo_match_object_id(&commit_id, NULL,
9631 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9632 if (error)
9633 goto done;
9635 for (i = 0; i < argc; i++) {
9636 if (force_path) {
9637 error = got_object_id_by_path(&id, repo, commit_id,
9638 argv[i]);
9639 if (error)
9640 break;
9641 } else {
9642 error = got_repo_match_object_id(&id, &label, argv[i],
9643 GOT_OBJ_TYPE_ANY, 0, repo);
9644 if (error) {
9645 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9646 error->code != GOT_ERR_NOT_REF)
9647 break;
9648 error = got_object_id_by_path(&id, repo,
9649 commit_id, argv[i]);
9650 if (error)
9651 break;
9655 error = got_object_get_type(&obj_type, repo, id);
9656 if (error)
9657 break;
9659 switch (obj_type) {
9660 case GOT_OBJ_TYPE_BLOB:
9661 error = cat_blob(id, repo, stdout);
9662 break;
9663 case GOT_OBJ_TYPE_TREE:
9664 error = cat_tree(id, repo, stdout);
9665 break;
9666 case GOT_OBJ_TYPE_COMMIT:
9667 error = cat_commit(id, repo, stdout);
9668 break;
9669 case GOT_OBJ_TYPE_TAG:
9670 error = cat_tag(id, repo, stdout);
9671 break;
9672 default:
9673 error = got_error(GOT_ERR_OBJ_TYPE);
9674 break;
9676 if (error)
9677 break;
9678 free(label);
9679 label = NULL;
9680 free(id);
9681 id = NULL;
9683 done:
9684 free(label);
9685 free(id);
9686 free(commit_id);
9687 if (worktree)
9688 got_worktree_close(worktree);
9689 if (repo) {
9690 const struct got_error *repo_error;
9691 repo_error = got_repo_close(repo);
9692 if (error == NULL)
9693 error = repo_error;
9695 return error;
9698 __dead static void
9699 usage_info(void)
9701 fprintf(stderr, "usage: %s info [path ...]\n",
9702 getprogname());
9703 exit(1);
9706 static const struct got_error *
9707 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9708 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9709 struct got_object_id *commit_id)
9711 const struct got_error *err = NULL;
9712 char *id_str = NULL;
9713 char datebuf[128];
9714 struct tm mytm, *tm;
9715 struct got_pathlist_head *paths = arg;
9716 struct got_pathlist_entry *pe;
9719 * Clear error indication from any of the path arguments which
9720 * would cause this file index entry to be displayed.
9722 TAILQ_FOREACH(pe, paths, entry) {
9723 if (got_path_cmp(path, pe->path, strlen(path),
9724 pe->path_len) == 0 ||
9725 got_path_is_child(path, pe->path, pe->path_len))
9726 pe->data = NULL; /* no error */
9729 printf(GOT_COMMIT_SEP_STR);
9730 if (S_ISLNK(mode))
9731 printf("symlink: %s\n", path);
9732 else if (S_ISREG(mode)) {
9733 printf("file: %s\n", path);
9734 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9735 } else if (S_ISDIR(mode))
9736 printf("directory: %s\n", path);
9737 else
9738 printf("something: %s\n", path);
9740 tm = localtime_r(&mtime, &mytm);
9741 if (tm == NULL)
9742 return NULL;
9743 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9744 return got_error(GOT_ERR_NO_SPACE);
9745 printf("timestamp: %s\n", datebuf);
9747 if (blob_id) {
9748 err = got_object_id_str(&id_str, blob_id);
9749 if (err)
9750 return err;
9751 printf("based on blob: %s\n", id_str);
9752 free(id_str);
9755 if (staged_blob_id) {
9756 err = got_object_id_str(&id_str, staged_blob_id);
9757 if (err)
9758 return err;
9759 printf("based on staged blob: %s\n", id_str);
9760 free(id_str);
9763 if (commit_id) {
9764 err = got_object_id_str(&id_str, commit_id);
9765 if (err)
9766 return err;
9767 printf("based on commit: %s\n", id_str);
9768 free(id_str);
9771 return NULL;
9774 static const struct got_error *
9775 cmd_info(int argc, char *argv[])
9777 const struct got_error *error = NULL;
9778 struct got_worktree *worktree = NULL;
9779 char *cwd = NULL, *id_str = NULL;
9780 struct got_pathlist_head paths;
9781 struct got_pathlist_entry *pe;
9782 char *uuidstr = NULL;
9783 int ch, show_files = 0;
9785 TAILQ_INIT(&paths);
9787 while ((ch = getopt(argc, argv, "")) != -1) {
9788 switch (ch) {
9789 default:
9790 usage_info();
9791 /* NOTREACHED */
9795 argc -= optind;
9796 argv += optind;
9798 #ifndef PROFILE
9799 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9800 NULL) == -1)
9801 err(1, "pledge");
9802 #endif
9803 cwd = getcwd(NULL, 0);
9804 if (cwd == NULL) {
9805 error = got_error_from_errno("getcwd");
9806 goto done;
9809 error = got_worktree_open(&worktree, cwd);
9810 if (error) {
9811 if (error->code == GOT_ERR_NOT_WORKTREE)
9812 error = wrap_not_worktree_error(error, "status", cwd);
9813 goto done;
9816 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9817 if (error)
9818 goto done;
9820 if (argc >= 1) {
9821 error = get_worktree_paths_from_argv(&paths, argc, argv,
9822 worktree);
9823 if (error)
9824 goto done;
9825 show_files = 1;
9828 error = got_object_id_str(&id_str,
9829 got_worktree_get_base_commit_id(worktree));
9830 if (error)
9831 goto done;
9833 error = got_worktree_get_uuid(&uuidstr, worktree);
9834 if (error)
9835 goto done;
9837 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9838 printf("work tree base commit: %s\n", id_str);
9839 printf("work tree path prefix: %s\n",
9840 got_worktree_get_path_prefix(worktree));
9841 printf("work tree branch reference: %s\n",
9842 got_worktree_get_head_ref_name(worktree));
9843 printf("work tree UUID: %s\n", uuidstr);
9844 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9846 if (show_files) {
9847 struct got_pathlist_entry *pe;
9848 TAILQ_FOREACH(pe, &paths, entry) {
9849 if (pe->path_len == 0)
9850 continue;
9852 * Assume this path will fail. This will be corrected
9853 * in print_path_info() in case the path does suceeed.
9855 pe->data = (void *)got_error_path(pe->path,
9856 GOT_ERR_BAD_PATH);
9858 error = got_worktree_path_info(worktree, &paths,
9859 print_path_info, &paths, check_cancelled, NULL);
9860 if (error)
9861 goto done;
9862 TAILQ_FOREACH(pe, &paths, entry) {
9863 if (pe->data != NULL) {
9864 error = pe->data; /* bad path */
9865 break;
9869 done:
9870 TAILQ_FOREACH(pe, &paths, entry)
9871 free((char *)pe->path);
9872 got_pathlist_free(&paths);
9873 free(cwd);
9874 free(id_str);
9875 free(uuidstr);
9876 return error;