Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 int i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0 }
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag, 1);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 1;
217 optreset = 1;
219 if (Vflag) {
220 got_version_print_str();
221 return 0;
224 if (argc <= 0)
225 usage(hflag, hflag ? 0 : 1);
227 signal(SIGINT, catch_sigint);
228 signal(SIGPIPE, catch_sigpipe);
230 for (i = 0; i < nitems(got_commands); i++) {
231 const struct got_error *error;
233 cmd = &got_commands[i];
235 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
236 strcmp(cmd->cmd_alias, argv[0]) != 0)
237 continue;
239 if (hflag)
240 got_commands[i].cmd_usage();
242 error = got_commands[i].cmd_main(argc, argv);
243 if (error && error->code != GOT_ERR_CANCELLED &&
244 error->code != GOT_ERR_PRIVSEP_EXIT &&
245 !(sigpipe_received &&
246 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
247 !(sigint_received &&
248 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
249 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
250 return 1;
253 return 0;
256 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
257 list_commands(stderr);
258 return 1;
261 __dead static void
262 usage(int hflag, int status)
264 FILE *fp = (status == 0) ? stdout : stderr;
266 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
267 getprogname());
268 if (hflag)
269 list_commands(fp);
270 exit(status);
273 static const struct got_error *
274 get_editor(char **abspath)
276 const struct got_error *err = NULL;
277 const char *editor;
279 *abspath = NULL;
281 editor = getenv("VISUAL");
282 if (editor == NULL)
283 editor = getenv("EDITOR");
285 if (editor) {
286 err = got_path_find_prog(abspath, editor);
287 if (err)
288 return err;
291 if (*abspath == NULL) {
292 *abspath = strdup("/bin/ed");
293 if (*abspath == NULL)
294 return got_error_from_errno("strdup");
297 return NULL;
300 static const struct got_error *
301 apply_unveil(const char *repo_path, int repo_read_only,
302 const char *worktree_path)
304 const struct got_error *err;
306 #ifdef PROFILE
307 if (unveil("gmon.out", "rwc") != 0)
308 return got_error_from_errno2("unveil", "gmon.out");
309 #endif
310 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
311 return got_error_from_errno2("unveil", repo_path);
313 if (worktree_path && unveil(worktree_path, "rwc") != 0)
314 return got_error_from_errno2("unveil", worktree_path);
316 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
317 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
319 err = got_privsep_unveil_exec_helpers();
320 if (err != NULL)
321 return err;
323 if (unveil(NULL, NULL) != 0)
324 return got_error_from_errno("unveil");
326 return NULL;
329 __dead static void
330 usage_init(void)
332 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
333 exit(1);
336 static const struct got_error *
337 cmd_init(int argc, char *argv[])
339 const struct got_error *error = NULL;
340 char *repo_path = NULL;
341 int ch;
343 while ((ch = getopt(argc, argv, "")) != -1) {
344 switch (ch) {
345 default:
346 usage_init();
347 /* NOTREACHED */
351 argc -= optind;
352 argv += optind;
354 #ifndef PROFILE
355 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
356 err(1, "pledge");
357 #endif
358 if (argc != 1)
359 usage_init();
361 repo_path = strdup(argv[0]);
362 if (repo_path == NULL)
363 return got_error_from_errno("strdup");
365 got_path_strip_trailing_slashes(repo_path);
367 error = got_path_mkdir(repo_path);
368 if (error &&
369 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
370 goto done;
372 error = apply_unveil(repo_path, 0, NULL);
373 if (error)
374 goto done;
376 error = got_repo_init(repo_path);
377 done:
378 free(repo_path);
379 return error;
382 __dead static void
383 usage_import(void)
385 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
386 "[-r repository-path] [-I pattern] path\n", getprogname());
387 exit(1);
390 int
391 spawn_editor(const char *editor, const char *file)
393 pid_t pid;
394 sig_t sighup, sigint, sigquit;
395 int st = -1;
397 sighup = signal(SIGHUP, SIG_IGN);
398 sigint = signal(SIGINT, SIG_IGN);
399 sigquit = signal(SIGQUIT, SIG_IGN);
401 switch (pid = fork()) {
402 case -1:
403 goto doneediting;
404 case 0:
405 execl(editor, editor, file, (char *)NULL);
406 _exit(127);
409 while (waitpid(pid, &st, 0) == -1)
410 if (errno != EINTR)
411 break;
413 doneediting:
414 (void)signal(SIGHUP, sighup);
415 (void)signal(SIGINT, sigint);
416 (void)signal(SIGQUIT, sigquit);
418 if (!WIFEXITED(st)) {
419 errno = EINTR;
420 return -1;
423 return WEXITSTATUS(st);
426 static const struct got_error *
427 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
428 const char *initial_content, size_t initial_content_len)
430 const struct got_error *err = NULL;
431 char *line = NULL;
432 size_t linesize = 0;
433 ssize_t linelen;
434 struct stat st, st2;
435 FILE *fp = NULL;
436 size_t len, logmsg_len;
437 char *initial_content_stripped = NULL, *buf = NULL, *s;
439 *logmsg = NULL;
441 if (stat(logmsg_path, &st) == -1)
442 return got_error_from_errno2("stat", logmsg_path);
444 if (spawn_editor(editor, logmsg_path) == -1)
445 return got_error_from_errno("failed spawning editor");
447 if (stat(logmsg_path, &st2) == -1)
448 return got_error_from_errno("stat");
450 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
451 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
452 "no changes made to commit message, aborting");
454 /*
455 * Set up a stripped version of the initial content without comments
456 * and blank lines. We need this in order to check if the message
457 * has in fact been edited.
458 */
459 initial_content_stripped = malloc(initial_content_len + 1);
460 if (initial_content_stripped == NULL)
461 return got_error_from_errno("malloc");
462 initial_content_stripped[0] = '\0';
464 buf = strdup(initial_content);
465 if (buf == NULL) {
466 err = got_error_from_errno("strdup");
467 goto done;
469 s = buf;
470 len = 0;
471 while ((line = strsep(&s, "\n")) != NULL) {
472 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
473 continue; /* remove comments and leading empty lines */
474 len = strlcat(initial_content_stripped, line,
475 initial_content_len + 1);
476 if (len >= initial_content_len + 1) {
477 err = got_error(GOT_ERR_NO_SPACE);
478 goto done;
481 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
482 initial_content_stripped[len - 1] = '\0';
483 len--;
486 logmsg_len = st2.st_size;
487 *logmsg = malloc(logmsg_len + 1);
488 if (*logmsg == NULL)
489 return got_error_from_errno("malloc");
490 (*logmsg)[0] = '\0';
492 fp = fopen(logmsg_path, "r");
493 if (fp == NULL) {
494 err = got_error_from_errno("fopen");
495 goto done;
498 len = 0;
499 while ((linelen = getline(&line, &linesize, fp)) != -1) {
500 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
501 continue; /* remove comments and leading empty lines */
502 len = strlcat(*logmsg, line, logmsg_len + 1);
503 if (len >= logmsg_len + 1) {
504 err = got_error(GOT_ERR_NO_SPACE);
505 goto done;
508 free(line);
509 if (ferror(fp)) {
510 err = got_ferror(fp, GOT_ERR_IO);
511 goto done;
513 while (len > 0 && (*logmsg)[len - 1] == '\n') {
514 (*logmsg)[len - 1] = '\0';
515 len--;
518 if (len == 0) {
519 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
520 "commit message cannot be empty, aborting");
521 goto done;
523 if (strcmp(*logmsg, initial_content_stripped) == 0)
524 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
525 "no changes made to commit message, aborting");
526 done:
527 free(initial_content_stripped);
528 free(buf);
529 if (fp && fclose(fp) == EOF && err == NULL)
530 err = got_error_from_errno("fclose");
531 if (err) {
532 free(*logmsg);
533 *logmsg = NULL;
535 return err;
538 static const struct got_error *
539 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
540 const char *path_dir, const char *branch_name)
542 char *initial_content = NULL;
543 const struct got_error *err = NULL;
544 int initial_content_len;
545 int fd = -1;
547 initial_content_len = asprintf(&initial_content,
548 "\n# %s to be imported to branch %s\n", path_dir,
549 branch_name);
550 if (initial_content_len == -1)
551 return got_error_from_errno("asprintf");
553 err = got_opentemp_named_fd(logmsg_path, &fd,
554 GOT_TMPDIR_STR "/got-importmsg");
555 if (err)
556 goto done;
558 if (write(fd, initial_content, initial_content_len) == -1) {
559 err = got_error_from_errno2("write", *logmsg_path);
560 goto done;
563 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
564 initial_content_len);
565 done:
566 if (fd != -1 && close(fd) == -1 && err == NULL)
567 err = got_error_from_errno2("close", *logmsg_path);
568 free(initial_content);
569 if (err) {
570 free(*logmsg_path);
571 *logmsg_path = NULL;
573 return err;
576 static const struct got_error *
577 import_progress(void *arg, const char *path)
579 printf("A %s\n", path);
580 return NULL;
583 static const struct got_error *
584 get_author(char **author, struct got_repository *repo,
585 struct got_worktree *worktree)
587 const struct got_error *err = NULL;
588 const char *got_author = NULL, *name, *email;
589 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
591 *author = NULL;
593 if (worktree)
594 worktree_conf = got_worktree_get_gotconfig(worktree);
595 repo_conf = got_repo_get_gotconfig(repo);
597 /*
598 * Priority of potential author information sources, from most
599 * significant to least significant:
600 * 1) work tree's .got/got.conf file
601 * 2) repository's got.conf file
602 * 3) repository's git config file
603 * 4) environment variables
604 * 5) global git config files (in user's home directory or /etc)
605 */
607 if (worktree_conf)
608 got_author = got_gotconfig_get_author(worktree_conf);
609 if (got_author == NULL)
610 got_author = got_gotconfig_get_author(repo_conf);
611 if (got_author == NULL) {
612 name = got_repo_get_gitconfig_author_name(repo);
613 email = got_repo_get_gitconfig_author_email(repo);
614 if (name && email) {
615 if (asprintf(author, "%s <%s>", name, email) == -1)
616 return got_error_from_errno("asprintf");
617 return NULL;
620 got_author = getenv("GOT_AUTHOR");
621 if (got_author == NULL) {
622 name = got_repo_get_global_gitconfig_author_name(repo);
623 email = got_repo_get_global_gitconfig_author_email(
624 repo);
625 if (name && email) {
626 if (asprintf(author, "%s <%s>", name, email)
627 == -1)
628 return got_error_from_errno("asprintf");
629 return NULL;
631 /* TODO: Look up user in password database? */
632 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
636 *author = strdup(got_author);
637 if (*author == NULL)
638 return got_error_from_errno("strdup");
640 /*
641 * Really dumb email address check; we're only doing this to
642 * avoid git's object parser breaking on commits we create.
643 */
644 while (*got_author && *got_author != '<')
645 got_author++;
646 if (*got_author != '<') {
647 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
648 goto done;
650 while (*got_author && *got_author != '@')
651 got_author++;
652 if (*got_author != '@') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '>')
657 got_author++;
658 if (*got_author != '>')
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 done:
661 if (err) {
662 free(*author);
663 *author = NULL;
665 return err;
668 static const struct got_error *
669 get_gitconfig_path(char **gitconfig_path)
671 const char *homedir = getenv("HOME");
673 *gitconfig_path = NULL;
674 if (homedir) {
675 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
676 return got_error_from_errno("asprintf");
679 return NULL;
682 static const struct got_error *
683 cmd_import(int argc, char *argv[])
685 const struct got_error *error = NULL;
686 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
687 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
688 const char *branch_name = "main";
689 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
690 struct got_repository *repo = NULL;
691 struct got_reference *branch_ref = NULL, *head_ref = NULL;
692 struct got_object_id *new_commit_id = NULL;
693 int ch;
694 struct got_pathlist_head ignores;
695 struct got_pathlist_entry *pe;
696 int preserve_logmsg = 0;
698 TAILQ_INIT(&ignores);
700 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
701 switch (ch) {
702 case 'b':
703 branch_name = optarg;
704 break;
705 case 'm':
706 logmsg = strdup(optarg);
707 if (logmsg == NULL) {
708 error = got_error_from_errno("strdup");
709 goto done;
711 break;
712 case 'r':
713 repo_path = realpath(optarg, NULL);
714 if (repo_path == NULL) {
715 error = got_error_from_errno2("realpath",
716 optarg);
717 goto done;
719 break;
720 case 'I':
721 if (optarg[0] == '\0')
722 break;
723 error = got_pathlist_insert(&pe, &ignores, optarg,
724 NULL);
725 if (error)
726 goto done;
727 break;
728 default:
729 usage_import();
730 /* NOTREACHED */
734 argc -= optind;
735 argv += optind;
737 #ifndef PROFILE
738 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
739 "unveil",
740 NULL) == -1)
741 err(1, "pledge");
742 #endif
743 if (argc != 1)
744 usage_import();
746 if (repo_path == NULL) {
747 repo_path = getcwd(NULL, 0);
748 if (repo_path == NULL)
749 return got_error_from_errno("getcwd");
751 got_path_strip_trailing_slashes(repo_path);
752 error = get_gitconfig_path(&gitconfig_path);
753 if (error)
754 goto done;
755 error = got_repo_open(&repo, repo_path, gitconfig_path);
756 if (error)
757 goto done;
759 error = get_author(&author, repo, NULL);
760 if (error)
761 return error;
763 /*
764 * Don't let the user create a branch name with a leading '-'.
765 * While technically a valid reference name, this case is usually
766 * an unintended typo.
767 */
768 if (branch_name[0] == '-')
769 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
772 error = got_error_from_errno("asprintf");
773 goto done;
776 error = got_ref_open(&branch_ref, repo, refname, 0);
777 if (error) {
778 if (error->code != GOT_ERR_NOT_REF)
779 goto done;
780 } else {
781 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
782 "import target branch already exists");
783 goto done;
786 path_dir = realpath(argv[0], NULL);
787 if (path_dir == NULL) {
788 error = got_error_from_errno2("realpath", argv[0]);
789 goto done;
791 got_path_strip_trailing_slashes(path_dir);
793 /*
794 * unveil(2) traverses exec(2); if an editor is used we have
795 * to apply unveil after the log message has been written.
796 */
797 if (logmsg == NULL || strlen(logmsg) == 0) {
798 error = get_editor(&editor);
799 if (error)
800 goto done;
801 free(logmsg);
802 error = collect_import_msg(&logmsg, &logmsg_path, editor,
803 path_dir, refname);
804 if (error) {
805 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
806 logmsg_path != NULL)
807 preserve_logmsg = 1;
808 goto done;
812 if (unveil(path_dir, "r") != 0) {
813 error = got_error_from_errno2("unveil", path_dir);
814 if (logmsg_path)
815 preserve_logmsg = 1;
816 goto done;
819 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
820 if (error) {
821 if (logmsg_path)
822 preserve_logmsg = 1;
823 goto done;
826 error = got_repo_import(&new_commit_id, path_dir, logmsg,
827 author, &ignores, repo, import_progress, NULL);
828 if (error) {
829 if (logmsg_path)
830 preserve_logmsg = 1;
831 goto done;
834 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
835 if (error) {
836 if (logmsg_path)
837 preserve_logmsg = 1;
838 goto done;
841 error = got_ref_write(branch_ref, repo);
842 if (error) {
843 if (logmsg_path)
844 preserve_logmsg = 1;
845 goto done;
848 error = got_object_id_str(&id_str, new_commit_id);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
856 if (error) {
857 if (error->code != GOT_ERR_NOT_REF) {
858 if (logmsg_path)
859 preserve_logmsg = 1;
860 goto done;
863 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
864 branch_ref);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_write(head_ref, repo);
872 if (error) {
873 if (logmsg_path)
874 preserve_logmsg = 1;
875 goto done;
879 printf("Created branch %s with commit %s\n",
880 got_ref_get_name(branch_ref), id_str);
881 done:
882 if (preserve_logmsg) {
883 fprintf(stderr, "%s: log message preserved in %s\n",
884 getprogname(), logmsg_path);
885 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
886 error = got_error_from_errno2("unlink", logmsg_path);
887 free(logmsg);
888 free(logmsg_path);
889 free(repo_path);
890 free(editor);
891 free(refname);
892 free(new_commit_id);
893 free(id_str);
894 free(author);
895 free(gitconfig_path);
896 if (branch_ref)
897 got_ref_close(branch_ref);
898 if (head_ref)
899 got_ref_close(head_ref);
900 return error;
903 __dead static void
904 usage_clone(void)
906 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
907 "[-R reference] repository-url [directory]\n", getprogname());
908 exit(1);
911 struct got_fetch_progress_arg {
912 char last_scaled_size[FMT_SCALED_STRSIZE];
913 int last_p_indexed;
914 int last_p_resolved;
915 int verbosity;
917 struct got_repository *repo;
919 int create_configs;
920 int configs_created;
921 struct {
922 struct got_pathlist_head *symrefs;
923 struct got_pathlist_head *wanted_branches;
924 const char *proto;
925 const char *host;
926 const char *port;
927 const char *remote_repo_path;
928 const char *git_url;
929 int fetch_all_branches;
930 int mirror_references;
931 } config_info;
932 };
934 /* XXX forward declaration */
935 static const struct got_error *
936 create_config_files(const char *proto, const char *host, const char *port,
937 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
938 int mirror_references, struct got_pathlist_head *symrefs,
939 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
941 static const struct got_error *
942 fetch_progress(void *arg, const char *message, off_t packfile_size,
943 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
945 const struct got_error *err = NULL;
946 struct got_fetch_progress_arg *a = arg;
947 char scaled_size[FMT_SCALED_STRSIZE];
948 int p_indexed, p_resolved;
949 int print_size = 0, print_indexed = 0, print_resolved = 0;
951 /*
952 * In order to allow a failed clone to be resumed with 'got fetch'
953 * we try to create configuration files as soon as possible.
954 * Once the server has sent information about its default branch
955 * we have all required information.
956 */
957 if (a->create_configs && !a->configs_created &&
958 !TAILQ_EMPTY(a->config_info.symrefs)) {
959 err = create_config_files(a->config_info.proto,
960 a->config_info.host, a->config_info.port,
961 a->config_info.remote_repo_path,
962 a->config_info.git_url,
963 a->config_info.fetch_all_branches,
964 a->config_info.mirror_references,
965 a->config_info.symrefs,
966 a->config_info.wanted_branches, a->repo);
967 if (err)
968 return err;
969 a->configs_created = 1;
972 if (a->verbosity < 0)
973 return NULL;
975 if (message && message[0] != '\0') {
976 printf("\rserver: %s", message);
977 fflush(stdout);
978 return NULL;
981 if (packfile_size > 0 || nobj_indexed > 0) {
982 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
983 (a->last_scaled_size[0] == '\0' ||
984 strcmp(scaled_size, a->last_scaled_size)) != 0) {
985 print_size = 1;
986 if (strlcpy(a->last_scaled_size, scaled_size,
987 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
988 return got_error(GOT_ERR_NO_SPACE);
990 if (nobj_indexed > 0) {
991 p_indexed = (nobj_indexed * 100) / nobj_total;
992 if (p_indexed != a->last_p_indexed) {
993 a->last_p_indexed = p_indexed;
994 print_indexed = 1;
995 print_size = 1;
998 if (nobj_resolved > 0) {
999 p_resolved = (nobj_resolved * 100) /
1000 (nobj_total - nobj_loose);
1001 if (p_resolved != a->last_p_resolved) {
1002 a->last_p_resolved = p_resolved;
1003 print_resolved = 1;
1004 print_indexed = 1;
1005 print_size = 1;
1010 if (print_size || print_indexed || print_resolved)
1011 printf("\r");
1012 if (print_size)
1013 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1014 if (print_indexed)
1015 printf("; indexing %d%%", p_indexed);
1016 if (print_resolved)
1017 printf("; resolving deltas %d%%", p_resolved);
1018 if (print_size || print_indexed || print_resolved)
1019 fflush(stdout);
1021 return NULL;
1024 static const struct got_error *
1025 create_symref(const char *refname, struct got_reference *target_ref,
1026 int verbosity, struct got_repository *repo)
1028 const struct got_error *err;
1029 struct got_reference *head_symref;
1031 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1032 if (err)
1033 return err;
1035 err = got_ref_write(head_symref, repo);
1036 if (err == NULL && verbosity > 0) {
1037 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1038 got_ref_get_name(target_ref));
1040 got_ref_close(head_symref);
1041 return err;
1044 static const struct got_error *
1045 list_remote_refs(struct got_pathlist_head *symrefs,
1046 struct got_pathlist_head *refs)
1048 const struct got_error *err;
1049 struct got_pathlist_entry *pe;
1051 TAILQ_FOREACH(pe, symrefs, entry) {
1052 const char *refname = pe->path;
1053 const char *targetref = pe->data;
1055 printf("%s: %s\n", refname, targetref);
1058 TAILQ_FOREACH(pe, refs, entry) {
1059 const char *refname = pe->path;
1060 struct got_object_id *id = pe->data;
1061 char *id_str;
1063 err = got_object_id_str(&id_str, id);
1064 if (err)
1065 return err;
1066 printf("%s: %s\n", refname, id_str);
1067 free(id_str);
1070 return NULL;
1073 static const struct got_error *
1074 create_ref(const char *refname, struct got_object_id *id,
1075 int verbosity, struct got_repository *repo)
1077 const struct got_error *err = NULL;
1078 struct got_reference *ref;
1079 char *id_str;
1081 err = got_object_id_str(&id_str, id);
1082 if (err)
1083 return err;
1085 err = got_ref_alloc(&ref, refname, id);
1086 if (err)
1087 goto done;
1089 err = got_ref_write(ref, repo);
1090 got_ref_close(ref);
1092 if (err == NULL && verbosity >= 0)
1093 printf("Created reference %s: %s\n", refname, id_str);
1094 done:
1095 free(id_str);
1096 return err;
1099 static int
1100 match_wanted_ref(const char *refname, const char *wanted_ref)
1102 if (strncmp(refname, "refs/", 5) != 0)
1103 return 0;
1104 refname += 5;
1107 * Prevent fetching of references that won't make any
1108 * sense outside of the remote repository's context.
1110 if (strncmp(refname, "got/", 4) == 0)
1111 return 0;
1112 if (strncmp(refname, "remotes/", 8) == 0)
1113 return 0;
1115 if (strncmp(wanted_ref, "refs/", 5) == 0)
1116 wanted_ref += 5;
1118 /* Allow prefix match. */
1119 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1120 return 1;
1122 /* Allow exact match. */
1123 return (strcmp(refname, wanted_ref) == 0);
1126 static int
1127 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1129 struct got_pathlist_entry *pe;
1131 TAILQ_FOREACH(pe, wanted_refs, entry) {
1132 if (match_wanted_ref(refname, pe->path))
1133 return 1;
1136 return 0;
1139 static const struct got_error *
1140 create_wanted_ref(const char *refname, struct got_object_id *id,
1141 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1143 const struct got_error *err;
1144 char *remote_refname;
1146 if (strncmp("refs/", refname, 5) == 0)
1147 refname += 5;
1149 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1150 remote_repo_name, refname) == -1)
1151 return got_error_from_errno("asprintf");
1153 err = create_ref(remote_refname, id, verbosity, repo);
1154 free(remote_refname);
1155 return err;
1158 static const struct got_error *
1159 create_gotconfig(const char *proto, const char *host, const char *port,
1160 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1161 struct got_repository *repo)
1163 const struct got_error *err = NULL;
1164 char *gotconfig_path = NULL;
1165 char *gotconfig = NULL;
1166 FILE *gotconfig_file = NULL;
1167 ssize_t n;
1169 /* Create got.conf(5). */
1170 gotconfig_path = got_repo_get_path_gotconfig(repo);
1171 if (gotconfig_path == NULL) {
1172 err = got_error_from_errno("got_repo_get_path_gotconfig");
1173 goto done;
1175 gotconfig_file = fopen(gotconfig_path, "a");
1176 if (gotconfig_file == NULL) {
1177 err = got_error_from_errno2("fopen", gotconfig_path);
1178 goto done;
1180 if (asprintf(&gotconfig,
1181 "remote \"%s\" {\n"
1182 "\tserver %s\n"
1183 "\tprotocol %s\n"
1184 "%s%s%s"
1185 "\trepository \"%s\"\n"
1186 "%s"
1187 "}\n",
1188 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1189 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1190 remote_repo_path,
1191 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1196 if (n != strlen(gotconfig)) {
1197 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1198 goto done;
1201 done:
1202 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1203 err = got_error_from_errno2("fclose", gotconfig_path);
1204 free(gotconfig_path);
1205 return err;
1208 static const struct got_error *
1209 create_gitconfig(const char *git_url, const char *default_branch,
1210 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1212 const struct got_error *err = NULL;
1213 char *gitconfig_path = NULL;
1214 char *gitconfig = NULL;
1215 FILE *gitconfig_file = NULL;
1216 ssize_t n;
1218 /* Create a config file Git can understand. */
1219 gitconfig_path = got_repo_get_path_gitconfig(repo);
1220 if (gitconfig_path == NULL) {
1221 err = got_error_from_errno("got_repo_get_path_gitconfig");
1222 goto done;
1224 gitconfig_file = fopen(gitconfig_path, "a");
1225 if (gitconfig_file == NULL) {
1226 err = got_error_from_errno2("fopen", gitconfig_path);
1227 goto done;
1229 if (mirror_references) {
1230 if (asprintf(&gitconfig,
1231 "[remote \"%s\"]\n"
1232 "\turl = %s\n"
1233 "\tfetch = +refs/*:refs/*\n"
1234 "\tmirror = true\n",
1235 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1236 err = got_error_from_errno("asprintf");
1237 goto done;
1239 } else if (fetch_all_branches) {
1240 if (asprintf(&gitconfig,
1241 "[remote \"%s\"]\n"
1242 "\turl = %s\n"
1243 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1244 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1245 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1246 err = got_error_from_errno("asprintf");
1247 goto done;
1249 } else {
1250 const char *branchname;
1253 * If the server specified a default branch, use just that one.
1254 * Otherwise fall back to fetching all branches on next fetch.
1256 if (default_branch) {
1257 branchname = default_branch;
1258 if (strncmp(branchname, "refs/heads/", 11) == 0)
1259 branchname += 11;
1260 } else
1261 branchname = "*"; /* fall back to all branches */
1262 if (asprintf(&gitconfig,
1263 "[remote \"%s\"]\n"
1264 "\turl = %s\n"
1265 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1266 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1267 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1268 branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1273 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1274 if (n != strlen(gitconfig)) {
1275 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1276 goto done;
1278 done:
1279 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1280 err = got_error_from_errno2("fclose", gitconfig_path);
1281 free(gitconfig_path);
1282 return err;
1285 static const struct got_error *
1286 create_config_files(const char *proto, const char *host, const char *port,
1287 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1288 int mirror_references, struct got_pathlist_head *symrefs,
1289 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1291 const struct got_error *err = NULL;
1292 const char *default_branch = NULL;
1293 struct got_pathlist_entry *pe;
1296 * If we asked for a set of wanted branches then use the first
1297 * one of those.
1299 if (!TAILQ_EMPTY(wanted_branches)) {
1300 pe = TAILQ_FIRST(wanted_branches);
1301 default_branch = pe->path;
1302 } else {
1303 /* First HEAD ref listed by server is the default branch. */
1304 TAILQ_FOREACH(pe, symrefs, entry) {
1305 const char *refname = pe->path;
1306 const char *target = pe->data;
1308 if (strcmp(refname, GOT_REF_HEAD) != 0)
1309 continue;
1311 default_branch = target;
1312 break;
1316 /* Create got.conf(5). */
1317 err = create_gotconfig(proto, host, port, remote_repo_path,
1318 fetch_all_branches, mirror_references, repo);
1319 if (err)
1320 return err;
1322 /* Create a config file Git can understand. */
1323 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1324 mirror_references, repo);
1327 static const struct got_error *
1328 cmd_clone(int argc, char *argv[])
1330 const struct got_error *error = NULL;
1331 const char *uri, *dirname;
1332 char *proto, *host, *port, *repo_name, *server_path;
1333 char *default_destdir = NULL, *id_str = NULL;
1334 const char *repo_path;
1335 struct got_repository *repo = NULL;
1336 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1337 struct got_pathlist_entry *pe;
1338 struct got_object_id *pack_hash = NULL;
1339 int ch, fetchfd = -1, fetchstatus;
1340 pid_t fetchpid = -1;
1341 struct got_fetch_progress_arg fpa;
1342 char *git_url = NULL;
1343 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1344 int list_refs_only = 0;
1346 TAILQ_INIT(&refs);
1347 TAILQ_INIT(&symrefs);
1348 TAILQ_INIT(&wanted_branches);
1349 TAILQ_INIT(&wanted_refs);
1351 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1352 switch (ch) {
1353 case 'a':
1354 fetch_all_branches = 1;
1355 break;
1356 case 'b':
1357 error = got_pathlist_append(&wanted_branches,
1358 optarg, NULL);
1359 if (error)
1360 return error;
1361 break;
1362 case 'l':
1363 list_refs_only = 1;
1364 break;
1365 case 'm':
1366 mirror_references = 1;
1367 break;
1368 case 'v':
1369 if (verbosity < 0)
1370 verbosity = 0;
1371 else if (verbosity < 3)
1372 verbosity++;
1373 break;
1374 case 'q':
1375 verbosity = -1;
1376 break;
1377 case 'R':
1378 error = got_pathlist_append(&wanted_refs,
1379 optarg, NULL);
1380 if (error)
1381 return error;
1382 break;
1383 default:
1384 usage_clone();
1385 break;
1388 argc -= optind;
1389 argv += optind;
1391 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1392 errx(1, "-a and -b options are mutually exclusive");
1393 if (list_refs_only) {
1394 if (!TAILQ_EMPTY(&wanted_branches))
1395 errx(1, "-l and -b options are mutually exclusive");
1396 if (fetch_all_branches)
1397 errx(1, "-l and -a options are mutually exclusive");
1398 if (mirror_references)
1399 errx(1, "-l and -m options are mutually exclusive");
1400 if (verbosity == -1)
1401 errx(1, "-l and -q options are mutually exclusive");
1402 if (!TAILQ_EMPTY(&wanted_refs))
1403 errx(1, "-l and -R options are mutually exclusive");
1406 uri = argv[0];
1408 if (argc == 1)
1409 dirname = NULL;
1410 else if (argc == 2)
1411 dirname = argv[1];
1412 else
1413 usage_clone();
1415 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1416 &repo_name, uri);
1417 if (error)
1418 goto done;
1420 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1421 host, port ? ":" : "", port ? port : "",
1422 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1423 error = got_error_from_errno("asprintf");
1424 goto done;
1427 if (strcmp(proto, "git") == 0) {
1428 #ifndef PROFILE
1429 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1430 "sendfd dns inet unveil", NULL) == -1)
1431 err(1, "pledge");
1432 #endif
1433 } else if (strcmp(proto, "git+ssh") == 0 ||
1434 strcmp(proto, "ssh") == 0) {
1435 #ifndef PROFILE
1436 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1437 "sendfd unveil", NULL) == -1)
1438 err(1, "pledge");
1439 #endif
1440 } else if (strcmp(proto, "http") == 0 ||
1441 strcmp(proto, "git+http") == 0) {
1442 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1443 goto done;
1444 } else {
1445 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1446 goto done;
1448 if (dirname == NULL) {
1449 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1450 error = got_error_from_errno("asprintf");
1451 goto done;
1453 repo_path = default_destdir;
1454 } else
1455 repo_path = dirname;
1457 if (!list_refs_only) {
1458 error = got_path_mkdir(repo_path);
1459 if (error &&
1460 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1461 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1462 goto done;
1463 if (!got_path_dir_is_empty(repo_path)) {
1464 error = got_error_path(repo_path,
1465 GOT_ERR_DIR_NOT_EMPTY);
1466 goto done;
1470 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1471 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1472 error = got_error_from_errno2("unveil",
1473 GOT_FETCH_PATH_SSH);
1474 goto done;
1477 error = apply_unveil(repo_path, 0, NULL);
1478 if (error)
1479 goto done;
1481 if (verbosity >= 0)
1482 printf("Connecting to %s%s%s\n", host,
1483 port ? ":" : "", port ? port : "");
1485 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1486 server_path, verbosity);
1487 if (error)
1488 goto done;
1490 if (!list_refs_only) {
1491 error = got_repo_init(repo_path);
1492 if (error)
1493 goto done;
1494 error = got_repo_open(&repo, repo_path, NULL);
1495 if (error)
1496 goto done;
1499 fpa.last_scaled_size[0] = '\0';
1500 fpa.last_p_indexed = -1;
1501 fpa.last_p_resolved = -1;
1502 fpa.verbosity = verbosity;
1503 fpa.create_configs = 1;
1504 fpa.configs_created = 0;
1505 fpa.repo = repo;
1506 fpa.config_info.symrefs = &symrefs;
1507 fpa.config_info.wanted_branches = &wanted_branches;
1508 fpa.config_info.proto = proto;
1509 fpa.config_info.host = host;
1510 fpa.config_info.port = port;
1511 fpa.config_info.remote_repo_path = server_path;
1512 fpa.config_info.git_url = git_url;
1513 fpa.config_info.fetch_all_branches = fetch_all_branches;
1514 fpa.config_info.mirror_references = mirror_references;
1515 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1516 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1517 fetch_all_branches, &wanted_branches, &wanted_refs,
1518 list_refs_only, verbosity, fetchfd, repo,
1519 fetch_progress, &fpa);
1520 if (error)
1521 goto done;
1523 if (list_refs_only) {
1524 error = list_remote_refs(&symrefs, &refs);
1525 goto done;
1528 error = got_object_id_str(&id_str, pack_hash);
1529 if (error)
1530 goto done;
1531 if (verbosity >= 0)
1532 printf("\nFetched %s.pack\n", id_str);
1533 free(id_str);
1535 /* Set up references provided with the pack file. */
1536 TAILQ_FOREACH(pe, &refs, entry) {
1537 const char *refname = pe->path;
1538 struct got_object_id *id = pe->data;
1539 char *remote_refname;
1541 if (is_wanted_ref(&wanted_refs, refname) &&
1542 !mirror_references) {
1543 error = create_wanted_ref(refname, id,
1544 GOT_FETCH_DEFAULT_REMOTE_NAME,
1545 verbosity - 1, repo);
1546 if (error)
1547 goto done;
1548 continue;
1551 error = create_ref(refname, id, verbosity - 1, repo);
1552 if (error)
1553 goto done;
1555 if (mirror_references)
1556 continue;
1558 if (strncmp("refs/heads/", refname, 11) != 0)
1559 continue;
1561 if (asprintf(&remote_refname,
1562 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1563 refname + 11) == -1) {
1564 error = got_error_from_errno("asprintf");
1565 goto done;
1567 error = create_ref(remote_refname, id, verbosity - 1, repo);
1568 free(remote_refname);
1569 if (error)
1570 goto done;
1573 /* Set the HEAD reference if the server provided one. */
1574 TAILQ_FOREACH(pe, &symrefs, entry) {
1575 struct got_reference *target_ref;
1576 const char *refname = pe->path;
1577 const char *target = pe->data;
1578 char *remote_refname = NULL, *remote_target = NULL;
1580 if (strcmp(refname, GOT_REF_HEAD) != 0)
1581 continue;
1583 error = got_ref_open(&target_ref, repo, target, 0);
1584 if (error) {
1585 if (error->code == GOT_ERR_NOT_REF) {
1586 error = NULL;
1587 continue;
1589 goto done;
1592 error = create_symref(refname, target_ref, verbosity, repo);
1593 got_ref_close(target_ref);
1594 if (error)
1595 goto done;
1597 if (mirror_references)
1598 continue;
1600 if (strncmp("refs/heads/", target, 11) != 0)
1601 continue;
1603 if (asprintf(&remote_refname,
1604 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1605 refname) == -1) {
1606 error = got_error_from_errno("asprintf");
1607 goto done;
1609 if (asprintf(&remote_target,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 target + 11) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 free(remote_refname);
1614 goto done;
1616 error = got_ref_open(&target_ref, repo, remote_target, 0);
1617 if (error) {
1618 free(remote_refname);
1619 free(remote_target);
1620 if (error->code == GOT_ERR_NOT_REF) {
1621 error = NULL;
1622 continue;
1624 goto done;
1626 error = create_symref(remote_refname, target_ref,
1627 verbosity - 1, repo);
1628 free(remote_refname);
1629 free(remote_target);
1630 got_ref_close(target_ref);
1631 if (error)
1632 goto done;
1634 if (pe == NULL) {
1636 * We failed to set the HEAD reference. If we asked for
1637 * a set of wanted branches use the first of one of those
1638 * which could be fetched instead.
1640 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1641 const char *target = pe->path;
1642 struct got_reference *target_ref;
1644 error = got_ref_open(&target_ref, repo, target, 0);
1645 if (error) {
1646 if (error->code == GOT_ERR_NOT_REF) {
1647 error = NULL;
1648 continue;
1650 goto done;
1653 error = create_symref(GOT_REF_HEAD, target_ref,
1654 verbosity, repo);
1655 got_ref_close(target_ref);
1656 if (error)
1657 goto done;
1658 break;
1662 if (verbosity >= 0)
1663 printf("Created %s repository '%s'\n",
1664 mirror_references ? "mirrored" : "cloned", repo_path);
1665 done:
1666 if (fetchpid > 0) {
1667 if (kill(fetchpid, SIGTERM) == -1)
1668 error = got_error_from_errno("kill");
1669 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1670 error = got_error_from_errno("waitpid");
1672 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1673 error = got_error_from_errno("close");
1674 if (repo)
1675 got_repo_close(repo);
1676 TAILQ_FOREACH(pe, &refs, entry) {
1677 free((void *)pe->path);
1678 free(pe->data);
1680 got_pathlist_free(&refs);
1681 TAILQ_FOREACH(pe, &symrefs, entry) {
1682 free((void *)pe->path);
1683 free(pe->data);
1685 got_pathlist_free(&symrefs);
1686 got_pathlist_free(&wanted_branches);
1687 got_pathlist_free(&wanted_refs);
1688 free(pack_hash);
1689 free(proto);
1690 free(host);
1691 free(port);
1692 free(server_path);
1693 free(repo_name);
1694 free(default_destdir);
1695 free(git_url);
1696 return error;
1699 static const struct got_error *
1700 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1701 int replace_tags, int verbosity, struct got_repository *repo)
1703 const struct got_error *err = NULL;
1704 char *new_id_str = NULL;
1705 struct got_object_id *old_id = NULL;
1707 err = got_object_id_str(&new_id_str, new_id);
1708 if (err)
1709 goto done;
1711 if (!replace_tags &&
1712 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1713 err = got_ref_resolve(&old_id, repo, ref);
1714 if (err)
1715 goto done;
1716 if (got_object_id_cmp(old_id, new_id) == 0)
1717 goto done;
1718 if (verbosity >= 0) {
1719 printf("Rejecting update of existing tag %s: %s\n",
1720 got_ref_get_name(ref), new_id_str);
1722 goto done;
1725 if (got_ref_is_symbolic(ref)) {
1726 if (verbosity >= 0) {
1727 printf("Replacing reference %s: %s\n",
1728 got_ref_get_name(ref),
1729 got_ref_get_symref_target(ref));
1731 err = got_ref_change_symref_to_ref(ref, new_id);
1732 if (err)
1733 goto done;
1734 err = got_ref_write(ref, repo);
1735 if (err)
1736 goto done;
1737 } else {
1738 err = got_ref_resolve(&old_id, repo, ref);
1739 if (err)
1740 goto done;
1741 if (got_object_id_cmp(old_id, new_id) == 0)
1742 goto done;
1744 err = got_ref_change_ref(ref, new_id);
1745 if (err)
1746 goto done;
1747 err = got_ref_write(ref, repo);
1748 if (err)
1749 goto done;
1752 if (verbosity >= 0)
1753 printf("Updated %s: %s\n", got_ref_get_name(ref),
1754 new_id_str);
1755 done:
1756 free(old_id);
1757 free(new_id_str);
1758 return err;
1761 static const struct got_error *
1762 update_symref(const char *refname, struct got_reference *target_ref,
1763 int verbosity, struct got_repository *repo)
1765 const struct got_error *err = NULL, *unlock_err;
1766 struct got_reference *symref;
1767 int symref_is_locked = 0;
1769 err = got_ref_open(&symref, repo, refname, 1);
1770 if (err) {
1771 if (err->code != GOT_ERR_NOT_REF)
1772 return err;
1773 err = got_ref_alloc_symref(&symref, refname, target_ref);
1774 if (err)
1775 goto done;
1777 err = got_ref_write(symref, repo);
1778 if (err)
1779 goto done;
1781 if (verbosity >= 0)
1782 printf("Created reference %s: %s\n",
1783 got_ref_get_name(symref),
1784 got_ref_get_symref_target(symref));
1785 } else {
1786 symref_is_locked = 1;
1788 if (strcmp(got_ref_get_symref_target(symref),
1789 got_ref_get_name(target_ref)) == 0)
1790 goto done;
1792 err = got_ref_change_symref(symref,
1793 got_ref_get_name(target_ref));
1794 if (err)
1795 goto done;
1797 err = got_ref_write(symref, repo);
1798 if (err)
1799 goto done;
1801 if (verbosity >= 0)
1802 printf("Updated %s: %s\n", got_ref_get_name(symref),
1803 got_ref_get_symref_target(symref));
1806 done:
1807 if (symref_is_locked) {
1808 unlock_err = got_ref_unlock(symref);
1809 if (unlock_err && err == NULL)
1810 err = unlock_err;
1812 got_ref_close(symref);
1813 return err;
1816 __dead static void
1817 usage_fetch(void)
1819 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1820 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1821 "[remote-repository-name]\n",
1822 getprogname());
1823 exit(1);
1826 static const struct got_error *
1827 delete_missing_ref(struct got_reference *ref,
1828 int verbosity, struct got_repository *repo)
1830 const struct got_error *err = NULL;
1831 struct got_object_id *id = NULL;
1832 char *id_str = NULL;
1834 if (got_ref_is_symbolic(ref)) {
1835 err = got_ref_delete(ref, repo);
1836 if (err)
1837 return err;
1838 if (verbosity >= 0) {
1839 printf("Deleted reference %s: %s\n",
1840 got_ref_get_name(ref),
1841 got_ref_get_symref_target(ref));
1843 } else {
1844 err = got_ref_resolve(&id, repo, ref);
1845 if (err)
1846 return err;
1847 err = got_object_id_str(&id_str, id);
1848 if (err)
1849 goto done;
1851 err = got_ref_delete(ref, repo);
1852 if (err)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Deleted reference %s: %s\n",
1856 got_ref_get_name(ref), id_str);
1859 done:
1860 free(id);
1861 free(id_str);
1862 return NULL;
1865 static const struct got_error *
1866 delete_missing_refs(struct got_pathlist_head *their_refs,
1867 struct got_pathlist_head *their_symrefs,
1868 const struct got_remote_repo *remote,
1869 int verbosity, struct got_repository *repo)
1871 const struct got_error *err = NULL, *unlock_err;
1872 struct got_reflist_head my_refs;
1873 struct got_reflist_entry *re;
1874 struct got_pathlist_entry *pe;
1875 char *remote_namespace = NULL;
1876 char *local_refname = NULL;
1878 SIMPLEQ_INIT(&my_refs);
1880 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1881 == -1)
1882 return got_error_from_errno("asprintf");
1884 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1885 if (err)
1886 goto done;
1888 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1889 const char *refname = got_ref_get_name(re->ref);
1891 if (!remote->mirror_references) {
1892 if (strncmp(refname, remote_namespace,
1893 strlen(remote_namespace)) == 0) {
1894 if (strcmp(refname + strlen(remote_namespace),
1895 GOT_REF_HEAD) == 0)
1896 continue;
1897 if (asprintf(&local_refname, "refs/heads/%s",
1898 refname + strlen(remote_namespace)) == -1) {
1899 err = got_error_from_errno("asprintf");
1900 goto done;
1902 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1903 continue;
1906 TAILQ_FOREACH(pe, their_refs, entry) {
1907 if (strcmp(local_refname, pe->path) == 0)
1908 break;
1910 if (pe != NULL)
1911 continue;
1913 TAILQ_FOREACH(pe, their_symrefs, entry) {
1914 if (strcmp(local_refname, pe->path) == 0)
1915 break;
1917 if (pe != NULL)
1918 continue;
1920 err = delete_missing_ref(re->ref, verbosity, repo);
1921 if (err)
1922 break;
1924 if (local_refname) {
1925 struct got_reference *ref;
1926 err = got_ref_open(&ref, repo, local_refname, 1);
1927 if (err) {
1928 if (err->code != GOT_ERR_NOT_REF)
1929 break;
1930 free(local_refname);
1931 local_refname = NULL;
1932 continue;
1934 err = delete_missing_ref(ref, verbosity, repo);
1935 if (err)
1936 break;
1937 unlock_err = got_ref_unlock(ref);
1938 got_ref_close(ref);
1939 if (unlock_err && err == NULL) {
1940 err = unlock_err;
1941 break;
1944 free(local_refname);
1945 local_refname = NULL;
1948 done:
1949 free(remote_namespace);
1950 free(local_refname);
1951 return err;
1954 static const struct got_error *
1955 update_wanted_ref(const char *refname, struct got_object_id *id,
1956 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1958 const struct got_error *err, *unlock_err;
1959 char *remote_refname;
1960 struct got_reference *ref;
1962 if (strncmp("refs/", refname, 5) == 0)
1963 refname += 5;
1965 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1966 remote_repo_name, refname) == -1)
1967 return got_error_from_errno("asprintf");
1969 err = got_ref_open(&ref, repo, remote_refname, 1);
1970 if (err) {
1971 if (err->code != GOT_ERR_NOT_REF)
1972 goto done;
1973 err = create_ref(remote_refname, id, verbosity, repo);
1974 } else {
1975 err = update_ref(ref, id, 0, verbosity, repo);
1976 unlock_err = got_ref_unlock(ref);
1977 if (unlock_err && err == NULL)
1978 err = unlock_err;
1979 got_ref_close(ref);
1981 done:
1982 free(remote_refname);
1983 return err;
1986 static const struct got_error *
1987 cmd_fetch(int argc, char *argv[])
1989 const struct got_error *error = NULL, *unlock_err;
1990 char *cwd = NULL, *repo_path = NULL;
1991 const char *remote_name;
1992 char *proto = NULL, *host = NULL, *port = NULL;
1993 char *repo_name = NULL, *server_path = NULL;
1994 const struct got_remote_repo *remotes, *remote = NULL;
1995 int nremotes;
1996 char *id_str = NULL;
1997 struct got_repository *repo = NULL;
1998 struct got_worktree *worktree = NULL;
1999 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2000 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2001 struct got_pathlist_entry *pe;
2002 struct got_object_id *pack_hash = NULL;
2003 int i, ch, fetchfd = -1, fetchstatus;
2004 pid_t fetchpid = -1;
2005 struct got_fetch_progress_arg fpa;
2006 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2007 int delete_refs = 0, replace_tags = 0;
2009 TAILQ_INIT(&refs);
2010 TAILQ_INIT(&symrefs);
2011 TAILQ_INIT(&wanted_branches);
2012 TAILQ_INIT(&wanted_refs);
2014 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2015 switch (ch) {
2016 case 'a':
2017 fetch_all_branches = 1;
2018 break;
2019 case 'b':
2020 error = got_pathlist_append(&wanted_branches,
2021 optarg, NULL);
2022 if (error)
2023 return error;
2024 break;
2025 case 'd':
2026 delete_refs = 1;
2027 break;
2028 case 'l':
2029 list_refs_only = 1;
2030 break;
2031 case 'r':
2032 repo_path = realpath(optarg, NULL);
2033 if (repo_path == NULL)
2034 return got_error_from_errno2("realpath",
2035 optarg);
2036 got_path_strip_trailing_slashes(repo_path);
2037 break;
2038 case 't':
2039 replace_tags = 1;
2040 break;
2041 case 'v':
2042 if (verbosity < 0)
2043 verbosity = 0;
2044 else if (verbosity < 3)
2045 verbosity++;
2046 break;
2047 case 'q':
2048 verbosity = -1;
2049 break;
2050 case 'R':
2051 error = got_pathlist_append(&wanted_refs,
2052 optarg, NULL);
2053 if (error)
2054 return error;
2055 break;
2056 default:
2057 usage_fetch();
2058 break;
2061 argc -= optind;
2062 argv += optind;
2064 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2065 errx(1, "-a and -b options are mutually exclusive");
2066 if (list_refs_only) {
2067 if (!TAILQ_EMPTY(&wanted_branches))
2068 errx(1, "-l and -b options are mutually exclusive");
2069 if (fetch_all_branches)
2070 errx(1, "-l and -a options are mutually exclusive");
2071 if (delete_refs)
2072 errx(1, "-l and -d options are mutually exclusive");
2073 if (verbosity == -1)
2074 errx(1, "-l and -q options are mutually exclusive");
2077 if (argc == 0)
2078 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2079 else if (argc == 1)
2080 remote_name = argv[0];
2081 else
2082 usage_fetch();
2084 cwd = getcwd(NULL, 0);
2085 if (cwd == NULL) {
2086 error = got_error_from_errno("getcwd");
2087 goto done;
2090 if (repo_path == NULL) {
2091 error = got_worktree_open(&worktree, cwd);
2092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2093 goto done;
2094 else
2095 error = NULL;
2096 if (worktree) {
2097 repo_path =
2098 strdup(got_worktree_get_repo_path(worktree));
2099 if (repo_path == NULL)
2100 error = got_error_from_errno("strdup");
2101 if (error)
2102 goto done;
2103 } else {
2104 repo_path = strdup(cwd);
2105 if (repo_path == NULL) {
2106 error = got_error_from_errno("strdup");
2107 goto done;
2112 error = got_repo_open(&repo, repo_path, NULL);
2113 if (error)
2114 goto done;
2116 if (worktree) {
2117 worktree_conf = got_worktree_get_gotconfig(worktree);
2118 if (worktree_conf) {
2119 got_gotconfig_get_remotes(&nremotes, &remotes,
2120 worktree_conf);
2121 for (i = 0; i < nremotes; i++) {
2122 if (strcmp(remotes[i].name, remote_name) == 0) {
2123 remote = &remotes[i];
2124 break;
2129 if (remote == NULL) {
2130 repo_conf = got_repo_get_gotconfig(repo);
2131 if (repo_conf) {
2132 got_gotconfig_get_remotes(&nremotes, &remotes,
2133 repo_conf);
2134 for (i = 0; i < nremotes; i++) {
2135 if (strcmp(remotes[i].name, remote_name) == 0) {
2136 remote = &remotes[i];
2137 break;
2142 if (remote == NULL) {
2143 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2144 for (i = 0; i < nremotes; i++) {
2145 if (strcmp(remotes[i].name, remote_name) == 0) {
2146 remote = &remotes[i];
2147 break;
2151 if (remote == NULL) {
2152 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2153 goto done;
2156 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2157 for (i = 0; i < remote->nbranches; i++) {
2158 got_pathlist_append(&wanted_branches,
2159 remote->branches[i], NULL);
2164 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2165 &repo_name, remote->url);
2166 if (error)
2167 goto done;
2169 if (strcmp(proto, "git") == 0) {
2170 #ifndef PROFILE
2171 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2172 "sendfd dns inet unveil", NULL) == -1)
2173 err(1, "pledge");
2174 #endif
2175 } else if (strcmp(proto, "git+ssh") == 0 ||
2176 strcmp(proto, "ssh") == 0) {
2177 #ifndef PROFILE
2178 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2179 "sendfd unveil", NULL) == -1)
2180 err(1, "pledge");
2181 #endif
2182 } else if (strcmp(proto, "http") == 0 ||
2183 strcmp(proto, "git+http") == 0) {
2184 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2185 goto done;
2186 } else {
2187 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2188 goto done;
2191 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2192 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2193 error = got_error_from_errno2("unveil",
2194 GOT_FETCH_PATH_SSH);
2195 goto done;
2198 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2199 if (error)
2200 goto done;
2202 if (verbosity >= 0)
2203 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2204 port ? ":" : "", port ? port : "");
2206 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2207 server_path, verbosity);
2208 if (error)
2209 goto done;
2211 fpa.last_scaled_size[0] = '\0';
2212 fpa.last_p_indexed = -1;
2213 fpa.last_p_resolved = -1;
2214 fpa.verbosity = verbosity;
2215 fpa.repo = repo;
2216 fpa.create_configs = 0;
2217 fpa.configs_created = 0;
2218 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2219 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2220 remote->mirror_references, fetch_all_branches, &wanted_branches,
2221 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2222 fetch_progress, &fpa);
2223 if (error)
2224 goto done;
2226 if (list_refs_only) {
2227 error = list_remote_refs(&symrefs, &refs);
2228 goto done;
2231 if (pack_hash == NULL) {
2232 if (verbosity >= 0)
2233 printf("Already up-to-date\n");
2234 } else if (verbosity >= 0) {
2235 error = got_object_id_str(&id_str, pack_hash);
2236 if (error)
2237 goto done;
2238 printf("\nFetched %s.pack\n", id_str);
2239 free(id_str);
2240 id_str = NULL;
2243 /* Update references provided with the pack file. */
2244 TAILQ_FOREACH(pe, &refs, entry) {
2245 const char *refname = pe->path;
2246 struct got_object_id *id = pe->data;
2247 struct got_reference *ref;
2248 char *remote_refname;
2250 if (is_wanted_ref(&wanted_refs, refname) &&
2251 !remote->mirror_references) {
2252 error = update_wanted_ref(refname, id,
2253 remote->name, verbosity, repo);
2254 if (error)
2255 goto done;
2256 continue;
2259 if (remote->mirror_references ||
2260 strncmp("refs/tags/", refname, 10) == 0) {
2261 error = got_ref_open(&ref, repo, refname, 1);
2262 if (error) {
2263 if (error->code != GOT_ERR_NOT_REF)
2264 goto done;
2265 error = create_ref(refname, id, verbosity,
2266 repo);
2267 if (error)
2268 goto done;
2269 } else {
2270 error = update_ref(ref, id, replace_tags,
2271 verbosity, repo);
2272 unlock_err = got_ref_unlock(ref);
2273 if (unlock_err && error == NULL)
2274 error = unlock_err;
2275 got_ref_close(ref);
2276 if (error)
2277 goto done;
2279 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2280 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2281 remote_name, refname + 11) == -1) {
2282 error = got_error_from_errno("asprintf");
2283 goto done;
2286 error = got_ref_open(&ref, repo, remote_refname, 1);
2287 if (error) {
2288 if (error->code != GOT_ERR_NOT_REF)
2289 goto done;
2290 error = create_ref(remote_refname, id,
2291 verbosity, repo);
2292 if (error)
2293 goto done;
2294 } else {
2295 error = update_ref(ref, id, replace_tags,
2296 verbosity, repo);
2297 unlock_err = got_ref_unlock(ref);
2298 if (unlock_err && error == NULL)
2299 error = unlock_err;
2300 got_ref_close(ref);
2301 if (error)
2302 goto done;
2305 /* Also create a local branch if none exists yet. */
2306 error = got_ref_open(&ref, repo, refname, 1);
2307 if (error) {
2308 if (error->code != GOT_ERR_NOT_REF)
2309 goto done;
2310 error = create_ref(refname, id, verbosity,
2311 repo);
2312 if (error)
2313 goto done;
2314 } else {
2315 unlock_err = got_ref_unlock(ref);
2316 if (unlock_err && error == NULL)
2317 error = unlock_err;
2318 got_ref_close(ref);
2322 if (delete_refs) {
2323 error = delete_missing_refs(&refs, &symrefs, remote,
2324 verbosity, repo);
2325 if (error)
2326 goto done;
2329 if (!remote->mirror_references) {
2330 /* Update remote HEAD reference if the server provided one. */
2331 TAILQ_FOREACH(pe, &symrefs, entry) {
2332 struct got_reference *target_ref;
2333 const char *refname = pe->path;
2334 const char *target = pe->data;
2335 char *remote_refname = NULL, *remote_target = NULL;
2337 if (strcmp(refname, GOT_REF_HEAD) != 0)
2338 continue;
2340 if (strncmp("refs/heads/", target, 11) != 0)
2341 continue;
2343 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2344 remote->name, refname) == -1) {
2345 error = got_error_from_errno("asprintf");
2346 goto done;
2348 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2349 remote->name, target + 11) == -1) {
2350 error = got_error_from_errno("asprintf");
2351 free(remote_refname);
2352 goto done;
2355 error = got_ref_open(&target_ref, repo, remote_target,
2356 0);
2357 if (error) {
2358 free(remote_refname);
2359 free(remote_target);
2360 if (error->code == GOT_ERR_NOT_REF) {
2361 error = NULL;
2362 continue;
2364 goto done;
2366 error = update_symref(remote_refname, target_ref,
2367 verbosity, repo);
2368 free(remote_refname);
2369 free(remote_target);
2370 got_ref_close(target_ref);
2371 if (error)
2372 goto done;
2375 done:
2376 if (fetchpid > 0) {
2377 if (kill(fetchpid, SIGTERM) == -1)
2378 error = got_error_from_errno("kill");
2379 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2380 error = got_error_from_errno("waitpid");
2382 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2383 error = got_error_from_errno("close");
2384 if (repo)
2385 got_repo_close(repo);
2386 if (worktree)
2387 got_worktree_close(worktree);
2388 TAILQ_FOREACH(pe, &refs, entry) {
2389 free((void *)pe->path);
2390 free(pe->data);
2392 got_pathlist_free(&refs);
2393 TAILQ_FOREACH(pe, &symrefs, entry) {
2394 free((void *)pe->path);
2395 free(pe->data);
2397 got_pathlist_free(&symrefs);
2398 got_pathlist_free(&wanted_branches);
2399 got_pathlist_free(&wanted_refs);
2400 free(id_str);
2401 free(cwd);
2402 free(repo_path);
2403 free(pack_hash);
2404 free(proto);
2405 free(host);
2406 free(port);
2407 free(server_path);
2408 free(repo_name);
2409 return error;
2413 __dead static void
2414 usage_checkout(void)
2416 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2417 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2418 exit(1);
2421 static void
2422 show_worktree_base_ref_warning(void)
2424 fprintf(stderr, "%s: warning: could not create a reference "
2425 "to the work tree's base commit; the commit could be "
2426 "garbage-collected by Git; making the repository "
2427 "writable and running 'got update' will prevent this\n",
2428 getprogname());
2431 struct got_checkout_progress_arg {
2432 const char *worktree_path;
2433 int had_base_commit_ref_error;
2436 static const struct got_error *
2437 checkout_progress(void *arg, unsigned char status, const char *path)
2439 struct got_checkout_progress_arg *a = arg;
2441 /* Base commit bump happens silently. */
2442 if (status == GOT_STATUS_BUMP_BASE)
2443 return NULL;
2445 if (status == GOT_STATUS_BASE_REF_ERR) {
2446 a->had_base_commit_ref_error = 1;
2447 return NULL;
2450 while (path[0] == '/')
2451 path++;
2453 printf("%c %s/%s\n", status, a->worktree_path, path);
2454 return NULL;
2457 static const struct got_error *
2458 check_cancelled(void *arg)
2460 if (sigint_received || sigpipe_received)
2461 return got_error(GOT_ERR_CANCELLED);
2462 return NULL;
2465 static const struct got_error *
2466 check_linear_ancestry(struct got_object_id *commit_id,
2467 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2468 struct got_repository *repo)
2470 const struct got_error *err = NULL;
2471 struct got_object_id *yca_id;
2473 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2474 commit_id, base_commit_id, repo, check_cancelled, NULL);
2475 if (err)
2476 return err;
2478 if (yca_id == NULL)
2479 return got_error(GOT_ERR_ANCESTRY);
2482 * Require a straight line of history between the target commit
2483 * and the work tree's base commit.
2485 * Non-linear situations such as this require a rebase:
2487 * (commit) D F (base_commit)
2488 * \ /
2489 * C E
2490 * \ /
2491 * B (yca)
2492 * |
2493 * A
2495 * 'got update' only handles linear cases:
2496 * Update forwards in time: A (base/yca) - B - C - D (commit)
2497 * Update backwards in time: D (base) - C - B - A (commit/yca)
2499 if (allow_forwards_in_time_only) {
2500 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2501 return got_error(GOT_ERR_ANCESTRY);
2502 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2503 got_object_id_cmp(base_commit_id, yca_id) != 0)
2504 return got_error(GOT_ERR_ANCESTRY);
2506 free(yca_id);
2507 return NULL;
2510 static const struct got_error *
2511 check_same_branch(struct got_object_id *commit_id,
2512 struct got_reference *head_ref, struct got_object_id *yca_id,
2513 struct got_repository *repo)
2515 const struct got_error *err = NULL;
2516 struct got_commit_graph *graph = NULL;
2517 struct got_object_id *head_commit_id = NULL;
2518 int is_same_branch = 0;
2520 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2521 if (err)
2522 goto done;
2524 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2525 is_same_branch = 1;
2526 goto done;
2528 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2529 is_same_branch = 1;
2530 goto done;
2533 err = got_commit_graph_open(&graph, "/", 1);
2534 if (err)
2535 goto done;
2537 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2538 check_cancelled, NULL);
2539 if (err)
2540 goto done;
2542 for (;;) {
2543 struct got_object_id *id;
2544 err = got_commit_graph_iter_next(&id, graph, repo,
2545 check_cancelled, NULL);
2546 if (err) {
2547 if (err->code == GOT_ERR_ITER_COMPLETED)
2548 err = NULL;
2549 break;
2552 if (id) {
2553 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2554 break;
2555 if (got_object_id_cmp(id, commit_id) == 0) {
2556 is_same_branch = 1;
2557 break;
2561 done:
2562 if (graph)
2563 got_commit_graph_close(graph);
2564 free(head_commit_id);
2565 if (!err && !is_same_branch)
2566 err = got_error(GOT_ERR_ANCESTRY);
2567 return err;
2570 static const struct got_error *
2571 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2573 static char msg[512];
2574 const char *branch_name;
2576 if (got_ref_is_symbolic(ref))
2577 branch_name = got_ref_get_symref_target(ref);
2578 else
2579 branch_name = got_ref_get_name(ref);
2581 if (strncmp("refs/heads/", branch_name, 11) == 0)
2582 branch_name += 11;
2584 snprintf(msg, sizeof(msg),
2585 "target commit is not contained in branch '%s'; "
2586 "the branch to use must be specified with -b; "
2587 "if necessary a new branch can be created for "
2588 "this commit with 'got branch -c %s BRANCH_NAME'",
2589 branch_name, commit_id_str);
2591 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2594 static const struct got_error *
2595 cmd_checkout(int argc, char *argv[])
2597 const struct got_error *error = NULL;
2598 struct got_repository *repo = NULL;
2599 struct got_reference *head_ref = NULL;
2600 struct got_worktree *worktree = NULL;
2601 char *repo_path = NULL;
2602 char *worktree_path = NULL;
2603 const char *path_prefix = "";
2604 const char *branch_name = GOT_REF_HEAD;
2605 char *commit_id_str = NULL;
2606 char *cwd = NULL;
2607 int ch, same_path_prefix, allow_nonempty = 0;
2608 struct got_pathlist_head paths;
2609 struct got_checkout_progress_arg cpa;
2611 TAILQ_INIT(&paths);
2613 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2614 switch (ch) {
2615 case 'b':
2616 branch_name = optarg;
2617 break;
2618 case 'c':
2619 commit_id_str = strdup(optarg);
2620 if (commit_id_str == NULL)
2621 return got_error_from_errno("strdup");
2622 break;
2623 case 'E':
2624 allow_nonempty = 1;
2625 break;
2626 case 'p':
2627 path_prefix = optarg;
2628 break;
2629 default:
2630 usage_checkout();
2631 /* NOTREACHED */
2635 argc -= optind;
2636 argv += optind;
2638 #ifndef PROFILE
2639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2640 "unveil", NULL) == -1)
2641 err(1, "pledge");
2642 #endif
2643 if (argc == 1) {
2644 char *base, *dotgit;
2645 const char *path;
2646 repo_path = realpath(argv[0], NULL);
2647 if (repo_path == NULL)
2648 return got_error_from_errno2("realpath", argv[0]);
2649 cwd = getcwd(NULL, 0);
2650 if (cwd == NULL) {
2651 error = got_error_from_errno("getcwd");
2652 goto done;
2654 if (path_prefix[0])
2655 path = path_prefix;
2656 else
2657 path = repo_path;
2658 error = got_path_basename(&base, path);
2659 if (error)
2660 goto done;
2661 dotgit = strstr(base, ".git");
2662 if (dotgit)
2663 *dotgit = '\0';
2664 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2665 error = got_error_from_errno("asprintf");
2666 free(base);
2667 goto done;
2669 free(base);
2670 } else if (argc == 2) {
2671 repo_path = realpath(argv[0], NULL);
2672 if (repo_path == NULL) {
2673 error = got_error_from_errno2("realpath", argv[0]);
2674 goto done;
2676 worktree_path = realpath(argv[1], NULL);
2677 if (worktree_path == NULL) {
2678 if (errno != ENOENT) {
2679 error = got_error_from_errno2("realpath",
2680 argv[1]);
2681 goto done;
2683 worktree_path = strdup(argv[1]);
2684 if (worktree_path == NULL) {
2685 error = got_error_from_errno("strdup");
2686 goto done;
2689 } else
2690 usage_checkout();
2692 got_path_strip_trailing_slashes(repo_path);
2693 got_path_strip_trailing_slashes(worktree_path);
2695 error = got_repo_open(&repo, repo_path, NULL);
2696 if (error != NULL)
2697 goto done;
2699 /* Pre-create work tree path for unveil(2) */
2700 error = got_path_mkdir(worktree_path);
2701 if (error) {
2702 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2703 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2704 goto done;
2705 if (!allow_nonempty &&
2706 !got_path_dir_is_empty(worktree_path)) {
2707 error = got_error_path(worktree_path,
2708 GOT_ERR_DIR_NOT_EMPTY);
2709 goto done;
2713 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2714 if (error)
2715 goto done;
2717 error = got_ref_open(&head_ref, repo, branch_name, 0);
2718 if (error != NULL)
2719 goto done;
2721 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2722 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2723 goto done;
2725 error = got_worktree_open(&worktree, worktree_path);
2726 if (error != NULL)
2727 goto done;
2729 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2730 path_prefix);
2731 if (error != NULL)
2732 goto done;
2733 if (!same_path_prefix) {
2734 error = got_error(GOT_ERR_PATH_PREFIX);
2735 goto done;
2738 if (commit_id_str) {
2739 struct got_object_id *commit_id;
2740 error = got_repo_match_object_id(&commit_id, NULL,
2741 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2742 if (error)
2743 goto done;
2744 error = check_linear_ancestry(commit_id,
2745 got_worktree_get_base_commit_id(worktree), 0, repo);
2746 if (error != NULL) {
2747 free(commit_id);
2748 if (error->code == GOT_ERR_ANCESTRY) {
2749 error = checkout_ancestry_error(
2750 head_ref, commit_id_str);
2752 goto done;
2754 error = check_same_branch(commit_id, head_ref, NULL, repo);
2755 if (error) {
2756 if (error->code == GOT_ERR_ANCESTRY) {
2757 error = checkout_ancestry_error(
2758 head_ref, commit_id_str);
2760 goto done;
2762 error = got_worktree_set_base_commit_id(worktree, repo,
2763 commit_id);
2764 free(commit_id);
2765 if (error)
2766 goto done;
2769 error = got_pathlist_append(&paths, "", NULL);
2770 if (error)
2771 goto done;
2772 cpa.worktree_path = worktree_path;
2773 cpa.had_base_commit_ref_error = 0;
2774 error = got_worktree_checkout_files(worktree, &paths, repo,
2775 checkout_progress, &cpa, check_cancelled, NULL);
2776 if (error != NULL)
2777 goto done;
2779 printf("Now shut up and hack\n");
2780 if (cpa.had_base_commit_ref_error)
2781 show_worktree_base_ref_warning();
2782 done:
2783 got_pathlist_free(&paths);
2784 free(commit_id_str);
2785 free(repo_path);
2786 free(worktree_path);
2787 free(cwd);
2788 return error;
2791 struct got_update_progress_arg {
2792 int did_something;
2793 int conflicts;
2794 int obstructed;
2795 int not_updated;
2798 void
2799 print_update_progress_stats(struct got_update_progress_arg *upa)
2801 if (!upa->did_something)
2802 return;
2804 if (upa->conflicts > 0)
2805 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2806 if (upa->obstructed > 0)
2807 printf("File paths obstructed by a non-regular file: %d\n",
2808 upa->obstructed);
2809 if (upa->not_updated > 0)
2810 printf("Files not updated because of existing merge "
2811 "conflicts: %d\n", upa->not_updated);
2814 __dead static void
2815 usage_update(void)
2817 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2818 getprogname());
2819 exit(1);
2822 static const struct got_error *
2823 update_progress(void *arg, unsigned char status, const char *path)
2825 struct got_update_progress_arg *upa = arg;
2827 if (status == GOT_STATUS_EXISTS ||
2828 status == GOT_STATUS_BASE_REF_ERR)
2829 return NULL;
2831 upa->did_something = 1;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_CONFLICT)
2838 upa->conflicts++;
2839 if (status == GOT_STATUS_OBSTRUCTED)
2840 upa->obstructed++;
2841 if (status == GOT_STATUS_CANNOT_UPDATE)
2842 upa->not_updated++;
2844 while (path[0] == '/')
2845 path++;
2846 printf("%c %s\n", status, path);
2847 return NULL;
2850 static const struct got_error *
2851 switch_head_ref(struct got_reference *head_ref,
2852 struct got_object_id *commit_id, struct got_worktree *worktree,
2853 struct got_repository *repo)
2855 const struct got_error *err = NULL;
2856 char *base_id_str;
2857 int ref_has_moved = 0;
2859 /* Trivial case: switching between two different references. */
2860 if (strcmp(got_ref_get_name(head_ref),
2861 got_worktree_get_head_ref_name(worktree)) != 0) {
2862 printf("Switching work tree from %s to %s\n",
2863 got_worktree_get_head_ref_name(worktree),
2864 got_ref_get_name(head_ref));
2865 return got_worktree_set_head_ref(worktree, head_ref);
2868 err = check_linear_ancestry(commit_id,
2869 got_worktree_get_base_commit_id(worktree), 0, repo);
2870 if (err) {
2871 if (err->code != GOT_ERR_ANCESTRY)
2872 return err;
2873 ref_has_moved = 1;
2875 if (!ref_has_moved)
2876 return NULL;
2878 /* Switching to a rebased branch with the same reference name. */
2879 err = got_object_id_str(&base_id_str,
2880 got_worktree_get_base_commit_id(worktree));
2881 if (err)
2882 return err;
2883 printf("Reference %s now points at a different branch\n",
2884 got_worktree_get_head_ref_name(worktree));
2885 printf("Switching work tree from %s to %s\n", base_id_str,
2886 got_worktree_get_head_ref_name(worktree));
2887 return NULL;
2890 static const struct got_error *
2891 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2893 const struct got_error *err;
2894 int in_progress;
2896 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2897 if (err)
2898 return err;
2899 if (in_progress)
2900 return got_error(GOT_ERR_REBASING);
2902 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2903 if (err)
2904 return err;
2905 if (in_progress)
2906 return got_error(GOT_ERR_HISTEDIT_BUSY);
2908 return NULL;
2911 static const struct got_error *
2912 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2913 char *argv[], struct got_worktree *worktree)
2915 const struct got_error *err = NULL;
2916 char *path;
2917 int i;
2919 if (argc == 0) {
2920 path = strdup("");
2921 if (path == NULL)
2922 return got_error_from_errno("strdup");
2923 return got_pathlist_append(paths, path, NULL);
2926 for (i = 0; i < argc; i++) {
2927 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2928 if (err)
2929 break;
2930 err = got_pathlist_append(paths, path, NULL);
2931 if (err) {
2932 free(path);
2933 break;
2937 return err;
2940 static const struct got_error *
2941 wrap_not_worktree_error(const struct got_error *orig_err,
2942 const char *cmdname, const char *path)
2944 const struct got_error *err;
2945 struct got_repository *repo;
2946 static char msg[512];
2948 err = got_repo_open(&repo, path, NULL);
2949 if (err)
2950 return orig_err;
2952 snprintf(msg, sizeof(msg),
2953 "'got %s' needs a work tree in addition to a git repository\n"
2954 "Work trees can be checked out from this Git repository with "
2955 "'got checkout'.\n"
2956 "The got(1) manual page contains more information.", cmdname);
2957 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2958 got_repo_close(repo);
2959 return err;
2962 static const struct got_error *
2963 cmd_update(int argc, char *argv[])
2965 const struct got_error *error = NULL;
2966 struct got_repository *repo = NULL;
2967 struct got_worktree *worktree = NULL;
2968 char *worktree_path = NULL;
2969 struct got_object_id *commit_id = NULL;
2970 char *commit_id_str = NULL;
2971 const char *branch_name = NULL;
2972 struct got_reference *head_ref = NULL;
2973 struct got_pathlist_head paths;
2974 struct got_pathlist_entry *pe;
2975 int ch;
2976 struct got_update_progress_arg upa;
2978 TAILQ_INIT(&paths);
2980 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2981 switch (ch) {
2982 case 'b':
2983 branch_name = optarg;
2984 break;
2985 case 'c':
2986 commit_id_str = strdup(optarg);
2987 if (commit_id_str == NULL)
2988 return got_error_from_errno("strdup");
2989 break;
2990 default:
2991 usage_update();
2992 /* NOTREACHED */
2996 argc -= optind;
2997 argv += optind;
2999 #ifndef PROFILE
3000 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3001 "unveil", NULL) == -1)
3002 err(1, "pledge");
3003 #endif
3004 worktree_path = getcwd(NULL, 0);
3005 if (worktree_path == NULL) {
3006 error = got_error_from_errno("getcwd");
3007 goto done;
3009 error = got_worktree_open(&worktree, worktree_path);
3010 if (error) {
3011 if (error->code == GOT_ERR_NOT_WORKTREE)
3012 error = wrap_not_worktree_error(error, "update",
3013 worktree_path);
3014 goto done;
3017 error = check_rebase_or_histedit_in_progress(worktree);
3018 if (error)
3019 goto done;
3021 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3022 NULL);
3023 if (error != NULL)
3024 goto done;
3026 error = apply_unveil(got_repo_get_path(repo), 0,
3027 got_worktree_get_root_path(worktree));
3028 if (error)
3029 goto done;
3031 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3032 if (error)
3033 goto done;
3035 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3036 got_worktree_get_head_ref_name(worktree), 0);
3037 if (error != NULL)
3038 goto done;
3039 if (commit_id_str == NULL) {
3040 error = got_ref_resolve(&commit_id, repo, head_ref);
3041 if (error != NULL)
3042 goto done;
3043 error = got_object_id_str(&commit_id_str, commit_id);
3044 if (error != NULL)
3045 goto done;
3046 } else {
3047 error = got_repo_match_object_id(&commit_id, NULL,
3048 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3049 free(commit_id_str);
3050 commit_id_str = NULL;
3051 if (error)
3052 goto done;
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3058 if (branch_name) {
3059 struct got_object_id *head_commit_id;
3060 TAILQ_FOREACH(pe, &paths, entry) {
3061 if (pe->path_len == 0)
3062 continue;
3063 error = got_error_msg(GOT_ERR_BAD_PATH,
3064 "switching between branches requires that "
3065 "the entire work tree gets updated");
3066 goto done;
3068 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3069 if (error)
3070 goto done;
3071 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3072 repo);
3073 free(head_commit_id);
3074 if (error != NULL)
3075 goto done;
3076 error = check_same_branch(commit_id, head_ref, NULL, repo);
3077 if (error)
3078 goto done;
3079 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3080 if (error)
3081 goto done;
3082 } else {
3083 error = check_linear_ancestry(commit_id,
3084 got_worktree_get_base_commit_id(worktree), 0, repo);
3085 if (error != NULL) {
3086 if (error->code == GOT_ERR_ANCESTRY)
3087 error = got_error(GOT_ERR_BRANCH_MOVED);
3088 goto done;
3090 error = check_same_branch(commit_id, head_ref, NULL, repo);
3091 if (error)
3092 goto done;
3095 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3096 commit_id) != 0) {
3097 error = got_worktree_set_base_commit_id(worktree, repo,
3098 commit_id);
3099 if (error)
3100 goto done;
3103 memset(&upa, 0, sizeof(upa));
3104 error = got_worktree_checkout_files(worktree, &paths, repo,
3105 update_progress, &upa, check_cancelled, NULL);
3106 if (error != NULL)
3107 goto done;
3109 if (upa.did_something)
3110 printf("Updated to commit %s\n", commit_id_str);
3111 else
3112 printf("Already up-to-date\n");
3113 print_update_progress_stats(&upa);
3114 done:
3115 free(worktree_path);
3116 TAILQ_FOREACH(pe, &paths, entry)
3117 free((char *)pe->path);
3118 got_pathlist_free(&paths);
3119 free(commit_id);
3120 free(commit_id_str);
3121 return error;
3124 static const struct got_error *
3125 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3126 const char *path, int diff_context, int ignore_whitespace,
3127 struct got_repository *repo)
3129 const struct got_error *err = NULL;
3130 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3132 if (blob_id1) {
3133 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3134 if (err)
3135 goto done;
3138 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3139 if (err)
3140 goto done;
3142 while (path[0] == '/')
3143 path++;
3144 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3145 ignore_whitespace, stdout);
3146 done:
3147 if (blob1)
3148 got_object_blob_close(blob1);
3149 got_object_blob_close(blob2);
3150 return err;
3153 static const struct got_error *
3154 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3155 const char *path, int diff_context, int ignore_whitespace,
3156 struct got_repository *repo)
3158 const struct got_error *err = NULL;
3159 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3160 struct got_diff_blob_output_unidiff_arg arg;
3162 if (tree_id1) {
3163 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3164 if (err)
3165 goto done;
3168 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3169 if (err)
3170 goto done;
3172 arg.diff_context = diff_context;
3173 arg.ignore_whitespace = ignore_whitespace;
3174 arg.outfile = stdout;
3175 while (path[0] == '/')
3176 path++;
3177 err = got_diff_tree(tree1, tree2, path, path, repo,
3178 got_diff_blob_output_unidiff, &arg, 1);
3179 done:
3180 if (tree1)
3181 got_object_tree_close(tree1);
3182 if (tree2)
3183 got_object_tree_close(tree2);
3184 return err;
3187 static const struct got_error *
3188 get_changed_paths(struct got_pathlist_head *paths,
3189 struct got_commit_object *commit, struct got_repository *repo)
3191 const struct got_error *err = NULL;
3192 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3193 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3194 struct got_object_qid *qid;
3196 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3197 if (qid != NULL) {
3198 struct got_commit_object *pcommit;
3199 err = got_object_open_as_commit(&pcommit, repo,
3200 qid->id);
3201 if (err)
3202 return err;
3204 tree_id1 = got_object_commit_get_tree_id(pcommit);
3205 got_object_commit_close(pcommit);
3209 if (tree_id1) {
3210 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3211 if (err)
3212 goto done;
3215 tree_id2 = got_object_commit_get_tree_id(commit);
3216 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3217 if (err)
3218 goto done;
3220 err = got_diff_tree(tree1, tree2, "", "", repo,
3221 got_diff_tree_collect_changed_paths, paths, 0);
3222 done:
3223 if (tree1)
3224 got_object_tree_close(tree1);
3225 if (tree2)
3226 got_object_tree_close(tree2);
3227 return err;
3230 static const struct got_error *
3231 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3232 const char *path, int diff_context, struct got_repository *repo)
3234 const struct got_error *err = NULL;
3235 struct got_commit_object *pcommit = NULL;
3236 char *id_str1 = NULL, *id_str2 = NULL;
3237 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3238 struct got_object_qid *qid;
3240 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3241 if (qid != NULL) {
3242 err = got_object_open_as_commit(&pcommit, repo,
3243 qid->id);
3244 if (err)
3245 return err;
3248 if (path && path[0] != '\0') {
3249 int obj_type;
3250 err = got_object_id_by_path(&obj_id2, repo, id, path);
3251 if (err)
3252 goto done;
3253 err = got_object_id_str(&id_str2, obj_id2);
3254 if (err) {
3255 free(obj_id2);
3256 goto done;
3258 if (pcommit) {
3259 err = got_object_id_by_path(&obj_id1, repo,
3260 qid->id, path);
3261 if (err) {
3262 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3263 free(obj_id2);
3264 goto done;
3266 } else {
3267 err = got_object_id_str(&id_str1, obj_id1);
3268 if (err) {
3269 free(obj_id2);
3270 goto done;
3274 err = got_object_get_type(&obj_type, repo, obj_id2);
3275 if (err) {
3276 free(obj_id2);
3277 goto done;
3279 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3280 switch (obj_type) {
3281 case GOT_OBJ_TYPE_BLOB:
3282 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3283 0, repo);
3284 break;
3285 case GOT_OBJ_TYPE_TREE:
3286 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3287 0, repo);
3288 break;
3289 default:
3290 err = got_error(GOT_ERR_OBJ_TYPE);
3291 break;
3293 free(obj_id1);
3294 free(obj_id2);
3295 } else {
3296 obj_id2 = got_object_commit_get_tree_id(commit);
3297 err = got_object_id_str(&id_str2, obj_id2);
3298 if (err)
3299 goto done;
3300 if (pcommit) {
3301 obj_id1 = got_object_commit_get_tree_id(pcommit);
3302 err = got_object_id_str(&id_str1, obj_id1);
3303 if (err)
3304 goto done;
3306 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3307 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3309 done:
3310 free(id_str1);
3311 free(id_str2);
3312 if (pcommit)
3313 got_object_commit_close(pcommit);
3314 return err;
3317 static char *
3318 get_datestr(time_t *time, char *datebuf)
3320 struct tm mytm, *tm;
3321 char *p, *s;
3323 tm = gmtime_r(time, &mytm);
3324 if (tm == NULL)
3325 return NULL;
3326 s = asctime_r(tm, datebuf);
3327 if (s == NULL)
3328 return NULL;
3329 p = strchr(s, '\n');
3330 if (p)
3331 *p = '\0';
3332 return s;
3335 static const struct got_error *
3336 match_logmsg(int *have_match, struct got_object_id *id,
3337 struct got_commit_object *commit, regex_t *regex)
3339 const struct got_error *err = NULL;
3340 regmatch_t regmatch;
3341 char *id_str = NULL, *logmsg = NULL;
3343 *have_match = 0;
3345 err = got_object_id_str(&id_str, id);
3346 if (err)
3347 return err;
3349 err = got_object_commit_get_logmsg(&logmsg, commit);
3350 if (err)
3351 goto done;
3353 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3354 *have_match = 1;
3355 done:
3356 free(id_str);
3357 free(logmsg);
3358 return err;
3361 static void
3362 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3363 regex_t *regex)
3365 regmatch_t regmatch;
3366 struct got_pathlist_entry *pe;
3368 *have_match = 0;
3370 TAILQ_FOREACH(pe, changed_paths, entry) {
3371 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3372 *have_match = 1;
3373 break;
3378 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3380 static const struct got_error *
3381 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3382 struct got_repository *repo, const char *path,
3383 struct got_pathlist_head *changed_paths, int show_patch,
3384 int diff_context, struct got_reflist_head *refs)
3386 const struct got_error *err = NULL;
3387 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3388 char datebuf[26];
3389 time_t committer_time;
3390 const char *author, *committer;
3391 char *refs_str = NULL;
3392 struct got_reflist_entry *re;
3394 SIMPLEQ_FOREACH(re, refs, entry) {
3395 char *s;
3396 const char *name;
3397 struct got_tag_object *tag = NULL;
3398 struct got_object_id *ref_id;
3399 int cmp;
3401 name = got_ref_get_name(re->ref);
3402 if (strcmp(name, GOT_REF_HEAD) == 0)
3403 continue;
3404 if (strncmp(name, "refs/", 5) == 0)
3405 name += 5;
3406 if (strncmp(name, "got/", 4) == 0)
3407 continue;
3408 if (strncmp(name, "heads/", 6) == 0)
3409 name += 6;
3410 if (strncmp(name, "remotes/", 8) == 0) {
3411 name += 8;
3412 s = strstr(name, "/" GOT_REF_HEAD);
3413 if (s != NULL && s[strlen(s)] == '\0')
3414 continue;
3416 err = got_ref_resolve(&ref_id, repo, re->ref);
3417 if (err)
3418 return err;
3419 if (strncmp(name, "tags/", 5) == 0) {
3420 err = got_object_open_as_tag(&tag, repo, ref_id);
3421 if (err) {
3422 if (err->code != GOT_ERR_OBJ_TYPE) {
3423 free(ref_id);
3424 return err;
3426 /* Ref points at something other than a tag. */
3427 err = NULL;
3428 tag = NULL;
3431 cmp = got_object_id_cmp(tag ?
3432 got_object_tag_get_object_id(tag) : ref_id, id);
3433 free(ref_id);
3434 if (tag)
3435 got_object_tag_close(tag);
3436 if (cmp != 0)
3437 continue;
3438 s = refs_str;
3439 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3440 name) == -1) {
3441 err = got_error_from_errno("asprintf");
3442 free(s);
3443 return err;
3445 free(s);
3447 err = got_object_id_str(&id_str, id);
3448 if (err)
3449 return err;
3451 printf(GOT_COMMIT_SEP_STR);
3452 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3453 refs_str ? refs_str : "", refs_str ? ")" : "");
3454 free(id_str);
3455 id_str = NULL;
3456 free(refs_str);
3457 refs_str = NULL;
3458 printf("from: %s\n", got_object_commit_get_author(commit));
3459 committer_time = got_object_commit_get_committer_time(commit);
3460 datestr = get_datestr(&committer_time, datebuf);
3461 if (datestr)
3462 printf("date: %s UTC\n", datestr);
3463 author = got_object_commit_get_author(commit);
3464 committer = got_object_commit_get_committer(commit);
3465 if (strcmp(author, committer) != 0)
3466 printf("via: %s\n", committer);
3467 if (got_object_commit_get_nparents(commit) > 1) {
3468 const struct got_object_id_queue *parent_ids;
3469 struct got_object_qid *qid;
3470 int n = 1;
3471 parent_ids = got_object_commit_get_parent_ids(commit);
3472 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3473 err = got_object_id_str(&id_str, qid->id);
3474 if (err)
3475 return err;
3476 printf("parent %d: %s\n", n++, id_str);
3477 free(id_str);
3481 err = got_object_commit_get_logmsg(&logmsg0, commit);
3482 if (err)
3483 return err;
3485 logmsg = logmsg0;
3486 do {
3487 line = strsep(&logmsg, "\n");
3488 if (line)
3489 printf(" %s\n", line);
3490 } while (line);
3491 free(logmsg0);
3493 if (changed_paths) {
3494 struct got_pathlist_entry *pe;
3495 TAILQ_FOREACH(pe, changed_paths, entry) {
3496 struct got_diff_changed_path *cp = pe->data;
3497 printf(" %c %s\n", cp->status, pe->path);
3499 printf("\n");
3501 if (show_patch) {
3502 err = print_patch(commit, id, path, diff_context, repo);
3503 if (err == 0)
3504 printf("\n");
3507 if (fflush(stdout) != 0 && err == NULL)
3508 err = got_error_from_errno("fflush");
3509 return err;
3512 static const struct got_error *
3513 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3514 struct got_repository *repo, const char *path, int show_changed_paths,
3515 int show_patch, const char *search_pattern, int diff_context, int limit,
3516 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3518 const struct got_error *err;
3519 struct got_commit_graph *graph;
3520 regex_t regex;
3521 int have_match;
3522 struct got_object_id_queue reversed_commits;
3523 struct got_object_qid *qid;
3524 struct got_commit_object *commit;
3525 struct got_pathlist_head changed_paths;
3526 struct got_pathlist_entry *pe;
3528 SIMPLEQ_INIT(&reversed_commits);
3529 TAILQ_INIT(&changed_paths);
3531 if (search_pattern && regcomp(&regex, search_pattern,
3532 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3533 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3535 err = got_commit_graph_open(&graph, path, !log_branches);
3536 if (err)
3537 return err;
3538 err = got_commit_graph_iter_start(graph, root_id, repo,
3539 check_cancelled, NULL);
3540 if (err)
3541 goto done;
3542 for (;;) {
3543 struct got_object_id *id;
3545 if (sigint_received || sigpipe_received)
3546 break;
3548 err = got_commit_graph_iter_next(&id, graph, repo,
3549 check_cancelled, NULL);
3550 if (err) {
3551 if (err->code == GOT_ERR_ITER_COMPLETED)
3552 err = NULL;
3553 break;
3555 if (id == NULL)
3556 break;
3558 err = got_object_open_as_commit(&commit, repo, id);
3559 if (err)
3560 break;
3562 if (show_changed_paths && !reverse_display_order) {
3563 err = get_changed_paths(&changed_paths, commit, repo);
3564 if (err)
3565 break;
3568 if (search_pattern) {
3569 err = match_logmsg(&have_match, id, commit, &regex);
3570 if (err) {
3571 got_object_commit_close(commit);
3572 break;
3574 if (have_match == 0 && show_changed_paths)
3575 match_changed_paths(&have_match,
3576 &changed_paths, &regex);
3577 if (have_match == 0) {
3578 got_object_commit_close(commit);
3579 TAILQ_FOREACH(pe, &changed_paths, entry) {
3580 free((char *)pe->path);
3581 free(pe->data);
3583 got_pathlist_free(&changed_paths);
3584 continue;
3588 if (reverse_display_order) {
3589 err = got_object_qid_alloc(&qid, id);
3590 if (err)
3591 break;
3592 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3593 got_object_commit_close(commit);
3594 } else {
3595 err = print_commit(commit, id, repo, path,
3596 show_changed_paths ? &changed_paths : NULL,
3597 show_patch, diff_context, refs);
3598 got_object_commit_close(commit);
3599 if (err)
3600 break;
3602 if ((limit && --limit == 0) ||
3603 (end_id && got_object_id_cmp(id, end_id) == 0))
3604 break;
3606 TAILQ_FOREACH(pe, &changed_paths, entry) {
3607 free((char *)pe->path);
3608 free(pe->data);
3610 got_pathlist_free(&changed_paths);
3612 if (reverse_display_order) {
3613 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3614 err = got_object_open_as_commit(&commit, repo, qid->id);
3615 if (err)
3616 break;
3617 if (show_changed_paths) {
3618 err = get_changed_paths(&changed_paths,
3619 commit, repo);
3620 if (err)
3621 break;
3623 err = print_commit(commit, qid->id, repo, path,
3624 show_changed_paths ? &changed_paths : NULL,
3625 show_patch, diff_context, refs);
3626 got_object_commit_close(commit);
3627 if (err)
3628 break;
3629 TAILQ_FOREACH(pe, &changed_paths, entry) {
3630 free((char *)pe->path);
3631 free(pe->data);
3633 got_pathlist_free(&changed_paths);
3636 done:
3637 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3638 qid = SIMPLEQ_FIRST(&reversed_commits);
3639 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3640 got_object_qid_free(qid);
3642 TAILQ_FOREACH(pe, &changed_paths, entry) {
3643 free((char *)pe->path);
3644 free(pe->data);
3646 got_pathlist_free(&changed_paths);
3647 if (search_pattern)
3648 regfree(&regex);
3649 got_commit_graph_close(graph);
3650 return err;
3653 __dead static void
3654 usage_log(void)
3656 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3657 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3658 "[-R] [path]\n", getprogname());
3659 exit(1);
3662 static int
3663 get_default_log_limit(void)
3665 const char *got_default_log_limit;
3666 long long n;
3667 const char *errstr;
3669 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3670 if (got_default_log_limit == NULL)
3671 return 0;
3672 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3673 if (errstr != NULL)
3674 return 0;
3675 return n;
3678 static const struct got_error *
3679 cmd_log(int argc, char *argv[])
3681 const struct got_error *error;
3682 struct got_repository *repo = NULL;
3683 struct got_worktree *worktree = NULL;
3684 struct got_object_id *start_id = NULL, *end_id = NULL;
3685 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3686 const char *start_commit = NULL, *end_commit = NULL;
3687 const char *search_pattern = NULL;
3688 int diff_context = -1, ch;
3689 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3690 int reverse_display_order = 0;
3691 const char *errstr;
3692 struct got_reflist_head refs;
3694 SIMPLEQ_INIT(&refs);
3696 #ifndef PROFILE
3697 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3698 NULL)
3699 == -1)
3700 err(1, "pledge");
3701 #endif
3703 limit = get_default_log_limit();
3705 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3706 switch (ch) {
3707 case 'p':
3708 show_patch = 1;
3709 break;
3710 case 'P':
3711 show_changed_paths = 1;
3712 break;
3713 case 'c':
3714 start_commit = optarg;
3715 break;
3716 case 'C':
3717 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3718 &errstr);
3719 if (errstr != NULL)
3720 err(1, "-C option %s", errstr);
3721 break;
3722 case 'l':
3723 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3724 if (errstr != NULL)
3725 err(1, "-l option %s", errstr);
3726 break;
3727 case 'b':
3728 log_branches = 1;
3729 break;
3730 case 'r':
3731 repo_path = realpath(optarg, NULL);
3732 if (repo_path == NULL)
3733 return got_error_from_errno2("realpath",
3734 optarg);
3735 got_path_strip_trailing_slashes(repo_path);
3736 break;
3737 case 'R':
3738 reverse_display_order = 1;
3739 break;
3740 case 's':
3741 search_pattern = optarg;
3742 break;
3743 case 'x':
3744 end_commit = optarg;
3745 break;
3746 default:
3747 usage_log();
3748 /* NOTREACHED */
3752 argc -= optind;
3753 argv += optind;
3755 if (diff_context == -1)
3756 diff_context = 3;
3757 else if (!show_patch)
3758 errx(1, "-C requires -p");
3760 cwd = getcwd(NULL, 0);
3761 if (cwd == NULL) {
3762 error = got_error_from_errno("getcwd");
3763 goto done;
3766 if (repo_path == NULL) {
3767 error = got_worktree_open(&worktree, cwd);
3768 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3769 goto done;
3770 error = NULL;
3773 if (argc == 1) {
3774 if (worktree) {
3775 error = got_worktree_resolve_path(&path, worktree,
3776 argv[0]);
3777 if (error)
3778 goto done;
3779 } else {
3780 path = strdup(argv[0]);
3781 if (path == NULL) {
3782 error = got_error_from_errno("strdup");
3783 goto done;
3786 } else if (argc != 0)
3787 usage_log();
3789 if (repo_path == NULL) {
3790 repo_path = worktree ?
3791 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3793 if (repo_path == NULL) {
3794 error = got_error_from_errno("strdup");
3795 goto done;
3798 error = got_repo_open(&repo, repo_path, NULL);
3799 if (error != NULL)
3800 goto done;
3802 error = apply_unveil(got_repo_get_path(repo), 1,
3803 worktree ? got_worktree_get_root_path(worktree) : NULL);
3804 if (error)
3805 goto done;
3807 if (start_commit == NULL) {
3808 struct got_reference *head_ref;
3809 struct got_commit_object *commit = NULL;
3810 error = got_ref_open(&head_ref, repo,
3811 worktree ? got_worktree_get_head_ref_name(worktree)
3812 : GOT_REF_HEAD, 0);
3813 if (error != NULL)
3814 goto done;
3815 error = got_ref_resolve(&start_id, repo, head_ref);
3816 got_ref_close(head_ref);
3817 if (error != NULL)
3818 goto done;
3819 error = got_object_open_as_commit(&commit, repo,
3820 start_id);
3821 if (error != NULL)
3822 goto done;
3823 got_object_commit_close(commit);
3824 } else {
3825 error = got_repo_match_object_id(&start_id, NULL,
3826 start_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3827 if (error != NULL)
3828 goto done;
3830 if (end_commit != NULL) {
3831 error = got_repo_match_object_id(&end_id, NULL,
3832 end_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3833 if (error != NULL)
3834 goto done;
3837 if (worktree) {
3839 * If a path was specified on the command line it was resolved
3840 * to a path in the work tree above. Prepend the work tree's
3841 * path prefix to obtain the corresponding in-repository path.
3843 if (path) {
3844 const char *prefix;
3845 prefix = got_worktree_get_path_prefix(worktree);
3846 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3847 (path[0] != '\0') ? "/" : "", path) == -1) {
3848 error = got_error_from_errno("asprintf");
3849 goto done;
3852 } else
3853 error = got_repo_map_path(&in_repo_path, repo,
3854 path ? path : "", 1);
3855 if (error != NULL)
3856 goto done;
3857 if (in_repo_path) {
3858 free(path);
3859 path = in_repo_path;
3862 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3863 if (error)
3864 goto done;
3866 error = print_commits(start_id, end_id, repo, path ? path : "",
3867 show_changed_paths, show_patch, search_pattern, diff_context,
3868 limit, log_branches, reverse_display_order, &refs);
3869 done:
3870 free(path);
3871 free(repo_path);
3872 free(cwd);
3873 if (worktree)
3874 got_worktree_close(worktree);
3875 if (repo) {
3876 const struct got_error *repo_error;
3877 repo_error = got_repo_close(repo);
3878 if (error == NULL)
3879 error = repo_error;
3881 got_ref_list_free(&refs);
3882 return error;
3885 __dead static void
3886 usage_diff(void)
3888 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3889 "[-w] [object1 object2 | path]\n", getprogname());
3890 exit(1);
3893 struct print_diff_arg {
3894 struct got_repository *repo;
3895 struct got_worktree *worktree;
3896 int diff_context;
3897 const char *id_str;
3898 int header_shown;
3899 int diff_staged;
3900 int ignore_whitespace;
3904 * Create a file which contains the target path of a symlink so we can feed
3905 * it as content to the diff engine.
3907 static const struct got_error *
3908 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3909 const char *abspath)
3911 const struct got_error *err = NULL;
3912 char target_path[PATH_MAX];
3913 ssize_t target_len, outlen;
3915 *fd = -1;
3917 if (dirfd != -1) {
3918 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3919 if (target_len == -1)
3920 return got_error_from_errno2("readlinkat", abspath);
3921 } else {
3922 target_len = readlink(abspath, target_path, PATH_MAX);
3923 if (target_len == -1)
3924 return got_error_from_errno2("readlink", abspath);
3927 *fd = got_opentempfd();
3928 if (*fd == -1)
3929 return got_error_from_errno("got_opentempfd");
3931 outlen = write(*fd, target_path, target_len);
3932 if (outlen == -1) {
3933 err = got_error_from_errno("got_opentempfd");
3934 goto done;
3937 if (lseek(*fd, 0, SEEK_SET) == -1) {
3938 err = got_error_from_errno2("lseek", abspath);
3939 goto done;
3941 done:
3942 if (err) {
3943 close(*fd);
3944 *fd = -1;
3946 return err;
3949 static const struct got_error *
3950 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3951 const char *path, struct got_object_id *blob_id,
3952 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3953 int dirfd, const char *de_name)
3955 struct print_diff_arg *a = arg;
3956 const struct got_error *err = NULL;
3957 struct got_blob_object *blob1 = NULL;
3958 int fd = -1;
3959 FILE *f2 = NULL;
3960 char *abspath = NULL, *label1 = NULL;
3961 struct stat sb;
3963 if (a->diff_staged) {
3964 if (staged_status != GOT_STATUS_MODIFY &&
3965 staged_status != GOT_STATUS_ADD &&
3966 staged_status != GOT_STATUS_DELETE)
3967 return NULL;
3968 } else {
3969 if (staged_status == GOT_STATUS_DELETE)
3970 return NULL;
3971 if (status == GOT_STATUS_NONEXISTENT)
3972 return got_error_set_errno(ENOENT, path);
3973 if (status != GOT_STATUS_MODIFY &&
3974 status != GOT_STATUS_ADD &&
3975 status != GOT_STATUS_DELETE &&
3976 status != GOT_STATUS_CONFLICT)
3977 return NULL;
3980 if (!a->header_shown) {
3981 printf("diff %s %s%s\n", a->id_str,
3982 got_worktree_get_root_path(a->worktree),
3983 a->diff_staged ? " (staged changes)" : "");
3984 a->header_shown = 1;
3987 if (a->diff_staged) {
3988 const char *label1 = NULL, *label2 = NULL;
3989 switch (staged_status) {
3990 case GOT_STATUS_MODIFY:
3991 label1 = path;
3992 label2 = path;
3993 break;
3994 case GOT_STATUS_ADD:
3995 label2 = path;
3996 break;
3997 case GOT_STATUS_DELETE:
3998 label1 = path;
3999 break;
4000 default:
4001 return got_error(GOT_ERR_FILE_STATUS);
4003 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
4004 label1, label2, a->diff_context, a->ignore_whitespace,
4005 a->repo, stdout);
4008 if (staged_status == GOT_STATUS_ADD ||
4009 staged_status == GOT_STATUS_MODIFY) {
4010 char *id_str;
4011 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4012 8192);
4013 if (err)
4014 goto done;
4015 err = got_object_id_str(&id_str, staged_blob_id);
4016 if (err)
4017 goto done;
4018 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4019 err = got_error_from_errno("asprintf");
4020 free(id_str);
4021 goto done;
4023 free(id_str);
4024 } else if (status != GOT_STATUS_ADD) {
4025 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4026 if (err)
4027 goto done;
4030 if (status != GOT_STATUS_DELETE) {
4031 if (asprintf(&abspath, "%s/%s",
4032 got_worktree_get_root_path(a->worktree), path) == -1) {
4033 err = got_error_from_errno("asprintf");
4034 goto done;
4037 if (dirfd != -1) {
4038 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4039 if (fd == -1) {
4040 if (errno != ELOOP) {
4041 err = got_error_from_errno2("openat",
4042 abspath);
4043 goto done;
4045 err = get_symlink_target_file(&fd, dirfd,
4046 de_name, abspath);
4047 if (err)
4048 goto done;
4050 } else {
4051 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4052 if (fd == -1) {
4053 if (errno != ELOOP) {
4054 err = got_error_from_errno2("open",
4055 abspath);
4056 goto done;
4058 err = get_symlink_target_file(&fd, dirfd,
4059 de_name, abspath);
4060 if (err)
4061 goto done;
4064 if (fstat(fd, &sb) == -1) {
4065 err = got_error_from_errno2("fstat", abspath);
4066 goto done;
4068 f2 = fdopen(fd, "r");
4069 if (f2 == NULL) {
4070 err = got_error_from_errno2("fdopen", abspath);
4071 goto done;
4073 fd = -1;
4074 } else
4075 sb.st_size = 0;
4077 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4078 a->diff_context, a->ignore_whitespace, stdout);
4079 done:
4080 if (blob1)
4081 got_object_blob_close(blob1);
4082 if (f2 && fclose(f2) == EOF && err == NULL)
4083 err = got_error_from_errno("fclose");
4084 if (fd != -1 && close(fd) == -1 && err == NULL)
4085 err = got_error_from_errno("close");
4086 free(abspath);
4087 return err;
4090 static const struct got_error *
4091 cmd_diff(int argc, char *argv[])
4093 const struct got_error *error;
4094 struct got_repository *repo = NULL;
4095 struct got_worktree *worktree = NULL;
4096 char *cwd = NULL, *repo_path = NULL;
4097 struct got_object_id *id1 = NULL, *id2 = NULL;
4098 const char *id_str1 = NULL, *id_str2 = NULL;
4099 char *label1 = NULL, *label2 = NULL;
4100 int type1, type2;
4101 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4102 const char *errstr;
4103 char *path = NULL;
4105 #ifndef PROFILE
4106 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4107 NULL) == -1)
4108 err(1, "pledge");
4109 #endif
4111 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4112 switch (ch) {
4113 case 'C':
4114 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4115 &errstr);
4116 if (errstr != NULL)
4117 err(1, "-C option %s", errstr);
4118 break;
4119 case 'r':
4120 repo_path = realpath(optarg, NULL);
4121 if (repo_path == NULL)
4122 return got_error_from_errno2("realpath",
4123 optarg);
4124 got_path_strip_trailing_slashes(repo_path);
4125 break;
4126 case 's':
4127 diff_staged = 1;
4128 break;
4129 case 'w':
4130 ignore_whitespace = 1;
4131 break;
4132 default:
4133 usage_diff();
4134 /* NOTREACHED */
4138 argc -= optind;
4139 argv += optind;
4141 cwd = getcwd(NULL, 0);
4142 if (cwd == NULL) {
4143 error = got_error_from_errno("getcwd");
4144 goto done;
4146 if (argc <= 1) {
4147 if (repo_path)
4148 errx(1,
4149 "-r option can't be used when diffing a work tree");
4150 error = got_worktree_open(&worktree, cwd);
4151 if (error) {
4152 if (error->code == GOT_ERR_NOT_WORKTREE)
4153 error = wrap_not_worktree_error(error, "diff",
4154 cwd);
4155 goto done;
4157 repo_path = strdup(got_worktree_get_repo_path(worktree));
4158 if (repo_path == NULL) {
4159 error = got_error_from_errno("strdup");
4160 goto done;
4162 if (argc == 1) {
4163 error = got_worktree_resolve_path(&path, worktree,
4164 argv[0]);
4165 if (error)
4166 goto done;
4167 } else {
4168 path = strdup("");
4169 if (path == NULL) {
4170 error = got_error_from_errno("strdup");
4171 goto done;
4174 } else if (argc == 2) {
4175 if (diff_staged)
4176 errx(1, "-s option can't be used when diffing "
4177 "objects in repository");
4178 id_str1 = argv[0];
4179 id_str2 = argv[1];
4180 if (repo_path == NULL) {
4181 error = got_worktree_open(&worktree, cwd);
4182 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4183 goto done;
4184 if (worktree) {
4185 repo_path = strdup(
4186 got_worktree_get_repo_path(worktree));
4187 if (repo_path == NULL) {
4188 error = got_error_from_errno("strdup");
4189 goto done;
4191 } else {
4192 repo_path = strdup(cwd);
4193 if (repo_path == NULL) {
4194 error = got_error_from_errno("strdup");
4195 goto done;
4199 } else
4200 usage_diff();
4202 error = got_repo_open(&repo, repo_path, NULL);
4203 free(repo_path);
4204 if (error != NULL)
4205 goto done;
4207 error = apply_unveil(got_repo_get_path(repo), 1,
4208 worktree ? got_worktree_get_root_path(worktree) : NULL);
4209 if (error)
4210 goto done;
4212 if (argc <= 1) {
4213 struct print_diff_arg arg;
4214 struct got_pathlist_head paths;
4215 char *id_str;
4217 TAILQ_INIT(&paths);
4219 error = got_object_id_str(&id_str,
4220 got_worktree_get_base_commit_id(worktree));
4221 if (error)
4222 goto done;
4223 arg.repo = repo;
4224 arg.worktree = worktree;
4225 arg.diff_context = diff_context;
4226 arg.id_str = id_str;
4227 arg.header_shown = 0;
4228 arg.diff_staged = diff_staged;
4229 arg.ignore_whitespace = ignore_whitespace;
4231 error = got_pathlist_append(&paths, path, NULL);
4232 if (error)
4233 goto done;
4235 error = got_worktree_status(worktree, &paths, repo, print_diff,
4236 &arg, check_cancelled, NULL);
4237 free(id_str);
4238 got_pathlist_free(&paths);
4239 goto done;
4242 error = got_repo_match_object_id(&id1, &label1, id_str1,
4243 GOT_OBJ_TYPE_ANY, 1, repo);
4244 if (error)
4245 goto done;
4247 error = got_repo_match_object_id(&id2, &label2, id_str2,
4248 GOT_OBJ_TYPE_ANY, 1, repo);
4249 if (error)
4250 goto done;
4252 error = got_object_get_type(&type1, repo, id1);
4253 if (error)
4254 goto done;
4256 error = got_object_get_type(&type2, repo, id2);
4257 if (error)
4258 goto done;
4260 if (type1 != type2) {
4261 error = got_error(GOT_ERR_OBJ_TYPE);
4262 goto done;
4265 switch (type1) {
4266 case GOT_OBJ_TYPE_BLOB:
4267 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4268 diff_context, ignore_whitespace, repo, stdout);
4269 break;
4270 case GOT_OBJ_TYPE_TREE:
4271 error = got_diff_objects_as_trees(id1, id2, "", "",
4272 diff_context, ignore_whitespace, repo, stdout);
4273 break;
4274 case GOT_OBJ_TYPE_COMMIT:
4275 printf("diff %s %s\n", label1, label2);
4276 error = got_diff_objects_as_commits(id1, id2, diff_context,
4277 ignore_whitespace, repo, stdout);
4278 break;
4279 default:
4280 error = got_error(GOT_ERR_OBJ_TYPE);
4282 done:
4283 free(label1);
4284 free(label2);
4285 free(id1);
4286 free(id2);
4287 free(path);
4288 if (worktree)
4289 got_worktree_close(worktree);
4290 if (repo) {
4291 const struct got_error *repo_error;
4292 repo_error = got_repo_close(repo);
4293 if (error == NULL)
4294 error = repo_error;
4296 return error;
4299 __dead static void
4300 usage_blame(void)
4302 fprintf(stderr,
4303 "usage: %s blame [-c commit] [-r repository-path] path\n",
4304 getprogname());
4305 exit(1);
4308 struct blame_line {
4309 int annotated;
4310 char *id_str;
4311 char *committer;
4312 char datebuf[11]; /* YYYY-MM-DD + NUL */
4315 struct blame_cb_args {
4316 struct blame_line *lines;
4317 int nlines;
4318 int nlines_prec;
4319 int lineno_cur;
4320 off_t *line_offsets;
4321 FILE *f;
4322 struct got_repository *repo;
4325 static const struct got_error *
4326 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4328 const struct got_error *err = NULL;
4329 struct blame_cb_args *a = arg;
4330 struct blame_line *bline;
4331 char *line = NULL;
4332 size_t linesize = 0;
4333 struct got_commit_object *commit = NULL;
4334 off_t offset;
4335 struct tm tm;
4336 time_t committer_time;
4338 if (nlines != a->nlines ||
4339 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4340 return got_error(GOT_ERR_RANGE);
4342 if (sigint_received)
4343 return got_error(GOT_ERR_ITER_COMPLETED);
4345 if (lineno == -1)
4346 return NULL; /* no change in this commit */
4348 /* Annotate this line. */
4349 bline = &a->lines[lineno - 1];
4350 if (bline->annotated)
4351 return NULL;
4352 err = got_object_id_str(&bline->id_str, id);
4353 if (err)
4354 return err;
4356 err = got_object_open_as_commit(&commit, a->repo, id);
4357 if (err)
4358 goto done;
4360 bline->committer = strdup(got_object_commit_get_committer(commit));
4361 if (bline->committer == NULL) {
4362 err = got_error_from_errno("strdup");
4363 goto done;
4366 committer_time = got_object_commit_get_committer_time(commit);
4367 if (localtime_r(&committer_time, &tm) == NULL)
4368 return got_error_from_errno("localtime_r");
4369 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4370 &tm) >= sizeof(bline->datebuf)) {
4371 err = got_error(GOT_ERR_NO_SPACE);
4372 goto done;
4374 bline->annotated = 1;
4376 /* Print lines annotated so far. */
4377 bline = &a->lines[a->lineno_cur - 1];
4378 if (!bline->annotated)
4379 goto done;
4381 offset = a->line_offsets[a->lineno_cur - 1];
4382 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4383 err = got_error_from_errno("fseeko");
4384 goto done;
4387 while (bline->annotated) {
4388 char *smallerthan, *at, *nl, *committer;
4389 size_t len;
4391 if (getline(&line, &linesize, a->f) == -1) {
4392 if (ferror(a->f))
4393 err = got_error_from_errno("getline");
4394 break;
4397 committer = bline->committer;
4398 smallerthan = strchr(committer, '<');
4399 if (smallerthan && smallerthan[1] != '\0')
4400 committer = smallerthan + 1;
4401 at = strchr(committer, '@');
4402 if (at)
4403 *at = '\0';
4404 len = strlen(committer);
4405 if (len >= 9)
4406 committer[8] = '\0';
4408 nl = strchr(line, '\n');
4409 if (nl)
4410 *nl = '\0';
4411 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4412 bline->id_str, bline->datebuf, committer, line);
4414 a->lineno_cur++;
4415 bline = &a->lines[a->lineno_cur - 1];
4417 done:
4418 if (commit)
4419 got_object_commit_close(commit);
4420 free(line);
4421 return err;
4424 static const struct got_error *
4425 cmd_blame(int argc, char *argv[])
4427 const struct got_error *error;
4428 struct got_repository *repo = NULL;
4429 struct got_worktree *worktree = NULL;
4430 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4431 char *link_target = NULL;
4432 struct got_object_id *obj_id = NULL;
4433 struct got_object_id *commit_id = NULL;
4434 struct got_blob_object *blob = NULL;
4435 char *commit_id_str = NULL;
4436 struct blame_cb_args bca;
4437 int ch, obj_type, i;
4438 size_t filesize;
4440 memset(&bca, 0, sizeof(bca));
4442 #ifndef PROFILE
4443 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4444 NULL) == -1)
4445 err(1, "pledge");
4446 #endif
4448 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4449 switch (ch) {
4450 case 'c':
4451 commit_id_str = optarg;
4452 break;
4453 case 'r':
4454 repo_path = realpath(optarg, NULL);
4455 if (repo_path == NULL)
4456 return got_error_from_errno2("realpath",
4457 optarg);
4458 got_path_strip_trailing_slashes(repo_path);
4459 break;
4460 default:
4461 usage_blame();
4462 /* NOTREACHED */
4466 argc -= optind;
4467 argv += optind;
4469 if (argc == 1)
4470 path = argv[0];
4471 else
4472 usage_blame();
4474 cwd = getcwd(NULL, 0);
4475 if (cwd == NULL) {
4476 error = got_error_from_errno("getcwd");
4477 goto done;
4479 if (repo_path == NULL) {
4480 error = got_worktree_open(&worktree, cwd);
4481 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4482 goto done;
4483 else
4484 error = NULL;
4485 if (worktree) {
4486 repo_path =
4487 strdup(got_worktree_get_repo_path(worktree));
4488 if (repo_path == NULL) {
4489 error = got_error_from_errno("strdup");
4490 if (error)
4491 goto done;
4493 } else {
4494 repo_path = strdup(cwd);
4495 if (repo_path == NULL) {
4496 error = got_error_from_errno("strdup");
4497 goto done;
4502 error = got_repo_open(&repo, repo_path, NULL);
4503 if (error != NULL)
4504 goto done;
4506 if (worktree) {
4507 const char *prefix = got_worktree_get_path_prefix(worktree);
4508 char *p;
4510 error = got_worktree_resolve_path(&p, worktree, path);
4511 if (error)
4512 goto done;
4513 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4514 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4515 p) == -1) {
4516 error = got_error_from_errno("asprintf");
4517 free(p);
4518 goto done;
4520 free(p);
4521 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4522 } else {
4523 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4524 if (error)
4525 goto done;
4526 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4528 if (error)
4529 goto done;
4531 if (commit_id_str == NULL) {
4532 struct got_reference *head_ref;
4533 error = got_ref_open(&head_ref, repo, worktree ?
4534 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4535 if (error != NULL)
4536 goto done;
4537 error = got_ref_resolve(&commit_id, repo, head_ref);
4538 got_ref_close(head_ref);
4539 if (error != NULL)
4540 goto done;
4541 } else {
4542 error = got_repo_match_object_id(&commit_id, NULL,
4543 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4544 if (error)
4545 goto done;
4548 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4549 commit_id, repo);
4550 if (error)
4551 goto done;
4553 error = got_object_id_by_path(&obj_id, repo, commit_id,
4554 link_target ? link_target : in_repo_path);
4555 if (error)
4556 goto done;
4558 error = got_object_get_type(&obj_type, repo, obj_id);
4559 if (error)
4560 goto done;
4562 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4563 error = got_error_path(link_target ? link_target : in_repo_path,
4564 GOT_ERR_OBJ_TYPE);
4565 goto done;
4568 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4569 if (error)
4570 goto done;
4571 bca.f = got_opentemp();
4572 if (bca.f == NULL) {
4573 error = got_error_from_errno("got_opentemp");
4574 goto done;
4576 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4577 &bca.line_offsets, bca.f, blob);
4578 if (error || bca.nlines == 0)
4579 goto done;
4581 /* Don't include \n at EOF in the blame line count. */
4582 if (bca.line_offsets[bca.nlines - 1] == filesize)
4583 bca.nlines--;
4585 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4586 if (bca.lines == NULL) {
4587 error = got_error_from_errno("calloc");
4588 goto done;
4590 bca.lineno_cur = 1;
4591 bca.nlines_prec = 0;
4592 i = bca.nlines;
4593 while (i > 0) {
4594 i /= 10;
4595 bca.nlines_prec++;
4597 bca.repo = repo;
4599 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4600 repo, blame_cb, &bca, check_cancelled, NULL);
4601 done:
4602 free(in_repo_path);
4603 free(link_target);
4604 free(repo_path);
4605 free(cwd);
4606 free(commit_id);
4607 free(obj_id);
4608 if (blob)
4609 got_object_blob_close(blob);
4610 if (worktree)
4611 got_worktree_close(worktree);
4612 if (repo) {
4613 const struct got_error *repo_error;
4614 repo_error = got_repo_close(repo);
4615 if (error == NULL)
4616 error = repo_error;
4618 if (bca.lines) {
4619 for (i = 0; i < bca.nlines; i++) {
4620 struct blame_line *bline = &bca.lines[i];
4621 free(bline->id_str);
4622 free(bline->committer);
4624 free(bca.lines);
4626 free(bca.line_offsets);
4627 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4628 error = got_error_from_errno("fclose");
4629 return error;
4632 __dead static void
4633 usage_tree(void)
4635 fprintf(stderr,
4636 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4637 getprogname());
4638 exit(1);
4641 static const struct got_error *
4642 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4643 const char *root_path, struct got_repository *repo)
4645 const struct got_error *err = NULL;
4646 int is_root_path = (strcmp(path, root_path) == 0);
4647 const char *modestr = "";
4648 mode_t mode = got_tree_entry_get_mode(te);
4649 char *link_target = NULL;
4651 path += strlen(root_path);
4652 while (path[0] == '/')
4653 path++;
4655 if (got_object_tree_entry_is_submodule(te))
4656 modestr = "$";
4657 else if (S_ISLNK(mode)) {
4658 int i;
4660 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4661 if (err)
4662 return err;
4663 for (i = 0; i < strlen(link_target); i++) {
4664 if (!isprint((unsigned char)link_target[i]))
4665 link_target[i] = '?';
4668 modestr = "@";
4670 else if (S_ISDIR(mode))
4671 modestr = "/";
4672 else if (mode & S_IXUSR)
4673 modestr = "*";
4675 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4676 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4677 link_target ? " -> ": "", link_target ? link_target : "");
4679 free(link_target);
4680 return NULL;
4683 static const struct got_error *
4684 print_tree(const char *path, struct got_object_id *commit_id,
4685 int show_ids, int recurse, const char *root_path,
4686 struct got_repository *repo)
4688 const struct got_error *err = NULL;
4689 struct got_object_id *tree_id = NULL;
4690 struct got_tree_object *tree = NULL;
4691 int nentries, i;
4693 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4694 if (err)
4695 goto done;
4697 err = got_object_open_as_tree(&tree, repo, tree_id);
4698 if (err)
4699 goto done;
4700 nentries = got_object_tree_get_nentries(tree);
4701 for (i = 0; i < nentries; i++) {
4702 struct got_tree_entry *te;
4703 char *id = NULL;
4705 if (sigint_received || sigpipe_received)
4706 break;
4708 te = got_object_tree_get_entry(tree, i);
4709 if (show_ids) {
4710 char *id_str;
4711 err = got_object_id_str(&id_str,
4712 got_tree_entry_get_id(te));
4713 if (err)
4714 goto done;
4715 if (asprintf(&id, "%s ", id_str) == -1) {
4716 err = got_error_from_errno("asprintf");
4717 free(id_str);
4718 goto done;
4720 free(id_str);
4722 err = print_entry(te, id, path, root_path, repo);
4723 free(id);
4724 if (err)
4725 goto done;
4727 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4728 char *child_path;
4729 if (asprintf(&child_path, "%s%s%s", path,
4730 path[0] == '/' && path[1] == '\0' ? "" : "/",
4731 got_tree_entry_get_name(te)) == -1) {
4732 err = got_error_from_errno("asprintf");
4733 goto done;
4735 err = print_tree(child_path, commit_id, show_ids, 1,
4736 root_path, repo);
4737 free(child_path);
4738 if (err)
4739 goto done;
4742 done:
4743 if (tree)
4744 got_object_tree_close(tree);
4745 free(tree_id);
4746 return err;
4749 static const struct got_error *
4750 cmd_tree(int argc, char *argv[])
4752 const struct got_error *error;
4753 struct got_repository *repo = NULL;
4754 struct got_worktree *worktree = NULL;
4755 const char *path, *refname = NULL;
4756 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4757 struct got_object_id *commit_id = NULL;
4758 char *commit_id_str = NULL;
4759 int show_ids = 0, recurse = 0;
4760 int ch;
4762 #ifndef PROFILE
4763 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4764 NULL) == -1)
4765 err(1, "pledge");
4766 #endif
4768 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4769 switch (ch) {
4770 case 'c':
4771 commit_id_str = optarg;
4772 break;
4773 case 'r':
4774 repo_path = realpath(optarg, NULL);
4775 if (repo_path == NULL)
4776 return got_error_from_errno2("realpath",
4777 optarg);
4778 got_path_strip_trailing_slashes(repo_path);
4779 break;
4780 case 'i':
4781 show_ids = 1;
4782 break;
4783 case 'R':
4784 recurse = 1;
4785 break;
4786 default:
4787 usage_tree();
4788 /* NOTREACHED */
4792 argc -= optind;
4793 argv += optind;
4795 if (argc == 1)
4796 path = argv[0];
4797 else if (argc > 1)
4798 usage_tree();
4799 else
4800 path = NULL;
4802 cwd = getcwd(NULL, 0);
4803 if (cwd == NULL) {
4804 error = got_error_from_errno("getcwd");
4805 goto done;
4807 if (repo_path == NULL) {
4808 error = got_worktree_open(&worktree, cwd);
4809 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4810 goto done;
4811 else
4812 error = NULL;
4813 if (worktree) {
4814 repo_path =
4815 strdup(got_worktree_get_repo_path(worktree));
4816 if (repo_path == NULL)
4817 error = got_error_from_errno("strdup");
4818 if (error)
4819 goto done;
4820 } else {
4821 repo_path = strdup(cwd);
4822 if (repo_path == NULL) {
4823 error = got_error_from_errno("strdup");
4824 goto done;
4829 error = got_repo_open(&repo, repo_path, NULL);
4830 if (error != NULL)
4831 goto done;
4833 if (worktree) {
4834 const char *prefix = got_worktree_get_path_prefix(worktree);
4835 char *p;
4837 if (path == NULL)
4838 path = "";
4839 error = got_worktree_resolve_path(&p, worktree, path);
4840 if (error)
4841 goto done;
4842 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4843 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4844 p) == -1) {
4845 error = got_error_from_errno("asprintf");
4846 free(p);
4847 goto done;
4849 free(p);
4850 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4851 if (error)
4852 goto done;
4853 } else {
4854 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4855 if (error)
4856 goto done;
4857 if (path == NULL)
4858 path = "/";
4859 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4860 if (error != NULL)
4861 goto done;
4864 if (commit_id_str == NULL) {
4865 struct got_reference *head_ref;
4866 if (worktree)
4867 refname = got_worktree_get_head_ref_name(worktree);
4868 else
4869 refname = GOT_REF_HEAD;
4870 error = got_ref_open(&head_ref, repo, refname, 0);
4871 if (error != NULL)
4872 goto done;
4873 error = got_ref_resolve(&commit_id, repo, head_ref);
4874 got_ref_close(head_ref);
4875 if (error != NULL)
4876 goto done;
4877 } else {
4878 error = got_repo_match_object_id(&commit_id, NULL,
4879 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4880 if (error)
4881 goto done;
4884 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4885 in_repo_path, repo);
4886 done:
4887 free(in_repo_path);
4888 free(repo_path);
4889 free(cwd);
4890 free(commit_id);
4891 if (worktree)
4892 got_worktree_close(worktree);
4893 if (repo) {
4894 const struct got_error *repo_error;
4895 repo_error = got_repo_close(repo);
4896 if (error == NULL)
4897 error = repo_error;
4899 return error;
4902 __dead static void
4903 usage_status(void)
4905 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4906 getprogname());
4907 exit(1);
4910 static const struct got_error *
4911 print_status(void *arg, unsigned char status, unsigned char staged_status,
4912 const char *path, struct got_object_id *blob_id,
4913 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4914 int dirfd, const char *de_name)
4916 if (status == staged_status && (status == GOT_STATUS_DELETE))
4917 status = GOT_STATUS_NO_CHANGE;
4918 if (arg) {
4919 char *status_codes = arg;
4920 size_t ncodes = strlen(status_codes);
4921 int i;
4922 for (i = 0; i < ncodes ; i++) {
4923 if (status == status_codes[i] ||
4924 staged_status == status_codes[i])
4925 break;
4927 if (i == ncodes)
4928 return NULL;
4930 printf("%c%c %s\n", status, staged_status, path);
4931 return NULL;
4934 static const struct got_error *
4935 cmd_status(int argc, char *argv[])
4937 const struct got_error *error = NULL;
4938 struct got_repository *repo = NULL;
4939 struct got_worktree *worktree = NULL;
4940 char *cwd = NULL, *status_codes = NULL;;
4941 struct got_pathlist_head paths;
4942 struct got_pathlist_entry *pe;
4943 int ch, i;
4945 TAILQ_INIT(&paths);
4947 while ((ch = getopt(argc, argv, "s:")) != -1) {
4948 switch (ch) {
4949 case 's':
4950 for (i = 0; i < strlen(optarg); i++) {
4951 switch (optarg[i]) {
4952 case GOT_STATUS_MODIFY:
4953 case GOT_STATUS_ADD:
4954 case GOT_STATUS_DELETE:
4955 case GOT_STATUS_CONFLICT:
4956 case GOT_STATUS_MISSING:
4957 case GOT_STATUS_OBSTRUCTED:
4958 case GOT_STATUS_UNVERSIONED:
4959 case GOT_STATUS_MODE_CHANGE:
4960 case GOT_STATUS_NONEXISTENT:
4961 break;
4962 default:
4963 errx(1, "invalid status code '%c'",
4964 optarg[i]);
4967 status_codes = optarg;
4968 break;
4969 default:
4970 usage_status();
4971 /* NOTREACHED */
4975 argc -= optind;
4976 argv += optind;
4978 #ifndef PROFILE
4979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4980 NULL) == -1)
4981 err(1, "pledge");
4982 #endif
4983 cwd = getcwd(NULL, 0);
4984 if (cwd == NULL) {
4985 error = got_error_from_errno("getcwd");
4986 goto done;
4989 error = got_worktree_open(&worktree, cwd);
4990 if (error) {
4991 if (error->code == GOT_ERR_NOT_WORKTREE)
4992 error = wrap_not_worktree_error(error, "status", cwd);
4993 goto done;
4996 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4997 NULL);
4998 if (error != NULL)
4999 goto done;
5001 error = apply_unveil(got_repo_get_path(repo), 1,
5002 got_worktree_get_root_path(worktree));
5003 if (error)
5004 goto done;
5006 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5007 if (error)
5008 goto done;
5010 error = got_worktree_status(worktree, &paths, repo, print_status,
5011 status_codes, check_cancelled, NULL);
5012 done:
5013 TAILQ_FOREACH(pe, &paths, entry)
5014 free((char *)pe->path);
5015 got_pathlist_free(&paths);
5016 free(cwd);
5017 return error;
5020 __dead static void
5021 usage_ref(void)
5023 fprintf(stderr,
5024 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5025 "[-d] [name]\n",
5026 getprogname());
5027 exit(1);
5030 static const struct got_error *
5031 list_refs(struct got_repository *repo, const char *refname)
5033 static const struct got_error *err = NULL;
5034 struct got_reflist_head refs;
5035 struct got_reflist_entry *re;
5037 SIMPLEQ_INIT(&refs);
5038 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5039 if (err)
5040 return err;
5042 SIMPLEQ_FOREACH(re, &refs, entry) {
5043 char *refstr;
5044 refstr = got_ref_to_str(re->ref);
5045 if (refstr == NULL)
5046 return got_error_from_errno("got_ref_to_str");
5047 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5048 free(refstr);
5051 got_ref_list_free(&refs);
5052 return NULL;
5055 static const struct got_error *
5056 delete_ref(struct got_repository *repo, const char *refname)
5058 const struct got_error *err = NULL;
5059 struct got_reference *ref;
5061 err = got_ref_open(&ref, repo, refname, 0);
5062 if (err)
5063 return err;
5065 err = got_ref_delete(ref, repo);
5066 got_ref_close(ref);
5067 return err;
5070 static const struct got_error *
5071 add_ref(struct got_repository *repo, const char *refname, const char *target)
5073 const struct got_error *err = NULL;
5074 struct got_object_id *id;
5075 struct got_reference *ref = NULL;
5078 * Don't let the user create a reference name with a leading '-'.
5079 * While technically a valid reference name, this case is usually
5080 * an unintended typo.
5082 if (refname[0] == '-')
5083 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5085 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5086 repo);
5087 if (err) {
5088 struct got_reference *target_ref;
5090 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5091 return err;
5092 err = got_ref_open(&target_ref, repo, target, 0);
5093 if (err)
5094 return err;
5095 err = got_ref_resolve(&id, repo, target_ref);
5096 got_ref_close(target_ref);
5097 if (err)
5098 return err;
5101 err = got_ref_alloc(&ref, refname, id);
5102 if (err)
5103 goto done;
5105 err = got_ref_write(ref, repo);
5106 done:
5107 if (ref)
5108 got_ref_close(ref);
5109 free(id);
5110 return err;
5113 static const struct got_error *
5114 add_symref(struct got_repository *repo, const char *refname, const char *target)
5116 const struct got_error *err = NULL;
5117 struct got_reference *ref = NULL;
5118 struct got_reference *target_ref = NULL;
5121 * Don't let the user create a reference name with a leading '-'.
5122 * While technically a valid reference name, this case is usually
5123 * an unintended typo.
5125 if (refname[0] == '-')
5126 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5128 err = got_ref_open(&target_ref, repo, target, 0);
5129 if (err)
5130 return err;
5132 err = got_ref_alloc_symref(&ref, refname, target_ref);
5133 if (err)
5134 goto done;
5136 err = got_ref_write(ref, repo);
5137 done:
5138 if (target_ref)
5139 got_ref_close(target_ref);
5140 if (ref)
5141 got_ref_close(ref);
5142 return err;
5145 static const struct got_error *
5146 cmd_ref(int argc, char *argv[])
5148 const struct got_error *error = NULL;
5149 struct got_repository *repo = NULL;
5150 struct got_worktree *worktree = NULL;
5151 char *cwd = NULL, *repo_path = NULL;
5152 int ch, do_list = 0, do_delete = 0;
5153 const char *obj_arg = NULL, *symref_target= NULL;
5154 char *refname = NULL;
5156 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5157 switch (ch) {
5158 case 'c':
5159 obj_arg = optarg;
5160 break;
5161 case 'd':
5162 do_delete = 1;
5163 break;
5164 case 'r':
5165 repo_path = realpath(optarg, NULL);
5166 if (repo_path == NULL)
5167 return got_error_from_errno2("realpath",
5168 optarg);
5169 got_path_strip_trailing_slashes(repo_path);
5170 break;
5171 case 'l':
5172 do_list = 1;
5173 break;
5174 case 's':
5175 symref_target = optarg;
5176 break;
5177 default:
5178 usage_ref();
5179 /* NOTREACHED */
5183 if (obj_arg && do_list)
5184 errx(1, "-c and -l options are mutually exclusive");
5185 if (obj_arg && do_delete)
5186 errx(1, "-c and -d options are mutually exclusive");
5187 if (obj_arg && symref_target)
5188 errx(1, "-c and -s options are mutually exclusive");
5189 if (symref_target && do_delete)
5190 errx(1, "-s and -d options are mutually exclusive");
5191 if (symref_target && do_list)
5192 errx(1, "-s and -l options are mutually exclusive");
5193 if (do_delete && do_list)
5194 errx(1, "-d and -l options are mutually exclusive");
5196 argc -= optind;
5197 argv += optind;
5199 if (do_list) {
5200 if (argc != 0 && argc != 1)
5201 usage_ref();
5202 if (argc == 1) {
5203 refname = strdup(argv[0]);
5204 if (refname == NULL) {
5205 error = got_error_from_errno("strdup");
5206 goto done;
5209 } else {
5210 if (argc != 1)
5211 usage_ref();
5212 refname = strdup(argv[0]);
5213 if (refname == NULL) {
5214 error = got_error_from_errno("strdup");
5215 goto done;
5219 if (refname)
5220 got_path_strip_trailing_slashes(refname);
5222 #ifndef PROFILE
5223 if (do_list) {
5224 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5225 NULL) == -1)
5226 err(1, "pledge");
5227 } else {
5228 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5229 "sendfd unveil", NULL) == -1)
5230 err(1, "pledge");
5232 #endif
5233 cwd = getcwd(NULL, 0);
5234 if (cwd == NULL) {
5235 error = got_error_from_errno("getcwd");
5236 goto done;
5239 if (repo_path == NULL) {
5240 error = got_worktree_open(&worktree, cwd);
5241 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5242 goto done;
5243 else
5244 error = NULL;
5245 if (worktree) {
5246 repo_path =
5247 strdup(got_worktree_get_repo_path(worktree));
5248 if (repo_path == NULL)
5249 error = got_error_from_errno("strdup");
5250 if (error)
5251 goto done;
5252 } else {
5253 repo_path = strdup(cwd);
5254 if (repo_path == NULL) {
5255 error = got_error_from_errno("strdup");
5256 goto done;
5261 error = got_repo_open(&repo, repo_path, NULL);
5262 if (error != NULL)
5263 goto done;
5265 error = apply_unveil(got_repo_get_path(repo), do_list,
5266 worktree ? got_worktree_get_root_path(worktree) : NULL);
5267 if (error)
5268 goto done;
5270 if (do_list)
5271 error = list_refs(repo, refname);
5272 else if (do_delete)
5273 error = delete_ref(repo, refname);
5274 else if (symref_target)
5275 error = add_symref(repo, refname, symref_target);
5276 else {
5277 if (obj_arg == NULL)
5278 usage_ref();
5279 error = add_ref(repo, refname, obj_arg);
5281 done:
5282 free(refname);
5283 if (repo)
5284 got_repo_close(repo);
5285 if (worktree)
5286 got_worktree_close(worktree);
5287 free(cwd);
5288 free(repo_path);
5289 return error;
5292 __dead static void
5293 usage_branch(void)
5295 fprintf(stderr,
5296 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5297 "[name]\n", getprogname());
5298 exit(1);
5301 static const struct got_error *
5302 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5303 struct got_reference *ref)
5305 const struct got_error *err = NULL;
5306 const char *refname, *marker = " ";
5307 char *refstr;
5309 refname = got_ref_get_name(ref);
5310 if (worktree && strcmp(refname,
5311 got_worktree_get_head_ref_name(worktree)) == 0) {
5312 struct got_object_id *id = NULL;
5314 err = got_ref_resolve(&id, repo, ref);
5315 if (err)
5316 return err;
5317 if (got_object_id_cmp(id,
5318 got_worktree_get_base_commit_id(worktree)) == 0)
5319 marker = "* ";
5320 else
5321 marker = "~ ";
5322 free(id);
5325 if (strncmp(refname, "refs/heads/", 11) == 0)
5326 refname += 11;
5327 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5328 refname += 18;
5330 refstr = got_ref_to_str(ref);
5331 if (refstr == NULL)
5332 return got_error_from_errno("got_ref_to_str");
5334 printf("%s%s: %s\n", marker, refname, refstr);
5335 free(refstr);
5336 return NULL;
5339 static const struct got_error *
5340 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5342 const char *refname;
5344 if (worktree == NULL)
5345 return got_error(GOT_ERR_NOT_WORKTREE);
5347 refname = got_worktree_get_head_ref_name(worktree);
5349 if (strncmp(refname, "refs/heads/", 11) == 0)
5350 refname += 11;
5351 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5352 refname += 18;
5354 printf("%s\n", refname);
5356 return NULL;
5359 static const struct got_error *
5360 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5362 static const struct got_error *err = NULL;
5363 struct got_reflist_head refs;
5364 struct got_reflist_entry *re;
5365 struct got_reference *temp_ref = NULL;
5366 int rebase_in_progress, histedit_in_progress;
5368 SIMPLEQ_INIT(&refs);
5370 if (worktree) {
5371 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5372 worktree);
5373 if (err)
5374 return err;
5376 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5377 worktree);
5378 if (err)
5379 return err;
5381 if (rebase_in_progress || histedit_in_progress) {
5382 err = got_ref_open(&temp_ref, repo,
5383 got_worktree_get_head_ref_name(worktree), 0);
5384 if (err)
5385 return err;
5386 list_branch(repo, worktree, temp_ref);
5387 got_ref_close(temp_ref);
5391 err = got_ref_list(&refs, repo, "refs/heads",
5392 got_ref_cmp_by_name, NULL);
5393 if (err)
5394 return err;
5396 SIMPLEQ_FOREACH(re, &refs, entry)
5397 list_branch(repo, worktree, re->ref);
5399 got_ref_list_free(&refs);
5400 return NULL;
5403 static const struct got_error *
5404 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5405 const char *branch_name)
5407 const struct got_error *err = NULL;
5408 struct got_reference *ref = NULL;
5409 char *refname;
5411 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5412 return got_error_from_errno("asprintf");
5414 err = got_ref_open(&ref, repo, refname, 0);
5415 if (err)
5416 goto done;
5418 if (worktree &&
5419 strcmp(got_worktree_get_head_ref_name(worktree),
5420 got_ref_get_name(ref)) == 0) {
5421 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5422 "will not delete this work tree's current branch");
5423 goto done;
5426 err = got_ref_delete(ref, repo);
5427 done:
5428 if (ref)
5429 got_ref_close(ref);
5430 free(refname);
5431 return err;
5434 static const struct got_error *
5435 add_branch(struct got_repository *repo, const char *branch_name,
5436 struct got_object_id *base_commit_id)
5438 const struct got_error *err = NULL;
5439 struct got_reference *ref = NULL;
5440 char *base_refname = NULL, *refname = NULL;
5443 * Don't let the user create a branch name with a leading '-'.
5444 * While technically a valid reference name, this case is usually
5445 * an unintended typo.
5447 if (branch_name[0] == '-')
5448 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5450 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5451 err = got_error_from_errno("asprintf");
5452 goto done;
5455 err = got_ref_open(&ref, repo, refname, 0);
5456 if (err == NULL) {
5457 err = got_error(GOT_ERR_BRANCH_EXISTS);
5458 goto done;
5459 } else if (err->code != GOT_ERR_NOT_REF)
5460 goto done;
5462 err = got_ref_alloc(&ref, refname, base_commit_id);
5463 if (err)
5464 goto done;
5466 err = got_ref_write(ref, repo);
5467 done:
5468 if (ref)
5469 got_ref_close(ref);
5470 free(base_refname);
5471 free(refname);
5472 return err;
5475 static const struct got_error *
5476 cmd_branch(int argc, char *argv[])
5478 const struct got_error *error = NULL;
5479 struct got_repository *repo = NULL;
5480 struct got_worktree *worktree = NULL;
5481 char *cwd = NULL, *repo_path = NULL;
5482 int ch, do_list = 0, do_show = 0, do_update = 1;
5483 const char *delref = NULL, *commit_id_arg = NULL;
5484 struct got_reference *ref = NULL;
5485 struct got_pathlist_head paths;
5486 struct got_pathlist_entry *pe;
5487 struct got_object_id *commit_id = NULL;
5488 char *commit_id_str = NULL;
5490 TAILQ_INIT(&paths);
5492 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5493 switch (ch) {
5494 case 'c':
5495 commit_id_arg = optarg;
5496 break;
5497 case 'd':
5498 delref = optarg;
5499 break;
5500 case 'r':
5501 repo_path = realpath(optarg, NULL);
5502 if (repo_path == NULL)
5503 return got_error_from_errno2("realpath",
5504 optarg);
5505 got_path_strip_trailing_slashes(repo_path);
5506 break;
5507 case 'l':
5508 do_list = 1;
5509 break;
5510 case 'n':
5511 do_update = 0;
5512 break;
5513 default:
5514 usage_branch();
5515 /* NOTREACHED */
5519 if (do_list && delref)
5520 errx(1, "-l and -d options are mutually exclusive");
5522 argc -= optind;
5523 argv += optind;
5525 if (!do_list && !delref && argc == 0)
5526 do_show = 1;
5528 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5529 errx(1, "-c option can only be used when creating a branch");
5531 if (do_list || delref) {
5532 if (argc > 0)
5533 usage_branch();
5534 } else if (!do_show && argc != 1)
5535 usage_branch();
5537 #ifndef PROFILE
5538 if (do_list || do_show) {
5539 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5540 NULL) == -1)
5541 err(1, "pledge");
5542 } else {
5543 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5544 "sendfd unveil", NULL) == -1)
5545 err(1, "pledge");
5547 #endif
5548 cwd = getcwd(NULL, 0);
5549 if (cwd == NULL) {
5550 error = got_error_from_errno("getcwd");
5551 goto done;
5554 if (repo_path == NULL) {
5555 error = got_worktree_open(&worktree, cwd);
5556 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5557 goto done;
5558 else
5559 error = NULL;
5560 if (worktree) {
5561 repo_path =
5562 strdup(got_worktree_get_repo_path(worktree));
5563 if (repo_path == NULL)
5564 error = got_error_from_errno("strdup");
5565 if (error)
5566 goto done;
5567 } else {
5568 repo_path = strdup(cwd);
5569 if (repo_path == NULL) {
5570 error = got_error_from_errno("strdup");
5571 goto done;
5576 error = got_repo_open(&repo, repo_path, NULL);
5577 if (error != NULL)
5578 goto done;
5580 error = apply_unveil(got_repo_get_path(repo), do_list,
5581 worktree ? got_worktree_get_root_path(worktree) : NULL);
5582 if (error)
5583 goto done;
5585 if (do_show)
5586 error = show_current_branch(repo, worktree);
5587 else if (do_list)
5588 error = list_branches(repo, worktree);
5589 else if (delref)
5590 error = delete_branch(repo, worktree, delref);
5591 else {
5592 if (commit_id_arg == NULL)
5593 commit_id_arg = worktree ?
5594 got_worktree_get_head_ref_name(worktree) :
5595 GOT_REF_HEAD;
5596 error = got_repo_match_object_id(&commit_id, NULL,
5597 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5598 if (error)
5599 goto done;
5600 error = add_branch(repo, argv[0], commit_id);
5601 if (error)
5602 goto done;
5603 if (worktree && do_update) {
5604 struct got_update_progress_arg upa;
5605 char *branch_refname = NULL;
5607 error = got_object_id_str(&commit_id_str, commit_id);
5608 if (error)
5609 goto done;
5610 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5611 worktree);
5612 if (error)
5613 goto done;
5614 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5615 == -1) {
5616 error = got_error_from_errno("asprintf");
5617 goto done;
5619 error = got_ref_open(&ref, repo, branch_refname, 0);
5620 free(branch_refname);
5621 if (error)
5622 goto done;
5623 error = switch_head_ref(ref, commit_id, worktree,
5624 repo);
5625 if (error)
5626 goto done;
5627 error = got_worktree_set_base_commit_id(worktree, repo,
5628 commit_id);
5629 if (error)
5630 goto done;
5631 memset(&upa, 0, sizeof(upa));
5632 error = got_worktree_checkout_files(worktree, &paths,
5633 repo, update_progress, &upa, check_cancelled,
5634 NULL);
5635 if (error)
5636 goto done;
5637 if (upa.did_something)
5638 printf("Updated to commit %s\n", commit_id_str);
5639 print_update_progress_stats(&upa);
5642 done:
5643 if (ref)
5644 got_ref_close(ref);
5645 if (repo)
5646 got_repo_close(repo);
5647 if (worktree)
5648 got_worktree_close(worktree);
5649 free(cwd);
5650 free(repo_path);
5651 free(commit_id);
5652 free(commit_id_str);
5653 TAILQ_FOREACH(pe, &paths, entry)
5654 free((char *)pe->path);
5655 got_pathlist_free(&paths);
5656 return error;
5660 __dead static void
5661 usage_tag(void)
5663 fprintf(stderr,
5664 "usage: %s tag [-c commit] [-r repository] [-l] "
5665 "[-m message] name\n", getprogname());
5666 exit(1);
5669 #if 0
5670 static const struct got_error *
5671 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5673 const struct got_error *err = NULL;
5674 struct got_reflist_entry *re, *se, *new;
5675 struct got_object_id *re_id, *se_id;
5676 struct got_tag_object *re_tag, *se_tag;
5677 time_t re_time, se_time;
5679 SIMPLEQ_FOREACH(re, tags, entry) {
5680 se = SIMPLEQ_FIRST(sorted);
5681 if (se == NULL) {
5682 err = got_reflist_entry_dup(&new, re);
5683 if (err)
5684 return err;
5685 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5686 continue;
5687 } else {
5688 err = got_ref_resolve(&re_id, repo, re->ref);
5689 if (err)
5690 break;
5691 err = got_object_open_as_tag(&re_tag, repo, re_id);
5692 free(re_id);
5693 if (err)
5694 break;
5695 re_time = got_object_tag_get_tagger_time(re_tag);
5696 got_object_tag_close(re_tag);
5699 while (se) {
5700 err = got_ref_resolve(&se_id, repo, re->ref);
5701 if (err)
5702 break;
5703 err = got_object_open_as_tag(&se_tag, repo, se_id);
5704 free(se_id);
5705 if (err)
5706 break;
5707 se_time = got_object_tag_get_tagger_time(se_tag);
5708 got_object_tag_close(se_tag);
5710 if (se_time > re_time) {
5711 err = got_reflist_entry_dup(&new, re);
5712 if (err)
5713 return err;
5714 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5715 break;
5717 se = SIMPLEQ_NEXT(se, entry);
5718 continue;
5721 done:
5722 return err;
5724 #endif
5726 static const struct got_error *
5727 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5729 static const struct got_error *err = NULL;
5730 struct got_reflist_head refs;
5731 struct got_reflist_entry *re;
5733 SIMPLEQ_INIT(&refs);
5735 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5736 if (err)
5737 return err;
5739 SIMPLEQ_FOREACH(re, &refs, entry) {
5740 const char *refname;
5741 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5742 char datebuf[26];
5743 const char *tagger;
5744 time_t tagger_time;
5745 struct got_object_id *id;
5746 struct got_tag_object *tag;
5747 struct got_commit_object *commit = NULL;
5749 refname = got_ref_get_name(re->ref);
5750 if (strncmp(refname, "refs/tags/", 10) != 0)
5751 continue;
5752 refname += 10;
5753 refstr = got_ref_to_str(re->ref);
5754 if (refstr == NULL) {
5755 err = got_error_from_errno("got_ref_to_str");
5756 break;
5758 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5759 free(refstr);
5761 err = got_ref_resolve(&id, repo, re->ref);
5762 if (err)
5763 break;
5764 err = got_object_open_as_tag(&tag, repo, id);
5765 if (err) {
5766 if (err->code != GOT_ERR_OBJ_TYPE) {
5767 free(id);
5768 break;
5770 /* "lightweight" tag */
5771 err = got_object_open_as_commit(&commit, repo, id);
5772 if (err) {
5773 free(id);
5774 break;
5776 tagger = got_object_commit_get_committer(commit);
5777 tagger_time =
5778 got_object_commit_get_committer_time(commit);
5779 err = got_object_id_str(&id_str, id);
5780 free(id);
5781 if (err)
5782 break;
5783 } else {
5784 free(id);
5785 tagger = got_object_tag_get_tagger(tag);
5786 tagger_time = got_object_tag_get_tagger_time(tag);
5787 err = got_object_id_str(&id_str,
5788 got_object_tag_get_object_id(tag));
5789 if (err)
5790 break;
5792 printf("from: %s\n", tagger);
5793 datestr = get_datestr(&tagger_time, datebuf);
5794 if (datestr)
5795 printf("date: %s UTC\n", datestr);
5796 if (commit)
5797 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5798 else {
5799 switch (got_object_tag_get_object_type(tag)) {
5800 case GOT_OBJ_TYPE_BLOB:
5801 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5802 id_str);
5803 break;
5804 case GOT_OBJ_TYPE_TREE:
5805 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5806 id_str);
5807 break;
5808 case GOT_OBJ_TYPE_COMMIT:
5809 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5810 id_str);
5811 break;
5812 case GOT_OBJ_TYPE_TAG:
5813 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5814 id_str);
5815 break;
5816 default:
5817 break;
5820 free(id_str);
5821 if (commit) {
5822 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5823 if (err)
5824 break;
5825 got_object_commit_close(commit);
5826 } else {
5827 tagmsg0 = strdup(got_object_tag_get_message(tag));
5828 got_object_tag_close(tag);
5829 if (tagmsg0 == NULL) {
5830 err = got_error_from_errno("strdup");
5831 break;
5835 tagmsg = tagmsg0;
5836 do {
5837 line = strsep(&tagmsg, "\n");
5838 if (line)
5839 printf(" %s\n", line);
5840 } while (line);
5841 free(tagmsg0);
5844 got_ref_list_free(&refs);
5845 return NULL;
5848 static const struct got_error *
5849 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5850 const char *tag_name, const char *repo_path)
5852 const struct got_error *err = NULL;
5853 char *template = NULL, *initial_content = NULL;
5854 char *editor = NULL;
5855 int initial_content_len;
5856 int fd = -1;
5858 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5859 err = got_error_from_errno("asprintf");
5860 goto done;
5863 initial_content_len = asprintf(&initial_content,
5864 "\n# tagging commit %s as %s\n",
5865 commit_id_str, tag_name);
5866 if (initial_content_len == -1) {
5867 err = got_error_from_errno("asprintf");
5868 goto done;
5871 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5872 if (err)
5873 goto done;
5875 if (write(fd, initial_content, initial_content_len) == -1) {
5876 err = got_error_from_errno2("write", *tagmsg_path);
5877 goto done;
5880 err = get_editor(&editor);
5881 if (err)
5882 goto done;
5883 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5884 initial_content_len);
5885 done:
5886 free(initial_content);
5887 free(template);
5888 free(editor);
5890 if (fd != -1 && close(fd) == -1 && err == NULL)
5891 err = got_error_from_errno2("close", *tagmsg_path);
5893 /* Editor is done; we can now apply unveil(2) */
5894 if (err == NULL)
5895 err = apply_unveil(repo_path, 0, NULL);
5896 if (err) {
5897 free(*tagmsg);
5898 *tagmsg = NULL;
5900 return err;
5903 static const struct got_error *
5904 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5905 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5907 const struct got_error *err = NULL;
5908 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5909 char *label = NULL, *commit_id_str = NULL;
5910 struct got_reference *ref = NULL;
5911 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5912 char *tagmsg_path = NULL, *tag_id_str = NULL;
5913 int preserve_tagmsg = 0;
5916 * Don't let the user create a tag name with a leading '-'.
5917 * While technically a valid reference name, this case is usually
5918 * an unintended typo.
5920 if (tag_name[0] == '-')
5921 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5923 err = get_author(&tagger, repo, worktree);
5924 if (err)
5925 return err;
5927 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5928 GOT_OBJ_TYPE_COMMIT, 1, repo);
5929 if (err)
5930 goto done;
5932 err = got_object_id_str(&commit_id_str, commit_id);
5933 if (err)
5934 goto done;
5936 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5937 refname = strdup(tag_name);
5938 if (refname == NULL) {
5939 err = got_error_from_errno("strdup");
5940 goto done;
5942 tag_name += 10;
5943 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5944 err = got_error_from_errno("asprintf");
5945 goto done;
5948 err = got_ref_open(&ref, repo, refname, 0);
5949 if (err == NULL) {
5950 err = got_error(GOT_ERR_TAG_EXISTS);
5951 goto done;
5952 } else if (err->code != GOT_ERR_NOT_REF)
5953 goto done;
5955 if (tagmsg_arg == NULL) {
5956 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5957 tag_name, got_repo_get_path(repo));
5958 if (err) {
5959 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5960 tagmsg_path != NULL)
5961 preserve_tagmsg = 1;
5962 goto done;
5966 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5967 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5968 if (err) {
5969 if (tagmsg_path)
5970 preserve_tagmsg = 1;
5971 goto done;
5974 err = got_ref_alloc(&ref, refname, tag_id);
5975 if (err) {
5976 if (tagmsg_path)
5977 preserve_tagmsg = 1;
5978 goto done;
5981 err = got_ref_write(ref, repo);
5982 if (err) {
5983 if (tagmsg_path)
5984 preserve_tagmsg = 1;
5985 goto done;
5988 err = got_object_id_str(&tag_id_str, tag_id);
5989 if (err) {
5990 if (tagmsg_path)
5991 preserve_tagmsg = 1;
5992 goto done;
5994 printf("Created tag %s\n", tag_id_str);
5995 done:
5996 if (preserve_tagmsg) {
5997 fprintf(stderr, "%s: tag message preserved in %s\n",
5998 getprogname(), tagmsg_path);
5999 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6000 err = got_error_from_errno2("unlink", tagmsg_path);
6001 free(tag_id_str);
6002 if (ref)
6003 got_ref_close(ref);
6004 free(commit_id);
6005 free(commit_id_str);
6006 free(refname);
6007 free(tagmsg);
6008 free(tagmsg_path);
6009 free(tagger);
6010 return err;
6013 static const struct got_error *
6014 cmd_tag(int argc, char *argv[])
6016 const struct got_error *error = NULL;
6017 struct got_repository *repo = NULL;
6018 struct got_worktree *worktree = NULL;
6019 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6020 char *gitconfig_path = NULL;
6021 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6022 int ch, do_list = 0;
6024 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6025 switch (ch) {
6026 case 'c':
6027 commit_id_arg = optarg;
6028 break;
6029 case 'm':
6030 tagmsg = optarg;
6031 break;
6032 case 'r':
6033 repo_path = realpath(optarg, NULL);
6034 if (repo_path == NULL)
6035 return got_error_from_errno2("realpath",
6036 optarg);
6037 got_path_strip_trailing_slashes(repo_path);
6038 break;
6039 case 'l':
6040 do_list = 1;
6041 break;
6042 default:
6043 usage_tag();
6044 /* NOTREACHED */
6048 argc -= optind;
6049 argv += optind;
6051 if (do_list) {
6052 if (commit_id_arg != NULL)
6053 errx(1,
6054 "-c option can only be used when creating a tag");
6055 if (tagmsg)
6056 errx(1, "-l and -m options are mutually exclusive");
6057 if (argc > 0)
6058 usage_tag();
6059 } else if (argc != 1)
6060 usage_tag();
6062 tag_name = argv[0];
6064 #ifndef PROFILE
6065 if (do_list) {
6066 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6067 NULL) == -1)
6068 err(1, "pledge");
6069 } else {
6070 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6071 "sendfd unveil", NULL) == -1)
6072 err(1, "pledge");
6074 #endif
6075 cwd = getcwd(NULL, 0);
6076 if (cwd == NULL) {
6077 error = got_error_from_errno("getcwd");
6078 goto done;
6081 if (repo_path == NULL) {
6082 error = got_worktree_open(&worktree, cwd);
6083 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6084 goto done;
6085 else
6086 error = NULL;
6087 if (worktree) {
6088 repo_path =
6089 strdup(got_worktree_get_repo_path(worktree));
6090 if (repo_path == NULL)
6091 error = got_error_from_errno("strdup");
6092 if (error)
6093 goto done;
6094 } else {
6095 repo_path = strdup(cwd);
6096 if (repo_path == NULL) {
6097 error = got_error_from_errno("strdup");
6098 goto done;
6103 if (do_list) {
6104 error = got_repo_open(&repo, repo_path, NULL);
6105 if (error != NULL)
6106 goto done;
6107 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6108 if (error)
6109 goto done;
6110 error = list_tags(repo, worktree);
6111 } else {
6112 error = get_gitconfig_path(&gitconfig_path);
6113 if (error)
6114 goto done;
6115 error = got_repo_open(&repo, repo_path, gitconfig_path);
6116 if (error != NULL)
6117 goto done;
6119 if (tagmsg) {
6120 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6121 if (error)
6122 goto done;
6125 if (commit_id_arg == NULL) {
6126 struct got_reference *head_ref;
6127 struct got_object_id *commit_id;
6128 error = got_ref_open(&head_ref, repo,
6129 worktree ? got_worktree_get_head_ref_name(worktree)
6130 : GOT_REF_HEAD, 0);
6131 if (error)
6132 goto done;
6133 error = got_ref_resolve(&commit_id, repo, head_ref);
6134 got_ref_close(head_ref);
6135 if (error)
6136 goto done;
6137 error = got_object_id_str(&commit_id_str, commit_id);
6138 free(commit_id);
6139 if (error)
6140 goto done;
6143 error = add_tag(repo, worktree, tag_name,
6144 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6146 done:
6147 if (repo)
6148 got_repo_close(repo);
6149 if (worktree)
6150 got_worktree_close(worktree);
6151 free(cwd);
6152 free(repo_path);
6153 free(gitconfig_path);
6154 free(commit_id_str);
6155 return error;
6158 __dead static void
6159 usage_add(void)
6161 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6162 getprogname());
6163 exit(1);
6166 static const struct got_error *
6167 add_progress(void *arg, unsigned char status, const char *path)
6169 while (path[0] == '/')
6170 path++;
6171 printf("%c %s\n", status, path);
6172 return NULL;
6175 static const struct got_error *
6176 cmd_add(int argc, char *argv[])
6178 const struct got_error *error = NULL;
6179 struct got_repository *repo = NULL;
6180 struct got_worktree *worktree = NULL;
6181 char *cwd = NULL;
6182 struct got_pathlist_head paths;
6183 struct got_pathlist_entry *pe;
6184 int ch, can_recurse = 0, no_ignores = 0;
6186 TAILQ_INIT(&paths);
6188 while ((ch = getopt(argc, argv, "IR")) != -1) {
6189 switch (ch) {
6190 case 'I':
6191 no_ignores = 1;
6192 break;
6193 case 'R':
6194 can_recurse = 1;
6195 break;
6196 default:
6197 usage_add();
6198 /* NOTREACHED */
6202 argc -= optind;
6203 argv += optind;
6205 #ifndef PROFILE
6206 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6207 NULL) == -1)
6208 err(1, "pledge");
6209 #endif
6210 if (argc < 1)
6211 usage_add();
6213 cwd = getcwd(NULL, 0);
6214 if (cwd == NULL) {
6215 error = got_error_from_errno("getcwd");
6216 goto done;
6219 error = got_worktree_open(&worktree, cwd);
6220 if (error) {
6221 if (error->code == GOT_ERR_NOT_WORKTREE)
6222 error = wrap_not_worktree_error(error, "add", cwd);
6223 goto done;
6226 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6227 NULL);
6228 if (error != NULL)
6229 goto done;
6231 error = apply_unveil(got_repo_get_path(repo), 1,
6232 got_worktree_get_root_path(worktree));
6233 if (error)
6234 goto done;
6236 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6237 if (error)
6238 goto done;
6240 if (!can_recurse && no_ignores) {
6241 error = got_error_msg(GOT_ERR_BAD_PATH,
6242 "disregarding ignores requires -R option");
6243 goto done;
6247 if (!can_recurse) {
6248 char *ondisk_path;
6249 struct stat sb;
6250 TAILQ_FOREACH(pe, &paths, entry) {
6251 if (asprintf(&ondisk_path, "%s/%s",
6252 got_worktree_get_root_path(worktree),
6253 pe->path) == -1) {
6254 error = got_error_from_errno("asprintf");
6255 goto done;
6257 if (lstat(ondisk_path, &sb) == -1) {
6258 if (errno == ENOENT) {
6259 free(ondisk_path);
6260 continue;
6262 error = got_error_from_errno2("lstat",
6263 ondisk_path);
6264 free(ondisk_path);
6265 goto done;
6267 free(ondisk_path);
6268 if (S_ISDIR(sb.st_mode)) {
6269 error = got_error_msg(GOT_ERR_BAD_PATH,
6270 "adding directories requires -R option");
6271 goto done;
6276 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6277 NULL, repo, no_ignores);
6278 done:
6279 if (repo)
6280 got_repo_close(repo);
6281 if (worktree)
6282 got_worktree_close(worktree);
6283 TAILQ_FOREACH(pe, &paths, entry)
6284 free((char *)pe->path);
6285 got_pathlist_free(&paths);
6286 free(cwd);
6287 return error;
6290 __dead static void
6291 usage_remove(void)
6293 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6294 "path ...\n", getprogname());
6295 exit(1);
6298 static const struct got_error *
6299 print_remove_status(void *arg, unsigned char status,
6300 unsigned char staged_status, const char *path)
6302 while (path[0] == '/')
6303 path++;
6304 if (status == GOT_STATUS_NONEXISTENT)
6305 return NULL;
6306 if (status == staged_status && (status == GOT_STATUS_DELETE))
6307 status = GOT_STATUS_NO_CHANGE;
6308 printf("%c%c %s\n", status, staged_status, path);
6309 return NULL;
6312 static const struct got_error *
6313 cmd_remove(int argc, char *argv[])
6315 const struct got_error *error = NULL;
6316 struct got_worktree *worktree = NULL;
6317 struct got_repository *repo = NULL;
6318 const char *status_codes = NULL;
6319 char *cwd = NULL;
6320 struct got_pathlist_head paths;
6321 struct got_pathlist_entry *pe;
6322 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6324 TAILQ_INIT(&paths);
6326 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6327 switch (ch) {
6328 case 'f':
6329 delete_local_mods = 1;
6330 break;
6331 case 'k':
6332 keep_on_disk = 1;
6333 break;
6334 case 'R':
6335 can_recurse = 1;
6336 break;
6337 case 's':
6338 for (i = 0; i < strlen(optarg); i++) {
6339 switch (optarg[i]) {
6340 case GOT_STATUS_MODIFY:
6341 delete_local_mods = 1;
6342 break;
6343 case GOT_STATUS_MISSING:
6344 break;
6345 default:
6346 errx(1, "invalid status code '%c'",
6347 optarg[i]);
6350 status_codes = optarg;
6351 break;
6352 default:
6353 usage_remove();
6354 /* NOTREACHED */
6358 argc -= optind;
6359 argv += optind;
6361 #ifndef PROFILE
6362 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6363 NULL) == -1)
6364 err(1, "pledge");
6365 #endif
6366 if (argc < 1)
6367 usage_remove();
6369 cwd = getcwd(NULL, 0);
6370 if (cwd == NULL) {
6371 error = got_error_from_errno("getcwd");
6372 goto done;
6374 error = got_worktree_open(&worktree, cwd);
6375 if (error) {
6376 if (error->code == GOT_ERR_NOT_WORKTREE)
6377 error = wrap_not_worktree_error(error, "remove", cwd);
6378 goto done;
6381 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6382 NULL);
6383 if (error)
6384 goto done;
6386 error = apply_unveil(got_repo_get_path(repo), 1,
6387 got_worktree_get_root_path(worktree));
6388 if (error)
6389 goto done;
6391 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6392 if (error)
6393 goto done;
6395 if (!can_recurse) {
6396 char *ondisk_path;
6397 struct stat sb;
6398 TAILQ_FOREACH(pe, &paths, entry) {
6399 if (asprintf(&ondisk_path, "%s/%s",
6400 got_worktree_get_root_path(worktree),
6401 pe->path) == -1) {
6402 error = got_error_from_errno("asprintf");
6403 goto done;
6405 if (lstat(ondisk_path, &sb) == -1) {
6406 if (errno == ENOENT) {
6407 free(ondisk_path);
6408 continue;
6410 error = got_error_from_errno2("lstat",
6411 ondisk_path);
6412 free(ondisk_path);
6413 goto done;
6415 free(ondisk_path);
6416 if (S_ISDIR(sb.st_mode)) {
6417 error = got_error_msg(GOT_ERR_BAD_PATH,
6418 "removing directories requires -R option");
6419 goto done;
6424 error = got_worktree_schedule_delete(worktree, &paths,
6425 delete_local_mods, status_codes, print_remove_status, NULL,
6426 repo, keep_on_disk);
6427 done:
6428 if (repo)
6429 got_repo_close(repo);
6430 if (worktree)
6431 got_worktree_close(worktree);
6432 TAILQ_FOREACH(pe, &paths, entry)
6433 free((char *)pe->path);
6434 got_pathlist_free(&paths);
6435 free(cwd);
6436 return error;
6439 __dead static void
6440 usage_revert(void)
6442 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6443 "path ...\n", getprogname());
6444 exit(1);
6447 static const struct got_error *
6448 revert_progress(void *arg, unsigned char status, const char *path)
6450 if (status == GOT_STATUS_UNVERSIONED)
6451 return NULL;
6453 while (path[0] == '/')
6454 path++;
6455 printf("%c %s\n", status, path);
6456 return NULL;
6459 struct choose_patch_arg {
6460 FILE *patch_script_file;
6461 const char *action;
6464 static const struct got_error *
6465 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6466 int nchanges, const char *action)
6468 char *line = NULL;
6469 size_t linesize = 0;
6470 ssize_t linelen;
6472 switch (status) {
6473 case GOT_STATUS_ADD:
6474 printf("A %s\n%s this addition? [y/n] ", path, action);
6475 break;
6476 case GOT_STATUS_DELETE:
6477 printf("D %s\n%s this deletion? [y/n] ", path, action);
6478 break;
6479 case GOT_STATUS_MODIFY:
6480 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6481 return got_error_from_errno("fseek");
6482 printf(GOT_COMMIT_SEP_STR);
6483 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6484 printf("%s", line);
6485 if (ferror(patch_file))
6486 return got_error_from_errno("getline");
6487 printf(GOT_COMMIT_SEP_STR);
6488 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6489 path, n, nchanges, action);
6490 break;
6491 default:
6492 return got_error_path(path, GOT_ERR_FILE_STATUS);
6495 return NULL;
6498 static const struct got_error *
6499 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6500 FILE *patch_file, int n, int nchanges)
6502 const struct got_error *err = NULL;
6503 char *line = NULL;
6504 size_t linesize = 0;
6505 ssize_t linelen;
6506 int resp = ' ';
6507 struct choose_patch_arg *a = arg;
6509 *choice = GOT_PATCH_CHOICE_NONE;
6511 if (a->patch_script_file) {
6512 char *nl;
6513 err = show_change(status, path, patch_file, n, nchanges,
6514 a->action);
6515 if (err)
6516 return err;
6517 linelen = getline(&line, &linesize, a->patch_script_file);
6518 if (linelen == -1) {
6519 if (ferror(a->patch_script_file))
6520 return got_error_from_errno("getline");
6521 return NULL;
6523 nl = strchr(line, '\n');
6524 if (nl)
6525 *nl = '\0';
6526 if (strcmp(line, "y") == 0) {
6527 *choice = GOT_PATCH_CHOICE_YES;
6528 printf("y\n");
6529 } else if (strcmp(line, "n") == 0) {
6530 *choice = GOT_PATCH_CHOICE_NO;
6531 printf("n\n");
6532 } else if (strcmp(line, "q") == 0 &&
6533 status == GOT_STATUS_MODIFY) {
6534 *choice = GOT_PATCH_CHOICE_QUIT;
6535 printf("q\n");
6536 } else
6537 printf("invalid response '%s'\n", line);
6538 free(line);
6539 return NULL;
6542 while (resp != 'y' && resp != 'n' && resp != 'q') {
6543 err = show_change(status, path, patch_file, n, nchanges,
6544 a->action);
6545 if (err)
6546 return err;
6547 resp = getchar();
6548 if (resp == '\n')
6549 resp = getchar();
6550 if (status == GOT_STATUS_MODIFY) {
6551 if (resp != 'y' && resp != 'n' && resp != 'q') {
6552 printf("invalid response '%c'\n", resp);
6553 resp = ' ';
6555 } else if (resp != 'y' && resp != 'n') {
6556 printf("invalid response '%c'\n", resp);
6557 resp = ' ';
6561 if (resp == 'y')
6562 *choice = GOT_PATCH_CHOICE_YES;
6563 else if (resp == 'n')
6564 *choice = GOT_PATCH_CHOICE_NO;
6565 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6566 *choice = GOT_PATCH_CHOICE_QUIT;
6568 return NULL;
6572 static const struct got_error *
6573 cmd_revert(int argc, char *argv[])
6575 const struct got_error *error = NULL;
6576 struct got_worktree *worktree = NULL;
6577 struct got_repository *repo = NULL;
6578 char *cwd = NULL, *path = NULL;
6579 struct got_pathlist_head paths;
6580 struct got_pathlist_entry *pe;
6581 int ch, can_recurse = 0, pflag = 0;
6582 FILE *patch_script_file = NULL;
6583 const char *patch_script_path = NULL;
6584 struct choose_patch_arg cpa;
6586 TAILQ_INIT(&paths);
6588 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6589 switch (ch) {
6590 case 'p':
6591 pflag = 1;
6592 break;
6593 case 'F':
6594 patch_script_path = optarg;
6595 break;
6596 case 'R':
6597 can_recurse = 1;
6598 break;
6599 default:
6600 usage_revert();
6601 /* NOTREACHED */
6605 argc -= optind;
6606 argv += optind;
6608 #ifndef PROFILE
6609 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6610 "unveil", NULL) == -1)
6611 err(1, "pledge");
6612 #endif
6613 if (argc < 1)
6614 usage_revert();
6615 if (patch_script_path && !pflag)
6616 errx(1, "-F option can only be used together with -p option");
6618 cwd = getcwd(NULL, 0);
6619 if (cwd == NULL) {
6620 error = got_error_from_errno("getcwd");
6621 goto done;
6623 error = got_worktree_open(&worktree, cwd);
6624 if (error) {
6625 if (error->code == GOT_ERR_NOT_WORKTREE)
6626 error = wrap_not_worktree_error(error, "revert", cwd);
6627 goto done;
6630 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6631 NULL);
6632 if (error != NULL)
6633 goto done;
6635 if (patch_script_path) {
6636 patch_script_file = fopen(patch_script_path, "r");
6637 if (patch_script_file == NULL) {
6638 error = got_error_from_errno2("fopen",
6639 patch_script_path);
6640 goto done;
6643 error = apply_unveil(got_repo_get_path(repo), 1,
6644 got_worktree_get_root_path(worktree));
6645 if (error)
6646 goto done;
6648 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6649 if (error)
6650 goto done;
6652 if (!can_recurse) {
6653 char *ondisk_path;
6654 struct stat sb;
6655 TAILQ_FOREACH(pe, &paths, entry) {
6656 if (asprintf(&ondisk_path, "%s/%s",
6657 got_worktree_get_root_path(worktree),
6658 pe->path) == -1) {
6659 error = got_error_from_errno("asprintf");
6660 goto done;
6662 if (lstat(ondisk_path, &sb) == -1) {
6663 if (errno == ENOENT) {
6664 free(ondisk_path);
6665 continue;
6667 error = got_error_from_errno2("lstat",
6668 ondisk_path);
6669 free(ondisk_path);
6670 goto done;
6672 free(ondisk_path);
6673 if (S_ISDIR(sb.st_mode)) {
6674 error = got_error_msg(GOT_ERR_BAD_PATH,
6675 "reverting directories requires -R option");
6676 goto done;
6681 cpa.patch_script_file = patch_script_file;
6682 cpa.action = "revert";
6683 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6684 pflag ? choose_patch : NULL, &cpa, repo);
6685 done:
6686 if (patch_script_file && fclose(patch_script_file) == EOF &&
6687 error == NULL)
6688 error = got_error_from_errno2("fclose", patch_script_path);
6689 if (repo)
6690 got_repo_close(repo);
6691 if (worktree)
6692 got_worktree_close(worktree);
6693 free(path);
6694 free(cwd);
6695 return error;
6698 __dead static void
6699 usage_commit(void)
6701 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6702 getprogname());
6703 exit(1);
6706 struct collect_commit_logmsg_arg {
6707 const char *cmdline_log;
6708 const char *editor;
6709 const char *worktree_path;
6710 const char *branch_name;
6711 const char *repo_path;
6712 char *logmsg_path;
6716 static const struct got_error *
6717 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6718 void *arg)
6720 char *initial_content = NULL;
6721 struct got_pathlist_entry *pe;
6722 const struct got_error *err = NULL;
6723 char *template = NULL;
6724 struct collect_commit_logmsg_arg *a = arg;
6725 int initial_content_len;
6726 int fd = -1;
6727 size_t len;
6729 /* if a message was specified on the command line, just use it */
6730 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6731 len = strlen(a->cmdline_log) + 1;
6732 *logmsg = malloc(len + 1);
6733 if (*logmsg == NULL)
6734 return got_error_from_errno("malloc");
6735 strlcpy(*logmsg, a->cmdline_log, len);
6736 return NULL;
6739 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6740 return got_error_from_errno("asprintf");
6742 initial_content_len = asprintf(&initial_content,
6743 "\n# changes to be committed on branch %s:\n",
6744 a->branch_name);
6745 if (initial_content_len == -1)
6746 return got_error_from_errno("asprintf");
6748 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6749 if (err)
6750 goto done;
6752 if (write(fd, initial_content, initial_content_len) == -1) {
6753 err = got_error_from_errno2("write", a->logmsg_path);
6754 goto done;
6757 TAILQ_FOREACH(pe, commitable_paths, entry) {
6758 struct got_commitable *ct = pe->data;
6759 dprintf(fd, "# %c %s\n",
6760 got_commitable_get_status(ct),
6761 got_commitable_get_path(ct));
6764 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6765 initial_content_len);
6766 done:
6767 free(initial_content);
6768 free(template);
6770 if (fd != -1 && close(fd) == -1 && err == NULL)
6771 err = got_error_from_errno2("close", a->logmsg_path);
6773 /* Editor is done; we can now apply unveil(2) */
6774 if (err == NULL)
6775 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6776 if (err) {
6777 free(*logmsg);
6778 *logmsg = NULL;
6780 return err;
6783 static const struct got_error *
6784 cmd_commit(int argc, char *argv[])
6786 const struct got_error *error = NULL;
6787 struct got_worktree *worktree = NULL;
6788 struct got_repository *repo = NULL;
6789 char *cwd = NULL, *id_str = NULL;
6790 struct got_object_id *id = NULL;
6791 const char *logmsg = NULL;
6792 struct collect_commit_logmsg_arg cl_arg;
6793 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6794 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6795 int allow_bad_symlinks = 0;
6796 struct got_pathlist_head paths;
6798 TAILQ_INIT(&paths);
6799 cl_arg.logmsg_path = NULL;
6801 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6802 switch (ch) {
6803 case 'm':
6804 logmsg = optarg;
6805 break;
6806 case 'S':
6807 allow_bad_symlinks = 1;
6808 break;
6809 default:
6810 usage_commit();
6811 /* NOTREACHED */
6815 argc -= optind;
6816 argv += optind;
6818 #ifndef PROFILE
6819 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6820 "unveil", NULL) == -1)
6821 err(1, "pledge");
6822 #endif
6823 cwd = getcwd(NULL, 0);
6824 if (cwd == NULL) {
6825 error = got_error_from_errno("getcwd");
6826 goto done;
6828 error = got_worktree_open(&worktree, cwd);
6829 if (error) {
6830 if (error->code == GOT_ERR_NOT_WORKTREE)
6831 error = wrap_not_worktree_error(error, "commit", cwd);
6832 goto done;
6835 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6836 if (error)
6837 goto done;
6838 if (rebase_in_progress) {
6839 error = got_error(GOT_ERR_REBASING);
6840 goto done;
6843 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6844 worktree);
6845 if (error)
6846 goto done;
6848 error = get_gitconfig_path(&gitconfig_path);
6849 if (error)
6850 goto done;
6851 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6852 gitconfig_path);
6853 if (error != NULL)
6854 goto done;
6856 error = get_author(&author, repo, worktree);
6857 if (error)
6858 return error;
6861 * unveil(2) traverses exec(2); if an editor is used we have
6862 * to apply unveil after the log message has been written.
6864 if (logmsg == NULL || strlen(logmsg) == 0)
6865 error = get_editor(&editor);
6866 else
6867 error = apply_unveil(got_repo_get_path(repo), 0,
6868 got_worktree_get_root_path(worktree));
6869 if (error)
6870 goto done;
6872 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6873 if (error)
6874 goto done;
6876 cl_arg.editor = editor;
6877 cl_arg.cmdline_log = logmsg;
6878 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6879 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6880 if (!histedit_in_progress) {
6881 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6882 error = got_error(GOT_ERR_COMMIT_BRANCH);
6883 goto done;
6885 cl_arg.branch_name += 11;
6887 cl_arg.repo_path = got_repo_get_path(repo);
6888 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6889 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6890 print_status, NULL, repo);
6891 if (error) {
6892 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6893 cl_arg.logmsg_path != NULL)
6894 preserve_logmsg = 1;
6895 goto done;
6898 error = got_object_id_str(&id_str, id);
6899 if (error)
6900 goto done;
6901 printf("Created commit %s\n", id_str);
6902 done:
6903 if (preserve_logmsg) {
6904 fprintf(stderr, "%s: log message preserved in %s\n",
6905 getprogname(), cl_arg.logmsg_path);
6906 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6907 error == NULL)
6908 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6909 free(cl_arg.logmsg_path);
6910 if (repo)
6911 got_repo_close(repo);
6912 if (worktree)
6913 got_worktree_close(worktree);
6914 free(cwd);
6915 free(id_str);
6916 free(gitconfig_path);
6917 free(editor);
6918 free(author);
6919 return error;
6922 __dead static void
6923 usage_cherrypick(void)
6925 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6926 exit(1);
6929 static const struct got_error *
6930 cmd_cherrypick(int argc, char *argv[])
6932 const struct got_error *error = NULL;
6933 struct got_worktree *worktree = NULL;
6934 struct got_repository *repo = NULL;
6935 char *cwd = NULL, *commit_id_str = NULL;
6936 struct got_object_id *commit_id = NULL;
6937 struct got_commit_object *commit = NULL;
6938 struct got_object_qid *pid;
6939 struct got_reference *head_ref = NULL;
6940 int ch;
6941 struct got_update_progress_arg upa;
6943 while ((ch = getopt(argc, argv, "")) != -1) {
6944 switch (ch) {
6945 default:
6946 usage_cherrypick();
6947 /* NOTREACHED */
6951 argc -= optind;
6952 argv += optind;
6954 #ifndef PROFILE
6955 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6956 "unveil", NULL) == -1)
6957 err(1, "pledge");
6958 #endif
6959 if (argc != 1)
6960 usage_cherrypick();
6962 cwd = getcwd(NULL, 0);
6963 if (cwd == NULL) {
6964 error = got_error_from_errno("getcwd");
6965 goto done;
6967 error = got_worktree_open(&worktree, cwd);
6968 if (error) {
6969 if (error->code == GOT_ERR_NOT_WORKTREE)
6970 error = wrap_not_worktree_error(error, "cherrypick",
6971 cwd);
6972 goto done;
6975 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6976 NULL);
6977 if (error != NULL)
6978 goto done;
6980 error = apply_unveil(got_repo_get_path(repo), 0,
6981 got_worktree_get_root_path(worktree));
6982 if (error)
6983 goto done;
6985 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6986 GOT_OBJ_TYPE_COMMIT, repo);
6987 if (error != NULL) {
6988 struct got_reference *ref;
6989 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6990 goto done;
6991 error = got_ref_open(&ref, repo, argv[0], 0);
6992 if (error != NULL)
6993 goto done;
6994 error = got_ref_resolve(&commit_id, repo, ref);
6995 got_ref_close(ref);
6996 if (error != NULL)
6997 goto done;
6999 error = got_object_id_str(&commit_id_str, commit_id);
7000 if (error)
7001 goto done;
7003 error = got_ref_open(&head_ref, repo,
7004 got_worktree_get_head_ref_name(worktree), 0);
7005 if (error != NULL)
7006 goto done;
7008 error = check_same_branch(commit_id, head_ref, NULL, repo);
7009 if (error) {
7010 if (error->code != GOT_ERR_ANCESTRY)
7011 goto done;
7012 error = NULL;
7013 } else {
7014 error = got_error(GOT_ERR_SAME_BRANCH);
7015 goto done;
7018 error = got_object_open_as_commit(&commit, repo, commit_id);
7019 if (error)
7020 goto done;
7021 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7022 memset(&upa, 0, sizeof(upa));
7023 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7024 commit_id, repo, update_progress, &upa, check_cancelled,
7025 NULL);
7026 if (error != NULL)
7027 goto done;
7029 if (upa.did_something)
7030 printf("Merged commit %s\n", commit_id_str);
7031 print_update_progress_stats(&upa);
7032 done:
7033 if (commit)
7034 got_object_commit_close(commit);
7035 free(commit_id_str);
7036 if (head_ref)
7037 got_ref_close(head_ref);
7038 if (worktree)
7039 got_worktree_close(worktree);
7040 if (repo)
7041 got_repo_close(repo);
7042 return error;
7045 __dead static void
7046 usage_backout(void)
7048 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7049 exit(1);
7052 static const struct got_error *
7053 cmd_backout(int argc, char *argv[])
7055 const struct got_error *error = NULL;
7056 struct got_worktree *worktree = NULL;
7057 struct got_repository *repo = NULL;
7058 char *cwd = NULL, *commit_id_str = NULL;
7059 struct got_object_id *commit_id = NULL;
7060 struct got_commit_object *commit = NULL;
7061 struct got_object_qid *pid;
7062 struct got_reference *head_ref = NULL;
7063 int ch;
7064 struct got_update_progress_arg upa;
7066 while ((ch = getopt(argc, argv, "")) != -1) {
7067 switch (ch) {
7068 default:
7069 usage_backout();
7070 /* NOTREACHED */
7074 argc -= optind;
7075 argv += optind;
7077 #ifndef PROFILE
7078 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7079 "unveil", NULL) == -1)
7080 err(1, "pledge");
7081 #endif
7082 if (argc != 1)
7083 usage_backout();
7085 cwd = getcwd(NULL, 0);
7086 if (cwd == NULL) {
7087 error = got_error_from_errno("getcwd");
7088 goto done;
7090 error = got_worktree_open(&worktree, cwd);
7091 if (error) {
7092 if (error->code == GOT_ERR_NOT_WORKTREE)
7093 error = wrap_not_worktree_error(error, "backout", cwd);
7094 goto done;
7097 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7098 NULL);
7099 if (error != NULL)
7100 goto done;
7102 error = apply_unveil(got_repo_get_path(repo), 0,
7103 got_worktree_get_root_path(worktree));
7104 if (error)
7105 goto done;
7107 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7108 GOT_OBJ_TYPE_COMMIT, repo);
7109 if (error != NULL) {
7110 struct got_reference *ref;
7111 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7112 goto done;
7113 error = got_ref_open(&ref, repo, argv[0], 0);
7114 if (error != NULL)
7115 goto done;
7116 error = got_ref_resolve(&commit_id, repo, ref);
7117 got_ref_close(ref);
7118 if (error != NULL)
7119 goto done;
7121 error = got_object_id_str(&commit_id_str, commit_id);
7122 if (error)
7123 goto done;
7125 error = got_ref_open(&head_ref, repo,
7126 got_worktree_get_head_ref_name(worktree), 0);
7127 if (error != NULL)
7128 goto done;
7130 error = check_same_branch(commit_id, head_ref, NULL, repo);
7131 if (error)
7132 goto done;
7134 error = got_object_open_as_commit(&commit, repo, commit_id);
7135 if (error)
7136 goto done;
7137 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7138 if (pid == NULL) {
7139 error = got_error(GOT_ERR_ROOT_COMMIT);
7140 goto done;
7143 memset(&upa, 0, sizeof(upa));
7144 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7145 update_progress, &upa, check_cancelled, NULL);
7146 if (error != NULL)
7147 goto done;
7149 if (upa.did_something)
7150 printf("Backed out commit %s\n", commit_id_str);
7151 print_update_progress_stats(&upa);
7152 done:
7153 if (commit)
7154 got_object_commit_close(commit);
7155 free(commit_id_str);
7156 if (head_ref)
7157 got_ref_close(head_ref);
7158 if (worktree)
7159 got_worktree_close(worktree);
7160 if (repo)
7161 got_repo_close(repo);
7162 return error;
7165 __dead static void
7166 usage_rebase(void)
7168 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7169 getprogname());
7170 exit(1);
7173 void
7174 trim_logmsg(char *logmsg, int limit)
7176 char *nl;
7177 size_t len;
7179 len = strlen(logmsg);
7180 if (len > limit)
7181 len = limit;
7182 logmsg[len] = '\0';
7183 nl = strchr(logmsg, '\n');
7184 if (nl)
7185 *nl = '\0';
7188 static const struct got_error *
7189 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7191 const struct got_error *err;
7192 char *logmsg0 = NULL;
7193 const char *s;
7195 err = got_object_commit_get_logmsg(&logmsg0, commit);
7196 if (err)
7197 return err;
7199 s = logmsg0;
7200 while (isspace((unsigned char)s[0]))
7201 s++;
7203 *logmsg = strdup(s);
7204 if (*logmsg == NULL) {
7205 err = got_error_from_errno("strdup");
7206 goto done;
7209 trim_logmsg(*logmsg, limit);
7210 done:
7211 free(logmsg0);
7212 return err;
7215 static const struct got_error *
7216 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7218 const struct got_error *err;
7219 struct got_commit_object *commit = NULL;
7220 char *id_str = NULL, *logmsg = NULL;
7222 err = got_object_open_as_commit(&commit, repo, id);
7223 if (err)
7224 return err;
7226 err = got_object_id_str(&id_str, id);
7227 if (err)
7228 goto done;
7230 id_str[12] = '\0';
7232 err = get_short_logmsg(&logmsg, 42, commit);
7233 if (err)
7234 goto done;
7236 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7237 done:
7238 free(id_str);
7239 got_object_commit_close(commit);
7240 free(logmsg);
7241 return err;
7244 static const struct got_error *
7245 show_rebase_progress(struct got_commit_object *commit,
7246 struct got_object_id *old_id, struct got_object_id *new_id)
7248 const struct got_error *err;
7249 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7251 err = got_object_id_str(&old_id_str, old_id);
7252 if (err)
7253 goto done;
7255 if (new_id) {
7256 err = got_object_id_str(&new_id_str, new_id);
7257 if (err)
7258 goto done;
7261 old_id_str[12] = '\0';
7262 if (new_id_str)
7263 new_id_str[12] = '\0';
7265 err = get_short_logmsg(&logmsg, 42, commit);
7266 if (err)
7267 goto done;
7269 printf("%s -> %s: %s\n", old_id_str,
7270 new_id_str ? new_id_str : "no-op change", logmsg);
7271 done:
7272 free(old_id_str);
7273 free(new_id_str);
7274 free(logmsg);
7275 return err;
7278 static const struct got_error *
7279 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7280 struct got_reference *branch, struct got_reference *new_base_branch,
7281 struct got_reference *tmp_branch, struct got_repository *repo)
7283 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7284 return got_worktree_rebase_complete(worktree, fileindex,
7285 new_base_branch, tmp_branch, branch, repo);
7288 static const struct got_error *
7289 rebase_commit(struct got_pathlist_head *merged_paths,
7290 struct got_worktree *worktree, struct got_fileindex *fileindex,
7291 struct got_reference *tmp_branch,
7292 struct got_object_id *commit_id, struct got_repository *repo)
7294 const struct got_error *error;
7295 struct got_commit_object *commit;
7296 struct got_object_id *new_commit_id;
7298 error = got_object_open_as_commit(&commit, repo, commit_id);
7299 if (error)
7300 return error;
7302 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7303 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7304 if (error) {
7305 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7306 goto done;
7307 error = show_rebase_progress(commit, commit_id, NULL);
7308 } else {
7309 error = show_rebase_progress(commit, commit_id, new_commit_id);
7310 free(new_commit_id);
7312 done:
7313 got_object_commit_close(commit);
7314 return error;
7317 struct check_path_prefix_arg {
7318 const char *path_prefix;
7319 size_t len;
7320 int errcode;
7323 static const struct got_error *
7324 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7325 struct got_blob_object *blob2, struct got_object_id *id1,
7326 struct got_object_id *id2, const char *path1, const char *path2,
7327 mode_t mode1, mode_t mode2, struct got_repository *repo)
7329 struct check_path_prefix_arg *a = arg;
7331 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7332 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7333 return got_error(a->errcode);
7335 return NULL;
7338 static const struct got_error *
7339 check_path_prefix(struct got_object_id *parent_id,
7340 struct got_object_id *commit_id, const char *path_prefix,
7341 int errcode, struct got_repository *repo)
7343 const struct got_error *err;
7344 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7345 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7346 struct check_path_prefix_arg cpp_arg;
7348 if (got_path_is_root_dir(path_prefix))
7349 return NULL;
7351 err = got_object_open_as_commit(&commit, repo, commit_id);
7352 if (err)
7353 goto done;
7355 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7356 if (err)
7357 goto done;
7359 err = got_object_open_as_tree(&tree1, repo,
7360 got_object_commit_get_tree_id(parent_commit));
7361 if (err)
7362 goto done;
7364 err = got_object_open_as_tree(&tree2, repo,
7365 got_object_commit_get_tree_id(commit));
7366 if (err)
7367 goto done;
7369 cpp_arg.path_prefix = path_prefix;
7370 while (cpp_arg.path_prefix[0] == '/')
7371 cpp_arg.path_prefix++;
7372 cpp_arg.len = strlen(cpp_arg.path_prefix);
7373 cpp_arg.errcode = errcode;
7374 err = got_diff_tree(tree1, tree2, "", "", repo,
7375 check_path_prefix_in_diff, &cpp_arg, 0);
7376 done:
7377 if (tree1)
7378 got_object_tree_close(tree1);
7379 if (tree2)
7380 got_object_tree_close(tree2);
7381 if (commit)
7382 got_object_commit_close(commit);
7383 if (parent_commit)
7384 got_object_commit_close(parent_commit);
7385 return err;
7388 static const struct got_error *
7389 collect_commits(struct got_object_id_queue *commits,
7390 struct got_object_id *initial_commit_id,
7391 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7392 const char *path_prefix, int path_prefix_errcode,
7393 struct got_repository *repo)
7395 const struct got_error *err = NULL;
7396 struct got_commit_graph *graph = NULL;
7397 struct got_object_id *parent_id = NULL;
7398 struct got_object_qid *qid;
7399 struct got_object_id *commit_id = initial_commit_id;
7401 err = got_commit_graph_open(&graph, "/", 1);
7402 if (err)
7403 return err;
7405 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7406 check_cancelled, NULL);
7407 if (err)
7408 goto done;
7409 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7410 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7411 check_cancelled, NULL);
7412 if (err) {
7413 if (err->code == GOT_ERR_ITER_COMPLETED) {
7414 err = got_error_msg(GOT_ERR_ANCESTRY,
7415 "ran out of commits to rebase before "
7416 "youngest common ancestor commit has "
7417 "been reached?!?");
7419 goto done;
7420 } else {
7421 err = check_path_prefix(parent_id, commit_id,
7422 path_prefix, path_prefix_errcode, repo);
7423 if (err)
7424 goto done;
7426 err = got_object_qid_alloc(&qid, commit_id);
7427 if (err)
7428 goto done;
7429 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7430 commit_id = parent_id;
7433 done:
7434 got_commit_graph_close(graph);
7435 return err;
7438 static const struct got_error *
7439 cmd_rebase(int argc, char *argv[])
7441 const struct got_error *error = NULL;
7442 struct got_worktree *worktree = NULL;
7443 struct got_repository *repo = NULL;
7444 struct got_fileindex *fileindex = NULL;
7445 char *cwd = NULL;
7446 struct got_reference *branch = NULL;
7447 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7448 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7449 struct got_object_id *resume_commit_id = NULL;
7450 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7451 struct got_commit_object *commit = NULL;
7452 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7453 int histedit_in_progress = 0;
7454 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7455 struct got_object_id_queue commits;
7456 struct got_pathlist_head merged_paths;
7457 const struct got_object_id_queue *parent_ids;
7458 struct got_object_qid *qid, *pid;
7460 SIMPLEQ_INIT(&commits);
7461 TAILQ_INIT(&merged_paths);
7463 while ((ch = getopt(argc, argv, "ac")) != -1) {
7464 switch (ch) {
7465 case 'a':
7466 abort_rebase = 1;
7467 break;
7468 case 'c':
7469 continue_rebase = 1;
7470 break;
7471 default:
7472 usage_rebase();
7473 /* NOTREACHED */
7477 argc -= optind;
7478 argv += optind;
7480 #ifndef PROFILE
7481 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7482 "unveil", NULL) == -1)
7483 err(1, "pledge");
7484 #endif
7485 if (abort_rebase && continue_rebase)
7486 usage_rebase();
7487 else if (abort_rebase || continue_rebase) {
7488 if (argc != 0)
7489 usage_rebase();
7490 } else if (argc != 1)
7491 usage_rebase();
7493 cwd = getcwd(NULL, 0);
7494 if (cwd == NULL) {
7495 error = got_error_from_errno("getcwd");
7496 goto done;
7498 error = got_worktree_open(&worktree, cwd);
7499 if (error) {
7500 if (error->code == GOT_ERR_NOT_WORKTREE)
7501 error = wrap_not_worktree_error(error, "rebase", cwd);
7502 goto done;
7505 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7506 NULL);
7507 if (error != NULL)
7508 goto done;
7510 error = apply_unveil(got_repo_get_path(repo), 0,
7511 got_worktree_get_root_path(worktree));
7512 if (error)
7513 goto done;
7515 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7516 worktree);
7517 if (error)
7518 goto done;
7519 if (histedit_in_progress) {
7520 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7521 goto done;
7524 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7525 if (error)
7526 goto done;
7528 if (abort_rebase) {
7529 struct got_update_progress_arg upa;
7530 if (!rebase_in_progress) {
7531 error = got_error(GOT_ERR_NOT_REBASING);
7532 goto done;
7534 error = got_worktree_rebase_continue(&resume_commit_id,
7535 &new_base_branch, &tmp_branch, &branch, &fileindex,
7536 worktree, repo);
7537 if (error)
7538 goto done;
7539 printf("Switching work tree to %s\n",
7540 got_ref_get_symref_target(new_base_branch));
7541 memset(&upa, 0, sizeof(upa));
7542 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7543 new_base_branch, update_progress, &upa);
7544 if (error)
7545 goto done;
7546 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7547 print_update_progress_stats(&upa);
7548 goto done; /* nothing else to do */
7551 if (continue_rebase) {
7552 if (!rebase_in_progress) {
7553 error = got_error(GOT_ERR_NOT_REBASING);
7554 goto done;
7556 error = got_worktree_rebase_continue(&resume_commit_id,
7557 &new_base_branch, &tmp_branch, &branch, &fileindex,
7558 worktree, repo);
7559 if (error)
7560 goto done;
7562 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7563 resume_commit_id, repo);
7564 if (error)
7565 goto done;
7567 yca_id = got_object_id_dup(resume_commit_id);
7568 if (yca_id == NULL) {
7569 error = got_error_from_errno("got_object_id_dup");
7570 goto done;
7572 } else {
7573 error = got_ref_open(&branch, repo, argv[0], 0);
7574 if (error != NULL)
7575 goto done;
7578 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7579 if (error)
7580 goto done;
7582 if (!continue_rebase) {
7583 struct got_object_id *base_commit_id;
7585 base_commit_id = got_worktree_get_base_commit_id(worktree);
7586 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7587 base_commit_id, branch_head_commit_id, repo,
7588 check_cancelled, NULL);
7589 if (error)
7590 goto done;
7591 if (yca_id == NULL) {
7592 error = got_error_msg(GOT_ERR_ANCESTRY,
7593 "specified branch shares no common ancestry "
7594 "with work tree's branch");
7595 goto done;
7598 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7599 if (error) {
7600 if (error->code != GOT_ERR_ANCESTRY)
7601 goto done;
7602 error = NULL;
7603 } else {
7604 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7605 "specified branch resolves to a commit which "
7606 "is already contained in work tree's branch");
7607 goto done;
7609 error = got_worktree_rebase_prepare(&new_base_branch,
7610 &tmp_branch, &fileindex, worktree, branch, repo);
7611 if (error)
7612 goto done;
7615 commit_id = branch_head_commit_id;
7616 error = got_object_open_as_commit(&commit, repo, commit_id);
7617 if (error)
7618 goto done;
7620 parent_ids = got_object_commit_get_parent_ids(commit);
7621 pid = SIMPLEQ_FIRST(parent_ids);
7622 if (pid == NULL) {
7623 if (!continue_rebase) {
7624 struct got_update_progress_arg upa;
7625 memset(&upa, 0, sizeof(upa));
7626 error = got_worktree_rebase_abort(worktree, fileindex,
7627 repo, new_base_branch, update_progress, &upa);
7628 if (error)
7629 goto done;
7630 printf("Rebase of %s aborted\n",
7631 got_ref_get_name(branch));
7632 print_update_progress_stats(&upa);
7635 error = got_error(GOT_ERR_EMPTY_REBASE);
7636 goto done;
7638 error = collect_commits(&commits, commit_id, pid->id,
7639 yca_id, got_worktree_get_path_prefix(worktree),
7640 GOT_ERR_REBASE_PATH, repo);
7641 got_object_commit_close(commit);
7642 commit = NULL;
7643 if (error)
7644 goto done;
7646 if (SIMPLEQ_EMPTY(&commits)) {
7647 if (continue_rebase) {
7648 error = rebase_complete(worktree, fileindex,
7649 branch, new_base_branch, tmp_branch, repo);
7650 goto done;
7651 } else {
7652 /* Fast-forward the reference of the branch. */
7653 struct got_object_id *new_head_commit_id;
7654 char *id_str;
7655 error = got_ref_resolve(&new_head_commit_id, repo,
7656 new_base_branch);
7657 if (error)
7658 goto done;
7659 error = got_object_id_str(&id_str, new_head_commit_id);
7660 printf("Forwarding %s to commit %s\n",
7661 got_ref_get_name(branch), id_str);
7662 free(id_str);
7663 error = got_ref_change_ref(branch,
7664 new_head_commit_id);
7665 if (error)
7666 goto done;
7670 pid = NULL;
7671 SIMPLEQ_FOREACH(qid, &commits, entry) {
7672 struct got_update_progress_arg upa;
7674 commit_id = qid->id;
7675 parent_id = pid ? pid->id : yca_id;
7676 pid = qid;
7678 memset(&upa, 0, sizeof(upa));
7679 error = got_worktree_rebase_merge_files(&merged_paths,
7680 worktree, fileindex, parent_id, commit_id, repo,
7681 update_progress, &upa, check_cancelled, NULL);
7682 if (error)
7683 goto done;
7685 print_update_progress_stats(&upa);
7686 if (upa.conflicts > 0)
7687 rebase_status = GOT_STATUS_CONFLICT;
7689 if (rebase_status == GOT_STATUS_CONFLICT) {
7690 error = show_rebase_merge_conflict(qid->id, repo);
7691 if (error)
7692 goto done;
7693 got_worktree_rebase_pathlist_free(&merged_paths);
7694 break;
7697 error = rebase_commit(&merged_paths, worktree, fileindex,
7698 tmp_branch, commit_id, repo);
7699 got_worktree_rebase_pathlist_free(&merged_paths);
7700 if (error)
7701 goto done;
7704 if (rebase_status == GOT_STATUS_CONFLICT) {
7705 error = got_worktree_rebase_postpone(worktree, fileindex);
7706 if (error)
7707 goto done;
7708 error = got_error_msg(GOT_ERR_CONFLICTS,
7709 "conflicts must be resolved before rebasing can continue");
7710 } else
7711 error = rebase_complete(worktree, fileindex, branch,
7712 new_base_branch, tmp_branch, repo);
7713 done:
7714 got_object_id_queue_free(&commits);
7715 free(branch_head_commit_id);
7716 free(resume_commit_id);
7717 free(yca_id);
7718 if (commit)
7719 got_object_commit_close(commit);
7720 if (branch)
7721 got_ref_close(branch);
7722 if (new_base_branch)
7723 got_ref_close(new_base_branch);
7724 if (tmp_branch)
7725 got_ref_close(tmp_branch);
7726 if (worktree)
7727 got_worktree_close(worktree);
7728 if (repo)
7729 got_repo_close(repo);
7730 return error;
7733 __dead static void
7734 usage_histedit(void)
7736 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7737 getprogname());
7738 exit(1);
7741 #define GOT_HISTEDIT_PICK 'p'
7742 #define GOT_HISTEDIT_EDIT 'e'
7743 #define GOT_HISTEDIT_FOLD 'f'
7744 #define GOT_HISTEDIT_DROP 'd'
7745 #define GOT_HISTEDIT_MESG 'm'
7747 static struct got_histedit_cmd {
7748 unsigned char code;
7749 const char *name;
7750 const char *desc;
7751 } got_histedit_cmds[] = {
7752 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7753 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7754 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7755 "be used" },
7756 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7757 { GOT_HISTEDIT_MESG, "mesg",
7758 "single-line log message for commit above (open editor if empty)" },
7761 struct got_histedit_list_entry {
7762 TAILQ_ENTRY(got_histedit_list_entry) entry;
7763 struct got_object_id *commit_id;
7764 const struct got_histedit_cmd *cmd;
7765 char *logmsg;
7767 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7769 static const struct got_error *
7770 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7771 FILE *f, struct got_repository *repo)
7773 const struct got_error *err = NULL;
7774 char *logmsg = NULL, *id_str = NULL;
7775 struct got_commit_object *commit = NULL;
7776 int n;
7778 err = got_object_open_as_commit(&commit, repo, commit_id);
7779 if (err)
7780 goto done;
7782 err = get_short_logmsg(&logmsg, 34, commit);
7783 if (err)
7784 goto done;
7786 err = got_object_id_str(&id_str, commit_id);
7787 if (err)
7788 goto done;
7790 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7791 if (n < 0)
7792 err = got_ferror(f, GOT_ERR_IO);
7793 done:
7794 if (commit)
7795 got_object_commit_close(commit);
7796 free(id_str);
7797 free(logmsg);
7798 return err;
7801 static const struct got_error *
7802 histedit_write_commit_list(struct got_object_id_queue *commits,
7803 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7805 const struct got_error *err = NULL;
7806 struct got_object_qid *qid;
7808 if (SIMPLEQ_EMPTY(commits))
7809 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7811 SIMPLEQ_FOREACH(qid, commits, entry) {
7812 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7813 f, repo);
7814 if (err)
7815 break;
7816 if (edit_logmsg_only) {
7817 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7818 if (n < 0) {
7819 err = got_ferror(f, GOT_ERR_IO);
7820 break;
7825 return err;
7828 static const struct got_error *
7829 write_cmd_list(FILE *f, const char *branch_name,
7830 struct got_object_id_queue *commits)
7832 const struct got_error *err = NULL;
7833 int n, i;
7834 char *id_str;
7835 struct got_object_qid *qid;
7837 qid = SIMPLEQ_FIRST(commits);
7838 err = got_object_id_str(&id_str, qid->id);
7839 if (err)
7840 return err;
7842 n = fprintf(f,
7843 "# Editing the history of branch '%s' starting at\n"
7844 "# commit %s\n"
7845 "# Commits will be processed in order from top to "
7846 "bottom of this file.\n", branch_name, id_str);
7847 if (n < 0) {
7848 err = got_ferror(f, GOT_ERR_IO);
7849 goto done;
7852 n = fprintf(f, "# Available histedit commands:\n");
7853 if (n < 0) {
7854 err = got_ferror(f, GOT_ERR_IO);
7855 goto done;
7858 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7859 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7860 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7861 cmd->desc);
7862 if (n < 0) {
7863 err = got_ferror(f, GOT_ERR_IO);
7864 break;
7867 done:
7868 free(id_str);
7869 return err;
7872 static const struct got_error *
7873 histedit_syntax_error(int lineno)
7875 static char msg[42];
7876 int ret;
7878 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7879 lineno);
7880 if (ret == -1 || ret >= sizeof(msg))
7881 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7883 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7886 static const struct got_error *
7887 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7888 char *logmsg, struct got_repository *repo)
7890 const struct got_error *err;
7891 struct got_commit_object *folded_commit = NULL;
7892 char *id_str, *folded_logmsg = NULL;
7894 err = got_object_id_str(&id_str, hle->commit_id);
7895 if (err)
7896 return err;
7898 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7899 if (err)
7900 goto done;
7902 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7903 if (err)
7904 goto done;
7905 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7906 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7907 folded_logmsg) == -1) {
7908 err = got_error_from_errno("asprintf");
7910 done:
7911 if (folded_commit)
7912 got_object_commit_close(folded_commit);
7913 free(id_str);
7914 free(folded_logmsg);
7915 return err;
7918 static struct got_histedit_list_entry *
7919 get_folded_commits(struct got_histedit_list_entry *hle)
7921 struct got_histedit_list_entry *prev, *folded = NULL;
7923 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7924 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7925 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7926 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7927 folded = prev;
7928 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7931 return folded;
7934 static const struct got_error *
7935 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7936 struct got_repository *repo)
7938 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7939 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7940 const struct got_error *err = NULL;
7941 struct got_commit_object *commit = NULL;
7942 int logmsg_len;
7943 int fd;
7944 struct got_histedit_list_entry *folded = NULL;
7946 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7947 if (err)
7948 return err;
7950 folded = get_folded_commits(hle);
7951 if (folded) {
7952 while (folded != hle) {
7953 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7954 folded = TAILQ_NEXT(folded, entry);
7955 continue;
7957 err = append_folded_commit_msg(&new_msg, folded,
7958 logmsg, repo);
7959 if (err)
7960 goto done;
7961 free(logmsg);
7962 logmsg = new_msg;
7963 folded = TAILQ_NEXT(folded, entry);
7967 err = got_object_id_str(&id_str, hle->commit_id);
7968 if (err)
7969 goto done;
7970 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7971 if (err)
7972 goto done;
7973 logmsg_len = asprintf(&new_msg,
7974 "%s\n# original log message of commit %s: %s",
7975 logmsg ? logmsg : "", id_str, orig_logmsg);
7976 if (logmsg_len == -1) {
7977 err = got_error_from_errno("asprintf");
7978 goto done;
7980 free(logmsg);
7981 logmsg = new_msg;
7983 err = got_object_id_str(&id_str, hle->commit_id);
7984 if (err)
7985 goto done;
7987 err = got_opentemp_named_fd(&logmsg_path, &fd,
7988 GOT_TMPDIR_STR "/got-logmsg");
7989 if (err)
7990 goto done;
7992 write(fd, logmsg, logmsg_len);
7993 close(fd);
7995 err = get_editor(&editor);
7996 if (err)
7997 goto done;
7999 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8000 logmsg_len);
8001 if (err) {
8002 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8003 goto done;
8004 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8006 done:
8007 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8008 err = got_error_from_errno2("unlink", logmsg_path);
8009 free(logmsg_path);
8010 free(logmsg);
8011 free(orig_logmsg);
8012 free(editor);
8013 if (commit)
8014 got_object_commit_close(commit);
8015 return err;
8018 static const struct got_error *
8019 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8020 FILE *f, struct got_repository *repo)
8022 const struct got_error *err = NULL;
8023 char *line = NULL, *p, *end;
8024 size_t size;
8025 ssize_t len;
8026 int lineno = 0, i;
8027 const struct got_histedit_cmd *cmd;
8028 struct got_object_id *commit_id = NULL;
8029 struct got_histedit_list_entry *hle = NULL;
8031 for (;;) {
8032 len = getline(&line, &size, f);
8033 if (len == -1) {
8034 const struct got_error *getline_err;
8035 if (feof(f))
8036 break;
8037 getline_err = got_error_from_errno("getline");
8038 err = got_ferror(f, getline_err->code);
8039 break;
8041 lineno++;
8042 p = line;
8043 while (isspace((unsigned char)p[0]))
8044 p++;
8045 if (p[0] == '#' || p[0] == '\0') {
8046 free(line);
8047 line = NULL;
8048 continue;
8050 cmd = NULL;
8051 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8052 cmd = &got_histedit_cmds[i];
8053 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8054 isspace((unsigned char)p[strlen(cmd->name)])) {
8055 p += strlen(cmd->name);
8056 break;
8058 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8059 p++;
8060 break;
8063 if (i == nitems(got_histedit_cmds)) {
8064 err = histedit_syntax_error(lineno);
8065 break;
8067 while (isspace((unsigned char)p[0]))
8068 p++;
8069 if (cmd->code == GOT_HISTEDIT_MESG) {
8070 if (hle == NULL || hle->logmsg != NULL) {
8071 err = got_error(GOT_ERR_HISTEDIT_CMD);
8072 break;
8074 if (p[0] == '\0') {
8075 err = histedit_edit_logmsg(hle, repo);
8076 if (err)
8077 break;
8078 } else {
8079 hle->logmsg = strdup(p);
8080 if (hle->logmsg == NULL) {
8081 err = got_error_from_errno("strdup");
8082 break;
8085 free(line);
8086 line = NULL;
8087 continue;
8088 } else {
8089 end = p;
8090 while (end[0] && !isspace((unsigned char)end[0]))
8091 end++;
8092 *end = '\0';
8094 err = got_object_resolve_id_str(&commit_id, repo, p);
8095 if (err) {
8096 /* override error code */
8097 err = histedit_syntax_error(lineno);
8098 break;
8101 hle = malloc(sizeof(*hle));
8102 if (hle == NULL) {
8103 err = got_error_from_errno("malloc");
8104 break;
8106 hle->cmd = cmd;
8107 hle->commit_id = commit_id;
8108 hle->logmsg = NULL;
8109 commit_id = NULL;
8110 free(line);
8111 line = NULL;
8112 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8115 free(line);
8116 free(commit_id);
8117 return err;
8120 static const struct got_error *
8121 histedit_check_script(struct got_histedit_list *histedit_cmds,
8122 struct got_object_id_queue *commits, struct got_repository *repo)
8124 const struct got_error *err = NULL;
8125 struct got_object_qid *qid;
8126 struct got_histedit_list_entry *hle;
8127 static char msg[92];
8128 char *id_str;
8130 if (TAILQ_EMPTY(histedit_cmds))
8131 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8132 "histedit script contains no commands");
8133 if (SIMPLEQ_EMPTY(commits))
8134 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8136 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8137 struct got_histedit_list_entry *hle2;
8138 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8139 if (hle == hle2)
8140 continue;
8141 if (got_object_id_cmp(hle->commit_id,
8142 hle2->commit_id) != 0)
8143 continue;
8144 err = got_object_id_str(&id_str, hle->commit_id);
8145 if (err)
8146 return err;
8147 snprintf(msg, sizeof(msg), "commit %s is listed "
8148 "more than once in histedit script", id_str);
8149 free(id_str);
8150 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8154 SIMPLEQ_FOREACH(qid, commits, entry) {
8155 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8156 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8157 break;
8159 if (hle == NULL) {
8160 err = got_object_id_str(&id_str, qid->id);
8161 if (err)
8162 return err;
8163 snprintf(msg, sizeof(msg),
8164 "commit %s missing from histedit script", id_str);
8165 free(id_str);
8166 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8170 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8171 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8172 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8173 "last commit in histedit script cannot be folded");
8175 return NULL;
8178 static const struct got_error *
8179 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8180 const char *path, struct got_object_id_queue *commits,
8181 struct got_repository *repo)
8183 const struct got_error *err = NULL;
8184 char *editor;
8185 FILE *f = NULL;
8187 err = get_editor(&editor);
8188 if (err)
8189 return err;
8191 if (spawn_editor(editor, path) == -1) {
8192 err = got_error_from_errno("failed spawning editor");
8193 goto done;
8196 f = fopen(path, "r");
8197 if (f == NULL) {
8198 err = got_error_from_errno("fopen");
8199 goto done;
8201 err = histedit_parse_list(histedit_cmds, f, repo);
8202 if (err)
8203 goto done;
8205 err = histedit_check_script(histedit_cmds, commits, repo);
8206 done:
8207 if (f && fclose(f) != 0 && err == NULL)
8208 err = got_error_from_errno("fclose");
8209 free(editor);
8210 return err;
8213 static const struct got_error *
8214 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8215 struct got_object_id_queue *, const char *, const char *,
8216 struct got_repository *);
8218 static const struct got_error *
8219 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8220 struct got_object_id_queue *commits, const char *branch_name,
8221 int edit_logmsg_only, struct got_repository *repo)
8223 const struct got_error *err;
8224 FILE *f = NULL;
8225 char *path = NULL;
8227 err = got_opentemp_named(&path, &f, "got-histedit");
8228 if (err)
8229 return err;
8231 err = write_cmd_list(f, branch_name, commits);
8232 if (err)
8233 goto done;
8235 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8236 if (err)
8237 goto done;
8239 if (edit_logmsg_only) {
8240 rewind(f);
8241 err = histedit_parse_list(histedit_cmds, f, repo);
8242 } else {
8243 if (fclose(f) != 0) {
8244 err = got_error_from_errno("fclose");
8245 goto done;
8247 f = NULL;
8248 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8249 if (err) {
8250 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8251 err->code != GOT_ERR_HISTEDIT_CMD)
8252 goto done;
8253 err = histedit_edit_list_retry(histedit_cmds, err,
8254 commits, path, branch_name, repo);
8257 done:
8258 if (f && fclose(f) != 0 && err == NULL)
8259 err = got_error_from_errno("fclose");
8260 if (path && unlink(path) != 0 && err == NULL)
8261 err = got_error_from_errno2("unlink", path);
8262 free(path);
8263 return err;
8266 static const struct got_error *
8267 histedit_save_list(struct got_histedit_list *histedit_cmds,
8268 struct got_worktree *worktree, struct got_repository *repo)
8270 const struct got_error *err = NULL;
8271 char *path = NULL;
8272 FILE *f = NULL;
8273 struct got_histedit_list_entry *hle;
8274 struct got_commit_object *commit = NULL;
8276 err = got_worktree_get_histedit_script_path(&path, worktree);
8277 if (err)
8278 return err;
8280 f = fopen(path, "w");
8281 if (f == NULL) {
8282 err = got_error_from_errno2("fopen", path);
8283 goto done;
8285 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8286 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8287 repo);
8288 if (err)
8289 break;
8291 if (hle->logmsg) {
8292 int n = fprintf(f, "%c %s\n",
8293 GOT_HISTEDIT_MESG, hle->logmsg);
8294 if (n < 0) {
8295 err = got_ferror(f, GOT_ERR_IO);
8296 break;
8300 done:
8301 if (f && fclose(f) != 0 && err == NULL)
8302 err = got_error_from_errno("fclose");
8303 free(path);
8304 if (commit)
8305 got_object_commit_close(commit);
8306 return err;
8309 void
8310 histedit_free_list(struct got_histedit_list *histedit_cmds)
8312 struct got_histedit_list_entry *hle;
8314 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8315 TAILQ_REMOVE(histedit_cmds, hle, entry);
8316 free(hle);
8320 static const struct got_error *
8321 histedit_load_list(struct got_histedit_list *histedit_cmds,
8322 const char *path, struct got_repository *repo)
8324 const struct got_error *err = NULL;
8325 FILE *f = NULL;
8327 f = fopen(path, "r");
8328 if (f == NULL) {
8329 err = got_error_from_errno2("fopen", path);
8330 goto done;
8333 err = histedit_parse_list(histedit_cmds, f, repo);
8334 done:
8335 if (f && fclose(f) != 0 && err == NULL)
8336 err = got_error_from_errno("fclose");
8337 return err;
8340 static const struct got_error *
8341 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8342 const struct got_error *edit_err, struct got_object_id_queue *commits,
8343 const char *path, const char *branch_name, struct got_repository *repo)
8345 const struct got_error *err = NULL, *prev_err = edit_err;
8346 int resp = ' ';
8348 while (resp != 'c' && resp != 'r' && resp != 'a') {
8349 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8350 "or (a)bort: ", getprogname(), prev_err->msg);
8351 resp = getchar();
8352 if (resp == '\n')
8353 resp = getchar();
8354 if (resp == 'c') {
8355 histedit_free_list(histedit_cmds);
8356 err = histedit_run_editor(histedit_cmds, path, commits,
8357 repo);
8358 if (err) {
8359 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8360 err->code != GOT_ERR_HISTEDIT_CMD)
8361 break;
8362 prev_err = err;
8363 resp = ' ';
8364 continue;
8366 break;
8367 } else if (resp == 'r') {
8368 histedit_free_list(histedit_cmds);
8369 err = histedit_edit_script(histedit_cmds,
8370 commits, branch_name, 0, repo);
8371 if (err) {
8372 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8373 err->code != GOT_ERR_HISTEDIT_CMD)
8374 break;
8375 prev_err = err;
8376 resp = ' ';
8377 continue;
8379 break;
8380 } else if (resp == 'a') {
8381 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8382 break;
8383 } else
8384 printf("invalid response '%c'\n", resp);
8387 return err;
8390 static const struct got_error *
8391 histedit_complete(struct got_worktree *worktree,
8392 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8393 struct got_reference *branch, struct got_repository *repo)
8395 printf("Switching work tree to %s\n",
8396 got_ref_get_symref_target(branch));
8397 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8398 branch, repo);
8401 static const struct got_error *
8402 show_histedit_progress(struct got_commit_object *commit,
8403 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8405 const struct got_error *err;
8406 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8408 err = got_object_id_str(&old_id_str, hle->commit_id);
8409 if (err)
8410 goto done;
8412 if (new_id) {
8413 err = got_object_id_str(&new_id_str, new_id);
8414 if (err)
8415 goto done;
8418 old_id_str[12] = '\0';
8419 if (new_id_str)
8420 new_id_str[12] = '\0';
8422 if (hle->logmsg) {
8423 logmsg = strdup(hle->logmsg);
8424 if (logmsg == NULL) {
8425 err = got_error_from_errno("strdup");
8426 goto done;
8428 trim_logmsg(logmsg, 42);
8429 } else {
8430 err = get_short_logmsg(&logmsg, 42, commit);
8431 if (err)
8432 goto done;
8435 switch (hle->cmd->code) {
8436 case GOT_HISTEDIT_PICK:
8437 case GOT_HISTEDIT_EDIT:
8438 printf("%s -> %s: %s\n", old_id_str,
8439 new_id_str ? new_id_str : "no-op change", logmsg);
8440 break;
8441 case GOT_HISTEDIT_DROP:
8442 case GOT_HISTEDIT_FOLD:
8443 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8444 logmsg);
8445 break;
8446 default:
8447 break;
8449 done:
8450 free(old_id_str);
8451 free(new_id_str);
8452 return err;
8455 static const struct got_error *
8456 histedit_commit(struct got_pathlist_head *merged_paths,
8457 struct got_worktree *worktree, struct got_fileindex *fileindex,
8458 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8459 struct got_repository *repo)
8461 const struct got_error *err;
8462 struct got_commit_object *commit;
8463 struct got_object_id *new_commit_id;
8465 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8466 && hle->logmsg == NULL) {
8467 err = histedit_edit_logmsg(hle, repo);
8468 if (err)
8469 return err;
8472 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8473 if (err)
8474 return err;
8476 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8477 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8478 hle->logmsg, repo);
8479 if (err) {
8480 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8481 goto done;
8482 err = show_histedit_progress(commit, hle, NULL);
8483 } else {
8484 err = show_histedit_progress(commit, hle, new_commit_id);
8485 free(new_commit_id);
8487 done:
8488 got_object_commit_close(commit);
8489 return err;
8492 static const struct got_error *
8493 histedit_skip_commit(struct got_histedit_list_entry *hle,
8494 struct got_worktree *worktree, struct got_repository *repo)
8496 const struct got_error *error;
8497 struct got_commit_object *commit;
8499 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8500 repo);
8501 if (error)
8502 return error;
8504 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8505 if (error)
8506 return error;
8508 error = show_histedit_progress(commit, hle, NULL);
8509 got_object_commit_close(commit);
8510 return error;
8513 static const struct got_error *
8514 check_local_changes(void *arg, unsigned char status,
8515 unsigned char staged_status, const char *path,
8516 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8517 struct got_object_id *commit_id, int dirfd, const char *de_name)
8519 int *have_local_changes = arg;
8521 switch (status) {
8522 case GOT_STATUS_ADD:
8523 case GOT_STATUS_DELETE:
8524 case GOT_STATUS_MODIFY:
8525 case GOT_STATUS_CONFLICT:
8526 *have_local_changes = 1;
8527 return got_error(GOT_ERR_CANCELLED);
8528 default:
8529 break;
8532 switch (staged_status) {
8533 case GOT_STATUS_ADD:
8534 case GOT_STATUS_DELETE:
8535 case GOT_STATUS_MODIFY:
8536 *have_local_changes = 1;
8537 return got_error(GOT_ERR_CANCELLED);
8538 default:
8539 break;
8542 return NULL;
8545 static const struct got_error *
8546 cmd_histedit(int argc, char *argv[])
8548 const struct got_error *error = NULL;
8549 struct got_worktree *worktree = NULL;
8550 struct got_fileindex *fileindex = NULL;
8551 struct got_repository *repo = NULL;
8552 char *cwd = NULL;
8553 struct got_reference *branch = NULL;
8554 struct got_reference *tmp_branch = NULL;
8555 struct got_object_id *resume_commit_id = NULL;
8556 struct got_object_id *base_commit_id = NULL;
8557 struct got_object_id *head_commit_id = NULL;
8558 struct got_commit_object *commit = NULL;
8559 int ch, rebase_in_progress = 0;
8560 struct got_update_progress_arg upa;
8561 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8562 int edit_logmsg_only = 0;
8563 const char *edit_script_path = NULL;
8564 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8565 struct got_object_id_queue commits;
8566 struct got_pathlist_head merged_paths;
8567 const struct got_object_id_queue *parent_ids;
8568 struct got_object_qid *pid;
8569 struct got_histedit_list histedit_cmds;
8570 struct got_histedit_list_entry *hle;
8572 SIMPLEQ_INIT(&commits);
8573 TAILQ_INIT(&histedit_cmds);
8574 TAILQ_INIT(&merged_paths);
8575 memset(&upa, 0, sizeof(upa));
8577 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8578 switch (ch) {
8579 case 'a':
8580 abort_edit = 1;
8581 break;
8582 case 'c':
8583 continue_edit = 1;
8584 break;
8585 case 'F':
8586 edit_script_path = optarg;
8587 break;
8588 case 'm':
8589 edit_logmsg_only = 1;
8590 break;
8591 default:
8592 usage_histedit();
8593 /* NOTREACHED */
8597 argc -= optind;
8598 argv += optind;
8600 #ifndef PROFILE
8601 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8602 "unveil", NULL) == -1)
8603 err(1, "pledge");
8604 #endif
8605 if (abort_edit && continue_edit)
8606 errx(1, "histedit's -a and -c options are mutually exclusive");
8607 if (edit_script_path && edit_logmsg_only)
8608 errx(1, "histedit's -F and -m options are mutually exclusive");
8609 if (abort_edit && edit_logmsg_only)
8610 errx(1, "histedit's -a and -m options are mutually exclusive");
8611 if (continue_edit && edit_logmsg_only)
8612 errx(1, "histedit's -c and -m options are mutually exclusive");
8613 if (argc != 0)
8614 usage_histedit();
8617 * This command cannot apply unveil(2) in all cases because the
8618 * user may choose to run an editor to edit the histedit script
8619 * and to edit individual commit log messages.
8620 * unveil(2) traverses exec(2); if an editor is used we have to
8621 * apply unveil after edit script and log messages have been written.
8622 * XXX TODO: Make use of unveil(2) where possible.
8625 cwd = getcwd(NULL, 0);
8626 if (cwd == NULL) {
8627 error = got_error_from_errno("getcwd");
8628 goto done;
8630 error = got_worktree_open(&worktree, cwd);
8631 if (error) {
8632 if (error->code == GOT_ERR_NOT_WORKTREE)
8633 error = wrap_not_worktree_error(error, "histedit", cwd);
8634 goto done;
8637 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8638 NULL);
8639 if (error != NULL)
8640 goto done;
8642 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8643 if (error)
8644 goto done;
8645 if (rebase_in_progress) {
8646 error = got_error(GOT_ERR_REBASING);
8647 goto done;
8650 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8651 if (error)
8652 goto done;
8654 if (edit_in_progress && edit_logmsg_only) {
8655 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8656 "histedit operation is in progress in this "
8657 "work tree and must be continued or aborted "
8658 "before the -m option can be used");
8659 goto done;
8662 if (edit_in_progress && abort_edit) {
8663 error = got_worktree_histedit_continue(&resume_commit_id,
8664 &tmp_branch, &branch, &base_commit_id, &fileindex,
8665 worktree, repo);
8666 if (error)
8667 goto done;
8668 printf("Switching work tree to %s\n",
8669 got_ref_get_symref_target(branch));
8670 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8671 branch, base_commit_id, update_progress, &upa);
8672 if (error)
8673 goto done;
8674 printf("Histedit of %s aborted\n",
8675 got_ref_get_symref_target(branch));
8676 print_update_progress_stats(&upa);
8677 goto done; /* nothing else to do */
8678 } else if (abort_edit) {
8679 error = got_error(GOT_ERR_NOT_HISTEDIT);
8680 goto done;
8683 if (continue_edit) {
8684 char *path;
8686 if (!edit_in_progress) {
8687 error = got_error(GOT_ERR_NOT_HISTEDIT);
8688 goto done;
8691 error = got_worktree_get_histedit_script_path(&path, worktree);
8692 if (error)
8693 goto done;
8695 error = histedit_load_list(&histedit_cmds, path, repo);
8696 free(path);
8697 if (error)
8698 goto done;
8700 error = got_worktree_histedit_continue(&resume_commit_id,
8701 &tmp_branch, &branch, &base_commit_id, &fileindex,
8702 worktree, repo);
8703 if (error)
8704 goto done;
8706 error = got_ref_resolve(&head_commit_id, repo, branch);
8707 if (error)
8708 goto done;
8710 error = got_object_open_as_commit(&commit, repo,
8711 head_commit_id);
8712 if (error)
8713 goto done;
8714 parent_ids = got_object_commit_get_parent_ids(commit);
8715 pid = SIMPLEQ_FIRST(parent_ids);
8716 if (pid == NULL) {
8717 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8718 goto done;
8720 error = collect_commits(&commits, head_commit_id, pid->id,
8721 base_commit_id, got_worktree_get_path_prefix(worktree),
8722 GOT_ERR_HISTEDIT_PATH, repo);
8723 got_object_commit_close(commit);
8724 commit = NULL;
8725 if (error)
8726 goto done;
8727 } else {
8728 if (edit_in_progress) {
8729 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8730 goto done;
8733 error = got_ref_open(&branch, repo,
8734 got_worktree_get_head_ref_name(worktree), 0);
8735 if (error != NULL)
8736 goto done;
8738 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8739 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8740 "will not edit commit history of a branch outside "
8741 "the \"refs/heads/\" reference namespace");
8742 goto done;
8745 error = got_ref_resolve(&head_commit_id, repo, branch);
8746 got_ref_close(branch);
8747 branch = NULL;
8748 if (error)
8749 goto done;
8751 error = got_object_open_as_commit(&commit, repo,
8752 head_commit_id);
8753 if (error)
8754 goto done;
8755 parent_ids = got_object_commit_get_parent_ids(commit);
8756 pid = SIMPLEQ_FIRST(parent_ids);
8757 if (pid == NULL) {
8758 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8759 goto done;
8761 error = collect_commits(&commits, head_commit_id, pid->id,
8762 got_worktree_get_base_commit_id(worktree),
8763 got_worktree_get_path_prefix(worktree),
8764 GOT_ERR_HISTEDIT_PATH, repo);
8765 got_object_commit_close(commit);
8766 commit = NULL;
8767 if (error)
8768 goto done;
8770 if (SIMPLEQ_EMPTY(&commits)) {
8771 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8772 goto done;
8775 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8776 &base_commit_id, &fileindex, worktree, repo);
8777 if (error)
8778 goto done;
8780 if (edit_script_path) {
8781 error = histedit_load_list(&histedit_cmds,
8782 edit_script_path, repo);
8783 if (error) {
8784 got_worktree_histedit_abort(worktree, fileindex,
8785 repo, branch, base_commit_id,
8786 update_progress, &upa);
8787 print_update_progress_stats(&upa);
8788 goto done;
8790 } else {
8791 const char *branch_name;
8792 branch_name = got_ref_get_symref_target(branch);
8793 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8794 branch_name += 11;
8795 error = histedit_edit_script(&histedit_cmds, &commits,
8796 branch_name, edit_logmsg_only, repo);
8797 if (error) {
8798 got_worktree_histedit_abort(worktree, fileindex,
8799 repo, branch, base_commit_id,
8800 update_progress, &upa);
8801 print_update_progress_stats(&upa);
8802 goto done;
8807 error = histedit_save_list(&histedit_cmds, worktree,
8808 repo);
8809 if (error) {
8810 got_worktree_histedit_abort(worktree, fileindex,
8811 repo, branch, base_commit_id,
8812 update_progress, &upa);
8813 print_update_progress_stats(&upa);
8814 goto done;
8819 error = histedit_check_script(&histedit_cmds, &commits, repo);
8820 if (error)
8821 goto done;
8823 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8824 if (resume_commit_id) {
8825 if (got_object_id_cmp(hle->commit_id,
8826 resume_commit_id) != 0)
8827 continue;
8829 resume_commit_id = NULL;
8830 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8831 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8832 error = histedit_skip_commit(hle, worktree,
8833 repo);
8834 if (error)
8835 goto done;
8836 } else {
8837 struct got_pathlist_head paths;
8838 int have_changes = 0;
8840 TAILQ_INIT(&paths);
8841 error = got_pathlist_append(&paths, "", NULL);
8842 if (error)
8843 goto done;
8844 error = got_worktree_status(worktree, &paths,
8845 repo, check_local_changes, &have_changes,
8846 check_cancelled, NULL);
8847 got_pathlist_free(&paths);
8848 if (error) {
8849 if (error->code != GOT_ERR_CANCELLED)
8850 goto done;
8851 if (sigint_received || sigpipe_received)
8852 goto done;
8854 if (have_changes) {
8855 error = histedit_commit(NULL, worktree,
8856 fileindex, tmp_branch, hle, repo);
8857 if (error)
8858 goto done;
8859 } else {
8860 error = got_object_open_as_commit(
8861 &commit, repo, hle->commit_id);
8862 if (error)
8863 goto done;
8864 error = show_histedit_progress(commit,
8865 hle, NULL);
8866 got_object_commit_close(commit);
8867 commit = NULL;
8868 if (error)
8869 goto done;
8872 continue;
8875 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8876 error = histedit_skip_commit(hle, worktree, repo);
8877 if (error)
8878 goto done;
8879 continue;
8882 error = got_object_open_as_commit(&commit, repo,
8883 hle->commit_id);
8884 if (error)
8885 goto done;
8886 parent_ids = got_object_commit_get_parent_ids(commit);
8887 pid = SIMPLEQ_FIRST(parent_ids);
8889 error = got_worktree_histedit_merge_files(&merged_paths,
8890 worktree, fileindex, pid->id, hle->commit_id, repo,
8891 update_progress, &upa, check_cancelled, NULL);
8892 if (error)
8893 goto done;
8894 got_object_commit_close(commit);
8895 commit = NULL;
8897 print_update_progress_stats(&upa);
8898 if (upa.conflicts > 0)
8899 rebase_status = GOT_STATUS_CONFLICT;
8901 if (rebase_status == GOT_STATUS_CONFLICT) {
8902 error = show_rebase_merge_conflict(hle->commit_id,
8903 repo);
8904 if (error)
8905 goto done;
8906 got_worktree_rebase_pathlist_free(&merged_paths);
8907 break;
8910 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8911 char *id_str;
8912 error = got_object_id_str(&id_str, hle->commit_id);
8913 if (error)
8914 goto done;
8915 printf("Stopping histedit for amending commit %s\n",
8916 id_str);
8917 free(id_str);
8918 got_worktree_rebase_pathlist_free(&merged_paths);
8919 error = got_worktree_histedit_postpone(worktree,
8920 fileindex);
8921 goto done;
8924 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8925 error = histedit_skip_commit(hle, worktree, repo);
8926 if (error)
8927 goto done;
8928 continue;
8931 error = histedit_commit(&merged_paths, worktree, fileindex,
8932 tmp_branch, hle, repo);
8933 got_worktree_rebase_pathlist_free(&merged_paths);
8934 if (error)
8935 goto done;
8938 if (rebase_status == GOT_STATUS_CONFLICT) {
8939 error = got_worktree_histedit_postpone(worktree, fileindex);
8940 if (error)
8941 goto done;
8942 error = got_error_msg(GOT_ERR_CONFLICTS,
8943 "conflicts must be resolved before histedit can continue");
8944 } else
8945 error = histedit_complete(worktree, fileindex, tmp_branch,
8946 branch, repo);
8947 done:
8948 got_object_id_queue_free(&commits);
8949 histedit_free_list(&histedit_cmds);
8950 free(head_commit_id);
8951 free(base_commit_id);
8952 free(resume_commit_id);
8953 if (commit)
8954 got_object_commit_close(commit);
8955 if (branch)
8956 got_ref_close(branch);
8957 if (tmp_branch)
8958 got_ref_close(tmp_branch);
8959 if (worktree)
8960 got_worktree_close(worktree);
8961 if (repo)
8962 got_repo_close(repo);
8963 return error;
8966 __dead static void
8967 usage_integrate(void)
8969 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8970 exit(1);
8973 static const struct got_error *
8974 cmd_integrate(int argc, char *argv[])
8976 const struct got_error *error = NULL;
8977 struct got_repository *repo = NULL;
8978 struct got_worktree *worktree = NULL;
8979 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8980 const char *branch_arg = NULL;
8981 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8982 struct got_fileindex *fileindex = NULL;
8983 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8984 int ch;
8985 struct got_update_progress_arg upa;
8987 while ((ch = getopt(argc, argv, "")) != -1) {
8988 switch (ch) {
8989 default:
8990 usage_integrate();
8991 /* NOTREACHED */
8995 argc -= optind;
8996 argv += optind;
8998 if (argc != 1)
8999 usage_integrate();
9000 branch_arg = argv[0];
9001 #ifndef PROFILE
9002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9003 "unveil", NULL) == -1)
9004 err(1, "pledge");
9005 #endif
9006 cwd = getcwd(NULL, 0);
9007 if (cwd == NULL) {
9008 error = got_error_from_errno("getcwd");
9009 goto done;
9012 error = got_worktree_open(&worktree, cwd);
9013 if (error) {
9014 if (error->code == GOT_ERR_NOT_WORKTREE)
9015 error = wrap_not_worktree_error(error, "integrate",
9016 cwd);
9017 goto done;
9020 error = check_rebase_or_histedit_in_progress(worktree);
9021 if (error)
9022 goto done;
9024 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9025 NULL);
9026 if (error != NULL)
9027 goto done;
9029 error = apply_unveil(got_repo_get_path(repo), 0,
9030 got_worktree_get_root_path(worktree));
9031 if (error)
9032 goto done;
9034 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9035 error = got_error_from_errno("asprintf");
9036 goto done;
9039 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9040 &base_branch_ref, worktree, refname, repo);
9041 if (error)
9042 goto done;
9044 refname = strdup(got_ref_get_name(branch_ref));
9045 if (refname == NULL) {
9046 error = got_error_from_errno("strdup");
9047 got_worktree_integrate_abort(worktree, fileindex, repo,
9048 branch_ref, base_branch_ref);
9049 goto done;
9051 base_refname = strdup(got_ref_get_name(base_branch_ref));
9052 if (base_refname == NULL) {
9053 error = got_error_from_errno("strdup");
9054 got_worktree_integrate_abort(worktree, fileindex, repo,
9055 branch_ref, base_branch_ref);
9056 goto done;
9059 error = got_ref_resolve(&commit_id, repo, branch_ref);
9060 if (error)
9061 goto done;
9063 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9064 if (error)
9065 goto done;
9067 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9068 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9069 "specified branch has already been integrated");
9070 got_worktree_integrate_abort(worktree, fileindex, repo,
9071 branch_ref, base_branch_ref);
9072 goto done;
9075 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9076 if (error) {
9077 if (error->code == GOT_ERR_ANCESTRY)
9078 error = got_error(GOT_ERR_REBASE_REQUIRED);
9079 got_worktree_integrate_abort(worktree, fileindex, repo,
9080 branch_ref, base_branch_ref);
9081 goto done;
9084 memset(&upa, 0, sizeof(upa));
9085 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9086 branch_ref, base_branch_ref, update_progress, &upa,
9087 check_cancelled, NULL);
9088 if (error)
9089 goto done;
9091 printf("Integrated %s into %s\n", refname, base_refname);
9092 print_update_progress_stats(&upa);
9093 done:
9094 if (repo)
9095 got_repo_close(repo);
9096 if (worktree)
9097 got_worktree_close(worktree);
9098 free(cwd);
9099 free(base_commit_id);
9100 free(commit_id);
9101 free(refname);
9102 free(base_refname);
9103 return error;
9106 __dead static void
9107 usage_stage(void)
9109 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9110 "[-S] [file-path ...]\n",
9111 getprogname());
9112 exit(1);
9115 static const struct got_error *
9116 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9117 const char *path, struct got_object_id *blob_id,
9118 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9119 int dirfd, const char *de_name)
9121 const struct got_error *err = NULL;
9122 char *id_str = NULL;
9124 if (staged_status != GOT_STATUS_ADD &&
9125 staged_status != GOT_STATUS_MODIFY &&
9126 staged_status != GOT_STATUS_DELETE)
9127 return NULL;
9129 if (staged_status == GOT_STATUS_ADD ||
9130 staged_status == GOT_STATUS_MODIFY)
9131 err = got_object_id_str(&id_str, staged_blob_id);
9132 else
9133 err = got_object_id_str(&id_str, blob_id);
9134 if (err)
9135 return err;
9137 printf("%s %c %s\n", id_str, staged_status, path);
9138 free(id_str);
9139 return NULL;
9142 static const struct got_error *
9143 cmd_stage(int argc, char *argv[])
9145 const struct got_error *error = NULL;
9146 struct got_repository *repo = NULL;
9147 struct got_worktree *worktree = NULL;
9148 char *cwd = NULL;
9149 struct got_pathlist_head paths;
9150 struct got_pathlist_entry *pe;
9151 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9152 FILE *patch_script_file = NULL;
9153 const char *patch_script_path = NULL;
9154 struct choose_patch_arg cpa;
9156 TAILQ_INIT(&paths);
9158 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9159 switch (ch) {
9160 case 'l':
9161 list_stage = 1;
9162 break;
9163 case 'p':
9164 pflag = 1;
9165 break;
9166 case 'F':
9167 patch_script_path = optarg;
9168 break;
9169 case 'S':
9170 allow_bad_symlinks = 1;
9171 break;
9172 default:
9173 usage_stage();
9174 /* NOTREACHED */
9178 argc -= optind;
9179 argv += optind;
9181 #ifndef PROFILE
9182 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9183 "unveil", NULL) == -1)
9184 err(1, "pledge");
9185 #endif
9186 if (list_stage && (pflag || patch_script_path))
9187 errx(1, "-l option cannot be used with other options");
9188 if (patch_script_path && !pflag)
9189 errx(1, "-F option can only be used together with -p option");
9191 cwd = getcwd(NULL, 0);
9192 if (cwd == NULL) {
9193 error = got_error_from_errno("getcwd");
9194 goto done;
9197 error = got_worktree_open(&worktree, cwd);
9198 if (error) {
9199 if (error->code == GOT_ERR_NOT_WORKTREE)
9200 error = wrap_not_worktree_error(error, "stage", cwd);
9201 goto done;
9204 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9205 NULL);
9206 if (error != NULL)
9207 goto done;
9209 if (patch_script_path) {
9210 patch_script_file = fopen(patch_script_path, "r");
9211 if (patch_script_file == NULL) {
9212 error = got_error_from_errno2("fopen",
9213 patch_script_path);
9214 goto done;
9217 error = apply_unveil(got_repo_get_path(repo), 0,
9218 got_worktree_get_root_path(worktree));
9219 if (error)
9220 goto done;
9222 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9223 if (error)
9224 goto done;
9226 if (list_stage)
9227 error = got_worktree_status(worktree, &paths, repo,
9228 print_stage, NULL, check_cancelled, NULL);
9229 else {
9230 cpa.patch_script_file = patch_script_file;
9231 cpa.action = "stage";
9232 error = got_worktree_stage(worktree, &paths,
9233 pflag ? NULL : print_status, NULL,
9234 pflag ? choose_patch : NULL, &cpa,
9235 allow_bad_symlinks, repo);
9237 done:
9238 if (patch_script_file && fclose(patch_script_file) == EOF &&
9239 error == NULL)
9240 error = got_error_from_errno2("fclose", patch_script_path);
9241 if (repo)
9242 got_repo_close(repo);
9243 if (worktree)
9244 got_worktree_close(worktree);
9245 TAILQ_FOREACH(pe, &paths, entry)
9246 free((char *)pe->path);
9247 got_pathlist_free(&paths);
9248 free(cwd);
9249 return error;
9252 __dead static void
9253 usage_unstage(void)
9255 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9256 "[file-path ...]\n",
9257 getprogname());
9258 exit(1);
9262 static const struct got_error *
9263 cmd_unstage(int argc, char *argv[])
9265 const struct got_error *error = NULL;
9266 struct got_repository *repo = NULL;
9267 struct got_worktree *worktree = NULL;
9268 char *cwd = NULL;
9269 struct got_pathlist_head paths;
9270 struct got_pathlist_entry *pe;
9271 int ch, pflag = 0;
9272 struct got_update_progress_arg upa;
9273 FILE *patch_script_file = NULL;
9274 const char *patch_script_path = NULL;
9275 struct choose_patch_arg cpa;
9277 TAILQ_INIT(&paths);
9279 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9280 switch (ch) {
9281 case 'p':
9282 pflag = 1;
9283 break;
9284 case 'F':
9285 patch_script_path = optarg;
9286 break;
9287 default:
9288 usage_unstage();
9289 /* NOTREACHED */
9293 argc -= optind;
9294 argv += optind;
9296 #ifndef PROFILE
9297 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9298 "unveil", NULL) == -1)
9299 err(1, "pledge");
9300 #endif
9301 if (patch_script_path && !pflag)
9302 errx(1, "-F option can only be used together with -p option");
9304 cwd = getcwd(NULL, 0);
9305 if (cwd == NULL) {
9306 error = got_error_from_errno("getcwd");
9307 goto done;
9310 error = got_worktree_open(&worktree, cwd);
9311 if (error) {
9312 if (error->code == GOT_ERR_NOT_WORKTREE)
9313 error = wrap_not_worktree_error(error, "unstage", cwd);
9314 goto done;
9317 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9318 NULL);
9319 if (error != NULL)
9320 goto done;
9322 if (patch_script_path) {
9323 patch_script_file = fopen(patch_script_path, "r");
9324 if (patch_script_file == NULL) {
9325 error = got_error_from_errno2("fopen",
9326 patch_script_path);
9327 goto done;
9331 error = apply_unveil(got_repo_get_path(repo), 0,
9332 got_worktree_get_root_path(worktree));
9333 if (error)
9334 goto done;
9336 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9337 if (error)
9338 goto done;
9340 cpa.patch_script_file = patch_script_file;
9341 cpa.action = "unstage";
9342 memset(&upa, 0, sizeof(upa));
9343 error = got_worktree_unstage(worktree, &paths, update_progress,
9344 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9345 if (!error)
9346 print_update_progress_stats(&upa);
9347 done:
9348 if (patch_script_file && fclose(patch_script_file) == EOF &&
9349 error == NULL)
9350 error = got_error_from_errno2("fclose", patch_script_path);
9351 if (repo)
9352 got_repo_close(repo);
9353 if (worktree)
9354 got_worktree_close(worktree);
9355 TAILQ_FOREACH(pe, &paths, entry)
9356 free((char *)pe->path);
9357 got_pathlist_free(&paths);
9358 free(cwd);
9359 return error;
9362 __dead static void
9363 usage_cat(void)
9365 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9366 "arg1 [arg2 ...]\n", getprogname());
9367 exit(1);
9370 static const struct got_error *
9371 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9373 const struct got_error *err;
9374 struct got_blob_object *blob;
9376 err = got_object_open_as_blob(&blob, repo, id, 8192);
9377 if (err)
9378 return err;
9380 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9381 got_object_blob_close(blob);
9382 return err;
9385 static const struct got_error *
9386 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9388 const struct got_error *err;
9389 struct got_tree_object *tree;
9390 int nentries, i;
9392 err = got_object_open_as_tree(&tree, repo, id);
9393 if (err)
9394 return err;
9396 nentries = got_object_tree_get_nentries(tree);
9397 for (i = 0; i < nentries; i++) {
9398 struct got_tree_entry *te;
9399 char *id_str;
9400 if (sigint_received || sigpipe_received)
9401 break;
9402 te = got_object_tree_get_entry(tree, i);
9403 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9404 if (err)
9405 break;
9406 fprintf(outfile, "%s %.7o %s\n", id_str,
9407 got_tree_entry_get_mode(te),
9408 got_tree_entry_get_name(te));
9409 free(id_str);
9412 got_object_tree_close(tree);
9413 return err;
9416 static const struct got_error *
9417 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9419 const struct got_error *err;
9420 struct got_commit_object *commit;
9421 const struct got_object_id_queue *parent_ids;
9422 struct got_object_qid *pid;
9423 char *id_str = NULL;
9424 const char *logmsg = NULL;
9426 err = got_object_open_as_commit(&commit, repo, id);
9427 if (err)
9428 return err;
9430 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9431 if (err)
9432 goto done;
9434 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9435 parent_ids = got_object_commit_get_parent_ids(commit);
9436 fprintf(outfile, "numparents %d\n",
9437 got_object_commit_get_nparents(commit));
9438 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9439 char *pid_str;
9440 err = got_object_id_str(&pid_str, pid->id);
9441 if (err)
9442 goto done;
9443 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9444 free(pid_str);
9446 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9447 got_object_commit_get_author(commit),
9448 (long long)got_object_commit_get_author_time(commit));
9450 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9451 got_object_commit_get_author(commit),
9452 (long long)got_object_commit_get_committer_time(commit));
9454 logmsg = got_object_commit_get_logmsg_raw(commit);
9455 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9456 fprintf(outfile, "%s", logmsg);
9457 done:
9458 free(id_str);
9459 got_object_commit_close(commit);
9460 return err;
9463 static const struct got_error *
9464 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9466 const struct got_error *err;
9467 struct got_tag_object *tag;
9468 char *id_str = NULL;
9469 const char *tagmsg = NULL;
9471 err = got_object_open_as_tag(&tag, repo, id);
9472 if (err)
9473 return err;
9475 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9476 if (err)
9477 goto done;
9479 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9481 switch (got_object_tag_get_object_type(tag)) {
9482 case GOT_OBJ_TYPE_BLOB:
9483 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9484 GOT_OBJ_LABEL_BLOB);
9485 break;
9486 case GOT_OBJ_TYPE_TREE:
9487 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9488 GOT_OBJ_LABEL_TREE);
9489 break;
9490 case GOT_OBJ_TYPE_COMMIT:
9491 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9492 GOT_OBJ_LABEL_COMMIT);
9493 break;
9494 case GOT_OBJ_TYPE_TAG:
9495 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9496 GOT_OBJ_LABEL_TAG);
9497 break;
9498 default:
9499 break;
9502 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9503 got_object_tag_get_name(tag));
9505 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9506 got_object_tag_get_tagger(tag),
9507 (long long)got_object_tag_get_tagger_time(tag));
9509 tagmsg = got_object_tag_get_message(tag);
9510 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9511 fprintf(outfile, "%s", tagmsg);
9512 done:
9513 free(id_str);
9514 got_object_tag_close(tag);
9515 return err;
9518 static const struct got_error *
9519 cmd_cat(int argc, char *argv[])
9521 const struct got_error *error;
9522 struct got_repository *repo = NULL;
9523 struct got_worktree *worktree = NULL;
9524 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9525 const char *commit_id_str = NULL;
9526 struct got_object_id *id = NULL, *commit_id = NULL;
9527 int ch, obj_type, i, force_path = 0;
9529 #ifndef PROFILE
9530 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9531 NULL) == -1)
9532 err(1, "pledge");
9533 #endif
9535 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9536 switch (ch) {
9537 case 'c':
9538 commit_id_str = optarg;
9539 break;
9540 case 'r':
9541 repo_path = realpath(optarg, NULL);
9542 if (repo_path == NULL)
9543 return got_error_from_errno2("realpath",
9544 optarg);
9545 got_path_strip_trailing_slashes(repo_path);
9546 break;
9547 case 'P':
9548 force_path = 1;
9549 break;
9550 default:
9551 usage_cat();
9552 /* NOTREACHED */
9556 argc -= optind;
9557 argv += optind;
9559 cwd = getcwd(NULL, 0);
9560 if (cwd == NULL) {
9561 error = got_error_from_errno("getcwd");
9562 goto done;
9564 error = got_worktree_open(&worktree, cwd);
9565 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9566 goto done;
9567 if (worktree) {
9568 if (repo_path == NULL) {
9569 repo_path = strdup(
9570 got_worktree_get_repo_path(worktree));
9571 if (repo_path == NULL) {
9572 error = got_error_from_errno("strdup");
9573 goto done;
9578 if (repo_path == NULL) {
9579 repo_path = getcwd(NULL, 0);
9580 if (repo_path == NULL)
9581 return got_error_from_errno("getcwd");
9584 error = got_repo_open(&repo, repo_path, NULL);
9585 free(repo_path);
9586 if (error != NULL)
9587 goto done;
9589 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9590 if (error)
9591 goto done;
9593 if (commit_id_str == NULL)
9594 commit_id_str = GOT_REF_HEAD;
9595 error = got_repo_match_object_id(&commit_id, NULL,
9596 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9597 if (error)
9598 goto done;
9600 for (i = 0; i < argc; i++) {
9601 if (force_path) {
9602 error = got_object_id_by_path(&id, repo, commit_id,
9603 argv[i]);
9604 if (error)
9605 break;
9606 } else {
9607 error = got_repo_match_object_id(&id, &label, argv[i],
9608 GOT_OBJ_TYPE_ANY, 0, repo);
9609 if (error) {
9610 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9611 error->code != GOT_ERR_NOT_REF)
9612 break;
9613 error = got_object_id_by_path(&id, repo,
9614 commit_id, argv[i]);
9615 if (error)
9616 break;
9620 error = got_object_get_type(&obj_type, repo, id);
9621 if (error)
9622 break;
9624 switch (obj_type) {
9625 case GOT_OBJ_TYPE_BLOB:
9626 error = cat_blob(id, repo, stdout);
9627 break;
9628 case GOT_OBJ_TYPE_TREE:
9629 error = cat_tree(id, repo, stdout);
9630 break;
9631 case GOT_OBJ_TYPE_COMMIT:
9632 error = cat_commit(id, repo, stdout);
9633 break;
9634 case GOT_OBJ_TYPE_TAG:
9635 error = cat_tag(id, repo, stdout);
9636 break;
9637 default:
9638 error = got_error(GOT_ERR_OBJ_TYPE);
9639 break;
9641 if (error)
9642 break;
9643 free(label);
9644 label = NULL;
9645 free(id);
9646 id = NULL;
9648 done:
9649 free(label);
9650 free(id);
9651 free(commit_id);
9652 if (worktree)
9653 got_worktree_close(worktree);
9654 if (repo) {
9655 const struct got_error *repo_error;
9656 repo_error = got_repo_close(repo);
9657 if (error == NULL)
9658 error = repo_error;
9660 return error;
9663 __dead static void
9664 usage_info(void)
9666 fprintf(stderr, "usage: %s info [path ...]\n",
9667 getprogname());
9668 exit(1);
9671 static const struct got_error *
9672 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9673 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9674 struct got_object_id *commit_id)
9676 const struct got_error *err = NULL;
9677 char *id_str = NULL;
9678 char datebuf[128];
9679 struct tm mytm, *tm;
9680 struct got_pathlist_head *paths = arg;
9681 struct got_pathlist_entry *pe;
9684 * Clear error indication from any of the path arguments which
9685 * would cause this file index entry to be displayed.
9687 TAILQ_FOREACH(pe, paths, entry) {
9688 if (got_path_cmp(path, pe->path, strlen(path),
9689 pe->path_len) == 0 ||
9690 got_path_is_child(path, pe->path, pe->path_len))
9691 pe->data = NULL; /* no error */
9694 printf(GOT_COMMIT_SEP_STR);
9695 if (S_ISLNK(mode))
9696 printf("symlink: %s\n", path);
9697 else if (S_ISREG(mode)) {
9698 printf("file: %s\n", path);
9699 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9700 } else if (S_ISDIR(mode))
9701 printf("directory: %s\n", path);
9702 else
9703 printf("something: %s\n", path);
9705 tm = localtime_r(&mtime, &mytm);
9706 if (tm == NULL)
9707 return NULL;
9708 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9709 return got_error(GOT_ERR_NO_SPACE);
9710 printf("timestamp: %s\n", datebuf);
9712 if (blob_id) {
9713 err = got_object_id_str(&id_str, blob_id);
9714 if (err)
9715 return err;
9716 printf("based on blob: %s\n", id_str);
9717 free(id_str);
9720 if (staged_blob_id) {
9721 err = got_object_id_str(&id_str, staged_blob_id);
9722 if (err)
9723 return err;
9724 printf("based on staged blob: %s\n", id_str);
9725 free(id_str);
9728 if (commit_id) {
9729 err = got_object_id_str(&id_str, commit_id);
9730 if (err)
9731 return err;
9732 printf("based on commit: %s\n", id_str);
9733 free(id_str);
9736 return NULL;
9739 static const struct got_error *
9740 cmd_info(int argc, char *argv[])
9742 const struct got_error *error = NULL;
9743 struct got_worktree *worktree = NULL;
9744 char *cwd = NULL, *id_str = NULL;
9745 struct got_pathlist_head paths;
9746 struct got_pathlist_entry *pe;
9747 char *uuidstr = NULL;
9748 int ch, show_files = 0;
9750 TAILQ_INIT(&paths);
9752 while ((ch = getopt(argc, argv, "")) != -1) {
9753 switch (ch) {
9754 default:
9755 usage_info();
9756 /* NOTREACHED */
9760 argc -= optind;
9761 argv += optind;
9763 #ifndef PROFILE
9764 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9765 NULL) == -1)
9766 err(1, "pledge");
9767 #endif
9768 cwd = getcwd(NULL, 0);
9769 if (cwd == NULL) {
9770 error = got_error_from_errno("getcwd");
9771 goto done;
9774 error = got_worktree_open(&worktree, cwd);
9775 if (error) {
9776 if (error->code == GOT_ERR_NOT_WORKTREE)
9777 error = wrap_not_worktree_error(error, "status", cwd);
9778 goto done;
9781 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9782 if (error)
9783 goto done;
9785 if (argc >= 1) {
9786 error = get_worktree_paths_from_argv(&paths, argc, argv,
9787 worktree);
9788 if (error)
9789 goto done;
9790 show_files = 1;
9793 error = got_object_id_str(&id_str,
9794 got_worktree_get_base_commit_id(worktree));
9795 if (error)
9796 goto done;
9798 error = got_worktree_get_uuid(&uuidstr, worktree);
9799 if (error)
9800 goto done;
9802 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9803 printf("work tree base commit: %s\n", id_str);
9804 printf("work tree path prefix: %s\n",
9805 got_worktree_get_path_prefix(worktree));
9806 printf("work tree branch reference: %s\n",
9807 got_worktree_get_head_ref_name(worktree));
9808 printf("work tree UUID: %s\n", uuidstr);
9809 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9811 if (show_files) {
9812 struct got_pathlist_entry *pe;
9813 TAILQ_FOREACH(pe, &paths, entry) {
9814 if (pe->path_len == 0)
9815 continue;
9817 * Assume this path will fail. This will be corrected
9818 * in print_path_info() in case the path does suceeed.
9820 pe->data = (void *)got_error_path(pe->path,
9821 GOT_ERR_BAD_PATH);
9823 error = got_worktree_path_info(worktree, &paths,
9824 print_path_info, &paths, check_cancelled, NULL);
9825 if (error)
9826 goto done;
9827 TAILQ_FOREACH(pe, &paths, entry) {
9828 if (pe->data != NULL) {
9829 error = pe->data; /* bad path */
9830 break;
9834 done:
9835 TAILQ_FOREACH(pe, &paths, entry)
9836 free((char *)pe->path);
9837 got_pathlist_free(&paths);
9838 free(cwd);
9839 free(id_str);
9840 free(uuidstr);
9841 return error;