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 int force_text_diff, 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(NULL, NULL, blob1, blob2, path, path,
3145 diff_context, ignore_whitespace, force_text_diff, 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 int force_text_diff, 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.force_text_diff = force_text_diff;
3175 arg.outfile = stdout;
3176 arg.line_offsets = NULL;
3177 arg.nlines = 0;
3178 while (path[0] == '/')
3179 path++;
3180 err = got_diff_tree(tree1, tree2, path, path, repo,
3181 got_diff_blob_output_unidiff, &arg, 1);
3182 done:
3183 if (tree1)
3184 got_object_tree_close(tree1);
3185 if (tree2)
3186 got_object_tree_close(tree2);
3187 return err;
3190 static const struct got_error *
3191 get_changed_paths(struct got_pathlist_head *paths,
3192 struct got_commit_object *commit, struct got_repository *repo)
3194 const struct got_error *err = NULL;
3195 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3196 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3197 struct got_object_qid *qid;
3199 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3200 if (qid != NULL) {
3201 struct got_commit_object *pcommit;
3202 err = got_object_open_as_commit(&pcommit, repo,
3203 qid->id);
3204 if (err)
3205 return err;
3207 tree_id1 = got_object_commit_get_tree_id(pcommit);
3208 got_object_commit_close(pcommit);
3212 if (tree_id1) {
3213 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3214 if (err)
3215 goto done;
3218 tree_id2 = got_object_commit_get_tree_id(commit);
3219 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3220 if (err)
3221 goto done;
3223 err = got_diff_tree(tree1, tree2, "", "", repo,
3224 got_diff_tree_collect_changed_paths, paths, 0);
3225 done:
3226 if (tree1)
3227 got_object_tree_close(tree1);
3228 if (tree2)
3229 got_object_tree_close(tree2);
3230 return err;
3233 static const struct got_error *
3234 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3235 const char *path, int diff_context, struct got_repository *repo)
3237 const struct got_error *err = NULL;
3238 struct got_commit_object *pcommit = NULL;
3239 char *id_str1 = NULL, *id_str2 = NULL;
3240 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3241 struct got_object_qid *qid;
3243 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3244 if (qid != NULL) {
3245 err = got_object_open_as_commit(&pcommit, repo,
3246 qid->id);
3247 if (err)
3248 return err;
3251 if (path && path[0] != '\0') {
3252 int obj_type;
3253 err = got_object_id_by_path(&obj_id2, repo, id, path);
3254 if (err)
3255 goto done;
3256 err = got_object_id_str(&id_str2, obj_id2);
3257 if (err) {
3258 free(obj_id2);
3259 goto done;
3261 if (pcommit) {
3262 err = got_object_id_by_path(&obj_id1, repo,
3263 qid->id, path);
3264 if (err) {
3265 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3266 free(obj_id2);
3267 goto done;
3269 } else {
3270 err = got_object_id_str(&id_str1, obj_id1);
3271 if (err) {
3272 free(obj_id2);
3273 goto done;
3277 err = got_object_get_type(&obj_type, repo, obj_id2);
3278 if (err) {
3279 free(obj_id2);
3280 goto done;
3282 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3283 switch (obj_type) {
3284 case GOT_OBJ_TYPE_BLOB:
3285 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3286 0, 0, repo);
3287 break;
3288 case GOT_OBJ_TYPE_TREE:
3289 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3290 0, 0, repo);
3291 break;
3292 default:
3293 err = got_error(GOT_ERR_OBJ_TYPE);
3294 break;
3296 free(obj_id1);
3297 free(obj_id2);
3298 } else {
3299 obj_id2 = got_object_commit_get_tree_id(commit);
3300 err = got_object_id_str(&id_str2, obj_id2);
3301 if (err)
3302 goto done;
3303 if (pcommit) {
3304 obj_id1 = got_object_commit_get_tree_id(pcommit);
3305 err = got_object_id_str(&id_str1, obj_id1);
3306 if (err)
3307 goto done;
3309 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3310 id_str2);
3311 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3312 repo);
3314 done:
3315 free(id_str1);
3316 free(id_str2);
3317 if (pcommit)
3318 got_object_commit_close(pcommit);
3319 return err;
3322 static char *
3323 get_datestr(time_t *time, char *datebuf)
3325 struct tm mytm, *tm;
3326 char *p, *s;
3328 tm = gmtime_r(time, &mytm);
3329 if (tm == NULL)
3330 return NULL;
3331 s = asctime_r(tm, datebuf);
3332 if (s == NULL)
3333 return NULL;
3334 p = strchr(s, '\n');
3335 if (p)
3336 *p = '\0';
3337 return s;
3340 static const struct got_error *
3341 match_logmsg(int *have_match, struct got_object_id *id,
3342 struct got_commit_object *commit, regex_t *regex)
3344 const struct got_error *err = NULL;
3345 regmatch_t regmatch;
3346 char *id_str = NULL, *logmsg = NULL;
3348 *have_match = 0;
3350 err = got_object_id_str(&id_str, id);
3351 if (err)
3352 return err;
3354 err = got_object_commit_get_logmsg(&logmsg, commit);
3355 if (err)
3356 goto done;
3358 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3359 *have_match = 1;
3360 done:
3361 free(id_str);
3362 free(logmsg);
3363 return err;
3366 static void
3367 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3368 regex_t *regex)
3370 regmatch_t regmatch;
3371 struct got_pathlist_entry *pe;
3373 *have_match = 0;
3375 TAILQ_FOREACH(pe, changed_paths, entry) {
3376 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3377 *have_match = 1;
3378 break;
3383 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3385 static const struct got_error *
3386 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3387 struct got_repository *repo, const char *path,
3388 struct got_pathlist_head *changed_paths, int show_patch,
3389 int diff_context, struct got_reflist_head *refs)
3391 const struct got_error *err = NULL;
3392 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3393 char datebuf[26];
3394 time_t committer_time;
3395 const char *author, *committer;
3396 char *refs_str = NULL;
3397 struct got_reflist_entry *re;
3399 SIMPLEQ_FOREACH(re, refs, entry) {
3400 char *s;
3401 const char *name;
3402 struct got_tag_object *tag = NULL;
3403 struct got_object_id *ref_id;
3404 int cmp;
3406 name = got_ref_get_name(re->ref);
3407 if (strcmp(name, GOT_REF_HEAD) == 0)
3408 continue;
3409 if (strncmp(name, "refs/", 5) == 0)
3410 name += 5;
3411 if (strncmp(name, "got/", 4) == 0)
3412 continue;
3413 if (strncmp(name, "heads/", 6) == 0)
3414 name += 6;
3415 if (strncmp(name, "remotes/", 8) == 0) {
3416 name += 8;
3417 s = strstr(name, "/" GOT_REF_HEAD);
3418 if (s != NULL && s[strlen(s)] == '\0')
3419 continue;
3421 err = got_ref_resolve(&ref_id, repo, re->ref);
3422 if (err)
3423 return err;
3424 if (strncmp(name, "tags/", 5) == 0) {
3425 err = got_object_open_as_tag(&tag, repo, ref_id);
3426 if (err) {
3427 if (err->code != GOT_ERR_OBJ_TYPE) {
3428 free(ref_id);
3429 return err;
3431 /* Ref points at something other than a tag. */
3432 err = NULL;
3433 tag = NULL;
3436 cmp = got_object_id_cmp(tag ?
3437 got_object_tag_get_object_id(tag) : ref_id, id);
3438 free(ref_id);
3439 if (tag)
3440 got_object_tag_close(tag);
3441 if (cmp != 0)
3442 continue;
3443 s = refs_str;
3444 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3445 name) == -1) {
3446 err = got_error_from_errno("asprintf");
3447 free(s);
3448 return err;
3450 free(s);
3452 err = got_object_id_str(&id_str, id);
3453 if (err)
3454 return err;
3456 printf(GOT_COMMIT_SEP_STR);
3457 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3458 refs_str ? refs_str : "", refs_str ? ")" : "");
3459 free(id_str);
3460 id_str = NULL;
3461 free(refs_str);
3462 refs_str = NULL;
3463 printf("from: %s\n", got_object_commit_get_author(commit));
3464 committer_time = got_object_commit_get_committer_time(commit);
3465 datestr = get_datestr(&committer_time, datebuf);
3466 if (datestr)
3467 printf("date: %s UTC\n", datestr);
3468 author = got_object_commit_get_author(commit);
3469 committer = got_object_commit_get_committer(commit);
3470 if (strcmp(author, committer) != 0)
3471 printf("via: %s\n", committer);
3472 if (got_object_commit_get_nparents(commit) > 1) {
3473 const struct got_object_id_queue *parent_ids;
3474 struct got_object_qid *qid;
3475 int n = 1;
3476 parent_ids = got_object_commit_get_parent_ids(commit);
3477 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3478 err = got_object_id_str(&id_str, qid->id);
3479 if (err)
3480 return err;
3481 printf("parent %d: %s\n", n++, id_str);
3482 free(id_str);
3486 err = got_object_commit_get_logmsg(&logmsg0, commit);
3487 if (err)
3488 return err;
3490 logmsg = logmsg0;
3491 do {
3492 line = strsep(&logmsg, "\n");
3493 if (line)
3494 printf(" %s\n", line);
3495 } while (line);
3496 free(logmsg0);
3498 if (changed_paths) {
3499 struct got_pathlist_entry *pe;
3500 TAILQ_FOREACH(pe, changed_paths, entry) {
3501 struct got_diff_changed_path *cp = pe->data;
3502 printf(" %c %s\n", cp->status, pe->path);
3504 printf("\n");
3506 if (show_patch) {
3507 err = print_patch(commit, id, path, diff_context, repo);
3508 if (err == 0)
3509 printf("\n");
3512 if (fflush(stdout) != 0 && err == NULL)
3513 err = got_error_from_errno("fflush");
3514 return err;
3517 static const struct got_error *
3518 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3519 struct got_repository *repo, const char *path, int show_changed_paths,
3520 int show_patch, const char *search_pattern, int diff_context, int limit,
3521 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3523 const struct got_error *err;
3524 struct got_commit_graph *graph;
3525 regex_t regex;
3526 int have_match;
3527 struct got_object_id_queue reversed_commits;
3528 struct got_object_qid *qid;
3529 struct got_commit_object *commit;
3530 struct got_pathlist_head changed_paths;
3531 struct got_pathlist_entry *pe;
3533 SIMPLEQ_INIT(&reversed_commits);
3534 TAILQ_INIT(&changed_paths);
3536 if (search_pattern && regcomp(&regex, search_pattern,
3537 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3538 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3540 err = got_commit_graph_open(&graph, path, !log_branches);
3541 if (err)
3542 return err;
3543 err = got_commit_graph_iter_start(graph, root_id, repo,
3544 check_cancelled, NULL);
3545 if (err)
3546 goto done;
3547 for (;;) {
3548 struct got_object_id *id;
3550 if (sigint_received || sigpipe_received)
3551 break;
3553 err = got_commit_graph_iter_next(&id, graph, repo,
3554 check_cancelled, NULL);
3555 if (err) {
3556 if (err->code == GOT_ERR_ITER_COMPLETED)
3557 err = NULL;
3558 break;
3560 if (id == NULL)
3561 break;
3563 err = got_object_open_as_commit(&commit, repo, id);
3564 if (err)
3565 break;
3567 if (show_changed_paths && !reverse_display_order) {
3568 err = get_changed_paths(&changed_paths, commit, repo);
3569 if (err)
3570 break;
3573 if (search_pattern) {
3574 err = match_logmsg(&have_match, id, commit, &regex);
3575 if (err) {
3576 got_object_commit_close(commit);
3577 break;
3579 if (have_match == 0 && show_changed_paths)
3580 match_changed_paths(&have_match,
3581 &changed_paths, &regex);
3582 if (have_match == 0) {
3583 got_object_commit_close(commit);
3584 TAILQ_FOREACH(pe, &changed_paths, entry) {
3585 free((char *)pe->path);
3586 free(pe->data);
3588 got_pathlist_free(&changed_paths);
3589 continue;
3593 if (reverse_display_order) {
3594 err = got_object_qid_alloc(&qid, id);
3595 if (err)
3596 break;
3597 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3598 got_object_commit_close(commit);
3599 } else {
3600 err = print_commit(commit, id, repo, path,
3601 show_changed_paths ? &changed_paths : NULL,
3602 show_patch, diff_context, refs);
3603 got_object_commit_close(commit);
3604 if (err)
3605 break;
3607 if ((limit && --limit == 0) ||
3608 (end_id && got_object_id_cmp(id, end_id) == 0))
3609 break;
3611 TAILQ_FOREACH(pe, &changed_paths, entry) {
3612 free((char *)pe->path);
3613 free(pe->data);
3615 got_pathlist_free(&changed_paths);
3617 if (reverse_display_order) {
3618 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3619 err = got_object_open_as_commit(&commit, repo, qid->id);
3620 if (err)
3621 break;
3622 if (show_changed_paths) {
3623 err = get_changed_paths(&changed_paths,
3624 commit, repo);
3625 if (err)
3626 break;
3628 err = print_commit(commit, qid->id, repo, path,
3629 show_changed_paths ? &changed_paths : NULL,
3630 show_patch, diff_context, refs);
3631 got_object_commit_close(commit);
3632 if (err)
3633 break;
3634 TAILQ_FOREACH(pe, &changed_paths, entry) {
3635 free((char *)pe->path);
3636 free(pe->data);
3638 got_pathlist_free(&changed_paths);
3641 done:
3642 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3643 qid = SIMPLEQ_FIRST(&reversed_commits);
3644 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3645 got_object_qid_free(qid);
3647 TAILQ_FOREACH(pe, &changed_paths, entry) {
3648 free((char *)pe->path);
3649 free(pe->data);
3651 got_pathlist_free(&changed_paths);
3652 if (search_pattern)
3653 regfree(&regex);
3654 got_commit_graph_close(graph);
3655 return err;
3658 __dead static void
3659 usage_log(void)
3661 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3662 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3663 "[-R] [path]\n", getprogname());
3664 exit(1);
3667 static int
3668 get_default_log_limit(void)
3670 const char *got_default_log_limit;
3671 long long n;
3672 const char *errstr;
3674 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3675 if (got_default_log_limit == NULL)
3676 return 0;
3677 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3678 if (errstr != NULL)
3679 return 0;
3680 return n;
3683 static const struct got_error *
3684 cmd_log(int argc, char *argv[])
3686 const struct got_error *error;
3687 struct got_repository *repo = NULL;
3688 struct got_worktree *worktree = NULL;
3689 struct got_object_id *start_id = NULL, *end_id = NULL;
3690 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3691 const char *start_commit = NULL, *end_commit = NULL;
3692 const char *search_pattern = NULL;
3693 int diff_context = -1, ch;
3694 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3695 int reverse_display_order = 0;
3696 const char *errstr;
3697 struct got_reflist_head refs;
3699 SIMPLEQ_INIT(&refs);
3701 #ifndef PROFILE
3702 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3703 NULL)
3704 == -1)
3705 err(1, "pledge");
3706 #endif
3708 limit = get_default_log_limit();
3710 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3711 switch (ch) {
3712 case 'p':
3713 show_patch = 1;
3714 break;
3715 case 'P':
3716 show_changed_paths = 1;
3717 break;
3718 case 'c':
3719 start_commit = optarg;
3720 break;
3721 case 'C':
3722 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3723 &errstr);
3724 if (errstr != NULL)
3725 err(1, "-C option %s", errstr);
3726 break;
3727 case 'l':
3728 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3729 if (errstr != NULL)
3730 err(1, "-l option %s", errstr);
3731 break;
3732 case 'b':
3733 log_branches = 1;
3734 break;
3735 case 'r':
3736 repo_path = realpath(optarg, NULL);
3737 if (repo_path == NULL)
3738 return got_error_from_errno2("realpath",
3739 optarg);
3740 got_path_strip_trailing_slashes(repo_path);
3741 break;
3742 case 'R':
3743 reverse_display_order = 1;
3744 break;
3745 case 's':
3746 search_pattern = optarg;
3747 break;
3748 case 'x':
3749 end_commit = optarg;
3750 break;
3751 default:
3752 usage_log();
3753 /* NOTREACHED */
3757 argc -= optind;
3758 argv += optind;
3760 if (diff_context == -1)
3761 diff_context = 3;
3762 else if (!show_patch)
3763 errx(1, "-C requires -p");
3765 cwd = getcwd(NULL, 0);
3766 if (cwd == NULL) {
3767 error = got_error_from_errno("getcwd");
3768 goto done;
3771 if (repo_path == NULL) {
3772 error = got_worktree_open(&worktree, cwd);
3773 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3774 goto done;
3775 error = NULL;
3778 if (argc == 1) {
3779 if (worktree) {
3780 error = got_worktree_resolve_path(&path, worktree,
3781 argv[0]);
3782 if (error)
3783 goto done;
3784 } else {
3785 path = strdup(argv[0]);
3786 if (path == NULL) {
3787 error = got_error_from_errno("strdup");
3788 goto done;
3791 } else if (argc != 0)
3792 usage_log();
3794 if (repo_path == NULL) {
3795 repo_path = worktree ?
3796 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3798 if (repo_path == NULL) {
3799 error = got_error_from_errno("strdup");
3800 goto done;
3803 error = got_repo_open(&repo, repo_path, NULL);
3804 if (error != NULL)
3805 goto done;
3807 error = apply_unveil(got_repo_get_path(repo), 1,
3808 worktree ? got_worktree_get_root_path(worktree) : NULL);
3809 if (error)
3810 goto done;
3812 if (start_commit == NULL) {
3813 struct got_reference *head_ref;
3814 struct got_commit_object *commit = NULL;
3815 error = got_ref_open(&head_ref, repo,
3816 worktree ? got_worktree_get_head_ref_name(worktree)
3817 : GOT_REF_HEAD, 0);
3818 if (error != NULL)
3819 goto done;
3820 error = got_ref_resolve(&start_id, repo, head_ref);
3821 got_ref_close(head_ref);
3822 if (error != NULL)
3823 goto done;
3824 error = got_object_open_as_commit(&commit, repo,
3825 start_id);
3826 if (error != NULL)
3827 goto done;
3828 got_object_commit_close(commit);
3829 } else {
3830 error = got_repo_match_object_id(&start_id, NULL,
3831 start_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3832 if (error != NULL)
3833 goto done;
3835 if (end_commit != NULL) {
3836 error = got_repo_match_object_id(&end_id, NULL,
3837 end_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3838 if (error != NULL)
3839 goto done;
3842 if (worktree) {
3844 * If a path was specified on the command line it was resolved
3845 * to a path in the work tree above. Prepend the work tree's
3846 * path prefix to obtain the corresponding in-repository path.
3848 if (path) {
3849 const char *prefix;
3850 prefix = got_worktree_get_path_prefix(worktree);
3851 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3852 (path[0] != '\0') ? "/" : "", path) == -1) {
3853 error = got_error_from_errno("asprintf");
3854 goto done;
3857 } else
3858 error = got_repo_map_path(&in_repo_path, repo,
3859 path ? path : "");
3860 if (error != NULL)
3861 goto done;
3862 if (in_repo_path) {
3863 free(path);
3864 path = in_repo_path;
3867 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3868 if (error)
3869 goto done;
3871 error = print_commits(start_id, end_id, repo, path ? path : "",
3872 show_changed_paths, show_patch, search_pattern, diff_context,
3873 limit, log_branches, reverse_display_order, &refs);
3874 done:
3875 free(path);
3876 free(repo_path);
3877 free(cwd);
3878 if (worktree)
3879 got_worktree_close(worktree);
3880 if (repo) {
3881 const struct got_error *repo_error;
3882 repo_error = got_repo_close(repo);
3883 if (error == NULL)
3884 error = repo_error;
3886 got_ref_list_free(&refs);
3887 return error;
3890 __dead static void
3891 usage_diff(void)
3893 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3894 "[-s] [-w] [object1 object2 | path]\n", getprogname());
3895 exit(1);
3898 struct print_diff_arg {
3899 struct got_repository *repo;
3900 struct got_worktree *worktree;
3901 int diff_context;
3902 const char *id_str;
3903 int header_shown;
3904 int diff_staged;
3905 int ignore_whitespace;
3906 int force_text_diff;
3910 * Create a file which contains the target path of a symlink so we can feed
3911 * it as content to the diff engine.
3913 static const struct got_error *
3914 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3915 const char *abspath)
3917 const struct got_error *err = NULL;
3918 char target_path[PATH_MAX];
3919 ssize_t target_len, outlen;
3921 *fd = -1;
3923 if (dirfd != -1) {
3924 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3925 if (target_len == -1)
3926 return got_error_from_errno2("readlinkat", abspath);
3927 } else {
3928 target_len = readlink(abspath, target_path, PATH_MAX);
3929 if (target_len == -1)
3930 return got_error_from_errno2("readlink", abspath);
3933 *fd = got_opentempfd();
3934 if (*fd == -1)
3935 return got_error_from_errno("got_opentempfd");
3937 outlen = write(*fd, target_path, target_len);
3938 if (outlen == -1) {
3939 err = got_error_from_errno("got_opentempfd");
3940 goto done;
3943 if (lseek(*fd, 0, SEEK_SET) == -1) {
3944 err = got_error_from_errno2("lseek", abspath);
3945 goto done;
3947 done:
3948 if (err) {
3949 close(*fd);
3950 *fd = -1;
3952 return err;
3955 static const struct got_error *
3956 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3957 const char *path, struct got_object_id *blob_id,
3958 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3959 int dirfd, const char *de_name)
3961 struct print_diff_arg *a = arg;
3962 const struct got_error *err = NULL;
3963 struct got_blob_object *blob1 = NULL;
3964 int fd = -1;
3965 FILE *f2 = NULL;
3966 char *abspath = NULL, *label1 = NULL;
3967 struct stat sb;
3969 if (a->diff_staged) {
3970 if (staged_status != GOT_STATUS_MODIFY &&
3971 staged_status != GOT_STATUS_ADD &&
3972 staged_status != GOT_STATUS_DELETE)
3973 return NULL;
3974 } else {
3975 if (staged_status == GOT_STATUS_DELETE)
3976 return NULL;
3977 if (status == GOT_STATUS_NONEXISTENT)
3978 return got_error_set_errno(ENOENT, path);
3979 if (status != GOT_STATUS_MODIFY &&
3980 status != GOT_STATUS_ADD &&
3981 status != GOT_STATUS_DELETE &&
3982 status != GOT_STATUS_CONFLICT)
3983 return NULL;
3986 if (!a->header_shown) {
3987 printf("diff %s %s%s\n", a->id_str,
3988 got_worktree_get_root_path(a->worktree),
3989 a->diff_staged ? " (staged changes)" : "");
3990 a->header_shown = 1;
3993 if (a->diff_staged) {
3994 const char *label1 = NULL, *label2 = NULL;
3995 switch (staged_status) {
3996 case GOT_STATUS_MODIFY:
3997 label1 = path;
3998 label2 = path;
3999 break;
4000 case GOT_STATUS_ADD:
4001 label2 = path;
4002 break;
4003 case GOT_STATUS_DELETE:
4004 label1 = path;
4005 break;
4006 default:
4007 return got_error(GOT_ERR_FILE_STATUS);
4009 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4010 staged_blob_id, label1, label2, a->diff_context,
4011 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4014 if (staged_status == GOT_STATUS_ADD ||
4015 staged_status == GOT_STATUS_MODIFY) {
4016 char *id_str;
4017 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4018 8192);
4019 if (err)
4020 goto done;
4021 err = got_object_id_str(&id_str, staged_blob_id);
4022 if (err)
4023 goto done;
4024 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4025 err = got_error_from_errno("asprintf");
4026 free(id_str);
4027 goto done;
4029 free(id_str);
4030 } else if (status != GOT_STATUS_ADD) {
4031 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4032 if (err)
4033 goto done;
4036 if (status != GOT_STATUS_DELETE) {
4037 if (asprintf(&abspath, "%s/%s",
4038 got_worktree_get_root_path(a->worktree), path) == -1) {
4039 err = got_error_from_errno("asprintf");
4040 goto done;
4043 if (dirfd != -1) {
4044 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4045 if (fd == -1) {
4046 if (errno != ELOOP) {
4047 err = got_error_from_errno2("openat",
4048 abspath);
4049 goto done;
4051 err = get_symlink_target_file(&fd, dirfd,
4052 de_name, abspath);
4053 if (err)
4054 goto done;
4056 } else {
4057 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4058 if (fd == -1) {
4059 if (errno != ELOOP) {
4060 err = got_error_from_errno2("open",
4061 abspath);
4062 goto done;
4064 err = get_symlink_target_file(&fd, dirfd,
4065 de_name, abspath);
4066 if (err)
4067 goto done;
4070 if (fstat(fd, &sb) == -1) {
4071 err = got_error_from_errno2("fstat", abspath);
4072 goto done;
4074 f2 = fdopen(fd, "r");
4075 if (f2 == NULL) {
4076 err = got_error_from_errno2("fdopen", abspath);
4077 goto done;
4079 fd = -1;
4080 } else
4081 sb.st_size = 0;
4083 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4084 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4085 done:
4086 if (blob1)
4087 got_object_blob_close(blob1);
4088 if (f2 && fclose(f2) == EOF && err == NULL)
4089 err = got_error_from_errno("fclose");
4090 if (fd != -1 && close(fd) == -1 && err == NULL)
4091 err = got_error_from_errno("close");
4092 free(abspath);
4093 return err;
4096 static const struct got_error *
4097 cmd_diff(int argc, char *argv[])
4099 const struct got_error *error;
4100 struct got_repository *repo = NULL;
4101 struct got_worktree *worktree = NULL;
4102 char *cwd = NULL, *repo_path = NULL;
4103 struct got_object_id *id1 = NULL, *id2 = NULL;
4104 const char *id_str1 = NULL, *id_str2 = NULL;
4105 char *label1 = NULL, *label2 = NULL;
4106 int type1, type2;
4107 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4108 int force_text_diff = 0;
4109 const char *errstr;
4110 char *path = NULL;
4112 #ifndef PROFILE
4113 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4114 NULL) == -1)
4115 err(1, "pledge");
4116 #endif
4118 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4119 switch (ch) {
4120 case 'a':
4121 force_text_diff = 1;
4122 break;
4123 case 'C':
4124 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4125 &errstr);
4126 if (errstr != NULL)
4127 err(1, "-C option %s", errstr);
4128 break;
4129 case 'r':
4130 repo_path = realpath(optarg, NULL);
4131 if (repo_path == NULL)
4132 return got_error_from_errno2("realpath",
4133 optarg);
4134 got_path_strip_trailing_slashes(repo_path);
4135 break;
4136 case 's':
4137 diff_staged = 1;
4138 break;
4139 case 'w':
4140 ignore_whitespace = 1;
4141 break;
4142 default:
4143 usage_diff();
4144 /* NOTREACHED */
4148 argc -= optind;
4149 argv += optind;
4151 cwd = getcwd(NULL, 0);
4152 if (cwd == NULL) {
4153 error = got_error_from_errno("getcwd");
4154 goto done;
4156 if (argc <= 1) {
4157 if (repo_path)
4158 errx(1,
4159 "-r option can't be used when diffing a work tree");
4160 error = got_worktree_open(&worktree, cwd);
4161 if (error) {
4162 if (error->code == GOT_ERR_NOT_WORKTREE)
4163 error = wrap_not_worktree_error(error, "diff",
4164 cwd);
4165 goto done;
4167 repo_path = strdup(got_worktree_get_repo_path(worktree));
4168 if (repo_path == NULL) {
4169 error = got_error_from_errno("strdup");
4170 goto done;
4172 if (argc == 1) {
4173 error = got_worktree_resolve_path(&path, worktree,
4174 argv[0]);
4175 if (error)
4176 goto done;
4177 } else {
4178 path = strdup("");
4179 if (path == NULL) {
4180 error = got_error_from_errno("strdup");
4181 goto done;
4184 } else if (argc == 2) {
4185 if (diff_staged)
4186 errx(1, "-s option can't be used when diffing "
4187 "objects in repository");
4188 id_str1 = argv[0];
4189 id_str2 = argv[1];
4190 if (repo_path == NULL) {
4191 error = got_worktree_open(&worktree, cwd);
4192 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4193 goto done;
4194 if (worktree) {
4195 repo_path = strdup(
4196 got_worktree_get_repo_path(worktree));
4197 if (repo_path == NULL) {
4198 error = got_error_from_errno("strdup");
4199 goto done;
4201 } else {
4202 repo_path = strdup(cwd);
4203 if (repo_path == NULL) {
4204 error = got_error_from_errno("strdup");
4205 goto done;
4209 } else
4210 usage_diff();
4212 error = got_repo_open(&repo, repo_path, NULL);
4213 free(repo_path);
4214 if (error != NULL)
4215 goto done;
4217 error = apply_unveil(got_repo_get_path(repo), 1,
4218 worktree ? got_worktree_get_root_path(worktree) : NULL);
4219 if (error)
4220 goto done;
4222 if (argc <= 1) {
4223 struct print_diff_arg arg;
4224 struct got_pathlist_head paths;
4225 char *id_str;
4227 TAILQ_INIT(&paths);
4229 error = got_object_id_str(&id_str,
4230 got_worktree_get_base_commit_id(worktree));
4231 if (error)
4232 goto done;
4233 arg.repo = repo;
4234 arg.worktree = worktree;
4235 arg.diff_context = diff_context;
4236 arg.id_str = id_str;
4237 arg.header_shown = 0;
4238 arg.diff_staged = diff_staged;
4239 arg.ignore_whitespace = ignore_whitespace;
4240 arg.force_text_diff = force_text_diff;
4242 error = got_pathlist_append(&paths, path, NULL);
4243 if (error)
4244 goto done;
4246 error = got_worktree_status(worktree, &paths, repo, print_diff,
4247 &arg, check_cancelled, NULL);
4248 free(id_str);
4249 got_pathlist_free(&paths);
4250 goto done;
4253 error = got_repo_match_object_id(&id1, &label1, id_str1,
4254 GOT_OBJ_TYPE_ANY, 1, repo);
4255 if (error)
4256 goto done;
4258 error = got_repo_match_object_id(&id2, &label2, id_str2,
4259 GOT_OBJ_TYPE_ANY, 1, repo);
4260 if (error)
4261 goto done;
4263 error = got_object_get_type(&type1, repo, id1);
4264 if (error)
4265 goto done;
4267 error = got_object_get_type(&type2, repo, id2);
4268 if (error)
4269 goto done;
4271 if (type1 != type2) {
4272 error = got_error(GOT_ERR_OBJ_TYPE);
4273 goto done;
4276 switch (type1) {
4277 case GOT_OBJ_TYPE_BLOB:
4278 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4279 NULL, NULL, diff_context, ignore_whitespace,
4280 force_text_diff, repo, stdout);
4281 break;
4282 case GOT_OBJ_TYPE_TREE:
4283 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4284 "", "", diff_context, ignore_whitespace, force_text_diff,
4285 repo, stdout);
4286 break;
4287 case GOT_OBJ_TYPE_COMMIT:
4288 printf("diff %s %s\n", label1, label2);
4289 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4290 diff_context, ignore_whitespace, force_text_diff, repo,
4291 stdout);
4292 break;
4293 default:
4294 error = got_error(GOT_ERR_OBJ_TYPE);
4296 done:
4297 free(label1);
4298 free(label2);
4299 free(id1);
4300 free(id2);
4301 free(path);
4302 if (worktree)
4303 got_worktree_close(worktree);
4304 if (repo) {
4305 const struct got_error *repo_error;
4306 repo_error = got_repo_close(repo);
4307 if (error == NULL)
4308 error = repo_error;
4310 return error;
4313 __dead static void
4314 usage_blame(void)
4316 fprintf(stderr,
4317 "usage: %s blame [-c commit] [-r repository-path] path\n",
4318 getprogname());
4319 exit(1);
4322 struct blame_line {
4323 int annotated;
4324 char *id_str;
4325 char *committer;
4326 char datebuf[11]; /* YYYY-MM-DD + NUL */
4329 struct blame_cb_args {
4330 struct blame_line *lines;
4331 int nlines;
4332 int nlines_prec;
4333 int lineno_cur;
4334 off_t *line_offsets;
4335 FILE *f;
4336 struct got_repository *repo;
4339 static const struct got_error *
4340 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4342 const struct got_error *err = NULL;
4343 struct blame_cb_args *a = arg;
4344 struct blame_line *bline;
4345 char *line = NULL;
4346 size_t linesize = 0;
4347 struct got_commit_object *commit = NULL;
4348 off_t offset;
4349 struct tm tm;
4350 time_t committer_time;
4352 if (nlines != a->nlines ||
4353 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4354 return got_error(GOT_ERR_RANGE);
4356 if (sigint_received)
4357 return got_error(GOT_ERR_ITER_COMPLETED);
4359 if (lineno == -1)
4360 return NULL; /* no change in this commit */
4362 /* Annotate this line. */
4363 bline = &a->lines[lineno - 1];
4364 if (bline->annotated)
4365 return NULL;
4366 err = got_object_id_str(&bline->id_str, id);
4367 if (err)
4368 return err;
4370 err = got_object_open_as_commit(&commit, a->repo, id);
4371 if (err)
4372 goto done;
4374 bline->committer = strdup(got_object_commit_get_committer(commit));
4375 if (bline->committer == NULL) {
4376 err = got_error_from_errno("strdup");
4377 goto done;
4380 committer_time = got_object_commit_get_committer_time(commit);
4381 if (localtime_r(&committer_time, &tm) == NULL)
4382 return got_error_from_errno("localtime_r");
4383 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4384 &tm) >= sizeof(bline->datebuf)) {
4385 err = got_error(GOT_ERR_NO_SPACE);
4386 goto done;
4388 bline->annotated = 1;
4390 /* Print lines annotated so far. */
4391 bline = &a->lines[a->lineno_cur - 1];
4392 if (!bline->annotated)
4393 goto done;
4395 offset = a->line_offsets[a->lineno_cur - 1];
4396 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4397 err = got_error_from_errno("fseeko");
4398 goto done;
4401 while (bline->annotated) {
4402 char *smallerthan, *at, *nl, *committer;
4403 size_t len;
4405 if (getline(&line, &linesize, a->f) == -1) {
4406 if (ferror(a->f))
4407 err = got_error_from_errno("getline");
4408 break;
4411 committer = bline->committer;
4412 smallerthan = strchr(committer, '<');
4413 if (smallerthan && smallerthan[1] != '\0')
4414 committer = smallerthan + 1;
4415 at = strchr(committer, '@');
4416 if (at)
4417 *at = '\0';
4418 len = strlen(committer);
4419 if (len >= 9)
4420 committer[8] = '\0';
4422 nl = strchr(line, '\n');
4423 if (nl)
4424 *nl = '\0';
4425 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4426 bline->id_str, bline->datebuf, committer, line);
4428 a->lineno_cur++;
4429 bline = &a->lines[a->lineno_cur - 1];
4431 done:
4432 if (commit)
4433 got_object_commit_close(commit);
4434 free(line);
4435 return err;
4438 static const struct got_error *
4439 cmd_blame(int argc, char *argv[])
4441 const struct got_error *error;
4442 struct got_repository *repo = NULL;
4443 struct got_worktree *worktree = NULL;
4444 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4445 char *link_target = NULL;
4446 struct got_object_id *obj_id = NULL;
4447 struct got_object_id *commit_id = NULL;
4448 struct got_blob_object *blob = NULL;
4449 char *commit_id_str = NULL;
4450 struct blame_cb_args bca;
4451 int ch, obj_type, i;
4452 off_t filesize;
4454 memset(&bca, 0, sizeof(bca));
4456 #ifndef PROFILE
4457 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4458 NULL) == -1)
4459 err(1, "pledge");
4460 #endif
4462 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4463 switch (ch) {
4464 case 'c':
4465 commit_id_str = optarg;
4466 break;
4467 case 'r':
4468 repo_path = realpath(optarg, NULL);
4469 if (repo_path == NULL)
4470 return got_error_from_errno2("realpath",
4471 optarg);
4472 got_path_strip_trailing_slashes(repo_path);
4473 break;
4474 default:
4475 usage_blame();
4476 /* NOTREACHED */
4480 argc -= optind;
4481 argv += optind;
4483 if (argc == 1)
4484 path = argv[0];
4485 else
4486 usage_blame();
4488 cwd = getcwd(NULL, 0);
4489 if (cwd == NULL) {
4490 error = got_error_from_errno("getcwd");
4491 goto done;
4493 if (repo_path == NULL) {
4494 error = got_worktree_open(&worktree, cwd);
4495 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4496 goto done;
4497 else
4498 error = NULL;
4499 if (worktree) {
4500 repo_path =
4501 strdup(got_worktree_get_repo_path(worktree));
4502 if (repo_path == NULL) {
4503 error = got_error_from_errno("strdup");
4504 if (error)
4505 goto done;
4507 } else {
4508 repo_path = strdup(cwd);
4509 if (repo_path == NULL) {
4510 error = got_error_from_errno("strdup");
4511 goto done;
4516 error = got_repo_open(&repo, repo_path, NULL);
4517 if (error != NULL)
4518 goto done;
4520 if (worktree) {
4521 const char *prefix = got_worktree_get_path_prefix(worktree);
4522 char *p;
4524 error = got_worktree_resolve_path(&p, worktree, path);
4525 if (error)
4526 goto done;
4527 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4528 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4529 p) == -1) {
4530 error = got_error_from_errno("asprintf");
4531 free(p);
4532 goto done;
4534 free(p);
4535 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4536 } else {
4537 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4538 if (error)
4539 goto done;
4540 error = got_repo_map_path(&in_repo_path, repo, path);
4542 if (error)
4543 goto done;
4545 if (commit_id_str == NULL) {
4546 struct got_reference *head_ref;
4547 error = got_ref_open(&head_ref, repo, worktree ?
4548 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4549 if (error != NULL)
4550 goto done;
4551 error = got_ref_resolve(&commit_id, repo, head_ref);
4552 got_ref_close(head_ref);
4553 if (error != NULL)
4554 goto done;
4555 } else {
4556 error = got_repo_match_object_id(&commit_id, NULL,
4557 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4558 if (error)
4559 goto done;
4562 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4563 commit_id, repo);
4564 if (error)
4565 goto done;
4567 error = got_object_id_by_path(&obj_id, repo, commit_id,
4568 link_target ? link_target : in_repo_path);
4569 if (error)
4570 goto done;
4572 error = got_object_get_type(&obj_type, repo, obj_id);
4573 if (error)
4574 goto done;
4576 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4577 error = got_error_path(link_target ? link_target : in_repo_path,
4578 GOT_ERR_OBJ_TYPE);
4579 goto done;
4582 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4583 if (error)
4584 goto done;
4585 bca.f = got_opentemp();
4586 if (bca.f == NULL) {
4587 error = got_error_from_errno("got_opentemp");
4588 goto done;
4590 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4591 &bca.line_offsets, bca.f, blob);
4592 if (error || bca.nlines == 0)
4593 goto done;
4595 /* Don't include \n at EOF in the blame line count. */
4596 if (bca.line_offsets[bca.nlines - 1] == filesize)
4597 bca.nlines--;
4599 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4600 if (bca.lines == NULL) {
4601 error = got_error_from_errno("calloc");
4602 goto done;
4604 bca.lineno_cur = 1;
4605 bca.nlines_prec = 0;
4606 i = bca.nlines;
4607 while (i > 0) {
4608 i /= 10;
4609 bca.nlines_prec++;
4611 bca.repo = repo;
4613 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4614 repo, blame_cb, &bca, check_cancelled, NULL);
4615 done:
4616 free(in_repo_path);
4617 free(link_target);
4618 free(repo_path);
4619 free(cwd);
4620 free(commit_id);
4621 free(obj_id);
4622 if (blob)
4623 got_object_blob_close(blob);
4624 if (worktree)
4625 got_worktree_close(worktree);
4626 if (repo) {
4627 const struct got_error *repo_error;
4628 repo_error = got_repo_close(repo);
4629 if (error == NULL)
4630 error = repo_error;
4632 if (bca.lines) {
4633 for (i = 0; i < bca.nlines; i++) {
4634 struct blame_line *bline = &bca.lines[i];
4635 free(bline->id_str);
4636 free(bline->committer);
4638 free(bca.lines);
4640 free(bca.line_offsets);
4641 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4642 error = got_error_from_errno("fclose");
4643 return error;
4646 __dead static void
4647 usage_tree(void)
4649 fprintf(stderr,
4650 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4651 getprogname());
4652 exit(1);
4655 static const struct got_error *
4656 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4657 const char *root_path, struct got_repository *repo)
4659 const struct got_error *err = NULL;
4660 int is_root_path = (strcmp(path, root_path) == 0);
4661 const char *modestr = "";
4662 mode_t mode = got_tree_entry_get_mode(te);
4663 char *link_target = NULL;
4665 path += strlen(root_path);
4666 while (path[0] == '/')
4667 path++;
4669 if (got_object_tree_entry_is_submodule(te))
4670 modestr = "$";
4671 else if (S_ISLNK(mode)) {
4672 int i;
4674 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4675 if (err)
4676 return err;
4677 for (i = 0; i < strlen(link_target); i++) {
4678 if (!isprint((unsigned char)link_target[i]))
4679 link_target[i] = '?';
4682 modestr = "@";
4684 else if (S_ISDIR(mode))
4685 modestr = "/";
4686 else if (mode & S_IXUSR)
4687 modestr = "*";
4689 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4690 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4691 link_target ? " -> ": "", link_target ? link_target : "");
4693 free(link_target);
4694 return NULL;
4697 static const struct got_error *
4698 print_tree(const char *path, struct got_object_id *commit_id,
4699 int show_ids, int recurse, const char *root_path,
4700 struct got_repository *repo)
4702 const struct got_error *err = NULL;
4703 struct got_object_id *tree_id = NULL;
4704 struct got_tree_object *tree = NULL;
4705 int nentries, i;
4707 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4708 if (err)
4709 goto done;
4711 err = got_object_open_as_tree(&tree, repo, tree_id);
4712 if (err)
4713 goto done;
4714 nentries = got_object_tree_get_nentries(tree);
4715 for (i = 0; i < nentries; i++) {
4716 struct got_tree_entry *te;
4717 char *id = NULL;
4719 if (sigint_received || sigpipe_received)
4720 break;
4722 te = got_object_tree_get_entry(tree, i);
4723 if (show_ids) {
4724 char *id_str;
4725 err = got_object_id_str(&id_str,
4726 got_tree_entry_get_id(te));
4727 if (err)
4728 goto done;
4729 if (asprintf(&id, "%s ", id_str) == -1) {
4730 err = got_error_from_errno("asprintf");
4731 free(id_str);
4732 goto done;
4734 free(id_str);
4736 err = print_entry(te, id, path, root_path, repo);
4737 free(id);
4738 if (err)
4739 goto done;
4741 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4742 char *child_path;
4743 if (asprintf(&child_path, "%s%s%s", path,
4744 path[0] == '/' && path[1] == '\0' ? "" : "/",
4745 got_tree_entry_get_name(te)) == -1) {
4746 err = got_error_from_errno("asprintf");
4747 goto done;
4749 err = print_tree(child_path, commit_id, show_ids, 1,
4750 root_path, repo);
4751 free(child_path);
4752 if (err)
4753 goto done;
4756 done:
4757 if (tree)
4758 got_object_tree_close(tree);
4759 free(tree_id);
4760 return err;
4763 static const struct got_error *
4764 cmd_tree(int argc, char *argv[])
4766 const struct got_error *error;
4767 struct got_repository *repo = NULL;
4768 struct got_worktree *worktree = NULL;
4769 const char *path, *refname = NULL;
4770 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4771 struct got_object_id *commit_id = NULL;
4772 char *commit_id_str = NULL;
4773 int show_ids = 0, recurse = 0;
4774 int ch;
4776 #ifndef PROFILE
4777 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4778 NULL) == -1)
4779 err(1, "pledge");
4780 #endif
4782 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4783 switch (ch) {
4784 case 'c':
4785 commit_id_str = optarg;
4786 break;
4787 case 'r':
4788 repo_path = realpath(optarg, NULL);
4789 if (repo_path == NULL)
4790 return got_error_from_errno2("realpath",
4791 optarg);
4792 got_path_strip_trailing_slashes(repo_path);
4793 break;
4794 case 'i':
4795 show_ids = 1;
4796 break;
4797 case 'R':
4798 recurse = 1;
4799 break;
4800 default:
4801 usage_tree();
4802 /* NOTREACHED */
4806 argc -= optind;
4807 argv += optind;
4809 if (argc == 1)
4810 path = argv[0];
4811 else if (argc > 1)
4812 usage_tree();
4813 else
4814 path = NULL;
4816 cwd = getcwd(NULL, 0);
4817 if (cwd == NULL) {
4818 error = got_error_from_errno("getcwd");
4819 goto done;
4821 if (repo_path == NULL) {
4822 error = got_worktree_open(&worktree, cwd);
4823 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4824 goto done;
4825 else
4826 error = NULL;
4827 if (worktree) {
4828 repo_path =
4829 strdup(got_worktree_get_repo_path(worktree));
4830 if (repo_path == NULL)
4831 error = got_error_from_errno("strdup");
4832 if (error)
4833 goto done;
4834 } else {
4835 repo_path = strdup(cwd);
4836 if (repo_path == NULL) {
4837 error = got_error_from_errno("strdup");
4838 goto done;
4843 error = got_repo_open(&repo, repo_path, NULL);
4844 if (error != NULL)
4845 goto done;
4847 if (worktree) {
4848 const char *prefix = got_worktree_get_path_prefix(worktree);
4849 char *p;
4851 if (path == NULL)
4852 path = "";
4853 error = got_worktree_resolve_path(&p, worktree, path);
4854 if (error)
4855 goto done;
4856 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4857 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4858 p) == -1) {
4859 error = got_error_from_errno("asprintf");
4860 free(p);
4861 goto done;
4863 free(p);
4864 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4865 if (error)
4866 goto done;
4867 } else {
4868 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4869 if (error)
4870 goto done;
4871 if (path == NULL)
4872 path = "/";
4873 error = got_repo_map_path(&in_repo_path, repo, path);
4874 if (error != NULL)
4875 goto done;
4878 if (commit_id_str == NULL) {
4879 struct got_reference *head_ref;
4880 if (worktree)
4881 refname = got_worktree_get_head_ref_name(worktree);
4882 else
4883 refname = GOT_REF_HEAD;
4884 error = got_ref_open(&head_ref, repo, refname, 0);
4885 if (error != NULL)
4886 goto done;
4887 error = got_ref_resolve(&commit_id, repo, head_ref);
4888 got_ref_close(head_ref);
4889 if (error != NULL)
4890 goto done;
4891 } else {
4892 error = got_repo_match_object_id(&commit_id, NULL,
4893 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4894 if (error)
4895 goto done;
4898 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4899 in_repo_path, repo);
4900 done:
4901 free(in_repo_path);
4902 free(repo_path);
4903 free(cwd);
4904 free(commit_id);
4905 if (worktree)
4906 got_worktree_close(worktree);
4907 if (repo) {
4908 const struct got_error *repo_error;
4909 repo_error = got_repo_close(repo);
4910 if (error == NULL)
4911 error = repo_error;
4913 return error;
4916 __dead static void
4917 usage_status(void)
4919 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4920 getprogname());
4921 exit(1);
4924 static const struct got_error *
4925 print_status(void *arg, unsigned char status, unsigned char staged_status,
4926 const char *path, struct got_object_id *blob_id,
4927 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4928 int dirfd, const char *de_name)
4930 if (status == staged_status && (status == GOT_STATUS_DELETE))
4931 status = GOT_STATUS_NO_CHANGE;
4932 if (arg) {
4933 char *status_codes = arg;
4934 size_t ncodes = strlen(status_codes);
4935 int i;
4936 for (i = 0; i < ncodes ; i++) {
4937 if (status == status_codes[i] ||
4938 staged_status == status_codes[i])
4939 break;
4941 if (i == ncodes)
4942 return NULL;
4944 printf("%c%c %s\n", status, staged_status, path);
4945 return NULL;
4948 static const struct got_error *
4949 cmd_status(int argc, char *argv[])
4951 const struct got_error *error = NULL;
4952 struct got_repository *repo = NULL;
4953 struct got_worktree *worktree = NULL;
4954 char *cwd = NULL, *status_codes = NULL;;
4955 struct got_pathlist_head paths;
4956 struct got_pathlist_entry *pe;
4957 int ch, i;
4959 TAILQ_INIT(&paths);
4961 while ((ch = getopt(argc, argv, "s:")) != -1) {
4962 switch (ch) {
4963 case 's':
4964 for (i = 0; i < strlen(optarg); i++) {
4965 switch (optarg[i]) {
4966 case GOT_STATUS_MODIFY:
4967 case GOT_STATUS_ADD:
4968 case GOT_STATUS_DELETE:
4969 case GOT_STATUS_CONFLICT:
4970 case GOT_STATUS_MISSING:
4971 case GOT_STATUS_OBSTRUCTED:
4972 case GOT_STATUS_UNVERSIONED:
4973 case GOT_STATUS_MODE_CHANGE:
4974 case GOT_STATUS_NONEXISTENT:
4975 break;
4976 default:
4977 errx(1, "invalid status code '%c'",
4978 optarg[i]);
4981 status_codes = optarg;
4982 break;
4983 default:
4984 usage_status();
4985 /* NOTREACHED */
4989 argc -= optind;
4990 argv += optind;
4992 #ifndef PROFILE
4993 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4994 NULL) == -1)
4995 err(1, "pledge");
4996 #endif
4997 cwd = getcwd(NULL, 0);
4998 if (cwd == NULL) {
4999 error = got_error_from_errno("getcwd");
5000 goto done;
5003 error = got_worktree_open(&worktree, cwd);
5004 if (error) {
5005 if (error->code == GOT_ERR_NOT_WORKTREE)
5006 error = wrap_not_worktree_error(error, "status", cwd);
5007 goto done;
5010 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5011 NULL);
5012 if (error != NULL)
5013 goto done;
5015 error = apply_unveil(got_repo_get_path(repo), 1,
5016 got_worktree_get_root_path(worktree));
5017 if (error)
5018 goto done;
5020 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5021 if (error)
5022 goto done;
5024 error = got_worktree_status(worktree, &paths, repo, print_status,
5025 status_codes, check_cancelled, NULL);
5026 done:
5027 TAILQ_FOREACH(pe, &paths, entry)
5028 free((char *)pe->path);
5029 got_pathlist_free(&paths);
5030 free(cwd);
5031 return error;
5034 __dead static void
5035 usage_ref(void)
5037 fprintf(stderr,
5038 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5039 "[-d] [name]\n",
5040 getprogname());
5041 exit(1);
5044 static const struct got_error *
5045 list_refs(struct got_repository *repo, const char *refname)
5047 static const struct got_error *err = NULL;
5048 struct got_reflist_head refs;
5049 struct got_reflist_entry *re;
5051 SIMPLEQ_INIT(&refs);
5052 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5053 if (err)
5054 return err;
5056 SIMPLEQ_FOREACH(re, &refs, entry) {
5057 char *refstr;
5058 refstr = got_ref_to_str(re->ref);
5059 if (refstr == NULL)
5060 return got_error_from_errno("got_ref_to_str");
5061 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5062 free(refstr);
5065 got_ref_list_free(&refs);
5066 return NULL;
5069 static const struct got_error *
5070 delete_ref(struct got_repository *repo, const char *refname)
5072 const struct got_error *err = NULL;
5073 struct got_reference *ref;
5075 err = got_ref_open(&ref, repo, refname, 0);
5076 if (err)
5077 return err;
5079 err = got_ref_delete(ref, repo);
5080 got_ref_close(ref);
5081 return err;
5084 static const struct got_error *
5085 add_ref(struct got_repository *repo, const char *refname, const char *target)
5087 const struct got_error *err = NULL;
5088 struct got_object_id *id;
5089 struct got_reference *ref = NULL;
5092 * Don't let the user create a reference name with a leading '-'.
5093 * While technically a valid reference name, this case is usually
5094 * an unintended typo.
5096 if (refname[0] == '-')
5097 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5099 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5100 repo);
5101 if (err) {
5102 struct got_reference *target_ref;
5104 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5105 return err;
5106 err = got_ref_open(&target_ref, repo, target, 0);
5107 if (err)
5108 return err;
5109 err = got_ref_resolve(&id, repo, target_ref);
5110 got_ref_close(target_ref);
5111 if (err)
5112 return err;
5115 err = got_ref_alloc(&ref, refname, id);
5116 if (err)
5117 goto done;
5119 err = got_ref_write(ref, repo);
5120 done:
5121 if (ref)
5122 got_ref_close(ref);
5123 free(id);
5124 return err;
5127 static const struct got_error *
5128 add_symref(struct got_repository *repo, const char *refname, const char *target)
5130 const struct got_error *err = NULL;
5131 struct got_reference *ref = NULL;
5132 struct got_reference *target_ref = NULL;
5135 * Don't let the user create a reference name with a leading '-'.
5136 * While technically a valid reference name, this case is usually
5137 * an unintended typo.
5139 if (refname[0] == '-')
5140 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5142 err = got_ref_open(&target_ref, repo, target, 0);
5143 if (err)
5144 return err;
5146 err = got_ref_alloc_symref(&ref, refname, target_ref);
5147 if (err)
5148 goto done;
5150 err = got_ref_write(ref, repo);
5151 done:
5152 if (target_ref)
5153 got_ref_close(target_ref);
5154 if (ref)
5155 got_ref_close(ref);
5156 return err;
5159 static const struct got_error *
5160 cmd_ref(int argc, char *argv[])
5162 const struct got_error *error = NULL;
5163 struct got_repository *repo = NULL;
5164 struct got_worktree *worktree = NULL;
5165 char *cwd = NULL, *repo_path = NULL;
5166 int ch, do_list = 0, do_delete = 0;
5167 const char *obj_arg = NULL, *symref_target= NULL;
5168 char *refname = NULL;
5170 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5171 switch (ch) {
5172 case 'c':
5173 obj_arg = optarg;
5174 break;
5175 case 'd':
5176 do_delete = 1;
5177 break;
5178 case 'r':
5179 repo_path = realpath(optarg, NULL);
5180 if (repo_path == NULL)
5181 return got_error_from_errno2("realpath",
5182 optarg);
5183 got_path_strip_trailing_slashes(repo_path);
5184 break;
5185 case 'l':
5186 do_list = 1;
5187 break;
5188 case 's':
5189 symref_target = optarg;
5190 break;
5191 default:
5192 usage_ref();
5193 /* NOTREACHED */
5197 if (obj_arg && do_list)
5198 errx(1, "-c and -l options are mutually exclusive");
5199 if (obj_arg && do_delete)
5200 errx(1, "-c and -d options are mutually exclusive");
5201 if (obj_arg && symref_target)
5202 errx(1, "-c and -s options are mutually exclusive");
5203 if (symref_target && do_delete)
5204 errx(1, "-s and -d options are mutually exclusive");
5205 if (symref_target && do_list)
5206 errx(1, "-s and -l options are mutually exclusive");
5207 if (do_delete && do_list)
5208 errx(1, "-d and -l options are mutually exclusive");
5210 argc -= optind;
5211 argv += optind;
5213 if (do_list) {
5214 if (argc != 0 && argc != 1)
5215 usage_ref();
5216 if (argc == 1) {
5217 refname = strdup(argv[0]);
5218 if (refname == NULL) {
5219 error = got_error_from_errno("strdup");
5220 goto done;
5223 } else {
5224 if (argc != 1)
5225 usage_ref();
5226 refname = strdup(argv[0]);
5227 if (refname == NULL) {
5228 error = got_error_from_errno("strdup");
5229 goto done;
5233 if (refname)
5234 got_path_strip_trailing_slashes(refname);
5236 #ifndef PROFILE
5237 if (do_list) {
5238 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5239 NULL) == -1)
5240 err(1, "pledge");
5241 } else {
5242 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5243 "sendfd unveil", NULL) == -1)
5244 err(1, "pledge");
5246 #endif
5247 cwd = getcwd(NULL, 0);
5248 if (cwd == NULL) {
5249 error = got_error_from_errno("getcwd");
5250 goto done;
5253 if (repo_path == NULL) {
5254 error = got_worktree_open(&worktree, cwd);
5255 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5256 goto done;
5257 else
5258 error = NULL;
5259 if (worktree) {
5260 repo_path =
5261 strdup(got_worktree_get_repo_path(worktree));
5262 if (repo_path == NULL)
5263 error = got_error_from_errno("strdup");
5264 if (error)
5265 goto done;
5266 } else {
5267 repo_path = strdup(cwd);
5268 if (repo_path == NULL) {
5269 error = got_error_from_errno("strdup");
5270 goto done;
5275 error = got_repo_open(&repo, repo_path, NULL);
5276 if (error != NULL)
5277 goto done;
5279 error = apply_unveil(got_repo_get_path(repo), do_list,
5280 worktree ? got_worktree_get_root_path(worktree) : NULL);
5281 if (error)
5282 goto done;
5284 if (do_list)
5285 error = list_refs(repo, refname);
5286 else if (do_delete)
5287 error = delete_ref(repo, refname);
5288 else if (symref_target)
5289 error = add_symref(repo, refname, symref_target);
5290 else {
5291 if (obj_arg == NULL)
5292 usage_ref();
5293 error = add_ref(repo, refname, obj_arg);
5295 done:
5296 free(refname);
5297 if (repo)
5298 got_repo_close(repo);
5299 if (worktree)
5300 got_worktree_close(worktree);
5301 free(cwd);
5302 free(repo_path);
5303 return error;
5306 __dead static void
5307 usage_branch(void)
5309 fprintf(stderr,
5310 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5311 "[name]\n", getprogname());
5312 exit(1);
5315 static const struct got_error *
5316 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5317 struct got_reference *ref)
5319 const struct got_error *err = NULL;
5320 const char *refname, *marker = " ";
5321 char *refstr;
5323 refname = got_ref_get_name(ref);
5324 if (worktree && strcmp(refname,
5325 got_worktree_get_head_ref_name(worktree)) == 0) {
5326 struct got_object_id *id = NULL;
5328 err = got_ref_resolve(&id, repo, ref);
5329 if (err)
5330 return err;
5331 if (got_object_id_cmp(id,
5332 got_worktree_get_base_commit_id(worktree)) == 0)
5333 marker = "* ";
5334 else
5335 marker = "~ ";
5336 free(id);
5339 if (strncmp(refname, "refs/heads/", 11) == 0)
5340 refname += 11;
5341 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5342 refname += 18;
5344 refstr = got_ref_to_str(ref);
5345 if (refstr == NULL)
5346 return got_error_from_errno("got_ref_to_str");
5348 printf("%s%s: %s\n", marker, refname, refstr);
5349 free(refstr);
5350 return NULL;
5353 static const struct got_error *
5354 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5356 const char *refname;
5358 if (worktree == NULL)
5359 return got_error(GOT_ERR_NOT_WORKTREE);
5361 refname = got_worktree_get_head_ref_name(worktree);
5363 if (strncmp(refname, "refs/heads/", 11) == 0)
5364 refname += 11;
5365 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5366 refname += 18;
5368 printf("%s\n", refname);
5370 return NULL;
5373 static const struct got_error *
5374 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5376 static const struct got_error *err = NULL;
5377 struct got_reflist_head refs;
5378 struct got_reflist_entry *re;
5379 struct got_reference *temp_ref = NULL;
5380 int rebase_in_progress, histedit_in_progress;
5382 SIMPLEQ_INIT(&refs);
5384 if (worktree) {
5385 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5386 worktree);
5387 if (err)
5388 return err;
5390 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5391 worktree);
5392 if (err)
5393 return err;
5395 if (rebase_in_progress || histedit_in_progress) {
5396 err = got_ref_open(&temp_ref, repo,
5397 got_worktree_get_head_ref_name(worktree), 0);
5398 if (err)
5399 return err;
5400 list_branch(repo, worktree, temp_ref);
5401 got_ref_close(temp_ref);
5405 err = got_ref_list(&refs, repo, "refs/heads",
5406 got_ref_cmp_by_name, NULL);
5407 if (err)
5408 return err;
5410 SIMPLEQ_FOREACH(re, &refs, entry)
5411 list_branch(repo, worktree, re->ref);
5413 got_ref_list_free(&refs);
5414 return NULL;
5417 static const struct got_error *
5418 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5419 const char *branch_name)
5421 const struct got_error *err = NULL;
5422 struct got_reference *ref = NULL;
5423 char *refname;
5425 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5426 return got_error_from_errno("asprintf");
5428 err = got_ref_open(&ref, repo, refname, 0);
5429 if (err)
5430 goto done;
5432 if (worktree &&
5433 strcmp(got_worktree_get_head_ref_name(worktree),
5434 got_ref_get_name(ref)) == 0) {
5435 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5436 "will not delete this work tree's current branch");
5437 goto done;
5440 err = got_ref_delete(ref, repo);
5441 done:
5442 if (ref)
5443 got_ref_close(ref);
5444 free(refname);
5445 return err;
5448 static const struct got_error *
5449 add_branch(struct got_repository *repo, const char *branch_name,
5450 struct got_object_id *base_commit_id)
5452 const struct got_error *err = NULL;
5453 struct got_reference *ref = NULL;
5454 char *base_refname = NULL, *refname = NULL;
5457 * Don't let the user create a branch name with a leading '-'.
5458 * While technically a valid reference name, this case is usually
5459 * an unintended typo.
5461 if (branch_name[0] == '-')
5462 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5464 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5465 err = got_error_from_errno("asprintf");
5466 goto done;
5469 err = got_ref_open(&ref, repo, refname, 0);
5470 if (err == NULL) {
5471 err = got_error(GOT_ERR_BRANCH_EXISTS);
5472 goto done;
5473 } else if (err->code != GOT_ERR_NOT_REF)
5474 goto done;
5476 err = got_ref_alloc(&ref, refname, base_commit_id);
5477 if (err)
5478 goto done;
5480 err = got_ref_write(ref, repo);
5481 done:
5482 if (ref)
5483 got_ref_close(ref);
5484 free(base_refname);
5485 free(refname);
5486 return err;
5489 static const struct got_error *
5490 cmd_branch(int argc, char *argv[])
5492 const struct got_error *error = NULL;
5493 struct got_repository *repo = NULL;
5494 struct got_worktree *worktree = NULL;
5495 char *cwd = NULL, *repo_path = NULL;
5496 int ch, do_list = 0, do_show = 0, do_update = 1;
5497 const char *delref = NULL, *commit_id_arg = NULL;
5498 struct got_reference *ref = NULL;
5499 struct got_pathlist_head paths;
5500 struct got_pathlist_entry *pe;
5501 struct got_object_id *commit_id = NULL;
5502 char *commit_id_str = NULL;
5504 TAILQ_INIT(&paths);
5506 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5507 switch (ch) {
5508 case 'c':
5509 commit_id_arg = optarg;
5510 break;
5511 case 'd':
5512 delref = optarg;
5513 break;
5514 case 'r':
5515 repo_path = realpath(optarg, NULL);
5516 if (repo_path == NULL)
5517 return got_error_from_errno2("realpath",
5518 optarg);
5519 got_path_strip_trailing_slashes(repo_path);
5520 break;
5521 case 'l':
5522 do_list = 1;
5523 break;
5524 case 'n':
5525 do_update = 0;
5526 break;
5527 default:
5528 usage_branch();
5529 /* NOTREACHED */
5533 if (do_list && delref)
5534 errx(1, "-l and -d options are mutually exclusive");
5536 argc -= optind;
5537 argv += optind;
5539 if (!do_list && !delref && argc == 0)
5540 do_show = 1;
5542 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5543 errx(1, "-c option can only be used when creating a branch");
5545 if (do_list || delref) {
5546 if (argc > 0)
5547 usage_branch();
5548 } else if (!do_show && argc != 1)
5549 usage_branch();
5551 #ifndef PROFILE
5552 if (do_list || do_show) {
5553 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5554 NULL) == -1)
5555 err(1, "pledge");
5556 } else {
5557 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5558 "sendfd unveil", NULL) == -1)
5559 err(1, "pledge");
5561 #endif
5562 cwd = getcwd(NULL, 0);
5563 if (cwd == NULL) {
5564 error = got_error_from_errno("getcwd");
5565 goto done;
5568 if (repo_path == NULL) {
5569 error = got_worktree_open(&worktree, cwd);
5570 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5571 goto done;
5572 else
5573 error = NULL;
5574 if (worktree) {
5575 repo_path =
5576 strdup(got_worktree_get_repo_path(worktree));
5577 if (repo_path == NULL)
5578 error = got_error_from_errno("strdup");
5579 if (error)
5580 goto done;
5581 } else {
5582 repo_path = strdup(cwd);
5583 if (repo_path == NULL) {
5584 error = got_error_from_errno("strdup");
5585 goto done;
5590 error = got_repo_open(&repo, repo_path, NULL);
5591 if (error != NULL)
5592 goto done;
5594 error = apply_unveil(got_repo_get_path(repo), do_list,
5595 worktree ? got_worktree_get_root_path(worktree) : NULL);
5596 if (error)
5597 goto done;
5599 if (do_show)
5600 error = show_current_branch(repo, worktree);
5601 else if (do_list)
5602 error = list_branches(repo, worktree);
5603 else if (delref)
5604 error = delete_branch(repo, worktree, delref);
5605 else {
5606 if (commit_id_arg == NULL)
5607 commit_id_arg = worktree ?
5608 got_worktree_get_head_ref_name(worktree) :
5609 GOT_REF_HEAD;
5610 error = got_repo_match_object_id(&commit_id, NULL,
5611 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5612 if (error)
5613 goto done;
5614 error = add_branch(repo, argv[0], commit_id);
5615 if (error)
5616 goto done;
5617 if (worktree && do_update) {
5618 struct got_update_progress_arg upa;
5619 char *branch_refname = NULL;
5621 error = got_object_id_str(&commit_id_str, commit_id);
5622 if (error)
5623 goto done;
5624 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5625 worktree);
5626 if (error)
5627 goto done;
5628 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5629 == -1) {
5630 error = got_error_from_errno("asprintf");
5631 goto done;
5633 error = got_ref_open(&ref, repo, branch_refname, 0);
5634 free(branch_refname);
5635 if (error)
5636 goto done;
5637 error = switch_head_ref(ref, commit_id, worktree,
5638 repo);
5639 if (error)
5640 goto done;
5641 error = got_worktree_set_base_commit_id(worktree, repo,
5642 commit_id);
5643 if (error)
5644 goto done;
5645 memset(&upa, 0, sizeof(upa));
5646 error = got_worktree_checkout_files(worktree, &paths,
5647 repo, update_progress, &upa, check_cancelled,
5648 NULL);
5649 if (error)
5650 goto done;
5651 if (upa.did_something)
5652 printf("Updated to commit %s\n", commit_id_str);
5653 print_update_progress_stats(&upa);
5656 done:
5657 if (ref)
5658 got_ref_close(ref);
5659 if (repo)
5660 got_repo_close(repo);
5661 if (worktree)
5662 got_worktree_close(worktree);
5663 free(cwd);
5664 free(repo_path);
5665 free(commit_id);
5666 free(commit_id_str);
5667 TAILQ_FOREACH(pe, &paths, entry)
5668 free((char *)pe->path);
5669 got_pathlist_free(&paths);
5670 return error;
5674 __dead static void
5675 usage_tag(void)
5677 fprintf(stderr,
5678 "usage: %s tag [-c commit] [-r repository] [-l] "
5679 "[-m message] name\n", getprogname());
5680 exit(1);
5683 #if 0
5684 static const struct got_error *
5685 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5687 const struct got_error *err = NULL;
5688 struct got_reflist_entry *re, *se, *new;
5689 struct got_object_id *re_id, *se_id;
5690 struct got_tag_object *re_tag, *se_tag;
5691 time_t re_time, se_time;
5693 SIMPLEQ_FOREACH(re, tags, entry) {
5694 se = SIMPLEQ_FIRST(sorted);
5695 if (se == NULL) {
5696 err = got_reflist_entry_dup(&new, re);
5697 if (err)
5698 return err;
5699 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5700 continue;
5701 } else {
5702 err = got_ref_resolve(&re_id, repo, re->ref);
5703 if (err)
5704 break;
5705 err = got_object_open_as_tag(&re_tag, repo, re_id);
5706 free(re_id);
5707 if (err)
5708 break;
5709 re_time = got_object_tag_get_tagger_time(re_tag);
5710 got_object_tag_close(re_tag);
5713 while (se) {
5714 err = got_ref_resolve(&se_id, repo, re->ref);
5715 if (err)
5716 break;
5717 err = got_object_open_as_tag(&se_tag, repo, se_id);
5718 free(se_id);
5719 if (err)
5720 break;
5721 se_time = got_object_tag_get_tagger_time(se_tag);
5722 got_object_tag_close(se_tag);
5724 if (se_time > re_time) {
5725 err = got_reflist_entry_dup(&new, re);
5726 if (err)
5727 return err;
5728 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5729 break;
5731 se = SIMPLEQ_NEXT(se, entry);
5732 continue;
5735 done:
5736 return err;
5738 #endif
5740 static const struct got_error *
5741 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5743 static const struct got_error *err = NULL;
5744 struct got_reflist_head refs;
5745 struct got_reflist_entry *re;
5747 SIMPLEQ_INIT(&refs);
5749 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5750 if (err)
5751 return err;
5753 SIMPLEQ_FOREACH(re, &refs, entry) {
5754 const char *refname;
5755 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5756 char datebuf[26];
5757 const char *tagger;
5758 time_t tagger_time;
5759 struct got_object_id *id;
5760 struct got_tag_object *tag;
5761 struct got_commit_object *commit = NULL;
5763 refname = got_ref_get_name(re->ref);
5764 if (strncmp(refname, "refs/tags/", 10) != 0)
5765 continue;
5766 refname += 10;
5767 refstr = got_ref_to_str(re->ref);
5768 if (refstr == NULL) {
5769 err = got_error_from_errno("got_ref_to_str");
5770 break;
5772 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5773 free(refstr);
5775 err = got_ref_resolve(&id, repo, re->ref);
5776 if (err)
5777 break;
5778 err = got_object_open_as_tag(&tag, repo, id);
5779 if (err) {
5780 if (err->code != GOT_ERR_OBJ_TYPE) {
5781 free(id);
5782 break;
5784 /* "lightweight" tag */
5785 err = got_object_open_as_commit(&commit, repo, id);
5786 if (err) {
5787 free(id);
5788 break;
5790 tagger = got_object_commit_get_committer(commit);
5791 tagger_time =
5792 got_object_commit_get_committer_time(commit);
5793 err = got_object_id_str(&id_str, id);
5794 free(id);
5795 if (err)
5796 break;
5797 } else {
5798 free(id);
5799 tagger = got_object_tag_get_tagger(tag);
5800 tagger_time = got_object_tag_get_tagger_time(tag);
5801 err = got_object_id_str(&id_str,
5802 got_object_tag_get_object_id(tag));
5803 if (err)
5804 break;
5806 printf("from: %s\n", tagger);
5807 datestr = get_datestr(&tagger_time, datebuf);
5808 if (datestr)
5809 printf("date: %s UTC\n", datestr);
5810 if (commit)
5811 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5812 else {
5813 switch (got_object_tag_get_object_type(tag)) {
5814 case GOT_OBJ_TYPE_BLOB:
5815 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5816 id_str);
5817 break;
5818 case GOT_OBJ_TYPE_TREE:
5819 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5820 id_str);
5821 break;
5822 case GOT_OBJ_TYPE_COMMIT:
5823 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5824 id_str);
5825 break;
5826 case GOT_OBJ_TYPE_TAG:
5827 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5828 id_str);
5829 break;
5830 default:
5831 break;
5834 free(id_str);
5835 if (commit) {
5836 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5837 if (err)
5838 break;
5839 got_object_commit_close(commit);
5840 } else {
5841 tagmsg0 = strdup(got_object_tag_get_message(tag));
5842 got_object_tag_close(tag);
5843 if (tagmsg0 == NULL) {
5844 err = got_error_from_errno("strdup");
5845 break;
5849 tagmsg = tagmsg0;
5850 do {
5851 line = strsep(&tagmsg, "\n");
5852 if (line)
5853 printf(" %s\n", line);
5854 } while (line);
5855 free(tagmsg0);
5858 got_ref_list_free(&refs);
5859 return NULL;
5862 static const struct got_error *
5863 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5864 const char *tag_name, const char *repo_path)
5866 const struct got_error *err = NULL;
5867 char *template = NULL, *initial_content = NULL;
5868 char *editor = NULL;
5869 int initial_content_len;
5870 int fd = -1;
5872 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5873 err = got_error_from_errno("asprintf");
5874 goto done;
5877 initial_content_len = asprintf(&initial_content,
5878 "\n# tagging commit %s as %s\n",
5879 commit_id_str, tag_name);
5880 if (initial_content_len == -1) {
5881 err = got_error_from_errno("asprintf");
5882 goto done;
5885 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5886 if (err)
5887 goto done;
5889 if (write(fd, initial_content, initial_content_len) == -1) {
5890 err = got_error_from_errno2("write", *tagmsg_path);
5891 goto done;
5894 err = get_editor(&editor);
5895 if (err)
5896 goto done;
5897 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5898 initial_content_len);
5899 done:
5900 free(initial_content);
5901 free(template);
5902 free(editor);
5904 if (fd != -1 && close(fd) == -1 && err == NULL)
5905 err = got_error_from_errno2("close", *tagmsg_path);
5907 /* Editor is done; we can now apply unveil(2) */
5908 if (err == NULL)
5909 err = apply_unveil(repo_path, 0, NULL);
5910 if (err) {
5911 free(*tagmsg);
5912 *tagmsg = NULL;
5914 return err;
5917 static const struct got_error *
5918 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5919 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5921 const struct got_error *err = NULL;
5922 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5923 char *label = NULL, *commit_id_str = NULL;
5924 struct got_reference *ref = NULL;
5925 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5926 char *tagmsg_path = NULL, *tag_id_str = NULL;
5927 int preserve_tagmsg = 0;
5930 * Don't let the user create a tag name with a leading '-'.
5931 * While technically a valid reference name, this case is usually
5932 * an unintended typo.
5934 if (tag_name[0] == '-')
5935 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5937 err = get_author(&tagger, repo, worktree);
5938 if (err)
5939 return err;
5941 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5942 GOT_OBJ_TYPE_COMMIT, 1, repo);
5943 if (err)
5944 goto done;
5946 err = got_object_id_str(&commit_id_str, commit_id);
5947 if (err)
5948 goto done;
5950 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5951 refname = strdup(tag_name);
5952 if (refname == NULL) {
5953 err = got_error_from_errno("strdup");
5954 goto done;
5956 tag_name += 10;
5957 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5958 err = got_error_from_errno("asprintf");
5959 goto done;
5962 err = got_ref_open(&ref, repo, refname, 0);
5963 if (err == NULL) {
5964 err = got_error(GOT_ERR_TAG_EXISTS);
5965 goto done;
5966 } else if (err->code != GOT_ERR_NOT_REF)
5967 goto done;
5969 if (tagmsg_arg == NULL) {
5970 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5971 tag_name, got_repo_get_path(repo));
5972 if (err) {
5973 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5974 tagmsg_path != NULL)
5975 preserve_tagmsg = 1;
5976 goto done;
5980 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5981 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5982 if (err) {
5983 if (tagmsg_path)
5984 preserve_tagmsg = 1;
5985 goto done;
5988 err = got_ref_alloc(&ref, refname, tag_id);
5989 if (err) {
5990 if (tagmsg_path)
5991 preserve_tagmsg = 1;
5992 goto done;
5995 err = got_ref_write(ref, repo);
5996 if (err) {
5997 if (tagmsg_path)
5998 preserve_tagmsg = 1;
5999 goto done;
6002 err = got_object_id_str(&tag_id_str, tag_id);
6003 if (err) {
6004 if (tagmsg_path)
6005 preserve_tagmsg = 1;
6006 goto done;
6008 printf("Created tag %s\n", tag_id_str);
6009 done:
6010 if (preserve_tagmsg) {
6011 fprintf(stderr, "%s: tag message preserved in %s\n",
6012 getprogname(), tagmsg_path);
6013 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6014 err = got_error_from_errno2("unlink", tagmsg_path);
6015 free(tag_id_str);
6016 if (ref)
6017 got_ref_close(ref);
6018 free(commit_id);
6019 free(commit_id_str);
6020 free(refname);
6021 free(tagmsg);
6022 free(tagmsg_path);
6023 free(tagger);
6024 return err;
6027 static const struct got_error *
6028 cmd_tag(int argc, char *argv[])
6030 const struct got_error *error = NULL;
6031 struct got_repository *repo = NULL;
6032 struct got_worktree *worktree = NULL;
6033 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6034 char *gitconfig_path = NULL;
6035 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6036 int ch, do_list = 0;
6038 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6039 switch (ch) {
6040 case 'c':
6041 commit_id_arg = optarg;
6042 break;
6043 case 'm':
6044 tagmsg = optarg;
6045 break;
6046 case 'r':
6047 repo_path = realpath(optarg, NULL);
6048 if (repo_path == NULL)
6049 return got_error_from_errno2("realpath",
6050 optarg);
6051 got_path_strip_trailing_slashes(repo_path);
6052 break;
6053 case 'l':
6054 do_list = 1;
6055 break;
6056 default:
6057 usage_tag();
6058 /* NOTREACHED */
6062 argc -= optind;
6063 argv += optind;
6065 if (do_list) {
6066 if (commit_id_arg != NULL)
6067 errx(1,
6068 "-c option can only be used when creating a tag");
6069 if (tagmsg)
6070 errx(1, "-l and -m options are mutually exclusive");
6071 if (argc > 0)
6072 usage_tag();
6073 } else if (argc != 1)
6074 usage_tag();
6076 tag_name = argv[0];
6078 #ifndef PROFILE
6079 if (do_list) {
6080 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6081 NULL) == -1)
6082 err(1, "pledge");
6083 } else {
6084 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6085 "sendfd unveil", NULL) == -1)
6086 err(1, "pledge");
6088 #endif
6089 cwd = getcwd(NULL, 0);
6090 if (cwd == NULL) {
6091 error = got_error_from_errno("getcwd");
6092 goto done;
6095 if (repo_path == NULL) {
6096 error = got_worktree_open(&worktree, cwd);
6097 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6098 goto done;
6099 else
6100 error = NULL;
6101 if (worktree) {
6102 repo_path =
6103 strdup(got_worktree_get_repo_path(worktree));
6104 if (repo_path == NULL)
6105 error = got_error_from_errno("strdup");
6106 if (error)
6107 goto done;
6108 } else {
6109 repo_path = strdup(cwd);
6110 if (repo_path == NULL) {
6111 error = got_error_from_errno("strdup");
6112 goto done;
6117 if (do_list) {
6118 error = got_repo_open(&repo, repo_path, NULL);
6119 if (error != NULL)
6120 goto done;
6121 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6122 if (error)
6123 goto done;
6124 error = list_tags(repo, worktree);
6125 } else {
6126 error = get_gitconfig_path(&gitconfig_path);
6127 if (error)
6128 goto done;
6129 error = got_repo_open(&repo, repo_path, gitconfig_path);
6130 if (error != NULL)
6131 goto done;
6133 if (tagmsg) {
6134 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6135 if (error)
6136 goto done;
6139 if (commit_id_arg == NULL) {
6140 struct got_reference *head_ref;
6141 struct got_object_id *commit_id;
6142 error = got_ref_open(&head_ref, repo,
6143 worktree ? got_worktree_get_head_ref_name(worktree)
6144 : GOT_REF_HEAD, 0);
6145 if (error)
6146 goto done;
6147 error = got_ref_resolve(&commit_id, repo, head_ref);
6148 got_ref_close(head_ref);
6149 if (error)
6150 goto done;
6151 error = got_object_id_str(&commit_id_str, commit_id);
6152 free(commit_id);
6153 if (error)
6154 goto done;
6157 error = add_tag(repo, worktree, tag_name,
6158 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6160 done:
6161 if (repo)
6162 got_repo_close(repo);
6163 if (worktree)
6164 got_worktree_close(worktree);
6165 free(cwd);
6166 free(repo_path);
6167 free(gitconfig_path);
6168 free(commit_id_str);
6169 return error;
6172 __dead static void
6173 usage_add(void)
6175 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6176 getprogname());
6177 exit(1);
6180 static const struct got_error *
6181 add_progress(void *arg, unsigned char status, const char *path)
6183 while (path[0] == '/')
6184 path++;
6185 printf("%c %s\n", status, path);
6186 return NULL;
6189 static const struct got_error *
6190 cmd_add(int argc, char *argv[])
6192 const struct got_error *error = NULL;
6193 struct got_repository *repo = NULL;
6194 struct got_worktree *worktree = NULL;
6195 char *cwd = NULL;
6196 struct got_pathlist_head paths;
6197 struct got_pathlist_entry *pe;
6198 int ch, can_recurse = 0, no_ignores = 0;
6200 TAILQ_INIT(&paths);
6202 while ((ch = getopt(argc, argv, "IR")) != -1) {
6203 switch (ch) {
6204 case 'I':
6205 no_ignores = 1;
6206 break;
6207 case 'R':
6208 can_recurse = 1;
6209 break;
6210 default:
6211 usage_add();
6212 /* NOTREACHED */
6216 argc -= optind;
6217 argv += optind;
6219 #ifndef PROFILE
6220 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6221 NULL) == -1)
6222 err(1, "pledge");
6223 #endif
6224 if (argc < 1)
6225 usage_add();
6227 cwd = getcwd(NULL, 0);
6228 if (cwd == NULL) {
6229 error = got_error_from_errno("getcwd");
6230 goto done;
6233 error = got_worktree_open(&worktree, cwd);
6234 if (error) {
6235 if (error->code == GOT_ERR_NOT_WORKTREE)
6236 error = wrap_not_worktree_error(error, "add", cwd);
6237 goto done;
6240 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6241 NULL);
6242 if (error != NULL)
6243 goto done;
6245 error = apply_unveil(got_repo_get_path(repo), 1,
6246 got_worktree_get_root_path(worktree));
6247 if (error)
6248 goto done;
6250 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6251 if (error)
6252 goto done;
6254 if (!can_recurse && no_ignores) {
6255 error = got_error_msg(GOT_ERR_BAD_PATH,
6256 "disregarding ignores requires -R option");
6257 goto done;
6261 if (!can_recurse) {
6262 char *ondisk_path;
6263 struct stat sb;
6264 TAILQ_FOREACH(pe, &paths, entry) {
6265 if (asprintf(&ondisk_path, "%s/%s",
6266 got_worktree_get_root_path(worktree),
6267 pe->path) == -1) {
6268 error = got_error_from_errno("asprintf");
6269 goto done;
6271 if (lstat(ondisk_path, &sb) == -1) {
6272 if (errno == ENOENT) {
6273 free(ondisk_path);
6274 continue;
6276 error = got_error_from_errno2("lstat",
6277 ondisk_path);
6278 free(ondisk_path);
6279 goto done;
6281 free(ondisk_path);
6282 if (S_ISDIR(sb.st_mode)) {
6283 error = got_error_msg(GOT_ERR_BAD_PATH,
6284 "adding directories requires -R option");
6285 goto done;
6290 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6291 NULL, repo, no_ignores);
6292 done:
6293 if (repo)
6294 got_repo_close(repo);
6295 if (worktree)
6296 got_worktree_close(worktree);
6297 TAILQ_FOREACH(pe, &paths, entry)
6298 free((char *)pe->path);
6299 got_pathlist_free(&paths);
6300 free(cwd);
6301 return error;
6304 __dead static void
6305 usage_remove(void)
6307 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6308 "path ...\n", getprogname());
6309 exit(1);
6312 static const struct got_error *
6313 print_remove_status(void *arg, unsigned char status,
6314 unsigned char staged_status, const char *path)
6316 while (path[0] == '/')
6317 path++;
6318 if (status == GOT_STATUS_NONEXISTENT)
6319 return NULL;
6320 if (status == staged_status && (status == GOT_STATUS_DELETE))
6321 status = GOT_STATUS_NO_CHANGE;
6322 printf("%c%c %s\n", status, staged_status, path);
6323 return NULL;
6326 static const struct got_error *
6327 cmd_remove(int argc, char *argv[])
6329 const struct got_error *error = NULL;
6330 struct got_worktree *worktree = NULL;
6331 struct got_repository *repo = NULL;
6332 const char *status_codes = NULL;
6333 char *cwd = NULL;
6334 struct got_pathlist_head paths;
6335 struct got_pathlist_entry *pe;
6336 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6338 TAILQ_INIT(&paths);
6340 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6341 switch (ch) {
6342 case 'f':
6343 delete_local_mods = 1;
6344 break;
6345 case 'k':
6346 keep_on_disk = 1;
6347 break;
6348 case 'R':
6349 can_recurse = 1;
6350 break;
6351 case 's':
6352 for (i = 0; i < strlen(optarg); i++) {
6353 switch (optarg[i]) {
6354 case GOT_STATUS_MODIFY:
6355 delete_local_mods = 1;
6356 break;
6357 case GOT_STATUS_MISSING:
6358 break;
6359 default:
6360 errx(1, "invalid status code '%c'",
6361 optarg[i]);
6364 status_codes = optarg;
6365 break;
6366 default:
6367 usage_remove();
6368 /* NOTREACHED */
6372 argc -= optind;
6373 argv += optind;
6375 #ifndef PROFILE
6376 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6377 NULL) == -1)
6378 err(1, "pledge");
6379 #endif
6380 if (argc < 1)
6381 usage_remove();
6383 cwd = getcwd(NULL, 0);
6384 if (cwd == NULL) {
6385 error = got_error_from_errno("getcwd");
6386 goto done;
6388 error = got_worktree_open(&worktree, cwd);
6389 if (error) {
6390 if (error->code == GOT_ERR_NOT_WORKTREE)
6391 error = wrap_not_worktree_error(error, "remove", cwd);
6392 goto done;
6395 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6396 NULL);
6397 if (error)
6398 goto done;
6400 error = apply_unveil(got_repo_get_path(repo), 1,
6401 got_worktree_get_root_path(worktree));
6402 if (error)
6403 goto done;
6405 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6406 if (error)
6407 goto done;
6409 if (!can_recurse) {
6410 char *ondisk_path;
6411 struct stat sb;
6412 TAILQ_FOREACH(pe, &paths, entry) {
6413 if (asprintf(&ondisk_path, "%s/%s",
6414 got_worktree_get_root_path(worktree),
6415 pe->path) == -1) {
6416 error = got_error_from_errno("asprintf");
6417 goto done;
6419 if (lstat(ondisk_path, &sb) == -1) {
6420 if (errno == ENOENT) {
6421 free(ondisk_path);
6422 continue;
6424 error = got_error_from_errno2("lstat",
6425 ondisk_path);
6426 free(ondisk_path);
6427 goto done;
6429 free(ondisk_path);
6430 if (S_ISDIR(sb.st_mode)) {
6431 error = got_error_msg(GOT_ERR_BAD_PATH,
6432 "removing directories requires -R option");
6433 goto done;
6438 error = got_worktree_schedule_delete(worktree, &paths,
6439 delete_local_mods, status_codes, print_remove_status, NULL,
6440 repo, keep_on_disk);
6441 done:
6442 if (repo)
6443 got_repo_close(repo);
6444 if (worktree)
6445 got_worktree_close(worktree);
6446 TAILQ_FOREACH(pe, &paths, entry)
6447 free((char *)pe->path);
6448 got_pathlist_free(&paths);
6449 free(cwd);
6450 return error;
6453 __dead static void
6454 usage_revert(void)
6456 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6457 "path ...\n", getprogname());
6458 exit(1);
6461 static const struct got_error *
6462 revert_progress(void *arg, unsigned char status, const char *path)
6464 if (status == GOT_STATUS_UNVERSIONED)
6465 return NULL;
6467 while (path[0] == '/')
6468 path++;
6469 printf("%c %s\n", status, path);
6470 return NULL;
6473 struct choose_patch_arg {
6474 FILE *patch_script_file;
6475 const char *action;
6478 static const struct got_error *
6479 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6480 int nchanges, const char *action)
6482 char *line = NULL;
6483 size_t linesize = 0;
6484 ssize_t linelen;
6486 switch (status) {
6487 case GOT_STATUS_ADD:
6488 printf("A %s\n%s this addition? [y/n] ", path, action);
6489 break;
6490 case GOT_STATUS_DELETE:
6491 printf("D %s\n%s this deletion? [y/n] ", path, action);
6492 break;
6493 case GOT_STATUS_MODIFY:
6494 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6495 return got_error_from_errno("fseek");
6496 printf(GOT_COMMIT_SEP_STR);
6497 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6498 printf("%s", line);
6499 if (ferror(patch_file))
6500 return got_error_from_errno("getline");
6501 printf(GOT_COMMIT_SEP_STR);
6502 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6503 path, n, nchanges, action);
6504 break;
6505 default:
6506 return got_error_path(path, GOT_ERR_FILE_STATUS);
6509 return NULL;
6512 static const struct got_error *
6513 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6514 FILE *patch_file, int n, int nchanges)
6516 const struct got_error *err = NULL;
6517 char *line = NULL;
6518 size_t linesize = 0;
6519 ssize_t linelen;
6520 int resp = ' ';
6521 struct choose_patch_arg *a = arg;
6523 *choice = GOT_PATCH_CHOICE_NONE;
6525 if (a->patch_script_file) {
6526 char *nl;
6527 err = show_change(status, path, patch_file, n, nchanges,
6528 a->action);
6529 if (err)
6530 return err;
6531 linelen = getline(&line, &linesize, a->patch_script_file);
6532 if (linelen == -1) {
6533 if (ferror(a->patch_script_file))
6534 return got_error_from_errno("getline");
6535 return NULL;
6537 nl = strchr(line, '\n');
6538 if (nl)
6539 *nl = '\0';
6540 if (strcmp(line, "y") == 0) {
6541 *choice = GOT_PATCH_CHOICE_YES;
6542 printf("y\n");
6543 } else if (strcmp(line, "n") == 0) {
6544 *choice = GOT_PATCH_CHOICE_NO;
6545 printf("n\n");
6546 } else if (strcmp(line, "q") == 0 &&
6547 status == GOT_STATUS_MODIFY) {
6548 *choice = GOT_PATCH_CHOICE_QUIT;
6549 printf("q\n");
6550 } else
6551 printf("invalid response '%s'\n", line);
6552 free(line);
6553 return NULL;
6556 while (resp != 'y' && resp != 'n' && resp != 'q') {
6557 err = show_change(status, path, patch_file, n, nchanges,
6558 a->action);
6559 if (err)
6560 return err;
6561 resp = getchar();
6562 if (resp == '\n')
6563 resp = getchar();
6564 if (status == GOT_STATUS_MODIFY) {
6565 if (resp != 'y' && resp != 'n' && resp != 'q') {
6566 printf("invalid response '%c'\n", resp);
6567 resp = ' ';
6569 } else if (resp != 'y' && resp != 'n') {
6570 printf("invalid response '%c'\n", resp);
6571 resp = ' ';
6575 if (resp == 'y')
6576 *choice = GOT_PATCH_CHOICE_YES;
6577 else if (resp == 'n')
6578 *choice = GOT_PATCH_CHOICE_NO;
6579 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6580 *choice = GOT_PATCH_CHOICE_QUIT;
6582 return NULL;
6586 static const struct got_error *
6587 cmd_revert(int argc, char *argv[])
6589 const struct got_error *error = NULL;
6590 struct got_worktree *worktree = NULL;
6591 struct got_repository *repo = NULL;
6592 char *cwd = NULL, *path = NULL;
6593 struct got_pathlist_head paths;
6594 struct got_pathlist_entry *pe;
6595 int ch, can_recurse = 0, pflag = 0;
6596 FILE *patch_script_file = NULL;
6597 const char *patch_script_path = NULL;
6598 struct choose_patch_arg cpa;
6600 TAILQ_INIT(&paths);
6602 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6603 switch (ch) {
6604 case 'p':
6605 pflag = 1;
6606 break;
6607 case 'F':
6608 patch_script_path = optarg;
6609 break;
6610 case 'R':
6611 can_recurse = 1;
6612 break;
6613 default:
6614 usage_revert();
6615 /* NOTREACHED */
6619 argc -= optind;
6620 argv += optind;
6622 #ifndef PROFILE
6623 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6624 "unveil", NULL) == -1)
6625 err(1, "pledge");
6626 #endif
6627 if (argc < 1)
6628 usage_revert();
6629 if (patch_script_path && !pflag)
6630 errx(1, "-F option can only be used together with -p option");
6632 cwd = getcwd(NULL, 0);
6633 if (cwd == NULL) {
6634 error = got_error_from_errno("getcwd");
6635 goto done;
6637 error = got_worktree_open(&worktree, cwd);
6638 if (error) {
6639 if (error->code == GOT_ERR_NOT_WORKTREE)
6640 error = wrap_not_worktree_error(error, "revert", cwd);
6641 goto done;
6644 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6645 NULL);
6646 if (error != NULL)
6647 goto done;
6649 if (patch_script_path) {
6650 patch_script_file = fopen(patch_script_path, "r");
6651 if (patch_script_file == NULL) {
6652 error = got_error_from_errno2("fopen",
6653 patch_script_path);
6654 goto done;
6657 error = apply_unveil(got_repo_get_path(repo), 1,
6658 got_worktree_get_root_path(worktree));
6659 if (error)
6660 goto done;
6662 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6663 if (error)
6664 goto done;
6666 if (!can_recurse) {
6667 char *ondisk_path;
6668 struct stat sb;
6669 TAILQ_FOREACH(pe, &paths, entry) {
6670 if (asprintf(&ondisk_path, "%s/%s",
6671 got_worktree_get_root_path(worktree),
6672 pe->path) == -1) {
6673 error = got_error_from_errno("asprintf");
6674 goto done;
6676 if (lstat(ondisk_path, &sb) == -1) {
6677 if (errno == ENOENT) {
6678 free(ondisk_path);
6679 continue;
6681 error = got_error_from_errno2("lstat",
6682 ondisk_path);
6683 free(ondisk_path);
6684 goto done;
6686 free(ondisk_path);
6687 if (S_ISDIR(sb.st_mode)) {
6688 error = got_error_msg(GOT_ERR_BAD_PATH,
6689 "reverting directories requires -R option");
6690 goto done;
6695 cpa.patch_script_file = patch_script_file;
6696 cpa.action = "revert";
6697 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6698 pflag ? choose_patch : NULL, &cpa, repo);
6699 done:
6700 if (patch_script_file && fclose(patch_script_file) == EOF &&
6701 error == NULL)
6702 error = got_error_from_errno2("fclose", patch_script_path);
6703 if (repo)
6704 got_repo_close(repo);
6705 if (worktree)
6706 got_worktree_close(worktree);
6707 free(path);
6708 free(cwd);
6709 return error;
6712 __dead static void
6713 usage_commit(void)
6715 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6716 getprogname());
6717 exit(1);
6720 struct collect_commit_logmsg_arg {
6721 const char *cmdline_log;
6722 const char *editor;
6723 const char *worktree_path;
6724 const char *branch_name;
6725 const char *repo_path;
6726 char *logmsg_path;
6730 static const struct got_error *
6731 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6732 void *arg)
6734 char *initial_content = NULL;
6735 struct got_pathlist_entry *pe;
6736 const struct got_error *err = NULL;
6737 char *template = NULL;
6738 struct collect_commit_logmsg_arg *a = arg;
6739 int initial_content_len;
6740 int fd = -1;
6741 size_t len;
6743 /* if a message was specified on the command line, just use it */
6744 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6745 len = strlen(a->cmdline_log) + 1;
6746 *logmsg = malloc(len + 1);
6747 if (*logmsg == NULL)
6748 return got_error_from_errno("malloc");
6749 strlcpy(*logmsg, a->cmdline_log, len);
6750 return NULL;
6753 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6754 return got_error_from_errno("asprintf");
6756 initial_content_len = asprintf(&initial_content,
6757 "\n# changes to be committed on branch %s:\n",
6758 a->branch_name);
6759 if (initial_content_len == -1)
6760 return got_error_from_errno("asprintf");
6762 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6763 if (err)
6764 goto done;
6766 if (write(fd, initial_content, initial_content_len) == -1) {
6767 err = got_error_from_errno2("write", a->logmsg_path);
6768 goto done;
6771 TAILQ_FOREACH(pe, commitable_paths, entry) {
6772 struct got_commitable *ct = pe->data;
6773 dprintf(fd, "# %c %s\n",
6774 got_commitable_get_status(ct),
6775 got_commitable_get_path(ct));
6778 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6779 initial_content_len);
6780 done:
6781 free(initial_content);
6782 free(template);
6784 if (fd != -1 && close(fd) == -1 && err == NULL)
6785 err = got_error_from_errno2("close", a->logmsg_path);
6787 /* Editor is done; we can now apply unveil(2) */
6788 if (err == NULL)
6789 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6790 if (err) {
6791 free(*logmsg);
6792 *logmsg = NULL;
6794 return err;
6797 static const struct got_error *
6798 cmd_commit(int argc, char *argv[])
6800 const struct got_error *error = NULL;
6801 struct got_worktree *worktree = NULL;
6802 struct got_repository *repo = NULL;
6803 char *cwd = NULL, *id_str = NULL;
6804 struct got_object_id *id = NULL;
6805 const char *logmsg = NULL;
6806 struct collect_commit_logmsg_arg cl_arg;
6807 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6808 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6809 int allow_bad_symlinks = 0;
6810 struct got_pathlist_head paths;
6812 TAILQ_INIT(&paths);
6813 cl_arg.logmsg_path = NULL;
6815 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6816 switch (ch) {
6817 case 'm':
6818 logmsg = optarg;
6819 break;
6820 case 'S':
6821 allow_bad_symlinks = 1;
6822 break;
6823 default:
6824 usage_commit();
6825 /* NOTREACHED */
6829 argc -= optind;
6830 argv += optind;
6832 #ifndef PROFILE
6833 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6834 "unveil", NULL) == -1)
6835 err(1, "pledge");
6836 #endif
6837 cwd = getcwd(NULL, 0);
6838 if (cwd == NULL) {
6839 error = got_error_from_errno("getcwd");
6840 goto done;
6842 error = got_worktree_open(&worktree, cwd);
6843 if (error) {
6844 if (error->code == GOT_ERR_NOT_WORKTREE)
6845 error = wrap_not_worktree_error(error, "commit", cwd);
6846 goto done;
6849 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6850 if (error)
6851 goto done;
6852 if (rebase_in_progress) {
6853 error = got_error(GOT_ERR_REBASING);
6854 goto done;
6857 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6858 worktree);
6859 if (error)
6860 goto done;
6862 error = get_gitconfig_path(&gitconfig_path);
6863 if (error)
6864 goto done;
6865 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6866 gitconfig_path);
6867 if (error != NULL)
6868 goto done;
6870 error = get_author(&author, repo, worktree);
6871 if (error)
6872 return error;
6875 * unveil(2) traverses exec(2); if an editor is used we have
6876 * to apply unveil after the log message has been written.
6878 if (logmsg == NULL || strlen(logmsg) == 0)
6879 error = get_editor(&editor);
6880 else
6881 error = apply_unveil(got_repo_get_path(repo), 0,
6882 got_worktree_get_root_path(worktree));
6883 if (error)
6884 goto done;
6886 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6887 if (error)
6888 goto done;
6890 cl_arg.editor = editor;
6891 cl_arg.cmdline_log = logmsg;
6892 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6893 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6894 if (!histedit_in_progress) {
6895 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6896 error = got_error(GOT_ERR_COMMIT_BRANCH);
6897 goto done;
6899 cl_arg.branch_name += 11;
6901 cl_arg.repo_path = got_repo_get_path(repo);
6902 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6903 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6904 print_status, NULL, repo);
6905 if (error) {
6906 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6907 cl_arg.logmsg_path != NULL)
6908 preserve_logmsg = 1;
6909 goto done;
6912 error = got_object_id_str(&id_str, id);
6913 if (error)
6914 goto done;
6915 printf("Created commit %s\n", id_str);
6916 done:
6917 if (preserve_logmsg) {
6918 fprintf(stderr, "%s: log message preserved in %s\n",
6919 getprogname(), cl_arg.logmsg_path);
6920 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6921 error == NULL)
6922 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6923 free(cl_arg.logmsg_path);
6924 if (repo)
6925 got_repo_close(repo);
6926 if (worktree)
6927 got_worktree_close(worktree);
6928 free(cwd);
6929 free(id_str);
6930 free(gitconfig_path);
6931 free(editor);
6932 free(author);
6933 return error;
6936 __dead static void
6937 usage_cherrypick(void)
6939 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6940 exit(1);
6943 static const struct got_error *
6944 cmd_cherrypick(int argc, char *argv[])
6946 const struct got_error *error = NULL;
6947 struct got_worktree *worktree = NULL;
6948 struct got_repository *repo = NULL;
6949 char *cwd = NULL, *commit_id_str = NULL;
6950 struct got_object_id *commit_id = NULL;
6951 struct got_commit_object *commit = NULL;
6952 struct got_object_qid *pid;
6953 struct got_reference *head_ref = NULL;
6954 int ch;
6955 struct got_update_progress_arg upa;
6957 while ((ch = getopt(argc, argv, "")) != -1) {
6958 switch (ch) {
6959 default:
6960 usage_cherrypick();
6961 /* NOTREACHED */
6965 argc -= optind;
6966 argv += optind;
6968 #ifndef PROFILE
6969 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6970 "unveil", NULL) == -1)
6971 err(1, "pledge");
6972 #endif
6973 if (argc != 1)
6974 usage_cherrypick();
6976 cwd = getcwd(NULL, 0);
6977 if (cwd == NULL) {
6978 error = got_error_from_errno("getcwd");
6979 goto done;
6981 error = got_worktree_open(&worktree, cwd);
6982 if (error) {
6983 if (error->code == GOT_ERR_NOT_WORKTREE)
6984 error = wrap_not_worktree_error(error, "cherrypick",
6985 cwd);
6986 goto done;
6989 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6990 NULL);
6991 if (error != NULL)
6992 goto done;
6994 error = apply_unveil(got_repo_get_path(repo), 0,
6995 got_worktree_get_root_path(worktree));
6996 if (error)
6997 goto done;
6999 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7000 GOT_OBJ_TYPE_COMMIT, repo);
7001 if (error != NULL) {
7002 struct got_reference *ref;
7003 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7004 goto done;
7005 error = got_ref_open(&ref, repo, argv[0], 0);
7006 if (error != NULL)
7007 goto done;
7008 error = got_ref_resolve(&commit_id, repo, ref);
7009 got_ref_close(ref);
7010 if (error != NULL)
7011 goto done;
7013 error = got_object_id_str(&commit_id_str, commit_id);
7014 if (error)
7015 goto done;
7017 error = got_ref_open(&head_ref, repo,
7018 got_worktree_get_head_ref_name(worktree), 0);
7019 if (error != NULL)
7020 goto done;
7022 error = check_same_branch(commit_id, head_ref, NULL, repo);
7023 if (error) {
7024 if (error->code != GOT_ERR_ANCESTRY)
7025 goto done;
7026 error = NULL;
7027 } else {
7028 error = got_error(GOT_ERR_SAME_BRANCH);
7029 goto done;
7032 error = got_object_open_as_commit(&commit, repo, commit_id);
7033 if (error)
7034 goto done;
7035 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7036 memset(&upa, 0, sizeof(upa));
7037 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7038 commit_id, repo, update_progress, &upa, check_cancelled,
7039 NULL);
7040 if (error != NULL)
7041 goto done;
7043 if (upa.did_something)
7044 printf("Merged commit %s\n", commit_id_str);
7045 print_update_progress_stats(&upa);
7046 done:
7047 if (commit)
7048 got_object_commit_close(commit);
7049 free(commit_id_str);
7050 if (head_ref)
7051 got_ref_close(head_ref);
7052 if (worktree)
7053 got_worktree_close(worktree);
7054 if (repo)
7055 got_repo_close(repo);
7056 return error;
7059 __dead static void
7060 usage_backout(void)
7062 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7063 exit(1);
7066 static const struct got_error *
7067 cmd_backout(int argc, char *argv[])
7069 const struct got_error *error = NULL;
7070 struct got_worktree *worktree = NULL;
7071 struct got_repository *repo = NULL;
7072 char *cwd = NULL, *commit_id_str = NULL;
7073 struct got_object_id *commit_id = NULL;
7074 struct got_commit_object *commit = NULL;
7075 struct got_object_qid *pid;
7076 struct got_reference *head_ref = NULL;
7077 int ch;
7078 struct got_update_progress_arg upa;
7080 while ((ch = getopt(argc, argv, "")) != -1) {
7081 switch (ch) {
7082 default:
7083 usage_backout();
7084 /* NOTREACHED */
7088 argc -= optind;
7089 argv += optind;
7091 #ifndef PROFILE
7092 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7093 "unveil", NULL) == -1)
7094 err(1, "pledge");
7095 #endif
7096 if (argc != 1)
7097 usage_backout();
7099 cwd = getcwd(NULL, 0);
7100 if (cwd == NULL) {
7101 error = got_error_from_errno("getcwd");
7102 goto done;
7104 error = got_worktree_open(&worktree, cwd);
7105 if (error) {
7106 if (error->code == GOT_ERR_NOT_WORKTREE)
7107 error = wrap_not_worktree_error(error, "backout", cwd);
7108 goto done;
7111 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7112 NULL);
7113 if (error != NULL)
7114 goto done;
7116 error = apply_unveil(got_repo_get_path(repo), 0,
7117 got_worktree_get_root_path(worktree));
7118 if (error)
7119 goto done;
7121 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7122 GOT_OBJ_TYPE_COMMIT, repo);
7123 if (error != NULL) {
7124 struct got_reference *ref;
7125 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7126 goto done;
7127 error = got_ref_open(&ref, repo, argv[0], 0);
7128 if (error != NULL)
7129 goto done;
7130 error = got_ref_resolve(&commit_id, repo, ref);
7131 got_ref_close(ref);
7132 if (error != NULL)
7133 goto done;
7135 error = got_object_id_str(&commit_id_str, commit_id);
7136 if (error)
7137 goto done;
7139 error = got_ref_open(&head_ref, repo,
7140 got_worktree_get_head_ref_name(worktree), 0);
7141 if (error != NULL)
7142 goto done;
7144 error = check_same_branch(commit_id, head_ref, NULL, repo);
7145 if (error)
7146 goto done;
7148 error = got_object_open_as_commit(&commit, repo, commit_id);
7149 if (error)
7150 goto done;
7151 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7152 if (pid == NULL) {
7153 error = got_error(GOT_ERR_ROOT_COMMIT);
7154 goto done;
7157 memset(&upa, 0, sizeof(upa));
7158 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7159 update_progress, &upa, check_cancelled, NULL);
7160 if (error != NULL)
7161 goto done;
7163 if (upa.did_something)
7164 printf("Backed out commit %s\n", commit_id_str);
7165 print_update_progress_stats(&upa);
7166 done:
7167 if (commit)
7168 got_object_commit_close(commit);
7169 free(commit_id_str);
7170 if (head_ref)
7171 got_ref_close(head_ref);
7172 if (worktree)
7173 got_worktree_close(worktree);
7174 if (repo)
7175 got_repo_close(repo);
7176 return error;
7179 __dead static void
7180 usage_rebase(void)
7182 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7183 getprogname());
7184 exit(1);
7187 void
7188 trim_logmsg(char *logmsg, int limit)
7190 char *nl;
7191 size_t len;
7193 len = strlen(logmsg);
7194 if (len > limit)
7195 len = limit;
7196 logmsg[len] = '\0';
7197 nl = strchr(logmsg, '\n');
7198 if (nl)
7199 *nl = '\0';
7202 static const struct got_error *
7203 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7205 const struct got_error *err;
7206 char *logmsg0 = NULL;
7207 const char *s;
7209 err = got_object_commit_get_logmsg(&logmsg0, commit);
7210 if (err)
7211 return err;
7213 s = logmsg0;
7214 while (isspace((unsigned char)s[0]))
7215 s++;
7217 *logmsg = strdup(s);
7218 if (*logmsg == NULL) {
7219 err = got_error_from_errno("strdup");
7220 goto done;
7223 trim_logmsg(*logmsg, limit);
7224 done:
7225 free(logmsg0);
7226 return err;
7229 static const struct got_error *
7230 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7232 const struct got_error *err;
7233 struct got_commit_object *commit = NULL;
7234 char *id_str = NULL, *logmsg = NULL;
7236 err = got_object_open_as_commit(&commit, repo, id);
7237 if (err)
7238 return err;
7240 err = got_object_id_str(&id_str, id);
7241 if (err)
7242 goto done;
7244 id_str[12] = '\0';
7246 err = get_short_logmsg(&logmsg, 42, commit);
7247 if (err)
7248 goto done;
7250 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7251 done:
7252 free(id_str);
7253 got_object_commit_close(commit);
7254 free(logmsg);
7255 return err;
7258 static const struct got_error *
7259 show_rebase_progress(struct got_commit_object *commit,
7260 struct got_object_id *old_id, struct got_object_id *new_id)
7262 const struct got_error *err;
7263 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7265 err = got_object_id_str(&old_id_str, old_id);
7266 if (err)
7267 goto done;
7269 if (new_id) {
7270 err = got_object_id_str(&new_id_str, new_id);
7271 if (err)
7272 goto done;
7275 old_id_str[12] = '\0';
7276 if (new_id_str)
7277 new_id_str[12] = '\0';
7279 err = get_short_logmsg(&logmsg, 42, commit);
7280 if (err)
7281 goto done;
7283 printf("%s -> %s: %s\n", old_id_str,
7284 new_id_str ? new_id_str : "no-op change", logmsg);
7285 done:
7286 free(old_id_str);
7287 free(new_id_str);
7288 free(logmsg);
7289 return err;
7292 static const struct got_error *
7293 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7294 struct got_reference *branch, struct got_reference *new_base_branch,
7295 struct got_reference *tmp_branch, struct got_repository *repo)
7297 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7298 return got_worktree_rebase_complete(worktree, fileindex,
7299 new_base_branch, tmp_branch, branch, repo);
7302 static const struct got_error *
7303 rebase_commit(struct got_pathlist_head *merged_paths,
7304 struct got_worktree *worktree, struct got_fileindex *fileindex,
7305 struct got_reference *tmp_branch,
7306 struct got_object_id *commit_id, struct got_repository *repo)
7308 const struct got_error *error;
7309 struct got_commit_object *commit;
7310 struct got_object_id *new_commit_id;
7312 error = got_object_open_as_commit(&commit, repo, commit_id);
7313 if (error)
7314 return error;
7316 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7317 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7318 if (error) {
7319 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7320 goto done;
7321 error = show_rebase_progress(commit, commit_id, NULL);
7322 } else {
7323 error = show_rebase_progress(commit, commit_id, new_commit_id);
7324 free(new_commit_id);
7326 done:
7327 got_object_commit_close(commit);
7328 return error;
7331 struct check_path_prefix_arg {
7332 const char *path_prefix;
7333 size_t len;
7334 int errcode;
7337 static const struct got_error *
7338 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7339 struct got_blob_object *blob2, struct got_object_id *id1,
7340 struct got_object_id *id2, const char *path1, const char *path2,
7341 mode_t mode1, mode_t mode2, struct got_repository *repo)
7343 struct check_path_prefix_arg *a = arg;
7345 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7346 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7347 return got_error(a->errcode);
7349 return NULL;
7352 static const struct got_error *
7353 check_path_prefix(struct got_object_id *parent_id,
7354 struct got_object_id *commit_id, const char *path_prefix,
7355 int errcode, struct got_repository *repo)
7357 const struct got_error *err;
7358 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7359 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7360 struct check_path_prefix_arg cpp_arg;
7362 if (got_path_is_root_dir(path_prefix))
7363 return NULL;
7365 err = got_object_open_as_commit(&commit, repo, commit_id);
7366 if (err)
7367 goto done;
7369 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7370 if (err)
7371 goto done;
7373 err = got_object_open_as_tree(&tree1, repo,
7374 got_object_commit_get_tree_id(parent_commit));
7375 if (err)
7376 goto done;
7378 err = got_object_open_as_tree(&tree2, repo,
7379 got_object_commit_get_tree_id(commit));
7380 if (err)
7381 goto done;
7383 cpp_arg.path_prefix = path_prefix;
7384 while (cpp_arg.path_prefix[0] == '/')
7385 cpp_arg.path_prefix++;
7386 cpp_arg.len = strlen(cpp_arg.path_prefix);
7387 cpp_arg.errcode = errcode;
7388 err = got_diff_tree(tree1, tree2, "", "", repo,
7389 check_path_prefix_in_diff, &cpp_arg, 0);
7390 done:
7391 if (tree1)
7392 got_object_tree_close(tree1);
7393 if (tree2)
7394 got_object_tree_close(tree2);
7395 if (commit)
7396 got_object_commit_close(commit);
7397 if (parent_commit)
7398 got_object_commit_close(parent_commit);
7399 return err;
7402 static const struct got_error *
7403 collect_commits(struct got_object_id_queue *commits,
7404 struct got_object_id *initial_commit_id,
7405 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7406 const char *path_prefix, int path_prefix_errcode,
7407 struct got_repository *repo)
7409 const struct got_error *err = NULL;
7410 struct got_commit_graph *graph = NULL;
7411 struct got_object_id *parent_id = NULL;
7412 struct got_object_qid *qid;
7413 struct got_object_id *commit_id = initial_commit_id;
7415 err = got_commit_graph_open(&graph, "/", 1);
7416 if (err)
7417 return err;
7419 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7420 check_cancelled, NULL);
7421 if (err)
7422 goto done;
7423 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7424 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7425 check_cancelled, NULL);
7426 if (err) {
7427 if (err->code == GOT_ERR_ITER_COMPLETED) {
7428 err = got_error_msg(GOT_ERR_ANCESTRY,
7429 "ran out of commits to rebase before "
7430 "youngest common ancestor commit has "
7431 "been reached?!?");
7433 goto done;
7434 } else {
7435 err = check_path_prefix(parent_id, commit_id,
7436 path_prefix, path_prefix_errcode, repo);
7437 if (err)
7438 goto done;
7440 err = got_object_qid_alloc(&qid, commit_id);
7441 if (err)
7442 goto done;
7443 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7444 commit_id = parent_id;
7447 done:
7448 got_commit_graph_close(graph);
7449 return err;
7452 static const struct got_error *
7453 cmd_rebase(int argc, char *argv[])
7455 const struct got_error *error = NULL;
7456 struct got_worktree *worktree = NULL;
7457 struct got_repository *repo = NULL;
7458 struct got_fileindex *fileindex = NULL;
7459 char *cwd = NULL;
7460 struct got_reference *branch = NULL;
7461 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7462 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7463 struct got_object_id *resume_commit_id = NULL;
7464 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7465 struct got_commit_object *commit = NULL;
7466 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7467 int histedit_in_progress = 0;
7468 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7469 struct got_object_id_queue commits;
7470 struct got_pathlist_head merged_paths;
7471 const struct got_object_id_queue *parent_ids;
7472 struct got_object_qid *qid, *pid;
7474 SIMPLEQ_INIT(&commits);
7475 TAILQ_INIT(&merged_paths);
7477 while ((ch = getopt(argc, argv, "ac")) != -1) {
7478 switch (ch) {
7479 case 'a':
7480 abort_rebase = 1;
7481 break;
7482 case 'c':
7483 continue_rebase = 1;
7484 break;
7485 default:
7486 usage_rebase();
7487 /* NOTREACHED */
7491 argc -= optind;
7492 argv += optind;
7494 #ifndef PROFILE
7495 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7496 "unveil", NULL) == -1)
7497 err(1, "pledge");
7498 #endif
7499 if (abort_rebase && continue_rebase)
7500 usage_rebase();
7501 else if (abort_rebase || continue_rebase) {
7502 if (argc != 0)
7503 usage_rebase();
7504 } else if (argc != 1)
7505 usage_rebase();
7507 cwd = getcwd(NULL, 0);
7508 if (cwd == NULL) {
7509 error = got_error_from_errno("getcwd");
7510 goto done;
7512 error = got_worktree_open(&worktree, cwd);
7513 if (error) {
7514 if (error->code == GOT_ERR_NOT_WORKTREE)
7515 error = wrap_not_worktree_error(error, "rebase", cwd);
7516 goto done;
7519 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7520 NULL);
7521 if (error != NULL)
7522 goto done;
7524 error = apply_unveil(got_repo_get_path(repo), 0,
7525 got_worktree_get_root_path(worktree));
7526 if (error)
7527 goto done;
7529 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7530 worktree);
7531 if (error)
7532 goto done;
7533 if (histedit_in_progress) {
7534 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7535 goto done;
7538 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7539 if (error)
7540 goto done;
7542 if (abort_rebase) {
7543 struct got_update_progress_arg upa;
7544 if (!rebase_in_progress) {
7545 error = got_error(GOT_ERR_NOT_REBASING);
7546 goto done;
7548 error = got_worktree_rebase_continue(&resume_commit_id,
7549 &new_base_branch, &tmp_branch, &branch, &fileindex,
7550 worktree, repo);
7551 if (error)
7552 goto done;
7553 printf("Switching work tree to %s\n",
7554 got_ref_get_symref_target(new_base_branch));
7555 memset(&upa, 0, sizeof(upa));
7556 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7557 new_base_branch, update_progress, &upa);
7558 if (error)
7559 goto done;
7560 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7561 print_update_progress_stats(&upa);
7562 goto done; /* nothing else to do */
7565 if (continue_rebase) {
7566 if (!rebase_in_progress) {
7567 error = got_error(GOT_ERR_NOT_REBASING);
7568 goto done;
7570 error = got_worktree_rebase_continue(&resume_commit_id,
7571 &new_base_branch, &tmp_branch, &branch, &fileindex,
7572 worktree, repo);
7573 if (error)
7574 goto done;
7576 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7577 resume_commit_id, repo);
7578 if (error)
7579 goto done;
7581 yca_id = got_object_id_dup(resume_commit_id);
7582 if (yca_id == NULL) {
7583 error = got_error_from_errno("got_object_id_dup");
7584 goto done;
7586 } else {
7587 error = got_ref_open(&branch, repo, argv[0], 0);
7588 if (error != NULL)
7589 goto done;
7592 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7593 if (error)
7594 goto done;
7596 if (!continue_rebase) {
7597 struct got_object_id *base_commit_id;
7599 base_commit_id = got_worktree_get_base_commit_id(worktree);
7600 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7601 base_commit_id, branch_head_commit_id, repo,
7602 check_cancelled, NULL);
7603 if (error)
7604 goto done;
7605 if (yca_id == NULL) {
7606 error = got_error_msg(GOT_ERR_ANCESTRY,
7607 "specified branch shares no common ancestry "
7608 "with work tree's branch");
7609 goto done;
7612 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7613 if (error) {
7614 if (error->code != GOT_ERR_ANCESTRY)
7615 goto done;
7616 error = NULL;
7617 } else {
7618 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7619 "specified branch resolves to a commit which "
7620 "is already contained in work tree's branch");
7621 goto done;
7623 error = got_worktree_rebase_prepare(&new_base_branch,
7624 &tmp_branch, &fileindex, worktree, branch, repo);
7625 if (error)
7626 goto done;
7629 commit_id = branch_head_commit_id;
7630 error = got_object_open_as_commit(&commit, repo, commit_id);
7631 if (error)
7632 goto done;
7634 parent_ids = got_object_commit_get_parent_ids(commit);
7635 pid = SIMPLEQ_FIRST(parent_ids);
7636 if (pid == NULL) {
7637 if (!continue_rebase) {
7638 struct got_update_progress_arg upa;
7639 memset(&upa, 0, sizeof(upa));
7640 error = got_worktree_rebase_abort(worktree, fileindex,
7641 repo, new_base_branch, update_progress, &upa);
7642 if (error)
7643 goto done;
7644 printf("Rebase of %s aborted\n",
7645 got_ref_get_name(branch));
7646 print_update_progress_stats(&upa);
7649 error = got_error(GOT_ERR_EMPTY_REBASE);
7650 goto done;
7652 error = collect_commits(&commits, commit_id, pid->id,
7653 yca_id, got_worktree_get_path_prefix(worktree),
7654 GOT_ERR_REBASE_PATH, repo);
7655 got_object_commit_close(commit);
7656 commit = NULL;
7657 if (error)
7658 goto done;
7660 if (SIMPLEQ_EMPTY(&commits)) {
7661 if (continue_rebase) {
7662 error = rebase_complete(worktree, fileindex,
7663 branch, new_base_branch, tmp_branch, repo);
7664 goto done;
7665 } else {
7666 /* Fast-forward the reference of the branch. */
7667 struct got_object_id *new_head_commit_id;
7668 char *id_str;
7669 error = got_ref_resolve(&new_head_commit_id, repo,
7670 new_base_branch);
7671 if (error)
7672 goto done;
7673 error = got_object_id_str(&id_str, new_head_commit_id);
7674 printf("Forwarding %s to commit %s\n",
7675 got_ref_get_name(branch), id_str);
7676 free(id_str);
7677 error = got_ref_change_ref(branch,
7678 new_head_commit_id);
7679 if (error)
7680 goto done;
7684 pid = NULL;
7685 SIMPLEQ_FOREACH(qid, &commits, entry) {
7686 struct got_update_progress_arg upa;
7688 commit_id = qid->id;
7689 parent_id = pid ? pid->id : yca_id;
7690 pid = qid;
7692 memset(&upa, 0, sizeof(upa));
7693 error = got_worktree_rebase_merge_files(&merged_paths,
7694 worktree, fileindex, parent_id, commit_id, repo,
7695 update_progress, &upa, check_cancelled, NULL);
7696 if (error)
7697 goto done;
7699 print_update_progress_stats(&upa);
7700 if (upa.conflicts > 0)
7701 rebase_status = GOT_STATUS_CONFLICT;
7703 if (rebase_status == GOT_STATUS_CONFLICT) {
7704 error = show_rebase_merge_conflict(qid->id, repo);
7705 if (error)
7706 goto done;
7707 got_worktree_rebase_pathlist_free(&merged_paths);
7708 break;
7711 error = rebase_commit(&merged_paths, worktree, fileindex,
7712 tmp_branch, commit_id, repo);
7713 got_worktree_rebase_pathlist_free(&merged_paths);
7714 if (error)
7715 goto done;
7718 if (rebase_status == GOT_STATUS_CONFLICT) {
7719 error = got_worktree_rebase_postpone(worktree, fileindex);
7720 if (error)
7721 goto done;
7722 error = got_error_msg(GOT_ERR_CONFLICTS,
7723 "conflicts must be resolved before rebasing can continue");
7724 } else
7725 error = rebase_complete(worktree, fileindex, branch,
7726 new_base_branch, tmp_branch, repo);
7727 done:
7728 got_object_id_queue_free(&commits);
7729 free(branch_head_commit_id);
7730 free(resume_commit_id);
7731 free(yca_id);
7732 if (commit)
7733 got_object_commit_close(commit);
7734 if (branch)
7735 got_ref_close(branch);
7736 if (new_base_branch)
7737 got_ref_close(new_base_branch);
7738 if (tmp_branch)
7739 got_ref_close(tmp_branch);
7740 if (worktree)
7741 got_worktree_close(worktree);
7742 if (repo)
7743 got_repo_close(repo);
7744 return error;
7747 __dead static void
7748 usage_histedit(void)
7750 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
7751 getprogname());
7752 exit(1);
7755 #define GOT_HISTEDIT_PICK 'p'
7756 #define GOT_HISTEDIT_EDIT 'e'
7757 #define GOT_HISTEDIT_FOLD 'f'
7758 #define GOT_HISTEDIT_DROP 'd'
7759 #define GOT_HISTEDIT_MESG 'm'
7761 static struct got_histedit_cmd {
7762 unsigned char code;
7763 const char *name;
7764 const char *desc;
7765 } got_histedit_cmds[] = {
7766 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7767 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7768 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7769 "be used" },
7770 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7771 { GOT_HISTEDIT_MESG, "mesg",
7772 "single-line log message for commit above (open editor if empty)" },
7775 struct got_histedit_list_entry {
7776 TAILQ_ENTRY(got_histedit_list_entry) entry;
7777 struct got_object_id *commit_id;
7778 const struct got_histedit_cmd *cmd;
7779 char *logmsg;
7781 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7783 static const struct got_error *
7784 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7785 FILE *f, struct got_repository *repo)
7787 const struct got_error *err = NULL;
7788 char *logmsg = NULL, *id_str = NULL;
7789 struct got_commit_object *commit = NULL;
7790 int n;
7792 err = got_object_open_as_commit(&commit, repo, commit_id);
7793 if (err)
7794 goto done;
7796 err = get_short_logmsg(&logmsg, 34, commit);
7797 if (err)
7798 goto done;
7800 err = got_object_id_str(&id_str, commit_id);
7801 if (err)
7802 goto done;
7804 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7805 if (n < 0)
7806 err = got_ferror(f, GOT_ERR_IO);
7807 done:
7808 if (commit)
7809 got_object_commit_close(commit);
7810 free(id_str);
7811 free(logmsg);
7812 return err;
7815 static const struct got_error *
7816 histedit_write_commit_list(struct got_object_id_queue *commits,
7817 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
7819 const struct got_error *err = NULL;
7820 struct got_object_qid *qid;
7821 const char *histedit_cmd = NULL;
7823 if (SIMPLEQ_EMPTY(commits))
7824 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7826 SIMPLEQ_FOREACH(qid, commits, entry) {
7827 histedit_cmd = got_histedit_cmds[0].name;
7828 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
7829 histedit_cmd = "fold";
7830 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
7831 if (err)
7832 break;
7833 if (edit_logmsg_only) {
7834 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7835 if (n < 0) {
7836 err = got_ferror(f, GOT_ERR_IO);
7837 break;
7842 return err;
7845 static const struct got_error *
7846 write_cmd_list(FILE *f, const char *branch_name,
7847 struct got_object_id_queue *commits)
7849 const struct got_error *err = NULL;
7850 int n, i;
7851 char *id_str;
7852 struct got_object_qid *qid;
7854 qid = SIMPLEQ_FIRST(commits);
7855 err = got_object_id_str(&id_str, qid->id);
7856 if (err)
7857 return err;
7859 n = fprintf(f,
7860 "# Editing the history of branch '%s' starting at\n"
7861 "# commit %s\n"
7862 "# Commits will be processed in order from top to "
7863 "bottom of this file.\n", branch_name, id_str);
7864 if (n < 0) {
7865 err = got_ferror(f, GOT_ERR_IO);
7866 goto done;
7869 n = fprintf(f, "# Available histedit commands:\n");
7870 if (n < 0) {
7871 err = got_ferror(f, GOT_ERR_IO);
7872 goto done;
7875 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7876 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7877 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7878 cmd->desc);
7879 if (n < 0) {
7880 err = got_ferror(f, GOT_ERR_IO);
7881 break;
7884 done:
7885 free(id_str);
7886 return err;
7889 static const struct got_error *
7890 histedit_syntax_error(int lineno)
7892 static char msg[42];
7893 int ret;
7895 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7896 lineno);
7897 if (ret == -1 || ret >= sizeof(msg))
7898 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7900 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7903 static const struct got_error *
7904 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7905 char *logmsg, struct got_repository *repo)
7907 const struct got_error *err;
7908 struct got_commit_object *folded_commit = NULL;
7909 char *id_str, *folded_logmsg = NULL;
7911 err = got_object_id_str(&id_str, hle->commit_id);
7912 if (err)
7913 return err;
7915 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7916 if (err)
7917 goto done;
7919 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7920 if (err)
7921 goto done;
7922 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7923 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7924 folded_logmsg) == -1) {
7925 err = got_error_from_errno("asprintf");
7927 done:
7928 if (folded_commit)
7929 got_object_commit_close(folded_commit);
7930 free(id_str);
7931 free(folded_logmsg);
7932 return err;
7935 static struct got_histedit_list_entry *
7936 get_folded_commits(struct got_histedit_list_entry *hle)
7938 struct got_histedit_list_entry *prev, *folded = NULL;
7940 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7941 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7942 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7943 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7944 folded = prev;
7945 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7948 return folded;
7951 static const struct got_error *
7952 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7953 struct got_repository *repo)
7955 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7956 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7957 const struct got_error *err = NULL;
7958 struct got_commit_object *commit = NULL;
7959 int logmsg_len;
7960 int fd;
7961 struct got_histedit_list_entry *folded = NULL;
7963 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7964 if (err)
7965 return err;
7967 folded = get_folded_commits(hle);
7968 if (folded) {
7969 while (folded != hle) {
7970 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7971 folded = TAILQ_NEXT(folded, entry);
7972 continue;
7974 err = append_folded_commit_msg(&new_msg, folded,
7975 logmsg, repo);
7976 if (err)
7977 goto done;
7978 free(logmsg);
7979 logmsg = new_msg;
7980 folded = TAILQ_NEXT(folded, entry);
7984 err = got_object_id_str(&id_str, hle->commit_id);
7985 if (err)
7986 goto done;
7987 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7988 if (err)
7989 goto done;
7990 logmsg_len = asprintf(&new_msg,
7991 "%s\n# original log message of commit %s: %s",
7992 logmsg ? logmsg : "", id_str, orig_logmsg);
7993 if (logmsg_len == -1) {
7994 err = got_error_from_errno("asprintf");
7995 goto done;
7997 free(logmsg);
7998 logmsg = new_msg;
8000 err = got_object_id_str(&id_str, hle->commit_id);
8001 if (err)
8002 goto done;
8004 err = got_opentemp_named_fd(&logmsg_path, &fd,
8005 GOT_TMPDIR_STR "/got-logmsg");
8006 if (err)
8007 goto done;
8009 write(fd, logmsg, logmsg_len);
8010 close(fd);
8012 err = get_editor(&editor);
8013 if (err)
8014 goto done;
8016 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8017 logmsg_len);
8018 if (err) {
8019 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8020 goto done;
8021 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8023 done:
8024 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8025 err = got_error_from_errno2("unlink", logmsg_path);
8026 free(logmsg_path);
8027 free(logmsg);
8028 free(orig_logmsg);
8029 free(editor);
8030 if (commit)
8031 got_object_commit_close(commit);
8032 return err;
8035 static const struct got_error *
8036 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8037 FILE *f, struct got_repository *repo)
8039 const struct got_error *err = NULL;
8040 char *line = NULL, *p, *end;
8041 size_t size;
8042 ssize_t len;
8043 int lineno = 0, i;
8044 const struct got_histedit_cmd *cmd;
8045 struct got_object_id *commit_id = NULL;
8046 struct got_histedit_list_entry *hle = NULL;
8048 for (;;) {
8049 len = getline(&line, &size, f);
8050 if (len == -1) {
8051 const struct got_error *getline_err;
8052 if (feof(f))
8053 break;
8054 getline_err = got_error_from_errno("getline");
8055 err = got_ferror(f, getline_err->code);
8056 break;
8058 lineno++;
8059 p = line;
8060 while (isspace((unsigned char)p[0]))
8061 p++;
8062 if (p[0] == '#' || p[0] == '\0') {
8063 free(line);
8064 line = NULL;
8065 continue;
8067 cmd = NULL;
8068 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8069 cmd = &got_histedit_cmds[i];
8070 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8071 isspace((unsigned char)p[strlen(cmd->name)])) {
8072 p += strlen(cmd->name);
8073 break;
8075 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8076 p++;
8077 break;
8080 if (i == nitems(got_histedit_cmds)) {
8081 err = histedit_syntax_error(lineno);
8082 break;
8084 while (isspace((unsigned char)p[0]))
8085 p++;
8086 if (cmd->code == GOT_HISTEDIT_MESG) {
8087 if (hle == NULL || hle->logmsg != NULL) {
8088 err = got_error(GOT_ERR_HISTEDIT_CMD);
8089 break;
8091 if (p[0] == '\0') {
8092 err = histedit_edit_logmsg(hle, repo);
8093 if (err)
8094 break;
8095 } else {
8096 hle->logmsg = strdup(p);
8097 if (hle->logmsg == NULL) {
8098 err = got_error_from_errno("strdup");
8099 break;
8102 free(line);
8103 line = NULL;
8104 continue;
8105 } else {
8106 end = p;
8107 while (end[0] && !isspace((unsigned char)end[0]))
8108 end++;
8109 *end = '\0';
8111 err = got_object_resolve_id_str(&commit_id, repo, p);
8112 if (err) {
8113 /* override error code */
8114 err = histedit_syntax_error(lineno);
8115 break;
8118 hle = malloc(sizeof(*hle));
8119 if (hle == NULL) {
8120 err = got_error_from_errno("malloc");
8121 break;
8123 hle->cmd = cmd;
8124 hle->commit_id = commit_id;
8125 hle->logmsg = NULL;
8126 commit_id = NULL;
8127 free(line);
8128 line = NULL;
8129 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8132 free(line);
8133 free(commit_id);
8134 return err;
8137 static const struct got_error *
8138 histedit_check_script(struct got_histedit_list *histedit_cmds,
8139 struct got_object_id_queue *commits, struct got_repository *repo)
8141 const struct got_error *err = NULL;
8142 struct got_object_qid *qid;
8143 struct got_histedit_list_entry *hle;
8144 static char msg[92];
8145 char *id_str;
8147 if (TAILQ_EMPTY(histedit_cmds))
8148 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8149 "histedit script contains no commands");
8150 if (SIMPLEQ_EMPTY(commits))
8151 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8153 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8154 struct got_histedit_list_entry *hle2;
8155 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8156 if (hle == hle2)
8157 continue;
8158 if (got_object_id_cmp(hle->commit_id,
8159 hle2->commit_id) != 0)
8160 continue;
8161 err = got_object_id_str(&id_str, hle->commit_id);
8162 if (err)
8163 return err;
8164 snprintf(msg, sizeof(msg), "commit %s is listed "
8165 "more than once in histedit script", id_str);
8166 free(id_str);
8167 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8171 SIMPLEQ_FOREACH(qid, commits, entry) {
8172 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8173 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8174 break;
8176 if (hle == NULL) {
8177 err = got_object_id_str(&id_str, qid->id);
8178 if (err)
8179 return err;
8180 snprintf(msg, sizeof(msg),
8181 "commit %s missing from histedit script", id_str);
8182 free(id_str);
8183 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8187 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8188 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8189 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8190 "last commit in histedit script cannot be folded");
8192 return NULL;
8195 static const struct got_error *
8196 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8197 const char *path, struct got_object_id_queue *commits,
8198 struct got_repository *repo)
8200 const struct got_error *err = NULL;
8201 char *editor;
8202 FILE *f = NULL;
8204 err = get_editor(&editor);
8205 if (err)
8206 return err;
8208 if (spawn_editor(editor, path) == -1) {
8209 err = got_error_from_errno("failed spawning editor");
8210 goto done;
8213 f = fopen(path, "r");
8214 if (f == NULL) {
8215 err = got_error_from_errno("fopen");
8216 goto done;
8218 err = histedit_parse_list(histedit_cmds, f, repo);
8219 if (err)
8220 goto done;
8222 err = histedit_check_script(histedit_cmds, commits, repo);
8223 done:
8224 if (f && fclose(f) != 0 && err == NULL)
8225 err = got_error_from_errno("fclose");
8226 free(editor);
8227 return err;
8230 static const struct got_error *
8231 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8232 struct got_object_id_queue *, const char *, const char *,
8233 struct got_repository *);
8235 static const struct got_error *
8236 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8237 struct got_object_id_queue *commits, const char *branch_name,
8238 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8240 const struct got_error *err;
8241 FILE *f = NULL;
8242 char *path = NULL;
8244 err = got_opentemp_named(&path, &f, "got-histedit");
8245 if (err)
8246 return err;
8248 err = write_cmd_list(f, branch_name, commits);
8249 if (err)
8250 goto done;
8252 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8253 fold_only, repo);
8254 if (err)
8255 goto done;
8257 if (edit_logmsg_only || fold_only) {
8258 rewind(f);
8259 err = histedit_parse_list(histedit_cmds, f, repo);
8260 } else {
8261 if (fclose(f) != 0) {
8262 err = got_error_from_errno("fclose");
8263 goto done;
8265 f = NULL;
8266 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8267 if (err) {
8268 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8269 err->code != GOT_ERR_HISTEDIT_CMD)
8270 goto done;
8271 err = histedit_edit_list_retry(histedit_cmds, err,
8272 commits, path, branch_name, repo);
8275 done:
8276 if (f && fclose(f) != 0 && err == NULL)
8277 err = got_error_from_errno("fclose");
8278 if (path && unlink(path) != 0 && err == NULL)
8279 err = got_error_from_errno2("unlink", path);
8280 free(path);
8281 return err;
8284 static const struct got_error *
8285 histedit_save_list(struct got_histedit_list *histedit_cmds,
8286 struct got_worktree *worktree, struct got_repository *repo)
8288 const struct got_error *err = NULL;
8289 char *path = NULL;
8290 FILE *f = NULL;
8291 struct got_histedit_list_entry *hle;
8292 struct got_commit_object *commit = NULL;
8294 err = got_worktree_get_histedit_script_path(&path, worktree);
8295 if (err)
8296 return err;
8298 f = fopen(path, "w");
8299 if (f == NULL) {
8300 err = got_error_from_errno2("fopen", path);
8301 goto done;
8303 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8304 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8305 repo);
8306 if (err)
8307 break;
8309 if (hle->logmsg) {
8310 int n = fprintf(f, "%c %s\n",
8311 GOT_HISTEDIT_MESG, hle->logmsg);
8312 if (n < 0) {
8313 err = got_ferror(f, GOT_ERR_IO);
8314 break;
8318 done:
8319 if (f && fclose(f) != 0 && err == NULL)
8320 err = got_error_from_errno("fclose");
8321 free(path);
8322 if (commit)
8323 got_object_commit_close(commit);
8324 return err;
8327 void
8328 histedit_free_list(struct got_histedit_list *histedit_cmds)
8330 struct got_histedit_list_entry *hle;
8332 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8333 TAILQ_REMOVE(histedit_cmds, hle, entry);
8334 free(hle);
8338 static const struct got_error *
8339 histedit_load_list(struct got_histedit_list *histedit_cmds,
8340 const char *path, struct got_repository *repo)
8342 const struct got_error *err = NULL;
8343 FILE *f = NULL;
8345 f = fopen(path, "r");
8346 if (f == NULL) {
8347 err = got_error_from_errno2("fopen", path);
8348 goto done;
8351 err = histedit_parse_list(histedit_cmds, f, repo);
8352 done:
8353 if (f && fclose(f) != 0 && err == NULL)
8354 err = got_error_from_errno("fclose");
8355 return err;
8358 static const struct got_error *
8359 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8360 const struct got_error *edit_err, struct got_object_id_queue *commits,
8361 const char *path, const char *branch_name, struct got_repository *repo)
8363 const struct got_error *err = NULL, *prev_err = edit_err;
8364 int resp = ' ';
8366 while (resp != 'c' && resp != 'r' && resp != 'a') {
8367 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8368 "or (a)bort: ", getprogname(), prev_err->msg);
8369 resp = getchar();
8370 if (resp == '\n')
8371 resp = getchar();
8372 if (resp == 'c') {
8373 histedit_free_list(histedit_cmds);
8374 err = histedit_run_editor(histedit_cmds, path, commits,
8375 repo);
8376 if (err) {
8377 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8378 err->code != GOT_ERR_HISTEDIT_CMD)
8379 break;
8380 prev_err = err;
8381 resp = ' ';
8382 continue;
8384 break;
8385 } else if (resp == 'r') {
8386 histedit_free_list(histedit_cmds);
8387 err = histedit_edit_script(histedit_cmds,
8388 commits, branch_name, 0, 0, repo);
8389 if (err) {
8390 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8391 err->code != GOT_ERR_HISTEDIT_CMD)
8392 break;
8393 prev_err = err;
8394 resp = ' ';
8395 continue;
8397 break;
8398 } else if (resp == 'a') {
8399 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8400 break;
8401 } else
8402 printf("invalid response '%c'\n", resp);
8405 return err;
8408 static const struct got_error *
8409 histedit_complete(struct got_worktree *worktree,
8410 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8411 struct got_reference *branch, struct got_repository *repo)
8413 printf("Switching work tree to %s\n",
8414 got_ref_get_symref_target(branch));
8415 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8416 branch, repo);
8419 static const struct got_error *
8420 show_histedit_progress(struct got_commit_object *commit,
8421 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8423 const struct got_error *err;
8424 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8426 err = got_object_id_str(&old_id_str, hle->commit_id);
8427 if (err)
8428 goto done;
8430 if (new_id) {
8431 err = got_object_id_str(&new_id_str, new_id);
8432 if (err)
8433 goto done;
8436 old_id_str[12] = '\0';
8437 if (new_id_str)
8438 new_id_str[12] = '\0';
8440 if (hle->logmsg) {
8441 logmsg = strdup(hle->logmsg);
8442 if (logmsg == NULL) {
8443 err = got_error_from_errno("strdup");
8444 goto done;
8446 trim_logmsg(logmsg, 42);
8447 } else {
8448 err = get_short_logmsg(&logmsg, 42, commit);
8449 if (err)
8450 goto done;
8453 switch (hle->cmd->code) {
8454 case GOT_HISTEDIT_PICK:
8455 case GOT_HISTEDIT_EDIT:
8456 printf("%s -> %s: %s\n", old_id_str,
8457 new_id_str ? new_id_str : "no-op change", logmsg);
8458 break;
8459 case GOT_HISTEDIT_DROP:
8460 case GOT_HISTEDIT_FOLD:
8461 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8462 logmsg);
8463 break;
8464 default:
8465 break;
8467 done:
8468 free(old_id_str);
8469 free(new_id_str);
8470 return err;
8473 static const struct got_error *
8474 histedit_commit(struct got_pathlist_head *merged_paths,
8475 struct got_worktree *worktree, struct got_fileindex *fileindex,
8476 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8477 struct got_repository *repo)
8479 const struct got_error *err;
8480 struct got_commit_object *commit;
8481 struct got_object_id *new_commit_id;
8483 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8484 && hle->logmsg == NULL) {
8485 err = histedit_edit_logmsg(hle, repo);
8486 if (err)
8487 return err;
8490 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8491 if (err)
8492 return err;
8494 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8495 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8496 hle->logmsg, repo);
8497 if (err) {
8498 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8499 goto done;
8500 err = show_histedit_progress(commit, hle, NULL);
8501 } else {
8502 err = show_histedit_progress(commit, hle, new_commit_id);
8503 free(new_commit_id);
8505 done:
8506 got_object_commit_close(commit);
8507 return err;
8510 static const struct got_error *
8511 histedit_skip_commit(struct got_histedit_list_entry *hle,
8512 struct got_worktree *worktree, struct got_repository *repo)
8514 const struct got_error *error;
8515 struct got_commit_object *commit;
8517 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8518 repo);
8519 if (error)
8520 return error;
8522 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8523 if (error)
8524 return error;
8526 error = show_histedit_progress(commit, hle, NULL);
8527 got_object_commit_close(commit);
8528 return error;
8531 static const struct got_error *
8532 check_local_changes(void *arg, unsigned char status,
8533 unsigned char staged_status, const char *path,
8534 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8535 struct got_object_id *commit_id, int dirfd, const char *de_name)
8537 int *have_local_changes = arg;
8539 switch (status) {
8540 case GOT_STATUS_ADD:
8541 case GOT_STATUS_DELETE:
8542 case GOT_STATUS_MODIFY:
8543 case GOT_STATUS_CONFLICT:
8544 *have_local_changes = 1;
8545 return got_error(GOT_ERR_CANCELLED);
8546 default:
8547 break;
8550 switch (staged_status) {
8551 case GOT_STATUS_ADD:
8552 case GOT_STATUS_DELETE:
8553 case GOT_STATUS_MODIFY:
8554 *have_local_changes = 1;
8555 return got_error(GOT_ERR_CANCELLED);
8556 default:
8557 break;
8560 return NULL;
8563 static const struct got_error *
8564 cmd_histedit(int argc, char *argv[])
8566 const struct got_error *error = NULL;
8567 struct got_worktree *worktree = NULL;
8568 struct got_fileindex *fileindex = NULL;
8569 struct got_repository *repo = NULL;
8570 char *cwd = NULL;
8571 struct got_reference *branch = NULL;
8572 struct got_reference *tmp_branch = NULL;
8573 struct got_object_id *resume_commit_id = NULL;
8574 struct got_object_id *base_commit_id = NULL;
8575 struct got_object_id *head_commit_id = NULL;
8576 struct got_commit_object *commit = NULL;
8577 int ch, rebase_in_progress = 0;
8578 struct got_update_progress_arg upa;
8579 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8580 int edit_logmsg_only = 0, fold_only = 0;
8581 const char *edit_script_path = NULL;
8582 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8583 struct got_object_id_queue commits;
8584 struct got_pathlist_head merged_paths;
8585 const struct got_object_id_queue *parent_ids;
8586 struct got_object_qid *pid;
8587 struct got_histedit_list histedit_cmds;
8588 struct got_histedit_list_entry *hle;
8590 SIMPLEQ_INIT(&commits);
8591 TAILQ_INIT(&histedit_cmds);
8592 TAILQ_INIT(&merged_paths);
8593 memset(&upa, 0, sizeof(upa));
8595 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8596 switch (ch) {
8597 case 'a':
8598 abort_edit = 1;
8599 break;
8600 case 'c':
8601 continue_edit = 1;
8602 break;
8603 case 'f':
8604 fold_only = 1;
8605 break;
8606 case 'F':
8607 edit_script_path = optarg;
8608 break;
8609 case 'm':
8610 edit_logmsg_only = 1;
8611 break;
8612 default:
8613 usage_histedit();
8614 /* NOTREACHED */
8618 argc -= optind;
8619 argv += optind;
8621 #ifndef PROFILE
8622 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8623 "unveil", NULL) == -1)
8624 err(1, "pledge");
8625 #endif
8626 if (abort_edit && continue_edit)
8627 errx(1, "histedit's -a and -c options are mutually exclusive");
8628 if (edit_script_path && edit_logmsg_only)
8629 errx(1, "histedit's -F and -m options are mutually exclusive");
8630 if (abort_edit && edit_logmsg_only)
8631 errx(1, "histedit's -a and -m options are mutually exclusive");
8632 if (continue_edit && edit_logmsg_only)
8633 errx(1, "histedit's -c and -m options are mutually exclusive");
8634 if (abort_edit && fold_only)
8635 errx(1, "histedit's -a and -f options are mutually exclusive");
8636 if (continue_edit && fold_only)
8637 errx(1, "histedit's -c and -f options are mutually exclusive");
8638 if (fold_only && edit_logmsg_only)
8639 errx(1, "histedit's -f and -m options are mutually exclusive");
8640 if (argc != 0)
8641 usage_histedit();
8644 * This command cannot apply unveil(2) in all cases because the
8645 * user may choose to run an editor to edit the histedit script
8646 * and to edit individual commit log messages.
8647 * unveil(2) traverses exec(2); if an editor is used we have to
8648 * apply unveil after edit script and log messages have been written.
8649 * XXX TODO: Make use of unveil(2) where possible.
8652 cwd = getcwd(NULL, 0);
8653 if (cwd == NULL) {
8654 error = got_error_from_errno("getcwd");
8655 goto done;
8657 error = got_worktree_open(&worktree, cwd);
8658 if (error) {
8659 if (error->code == GOT_ERR_NOT_WORKTREE)
8660 error = wrap_not_worktree_error(error, "histedit", cwd);
8661 goto done;
8664 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8665 NULL);
8666 if (error != NULL)
8667 goto done;
8669 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8670 if (error)
8671 goto done;
8672 if (rebase_in_progress) {
8673 error = got_error(GOT_ERR_REBASING);
8674 goto done;
8677 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8678 if (error)
8679 goto done;
8681 if (edit_in_progress && edit_logmsg_only) {
8682 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8683 "histedit operation is in progress in this "
8684 "work tree and must be continued or aborted "
8685 "before the -m option can be used");
8686 goto done;
8688 if (edit_in_progress && fold_only) {
8689 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8690 "histedit operation is in progress in this "
8691 "work tree and must be continued or aborted "
8692 "before the -f option can be used");
8693 goto done;
8696 if (edit_in_progress && abort_edit) {
8697 error = got_worktree_histedit_continue(&resume_commit_id,
8698 &tmp_branch, &branch, &base_commit_id, &fileindex,
8699 worktree, repo);
8700 if (error)
8701 goto done;
8702 printf("Switching work tree to %s\n",
8703 got_ref_get_symref_target(branch));
8704 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8705 branch, base_commit_id, update_progress, &upa);
8706 if (error)
8707 goto done;
8708 printf("Histedit of %s aborted\n",
8709 got_ref_get_symref_target(branch));
8710 print_update_progress_stats(&upa);
8711 goto done; /* nothing else to do */
8712 } else if (abort_edit) {
8713 error = got_error(GOT_ERR_NOT_HISTEDIT);
8714 goto done;
8717 if (continue_edit) {
8718 char *path;
8720 if (!edit_in_progress) {
8721 error = got_error(GOT_ERR_NOT_HISTEDIT);
8722 goto done;
8725 error = got_worktree_get_histedit_script_path(&path, worktree);
8726 if (error)
8727 goto done;
8729 error = histedit_load_list(&histedit_cmds, path, repo);
8730 free(path);
8731 if (error)
8732 goto done;
8734 error = got_worktree_histedit_continue(&resume_commit_id,
8735 &tmp_branch, &branch, &base_commit_id, &fileindex,
8736 worktree, repo);
8737 if (error)
8738 goto done;
8740 error = got_ref_resolve(&head_commit_id, repo, branch);
8741 if (error)
8742 goto done;
8744 error = got_object_open_as_commit(&commit, repo,
8745 head_commit_id);
8746 if (error)
8747 goto done;
8748 parent_ids = got_object_commit_get_parent_ids(commit);
8749 pid = SIMPLEQ_FIRST(parent_ids);
8750 if (pid == NULL) {
8751 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8752 goto done;
8754 error = collect_commits(&commits, head_commit_id, pid->id,
8755 base_commit_id, got_worktree_get_path_prefix(worktree),
8756 GOT_ERR_HISTEDIT_PATH, repo);
8757 got_object_commit_close(commit);
8758 commit = NULL;
8759 if (error)
8760 goto done;
8761 } else {
8762 if (edit_in_progress) {
8763 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8764 goto done;
8767 error = got_ref_open(&branch, repo,
8768 got_worktree_get_head_ref_name(worktree), 0);
8769 if (error != NULL)
8770 goto done;
8772 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8773 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8774 "will not edit commit history of a branch outside "
8775 "the \"refs/heads/\" reference namespace");
8776 goto done;
8779 error = got_ref_resolve(&head_commit_id, repo, branch);
8780 got_ref_close(branch);
8781 branch = NULL;
8782 if (error)
8783 goto done;
8785 error = got_object_open_as_commit(&commit, repo,
8786 head_commit_id);
8787 if (error)
8788 goto done;
8789 parent_ids = got_object_commit_get_parent_ids(commit);
8790 pid = SIMPLEQ_FIRST(parent_ids);
8791 if (pid == NULL) {
8792 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8793 goto done;
8795 error = collect_commits(&commits, head_commit_id, pid->id,
8796 got_worktree_get_base_commit_id(worktree),
8797 got_worktree_get_path_prefix(worktree),
8798 GOT_ERR_HISTEDIT_PATH, repo);
8799 got_object_commit_close(commit);
8800 commit = NULL;
8801 if (error)
8802 goto done;
8804 if (SIMPLEQ_EMPTY(&commits)) {
8805 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8806 goto done;
8809 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8810 &base_commit_id, &fileindex, worktree, repo);
8811 if (error)
8812 goto done;
8814 if (edit_script_path) {
8815 error = histedit_load_list(&histedit_cmds,
8816 edit_script_path, repo);
8817 if (error) {
8818 got_worktree_histedit_abort(worktree, fileindex,
8819 repo, branch, base_commit_id,
8820 update_progress, &upa);
8821 print_update_progress_stats(&upa);
8822 goto done;
8824 } else {
8825 const char *branch_name;
8826 branch_name = got_ref_get_symref_target(branch);
8827 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8828 branch_name += 11;
8829 error = histedit_edit_script(&histedit_cmds, &commits,
8830 branch_name, edit_logmsg_only, fold_only, repo);
8831 if (error) {
8832 got_worktree_histedit_abort(worktree, fileindex,
8833 repo, branch, base_commit_id,
8834 update_progress, &upa);
8835 print_update_progress_stats(&upa);
8836 goto done;
8841 error = histedit_save_list(&histedit_cmds, worktree,
8842 repo);
8843 if (error) {
8844 got_worktree_histedit_abort(worktree, fileindex,
8845 repo, branch, base_commit_id,
8846 update_progress, &upa);
8847 print_update_progress_stats(&upa);
8848 goto done;
8853 error = histedit_check_script(&histedit_cmds, &commits, repo);
8854 if (error)
8855 goto done;
8857 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8858 if (resume_commit_id) {
8859 if (got_object_id_cmp(hle->commit_id,
8860 resume_commit_id) != 0)
8861 continue;
8863 resume_commit_id = NULL;
8864 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8865 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8866 error = histedit_skip_commit(hle, worktree,
8867 repo);
8868 if (error)
8869 goto done;
8870 } else {
8871 struct got_pathlist_head paths;
8872 int have_changes = 0;
8874 TAILQ_INIT(&paths);
8875 error = got_pathlist_append(&paths, "", NULL);
8876 if (error)
8877 goto done;
8878 error = got_worktree_status(worktree, &paths,
8879 repo, check_local_changes, &have_changes,
8880 check_cancelled, NULL);
8881 got_pathlist_free(&paths);
8882 if (error) {
8883 if (error->code != GOT_ERR_CANCELLED)
8884 goto done;
8885 if (sigint_received || sigpipe_received)
8886 goto done;
8888 if (have_changes) {
8889 error = histedit_commit(NULL, worktree,
8890 fileindex, tmp_branch, hle, repo);
8891 if (error)
8892 goto done;
8893 } else {
8894 error = got_object_open_as_commit(
8895 &commit, repo, hle->commit_id);
8896 if (error)
8897 goto done;
8898 error = show_histedit_progress(commit,
8899 hle, NULL);
8900 got_object_commit_close(commit);
8901 commit = NULL;
8902 if (error)
8903 goto done;
8906 continue;
8909 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8910 error = histedit_skip_commit(hle, worktree, repo);
8911 if (error)
8912 goto done;
8913 continue;
8916 error = got_object_open_as_commit(&commit, repo,
8917 hle->commit_id);
8918 if (error)
8919 goto done;
8920 parent_ids = got_object_commit_get_parent_ids(commit);
8921 pid = SIMPLEQ_FIRST(parent_ids);
8923 error = got_worktree_histedit_merge_files(&merged_paths,
8924 worktree, fileindex, pid->id, hle->commit_id, repo,
8925 update_progress, &upa, check_cancelled, NULL);
8926 if (error)
8927 goto done;
8928 got_object_commit_close(commit);
8929 commit = NULL;
8931 print_update_progress_stats(&upa);
8932 if (upa.conflicts > 0)
8933 rebase_status = GOT_STATUS_CONFLICT;
8935 if (rebase_status == GOT_STATUS_CONFLICT) {
8936 error = show_rebase_merge_conflict(hle->commit_id,
8937 repo);
8938 if (error)
8939 goto done;
8940 got_worktree_rebase_pathlist_free(&merged_paths);
8941 break;
8944 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8945 char *id_str;
8946 error = got_object_id_str(&id_str, hle->commit_id);
8947 if (error)
8948 goto done;
8949 printf("Stopping histedit for amending commit %s\n",
8950 id_str);
8951 free(id_str);
8952 got_worktree_rebase_pathlist_free(&merged_paths);
8953 error = got_worktree_histedit_postpone(worktree,
8954 fileindex);
8955 goto done;
8958 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8959 error = histedit_skip_commit(hle, worktree, repo);
8960 if (error)
8961 goto done;
8962 continue;
8965 error = histedit_commit(&merged_paths, worktree, fileindex,
8966 tmp_branch, hle, repo);
8967 got_worktree_rebase_pathlist_free(&merged_paths);
8968 if (error)
8969 goto done;
8972 if (rebase_status == GOT_STATUS_CONFLICT) {
8973 error = got_worktree_histedit_postpone(worktree, fileindex);
8974 if (error)
8975 goto done;
8976 error = got_error_msg(GOT_ERR_CONFLICTS,
8977 "conflicts must be resolved before histedit can continue");
8978 } else
8979 error = histedit_complete(worktree, fileindex, tmp_branch,
8980 branch, repo);
8981 done:
8982 got_object_id_queue_free(&commits);
8983 histedit_free_list(&histedit_cmds);
8984 free(head_commit_id);
8985 free(base_commit_id);
8986 free(resume_commit_id);
8987 if (commit)
8988 got_object_commit_close(commit);
8989 if (branch)
8990 got_ref_close(branch);
8991 if (tmp_branch)
8992 got_ref_close(tmp_branch);
8993 if (worktree)
8994 got_worktree_close(worktree);
8995 if (repo)
8996 got_repo_close(repo);
8997 return error;
9000 __dead static void
9001 usage_integrate(void)
9003 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9004 exit(1);
9007 static const struct got_error *
9008 cmd_integrate(int argc, char *argv[])
9010 const struct got_error *error = NULL;
9011 struct got_repository *repo = NULL;
9012 struct got_worktree *worktree = NULL;
9013 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9014 const char *branch_arg = NULL;
9015 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9016 struct got_fileindex *fileindex = NULL;
9017 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9018 int ch;
9019 struct got_update_progress_arg upa;
9021 while ((ch = getopt(argc, argv, "")) != -1) {
9022 switch (ch) {
9023 default:
9024 usage_integrate();
9025 /* NOTREACHED */
9029 argc -= optind;
9030 argv += optind;
9032 if (argc != 1)
9033 usage_integrate();
9034 branch_arg = argv[0];
9035 #ifndef PROFILE
9036 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9037 "unveil", NULL) == -1)
9038 err(1, "pledge");
9039 #endif
9040 cwd = getcwd(NULL, 0);
9041 if (cwd == NULL) {
9042 error = got_error_from_errno("getcwd");
9043 goto done;
9046 error = got_worktree_open(&worktree, cwd);
9047 if (error) {
9048 if (error->code == GOT_ERR_NOT_WORKTREE)
9049 error = wrap_not_worktree_error(error, "integrate",
9050 cwd);
9051 goto done;
9054 error = check_rebase_or_histedit_in_progress(worktree);
9055 if (error)
9056 goto done;
9058 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9059 NULL);
9060 if (error != NULL)
9061 goto done;
9063 error = apply_unveil(got_repo_get_path(repo), 0,
9064 got_worktree_get_root_path(worktree));
9065 if (error)
9066 goto done;
9068 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9069 error = got_error_from_errno("asprintf");
9070 goto done;
9073 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9074 &base_branch_ref, worktree, refname, repo);
9075 if (error)
9076 goto done;
9078 refname = strdup(got_ref_get_name(branch_ref));
9079 if (refname == NULL) {
9080 error = got_error_from_errno("strdup");
9081 got_worktree_integrate_abort(worktree, fileindex, repo,
9082 branch_ref, base_branch_ref);
9083 goto done;
9085 base_refname = strdup(got_ref_get_name(base_branch_ref));
9086 if (base_refname == NULL) {
9087 error = got_error_from_errno("strdup");
9088 got_worktree_integrate_abort(worktree, fileindex, repo,
9089 branch_ref, base_branch_ref);
9090 goto done;
9093 error = got_ref_resolve(&commit_id, repo, branch_ref);
9094 if (error)
9095 goto done;
9097 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9098 if (error)
9099 goto done;
9101 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9102 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9103 "specified branch has already been integrated");
9104 got_worktree_integrate_abort(worktree, fileindex, repo,
9105 branch_ref, base_branch_ref);
9106 goto done;
9109 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9110 if (error) {
9111 if (error->code == GOT_ERR_ANCESTRY)
9112 error = got_error(GOT_ERR_REBASE_REQUIRED);
9113 got_worktree_integrate_abort(worktree, fileindex, repo,
9114 branch_ref, base_branch_ref);
9115 goto done;
9118 memset(&upa, 0, sizeof(upa));
9119 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9120 branch_ref, base_branch_ref, update_progress, &upa,
9121 check_cancelled, NULL);
9122 if (error)
9123 goto done;
9125 printf("Integrated %s into %s\n", refname, base_refname);
9126 print_update_progress_stats(&upa);
9127 done:
9128 if (repo)
9129 got_repo_close(repo);
9130 if (worktree)
9131 got_worktree_close(worktree);
9132 free(cwd);
9133 free(base_commit_id);
9134 free(commit_id);
9135 free(refname);
9136 free(base_refname);
9137 return error;
9140 __dead static void
9141 usage_stage(void)
9143 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9144 "[-S] [file-path ...]\n",
9145 getprogname());
9146 exit(1);
9149 static const struct got_error *
9150 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9151 const char *path, struct got_object_id *blob_id,
9152 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9153 int dirfd, const char *de_name)
9155 const struct got_error *err = NULL;
9156 char *id_str = NULL;
9158 if (staged_status != GOT_STATUS_ADD &&
9159 staged_status != GOT_STATUS_MODIFY &&
9160 staged_status != GOT_STATUS_DELETE)
9161 return NULL;
9163 if (staged_status == GOT_STATUS_ADD ||
9164 staged_status == GOT_STATUS_MODIFY)
9165 err = got_object_id_str(&id_str, staged_blob_id);
9166 else
9167 err = got_object_id_str(&id_str, blob_id);
9168 if (err)
9169 return err;
9171 printf("%s %c %s\n", id_str, staged_status, path);
9172 free(id_str);
9173 return NULL;
9176 static const struct got_error *
9177 cmd_stage(int argc, char *argv[])
9179 const struct got_error *error = NULL;
9180 struct got_repository *repo = NULL;
9181 struct got_worktree *worktree = NULL;
9182 char *cwd = NULL;
9183 struct got_pathlist_head paths;
9184 struct got_pathlist_entry *pe;
9185 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9186 FILE *patch_script_file = NULL;
9187 const char *patch_script_path = NULL;
9188 struct choose_patch_arg cpa;
9190 TAILQ_INIT(&paths);
9192 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9193 switch (ch) {
9194 case 'l':
9195 list_stage = 1;
9196 break;
9197 case 'p':
9198 pflag = 1;
9199 break;
9200 case 'F':
9201 patch_script_path = optarg;
9202 break;
9203 case 'S':
9204 allow_bad_symlinks = 1;
9205 break;
9206 default:
9207 usage_stage();
9208 /* NOTREACHED */
9212 argc -= optind;
9213 argv += optind;
9215 #ifndef PROFILE
9216 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9217 "unveil", NULL) == -1)
9218 err(1, "pledge");
9219 #endif
9220 if (list_stage && (pflag || patch_script_path))
9221 errx(1, "-l option cannot be used with other options");
9222 if (patch_script_path && !pflag)
9223 errx(1, "-F option can only be used together with -p option");
9225 cwd = getcwd(NULL, 0);
9226 if (cwd == NULL) {
9227 error = got_error_from_errno("getcwd");
9228 goto done;
9231 error = got_worktree_open(&worktree, cwd);
9232 if (error) {
9233 if (error->code == GOT_ERR_NOT_WORKTREE)
9234 error = wrap_not_worktree_error(error, "stage", cwd);
9235 goto done;
9238 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9239 NULL);
9240 if (error != NULL)
9241 goto done;
9243 if (patch_script_path) {
9244 patch_script_file = fopen(patch_script_path, "r");
9245 if (patch_script_file == NULL) {
9246 error = got_error_from_errno2("fopen",
9247 patch_script_path);
9248 goto done;
9251 error = apply_unveil(got_repo_get_path(repo), 0,
9252 got_worktree_get_root_path(worktree));
9253 if (error)
9254 goto done;
9256 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9257 if (error)
9258 goto done;
9260 if (list_stage)
9261 error = got_worktree_status(worktree, &paths, repo,
9262 print_stage, NULL, check_cancelled, NULL);
9263 else {
9264 cpa.patch_script_file = patch_script_file;
9265 cpa.action = "stage";
9266 error = got_worktree_stage(worktree, &paths,
9267 pflag ? NULL : print_status, NULL,
9268 pflag ? choose_patch : NULL, &cpa,
9269 allow_bad_symlinks, repo);
9271 done:
9272 if (patch_script_file && fclose(patch_script_file) == EOF &&
9273 error == NULL)
9274 error = got_error_from_errno2("fclose", patch_script_path);
9275 if (repo)
9276 got_repo_close(repo);
9277 if (worktree)
9278 got_worktree_close(worktree);
9279 TAILQ_FOREACH(pe, &paths, entry)
9280 free((char *)pe->path);
9281 got_pathlist_free(&paths);
9282 free(cwd);
9283 return error;
9286 __dead static void
9287 usage_unstage(void)
9289 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9290 "[file-path ...]\n",
9291 getprogname());
9292 exit(1);
9296 static const struct got_error *
9297 cmd_unstage(int argc, char *argv[])
9299 const struct got_error *error = NULL;
9300 struct got_repository *repo = NULL;
9301 struct got_worktree *worktree = NULL;
9302 char *cwd = NULL;
9303 struct got_pathlist_head paths;
9304 struct got_pathlist_entry *pe;
9305 int ch, pflag = 0;
9306 struct got_update_progress_arg upa;
9307 FILE *patch_script_file = NULL;
9308 const char *patch_script_path = NULL;
9309 struct choose_patch_arg cpa;
9311 TAILQ_INIT(&paths);
9313 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9314 switch (ch) {
9315 case 'p':
9316 pflag = 1;
9317 break;
9318 case 'F':
9319 patch_script_path = optarg;
9320 break;
9321 default:
9322 usage_unstage();
9323 /* NOTREACHED */
9327 argc -= optind;
9328 argv += optind;
9330 #ifndef PROFILE
9331 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9332 "unveil", NULL) == -1)
9333 err(1, "pledge");
9334 #endif
9335 if (patch_script_path && !pflag)
9336 errx(1, "-F option can only be used together with -p option");
9338 cwd = getcwd(NULL, 0);
9339 if (cwd == NULL) {
9340 error = got_error_from_errno("getcwd");
9341 goto done;
9344 error = got_worktree_open(&worktree, cwd);
9345 if (error) {
9346 if (error->code == GOT_ERR_NOT_WORKTREE)
9347 error = wrap_not_worktree_error(error, "unstage", cwd);
9348 goto done;
9351 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9352 NULL);
9353 if (error != NULL)
9354 goto done;
9356 if (patch_script_path) {
9357 patch_script_file = fopen(patch_script_path, "r");
9358 if (patch_script_file == NULL) {
9359 error = got_error_from_errno2("fopen",
9360 patch_script_path);
9361 goto done;
9365 error = apply_unveil(got_repo_get_path(repo), 0,
9366 got_worktree_get_root_path(worktree));
9367 if (error)
9368 goto done;
9370 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9371 if (error)
9372 goto done;
9374 cpa.patch_script_file = patch_script_file;
9375 cpa.action = "unstage";
9376 memset(&upa, 0, sizeof(upa));
9377 error = got_worktree_unstage(worktree, &paths, update_progress,
9378 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9379 if (!error)
9380 print_update_progress_stats(&upa);
9381 done:
9382 if (patch_script_file && fclose(patch_script_file) == EOF &&
9383 error == NULL)
9384 error = got_error_from_errno2("fclose", patch_script_path);
9385 if (repo)
9386 got_repo_close(repo);
9387 if (worktree)
9388 got_worktree_close(worktree);
9389 TAILQ_FOREACH(pe, &paths, entry)
9390 free((char *)pe->path);
9391 got_pathlist_free(&paths);
9392 free(cwd);
9393 return error;
9396 __dead static void
9397 usage_cat(void)
9399 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9400 "arg1 [arg2 ...]\n", getprogname());
9401 exit(1);
9404 static const struct got_error *
9405 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9407 const struct got_error *err;
9408 struct got_blob_object *blob;
9410 err = got_object_open_as_blob(&blob, repo, id, 8192);
9411 if (err)
9412 return err;
9414 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9415 got_object_blob_close(blob);
9416 return err;
9419 static const struct got_error *
9420 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9422 const struct got_error *err;
9423 struct got_tree_object *tree;
9424 int nentries, i;
9426 err = got_object_open_as_tree(&tree, repo, id);
9427 if (err)
9428 return err;
9430 nentries = got_object_tree_get_nentries(tree);
9431 for (i = 0; i < nentries; i++) {
9432 struct got_tree_entry *te;
9433 char *id_str;
9434 if (sigint_received || sigpipe_received)
9435 break;
9436 te = got_object_tree_get_entry(tree, i);
9437 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9438 if (err)
9439 break;
9440 fprintf(outfile, "%s %.7o %s\n", id_str,
9441 got_tree_entry_get_mode(te),
9442 got_tree_entry_get_name(te));
9443 free(id_str);
9446 got_object_tree_close(tree);
9447 return err;
9450 static const struct got_error *
9451 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9453 const struct got_error *err;
9454 struct got_commit_object *commit;
9455 const struct got_object_id_queue *parent_ids;
9456 struct got_object_qid *pid;
9457 char *id_str = NULL;
9458 const char *logmsg = NULL;
9460 err = got_object_open_as_commit(&commit, repo, id);
9461 if (err)
9462 return err;
9464 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9465 if (err)
9466 goto done;
9468 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9469 parent_ids = got_object_commit_get_parent_ids(commit);
9470 fprintf(outfile, "numparents %d\n",
9471 got_object_commit_get_nparents(commit));
9472 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9473 char *pid_str;
9474 err = got_object_id_str(&pid_str, pid->id);
9475 if (err)
9476 goto done;
9477 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9478 free(pid_str);
9480 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9481 got_object_commit_get_author(commit),
9482 (long long)got_object_commit_get_author_time(commit));
9484 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9485 got_object_commit_get_author(commit),
9486 (long long)got_object_commit_get_committer_time(commit));
9488 logmsg = got_object_commit_get_logmsg_raw(commit);
9489 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9490 fprintf(outfile, "%s", logmsg);
9491 done:
9492 free(id_str);
9493 got_object_commit_close(commit);
9494 return err;
9497 static const struct got_error *
9498 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9500 const struct got_error *err;
9501 struct got_tag_object *tag;
9502 char *id_str = NULL;
9503 const char *tagmsg = NULL;
9505 err = got_object_open_as_tag(&tag, repo, id);
9506 if (err)
9507 return err;
9509 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9510 if (err)
9511 goto done;
9513 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9515 switch (got_object_tag_get_object_type(tag)) {
9516 case GOT_OBJ_TYPE_BLOB:
9517 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9518 GOT_OBJ_LABEL_BLOB);
9519 break;
9520 case GOT_OBJ_TYPE_TREE:
9521 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9522 GOT_OBJ_LABEL_TREE);
9523 break;
9524 case GOT_OBJ_TYPE_COMMIT:
9525 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9526 GOT_OBJ_LABEL_COMMIT);
9527 break;
9528 case GOT_OBJ_TYPE_TAG:
9529 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9530 GOT_OBJ_LABEL_TAG);
9531 break;
9532 default:
9533 break;
9536 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9537 got_object_tag_get_name(tag));
9539 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9540 got_object_tag_get_tagger(tag),
9541 (long long)got_object_tag_get_tagger_time(tag));
9543 tagmsg = got_object_tag_get_message(tag);
9544 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9545 fprintf(outfile, "%s", tagmsg);
9546 done:
9547 free(id_str);
9548 got_object_tag_close(tag);
9549 return err;
9552 static const struct got_error *
9553 cmd_cat(int argc, char *argv[])
9555 const struct got_error *error;
9556 struct got_repository *repo = NULL;
9557 struct got_worktree *worktree = NULL;
9558 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9559 const char *commit_id_str = NULL;
9560 struct got_object_id *id = NULL, *commit_id = NULL;
9561 int ch, obj_type, i, force_path = 0;
9563 #ifndef PROFILE
9564 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9565 NULL) == -1)
9566 err(1, "pledge");
9567 #endif
9569 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9570 switch (ch) {
9571 case 'c':
9572 commit_id_str = optarg;
9573 break;
9574 case 'r':
9575 repo_path = realpath(optarg, NULL);
9576 if (repo_path == NULL)
9577 return got_error_from_errno2("realpath",
9578 optarg);
9579 got_path_strip_trailing_slashes(repo_path);
9580 break;
9581 case 'P':
9582 force_path = 1;
9583 break;
9584 default:
9585 usage_cat();
9586 /* NOTREACHED */
9590 argc -= optind;
9591 argv += optind;
9593 cwd = getcwd(NULL, 0);
9594 if (cwd == NULL) {
9595 error = got_error_from_errno("getcwd");
9596 goto done;
9598 error = got_worktree_open(&worktree, cwd);
9599 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9600 goto done;
9601 if (worktree) {
9602 if (repo_path == NULL) {
9603 repo_path = strdup(
9604 got_worktree_get_repo_path(worktree));
9605 if (repo_path == NULL) {
9606 error = got_error_from_errno("strdup");
9607 goto done;
9612 if (repo_path == NULL) {
9613 repo_path = getcwd(NULL, 0);
9614 if (repo_path == NULL)
9615 return got_error_from_errno("getcwd");
9618 error = got_repo_open(&repo, repo_path, NULL);
9619 free(repo_path);
9620 if (error != NULL)
9621 goto done;
9623 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9624 if (error)
9625 goto done;
9627 if (commit_id_str == NULL)
9628 commit_id_str = GOT_REF_HEAD;
9629 error = got_repo_match_object_id(&commit_id, NULL,
9630 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9631 if (error)
9632 goto done;
9634 for (i = 0; i < argc; i++) {
9635 if (force_path) {
9636 error = got_object_id_by_path(&id, repo, commit_id,
9637 argv[i]);
9638 if (error)
9639 break;
9640 } else {
9641 error = got_repo_match_object_id(&id, &label, argv[i],
9642 GOT_OBJ_TYPE_ANY, 0, repo);
9643 if (error) {
9644 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9645 error->code != GOT_ERR_NOT_REF)
9646 break;
9647 error = got_object_id_by_path(&id, repo,
9648 commit_id, argv[i]);
9649 if (error)
9650 break;
9654 error = got_object_get_type(&obj_type, repo, id);
9655 if (error)
9656 break;
9658 switch (obj_type) {
9659 case GOT_OBJ_TYPE_BLOB:
9660 error = cat_blob(id, repo, stdout);
9661 break;
9662 case GOT_OBJ_TYPE_TREE:
9663 error = cat_tree(id, repo, stdout);
9664 break;
9665 case GOT_OBJ_TYPE_COMMIT:
9666 error = cat_commit(id, repo, stdout);
9667 break;
9668 case GOT_OBJ_TYPE_TAG:
9669 error = cat_tag(id, repo, stdout);
9670 break;
9671 default:
9672 error = got_error(GOT_ERR_OBJ_TYPE);
9673 break;
9675 if (error)
9676 break;
9677 free(label);
9678 label = NULL;
9679 free(id);
9680 id = NULL;
9682 done:
9683 free(label);
9684 free(id);
9685 free(commit_id);
9686 if (worktree)
9687 got_worktree_close(worktree);
9688 if (repo) {
9689 const struct got_error *repo_error;
9690 repo_error = got_repo_close(repo);
9691 if (error == NULL)
9692 error = repo_error;
9694 return error;
9697 __dead static void
9698 usage_info(void)
9700 fprintf(stderr, "usage: %s info [path ...]\n",
9701 getprogname());
9702 exit(1);
9705 static const struct got_error *
9706 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9707 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9708 struct got_object_id *commit_id)
9710 const struct got_error *err = NULL;
9711 char *id_str = NULL;
9712 char datebuf[128];
9713 struct tm mytm, *tm;
9714 struct got_pathlist_head *paths = arg;
9715 struct got_pathlist_entry *pe;
9718 * Clear error indication from any of the path arguments which
9719 * would cause this file index entry to be displayed.
9721 TAILQ_FOREACH(pe, paths, entry) {
9722 if (got_path_cmp(path, pe->path, strlen(path),
9723 pe->path_len) == 0 ||
9724 got_path_is_child(path, pe->path, pe->path_len))
9725 pe->data = NULL; /* no error */
9728 printf(GOT_COMMIT_SEP_STR);
9729 if (S_ISLNK(mode))
9730 printf("symlink: %s\n", path);
9731 else if (S_ISREG(mode)) {
9732 printf("file: %s\n", path);
9733 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9734 } else if (S_ISDIR(mode))
9735 printf("directory: %s\n", path);
9736 else
9737 printf("something: %s\n", path);
9739 tm = localtime_r(&mtime, &mytm);
9740 if (tm == NULL)
9741 return NULL;
9742 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9743 return got_error(GOT_ERR_NO_SPACE);
9744 printf("timestamp: %s\n", datebuf);
9746 if (blob_id) {
9747 err = got_object_id_str(&id_str, blob_id);
9748 if (err)
9749 return err;
9750 printf("based on blob: %s\n", id_str);
9751 free(id_str);
9754 if (staged_blob_id) {
9755 err = got_object_id_str(&id_str, staged_blob_id);
9756 if (err)
9757 return err;
9758 printf("based on staged blob: %s\n", id_str);
9759 free(id_str);
9762 if (commit_id) {
9763 err = got_object_id_str(&id_str, commit_id);
9764 if (err)
9765 return err;
9766 printf("based on commit: %s\n", id_str);
9767 free(id_str);
9770 return NULL;
9773 static const struct got_error *
9774 cmd_info(int argc, char *argv[])
9776 const struct got_error *error = NULL;
9777 struct got_worktree *worktree = NULL;
9778 char *cwd = NULL, *id_str = NULL;
9779 struct got_pathlist_head paths;
9780 struct got_pathlist_entry *pe;
9781 char *uuidstr = NULL;
9782 int ch, show_files = 0;
9784 TAILQ_INIT(&paths);
9786 while ((ch = getopt(argc, argv, "")) != -1) {
9787 switch (ch) {
9788 default:
9789 usage_info();
9790 /* NOTREACHED */
9794 argc -= optind;
9795 argv += optind;
9797 #ifndef PROFILE
9798 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9799 NULL) == -1)
9800 err(1, "pledge");
9801 #endif
9802 cwd = getcwd(NULL, 0);
9803 if (cwd == NULL) {
9804 error = got_error_from_errno("getcwd");
9805 goto done;
9808 error = got_worktree_open(&worktree, cwd);
9809 if (error) {
9810 if (error->code == GOT_ERR_NOT_WORKTREE)
9811 error = wrap_not_worktree_error(error, "status", cwd);
9812 goto done;
9815 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9816 if (error)
9817 goto done;
9819 if (argc >= 1) {
9820 error = get_worktree_paths_from_argv(&paths, argc, argv,
9821 worktree);
9822 if (error)
9823 goto done;
9824 show_files = 1;
9827 error = got_object_id_str(&id_str,
9828 got_worktree_get_base_commit_id(worktree));
9829 if (error)
9830 goto done;
9832 error = got_worktree_get_uuid(&uuidstr, worktree);
9833 if (error)
9834 goto done;
9836 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9837 printf("work tree base commit: %s\n", id_str);
9838 printf("work tree path prefix: %s\n",
9839 got_worktree_get_path_prefix(worktree));
9840 printf("work tree branch reference: %s\n",
9841 got_worktree_get_head_ref_name(worktree));
9842 printf("work tree UUID: %s\n", uuidstr);
9843 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9845 if (show_files) {
9846 struct got_pathlist_entry *pe;
9847 TAILQ_FOREACH(pe, &paths, entry) {
9848 if (pe->path_len == 0)
9849 continue;
9851 * Assume this path will fail. This will be corrected
9852 * in print_path_info() in case the path does suceeed.
9854 pe->data = (void *)got_error_path(pe->path,
9855 GOT_ERR_BAD_PATH);
9857 error = got_worktree_path_info(worktree, &paths,
9858 print_path_info, &paths, check_cancelled, NULL);
9859 if (error)
9860 goto done;
9861 TAILQ_FOREACH(pe, &paths, entry) {
9862 if (pe->data != NULL) {
9863 error = pe->data; /* bad path */
9864 break;
9868 done:
9869 TAILQ_FOREACH(pe, &paths, entry)
9870 free((char *)pe->path);
9871 got_pathlist_free(&paths);
9872 free(cwd);
9873 free(id_str);
9874 free(uuidstr);
9875 return error;