Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(FILE *fp)
176 int i;
178 fprintf(fp, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(fp, " %s", cmd->cmd_name);
183 fputc('\n', fp);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0 }
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag, 1);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 1;
217 optreset = 1;
219 if (Vflag) {
220 got_version_print_str();
221 return 0;
224 if (argc <= 0)
225 usage(hflag, hflag ? 0 : 1);
227 signal(SIGINT, catch_sigint);
228 signal(SIGPIPE, catch_sigpipe);
230 for (i = 0; i < nitems(got_commands); i++) {
231 const struct got_error *error;
233 cmd = &got_commands[i];
235 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
236 strcmp(cmd->cmd_alias, argv[0]) != 0)
237 continue;
239 if (hflag)
240 got_commands[i].cmd_usage();
242 error = got_commands[i].cmd_main(argc, argv);
243 if (error && error->code != GOT_ERR_CANCELLED &&
244 error->code != GOT_ERR_PRIVSEP_EXIT &&
245 !(sigpipe_received &&
246 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
247 !(sigint_received &&
248 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
249 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
250 return 1;
253 return 0;
256 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
257 list_commands(stderr);
258 return 1;
261 __dead static void
262 usage(int hflag, int status)
264 FILE *fp = (status == 0) ? stdout : stderr;
266 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
267 getprogname());
268 if (hflag)
269 list_commands(fp);
270 exit(status);
273 static const struct got_error *
274 get_editor(char **abspath)
276 const struct got_error *err = NULL;
277 const char *editor;
279 *abspath = NULL;
281 editor = getenv("VISUAL");
282 if (editor == NULL)
283 editor = getenv("EDITOR");
285 if (editor) {
286 err = got_path_find_prog(abspath, editor);
287 if (err)
288 return err;
291 if (*abspath == NULL) {
292 *abspath = strdup("/bin/ed");
293 if (*abspath == NULL)
294 return got_error_from_errno("strdup");
297 return NULL;
300 static const struct got_error *
301 apply_unveil(const char *repo_path, int repo_read_only,
302 const char *worktree_path)
304 const struct got_error *err;
306 #ifdef PROFILE
307 if (unveil("gmon.out", "rwc") != 0)
308 return got_error_from_errno2("unveil", "gmon.out");
309 #endif
310 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
311 return got_error_from_errno2("unveil", repo_path);
313 if (worktree_path && unveil(worktree_path, "rwc") != 0)
314 return got_error_from_errno2("unveil", worktree_path);
316 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
317 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
319 err = got_privsep_unveil_exec_helpers();
320 if (err != NULL)
321 return err;
323 if (unveil(NULL, NULL) != 0)
324 return got_error_from_errno("unveil");
326 return NULL;
329 __dead static void
330 usage_init(void)
332 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
333 exit(1);
336 static const struct got_error *
337 cmd_init(int argc, char *argv[])
339 const struct got_error *error = NULL;
340 char *repo_path = NULL;
341 int ch;
343 while ((ch = getopt(argc, argv, "")) != -1) {
344 switch (ch) {
345 default:
346 usage_init();
347 /* NOTREACHED */
351 argc -= optind;
352 argv += optind;
354 #ifndef PROFILE
355 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
356 err(1, "pledge");
357 #endif
358 if (argc != 1)
359 usage_init();
361 repo_path = strdup(argv[0]);
362 if (repo_path == NULL)
363 return got_error_from_errno("strdup");
365 got_path_strip_trailing_slashes(repo_path);
367 error = got_path_mkdir(repo_path);
368 if (error &&
369 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
370 goto done;
372 error = apply_unveil(repo_path, 0, NULL);
373 if (error)
374 goto done;
376 error = got_repo_init(repo_path);
377 done:
378 free(repo_path);
379 return error;
382 __dead static void
383 usage_import(void)
385 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
386 "[-r repository-path] [-I pattern] path\n", getprogname());
387 exit(1);
390 int
391 spawn_editor(const char *editor, const char *file)
393 pid_t pid;
394 sig_t sighup, sigint, sigquit;
395 int st = -1;
397 sighup = signal(SIGHUP, SIG_IGN);
398 sigint = signal(SIGINT, SIG_IGN);
399 sigquit = signal(SIGQUIT, SIG_IGN);
401 switch (pid = fork()) {
402 case -1:
403 goto doneediting;
404 case 0:
405 execl(editor, editor, file, (char *)NULL);
406 _exit(127);
409 while (waitpid(pid, &st, 0) == -1)
410 if (errno != EINTR)
411 break;
413 doneediting:
414 (void)signal(SIGHUP, sighup);
415 (void)signal(SIGINT, sigint);
416 (void)signal(SIGQUIT, sigquit);
418 if (!WIFEXITED(st)) {
419 errno = EINTR;
420 return -1;
423 return WEXITSTATUS(st);
426 static const struct got_error *
427 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
428 const char *initial_content, size_t initial_content_len)
430 const struct got_error *err = NULL;
431 char *line = NULL;
432 size_t linesize = 0;
433 ssize_t linelen;
434 struct stat st, st2;
435 FILE *fp = NULL;
436 size_t len, logmsg_len;
437 char *initial_content_stripped = NULL, *buf = NULL, *s;
439 *logmsg = NULL;
441 if (stat(logmsg_path, &st) == -1)
442 return got_error_from_errno2("stat", logmsg_path);
444 if (spawn_editor(editor, logmsg_path) == -1)
445 return got_error_from_errno("failed spawning editor");
447 if (stat(logmsg_path, &st2) == -1)
448 return got_error_from_errno("stat");
450 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
451 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
452 "no changes made to commit message, aborting");
454 /*
455 * Set up a stripped version of the initial content without comments
456 * and blank lines. We need this in order to check if the message
457 * has in fact been edited.
458 */
459 initial_content_stripped = malloc(initial_content_len + 1);
460 if (initial_content_stripped == NULL)
461 return got_error_from_errno("malloc");
462 initial_content_stripped[0] = '\0';
464 buf = strdup(initial_content);
465 if (buf == NULL) {
466 err = got_error_from_errno("strdup");
467 goto done;
469 s = buf;
470 len = 0;
471 while ((line = strsep(&s, "\n")) != NULL) {
472 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
473 continue; /* remove comments and leading empty lines */
474 len = strlcat(initial_content_stripped, line,
475 initial_content_len + 1);
476 if (len >= initial_content_len + 1) {
477 err = got_error(GOT_ERR_NO_SPACE);
478 goto done;
481 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
482 initial_content_stripped[len - 1] = '\0';
483 len--;
486 logmsg_len = st2.st_size;
487 *logmsg = malloc(logmsg_len + 1);
488 if (*logmsg == NULL)
489 return got_error_from_errno("malloc");
490 (*logmsg)[0] = '\0';
492 fp = fopen(logmsg_path, "r");
493 if (fp == NULL) {
494 err = got_error_from_errno("fopen");
495 goto done;
498 len = 0;
499 while ((linelen = getline(&line, &linesize, fp)) != -1) {
500 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
501 continue; /* remove comments and leading empty lines */
502 len = strlcat(*logmsg, line, logmsg_len + 1);
503 if (len >= logmsg_len + 1) {
504 err = got_error(GOT_ERR_NO_SPACE);
505 goto done;
508 free(line);
509 if (ferror(fp)) {
510 err = got_ferror(fp, GOT_ERR_IO);
511 goto done;
513 while (len > 0 && (*logmsg)[len - 1] == '\n') {
514 (*logmsg)[len - 1] = '\0';
515 len--;
518 if (len == 0) {
519 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
520 "commit message cannot be empty, aborting");
521 goto done;
523 if (strcmp(*logmsg, initial_content_stripped) == 0)
524 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
525 "no changes made to commit message, aborting");
526 done:
527 free(initial_content_stripped);
528 free(buf);
529 if (fp && fclose(fp) == EOF && err == NULL)
530 err = got_error_from_errno("fclose");
531 if (err) {
532 free(*logmsg);
533 *logmsg = NULL;
535 return err;
538 static const struct got_error *
539 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
540 const char *path_dir, const char *branch_name)
542 char *initial_content = NULL;
543 const struct got_error *err = NULL;
544 int initial_content_len;
545 int fd = -1;
547 initial_content_len = asprintf(&initial_content,
548 "\n# %s to be imported to branch %s\n", path_dir,
549 branch_name);
550 if (initial_content_len == -1)
551 return got_error_from_errno("asprintf");
553 err = got_opentemp_named_fd(logmsg_path, &fd,
554 GOT_TMPDIR_STR "/got-importmsg");
555 if (err)
556 goto done;
558 if (write(fd, initial_content, initial_content_len) == -1) {
559 err = got_error_from_errno2("write", *logmsg_path);
560 goto done;
563 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
564 initial_content_len);
565 done:
566 if (fd != -1 && close(fd) == -1 && err == NULL)
567 err = got_error_from_errno2("close", *logmsg_path);
568 free(initial_content);
569 if (err) {
570 free(*logmsg_path);
571 *logmsg_path = NULL;
573 return err;
576 static const struct got_error *
577 import_progress(void *arg, const char *path)
579 printf("A %s\n", path);
580 return NULL;
583 static const struct got_error *
584 get_author(char **author, struct got_repository *repo,
585 struct got_worktree *worktree)
587 const struct got_error *err = NULL;
588 const char *got_author = NULL, *name, *email;
589 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
591 *author = NULL;
593 if (worktree)
594 worktree_conf = got_worktree_get_gotconfig(worktree);
595 repo_conf = got_repo_get_gotconfig(repo);
597 /*
598 * Priority of potential author information sources, from most
599 * significant to least significant:
600 * 1) work tree's .got/got.conf file
601 * 2) repository's got.conf file
602 * 3) repository's git config file
603 * 4) environment variables
604 * 5) global git config files (in user's home directory or /etc)
605 */
607 if (worktree_conf)
608 got_author = got_gotconfig_get_author(worktree_conf);
609 if (got_author == NULL)
610 got_author = got_gotconfig_get_author(repo_conf);
611 if (got_author == NULL) {
612 name = got_repo_get_gitconfig_author_name(repo);
613 email = got_repo_get_gitconfig_author_email(repo);
614 if (name && email) {
615 if (asprintf(author, "%s <%s>", name, email) == -1)
616 return got_error_from_errno("asprintf");
617 return NULL;
620 got_author = getenv("GOT_AUTHOR");
621 if (got_author == NULL) {
622 name = got_repo_get_global_gitconfig_author_name(repo);
623 email = got_repo_get_global_gitconfig_author_email(
624 repo);
625 if (name && email) {
626 if (asprintf(author, "%s <%s>", name, email)
627 == -1)
628 return got_error_from_errno("asprintf");
629 return NULL;
631 /* TODO: Look up user in password database? */
632 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
636 *author = strdup(got_author);
637 if (*author == NULL)
638 return got_error_from_errno("strdup");
640 /*
641 * Really dumb email address check; we're only doing this to
642 * avoid git's object parser breaking on commits we create.
643 */
644 while (*got_author && *got_author != '<')
645 got_author++;
646 if (*got_author != '<') {
647 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
648 goto done;
650 while (*got_author && *got_author != '@')
651 got_author++;
652 if (*got_author != '@') {
653 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
654 goto done;
656 while (*got_author && *got_author != '>')
657 got_author++;
658 if (*got_author != '>')
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 done:
661 if (err) {
662 free(*author);
663 *author = NULL;
665 return err;
668 static const struct got_error *
669 get_gitconfig_path(char **gitconfig_path)
671 const char *homedir = getenv("HOME");
673 *gitconfig_path = NULL;
674 if (homedir) {
675 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
676 return got_error_from_errno("asprintf");
679 return NULL;
682 static const struct got_error *
683 cmd_import(int argc, char *argv[])
685 const struct got_error *error = NULL;
686 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
687 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
688 const char *branch_name = "main";
689 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
690 struct got_repository *repo = NULL;
691 struct got_reference *branch_ref = NULL, *head_ref = NULL;
692 struct got_object_id *new_commit_id = NULL;
693 int ch;
694 struct got_pathlist_head ignores;
695 struct got_pathlist_entry *pe;
696 int preserve_logmsg = 0;
698 TAILQ_INIT(&ignores);
700 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
701 switch (ch) {
702 case 'b':
703 branch_name = optarg;
704 break;
705 case 'm':
706 logmsg = strdup(optarg);
707 if (logmsg == NULL) {
708 error = got_error_from_errno("strdup");
709 goto done;
711 break;
712 case 'r':
713 repo_path = realpath(optarg, NULL);
714 if (repo_path == NULL) {
715 error = got_error_from_errno2("realpath",
716 optarg);
717 goto done;
719 break;
720 case 'I':
721 if (optarg[0] == '\0')
722 break;
723 error = got_pathlist_insert(&pe, &ignores, optarg,
724 NULL);
725 if (error)
726 goto done;
727 break;
728 default:
729 usage_import();
730 /* NOTREACHED */
734 argc -= optind;
735 argv += optind;
737 #ifndef PROFILE
738 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
739 "unveil",
740 NULL) == -1)
741 err(1, "pledge");
742 #endif
743 if (argc != 1)
744 usage_import();
746 if (repo_path == NULL) {
747 repo_path = getcwd(NULL, 0);
748 if (repo_path == NULL)
749 return got_error_from_errno("getcwd");
751 got_path_strip_trailing_slashes(repo_path);
752 error = get_gitconfig_path(&gitconfig_path);
753 if (error)
754 goto done;
755 error = got_repo_open(&repo, repo_path, gitconfig_path);
756 if (error)
757 goto done;
759 error = get_author(&author, repo, NULL);
760 if (error)
761 return error;
763 /*
764 * Don't let the user create a branch name with a leading '-'.
765 * While technically a valid reference name, this case is usually
766 * an unintended typo.
767 */
768 if (branch_name[0] == '-')
769 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
772 error = got_error_from_errno("asprintf");
773 goto done;
776 error = got_ref_open(&branch_ref, repo, refname, 0);
777 if (error) {
778 if (error->code != GOT_ERR_NOT_REF)
779 goto done;
780 } else {
781 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
782 "import target branch already exists");
783 goto done;
786 path_dir = realpath(argv[0], NULL);
787 if (path_dir == NULL) {
788 error = got_error_from_errno2("realpath", argv[0]);
789 goto done;
791 got_path_strip_trailing_slashes(path_dir);
793 /*
794 * unveil(2) traverses exec(2); if an editor is used we have
795 * to apply unveil after the log message has been written.
796 */
797 if (logmsg == NULL || strlen(logmsg) == 0) {
798 error = get_editor(&editor);
799 if (error)
800 goto done;
801 free(logmsg);
802 error = collect_import_msg(&logmsg, &logmsg_path, editor,
803 path_dir, refname);
804 if (error) {
805 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
806 logmsg_path != NULL)
807 preserve_logmsg = 1;
808 goto done;
812 if (unveil(path_dir, "r") != 0) {
813 error = got_error_from_errno2("unveil", path_dir);
814 if (logmsg_path)
815 preserve_logmsg = 1;
816 goto done;
819 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
820 if (error) {
821 if (logmsg_path)
822 preserve_logmsg = 1;
823 goto done;
826 error = got_repo_import(&new_commit_id, path_dir, logmsg,
827 author, &ignores, repo, import_progress, NULL);
828 if (error) {
829 if (logmsg_path)
830 preserve_logmsg = 1;
831 goto done;
834 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
835 if (error) {
836 if (logmsg_path)
837 preserve_logmsg = 1;
838 goto done;
841 error = got_ref_write(branch_ref, repo);
842 if (error) {
843 if (logmsg_path)
844 preserve_logmsg = 1;
845 goto done;
848 error = got_object_id_str(&id_str, new_commit_id);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
856 if (error) {
857 if (error->code != GOT_ERR_NOT_REF) {
858 if (logmsg_path)
859 preserve_logmsg = 1;
860 goto done;
863 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
864 branch_ref);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_write(head_ref, repo);
872 if (error) {
873 if (logmsg_path)
874 preserve_logmsg = 1;
875 goto done;
879 printf("Created branch %s with commit %s\n",
880 got_ref_get_name(branch_ref), id_str);
881 done:
882 if (preserve_logmsg) {
883 fprintf(stderr, "%s: log message preserved in %s\n",
884 getprogname(), logmsg_path);
885 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
886 error = got_error_from_errno2("unlink", logmsg_path);
887 free(logmsg);
888 free(logmsg_path);
889 free(repo_path);
890 free(editor);
891 free(refname);
892 free(new_commit_id);
893 free(id_str);
894 free(author);
895 free(gitconfig_path);
896 if (branch_ref)
897 got_ref_close(branch_ref);
898 if (head_ref)
899 got_ref_close(head_ref);
900 return error;
903 __dead static void
904 usage_clone(void)
906 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
907 "[-R reference] repository-url [directory]\n", getprogname());
908 exit(1);
911 struct got_fetch_progress_arg {
912 char last_scaled_size[FMT_SCALED_STRSIZE];
913 int last_p_indexed;
914 int last_p_resolved;
915 int verbosity;
917 struct got_repository *repo;
919 int create_configs;
920 int configs_created;
921 struct {
922 struct got_pathlist_head *symrefs;
923 struct got_pathlist_head *wanted_branches;
924 const char *proto;
925 const char *host;
926 const char *port;
927 const char *remote_repo_path;
928 const char *git_url;
929 int fetch_all_branches;
930 int mirror_references;
931 } config_info;
932 };
934 /* XXX forward declaration */
935 static const struct got_error *
936 create_config_files(const char *proto, const char *host, const char *port,
937 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
938 int mirror_references, struct got_pathlist_head *symrefs,
939 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
941 static const struct got_error *
942 fetch_progress(void *arg, const char *message, off_t packfile_size,
943 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
945 const struct got_error *err = NULL;
946 struct got_fetch_progress_arg *a = arg;
947 char scaled_size[FMT_SCALED_STRSIZE];
948 int p_indexed, p_resolved;
949 int print_size = 0, print_indexed = 0, print_resolved = 0;
951 /*
952 * In order to allow a failed clone to be resumed with 'got fetch'
953 * we try to create configuration files as soon as possible.
954 * Once the server has sent information about its default branch
955 * we have all required information.
956 */
957 if (a->create_configs && !a->configs_created &&
958 !TAILQ_EMPTY(a->config_info.symrefs)) {
959 err = create_config_files(a->config_info.proto,
960 a->config_info.host, a->config_info.port,
961 a->config_info.remote_repo_path,
962 a->config_info.git_url,
963 a->config_info.fetch_all_branches,
964 a->config_info.mirror_references,
965 a->config_info.symrefs,
966 a->config_info.wanted_branches, a->repo);
967 if (err)
968 return err;
969 a->configs_created = 1;
972 if (a->verbosity < 0)
973 return NULL;
975 if (message && message[0] != '\0') {
976 printf("\rserver: %s", message);
977 fflush(stdout);
978 return NULL;
981 if (packfile_size > 0 || nobj_indexed > 0) {
982 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
983 (a->last_scaled_size[0] == '\0' ||
984 strcmp(scaled_size, a->last_scaled_size)) != 0) {
985 print_size = 1;
986 if (strlcpy(a->last_scaled_size, scaled_size,
987 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
988 return got_error(GOT_ERR_NO_SPACE);
990 if (nobj_indexed > 0) {
991 p_indexed = (nobj_indexed * 100) / nobj_total;
992 if (p_indexed != a->last_p_indexed) {
993 a->last_p_indexed = p_indexed;
994 print_indexed = 1;
995 print_size = 1;
998 if (nobj_resolved > 0) {
999 p_resolved = (nobj_resolved * 100) /
1000 (nobj_total - nobj_loose);
1001 if (p_resolved != a->last_p_resolved) {
1002 a->last_p_resolved = p_resolved;
1003 print_resolved = 1;
1004 print_indexed = 1;
1005 print_size = 1;
1010 if (print_size || print_indexed || print_resolved)
1011 printf("\r");
1012 if (print_size)
1013 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1014 if (print_indexed)
1015 printf("; indexing %d%%", p_indexed);
1016 if (print_resolved)
1017 printf("; resolving deltas %d%%", p_resolved);
1018 if (print_size || print_indexed || print_resolved)
1019 fflush(stdout);
1021 return NULL;
1024 static const struct got_error *
1025 create_symref(const char *refname, struct got_reference *target_ref,
1026 int verbosity, struct got_repository *repo)
1028 const struct got_error *err;
1029 struct got_reference *head_symref;
1031 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1032 if (err)
1033 return err;
1035 err = got_ref_write(head_symref, repo);
1036 if (err == NULL && verbosity > 0) {
1037 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1038 got_ref_get_name(target_ref));
1040 got_ref_close(head_symref);
1041 return err;
1044 static const struct got_error *
1045 list_remote_refs(struct got_pathlist_head *symrefs,
1046 struct got_pathlist_head *refs)
1048 const struct got_error *err;
1049 struct got_pathlist_entry *pe;
1051 TAILQ_FOREACH(pe, symrefs, entry) {
1052 const char *refname = pe->path;
1053 const char *targetref = pe->data;
1055 printf("%s: %s\n", refname, targetref);
1058 TAILQ_FOREACH(pe, refs, entry) {
1059 const char *refname = pe->path;
1060 struct got_object_id *id = pe->data;
1061 char *id_str;
1063 err = got_object_id_str(&id_str, id);
1064 if (err)
1065 return err;
1066 printf("%s: %s\n", refname, id_str);
1067 free(id_str);
1070 return NULL;
1073 static const struct got_error *
1074 create_ref(const char *refname, struct got_object_id *id,
1075 int verbosity, struct got_repository *repo)
1077 const struct got_error *err = NULL;
1078 struct got_reference *ref;
1079 char *id_str;
1081 err = got_object_id_str(&id_str, id);
1082 if (err)
1083 return err;
1085 err = got_ref_alloc(&ref, refname, id);
1086 if (err)
1087 goto done;
1089 err = got_ref_write(ref, repo);
1090 got_ref_close(ref);
1092 if (err == NULL && verbosity >= 0)
1093 printf("Created reference %s: %s\n", refname, id_str);
1094 done:
1095 free(id_str);
1096 return err;
1099 static int
1100 match_wanted_ref(const char *refname, const char *wanted_ref)
1102 if (strncmp(refname, "refs/", 5) != 0)
1103 return 0;
1104 refname += 5;
1107 * Prevent fetching of references that won't make any
1108 * sense outside of the remote repository's context.
1110 if (strncmp(refname, "got/", 4) == 0)
1111 return 0;
1112 if (strncmp(refname, "remotes/", 8) == 0)
1113 return 0;
1115 if (strncmp(wanted_ref, "refs/", 5) == 0)
1116 wanted_ref += 5;
1118 /* Allow prefix match. */
1119 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1120 return 1;
1122 /* Allow exact match. */
1123 return (strcmp(refname, wanted_ref) == 0);
1126 static int
1127 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1129 struct got_pathlist_entry *pe;
1131 TAILQ_FOREACH(pe, wanted_refs, entry) {
1132 if (match_wanted_ref(refname, pe->path))
1133 return 1;
1136 return 0;
1139 static const struct got_error *
1140 create_wanted_ref(const char *refname, struct got_object_id *id,
1141 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1143 const struct got_error *err;
1144 char *remote_refname;
1146 if (strncmp("refs/", refname, 5) == 0)
1147 refname += 5;
1149 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1150 remote_repo_name, refname) == -1)
1151 return got_error_from_errno("asprintf");
1153 err = create_ref(remote_refname, id, verbosity, repo);
1154 free(remote_refname);
1155 return err;
1158 static const struct got_error *
1159 create_gotconfig(const char *proto, const char *host, const char *port,
1160 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1161 struct got_repository *repo)
1163 const struct got_error *err = NULL;
1164 char *gotconfig_path = NULL;
1165 char *gotconfig = NULL;
1166 FILE *gotconfig_file = NULL;
1167 ssize_t n;
1169 /* Create got.conf(5). */
1170 gotconfig_path = got_repo_get_path_gotconfig(repo);
1171 if (gotconfig_path == NULL) {
1172 err = got_error_from_errno("got_repo_get_path_gotconfig");
1173 goto done;
1175 gotconfig_file = fopen(gotconfig_path, "a");
1176 if (gotconfig_file == NULL) {
1177 err = got_error_from_errno2("fopen", gotconfig_path);
1178 goto done;
1180 if (asprintf(&gotconfig,
1181 "remote \"%s\" {\n"
1182 "\tserver %s\n"
1183 "\tprotocol %s\n"
1184 "%s%s%s"
1185 "\trepository \"%s\"\n"
1186 "%s"
1187 "}\n",
1188 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1189 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1190 remote_repo_path,
1191 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1196 if (n != strlen(gotconfig)) {
1197 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1198 goto done;
1201 done:
1202 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1203 err = got_error_from_errno2("fclose", gotconfig_path);
1204 free(gotconfig_path);
1205 return err;
1208 static const struct got_error *
1209 create_gitconfig(const char *git_url, const char *default_branch,
1210 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1212 const struct got_error *err = NULL;
1213 char *gitconfig_path = NULL;
1214 char *gitconfig = NULL;
1215 FILE *gitconfig_file = NULL;
1216 ssize_t n;
1218 /* Create a config file Git can understand. */
1219 gitconfig_path = got_repo_get_path_gitconfig(repo);
1220 if (gitconfig_path == NULL) {
1221 err = got_error_from_errno("got_repo_get_path_gitconfig");
1222 goto done;
1224 gitconfig_file = fopen(gitconfig_path, "a");
1225 if (gitconfig_file == NULL) {
1226 err = got_error_from_errno2("fopen", gitconfig_path);
1227 goto done;
1229 if (mirror_references) {
1230 if (asprintf(&gitconfig,
1231 "[remote \"%s\"]\n"
1232 "\turl = %s\n"
1233 "\tfetch = +refs/*:refs/*\n"
1234 "\tmirror = true\n",
1235 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1236 err = got_error_from_errno("asprintf");
1237 goto done;
1239 } else if (fetch_all_branches) {
1240 if (asprintf(&gitconfig,
1241 "[remote \"%s\"]\n"
1242 "\turl = %s\n"
1243 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1244 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1245 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1246 err = got_error_from_errno("asprintf");
1247 goto done;
1249 } else {
1250 const char *branchname;
1253 * If the server specified a default branch, use just that one.
1254 * Otherwise fall back to fetching all branches on next fetch.
1256 if (default_branch) {
1257 branchname = default_branch;
1258 if (strncmp(branchname, "refs/heads/", 11) == 0)
1259 branchname += 11;
1260 } else
1261 branchname = "*"; /* fall back to all branches */
1262 if (asprintf(&gitconfig,
1263 "[remote \"%s\"]\n"
1264 "\turl = %s\n"
1265 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1266 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1267 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1268 branchname) == -1) {
1269 err = got_error_from_errno("asprintf");
1270 goto done;
1273 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1274 if (n != strlen(gitconfig)) {
1275 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1276 goto done;
1278 done:
1279 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1280 err = got_error_from_errno2("fclose", gitconfig_path);
1281 free(gitconfig_path);
1282 return err;
1285 static const struct got_error *
1286 create_config_files(const char *proto, const char *host, const char *port,
1287 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1288 int mirror_references, struct got_pathlist_head *symrefs,
1289 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1291 const struct got_error *err = NULL;
1292 const char *default_branch = NULL;
1293 struct got_pathlist_entry *pe;
1296 * If we asked for a set of wanted branches then use the first
1297 * one of those.
1299 if (!TAILQ_EMPTY(wanted_branches)) {
1300 pe = TAILQ_FIRST(wanted_branches);
1301 default_branch = pe->path;
1302 } else {
1303 /* First HEAD ref listed by server is the default branch. */
1304 TAILQ_FOREACH(pe, symrefs, entry) {
1305 const char *refname = pe->path;
1306 const char *target = pe->data;
1308 if (strcmp(refname, GOT_REF_HEAD) != 0)
1309 continue;
1311 default_branch = target;
1312 break;
1316 /* Create got.conf(5). */
1317 err = create_gotconfig(proto, host, port, remote_repo_path,
1318 fetch_all_branches, mirror_references, repo);
1319 if (err)
1320 return err;
1322 /* Create a config file Git can understand. */
1323 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1324 mirror_references, repo);
1327 static const struct got_error *
1328 cmd_clone(int argc, char *argv[])
1330 const struct got_error *error = NULL;
1331 const char *uri, *dirname;
1332 char *proto, *host, *port, *repo_name, *server_path;
1333 char *default_destdir = NULL, *id_str = NULL;
1334 const char *repo_path;
1335 struct got_repository *repo = NULL;
1336 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1337 struct got_pathlist_entry *pe;
1338 struct got_object_id *pack_hash = NULL;
1339 int ch, fetchfd = -1, fetchstatus;
1340 pid_t fetchpid = -1;
1341 struct got_fetch_progress_arg fpa;
1342 char *git_url = NULL;
1343 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1344 int list_refs_only = 0;
1346 TAILQ_INIT(&refs);
1347 TAILQ_INIT(&symrefs);
1348 TAILQ_INIT(&wanted_branches);
1349 TAILQ_INIT(&wanted_refs);
1351 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1352 switch (ch) {
1353 case 'a':
1354 fetch_all_branches = 1;
1355 break;
1356 case 'b':
1357 error = got_pathlist_append(&wanted_branches,
1358 optarg, NULL);
1359 if (error)
1360 return error;
1361 break;
1362 case 'l':
1363 list_refs_only = 1;
1364 break;
1365 case 'm':
1366 mirror_references = 1;
1367 break;
1368 case 'v':
1369 if (verbosity < 0)
1370 verbosity = 0;
1371 else if (verbosity < 3)
1372 verbosity++;
1373 break;
1374 case 'q':
1375 verbosity = -1;
1376 break;
1377 case 'R':
1378 error = got_pathlist_append(&wanted_refs,
1379 optarg, NULL);
1380 if (error)
1381 return error;
1382 break;
1383 default:
1384 usage_clone();
1385 break;
1388 argc -= optind;
1389 argv += optind;
1391 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1392 errx(1, "-a and -b options are mutually exclusive");
1393 if (list_refs_only) {
1394 if (!TAILQ_EMPTY(&wanted_branches))
1395 errx(1, "-l and -b options are mutually exclusive");
1396 if (fetch_all_branches)
1397 errx(1, "-l and -a options are mutually exclusive");
1398 if (mirror_references)
1399 errx(1, "-l and -m options are mutually exclusive");
1400 if (verbosity == -1)
1401 errx(1, "-l and -q options are mutually exclusive");
1402 if (!TAILQ_EMPTY(&wanted_refs))
1403 errx(1, "-l and -R options are mutually exclusive");
1406 uri = argv[0];
1408 if (argc == 1)
1409 dirname = NULL;
1410 else if (argc == 2)
1411 dirname = argv[1];
1412 else
1413 usage_clone();
1415 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1416 &repo_name, uri);
1417 if (error)
1418 goto done;
1420 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1421 host, port ? ":" : "", port ? port : "",
1422 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1423 error = got_error_from_errno("asprintf");
1424 goto done;
1427 if (strcmp(proto, "git") == 0) {
1428 #ifndef PROFILE
1429 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1430 "sendfd dns inet unveil", NULL) == -1)
1431 err(1, "pledge");
1432 #endif
1433 } else if (strcmp(proto, "git+ssh") == 0 ||
1434 strcmp(proto, "ssh") == 0) {
1435 #ifndef PROFILE
1436 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1437 "sendfd unveil", NULL) == -1)
1438 err(1, "pledge");
1439 #endif
1440 } else if (strcmp(proto, "http") == 0 ||
1441 strcmp(proto, "git+http") == 0) {
1442 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1443 goto done;
1444 } else {
1445 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1446 goto done;
1448 if (dirname == NULL) {
1449 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1450 error = got_error_from_errno("asprintf");
1451 goto done;
1453 repo_path = default_destdir;
1454 } else
1455 repo_path = dirname;
1457 if (!list_refs_only) {
1458 error = got_path_mkdir(repo_path);
1459 if (error &&
1460 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1461 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1462 goto done;
1463 if (!got_path_dir_is_empty(repo_path)) {
1464 error = got_error_path(repo_path,
1465 GOT_ERR_DIR_NOT_EMPTY);
1466 goto done;
1470 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1471 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1472 error = got_error_from_errno2("unveil",
1473 GOT_FETCH_PATH_SSH);
1474 goto done;
1477 error = apply_unveil(repo_path, 0, NULL);
1478 if (error)
1479 goto done;
1481 if (verbosity >= 0)
1482 printf("Connecting to %s%s%s\n", host,
1483 port ? ":" : "", port ? port : "");
1485 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1486 server_path, verbosity);
1487 if (error)
1488 goto done;
1490 if (!list_refs_only) {
1491 error = got_repo_init(repo_path);
1492 if (error)
1493 goto done;
1494 error = got_repo_open(&repo, repo_path, NULL);
1495 if (error)
1496 goto done;
1499 fpa.last_scaled_size[0] = '\0';
1500 fpa.last_p_indexed = -1;
1501 fpa.last_p_resolved = -1;
1502 fpa.verbosity = verbosity;
1503 fpa.create_configs = 1;
1504 fpa.configs_created = 0;
1505 fpa.repo = repo;
1506 fpa.config_info.symrefs = &symrefs;
1507 fpa.config_info.wanted_branches = &wanted_branches;
1508 fpa.config_info.proto = proto;
1509 fpa.config_info.host = host;
1510 fpa.config_info.port = port;
1511 fpa.config_info.remote_repo_path = server_path;
1512 fpa.config_info.git_url = git_url;
1513 fpa.config_info.fetch_all_branches = fetch_all_branches;
1514 fpa.config_info.mirror_references = mirror_references;
1515 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1516 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1517 fetch_all_branches, &wanted_branches, &wanted_refs,
1518 list_refs_only, verbosity, fetchfd, repo,
1519 fetch_progress, &fpa);
1520 if (error)
1521 goto done;
1523 if (list_refs_only) {
1524 error = list_remote_refs(&symrefs, &refs);
1525 goto done;
1528 error = got_object_id_str(&id_str, pack_hash);
1529 if (error)
1530 goto done;
1531 if (verbosity >= 0)
1532 printf("\nFetched %s.pack\n", id_str);
1533 free(id_str);
1535 /* Set up references provided with the pack file. */
1536 TAILQ_FOREACH(pe, &refs, entry) {
1537 const char *refname = pe->path;
1538 struct got_object_id *id = pe->data;
1539 char *remote_refname;
1541 if (is_wanted_ref(&wanted_refs, refname) &&
1542 !mirror_references) {
1543 error = create_wanted_ref(refname, id,
1544 GOT_FETCH_DEFAULT_REMOTE_NAME,
1545 verbosity - 1, repo);
1546 if (error)
1547 goto done;
1548 continue;
1551 error = create_ref(refname, id, verbosity - 1, repo);
1552 if (error)
1553 goto done;
1555 if (mirror_references)
1556 continue;
1558 if (strncmp("refs/heads/", refname, 11) != 0)
1559 continue;
1561 if (asprintf(&remote_refname,
1562 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1563 refname + 11) == -1) {
1564 error = got_error_from_errno("asprintf");
1565 goto done;
1567 error = create_ref(remote_refname, id, verbosity - 1, repo);
1568 free(remote_refname);
1569 if (error)
1570 goto done;
1573 /* Set the HEAD reference if the server provided one. */
1574 TAILQ_FOREACH(pe, &symrefs, entry) {
1575 struct got_reference *target_ref;
1576 const char *refname = pe->path;
1577 const char *target = pe->data;
1578 char *remote_refname = NULL, *remote_target = NULL;
1580 if (strcmp(refname, GOT_REF_HEAD) != 0)
1581 continue;
1583 error = got_ref_open(&target_ref, repo, target, 0);
1584 if (error) {
1585 if (error->code == GOT_ERR_NOT_REF) {
1586 error = NULL;
1587 continue;
1589 goto done;
1592 error = create_symref(refname, target_ref, verbosity, repo);
1593 got_ref_close(target_ref);
1594 if (error)
1595 goto done;
1597 if (mirror_references)
1598 continue;
1600 if (strncmp("refs/heads/", target, 11) != 0)
1601 continue;
1603 if (asprintf(&remote_refname,
1604 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1605 refname) == -1) {
1606 error = got_error_from_errno("asprintf");
1607 goto done;
1609 if (asprintf(&remote_target,
1610 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1611 target + 11) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 free(remote_refname);
1614 goto done;
1616 error = got_ref_open(&target_ref, repo, remote_target, 0);
1617 if (error) {
1618 free(remote_refname);
1619 free(remote_target);
1620 if (error->code == GOT_ERR_NOT_REF) {
1621 error = NULL;
1622 continue;
1624 goto done;
1626 error = create_symref(remote_refname, target_ref,
1627 verbosity - 1, repo);
1628 free(remote_refname);
1629 free(remote_target);
1630 got_ref_close(target_ref);
1631 if (error)
1632 goto done;
1634 if (pe == NULL) {
1636 * We failed to set the HEAD reference. If we asked for
1637 * a set of wanted branches use the first of one of those
1638 * which could be fetched instead.
1640 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1641 const char *target = pe->path;
1642 struct got_reference *target_ref;
1644 error = got_ref_open(&target_ref, repo, target, 0);
1645 if (error) {
1646 if (error->code == GOT_ERR_NOT_REF) {
1647 error = NULL;
1648 continue;
1650 goto done;
1653 error = create_symref(GOT_REF_HEAD, target_ref,
1654 verbosity, repo);
1655 got_ref_close(target_ref);
1656 if (error)
1657 goto done;
1658 break;
1662 if (verbosity >= 0)
1663 printf("Created %s repository '%s'\n",
1664 mirror_references ? "mirrored" : "cloned", repo_path);
1665 done:
1666 if (fetchpid > 0) {
1667 if (kill(fetchpid, SIGTERM) == -1)
1668 error = got_error_from_errno("kill");
1669 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1670 error = got_error_from_errno("waitpid");
1672 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1673 error = got_error_from_errno("close");
1674 if (repo)
1675 got_repo_close(repo);
1676 TAILQ_FOREACH(pe, &refs, entry) {
1677 free((void *)pe->path);
1678 free(pe->data);
1680 got_pathlist_free(&refs);
1681 TAILQ_FOREACH(pe, &symrefs, entry) {
1682 free((void *)pe->path);
1683 free(pe->data);
1685 got_pathlist_free(&symrefs);
1686 got_pathlist_free(&wanted_branches);
1687 got_pathlist_free(&wanted_refs);
1688 free(pack_hash);
1689 free(proto);
1690 free(host);
1691 free(port);
1692 free(server_path);
1693 free(repo_name);
1694 free(default_destdir);
1695 free(git_url);
1696 return error;
1699 static const struct got_error *
1700 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1701 int replace_tags, int verbosity, struct got_repository *repo)
1703 const struct got_error *err = NULL;
1704 char *new_id_str = NULL;
1705 struct got_object_id *old_id = NULL;
1707 err = got_object_id_str(&new_id_str, new_id);
1708 if (err)
1709 goto done;
1711 if (!replace_tags &&
1712 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1713 err = got_ref_resolve(&old_id, repo, ref);
1714 if (err)
1715 goto done;
1716 if (got_object_id_cmp(old_id, new_id) == 0)
1717 goto done;
1718 if (verbosity >= 0) {
1719 printf("Rejecting update of existing tag %s: %s\n",
1720 got_ref_get_name(ref), new_id_str);
1722 goto done;
1725 if (got_ref_is_symbolic(ref)) {
1726 if (verbosity >= 0) {
1727 printf("Replacing reference %s: %s\n",
1728 got_ref_get_name(ref),
1729 got_ref_get_symref_target(ref));
1731 err = got_ref_change_symref_to_ref(ref, new_id);
1732 if (err)
1733 goto done;
1734 err = got_ref_write(ref, repo);
1735 if (err)
1736 goto done;
1737 } else {
1738 err = got_ref_resolve(&old_id, repo, ref);
1739 if (err)
1740 goto done;
1741 if (got_object_id_cmp(old_id, new_id) == 0)
1742 goto done;
1744 err = got_ref_change_ref(ref, new_id);
1745 if (err)
1746 goto done;
1747 err = got_ref_write(ref, repo);
1748 if (err)
1749 goto done;
1752 if (verbosity >= 0)
1753 printf("Updated %s: %s\n", got_ref_get_name(ref),
1754 new_id_str);
1755 done:
1756 free(old_id);
1757 free(new_id_str);
1758 return err;
1761 static const struct got_error *
1762 update_symref(const char *refname, struct got_reference *target_ref,
1763 int verbosity, struct got_repository *repo)
1765 const struct got_error *err = NULL, *unlock_err;
1766 struct got_reference *symref;
1767 int symref_is_locked = 0;
1769 err = got_ref_open(&symref, repo, refname, 1);
1770 if (err) {
1771 if (err->code != GOT_ERR_NOT_REF)
1772 return err;
1773 err = got_ref_alloc_symref(&symref, refname, target_ref);
1774 if (err)
1775 goto done;
1777 err = got_ref_write(symref, repo);
1778 if (err)
1779 goto done;
1781 if (verbosity >= 0)
1782 printf("Created reference %s: %s\n",
1783 got_ref_get_name(symref),
1784 got_ref_get_symref_target(symref));
1785 } else {
1786 symref_is_locked = 1;
1788 if (strcmp(got_ref_get_symref_target(symref),
1789 got_ref_get_name(target_ref)) == 0)
1790 goto done;
1792 err = got_ref_change_symref(symref,
1793 got_ref_get_name(target_ref));
1794 if (err)
1795 goto done;
1797 err = got_ref_write(symref, repo);
1798 if (err)
1799 goto done;
1801 if (verbosity >= 0)
1802 printf("Updated %s: %s\n", got_ref_get_name(symref),
1803 got_ref_get_symref_target(symref));
1806 done:
1807 if (symref_is_locked) {
1808 unlock_err = got_ref_unlock(symref);
1809 if (unlock_err && err == NULL)
1810 err = unlock_err;
1812 got_ref_close(symref);
1813 return err;
1816 __dead static void
1817 usage_fetch(void)
1819 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1820 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1821 "[remote-repository-name]\n",
1822 getprogname());
1823 exit(1);
1826 static const struct got_error *
1827 delete_missing_ref(struct got_reference *ref,
1828 int verbosity, struct got_repository *repo)
1830 const struct got_error *err = NULL;
1831 struct got_object_id *id = NULL;
1832 char *id_str = NULL;
1834 if (got_ref_is_symbolic(ref)) {
1835 err = got_ref_delete(ref, repo);
1836 if (err)
1837 return err;
1838 if (verbosity >= 0) {
1839 printf("Deleted reference %s: %s\n",
1840 got_ref_get_name(ref),
1841 got_ref_get_symref_target(ref));
1843 } else {
1844 err = got_ref_resolve(&id, repo, ref);
1845 if (err)
1846 return err;
1847 err = got_object_id_str(&id_str, id);
1848 if (err)
1849 goto done;
1851 err = got_ref_delete(ref, repo);
1852 if (err)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Deleted reference %s: %s\n",
1856 got_ref_get_name(ref), id_str);
1859 done:
1860 free(id);
1861 free(id_str);
1862 return NULL;
1865 static const struct got_error *
1866 delete_missing_refs(struct got_pathlist_head *their_refs,
1867 struct got_pathlist_head *their_symrefs,
1868 const struct got_remote_repo *remote,
1869 int verbosity, struct got_repository *repo)
1871 const struct got_error *err = NULL, *unlock_err;
1872 struct got_reflist_head my_refs;
1873 struct got_reflist_entry *re;
1874 struct got_pathlist_entry *pe;
1875 char *remote_namespace = NULL;
1876 char *local_refname = NULL;
1878 SIMPLEQ_INIT(&my_refs);
1880 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1881 == -1)
1882 return got_error_from_errno("asprintf");
1884 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1885 if (err)
1886 goto done;
1888 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1889 const char *refname = got_ref_get_name(re->ref);
1891 if (!remote->mirror_references) {
1892 if (strncmp(refname, remote_namespace,
1893 strlen(remote_namespace)) == 0) {
1894 if (strcmp(refname + strlen(remote_namespace),
1895 GOT_REF_HEAD) == 0)
1896 continue;
1897 if (asprintf(&local_refname, "refs/heads/%s",
1898 refname + strlen(remote_namespace)) == -1) {
1899 err = got_error_from_errno("asprintf");
1900 goto done;
1902 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1903 continue;
1906 TAILQ_FOREACH(pe, their_refs, entry) {
1907 if (strcmp(local_refname, pe->path) == 0)
1908 break;
1910 if (pe != NULL)
1911 continue;
1913 TAILQ_FOREACH(pe, their_symrefs, entry) {
1914 if (strcmp(local_refname, pe->path) == 0)
1915 break;
1917 if (pe != NULL)
1918 continue;
1920 err = delete_missing_ref(re->ref, verbosity, repo);
1921 if (err)
1922 break;
1924 if (local_refname) {
1925 struct got_reference *ref;
1926 err = got_ref_open(&ref, repo, local_refname, 1);
1927 if (err) {
1928 if (err->code != GOT_ERR_NOT_REF)
1929 break;
1930 free(local_refname);
1931 local_refname = NULL;
1932 continue;
1934 err = delete_missing_ref(ref, verbosity, repo);
1935 if (err)
1936 break;
1937 unlock_err = got_ref_unlock(ref);
1938 got_ref_close(ref);
1939 if (unlock_err && err == NULL) {
1940 err = unlock_err;
1941 break;
1944 free(local_refname);
1945 local_refname = NULL;
1948 done:
1949 free(remote_namespace);
1950 free(local_refname);
1951 return err;
1954 static const struct got_error *
1955 update_wanted_ref(const char *refname, struct got_object_id *id,
1956 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1958 const struct got_error *err, *unlock_err;
1959 char *remote_refname;
1960 struct got_reference *ref;
1962 if (strncmp("refs/", refname, 5) == 0)
1963 refname += 5;
1965 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1966 remote_repo_name, refname) == -1)
1967 return got_error_from_errno("asprintf");
1969 err = got_ref_open(&ref, repo, remote_refname, 1);
1970 if (err) {
1971 if (err->code != GOT_ERR_NOT_REF)
1972 goto done;
1973 err = create_ref(remote_refname, id, verbosity, repo);
1974 } else {
1975 err = update_ref(ref, id, 0, verbosity, repo);
1976 unlock_err = got_ref_unlock(ref);
1977 if (unlock_err && err == NULL)
1978 err = unlock_err;
1979 got_ref_close(ref);
1981 done:
1982 free(remote_refname);
1983 return err;
1986 static const struct got_error *
1987 cmd_fetch(int argc, char *argv[])
1989 const struct got_error *error = NULL, *unlock_err;
1990 char *cwd = NULL, *repo_path = NULL;
1991 const char *remote_name;
1992 char *proto = NULL, *host = NULL, *port = NULL;
1993 char *repo_name = NULL, *server_path = NULL;
1994 const struct got_remote_repo *remotes, *remote = NULL;
1995 int nremotes;
1996 char *id_str = NULL;
1997 struct got_repository *repo = NULL;
1998 struct got_worktree *worktree = NULL;
1999 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2000 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2001 struct got_pathlist_entry *pe;
2002 struct got_object_id *pack_hash = NULL;
2003 int i, ch, fetchfd = -1, fetchstatus;
2004 pid_t fetchpid = -1;
2005 struct got_fetch_progress_arg fpa;
2006 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2007 int delete_refs = 0, replace_tags = 0;
2009 TAILQ_INIT(&refs);
2010 TAILQ_INIT(&symrefs);
2011 TAILQ_INIT(&wanted_branches);
2012 TAILQ_INIT(&wanted_refs);
2014 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2015 switch (ch) {
2016 case 'a':
2017 fetch_all_branches = 1;
2018 break;
2019 case 'b':
2020 error = got_pathlist_append(&wanted_branches,
2021 optarg, NULL);
2022 if (error)
2023 return error;
2024 break;
2025 case 'd':
2026 delete_refs = 1;
2027 break;
2028 case 'l':
2029 list_refs_only = 1;
2030 break;
2031 case 'r':
2032 repo_path = realpath(optarg, NULL);
2033 if (repo_path == NULL)
2034 return got_error_from_errno2("realpath",
2035 optarg);
2036 got_path_strip_trailing_slashes(repo_path);
2037 break;
2038 case 't':
2039 replace_tags = 1;
2040 break;
2041 case 'v':
2042 if (verbosity < 0)
2043 verbosity = 0;
2044 else if (verbosity < 3)
2045 verbosity++;
2046 break;
2047 case 'q':
2048 verbosity = -1;
2049 break;
2050 case 'R':
2051 error = got_pathlist_append(&wanted_refs,
2052 optarg, NULL);
2053 if (error)
2054 return error;
2055 break;
2056 default:
2057 usage_fetch();
2058 break;
2061 argc -= optind;
2062 argv += optind;
2064 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2065 errx(1, "-a and -b options are mutually exclusive");
2066 if (list_refs_only) {
2067 if (!TAILQ_EMPTY(&wanted_branches))
2068 errx(1, "-l and -b options are mutually exclusive");
2069 if (fetch_all_branches)
2070 errx(1, "-l and -a options are mutually exclusive");
2071 if (delete_refs)
2072 errx(1, "-l and -d options are mutually exclusive");
2073 if (verbosity == -1)
2074 errx(1, "-l and -q options are mutually exclusive");
2077 if (argc == 0)
2078 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2079 else if (argc == 1)
2080 remote_name = argv[0];
2081 else
2082 usage_fetch();
2084 cwd = getcwd(NULL, 0);
2085 if (cwd == NULL) {
2086 error = got_error_from_errno("getcwd");
2087 goto done;
2090 if (repo_path == NULL) {
2091 error = got_worktree_open(&worktree, cwd);
2092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2093 goto done;
2094 else
2095 error = NULL;
2096 if (worktree) {
2097 repo_path =
2098 strdup(got_worktree_get_repo_path(worktree));
2099 if (repo_path == NULL)
2100 error = got_error_from_errno("strdup");
2101 if (error)
2102 goto done;
2103 } else {
2104 repo_path = strdup(cwd);
2105 if (repo_path == NULL) {
2106 error = got_error_from_errno("strdup");
2107 goto done;
2112 error = got_repo_open(&repo, repo_path, NULL);
2113 if (error)
2114 goto done;
2116 if (worktree) {
2117 worktree_conf = got_worktree_get_gotconfig(worktree);
2118 if (worktree_conf) {
2119 got_gotconfig_get_remotes(&nremotes, &remotes,
2120 worktree_conf);
2121 for (i = 0; i < nremotes; i++) {
2122 if (strcmp(remotes[i].name, remote_name) == 0) {
2123 remote = &remotes[i];
2124 break;
2129 if (remote == NULL) {
2130 repo_conf = got_repo_get_gotconfig(repo);
2131 if (repo_conf) {
2132 got_gotconfig_get_remotes(&nremotes, &remotes,
2133 repo_conf);
2134 for (i = 0; i < nremotes; i++) {
2135 if (strcmp(remotes[i].name, remote_name) == 0) {
2136 remote = &remotes[i];
2137 break;
2142 if (remote == NULL) {
2143 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2144 for (i = 0; i < nremotes; i++) {
2145 if (strcmp(remotes[i].name, remote_name) == 0) {
2146 remote = &remotes[i];
2147 break;
2151 if (remote == NULL) {
2152 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2153 goto done;
2156 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2157 for (i = 0; i < remote->nbranches; i++) {
2158 got_pathlist_append(&wanted_branches,
2159 remote->branches[i], NULL);
2164 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2165 &repo_name, remote->url);
2166 if (error)
2167 goto done;
2169 if (strcmp(proto, "git") == 0) {
2170 #ifndef PROFILE
2171 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2172 "sendfd dns inet unveil", NULL) == -1)
2173 err(1, "pledge");
2174 #endif
2175 } else if (strcmp(proto, "git+ssh") == 0 ||
2176 strcmp(proto, "ssh") == 0) {
2177 #ifndef PROFILE
2178 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2179 "sendfd unveil", NULL) == -1)
2180 err(1, "pledge");
2181 #endif
2182 } else if (strcmp(proto, "http") == 0 ||
2183 strcmp(proto, "git+http") == 0) {
2184 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2185 goto done;
2186 } else {
2187 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2188 goto done;
2191 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2192 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2193 error = got_error_from_errno2("unveil",
2194 GOT_FETCH_PATH_SSH);
2195 goto done;
2198 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2199 if (error)
2200 goto done;
2202 if (verbosity >= 0)
2203 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2204 port ? ":" : "", port ? port : "");
2206 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2207 server_path, verbosity);
2208 if (error)
2209 goto done;
2211 fpa.last_scaled_size[0] = '\0';
2212 fpa.last_p_indexed = -1;
2213 fpa.last_p_resolved = -1;
2214 fpa.verbosity = verbosity;
2215 fpa.repo = repo;
2216 fpa.create_configs = 0;
2217 fpa.configs_created = 0;
2218 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2219 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2220 remote->mirror_references, fetch_all_branches, &wanted_branches,
2221 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2222 fetch_progress, &fpa);
2223 if (error)
2224 goto done;
2226 if (list_refs_only) {
2227 error = list_remote_refs(&symrefs, &refs);
2228 goto done;
2231 if (pack_hash == NULL) {
2232 if (verbosity >= 0)
2233 printf("Already up-to-date\n");
2234 } else if (verbosity >= 0) {
2235 error = got_object_id_str(&id_str, pack_hash);
2236 if (error)
2237 goto done;
2238 printf("\nFetched %s.pack\n", id_str);
2239 free(id_str);
2240 id_str = NULL;
2243 /* Update references provided with the pack file. */
2244 TAILQ_FOREACH(pe, &refs, entry) {
2245 const char *refname = pe->path;
2246 struct got_object_id *id = pe->data;
2247 struct got_reference *ref;
2248 char *remote_refname;
2250 if (is_wanted_ref(&wanted_refs, refname) &&
2251 !remote->mirror_references) {
2252 error = update_wanted_ref(refname, id,
2253 remote->name, verbosity, repo);
2254 if (error)
2255 goto done;
2256 continue;
2259 if (remote->mirror_references ||
2260 strncmp("refs/tags/", refname, 10) == 0) {
2261 error = got_ref_open(&ref, repo, refname, 1);
2262 if (error) {
2263 if (error->code != GOT_ERR_NOT_REF)
2264 goto done;
2265 error = create_ref(refname, id, verbosity,
2266 repo);
2267 if (error)
2268 goto done;
2269 } else {
2270 error = update_ref(ref, id, replace_tags,
2271 verbosity, repo);
2272 unlock_err = got_ref_unlock(ref);
2273 if (unlock_err && error == NULL)
2274 error = unlock_err;
2275 got_ref_close(ref);
2276 if (error)
2277 goto done;
2279 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2280 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2281 remote_name, refname + 11) == -1) {
2282 error = got_error_from_errno("asprintf");
2283 goto done;
2286 error = got_ref_open(&ref, repo, remote_refname, 1);
2287 if (error) {
2288 if (error->code != GOT_ERR_NOT_REF)
2289 goto done;
2290 error = create_ref(remote_refname, id,
2291 verbosity, repo);
2292 if (error)
2293 goto done;
2294 } else {
2295 error = update_ref(ref, id, replace_tags,
2296 verbosity, repo);
2297 unlock_err = got_ref_unlock(ref);
2298 if (unlock_err && error == NULL)
2299 error = unlock_err;
2300 got_ref_close(ref);
2301 if (error)
2302 goto done;
2305 /* Also create a local branch if none exists yet. */
2306 error = got_ref_open(&ref, repo, refname, 1);
2307 if (error) {
2308 if (error->code != GOT_ERR_NOT_REF)
2309 goto done;
2310 error = create_ref(refname, id, verbosity,
2311 repo);
2312 if (error)
2313 goto done;
2314 } else {
2315 unlock_err = got_ref_unlock(ref);
2316 if (unlock_err && error == NULL)
2317 error = unlock_err;
2318 got_ref_close(ref);
2322 if (delete_refs) {
2323 error = delete_missing_refs(&refs, &symrefs, remote,
2324 verbosity, repo);
2325 if (error)
2326 goto done;
2329 if (!remote->mirror_references) {
2330 /* Update remote HEAD reference if the server provided one. */
2331 TAILQ_FOREACH(pe, &symrefs, entry) {
2332 struct got_reference *target_ref;
2333 const char *refname = pe->path;
2334 const char *target = pe->data;
2335 char *remote_refname = NULL, *remote_target = NULL;
2337 if (strcmp(refname, GOT_REF_HEAD) != 0)
2338 continue;
2340 if (strncmp("refs/heads/", target, 11) != 0)
2341 continue;
2343 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2344 remote->name, refname) == -1) {
2345 error = got_error_from_errno("asprintf");
2346 goto done;
2348 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2349 remote->name, target + 11) == -1) {
2350 error = got_error_from_errno("asprintf");
2351 free(remote_refname);
2352 goto done;
2355 error = got_ref_open(&target_ref, repo, remote_target,
2356 0);
2357 if (error) {
2358 free(remote_refname);
2359 free(remote_target);
2360 if (error->code == GOT_ERR_NOT_REF) {
2361 error = NULL;
2362 continue;
2364 goto done;
2366 error = update_symref(remote_refname, target_ref,
2367 verbosity, repo);
2368 free(remote_refname);
2369 free(remote_target);
2370 got_ref_close(target_ref);
2371 if (error)
2372 goto done;
2375 done:
2376 if (fetchpid > 0) {
2377 if (kill(fetchpid, SIGTERM) == -1)
2378 error = got_error_from_errno("kill");
2379 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2380 error = got_error_from_errno("waitpid");
2382 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2383 error = got_error_from_errno("close");
2384 if (repo)
2385 got_repo_close(repo);
2386 if (worktree)
2387 got_worktree_close(worktree);
2388 TAILQ_FOREACH(pe, &refs, entry) {
2389 free((void *)pe->path);
2390 free(pe->data);
2392 got_pathlist_free(&refs);
2393 TAILQ_FOREACH(pe, &symrefs, entry) {
2394 free((void *)pe->path);
2395 free(pe->data);
2397 got_pathlist_free(&symrefs);
2398 got_pathlist_free(&wanted_branches);
2399 got_pathlist_free(&wanted_refs);
2400 free(id_str);
2401 free(cwd);
2402 free(repo_path);
2403 free(pack_hash);
2404 free(proto);
2405 free(host);
2406 free(port);
2407 free(server_path);
2408 free(repo_name);
2409 return error;
2413 __dead static void
2414 usage_checkout(void)
2416 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2417 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2418 exit(1);
2421 static void
2422 show_worktree_base_ref_warning(void)
2424 fprintf(stderr, "%s: warning: could not create a reference "
2425 "to the work tree's base commit; the commit could be "
2426 "garbage-collected by Git; making the repository "
2427 "writable and running 'got update' will prevent this\n",
2428 getprogname());
2431 struct got_checkout_progress_arg {
2432 const char *worktree_path;
2433 int had_base_commit_ref_error;
2436 static const struct got_error *
2437 checkout_progress(void *arg, unsigned char status, const char *path)
2439 struct got_checkout_progress_arg *a = arg;
2441 /* Base commit bump happens silently. */
2442 if (status == GOT_STATUS_BUMP_BASE)
2443 return NULL;
2445 if (status == GOT_STATUS_BASE_REF_ERR) {
2446 a->had_base_commit_ref_error = 1;
2447 return NULL;
2450 while (path[0] == '/')
2451 path++;
2453 printf("%c %s/%s\n", status, a->worktree_path, path);
2454 return NULL;
2457 static const struct got_error *
2458 check_cancelled(void *arg)
2460 if (sigint_received || sigpipe_received)
2461 return got_error(GOT_ERR_CANCELLED);
2462 return NULL;
2465 static const struct got_error *
2466 check_linear_ancestry(struct got_object_id *commit_id,
2467 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2468 struct got_repository *repo)
2470 const struct got_error *err = NULL;
2471 struct got_object_id *yca_id;
2473 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2474 commit_id, base_commit_id, repo, check_cancelled, NULL);
2475 if (err)
2476 return err;
2478 if (yca_id == NULL)
2479 return got_error(GOT_ERR_ANCESTRY);
2482 * Require a straight line of history between the target commit
2483 * and the work tree's base commit.
2485 * Non-linear situations such as this require a rebase:
2487 * (commit) D F (base_commit)
2488 * \ /
2489 * C E
2490 * \ /
2491 * B (yca)
2492 * |
2493 * A
2495 * 'got update' only handles linear cases:
2496 * Update forwards in time: A (base/yca) - B - C - D (commit)
2497 * Update backwards in time: D (base) - C - B - A (commit/yca)
2499 if (allow_forwards_in_time_only) {
2500 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2501 return got_error(GOT_ERR_ANCESTRY);
2502 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2503 got_object_id_cmp(base_commit_id, yca_id) != 0)
2504 return got_error(GOT_ERR_ANCESTRY);
2506 free(yca_id);
2507 return NULL;
2510 static const struct got_error *
2511 check_same_branch(struct got_object_id *commit_id,
2512 struct got_reference *head_ref, struct got_object_id *yca_id,
2513 struct got_repository *repo)
2515 const struct got_error *err = NULL;
2516 struct got_commit_graph *graph = NULL;
2517 struct got_object_id *head_commit_id = NULL;
2518 int is_same_branch = 0;
2520 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2521 if (err)
2522 goto done;
2524 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2525 is_same_branch = 1;
2526 goto done;
2528 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2529 is_same_branch = 1;
2530 goto done;
2533 err = got_commit_graph_open(&graph, "/", 1);
2534 if (err)
2535 goto done;
2537 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2538 check_cancelled, NULL);
2539 if (err)
2540 goto done;
2542 for (;;) {
2543 struct got_object_id *id;
2544 err = got_commit_graph_iter_next(&id, graph, repo,
2545 check_cancelled, NULL);
2546 if (err) {
2547 if (err->code == GOT_ERR_ITER_COMPLETED)
2548 err = NULL;
2549 break;
2552 if (id) {
2553 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2554 break;
2555 if (got_object_id_cmp(id, commit_id) == 0) {
2556 is_same_branch = 1;
2557 break;
2561 done:
2562 if (graph)
2563 got_commit_graph_close(graph);
2564 free(head_commit_id);
2565 if (!err && !is_same_branch)
2566 err = got_error(GOT_ERR_ANCESTRY);
2567 return err;
2570 static const struct got_error *
2571 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2573 static char msg[512];
2574 const char *branch_name;
2576 if (got_ref_is_symbolic(ref))
2577 branch_name = got_ref_get_symref_target(ref);
2578 else
2579 branch_name = got_ref_get_name(ref);
2581 if (strncmp("refs/heads/", branch_name, 11) == 0)
2582 branch_name += 11;
2584 snprintf(msg, sizeof(msg),
2585 "target commit is not contained in branch '%s'; "
2586 "the branch to use must be specified with -b; "
2587 "if necessary a new branch can be created for "
2588 "this commit with 'got branch -c %s BRANCH_NAME'",
2589 branch_name, commit_id_str);
2591 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2594 static const struct got_error *
2595 cmd_checkout(int argc, char *argv[])
2597 const struct got_error *error = NULL;
2598 struct got_repository *repo = NULL;
2599 struct got_reference *head_ref = NULL;
2600 struct got_worktree *worktree = NULL;
2601 char *repo_path = NULL;
2602 char *worktree_path = NULL;
2603 const char *path_prefix = "";
2604 const char *branch_name = GOT_REF_HEAD;
2605 char *commit_id_str = NULL;
2606 char *cwd = NULL;
2607 int ch, same_path_prefix, allow_nonempty = 0;
2608 struct got_pathlist_head paths;
2609 struct got_checkout_progress_arg cpa;
2611 TAILQ_INIT(&paths);
2613 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2614 switch (ch) {
2615 case 'b':
2616 branch_name = optarg;
2617 break;
2618 case 'c':
2619 commit_id_str = strdup(optarg);
2620 if (commit_id_str == NULL)
2621 return got_error_from_errno("strdup");
2622 break;
2623 case 'E':
2624 allow_nonempty = 1;
2625 break;
2626 case 'p':
2627 path_prefix = optarg;
2628 break;
2629 default:
2630 usage_checkout();
2631 /* NOTREACHED */
2635 argc -= optind;
2636 argv += optind;
2638 #ifndef PROFILE
2639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2640 "unveil", NULL) == -1)
2641 err(1, "pledge");
2642 #endif
2643 if (argc == 1) {
2644 char *base, *dotgit;
2645 const char *path;
2646 repo_path = realpath(argv[0], NULL);
2647 if (repo_path == NULL)
2648 return got_error_from_errno2("realpath", argv[0]);
2649 cwd = getcwd(NULL, 0);
2650 if (cwd == NULL) {
2651 error = got_error_from_errno("getcwd");
2652 goto done;
2654 if (path_prefix[0])
2655 path = path_prefix;
2656 else
2657 path = repo_path;
2658 error = got_path_basename(&base, path);
2659 if (error)
2660 goto done;
2661 dotgit = strstr(base, ".git");
2662 if (dotgit)
2663 *dotgit = '\0';
2664 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2665 error = got_error_from_errno("asprintf");
2666 free(base);
2667 goto done;
2669 free(base);
2670 } else if (argc == 2) {
2671 repo_path = realpath(argv[0], NULL);
2672 if (repo_path == NULL) {
2673 error = got_error_from_errno2("realpath", argv[0]);
2674 goto done;
2676 worktree_path = realpath(argv[1], NULL);
2677 if (worktree_path == NULL) {
2678 if (errno != ENOENT) {
2679 error = got_error_from_errno2("realpath",
2680 argv[1]);
2681 goto done;
2683 worktree_path = strdup(argv[1]);
2684 if (worktree_path == NULL) {
2685 error = got_error_from_errno("strdup");
2686 goto done;
2689 } else
2690 usage_checkout();
2692 got_path_strip_trailing_slashes(repo_path);
2693 got_path_strip_trailing_slashes(worktree_path);
2695 error = got_repo_open(&repo, repo_path, NULL);
2696 if (error != NULL)
2697 goto done;
2699 /* Pre-create work tree path for unveil(2) */
2700 error = got_path_mkdir(worktree_path);
2701 if (error) {
2702 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2703 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2704 goto done;
2705 if (!allow_nonempty &&
2706 !got_path_dir_is_empty(worktree_path)) {
2707 error = got_error_path(worktree_path,
2708 GOT_ERR_DIR_NOT_EMPTY);
2709 goto done;
2713 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2714 if (error)
2715 goto done;
2717 error = got_ref_open(&head_ref, repo, branch_name, 0);
2718 if (error != NULL)
2719 goto done;
2721 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2722 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2723 goto done;
2725 error = got_worktree_open(&worktree, worktree_path);
2726 if (error != NULL)
2727 goto done;
2729 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2730 path_prefix);
2731 if (error != NULL)
2732 goto done;
2733 if (!same_path_prefix) {
2734 error = got_error(GOT_ERR_PATH_PREFIX);
2735 goto done;
2738 if (commit_id_str) {
2739 struct got_object_id *commit_id;
2740 error = got_repo_match_object_id(&commit_id, NULL,
2741 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2742 if (error)
2743 goto done;
2744 error = check_linear_ancestry(commit_id,
2745 got_worktree_get_base_commit_id(worktree), 0, repo);
2746 if (error != NULL) {
2747 free(commit_id);
2748 if (error->code == GOT_ERR_ANCESTRY) {
2749 error = checkout_ancestry_error(
2750 head_ref, commit_id_str);
2752 goto done;
2754 error = check_same_branch(commit_id, head_ref, NULL, repo);
2755 if (error) {
2756 if (error->code == GOT_ERR_ANCESTRY) {
2757 error = checkout_ancestry_error(
2758 head_ref, commit_id_str);
2760 goto done;
2762 error = got_worktree_set_base_commit_id(worktree, repo,
2763 commit_id);
2764 free(commit_id);
2765 if (error)
2766 goto done;
2769 error = got_pathlist_append(&paths, "", NULL);
2770 if (error)
2771 goto done;
2772 cpa.worktree_path = worktree_path;
2773 cpa.had_base_commit_ref_error = 0;
2774 error = got_worktree_checkout_files(worktree, &paths, repo,
2775 checkout_progress, &cpa, check_cancelled, NULL);
2776 if (error != NULL)
2777 goto done;
2779 printf("Now shut up and hack\n");
2780 if (cpa.had_base_commit_ref_error)
2781 show_worktree_base_ref_warning();
2782 done:
2783 got_pathlist_free(&paths);
2784 free(commit_id_str);
2785 free(repo_path);
2786 free(worktree_path);
2787 free(cwd);
2788 return error;
2791 struct got_update_progress_arg {
2792 int did_something;
2793 int conflicts;
2794 int obstructed;
2795 int not_updated;
2798 void
2799 print_update_progress_stats(struct got_update_progress_arg *upa)
2801 if (!upa->did_something)
2802 return;
2804 if (upa->conflicts > 0)
2805 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2806 if (upa->obstructed > 0)
2807 printf("File paths obstructed by a non-regular file: %d\n",
2808 upa->obstructed);
2809 if (upa->not_updated > 0)
2810 printf("Files not updated because of existing merge "
2811 "conflicts: %d\n", upa->not_updated);
2814 __dead static void
2815 usage_update(void)
2817 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2818 getprogname());
2819 exit(1);
2822 static const struct got_error *
2823 update_progress(void *arg, unsigned char status, const char *path)
2825 struct got_update_progress_arg *upa = arg;
2827 if (status == GOT_STATUS_EXISTS ||
2828 status == GOT_STATUS_BASE_REF_ERR)
2829 return NULL;
2831 upa->did_something = 1;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_CONFLICT)
2838 upa->conflicts++;
2839 if (status == GOT_STATUS_OBSTRUCTED)
2840 upa->obstructed++;
2841 if (status == GOT_STATUS_CANNOT_UPDATE)
2842 upa->not_updated++;
2844 while (path[0] == '/')
2845 path++;
2846 printf("%c %s\n", status, path);
2847 return NULL;
2850 static const struct got_error *
2851 switch_head_ref(struct got_reference *head_ref,
2852 struct got_object_id *commit_id, struct got_worktree *worktree,
2853 struct got_repository *repo)
2855 const struct got_error *err = NULL;
2856 char *base_id_str;
2857 int ref_has_moved = 0;
2859 /* Trivial case: switching between two different references. */
2860 if (strcmp(got_ref_get_name(head_ref),
2861 got_worktree_get_head_ref_name(worktree)) != 0) {
2862 printf("Switching work tree from %s to %s\n",
2863 got_worktree_get_head_ref_name(worktree),
2864 got_ref_get_name(head_ref));
2865 return got_worktree_set_head_ref(worktree, head_ref);
2868 err = check_linear_ancestry(commit_id,
2869 got_worktree_get_base_commit_id(worktree), 0, repo);
2870 if (err) {
2871 if (err->code != GOT_ERR_ANCESTRY)
2872 return err;
2873 ref_has_moved = 1;
2875 if (!ref_has_moved)
2876 return NULL;
2878 /* Switching to a rebased branch with the same reference name. */
2879 err = got_object_id_str(&base_id_str,
2880 got_worktree_get_base_commit_id(worktree));
2881 if (err)
2882 return err;
2883 printf("Reference %s now points at a different branch\n",
2884 got_worktree_get_head_ref_name(worktree));
2885 printf("Switching work tree from %s to %s\n", base_id_str,
2886 got_worktree_get_head_ref_name(worktree));
2887 return NULL;
2890 static const struct got_error *
2891 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2893 const struct got_error *err;
2894 int in_progress;
2896 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2897 if (err)
2898 return err;
2899 if (in_progress)
2900 return got_error(GOT_ERR_REBASING);
2902 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2903 if (err)
2904 return err;
2905 if (in_progress)
2906 return got_error(GOT_ERR_HISTEDIT_BUSY);
2908 return NULL;
2911 static const struct got_error *
2912 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2913 char *argv[], struct got_worktree *worktree)
2915 const struct got_error *err = NULL;
2916 char *path;
2917 int i;
2919 if (argc == 0) {
2920 path = strdup("");
2921 if (path == NULL)
2922 return got_error_from_errno("strdup");
2923 return got_pathlist_append(paths, path, NULL);
2926 for (i = 0; i < argc; i++) {
2927 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2928 if (err)
2929 break;
2930 err = got_pathlist_append(paths, path, NULL);
2931 if (err) {
2932 free(path);
2933 break;
2937 return err;
2940 static const struct got_error *
2941 wrap_not_worktree_error(const struct got_error *orig_err,
2942 const char *cmdname, const char *path)
2944 const struct got_error *err;
2945 struct got_repository *repo;
2946 static char msg[512];
2948 err = got_repo_open(&repo, path, NULL);
2949 if (err)
2950 return orig_err;
2952 snprintf(msg, sizeof(msg),
2953 "'got %s' needs a work tree in addition to a git repository\n"
2954 "Work trees can be checked out from this Git repository with "
2955 "'got checkout'.\n"
2956 "The got(1) manual page contains more information.", cmdname);
2957 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2958 got_repo_close(repo);
2959 return err;
2962 static const struct got_error *
2963 cmd_update(int argc, char *argv[])
2965 const struct got_error *error = NULL;
2966 struct got_repository *repo = NULL;
2967 struct got_worktree *worktree = NULL;
2968 char *worktree_path = NULL;
2969 struct got_object_id *commit_id = NULL;
2970 char *commit_id_str = NULL;
2971 const char *branch_name = NULL;
2972 struct got_reference *head_ref = NULL;
2973 struct got_pathlist_head paths;
2974 struct got_pathlist_entry *pe;
2975 int ch;
2976 struct got_update_progress_arg upa;
2978 TAILQ_INIT(&paths);
2980 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2981 switch (ch) {
2982 case 'b':
2983 branch_name = optarg;
2984 break;
2985 case 'c':
2986 commit_id_str = strdup(optarg);
2987 if (commit_id_str == NULL)
2988 return got_error_from_errno("strdup");
2989 break;
2990 default:
2991 usage_update();
2992 /* NOTREACHED */
2996 argc -= optind;
2997 argv += optind;
2999 #ifndef PROFILE
3000 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3001 "unveil", NULL) == -1)
3002 err(1, "pledge");
3003 #endif
3004 worktree_path = getcwd(NULL, 0);
3005 if (worktree_path == NULL) {
3006 error = got_error_from_errno("getcwd");
3007 goto done;
3009 error = got_worktree_open(&worktree, worktree_path);
3010 if (error) {
3011 if (error->code == GOT_ERR_NOT_WORKTREE)
3012 error = wrap_not_worktree_error(error, "update",
3013 worktree_path);
3014 goto done;
3017 error = check_rebase_or_histedit_in_progress(worktree);
3018 if (error)
3019 goto done;
3021 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3022 NULL);
3023 if (error != NULL)
3024 goto done;
3026 error = apply_unveil(got_repo_get_path(repo), 0,
3027 got_worktree_get_root_path(worktree));
3028 if (error)
3029 goto done;
3031 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3032 if (error)
3033 goto done;
3035 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3036 got_worktree_get_head_ref_name(worktree), 0);
3037 if (error != NULL)
3038 goto done;
3039 if (commit_id_str == NULL) {
3040 error = got_ref_resolve(&commit_id, repo, head_ref);
3041 if (error != NULL)
3042 goto done;
3043 error = got_object_id_str(&commit_id_str, commit_id);
3044 if (error != NULL)
3045 goto done;
3046 } else {
3047 error = got_repo_match_object_id(&commit_id, NULL,
3048 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3049 free(commit_id_str);
3050 commit_id_str = NULL;
3051 if (error)
3052 goto done;
3053 error = got_object_id_str(&commit_id_str, commit_id);
3054 if (error)
3055 goto done;
3058 if (branch_name) {
3059 struct got_object_id *head_commit_id;
3060 TAILQ_FOREACH(pe, &paths, entry) {
3061 if (pe->path_len == 0)
3062 continue;
3063 error = got_error_msg(GOT_ERR_BAD_PATH,
3064 "switching between branches requires that "
3065 "the entire work tree gets updated");
3066 goto done;
3068 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3069 if (error)
3070 goto done;
3071 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3072 repo);
3073 free(head_commit_id);
3074 if (error != NULL)
3075 goto done;
3076 error = check_same_branch(commit_id, head_ref, NULL, repo);
3077 if (error)
3078 goto done;
3079 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3080 if (error)
3081 goto done;
3082 } else {
3083 error = check_linear_ancestry(commit_id,
3084 got_worktree_get_base_commit_id(worktree), 0, repo);
3085 if (error != NULL) {
3086 if (error->code == GOT_ERR_ANCESTRY)
3087 error = got_error(GOT_ERR_BRANCH_MOVED);
3088 goto done;
3090 error = check_same_branch(commit_id, head_ref, NULL, repo);
3091 if (error)
3092 goto done;
3095 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3096 commit_id) != 0) {
3097 error = got_worktree_set_base_commit_id(worktree, repo,
3098 commit_id);
3099 if (error)
3100 goto done;
3103 memset(&upa, 0, sizeof(upa));
3104 error = got_worktree_checkout_files(worktree, &paths, repo,
3105 update_progress, &upa, check_cancelled, NULL);
3106 if (error != NULL)
3107 goto done;
3109 if (upa.did_something)
3110 printf("Updated to commit %s\n", commit_id_str);
3111 else
3112 printf("Already up-to-date\n");
3113 print_update_progress_stats(&upa);
3114 done:
3115 free(worktree_path);
3116 TAILQ_FOREACH(pe, &paths, entry)
3117 free((char *)pe->path);
3118 got_pathlist_free(&paths);
3119 free(commit_id);
3120 free(commit_id_str);
3121 return error;
3124 static const struct got_error *
3125 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3126 const char *path, int diff_context, int ignore_whitespace,
3127 struct got_repository *repo)
3129 const struct got_error *err = NULL;
3130 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3132 if (blob_id1) {
3133 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3134 if (err)
3135 goto done;
3138 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3139 if (err)
3140 goto done;
3142 while (path[0] == '/')
3143 path++;
3144 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3145 diff_context, ignore_whitespace, stdout);
3146 done:
3147 if (blob1)
3148 got_object_blob_close(blob1);
3149 got_object_blob_close(blob2);
3150 return err;
3153 static const struct got_error *
3154 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3155 const char *path, int diff_context, int ignore_whitespace,
3156 struct got_repository *repo)
3158 const struct got_error *err = NULL;
3159 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3160 struct got_diff_blob_output_unidiff_arg arg;
3162 if (tree_id1) {
3163 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3164 if (err)
3165 goto done;
3168 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3169 if (err)
3170 goto done;
3172 arg.diff_context = diff_context;
3173 arg.ignore_whitespace = ignore_whitespace;
3174 arg.outfile = stdout;
3175 arg.line_offsets = NULL;
3176 arg.nlines = 0;
3177 while (path[0] == '/')
3178 path++;
3179 err = got_diff_tree(tree1, tree2, path, path, repo,
3180 got_diff_blob_output_unidiff, &arg, 1);
3181 done:
3182 if (tree1)
3183 got_object_tree_close(tree1);
3184 if (tree2)
3185 got_object_tree_close(tree2);
3186 return err;
3189 static const struct got_error *
3190 get_changed_paths(struct got_pathlist_head *paths,
3191 struct got_commit_object *commit, struct got_repository *repo)
3193 const struct got_error *err = NULL;
3194 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3195 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3196 struct got_object_qid *qid;
3198 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3199 if (qid != NULL) {
3200 struct got_commit_object *pcommit;
3201 err = got_object_open_as_commit(&pcommit, repo,
3202 qid->id);
3203 if (err)
3204 return err;
3206 tree_id1 = got_object_commit_get_tree_id(pcommit);
3207 got_object_commit_close(pcommit);
3211 if (tree_id1) {
3212 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3213 if (err)
3214 goto done;
3217 tree_id2 = got_object_commit_get_tree_id(commit);
3218 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3219 if (err)
3220 goto done;
3222 err = got_diff_tree(tree1, tree2, "", "", repo,
3223 got_diff_tree_collect_changed_paths, paths, 0);
3224 done:
3225 if (tree1)
3226 got_object_tree_close(tree1);
3227 if (tree2)
3228 got_object_tree_close(tree2);
3229 return err;
3232 static const struct got_error *
3233 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3234 const char *path, int diff_context, struct got_repository *repo)
3236 const struct got_error *err = NULL;
3237 struct got_commit_object *pcommit = NULL;
3238 char *id_str1 = NULL, *id_str2 = NULL;
3239 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3240 struct got_object_qid *qid;
3242 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3243 if (qid != NULL) {
3244 err = got_object_open_as_commit(&pcommit, repo,
3245 qid->id);
3246 if (err)
3247 return err;
3250 if (path && path[0] != '\0') {
3251 int obj_type;
3252 err = got_object_id_by_path(&obj_id2, repo, id, path);
3253 if (err)
3254 goto done;
3255 err = got_object_id_str(&id_str2, obj_id2);
3256 if (err) {
3257 free(obj_id2);
3258 goto done;
3260 if (pcommit) {
3261 err = got_object_id_by_path(&obj_id1, repo,
3262 qid->id, path);
3263 if (err) {
3264 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3265 free(obj_id2);
3266 goto done;
3268 } else {
3269 err = got_object_id_str(&id_str1, obj_id1);
3270 if (err) {
3271 free(obj_id2);
3272 goto done;
3276 err = got_object_get_type(&obj_type, repo, obj_id2);
3277 if (err) {
3278 free(obj_id2);
3279 goto done;
3281 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3282 switch (obj_type) {
3283 case GOT_OBJ_TYPE_BLOB:
3284 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3285 0, repo);
3286 break;
3287 case GOT_OBJ_TYPE_TREE:
3288 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3289 0, repo);
3290 break;
3291 default:
3292 err = got_error(GOT_ERR_OBJ_TYPE);
3293 break;
3295 free(obj_id1);
3296 free(obj_id2);
3297 } else {
3298 obj_id2 = got_object_commit_get_tree_id(commit);
3299 err = got_object_id_str(&id_str2, obj_id2);
3300 if (err)
3301 goto done;
3302 if (pcommit) {
3303 obj_id1 = got_object_commit_get_tree_id(pcommit);
3304 err = got_object_id_str(&id_str1, obj_id1);
3305 if (err)
3306 goto done;
3308 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3309 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3311 done:
3312 free(id_str1);
3313 free(id_str2);
3314 if (pcommit)
3315 got_object_commit_close(pcommit);
3316 return err;
3319 static char *
3320 get_datestr(time_t *time, char *datebuf)
3322 struct tm mytm, *tm;
3323 char *p, *s;
3325 tm = gmtime_r(time, &mytm);
3326 if (tm == NULL)
3327 return NULL;
3328 s = asctime_r(tm, datebuf);
3329 if (s == NULL)
3330 return NULL;
3331 p = strchr(s, '\n');
3332 if (p)
3333 *p = '\0';
3334 return s;
3337 static const struct got_error *
3338 match_logmsg(int *have_match, struct got_object_id *id,
3339 struct got_commit_object *commit, regex_t *regex)
3341 const struct got_error *err = NULL;
3342 regmatch_t regmatch;
3343 char *id_str = NULL, *logmsg = NULL;
3345 *have_match = 0;
3347 err = got_object_id_str(&id_str, id);
3348 if (err)
3349 return err;
3351 err = got_object_commit_get_logmsg(&logmsg, commit);
3352 if (err)
3353 goto done;
3355 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3356 *have_match = 1;
3357 done:
3358 free(id_str);
3359 free(logmsg);
3360 return err;
3363 static void
3364 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3365 regex_t *regex)
3367 regmatch_t regmatch;
3368 struct got_pathlist_entry *pe;
3370 *have_match = 0;
3372 TAILQ_FOREACH(pe, changed_paths, entry) {
3373 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3374 *have_match = 1;
3375 break;
3380 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3382 static const struct got_error *
3383 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3384 struct got_repository *repo, const char *path,
3385 struct got_pathlist_head *changed_paths, int show_patch,
3386 int diff_context, struct got_reflist_head *refs)
3388 const struct got_error *err = NULL;
3389 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3390 char datebuf[26];
3391 time_t committer_time;
3392 const char *author, *committer;
3393 char *refs_str = NULL;
3394 struct got_reflist_entry *re;
3396 SIMPLEQ_FOREACH(re, refs, entry) {
3397 char *s;
3398 const char *name;
3399 struct got_tag_object *tag = NULL;
3400 struct got_object_id *ref_id;
3401 int cmp;
3403 name = got_ref_get_name(re->ref);
3404 if (strcmp(name, GOT_REF_HEAD) == 0)
3405 continue;
3406 if (strncmp(name, "refs/", 5) == 0)
3407 name += 5;
3408 if (strncmp(name, "got/", 4) == 0)
3409 continue;
3410 if (strncmp(name, "heads/", 6) == 0)
3411 name += 6;
3412 if (strncmp(name, "remotes/", 8) == 0) {
3413 name += 8;
3414 s = strstr(name, "/" GOT_REF_HEAD);
3415 if (s != NULL && s[strlen(s)] == '\0')
3416 continue;
3418 err = got_ref_resolve(&ref_id, repo, re->ref);
3419 if (err)
3420 return err;
3421 if (strncmp(name, "tags/", 5) == 0) {
3422 err = got_object_open_as_tag(&tag, repo, ref_id);
3423 if (err) {
3424 if (err->code != GOT_ERR_OBJ_TYPE) {
3425 free(ref_id);
3426 return err;
3428 /* Ref points at something other than a tag. */
3429 err = NULL;
3430 tag = NULL;
3433 cmp = got_object_id_cmp(tag ?
3434 got_object_tag_get_object_id(tag) : ref_id, id);
3435 free(ref_id);
3436 if (tag)
3437 got_object_tag_close(tag);
3438 if (cmp != 0)
3439 continue;
3440 s = refs_str;
3441 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3442 name) == -1) {
3443 err = got_error_from_errno("asprintf");
3444 free(s);
3445 return err;
3447 free(s);
3449 err = got_object_id_str(&id_str, id);
3450 if (err)
3451 return err;
3453 printf(GOT_COMMIT_SEP_STR);
3454 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3455 refs_str ? refs_str : "", refs_str ? ")" : "");
3456 free(id_str);
3457 id_str = NULL;
3458 free(refs_str);
3459 refs_str = NULL;
3460 printf("from: %s\n", got_object_commit_get_author(commit));
3461 committer_time = got_object_commit_get_committer_time(commit);
3462 datestr = get_datestr(&committer_time, datebuf);
3463 if (datestr)
3464 printf("date: %s UTC\n", datestr);
3465 author = got_object_commit_get_author(commit);
3466 committer = got_object_commit_get_committer(commit);
3467 if (strcmp(author, committer) != 0)
3468 printf("via: %s\n", committer);
3469 if (got_object_commit_get_nparents(commit) > 1) {
3470 const struct got_object_id_queue *parent_ids;
3471 struct got_object_qid *qid;
3472 int n = 1;
3473 parent_ids = got_object_commit_get_parent_ids(commit);
3474 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3475 err = got_object_id_str(&id_str, qid->id);
3476 if (err)
3477 return err;
3478 printf("parent %d: %s\n", n++, id_str);
3479 free(id_str);
3483 err = got_object_commit_get_logmsg(&logmsg0, commit);
3484 if (err)
3485 return err;
3487 logmsg = logmsg0;
3488 do {
3489 line = strsep(&logmsg, "\n");
3490 if (line)
3491 printf(" %s\n", line);
3492 } while (line);
3493 free(logmsg0);
3495 if (changed_paths) {
3496 struct got_pathlist_entry *pe;
3497 TAILQ_FOREACH(pe, changed_paths, entry) {
3498 struct got_diff_changed_path *cp = pe->data;
3499 printf(" %c %s\n", cp->status, pe->path);
3501 printf("\n");
3503 if (show_patch) {
3504 err = print_patch(commit, id, path, diff_context, repo);
3505 if (err == 0)
3506 printf("\n");
3509 if (fflush(stdout) != 0 && err == NULL)
3510 err = got_error_from_errno("fflush");
3511 return err;
3514 static const struct got_error *
3515 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3516 struct got_repository *repo, const char *path, int show_changed_paths,
3517 int show_patch, const char *search_pattern, int diff_context, int limit,
3518 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3520 const struct got_error *err;
3521 struct got_commit_graph *graph;
3522 regex_t regex;
3523 int have_match;
3524 struct got_object_id_queue reversed_commits;
3525 struct got_object_qid *qid;
3526 struct got_commit_object *commit;
3527 struct got_pathlist_head changed_paths;
3528 struct got_pathlist_entry *pe;
3530 SIMPLEQ_INIT(&reversed_commits);
3531 TAILQ_INIT(&changed_paths);
3533 if (search_pattern && regcomp(&regex, search_pattern,
3534 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3535 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3537 err = got_commit_graph_open(&graph, path, !log_branches);
3538 if (err)
3539 return err;
3540 err = got_commit_graph_iter_start(graph, root_id, repo,
3541 check_cancelled, NULL);
3542 if (err)
3543 goto done;
3544 for (;;) {
3545 struct got_object_id *id;
3547 if (sigint_received || sigpipe_received)
3548 break;
3550 err = got_commit_graph_iter_next(&id, graph, repo,
3551 check_cancelled, NULL);
3552 if (err) {
3553 if (err->code == GOT_ERR_ITER_COMPLETED)
3554 err = NULL;
3555 break;
3557 if (id == NULL)
3558 break;
3560 err = got_object_open_as_commit(&commit, repo, id);
3561 if (err)
3562 break;
3564 if (show_changed_paths && !reverse_display_order) {
3565 err = get_changed_paths(&changed_paths, commit, repo);
3566 if (err)
3567 break;
3570 if (search_pattern) {
3571 err = match_logmsg(&have_match, id, commit, &regex);
3572 if (err) {
3573 got_object_commit_close(commit);
3574 break;
3576 if (have_match == 0 && show_changed_paths)
3577 match_changed_paths(&have_match,
3578 &changed_paths, &regex);
3579 if (have_match == 0) {
3580 got_object_commit_close(commit);
3581 TAILQ_FOREACH(pe, &changed_paths, entry) {
3582 free((char *)pe->path);
3583 free(pe->data);
3585 got_pathlist_free(&changed_paths);
3586 continue;
3590 if (reverse_display_order) {
3591 err = got_object_qid_alloc(&qid, id);
3592 if (err)
3593 break;
3594 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3595 got_object_commit_close(commit);
3596 } else {
3597 err = print_commit(commit, id, repo, path,
3598 show_changed_paths ? &changed_paths : NULL,
3599 show_patch, diff_context, refs);
3600 got_object_commit_close(commit);
3601 if (err)
3602 break;
3604 if ((limit && --limit == 0) ||
3605 (end_id && got_object_id_cmp(id, end_id) == 0))
3606 break;
3608 TAILQ_FOREACH(pe, &changed_paths, entry) {
3609 free((char *)pe->path);
3610 free(pe->data);
3612 got_pathlist_free(&changed_paths);
3614 if (reverse_display_order) {
3615 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3616 err = got_object_open_as_commit(&commit, repo, qid->id);
3617 if (err)
3618 break;
3619 if (show_changed_paths) {
3620 err = get_changed_paths(&changed_paths,
3621 commit, repo);
3622 if (err)
3623 break;
3625 err = print_commit(commit, qid->id, repo, path,
3626 show_changed_paths ? &changed_paths : NULL,
3627 show_patch, diff_context, refs);
3628 got_object_commit_close(commit);
3629 if (err)
3630 break;
3631 TAILQ_FOREACH(pe, &changed_paths, entry) {
3632 free((char *)pe->path);
3633 free(pe->data);
3635 got_pathlist_free(&changed_paths);
3638 done:
3639 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3640 qid = SIMPLEQ_FIRST(&reversed_commits);
3641 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3642 got_object_qid_free(qid);
3644 TAILQ_FOREACH(pe, &changed_paths, entry) {
3645 free((char *)pe->path);
3646 free(pe->data);
3648 got_pathlist_free(&changed_paths);
3649 if (search_pattern)
3650 regfree(&regex);
3651 got_commit_graph_close(graph);
3652 return err;
3655 __dead static void
3656 usage_log(void)
3658 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3659 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3660 "[-R] [path]\n", getprogname());
3661 exit(1);
3664 static int
3665 get_default_log_limit(void)
3667 const char *got_default_log_limit;
3668 long long n;
3669 const char *errstr;
3671 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3672 if (got_default_log_limit == NULL)
3673 return 0;
3674 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3675 if (errstr != NULL)
3676 return 0;
3677 return n;
3680 static const struct got_error *
3681 cmd_log(int argc, char *argv[])
3683 const struct got_error *error;
3684 struct got_repository *repo = NULL;
3685 struct got_worktree *worktree = NULL;
3686 struct got_object_id *start_id = NULL, *end_id = NULL;
3687 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3688 const char *start_commit = NULL, *end_commit = NULL;
3689 const char *search_pattern = NULL;
3690 int diff_context = -1, ch;
3691 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3692 int reverse_display_order = 0;
3693 const char *errstr;
3694 struct got_reflist_head refs;
3696 SIMPLEQ_INIT(&refs);
3698 #ifndef PROFILE
3699 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3700 NULL)
3701 == -1)
3702 err(1, "pledge");
3703 #endif
3705 limit = get_default_log_limit();
3707 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3708 switch (ch) {
3709 case 'p':
3710 show_patch = 1;
3711 break;
3712 case 'P':
3713 show_changed_paths = 1;
3714 break;
3715 case 'c':
3716 start_commit = optarg;
3717 break;
3718 case 'C':
3719 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3720 &errstr);
3721 if (errstr != NULL)
3722 err(1, "-C option %s", errstr);
3723 break;
3724 case 'l':
3725 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3726 if (errstr != NULL)
3727 err(1, "-l option %s", errstr);
3728 break;
3729 case 'b':
3730 log_branches = 1;
3731 break;
3732 case 'r':
3733 repo_path = realpath(optarg, NULL);
3734 if (repo_path == NULL)
3735 return got_error_from_errno2("realpath",
3736 optarg);
3737 got_path_strip_trailing_slashes(repo_path);
3738 break;
3739 case 'R':
3740 reverse_display_order = 1;
3741 break;
3742 case 's':
3743 search_pattern = optarg;
3744 break;
3745 case 'x':
3746 end_commit = optarg;
3747 break;
3748 default:
3749 usage_log();
3750 /* NOTREACHED */
3754 argc -= optind;
3755 argv += optind;
3757 if (diff_context == -1)
3758 diff_context = 3;
3759 else if (!show_patch)
3760 errx(1, "-C requires -p");
3762 cwd = getcwd(NULL, 0);
3763 if (cwd == NULL) {
3764 error = got_error_from_errno("getcwd");
3765 goto done;
3768 if (repo_path == NULL) {
3769 error = got_worktree_open(&worktree, cwd);
3770 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3771 goto done;
3772 error = NULL;
3775 if (argc == 1) {
3776 if (worktree) {
3777 error = got_worktree_resolve_path(&path, worktree,
3778 argv[0]);
3779 if (error)
3780 goto done;
3781 } else {
3782 path = strdup(argv[0]);
3783 if (path == NULL) {
3784 error = got_error_from_errno("strdup");
3785 goto done;
3788 } else if (argc != 0)
3789 usage_log();
3791 if (repo_path == NULL) {
3792 repo_path = worktree ?
3793 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3795 if (repo_path == NULL) {
3796 error = got_error_from_errno("strdup");
3797 goto done;
3800 error = got_repo_open(&repo, repo_path, NULL);
3801 if (error != NULL)
3802 goto done;
3804 error = apply_unveil(got_repo_get_path(repo), 1,
3805 worktree ? got_worktree_get_root_path(worktree) : NULL);
3806 if (error)
3807 goto done;
3809 if (start_commit == NULL) {
3810 struct got_reference *head_ref;
3811 struct got_commit_object *commit = NULL;
3812 error = got_ref_open(&head_ref, repo,
3813 worktree ? got_worktree_get_head_ref_name(worktree)
3814 : GOT_REF_HEAD, 0);
3815 if (error != NULL)
3816 goto done;
3817 error = got_ref_resolve(&start_id, repo, head_ref);
3818 got_ref_close(head_ref);
3819 if (error != NULL)
3820 goto done;
3821 error = got_object_open_as_commit(&commit, repo,
3822 start_id);
3823 if (error != NULL)
3824 goto done;
3825 got_object_commit_close(commit);
3826 } else {
3827 error = got_repo_match_object_id(&start_id, NULL,
3828 start_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3829 if (error != NULL)
3830 goto done;
3832 if (end_commit != NULL) {
3833 error = got_repo_match_object_id(&end_id, NULL,
3834 end_commit, GOT_OBJ_TYPE_COMMIT, 1, repo);
3835 if (error != NULL)
3836 goto done;
3839 if (worktree) {
3841 * If a path was specified on the command line it was resolved
3842 * to a path in the work tree above. Prepend the work tree's
3843 * path prefix to obtain the corresponding in-repository path.
3845 if (path) {
3846 const char *prefix;
3847 prefix = got_worktree_get_path_prefix(worktree);
3848 if (asprintf(&in_repo_path, "%s%s%s", prefix,
3849 (path[0] != '\0') ? "/" : "", path) == -1) {
3850 error = got_error_from_errno("asprintf");
3851 goto done;
3854 } else
3855 error = got_repo_map_path(&in_repo_path, repo,
3856 path ? path : "");
3857 if (error != NULL)
3858 goto done;
3859 if (in_repo_path) {
3860 free(path);
3861 path = in_repo_path;
3864 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3865 if (error)
3866 goto done;
3868 error = print_commits(start_id, end_id, repo, path ? path : "",
3869 show_changed_paths, show_patch, search_pattern, diff_context,
3870 limit, log_branches, reverse_display_order, &refs);
3871 done:
3872 free(path);
3873 free(repo_path);
3874 free(cwd);
3875 if (worktree)
3876 got_worktree_close(worktree);
3877 if (repo) {
3878 const struct got_error *repo_error;
3879 repo_error = got_repo_close(repo);
3880 if (error == NULL)
3881 error = repo_error;
3883 got_ref_list_free(&refs);
3884 return error;
3887 __dead static void
3888 usage_diff(void)
3890 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3891 "[-w] [object1 object2 | path]\n", getprogname());
3892 exit(1);
3895 struct print_diff_arg {
3896 struct got_repository *repo;
3897 struct got_worktree *worktree;
3898 int diff_context;
3899 const char *id_str;
3900 int header_shown;
3901 int diff_staged;
3902 int ignore_whitespace;
3906 * Create a file which contains the target path of a symlink so we can feed
3907 * it as content to the diff engine.
3909 static const struct got_error *
3910 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3911 const char *abspath)
3913 const struct got_error *err = NULL;
3914 char target_path[PATH_MAX];
3915 ssize_t target_len, outlen;
3917 *fd = -1;
3919 if (dirfd != -1) {
3920 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3921 if (target_len == -1)
3922 return got_error_from_errno2("readlinkat", abspath);
3923 } else {
3924 target_len = readlink(abspath, target_path, PATH_MAX);
3925 if (target_len == -1)
3926 return got_error_from_errno2("readlink", abspath);
3929 *fd = got_opentempfd();
3930 if (*fd == -1)
3931 return got_error_from_errno("got_opentempfd");
3933 outlen = write(*fd, target_path, target_len);
3934 if (outlen == -1) {
3935 err = got_error_from_errno("got_opentempfd");
3936 goto done;
3939 if (lseek(*fd, 0, SEEK_SET) == -1) {
3940 err = got_error_from_errno2("lseek", abspath);
3941 goto done;
3943 done:
3944 if (err) {
3945 close(*fd);
3946 *fd = -1;
3948 return err;
3951 static const struct got_error *
3952 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3953 const char *path, struct got_object_id *blob_id,
3954 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3955 int dirfd, const char *de_name)
3957 struct print_diff_arg *a = arg;
3958 const struct got_error *err = NULL;
3959 struct got_blob_object *blob1 = NULL;
3960 int fd = -1;
3961 FILE *f2 = NULL;
3962 char *abspath = NULL, *label1 = NULL;
3963 struct stat sb;
3965 if (a->diff_staged) {
3966 if (staged_status != GOT_STATUS_MODIFY &&
3967 staged_status != GOT_STATUS_ADD &&
3968 staged_status != GOT_STATUS_DELETE)
3969 return NULL;
3970 } else {
3971 if (staged_status == GOT_STATUS_DELETE)
3972 return NULL;
3973 if (status == GOT_STATUS_NONEXISTENT)
3974 return got_error_set_errno(ENOENT, path);
3975 if (status != GOT_STATUS_MODIFY &&
3976 status != GOT_STATUS_ADD &&
3977 status != GOT_STATUS_DELETE &&
3978 status != GOT_STATUS_CONFLICT)
3979 return NULL;
3982 if (!a->header_shown) {
3983 printf("diff %s %s%s\n", a->id_str,
3984 got_worktree_get_root_path(a->worktree),
3985 a->diff_staged ? " (staged changes)" : "");
3986 a->header_shown = 1;
3989 if (a->diff_staged) {
3990 const char *label1 = NULL, *label2 = NULL;
3991 switch (staged_status) {
3992 case GOT_STATUS_MODIFY:
3993 label1 = path;
3994 label2 = path;
3995 break;
3996 case GOT_STATUS_ADD:
3997 label2 = path;
3998 break;
3999 case GOT_STATUS_DELETE:
4000 label1 = path;
4001 break;
4002 default:
4003 return got_error(GOT_ERR_FILE_STATUS);
4005 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4006 staged_blob_id, label1, label2, a->diff_context,
4007 a->ignore_whitespace, a->repo, stdout);
4010 if (staged_status == GOT_STATUS_ADD ||
4011 staged_status == GOT_STATUS_MODIFY) {
4012 char *id_str;
4013 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4014 8192);
4015 if (err)
4016 goto done;
4017 err = got_object_id_str(&id_str, staged_blob_id);
4018 if (err)
4019 goto done;
4020 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4021 err = got_error_from_errno("asprintf");
4022 free(id_str);
4023 goto done;
4025 free(id_str);
4026 } else if (status != GOT_STATUS_ADD) {
4027 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4028 if (err)
4029 goto done;
4032 if (status != GOT_STATUS_DELETE) {
4033 if (asprintf(&abspath, "%s/%s",
4034 got_worktree_get_root_path(a->worktree), path) == -1) {
4035 err = got_error_from_errno("asprintf");
4036 goto done;
4039 if (dirfd != -1) {
4040 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4041 if (fd == -1) {
4042 if (errno != ELOOP) {
4043 err = got_error_from_errno2("openat",
4044 abspath);
4045 goto done;
4047 err = get_symlink_target_file(&fd, dirfd,
4048 de_name, abspath);
4049 if (err)
4050 goto done;
4052 } else {
4053 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4054 if (fd == -1) {
4055 if (errno != ELOOP) {
4056 err = got_error_from_errno2("open",
4057 abspath);
4058 goto done;
4060 err = get_symlink_target_file(&fd, dirfd,
4061 de_name, abspath);
4062 if (err)
4063 goto done;
4066 if (fstat(fd, &sb) == -1) {
4067 err = got_error_from_errno2("fstat", abspath);
4068 goto done;
4070 f2 = fdopen(fd, "r");
4071 if (f2 == NULL) {
4072 err = got_error_from_errno2("fdopen", abspath);
4073 goto done;
4075 fd = -1;
4076 } else
4077 sb.st_size = 0;
4079 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4080 a->diff_context, a->ignore_whitespace, stdout);
4081 done:
4082 if (blob1)
4083 got_object_blob_close(blob1);
4084 if (f2 && fclose(f2) == EOF && err == NULL)
4085 err = got_error_from_errno("fclose");
4086 if (fd != -1 && close(fd) == -1 && err == NULL)
4087 err = got_error_from_errno("close");
4088 free(abspath);
4089 return err;
4092 static const struct got_error *
4093 cmd_diff(int argc, char *argv[])
4095 const struct got_error *error;
4096 struct got_repository *repo = NULL;
4097 struct got_worktree *worktree = NULL;
4098 char *cwd = NULL, *repo_path = NULL;
4099 struct got_object_id *id1 = NULL, *id2 = NULL;
4100 const char *id_str1 = NULL, *id_str2 = NULL;
4101 char *label1 = NULL, *label2 = NULL;
4102 int type1, type2;
4103 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4104 const char *errstr;
4105 char *path = NULL;
4107 #ifndef PROFILE
4108 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4109 NULL) == -1)
4110 err(1, "pledge");
4111 #endif
4113 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4114 switch (ch) {
4115 case 'C':
4116 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4117 &errstr);
4118 if (errstr != NULL)
4119 err(1, "-C option %s", errstr);
4120 break;
4121 case 'r':
4122 repo_path = realpath(optarg, NULL);
4123 if (repo_path == NULL)
4124 return got_error_from_errno2("realpath",
4125 optarg);
4126 got_path_strip_trailing_slashes(repo_path);
4127 break;
4128 case 's':
4129 diff_staged = 1;
4130 break;
4131 case 'w':
4132 ignore_whitespace = 1;
4133 break;
4134 default:
4135 usage_diff();
4136 /* NOTREACHED */
4140 argc -= optind;
4141 argv += optind;
4143 cwd = getcwd(NULL, 0);
4144 if (cwd == NULL) {
4145 error = got_error_from_errno("getcwd");
4146 goto done;
4148 if (argc <= 1) {
4149 if (repo_path)
4150 errx(1,
4151 "-r option can't be used when diffing a work tree");
4152 error = got_worktree_open(&worktree, cwd);
4153 if (error) {
4154 if (error->code == GOT_ERR_NOT_WORKTREE)
4155 error = wrap_not_worktree_error(error, "diff",
4156 cwd);
4157 goto done;
4159 repo_path = strdup(got_worktree_get_repo_path(worktree));
4160 if (repo_path == NULL) {
4161 error = got_error_from_errno("strdup");
4162 goto done;
4164 if (argc == 1) {
4165 error = got_worktree_resolve_path(&path, worktree,
4166 argv[0]);
4167 if (error)
4168 goto done;
4169 } else {
4170 path = strdup("");
4171 if (path == NULL) {
4172 error = got_error_from_errno("strdup");
4173 goto done;
4176 } else if (argc == 2) {
4177 if (diff_staged)
4178 errx(1, "-s option can't be used when diffing "
4179 "objects in repository");
4180 id_str1 = argv[0];
4181 id_str2 = argv[1];
4182 if (repo_path == NULL) {
4183 error = got_worktree_open(&worktree, cwd);
4184 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4185 goto done;
4186 if (worktree) {
4187 repo_path = strdup(
4188 got_worktree_get_repo_path(worktree));
4189 if (repo_path == NULL) {
4190 error = got_error_from_errno("strdup");
4191 goto done;
4193 } else {
4194 repo_path = strdup(cwd);
4195 if (repo_path == NULL) {
4196 error = got_error_from_errno("strdup");
4197 goto done;
4201 } else
4202 usage_diff();
4204 error = got_repo_open(&repo, repo_path, NULL);
4205 free(repo_path);
4206 if (error != NULL)
4207 goto done;
4209 error = apply_unveil(got_repo_get_path(repo), 1,
4210 worktree ? got_worktree_get_root_path(worktree) : NULL);
4211 if (error)
4212 goto done;
4214 if (argc <= 1) {
4215 struct print_diff_arg arg;
4216 struct got_pathlist_head paths;
4217 char *id_str;
4219 TAILQ_INIT(&paths);
4221 error = got_object_id_str(&id_str,
4222 got_worktree_get_base_commit_id(worktree));
4223 if (error)
4224 goto done;
4225 arg.repo = repo;
4226 arg.worktree = worktree;
4227 arg.diff_context = diff_context;
4228 arg.id_str = id_str;
4229 arg.header_shown = 0;
4230 arg.diff_staged = diff_staged;
4231 arg.ignore_whitespace = ignore_whitespace;
4233 error = got_pathlist_append(&paths, path, NULL);
4234 if (error)
4235 goto done;
4237 error = got_worktree_status(worktree, &paths, repo, print_diff,
4238 &arg, check_cancelled, NULL);
4239 free(id_str);
4240 got_pathlist_free(&paths);
4241 goto done;
4244 error = got_repo_match_object_id(&id1, &label1, id_str1,
4245 GOT_OBJ_TYPE_ANY, 1, repo);
4246 if (error)
4247 goto done;
4249 error = got_repo_match_object_id(&id2, &label2, id_str2,
4250 GOT_OBJ_TYPE_ANY, 1, repo);
4251 if (error)
4252 goto done;
4254 error = got_object_get_type(&type1, repo, id1);
4255 if (error)
4256 goto done;
4258 error = got_object_get_type(&type2, repo, id2);
4259 if (error)
4260 goto done;
4262 if (type1 != type2) {
4263 error = got_error(GOT_ERR_OBJ_TYPE);
4264 goto done;
4267 switch (type1) {
4268 case GOT_OBJ_TYPE_BLOB:
4269 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4270 NULL, NULL, diff_context, ignore_whitespace, repo,
4271 stdout);
4272 break;
4273 case GOT_OBJ_TYPE_TREE:
4274 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4275 "", "", diff_context, ignore_whitespace, repo, stdout);
4276 break;
4277 case GOT_OBJ_TYPE_COMMIT:
4278 printf("diff %s %s\n", label1, label2);
4279 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4280 diff_context, ignore_whitespace, repo, stdout);
4281 break;
4282 default:
4283 error = got_error(GOT_ERR_OBJ_TYPE);
4285 done:
4286 free(label1);
4287 free(label2);
4288 free(id1);
4289 free(id2);
4290 free(path);
4291 if (worktree)
4292 got_worktree_close(worktree);
4293 if (repo) {
4294 const struct got_error *repo_error;
4295 repo_error = got_repo_close(repo);
4296 if (error == NULL)
4297 error = repo_error;
4299 return error;
4302 __dead static void
4303 usage_blame(void)
4305 fprintf(stderr,
4306 "usage: %s blame [-c commit] [-r repository-path] path\n",
4307 getprogname());
4308 exit(1);
4311 struct blame_line {
4312 int annotated;
4313 char *id_str;
4314 char *committer;
4315 char datebuf[11]; /* YYYY-MM-DD + NUL */
4318 struct blame_cb_args {
4319 struct blame_line *lines;
4320 int nlines;
4321 int nlines_prec;
4322 int lineno_cur;
4323 off_t *line_offsets;
4324 FILE *f;
4325 struct got_repository *repo;
4328 static const struct got_error *
4329 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4331 const struct got_error *err = NULL;
4332 struct blame_cb_args *a = arg;
4333 struct blame_line *bline;
4334 char *line = NULL;
4335 size_t linesize = 0;
4336 struct got_commit_object *commit = NULL;
4337 off_t offset;
4338 struct tm tm;
4339 time_t committer_time;
4341 if (nlines != a->nlines ||
4342 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4343 return got_error(GOT_ERR_RANGE);
4345 if (sigint_received)
4346 return got_error(GOT_ERR_ITER_COMPLETED);
4348 if (lineno == -1)
4349 return NULL; /* no change in this commit */
4351 /* Annotate this line. */
4352 bline = &a->lines[lineno - 1];
4353 if (bline->annotated)
4354 return NULL;
4355 err = got_object_id_str(&bline->id_str, id);
4356 if (err)
4357 return err;
4359 err = got_object_open_as_commit(&commit, a->repo, id);
4360 if (err)
4361 goto done;
4363 bline->committer = strdup(got_object_commit_get_committer(commit));
4364 if (bline->committer == NULL) {
4365 err = got_error_from_errno("strdup");
4366 goto done;
4369 committer_time = got_object_commit_get_committer_time(commit);
4370 if (localtime_r(&committer_time, &tm) == NULL)
4371 return got_error_from_errno("localtime_r");
4372 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4373 &tm) >= sizeof(bline->datebuf)) {
4374 err = got_error(GOT_ERR_NO_SPACE);
4375 goto done;
4377 bline->annotated = 1;
4379 /* Print lines annotated so far. */
4380 bline = &a->lines[a->lineno_cur - 1];
4381 if (!bline->annotated)
4382 goto done;
4384 offset = a->line_offsets[a->lineno_cur - 1];
4385 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4386 err = got_error_from_errno("fseeko");
4387 goto done;
4390 while (bline->annotated) {
4391 char *smallerthan, *at, *nl, *committer;
4392 size_t len;
4394 if (getline(&line, &linesize, a->f) == -1) {
4395 if (ferror(a->f))
4396 err = got_error_from_errno("getline");
4397 break;
4400 committer = bline->committer;
4401 smallerthan = strchr(committer, '<');
4402 if (smallerthan && smallerthan[1] != '\0')
4403 committer = smallerthan + 1;
4404 at = strchr(committer, '@');
4405 if (at)
4406 *at = '\0';
4407 len = strlen(committer);
4408 if (len >= 9)
4409 committer[8] = '\0';
4411 nl = strchr(line, '\n');
4412 if (nl)
4413 *nl = '\0';
4414 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4415 bline->id_str, bline->datebuf, committer, line);
4417 a->lineno_cur++;
4418 bline = &a->lines[a->lineno_cur - 1];
4420 done:
4421 if (commit)
4422 got_object_commit_close(commit);
4423 free(line);
4424 return err;
4427 static const struct got_error *
4428 cmd_blame(int argc, char *argv[])
4430 const struct got_error *error;
4431 struct got_repository *repo = NULL;
4432 struct got_worktree *worktree = NULL;
4433 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4434 char *link_target = NULL;
4435 struct got_object_id *obj_id = NULL;
4436 struct got_object_id *commit_id = NULL;
4437 struct got_blob_object *blob = NULL;
4438 char *commit_id_str = NULL;
4439 struct blame_cb_args bca;
4440 int ch, obj_type, i;
4441 off_t filesize;
4443 memset(&bca, 0, sizeof(bca));
4445 #ifndef PROFILE
4446 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4447 NULL) == -1)
4448 err(1, "pledge");
4449 #endif
4451 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4452 switch (ch) {
4453 case 'c':
4454 commit_id_str = optarg;
4455 break;
4456 case 'r':
4457 repo_path = realpath(optarg, NULL);
4458 if (repo_path == NULL)
4459 return got_error_from_errno2("realpath",
4460 optarg);
4461 got_path_strip_trailing_slashes(repo_path);
4462 break;
4463 default:
4464 usage_blame();
4465 /* NOTREACHED */
4469 argc -= optind;
4470 argv += optind;
4472 if (argc == 1)
4473 path = argv[0];
4474 else
4475 usage_blame();
4477 cwd = getcwd(NULL, 0);
4478 if (cwd == NULL) {
4479 error = got_error_from_errno("getcwd");
4480 goto done;
4482 if (repo_path == NULL) {
4483 error = got_worktree_open(&worktree, cwd);
4484 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4485 goto done;
4486 else
4487 error = NULL;
4488 if (worktree) {
4489 repo_path =
4490 strdup(got_worktree_get_repo_path(worktree));
4491 if (repo_path == NULL) {
4492 error = got_error_from_errno("strdup");
4493 if (error)
4494 goto done;
4496 } else {
4497 repo_path = strdup(cwd);
4498 if (repo_path == NULL) {
4499 error = got_error_from_errno("strdup");
4500 goto done;
4505 error = got_repo_open(&repo, repo_path, NULL);
4506 if (error != NULL)
4507 goto done;
4509 if (worktree) {
4510 const char *prefix = got_worktree_get_path_prefix(worktree);
4511 char *p;
4513 error = got_worktree_resolve_path(&p, worktree, path);
4514 if (error)
4515 goto done;
4516 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4517 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4518 p) == -1) {
4519 error = got_error_from_errno("asprintf");
4520 free(p);
4521 goto done;
4523 free(p);
4524 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4525 } else {
4526 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4527 if (error)
4528 goto done;
4529 error = got_repo_map_path(&in_repo_path, repo, path);
4531 if (error)
4532 goto done;
4534 if (commit_id_str == NULL) {
4535 struct got_reference *head_ref;
4536 error = got_ref_open(&head_ref, repo, worktree ?
4537 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4538 if (error != NULL)
4539 goto done;
4540 error = got_ref_resolve(&commit_id, repo, head_ref);
4541 got_ref_close(head_ref);
4542 if (error != NULL)
4543 goto done;
4544 } else {
4545 error = got_repo_match_object_id(&commit_id, NULL,
4546 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4547 if (error)
4548 goto done;
4551 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4552 commit_id, repo);
4553 if (error)
4554 goto done;
4556 error = got_object_id_by_path(&obj_id, repo, commit_id,
4557 link_target ? link_target : in_repo_path);
4558 if (error)
4559 goto done;
4561 error = got_object_get_type(&obj_type, repo, obj_id);
4562 if (error)
4563 goto done;
4565 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4566 error = got_error_path(link_target ? link_target : in_repo_path,
4567 GOT_ERR_OBJ_TYPE);
4568 goto done;
4571 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4572 if (error)
4573 goto done;
4574 bca.f = got_opentemp();
4575 if (bca.f == NULL) {
4576 error = got_error_from_errno("got_opentemp");
4577 goto done;
4579 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4580 &bca.line_offsets, bca.f, blob);
4581 if (error || bca.nlines == 0)
4582 goto done;
4584 /* Don't include \n at EOF in the blame line count. */
4585 if (bca.line_offsets[bca.nlines - 1] == filesize)
4586 bca.nlines--;
4588 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4589 if (bca.lines == NULL) {
4590 error = got_error_from_errno("calloc");
4591 goto done;
4593 bca.lineno_cur = 1;
4594 bca.nlines_prec = 0;
4595 i = bca.nlines;
4596 while (i > 0) {
4597 i /= 10;
4598 bca.nlines_prec++;
4600 bca.repo = repo;
4602 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4603 repo, blame_cb, &bca, check_cancelled, NULL);
4604 done:
4605 free(in_repo_path);
4606 free(link_target);
4607 free(repo_path);
4608 free(cwd);
4609 free(commit_id);
4610 free(obj_id);
4611 if (blob)
4612 got_object_blob_close(blob);
4613 if (worktree)
4614 got_worktree_close(worktree);
4615 if (repo) {
4616 const struct got_error *repo_error;
4617 repo_error = got_repo_close(repo);
4618 if (error == NULL)
4619 error = repo_error;
4621 if (bca.lines) {
4622 for (i = 0; i < bca.nlines; i++) {
4623 struct blame_line *bline = &bca.lines[i];
4624 free(bline->id_str);
4625 free(bline->committer);
4627 free(bca.lines);
4629 free(bca.line_offsets);
4630 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4631 error = got_error_from_errno("fclose");
4632 return error;
4635 __dead static void
4636 usage_tree(void)
4638 fprintf(stderr,
4639 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4640 getprogname());
4641 exit(1);
4644 static const struct got_error *
4645 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4646 const char *root_path, struct got_repository *repo)
4648 const struct got_error *err = NULL;
4649 int is_root_path = (strcmp(path, root_path) == 0);
4650 const char *modestr = "";
4651 mode_t mode = got_tree_entry_get_mode(te);
4652 char *link_target = NULL;
4654 path += strlen(root_path);
4655 while (path[0] == '/')
4656 path++;
4658 if (got_object_tree_entry_is_submodule(te))
4659 modestr = "$";
4660 else if (S_ISLNK(mode)) {
4661 int i;
4663 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4664 if (err)
4665 return err;
4666 for (i = 0; i < strlen(link_target); i++) {
4667 if (!isprint((unsigned char)link_target[i]))
4668 link_target[i] = '?';
4671 modestr = "@";
4673 else if (S_ISDIR(mode))
4674 modestr = "/";
4675 else if (mode & S_IXUSR)
4676 modestr = "*";
4678 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4679 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4680 link_target ? " -> ": "", link_target ? link_target : "");
4682 free(link_target);
4683 return NULL;
4686 static const struct got_error *
4687 print_tree(const char *path, struct got_object_id *commit_id,
4688 int show_ids, int recurse, const char *root_path,
4689 struct got_repository *repo)
4691 const struct got_error *err = NULL;
4692 struct got_object_id *tree_id = NULL;
4693 struct got_tree_object *tree = NULL;
4694 int nentries, i;
4696 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4697 if (err)
4698 goto done;
4700 err = got_object_open_as_tree(&tree, repo, tree_id);
4701 if (err)
4702 goto done;
4703 nentries = got_object_tree_get_nentries(tree);
4704 for (i = 0; i < nentries; i++) {
4705 struct got_tree_entry *te;
4706 char *id = NULL;
4708 if (sigint_received || sigpipe_received)
4709 break;
4711 te = got_object_tree_get_entry(tree, i);
4712 if (show_ids) {
4713 char *id_str;
4714 err = got_object_id_str(&id_str,
4715 got_tree_entry_get_id(te));
4716 if (err)
4717 goto done;
4718 if (asprintf(&id, "%s ", id_str) == -1) {
4719 err = got_error_from_errno("asprintf");
4720 free(id_str);
4721 goto done;
4723 free(id_str);
4725 err = print_entry(te, id, path, root_path, repo);
4726 free(id);
4727 if (err)
4728 goto done;
4730 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4731 char *child_path;
4732 if (asprintf(&child_path, "%s%s%s", path,
4733 path[0] == '/' && path[1] == '\0' ? "" : "/",
4734 got_tree_entry_get_name(te)) == -1) {
4735 err = got_error_from_errno("asprintf");
4736 goto done;
4738 err = print_tree(child_path, commit_id, show_ids, 1,
4739 root_path, repo);
4740 free(child_path);
4741 if (err)
4742 goto done;
4745 done:
4746 if (tree)
4747 got_object_tree_close(tree);
4748 free(tree_id);
4749 return err;
4752 static const struct got_error *
4753 cmd_tree(int argc, char *argv[])
4755 const struct got_error *error;
4756 struct got_repository *repo = NULL;
4757 struct got_worktree *worktree = NULL;
4758 const char *path, *refname = NULL;
4759 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4760 struct got_object_id *commit_id = NULL;
4761 char *commit_id_str = NULL;
4762 int show_ids = 0, recurse = 0;
4763 int ch;
4765 #ifndef PROFILE
4766 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4767 NULL) == -1)
4768 err(1, "pledge");
4769 #endif
4771 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4772 switch (ch) {
4773 case 'c':
4774 commit_id_str = optarg;
4775 break;
4776 case 'r':
4777 repo_path = realpath(optarg, NULL);
4778 if (repo_path == NULL)
4779 return got_error_from_errno2("realpath",
4780 optarg);
4781 got_path_strip_trailing_slashes(repo_path);
4782 break;
4783 case 'i':
4784 show_ids = 1;
4785 break;
4786 case 'R':
4787 recurse = 1;
4788 break;
4789 default:
4790 usage_tree();
4791 /* NOTREACHED */
4795 argc -= optind;
4796 argv += optind;
4798 if (argc == 1)
4799 path = argv[0];
4800 else if (argc > 1)
4801 usage_tree();
4802 else
4803 path = NULL;
4805 cwd = getcwd(NULL, 0);
4806 if (cwd == NULL) {
4807 error = got_error_from_errno("getcwd");
4808 goto done;
4810 if (repo_path == NULL) {
4811 error = got_worktree_open(&worktree, cwd);
4812 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4813 goto done;
4814 else
4815 error = NULL;
4816 if (worktree) {
4817 repo_path =
4818 strdup(got_worktree_get_repo_path(worktree));
4819 if (repo_path == NULL)
4820 error = got_error_from_errno("strdup");
4821 if (error)
4822 goto done;
4823 } else {
4824 repo_path = strdup(cwd);
4825 if (repo_path == NULL) {
4826 error = got_error_from_errno("strdup");
4827 goto done;
4832 error = got_repo_open(&repo, repo_path, NULL);
4833 if (error != NULL)
4834 goto done;
4836 if (worktree) {
4837 const char *prefix = got_worktree_get_path_prefix(worktree);
4838 char *p;
4840 if (path == NULL)
4841 path = "";
4842 error = got_worktree_resolve_path(&p, worktree, path);
4843 if (error)
4844 goto done;
4845 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4846 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4847 p) == -1) {
4848 error = got_error_from_errno("asprintf");
4849 free(p);
4850 goto done;
4852 free(p);
4853 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4854 if (error)
4855 goto done;
4856 } else {
4857 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4858 if (error)
4859 goto done;
4860 if (path == NULL)
4861 path = "/";
4862 error = got_repo_map_path(&in_repo_path, repo, path);
4863 if (error != NULL)
4864 goto done;
4867 if (commit_id_str == NULL) {
4868 struct got_reference *head_ref;
4869 if (worktree)
4870 refname = got_worktree_get_head_ref_name(worktree);
4871 else
4872 refname = GOT_REF_HEAD;
4873 error = got_ref_open(&head_ref, repo, refname, 0);
4874 if (error != NULL)
4875 goto done;
4876 error = got_ref_resolve(&commit_id, repo, head_ref);
4877 got_ref_close(head_ref);
4878 if (error != NULL)
4879 goto done;
4880 } else {
4881 error = got_repo_match_object_id(&commit_id, NULL,
4882 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4883 if (error)
4884 goto done;
4887 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4888 in_repo_path, repo);
4889 done:
4890 free(in_repo_path);
4891 free(repo_path);
4892 free(cwd);
4893 free(commit_id);
4894 if (worktree)
4895 got_worktree_close(worktree);
4896 if (repo) {
4897 const struct got_error *repo_error;
4898 repo_error = got_repo_close(repo);
4899 if (error == NULL)
4900 error = repo_error;
4902 return error;
4905 __dead static void
4906 usage_status(void)
4908 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4909 getprogname());
4910 exit(1);
4913 static const struct got_error *
4914 print_status(void *arg, unsigned char status, unsigned char staged_status,
4915 const char *path, struct got_object_id *blob_id,
4916 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4917 int dirfd, const char *de_name)
4919 if (status == staged_status && (status == GOT_STATUS_DELETE))
4920 status = GOT_STATUS_NO_CHANGE;
4921 if (arg) {
4922 char *status_codes = arg;
4923 size_t ncodes = strlen(status_codes);
4924 int i;
4925 for (i = 0; i < ncodes ; i++) {
4926 if (status == status_codes[i] ||
4927 staged_status == status_codes[i])
4928 break;
4930 if (i == ncodes)
4931 return NULL;
4933 printf("%c%c %s\n", status, staged_status, path);
4934 return NULL;
4937 static const struct got_error *
4938 cmd_status(int argc, char *argv[])
4940 const struct got_error *error = NULL;
4941 struct got_repository *repo = NULL;
4942 struct got_worktree *worktree = NULL;
4943 char *cwd = NULL, *status_codes = NULL;;
4944 struct got_pathlist_head paths;
4945 struct got_pathlist_entry *pe;
4946 int ch, i;
4948 TAILQ_INIT(&paths);
4950 while ((ch = getopt(argc, argv, "s:")) != -1) {
4951 switch (ch) {
4952 case 's':
4953 for (i = 0; i < strlen(optarg); i++) {
4954 switch (optarg[i]) {
4955 case GOT_STATUS_MODIFY:
4956 case GOT_STATUS_ADD:
4957 case GOT_STATUS_DELETE:
4958 case GOT_STATUS_CONFLICT:
4959 case GOT_STATUS_MISSING:
4960 case GOT_STATUS_OBSTRUCTED:
4961 case GOT_STATUS_UNVERSIONED:
4962 case GOT_STATUS_MODE_CHANGE:
4963 case GOT_STATUS_NONEXISTENT:
4964 break;
4965 default:
4966 errx(1, "invalid status code '%c'",
4967 optarg[i]);
4970 status_codes = optarg;
4971 break;
4972 default:
4973 usage_status();
4974 /* NOTREACHED */
4978 argc -= optind;
4979 argv += optind;
4981 #ifndef PROFILE
4982 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4983 NULL) == -1)
4984 err(1, "pledge");
4985 #endif
4986 cwd = getcwd(NULL, 0);
4987 if (cwd == NULL) {
4988 error = got_error_from_errno("getcwd");
4989 goto done;
4992 error = got_worktree_open(&worktree, cwd);
4993 if (error) {
4994 if (error->code == GOT_ERR_NOT_WORKTREE)
4995 error = wrap_not_worktree_error(error, "status", cwd);
4996 goto done;
4999 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5000 NULL);
5001 if (error != NULL)
5002 goto done;
5004 error = apply_unveil(got_repo_get_path(repo), 1,
5005 got_worktree_get_root_path(worktree));
5006 if (error)
5007 goto done;
5009 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5010 if (error)
5011 goto done;
5013 error = got_worktree_status(worktree, &paths, repo, print_status,
5014 status_codes, check_cancelled, NULL);
5015 done:
5016 TAILQ_FOREACH(pe, &paths, entry)
5017 free((char *)pe->path);
5018 got_pathlist_free(&paths);
5019 free(cwd);
5020 return error;
5023 __dead static void
5024 usage_ref(void)
5026 fprintf(stderr,
5027 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5028 "[-d] [name]\n",
5029 getprogname());
5030 exit(1);
5033 static const struct got_error *
5034 list_refs(struct got_repository *repo, const char *refname)
5036 static const struct got_error *err = NULL;
5037 struct got_reflist_head refs;
5038 struct got_reflist_entry *re;
5040 SIMPLEQ_INIT(&refs);
5041 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5042 if (err)
5043 return err;
5045 SIMPLEQ_FOREACH(re, &refs, entry) {
5046 char *refstr;
5047 refstr = got_ref_to_str(re->ref);
5048 if (refstr == NULL)
5049 return got_error_from_errno("got_ref_to_str");
5050 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5051 free(refstr);
5054 got_ref_list_free(&refs);
5055 return NULL;
5058 static const struct got_error *
5059 delete_ref(struct got_repository *repo, const char *refname)
5061 const struct got_error *err = NULL;
5062 struct got_reference *ref;
5064 err = got_ref_open(&ref, repo, refname, 0);
5065 if (err)
5066 return err;
5068 err = got_ref_delete(ref, repo);
5069 got_ref_close(ref);
5070 return err;
5073 static const struct got_error *
5074 add_ref(struct got_repository *repo, const char *refname, const char *target)
5076 const struct got_error *err = NULL;
5077 struct got_object_id *id;
5078 struct got_reference *ref = NULL;
5081 * Don't let the user create a reference name with a leading '-'.
5082 * While technically a valid reference name, this case is usually
5083 * an unintended typo.
5085 if (refname[0] == '-')
5086 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5088 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5089 repo);
5090 if (err) {
5091 struct got_reference *target_ref;
5093 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5094 return err;
5095 err = got_ref_open(&target_ref, repo, target, 0);
5096 if (err)
5097 return err;
5098 err = got_ref_resolve(&id, repo, target_ref);
5099 got_ref_close(target_ref);
5100 if (err)
5101 return err;
5104 err = got_ref_alloc(&ref, refname, id);
5105 if (err)
5106 goto done;
5108 err = got_ref_write(ref, repo);
5109 done:
5110 if (ref)
5111 got_ref_close(ref);
5112 free(id);
5113 return err;
5116 static const struct got_error *
5117 add_symref(struct got_repository *repo, const char *refname, const char *target)
5119 const struct got_error *err = NULL;
5120 struct got_reference *ref = NULL;
5121 struct got_reference *target_ref = NULL;
5124 * Don't let the user create a reference name with a leading '-'.
5125 * While technically a valid reference name, this case is usually
5126 * an unintended typo.
5128 if (refname[0] == '-')
5129 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5131 err = got_ref_open(&target_ref, repo, target, 0);
5132 if (err)
5133 return err;
5135 err = got_ref_alloc_symref(&ref, refname, target_ref);
5136 if (err)
5137 goto done;
5139 err = got_ref_write(ref, repo);
5140 done:
5141 if (target_ref)
5142 got_ref_close(target_ref);
5143 if (ref)
5144 got_ref_close(ref);
5145 return err;
5148 static const struct got_error *
5149 cmd_ref(int argc, char *argv[])
5151 const struct got_error *error = NULL;
5152 struct got_repository *repo = NULL;
5153 struct got_worktree *worktree = NULL;
5154 char *cwd = NULL, *repo_path = NULL;
5155 int ch, do_list = 0, do_delete = 0;
5156 const char *obj_arg = NULL, *symref_target= NULL;
5157 char *refname = NULL;
5159 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5160 switch (ch) {
5161 case 'c':
5162 obj_arg = optarg;
5163 break;
5164 case 'd':
5165 do_delete = 1;
5166 break;
5167 case 'r':
5168 repo_path = realpath(optarg, NULL);
5169 if (repo_path == NULL)
5170 return got_error_from_errno2("realpath",
5171 optarg);
5172 got_path_strip_trailing_slashes(repo_path);
5173 break;
5174 case 'l':
5175 do_list = 1;
5176 break;
5177 case 's':
5178 symref_target = optarg;
5179 break;
5180 default:
5181 usage_ref();
5182 /* NOTREACHED */
5186 if (obj_arg && do_list)
5187 errx(1, "-c and -l options are mutually exclusive");
5188 if (obj_arg && do_delete)
5189 errx(1, "-c and -d options are mutually exclusive");
5190 if (obj_arg && symref_target)
5191 errx(1, "-c and -s options are mutually exclusive");
5192 if (symref_target && do_delete)
5193 errx(1, "-s and -d options are mutually exclusive");
5194 if (symref_target && do_list)
5195 errx(1, "-s and -l options are mutually exclusive");
5196 if (do_delete && do_list)
5197 errx(1, "-d and -l options are mutually exclusive");
5199 argc -= optind;
5200 argv += optind;
5202 if (do_list) {
5203 if (argc != 0 && argc != 1)
5204 usage_ref();
5205 if (argc == 1) {
5206 refname = strdup(argv[0]);
5207 if (refname == NULL) {
5208 error = got_error_from_errno("strdup");
5209 goto done;
5212 } else {
5213 if (argc != 1)
5214 usage_ref();
5215 refname = strdup(argv[0]);
5216 if (refname == NULL) {
5217 error = got_error_from_errno("strdup");
5218 goto done;
5222 if (refname)
5223 got_path_strip_trailing_slashes(refname);
5225 #ifndef PROFILE
5226 if (do_list) {
5227 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5228 NULL) == -1)
5229 err(1, "pledge");
5230 } else {
5231 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5232 "sendfd unveil", NULL) == -1)
5233 err(1, "pledge");
5235 #endif
5236 cwd = getcwd(NULL, 0);
5237 if (cwd == NULL) {
5238 error = got_error_from_errno("getcwd");
5239 goto done;
5242 if (repo_path == NULL) {
5243 error = got_worktree_open(&worktree, cwd);
5244 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5245 goto done;
5246 else
5247 error = NULL;
5248 if (worktree) {
5249 repo_path =
5250 strdup(got_worktree_get_repo_path(worktree));
5251 if (repo_path == NULL)
5252 error = got_error_from_errno("strdup");
5253 if (error)
5254 goto done;
5255 } else {
5256 repo_path = strdup(cwd);
5257 if (repo_path == NULL) {
5258 error = got_error_from_errno("strdup");
5259 goto done;
5264 error = got_repo_open(&repo, repo_path, NULL);
5265 if (error != NULL)
5266 goto done;
5268 error = apply_unveil(got_repo_get_path(repo), do_list,
5269 worktree ? got_worktree_get_root_path(worktree) : NULL);
5270 if (error)
5271 goto done;
5273 if (do_list)
5274 error = list_refs(repo, refname);
5275 else if (do_delete)
5276 error = delete_ref(repo, refname);
5277 else if (symref_target)
5278 error = add_symref(repo, refname, symref_target);
5279 else {
5280 if (obj_arg == NULL)
5281 usage_ref();
5282 error = add_ref(repo, refname, obj_arg);
5284 done:
5285 free(refname);
5286 if (repo)
5287 got_repo_close(repo);
5288 if (worktree)
5289 got_worktree_close(worktree);
5290 free(cwd);
5291 free(repo_path);
5292 return error;
5295 __dead static void
5296 usage_branch(void)
5298 fprintf(stderr,
5299 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5300 "[name]\n", getprogname());
5301 exit(1);
5304 static const struct got_error *
5305 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5306 struct got_reference *ref)
5308 const struct got_error *err = NULL;
5309 const char *refname, *marker = " ";
5310 char *refstr;
5312 refname = got_ref_get_name(ref);
5313 if (worktree && strcmp(refname,
5314 got_worktree_get_head_ref_name(worktree)) == 0) {
5315 struct got_object_id *id = NULL;
5317 err = got_ref_resolve(&id, repo, ref);
5318 if (err)
5319 return err;
5320 if (got_object_id_cmp(id,
5321 got_worktree_get_base_commit_id(worktree)) == 0)
5322 marker = "* ";
5323 else
5324 marker = "~ ";
5325 free(id);
5328 if (strncmp(refname, "refs/heads/", 11) == 0)
5329 refname += 11;
5330 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5331 refname += 18;
5333 refstr = got_ref_to_str(ref);
5334 if (refstr == NULL)
5335 return got_error_from_errno("got_ref_to_str");
5337 printf("%s%s: %s\n", marker, refname, refstr);
5338 free(refstr);
5339 return NULL;
5342 static const struct got_error *
5343 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5345 const char *refname;
5347 if (worktree == NULL)
5348 return got_error(GOT_ERR_NOT_WORKTREE);
5350 refname = got_worktree_get_head_ref_name(worktree);
5352 if (strncmp(refname, "refs/heads/", 11) == 0)
5353 refname += 11;
5354 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5355 refname += 18;
5357 printf("%s\n", refname);
5359 return NULL;
5362 static const struct got_error *
5363 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5365 static const struct got_error *err = NULL;
5366 struct got_reflist_head refs;
5367 struct got_reflist_entry *re;
5368 struct got_reference *temp_ref = NULL;
5369 int rebase_in_progress, histedit_in_progress;
5371 SIMPLEQ_INIT(&refs);
5373 if (worktree) {
5374 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5375 worktree);
5376 if (err)
5377 return err;
5379 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5380 worktree);
5381 if (err)
5382 return err;
5384 if (rebase_in_progress || histedit_in_progress) {
5385 err = got_ref_open(&temp_ref, repo,
5386 got_worktree_get_head_ref_name(worktree), 0);
5387 if (err)
5388 return err;
5389 list_branch(repo, worktree, temp_ref);
5390 got_ref_close(temp_ref);
5394 err = got_ref_list(&refs, repo, "refs/heads",
5395 got_ref_cmp_by_name, NULL);
5396 if (err)
5397 return err;
5399 SIMPLEQ_FOREACH(re, &refs, entry)
5400 list_branch(repo, worktree, re->ref);
5402 got_ref_list_free(&refs);
5403 return NULL;
5406 static const struct got_error *
5407 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5408 const char *branch_name)
5410 const struct got_error *err = NULL;
5411 struct got_reference *ref = NULL;
5412 char *refname;
5414 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5415 return got_error_from_errno("asprintf");
5417 err = got_ref_open(&ref, repo, refname, 0);
5418 if (err)
5419 goto done;
5421 if (worktree &&
5422 strcmp(got_worktree_get_head_ref_name(worktree),
5423 got_ref_get_name(ref)) == 0) {
5424 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5425 "will not delete this work tree's current branch");
5426 goto done;
5429 err = got_ref_delete(ref, repo);
5430 done:
5431 if (ref)
5432 got_ref_close(ref);
5433 free(refname);
5434 return err;
5437 static const struct got_error *
5438 add_branch(struct got_repository *repo, const char *branch_name,
5439 struct got_object_id *base_commit_id)
5441 const struct got_error *err = NULL;
5442 struct got_reference *ref = NULL;
5443 char *base_refname = NULL, *refname = NULL;
5446 * Don't let the user create a branch name with a leading '-'.
5447 * While technically a valid reference name, this case is usually
5448 * an unintended typo.
5450 if (branch_name[0] == '-')
5451 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5453 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5454 err = got_error_from_errno("asprintf");
5455 goto done;
5458 err = got_ref_open(&ref, repo, refname, 0);
5459 if (err == NULL) {
5460 err = got_error(GOT_ERR_BRANCH_EXISTS);
5461 goto done;
5462 } else if (err->code != GOT_ERR_NOT_REF)
5463 goto done;
5465 err = got_ref_alloc(&ref, refname, base_commit_id);
5466 if (err)
5467 goto done;
5469 err = got_ref_write(ref, repo);
5470 done:
5471 if (ref)
5472 got_ref_close(ref);
5473 free(base_refname);
5474 free(refname);
5475 return err;
5478 static const struct got_error *
5479 cmd_branch(int argc, char *argv[])
5481 const struct got_error *error = NULL;
5482 struct got_repository *repo = NULL;
5483 struct got_worktree *worktree = NULL;
5484 char *cwd = NULL, *repo_path = NULL;
5485 int ch, do_list = 0, do_show = 0, do_update = 1;
5486 const char *delref = NULL, *commit_id_arg = NULL;
5487 struct got_reference *ref = NULL;
5488 struct got_pathlist_head paths;
5489 struct got_pathlist_entry *pe;
5490 struct got_object_id *commit_id = NULL;
5491 char *commit_id_str = NULL;
5493 TAILQ_INIT(&paths);
5495 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5496 switch (ch) {
5497 case 'c':
5498 commit_id_arg = optarg;
5499 break;
5500 case 'd':
5501 delref = optarg;
5502 break;
5503 case 'r':
5504 repo_path = realpath(optarg, NULL);
5505 if (repo_path == NULL)
5506 return got_error_from_errno2("realpath",
5507 optarg);
5508 got_path_strip_trailing_slashes(repo_path);
5509 break;
5510 case 'l':
5511 do_list = 1;
5512 break;
5513 case 'n':
5514 do_update = 0;
5515 break;
5516 default:
5517 usage_branch();
5518 /* NOTREACHED */
5522 if (do_list && delref)
5523 errx(1, "-l and -d options are mutually exclusive");
5525 argc -= optind;
5526 argv += optind;
5528 if (!do_list && !delref && argc == 0)
5529 do_show = 1;
5531 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5532 errx(1, "-c option can only be used when creating a branch");
5534 if (do_list || delref) {
5535 if (argc > 0)
5536 usage_branch();
5537 } else if (!do_show && argc != 1)
5538 usage_branch();
5540 #ifndef PROFILE
5541 if (do_list || do_show) {
5542 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5543 NULL) == -1)
5544 err(1, "pledge");
5545 } else {
5546 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5547 "sendfd unveil", NULL) == -1)
5548 err(1, "pledge");
5550 #endif
5551 cwd = getcwd(NULL, 0);
5552 if (cwd == NULL) {
5553 error = got_error_from_errno("getcwd");
5554 goto done;
5557 if (repo_path == NULL) {
5558 error = got_worktree_open(&worktree, cwd);
5559 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5560 goto done;
5561 else
5562 error = NULL;
5563 if (worktree) {
5564 repo_path =
5565 strdup(got_worktree_get_repo_path(worktree));
5566 if (repo_path == NULL)
5567 error = got_error_from_errno("strdup");
5568 if (error)
5569 goto done;
5570 } else {
5571 repo_path = strdup(cwd);
5572 if (repo_path == NULL) {
5573 error = got_error_from_errno("strdup");
5574 goto done;
5579 error = got_repo_open(&repo, repo_path, NULL);
5580 if (error != NULL)
5581 goto done;
5583 error = apply_unveil(got_repo_get_path(repo), do_list,
5584 worktree ? got_worktree_get_root_path(worktree) : NULL);
5585 if (error)
5586 goto done;
5588 if (do_show)
5589 error = show_current_branch(repo, worktree);
5590 else if (do_list)
5591 error = list_branches(repo, worktree);
5592 else if (delref)
5593 error = delete_branch(repo, worktree, delref);
5594 else {
5595 if (commit_id_arg == NULL)
5596 commit_id_arg = worktree ?
5597 got_worktree_get_head_ref_name(worktree) :
5598 GOT_REF_HEAD;
5599 error = got_repo_match_object_id(&commit_id, NULL,
5600 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5601 if (error)
5602 goto done;
5603 error = add_branch(repo, argv[0], commit_id);
5604 if (error)
5605 goto done;
5606 if (worktree && do_update) {
5607 struct got_update_progress_arg upa;
5608 char *branch_refname = NULL;
5610 error = got_object_id_str(&commit_id_str, commit_id);
5611 if (error)
5612 goto done;
5613 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5614 worktree);
5615 if (error)
5616 goto done;
5617 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5618 == -1) {
5619 error = got_error_from_errno("asprintf");
5620 goto done;
5622 error = got_ref_open(&ref, repo, branch_refname, 0);
5623 free(branch_refname);
5624 if (error)
5625 goto done;
5626 error = switch_head_ref(ref, commit_id, worktree,
5627 repo);
5628 if (error)
5629 goto done;
5630 error = got_worktree_set_base_commit_id(worktree, repo,
5631 commit_id);
5632 if (error)
5633 goto done;
5634 memset(&upa, 0, sizeof(upa));
5635 error = got_worktree_checkout_files(worktree, &paths,
5636 repo, update_progress, &upa, check_cancelled,
5637 NULL);
5638 if (error)
5639 goto done;
5640 if (upa.did_something)
5641 printf("Updated to commit %s\n", commit_id_str);
5642 print_update_progress_stats(&upa);
5645 done:
5646 if (ref)
5647 got_ref_close(ref);
5648 if (repo)
5649 got_repo_close(repo);
5650 if (worktree)
5651 got_worktree_close(worktree);
5652 free(cwd);
5653 free(repo_path);
5654 free(commit_id);
5655 free(commit_id_str);
5656 TAILQ_FOREACH(pe, &paths, entry)
5657 free((char *)pe->path);
5658 got_pathlist_free(&paths);
5659 return error;
5663 __dead static void
5664 usage_tag(void)
5666 fprintf(stderr,
5667 "usage: %s tag [-c commit] [-r repository] [-l] "
5668 "[-m message] name\n", getprogname());
5669 exit(1);
5672 #if 0
5673 static const struct got_error *
5674 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5676 const struct got_error *err = NULL;
5677 struct got_reflist_entry *re, *se, *new;
5678 struct got_object_id *re_id, *se_id;
5679 struct got_tag_object *re_tag, *se_tag;
5680 time_t re_time, se_time;
5682 SIMPLEQ_FOREACH(re, tags, entry) {
5683 se = SIMPLEQ_FIRST(sorted);
5684 if (se == NULL) {
5685 err = got_reflist_entry_dup(&new, re);
5686 if (err)
5687 return err;
5688 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5689 continue;
5690 } else {
5691 err = got_ref_resolve(&re_id, repo, re->ref);
5692 if (err)
5693 break;
5694 err = got_object_open_as_tag(&re_tag, repo, re_id);
5695 free(re_id);
5696 if (err)
5697 break;
5698 re_time = got_object_tag_get_tagger_time(re_tag);
5699 got_object_tag_close(re_tag);
5702 while (se) {
5703 err = got_ref_resolve(&se_id, repo, re->ref);
5704 if (err)
5705 break;
5706 err = got_object_open_as_tag(&se_tag, repo, se_id);
5707 free(se_id);
5708 if (err)
5709 break;
5710 se_time = got_object_tag_get_tagger_time(se_tag);
5711 got_object_tag_close(se_tag);
5713 if (se_time > re_time) {
5714 err = got_reflist_entry_dup(&new, re);
5715 if (err)
5716 return err;
5717 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5718 break;
5720 se = SIMPLEQ_NEXT(se, entry);
5721 continue;
5724 done:
5725 return err;
5727 #endif
5729 static const struct got_error *
5730 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5732 static const struct got_error *err = NULL;
5733 struct got_reflist_head refs;
5734 struct got_reflist_entry *re;
5736 SIMPLEQ_INIT(&refs);
5738 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5739 if (err)
5740 return err;
5742 SIMPLEQ_FOREACH(re, &refs, entry) {
5743 const char *refname;
5744 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5745 char datebuf[26];
5746 const char *tagger;
5747 time_t tagger_time;
5748 struct got_object_id *id;
5749 struct got_tag_object *tag;
5750 struct got_commit_object *commit = NULL;
5752 refname = got_ref_get_name(re->ref);
5753 if (strncmp(refname, "refs/tags/", 10) != 0)
5754 continue;
5755 refname += 10;
5756 refstr = got_ref_to_str(re->ref);
5757 if (refstr == NULL) {
5758 err = got_error_from_errno("got_ref_to_str");
5759 break;
5761 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5762 free(refstr);
5764 err = got_ref_resolve(&id, repo, re->ref);
5765 if (err)
5766 break;
5767 err = got_object_open_as_tag(&tag, repo, id);
5768 if (err) {
5769 if (err->code != GOT_ERR_OBJ_TYPE) {
5770 free(id);
5771 break;
5773 /* "lightweight" tag */
5774 err = got_object_open_as_commit(&commit, repo, id);
5775 if (err) {
5776 free(id);
5777 break;
5779 tagger = got_object_commit_get_committer(commit);
5780 tagger_time =
5781 got_object_commit_get_committer_time(commit);
5782 err = got_object_id_str(&id_str, id);
5783 free(id);
5784 if (err)
5785 break;
5786 } else {
5787 free(id);
5788 tagger = got_object_tag_get_tagger(tag);
5789 tagger_time = got_object_tag_get_tagger_time(tag);
5790 err = got_object_id_str(&id_str,
5791 got_object_tag_get_object_id(tag));
5792 if (err)
5793 break;
5795 printf("from: %s\n", tagger);
5796 datestr = get_datestr(&tagger_time, datebuf);
5797 if (datestr)
5798 printf("date: %s UTC\n", datestr);
5799 if (commit)
5800 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5801 else {
5802 switch (got_object_tag_get_object_type(tag)) {
5803 case GOT_OBJ_TYPE_BLOB:
5804 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5805 id_str);
5806 break;
5807 case GOT_OBJ_TYPE_TREE:
5808 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5809 id_str);
5810 break;
5811 case GOT_OBJ_TYPE_COMMIT:
5812 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5813 id_str);
5814 break;
5815 case GOT_OBJ_TYPE_TAG:
5816 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5817 id_str);
5818 break;
5819 default:
5820 break;
5823 free(id_str);
5824 if (commit) {
5825 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5826 if (err)
5827 break;
5828 got_object_commit_close(commit);
5829 } else {
5830 tagmsg0 = strdup(got_object_tag_get_message(tag));
5831 got_object_tag_close(tag);
5832 if (tagmsg0 == NULL) {
5833 err = got_error_from_errno("strdup");
5834 break;
5838 tagmsg = tagmsg0;
5839 do {
5840 line = strsep(&tagmsg, "\n");
5841 if (line)
5842 printf(" %s\n", line);
5843 } while (line);
5844 free(tagmsg0);
5847 got_ref_list_free(&refs);
5848 return NULL;
5851 static const struct got_error *
5852 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5853 const char *tag_name, const char *repo_path)
5855 const struct got_error *err = NULL;
5856 char *template = NULL, *initial_content = NULL;
5857 char *editor = NULL;
5858 int initial_content_len;
5859 int fd = -1;
5861 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5862 err = got_error_from_errno("asprintf");
5863 goto done;
5866 initial_content_len = asprintf(&initial_content,
5867 "\n# tagging commit %s as %s\n",
5868 commit_id_str, tag_name);
5869 if (initial_content_len == -1) {
5870 err = got_error_from_errno("asprintf");
5871 goto done;
5874 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5875 if (err)
5876 goto done;
5878 if (write(fd, initial_content, initial_content_len) == -1) {
5879 err = got_error_from_errno2("write", *tagmsg_path);
5880 goto done;
5883 err = get_editor(&editor);
5884 if (err)
5885 goto done;
5886 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
5887 initial_content_len);
5888 done:
5889 free(initial_content);
5890 free(template);
5891 free(editor);
5893 if (fd != -1 && close(fd) == -1 && err == NULL)
5894 err = got_error_from_errno2("close", *tagmsg_path);
5896 /* Editor is done; we can now apply unveil(2) */
5897 if (err == NULL)
5898 err = apply_unveil(repo_path, 0, NULL);
5899 if (err) {
5900 free(*tagmsg);
5901 *tagmsg = NULL;
5903 return err;
5906 static const struct got_error *
5907 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5908 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5910 const struct got_error *err = NULL;
5911 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5912 char *label = NULL, *commit_id_str = NULL;
5913 struct got_reference *ref = NULL;
5914 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5915 char *tagmsg_path = NULL, *tag_id_str = NULL;
5916 int preserve_tagmsg = 0;
5919 * Don't let the user create a tag name with a leading '-'.
5920 * While technically a valid reference name, this case is usually
5921 * an unintended typo.
5923 if (tag_name[0] == '-')
5924 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5926 err = get_author(&tagger, repo, worktree);
5927 if (err)
5928 return err;
5930 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5931 GOT_OBJ_TYPE_COMMIT, 1, repo);
5932 if (err)
5933 goto done;
5935 err = got_object_id_str(&commit_id_str, commit_id);
5936 if (err)
5937 goto done;
5939 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5940 refname = strdup(tag_name);
5941 if (refname == NULL) {
5942 err = got_error_from_errno("strdup");
5943 goto done;
5945 tag_name += 10;
5946 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5947 err = got_error_from_errno("asprintf");
5948 goto done;
5951 err = got_ref_open(&ref, repo, refname, 0);
5952 if (err == NULL) {
5953 err = got_error(GOT_ERR_TAG_EXISTS);
5954 goto done;
5955 } else if (err->code != GOT_ERR_NOT_REF)
5956 goto done;
5958 if (tagmsg_arg == NULL) {
5959 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5960 tag_name, got_repo_get_path(repo));
5961 if (err) {
5962 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5963 tagmsg_path != NULL)
5964 preserve_tagmsg = 1;
5965 goto done;
5969 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5970 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5971 if (err) {
5972 if (tagmsg_path)
5973 preserve_tagmsg = 1;
5974 goto done;
5977 err = got_ref_alloc(&ref, refname, tag_id);
5978 if (err) {
5979 if (tagmsg_path)
5980 preserve_tagmsg = 1;
5981 goto done;
5984 err = got_ref_write(ref, repo);
5985 if (err) {
5986 if (tagmsg_path)
5987 preserve_tagmsg = 1;
5988 goto done;
5991 err = got_object_id_str(&tag_id_str, tag_id);
5992 if (err) {
5993 if (tagmsg_path)
5994 preserve_tagmsg = 1;
5995 goto done;
5997 printf("Created tag %s\n", tag_id_str);
5998 done:
5999 if (preserve_tagmsg) {
6000 fprintf(stderr, "%s: tag message preserved in %s\n",
6001 getprogname(), tagmsg_path);
6002 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6003 err = got_error_from_errno2("unlink", tagmsg_path);
6004 free(tag_id_str);
6005 if (ref)
6006 got_ref_close(ref);
6007 free(commit_id);
6008 free(commit_id_str);
6009 free(refname);
6010 free(tagmsg);
6011 free(tagmsg_path);
6012 free(tagger);
6013 return err;
6016 static const struct got_error *
6017 cmd_tag(int argc, char *argv[])
6019 const struct got_error *error = NULL;
6020 struct got_repository *repo = NULL;
6021 struct got_worktree *worktree = NULL;
6022 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6023 char *gitconfig_path = NULL;
6024 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6025 int ch, do_list = 0;
6027 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6028 switch (ch) {
6029 case 'c':
6030 commit_id_arg = optarg;
6031 break;
6032 case 'm':
6033 tagmsg = optarg;
6034 break;
6035 case 'r':
6036 repo_path = realpath(optarg, NULL);
6037 if (repo_path == NULL)
6038 return got_error_from_errno2("realpath",
6039 optarg);
6040 got_path_strip_trailing_slashes(repo_path);
6041 break;
6042 case 'l':
6043 do_list = 1;
6044 break;
6045 default:
6046 usage_tag();
6047 /* NOTREACHED */
6051 argc -= optind;
6052 argv += optind;
6054 if (do_list) {
6055 if (commit_id_arg != NULL)
6056 errx(1,
6057 "-c option can only be used when creating a tag");
6058 if (tagmsg)
6059 errx(1, "-l and -m options are mutually exclusive");
6060 if (argc > 0)
6061 usage_tag();
6062 } else if (argc != 1)
6063 usage_tag();
6065 tag_name = argv[0];
6067 #ifndef PROFILE
6068 if (do_list) {
6069 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6070 NULL) == -1)
6071 err(1, "pledge");
6072 } else {
6073 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6074 "sendfd unveil", NULL) == -1)
6075 err(1, "pledge");
6077 #endif
6078 cwd = getcwd(NULL, 0);
6079 if (cwd == NULL) {
6080 error = got_error_from_errno("getcwd");
6081 goto done;
6084 if (repo_path == NULL) {
6085 error = got_worktree_open(&worktree, cwd);
6086 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6087 goto done;
6088 else
6089 error = NULL;
6090 if (worktree) {
6091 repo_path =
6092 strdup(got_worktree_get_repo_path(worktree));
6093 if (repo_path == NULL)
6094 error = got_error_from_errno("strdup");
6095 if (error)
6096 goto done;
6097 } else {
6098 repo_path = strdup(cwd);
6099 if (repo_path == NULL) {
6100 error = got_error_from_errno("strdup");
6101 goto done;
6106 if (do_list) {
6107 error = got_repo_open(&repo, repo_path, NULL);
6108 if (error != NULL)
6109 goto done;
6110 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6111 if (error)
6112 goto done;
6113 error = list_tags(repo, worktree);
6114 } else {
6115 error = get_gitconfig_path(&gitconfig_path);
6116 if (error)
6117 goto done;
6118 error = got_repo_open(&repo, repo_path, gitconfig_path);
6119 if (error != NULL)
6120 goto done;
6122 if (tagmsg) {
6123 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6124 if (error)
6125 goto done;
6128 if (commit_id_arg == NULL) {
6129 struct got_reference *head_ref;
6130 struct got_object_id *commit_id;
6131 error = got_ref_open(&head_ref, repo,
6132 worktree ? got_worktree_get_head_ref_name(worktree)
6133 : GOT_REF_HEAD, 0);
6134 if (error)
6135 goto done;
6136 error = got_ref_resolve(&commit_id, repo, head_ref);
6137 got_ref_close(head_ref);
6138 if (error)
6139 goto done;
6140 error = got_object_id_str(&commit_id_str, commit_id);
6141 free(commit_id);
6142 if (error)
6143 goto done;
6146 error = add_tag(repo, worktree, tag_name,
6147 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6149 done:
6150 if (repo)
6151 got_repo_close(repo);
6152 if (worktree)
6153 got_worktree_close(worktree);
6154 free(cwd);
6155 free(repo_path);
6156 free(gitconfig_path);
6157 free(commit_id_str);
6158 return error;
6161 __dead static void
6162 usage_add(void)
6164 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6165 getprogname());
6166 exit(1);
6169 static const struct got_error *
6170 add_progress(void *arg, unsigned char status, const char *path)
6172 while (path[0] == '/')
6173 path++;
6174 printf("%c %s\n", status, path);
6175 return NULL;
6178 static const struct got_error *
6179 cmd_add(int argc, char *argv[])
6181 const struct got_error *error = NULL;
6182 struct got_repository *repo = NULL;
6183 struct got_worktree *worktree = NULL;
6184 char *cwd = NULL;
6185 struct got_pathlist_head paths;
6186 struct got_pathlist_entry *pe;
6187 int ch, can_recurse = 0, no_ignores = 0;
6189 TAILQ_INIT(&paths);
6191 while ((ch = getopt(argc, argv, "IR")) != -1) {
6192 switch (ch) {
6193 case 'I':
6194 no_ignores = 1;
6195 break;
6196 case 'R':
6197 can_recurse = 1;
6198 break;
6199 default:
6200 usage_add();
6201 /* NOTREACHED */
6205 argc -= optind;
6206 argv += optind;
6208 #ifndef PROFILE
6209 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6210 NULL) == -1)
6211 err(1, "pledge");
6212 #endif
6213 if (argc < 1)
6214 usage_add();
6216 cwd = getcwd(NULL, 0);
6217 if (cwd == NULL) {
6218 error = got_error_from_errno("getcwd");
6219 goto done;
6222 error = got_worktree_open(&worktree, cwd);
6223 if (error) {
6224 if (error->code == GOT_ERR_NOT_WORKTREE)
6225 error = wrap_not_worktree_error(error, "add", cwd);
6226 goto done;
6229 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6230 NULL);
6231 if (error != NULL)
6232 goto done;
6234 error = apply_unveil(got_repo_get_path(repo), 1,
6235 got_worktree_get_root_path(worktree));
6236 if (error)
6237 goto done;
6239 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6240 if (error)
6241 goto done;
6243 if (!can_recurse && no_ignores) {
6244 error = got_error_msg(GOT_ERR_BAD_PATH,
6245 "disregarding ignores requires -R option");
6246 goto done;
6250 if (!can_recurse) {
6251 char *ondisk_path;
6252 struct stat sb;
6253 TAILQ_FOREACH(pe, &paths, entry) {
6254 if (asprintf(&ondisk_path, "%s/%s",
6255 got_worktree_get_root_path(worktree),
6256 pe->path) == -1) {
6257 error = got_error_from_errno("asprintf");
6258 goto done;
6260 if (lstat(ondisk_path, &sb) == -1) {
6261 if (errno == ENOENT) {
6262 free(ondisk_path);
6263 continue;
6265 error = got_error_from_errno2("lstat",
6266 ondisk_path);
6267 free(ondisk_path);
6268 goto done;
6270 free(ondisk_path);
6271 if (S_ISDIR(sb.st_mode)) {
6272 error = got_error_msg(GOT_ERR_BAD_PATH,
6273 "adding directories requires -R option");
6274 goto done;
6279 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6280 NULL, repo, no_ignores);
6281 done:
6282 if (repo)
6283 got_repo_close(repo);
6284 if (worktree)
6285 got_worktree_close(worktree);
6286 TAILQ_FOREACH(pe, &paths, entry)
6287 free((char *)pe->path);
6288 got_pathlist_free(&paths);
6289 free(cwd);
6290 return error;
6293 __dead static void
6294 usage_remove(void)
6296 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6297 "path ...\n", getprogname());
6298 exit(1);
6301 static const struct got_error *
6302 print_remove_status(void *arg, unsigned char status,
6303 unsigned char staged_status, const char *path)
6305 while (path[0] == '/')
6306 path++;
6307 if (status == GOT_STATUS_NONEXISTENT)
6308 return NULL;
6309 if (status == staged_status && (status == GOT_STATUS_DELETE))
6310 status = GOT_STATUS_NO_CHANGE;
6311 printf("%c%c %s\n", status, staged_status, path);
6312 return NULL;
6315 static const struct got_error *
6316 cmd_remove(int argc, char *argv[])
6318 const struct got_error *error = NULL;
6319 struct got_worktree *worktree = NULL;
6320 struct got_repository *repo = NULL;
6321 const char *status_codes = NULL;
6322 char *cwd = NULL;
6323 struct got_pathlist_head paths;
6324 struct got_pathlist_entry *pe;
6325 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6327 TAILQ_INIT(&paths);
6329 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6330 switch (ch) {
6331 case 'f':
6332 delete_local_mods = 1;
6333 break;
6334 case 'k':
6335 keep_on_disk = 1;
6336 break;
6337 case 'R':
6338 can_recurse = 1;
6339 break;
6340 case 's':
6341 for (i = 0; i < strlen(optarg); i++) {
6342 switch (optarg[i]) {
6343 case GOT_STATUS_MODIFY:
6344 delete_local_mods = 1;
6345 break;
6346 case GOT_STATUS_MISSING:
6347 break;
6348 default:
6349 errx(1, "invalid status code '%c'",
6350 optarg[i]);
6353 status_codes = optarg;
6354 break;
6355 default:
6356 usage_remove();
6357 /* NOTREACHED */
6361 argc -= optind;
6362 argv += optind;
6364 #ifndef PROFILE
6365 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6366 NULL) == -1)
6367 err(1, "pledge");
6368 #endif
6369 if (argc < 1)
6370 usage_remove();
6372 cwd = getcwd(NULL, 0);
6373 if (cwd == NULL) {
6374 error = got_error_from_errno("getcwd");
6375 goto done;
6377 error = got_worktree_open(&worktree, cwd);
6378 if (error) {
6379 if (error->code == GOT_ERR_NOT_WORKTREE)
6380 error = wrap_not_worktree_error(error, "remove", cwd);
6381 goto done;
6384 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6385 NULL);
6386 if (error)
6387 goto done;
6389 error = apply_unveil(got_repo_get_path(repo), 1,
6390 got_worktree_get_root_path(worktree));
6391 if (error)
6392 goto done;
6394 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6395 if (error)
6396 goto done;
6398 if (!can_recurse) {
6399 char *ondisk_path;
6400 struct stat sb;
6401 TAILQ_FOREACH(pe, &paths, entry) {
6402 if (asprintf(&ondisk_path, "%s/%s",
6403 got_worktree_get_root_path(worktree),
6404 pe->path) == -1) {
6405 error = got_error_from_errno("asprintf");
6406 goto done;
6408 if (lstat(ondisk_path, &sb) == -1) {
6409 if (errno == ENOENT) {
6410 free(ondisk_path);
6411 continue;
6413 error = got_error_from_errno2("lstat",
6414 ondisk_path);
6415 free(ondisk_path);
6416 goto done;
6418 free(ondisk_path);
6419 if (S_ISDIR(sb.st_mode)) {
6420 error = got_error_msg(GOT_ERR_BAD_PATH,
6421 "removing directories requires -R option");
6422 goto done;
6427 error = got_worktree_schedule_delete(worktree, &paths,
6428 delete_local_mods, status_codes, print_remove_status, NULL,
6429 repo, keep_on_disk);
6430 done:
6431 if (repo)
6432 got_repo_close(repo);
6433 if (worktree)
6434 got_worktree_close(worktree);
6435 TAILQ_FOREACH(pe, &paths, entry)
6436 free((char *)pe->path);
6437 got_pathlist_free(&paths);
6438 free(cwd);
6439 return error;
6442 __dead static void
6443 usage_revert(void)
6445 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6446 "path ...\n", getprogname());
6447 exit(1);
6450 static const struct got_error *
6451 revert_progress(void *arg, unsigned char status, const char *path)
6453 if (status == GOT_STATUS_UNVERSIONED)
6454 return NULL;
6456 while (path[0] == '/')
6457 path++;
6458 printf("%c %s\n", status, path);
6459 return NULL;
6462 struct choose_patch_arg {
6463 FILE *patch_script_file;
6464 const char *action;
6467 static const struct got_error *
6468 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6469 int nchanges, const char *action)
6471 char *line = NULL;
6472 size_t linesize = 0;
6473 ssize_t linelen;
6475 switch (status) {
6476 case GOT_STATUS_ADD:
6477 printf("A %s\n%s this addition? [y/n] ", path, action);
6478 break;
6479 case GOT_STATUS_DELETE:
6480 printf("D %s\n%s this deletion? [y/n] ", path, action);
6481 break;
6482 case GOT_STATUS_MODIFY:
6483 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6484 return got_error_from_errno("fseek");
6485 printf(GOT_COMMIT_SEP_STR);
6486 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6487 printf("%s", line);
6488 if (ferror(patch_file))
6489 return got_error_from_errno("getline");
6490 printf(GOT_COMMIT_SEP_STR);
6491 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6492 path, n, nchanges, action);
6493 break;
6494 default:
6495 return got_error_path(path, GOT_ERR_FILE_STATUS);
6498 return NULL;
6501 static const struct got_error *
6502 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6503 FILE *patch_file, int n, int nchanges)
6505 const struct got_error *err = NULL;
6506 char *line = NULL;
6507 size_t linesize = 0;
6508 ssize_t linelen;
6509 int resp = ' ';
6510 struct choose_patch_arg *a = arg;
6512 *choice = GOT_PATCH_CHOICE_NONE;
6514 if (a->patch_script_file) {
6515 char *nl;
6516 err = show_change(status, path, patch_file, n, nchanges,
6517 a->action);
6518 if (err)
6519 return err;
6520 linelen = getline(&line, &linesize, a->patch_script_file);
6521 if (linelen == -1) {
6522 if (ferror(a->patch_script_file))
6523 return got_error_from_errno("getline");
6524 return NULL;
6526 nl = strchr(line, '\n');
6527 if (nl)
6528 *nl = '\0';
6529 if (strcmp(line, "y") == 0) {
6530 *choice = GOT_PATCH_CHOICE_YES;
6531 printf("y\n");
6532 } else if (strcmp(line, "n") == 0) {
6533 *choice = GOT_PATCH_CHOICE_NO;
6534 printf("n\n");
6535 } else if (strcmp(line, "q") == 0 &&
6536 status == GOT_STATUS_MODIFY) {
6537 *choice = GOT_PATCH_CHOICE_QUIT;
6538 printf("q\n");
6539 } else
6540 printf("invalid response '%s'\n", line);
6541 free(line);
6542 return NULL;
6545 while (resp != 'y' && resp != 'n' && resp != 'q') {
6546 err = show_change(status, path, patch_file, n, nchanges,
6547 a->action);
6548 if (err)
6549 return err;
6550 resp = getchar();
6551 if (resp == '\n')
6552 resp = getchar();
6553 if (status == GOT_STATUS_MODIFY) {
6554 if (resp != 'y' && resp != 'n' && resp != 'q') {
6555 printf("invalid response '%c'\n", resp);
6556 resp = ' ';
6558 } else if (resp != 'y' && resp != 'n') {
6559 printf("invalid response '%c'\n", resp);
6560 resp = ' ';
6564 if (resp == 'y')
6565 *choice = GOT_PATCH_CHOICE_YES;
6566 else if (resp == 'n')
6567 *choice = GOT_PATCH_CHOICE_NO;
6568 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6569 *choice = GOT_PATCH_CHOICE_QUIT;
6571 return NULL;
6575 static const struct got_error *
6576 cmd_revert(int argc, char *argv[])
6578 const struct got_error *error = NULL;
6579 struct got_worktree *worktree = NULL;
6580 struct got_repository *repo = NULL;
6581 char *cwd = NULL, *path = NULL;
6582 struct got_pathlist_head paths;
6583 struct got_pathlist_entry *pe;
6584 int ch, can_recurse = 0, pflag = 0;
6585 FILE *patch_script_file = NULL;
6586 const char *patch_script_path = NULL;
6587 struct choose_patch_arg cpa;
6589 TAILQ_INIT(&paths);
6591 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6592 switch (ch) {
6593 case 'p':
6594 pflag = 1;
6595 break;
6596 case 'F':
6597 patch_script_path = optarg;
6598 break;
6599 case 'R':
6600 can_recurse = 1;
6601 break;
6602 default:
6603 usage_revert();
6604 /* NOTREACHED */
6608 argc -= optind;
6609 argv += optind;
6611 #ifndef PROFILE
6612 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6613 "unveil", NULL) == -1)
6614 err(1, "pledge");
6615 #endif
6616 if (argc < 1)
6617 usage_revert();
6618 if (patch_script_path && !pflag)
6619 errx(1, "-F option can only be used together with -p option");
6621 cwd = getcwd(NULL, 0);
6622 if (cwd == NULL) {
6623 error = got_error_from_errno("getcwd");
6624 goto done;
6626 error = got_worktree_open(&worktree, cwd);
6627 if (error) {
6628 if (error->code == GOT_ERR_NOT_WORKTREE)
6629 error = wrap_not_worktree_error(error, "revert", cwd);
6630 goto done;
6633 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6634 NULL);
6635 if (error != NULL)
6636 goto done;
6638 if (patch_script_path) {
6639 patch_script_file = fopen(patch_script_path, "r");
6640 if (patch_script_file == NULL) {
6641 error = got_error_from_errno2("fopen",
6642 patch_script_path);
6643 goto done;
6646 error = apply_unveil(got_repo_get_path(repo), 1,
6647 got_worktree_get_root_path(worktree));
6648 if (error)
6649 goto done;
6651 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6652 if (error)
6653 goto done;
6655 if (!can_recurse) {
6656 char *ondisk_path;
6657 struct stat sb;
6658 TAILQ_FOREACH(pe, &paths, entry) {
6659 if (asprintf(&ondisk_path, "%s/%s",
6660 got_worktree_get_root_path(worktree),
6661 pe->path) == -1) {
6662 error = got_error_from_errno("asprintf");
6663 goto done;
6665 if (lstat(ondisk_path, &sb) == -1) {
6666 if (errno == ENOENT) {
6667 free(ondisk_path);
6668 continue;
6670 error = got_error_from_errno2("lstat",
6671 ondisk_path);
6672 free(ondisk_path);
6673 goto done;
6675 free(ondisk_path);
6676 if (S_ISDIR(sb.st_mode)) {
6677 error = got_error_msg(GOT_ERR_BAD_PATH,
6678 "reverting directories requires -R option");
6679 goto done;
6684 cpa.patch_script_file = patch_script_file;
6685 cpa.action = "revert";
6686 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6687 pflag ? choose_patch : NULL, &cpa, repo);
6688 done:
6689 if (patch_script_file && fclose(patch_script_file) == EOF &&
6690 error == NULL)
6691 error = got_error_from_errno2("fclose", patch_script_path);
6692 if (repo)
6693 got_repo_close(repo);
6694 if (worktree)
6695 got_worktree_close(worktree);
6696 free(path);
6697 free(cwd);
6698 return error;
6701 __dead static void
6702 usage_commit(void)
6704 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6705 getprogname());
6706 exit(1);
6709 struct collect_commit_logmsg_arg {
6710 const char *cmdline_log;
6711 const char *editor;
6712 const char *worktree_path;
6713 const char *branch_name;
6714 const char *repo_path;
6715 char *logmsg_path;
6719 static const struct got_error *
6720 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6721 void *arg)
6723 char *initial_content = NULL;
6724 struct got_pathlist_entry *pe;
6725 const struct got_error *err = NULL;
6726 char *template = NULL;
6727 struct collect_commit_logmsg_arg *a = arg;
6728 int initial_content_len;
6729 int fd = -1;
6730 size_t len;
6732 /* if a message was specified on the command line, just use it */
6733 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6734 len = strlen(a->cmdline_log) + 1;
6735 *logmsg = malloc(len + 1);
6736 if (*logmsg == NULL)
6737 return got_error_from_errno("malloc");
6738 strlcpy(*logmsg, a->cmdline_log, len);
6739 return NULL;
6742 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6743 return got_error_from_errno("asprintf");
6745 initial_content_len = asprintf(&initial_content,
6746 "\n# changes to be committed on branch %s:\n",
6747 a->branch_name);
6748 if (initial_content_len == -1)
6749 return got_error_from_errno("asprintf");
6751 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6752 if (err)
6753 goto done;
6755 if (write(fd, initial_content, initial_content_len) == -1) {
6756 err = got_error_from_errno2("write", a->logmsg_path);
6757 goto done;
6760 TAILQ_FOREACH(pe, commitable_paths, entry) {
6761 struct got_commitable *ct = pe->data;
6762 dprintf(fd, "# %c %s\n",
6763 got_commitable_get_status(ct),
6764 got_commitable_get_path(ct));
6767 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
6768 initial_content_len);
6769 done:
6770 free(initial_content);
6771 free(template);
6773 if (fd != -1 && close(fd) == -1 && err == NULL)
6774 err = got_error_from_errno2("close", a->logmsg_path);
6776 /* Editor is done; we can now apply unveil(2) */
6777 if (err == NULL)
6778 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6779 if (err) {
6780 free(*logmsg);
6781 *logmsg = NULL;
6783 return err;
6786 static const struct got_error *
6787 cmd_commit(int argc, char *argv[])
6789 const struct got_error *error = NULL;
6790 struct got_worktree *worktree = NULL;
6791 struct got_repository *repo = NULL;
6792 char *cwd = NULL, *id_str = NULL;
6793 struct got_object_id *id = NULL;
6794 const char *logmsg = NULL;
6795 struct collect_commit_logmsg_arg cl_arg;
6796 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6797 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6798 int allow_bad_symlinks = 0;
6799 struct got_pathlist_head paths;
6801 TAILQ_INIT(&paths);
6802 cl_arg.logmsg_path = NULL;
6804 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6805 switch (ch) {
6806 case 'm':
6807 logmsg = optarg;
6808 break;
6809 case 'S':
6810 allow_bad_symlinks = 1;
6811 break;
6812 default:
6813 usage_commit();
6814 /* NOTREACHED */
6818 argc -= optind;
6819 argv += optind;
6821 #ifndef PROFILE
6822 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6823 "unveil", NULL) == -1)
6824 err(1, "pledge");
6825 #endif
6826 cwd = getcwd(NULL, 0);
6827 if (cwd == NULL) {
6828 error = got_error_from_errno("getcwd");
6829 goto done;
6831 error = got_worktree_open(&worktree, cwd);
6832 if (error) {
6833 if (error->code == GOT_ERR_NOT_WORKTREE)
6834 error = wrap_not_worktree_error(error, "commit", cwd);
6835 goto done;
6838 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6839 if (error)
6840 goto done;
6841 if (rebase_in_progress) {
6842 error = got_error(GOT_ERR_REBASING);
6843 goto done;
6846 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6847 worktree);
6848 if (error)
6849 goto done;
6851 error = get_gitconfig_path(&gitconfig_path);
6852 if (error)
6853 goto done;
6854 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6855 gitconfig_path);
6856 if (error != NULL)
6857 goto done;
6859 error = get_author(&author, repo, worktree);
6860 if (error)
6861 return error;
6864 * unveil(2) traverses exec(2); if an editor is used we have
6865 * to apply unveil after the log message has been written.
6867 if (logmsg == NULL || strlen(logmsg) == 0)
6868 error = get_editor(&editor);
6869 else
6870 error = apply_unveil(got_repo_get_path(repo), 0,
6871 got_worktree_get_root_path(worktree));
6872 if (error)
6873 goto done;
6875 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6876 if (error)
6877 goto done;
6879 cl_arg.editor = editor;
6880 cl_arg.cmdline_log = logmsg;
6881 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6882 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6883 if (!histedit_in_progress) {
6884 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6885 error = got_error(GOT_ERR_COMMIT_BRANCH);
6886 goto done;
6888 cl_arg.branch_name += 11;
6890 cl_arg.repo_path = got_repo_get_path(repo);
6891 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6892 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6893 print_status, NULL, repo);
6894 if (error) {
6895 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6896 cl_arg.logmsg_path != NULL)
6897 preserve_logmsg = 1;
6898 goto done;
6901 error = got_object_id_str(&id_str, id);
6902 if (error)
6903 goto done;
6904 printf("Created commit %s\n", id_str);
6905 done:
6906 if (preserve_logmsg) {
6907 fprintf(stderr, "%s: log message preserved in %s\n",
6908 getprogname(), cl_arg.logmsg_path);
6909 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6910 error == NULL)
6911 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6912 free(cl_arg.logmsg_path);
6913 if (repo)
6914 got_repo_close(repo);
6915 if (worktree)
6916 got_worktree_close(worktree);
6917 free(cwd);
6918 free(id_str);
6919 free(gitconfig_path);
6920 free(editor);
6921 free(author);
6922 return error;
6925 __dead static void
6926 usage_cherrypick(void)
6928 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6929 exit(1);
6932 static const struct got_error *
6933 cmd_cherrypick(int argc, char *argv[])
6935 const struct got_error *error = NULL;
6936 struct got_worktree *worktree = NULL;
6937 struct got_repository *repo = NULL;
6938 char *cwd = NULL, *commit_id_str = NULL;
6939 struct got_object_id *commit_id = NULL;
6940 struct got_commit_object *commit = NULL;
6941 struct got_object_qid *pid;
6942 struct got_reference *head_ref = NULL;
6943 int ch;
6944 struct got_update_progress_arg upa;
6946 while ((ch = getopt(argc, argv, "")) != -1) {
6947 switch (ch) {
6948 default:
6949 usage_cherrypick();
6950 /* NOTREACHED */
6954 argc -= optind;
6955 argv += optind;
6957 #ifndef PROFILE
6958 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6959 "unveil", NULL) == -1)
6960 err(1, "pledge");
6961 #endif
6962 if (argc != 1)
6963 usage_cherrypick();
6965 cwd = getcwd(NULL, 0);
6966 if (cwd == NULL) {
6967 error = got_error_from_errno("getcwd");
6968 goto done;
6970 error = got_worktree_open(&worktree, cwd);
6971 if (error) {
6972 if (error->code == GOT_ERR_NOT_WORKTREE)
6973 error = wrap_not_worktree_error(error, "cherrypick",
6974 cwd);
6975 goto done;
6978 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6979 NULL);
6980 if (error != NULL)
6981 goto done;
6983 error = apply_unveil(got_repo_get_path(repo), 0,
6984 got_worktree_get_root_path(worktree));
6985 if (error)
6986 goto done;
6988 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6989 GOT_OBJ_TYPE_COMMIT, repo);
6990 if (error != NULL) {
6991 struct got_reference *ref;
6992 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6993 goto done;
6994 error = got_ref_open(&ref, repo, argv[0], 0);
6995 if (error != NULL)
6996 goto done;
6997 error = got_ref_resolve(&commit_id, repo, ref);
6998 got_ref_close(ref);
6999 if (error != NULL)
7000 goto done;
7002 error = got_object_id_str(&commit_id_str, commit_id);
7003 if (error)
7004 goto done;
7006 error = got_ref_open(&head_ref, repo,
7007 got_worktree_get_head_ref_name(worktree), 0);
7008 if (error != NULL)
7009 goto done;
7011 error = check_same_branch(commit_id, head_ref, NULL, repo);
7012 if (error) {
7013 if (error->code != GOT_ERR_ANCESTRY)
7014 goto done;
7015 error = NULL;
7016 } else {
7017 error = got_error(GOT_ERR_SAME_BRANCH);
7018 goto done;
7021 error = got_object_open_as_commit(&commit, repo, commit_id);
7022 if (error)
7023 goto done;
7024 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7025 memset(&upa, 0, sizeof(upa));
7026 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7027 commit_id, repo, update_progress, &upa, check_cancelled,
7028 NULL);
7029 if (error != NULL)
7030 goto done;
7032 if (upa.did_something)
7033 printf("Merged commit %s\n", commit_id_str);
7034 print_update_progress_stats(&upa);
7035 done:
7036 if (commit)
7037 got_object_commit_close(commit);
7038 free(commit_id_str);
7039 if (head_ref)
7040 got_ref_close(head_ref);
7041 if (worktree)
7042 got_worktree_close(worktree);
7043 if (repo)
7044 got_repo_close(repo);
7045 return error;
7048 __dead static void
7049 usage_backout(void)
7051 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7052 exit(1);
7055 static const struct got_error *
7056 cmd_backout(int argc, char *argv[])
7058 const struct got_error *error = NULL;
7059 struct got_worktree *worktree = NULL;
7060 struct got_repository *repo = NULL;
7061 char *cwd = NULL, *commit_id_str = NULL;
7062 struct got_object_id *commit_id = NULL;
7063 struct got_commit_object *commit = NULL;
7064 struct got_object_qid *pid;
7065 struct got_reference *head_ref = NULL;
7066 int ch;
7067 struct got_update_progress_arg upa;
7069 while ((ch = getopt(argc, argv, "")) != -1) {
7070 switch (ch) {
7071 default:
7072 usage_backout();
7073 /* NOTREACHED */
7077 argc -= optind;
7078 argv += optind;
7080 #ifndef PROFILE
7081 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7082 "unveil", NULL) == -1)
7083 err(1, "pledge");
7084 #endif
7085 if (argc != 1)
7086 usage_backout();
7088 cwd = getcwd(NULL, 0);
7089 if (cwd == NULL) {
7090 error = got_error_from_errno("getcwd");
7091 goto done;
7093 error = got_worktree_open(&worktree, cwd);
7094 if (error) {
7095 if (error->code == GOT_ERR_NOT_WORKTREE)
7096 error = wrap_not_worktree_error(error, "backout", cwd);
7097 goto done;
7100 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7101 NULL);
7102 if (error != NULL)
7103 goto done;
7105 error = apply_unveil(got_repo_get_path(repo), 0,
7106 got_worktree_get_root_path(worktree));
7107 if (error)
7108 goto done;
7110 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7111 GOT_OBJ_TYPE_COMMIT, repo);
7112 if (error != NULL) {
7113 struct got_reference *ref;
7114 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7115 goto done;
7116 error = got_ref_open(&ref, repo, argv[0], 0);
7117 if (error != NULL)
7118 goto done;
7119 error = got_ref_resolve(&commit_id, repo, ref);
7120 got_ref_close(ref);
7121 if (error != NULL)
7122 goto done;
7124 error = got_object_id_str(&commit_id_str, commit_id);
7125 if (error)
7126 goto done;
7128 error = got_ref_open(&head_ref, repo,
7129 got_worktree_get_head_ref_name(worktree), 0);
7130 if (error != NULL)
7131 goto done;
7133 error = check_same_branch(commit_id, head_ref, NULL, repo);
7134 if (error)
7135 goto done;
7137 error = got_object_open_as_commit(&commit, repo, commit_id);
7138 if (error)
7139 goto done;
7140 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7141 if (pid == NULL) {
7142 error = got_error(GOT_ERR_ROOT_COMMIT);
7143 goto done;
7146 memset(&upa, 0, sizeof(upa));
7147 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7148 update_progress, &upa, check_cancelled, NULL);
7149 if (error != NULL)
7150 goto done;
7152 if (upa.did_something)
7153 printf("Backed out commit %s\n", commit_id_str);
7154 print_update_progress_stats(&upa);
7155 done:
7156 if (commit)
7157 got_object_commit_close(commit);
7158 free(commit_id_str);
7159 if (head_ref)
7160 got_ref_close(head_ref);
7161 if (worktree)
7162 got_worktree_close(worktree);
7163 if (repo)
7164 got_repo_close(repo);
7165 return error;
7168 __dead static void
7169 usage_rebase(void)
7171 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7172 getprogname());
7173 exit(1);
7176 void
7177 trim_logmsg(char *logmsg, int limit)
7179 char *nl;
7180 size_t len;
7182 len = strlen(logmsg);
7183 if (len > limit)
7184 len = limit;
7185 logmsg[len] = '\0';
7186 nl = strchr(logmsg, '\n');
7187 if (nl)
7188 *nl = '\0';
7191 static const struct got_error *
7192 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7194 const struct got_error *err;
7195 char *logmsg0 = NULL;
7196 const char *s;
7198 err = got_object_commit_get_logmsg(&logmsg0, commit);
7199 if (err)
7200 return err;
7202 s = logmsg0;
7203 while (isspace((unsigned char)s[0]))
7204 s++;
7206 *logmsg = strdup(s);
7207 if (*logmsg == NULL) {
7208 err = got_error_from_errno("strdup");
7209 goto done;
7212 trim_logmsg(*logmsg, limit);
7213 done:
7214 free(logmsg0);
7215 return err;
7218 static const struct got_error *
7219 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7221 const struct got_error *err;
7222 struct got_commit_object *commit = NULL;
7223 char *id_str = NULL, *logmsg = NULL;
7225 err = got_object_open_as_commit(&commit, repo, id);
7226 if (err)
7227 return err;
7229 err = got_object_id_str(&id_str, id);
7230 if (err)
7231 goto done;
7233 id_str[12] = '\0';
7235 err = get_short_logmsg(&logmsg, 42, commit);
7236 if (err)
7237 goto done;
7239 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7240 done:
7241 free(id_str);
7242 got_object_commit_close(commit);
7243 free(logmsg);
7244 return err;
7247 static const struct got_error *
7248 show_rebase_progress(struct got_commit_object *commit,
7249 struct got_object_id *old_id, struct got_object_id *new_id)
7251 const struct got_error *err;
7252 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7254 err = got_object_id_str(&old_id_str, old_id);
7255 if (err)
7256 goto done;
7258 if (new_id) {
7259 err = got_object_id_str(&new_id_str, new_id);
7260 if (err)
7261 goto done;
7264 old_id_str[12] = '\0';
7265 if (new_id_str)
7266 new_id_str[12] = '\0';
7268 err = get_short_logmsg(&logmsg, 42, commit);
7269 if (err)
7270 goto done;
7272 printf("%s -> %s: %s\n", old_id_str,
7273 new_id_str ? new_id_str : "no-op change", logmsg);
7274 done:
7275 free(old_id_str);
7276 free(new_id_str);
7277 free(logmsg);
7278 return err;
7281 static const struct got_error *
7282 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7283 struct got_reference *branch, struct got_reference *new_base_branch,
7284 struct got_reference *tmp_branch, struct got_repository *repo)
7286 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7287 return got_worktree_rebase_complete(worktree, fileindex,
7288 new_base_branch, tmp_branch, branch, repo);
7291 static const struct got_error *
7292 rebase_commit(struct got_pathlist_head *merged_paths,
7293 struct got_worktree *worktree, struct got_fileindex *fileindex,
7294 struct got_reference *tmp_branch,
7295 struct got_object_id *commit_id, struct got_repository *repo)
7297 const struct got_error *error;
7298 struct got_commit_object *commit;
7299 struct got_object_id *new_commit_id;
7301 error = got_object_open_as_commit(&commit, repo, commit_id);
7302 if (error)
7303 return error;
7305 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7306 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7307 if (error) {
7308 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7309 goto done;
7310 error = show_rebase_progress(commit, commit_id, NULL);
7311 } else {
7312 error = show_rebase_progress(commit, commit_id, new_commit_id);
7313 free(new_commit_id);
7315 done:
7316 got_object_commit_close(commit);
7317 return error;
7320 struct check_path_prefix_arg {
7321 const char *path_prefix;
7322 size_t len;
7323 int errcode;
7326 static const struct got_error *
7327 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7328 struct got_blob_object *blob2, struct got_object_id *id1,
7329 struct got_object_id *id2, const char *path1, const char *path2,
7330 mode_t mode1, mode_t mode2, struct got_repository *repo)
7332 struct check_path_prefix_arg *a = arg;
7334 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7335 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7336 return got_error(a->errcode);
7338 return NULL;
7341 static const struct got_error *
7342 check_path_prefix(struct got_object_id *parent_id,
7343 struct got_object_id *commit_id, const char *path_prefix,
7344 int errcode, struct got_repository *repo)
7346 const struct got_error *err;
7347 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7348 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7349 struct check_path_prefix_arg cpp_arg;
7351 if (got_path_is_root_dir(path_prefix))
7352 return NULL;
7354 err = got_object_open_as_commit(&commit, repo, commit_id);
7355 if (err)
7356 goto done;
7358 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7359 if (err)
7360 goto done;
7362 err = got_object_open_as_tree(&tree1, repo,
7363 got_object_commit_get_tree_id(parent_commit));
7364 if (err)
7365 goto done;
7367 err = got_object_open_as_tree(&tree2, repo,
7368 got_object_commit_get_tree_id(commit));
7369 if (err)
7370 goto done;
7372 cpp_arg.path_prefix = path_prefix;
7373 while (cpp_arg.path_prefix[0] == '/')
7374 cpp_arg.path_prefix++;
7375 cpp_arg.len = strlen(cpp_arg.path_prefix);
7376 cpp_arg.errcode = errcode;
7377 err = got_diff_tree(tree1, tree2, "", "", repo,
7378 check_path_prefix_in_diff, &cpp_arg, 0);
7379 done:
7380 if (tree1)
7381 got_object_tree_close(tree1);
7382 if (tree2)
7383 got_object_tree_close(tree2);
7384 if (commit)
7385 got_object_commit_close(commit);
7386 if (parent_commit)
7387 got_object_commit_close(parent_commit);
7388 return err;
7391 static const struct got_error *
7392 collect_commits(struct got_object_id_queue *commits,
7393 struct got_object_id *initial_commit_id,
7394 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7395 const char *path_prefix, int path_prefix_errcode,
7396 struct got_repository *repo)
7398 const struct got_error *err = NULL;
7399 struct got_commit_graph *graph = NULL;
7400 struct got_object_id *parent_id = NULL;
7401 struct got_object_qid *qid;
7402 struct got_object_id *commit_id = initial_commit_id;
7404 err = got_commit_graph_open(&graph, "/", 1);
7405 if (err)
7406 return err;
7408 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7409 check_cancelled, NULL);
7410 if (err)
7411 goto done;
7412 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7413 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7414 check_cancelled, NULL);
7415 if (err) {
7416 if (err->code == GOT_ERR_ITER_COMPLETED) {
7417 err = got_error_msg(GOT_ERR_ANCESTRY,
7418 "ran out of commits to rebase before "
7419 "youngest common ancestor commit has "
7420 "been reached?!?");
7422 goto done;
7423 } else {
7424 err = check_path_prefix(parent_id, commit_id,
7425 path_prefix, path_prefix_errcode, repo);
7426 if (err)
7427 goto done;
7429 err = got_object_qid_alloc(&qid, commit_id);
7430 if (err)
7431 goto done;
7432 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7433 commit_id = parent_id;
7436 done:
7437 got_commit_graph_close(graph);
7438 return err;
7441 static const struct got_error *
7442 cmd_rebase(int argc, char *argv[])
7444 const struct got_error *error = NULL;
7445 struct got_worktree *worktree = NULL;
7446 struct got_repository *repo = NULL;
7447 struct got_fileindex *fileindex = NULL;
7448 char *cwd = NULL;
7449 struct got_reference *branch = NULL;
7450 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7451 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7452 struct got_object_id *resume_commit_id = NULL;
7453 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7454 struct got_commit_object *commit = NULL;
7455 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7456 int histedit_in_progress = 0;
7457 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7458 struct got_object_id_queue commits;
7459 struct got_pathlist_head merged_paths;
7460 const struct got_object_id_queue *parent_ids;
7461 struct got_object_qid *qid, *pid;
7463 SIMPLEQ_INIT(&commits);
7464 TAILQ_INIT(&merged_paths);
7466 while ((ch = getopt(argc, argv, "ac")) != -1) {
7467 switch (ch) {
7468 case 'a':
7469 abort_rebase = 1;
7470 break;
7471 case 'c':
7472 continue_rebase = 1;
7473 break;
7474 default:
7475 usage_rebase();
7476 /* NOTREACHED */
7480 argc -= optind;
7481 argv += optind;
7483 #ifndef PROFILE
7484 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7485 "unveil", NULL) == -1)
7486 err(1, "pledge");
7487 #endif
7488 if (abort_rebase && continue_rebase)
7489 usage_rebase();
7490 else if (abort_rebase || continue_rebase) {
7491 if (argc != 0)
7492 usage_rebase();
7493 } else if (argc != 1)
7494 usage_rebase();
7496 cwd = getcwd(NULL, 0);
7497 if (cwd == NULL) {
7498 error = got_error_from_errno("getcwd");
7499 goto done;
7501 error = got_worktree_open(&worktree, cwd);
7502 if (error) {
7503 if (error->code == GOT_ERR_NOT_WORKTREE)
7504 error = wrap_not_worktree_error(error, "rebase", cwd);
7505 goto done;
7508 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7509 NULL);
7510 if (error != NULL)
7511 goto done;
7513 error = apply_unveil(got_repo_get_path(repo), 0,
7514 got_worktree_get_root_path(worktree));
7515 if (error)
7516 goto done;
7518 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7519 worktree);
7520 if (error)
7521 goto done;
7522 if (histedit_in_progress) {
7523 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7524 goto done;
7527 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7528 if (error)
7529 goto done;
7531 if (abort_rebase) {
7532 struct got_update_progress_arg upa;
7533 if (!rebase_in_progress) {
7534 error = got_error(GOT_ERR_NOT_REBASING);
7535 goto done;
7537 error = got_worktree_rebase_continue(&resume_commit_id,
7538 &new_base_branch, &tmp_branch, &branch, &fileindex,
7539 worktree, repo);
7540 if (error)
7541 goto done;
7542 printf("Switching work tree to %s\n",
7543 got_ref_get_symref_target(new_base_branch));
7544 memset(&upa, 0, sizeof(upa));
7545 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7546 new_base_branch, update_progress, &upa);
7547 if (error)
7548 goto done;
7549 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7550 print_update_progress_stats(&upa);
7551 goto done; /* nothing else to do */
7554 if (continue_rebase) {
7555 if (!rebase_in_progress) {
7556 error = got_error(GOT_ERR_NOT_REBASING);
7557 goto done;
7559 error = got_worktree_rebase_continue(&resume_commit_id,
7560 &new_base_branch, &tmp_branch, &branch, &fileindex,
7561 worktree, repo);
7562 if (error)
7563 goto done;
7565 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7566 resume_commit_id, repo);
7567 if (error)
7568 goto done;
7570 yca_id = got_object_id_dup(resume_commit_id);
7571 if (yca_id == NULL) {
7572 error = got_error_from_errno("got_object_id_dup");
7573 goto done;
7575 } else {
7576 error = got_ref_open(&branch, repo, argv[0], 0);
7577 if (error != NULL)
7578 goto done;
7581 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7582 if (error)
7583 goto done;
7585 if (!continue_rebase) {
7586 struct got_object_id *base_commit_id;
7588 base_commit_id = got_worktree_get_base_commit_id(worktree);
7589 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7590 base_commit_id, branch_head_commit_id, repo,
7591 check_cancelled, NULL);
7592 if (error)
7593 goto done;
7594 if (yca_id == NULL) {
7595 error = got_error_msg(GOT_ERR_ANCESTRY,
7596 "specified branch shares no common ancestry "
7597 "with work tree's branch");
7598 goto done;
7601 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7602 if (error) {
7603 if (error->code != GOT_ERR_ANCESTRY)
7604 goto done;
7605 error = NULL;
7606 } else {
7607 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7608 "specified branch resolves to a commit which "
7609 "is already contained in work tree's branch");
7610 goto done;
7612 error = got_worktree_rebase_prepare(&new_base_branch,
7613 &tmp_branch, &fileindex, worktree, branch, repo);
7614 if (error)
7615 goto done;
7618 commit_id = branch_head_commit_id;
7619 error = got_object_open_as_commit(&commit, repo, commit_id);
7620 if (error)
7621 goto done;
7623 parent_ids = got_object_commit_get_parent_ids(commit);
7624 pid = SIMPLEQ_FIRST(parent_ids);
7625 if (pid == NULL) {
7626 if (!continue_rebase) {
7627 struct got_update_progress_arg upa;
7628 memset(&upa, 0, sizeof(upa));
7629 error = got_worktree_rebase_abort(worktree, fileindex,
7630 repo, new_base_branch, update_progress, &upa);
7631 if (error)
7632 goto done;
7633 printf("Rebase of %s aborted\n",
7634 got_ref_get_name(branch));
7635 print_update_progress_stats(&upa);
7638 error = got_error(GOT_ERR_EMPTY_REBASE);
7639 goto done;
7641 error = collect_commits(&commits, commit_id, pid->id,
7642 yca_id, got_worktree_get_path_prefix(worktree),
7643 GOT_ERR_REBASE_PATH, repo);
7644 got_object_commit_close(commit);
7645 commit = NULL;
7646 if (error)
7647 goto done;
7649 if (SIMPLEQ_EMPTY(&commits)) {
7650 if (continue_rebase) {
7651 error = rebase_complete(worktree, fileindex,
7652 branch, new_base_branch, tmp_branch, repo);
7653 goto done;
7654 } else {
7655 /* Fast-forward the reference of the branch. */
7656 struct got_object_id *new_head_commit_id;
7657 char *id_str;
7658 error = got_ref_resolve(&new_head_commit_id, repo,
7659 new_base_branch);
7660 if (error)
7661 goto done;
7662 error = got_object_id_str(&id_str, new_head_commit_id);
7663 printf("Forwarding %s to commit %s\n",
7664 got_ref_get_name(branch), id_str);
7665 free(id_str);
7666 error = got_ref_change_ref(branch,
7667 new_head_commit_id);
7668 if (error)
7669 goto done;
7673 pid = NULL;
7674 SIMPLEQ_FOREACH(qid, &commits, entry) {
7675 struct got_update_progress_arg upa;
7677 commit_id = qid->id;
7678 parent_id = pid ? pid->id : yca_id;
7679 pid = qid;
7681 memset(&upa, 0, sizeof(upa));
7682 error = got_worktree_rebase_merge_files(&merged_paths,
7683 worktree, fileindex, parent_id, commit_id, repo,
7684 update_progress, &upa, check_cancelled, NULL);
7685 if (error)
7686 goto done;
7688 print_update_progress_stats(&upa);
7689 if (upa.conflicts > 0)
7690 rebase_status = GOT_STATUS_CONFLICT;
7692 if (rebase_status == GOT_STATUS_CONFLICT) {
7693 error = show_rebase_merge_conflict(qid->id, repo);
7694 if (error)
7695 goto done;
7696 got_worktree_rebase_pathlist_free(&merged_paths);
7697 break;
7700 error = rebase_commit(&merged_paths, worktree, fileindex,
7701 tmp_branch, commit_id, repo);
7702 got_worktree_rebase_pathlist_free(&merged_paths);
7703 if (error)
7704 goto done;
7707 if (rebase_status == GOT_STATUS_CONFLICT) {
7708 error = got_worktree_rebase_postpone(worktree, fileindex);
7709 if (error)
7710 goto done;
7711 error = got_error_msg(GOT_ERR_CONFLICTS,
7712 "conflicts must be resolved before rebasing can continue");
7713 } else
7714 error = rebase_complete(worktree, fileindex, branch,
7715 new_base_branch, tmp_branch, repo);
7716 done:
7717 got_object_id_queue_free(&commits);
7718 free(branch_head_commit_id);
7719 free(resume_commit_id);
7720 free(yca_id);
7721 if (commit)
7722 got_object_commit_close(commit);
7723 if (branch)
7724 got_ref_close(branch);
7725 if (new_base_branch)
7726 got_ref_close(new_base_branch);
7727 if (tmp_branch)
7728 got_ref_close(tmp_branch);
7729 if (worktree)
7730 got_worktree_close(worktree);
7731 if (repo)
7732 got_repo_close(repo);
7733 return error;
7736 __dead static void
7737 usage_histedit(void)
7739 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7740 getprogname());
7741 exit(1);
7744 #define GOT_HISTEDIT_PICK 'p'
7745 #define GOT_HISTEDIT_EDIT 'e'
7746 #define GOT_HISTEDIT_FOLD 'f'
7747 #define GOT_HISTEDIT_DROP 'd'
7748 #define GOT_HISTEDIT_MESG 'm'
7750 static struct got_histedit_cmd {
7751 unsigned char code;
7752 const char *name;
7753 const char *desc;
7754 } got_histedit_cmds[] = {
7755 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7756 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7757 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7758 "be used" },
7759 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7760 { GOT_HISTEDIT_MESG, "mesg",
7761 "single-line log message for commit above (open editor if empty)" },
7764 struct got_histedit_list_entry {
7765 TAILQ_ENTRY(got_histedit_list_entry) entry;
7766 struct got_object_id *commit_id;
7767 const struct got_histedit_cmd *cmd;
7768 char *logmsg;
7770 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7772 static const struct got_error *
7773 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7774 FILE *f, struct got_repository *repo)
7776 const struct got_error *err = NULL;
7777 char *logmsg = NULL, *id_str = NULL;
7778 struct got_commit_object *commit = NULL;
7779 int n;
7781 err = got_object_open_as_commit(&commit, repo, commit_id);
7782 if (err)
7783 goto done;
7785 err = get_short_logmsg(&logmsg, 34, commit);
7786 if (err)
7787 goto done;
7789 err = got_object_id_str(&id_str, commit_id);
7790 if (err)
7791 goto done;
7793 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7794 if (n < 0)
7795 err = got_ferror(f, GOT_ERR_IO);
7796 done:
7797 if (commit)
7798 got_object_commit_close(commit);
7799 free(id_str);
7800 free(logmsg);
7801 return err;
7804 static const struct got_error *
7805 histedit_write_commit_list(struct got_object_id_queue *commits,
7806 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7808 const struct got_error *err = NULL;
7809 struct got_object_qid *qid;
7811 if (SIMPLEQ_EMPTY(commits))
7812 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7814 SIMPLEQ_FOREACH(qid, commits, entry) {
7815 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7816 f, repo);
7817 if (err)
7818 break;
7819 if (edit_logmsg_only) {
7820 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7821 if (n < 0) {
7822 err = got_ferror(f, GOT_ERR_IO);
7823 break;
7828 return err;
7831 static const struct got_error *
7832 write_cmd_list(FILE *f, const char *branch_name,
7833 struct got_object_id_queue *commits)
7835 const struct got_error *err = NULL;
7836 int n, i;
7837 char *id_str;
7838 struct got_object_qid *qid;
7840 qid = SIMPLEQ_FIRST(commits);
7841 err = got_object_id_str(&id_str, qid->id);
7842 if (err)
7843 return err;
7845 n = fprintf(f,
7846 "# Editing the history of branch '%s' starting at\n"
7847 "# commit %s\n"
7848 "# Commits will be processed in order from top to "
7849 "bottom of this file.\n", branch_name, id_str);
7850 if (n < 0) {
7851 err = got_ferror(f, GOT_ERR_IO);
7852 goto done;
7855 n = fprintf(f, "# Available histedit commands:\n");
7856 if (n < 0) {
7857 err = got_ferror(f, GOT_ERR_IO);
7858 goto done;
7861 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7862 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7863 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7864 cmd->desc);
7865 if (n < 0) {
7866 err = got_ferror(f, GOT_ERR_IO);
7867 break;
7870 done:
7871 free(id_str);
7872 return err;
7875 static const struct got_error *
7876 histedit_syntax_error(int lineno)
7878 static char msg[42];
7879 int ret;
7881 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7882 lineno);
7883 if (ret == -1 || ret >= sizeof(msg))
7884 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7886 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7889 static const struct got_error *
7890 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7891 char *logmsg, struct got_repository *repo)
7893 const struct got_error *err;
7894 struct got_commit_object *folded_commit = NULL;
7895 char *id_str, *folded_logmsg = NULL;
7897 err = got_object_id_str(&id_str, hle->commit_id);
7898 if (err)
7899 return err;
7901 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7902 if (err)
7903 goto done;
7905 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7906 if (err)
7907 goto done;
7908 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7909 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7910 folded_logmsg) == -1) {
7911 err = got_error_from_errno("asprintf");
7913 done:
7914 if (folded_commit)
7915 got_object_commit_close(folded_commit);
7916 free(id_str);
7917 free(folded_logmsg);
7918 return err;
7921 static struct got_histedit_list_entry *
7922 get_folded_commits(struct got_histedit_list_entry *hle)
7924 struct got_histedit_list_entry *prev, *folded = NULL;
7926 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7927 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7928 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7929 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7930 folded = prev;
7931 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7934 return folded;
7937 static const struct got_error *
7938 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7939 struct got_repository *repo)
7941 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7942 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7943 const struct got_error *err = NULL;
7944 struct got_commit_object *commit = NULL;
7945 int logmsg_len;
7946 int fd;
7947 struct got_histedit_list_entry *folded = NULL;
7949 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7950 if (err)
7951 return err;
7953 folded = get_folded_commits(hle);
7954 if (folded) {
7955 while (folded != hle) {
7956 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7957 folded = TAILQ_NEXT(folded, entry);
7958 continue;
7960 err = append_folded_commit_msg(&new_msg, folded,
7961 logmsg, repo);
7962 if (err)
7963 goto done;
7964 free(logmsg);
7965 logmsg = new_msg;
7966 folded = TAILQ_NEXT(folded, entry);
7970 err = got_object_id_str(&id_str, hle->commit_id);
7971 if (err)
7972 goto done;
7973 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7974 if (err)
7975 goto done;
7976 logmsg_len = asprintf(&new_msg,
7977 "%s\n# original log message of commit %s: %s",
7978 logmsg ? logmsg : "", id_str, orig_logmsg);
7979 if (logmsg_len == -1) {
7980 err = got_error_from_errno("asprintf");
7981 goto done;
7983 free(logmsg);
7984 logmsg = new_msg;
7986 err = got_object_id_str(&id_str, hle->commit_id);
7987 if (err)
7988 goto done;
7990 err = got_opentemp_named_fd(&logmsg_path, &fd,
7991 GOT_TMPDIR_STR "/got-logmsg");
7992 if (err)
7993 goto done;
7995 write(fd, logmsg, logmsg_len);
7996 close(fd);
7998 err = get_editor(&editor);
7999 if (err)
8000 goto done;
8002 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8003 logmsg_len);
8004 if (err) {
8005 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8006 goto done;
8007 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
8009 done:
8010 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8011 err = got_error_from_errno2("unlink", logmsg_path);
8012 free(logmsg_path);
8013 free(logmsg);
8014 free(orig_logmsg);
8015 free(editor);
8016 if (commit)
8017 got_object_commit_close(commit);
8018 return err;
8021 static const struct got_error *
8022 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8023 FILE *f, struct got_repository *repo)
8025 const struct got_error *err = NULL;
8026 char *line = NULL, *p, *end;
8027 size_t size;
8028 ssize_t len;
8029 int lineno = 0, i;
8030 const struct got_histedit_cmd *cmd;
8031 struct got_object_id *commit_id = NULL;
8032 struct got_histedit_list_entry *hle = NULL;
8034 for (;;) {
8035 len = getline(&line, &size, f);
8036 if (len == -1) {
8037 const struct got_error *getline_err;
8038 if (feof(f))
8039 break;
8040 getline_err = got_error_from_errno("getline");
8041 err = got_ferror(f, getline_err->code);
8042 break;
8044 lineno++;
8045 p = line;
8046 while (isspace((unsigned char)p[0]))
8047 p++;
8048 if (p[0] == '#' || p[0] == '\0') {
8049 free(line);
8050 line = NULL;
8051 continue;
8053 cmd = NULL;
8054 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8055 cmd = &got_histedit_cmds[i];
8056 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8057 isspace((unsigned char)p[strlen(cmd->name)])) {
8058 p += strlen(cmd->name);
8059 break;
8061 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8062 p++;
8063 break;
8066 if (i == nitems(got_histedit_cmds)) {
8067 err = histedit_syntax_error(lineno);
8068 break;
8070 while (isspace((unsigned char)p[0]))
8071 p++;
8072 if (cmd->code == GOT_HISTEDIT_MESG) {
8073 if (hle == NULL || hle->logmsg != NULL) {
8074 err = got_error(GOT_ERR_HISTEDIT_CMD);
8075 break;
8077 if (p[0] == '\0') {
8078 err = histedit_edit_logmsg(hle, repo);
8079 if (err)
8080 break;
8081 } else {
8082 hle->logmsg = strdup(p);
8083 if (hle->logmsg == NULL) {
8084 err = got_error_from_errno("strdup");
8085 break;
8088 free(line);
8089 line = NULL;
8090 continue;
8091 } else {
8092 end = p;
8093 while (end[0] && !isspace((unsigned char)end[0]))
8094 end++;
8095 *end = '\0';
8097 err = got_object_resolve_id_str(&commit_id, repo, p);
8098 if (err) {
8099 /* override error code */
8100 err = histedit_syntax_error(lineno);
8101 break;
8104 hle = malloc(sizeof(*hle));
8105 if (hle == NULL) {
8106 err = got_error_from_errno("malloc");
8107 break;
8109 hle->cmd = cmd;
8110 hle->commit_id = commit_id;
8111 hle->logmsg = NULL;
8112 commit_id = NULL;
8113 free(line);
8114 line = NULL;
8115 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8118 free(line);
8119 free(commit_id);
8120 return err;
8123 static const struct got_error *
8124 histedit_check_script(struct got_histedit_list *histedit_cmds,
8125 struct got_object_id_queue *commits, struct got_repository *repo)
8127 const struct got_error *err = NULL;
8128 struct got_object_qid *qid;
8129 struct got_histedit_list_entry *hle;
8130 static char msg[92];
8131 char *id_str;
8133 if (TAILQ_EMPTY(histedit_cmds))
8134 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8135 "histedit script contains no commands");
8136 if (SIMPLEQ_EMPTY(commits))
8137 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8139 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8140 struct got_histedit_list_entry *hle2;
8141 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8142 if (hle == hle2)
8143 continue;
8144 if (got_object_id_cmp(hle->commit_id,
8145 hle2->commit_id) != 0)
8146 continue;
8147 err = got_object_id_str(&id_str, hle->commit_id);
8148 if (err)
8149 return err;
8150 snprintf(msg, sizeof(msg), "commit %s is listed "
8151 "more than once in histedit script", id_str);
8152 free(id_str);
8153 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8157 SIMPLEQ_FOREACH(qid, commits, entry) {
8158 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8159 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8160 break;
8162 if (hle == NULL) {
8163 err = got_object_id_str(&id_str, qid->id);
8164 if (err)
8165 return err;
8166 snprintf(msg, sizeof(msg),
8167 "commit %s missing from histedit script", id_str);
8168 free(id_str);
8169 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8173 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8174 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8175 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8176 "last commit in histedit script cannot be folded");
8178 return NULL;
8181 static const struct got_error *
8182 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8183 const char *path, struct got_object_id_queue *commits,
8184 struct got_repository *repo)
8186 const struct got_error *err = NULL;
8187 char *editor;
8188 FILE *f = NULL;
8190 err = get_editor(&editor);
8191 if (err)
8192 return err;
8194 if (spawn_editor(editor, path) == -1) {
8195 err = got_error_from_errno("failed spawning editor");
8196 goto done;
8199 f = fopen(path, "r");
8200 if (f == NULL) {
8201 err = got_error_from_errno("fopen");
8202 goto done;
8204 err = histedit_parse_list(histedit_cmds, f, repo);
8205 if (err)
8206 goto done;
8208 err = histedit_check_script(histedit_cmds, commits, repo);
8209 done:
8210 if (f && fclose(f) != 0 && err == NULL)
8211 err = got_error_from_errno("fclose");
8212 free(editor);
8213 return err;
8216 static const struct got_error *
8217 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8218 struct got_object_id_queue *, const char *, const char *,
8219 struct got_repository *);
8221 static const struct got_error *
8222 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8223 struct got_object_id_queue *commits, const char *branch_name,
8224 int edit_logmsg_only, struct got_repository *repo)
8226 const struct got_error *err;
8227 FILE *f = NULL;
8228 char *path = NULL;
8230 err = got_opentemp_named(&path, &f, "got-histedit");
8231 if (err)
8232 return err;
8234 err = write_cmd_list(f, branch_name, commits);
8235 if (err)
8236 goto done;
8238 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8239 if (err)
8240 goto done;
8242 if (edit_logmsg_only) {
8243 rewind(f);
8244 err = histedit_parse_list(histedit_cmds, f, repo);
8245 } else {
8246 if (fclose(f) != 0) {
8247 err = got_error_from_errno("fclose");
8248 goto done;
8250 f = NULL;
8251 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8252 if (err) {
8253 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8254 err->code != GOT_ERR_HISTEDIT_CMD)
8255 goto done;
8256 err = histedit_edit_list_retry(histedit_cmds, err,
8257 commits, path, branch_name, repo);
8260 done:
8261 if (f && fclose(f) != 0 && err == NULL)
8262 err = got_error_from_errno("fclose");
8263 if (path && unlink(path) != 0 && err == NULL)
8264 err = got_error_from_errno2("unlink", path);
8265 free(path);
8266 return err;
8269 static const struct got_error *
8270 histedit_save_list(struct got_histedit_list *histedit_cmds,
8271 struct got_worktree *worktree, struct got_repository *repo)
8273 const struct got_error *err = NULL;
8274 char *path = NULL;
8275 FILE *f = NULL;
8276 struct got_histedit_list_entry *hle;
8277 struct got_commit_object *commit = NULL;
8279 err = got_worktree_get_histedit_script_path(&path, worktree);
8280 if (err)
8281 return err;
8283 f = fopen(path, "w");
8284 if (f == NULL) {
8285 err = got_error_from_errno2("fopen", path);
8286 goto done;
8288 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8289 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8290 repo);
8291 if (err)
8292 break;
8294 if (hle->logmsg) {
8295 int n = fprintf(f, "%c %s\n",
8296 GOT_HISTEDIT_MESG, hle->logmsg);
8297 if (n < 0) {
8298 err = got_ferror(f, GOT_ERR_IO);
8299 break;
8303 done:
8304 if (f && fclose(f) != 0 && err == NULL)
8305 err = got_error_from_errno("fclose");
8306 free(path);
8307 if (commit)
8308 got_object_commit_close(commit);
8309 return err;
8312 void
8313 histedit_free_list(struct got_histedit_list *histedit_cmds)
8315 struct got_histedit_list_entry *hle;
8317 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8318 TAILQ_REMOVE(histedit_cmds, hle, entry);
8319 free(hle);
8323 static const struct got_error *
8324 histedit_load_list(struct got_histedit_list *histedit_cmds,
8325 const char *path, struct got_repository *repo)
8327 const struct got_error *err = NULL;
8328 FILE *f = NULL;
8330 f = fopen(path, "r");
8331 if (f == NULL) {
8332 err = got_error_from_errno2("fopen", path);
8333 goto done;
8336 err = histedit_parse_list(histedit_cmds, f, repo);
8337 done:
8338 if (f && fclose(f) != 0 && err == NULL)
8339 err = got_error_from_errno("fclose");
8340 return err;
8343 static const struct got_error *
8344 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8345 const struct got_error *edit_err, struct got_object_id_queue *commits,
8346 const char *path, const char *branch_name, struct got_repository *repo)
8348 const struct got_error *err = NULL, *prev_err = edit_err;
8349 int resp = ' ';
8351 while (resp != 'c' && resp != 'r' && resp != 'a') {
8352 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8353 "or (a)bort: ", getprogname(), prev_err->msg);
8354 resp = getchar();
8355 if (resp == '\n')
8356 resp = getchar();
8357 if (resp == 'c') {
8358 histedit_free_list(histedit_cmds);
8359 err = histedit_run_editor(histedit_cmds, path, commits,
8360 repo);
8361 if (err) {
8362 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8363 err->code != GOT_ERR_HISTEDIT_CMD)
8364 break;
8365 prev_err = err;
8366 resp = ' ';
8367 continue;
8369 break;
8370 } else if (resp == 'r') {
8371 histedit_free_list(histedit_cmds);
8372 err = histedit_edit_script(histedit_cmds,
8373 commits, branch_name, 0, repo);
8374 if (err) {
8375 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8376 err->code != GOT_ERR_HISTEDIT_CMD)
8377 break;
8378 prev_err = err;
8379 resp = ' ';
8380 continue;
8382 break;
8383 } else if (resp == 'a') {
8384 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8385 break;
8386 } else
8387 printf("invalid response '%c'\n", resp);
8390 return err;
8393 static const struct got_error *
8394 histedit_complete(struct got_worktree *worktree,
8395 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8396 struct got_reference *branch, struct got_repository *repo)
8398 printf("Switching work tree to %s\n",
8399 got_ref_get_symref_target(branch));
8400 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8401 branch, repo);
8404 static const struct got_error *
8405 show_histedit_progress(struct got_commit_object *commit,
8406 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8408 const struct got_error *err;
8409 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8411 err = got_object_id_str(&old_id_str, hle->commit_id);
8412 if (err)
8413 goto done;
8415 if (new_id) {
8416 err = got_object_id_str(&new_id_str, new_id);
8417 if (err)
8418 goto done;
8421 old_id_str[12] = '\0';
8422 if (new_id_str)
8423 new_id_str[12] = '\0';
8425 if (hle->logmsg) {
8426 logmsg = strdup(hle->logmsg);
8427 if (logmsg == NULL) {
8428 err = got_error_from_errno("strdup");
8429 goto done;
8431 trim_logmsg(logmsg, 42);
8432 } else {
8433 err = get_short_logmsg(&logmsg, 42, commit);
8434 if (err)
8435 goto done;
8438 switch (hle->cmd->code) {
8439 case GOT_HISTEDIT_PICK:
8440 case GOT_HISTEDIT_EDIT:
8441 printf("%s -> %s: %s\n", old_id_str,
8442 new_id_str ? new_id_str : "no-op change", logmsg);
8443 break;
8444 case GOT_HISTEDIT_DROP:
8445 case GOT_HISTEDIT_FOLD:
8446 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8447 logmsg);
8448 break;
8449 default:
8450 break;
8452 done:
8453 free(old_id_str);
8454 free(new_id_str);
8455 return err;
8458 static const struct got_error *
8459 histedit_commit(struct got_pathlist_head *merged_paths,
8460 struct got_worktree *worktree, struct got_fileindex *fileindex,
8461 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8462 struct got_repository *repo)
8464 const struct got_error *err;
8465 struct got_commit_object *commit;
8466 struct got_object_id *new_commit_id;
8468 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8469 && hle->logmsg == NULL) {
8470 err = histedit_edit_logmsg(hle, repo);
8471 if (err)
8472 return err;
8475 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8476 if (err)
8477 return err;
8479 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8480 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8481 hle->logmsg, repo);
8482 if (err) {
8483 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8484 goto done;
8485 err = show_histedit_progress(commit, hle, NULL);
8486 } else {
8487 err = show_histedit_progress(commit, hle, new_commit_id);
8488 free(new_commit_id);
8490 done:
8491 got_object_commit_close(commit);
8492 return err;
8495 static const struct got_error *
8496 histedit_skip_commit(struct got_histedit_list_entry *hle,
8497 struct got_worktree *worktree, struct got_repository *repo)
8499 const struct got_error *error;
8500 struct got_commit_object *commit;
8502 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8503 repo);
8504 if (error)
8505 return error;
8507 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8508 if (error)
8509 return error;
8511 error = show_histedit_progress(commit, hle, NULL);
8512 got_object_commit_close(commit);
8513 return error;
8516 static const struct got_error *
8517 check_local_changes(void *arg, unsigned char status,
8518 unsigned char staged_status, const char *path,
8519 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8520 struct got_object_id *commit_id, int dirfd, const char *de_name)
8522 int *have_local_changes = arg;
8524 switch (status) {
8525 case GOT_STATUS_ADD:
8526 case GOT_STATUS_DELETE:
8527 case GOT_STATUS_MODIFY:
8528 case GOT_STATUS_CONFLICT:
8529 *have_local_changes = 1;
8530 return got_error(GOT_ERR_CANCELLED);
8531 default:
8532 break;
8535 switch (staged_status) {
8536 case GOT_STATUS_ADD:
8537 case GOT_STATUS_DELETE:
8538 case GOT_STATUS_MODIFY:
8539 *have_local_changes = 1;
8540 return got_error(GOT_ERR_CANCELLED);
8541 default:
8542 break;
8545 return NULL;
8548 static const struct got_error *
8549 cmd_histedit(int argc, char *argv[])
8551 const struct got_error *error = NULL;
8552 struct got_worktree *worktree = NULL;
8553 struct got_fileindex *fileindex = NULL;
8554 struct got_repository *repo = NULL;
8555 char *cwd = NULL;
8556 struct got_reference *branch = NULL;
8557 struct got_reference *tmp_branch = NULL;
8558 struct got_object_id *resume_commit_id = NULL;
8559 struct got_object_id *base_commit_id = NULL;
8560 struct got_object_id *head_commit_id = NULL;
8561 struct got_commit_object *commit = NULL;
8562 int ch, rebase_in_progress = 0;
8563 struct got_update_progress_arg upa;
8564 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8565 int edit_logmsg_only = 0;
8566 const char *edit_script_path = NULL;
8567 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8568 struct got_object_id_queue commits;
8569 struct got_pathlist_head merged_paths;
8570 const struct got_object_id_queue *parent_ids;
8571 struct got_object_qid *pid;
8572 struct got_histedit_list histedit_cmds;
8573 struct got_histedit_list_entry *hle;
8575 SIMPLEQ_INIT(&commits);
8576 TAILQ_INIT(&histedit_cmds);
8577 TAILQ_INIT(&merged_paths);
8578 memset(&upa, 0, sizeof(upa));
8580 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8581 switch (ch) {
8582 case 'a':
8583 abort_edit = 1;
8584 break;
8585 case 'c':
8586 continue_edit = 1;
8587 break;
8588 case 'F':
8589 edit_script_path = optarg;
8590 break;
8591 case 'm':
8592 edit_logmsg_only = 1;
8593 break;
8594 default:
8595 usage_histedit();
8596 /* NOTREACHED */
8600 argc -= optind;
8601 argv += optind;
8603 #ifndef PROFILE
8604 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8605 "unveil", NULL) == -1)
8606 err(1, "pledge");
8607 #endif
8608 if (abort_edit && continue_edit)
8609 errx(1, "histedit's -a and -c options are mutually exclusive");
8610 if (edit_script_path && edit_logmsg_only)
8611 errx(1, "histedit's -F and -m options are mutually exclusive");
8612 if (abort_edit && edit_logmsg_only)
8613 errx(1, "histedit's -a and -m options are mutually exclusive");
8614 if (continue_edit && edit_logmsg_only)
8615 errx(1, "histedit's -c and -m options are mutually exclusive");
8616 if (argc != 0)
8617 usage_histedit();
8620 * This command cannot apply unveil(2) in all cases because the
8621 * user may choose to run an editor to edit the histedit script
8622 * and to edit individual commit log messages.
8623 * unveil(2) traverses exec(2); if an editor is used we have to
8624 * apply unveil after edit script and log messages have been written.
8625 * XXX TODO: Make use of unveil(2) where possible.
8628 cwd = getcwd(NULL, 0);
8629 if (cwd == NULL) {
8630 error = got_error_from_errno("getcwd");
8631 goto done;
8633 error = got_worktree_open(&worktree, cwd);
8634 if (error) {
8635 if (error->code == GOT_ERR_NOT_WORKTREE)
8636 error = wrap_not_worktree_error(error, "histedit", cwd);
8637 goto done;
8640 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8641 NULL);
8642 if (error != NULL)
8643 goto done;
8645 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8646 if (error)
8647 goto done;
8648 if (rebase_in_progress) {
8649 error = got_error(GOT_ERR_REBASING);
8650 goto done;
8653 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8654 if (error)
8655 goto done;
8657 if (edit_in_progress && edit_logmsg_only) {
8658 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8659 "histedit operation is in progress in this "
8660 "work tree and must be continued or aborted "
8661 "before the -m option can be used");
8662 goto done;
8665 if (edit_in_progress && abort_edit) {
8666 error = got_worktree_histedit_continue(&resume_commit_id,
8667 &tmp_branch, &branch, &base_commit_id, &fileindex,
8668 worktree, repo);
8669 if (error)
8670 goto done;
8671 printf("Switching work tree to %s\n",
8672 got_ref_get_symref_target(branch));
8673 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8674 branch, base_commit_id, update_progress, &upa);
8675 if (error)
8676 goto done;
8677 printf("Histedit of %s aborted\n",
8678 got_ref_get_symref_target(branch));
8679 print_update_progress_stats(&upa);
8680 goto done; /* nothing else to do */
8681 } else if (abort_edit) {
8682 error = got_error(GOT_ERR_NOT_HISTEDIT);
8683 goto done;
8686 if (continue_edit) {
8687 char *path;
8689 if (!edit_in_progress) {
8690 error = got_error(GOT_ERR_NOT_HISTEDIT);
8691 goto done;
8694 error = got_worktree_get_histedit_script_path(&path, worktree);
8695 if (error)
8696 goto done;
8698 error = histedit_load_list(&histedit_cmds, path, repo);
8699 free(path);
8700 if (error)
8701 goto done;
8703 error = got_worktree_histedit_continue(&resume_commit_id,
8704 &tmp_branch, &branch, &base_commit_id, &fileindex,
8705 worktree, repo);
8706 if (error)
8707 goto done;
8709 error = got_ref_resolve(&head_commit_id, repo, branch);
8710 if (error)
8711 goto done;
8713 error = got_object_open_as_commit(&commit, repo,
8714 head_commit_id);
8715 if (error)
8716 goto done;
8717 parent_ids = got_object_commit_get_parent_ids(commit);
8718 pid = SIMPLEQ_FIRST(parent_ids);
8719 if (pid == NULL) {
8720 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8721 goto done;
8723 error = collect_commits(&commits, head_commit_id, pid->id,
8724 base_commit_id, got_worktree_get_path_prefix(worktree),
8725 GOT_ERR_HISTEDIT_PATH, repo);
8726 got_object_commit_close(commit);
8727 commit = NULL;
8728 if (error)
8729 goto done;
8730 } else {
8731 if (edit_in_progress) {
8732 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8733 goto done;
8736 error = got_ref_open(&branch, repo,
8737 got_worktree_get_head_ref_name(worktree), 0);
8738 if (error != NULL)
8739 goto done;
8741 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8742 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8743 "will not edit commit history of a branch outside "
8744 "the \"refs/heads/\" reference namespace");
8745 goto done;
8748 error = got_ref_resolve(&head_commit_id, repo, branch);
8749 got_ref_close(branch);
8750 branch = NULL;
8751 if (error)
8752 goto done;
8754 error = got_object_open_as_commit(&commit, repo,
8755 head_commit_id);
8756 if (error)
8757 goto done;
8758 parent_ids = got_object_commit_get_parent_ids(commit);
8759 pid = SIMPLEQ_FIRST(parent_ids);
8760 if (pid == NULL) {
8761 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8762 goto done;
8764 error = collect_commits(&commits, head_commit_id, pid->id,
8765 got_worktree_get_base_commit_id(worktree),
8766 got_worktree_get_path_prefix(worktree),
8767 GOT_ERR_HISTEDIT_PATH, repo);
8768 got_object_commit_close(commit);
8769 commit = NULL;
8770 if (error)
8771 goto done;
8773 if (SIMPLEQ_EMPTY(&commits)) {
8774 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8775 goto done;
8778 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8779 &base_commit_id, &fileindex, worktree, repo);
8780 if (error)
8781 goto done;
8783 if (edit_script_path) {
8784 error = histedit_load_list(&histedit_cmds,
8785 edit_script_path, repo);
8786 if (error) {
8787 got_worktree_histedit_abort(worktree, fileindex,
8788 repo, branch, base_commit_id,
8789 update_progress, &upa);
8790 print_update_progress_stats(&upa);
8791 goto done;
8793 } else {
8794 const char *branch_name;
8795 branch_name = got_ref_get_symref_target(branch);
8796 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8797 branch_name += 11;
8798 error = histedit_edit_script(&histedit_cmds, &commits,
8799 branch_name, edit_logmsg_only, repo);
8800 if (error) {
8801 got_worktree_histedit_abort(worktree, fileindex,
8802 repo, branch, base_commit_id,
8803 update_progress, &upa);
8804 print_update_progress_stats(&upa);
8805 goto done;
8810 error = histedit_save_list(&histedit_cmds, worktree,
8811 repo);
8812 if (error) {
8813 got_worktree_histedit_abort(worktree, fileindex,
8814 repo, branch, base_commit_id,
8815 update_progress, &upa);
8816 print_update_progress_stats(&upa);
8817 goto done;
8822 error = histedit_check_script(&histedit_cmds, &commits, repo);
8823 if (error)
8824 goto done;
8826 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8827 if (resume_commit_id) {
8828 if (got_object_id_cmp(hle->commit_id,
8829 resume_commit_id) != 0)
8830 continue;
8832 resume_commit_id = NULL;
8833 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8834 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8835 error = histedit_skip_commit(hle, worktree,
8836 repo);
8837 if (error)
8838 goto done;
8839 } else {
8840 struct got_pathlist_head paths;
8841 int have_changes = 0;
8843 TAILQ_INIT(&paths);
8844 error = got_pathlist_append(&paths, "", NULL);
8845 if (error)
8846 goto done;
8847 error = got_worktree_status(worktree, &paths,
8848 repo, check_local_changes, &have_changes,
8849 check_cancelled, NULL);
8850 got_pathlist_free(&paths);
8851 if (error) {
8852 if (error->code != GOT_ERR_CANCELLED)
8853 goto done;
8854 if (sigint_received || sigpipe_received)
8855 goto done;
8857 if (have_changes) {
8858 error = histedit_commit(NULL, worktree,
8859 fileindex, tmp_branch, hle, repo);
8860 if (error)
8861 goto done;
8862 } else {
8863 error = got_object_open_as_commit(
8864 &commit, repo, hle->commit_id);
8865 if (error)
8866 goto done;
8867 error = show_histedit_progress(commit,
8868 hle, NULL);
8869 got_object_commit_close(commit);
8870 commit = NULL;
8871 if (error)
8872 goto done;
8875 continue;
8878 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8879 error = histedit_skip_commit(hle, worktree, repo);
8880 if (error)
8881 goto done;
8882 continue;
8885 error = got_object_open_as_commit(&commit, repo,
8886 hle->commit_id);
8887 if (error)
8888 goto done;
8889 parent_ids = got_object_commit_get_parent_ids(commit);
8890 pid = SIMPLEQ_FIRST(parent_ids);
8892 error = got_worktree_histedit_merge_files(&merged_paths,
8893 worktree, fileindex, pid->id, hle->commit_id, repo,
8894 update_progress, &upa, check_cancelled, NULL);
8895 if (error)
8896 goto done;
8897 got_object_commit_close(commit);
8898 commit = NULL;
8900 print_update_progress_stats(&upa);
8901 if (upa.conflicts > 0)
8902 rebase_status = GOT_STATUS_CONFLICT;
8904 if (rebase_status == GOT_STATUS_CONFLICT) {
8905 error = show_rebase_merge_conflict(hle->commit_id,
8906 repo);
8907 if (error)
8908 goto done;
8909 got_worktree_rebase_pathlist_free(&merged_paths);
8910 break;
8913 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8914 char *id_str;
8915 error = got_object_id_str(&id_str, hle->commit_id);
8916 if (error)
8917 goto done;
8918 printf("Stopping histedit for amending commit %s\n",
8919 id_str);
8920 free(id_str);
8921 got_worktree_rebase_pathlist_free(&merged_paths);
8922 error = got_worktree_histedit_postpone(worktree,
8923 fileindex);
8924 goto done;
8927 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8928 error = histedit_skip_commit(hle, worktree, repo);
8929 if (error)
8930 goto done;
8931 continue;
8934 error = histedit_commit(&merged_paths, worktree, fileindex,
8935 tmp_branch, hle, repo);
8936 got_worktree_rebase_pathlist_free(&merged_paths);
8937 if (error)
8938 goto done;
8941 if (rebase_status == GOT_STATUS_CONFLICT) {
8942 error = got_worktree_histedit_postpone(worktree, fileindex);
8943 if (error)
8944 goto done;
8945 error = got_error_msg(GOT_ERR_CONFLICTS,
8946 "conflicts must be resolved before histedit can continue");
8947 } else
8948 error = histedit_complete(worktree, fileindex, tmp_branch,
8949 branch, repo);
8950 done:
8951 got_object_id_queue_free(&commits);
8952 histedit_free_list(&histedit_cmds);
8953 free(head_commit_id);
8954 free(base_commit_id);
8955 free(resume_commit_id);
8956 if (commit)
8957 got_object_commit_close(commit);
8958 if (branch)
8959 got_ref_close(branch);
8960 if (tmp_branch)
8961 got_ref_close(tmp_branch);
8962 if (worktree)
8963 got_worktree_close(worktree);
8964 if (repo)
8965 got_repo_close(repo);
8966 return error;
8969 __dead static void
8970 usage_integrate(void)
8972 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8973 exit(1);
8976 static const struct got_error *
8977 cmd_integrate(int argc, char *argv[])
8979 const struct got_error *error = NULL;
8980 struct got_repository *repo = NULL;
8981 struct got_worktree *worktree = NULL;
8982 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8983 const char *branch_arg = NULL;
8984 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8985 struct got_fileindex *fileindex = NULL;
8986 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8987 int ch;
8988 struct got_update_progress_arg upa;
8990 while ((ch = getopt(argc, argv, "")) != -1) {
8991 switch (ch) {
8992 default:
8993 usage_integrate();
8994 /* NOTREACHED */
8998 argc -= optind;
8999 argv += optind;
9001 if (argc != 1)
9002 usage_integrate();
9003 branch_arg = argv[0];
9004 #ifndef PROFILE
9005 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9006 "unveil", NULL) == -1)
9007 err(1, "pledge");
9008 #endif
9009 cwd = getcwd(NULL, 0);
9010 if (cwd == NULL) {
9011 error = got_error_from_errno("getcwd");
9012 goto done;
9015 error = got_worktree_open(&worktree, cwd);
9016 if (error) {
9017 if (error->code == GOT_ERR_NOT_WORKTREE)
9018 error = wrap_not_worktree_error(error, "integrate",
9019 cwd);
9020 goto done;
9023 error = check_rebase_or_histedit_in_progress(worktree);
9024 if (error)
9025 goto done;
9027 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9028 NULL);
9029 if (error != NULL)
9030 goto done;
9032 error = apply_unveil(got_repo_get_path(repo), 0,
9033 got_worktree_get_root_path(worktree));
9034 if (error)
9035 goto done;
9037 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9038 error = got_error_from_errno("asprintf");
9039 goto done;
9042 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9043 &base_branch_ref, worktree, refname, repo);
9044 if (error)
9045 goto done;
9047 refname = strdup(got_ref_get_name(branch_ref));
9048 if (refname == NULL) {
9049 error = got_error_from_errno("strdup");
9050 got_worktree_integrate_abort(worktree, fileindex, repo,
9051 branch_ref, base_branch_ref);
9052 goto done;
9054 base_refname = strdup(got_ref_get_name(base_branch_ref));
9055 if (base_refname == NULL) {
9056 error = got_error_from_errno("strdup");
9057 got_worktree_integrate_abort(worktree, fileindex, repo,
9058 branch_ref, base_branch_ref);
9059 goto done;
9062 error = got_ref_resolve(&commit_id, repo, branch_ref);
9063 if (error)
9064 goto done;
9066 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9067 if (error)
9068 goto done;
9070 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9071 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9072 "specified branch has already been integrated");
9073 got_worktree_integrate_abort(worktree, fileindex, repo,
9074 branch_ref, base_branch_ref);
9075 goto done;
9078 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9079 if (error) {
9080 if (error->code == GOT_ERR_ANCESTRY)
9081 error = got_error(GOT_ERR_REBASE_REQUIRED);
9082 got_worktree_integrate_abort(worktree, fileindex, repo,
9083 branch_ref, base_branch_ref);
9084 goto done;
9087 memset(&upa, 0, sizeof(upa));
9088 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9089 branch_ref, base_branch_ref, update_progress, &upa,
9090 check_cancelled, NULL);
9091 if (error)
9092 goto done;
9094 printf("Integrated %s into %s\n", refname, base_refname);
9095 print_update_progress_stats(&upa);
9096 done:
9097 if (repo)
9098 got_repo_close(repo);
9099 if (worktree)
9100 got_worktree_close(worktree);
9101 free(cwd);
9102 free(base_commit_id);
9103 free(commit_id);
9104 free(refname);
9105 free(base_refname);
9106 return error;
9109 __dead static void
9110 usage_stage(void)
9112 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9113 "[-S] [file-path ...]\n",
9114 getprogname());
9115 exit(1);
9118 static const struct got_error *
9119 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9120 const char *path, struct got_object_id *blob_id,
9121 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9122 int dirfd, const char *de_name)
9124 const struct got_error *err = NULL;
9125 char *id_str = NULL;
9127 if (staged_status != GOT_STATUS_ADD &&
9128 staged_status != GOT_STATUS_MODIFY &&
9129 staged_status != GOT_STATUS_DELETE)
9130 return NULL;
9132 if (staged_status == GOT_STATUS_ADD ||
9133 staged_status == GOT_STATUS_MODIFY)
9134 err = got_object_id_str(&id_str, staged_blob_id);
9135 else
9136 err = got_object_id_str(&id_str, blob_id);
9137 if (err)
9138 return err;
9140 printf("%s %c %s\n", id_str, staged_status, path);
9141 free(id_str);
9142 return NULL;
9145 static const struct got_error *
9146 cmd_stage(int argc, char *argv[])
9148 const struct got_error *error = NULL;
9149 struct got_repository *repo = NULL;
9150 struct got_worktree *worktree = NULL;
9151 char *cwd = NULL;
9152 struct got_pathlist_head paths;
9153 struct got_pathlist_entry *pe;
9154 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9155 FILE *patch_script_file = NULL;
9156 const char *patch_script_path = NULL;
9157 struct choose_patch_arg cpa;
9159 TAILQ_INIT(&paths);
9161 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9162 switch (ch) {
9163 case 'l':
9164 list_stage = 1;
9165 break;
9166 case 'p':
9167 pflag = 1;
9168 break;
9169 case 'F':
9170 patch_script_path = optarg;
9171 break;
9172 case 'S':
9173 allow_bad_symlinks = 1;
9174 break;
9175 default:
9176 usage_stage();
9177 /* NOTREACHED */
9181 argc -= optind;
9182 argv += optind;
9184 #ifndef PROFILE
9185 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9186 "unveil", NULL) == -1)
9187 err(1, "pledge");
9188 #endif
9189 if (list_stage && (pflag || patch_script_path))
9190 errx(1, "-l option cannot be used with other options");
9191 if (patch_script_path && !pflag)
9192 errx(1, "-F option can only be used together with -p option");
9194 cwd = getcwd(NULL, 0);
9195 if (cwd == NULL) {
9196 error = got_error_from_errno("getcwd");
9197 goto done;
9200 error = got_worktree_open(&worktree, cwd);
9201 if (error) {
9202 if (error->code == GOT_ERR_NOT_WORKTREE)
9203 error = wrap_not_worktree_error(error, "stage", cwd);
9204 goto done;
9207 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9208 NULL);
9209 if (error != NULL)
9210 goto done;
9212 if (patch_script_path) {
9213 patch_script_file = fopen(patch_script_path, "r");
9214 if (patch_script_file == NULL) {
9215 error = got_error_from_errno2("fopen",
9216 patch_script_path);
9217 goto done;
9220 error = apply_unveil(got_repo_get_path(repo), 0,
9221 got_worktree_get_root_path(worktree));
9222 if (error)
9223 goto done;
9225 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9226 if (error)
9227 goto done;
9229 if (list_stage)
9230 error = got_worktree_status(worktree, &paths, repo,
9231 print_stage, NULL, check_cancelled, NULL);
9232 else {
9233 cpa.patch_script_file = patch_script_file;
9234 cpa.action = "stage";
9235 error = got_worktree_stage(worktree, &paths,
9236 pflag ? NULL : print_status, NULL,
9237 pflag ? choose_patch : NULL, &cpa,
9238 allow_bad_symlinks, repo);
9240 done:
9241 if (patch_script_file && fclose(patch_script_file) == EOF &&
9242 error == NULL)
9243 error = got_error_from_errno2("fclose", patch_script_path);
9244 if (repo)
9245 got_repo_close(repo);
9246 if (worktree)
9247 got_worktree_close(worktree);
9248 TAILQ_FOREACH(pe, &paths, entry)
9249 free((char *)pe->path);
9250 got_pathlist_free(&paths);
9251 free(cwd);
9252 return error;
9255 __dead static void
9256 usage_unstage(void)
9258 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9259 "[file-path ...]\n",
9260 getprogname());
9261 exit(1);
9265 static const struct got_error *
9266 cmd_unstage(int argc, char *argv[])
9268 const struct got_error *error = NULL;
9269 struct got_repository *repo = NULL;
9270 struct got_worktree *worktree = NULL;
9271 char *cwd = NULL;
9272 struct got_pathlist_head paths;
9273 struct got_pathlist_entry *pe;
9274 int ch, pflag = 0;
9275 struct got_update_progress_arg upa;
9276 FILE *patch_script_file = NULL;
9277 const char *patch_script_path = NULL;
9278 struct choose_patch_arg cpa;
9280 TAILQ_INIT(&paths);
9282 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9283 switch (ch) {
9284 case 'p':
9285 pflag = 1;
9286 break;
9287 case 'F':
9288 patch_script_path = optarg;
9289 break;
9290 default:
9291 usage_unstage();
9292 /* NOTREACHED */
9296 argc -= optind;
9297 argv += optind;
9299 #ifndef PROFILE
9300 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9301 "unveil", NULL) == -1)
9302 err(1, "pledge");
9303 #endif
9304 if (patch_script_path && !pflag)
9305 errx(1, "-F option can only be used together with -p option");
9307 cwd = getcwd(NULL, 0);
9308 if (cwd == NULL) {
9309 error = got_error_from_errno("getcwd");
9310 goto done;
9313 error = got_worktree_open(&worktree, cwd);
9314 if (error) {
9315 if (error->code == GOT_ERR_NOT_WORKTREE)
9316 error = wrap_not_worktree_error(error, "unstage", cwd);
9317 goto done;
9320 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9321 NULL);
9322 if (error != NULL)
9323 goto done;
9325 if (patch_script_path) {
9326 patch_script_file = fopen(patch_script_path, "r");
9327 if (patch_script_file == NULL) {
9328 error = got_error_from_errno2("fopen",
9329 patch_script_path);
9330 goto done;
9334 error = apply_unveil(got_repo_get_path(repo), 0,
9335 got_worktree_get_root_path(worktree));
9336 if (error)
9337 goto done;
9339 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9340 if (error)
9341 goto done;
9343 cpa.patch_script_file = patch_script_file;
9344 cpa.action = "unstage";
9345 memset(&upa, 0, sizeof(upa));
9346 error = got_worktree_unstage(worktree, &paths, update_progress,
9347 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9348 if (!error)
9349 print_update_progress_stats(&upa);
9350 done:
9351 if (patch_script_file && fclose(patch_script_file) == EOF &&
9352 error == NULL)
9353 error = got_error_from_errno2("fclose", patch_script_path);
9354 if (repo)
9355 got_repo_close(repo);
9356 if (worktree)
9357 got_worktree_close(worktree);
9358 TAILQ_FOREACH(pe, &paths, entry)
9359 free((char *)pe->path);
9360 got_pathlist_free(&paths);
9361 free(cwd);
9362 return error;
9365 __dead static void
9366 usage_cat(void)
9368 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9369 "arg1 [arg2 ...]\n", getprogname());
9370 exit(1);
9373 static const struct got_error *
9374 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9376 const struct got_error *err;
9377 struct got_blob_object *blob;
9379 err = got_object_open_as_blob(&blob, repo, id, 8192);
9380 if (err)
9381 return err;
9383 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9384 got_object_blob_close(blob);
9385 return err;
9388 static const struct got_error *
9389 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9391 const struct got_error *err;
9392 struct got_tree_object *tree;
9393 int nentries, i;
9395 err = got_object_open_as_tree(&tree, repo, id);
9396 if (err)
9397 return err;
9399 nentries = got_object_tree_get_nentries(tree);
9400 for (i = 0; i < nentries; i++) {
9401 struct got_tree_entry *te;
9402 char *id_str;
9403 if (sigint_received || sigpipe_received)
9404 break;
9405 te = got_object_tree_get_entry(tree, i);
9406 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9407 if (err)
9408 break;
9409 fprintf(outfile, "%s %.7o %s\n", id_str,
9410 got_tree_entry_get_mode(te),
9411 got_tree_entry_get_name(te));
9412 free(id_str);
9415 got_object_tree_close(tree);
9416 return err;
9419 static const struct got_error *
9420 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9422 const struct got_error *err;
9423 struct got_commit_object *commit;
9424 const struct got_object_id_queue *parent_ids;
9425 struct got_object_qid *pid;
9426 char *id_str = NULL;
9427 const char *logmsg = NULL;
9429 err = got_object_open_as_commit(&commit, repo, id);
9430 if (err)
9431 return err;
9433 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9434 if (err)
9435 goto done;
9437 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9438 parent_ids = got_object_commit_get_parent_ids(commit);
9439 fprintf(outfile, "numparents %d\n",
9440 got_object_commit_get_nparents(commit));
9441 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9442 char *pid_str;
9443 err = got_object_id_str(&pid_str, pid->id);
9444 if (err)
9445 goto done;
9446 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9447 free(pid_str);
9449 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9450 got_object_commit_get_author(commit),
9451 (long long)got_object_commit_get_author_time(commit));
9453 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9454 got_object_commit_get_author(commit),
9455 (long long)got_object_commit_get_committer_time(commit));
9457 logmsg = got_object_commit_get_logmsg_raw(commit);
9458 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9459 fprintf(outfile, "%s", logmsg);
9460 done:
9461 free(id_str);
9462 got_object_commit_close(commit);
9463 return err;
9466 static const struct got_error *
9467 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9469 const struct got_error *err;
9470 struct got_tag_object *tag;
9471 char *id_str = NULL;
9472 const char *tagmsg = NULL;
9474 err = got_object_open_as_tag(&tag, repo, id);
9475 if (err)
9476 return err;
9478 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9479 if (err)
9480 goto done;
9482 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9484 switch (got_object_tag_get_object_type(tag)) {
9485 case GOT_OBJ_TYPE_BLOB:
9486 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9487 GOT_OBJ_LABEL_BLOB);
9488 break;
9489 case GOT_OBJ_TYPE_TREE:
9490 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9491 GOT_OBJ_LABEL_TREE);
9492 break;
9493 case GOT_OBJ_TYPE_COMMIT:
9494 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9495 GOT_OBJ_LABEL_COMMIT);
9496 break;
9497 case GOT_OBJ_TYPE_TAG:
9498 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9499 GOT_OBJ_LABEL_TAG);
9500 break;
9501 default:
9502 break;
9505 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9506 got_object_tag_get_name(tag));
9508 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9509 got_object_tag_get_tagger(tag),
9510 (long long)got_object_tag_get_tagger_time(tag));
9512 tagmsg = got_object_tag_get_message(tag);
9513 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9514 fprintf(outfile, "%s", tagmsg);
9515 done:
9516 free(id_str);
9517 got_object_tag_close(tag);
9518 return err;
9521 static const struct got_error *
9522 cmd_cat(int argc, char *argv[])
9524 const struct got_error *error;
9525 struct got_repository *repo = NULL;
9526 struct got_worktree *worktree = NULL;
9527 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9528 const char *commit_id_str = NULL;
9529 struct got_object_id *id = NULL, *commit_id = NULL;
9530 int ch, obj_type, i, force_path = 0;
9532 #ifndef PROFILE
9533 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9534 NULL) == -1)
9535 err(1, "pledge");
9536 #endif
9538 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9539 switch (ch) {
9540 case 'c':
9541 commit_id_str = optarg;
9542 break;
9543 case 'r':
9544 repo_path = realpath(optarg, NULL);
9545 if (repo_path == NULL)
9546 return got_error_from_errno2("realpath",
9547 optarg);
9548 got_path_strip_trailing_slashes(repo_path);
9549 break;
9550 case 'P':
9551 force_path = 1;
9552 break;
9553 default:
9554 usage_cat();
9555 /* NOTREACHED */
9559 argc -= optind;
9560 argv += optind;
9562 cwd = getcwd(NULL, 0);
9563 if (cwd == NULL) {
9564 error = got_error_from_errno("getcwd");
9565 goto done;
9567 error = got_worktree_open(&worktree, cwd);
9568 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9569 goto done;
9570 if (worktree) {
9571 if (repo_path == NULL) {
9572 repo_path = strdup(
9573 got_worktree_get_repo_path(worktree));
9574 if (repo_path == NULL) {
9575 error = got_error_from_errno("strdup");
9576 goto done;
9581 if (repo_path == NULL) {
9582 repo_path = getcwd(NULL, 0);
9583 if (repo_path == NULL)
9584 return got_error_from_errno("getcwd");
9587 error = got_repo_open(&repo, repo_path, NULL);
9588 free(repo_path);
9589 if (error != NULL)
9590 goto done;
9592 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9593 if (error)
9594 goto done;
9596 if (commit_id_str == NULL)
9597 commit_id_str = GOT_REF_HEAD;
9598 error = got_repo_match_object_id(&commit_id, NULL,
9599 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9600 if (error)
9601 goto done;
9603 for (i = 0; i < argc; i++) {
9604 if (force_path) {
9605 error = got_object_id_by_path(&id, repo, commit_id,
9606 argv[i]);
9607 if (error)
9608 break;
9609 } else {
9610 error = got_repo_match_object_id(&id, &label, argv[i],
9611 GOT_OBJ_TYPE_ANY, 0, repo);
9612 if (error) {
9613 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9614 error->code != GOT_ERR_NOT_REF)
9615 break;
9616 error = got_object_id_by_path(&id, repo,
9617 commit_id, argv[i]);
9618 if (error)
9619 break;
9623 error = got_object_get_type(&obj_type, repo, id);
9624 if (error)
9625 break;
9627 switch (obj_type) {
9628 case GOT_OBJ_TYPE_BLOB:
9629 error = cat_blob(id, repo, stdout);
9630 break;
9631 case GOT_OBJ_TYPE_TREE:
9632 error = cat_tree(id, repo, stdout);
9633 break;
9634 case GOT_OBJ_TYPE_COMMIT:
9635 error = cat_commit(id, repo, stdout);
9636 break;
9637 case GOT_OBJ_TYPE_TAG:
9638 error = cat_tag(id, repo, stdout);
9639 break;
9640 default:
9641 error = got_error(GOT_ERR_OBJ_TYPE);
9642 break;
9644 if (error)
9645 break;
9646 free(label);
9647 label = NULL;
9648 free(id);
9649 id = NULL;
9651 done:
9652 free(label);
9653 free(id);
9654 free(commit_id);
9655 if (worktree)
9656 got_worktree_close(worktree);
9657 if (repo) {
9658 const struct got_error *repo_error;
9659 repo_error = got_repo_close(repo);
9660 if (error == NULL)
9661 error = repo_error;
9663 return error;
9666 __dead static void
9667 usage_info(void)
9669 fprintf(stderr, "usage: %s info [path ...]\n",
9670 getprogname());
9671 exit(1);
9674 static const struct got_error *
9675 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9676 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9677 struct got_object_id *commit_id)
9679 const struct got_error *err = NULL;
9680 char *id_str = NULL;
9681 char datebuf[128];
9682 struct tm mytm, *tm;
9683 struct got_pathlist_head *paths = arg;
9684 struct got_pathlist_entry *pe;
9687 * Clear error indication from any of the path arguments which
9688 * would cause this file index entry to be displayed.
9690 TAILQ_FOREACH(pe, paths, entry) {
9691 if (got_path_cmp(path, pe->path, strlen(path),
9692 pe->path_len) == 0 ||
9693 got_path_is_child(path, pe->path, pe->path_len))
9694 pe->data = NULL; /* no error */
9697 printf(GOT_COMMIT_SEP_STR);
9698 if (S_ISLNK(mode))
9699 printf("symlink: %s\n", path);
9700 else if (S_ISREG(mode)) {
9701 printf("file: %s\n", path);
9702 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9703 } else if (S_ISDIR(mode))
9704 printf("directory: %s\n", path);
9705 else
9706 printf("something: %s\n", path);
9708 tm = localtime_r(&mtime, &mytm);
9709 if (tm == NULL)
9710 return NULL;
9711 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9712 return got_error(GOT_ERR_NO_SPACE);
9713 printf("timestamp: %s\n", datebuf);
9715 if (blob_id) {
9716 err = got_object_id_str(&id_str, blob_id);
9717 if (err)
9718 return err;
9719 printf("based on blob: %s\n", id_str);
9720 free(id_str);
9723 if (staged_blob_id) {
9724 err = got_object_id_str(&id_str, staged_blob_id);
9725 if (err)
9726 return err;
9727 printf("based on staged blob: %s\n", id_str);
9728 free(id_str);
9731 if (commit_id) {
9732 err = got_object_id_str(&id_str, commit_id);
9733 if (err)
9734 return err;
9735 printf("based on commit: %s\n", id_str);
9736 free(id_str);
9739 return NULL;
9742 static const struct got_error *
9743 cmd_info(int argc, char *argv[])
9745 const struct got_error *error = NULL;
9746 struct got_worktree *worktree = NULL;
9747 char *cwd = NULL, *id_str = NULL;
9748 struct got_pathlist_head paths;
9749 struct got_pathlist_entry *pe;
9750 char *uuidstr = NULL;
9751 int ch, show_files = 0;
9753 TAILQ_INIT(&paths);
9755 while ((ch = getopt(argc, argv, "")) != -1) {
9756 switch (ch) {
9757 default:
9758 usage_info();
9759 /* NOTREACHED */
9763 argc -= optind;
9764 argv += optind;
9766 #ifndef PROFILE
9767 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9768 NULL) == -1)
9769 err(1, "pledge");
9770 #endif
9771 cwd = getcwd(NULL, 0);
9772 if (cwd == NULL) {
9773 error = got_error_from_errno("getcwd");
9774 goto done;
9777 error = got_worktree_open(&worktree, cwd);
9778 if (error) {
9779 if (error->code == GOT_ERR_NOT_WORKTREE)
9780 error = wrap_not_worktree_error(error, "status", cwd);
9781 goto done;
9784 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9785 if (error)
9786 goto done;
9788 if (argc >= 1) {
9789 error = get_worktree_paths_from_argv(&paths, argc, argv,
9790 worktree);
9791 if (error)
9792 goto done;
9793 show_files = 1;
9796 error = got_object_id_str(&id_str,
9797 got_worktree_get_base_commit_id(worktree));
9798 if (error)
9799 goto done;
9801 error = got_worktree_get_uuid(&uuidstr, worktree);
9802 if (error)
9803 goto done;
9805 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9806 printf("work tree base commit: %s\n", id_str);
9807 printf("work tree path prefix: %s\n",
9808 got_worktree_get_path_prefix(worktree));
9809 printf("work tree branch reference: %s\n",
9810 got_worktree_get_head_ref_name(worktree));
9811 printf("work tree UUID: %s\n", uuidstr);
9812 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9814 if (show_files) {
9815 struct got_pathlist_entry *pe;
9816 TAILQ_FOREACH(pe, &paths, entry) {
9817 if (pe->path_len == 0)
9818 continue;
9820 * Assume this path will fail. This will be corrected
9821 * in print_path_info() in case the path does suceeed.
9823 pe->data = (void *)got_error_path(pe->path,
9824 GOT_ERR_BAD_PATH);
9826 error = got_worktree_path_info(worktree, &paths,
9827 print_path_info, &paths, check_cancelled, NULL);
9828 if (error)
9829 goto done;
9830 TAILQ_FOREACH(pe, &paths, entry) {
9831 if (pe->data != NULL) {
9832 error = pe->data; /* bad path */
9833 break;
9837 done:
9838 TAILQ_FOREACH(pe, &paths, entry)
9839 free((char *)pe->path);
9840 got_pathlist_free(&paths);
9841 free(cwd);
9842 free(id_str);
9843 free(uuidstr);
9844 return error;