Blob


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