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 size_t 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 __dead static void
187 option_conflict(char a, char b)
189 errx(1, "-%c and -%c options are mutually exclusive", a, b);
192 int
193 main(int argc, char *argv[])
195 struct got_cmd *cmd;
196 size_t i;
197 int ch;
198 int hflag = 0, Vflag = 0;
199 static struct option longopts[] = {
200 { "version", no_argument, NULL, 'V' },
201 { NULL, 0, NULL, 0 }
202 };
204 setlocale(LC_CTYPE, "");
206 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
207 switch (ch) {
208 case 'h':
209 hflag = 1;
210 break;
211 case 'V':
212 Vflag = 1;
213 break;
214 default:
215 usage(hflag, 1);
216 /* NOTREACHED */
220 argc -= optind;
221 argv += optind;
222 optind = 1;
223 optreset = 1;
225 if (Vflag) {
226 got_version_print_str();
227 return 0;
230 if (argc <= 0)
231 usage(hflag, hflag ? 0 : 1);
233 signal(SIGINT, catch_sigint);
234 signal(SIGPIPE, catch_sigpipe);
236 for (i = 0; i < nitems(got_commands); i++) {
237 const struct got_error *error;
239 cmd = &got_commands[i];
241 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
242 strcmp(cmd->cmd_alias, argv[0]) != 0)
243 continue;
245 if (hflag)
246 got_commands[i].cmd_usage();
248 error = got_commands[i].cmd_main(argc, argv);
249 if (error && error->code != GOT_ERR_CANCELLED &&
250 error->code != GOT_ERR_PRIVSEP_EXIT &&
251 !(sigpipe_received &&
252 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
253 !(sigint_received &&
254 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
255 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
256 return 1;
259 return 0;
262 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
263 list_commands(stderr);
264 return 1;
267 __dead static void
268 usage(int hflag, int status)
270 FILE *fp = (status == 0) ? stdout : stderr;
272 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
273 getprogname());
274 if (hflag)
275 list_commands(fp);
276 exit(status);
279 static const struct got_error *
280 get_editor(char **abspath)
282 const struct got_error *err = NULL;
283 const char *editor;
285 *abspath = NULL;
287 editor = getenv("VISUAL");
288 if (editor == NULL)
289 editor = getenv("EDITOR");
291 if (editor) {
292 err = got_path_find_prog(abspath, editor);
293 if (err)
294 return err;
297 if (*abspath == NULL) {
298 *abspath = strdup("/bin/ed");
299 if (*abspath == NULL)
300 return got_error_from_errno("strdup");
303 return NULL;
306 static const struct got_error *
307 apply_unveil(const char *repo_path, int repo_read_only,
308 const char *worktree_path)
310 const struct got_error *err;
312 #ifdef PROFILE
313 if (unveil("gmon.out", "rwc") != 0)
314 return got_error_from_errno2("unveil", "gmon.out");
315 #endif
316 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
317 return got_error_from_errno2("unveil", repo_path);
319 if (worktree_path && unveil(worktree_path, "rwc") != 0)
320 return got_error_from_errno2("unveil", worktree_path);
322 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
323 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
325 err = got_privsep_unveil_exec_helpers();
326 if (err != NULL)
327 return err;
329 if (unveil(NULL, NULL) != 0)
330 return got_error_from_errno("unveil");
332 return NULL;
335 __dead static void
336 usage_init(void)
338 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
339 exit(1);
342 static const struct got_error *
343 cmd_init(int argc, char *argv[])
345 const struct got_error *error = NULL;
346 char *repo_path = NULL;
347 int ch;
349 while ((ch = getopt(argc, argv, "")) != -1) {
350 switch (ch) {
351 default:
352 usage_init();
353 /* NOTREACHED */
357 argc -= optind;
358 argv += optind;
360 #ifndef PROFILE
361 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
362 err(1, "pledge");
363 #endif
364 if (argc != 1)
365 usage_init();
367 repo_path = strdup(argv[0]);
368 if (repo_path == NULL)
369 return got_error_from_errno("strdup");
371 got_path_strip_trailing_slashes(repo_path);
373 error = got_path_mkdir(repo_path);
374 if (error &&
375 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
376 goto done;
378 error = apply_unveil(repo_path, 0, NULL);
379 if (error)
380 goto done;
382 error = got_repo_init(repo_path);
383 done:
384 free(repo_path);
385 return error;
388 __dead static void
389 usage_import(void)
391 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
392 "[-r repository-path] [-I pattern] path\n", getprogname());
393 exit(1);
396 int
397 spawn_editor(const char *editor, const char *file)
399 pid_t pid;
400 sig_t sighup, sigint, sigquit;
401 int st = -1;
403 sighup = signal(SIGHUP, SIG_IGN);
404 sigint = signal(SIGINT, SIG_IGN);
405 sigquit = signal(SIGQUIT, SIG_IGN);
407 switch (pid = fork()) {
408 case -1:
409 goto doneediting;
410 case 0:
411 execl(editor, editor, file, (char *)NULL);
412 _exit(127);
415 while (waitpid(pid, &st, 0) == -1)
416 if (errno != EINTR)
417 break;
419 doneediting:
420 (void)signal(SIGHUP, sighup);
421 (void)signal(SIGINT, sigint);
422 (void)signal(SIGQUIT, sigquit);
424 if (!WIFEXITED(st)) {
425 errno = EINTR;
426 return -1;
429 return WEXITSTATUS(st);
432 static const struct got_error *
433 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
434 const char *initial_content, size_t initial_content_len,
435 int require_modification)
437 const struct got_error *err = NULL;
438 char *line = NULL;
439 size_t linesize = 0;
440 ssize_t linelen;
441 struct stat st, st2;
442 FILE *fp = NULL;
443 size_t len, logmsg_len;
444 char *initial_content_stripped = NULL, *buf = NULL, *s;
446 *logmsg = NULL;
448 if (stat(logmsg_path, &st) == -1)
449 return got_error_from_errno2("stat", logmsg_path);
451 if (spawn_editor(editor, logmsg_path) == -1)
452 return got_error_from_errno("failed spawning editor");
454 if (stat(logmsg_path, &st2) == -1)
455 return got_error_from_errno("stat");
457 if (require_modification &&
458 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
459 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
460 "no changes made to commit message, aborting");
462 /*
463 * Set up a stripped version of the initial content without comments
464 * and blank lines. We need this in order to check if the message
465 * has in fact been edited.
466 */
467 initial_content_stripped = malloc(initial_content_len + 1);
468 if (initial_content_stripped == NULL)
469 return got_error_from_errno("malloc");
470 initial_content_stripped[0] = '\0';
472 buf = strdup(initial_content);
473 if (buf == NULL) {
474 err = got_error_from_errno("strdup");
475 goto done;
477 s = buf;
478 len = 0;
479 while ((line = strsep(&s, "\n")) != NULL) {
480 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
481 continue; /* remove comments and leading empty lines */
482 len = strlcat(initial_content_stripped, line,
483 initial_content_len + 1);
484 if (len >= initial_content_len + 1) {
485 err = got_error(GOT_ERR_NO_SPACE);
486 goto done;
489 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
490 initial_content_stripped[len - 1] = '\0';
491 len--;
494 logmsg_len = st2.st_size;
495 *logmsg = malloc(logmsg_len + 1);
496 if (*logmsg == NULL)
497 return got_error_from_errno("malloc");
498 (*logmsg)[0] = '\0';
500 fp = fopen(logmsg_path, "r");
501 if (fp == NULL) {
502 err = got_error_from_errno("fopen");
503 goto done;
506 len = 0;
507 while ((linelen = getline(&line, &linesize, fp)) != -1) {
508 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
509 continue; /* remove comments and leading empty lines */
510 len = strlcat(*logmsg, line, logmsg_len + 1);
511 if (len >= logmsg_len + 1) {
512 err = got_error(GOT_ERR_NO_SPACE);
513 goto done;
516 free(line);
517 if (ferror(fp)) {
518 err = got_ferror(fp, GOT_ERR_IO);
519 goto done;
521 while (len > 0 && (*logmsg)[len - 1] == '\n') {
522 (*logmsg)[len - 1] = '\0';
523 len--;
526 if (len == 0) {
527 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
528 "commit message cannot be empty, aborting");
529 goto done;
531 if (require_modification &&
532 strcmp(*logmsg, initial_content_stripped) == 0)
533 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
534 "no changes made to commit message, aborting");
535 done:
536 free(initial_content_stripped);
537 free(buf);
538 if (fp && fclose(fp) == EOF && err == NULL)
539 err = got_error_from_errno("fclose");
540 if (err) {
541 free(*logmsg);
542 *logmsg = NULL;
544 return err;
547 static const struct got_error *
548 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
549 const char *path_dir, const char *branch_name)
551 char *initial_content = NULL;
552 const struct got_error *err = NULL;
553 int initial_content_len;
554 int fd = -1;
556 initial_content_len = asprintf(&initial_content,
557 "\n# %s to be imported to branch %s\n", path_dir,
558 branch_name);
559 if (initial_content_len == -1)
560 return got_error_from_errno("asprintf");
562 err = got_opentemp_named_fd(logmsg_path, &fd,
563 GOT_TMPDIR_STR "/got-importmsg");
564 if (err)
565 goto done;
567 if (write(fd, initial_content, initial_content_len) == -1) {
568 err = got_error_from_errno2("write", *logmsg_path);
569 goto done;
572 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
573 initial_content_len, 1);
574 done:
575 if (fd != -1 && close(fd) == -1 && err == NULL)
576 err = got_error_from_errno2("close", *logmsg_path);
577 free(initial_content);
578 if (err) {
579 free(*logmsg_path);
580 *logmsg_path = NULL;
582 return err;
585 static const struct got_error *
586 import_progress(void *arg, const char *path)
588 printf("A %s\n", path);
589 return NULL;
592 static const struct got_error *
593 get_author(char **author, struct got_repository *repo,
594 struct got_worktree *worktree)
596 const struct got_error *err = NULL;
597 const char *got_author = NULL, *name, *email;
598 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
600 *author = NULL;
602 if (worktree)
603 worktree_conf = got_worktree_get_gotconfig(worktree);
604 repo_conf = got_repo_get_gotconfig(repo);
606 /*
607 * Priority of potential author information sources, from most
608 * significant to least significant:
609 * 1) work tree's .got/got.conf file
610 * 2) repository's got.conf file
611 * 3) repository's git config file
612 * 4) environment variables
613 * 5) global git config files (in user's home directory or /etc)
614 */
616 if (worktree_conf)
617 got_author = got_gotconfig_get_author(worktree_conf);
618 if (got_author == NULL)
619 got_author = got_gotconfig_get_author(repo_conf);
620 if (got_author == NULL) {
621 name = got_repo_get_gitconfig_author_name(repo);
622 email = got_repo_get_gitconfig_author_email(repo);
623 if (name && email) {
624 if (asprintf(author, "%s <%s>", name, email) == -1)
625 return got_error_from_errno("asprintf");
626 return NULL;
629 got_author = getenv("GOT_AUTHOR");
630 if (got_author == NULL) {
631 name = got_repo_get_global_gitconfig_author_name(repo);
632 email = got_repo_get_global_gitconfig_author_email(
633 repo);
634 if (name && email) {
635 if (asprintf(author, "%s <%s>", name, email)
636 == -1)
637 return got_error_from_errno("asprintf");
638 return NULL;
640 /* TODO: Look up user in password database? */
641 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
645 *author = strdup(got_author);
646 if (*author == NULL)
647 return got_error_from_errno("strdup");
649 /*
650 * Really dumb email address check; we're only doing this to
651 * avoid git's object parser breaking on commits we create.
652 */
653 while (*got_author && *got_author != '<')
654 got_author++;
655 if (*got_author != '<') {
656 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
657 goto done;
659 while (*got_author && *got_author != '@')
660 got_author++;
661 if (*got_author != '@') {
662 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
663 goto done;
665 while (*got_author && *got_author != '>')
666 got_author++;
667 if (*got_author != '>')
668 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
669 done:
670 if (err) {
671 free(*author);
672 *author = NULL;
674 return err;
677 static const struct got_error *
678 get_gitconfig_path(char **gitconfig_path)
680 const char *homedir = getenv("HOME");
682 *gitconfig_path = NULL;
683 if (homedir) {
684 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
685 return got_error_from_errno("asprintf");
688 return NULL;
691 static const struct got_error *
692 cmd_import(int argc, char *argv[])
694 const struct got_error *error = NULL;
695 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
696 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
697 const char *branch_name = "main";
698 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
699 struct got_repository *repo = NULL;
700 struct got_reference *branch_ref = NULL, *head_ref = NULL;
701 struct got_object_id *new_commit_id = NULL;
702 int ch;
703 struct got_pathlist_head ignores;
704 struct got_pathlist_entry *pe;
705 int preserve_logmsg = 0;
707 TAILQ_INIT(&ignores);
709 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
710 switch (ch) {
711 case 'b':
712 branch_name = optarg;
713 break;
714 case 'm':
715 logmsg = strdup(optarg);
716 if (logmsg == NULL) {
717 error = got_error_from_errno("strdup");
718 goto done;
720 break;
721 case 'r':
722 repo_path = realpath(optarg, NULL);
723 if (repo_path == NULL) {
724 error = got_error_from_errno2("realpath",
725 optarg);
726 goto done;
728 break;
729 case 'I':
730 if (optarg[0] == '\0')
731 break;
732 error = got_pathlist_insert(&pe, &ignores, optarg,
733 NULL);
734 if (error)
735 goto done;
736 break;
737 default:
738 usage_import();
739 /* NOTREACHED */
743 argc -= optind;
744 argv += optind;
746 #ifndef PROFILE
747 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
748 "unveil",
749 NULL) == -1)
750 err(1, "pledge");
751 #endif
752 if (argc != 1)
753 usage_import();
755 if (repo_path == NULL) {
756 repo_path = getcwd(NULL, 0);
757 if (repo_path == NULL)
758 return got_error_from_errno("getcwd");
760 got_path_strip_trailing_slashes(repo_path);
761 error = get_gitconfig_path(&gitconfig_path);
762 if (error)
763 goto done;
764 error = got_repo_open(&repo, repo_path, gitconfig_path);
765 if (error)
766 goto done;
768 error = get_author(&author, repo, NULL);
769 if (error)
770 return error;
772 /*
773 * Don't let the user create a branch name with a leading '-'.
774 * While technically a valid reference name, this case is usually
775 * an unintended typo.
776 */
777 if (branch_name[0] == '-')
778 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
780 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
781 error = got_error_from_errno("asprintf");
782 goto done;
785 error = got_ref_open(&branch_ref, repo, refname, 0);
786 if (error) {
787 if (error->code != GOT_ERR_NOT_REF)
788 goto done;
789 } else {
790 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
791 "import target branch already exists");
792 goto done;
795 path_dir = realpath(argv[0], NULL);
796 if (path_dir == NULL) {
797 error = got_error_from_errno2("realpath", argv[0]);
798 goto done;
800 got_path_strip_trailing_slashes(path_dir);
802 /*
803 * unveil(2) traverses exec(2); if an editor is used we have
804 * to apply unveil after the log message has been written.
805 */
806 if (logmsg == NULL || strlen(logmsg) == 0) {
807 error = get_editor(&editor);
808 if (error)
809 goto done;
810 free(logmsg);
811 error = collect_import_msg(&logmsg, &logmsg_path, editor,
812 path_dir, refname);
813 if (error) {
814 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
815 logmsg_path != NULL)
816 preserve_logmsg = 1;
817 goto done;
821 if (unveil(path_dir, "r") != 0) {
822 error = got_error_from_errno2("unveil", path_dir);
823 if (logmsg_path)
824 preserve_logmsg = 1;
825 goto done;
828 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
829 if (error) {
830 if (logmsg_path)
831 preserve_logmsg = 1;
832 goto done;
835 error = got_repo_import(&new_commit_id, path_dir, logmsg,
836 author, &ignores, repo, import_progress, NULL);
837 if (error) {
838 if (logmsg_path)
839 preserve_logmsg = 1;
840 goto done;
843 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
844 if (error) {
845 if (logmsg_path)
846 preserve_logmsg = 1;
847 goto done;
850 error = got_ref_write(branch_ref, repo);
851 if (error) {
852 if (logmsg_path)
853 preserve_logmsg = 1;
854 goto done;
857 error = got_object_id_str(&id_str, new_commit_id);
858 if (error) {
859 if (logmsg_path)
860 preserve_logmsg = 1;
861 goto done;
864 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
865 if (error) {
866 if (error->code != GOT_ERR_NOT_REF) {
867 if (logmsg_path)
868 preserve_logmsg = 1;
869 goto done;
872 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
873 branch_ref);
874 if (error) {
875 if (logmsg_path)
876 preserve_logmsg = 1;
877 goto done;
880 error = got_ref_write(head_ref, repo);
881 if (error) {
882 if (logmsg_path)
883 preserve_logmsg = 1;
884 goto done;
888 printf("Created branch %s with commit %s\n",
889 got_ref_get_name(branch_ref), id_str);
890 done:
891 if (preserve_logmsg) {
892 fprintf(stderr, "%s: log message preserved in %s\n",
893 getprogname(), logmsg_path);
894 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
895 error = got_error_from_errno2("unlink", logmsg_path);
896 free(logmsg);
897 free(logmsg_path);
898 free(repo_path);
899 free(editor);
900 free(refname);
901 free(new_commit_id);
902 free(id_str);
903 free(author);
904 free(gitconfig_path);
905 if (branch_ref)
906 got_ref_close(branch_ref);
907 if (head_ref)
908 got_ref_close(head_ref);
909 return error;
912 __dead static void
913 usage_clone(void)
915 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
916 "[-R reference] repository-url [directory]\n", getprogname());
917 exit(1);
920 struct got_fetch_progress_arg {
921 char last_scaled_size[FMT_SCALED_STRSIZE];
922 int last_p_indexed;
923 int last_p_resolved;
924 int verbosity;
926 struct got_repository *repo;
928 int create_configs;
929 int configs_created;
930 struct {
931 struct got_pathlist_head *symrefs;
932 struct got_pathlist_head *wanted_branches;
933 struct got_pathlist_head *wanted_refs;
934 const char *proto;
935 const char *host;
936 const char *port;
937 const char *remote_repo_path;
938 const char *git_url;
939 int fetch_all_branches;
940 int mirror_references;
941 } config_info;
942 };
944 /* XXX forward declaration */
945 static const struct got_error *
946 create_config_files(const char *proto, const char *host, const char *port,
947 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
948 int mirror_references, struct got_pathlist_head *symrefs,
949 struct got_pathlist_head *wanted_branches,
950 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
952 static const struct got_error *
953 fetch_progress(void *arg, const char *message, off_t packfile_size,
954 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
956 const struct got_error *err = NULL;
957 struct got_fetch_progress_arg *a = arg;
958 char scaled_size[FMT_SCALED_STRSIZE];
959 int p_indexed, p_resolved;
960 int print_size = 0, print_indexed = 0, print_resolved = 0;
962 /*
963 * In order to allow a failed clone to be resumed with 'got fetch'
964 * we try to create configuration files as soon as possible.
965 * Once the server has sent information about its default branch
966 * we have all required information.
967 */
968 if (a->create_configs && !a->configs_created &&
969 !TAILQ_EMPTY(a->config_info.symrefs)) {
970 err = create_config_files(a->config_info.proto,
971 a->config_info.host, a->config_info.port,
972 a->config_info.remote_repo_path,
973 a->config_info.git_url,
974 a->config_info.fetch_all_branches,
975 a->config_info.mirror_references,
976 a->config_info.symrefs,
977 a->config_info.wanted_branches,
978 a->config_info.wanted_refs, a->repo);
979 if (err)
980 return err;
981 a->configs_created = 1;
984 if (a->verbosity < 0)
985 return NULL;
987 if (message && message[0] != '\0') {
988 printf("\rserver: %s", message);
989 fflush(stdout);
990 return NULL;
993 if (packfile_size > 0 || nobj_indexed > 0) {
994 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
995 (a->last_scaled_size[0] == '\0' ||
996 strcmp(scaled_size, a->last_scaled_size)) != 0) {
997 print_size = 1;
998 if (strlcpy(a->last_scaled_size, scaled_size,
999 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1000 return got_error(GOT_ERR_NO_SPACE);
1002 if (nobj_indexed > 0) {
1003 p_indexed = (nobj_indexed * 100) / nobj_total;
1004 if (p_indexed != a->last_p_indexed) {
1005 a->last_p_indexed = p_indexed;
1006 print_indexed = 1;
1007 print_size = 1;
1010 if (nobj_resolved > 0) {
1011 p_resolved = (nobj_resolved * 100) /
1012 (nobj_total - nobj_loose);
1013 if (p_resolved != a->last_p_resolved) {
1014 a->last_p_resolved = p_resolved;
1015 print_resolved = 1;
1016 print_indexed = 1;
1017 print_size = 1;
1022 if (print_size || print_indexed || print_resolved)
1023 printf("\r");
1024 if (print_size)
1025 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1026 if (print_indexed)
1027 printf("; indexing %d%%", p_indexed);
1028 if (print_resolved)
1029 printf("; resolving deltas %d%%", p_resolved);
1030 if (print_size || print_indexed || print_resolved)
1031 fflush(stdout);
1033 return NULL;
1036 static const struct got_error *
1037 create_symref(const char *refname, struct got_reference *target_ref,
1038 int verbosity, struct got_repository *repo)
1040 const struct got_error *err;
1041 struct got_reference *head_symref;
1043 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1044 if (err)
1045 return err;
1047 err = got_ref_write(head_symref, repo);
1048 if (err == NULL && verbosity > 0) {
1049 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1050 got_ref_get_name(target_ref));
1052 got_ref_close(head_symref);
1053 return err;
1056 static const struct got_error *
1057 list_remote_refs(struct got_pathlist_head *symrefs,
1058 struct got_pathlist_head *refs)
1060 const struct got_error *err;
1061 struct got_pathlist_entry *pe;
1063 TAILQ_FOREACH(pe, symrefs, entry) {
1064 const char *refname = pe->path;
1065 const char *targetref = pe->data;
1067 printf("%s: %s\n", refname, targetref);
1070 TAILQ_FOREACH(pe, refs, entry) {
1071 const char *refname = pe->path;
1072 struct got_object_id *id = pe->data;
1073 char *id_str;
1075 err = got_object_id_str(&id_str, id);
1076 if (err)
1077 return err;
1078 printf("%s: %s\n", refname, id_str);
1079 free(id_str);
1082 return NULL;
1085 static const struct got_error *
1086 create_ref(const char *refname, struct got_object_id *id,
1087 int verbosity, struct got_repository *repo)
1089 const struct got_error *err = NULL;
1090 struct got_reference *ref;
1091 char *id_str;
1093 err = got_object_id_str(&id_str, id);
1094 if (err)
1095 return err;
1097 err = got_ref_alloc(&ref, refname, id);
1098 if (err)
1099 goto done;
1101 err = got_ref_write(ref, repo);
1102 got_ref_close(ref);
1104 if (err == NULL && verbosity >= 0)
1105 printf("Created reference %s: %s\n", refname, id_str);
1106 done:
1107 free(id_str);
1108 return err;
1111 static int
1112 match_wanted_ref(const char *refname, const char *wanted_ref)
1114 if (strncmp(refname, "refs/", 5) != 0)
1115 return 0;
1116 refname += 5;
1119 * Prevent fetching of references that won't make any
1120 * sense outside of the remote repository's context.
1122 if (strncmp(refname, "got/", 4) == 0)
1123 return 0;
1124 if (strncmp(refname, "remotes/", 8) == 0)
1125 return 0;
1127 if (strncmp(wanted_ref, "refs/", 5) == 0)
1128 wanted_ref += 5;
1130 /* Allow prefix match. */
1131 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1132 return 1;
1134 /* Allow exact match. */
1135 return (strcmp(refname, wanted_ref) == 0);
1138 static int
1139 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1141 struct got_pathlist_entry *pe;
1143 TAILQ_FOREACH(pe, wanted_refs, entry) {
1144 if (match_wanted_ref(refname, pe->path))
1145 return 1;
1148 return 0;
1151 static const struct got_error *
1152 create_wanted_ref(const char *refname, struct got_object_id *id,
1153 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1155 const struct got_error *err;
1156 char *remote_refname;
1158 if (strncmp("refs/", refname, 5) == 0)
1159 refname += 5;
1161 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1162 remote_repo_name, refname) == -1)
1163 return got_error_from_errno("asprintf");
1165 err = create_ref(remote_refname, id, verbosity, repo);
1166 free(remote_refname);
1167 return err;
1170 static const struct got_error *
1171 create_gotconfig(const char *proto, const char *host, const char *port,
1172 const char *remote_repo_path, const char *default_branch,
1173 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1174 struct got_pathlist_head *wanted_refs, int mirror_references,
1175 struct got_repository *repo)
1177 const struct got_error *err = NULL;
1178 char *gotconfig_path = NULL;
1179 char *gotconfig = NULL;
1180 FILE *gotconfig_file = NULL;
1181 const char *branchname = NULL;
1182 char *branches = NULL, *refs = NULL;
1183 ssize_t n;
1185 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1186 struct got_pathlist_entry *pe;
1187 TAILQ_FOREACH(pe, wanted_branches, entry) {
1188 char *s;
1189 branchname = pe->path;
1190 if (strncmp(branchname, "refs/heads/", 11) == 0)
1191 branchname += 11;
1192 if (asprintf(&s, "%s\"%s\" ",
1193 branches ? branches : "", branchname) == -1) {
1194 err = got_error_from_errno("asprintf");
1195 goto done;
1197 free(branches);
1198 branches = s;
1200 } else if (!fetch_all_branches && default_branch) {
1201 branchname = default_branch;
1202 if (strncmp(branchname, "refs/heads/", 11) == 0)
1203 branchname += 11;
1204 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1205 err = got_error_from_errno("asprintf");
1206 goto done;
1209 if (!TAILQ_EMPTY(wanted_refs)) {
1210 struct got_pathlist_entry *pe;
1211 TAILQ_FOREACH(pe, wanted_refs, entry) {
1212 char *s;
1213 const char *refname = pe->path;
1214 if (strncmp(refname, "refs/", 5) == 0)
1215 branchname += 5;
1216 if (asprintf(&s, "%s\"%s\" ",
1217 refs ? refs : "", refname) == -1) {
1218 err = got_error_from_errno("asprintf");
1219 goto done;
1221 free(refs);
1222 refs = s;
1226 /* Create got.conf(5). */
1227 gotconfig_path = got_repo_get_path_gotconfig(repo);
1228 if (gotconfig_path == NULL) {
1229 err = got_error_from_errno("got_repo_get_path_gotconfig");
1230 goto done;
1232 gotconfig_file = fopen(gotconfig_path, "a");
1233 if (gotconfig_file == NULL) {
1234 err = got_error_from_errno2("fopen", gotconfig_path);
1235 goto done;
1237 if (asprintf(&gotconfig,
1238 "remote \"%s\" {\n"
1239 "\tserver %s\n"
1240 "\tprotocol %s\n"
1241 "%s%s%s"
1242 "\trepository \"%s\"\n"
1243 "%s%s%s"
1244 "%s%s%s"
1245 "%s"
1246 "%s"
1247 "}\n",
1248 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1249 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1250 remote_repo_path, branches ? "\tbranch { " : "",
1251 branches ? branches : "", branches ? "}\n" : "",
1252 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1253 mirror_references ? "\tmirror-references yes\n" : "",
1254 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1255 err = got_error_from_errno("asprintf");
1256 goto done;
1258 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1259 if (n != strlen(gotconfig)) {
1260 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1261 goto done;
1264 done:
1265 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1266 err = got_error_from_errno2("fclose", gotconfig_path);
1267 free(gotconfig_path);
1268 free(branches);
1269 return err;
1272 static const struct got_error *
1273 create_gitconfig(const char *git_url, const char *default_branch,
1274 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1275 struct got_pathlist_head *wanted_refs, int mirror_references,
1276 struct got_repository *repo)
1278 const struct got_error *err = NULL;
1279 char *gitconfig_path = NULL;
1280 char *gitconfig = NULL;
1281 FILE *gitconfig_file = NULL;
1282 char *branches = NULL, *refs = NULL;
1283 const char *branchname;
1284 ssize_t n;
1286 /* Create a config file Git can understand. */
1287 gitconfig_path = got_repo_get_path_gitconfig(repo);
1288 if (gitconfig_path == NULL) {
1289 err = got_error_from_errno("got_repo_get_path_gitconfig");
1290 goto done;
1292 gitconfig_file = fopen(gitconfig_path, "a");
1293 if (gitconfig_file == NULL) {
1294 err = got_error_from_errno2("fopen", gitconfig_path);
1295 goto done;
1297 if (fetch_all_branches) {
1298 if (mirror_references) {
1299 if (asprintf(&branches,
1300 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1301 err = got_error_from_errno("asprintf");
1302 goto done;
1304 } else if (asprintf(&branches,
1305 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1306 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 } else if (!TAILQ_EMPTY(wanted_branches)) {
1311 struct got_pathlist_entry *pe;
1312 TAILQ_FOREACH(pe, wanted_branches, entry) {
1313 char *s;
1314 branchname = pe->path;
1315 if (strncmp(branchname, "refs/heads/", 11) == 0)
1316 branchname += 11;
1317 if (mirror_references) {
1318 if (asprintf(&s,
1319 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1320 branches ? branches : "",
1321 branchname, branchname) == -1) {
1322 err = got_error_from_errno("asprintf");
1323 goto done;
1325 } else if (asprintf(&s,
1326 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1327 branches ? branches : "",
1328 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1329 branchname) == -1) {
1330 err = got_error_from_errno("asprintf");
1331 goto done;
1333 free(branches);
1334 branches = s;
1336 } else {
1338 * If the server specified a default branch, use just that one.
1339 * Otherwise fall back to fetching all branches on next fetch.
1341 if (default_branch) {
1342 branchname = default_branch;
1343 if (strncmp(branchname, "refs/heads/", 11) == 0)
1344 branchname += 11;
1345 } else
1346 branchname = "*"; /* fall back to all branches */
1347 if (mirror_references) {
1348 if (asprintf(&branches,
1349 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1350 branchname, branchname) == -1) {
1351 err = got_error_from_errno("asprintf");
1352 goto done;
1354 } else if (asprintf(&branches,
1355 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1356 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1357 branchname) == -1) {
1358 err = got_error_from_errno("asprintf");
1359 goto done;
1362 if (!TAILQ_EMPTY(wanted_refs)) {
1363 struct got_pathlist_entry *pe;
1364 TAILQ_FOREACH(pe, wanted_refs, entry) {
1365 char *s;
1366 const char *refname = pe->path;
1367 if (strncmp(refname, "refs/", 5) == 0)
1368 refname += 5;
1369 if (mirror_references) {
1370 if (asprintf(&s,
1371 "%s\tfetch = refs/%s:refs/%s\n",
1372 refs ? refs : "", refname, refname) == -1) {
1373 err = got_error_from_errno("asprintf");
1374 goto done;
1376 } else if (asprintf(&s,
1377 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1378 refs ? refs : "",
1379 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1380 refname) == -1) {
1381 err = got_error_from_errno("asprintf");
1382 goto done;
1384 free(refs);
1385 refs = s;
1389 if (asprintf(&gitconfig,
1390 "[remote \"%s\"]\n"
1391 "\turl = %s\n"
1392 "%s"
1393 "%s"
1394 "\tfetch = refs/tags/*:refs/tags/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1396 refs ? refs : "") == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1401 if (n != strlen(gitconfig)) {
1402 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1403 goto done;
1405 done:
1406 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1407 err = got_error_from_errno2("fclose", gitconfig_path);
1408 free(gitconfig_path);
1409 free(branches);
1410 return err;
1413 static const struct got_error *
1414 create_config_files(const char *proto, const char *host, const char *port,
1415 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1416 int mirror_references, struct got_pathlist_head *symrefs,
1417 struct got_pathlist_head *wanted_branches,
1418 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1420 const struct got_error *err = NULL;
1421 const char *default_branch = NULL;
1422 struct got_pathlist_entry *pe;
1425 * If we asked for a set of wanted branches then use the first
1426 * one of those.
1428 if (!TAILQ_EMPTY(wanted_branches)) {
1429 pe = TAILQ_FIRST(wanted_branches);
1430 default_branch = pe->path;
1431 } else {
1432 /* First HEAD ref listed by server is the default branch. */
1433 TAILQ_FOREACH(pe, symrefs, entry) {
1434 const char *refname = pe->path;
1435 const char *target = pe->data;
1437 if (strcmp(refname, GOT_REF_HEAD) != 0)
1438 continue;
1440 default_branch = target;
1441 break;
1445 /* Create got.conf(5). */
1446 err = create_gotconfig(proto, host, port, remote_repo_path,
1447 default_branch, fetch_all_branches, wanted_branches,
1448 wanted_refs, mirror_references, repo);
1449 if (err)
1450 return err;
1452 /* Create a config file Git can understand. */
1453 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1454 wanted_branches, wanted_refs, mirror_references, repo);
1457 static const struct got_error *
1458 cmd_clone(int argc, char *argv[])
1460 const struct got_error *error = NULL;
1461 const char *uri, *dirname;
1462 char *proto, *host, *port, *repo_name, *server_path;
1463 char *default_destdir = NULL, *id_str = NULL;
1464 const char *repo_path;
1465 struct got_repository *repo = NULL;
1466 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1467 struct got_pathlist_entry *pe;
1468 struct got_object_id *pack_hash = NULL;
1469 int ch, fetchfd = -1, fetchstatus;
1470 pid_t fetchpid = -1;
1471 struct got_fetch_progress_arg fpa;
1472 char *git_url = NULL;
1473 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1474 int list_refs_only = 0;
1476 TAILQ_INIT(&refs);
1477 TAILQ_INIT(&symrefs);
1478 TAILQ_INIT(&wanted_branches);
1479 TAILQ_INIT(&wanted_refs);
1481 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1482 switch (ch) {
1483 case 'a':
1484 fetch_all_branches = 1;
1485 break;
1486 case 'b':
1487 error = got_pathlist_append(&wanted_branches,
1488 optarg, NULL);
1489 if (error)
1490 return error;
1491 break;
1492 case 'l':
1493 list_refs_only = 1;
1494 break;
1495 case 'm':
1496 mirror_references = 1;
1497 break;
1498 case 'v':
1499 if (verbosity < 0)
1500 verbosity = 0;
1501 else if (verbosity < 3)
1502 verbosity++;
1503 break;
1504 case 'q':
1505 verbosity = -1;
1506 break;
1507 case 'R':
1508 error = got_pathlist_append(&wanted_refs,
1509 optarg, NULL);
1510 if (error)
1511 return error;
1512 break;
1513 default:
1514 usage_clone();
1515 break;
1518 argc -= optind;
1519 argv += optind;
1521 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1522 option_conflict('a', 'b');
1523 if (list_refs_only) {
1524 if (!TAILQ_EMPTY(&wanted_branches))
1525 option_conflict('l', 'b');
1526 if (fetch_all_branches)
1527 option_conflict('l', 'a');
1528 if (mirror_references)
1529 option_conflict('l', 'm');
1530 if (!TAILQ_EMPTY(&wanted_refs))
1531 option_conflict('l', 'R');
1534 uri = argv[0];
1536 if (argc == 1)
1537 dirname = NULL;
1538 else if (argc == 2)
1539 dirname = argv[1];
1540 else
1541 usage_clone();
1543 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1544 &repo_name, uri);
1545 if (error)
1546 goto done;
1548 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1549 host, port ? ":" : "", port ? port : "",
1550 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1551 error = got_error_from_errno("asprintf");
1552 goto done;
1555 if (strcmp(proto, "git") == 0) {
1556 #ifndef PROFILE
1557 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1558 "sendfd dns inet unveil", NULL) == -1)
1559 err(1, "pledge");
1560 #endif
1561 } else if (strcmp(proto, "git+ssh") == 0 ||
1562 strcmp(proto, "ssh") == 0) {
1563 #ifndef PROFILE
1564 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1565 "sendfd unveil", NULL) == -1)
1566 err(1, "pledge");
1567 #endif
1568 } else if (strcmp(proto, "http") == 0 ||
1569 strcmp(proto, "git+http") == 0) {
1570 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1571 goto done;
1572 } else {
1573 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1574 goto done;
1576 if (dirname == NULL) {
1577 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1578 error = got_error_from_errno("asprintf");
1579 goto done;
1581 repo_path = default_destdir;
1582 } else
1583 repo_path = dirname;
1585 if (!list_refs_only) {
1586 error = got_path_mkdir(repo_path);
1587 if (error &&
1588 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1589 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1590 goto done;
1591 if (!got_path_dir_is_empty(repo_path)) {
1592 error = got_error_path(repo_path,
1593 GOT_ERR_DIR_NOT_EMPTY);
1594 goto done;
1598 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1599 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1600 error = got_error_from_errno2("unveil",
1601 GOT_FETCH_PATH_SSH);
1602 goto done;
1605 error = apply_unveil(repo_path, 0, NULL);
1606 if (error)
1607 goto done;
1609 if (verbosity >= 0)
1610 printf("Connecting to %s%s%s\n", host,
1611 port ? ":" : "", port ? port : "");
1613 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1614 server_path, verbosity);
1615 if (error)
1616 goto done;
1618 if (!list_refs_only) {
1619 error = got_repo_init(repo_path);
1620 if (error)
1621 goto done;
1622 error = got_repo_open(&repo, repo_path, NULL);
1623 if (error)
1624 goto done;
1627 fpa.last_scaled_size[0] = '\0';
1628 fpa.last_p_indexed = -1;
1629 fpa.last_p_resolved = -1;
1630 fpa.verbosity = verbosity;
1631 fpa.create_configs = 1;
1632 fpa.configs_created = 0;
1633 fpa.repo = repo;
1634 fpa.config_info.symrefs = &symrefs;
1635 fpa.config_info.wanted_branches = &wanted_branches;
1636 fpa.config_info.wanted_refs = &wanted_refs;
1637 fpa.config_info.proto = proto;
1638 fpa.config_info.host = host;
1639 fpa.config_info.port = port;
1640 fpa.config_info.remote_repo_path = server_path;
1641 fpa.config_info.git_url = git_url;
1642 fpa.config_info.fetch_all_branches = fetch_all_branches;
1643 fpa.config_info.mirror_references = mirror_references;
1644 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1645 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1646 fetch_all_branches, &wanted_branches, &wanted_refs,
1647 list_refs_only, verbosity, fetchfd, repo,
1648 fetch_progress, &fpa);
1649 if (error)
1650 goto done;
1652 if (list_refs_only) {
1653 error = list_remote_refs(&symrefs, &refs);
1654 goto done;
1657 error = got_object_id_str(&id_str, pack_hash);
1658 if (error)
1659 goto done;
1660 if (verbosity >= 0)
1661 printf("\nFetched %s.pack\n", id_str);
1662 free(id_str);
1664 /* Set up references provided with the pack file. */
1665 TAILQ_FOREACH(pe, &refs, entry) {
1666 const char *refname = pe->path;
1667 struct got_object_id *id = pe->data;
1668 char *remote_refname;
1670 if (is_wanted_ref(&wanted_refs, refname) &&
1671 !mirror_references) {
1672 error = create_wanted_ref(refname, id,
1673 GOT_FETCH_DEFAULT_REMOTE_NAME,
1674 verbosity - 1, repo);
1675 if (error)
1676 goto done;
1677 continue;
1680 error = create_ref(refname, id, verbosity - 1, repo);
1681 if (error)
1682 goto done;
1684 if (mirror_references)
1685 continue;
1687 if (strncmp("refs/heads/", refname, 11) != 0)
1688 continue;
1690 if (asprintf(&remote_refname,
1691 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1692 refname + 11) == -1) {
1693 error = got_error_from_errno("asprintf");
1694 goto done;
1696 error = create_ref(remote_refname, id, verbosity - 1, repo);
1697 free(remote_refname);
1698 if (error)
1699 goto done;
1702 /* Set the HEAD reference if the server provided one. */
1703 TAILQ_FOREACH(pe, &symrefs, entry) {
1704 struct got_reference *target_ref;
1705 const char *refname = pe->path;
1706 const char *target = pe->data;
1707 char *remote_refname = NULL, *remote_target = NULL;
1709 if (strcmp(refname, GOT_REF_HEAD) != 0)
1710 continue;
1712 error = got_ref_open(&target_ref, repo, target, 0);
1713 if (error) {
1714 if (error->code == GOT_ERR_NOT_REF) {
1715 error = NULL;
1716 continue;
1718 goto done;
1721 error = create_symref(refname, target_ref, verbosity, repo);
1722 got_ref_close(target_ref);
1723 if (error)
1724 goto done;
1726 if (mirror_references)
1727 continue;
1729 if (strncmp("refs/heads/", target, 11) != 0)
1730 continue;
1732 if (asprintf(&remote_refname,
1733 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1734 refname) == -1) {
1735 error = got_error_from_errno("asprintf");
1736 goto done;
1738 if (asprintf(&remote_target,
1739 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1740 target + 11) == -1) {
1741 error = got_error_from_errno("asprintf");
1742 free(remote_refname);
1743 goto done;
1745 error = got_ref_open(&target_ref, repo, remote_target, 0);
1746 if (error) {
1747 free(remote_refname);
1748 free(remote_target);
1749 if (error->code == GOT_ERR_NOT_REF) {
1750 error = NULL;
1751 continue;
1753 goto done;
1755 error = create_symref(remote_refname, target_ref,
1756 verbosity - 1, repo);
1757 free(remote_refname);
1758 free(remote_target);
1759 got_ref_close(target_ref);
1760 if (error)
1761 goto done;
1763 if (pe == NULL) {
1765 * We failed to set the HEAD reference. If we asked for
1766 * a set of wanted branches use the first of one of those
1767 * which could be fetched instead.
1769 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1770 const char *target = pe->path;
1771 struct got_reference *target_ref;
1773 error = got_ref_open(&target_ref, repo, target, 0);
1774 if (error) {
1775 if (error->code == GOT_ERR_NOT_REF) {
1776 error = NULL;
1777 continue;
1779 goto done;
1782 error = create_symref(GOT_REF_HEAD, target_ref,
1783 verbosity, repo);
1784 got_ref_close(target_ref);
1785 if (error)
1786 goto done;
1787 break;
1791 if (verbosity >= 0)
1792 printf("Created %s repository '%s'\n",
1793 mirror_references ? "mirrored" : "cloned", repo_path);
1794 done:
1795 if (fetchpid > 0) {
1796 if (kill(fetchpid, SIGTERM) == -1)
1797 error = got_error_from_errno("kill");
1798 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1799 error = got_error_from_errno("waitpid");
1801 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1802 error = got_error_from_errno("close");
1803 if (repo)
1804 got_repo_close(repo);
1805 TAILQ_FOREACH(pe, &refs, entry) {
1806 free((void *)pe->path);
1807 free(pe->data);
1809 got_pathlist_free(&refs);
1810 TAILQ_FOREACH(pe, &symrefs, entry) {
1811 free((void *)pe->path);
1812 free(pe->data);
1814 got_pathlist_free(&symrefs);
1815 got_pathlist_free(&wanted_branches);
1816 got_pathlist_free(&wanted_refs);
1817 free(pack_hash);
1818 free(proto);
1819 free(host);
1820 free(port);
1821 free(server_path);
1822 free(repo_name);
1823 free(default_destdir);
1824 free(git_url);
1825 return error;
1828 static const struct got_error *
1829 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1830 int replace_tags, int verbosity, struct got_repository *repo)
1832 const struct got_error *err = NULL;
1833 char *new_id_str = NULL;
1834 struct got_object_id *old_id = NULL;
1836 err = got_object_id_str(&new_id_str, new_id);
1837 if (err)
1838 goto done;
1840 if (!replace_tags &&
1841 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1842 err = got_ref_resolve(&old_id, repo, ref);
1843 if (err)
1844 goto done;
1845 if (got_object_id_cmp(old_id, new_id) == 0)
1846 goto done;
1847 if (verbosity >= 0) {
1848 printf("Rejecting update of existing tag %s: %s\n",
1849 got_ref_get_name(ref), new_id_str);
1851 goto done;
1854 if (got_ref_is_symbolic(ref)) {
1855 if (verbosity >= 0) {
1856 printf("Replacing reference %s: %s\n",
1857 got_ref_get_name(ref),
1858 got_ref_get_symref_target(ref));
1860 err = got_ref_change_symref_to_ref(ref, new_id);
1861 if (err)
1862 goto done;
1863 err = got_ref_write(ref, repo);
1864 if (err)
1865 goto done;
1866 } else {
1867 err = got_ref_resolve(&old_id, repo, ref);
1868 if (err)
1869 goto done;
1870 if (got_object_id_cmp(old_id, new_id) == 0)
1871 goto done;
1873 err = got_ref_change_ref(ref, new_id);
1874 if (err)
1875 goto done;
1876 err = got_ref_write(ref, repo);
1877 if (err)
1878 goto done;
1881 if (verbosity >= 0)
1882 printf("Updated %s: %s\n", got_ref_get_name(ref),
1883 new_id_str);
1884 done:
1885 free(old_id);
1886 free(new_id_str);
1887 return err;
1890 static const struct got_error *
1891 update_symref(const char *refname, struct got_reference *target_ref,
1892 int verbosity, struct got_repository *repo)
1894 const struct got_error *err = NULL, *unlock_err;
1895 struct got_reference *symref;
1896 int symref_is_locked = 0;
1898 err = got_ref_open(&symref, repo, refname, 1);
1899 if (err) {
1900 if (err->code != GOT_ERR_NOT_REF)
1901 return err;
1902 err = got_ref_alloc_symref(&symref, refname, target_ref);
1903 if (err)
1904 goto done;
1906 err = got_ref_write(symref, repo);
1907 if (err)
1908 goto done;
1910 if (verbosity >= 0)
1911 printf("Created reference %s: %s\n",
1912 got_ref_get_name(symref),
1913 got_ref_get_symref_target(symref));
1914 } else {
1915 symref_is_locked = 1;
1917 if (strcmp(got_ref_get_symref_target(symref),
1918 got_ref_get_name(target_ref)) == 0)
1919 goto done;
1921 err = got_ref_change_symref(symref,
1922 got_ref_get_name(target_ref));
1923 if (err)
1924 goto done;
1926 err = got_ref_write(symref, repo);
1927 if (err)
1928 goto done;
1930 if (verbosity >= 0)
1931 printf("Updated %s: %s\n", got_ref_get_name(symref),
1932 got_ref_get_symref_target(symref));
1935 done:
1936 if (symref_is_locked) {
1937 unlock_err = got_ref_unlock(symref);
1938 if (unlock_err && err == NULL)
1939 err = unlock_err;
1941 got_ref_close(symref);
1942 return err;
1945 __dead static void
1946 usage_fetch(void)
1948 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1949 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1950 "[remote-repository-name]\n",
1951 getprogname());
1952 exit(1);
1955 static const struct got_error *
1956 delete_missing_ref(struct got_reference *ref,
1957 int verbosity, struct got_repository *repo)
1959 const struct got_error *err = NULL;
1960 struct got_object_id *id = NULL;
1961 char *id_str = NULL;
1963 if (got_ref_is_symbolic(ref)) {
1964 err = got_ref_delete(ref, repo);
1965 if (err)
1966 return err;
1967 if (verbosity >= 0) {
1968 printf("Deleted reference %s: %s\n",
1969 got_ref_get_name(ref),
1970 got_ref_get_symref_target(ref));
1972 } else {
1973 err = got_ref_resolve(&id, repo, ref);
1974 if (err)
1975 return err;
1976 err = got_object_id_str(&id_str, id);
1977 if (err)
1978 goto done;
1980 err = got_ref_delete(ref, repo);
1981 if (err)
1982 goto done;
1983 if (verbosity >= 0) {
1984 printf("Deleted reference %s: %s\n",
1985 got_ref_get_name(ref), id_str);
1988 done:
1989 free(id);
1990 free(id_str);
1991 return NULL;
1994 static const struct got_error *
1995 delete_missing_refs(struct got_pathlist_head *their_refs,
1996 struct got_pathlist_head *their_symrefs,
1997 const struct got_remote_repo *remote,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reflist_head my_refs;
2002 struct got_reflist_entry *re;
2003 struct got_pathlist_entry *pe;
2004 char *remote_namespace = NULL;
2005 char *local_refname = NULL;
2007 TAILQ_INIT(&my_refs);
2009 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2010 == -1)
2011 return got_error_from_errno("asprintf");
2013 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2014 if (err)
2015 goto done;
2017 TAILQ_FOREACH(re, &my_refs, entry) {
2018 const char *refname = got_ref_get_name(re->ref);
2020 if (!remote->mirror_references) {
2021 if (strncmp(refname, remote_namespace,
2022 strlen(remote_namespace)) == 0) {
2023 if (strcmp(refname + strlen(remote_namespace),
2024 GOT_REF_HEAD) == 0)
2025 continue;
2026 if (asprintf(&local_refname, "refs/heads/%s",
2027 refname + strlen(remote_namespace)) == -1) {
2028 err = got_error_from_errno("asprintf");
2029 goto done;
2031 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2032 continue;
2035 TAILQ_FOREACH(pe, their_refs, entry) {
2036 if (strcmp(local_refname, pe->path) == 0)
2037 break;
2039 if (pe != NULL)
2040 continue;
2042 TAILQ_FOREACH(pe, their_symrefs, entry) {
2043 if (strcmp(local_refname, pe->path) == 0)
2044 break;
2046 if (pe != NULL)
2047 continue;
2049 err = delete_missing_ref(re->ref, verbosity, repo);
2050 if (err)
2051 break;
2053 if (local_refname) {
2054 struct got_reference *ref;
2055 err = got_ref_open(&ref, repo, local_refname, 1);
2056 if (err) {
2057 if (err->code != GOT_ERR_NOT_REF)
2058 break;
2059 free(local_refname);
2060 local_refname = NULL;
2061 continue;
2063 err = delete_missing_ref(ref, verbosity, repo);
2064 if (err)
2065 break;
2066 unlock_err = got_ref_unlock(ref);
2067 got_ref_close(ref);
2068 if (unlock_err && err == NULL) {
2069 err = unlock_err;
2070 break;
2073 free(local_refname);
2074 local_refname = NULL;
2077 done:
2078 free(remote_namespace);
2079 free(local_refname);
2080 return err;
2083 static const struct got_error *
2084 update_wanted_ref(const char *refname, struct got_object_id *id,
2085 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2087 const struct got_error *err, *unlock_err;
2088 char *remote_refname;
2089 struct got_reference *ref;
2091 if (strncmp("refs/", refname, 5) == 0)
2092 refname += 5;
2094 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2095 remote_repo_name, refname) == -1)
2096 return got_error_from_errno("asprintf");
2098 err = got_ref_open(&ref, repo, remote_refname, 1);
2099 if (err) {
2100 if (err->code != GOT_ERR_NOT_REF)
2101 goto done;
2102 err = create_ref(remote_refname, id, verbosity, repo);
2103 } else {
2104 err = update_ref(ref, id, 0, verbosity, repo);
2105 unlock_err = got_ref_unlock(ref);
2106 if (unlock_err && err == NULL)
2107 err = unlock_err;
2108 got_ref_close(ref);
2110 done:
2111 free(remote_refname);
2112 return err;
2115 static const struct got_error *
2116 cmd_fetch(int argc, char *argv[])
2118 const struct got_error *error = NULL, *unlock_err;
2119 char *cwd = NULL, *repo_path = NULL;
2120 const char *remote_name;
2121 char *proto = NULL, *host = NULL, *port = NULL;
2122 char *repo_name = NULL, *server_path = NULL;
2123 const struct got_remote_repo *remotes, *remote = NULL;
2124 int nremotes;
2125 char *id_str = NULL;
2126 struct got_repository *repo = NULL;
2127 struct got_worktree *worktree = NULL;
2128 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2129 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2130 struct got_pathlist_entry *pe;
2131 struct got_object_id *pack_hash = NULL;
2132 int i, ch, fetchfd = -1, fetchstatus;
2133 pid_t fetchpid = -1;
2134 struct got_fetch_progress_arg fpa;
2135 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2136 int delete_refs = 0, replace_tags = 0;
2138 TAILQ_INIT(&refs);
2139 TAILQ_INIT(&symrefs);
2140 TAILQ_INIT(&wanted_branches);
2141 TAILQ_INIT(&wanted_refs);
2143 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2144 switch (ch) {
2145 case 'a':
2146 fetch_all_branches = 1;
2147 break;
2148 case 'b':
2149 error = got_pathlist_append(&wanted_branches,
2150 optarg, NULL);
2151 if (error)
2152 return error;
2153 break;
2154 case 'd':
2155 delete_refs = 1;
2156 break;
2157 case 'l':
2158 list_refs_only = 1;
2159 break;
2160 case 'r':
2161 repo_path = realpath(optarg, NULL);
2162 if (repo_path == NULL)
2163 return got_error_from_errno2("realpath",
2164 optarg);
2165 got_path_strip_trailing_slashes(repo_path);
2166 break;
2167 case 't':
2168 replace_tags = 1;
2169 break;
2170 case 'v':
2171 if (verbosity < 0)
2172 verbosity = 0;
2173 else if (verbosity < 3)
2174 verbosity++;
2175 break;
2176 case 'q':
2177 verbosity = -1;
2178 break;
2179 case 'R':
2180 error = got_pathlist_append(&wanted_refs,
2181 optarg, NULL);
2182 if (error)
2183 return error;
2184 break;
2185 default:
2186 usage_fetch();
2187 break;
2190 argc -= optind;
2191 argv += optind;
2193 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2194 option_conflict('a', 'b');
2195 if (list_refs_only) {
2196 if (!TAILQ_EMPTY(&wanted_branches))
2197 option_conflict('l', 'b');
2198 if (fetch_all_branches)
2199 option_conflict('l', 'a');
2200 if (delete_refs)
2201 option_conflict('l', 'd');
2204 if (argc == 0)
2205 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2206 else if (argc == 1)
2207 remote_name = argv[0];
2208 else
2209 usage_fetch();
2211 cwd = getcwd(NULL, 0);
2212 if (cwd == NULL) {
2213 error = got_error_from_errno("getcwd");
2214 goto done;
2217 if (repo_path == NULL) {
2218 error = got_worktree_open(&worktree, cwd);
2219 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2220 goto done;
2221 else
2222 error = NULL;
2223 if (worktree) {
2224 repo_path =
2225 strdup(got_worktree_get_repo_path(worktree));
2226 if (repo_path == NULL)
2227 error = got_error_from_errno("strdup");
2228 if (error)
2229 goto done;
2230 } else {
2231 repo_path = strdup(cwd);
2232 if (repo_path == NULL) {
2233 error = got_error_from_errno("strdup");
2234 goto done;
2239 error = got_repo_open(&repo, repo_path, NULL);
2240 if (error)
2241 goto done;
2243 if (worktree) {
2244 worktree_conf = got_worktree_get_gotconfig(worktree);
2245 if (worktree_conf) {
2246 got_gotconfig_get_remotes(&nremotes, &remotes,
2247 worktree_conf);
2248 for (i = 0; i < nremotes; i++) {
2249 if (strcmp(remotes[i].name, remote_name) == 0) {
2250 remote = &remotes[i];
2251 break;
2256 if (remote == NULL) {
2257 repo_conf = got_repo_get_gotconfig(repo);
2258 if (repo_conf) {
2259 got_gotconfig_get_remotes(&nremotes, &remotes,
2260 repo_conf);
2261 for (i = 0; i < nremotes; i++) {
2262 if (strcmp(remotes[i].name, remote_name) == 0) {
2263 remote = &remotes[i];
2264 break;
2269 if (remote == NULL) {
2270 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2271 for (i = 0; i < nremotes; i++) {
2272 if (strcmp(remotes[i].name, remote_name) == 0) {
2273 remote = &remotes[i];
2274 break;
2278 if (remote == NULL) {
2279 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2280 goto done;
2283 if (TAILQ_EMPTY(&wanted_branches)) {
2284 if (!fetch_all_branches)
2285 fetch_all_branches = remote->fetch_all_branches;
2286 for (i = 0; i < remote->nbranches; i++) {
2287 got_pathlist_append(&wanted_branches,
2288 remote->branches[i], NULL);
2291 if (TAILQ_EMPTY(&wanted_refs)) {
2292 for (i = 0; i < remote->nrefs; i++) {
2293 got_pathlist_append(&wanted_refs,
2294 remote->refs[i], NULL);
2298 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2299 &repo_name, remote->url);
2300 if (error)
2301 goto done;
2303 if (strcmp(proto, "git") == 0) {
2304 #ifndef PROFILE
2305 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2306 "sendfd dns inet unveil", NULL) == -1)
2307 err(1, "pledge");
2308 #endif
2309 } else if (strcmp(proto, "git+ssh") == 0 ||
2310 strcmp(proto, "ssh") == 0) {
2311 #ifndef PROFILE
2312 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2313 "sendfd unveil", NULL) == -1)
2314 err(1, "pledge");
2315 #endif
2316 } else if (strcmp(proto, "http") == 0 ||
2317 strcmp(proto, "git+http") == 0) {
2318 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2319 goto done;
2320 } else {
2321 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2322 goto done;
2325 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2326 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2327 error = got_error_from_errno2("unveil",
2328 GOT_FETCH_PATH_SSH);
2329 goto done;
2332 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2333 if (error)
2334 goto done;
2336 if (verbosity >= 0)
2337 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2338 port ? ":" : "", port ? port : "");
2340 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2341 server_path, verbosity);
2342 if (error)
2343 goto done;
2345 fpa.last_scaled_size[0] = '\0';
2346 fpa.last_p_indexed = -1;
2347 fpa.last_p_resolved = -1;
2348 fpa.verbosity = verbosity;
2349 fpa.repo = repo;
2350 fpa.create_configs = 0;
2351 fpa.configs_created = 0;
2352 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2353 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2354 remote->mirror_references, fetch_all_branches, &wanted_branches,
2355 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2356 fetch_progress, &fpa);
2357 if (error)
2358 goto done;
2360 if (list_refs_only) {
2361 error = list_remote_refs(&symrefs, &refs);
2362 goto done;
2365 if (pack_hash == NULL) {
2366 if (verbosity >= 0)
2367 printf("Already up-to-date\n");
2368 } else if (verbosity >= 0) {
2369 error = got_object_id_str(&id_str, pack_hash);
2370 if (error)
2371 goto done;
2372 printf("\nFetched %s.pack\n", id_str);
2373 free(id_str);
2374 id_str = NULL;
2377 /* Update references provided with the pack file. */
2378 TAILQ_FOREACH(pe, &refs, entry) {
2379 const char *refname = pe->path;
2380 struct got_object_id *id = pe->data;
2381 struct got_reference *ref;
2382 char *remote_refname;
2384 if (is_wanted_ref(&wanted_refs, refname) &&
2385 !remote->mirror_references) {
2386 error = update_wanted_ref(refname, id,
2387 remote->name, verbosity, repo);
2388 if (error)
2389 goto done;
2390 continue;
2393 if (remote->mirror_references ||
2394 strncmp("refs/tags/", refname, 10) == 0) {
2395 error = got_ref_open(&ref, repo, refname, 1);
2396 if (error) {
2397 if (error->code != GOT_ERR_NOT_REF)
2398 goto done;
2399 error = create_ref(refname, id, verbosity,
2400 repo);
2401 if (error)
2402 goto done;
2403 } else {
2404 error = update_ref(ref, id, replace_tags,
2405 verbosity, repo);
2406 unlock_err = got_ref_unlock(ref);
2407 if (unlock_err && error == NULL)
2408 error = unlock_err;
2409 got_ref_close(ref);
2410 if (error)
2411 goto done;
2413 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2414 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2415 remote_name, refname + 11) == -1) {
2416 error = got_error_from_errno("asprintf");
2417 goto done;
2420 error = got_ref_open(&ref, repo, remote_refname, 1);
2421 if (error) {
2422 if (error->code != GOT_ERR_NOT_REF)
2423 goto done;
2424 error = create_ref(remote_refname, id,
2425 verbosity, repo);
2426 if (error)
2427 goto done;
2428 } else {
2429 error = update_ref(ref, id, replace_tags,
2430 verbosity, repo);
2431 unlock_err = got_ref_unlock(ref);
2432 if (unlock_err && error == NULL)
2433 error = unlock_err;
2434 got_ref_close(ref);
2435 if (error)
2436 goto done;
2439 /* Also create a local branch if none exists yet. */
2440 error = got_ref_open(&ref, repo, refname, 1);
2441 if (error) {
2442 if (error->code != GOT_ERR_NOT_REF)
2443 goto done;
2444 error = create_ref(refname, id, verbosity,
2445 repo);
2446 if (error)
2447 goto done;
2448 } else {
2449 unlock_err = got_ref_unlock(ref);
2450 if (unlock_err && error == NULL)
2451 error = unlock_err;
2452 got_ref_close(ref);
2456 if (delete_refs) {
2457 error = delete_missing_refs(&refs, &symrefs, remote,
2458 verbosity, repo);
2459 if (error)
2460 goto done;
2463 if (!remote->mirror_references) {
2464 /* Update remote HEAD reference if the server provided one. */
2465 TAILQ_FOREACH(pe, &symrefs, entry) {
2466 struct got_reference *target_ref;
2467 const char *refname = pe->path;
2468 const char *target = pe->data;
2469 char *remote_refname = NULL, *remote_target = NULL;
2471 if (strcmp(refname, GOT_REF_HEAD) != 0)
2472 continue;
2474 if (strncmp("refs/heads/", target, 11) != 0)
2475 continue;
2477 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2478 remote->name, refname) == -1) {
2479 error = got_error_from_errno("asprintf");
2480 goto done;
2482 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2483 remote->name, target + 11) == -1) {
2484 error = got_error_from_errno("asprintf");
2485 free(remote_refname);
2486 goto done;
2489 error = got_ref_open(&target_ref, repo, remote_target,
2490 0);
2491 if (error) {
2492 free(remote_refname);
2493 free(remote_target);
2494 if (error->code == GOT_ERR_NOT_REF) {
2495 error = NULL;
2496 continue;
2498 goto done;
2500 error = update_symref(remote_refname, target_ref,
2501 verbosity, repo);
2502 free(remote_refname);
2503 free(remote_target);
2504 got_ref_close(target_ref);
2505 if (error)
2506 goto done;
2509 done:
2510 if (fetchpid > 0) {
2511 if (kill(fetchpid, SIGTERM) == -1)
2512 error = got_error_from_errno("kill");
2513 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2514 error = got_error_from_errno("waitpid");
2516 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2517 error = got_error_from_errno("close");
2518 if (repo)
2519 got_repo_close(repo);
2520 if (worktree)
2521 got_worktree_close(worktree);
2522 TAILQ_FOREACH(pe, &refs, entry) {
2523 free((void *)pe->path);
2524 free(pe->data);
2526 got_pathlist_free(&refs);
2527 TAILQ_FOREACH(pe, &symrefs, entry) {
2528 free((void *)pe->path);
2529 free(pe->data);
2531 got_pathlist_free(&symrefs);
2532 got_pathlist_free(&wanted_branches);
2533 got_pathlist_free(&wanted_refs);
2534 free(id_str);
2535 free(cwd);
2536 free(repo_path);
2537 free(pack_hash);
2538 free(proto);
2539 free(host);
2540 free(port);
2541 free(server_path);
2542 free(repo_name);
2543 return error;
2547 __dead static void
2548 usage_checkout(void)
2550 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2551 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2552 exit(1);
2555 static void
2556 show_worktree_base_ref_warning(void)
2558 fprintf(stderr, "%s: warning: could not create a reference "
2559 "to the work tree's base commit; the commit could be "
2560 "garbage-collected by Git; making the repository "
2561 "writable and running 'got update' will prevent this\n",
2562 getprogname());
2565 struct got_checkout_progress_arg {
2566 const char *worktree_path;
2567 int had_base_commit_ref_error;
2570 static const struct got_error *
2571 checkout_progress(void *arg, unsigned char status, const char *path)
2573 struct got_checkout_progress_arg *a = arg;
2575 /* Base commit bump happens silently. */
2576 if (status == GOT_STATUS_BUMP_BASE)
2577 return NULL;
2579 if (status == GOT_STATUS_BASE_REF_ERR) {
2580 a->had_base_commit_ref_error = 1;
2581 return NULL;
2584 while (path[0] == '/')
2585 path++;
2587 printf("%c %s/%s\n", status, a->worktree_path, path);
2588 return NULL;
2591 static const struct got_error *
2592 check_cancelled(void *arg)
2594 if (sigint_received || sigpipe_received)
2595 return got_error(GOT_ERR_CANCELLED);
2596 return NULL;
2599 static const struct got_error *
2600 check_linear_ancestry(struct got_object_id *commit_id,
2601 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2602 struct got_repository *repo)
2604 const struct got_error *err = NULL;
2605 struct got_object_id *yca_id;
2607 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2608 commit_id, base_commit_id, repo, check_cancelled, NULL);
2609 if (err)
2610 return err;
2612 if (yca_id == NULL)
2613 return got_error(GOT_ERR_ANCESTRY);
2616 * Require a straight line of history between the target commit
2617 * and the work tree's base commit.
2619 * Non-linear situations such as this require a rebase:
2621 * (commit) D F (base_commit)
2622 * \ /
2623 * C E
2624 * \ /
2625 * B (yca)
2626 * |
2627 * A
2629 * 'got update' only handles linear cases:
2630 * Update forwards in time: A (base/yca) - B - C - D (commit)
2631 * Update backwards in time: D (base) - C - B - A (commit/yca)
2633 if (allow_forwards_in_time_only) {
2634 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2635 return got_error(GOT_ERR_ANCESTRY);
2636 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2637 got_object_id_cmp(base_commit_id, yca_id) != 0)
2638 return got_error(GOT_ERR_ANCESTRY);
2640 free(yca_id);
2641 return NULL;
2644 static const struct got_error *
2645 check_same_branch(struct got_object_id *commit_id,
2646 struct got_reference *head_ref, struct got_object_id *yca_id,
2647 struct got_repository *repo)
2649 const struct got_error *err = NULL;
2650 struct got_commit_graph *graph = NULL;
2651 struct got_object_id *head_commit_id = NULL;
2652 int is_same_branch = 0;
2654 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2655 if (err)
2656 goto done;
2658 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2659 is_same_branch = 1;
2660 goto done;
2662 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2663 is_same_branch = 1;
2664 goto done;
2667 err = got_commit_graph_open(&graph, "/", 1);
2668 if (err)
2669 goto done;
2671 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2672 check_cancelled, NULL);
2673 if (err)
2674 goto done;
2676 for (;;) {
2677 struct got_object_id *id;
2678 err = got_commit_graph_iter_next(&id, graph, repo,
2679 check_cancelled, NULL);
2680 if (err) {
2681 if (err->code == GOT_ERR_ITER_COMPLETED)
2682 err = NULL;
2683 break;
2686 if (id) {
2687 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2688 break;
2689 if (got_object_id_cmp(id, commit_id) == 0) {
2690 is_same_branch = 1;
2691 break;
2695 done:
2696 if (graph)
2697 got_commit_graph_close(graph);
2698 free(head_commit_id);
2699 if (!err && !is_same_branch)
2700 err = got_error(GOT_ERR_ANCESTRY);
2701 return err;
2704 static const struct got_error *
2705 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2707 static char msg[512];
2708 const char *branch_name;
2710 if (got_ref_is_symbolic(ref))
2711 branch_name = got_ref_get_symref_target(ref);
2712 else
2713 branch_name = got_ref_get_name(ref);
2715 if (strncmp("refs/heads/", branch_name, 11) == 0)
2716 branch_name += 11;
2718 snprintf(msg, sizeof(msg),
2719 "target commit is not contained in branch '%s'; "
2720 "the branch to use must be specified with -b; "
2721 "if necessary a new branch can be created for "
2722 "this commit with 'got branch -c %s BRANCH_NAME'",
2723 branch_name, commit_id_str);
2725 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2728 static const struct got_error *
2729 cmd_checkout(int argc, char *argv[])
2731 const struct got_error *error = NULL;
2732 struct got_repository *repo = NULL;
2733 struct got_reference *head_ref = NULL;
2734 struct got_worktree *worktree = NULL;
2735 char *repo_path = NULL;
2736 char *worktree_path = NULL;
2737 const char *path_prefix = "";
2738 const char *branch_name = GOT_REF_HEAD;
2739 char *commit_id_str = NULL;
2740 char *cwd = NULL;
2741 int ch, same_path_prefix, allow_nonempty = 0;
2742 struct got_pathlist_head paths;
2743 struct got_checkout_progress_arg cpa;
2745 TAILQ_INIT(&paths);
2747 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2748 switch (ch) {
2749 case 'b':
2750 branch_name = optarg;
2751 break;
2752 case 'c':
2753 commit_id_str = strdup(optarg);
2754 if (commit_id_str == NULL)
2755 return got_error_from_errno("strdup");
2756 break;
2757 case 'E':
2758 allow_nonempty = 1;
2759 break;
2760 case 'p':
2761 path_prefix = optarg;
2762 break;
2763 default:
2764 usage_checkout();
2765 /* NOTREACHED */
2769 argc -= optind;
2770 argv += optind;
2772 #ifndef PROFILE
2773 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2774 "unveil", NULL) == -1)
2775 err(1, "pledge");
2776 #endif
2777 if (argc == 1) {
2778 char *base, *dotgit;
2779 const char *path;
2780 repo_path = realpath(argv[0], NULL);
2781 if (repo_path == NULL)
2782 return got_error_from_errno2("realpath", argv[0]);
2783 cwd = getcwd(NULL, 0);
2784 if (cwd == NULL) {
2785 error = got_error_from_errno("getcwd");
2786 goto done;
2788 if (path_prefix[0])
2789 path = path_prefix;
2790 else
2791 path = repo_path;
2792 error = got_path_basename(&base, path);
2793 if (error)
2794 goto done;
2795 dotgit = strstr(base, ".git");
2796 if (dotgit)
2797 *dotgit = '\0';
2798 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2799 error = got_error_from_errno("asprintf");
2800 free(base);
2801 goto done;
2803 free(base);
2804 } else if (argc == 2) {
2805 repo_path = realpath(argv[0], NULL);
2806 if (repo_path == NULL) {
2807 error = got_error_from_errno2("realpath", argv[0]);
2808 goto done;
2810 worktree_path = realpath(argv[1], NULL);
2811 if (worktree_path == NULL) {
2812 if (errno != ENOENT) {
2813 error = got_error_from_errno2("realpath",
2814 argv[1]);
2815 goto done;
2817 worktree_path = strdup(argv[1]);
2818 if (worktree_path == NULL) {
2819 error = got_error_from_errno("strdup");
2820 goto done;
2823 } else
2824 usage_checkout();
2826 got_path_strip_trailing_slashes(repo_path);
2827 got_path_strip_trailing_slashes(worktree_path);
2829 error = got_repo_open(&repo, repo_path, NULL);
2830 if (error != NULL)
2831 goto done;
2833 /* Pre-create work tree path for unveil(2) */
2834 error = got_path_mkdir(worktree_path);
2835 if (error) {
2836 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2837 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2838 goto done;
2839 if (!allow_nonempty &&
2840 !got_path_dir_is_empty(worktree_path)) {
2841 error = got_error_path(worktree_path,
2842 GOT_ERR_DIR_NOT_EMPTY);
2843 goto done;
2847 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2848 if (error)
2849 goto done;
2851 error = got_ref_open(&head_ref, repo, branch_name, 0);
2852 if (error != NULL)
2853 goto done;
2855 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2856 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2857 goto done;
2859 error = got_worktree_open(&worktree, worktree_path);
2860 if (error != NULL)
2861 goto done;
2863 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2864 path_prefix);
2865 if (error != NULL)
2866 goto done;
2867 if (!same_path_prefix) {
2868 error = got_error(GOT_ERR_PATH_PREFIX);
2869 goto done;
2872 if (commit_id_str) {
2873 struct got_object_id *commit_id;
2874 struct got_reflist_head refs;
2875 TAILQ_INIT(&refs);
2876 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2877 NULL);
2878 if (error)
2879 goto done;
2880 error = got_repo_match_object_id(&commit_id, NULL,
2881 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2882 got_ref_list_free(&refs);
2883 if (error)
2884 goto done;
2885 error = check_linear_ancestry(commit_id,
2886 got_worktree_get_base_commit_id(worktree), 0, repo);
2887 if (error != NULL) {
2888 free(commit_id);
2889 if (error->code == GOT_ERR_ANCESTRY) {
2890 error = checkout_ancestry_error(
2891 head_ref, commit_id_str);
2893 goto done;
2895 error = check_same_branch(commit_id, head_ref, NULL, repo);
2896 if (error) {
2897 if (error->code == GOT_ERR_ANCESTRY) {
2898 error = checkout_ancestry_error(
2899 head_ref, commit_id_str);
2901 goto done;
2903 error = got_worktree_set_base_commit_id(worktree, repo,
2904 commit_id);
2905 free(commit_id);
2906 if (error)
2907 goto done;
2910 error = got_pathlist_append(&paths, "", NULL);
2911 if (error)
2912 goto done;
2913 cpa.worktree_path = worktree_path;
2914 cpa.had_base_commit_ref_error = 0;
2915 error = got_worktree_checkout_files(worktree, &paths, repo,
2916 checkout_progress, &cpa, check_cancelled, NULL);
2917 if (error != NULL)
2918 goto done;
2920 printf("Now shut up and hack\n");
2921 if (cpa.had_base_commit_ref_error)
2922 show_worktree_base_ref_warning();
2923 done:
2924 got_pathlist_free(&paths);
2925 free(commit_id_str);
2926 free(repo_path);
2927 free(worktree_path);
2928 free(cwd);
2929 return error;
2932 struct got_update_progress_arg {
2933 int did_something;
2934 int conflicts;
2935 int obstructed;
2936 int not_updated;
2939 void
2940 print_update_progress_stats(struct got_update_progress_arg *upa)
2942 if (!upa->did_something)
2943 return;
2945 if (upa->conflicts > 0)
2946 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2947 if (upa->obstructed > 0)
2948 printf("File paths obstructed by a non-regular file: %d\n",
2949 upa->obstructed);
2950 if (upa->not_updated > 0)
2951 printf("Files not updated because of existing merge "
2952 "conflicts: %d\n", upa->not_updated);
2955 __dead static void
2956 usage_update(void)
2958 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2959 getprogname());
2960 exit(1);
2963 static const struct got_error *
2964 update_progress(void *arg, unsigned char status, const char *path)
2966 struct got_update_progress_arg *upa = arg;
2968 if (status == GOT_STATUS_EXISTS ||
2969 status == GOT_STATUS_BASE_REF_ERR)
2970 return NULL;
2972 upa->did_something = 1;
2974 /* Base commit bump happens silently. */
2975 if (status == GOT_STATUS_BUMP_BASE)
2976 return NULL;
2978 if (status == GOT_STATUS_CONFLICT)
2979 upa->conflicts++;
2980 if (status == GOT_STATUS_OBSTRUCTED)
2981 upa->obstructed++;
2982 if (status == GOT_STATUS_CANNOT_UPDATE)
2983 upa->not_updated++;
2985 while (path[0] == '/')
2986 path++;
2987 printf("%c %s\n", status, path);
2988 return NULL;
2991 static const struct got_error *
2992 switch_head_ref(struct got_reference *head_ref,
2993 struct got_object_id *commit_id, struct got_worktree *worktree,
2994 struct got_repository *repo)
2996 const struct got_error *err = NULL;
2997 char *base_id_str;
2998 int ref_has_moved = 0;
3000 /* Trivial case: switching between two different references. */
3001 if (strcmp(got_ref_get_name(head_ref),
3002 got_worktree_get_head_ref_name(worktree)) != 0) {
3003 printf("Switching work tree from %s to %s\n",
3004 got_worktree_get_head_ref_name(worktree),
3005 got_ref_get_name(head_ref));
3006 return got_worktree_set_head_ref(worktree, head_ref);
3009 err = check_linear_ancestry(commit_id,
3010 got_worktree_get_base_commit_id(worktree), 0, repo);
3011 if (err) {
3012 if (err->code != GOT_ERR_ANCESTRY)
3013 return err;
3014 ref_has_moved = 1;
3016 if (!ref_has_moved)
3017 return NULL;
3019 /* Switching to a rebased branch with the same reference name. */
3020 err = got_object_id_str(&base_id_str,
3021 got_worktree_get_base_commit_id(worktree));
3022 if (err)
3023 return err;
3024 printf("Reference %s now points at a different branch\n",
3025 got_worktree_get_head_ref_name(worktree));
3026 printf("Switching work tree from %s to %s\n", base_id_str,
3027 got_worktree_get_head_ref_name(worktree));
3028 return NULL;
3031 static const struct got_error *
3032 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3034 const struct got_error *err;
3035 int in_progress;
3037 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3038 if (err)
3039 return err;
3040 if (in_progress)
3041 return got_error(GOT_ERR_REBASING);
3043 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3044 if (err)
3045 return err;
3046 if (in_progress)
3047 return got_error(GOT_ERR_HISTEDIT_BUSY);
3049 return NULL;
3052 static const struct got_error *
3053 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3054 char *argv[], struct got_worktree *worktree)
3056 const struct got_error *err = NULL;
3057 char *path;
3058 int i;
3060 if (argc == 0) {
3061 path = strdup("");
3062 if (path == NULL)
3063 return got_error_from_errno("strdup");
3064 return got_pathlist_append(paths, path, NULL);
3067 for (i = 0; i < argc; i++) {
3068 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3069 if (err)
3070 break;
3071 err = got_pathlist_append(paths, path, NULL);
3072 if (err) {
3073 free(path);
3074 break;
3078 return err;
3081 static const struct got_error *
3082 wrap_not_worktree_error(const struct got_error *orig_err,
3083 const char *cmdname, const char *path)
3085 const struct got_error *err;
3086 struct got_repository *repo;
3087 static char msg[512];
3089 err = got_repo_open(&repo, path, NULL);
3090 if (err)
3091 return orig_err;
3093 snprintf(msg, sizeof(msg),
3094 "'got %s' needs a work tree in addition to a git repository\n"
3095 "Work trees can be checked out from this Git repository with "
3096 "'got checkout'.\n"
3097 "The got(1) manual page contains more information.", cmdname);
3098 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3099 got_repo_close(repo);
3100 return err;
3103 static const struct got_error *
3104 cmd_update(int argc, char *argv[])
3106 const struct got_error *error = NULL;
3107 struct got_repository *repo = NULL;
3108 struct got_worktree *worktree = NULL;
3109 char *worktree_path = NULL;
3110 struct got_object_id *commit_id = NULL;
3111 char *commit_id_str = NULL;
3112 const char *branch_name = NULL;
3113 struct got_reference *head_ref = NULL;
3114 struct got_pathlist_head paths;
3115 struct got_pathlist_entry *pe;
3116 int ch;
3117 struct got_update_progress_arg upa;
3119 TAILQ_INIT(&paths);
3121 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3122 switch (ch) {
3123 case 'b':
3124 branch_name = optarg;
3125 break;
3126 case 'c':
3127 commit_id_str = strdup(optarg);
3128 if (commit_id_str == NULL)
3129 return got_error_from_errno("strdup");
3130 break;
3131 default:
3132 usage_update();
3133 /* NOTREACHED */
3137 argc -= optind;
3138 argv += optind;
3140 #ifndef PROFILE
3141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3142 "unveil", NULL) == -1)
3143 err(1, "pledge");
3144 #endif
3145 worktree_path = getcwd(NULL, 0);
3146 if (worktree_path == NULL) {
3147 error = got_error_from_errno("getcwd");
3148 goto done;
3150 error = got_worktree_open(&worktree, worktree_path);
3151 if (error) {
3152 if (error->code == GOT_ERR_NOT_WORKTREE)
3153 error = wrap_not_worktree_error(error, "update",
3154 worktree_path);
3155 goto done;
3158 error = check_rebase_or_histedit_in_progress(worktree);
3159 if (error)
3160 goto done;
3162 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3163 NULL);
3164 if (error != NULL)
3165 goto done;
3167 error = apply_unveil(got_repo_get_path(repo), 0,
3168 got_worktree_get_root_path(worktree));
3169 if (error)
3170 goto done;
3172 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3173 if (error)
3174 goto done;
3176 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3177 got_worktree_get_head_ref_name(worktree), 0);
3178 if (error != NULL)
3179 goto done;
3180 if (commit_id_str == NULL) {
3181 error = got_ref_resolve(&commit_id, repo, head_ref);
3182 if (error != NULL)
3183 goto done;
3184 error = got_object_id_str(&commit_id_str, commit_id);
3185 if (error != NULL)
3186 goto done;
3187 } else {
3188 struct got_reflist_head refs;
3189 TAILQ_INIT(&refs);
3190 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3191 NULL);
3192 if (error)
3193 goto done;
3194 error = got_repo_match_object_id(&commit_id, NULL,
3195 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3196 got_ref_list_free(&refs);
3197 free(commit_id_str);
3198 commit_id_str = NULL;
3199 if (error)
3200 goto done;
3201 error = got_object_id_str(&commit_id_str, commit_id);
3202 if (error)
3203 goto done;
3206 if (branch_name) {
3207 struct got_object_id *head_commit_id;
3208 TAILQ_FOREACH(pe, &paths, entry) {
3209 if (pe->path_len == 0)
3210 continue;
3211 error = got_error_msg(GOT_ERR_BAD_PATH,
3212 "switching between branches requires that "
3213 "the entire work tree gets updated");
3214 goto done;
3216 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3217 if (error)
3218 goto done;
3219 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3220 repo);
3221 free(head_commit_id);
3222 if (error != NULL)
3223 goto done;
3224 error = check_same_branch(commit_id, head_ref, NULL, repo);
3225 if (error)
3226 goto done;
3227 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3228 if (error)
3229 goto done;
3230 } else {
3231 error = check_linear_ancestry(commit_id,
3232 got_worktree_get_base_commit_id(worktree), 0, repo);
3233 if (error != NULL) {
3234 if (error->code == GOT_ERR_ANCESTRY)
3235 error = got_error(GOT_ERR_BRANCH_MOVED);
3236 goto done;
3238 error = check_same_branch(commit_id, head_ref, NULL, repo);
3239 if (error)
3240 goto done;
3243 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3244 commit_id) != 0) {
3245 error = got_worktree_set_base_commit_id(worktree, repo,
3246 commit_id);
3247 if (error)
3248 goto done;
3251 memset(&upa, 0, sizeof(upa));
3252 error = got_worktree_checkout_files(worktree, &paths, repo,
3253 update_progress, &upa, check_cancelled, NULL);
3254 if (error != NULL)
3255 goto done;
3257 if (upa.did_something)
3258 printf("Updated to commit %s\n", commit_id_str);
3259 else
3260 printf("Already up-to-date\n");
3261 print_update_progress_stats(&upa);
3262 done:
3263 free(worktree_path);
3264 TAILQ_FOREACH(pe, &paths, entry)
3265 free((char *)pe->path);
3266 got_pathlist_free(&paths);
3267 free(commit_id);
3268 free(commit_id_str);
3269 return error;
3272 static const struct got_error *
3273 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3274 const char *path, int diff_context, int ignore_whitespace,
3275 int force_text_diff, struct got_repository *repo)
3277 const struct got_error *err = NULL;
3278 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3280 if (blob_id1) {
3281 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3282 if (err)
3283 goto done;
3286 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3287 if (err)
3288 goto done;
3290 while (path[0] == '/')
3291 path++;
3292 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3293 diff_context, ignore_whitespace, force_text_diff, stdout);
3294 done:
3295 if (blob1)
3296 got_object_blob_close(blob1);
3297 got_object_blob_close(blob2);
3298 return err;
3301 static const struct got_error *
3302 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3303 const char *path, int diff_context, int ignore_whitespace,
3304 int force_text_diff, struct got_repository *repo)
3306 const struct got_error *err = NULL;
3307 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3308 struct got_diff_blob_output_unidiff_arg arg;
3310 if (tree_id1) {
3311 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3312 if (err)
3313 goto done;
3316 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3317 if (err)
3318 goto done;
3320 arg.diff_context = diff_context;
3321 arg.ignore_whitespace = ignore_whitespace;
3322 arg.force_text_diff = force_text_diff;
3323 arg.outfile = stdout;
3324 arg.line_offsets = NULL;
3325 arg.nlines = 0;
3326 while (path[0] == '/')
3327 path++;
3328 err = got_diff_tree(tree1, tree2, path, path, repo,
3329 got_diff_blob_output_unidiff, &arg, 1);
3330 done:
3331 if (tree1)
3332 got_object_tree_close(tree1);
3333 if (tree2)
3334 got_object_tree_close(tree2);
3335 return err;
3338 static const struct got_error *
3339 get_changed_paths(struct got_pathlist_head *paths,
3340 struct got_commit_object *commit, struct got_repository *repo)
3342 const struct got_error *err = NULL;
3343 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3344 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3345 struct got_object_qid *qid;
3347 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3348 if (qid != NULL) {
3349 struct got_commit_object *pcommit;
3350 err = got_object_open_as_commit(&pcommit, repo,
3351 qid->id);
3352 if (err)
3353 return err;
3355 tree_id1 = got_object_commit_get_tree_id(pcommit);
3356 got_object_commit_close(pcommit);
3360 if (tree_id1) {
3361 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3362 if (err)
3363 goto done;
3366 tree_id2 = got_object_commit_get_tree_id(commit);
3367 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3368 if (err)
3369 goto done;
3371 err = got_diff_tree(tree1, tree2, "", "", repo,
3372 got_diff_tree_collect_changed_paths, paths, 0);
3373 done:
3374 if (tree1)
3375 got_object_tree_close(tree1);
3376 if (tree2)
3377 got_object_tree_close(tree2);
3378 return err;
3381 static const struct got_error *
3382 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3383 const char *path, int diff_context, struct got_repository *repo)
3385 const struct got_error *err = NULL;
3386 struct got_commit_object *pcommit = NULL;
3387 char *id_str1 = NULL, *id_str2 = NULL;
3388 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3389 struct got_object_qid *qid;
3391 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3392 if (qid != NULL) {
3393 err = got_object_open_as_commit(&pcommit, repo,
3394 qid->id);
3395 if (err)
3396 return err;
3399 if (path && path[0] != '\0') {
3400 int obj_type;
3401 err = got_object_id_by_path(&obj_id2, repo, id, path);
3402 if (err)
3403 goto done;
3404 err = got_object_id_str(&id_str2, obj_id2);
3405 if (err) {
3406 free(obj_id2);
3407 goto done;
3409 if (pcommit) {
3410 err = got_object_id_by_path(&obj_id1, repo,
3411 qid->id, path);
3412 if (err) {
3413 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3414 free(obj_id2);
3415 goto done;
3417 } else {
3418 err = got_object_id_str(&id_str1, obj_id1);
3419 if (err) {
3420 free(obj_id2);
3421 goto done;
3425 err = got_object_get_type(&obj_type, repo, obj_id2);
3426 if (err) {
3427 free(obj_id2);
3428 goto done;
3430 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3431 switch (obj_type) {
3432 case GOT_OBJ_TYPE_BLOB:
3433 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3434 0, 0, repo);
3435 break;
3436 case GOT_OBJ_TYPE_TREE:
3437 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3438 0, 0, repo);
3439 break;
3440 default:
3441 err = got_error(GOT_ERR_OBJ_TYPE);
3442 break;
3444 free(obj_id1);
3445 free(obj_id2);
3446 } else {
3447 obj_id2 = got_object_commit_get_tree_id(commit);
3448 err = got_object_id_str(&id_str2, obj_id2);
3449 if (err)
3450 goto done;
3451 if (pcommit) {
3452 obj_id1 = got_object_commit_get_tree_id(pcommit);
3453 err = got_object_id_str(&id_str1, obj_id1);
3454 if (err)
3455 goto done;
3457 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3458 id_str2);
3459 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3460 repo);
3462 done:
3463 free(id_str1);
3464 free(id_str2);
3465 if (pcommit)
3466 got_object_commit_close(pcommit);
3467 return err;
3470 static char *
3471 get_datestr(time_t *time, char *datebuf)
3473 struct tm mytm, *tm;
3474 char *p, *s;
3476 tm = gmtime_r(time, &mytm);
3477 if (tm == NULL)
3478 return NULL;
3479 s = asctime_r(tm, datebuf);
3480 if (s == NULL)
3481 return NULL;
3482 p = strchr(s, '\n');
3483 if (p)
3484 *p = '\0';
3485 return s;
3488 static const struct got_error *
3489 match_logmsg(int *have_match, struct got_object_id *id,
3490 struct got_commit_object *commit, regex_t *regex)
3492 const struct got_error *err = NULL;
3493 regmatch_t regmatch;
3494 char *id_str = NULL, *logmsg = NULL;
3496 *have_match = 0;
3498 err = got_object_id_str(&id_str, id);
3499 if (err)
3500 return err;
3502 err = got_object_commit_get_logmsg(&logmsg, commit);
3503 if (err)
3504 goto done;
3506 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3507 *have_match = 1;
3508 done:
3509 free(id_str);
3510 free(logmsg);
3511 return err;
3514 static void
3515 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3516 regex_t *regex)
3518 regmatch_t regmatch;
3519 struct got_pathlist_entry *pe;
3521 *have_match = 0;
3523 TAILQ_FOREACH(pe, changed_paths, entry) {
3524 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3525 *have_match = 1;
3526 break;
3531 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3533 static const struct got_error*
3534 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3535 struct got_object_id *id, struct got_repository *repo)
3537 static const struct got_error *err = NULL;
3538 struct got_reflist_entry *re;
3539 char *s;
3540 const char *name;
3542 *refs_str = NULL;
3544 TAILQ_FOREACH(re, refs, entry) {
3545 struct got_tag_object *tag = NULL;
3546 struct got_object_id *ref_id;
3547 int cmp;
3549 name = got_ref_get_name(re->ref);
3550 if (strcmp(name, GOT_REF_HEAD) == 0)
3551 continue;
3552 if (strncmp(name, "refs/", 5) == 0)
3553 name += 5;
3554 if (strncmp(name, "got/", 4) == 0)
3555 continue;
3556 if (strncmp(name, "heads/", 6) == 0)
3557 name += 6;
3558 if (strncmp(name, "remotes/", 8) == 0) {
3559 name += 8;
3560 s = strstr(name, "/" GOT_REF_HEAD);
3561 if (s != NULL && s[strlen(s)] == '\0')
3562 continue;
3564 err = got_ref_resolve(&ref_id, repo, re->ref);
3565 if (err)
3566 break;
3567 if (strncmp(name, "tags/", 5) == 0) {
3568 err = got_object_open_as_tag(&tag, repo, ref_id);
3569 if (err) {
3570 if (err->code != GOT_ERR_OBJ_TYPE) {
3571 free(ref_id);
3572 break;
3574 /* Ref points at something other than a tag. */
3575 err = NULL;
3576 tag = NULL;
3579 cmp = got_object_id_cmp(tag ?
3580 got_object_tag_get_object_id(tag) : ref_id, id);
3581 free(ref_id);
3582 if (tag)
3583 got_object_tag_close(tag);
3584 if (cmp != 0)
3585 continue;
3586 s = *refs_str;
3587 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3588 s ? ", " : "", name) == -1) {
3589 err = got_error_from_errno("asprintf");
3590 free(s);
3591 *refs_str = NULL;
3592 break;
3594 free(s);
3597 return err;
3600 static const struct got_error *
3601 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3602 struct got_repository *repo, const char *path,
3603 struct got_pathlist_head *changed_paths, int show_patch,
3604 int diff_context, struct got_reflist_object_id_map *refs_idmap)
3606 const struct got_error *err = NULL;
3607 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3608 char datebuf[26];
3609 time_t committer_time;
3610 const char *author, *committer;
3611 char *refs_str = NULL;
3612 struct got_reflist_head *refs;
3614 err = got_object_id_str(&id_str, id);
3615 if (err)
3616 return err;
3618 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3619 if (refs) {
3620 err = build_refs_str(&refs_str, refs, id, repo);
3621 if (err)
3622 goto done;
3625 printf(GOT_COMMIT_SEP_STR);
3626 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3627 refs_str ? refs_str : "", refs_str ? ")" : "");
3628 free(id_str);
3629 id_str = NULL;
3630 free(refs_str);
3631 refs_str = NULL;
3632 printf("from: %s\n", got_object_commit_get_author(commit));
3633 committer_time = got_object_commit_get_committer_time(commit);
3634 datestr = get_datestr(&committer_time, datebuf);
3635 if (datestr)
3636 printf("date: %s UTC\n", datestr);
3637 author = got_object_commit_get_author(commit);
3638 committer = got_object_commit_get_committer(commit);
3639 if (strcmp(author, committer) != 0)
3640 printf("via: %s\n", committer);
3641 if (got_object_commit_get_nparents(commit) > 1) {
3642 const struct got_object_id_queue *parent_ids;
3643 struct got_object_qid *qid;
3644 int n = 1;
3645 parent_ids = got_object_commit_get_parent_ids(commit);
3646 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3647 err = got_object_id_str(&id_str, qid->id);
3648 if (err)
3649 goto done;
3650 printf("parent %d: %s\n", n++, id_str);
3651 free(id_str);
3652 id_str = NULL;
3656 err = got_object_commit_get_logmsg(&logmsg0, commit);
3657 if (err)
3658 goto done;
3660 logmsg = logmsg0;
3661 do {
3662 line = strsep(&logmsg, "\n");
3663 if (line)
3664 printf(" %s\n", line);
3665 } while (line);
3666 free(logmsg0);
3668 if (changed_paths) {
3669 struct got_pathlist_entry *pe;
3670 TAILQ_FOREACH(pe, changed_paths, entry) {
3671 struct got_diff_changed_path *cp = pe->data;
3672 printf(" %c %s\n", cp->status, pe->path);
3674 printf("\n");
3676 if (show_patch) {
3677 err = print_patch(commit, id, path, diff_context, repo);
3678 if (err == 0)
3679 printf("\n");
3682 if (fflush(stdout) != 0 && err == NULL)
3683 err = got_error_from_errno("fflush");
3684 done:
3685 free(id_str);
3686 free(refs_str);
3687 return err;
3690 static const struct got_error *
3691 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3692 struct got_repository *repo, const char *path, int show_changed_paths,
3693 int show_patch, const char *search_pattern, int diff_context, int limit,
3694 int log_branches, int reverse_display_order,
3695 struct got_reflist_object_id_map *refs_idmap)
3697 const struct got_error *err;
3698 struct got_commit_graph *graph;
3699 regex_t regex;
3700 int have_match;
3701 struct got_object_id_queue reversed_commits;
3702 struct got_object_qid *qid;
3703 struct got_commit_object *commit;
3704 struct got_pathlist_head changed_paths;
3705 struct got_pathlist_entry *pe;
3707 SIMPLEQ_INIT(&reversed_commits);
3708 TAILQ_INIT(&changed_paths);
3710 if (search_pattern && regcomp(&regex, search_pattern,
3711 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3712 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3714 err = got_commit_graph_open(&graph, path, !log_branches);
3715 if (err)
3716 return err;
3717 err = got_commit_graph_iter_start(graph, root_id, repo,
3718 check_cancelled, NULL);
3719 if (err)
3720 goto done;
3721 for (;;) {
3722 struct got_object_id *id;
3724 if (sigint_received || sigpipe_received)
3725 break;
3727 err = got_commit_graph_iter_next(&id, graph, repo,
3728 check_cancelled, NULL);
3729 if (err) {
3730 if (err->code == GOT_ERR_ITER_COMPLETED)
3731 err = NULL;
3732 break;
3734 if (id == NULL)
3735 break;
3737 err = got_object_open_as_commit(&commit, repo, id);
3738 if (err)
3739 break;
3741 if (show_changed_paths && !reverse_display_order) {
3742 err = get_changed_paths(&changed_paths, commit, repo);
3743 if (err)
3744 break;
3747 if (search_pattern) {
3748 err = match_logmsg(&have_match, id, commit, &regex);
3749 if (err) {
3750 got_object_commit_close(commit);
3751 break;
3753 if (have_match == 0 && show_changed_paths)
3754 match_changed_paths(&have_match,
3755 &changed_paths, &regex);
3756 if (have_match == 0) {
3757 got_object_commit_close(commit);
3758 TAILQ_FOREACH(pe, &changed_paths, entry) {
3759 free((char *)pe->path);
3760 free(pe->data);
3762 got_pathlist_free(&changed_paths);
3763 continue;
3767 if (reverse_display_order) {
3768 err = got_object_qid_alloc(&qid, id);
3769 if (err)
3770 break;
3771 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3772 got_object_commit_close(commit);
3773 } else {
3774 err = print_commit(commit, id, repo, path,
3775 show_changed_paths ? &changed_paths : NULL,
3776 show_patch, diff_context, refs_idmap);
3777 got_object_commit_close(commit);
3778 if (err)
3779 break;
3781 if ((limit && --limit == 0) ||
3782 (end_id && got_object_id_cmp(id, end_id) == 0))
3783 break;
3785 TAILQ_FOREACH(pe, &changed_paths, entry) {
3786 free((char *)pe->path);
3787 free(pe->data);
3789 got_pathlist_free(&changed_paths);
3791 if (reverse_display_order) {
3792 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3793 err = got_object_open_as_commit(&commit, repo, qid->id);
3794 if (err)
3795 break;
3796 if (show_changed_paths) {
3797 err = get_changed_paths(&changed_paths,
3798 commit, repo);
3799 if (err)
3800 break;
3802 err = print_commit(commit, qid->id, repo, path,
3803 show_changed_paths ? &changed_paths : NULL,
3804 show_patch, diff_context, refs_idmap);
3805 got_object_commit_close(commit);
3806 if (err)
3807 break;
3808 TAILQ_FOREACH(pe, &changed_paths, entry) {
3809 free((char *)pe->path);
3810 free(pe->data);
3812 got_pathlist_free(&changed_paths);
3815 done:
3816 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3817 qid = SIMPLEQ_FIRST(&reversed_commits);
3818 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3819 got_object_qid_free(qid);
3821 TAILQ_FOREACH(pe, &changed_paths, entry) {
3822 free((char *)pe->path);
3823 free(pe->data);
3825 got_pathlist_free(&changed_paths);
3826 if (search_pattern)
3827 regfree(&regex);
3828 got_commit_graph_close(graph);
3829 return err;
3832 __dead static void
3833 usage_log(void)
3835 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3836 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3837 "[-R] [path]\n", getprogname());
3838 exit(1);
3841 static int
3842 get_default_log_limit(void)
3844 const char *got_default_log_limit;
3845 long long n;
3846 const char *errstr;
3848 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3849 if (got_default_log_limit == NULL)
3850 return 0;
3851 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3852 if (errstr != NULL)
3853 return 0;
3854 return n;
3857 static const struct got_error *
3858 cmd_log(int argc, char *argv[])
3860 const struct got_error *error;
3861 struct got_repository *repo = NULL;
3862 struct got_worktree *worktree = NULL;
3863 struct got_object_id *start_id = NULL, *end_id = NULL;
3864 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3865 const char *start_commit = NULL, *end_commit = NULL;
3866 const char *search_pattern = NULL;
3867 int diff_context = -1, ch;
3868 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3869 int reverse_display_order = 0;
3870 const char *errstr;
3871 struct got_reflist_head refs;
3872 struct got_reflist_object_id_map *refs_idmap = NULL;
3874 TAILQ_INIT(&refs);
3876 #ifndef PROFILE
3877 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3878 NULL)
3879 == -1)
3880 err(1, "pledge");
3881 #endif
3883 limit = get_default_log_limit();
3885 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3886 switch (ch) {
3887 case 'p':
3888 show_patch = 1;
3889 break;
3890 case 'P':
3891 show_changed_paths = 1;
3892 break;
3893 case 'c':
3894 start_commit = optarg;
3895 break;
3896 case 'C':
3897 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3898 &errstr);
3899 if (errstr != NULL)
3900 err(1, "-C option %s", errstr);
3901 break;
3902 case 'l':
3903 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3904 if (errstr != NULL)
3905 err(1, "-l option %s", errstr);
3906 break;
3907 case 'b':
3908 log_branches = 1;
3909 break;
3910 case 'r':
3911 repo_path = realpath(optarg, NULL);
3912 if (repo_path == NULL)
3913 return got_error_from_errno2("realpath",
3914 optarg);
3915 got_path_strip_trailing_slashes(repo_path);
3916 break;
3917 case 'R':
3918 reverse_display_order = 1;
3919 break;
3920 case 's':
3921 search_pattern = optarg;
3922 break;
3923 case 'x':
3924 end_commit = optarg;
3925 break;
3926 default:
3927 usage_log();
3928 /* NOTREACHED */
3932 argc -= optind;
3933 argv += optind;
3935 if (diff_context == -1)
3936 diff_context = 3;
3937 else if (!show_patch)
3938 errx(1, "-C requires -p");
3940 cwd = getcwd(NULL, 0);
3941 if (cwd == NULL) {
3942 error = got_error_from_errno("getcwd");
3943 goto done;
3946 if (repo_path == NULL) {
3947 error = got_worktree_open(&worktree, cwd);
3948 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3949 goto done;
3950 error = NULL;
3953 if (argc == 1) {
3954 if (worktree) {
3955 error = got_worktree_resolve_path(&path, worktree,
3956 argv[0]);
3957 if (error)
3958 goto done;
3959 } else {
3960 path = strdup(argv[0]);
3961 if (path == NULL) {
3962 error = got_error_from_errno("strdup");
3963 goto done;
3966 } else if (argc != 0)
3967 usage_log();
3969 if (repo_path == NULL) {
3970 repo_path = worktree ?
3971 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3973 if (repo_path == NULL) {
3974 error = got_error_from_errno("strdup");
3975 goto done;
3978 error = got_repo_open(&repo, repo_path, NULL);
3979 if (error != NULL)
3980 goto done;
3982 error = apply_unveil(got_repo_get_path(repo), 1,
3983 worktree ? got_worktree_get_root_path(worktree) : NULL);
3984 if (error)
3985 goto done;
3987 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3988 if (error)
3989 goto done;
3991 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
3992 if (error)
3993 goto done;
3995 if (start_commit == NULL) {
3996 struct got_reference *head_ref;
3997 struct got_commit_object *commit = NULL;
3998 error = got_ref_open(&head_ref, repo,
3999 worktree ? got_worktree_get_head_ref_name(worktree)
4000 : GOT_REF_HEAD, 0);
4001 if (error != NULL)
4002 goto done;
4003 error = got_ref_resolve(&start_id, repo, head_ref);
4004 got_ref_close(head_ref);
4005 if (error != NULL)
4006 goto done;
4007 error = got_object_open_as_commit(&commit, repo,
4008 start_id);
4009 if (error != NULL)
4010 goto done;
4011 got_object_commit_close(commit);
4012 } else {
4013 error = got_repo_match_object_id(&start_id, NULL,
4014 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4015 if (error != NULL)
4016 goto done;
4018 if (end_commit != NULL) {
4019 error = got_repo_match_object_id(&end_id, NULL,
4020 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4021 if (error != NULL)
4022 goto done;
4025 if (worktree) {
4027 * If a path was specified on the command line it was resolved
4028 * to a path in the work tree above. Prepend the work tree's
4029 * path prefix to obtain the corresponding in-repository path.
4031 if (path) {
4032 const char *prefix;
4033 prefix = got_worktree_get_path_prefix(worktree);
4034 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4035 (path[0] != '\0') ? "/" : "", path) == -1) {
4036 error = got_error_from_errno("asprintf");
4037 goto done;
4040 } else
4041 error = got_repo_map_path(&in_repo_path, repo,
4042 path ? path : "");
4043 if (error != NULL)
4044 goto done;
4045 if (in_repo_path) {
4046 free(path);
4047 path = in_repo_path;
4050 error = print_commits(start_id, end_id, repo, path ? path : "",
4051 show_changed_paths, show_patch, search_pattern, diff_context,
4052 limit, log_branches, reverse_display_order, refs_idmap);
4053 done:
4054 free(path);
4055 free(repo_path);
4056 free(cwd);
4057 if (worktree)
4058 got_worktree_close(worktree);
4059 if (repo) {
4060 const struct got_error *repo_error;
4061 repo_error = got_repo_close(repo);
4062 if (error == NULL)
4063 error = repo_error;
4065 if (refs_idmap)
4066 got_reflist_object_id_map_free(refs_idmap);
4067 got_ref_list_free(&refs);
4068 return error;
4071 __dead static void
4072 usage_diff(void)
4074 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4075 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4076 exit(1);
4079 struct print_diff_arg {
4080 struct got_repository *repo;
4081 struct got_worktree *worktree;
4082 int diff_context;
4083 const char *id_str;
4084 int header_shown;
4085 int diff_staged;
4086 int ignore_whitespace;
4087 int force_text_diff;
4091 * Create a file which contains the target path of a symlink so we can feed
4092 * it as content to the diff engine.
4094 static const struct got_error *
4095 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4096 const char *abspath)
4098 const struct got_error *err = NULL;
4099 char target_path[PATH_MAX];
4100 ssize_t target_len, outlen;
4102 *fd = -1;
4104 if (dirfd != -1) {
4105 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4106 if (target_len == -1)
4107 return got_error_from_errno2("readlinkat", abspath);
4108 } else {
4109 target_len = readlink(abspath, target_path, PATH_MAX);
4110 if (target_len == -1)
4111 return got_error_from_errno2("readlink", abspath);
4114 *fd = got_opentempfd();
4115 if (*fd == -1)
4116 return got_error_from_errno("got_opentempfd");
4118 outlen = write(*fd, target_path, target_len);
4119 if (outlen == -1) {
4120 err = got_error_from_errno("got_opentempfd");
4121 goto done;
4124 if (lseek(*fd, 0, SEEK_SET) == -1) {
4125 err = got_error_from_errno2("lseek", abspath);
4126 goto done;
4128 done:
4129 if (err) {
4130 close(*fd);
4131 *fd = -1;
4133 return err;
4136 static const struct got_error *
4137 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4138 const char *path, struct got_object_id *blob_id,
4139 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4140 int dirfd, const char *de_name)
4142 struct print_diff_arg *a = arg;
4143 const struct got_error *err = NULL;
4144 struct got_blob_object *blob1 = NULL;
4145 int fd = -1;
4146 FILE *f2 = NULL;
4147 char *abspath = NULL, *label1 = NULL;
4148 struct stat sb;
4150 if (a->diff_staged) {
4151 if (staged_status != GOT_STATUS_MODIFY &&
4152 staged_status != GOT_STATUS_ADD &&
4153 staged_status != GOT_STATUS_DELETE)
4154 return NULL;
4155 } else {
4156 if (staged_status == GOT_STATUS_DELETE)
4157 return NULL;
4158 if (status == GOT_STATUS_NONEXISTENT)
4159 return got_error_set_errno(ENOENT, path);
4160 if (status != GOT_STATUS_MODIFY &&
4161 status != GOT_STATUS_ADD &&
4162 status != GOT_STATUS_DELETE &&
4163 status != GOT_STATUS_CONFLICT)
4164 return NULL;
4167 if (!a->header_shown) {
4168 printf("diff %s %s%s\n", a->id_str,
4169 got_worktree_get_root_path(a->worktree),
4170 a->diff_staged ? " (staged changes)" : "");
4171 a->header_shown = 1;
4174 if (a->diff_staged) {
4175 const char *label1 = NULL, *label2 = NULL;
4176 switch (staged_status) {
4177 case GOT_STATUS_MODIFY:
4178 label1 = path;
4179 label2 = path;
4180 break;
4181 case GOT_STATUS_ADD:
4182 label2 = path;
4183 break;
4184 case GOT_STATUS_DELETE:
4185 label1 = path;
4186 break;
4187 default:
4188 return got_error(GOT_ERR_FILE_STATUS);
4190 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4191 staged_blob_id, label1, label2, a->diff_context,
4192 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4195 if (staged_status == GOT_STATUS_ADD ||
4196 staged_status == GOT_STATUS_MODIFY) {
4197 char *id_str;
4198 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4199 8192);
4200 if (err)
4201 goto done;
4202 err = got_object_id_str(&id_str, staged_blob_id);
4203 if (err)
4204 goto done;
4205 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4206 err = got_error_from_errno("asprintf");
4207 free(id_str);
4208 goto done;
4210 free(id_str);
4211 } else if (status != GOT_STATUS_ADD) {
4212 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4213 if (err)
4214 goto done;
4217 if (status != GOT_STATUS_DELETE) {
4218 if (asprintf(&abspath, "%s/%s",
4219 got_worktree_get_root_path(a->worktree), path) == -1) {
4220 err = got_error_from_errno("asprintf");
4221 goto done;
4224 if (dirfd != -1) {
4225 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4226 if (fd == -1) {
4227 if (errno != ELOOP) {
4228 err = got_error_from_errno2("openat",
4229 abspath);
4230 goto done;
4232 err = get_symlink_target_file(&fd, dirfd,
4233 de_name, abspath);
4234 if (err)
4235 goto done;
4237 } else {
4238 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4239 if (fd == -1) {
4240 if (errno != ELOOP) {
4241 err = got_error_from_errno2("open",
4242 abspath);
4243 goto done;
4245 err = get_symlink_target_file(&fd, dirfd,
4246 de_name, abspath);
4247 if (err)
4248 goto done;
4251 if (fstat(fd, &sb) == -1) {
4252 err = got_error_from_errno2("fstat", abspath);
4253 goto done;
4255 f2 = fdopen(fd, "r");
4256 if (f2 == NULL) {
4257 err = got_error_from_errno2("fdopen", abspath);
4258 goto done;
4260 fd = -1;
4261 } else
4262 sb.st_size = 0;
4264 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4265 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4266 done:
4267 if (blob1)
4268 got_object_blob_close(blob1);
4269 if (f2 && fclose(f2) == EOF && err == NULL)
4270 err = got_error_from_errno("fclose");
4271 if (fd != -1 && close(fd) == -1 && err == NULL)
4272 err = got_error_from_errno("close");
4273 free(abspath);
4274 return err;
4277 static const struct got_error *
4278 cmd_diff(int argc, char *argv[])
4280 const struct got_error *error;
4281 struct got_repository *repo = NULL;
4282 struct got_worktree *worktree = NULL;
4283 char *cwd = NULL, *repo_path = NULL;
4284 struct got_object_id *id1 = NULL, *id2 = NULL;
4285 const char *id_str1 = NULL, *id_str2 = NULL;
4286 char *label1 = NULL, *label2 = NULL;
4287 int type1, type2;
4288 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4289 int force_text_diff = 0;
4290 const char *errstr;
4291 char *path = NULL;
4292 struct got_reflist_head refs;
4294 TAILQ_INIT(&refs);
4296 #ifndef PROFILE
4297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4298 NULL) == -1)
4299 err(1, "pledge");
4300 #endif
4302 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4303 switch (ch) {
4304 case 'a':
4305 force_text_diff = 1;
4306 break;
4307 case 'C':
4308 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4309 &errstr);
4310 if (errstr != NULL)
4311 err(1, "-C option %s", errstr);
4312 break;
4313 case 'r':
4314 repo_path = realpath(optarg, NULL);
4315 if (repo_path == NULL)
4316 return got_error_from_errno2("realpath",
4317 optarg);
4318 got_path_strip_trailing_slashes(repo_path);
4319 break;
4320 case 's':
4321 diff_staged = 1;
4322 break;
4323 case 'w':
4324 ignore_whitespace = 1;
4325 break;
4326 default:
4327 usage_diff();
4328 /* NOTREACHED */
4332 argc -= optind;
4333 argv += optind;
4335 cwd = getcwd(NULL, 0);
4336 if (cwd == NULL) {
4337 error = got_error_from_errno("getcwd");
4338 goto done;
4340 if (argc <= 1) {
4341 if (repo_path)
4342 errx(1,
4343 "-r option can't be used when diffing a work tree");
4344 error = got_worktree_open(&worktree, cwd);
4345 if (error) {
4346 if (error->code == GOT_ERR_NOT_WORKTREE)
4347 error = wrap_not_worktree_error(error, "diff",
4348 cwd);
4349 goto done;
4351 repo_path = strdup(got_worktree_get_repo_path(worktree));
4352 if (repo_path == NULL) {
4353 error = got_error_from_errno("strdup");
4354 goto done;
4356 if (argc == 1) {
4357 error = got_worktree_resolve_path(&path, worktree,
4358 argv[0]);
4359 if (error)
4360 goto done;
4361 } else {
4362 path = strdup("");
4363 if (path == NULL) {
4364 error = got_error_from_errno("strdup");
4365 goto done;
4368 } else if (argc == 2) {
4369 if (diff_staged)
4370 errx(1, "-s option can't be used when diffing "
4371 "objects in repository");
4372 id_str1 = argv[0];
4373 id_str2 = argv[1];
4374 if (repo_path == NULL) {
4375 error = got_worktree_open(&worktree, cwd);
4376 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4377 goto done;
4378 if (worktree) {
4379 repo_path = strdup(
4380 got_worktree_get_repo_path(worktree));
4381 if (repo_path == NULL) {
4382 error = got_error_from_errno("strdup");
4383 goto done;
4385 } else {
4386 repo_path = strdup(cwd);
4387 if (repo_path == NULL) {
4388 error = got_error_from_errno("strdup");
4389 goto done;
4393 } else
4394 usage_diff();
4396 error = got_repo_open(&repo, repo_path, NULL);
4397 free(repo_path);
4398 if (error != NULL)
4399 goto done;
4401 error = apply_unveil(got_repo_get_path(repo), 1,
4402 worktree ? got_worktree_get_root_path(worktree) : NULL);
4403 if (error)
4404 goto done;
4406 if (argc <= 1) {
4407 struct print_diff_arg arg;
4408 struct got_pathlist_head paths;
4409 char *id_str;
4411 TAILQ_INIT(&paths);
4413 error = got_object_id_str(&id_str,
4414 got_worktree_get_base_commit_id(worktree));
4415 if (error)
4416 goto done;
4417 arg.repo = repo;
4418 arg.worktree = worktree;
4419 arg.diff_context = diff_context;
4420 arg.id_str = id_str;
4421 arg.header_shown = 0;
4422 arg.diff_staged = diff_staged;
4423 arg.ignore_whitespace = ignore_whitespace;
4424 arg.force_text_diff = force_text_diff;
4426 error = got_pathlist_append(&paths, path, NULL);
4427 if (error)
4428 goto done;
4430 error = got_worktree_status(worktree, &paths, repo, print_diff,
4431 &arg, check_cancelled, NULL);
4432 free(id_str);
4433 got_pathlist_free(&paths);
4434 goto done;
4437 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4438 if (error)
4439 return error;
4441 error = got_repo_match_object_id(&id1, &label1, id_str1,
4442 GOT_OBJ_TYPE_ANY, &refs, repo);
4443 if (error)
4444 goto done;
4446 error = got_repo_match_object_id(&id2, &label2, id_str2,
4447 GOT_OBJ_TYPE_ANY, &refs, repo);
4448 if (error)
4449 goto done;
4451 error = got_object_get_type(&type1, repo, id1);
4452 if (error)
4453 goto done;
4455 error = got_object_get_type(&type2, repo, id2);
4456 if (error)
4457 goto done;
4459 if (type1 != type2) {
4460 error = got_error(GOT_ERR_OBJ_TYPE);
4461 goto done;
4464 switch (type1) {
4465 case GOT_OBJ_TYPE_BLOB:
4466 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4467 NULL, NULL, diff_context, ignore_whitespace,
4468 force_text_diff, repo, stdout);
4469 break;
4470 case GOT_OBJ_TYPE_TREE:
4471 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4472 "", "", diff_context, ignore_whitespace, force_text_diff,
4473 repo, stdout);
4474 break;
4475 case GOT_OBJ_TYPE_COMMIT:
4476 printf("diff %s %s\n", label1, label2);
4477 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4478 diff_context, ignore_whitespace, force_text_diff, repo,
4479 stdout);
4480 break;
4481 default:
4482 error = got_error(GOT_ERR_OBJ_TYPE);
4484 done:
4485 free(label1);
4486 free(label2);
4487 free(id1);
4488 free(id2);
4489 free(path);
4490 if (worktree)
4491 got_worktree_close(worktree);
4492 if (repo) {
4493 const struct got_error *repo_error;
4494 repo_error = got_repo_close(repo);
4495 if (error == NULL)
4496 error = repo_error;
4498 got_ref_list_free(&refs);
4499 return error;
4502 __dead static void
4503 usage_blame(void)
4505 fprintf(stderr,
4506 "usage: %s blame [-c commit] [-r repository-path] path\n",
4507 getprogname());
4508 exit(1);
4511 struct blame_line {
4512 int annotated;
4513 char *id_str;
4514 char *committer;
4515 char datebuf[11]; /* YYYY-MM-DD + NUL */
4518 struct blame_cb_args {
4519 struct blame_line *lines;
4520 int nlines;
4521 int nlines_prec;
4522 int lineno_cur;
4523 off_t *line_offsets;
4524 FILE *f;
4525 struct got_repository *repo;
4528 static const struct got_error *
4529 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4531 const struct got_error *err = NULL;
4532 struct blame_cb_args *a = arg;
4533 struct blame_line *bline;
4534 char *line = NULL;
4535 size_t linesize = 0;
4536 struct got_commit_object *commit = NULL;
4537 off_t offset;
4538 struct tm tm;
4539 time_t committer_time;
4541 if (nlines != a->nlines ||
4542 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4543 return got_error(GOT_ERR_RANGE);
4545 if (sigint_received)
4546 return got_error(GOT_ERR_ITER_COMPLETED);
4548 if (lineno == -1)
4549 return NULL; /* no change in this commit */
4551 /* Annotate this line. */
4552 bline = &a->lines[lineno - 1];
4553 if (bline->annotated)
4554 return NULL;
4555 err = got_object_id_str(&bline->id_str, id);
4556 if (err)
4557 return err;
4559 err = got_object_open_as_commit(&commit, a->repo, id);
4560 if (err)
4561 goto done;
4563 bline->committer = strdup(got_object_commit_get_committer(commit));
4564 if (bline->committer == NULL) {
4565 err = got_error_from_errno("strdup");
4566 goto done;
4569 committer_time = got_object_commit_get_committer_time(commit);
4570 if (localtime_r(&committer_time, &tm) == NULL)
4571 return got_error_from_errno("localtime_r");
4572 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4573 &tm) >= sizeof(bline->datebuf)) {
4574 err = got_error(GOT_ERR_NO_SPACE);
4575 goto done;
4577 bline->annotated = 1;
4579 /* Print lines annotated so far. */
4580 bline = &a->lines[a->lineno_cur - 1];
4581 if (!bline->annotated)
4582 goto done;
4584 offset = a->line_offsets[a->lineno_cur - 1];
4585 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4586 err = got_error_from_errno("fseeko");
4587 goto done;
4590 while (bline->annotated) {
4591 char *smallerthan, *at, *nl, *committer;
4592 size_t len;
4594 if (getline(&line, &linesize, a->f) == -1) {
4595 if (ferror(a->f))
4596 err = got_error_from_errno("getline");
4597 break;
4600 committer = bline->committer;
4601 smallerthan = strchr(committer, '<');
4602 if (smallerthan && smallerthan[1] != '\0')
4603 committer = smallerthan + 1;
4604 at = strchr(committer, '@');
4605 if (at)
4606 *at = '\0';
4607 len = strlen(committer);
4608 if (len >= 9)
4609 committer[8] = '\0';
4611 nl = strchr(line, '\n');
4612 if (nl)
4613 *nl = '\0';
4614 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4615 bline->id_str, bline->datebuf, committer, line);
4617 a->lineno_cur++;
4618 bline = &a->lines[a->lineno_cur - 1];
4620 done:
4621 if (commit)
4622 got_object_commit_close(commit);
4623 free(line);
4624 return err;
4627 static const struct got_error *
4628 cmd_blame(int argc, char *argv[])
4630 const struct got_error *error;
4631 struct got_repository *repo = NULL;
4632 struct got_worktree *worktree = NULL;
4633 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4634 char *link_target = NULL;
4635 struct got_object_id *obj_id = NULL;
4636 struct got_object_id *commit_id = NULL;
4637 struct got_blob_object *blob = NULL;
4638 char *commit_id_str = NULL;
4639 struct blame_cb_args bca;
4640 int ch, obj_type, i;
4641 off_t filesize;
4643 memset(&bca, 0, sizeof(bca));
4645 #ifndef PROFILE
4646 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4647 NULL) == -1)
4648 err(1, "pledge");
4649 #endif
4651 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4652 switch (ch) {
4653 case 'c':
4654 commit_id_str = optarg;
4655 break;
4656 case 'r':
4657 repo_path = realpath(optarg, NULL);
4658 if (repo_path == NULL)
4659 return got_error_from_errno2("realpath",
4660 optarg);
4661 got_path_strip_trailing_slashes(repo_path);
4662 break;
4663 default:
4664 usage_blame();
4665 /* NOTREACHED */
4669 argc -= optind;
4670 argv += optind;
4672 if (argc == 1)
4673 path = argv[0];
4674 else
4675 usage_blame();
4677 cwd = getcwd(NULL, 0);
4678 if (cwd == NULL) {
4679 error = got_error_from_errno("getcwd");
4680 goto done;
4682 if (repo_path == NULL) {
4683 error = got_worktree_open(&worktree, cwd);
4684 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4685 goto done;
4686 else
4687 error = NULL;
4688 if (worktree) {
4689 repo_path =
4690 strdup(got_worktree_get_repo_path(worktree));
4691 if (repo_path == NULL) {
4692 error = got_error_from_errno("strdup");
4693 if (error)
4694 goto done;
4696 } else {
4697 repo_path = strdup(cwd);
4698 if (repo_path == NULL) {
4699 error = got_error_from_errno("strdup");
4700 goto done;
4705 error = got_repo_open(&repo, repo_path, NULL);
4706 if (error != NULL)
4707 goto done;
4709 if (worktree) {
4710 const char *prefix = got_worktree_get_path_prefix(worktree);
4711 char *p;
4713 error = got_worktree_resolve_path(&p, worktree, path);
4714 if (error)
4715 goto done;
4716 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4717 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4718 p) == -1) {
4719 error = got_error_from_errno("asprintf");
4720 free(p);
4721 goto done;
4723 free(p);
4724 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4725 } else {
4726 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4727 if (error)
4728 goto done;
4729 error = got_repo_map_path(&in_repo_path, repo, path);
4731 if (error)
4732 goto done;
4734 if (commit_id_str == NULL) {
4735 struct got_reference *head_ref;
4736 error = got_ref_open(&head_ref, repo, worktree ?
4737 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4738 if (error != NULL)
4739 goto done;
4740 error = got_ref_resolve(&commit_id, repo, head_ref);
4741 got_ref_close(head_ref);
4742 if (error != NULL)
4743 goto done;
4744 } else {
4745 struct got_reflist_head refs;
4746 TAILQ_INIT(&refs);
4747 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4748 NULL);
4749 if (error)
4750 goto done;
4751 error = got_repo_match_object_id(&commit_id, NULL,
4752 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4753 got_ref_list_free(&refs);
4754 if (error)
4755 goto done;
4758 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4759 commit_id, repo);
4760 if (error)
4761 goto done;
4763 error = got_object_id_by_path(&obj_id, repo, commit_id,
4764 link_target ? link_target : in_repo_path);
4765 if (error)
4766 goto done;
4768 error = got_object_get_type(&obj_type, repo, obj_id);
4769 if (error)
4770 goto done;
4772 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4773 error = got_error_path(link_target ? link_target : in_repo_path,
4774 GOT_ERR_OBJ_TYPE);
4775 goto done;
4778 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4779 if (error)
4780 goto done;
4781 bca.f = got_opentemp();
4782 if (bca.f == NULL) {
4783 error = got_error_from_errno("got_opentemp");
4784 goto done;
4786 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4787 &bca.line_offsets, bca.f, blob);
4788 if (error || bca.nlines == 0)
4789 goto done;
4791 /* Don't include \n at EOF in the blame line count. */
4792 if (bca.line_offsets[bca.nlines - 1] == filesize)
4793 bca.nlines--;
4795 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4796 if (bca.lines == NULL) {
4797 error = got_error_from_errno("calloc");
4798 goto done;
4800 bca.lineno_cur = 1;
4801 bca.nlines_prec = 0;
4802 i = bca.nlines;
4803 while (i > 0) {
4804 i /= 10;
4805 bca.nlines_prec++;
4807 bca.repo = repo;
4809 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4810 repo, blame_cb, &bca, check_cancelled, NULL);
4811 done:
4812 free(in_repo_path);
4813 free(link_target);
4814 free(repo_path);
4815 free(cwd);
4816 free(commit_id);
4817 free(obj_id);
4818 if (blob)
4819 got_object_blob_close(blob);
4820 if (worktree)
4821 got_worktree_close(worktree);
4822 if (repo) {
4823 const struct got_error *repo_error;
4824 repo_error = got_repo_close(repo);
4825 if (error == NULL)
4826 error = repo_error;
4828 if (bca.lines) {
4829 for (i = 0; i < bca.nlines; i++) {
4830 struct blame_line *bline = &bca.lines[i];
4831 free(bline->id_str);
4832 free(bline->committer);
4834 free(bca.lines);
4836 free(bca.line_offsets);
4837 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4838 error = got_error_from_errno("fclose");
4839 return error;
4842 __dead static void
4843 usage_tree(void)
4845 fprintf(stderr,
4846 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4847 getprogname());
4848 exit(1);
4851 static const struct got_error *
4852 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4853 const char *root_path, struct got_repository *repo)
4855 const struct got_error *err = NULL;
4856 int is_root_path = (strcmp(path, root_path) == 0);
4857 const char *modestr = "";
4858 mode_t mode = got_tree_entry_get_mode(te);
4859 char *link_target = NULL;
4861 path += strlen(root_path);
4862 while (path[0] == '/')
4863 path++;
4865 if (got_object_tree_entry_is_submodule(te))
4866 modestr = "$";
4867 else if (S_ISLNK(mode)) {
4868 int i;
4870 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4871 if (err)
4872 return err;
4873 for (i = 0; i < strlen(link_target); i++) {
4874 if (!isprint((unsigned char)link_target[i]))
4875 link_target[i] = '?';
4878 modestr = "@";
4880 else if (S_ISDIR(mode))
4881 modestr = "/";
4882 else if (mode & S_IXUSR)
4883 modestr = "*";
4885 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4886 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4887 link_target ? " -> ": "", link_target ? link_target : "");
4889 free(link_target);
4890 return NULL;
4893 static const struct got_error *
4894 print_tree(const char *path, struct got_object_id *commit_id,
4895 int show_ids, int recurse, const char *root_path,
4896 struct got_repository *repo)
4898 const struct got_error *err = NULL;
4899 struct got_object_id *tree_id = NULL;
4900 struct got_tree_object *tree = NULL;
4901 int nentries, i;
4903 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4904 if (err)
4905 goto done;
4907 err = got_object_open_as_tree(&tree, repo, tree_id);
4908 if (err)
4909 goto done;
4910 nentries = got_object_tree_get_nentries(tree);
4911 for (i = 0; i < nentries; i++) {
4912 struct got_tree_entry *te;
4913 char *id = NULL;
4915 if (sigint_received || sigpipe_received)
4916 break;
4918 te = got_object_tree_get_entry(tree, i);
4919 if (show_ids) {
4920 char *id_str;
4921 err = got_object_id_str(&id_str,
4922 got_tree_entry_get_id(te));
4923 if (err)
4924 goto done;
4925 if (asprintf(&id, "%s ", id_str) == -1) {
4926 err = got_error_from_errno("asprintf");
4927 free(id_str);
4928 goto done;
4930 free(id_str);
4932 err = print_entry(te, id, path, root_path, repo);
4933 free(id);
4934 if (err)
4935 goto done;
4937 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4938 char *child_path;
4939 if (asprintf(&child_path, "%s%s%s", path,
4940 path[0] == '/' && path[1] == '\0' ? "" : "/",
4941 got_tree_entry_get_name(te)) == -1) {
4942 err = got_error_from_errno("asprintf");
4943 goto done;
4945 err = print_tree(child_path, commit_id, show_ids, 1,
4946 root_path, repo);
4947 free(child_path);
4948 if (err)
4949 goto done;
4952 done:
4953 if (tree)
4954 got_object_tree_close(tree);
4955 free(tree_id);
4956 return err;
4959 static const struct got_error *
4960 cmd_tree(int argc, char *argv[])
4962 const struct got_error *error;
4963 struct got_repository *repo = NULL;
4964 struct got_worktree *worktree = NULL;
4965 const char *path, *refname = NULL;
4966 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4967 struct got_object_id *commit_id = NULL;
4968 char *commit_id_str = NULL;
4969 int show_ids = 0, recurse = 0;
4970 int ch;
4972 #ifndef PROFILE
4973 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4974 NULL) == -1)
4975 err(1, "pledge");
4976 #endif
4978 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4979 switch (ch) {
4980 case 'c':
4981 commit_id_str = optarg;
4982 break;
4983 case 'r':
4984 repo_path = realpath(optarg, NULL);
4985 if (repo_path == NULL)
4986 return got_error_from_errno2("realpath",
4987 optarg);
4988 got_path_strip_trailing_slashes(repo_path);
4989 break;
4990 case 'i':
4991 show_ids = 1;
4992 break;
4993 case 'R':
4994 recurse = 1;
4995 break;
4996 default:
4997 usage_tree();
4998 /* NOTREACHED */
5002 argc -= optind;
5003 argv += optind;
5005 if (argc == 1)
5006 path = argv[0];
5007 else if (argc > 1)
5008 usage_tree();
5009 else
5010 path = NULL;
5012 cwd = getcwd(NULL, 0);
5013 if (cwd == NULL) {
5014 error = got_error_from_errno("getcwd");
5015 goto done;
5017 if (repo_path == NULL) {
5018 error = got_worktree_open(&worktree, cwd);
5019 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5020 goto done;
5021 else
5022 error = NULL;
5023 if (worktree) {
5024 repo_path =
5025 strdup(got_worktree_get_repo_path(worktree));
5026 if (repo_path == NULL)
5027 error = got_error_from_errno("strdup");
5028 if (error)
5029 goto done;
5030 } else {
5031 repo_path = strdup(cwd);
5032 if (repo_path == NULL) {
5033 error = got_error_from_errno("strdup");
5034 goto done;
5039 error = got_repo_open(&repo, repo_path, NULL);
5040 if (error != NULL)
5041 goto done;
5043 if (worktree) {
5044 const char *prefix = got_worktree_get_path_prefix(worktree);
5045 char *p;
5047 if (path == NULL)
5048 path = "";
5049 error = got_worktree_resolve_path(&p, worktree, path);
5050 if (error)
5051 goto done;
5052 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5053 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5054 p) == -1) {
5055 error = got_error_from_errno("asprintf");
5056 free(p);
5057 goto done;
5059 free(p);
5060 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5061 if (error)
5062 goto done;
5063 } else {
5064 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5065 if (error)
5066 goto done;
5067 if (path == NULL)
5068 path = "/";
5069 error = got_repo_map_path(&in_repo_path, repo, path);
5070 if (error != NULL)
5071 goto done;
5074 if (commit_id_str == NULL) {
5075 struct got_reference *head_ref;
5076 if (worktree)
5077 refname = got_worktree_get_head_ref_name(worktree);
5078 else
5079 refname = GOT_REF_HEAD;
5080 error = got_ref_open(&head_ref, repo, refname, 0);
5081 if (error != NULL)
5082 goto done;
5083 error = got_ref_resolve(&commit_id, repo, head_ref);
5084 got_ref_close(head_ref);
5085 if (error != NULL)
5086 goto done;
5087 } else {
5088 struct got_reflist_head refs;
5089 TAILQ_INIT(&refs);
5090 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5091 NULL);
5092 if (error)
5093 goto done;
5094 error = got_repo_match_object_id(&commit_id, NULL,
5095 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5096 got_ref_list_free(&refs);
5097 if (error)
5098 goto done;
5101 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5102 in_repo_path, repo);
5103 done:
5104 free(in_repo_path);
5105 free(repo_path);
5106 free(cwd);
5107 free(commit_id);
5108 if (worktree)
5109 got_worktree_close(worktree);
5110 if (repo) {
5111 const struct got_error *repo_error;
5112 repo_error = got_repo_close(repo);
5113 if (error == NULL)
5114 error = repo_error;
5116 return error;
5119 __dead static void
5120 usage_status(void)
5122 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
5123 getprogname());
5124 exit(1);
5127 static const struct got_error *
5128 print_status(void *arg, unsigned char status, unsigned char staged_status,
5129 const char *path, struct got_object_id *blob_id,
5130 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5131 int dirfd, const char *de_name)
5133 if (status == staged_status && (status == GOT_STATUS_DELETE))
5134 status = GOT_STATUS_NO_CHANGE;
5135 if (arg) {
5136 char *status_codes = arg;
5137 size_t ncodes = strlen(status_codes);
5138 int i;
5139 for (i = 0; i < ncodes ; i++) {
5140 if (status == status_codes[i] ||
5141 staged_status == status_codes[i])
5142 break;
5144 if (i == ncodes)
5145 return NULL;
5147 printf("%c%c %s\n", status, staged_status, path);
5148 return NULL;
5151 static const struct got_error *
5152 cmd_status(int argc, char *argv[])
5154 const struct got_error *error = NULL;
5155 struct got_repository *repo = NULL;
5156 struct got_worktree *worktree = NULL;
5157 char *cwd = NULL, *status_codes = NULL;;
5158 struct got_pathlist_head paths;
5159 struct got_pathlist_entry *pe;
5160 int ch, i;
5162 TAILQ_INIT(&paths);
5164 while ((ch = getopt(argc, argv, "s:")) != -1) {
5165 switch (ch) {
5166 case 's':
5167 for (i = 0; i < strlen(optarg); i++) {
5168 switch (optarg[i]) {
5169 case GOT_STATUS_MODIFY:
5170 case GOT_STATUS_ADD:
5171 case GOT_STATUS_DELETE:
5172 case GOT_STATUS_CONFLICT:
5173 case GOT_STATUS_MISSING:
5174 case GOT_STATUS_OBSTRUCTED:
5175 case GOT_STATUS_UNVERSIONED:
5176 case GOT_STATUS_MODE_CHANGE:
5177 case GOT_STATUS_NONEXISTENT:
5178 break;
5179 default:
5180 errx(1, "invalid status code '%c'",
5181 optarg[i]);
5184 status_codes = optarg;
5185 break;
5186 default:
5187 usage_status();
5188 /* NOTREACHED */
5192 argc -= optind;
5193 argv += optind;
5195 #ifndef PROFILE
5196 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5197 NULL) == -1)
5198 err(1, "pledge");
5199 #endif
5200 cwd = getcwd(NULL, 0);
5201 if (cwd == NULL) {
5202 error = got_error_from_errno("getcwd");
5203 goto done;
5206 error = got_worktree_open(&worktree, cwd);
5207 if (error) {
5208 if (error->code == GOT_ERR_NOT_WORKTREE)
5209 error = wrap_not_worktree_error(error, "status", cwd);
5210 goto done;
5213 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5214 NULL);
5215 if (error != NULL)
5216 goto done;
5218 error = apply_unveil(got_repo_get_path(repo), 1,
5219 got_worktree_get_root_path(worktree));
5220 if (error)
5221 goto done;
5223 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5224 if (error)
5225 goto done;
5227 error = got_worktree_status(worktree, &paths, repo, print_status,
5228 status_codes, check_cancelled, NULL);
5229 done:
5230 TAILQ_FOREACH(pe, &paths, entry)
5231 free((char *)pe->path);
5232 got_pathlist_free(&paths);
5233 free(cwd);
5234 return error;
5237 __dead static void
5238 usage_ref(void)
5240 fprintf(stderr,
5241 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5242 "[-d] [name]\n",
5243 getprogname());
5244 exit(1);
5247 static const struct got_error *
5248 list_refs(struct got_repository *repo, const char *refname)
5250 static const struct got_error *err = NULL;
5251 struct got_reflist_head refs;
5252 struct got_reflist_entry *re;
5254 TAILQ_INIT(&refs);
5255 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5256 if (err)
5257 return err;
5259 TAILQ_FOREACH(re, &refs, entry) {
5260 char *refstr;
5261 refstr = got_ref_to_str(re->ref);
5262 if (refstr == NULL)
5263 return got_error_from_errno("got_ref_to_str");
5264 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5265 free(refstr);
5268 got_ref_list_free(&refs);
5269 return NULL;
5272 static const struct got_error *
5273 delete_ref(struct got_repository *repo, const char *refname)
5275 const struct got_error *err = NULL;
5276 struct got_reference *ref;
5278 err = got_ref_open(&ref, repo, refname, 0);
5279 if (err)
5280 return err;
5282 err = got_ref_delete(ref, repo);
5283 got_ref_close(ref);
5284 return err;
5287 static const struct got_error *
5288 add_ref(struct got_repository *repo, const char *refname, const char *target)
5290 const struct got_error *err = NULL;
5291 struct got_object_id *id;
5292 struct got_reference *ref = NULL;
5295 * Don't let the user create a reference name with a leading '-'.
5296 * While technically a valid reference name, this case is usually
5297 * an unintended typo.
5299 if (refname[0] == '-')
5300 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5302 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5303 repo);
5304 if (err) {
5305 struct got_reference *target_ref;
5307 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5308 return err;
5309 err = got_ref_open(&target_ref, repo, target, 0);
5310 if (err)
5311 return err;
5312 err = got_ref_resolve(&id, repo, target_ref);
5313 got_ref_close(target_ref);
5314 if (err)
5315 return err;
5318 err = got_ref_alloc(&ref, refname, id);
5319 if (err)
5320 goto done;
5322 err = got_ref_write(ref, repo);
5323 done:
5324 if (ref)
5325 got_ref_close(ref);
5326 free(id);
5327 return err;
5330 static const struct got_error *
5331 add_symref(struct got_repository *repo, const char *refname, const char *target)
5333 const struct got_error *err = NULL;
5334 struct got_reference *ref = NULL;
5335 struct got_reference *target_ref = NULL;
5338 * Don't let the user create a reference name with a leading '-'.
5339 * While technically a valid reference name, this case is usually
5340 * an unintended typo.
5342 if (refname[0] == '-')
5343 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5345 err = got_ref_open(&target_ref, repo, target, 0);
5346 if (err)
5347 return err;
5349 err = got_ref_alloc_symref(&ref, refname, target_ref);
5350 if (err)
5351 goto done;
5353 err = got_ref_write(ref, repo);
5354 done:
5355 if (target_ref)
5356 got_ref_close(target_ref);
5357 if (ref)
5358 got_ref_close(ref);
5359 return err;
5362 static const struct got_error *
5363 cmd_ref(int argc, char *argv[])
5365 const struct got_error *error = NULL;
5366 struct got_repository *repo = NULL;
5367 struct got_worktree *worktree = NULL;
5368 char *cwd = NULL, *repo_path = NULL;
5369 int ch, do_list = 0, do_delete = 0;
5370 const char *obj_arg = NULL, *symref_target= NULL;
5371 char *refname = NULL;
5373 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5374 switch (ch) {
5375 case 'c':
5376 obj_arg = optarg;
5377 break;
5378 case 'd':
5379 do_delete = 1;
5380 break;
5381 case 'r':
5382 repo_path = realpath(optarg, NULL);
5383 if (repo_path == NULL)
5384 return got_error_from_errno2("realpath",
5385 optarg);
5386 got_path_strip_trailing_slashes(repo_path);
5387 break;
5388 case 'l':
5389 do_list = 1;
5390 break;
5391 case 's':
5392 symref_target = optarg;
5393 break;
5394 default:
5395 usage_ref();
5396 /* NOTREACHED */
5400 if (obj_arg && do_list)
5401 option_conflict('c', 'l');
5402 if (obj_arg && do_delete)
5403 option_conflict('c', 'd');
5404 if (obj_arg && symref_target)
5405 option_conflict('c', 's');
5406 if (symref_target && do_delete)
5407 option_conflict('s', 'd');
5408 if (symref_target && do_list)
5409 option_conflict('s', 'l');
5410 if (do_delete && do_list)
5411 option_conflict('d', 'l');
5413 argc -= optind;
5414 argv += optind;
5416 if (do_list) {
5417 if (argc != 0 && argc != 1)
5418 usage_ref();
5419 if (argc == 1) {
5420 refname = strdup(argv[0]);
5421 if (refname == NULL) {
5422 error = got_error_from_errno("strdup");
5423 goto done;
5426 } else {
5427 if (argc != 1)
5428 usage_ref();
5429 refname = strdup(argv[0]);
5430 if (refname == NULL) {
5431 error = got_error_from_errno("strdup");
5432 goto done;
5436 if (refname)
5437 got_path_strip_trailing_slashes(refname);
5439 #ifndef PROFILE
5440 if (do_list) {
5441 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5442 NULL) == -1)
5443 err(1, "pledge");
5444 } else {
5445 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5446 "sendfd unveil", NULL) == -1)
5447 err(1, "pledge");
5449 #endif
5450 cwd = getcwd(NULL, 0);
5451 if (cwd == NULL) {
5452 error = got_error_from_errno("getcwd");
5453 goto done;
5456 if (repo_path == NULL) {
5457 error = got_worktree_open(&worktree, cwd);
5458 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5459 goto done;
5460 else
5461 error = NULL;
5462 if (worktree) {
5463 repo_path =
5464 strdup(got_worktree_get_repo_path(worktree));
5465 if (repo_path == NULL)
5466 error = got_error_from_errno("strdup");
5467 if (error)
5468 goto done;
5469 } else {
5470 repo_path = strdup(cwd);
5471 if (repo_path == NULL) {
5472 error = got_error_from_errno("strdup");
5473 goto done;
5478 error = got_repo_open(&repo, repo_path, NULL);
5479 if (error != NULL)
5480 goto done;
5482 error = apply_unveil(got_repo_get_path(repo), do_list,
5483 worktree ? got_worktree_get_root_path(worktree) : NULL);
5484 if (error)
5485 goto done;
5487 if (do_list)
5488 error = list_refs(repo, refname);
5489 else if (do_delete)
5490 error = delete_ref(repo, refname);
5491 else if (symref_target)
5492 error = add_symref(repo, refname, symref_target);
5493 else {
5494 if (obj_arg == NULL)
5495 usage_ref();
5496 error = add_ref(repo, refname, obj_arg);
5498 done:
5499 free(refname);
5500 if (repo)
5501 got_repo_close(repo);
5502 if (worktree)
5503 got_worktree_close(worktree);
5504 free(cwd);
5505 free(repo_path);
5506 return error;
5509 __dead static void
5510 usage_branch(void)
5512 fprintf(stderr,
5513 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5514 "[name]\n", getprogname());
5515 exit(1);
5518 static const struct got_error *
5519 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5520 struct got_reference *ref)
5522 const struct got_error *err = NULL;
5523 const char *refname, *marker = " ";
5524 char *refstr;
5526 refname = got_ref_get_name(ref);
5527 if (worktree && strcmp(refname,
5528 got_worktree_get_head_ref_name(worktree)) == 0) {
5529 struct got_object_id *id = NULL;
5531 err = got_ref_resolve(&id, repo, ref);
5532 if (err)
5533 return err;
5534 if (got_object_id_cmp(id,
5535 got_worktree_get_base_commit_id(worktree)) == 0)
5536 marker = "* ";
5537 else
5538 marker = "~ ";
5539 free(id);
5542 if (strncmp(refname, "refs/heads/", 11) == 0)
5543 refname += 11;
5544 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5545 refname += 18;
5546 if (strncmp(refname, "refs/remotes/", 13) == 0)
5547 refname += 13;
5549 refstr = got_ref_to_str(ref);
5550 if (refstr == NULL)
5551 return got_error_from_errno("got_ref_to_str");
5553 printf("%s%s: %s\n", marker, refname, refstr);
5554 free(refstr);
5555 return NULL;
5558 static const struct got_error *
5559 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5561 const char *refname;
5563 if (worktree == NULL)
5564 return got_error(GOT_ERR_NOT_WORKTREE);
5566 refname = got_worktree_get_head_ref_name(worktree);
5568 if (strncmp(refname, "refs/heads/", 11) == 0)
5569 refname += 11;
5570 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5571 refname += 18;
5573 printf("%s\n", refname);
5575 return NULL;
5578 static const struct got_error *
5579 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5581 static const struct got_error *err = NULL;
5582 struct got_reflist_head refs;
5583 struct got_reflist_entry *re;
5584 struct got_reference *temp_ref = NULL;
5585 int rebase_in_progress, histedit_in_progress;
5587 TAILQ_INIT(&refs);
5589 if (worktree) {
5590 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5591 worktree);
5592 if (err)
5593 return err;
5595 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5596 worktree);
5597 if (err)
5598 return err;
5600 if (rebase_in_progress || histedit_in_progress) {
5601 err = got_ref_open(&temp_ref, repo,
5602 got_worktree_get_head_ref_name(worktree), 0);
5603 if (err)
5604 return err;
5605 list_branch(repo, worktree, temp_ref);
5606 got_ref_close(temp_ref);
5610 err = got_ref_list(&refs, repo, "refs/heads",
5611 got_ref_cmp_by_name, NULL);
5612 if (err)
5613 return err;
5615 TAILQ_FOREACH(re, &refs, entry)
5616 list_branch(repo, worktree, re->ref);
5618 got_ref_list_free(&refs);
5620 err = got_ref_list(&refs, repo, "refs/remotes",
5621 got_ref_cmp_by_name, NULL);
5622 if (err)
5623 return err;
5625 TAILQ_FOREACH(re, &refs, entry)
5626 list_branch(repo, worktree, re->ref);
5628 got_ref_list_free(&refs);
5630 return NULL;
5633 static const struct got_error *
5634 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5635 const char *branch_name)
5637 const struct got_error *err = NULL;
5638 struct got_reference *ref = NULL;
5639 char *refname;
5641 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5642 return got_error_from_errno("asprintf");
5644 err = got_ref_open(&ref, repo, refname, 0);
5645 if (err)
5646 goto done;
5648 if (worktree &&
5649 strcmp(got_worktree_get_head_ref_name(worktree),
5650 got_ref_get_name(ref)) == 0) {
5651 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5652 "will not delete this work tree's current branch");
5653 goto done;
5656 err = got_ref_delete(ref, repo);
5657 done:
5658 if (ref)
5659 got_ref_close(ref);
5660 free(refname);
5661 return err;
5664 static const struct got_error *
5665 add_branch(struct got_repository *repo, const char *branch_name,
5666 struct got_object_id *base_commit_id)
5668 const struct got_error *err = NULL;
5669 struct got_reference *ref = NULL;
5670 char *base_refname = NULL, *refname = NULL;
5673 * Don't let the user create a branch name with a leading '-'.
5674 * While technically a valid reference name, this case is usually
5675 * an unintended typo.
5677 if (branch_name[0] == '-')
5678 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5680 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5681 err = got_error_from_errno("asprintf");
5682 goto done;
5685 err = got_ref_open(&ref, repo, refname, 0);
5686 if (err == NULL) {
5687 err = got_error(GOT_ERR_BRANCH_EXISTS);
5688 goto done;
5689 } else if (err->code != GOT_ERR_NOT_REF)
5690 goto done;
5692 err = got_ref_alloc(&ref, refname, base_commit_id);
5693 if (err)
5694 goto done;
5696 err = got_ref_write(ref, repo);
5697 done:
5698 if (ref)
5699 got_ref_close(ref);
5700 free(base_refname);
5701 free(refname);
5702 return err;
5705 static const struct got_error *
5706 cmd_branch(int argc, char *argv[])
5708 const struct got_error *error = NULL;
5709 struct got_repository *repo = NULL;
5710 struct got_worktree *worktree = NULL;
5711 char *cwd = NULL, *repo_path = NULL;
5712 int ch, do_list = 0, do_show = 0, do_update = 1;
5713 const char *delref = NULL, *commit_id_arg = NULL;
5714 struct got_reference *ref = NULL;
5715 struct got_pathlist_head paths;
5716 struct got_pathlist_entry *pe;
5717 struct got_object_id *commit_id = NULL;
5718 char *commit_id_str = NULL;
5720 TAILQ_INIT(&paths);
5722 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5723 switch (ch) {
5724 case 'c':
5725 commit_id_arg = optarg;
5726 break;
5727 case 'd':
5728 delref = optarg;
5729 break;
5730 case 'r':
5731 repo_path = realpath(optarg, NULL);
5732 if (repo_path == NULL)
5733 return got_error_from_errno2("realpath",
5734 optarg);
5735 got_path_strip_trailing_slashes(repo_path);
5736 break;
5737 case 'l':
5738 do_list = 1;
5739 break;
5740 case 'n':
5741 do_update = 0;
5742 break;
5743 default:
5744 usage_branch();
5745 /* NOTREACHED */
5749 if (do_list && delref)
5750 option_conflict('l', 'd');
5752 argc -= optind;
5753 argv += optind;
5755 if (!do_list && !delref && argc == 0)
5756 do_show = 1;
5758 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5759 errx(1, "-c option can only be used when creating a branch");
5761 if (do_list || delref) {
5762 if (argc > 0)
5763 usage_branch();
5764 } else if (!do_show && argc != 1)
5765 usage_branch();
5767 #ifndef PROFILE
5768 if (do_list || do_show) {
5769 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5770 NULL) == -1)
5771 err(1, "pledge");
5772 } else {
5773 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5774 "sendfd unveil", NULL) == -1)
5775 err(1, "pledge");
5777 #endif
5778 cwd = getcwd(NULL, 0);
5779 if (cwd == NULL) {
5780 error = got_error_from_errno("getcwd");
5781 goto done;
5784 if (repo_path == NULL) {
5785 error = got_worktree_open(&worktree, cwd);
5786 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5787 goto done;
5788 else
5789 error = NULL;
5790 if (worktree) {
5791 repo_path =
5792 strdup(got_worktree_get_repo_path(worktree));
5793 if (repo_path == NULL)
5794 error = got_error_from_errno("strdup");
5795 if (error)
5796 goto done;
5797 } else {
5798 repo_path = strdup(cwd);
5799 if (repo_path == NULL) {
5800 error = got_error_from_errno("strdup");
5801 goto done;
5806 error = got_repo_open(&repo, repo_path, NULL);
5807 if (error != NULL)
5808 goto done;
5810 error = apply_unveil(got_repo_get_path(repo), do_list,
5811 worktree ? got_worktree_get_root_path(worktree) : NULL);
5812 if (error)
5813 goto done;
5815 if (do_show)
5816 error = show_current_branch(repo, worktree);
5817 else if (do_list)
5818 error = list_branches(repo, worktree);
5819 else if (delref)
5820 error = delete_branch(repo, worktree, delref);
5821 else {
5822 struct got_reflist_head refs;
5823 TAILQ_INIT(&refs);
5824 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5825 NULL);
5826 if (error)
5827 goto done;
5828 if (commit_id_arg == NULL)
5829 commit_id_arg = worktree ?
5830 got_worktree_get_head_ref_name(worktree) :
5831 GOT_REF_HEAD;
5832 error = got_repo_match_object_id(&commit_id, NULL,
5833 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5834 got_ref_list_free(&refs);
5835 if (error)
5836 goto done;
5837 error = add_branch(repo, argv[0], commit_id);
5838 if (error)
5839 goto done;
5840 if (worktree && do_update) {
5841 struct got_update_progress_arg upa;
5842 char *branch_refname = NULL;
5844 error = got_object_id_str(&commit_id_str, commit_id);
5845 if (error)
5846 goto done;
5847 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5848 worktree);
5849 if (error)
5850 goto done;
5851 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5852 == -1) {
5853 error = got_error_from_errno("asprintf");
5854 goto done;
5856 error = got_ref_open(&ref, repo, branch_refname, 0);
5857 free(branch_refname);
5858 if (error)
5859 goto done;
5860 error = switch_head_ref(ref, commit_id, worktree,
5861 repo);
5862 if (error)
5863 goto done;
5864 error = got_worktree_set_base_commit_id(worktree, repo,
5865 commit_id);
5866 if (error)
5867 goto done;
5868 memset(&upa, 0, sizeof(upa));
5869 error = got_worktree_checkout_files(worktree, &paths,
5870 repo, update_progress, &upa, check_cancelled,
5871 NULL);
5872 if (error)
5873 goto done;
5874 if (upa.did_something)
5875 printf("Updated to commit %s\n", commit_id_str);
5876 print_update_progress_stats(&upa);
5879 done:
5880 if (ref)
5881 got_ref_close(ref);
5882 if (repo)
5883 got_repo_close(repo);
5884 if (worktree)
5885 got_worktree_close(worktree);
5886 free(cwd);
5887 free(repo_path);
5888 free(commit_id);
5889 free(commit_id_str);
5890 TAILQ_FOREACH(pe, &paths, entry)
5891 free((char *)pe->path);
5892 got_pathlist_free(&paths);
5893 return error;
5897 __dead static void
5898 usage_tag(void)
5900 fprintf(stderr,
5901 "usage: %s tag [-c commit] [-r repository] [-l] "
5902 "[-m message] name\n", getprogname());
5903 exit(1);
5906 #if 0
5907 static const struct got_error *
5908 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5910 const struct got_error *err = NULL;
5911 struct got_reflist_entry *re, *se, *new;
5912 struct got_object_id *re_id, *se_id;
5913 struct got_tag_object *re_tag, *se_tag;
5914 time_t re_time, se_time;
5916 SIMPLEQ_FOREACH(re, tags, entry) {
5917 se = SIMPLEQ_FIRST(sorted);
5918 if (se == NULL) {
5919 err = got_reflist_entry_dup(&new, re);
5920 if (err)
5921 return err;
5922 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5923 continue;
5924 } else {
5925 err = got_ref_resolve(&re_id, repo, re->ref);
5926 if (err)
5927 break;
5928 err = got_object_open_as_tag(&re_tag, repo, re_id);
5929 free(re_id);
5930 if (err)
5931 break;
5932 re_time = got_object_tag_get_tagger_time(re_tag);
5933 got_object_tag_close(re_tag);
5936 while (se) {
5937 err = got_ref_resolve(&se_id, repo, re->ref);
5938 if (err)
5939 break;
5940 err = got_object_open_as_tag(&se_tag, repo, se_id);
5941 free(se_id);
5942 if (err)
5943 break;
5944 se_time = got_object_tag_get_tagger_time(se_tag);
5945 got_object_tag_close(se_tag);
5947 if (se_time > re_time) {
5948 err = got_reflist_entry_dup(&new, re);
5949 if (err)
5950 return err;
5951 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5952 break;
5954 se = SIMPLEQ_NEXT(se, entry);
5955 continue;
5958 done:
5959 return err;
5961 #endif
5963 static const struct got_error *
5964 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5966 static const struct got_error *err = NULL;
5967 struct got_reflist_head refs;
5968 struct got_reflist_entry *re;
5970 TAILQ_INIT(&refs);
5972 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5973 if (err)
5974 return err;
5976 TAILQ_FOREACH(re, &refs, entry) {
5977 const char *refname;
5978 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5979 char datebuf[26];
5980 const char *tagger;
5981 time_t tagger_time;
5982 struct got_object_id *id;
5983 struct got_tag_object *tag;
5984 struct got_commit_object *commit = NULL;
5986 refname = got_ref_get_name(re->ref);
5987 if (strncmp(refname, "refs/tags/", 10) != 0)
5988 continue;
5989 refname += 10;
5990 refstr = got_ref_to_str(re->ref);
5991 if (refstr == NULL) {
5992 err = got_error_from_errno("got_ref_to_str");
5993 break;
5995 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5996 free(refstr);
5998 err = got_ref_resolve(&id, repo, re->ref);
5999 if (err)
6000 break;
6001 err = got_object_open_as_tag(&tag, repo, id);
6002 if (err) {
6003 if (err->code != GOT_ERR_OBJ_TYPE) {
6004 free(id);
6005 break;
6007 /* "lightweight" tag */
6008 err = got_object_open_as_commit(&commit, repo, id);
6009 if (err) {
6010 free(id);
6011 break;
6013 tagger = got_object_commit_get_committer(commit);
6014 tagger_time =
6015 got_object_commit_get_committer_time(commit);
6016 err = got_object_id_str(&id_str, id);
6017 free(id);
6018 if (err)
6019 break;
6020 } else {
6021 free(id);
6022 tagger = got_object_tag_get_tagger(tag);
6023 tagger_time = got_object_tag_get_tagger_time(tag);
6024 err = got_object_id_str(&id_str,
6025 got_object_tag_get_object_id(tag));
6026 if (err)
6027 break;
6029 printf("from: %s\n", tagger);
6030 datestr = get_datestr(&tagger_time, datebuf);
6031 if (datestr)
6032 printf("date: %s UTC\n", datestr);
6033 if (commit)
6034 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6035 else {
6036 switch (got_object_tag_get_object_type(tag)) {
6037 case GOT_OBJ_TYPE_BLOB:
6038 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6039 id_str);
6040 break;
6041 case GOT_OBJ_TYPE_TREE:
6042 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6043 id_str);
6044 break;
6045 case GOT_OBJ_TYPE_COMMIT:
6046 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6047 id_str);
6048 break;
6049 case GOT_OBJ_TYPE_TAG:
6050 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6051 id_str);
6052 break;
6053 default:
6054 break;
6057 free(id_str);
6058 if (commit) {
6059 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6060 if (err)
6061 break;
6062 got_object_commit_close(commit);
6063 } else {
6064 tagmsg0 = strdup(got_object_tag_get_message(tag));
6065 got_object_tag_close(tag);
6066 if (tagmsg0 == NULL) {
6067 err = got_error_from_errno("strdup");
6068 break;
6072 tagmsg = tagmsg0;
6073 do {
6074 line = strsep(&tagmsg, "\n");
6075 if (line)
6076 printf(" %s\n", line);
6077 } while (line);
6078 free(tagmsg0);
6081 got_ref_list_free(&refs);
6082 return NULL;
6085 static const struct got_error *
6086 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6087 const char *tag_name, const char *repo_path)
6089 const struct got_error *err = NULL;
6090 char *template = NULL, *initial_content = NULL;
6091 char *editor = NULL;
6092 int initial_content_len;
6093 int fd = -1;
6095 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6096 err = got_error_from_errno("asprintf");
6097 goto done;
6100 initial_content_len = asprintf(&initial_content,
6101 "\n# tagging commit %s as %s\n",
6102 commit_id_str, tag_name);
6103 if (initial_content_len == -1) {
6104 err = got_error_from_errno("asprintf");
6105 goto done;
6108 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6109 if (err)
6110 goto done;
6112 if (write(fd, initial_content, initial_content_len) == -1) {
6113 err = got_error_from_errno2("write", *tagmsg_path);
6114 goto done;
6117 err = get_editor(&editor);
6118 if (err)
6119 goto done;
6120 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6121 initial_content_len, 1);
6122 done:
6123 free(initial_content);
6124 free(template);
6125 free(editor);
6127 if (fd != -1 && close(fd) == -1 && err == NULL)
6128 err = got_error_from_errno2("close", *tagmsg_path);
6130 /* Editor is done; we can now apply unveil(2) */
6131 if (err == NULL)
6132 err = apply_unveil(repo_path, 0, NULL);
6133 if (err) {
6134 free(*tagmsg);
6135 *tagmsg = NULL;
6137 return err;
6140 static const struct got_error *
6141 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6142 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6144 const struct got_error *err = NULL;
6145 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6146 char *label = NULL, *commit_id_str = NULL;
6147 struct got_reference *ref = NULL;
6148 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6149 char *tagmsg_path = NULL, *tag_id_str = NULL;
6150 int preserve_tagmsg = 0;
6151 struct got_reflist_head refs;
6153 TAILQ_INIT(&refs);
6156 * Don't let the user create a tag name with a leading '-'.
6157 * While technically a valid reference name, this case is usually
6158 * an unintended typo.
6160 if (tag_name[0] == '-')
6161 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6163 err = get_author(&tagger, repo, worktree);
6164 if (err)
6165 return err;
6167 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6168 if (err)
6169 goto done;
6171 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6172 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6173 if (err)
6174 goto done;
6176 err = got_object_id_str(&commit_id_str, commit_id);
6177 if (err)
6178 goto done;
6180 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6181 refname = strdup(tag_name);
6182 if (refname == NULL) {
6183 err = got_error_from_errno("strdup");
6184 goto done;
6186 tag_name += 10;
6187 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6188 err = got_error_from_errno("asprintf");
6189 goto done;
6192 err = got_ref_open(&ref, repo, refname, 0);
6193 if (err == NULL) {
6194 err = got_error(GOT_ERR_TAG_EXISTS);
6195 goto done;
6196 } else if (err->code != GOT_ERR_NOT_REF)
6197 goto done;
6199 if (tagmsg_arg == NULL) {
6200 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6201 tag_name, got_repo_get_path(repo));
6202 if (err) {
6203 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6204 tagmsg_path != NULL)
6205 preserve_tagmsg = 1;
6206 goto done;
6210 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6211 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6212 if (err) {
6213 if (tagmsg_path)
6214 preserve_tagmsg = 1;
6215 goto done;
6218 err = got_ref_alloc(&ref, refname, tag_id);
6219 if (err) {
6220 if (tagmsg_path)
6221 preserve_tagmsg = 1;
6222 goto done;
6225 err = got_ref_write(ref, repo);
6226 if (err) {
6227 if (tagmsg_path)
6228 preserve_tagmsg = 1;
6229 goto done;
6232 err = got_object_id_str(&tag_id_str, tag_id);
6233 if (err) {
6234 if (tagmsg_path)
6235 preserve_tagmsg = 1;
6236 goto done;
6238 printf("Created tag %s\n", tag_id_str);
6239 done:
6240 if (preserve_tagmsg) {
6241 fprintf(stderr, "%s: tag message preserved in %s\n",
6242 getprogname(), tagmsg_path);
6243 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6244 err = got_error_from_errno2("unlink", tagmsg_path);
6245 free(tag_id_str);
6246 if (ref)
6247 got_ref_close(ref);
6248 free(commit_id);
6249 free(commit_id_str);
6250 free(refname);
6251 free(tagmsg);
6252 free(tagmsg_path);
6253 free(tagger);
6254 got_ref_list_free(&refs);
6255 return err;
6258 static const struct got_error *
6259 cmd_tag(int argc, char *argv[])
6261 const struct got_error *error = NULL;
6262 struct got_repository *repo = NULL;
6263 struct got_worktree *worktree = NULL;
6264 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6265 char *gitconfig_path = NULL;
6266 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6267 int ch, do_list = 0;
6269 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6270 switch (ch) {
6271 case 'c':
6272 commit_id_arg = optarg;
6273 break;
6274 case 'm':
6275 tagmsg = optarg;
6276 break;
6277 case 'r':
6278 repo_path = realpath(optarg, NULL);
6279 if (repo_path == NULL)
6280 return got_error_from_errno2("realpath",
6281 optarg);
6282 got_path_strip_trailing_slashes(repo_path);
6283 break;
6284 case 'l':
6285 do_list = 1;
6286 break;
6287 default:
6288 usage_tag();
6289 /* NOTREACHED */
6293 argc -= optind;
6294 argv += optind;
6296 if (do_list) {
6297 if (commit_id_arg != NULL)
6298 errx(1,
6299 "-c option can only be used when creating a tag");
6300 if (tagmsg)
6301 option_conflict('l', 'm');
6302 if (argc > 0)
6303 usage_tag();
6304 } else if (argc != 1)
6305 usage_tag();
6307 tag_name = argv[0];
6309 #ifndef PROFILE
6310 if (do_list) {
6311 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6312 NULL) == -1)
6313 err(1, "pledge");
6314 } else {
6315 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6316 "sendfd unveil", NULL) == -1)
6317 err(1, "pledge");
6319 #endif
6320 cwd = getcwd(NULL, 0);
6321 if (cwd == NULL) {
6322 error = got_error_from_errno("getcwd");
6323 goto done;
6326 if (repo_path == NULL) {
6327 error = got_worktree_open(&worktree, cwd);
6328 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6329 goto done;
6330 else
6331 error = NULL;
6332 if (worktree) {
6333 repo_path =
6334 strdup(got_worktree_get_repo_path(worktree));
6335 if (repo_path == NULL)
6336 error = got_error_from_errno("strdup");
6337 if (error)
6338 goto done;
6339 } else {
6340 repo_path = strdup(cwd);
6341 if (repo_path == NULL) {
6342 error = got_error_from_errno("strdup");
6343 goto done;
6348 if (do_list) {
6349 error = got_repo_open(&repo, repo_path, NULL);
6350 if (error != NULL)
6351 goto done;
6352 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6353 if (error)
6354 goto done;
6355 error = list_tags(repo, worktree);
6356 } else {
6357 error = get_gitconfig_path(&gitconfig_path);
6358 if (error)
6359 goto done;
6360 error = got_repo_open(&repo, repo_path, gitconfig_path);
6361 if (error != NULL)
6362 goto done;
6364 if (tagmsg) {
6365 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6366 if (error)
6367 goto done;
6370 if (commit_id_arg == NULL) {
6371 struct got_reference *head_ref;
6372 struct got_object_id *commit_id;
6373 error = got_ref_open(&head_ref, repo,
6374 worktree ? got_worktree_get_head_ref_name(worktree)
6375 : GOT_REF_HEAD, 0);
6376 if (error)
6377 goto done;
6378 error = got_ref_resolve(&commit_id, repo, head_ref);
6379 got_ref_close(head_ref);
6380 if (error)
6381 goto done;
6382 error = got_object_id_str(&commit_id_str, commit_id);
6383 free(commit_id);
6384 if (error)
6385 goto done;
6388 error = add_tag(repo, worktree, tag_name,
6389 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6391 done:
6392 if (repo)
6393 got_repo_close(repo);
6394 if (worktree)
6395 got_worktree_close(worktree);
6396 free(cwd);
6397 free(repo_path);
6398 free(gitconfig_path);
6399 free(commit_id_str);
6400 return error;
6403 __dead static void
6404 usage_add(void)
6406 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6407 getprogname());
6408 exit(1);
6411 static const struct got_error *
6412 add_progress(void *arg, unsigned char status, const char *path)
6414 while (path[0] == '/')
6415 path++;
6416 printf("%c %s\n", status, path);
6417 return NULL;
6420 static const struct got_error *
6421 cmd_add(int argc, char *argv[])
6423 const struct got_error *error = NULL;
6424 struct got_repository *repo = NULL;
6425 struct got_worktree *worktree = NULL;
6426 char *cwd = NULL;
6427 struct got_pathlist_head paths;
6428 struct got_pathlist_entry *pe;
6429 int ch, can_recurse = 0, no_ignores = 0;
6431 TAILQ_INIT(&paths);
6433 while ((ch = getopt(argc, argv, "IR")) != -1) {
6434 switch (ch) {
6435 case 'I':
6436 no_ignores = 1;
6437 break;
6438 case 'R':
6439 can_recurse = 1;
6440 break;
6441 default:
6442 usage_add();
6443 /* NOTREACHED */
6447 argc -= optind;
6448 argv += optind;
6450 #ifndef PROFILE
6451 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6452 NULL) == -1)
6453 err(1, "pledge");
6454 #endif
6455 if (argc < 1)
6456 usage_add();
6458 cwd = getcwd(NULL, 0);
6459 if (cwd == NULL) {
6460 error = got_error_from_errno("getcwd");
6461 goto done;
6464 error = got_worktree_open(&worktree, cwd);
6465 if (error) {
6466 if (error->code == GOT_ERR_NOT_WORKTREE)
6467 error = wrap_not_worktree_error(error, "add", cwd);
6468 goto done;
6471 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6472 NULL);
6473 if (error != NULL)
6474 goto done;
6476 error = apply_unveil(got_repo_get_path(repo), 1,
6477 got_worktree_get_root_path(worktree));
6478 if (error)
6479 goto done;
6481 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6482 if (error)
6483 goto done;
6485 if (!can_recurse && no_ignores) {
6486 error = got_error_msg(GOT_ERR_BAD_PATH,
6487 "disregarding ignores requires -R option");
6488 goto done;
6492 if (!can_recurse) {
6493 char *ondisk_path;
6494 struct stat sb;
6495 TAILQ_FOREACH(pe, &paths, entry) {
6496 if (asprintf(&ondisk_path, "%s/%s",
6497 got_worktree_get_root_path(worktree),
6498 pe->path) == -1) {
6499 error = got_error_from_errno("asprintf");
6500 goto done;
6502 if (lstat(ondisk_path, &sb) == -1) {
6503 if (errno == ENOENT) {
6504 free(ondisk_path);
6505 continue;
6507 error = got_error_from_errno2("lstat",
6508 ondisk_path);
6509 free(ondisk_path);
6510 goto done;
6512 free(ondisk_path);
6513 if (S_ISDIR(sb.st_mode)) {
6514 error = got_error_msg(GOT_ERR_BAD_PATH,
6515 "adding directories requires -R option");
6516 goto done;
6521 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6522 NULL, repo, no_ignores);
6523 done:
6524 if (repo)
6525 got_repo_close(repo);
6526 if (worktree)
6527 got_worktree_close(worktree);
6528 TAILQ_FOREACH(pe, &paths, entry)
6529 free((char *)pe->path);
6530 got_pathlist_free(&paths);
6531 free(cwd);
6532 return error;
6535 __dead static void
6536 usage_remove(void)
6538 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6539 "path ...\n", getprogname());
6540 exit(1);
6543 static const struct got_error *
6544 print_remove_status(void *arg, unsigned char status,
6545 unsigned char staged_status, const char *path)
6547 while (path[0] == '/')
6548 path++;
6549 if (status == GOT_STATUS_NONEXISTENT)
6550 return NULL;
6551 if (status == staged_status && (status == GOT_STATUS_DELETE))
6552 status = GOT_STATUS_NO_CHANGE;
6553 printf("%c%c %s\n", status, staged_status, path);
6554 return NULL;
6557 static const struct got_error *
6558 cmd_remove(int argc, char *argv[])
6560 const struct got_error *error = NULL;
6561 struct got_worktree *worktree = NULL;
6562 struct got_repository *repo = NULL;
6563 const char *status_codes = NULL;
6564 char *cwd = NULL;
6565 struct got_pathlist_head paths;
6566 struct got_pathlist_entry *pe;
6567 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6569 TAILQ_INIT(&paths);
6571 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6572 switch (ch) {
6573 case 'f':
6574 delete_local_mods = 1;
6575 break;
6576 case 'k':
6577 keep_on_disk = 1;
6578 break;
6579 case 'R':
6580 can_recurse = 1;
6581 break;
6582 case 's':
6583 for (i = 0; i < strlen(optarg); i++) {
6584 switch (optarg[i]) {
6585 case GOT_STATUS_MODIFY:
6586 delete_local_mods = 1;
6587 break;
6588 case GOT_STATUS_MISSING:
6589 break;
6590 default:
6591 errx(1, "invalid status code '%c'",
6592 optarg[i]);
6595 status_codes = optarg;
6596 break;
6597 default:
6598 usage_remove();
6599 /* NOTREACHED */
6603 argc -= optind;
6604 argv += optind;
6606 #ifndef PROFILE
6607 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6608 NULL) == -1)
6609 err(1, "pledge");
6610 #endif
6611 if (argc < 1)
6612 usage_remove();
6614 cwd = getcwd(NULL, 0);
6615 if (cwd == NULL) {
6616 error = got_error_from_errno("getcwd");
6617 goto done;
6619 error = got_worktree_open(&worktree, cwd);
6620 if (error) {
6621 if (error->code == GOT_ERR_NOT_WORKTREE)
6622 error = wrap_not_worktree_error(error, "remove", cwd);
6623 goto done;
6626 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6627 NULL);
6628 if (error)
6629 goto done;
6631 error = apply_unveil(got_repo_get_path(repo), 1,
6632 got_worktree_get_root_path(worktree));
6633 if (error)
6634 goto done;
6636 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6637 if (error)
6638 goto done;
6640 if (!can_recurse) {
6641 char *ondisk_path;
6642 struct stat sb;
6643 TAILQ_FOREACH(pe, &paths, entry) {
6644 if (asprintf(&ondisk_path, "%s/%s",
6645 got_worktree_get_root_path(worktree),
6646 pe->path) == -1) {
6647 error = got_error_from_errno("asprintf");
6648 goto done;
6650 if (lstat(ondisk_path, &sb) == -1) {
6651 if (errno == ENOENT) {
6652 free(ondisk_path);
6653 continue;
6655 error = got_error_from_errno2("lstat",
6656 ondisk_path);
6657 free(ondisk_path);
6658 goto done;
6660 free(ondisk_path);
6661 if (S_ISDIR(sb.st_mode)) {
6662 error = got_error_msg(GOT_ERR_BAD_PATH,
6663 "removing directories requires -R option");
6664 goto done;
6669 error = got_worktree_schedule_delete(worktree, &paths,
6670 delete_local_mods, status_codes, print_remove_status, NULL,
6671 repo, keep_on_disk);
6672 done:
6673 if (repo)
6674 got_repo_close(repo);
6675 if (worktree)
6676 got_worktree_close(worktree);
6677 TAILQ_FOREACH(pe, &paths, entry)
6678 free((char *)pe->path);
6679 got_pathlist_free(&paths);
6680 free(cwd);
6681 return error;
6684 __dead static void
6685 usage_revert(void)
6687 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6688 "path ...\n", getprogname());
6689 exit(1);
6692 static const struct got_error *
6693 revert_progress(void *arg, unsigned char status, const char *path)
6695 if (status == GOT_STATUS_UNVERSIONED)
6696 return NULL;
6698 while (path[0] == '/')
6699 path++;
6700 printf("%c %s\n", status, path);
6701 return NULL;
6704 struct choose_patch_arg {
6705 FILE *patch_script_file;
6706 const char *action;
6709 static const struct got_error *
6710 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6711 int nchanges, const char *action)
6713 char *line = NULL;
6714 size_t linesize = 0;
6715 ssize_t linelen;
6717 switch (status) {
6718 case GOT_STATUS_ADD:
6719 printf("A %s\n%s this addition? [y/n] ", path, action);
6720 break;
6721 case GOT_STATUS_DELETE:
6722 printf("D %s\n%s this deletion? [y/n] ", path, action);
6723 break;
6724 case GOT_STATUS_MODIFY:
6725 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6726 return got_error_from_errno("fseek");
6727 printf(GOT_COMMIT_SEP_STR);
6728 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6729 printf("%s", line);
6730 if (ferror(patch_file))
6731 return got_error_from_errno("getline");
6732 printf(GOT_COMMIT_SEP_STR);
6733 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6734 path, n, nchanges, action);
6735 break;
6736 default:
6737 return got_error_path(path, GOT_ERR_FILE_STATUS);
6740 return NULL;
6743 static const struct got_error *
6744 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6745 FILE *patch_file, int n, int nchanges)
6747 const struct got_error *err = NULL;
6748 char *line = NULL;
6749 size_t linesize = 0;
6750 ssize_t linelen;
6751 int resp = ' ';
6752 struct choose_patch_arg *a = arg;
6754 *choice = GOT_PATCH_CHOICE_NONE;
6756 if (a->patch_script_file) {
6757 char *nl;
6758 err = show_change(status, path, patch_file, n, nchanges,
6759 a->action);
6760 if (err)
6761 return err;
6762 linelen = getline(&line, &linesize, a->patch_script_file);
6763 if (linelen == -1) {
6764 if (ferror(a->patch_script_file))
6765 return got_error_from_errno("getline");
6766 return NULL;
6768 nl = strchr(line, '\n');
6769 if (nl)
6770 *nl = '\0';
6771 if (strcmp(line, "y") == 0) {
6772 *choice = GOT_PATCH_CHOICE_YES;
6773 printf("y\n");
6774 } else if (strcmp(line, "n") == 0) {
6775 *choice = GOT_PATCH_CHOICE_NO;
6776 printf("n\n");
6777 } else if (strcmp(line, "q") == 0 &&
6778 status == GOT_STATUS_MODIFY) {
6779 *choice = GOT_PATCH_CHOICE_QUIT;
6780 printf("q\n");
6781 } else
6782 printf("invalid response '%s'\n", line);
6783 free(line);
6784 return NULL;
6787 while (resp != 'y' && resp != 'n' && resp != 'q') {
6788 err = show_change(status, path, patch_file, n, nchanges,
6789 a->action);
6790 if (err)
6791 return err;
6792 resp = getchar();
6793 if (resp == '\n')
6794 resp = getchar();
6795 if (status == GOT_STATUS_MODIFY) {
6796 if (resp != 'y' && resp != 'n' && resp != 'q') {
6797 printf("invalid response '%c'\n", resp);
6798 resp = ' ';
6800 } else if (resp != 'y' && resp != 'n') {
6801 printf("invalid response '%c'\n", resp);
6802 resp = ' ';
6806 if (resp == 'y')
6807 *choice = GOT_PATCH_CHOICE_YES;
6808 else if (resp == 'n')
6809 *choice = GOT_PATCH_CHOICE_NO;
6810 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6811 *choice = GOT_PATCH_CHOICE_QUIT;
6813 return NULL;
6817 static const struct got_error *
6818 cmd_revert(int argc, char *argv[])
6820 const struct got_error *error = NULL;
6821 struct got_worktree *worktree = NULL;
6822 struct got_repository *repo = NULL;
6823 char *cwd = NULL, *path = NULL;
6824 struct got_pathlist_head paths;
6825 struct got_pathlist_entry *pe;
6826 int ch, can_recurse = 0, pflag = 0;
6827 FILE *patch_script_file = NULL;
6828 const char *patch_script_path = NULL;
6829 struct choose_patch_arg cpa;
6831 TAILQ_INIT(&paths);
6833 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6834 switch (ch) {
6835 case 'p':
6836 pflag = 1;
6837 break;
6838 case 'F':
6839 patch_script_path = optarg;
6840 break;
6841 case 'R':
6842 can_recurse = 1;
6843 break;
6844 default:
6845 usage_revert();
6846 /* NOTREACHED */
6850 argc -= optind;
6851 argv += optind;
6853 #ifndef PROFILE
6854 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6855 "unveil", NULL) == -1)
6856 err(1, "pledge");
6857 #endif
6858 if (argc < 1)
6859 usage_revert();
6860 if (patch_script_path && !pflag)
6861 errx(1, "-F option can only be used together with -p option");
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, "revert", cwd);
6872 goto done;
6875 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6876 NULL);
6877 if (error != NULL)
6878 goto done;
6880 if (patch_script_path) {
6881 patch_script_file = fopen(patch_script_path, "r");
6882 if (patch_script_file == NULL) {
6883 error = got_error_from_errno2("fopen",
6884 patch_script_path);
6885 goto done;
6888 error = apply_unveil(got_repo_get_path(repo), 1,
6889 got_worktree_get_root_path(worktree));
6890 if (error)
6891 goto done;
6893 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6894 if (error)
6895 goto done;
6897 if (!can_recurse) {
6898 char *ondisk_path;
6899 struct stat sb;
6900 TAILQ_FOREACH(pe, &paths, entry) {
6901 if (asprintf(&ondisk_path, "%s/%s",
6902 got_worktree_get_root_path(worktree),
6903 pe->path) == -1) {
6904 error = got_error_from_errno("asprintf");
6905 goto done;
6907 if (lstat(ondisk_path, &sb) == -1) {
6908 if (errno == ENOENT) {
6909 free(ondisk_path);
6910 continue;
6912 error = got_error_from_errno2("lstat",
6913 ondisk_path);
6914 free(ondisk_path);
6915 goto done;
6917 free(ondisk_path);
6918 if (S_ISDIR(sb.st_mode)) {
6919 error = got_error_msg(GOT_ERR_BAD_PATH,
6920 "reverting directories requires -R option");
6921 goto done;
6926 cpa.patch_script_file = patch_script_file;
6927 cpa.action = "revert";
6928 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6929 pflag ? choose_patch : NULL, &cpa, repo);
6930 done:
6931 if (patch_script_file && fclose(patch_script_file) == EOF &&
6932 error == NULL)
6933 error = got_error_from_errno2("fclose", patch_script_path);
6934 if (repo)
6935 got_repo_close(repo);
6936 if (worktree)
6937 got_worktree_close(worktree);
6938 free(path);
6939 free(cwd);
6940 return error;
6943 __dead static void
6944 usage_commit(void)
6946 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
6947 "[path ...]\n", getprogname());
6948 exit(1);
6951 struct collect_commit_logmsg_arg {
6952 const char *cmdline_log;
6953 const char *prepared_log;
6954 int non_interactive;
6955 const char *editor;
6956 const char *worktree_path;
6957 const char *branch_name;
6958 const char *repo_path;
6959 char *logmsg_path;
6963 static const struct got_error *
6964 read_prepared_logmsg(char **logmsg, const char *path)
6966 const struct got_error *err = NULL;
6967 FILE *f = NULL;
6968 struct stat sb;
6969 size_t r;
6971 *logmsg = NULL;
6972 memset(&sb, 0, sizeof(sb));
6974 f = fopen(path, "r");
6975 if (f == NULL)
6976 return got_error_from_errno2("fopen", path);
6978 if (fstat(fileno(f), &sb) == -1) {
6979 err = got_error_from_errno2("fstat", path);
6980 goto done;
6982 if (sb.st_size == 0) {
6983 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
6984 goto done;
6987 *logmsg = malloc(sb.st_size + 1);
6988 if (*logmsg == NULL) {
6989 err = got_error_from_errno("malloc");
6990 goto done;
6993 r = fread(*logmsg, 1, sb.st_size, f);
6994 if (r != sb.st_size) {
6995 if (ferror(f))
6996 err = got_error_from_errno2("fread", path);
6997 else
6998 err = got_error(GOT_ERR_IO);
6999 goto done;
7001 (*logmsg)[sb.st_size] = '\0';
7002 done:
7003 if (fclose(f) == EOF && err == NULL)
7004 err = got_error_from_errno2("fclose", path);
7005 if (err) {
7006 free(*logmsg);
7007 *logmsg = NULL;
7009 return err;
7013 static const struct got_error *
7014 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7015 void *arg)
7017 char *initial_content = NULL;
7018 struct got_pathlist_entry *pe;
7019 const struct got_error *err = NULL;
7020 char *template = NULL;
7021 struct collect_commit_logmsg_arg *a = arg;
7022 int initial_content_len;
7023 int fd = -1;
7024 size_t len;
7026 /* if a message was specified on the command line, just use it */
7027 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7028 len = strlen(a->cmdline_log) + 1;
7029 *logmsg = malloc(len + 1);
7030 if (*logmsg == NULL)
7031 return got_error_from_errno("malloc");
7032 strlcpy(*logmsg, a->cmdline_log, len);
7033 return NULL;
7034 } else if (a->prepared_log != NULL && a->non_interactive)
7035 return read_prepared_logmsg(logmsg, a->prepared_log);
7037 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7038 return got_error_from_errno("asprintf");
7040 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7041 if (err)
7042 goto done;
7044 if (a->prepared_log) {
7045 char *msg;
7046 err = read_prepared_logmsg(&msg, a->prepared_log);
7047 if (err)
7048 goto done;
7049 if (write(fd, msg, strlen(msg)) == -1) {
7050 err = got_error_from_errno2("write", a->logmsg_path);
7051 free(msg);
7052 goto done;
7054 free(msg);
7057 initial_content_len = asprintf(&initial_content,
7058 "\n# changes to be committed on branch %s:\n",
7059 a->branch_name);
7060 if (initial_content_len == -1) {
7061 err = got_error_from_errno("asprintf");
7062 goto done;
7065 if (write(fd, initial_content, initial_content_len) == -1) {
7066 err = got_error_from_errno2("write", a->logmsg_path);
7067 goto done;
7070 TAILQ_FOREACH(pe, commitable_paths, entry) {
7071 struct got_commitable *ct = pe->data;
7072 dprintf(fd, "# %c %s\n",
7073 got_commitable_get_status(ct),
7074 got_commitable_get_path(ct));
7077 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7078 initial_content_len, a->prepared_log ? 0 : 1);
7079 done:
7080 free(initial_content);
7081 free(template);
7083 if (fd != -1 && close(fd) == -1 && err == NULL)
7084 err = got_error_from_errno2("close", a->logmsg_path);
7086 /* Editor is done; we can now apply unveil(2) */
7087 if (err == NULL)
7088 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7089 if (err) {
7090 free(*logmsg);
7091 *logmsg = NULL;
7093 return err;
7096 static const struct got_error *
7097 cmd_commit(int argc, char *argv[])
7099 const struct got_error *error = NULL;
7100 struct got_worktree *worktree = NULL;
7101 struct got_repository *repo = NULL;
7102 char *cwd = NULL, *id_str = NULL;
7103 struct got_object_id *id = NULL;
7104 const char *logmsg = NULL;
7105 char *prepared_logmsg = NULL;
7106 struct collect_commit_logmsg_arg cl_arg;
7107 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7108 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7109 int allow_bad_symlinks = 0, non_interactive = 0;
7110 struct got_pathlist_head paths;
7112 TAILQ_INIT(&paths);
7113 cl_arg.logmsg_path = NULL;
7115 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7116 switch (ch) {
7117 case 'F':
7118 if (logmsg != NULL)
7119 option_conflict('F', 'm');
7120 prepared_logmsg = realpath(optarg, NULL);
7121 if (prepared_logmsg == NULL)
7122 return got_error_from_errno2("realpath",
7123 optarg);
7124 break;
7125 case 'm':
7126 if (prepared_logmsg)
7127 option_conflict('m', 'F');
7128 logmsg = optarg;
7129 break;
7130 case 'N':
7131 non_interactive = 1;
7132 break;
7133 case 'S':
7134 allow_bad_symlinks = 1;
7135 break;
7136 default:
7137 usage_commit();
7138 /* NOTREACHED */
7142 argc -= optind;
7143 argv += optind;
7145 #ifndef PROFILE
7146 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7147 "unveil", NULL) == -1)
7148 err(1, "pledge");
7149 #endif
7150 cwd = getcwd(NULL, 0);
7151 if (cwd == NULL) {
7152 error = got_error_from_errno("getcwd");
7153 goto done;
7155 error = got_worktree_open(&worktree, cwd);
7156 if (error) {
7157 if (error->code == GOT_ERR_NOT_WORKTREE)
7158 error = wrap_not_worktree_error(error, "commit", cwd);
7159 goto done;
7162 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7163 if (error)
7164 goto done;
7165 if (rebase_in_progress) {
7166 error = got_error(GOT_ERR_REBASING);
7167 goto done;
7170 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7171 worktree);
7172 if (error)
7173 goto done;
7175 error = get_gitconfig_path(&gitconfig_path);
7176 if (error)
7177 goto done;
7178 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7179 gitconfig_path);
7180 if (error != NULL)
7181 goto done;
7183 error = get_author(&author, repo, worktree);
7184 if (error)
7185 return error;
7188 * unveil(2) traverses exec(2); if an editor is used we have
7189 * to apply unveil after the log message has been written.
7191 if (logmsg == NULL || strlen(logmsg) == 0)
7192 error = get_editor(&editor);
7193 else
7194 error = apply_unveil(got_repo_get_path(repo), 0,
7195 got_worktree_get_root_path(worktree));
7196 if (error)
7197 goto done;
7199 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7200 if (error)
7201 goto done;
7203 cl_arg.editor = editor;
7204 cl_arg.cmdline_log = logmsg;
7205 cl_arg.prepared_log = prepared_logmsg;
7206 cl_arg.non_interactive = non_interactive;
7207 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7208 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7209 if (!histedit_in_progress) {
7210 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7211 error = got_error(GOT_ERR_COMMIT_BRANCH);
7212 goto done;
7214 cl_arg.branch_name += 11;
7216 cl_arg.repo_path = got_repo_get_path(repo);
7217 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7218 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7219 print_status, NULL, repo);
7220 if (error) {
7221 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7222 cl_arg.logmsg_path != NULL)
7223 preserve_logmsg = 1;
7224 goto done;
7227 error = got_object_id_str(&id_str, id);
7228 if (error)
7229 goto done;
7230 printf("Created commit %s\n", id_str);
7231 done:
7232 if (preserve_logmsg) {
7233 fprintf(stderr, "%s: log message preserved in %s\n",
7234 getprogname(), cl_arg.logmsg_path);
7235 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7236 error == NULL)
7237 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7238 free(cl_arg.logmsg_path);
7239 if (repo)
7240 got_repo_close(repo);
7241 if (worktree)
7242 got_worktree_close(worktree);
7243 free(cwd);
7244 free(id_str);
7245 free(gitconfig_path);
7246 free(editor);
7247 free(author);
7248 free(prepared_logmsg);
7249 return error;
7252 __dead static void
7253 usage_cherrypick(void)
7255 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7256 exit(1);
7259 static const struct got_error *
7260 cmd_cherrypick(int argc, char *argv[])
7262 const struct got_error *error = NULL;
7263 struct got_worktree *worktree = NULL;
7264 struct got_repository *repo = NULL;
7265 char *cwd = NULL, *commit_id_str = NULL;
7266 struct got_object_id *commit_id = NULL;
7267 struct got_commit_object *commit = NULL;
7268 struct got_object_qid *pid;
7269 struct got_reference *head_ref = NULL;
7270 int ch;
7271 struct got_update_progress_arg upa;
7273 while ((ch = getopt(argc, argv, "")) != -1) {
7274 switch (ch) {
7275 default:
7276 usage_cherrypick();
7277 /* NOTREACHED */
7281 argc -= optind;
7282 argv += optind;
7284 #ifndef PROFILE
7285 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7286 "unveil", NULL) == -1)
7287 err(1, "pledge");
7288 #endif
7289 if (argc != 1)
7290 usage_cherrypick();
7292 cwd = getcwd(NULL, 0);
7293 if (cwd == NULL) {
7294 error = got_error_from_errno("getcwd");
7295 goto done;
7297 error = got_worktree_open(&worktree, cwd);
7298 if (error) {
7299 if (error->code == GOT_ERR_NOT_WORKTREE)
7300 error = wrap_not_worktree_error(error, "cherrypick",
7301 cwd);
7302 goto done;
7305 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7306 NULL);
7307 if (error != NULL)
7308 goto done;
7310 error = apply_unveil(got_repo_get_path(repo), 0,
7311 got_worktree_get_root_path(worktree));
7312 if (error)
7313 goto done;
7315 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7316 GOT_OBJ_TYPE_COMMIT, repo);
7317 if (error != NULL) {
7318 struct got_reference *ref;
7319 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7320 goto done;
7321 error = got_ref_open(&ref, repo, argv[0], 0);
7322 if (error != NULL)
7323 goto done;
7324 error = got_ref_resolve(&commit_id, repo, ref);
7325 got_ref_close(ref);
7326 if (error != NULL)
7327 goto done;
7329 error = got_object_id_str(&commit_id_str, commit_id);
7330 if (error)
7331 goto done;
7333 error = got_ref_open(&head_ref, repo,
7334 got_worktree_get_head_ref_name(worktree), 0);
7335 if (error != NULL)
7336 goto done;
7338 error = check_same_branch(commit_id, head_ref, NULL, repo);
7339 if (error) {
7340 if (error->code != GOT_ERR_ANCESTRY)
7341 goto done;
7342 error = NULL;
7343 } else {
7344 error = got_error(GOT_ERR_SAME_BRANCH);
7345 goto done;
7348 error = got_object_open_as_commit(&commit, repo, commit_id);
7349 if (error)
7350 goto done;
7351 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7352 memset(&upa, 0, sizeof(upa));
7353 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7354 commit_id, repo, update_progress, &upa, check_cancelled,
7355 NULL);
7356 if (error != NULL)
7357 goto done;
7359 if (upa.did_something)
7360 printf("Merged commit %s\n", commit_id_str);
7361 print_update_progress_stats(&upa);
7362 done:
7363 if (commit)
7364 got_object_commit_close(commit);
7365 free(commit_id_str);
7366 if (head_ref)
7367 got_ref_close(head_ref);
7368 if (worktree)
7369 got_worktree_close(worktree);
7370 if (repo)
7371 got_repo_close(repo);
7372 return error;
7375 __dead static void
7376 usage_backout(void)
7378 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7379 exit(1);
7382 static const struct got_error *
7383 cmd_backout(int argc, char *argv[])
7385 const struct got_error *error = NULL;
7386 struct got_worktree *worktree = NULL;
7387 struct got_repository *repo = NULL;
7388 char *cwd = NULL, *commit_id_str = NULL;
7389 struct got_object_id *commit_id = NULL;
7390 struct got_commit_object *commit = NULL;
7391 struct got_object_qid *pid;
7392 struct got_reference *head_ref = NULL;
7393 int ch;
7394 struct got_update_progress_arg upa;
7396 while ((ch = getopt(argc, argv, "")) != -1) {
7397 switch (ch) {
7398 default:
7399 usage_backout();
7400 /* NOTREACHED */
7404 argc -= optind;
7405 argv += optind;
7407 #ifndef PROFILE
7408 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7409 "unveil", NULL) == -1)
7410 err(1, "pledge");
7411 #endif
7412 if (argc != 1)
7413 usage_backout();
7415 cwd = getcwd(NULL, 0);
7416 if (cwd == NULL) {
7417 error = got_error_from_errno("getcwd");
7418 goto done;
7420 error = got_worktree_open(&worktree, cwd);
7421 if (error) {
7422 if (error->code == GOT_ERR_NOT_WORKTREE)
7423 error = wrap_not_worktree_error(error, "backout", cwd);
7424 goto done;
7427 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7428 NULL);
7429 if (error != NULL)
7430 goto done;
7432 error = apply_unveil(got_repo_get_path(repo), 0,
7433 got_worktree_get_root_path(worktree));
7434 if (error)
7435 goto done;
7437 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7438 GOT_OBJ_TYPE_COMMIT, repo);
7439 if (error != NULL) {
7440 struct got_reference *ref;
7441 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7442 goto done;
7443 error = got_ref_open(&ref, repo, argv[0], 0);
7444 if (error != NULL)
7445 goto done;
7446 error = got_ref_resolve(&commit_id, repo, ref);
7447 got_ref_close(ref);
7448 if (error != NULL)
7449 goto done;
7451 error = got_object_id_str(&commit_id_str, commit_id);
7452 if (error)
7453 goto done;
7455 error = got_ref_open(&head_ref, repo,
7456 got_worktree_get_head_ref_name(worktree), 0);
7457 if (error != NULL)
7458 goto done;
7460 error = check_same_branch(commit_id, head_ref, NULL, repo);
7461 if (error)
7462 goto done;
7464 error = got_object_open_as_commit(&commit, repo, commit_id);
7465 if (error)
7466 goto done;
7467 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7468 if (pid == NULL) {
7469 error = got_error(GOT_ERR_ROOT_COMMIT);
7470 goto done;
7473 memset(&upa, 0, sizeof(upa));
7474 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7475 update_progress, &upa, check_cancelled, NULL);
7476 if (error != NULL)
7477 goto done;
7479 if (upa.did_something)
7480 printf("Backed out commit %s\n", commit_id_str);
7481 print_update_progress_stats(&upa);
7482 done:
7483 if (commit)
7484 got_object_commit_close(commit);
7485 free(commit_id_str);
7486 if (head_ref)
7487 got_ref_close(head_ref);
7488 if (worktree)
7489 got_worktree_close(worktree);
7490 if (repo)
7491 got_repo_close(repo);
7492 return error;
7495 __dead static void
7496 usage_rebase(void)
7498 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7499 getprogname());
7500 exit(1);
7503 void
7504 trim_logmsg(char *logmsg, int limit)
7506 char *nl;
7507 size_t len;
7509 len = strlen(logmsg);
7510 if (len > limit)
7511 len = limit;
7512 logmsg[len] = '\0';
7513 nl = strchr(logmsg, '\n');
7514 if (nl)
7515 *nl = '\0';
7518 static const struct got_error *
7519 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7521 const struct got_error *err;
7522 char *logmsg0 = NULL;
7523 const char *s;
7525 err = got_object_commit_get_logmsg(&logmsg0, commit);
7526 if (err)
7527 return err;
7529 s = logmsg0;
7530 while (isspace((unsigned char)s[0]))
7531 s++;
7533 *logmsg = strdup(s);
7534 if (*logmsg == NULL) {
7535 err = got_error_from_errno("strdup");
7536 goto done;
7539 trim_logmsg(*logmsg, limit);
7540 done:
7541 free(logmsg0);
7542 return err;
7545 static const struct got_error *
7546 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7548 const struct got_error *err;
7549 struct got_commit_object *commit = NULL;
7550 char *id_str = NULL, *logmsg = NULL;
7552 err = got_object_open_as_commit(&commit, repo, id);
7553 if (err)
7554 return err;
7556 err = got_object_id_str(&id_str, id);
7557 if (err)
7558 goto done;
7560 id_str[12] = '\0';
7562 err = get_short_logmsg(&logmsg, 42, commit);
7563 if (err)
7564 goto done;
7566 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7567 done:
7568 free(id_str);
7569 got_object_commit_close(commit);
7570 free(logmsg);
7571 return err;
7574 static const struct got_error *
7575 show_rebase_progress(struct got_commit_object *commit,
7576 struct got_object_id *old_id, struct got_object_id *new_id)
7578 const struct got_error *err;
7579 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7581 err = got_object_id_str(&old_id_str, old_id);
7582 if (err)
7583 goto done;
7585 if (new_id) {
7586 err = got_object_id_str(&new_id_str, new_id);
7587 if (err)
7588 goto done;
7591 old_id_str[12] = '\0';
7592 if (new_id_str)
7593 new_id_str[12] = '\0';
7595 err = get_short_logmsg(&logmsg, 42, commit);
7596 if (err)
7597 goto done;
7599 printf("%s -> %s: %s\n", old_id_str,
7600 new_id_str ? new_id_str : "no-op change", logmsg);
7601 done:
7602 free(old_id_str);
7603 free(new_id_str);
7604 free(logmsg);
7605 return err;
7608 static const struct got_error *
7609 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7610 struct got_reference *branch, struct got_reference *new_base_branch,
7611 struct got_reference *tmp_branch, struct got_repository *repo)
7613 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7614 return got_worktree_rebase_complete(worktree, fileindex,
7615 new_base_branch, tmp_branch, branch, repo);
7618 static const struct got_error *
7619 rebase_commit(struct got_pathlist_head *merged_paths,
7620 struct got_worktree *worktree, struct got_fileindex *fileindex,
7621 struct got_reference *tmp_branch,
7622 struct got_object_id *commit_id, struct got_repository *repo)
7624 const struct got_error *error;
7625 struct got_commit_object *commit;
7626 struct got_object_id *new_commit_id;
7628 error = got_object_open_as_commit(&commit, repo, commit_id);
7629 if (error)
7630 return error;
7632 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7633 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7634 if (error) {
7635 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7636 goto done;
7637 error = show_rebase_progress(commit, commit_id, NULL);
7638 } else {
7639 error = show_rebase_progress(commit, commit_id, new_commit_id);
7640 free(new_commit_id);
7642 done:
7643 got_object_commit_close(commit);
7644 return error;
7647 struct check_path_prefix_arg {
7648 const char *path_prefix;
7649 size_t len;
7650 int errcode;
7653 static const struct got_error *
7654 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7655 struct got_blob_object *blob2, struct got_object_id *id1,
7656 struct got_object_id *id2, const char *path1, const char *path2,
7657 mode_t mode1, mode_t mode2, struct got_repository *repo)
7659 struct check_path_prefix_arg *a = arg;
7661 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7662 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7663 return got_error(a->errcode);
7665 return NULL;
7668 static const struct got_error *
7669 check_path_prefix(struct got_object_id *parent_id,
7670 struct got_object_id *commit_id, const char *path_prefix,
7671 int errcode, struct got_repository *repo)
7673 const struct got_error *err;
7674 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7675 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7676 struct check_path_prefix_arg cpp_arg;
7678 if (got_path_is_root_dir(path_prefix))
7679 return NULL;
7681 err = got_object_open_as_commit(&commit, repo, commit_id);
7682 if (err)
7683 goto done;
7685 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7686 if (err)
7687 goto done;
7689 err = got_object_open_as_tree(&tree1, repo,
7690 got_object_commit_get_tree_id(parent_commit));
7691 if (err)
7692 goto done;
7694 err = got_object_open_as_tree(&tree2, repo,
7695 got_object_commit_get_tree_id(commit));
7696 if (err)
7697 goto done;
7699 cpp_arg.path_prefix = path_prefix;
7700 while (cpp_arg.path_prefix[0] == '/')
7701 cpp_arg.path_prefix++;
7702 cpp_arg.len = strlen(cpp_arg.path_prefix);
7703 cpp_arg.errcode = errcode;
7704 err = got_diff_tree(tree1, tree2, "", "", repo,
7705 check_path_prefix_in_diff, &cpp_arg, 0);
7706 done:
7707 if (tree1)
7708 got_object_tree_close(tree1);
7709 if (tree2)
7710 got_object_tree_close(tree2);
7711 if (commit)
7712 got_object_commit_close(commit);
7713 if (parent_commit)
7714 got_object_commit_close(parent_commit);
7715 return err;
7718 static const struct got_error *
7719 collect_commits(struct got_object_id_queue *commits,
7720 struct got_object_id *initial_commit_id,
7721 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7722 const char *path_prefix, int path_prefix_errcode,
7723 struct got_repository *repo)
7725 const struct got_error *err = NULL;
7726 struct got_commit_graph *graph = NULL;
7727 struct got_object_id *parent_id = NULL;
7728 struct got_object_qid *qid;
7729 struct got_object_id *commit_id = initial_commit_id;
7731 err = got_commit_graph_open(&graph, "/", 1);
7732 if (err)
7733 return err;
7735 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7736 check_cancelled, NULL);
7737 if (err)
7738 goto done;
7739 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7740 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7741 check_cancelled, NULL);
7742 if (err) {
7743 if (err->code == GOT_ERR_ITER_COMPLETED) {
7744 err = got_error_msg(GOT_ERR_ANCESTRY,
7745 "ran out of commits to rebase before "
7746 "youngest common ancestor commit has "
7747 "been reached?!?");
7749 goto done;
7750 } else {
7751 err = check_path_prefix(parent_id, commit_id,
7752 path_prefix, path_prefix_errcode, repo);
7753 if (err)
7754 goto done;
7756 err = got_object_qid_alloc(&qid, commit_id);
7757 if (err)
7758 goto done;
7759 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7760 commit_id = parent_id;
7763 done:
7764 got_commit_graph_close(graph);
7765 return err;
7768 static const struct got_error *
7769 cmd_rebase(int argc, char *argv[])
7771 const struct got_error *error = NULL;
7772 struct got_worktree *worktree = NULL;
7773 struct got_repository *repo = NULL;
7774 struct got_fileindex *fileindex = NULL;
7775 char *cwd = NULL;
7776 struct got_reference *branch = NULL;
7777 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7778 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7779 struct got_object_id *resume_commit_id = NULL;
7780 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7781 struct got_commit_object *commit = NULL;
7782 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7783 int histedit_in_progress = 0;
7784 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7785 struct got_object_id_queue commits;
7786 struct got_pathlist_head merged_paths;
7787 const struct got_object_id_queue *parent_ids;
7788 struct got_object_qid *qid, *pid;
7790 SIMPLEQ_INIT(&commits);
7791 TAILQ_INIT(&merged_paths);
7793 while ((ch = getopt(argc, argv, "ac")) != -1) {
7794 switch (ch) {
7795 case 'a':
7796 abort_rebase = 1;
7797 break;
7798 case 'c':
7799 continue_rebase = 1;
7800 break;
7801 default:
7802 usage_rebase();
7803 /* NOTREACHED */
7807 argc -= optind;
7808 argv += optind;
7810 #ifndef PROFILE
7811 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7812 "unveil", NULL) == -1)
7813 err(1, "pledge");
7814 #endif
7815 if (abort_rebase && continue_rebase)
7816 usage_rebase();
7817 else if (abort_rebase || continue_rebase) {
7818 if (argc != 0)
7819 usage_rebase();
7820 } else if (argc != 1)
7821 usage_rebase();
7823 cwd = getcwd(NULL, 0);
7824 if (cwd == NULL) {
7825 error = got_error_from_errno("getcwd");
7826 goto done;
7828 error = got_worktree_open(&worktree, cwd);
7829 if (error) {
7830 if (error->code == GOT_ERR_NOT_WORKTREE)
7831 error = wrap_not_worktree_error(error, "rebase", cwd);
7832 goto done;
7835 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7836 NULL);
7837 if (error != NULL)
7838 goto done;
7840 error = apply_unveil(got_repo_get_path(repo), 0,
7841 got_worktree_get_root_path(worktree));
7842 if (error)
7843 goto done;
7845 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7846 worktree);
7847 if (error)
7848 goto done;
7849 if (histedit_in_progress) {
7850 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7851 goto done;
7854 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7855 if (error)
7856 goto done;
7858 if (abort_rebase) {
7859 struct got_update_progress_arg upa;
7860 if (!rebase_in_progress) {
7861 error = got_error(GOT_ERR_NOT_REBASING);
7862 goto done;
7864 error = got_worktree_rebase_continue(&resume_commit_id,
7865 &new_base_branch, &tmp_branch, &branch, &fileindex,
7866 worktree, repo);
7867 if (error)
7868 goto done;
7869 printf("Switching work tree to %s\n",
7870 got_ref_get_symref_target(new_base_branch));
7871 memset(&upa, 0, sizeof(upa));
7872 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7873 new_base_branch, update_progress, &upa);
7874 if (error)
7875 goto done;
7876 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7877 print_update_progress_stats(&upa);
7878 goto done; /* nothing else to do */
7881 if (continue_rebase) {
7882 if (!rebase_in_progress) {
7883 error = got_error(GOT_ERR_NOT_REBASING);
7884 goto done;
7886 error = got_worktree_rebase_continue(&resume_commit_id,
7887 &new_base_branch, &tmp_branch, &branch, &fileindex,
7888 worktree, repo);
7889 if (error)
7890 goto done;
7892 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7893 resume_commit_id, repo);
7894 if (error)
7895 goto done;
7897 yca_id = got_object_id_dup(resume_commit_id);
7898 if (yca_id == NULL) {
7899 error = got_error_from_errno("got_object_id_dup");
7900 goto done;
7902 } else {
7903 error = got_ref_open(&branch, repo, argv[0], 0);
7904 if (error != NULL)
7905 goto done;
7908 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7909 if (error)
7910 goto done;
7912 if (!continue_rebase) {
7913 struct got_object_id *base_commit_id;
7915 base_commit_id = got_worktree_get_base_commit_id(worktree);
7916 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7917 base_commit_id, branch_head_commit_id, repo,
7918 check_cancelled, NULL);
7919 if (error)
7920 goto done;
7921 if (yca_id == NULL) {
7922 error = got_error_msg(GOT_ERR_ANCESTRY,
7923 "specified branch shares no common ancestry "
7924 "with work tree's branch");
7925 goto done;
7928 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7929 if (error) {
7930 if (error->code != GOT_ERR_ANCESTRY)
7931 goto done;
7932 error = NULL;
7933 } else {
7934 static char msg[128];
7935 snprintf(msg, sizeof(msg),
7936 "%s is already based on %s",
7937 got_ref_get_name(branch),
7938 got_worktree_get_head_ref_name(worktree));
7939 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
7940 goto done;
7942 error = got_worktree_rebase_prepare(&new_base_branch,
7943 &tmp_branch, &fileindex, worktree, branch, repo);
7944 if (error)
7945 goto done;
7948 commit_id = branch_head_commit_id;
7949 error = got_object_open_as_commit(&commit, repo, commit_id);
7950 if (error)
7951 goto done;
7953 parent_ids = got_object_commit_get_parent_ids(commit);
7954 pid = SIMPLEQ_FIRST(parent_ids);
7955 if (pid == NULL) {
7956 if (!continue_rebase) {
7957 struct got_update_progress_arg upa;
7958 memset(&upa, 0, sizeof(upa));
7959 error = got_worktree_rebase_abort(worktree, fileindex,
7960 repo, new_base_branch, update_progress, &upa);
7961 if (error)
7962 goto done;
7963 printf("Rebase of %s aborted\n",
7964 got_ref_get_name(branch));
7965 print_update_progress_stats(&upa);
7968 error = got_error(GOT_ERR_EMPTY_REBASE);
7969 goto done;
7971 error = collect_commits(&commits, commit_id, pid->id,
7972 yca_id, got_worktree_get_path_prefix(worktree),
7973 GOT_ERR_REBASE_PATH, repo);
7974 got_object_commit_close(commit);
7975 commit = NULL;
7976 if (error)
7977 goto done;
7979 if (SIMPLEQ_EMPTY(&commits)) {
7980 if (continue_rebase) {
7981 error = rebase_complete(worktree, fileindex,
7982 branch, new_base_branch, tmp_branch, repo);
7983 goto done;
7984 } else {
7985 /* Fast-forward the reference of the branch. */
7986 struct got_object_id *new_head_commit_id;
7987 char *id_str;
7988 error = got_ref_resolve(&new_head_commit_id, repo,
7989 new_base_branch);
7990 if (error)
7991 goto done;
7992 error = got_object_id_str(&id_str, new_head_commit_id);
7993 printf("Forwarding %s to commit %s\n",
7994 got_ref_get_name(branch), id_str);
7995 free(id_str);
7996 error = got_ref_change_ref(branch,
7997 new_head_commit_id);
7998 if (error)
7999 goto done;
8003 pid = NULL;
8004 SIMPLEQ_FOREACH(qid, &commits, entry) {
8005 struct got_update_progress_arg upa;
8007 commit_id = qid->id;
8008 parent_id = pid ? pid->id : yca_id;
8009 pid = qid;
8011 memset(&upa, 0, sizeof(upa));
8012 error = got_worktree_rebase_merge_files(&merged_paths,
8013 worktree, fileindex, parent_id, commit_id, repo,
8014 update_progress, &upa, check_cancelled, NULL);
8015 if (error)
8016 goto done;
8018 print_update_progress_stats(&upa);
8019 if (upa.conflicts > 0)
8020 rebase_status = GOT_STATUS_CONFLICT;
8022 if (rebase_status == GOT_STATUS_CONFLICT) {
8023 error = show_rebase_merge_conflict(qid->id, repo);
8024 if (error)
8025 goto done;
8026 got_worktree_rebase_pathlist_free(&merged_paths);
8027 break;
8030 error = rebase_commit(&merged_paths, worktree, fileindex,
8031 tmp_branch, commit_id, repo);
8032 got_worktree_rebase_pathlist_free(&merged_paths);
8033 if (error)
8034 goto done;
8037 if (rebase_status == GOT_STATUS_CONFLICT) {
8038 error = got_worktree_rebase_postpone(worktree, fileindex);
8039 if (error)
8040 goto done;
8041 error = got_error_msg(GOT_ERR_CONFLICTS,
8042 "conflicts must be resolved before rebasing can continue");
8043 } else
8044 error = rebase_complete(worktree, fileindex, branch,
8045 new_base_branch, tmp_branch, repo);
8046 done:
8047 got_object_id_queue_free(&commits);
8048 free(branch_head_commit_id);
8049 free(resume_commit_id);
8050 free(yca_id);
8051 if (commit)
8052 got_object_commit_close(commit);
8053 if (branch)
8054 got_ref_close(branch);
8055 if (new_base_branch)
8056 got_ref_close(new_base_branch);
8057 if (tmp_branch)
8058 got_ref_close(tmp_branch);
8059 if (worktree)
8060 got_worktree_close(worktree);
8061 if (repo)
8062 got_repo_close(repo);
8063 return error;
8066 __dead static void
8067 usage_histedit(void)
8069 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] [-F histedit-script] [-m]\n",
8070 getprogname());
8071 exit(1);
8074 #define GOT_HISTEDIT_PICK 'p'
8075 #define GOT_HISTEDIT_EDIT 'e'
8076 #define GOT_HISTEDIT_FOLD 'f'
8077 #define GOT_HISTEDIT_DROP 'd'
8078 #define GOT_HISTEDIT_MESG 'm'
8080 static struct got_histedit_cmd {
8081 unsigned char code;
8082 const char *name;
8083 const char *desc;
8084 } got_histedit_cmds[] = {
8085 { GOT_HISTEDIT_PICK, "pick", "use commit" },
8086 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
8087 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
8088 "be used" },
8089 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
8090 { GOT_HISTEDIT_MESG, "mesg",
8091 "single-line log message for commit above (open editor if empty)" },
8094 struct got_histedit_list_entry {
8095 TAILQ_ENTRY(got_histedit_list_entry) entry;
8096 struct got_object_id *commit_id;
8097 const struct got_histedit_cmd *cmd;
8098 char *logmsg;
8100 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
8102 static const struct got_error *
8103 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
8104 FILE *f, struct got_repository *repo)
8106 const struct got_error *err = NULL;
8107 char *logmsg = NULL, *id_str = NULL;
8108 struct got_commit_object *commit = NULL;
8109 int n;
8111 err = got_object_open_as_commit(&commit, repo, commit_id);
8112 if (err)
8113 goto done;
8115 err = get_short_logmsg(&logmsg, 34, commit);
8116 if (err)
8117 goto done;
8119 err = got_object_id_str(&id_str, commit_id);
8120 if (err)
8121 goto done;
8123 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
8124 if (n < 0)
8125 err = got_ferror(f, GOT_ERR_IO);
8126 done:
8127 if (commit)
8128 got_object_commit_close(commit);
8129 free(id_str);
8130 free(logmsg);
8131 return err;
8134 static const struct got_error *
8135 histedit_write_commit_list(struct got_object_id_queue *commits,
8136 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
8138 const struct got_error *err = NULL;
8139 struct got_object_qid *qid;
8140 const char *histedit_cmd = NULL;
8142 if (SIMPLEQ_EMPTY(commits))
8143 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8145 SIMPLEQ_FOREACH(qid, commits, entry) {
8146 histedit_cmd = got_histedit_cmds[0].name;
8147 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
8148 histedit_cmd = "fold";
8149 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
8150 if (err)
8151 break;
8152 if (edit_logmsg_only) {
8153 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
8154 if (n < 0) {
8155 err = got_ferror(f, GOT_ERR_IO);
8156 break;
8161 return err;
8164 static const struct got_error *
8165 write_cmd_list(FILE *f, const char *branch_name,
8166 struct got_object_id_queue *commits)
8168 const struct got_error *err = NULL;
8169 size_t i;
8170 int n;
8171 char *id_str;
8172 struct got_object_qid *qid;
8174 qid = SIMPLEQ_FIRST(commits);
8175 err = got_object_id_str(&id_str, qid->id);
8176 if (err)
8177 return err;
8179 n = fprintf(f,
8180 "# Editing the history of branch '%s' starting at\n"
8181 "# commit %s\n"
8182 "# Commits will be processed in order from top to "
8183 "bottom of this file.\n", branch_name, id_str);
8184 if (n < 0) {
8185 err = got_ferror(f, GOT_ERR_IO);
8186 goto done;
8189 n = fprintf(f, "# Available histedit commands:\n");
8190 if (n < 0) {
8191 err = got_ferror(f, GOT_ERR_IO);
8192 goto done;
8195 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8196 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8197 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8198 cmd->desc);
8199 if (n < 0) {
8200 err = got_ferror(f, GOT_ERR_IO);
8201 break;
8204 done:
8205 free(id_str);
8206 return err;
8209 static const struct got_error *
8210 histedit_syntax_error(int lineno)
8212 static char msg[42];
8213 int ret;
8215 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8216 lineno);
8217 if (ret == -1 || ret >= sizeof(msg))
8218 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8220 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8223 static const struct got_error *
8224 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8225 char *logmsg, struct got_repository *repo)
8227 const struct got_error *err;
8228 struct got_commit_object *folded_commit = NULL;
8229 char *id_str, *folded_logmsg = NULL;
8231 err = got_object_id_str(&id_str, hle->commit_id);
8232 if (err)
8233 return err;
8235 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8236 if (err)
8237 goto done;
8239 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8240 if (err)
8241 goto done;
8242 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8243 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8244 folded_logmsg) == -1) {
8245 err = got_error_from_errno("asprintf");
8247 done:
8248 if (folded_commit)
8249 got_object_commit_close(folded_commit);
8250 free(id_str);
8251 free(folded_logmsg);
8252 return err;
8255 static struct got_histedit_list_entry *
8256 get_folded_commits(struct got_histedit_list_entry *hle)
8258 struct got_histedit_list_entry *prev, *folded = NULL;
8260 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8261 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8262 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8263 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8264 folded = prev;
8265 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8268 return folded;
8271 static const struct got_error *
8272 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8273 struct got_repository *repo)
8275 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8276 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8277 const struct got_error *err = NULL;
8278 struct got_commit_object *commit = NULL;
8279 int logmsg_len;
8280 int fd;
8281 struct got_histedit_list_entry *folded = NULL;
8283 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8284 if (err)
8285 return err;
8287 folded = get_folded_commits(hle);
8288 if (folded) {
8289 while (folded != hle) {
8290 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8291 folded = TAILQ_NEXT(folded, entry);
8292 continue;
8294 err = append_folded_commit_msg(&new_msg, folded,
8295 logmsg, repo);
8296 if (err)
8297 goto done;
8298 free(logmsg);
8299 logmsg = new_msg;
8300 folded = TAILQ_NEXT(folded, entry);
8304 err = got_object_id_str(&id_str, hle->commit_id);
8305 if (err)
8306 goto done;
8307 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8308 if (err)
8309 goto done;
8310 logmsg_len = asprintf(&new_msg,
8311 "%s\n# original log message of commit %s: %s",
8312 logmsg ? logmsg : "", id_str, orig_logmsg);
8313 if (logmsg_len == -1) {
8314 err = got_error_from_errno("asprintf");
8315 goto done;
8317 free(logmsg);
8318 logmsg = new_msg;
8320 err = got_object_id_str(&id_str, hle->commit_id);
8321 if (err)
8322 goto done;
8324 err = got_opentemp_named_fd(&logmsg_path, &fd,
8325 GOT_TMPDIR_STR "/got-logmsg");
8326 if (err)
8327 goto done;
8329 write(fd, logmsg, logmsg_len);
8330 close(fd);
8332 err = get_editor(&editor);
8333 if (err)
8334 goto done;
8336 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8337 logmsg_len, 0);
8338 if (err) {
8339 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8340 goto done;
8341 err = NULL;
8342 hle->logmsg = strdup(new_msg);
8343 if (hle->logmsg == NULL)
8344 err = got_error_from_errno("strdup");
8346 done:
8347 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8348 err = got_error_from_errno2("unlink", logmsg_path);
8349 free(logmsg_path);
8350 free(logmsg);
8351 free(orig_logmsg);
8352 free(editor);
8353 if (commit)
8354 got_object_commit_close(commit);
8355 return err;
8358 static const struct got_error *
8359 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8360 FILE *f, struct got_repository *repo)
8362 const struct got_error *err = NULL;
8363 char *line = NULL, *p, *end;
8364 size_t i, size;
8365 ssize_t len;
8366 int lineno = 0;
8367 const struct got_histedit_cmd *cmd;
8368 struct got_object_id *commit_id = NULL;
8369 struct got_histedit_list_entry *hle = NULL;
8371 for (;;) {
8372 len = getline(&line, &size, f);
8373 if (len == -1) {
8374 const struct got_error *getline_err;
8375 if (feof(f))
8376 break;
8377 getline_err = got_error_from_errno("getline");
8378 err = got_ferror(f, getline_err->code);
8379 break;
8381 lineno++;
8382 p = line;
8383 while (isspace((unsigned char)p[0]))
8384 p++;
8385 if (p[0] == '#' || p[0] == '\0') {
8386 free(line);
8387 line = NULL;
8388 continue;
8390 cmd = NULL;
8391 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8392 cmd = &got_histedit_cmds[i];
8393 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8394 isspace((unsigned char)p[strlen(cmd->name)])) {
8395 p += strlen(cmd->name);
8396 break;
8398 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8399 p++;
8400 break;
8403 if (i == nitems(got_histedit_cmds)) {
8404 err = histedit_syntax_error(lineno);
8405 break;
8407 while (isspace((unsigned char)p[0]))
8408 p++;
8409 if (cmd->code == GOT_HISTEDIT_MESG) {
8410 if (hle == NULL || hle->logmsg != NULL) {
8411 err = got_error(GOT_ERR_HISTEDIT_CMD);
8412 break;
8414 if (p[0] == '\0') {
8415 err = histedit_edit_logmsg(hle, repo);
8416 if (err)
8417 break;
8418 } else {
8419 hle->logmsg = strdup(p);
8420 if (hle->logmsg == NULL) {
8421 err = got_error_from_errno("strdup");
8422 break;
8425 free(line);
8426 line = NULL;
8427 continue;
8428 } else {
8429 end = p;
8430 while (end[0] && !isspace((unsigned char)end[0]))
8431 end++;
8432 *end = '\0';
8434 err = got_object_resolve_id_str(&commit_id, repo, p);
8435 if (err) {
8436 /* override error code */
8437 err = histedit_syntax_error(lineno);
8438 break;
8441 hle = malloc(sizeof(*hle));
8442 if (hle == NULL) {
8443 err = got_error_from_errno("malloc");
8444 break;
8446 hle->cmd = cmd;
8447 hle->commit_id = commit_id;
8448 hle->logmsg = NULL;
8449 commit_id = NULL;
8450 free(line);
8451 line = NULL;
8452 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8455 free(line);
8456 free(commit_id);
8457 return err;
8460 static const struct got_error *
8461 histedit_check_script(struct got_histedit_list *histedit_cmds,
8462 struct got_object_id_queue *commits, struct got_repository *repo)
8464 const struct got_error *err = NULL;
8465 struct got_object_qid *qid;
8466 struct got_histedit_list_entry *hle;
8467 static char msg[92];
8468 char *id_str;
8470 if (TAILQ_EMPTY(histedit_cmds))
8471 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8472 "histedit script contains no commands");
8473 if (SIMPLEQ_EMPTY(commits))
8474 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8476 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8477 struct got_histedit_list_entry *hle2;
8478 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8479 if (hle == hle2)
8480 continue;
8481 if (got_object_id_cmp(hle->commit_id,
8482 hle2->commit_id) != 0)
8483 continue;
8484 err = got_object_id_str(&id_str, hle->commit_id);
8485 if (err)
8486 return err;
8487 snprintf(msg, sizeof(msg), "commit %s is listed "
8488 "more than once in histedit script", id_str);
8489 free(id_str);
8490 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8494 SIMPLEQ_FOREACH(qid, commits, entry) {
8495 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8496 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8497 break;
8499 if (hle == NULL) {
8500 err = got_object_id_str(&id_str, qid->id);
8501 if (err)
8502 return err;
8503 snprintf(msg, sizeof(msg),
8504 "commit %s missing from histedit script", id_str);
8505 free(id_str);
8506 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8510 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8511 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8512 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8513 "last commit in histedit script cannot be folded");
8515 return NULL;
8518 static const struct got_error *
8519 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8520 const char *path, struct got_object_id_queue *commits,
8521 struct got_repository *repo)
8523 const struct got_error *err = NULL;
8524 char *editor;
8525 FILE *f = NULL;
8527 err = get_editor(&editor);
8528 if (err)
8529 return err;
8531 if (spawn_editor(editor, path) == -1) {
8532 err = got_error_from_errno("failed spawning editor");
8533 goto done;
8536 f = fopen(path, "r");
8537 if (f == NULL) {
8538 err = got_error_from_errno("fopen");
8539 goto done;
8541 err = histedit_parse_list(histedit_cmds, f, repo);
8542 if (err)
8543 goto done;
8545 err = histedit_check_script(histedit_cmds, commits, repo);
8546 done:
8547 if (f && fclose(f) == EOF && err == NULL)
8548 err = got_error_from_errno("fclose");
8549 free(editor);
8550 return err;
8553 static const struct got_error *
8554 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8555 struct got_object_id_queue *, const char *, const char *,
8556 struct got_repository *);
8558 static const struct got_error *
8559 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8560 struct got_object_id_queue *commits, const char *branch_name,
8561 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8563 const struct got_error *err;
8564 FILE *f = NULL;
8565 char *path = NULL;
8567 err = got_opentemp_named(&path, &f, "got-histedit");
8568 if (err)
8569 return err;
8571 err = write_cmd_list(f, branch_name, commits);
8572 if (err)
8573 goto done;
8575 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8576 fold_only, repo);
8577 if (err)
8578 goto done;
8580 if (edit_logmsg_only || fold_only) {
8581 rewind(f);
8582 err = histedit_parse_list(histedit_cmds, f, repo);
8583 } else {
8584 if (fclose(f) == EOF) {
8585 err = got_error_from_errno("fclose");
8586 goto done;
8588 f = NULL;
8589 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8590 if (err) {
8591 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8592 err->code != GOT_ERR_HISTEDIT_CMD)
8593 goto done;
8594 err = histedit_edit_list_retry(histedit_cmds, err,
8595 commits, path, branch_name, repo);
8598 done:
8599 if (f && fclose(f) == EOF && err == NULL)
8600 err = got_error_from_errno("fclose");
8601 if (path && unlink(path) != 0 && err == NULL)
8602 err = got_error_from_errno2("unlink", path);
8603 free(path);
8604 return err;
8607 static const struct got_error *
8608 histedit_save_list(struct got_histedit_list *histedit_cmds,
8609 struct got_worktree *worktree, struct got_repository *repo)
8611 const struct got_error *err = NULL;
8612 char *path = NULL;
8613 FILE *f = NULL;
8614 struct got_histedit_list_entry *hle;
8615 struct got_commit_object *commit = NULL;
8617 err = got_worktree_get_histedit_script_path(&path, worktree);
8618 if (err)
8619 return err;
8621 f = fopen(path, "w");
8622 if (f == NULL) {
8623 err = got_error_from_errno2("fopen", path);
8624 goto done;
8626 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8627 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8628 repo);
8629 if (err)
8630 break;
8632 if (hle->logmsg) {
8633 int n = fprintf(f, "%c %s\n",
8634 GOT_HISTEDIT_MESG, hle->logmsg);
8635 if (n < 0) {
8636 err = got_ferror(f, GOT_ERR_IO);
8637 break;
8641 done:
8642 if (f && fclose(f) == EOF && err == NULL)
8643 err = got_error_from_errno("fclose");
8644 free(path);
8645 if (commit)
8646 got_object_commit_close(commit);
8647 return err;
8650 void
8651 histedit_free_list(struct got_histedit_list *histedit_cmds)
8653 struct got_histedit_list_entry *hle;
8655 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8656 TAILQ_REMOVE(histedit_cmds, hle, entry);
8657 free(hle);
8661 static const struct got_error *
8662 histedit_load_list(struct got_histedit_list *histedit_cmds,
8663 const char *path, struct got_repository *repo)
8665 const struct got_error *err = NULL;
8666 FILE *f = NULL;
8668 f = fopen(path, "r");
8669 if (f == NULL) {
8670 err = got_error_from_errno2("fopen", path);
8671 goto done;
8674 err = histedit_parse_list(histedit_cmds, f, repo);
8675 done:
8676 if (f && fclose(f) == EOF && err == NULL)
8677 err = got_error_from_errno("fclose");
8678 return err;
8681 static const struct got_error *
8682 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8683 const struct got_error *edit_err, struct got_object_id_queue *commits,
8684 const char *path, const char *branch_name, struct got_repository *repo)
8686 const struct got_error *err = NULL, *prev_err = edit_err;
8687 int resp = ' ';
8689 while (resp != 'c' && resp != 'r' && resp != 'a') {
8690 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8691 "or (a)bort: ", getprogname(), prev_err->msg);
8692 resp = getchar();
8693 if (resp == '\n')
8694 resp = getchar();
8695 if (resp == 'c') {
8696 histedit_free_list(histedit_cmds);
8697 err = histedit_run_editor(histedit_cmds, path, commits,
8698 repo);
8699 if (err) {
8700 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8701 err->code != GOT_ERR_HISTEDIT_CMD)
8702 break;
8703 prev_err = err;
8704 resp = ' ';
8705 continue;
8707 break;
8708 } else if (resp == 'r') {
8709 histedit_free_list(histedit_cmds);
8710 err = histedit_edit_script(histedit_cmds,
8711 commits, branch_name, 0, 0, repo);
8712 if (err) {
8713 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8714 err->code != GOT_ERR_HISTEDIT_CMD)
8715 break;
8716 prev_err = err;
8717 resp = ' ';
8718 continue;
8720 break;
8721 } else if (resp == 'a') {
8722 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8723 break;
8724 } else
8725 printf("invalid response '%c'\n", resp);
8728 return err;
8731 static const struct got_error *
8732 histedit_complete(struct got_worktree *worktree,
8733 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8734 struct got_reference *branch, struct got_repository *repo)
8736 printf("Switching work tree to %s\n",
8737 got_ref_get_symref_target(branch));
8738 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8739 branch, repo);
8742 static const struct got_error *
8743 show_histedit_progress(struct got_commit_object *commit,
8744 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8746 const struct got_error *err;
8747 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8749 err = got_object_id_str(&old_id_str, hle->commit_id);
8750 if (err)
8751 goto done;
8753 if (new_id) {
8754 err = got_object_id_str(&new_id_str, new_id);
8755 if (err)
8756 goto done;
8759 old_id_str[12] = '\0';
8760 if (new_id_str)
8761 new_id_str[12] = '\0';
8763 if (hle->logmsg) {
8764 logmsg = strdup(hle->logmsg);
8765 if (logmsg == NULL) {
8766 err = got_error_from_errno("strdup");
8767 goto done;
8769 trim_logmsg(logmsg, 42);
8770 } else {
8771 err = get_short_logmsg(&logmsg, 42, commit);
8772 if (err)
8773 goto done;
8776 switch (hle->cmd->code) {
8777 case GOT_HISTEDIT_PICK:
8778 case GOT_HISTEDIT_EDIT:
8779 printf("%s -> %s: %s\n", old_id_str,
8780 new_id_str ? new_id_str : "no-op change", logmsg);
8781 break;
8782 case GOT_HISTEDIT_DROP:
8783 case GOT_HISTEDIT_FOLD:
8784 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8785 logmsg);
8786 break;
8787 default:
8788 break;
8790 done:
8791 free(old_id_str);
8792 free(new_id_str);
8793 return err;
8796 static const struct got_error *
8797 histedit_commit(struct got_pathlist_head *merged_paths,
8798 struct got_worktree *worktree, struct got_fileindex *fileindex,
8799 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8800 struct got_repository *repo)
8802 const struct got_error *err;
8803 struct got_commit_object *commit;
8804 struct got_object_id *new_commit_id;
8806 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8807 && hle->logmsg == NULL) {
8808 err = histedit_edit_logmsg(hle, repo);
8809 if (err)
8810 return err;
8813 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8814 if (err)
8815 return err;
8817 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8818 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8819 hle->logmsg, repo);
8820 if (err) {
8821 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8822 goto done;
8823 err = show_histedit_progress(commit, hle, NULL);
8824 } else {
8825 err = show_histedit_progress(commit, hle, new_commit_id);
8826 free(new_commit_id);
8828 done:
8829 got_object_commit_close(commit);
8830 return err;
8833 static const struct got_error *
8834 histedit_skip_commit(struct got_histedit_list_entry *hle,
8835 struct got_worktree *worktree, struct got_repository *repo)
8837 const struct got_error *error;
8838 struct got_commit_object *commit;
8840 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8841 repo);
8842 if (error)
8843 return error;
8845 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8846 if (error)
8847 return error;
8849 error = show_histedit_progress(commit, hle, NULL);
8850 got_object_commit_close(commit);
8851 return error;
8854 static const struct got_error *
8855 check_local_changes(void *arg, unsigned char status,
8856 unsigned char staged_status, const char *path,
8857 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8858 struct got_object_id *commit_id, int dirfd, const char *de_name)
8860 int *have_local_changes = arg;
8862 switch (status) {
8863 case GOT_STATUS_ADD:
8864 case GOT_STATUS_DELETE:
8865 case GOT_STATUS_MODIFY:
8866 case GOT_STATUS_CONFLICT:
8867 *have_local_changes = 1;
8868 return got_error(GOT_ERR_CANCELLED);
8869 default:
8870 break;
8873 switch (staged_status) {
8874 case GOT_STATUS_ADD:
8875 case GOT_STATUS_DELETE:
8876 case GOT_STATUS_MODIFY:
8877 *have_local_changes = 1;
8878 return got_error(GOT_ERR_CANCELLED);
8879 default:
8880 break;
8883 return NULL;
8886 static const struct got_error *
8887 cmd_histedit(int argc, char *argv[])
8889 const struct got_error *error = NULL;
8890 struct got_worktree *worktree = NULL;
8891 struct got_fileindex *fileindex = NULL;
8892 struct got_repository *repo = NULL;
8893 char *cwd = NULL;
8894 struct got_reference *branch = NULL;
8895 struct got_reference *tmp_branch = NULL;
8896 struct got_object_id *resume_commit_id = NULL;
8897 struct got_object_id *base_commit_id = NULL;
8898 struct got_object_id *head_commit_id = NULL;
8899 struct got_commit_object *commit = NULL;
8900 int ch, rebase_in_progress = 0;
8901 struct got_update_progress_arg upa;
8902 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8903 int edit_logmsg_only = 0, fold_only = 0;
8904 const char *edit_script_path = NULL;
8905 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8906 struct got_object_id_queue commits;
8907 struct got_pathlist_head merged_paths;
8908 const struct got_object_id_queue *parent_ids;
8909 struct got_object_qid *pid;
8910 struct got_histedit_list histedit_cmds;
8911 struct got_histedit_list_entry *hle;
8913 SIMPLEQ_INIT(&commits);
8914 TAILQ_INIT(&histedit_cmds);
8915 TAILQ_INIT(&merged_paths);
8916 memset(&upa, 0, sizeof(upa));
8918 while ((ch = getopt(argc, argv, "acfF:m")) != -1) {
8919 switch (ch) {
8920 case 'a':
8921 abort_edit = 1;
8922 break;
8923 case 'c':
8924 continue_edit = 1;
8925 break;
8926 case 'f':
8927 fold_only = 1;
8928 break;
8929 case 'F':
8930 edit_script_path = optarg;
8931 break;
8932 case 'm':
8933 edit_logmsg_only = 1;
8934 break;
8935 default:
8936 usage_histedit();
8937 /* NOTREACHED */
8941 argc -= optind;
8942 argv += optind;
8944 #ifndef PROFILE
8945 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8946 "unveil", NULL) == -1)
8947 err(1, "pledge");
8948 #endif
8949 if (abort_edit && continue_edit)
8950 option_conflict('a', 'c');
8951 if (edit_script_path && edit_logmsg_only)
8952 option_conflict('F', 'm');
8953 if (abort_edit && edit_logmsg_only)
8954 option_conflict('a', 'm');
8955 if (continue_edit && edit_logmsg_only)
8956 option_conflict('c', 'm');
8957 if (abort_edit && fold_only)
8958 option_conflict('a', 'f');
8959 if (continue_edit && fold_only)
8960 option_conflict('c', 'f');
8961 if (fold_only && edit_logmsg_only)
8962 option_conflict('f', 'm');
8963 if (edit_script_path && fold_only)
8964 option_conflict('F', 'f');
8965 if (argc != 0)
8966 usage_histedit();
8969 * This command cannot apply unveil(2) in all cases because the
8970 * user may choose to run an editor to edit the histedit script
8971 * and to edit individual commit log messages.
8972 * unveil(2) traverses exec(2); if an editor is used we have to
8973 * apply unveil after edit script and log messages have been written.
8974 * XXX TODO: Make use of unveil(2) where possible.
8977 cwd = getcwd(NULL, 0);
8978 if (cwd == NULL) {
8979 error = got_error_from_errno("getcwd");
8980 goto done;
8982 error = got_worktree_open(&worktree, cwd);
8983 if (error) {
8984 if (error->code == GOT_ERR_NOT_WORKTREE)
8985 error = wrap_not_worktree_error(error, "histedit", cwd);
8986 goto done;
8989 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8990 NULL);
8991 if (error != NULL)
8992 goto done;
8994 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8995 if (error)
8996 goto done;
8997 if (rebase_in_progress) {
8998 error = got_error(GOT_ERR_REBASING);
8999 goto done;
9002 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9003 if (error)
9004 goto done;
9006 if (edit_in_progress && edit_logmsg_only) {
9007 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9008 "histedit operation is in progress in this "
9009 "work tree and must be continued or aborted "
9010 "before the -m option can be used");
9011 goto done;
9013 if (edit_in_progress && fold_only) {
9014 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9015 "histedit operation is in progress in this "
9016 "work tree and must be continued or aborted "
9017 "before the -f option can be used");
9018 goto done;
9021 if (edit_in_progress && abort_edit) {
9022 error = got_worktree_histedit_continue(&resume_commit_id,
9023 &tmp_branch, &branch, &base_commit_id, &fileindex,
9024 worktree, repo);
9025 if (error)
9026 goto done;
9027 printf("Switching work tree to %s\n",
9028 got_ref_get_symref_target(branch));
9029 error = got_worktree_histedit_abort(worktree, fileindex, repo,
9030 branch, base_commit_id, update_progress, &upa);
9031 if (error)
9032 goto done;
9033 printf("Histedit of %s aborted\n",
9034 got_ref_get_symref_target(branch));
9035 print_update_progress_stats(&upa);
9036 goto done; /* nothing else to do */
9037 } else if (abort_edit) {
9038 error = got_error(GOT_ERR_NOT_HISTEDIT);
9039 goto done;
9042 if (continue_edit) {
9043 char *path;
9045 if (!edit_in_progress) {
9046 error = got_error(GOT_ERR_NOT_HISTEDIT);
9047 goto done;
9050 error = got_worktree_get_histedit_script_path(&path, worktree);
9051 if (error)
9052 goto done;
9054 error = histedit_load_list(&histedit_cmds, path, repo);
9055 free(path);
9056 if (error)
9057 goto done;
9059 error = got_worktree_histedit_continue(&resume_commit_id,
9060 &tmp_branch, &branch, &base_commit_id, &fileindex,
9061 worktree, repo);
9062 if (error)
9063 goto done;
9065 error = got_ref_resolve(&head_commit_id, repo, branch);
9066 if (error)
9067 goto done;
9069 error = got_object_open_as_commit(&commit, repo,
9070 head_commit_id);
9071 if (error)
9072 goto done;
9073 parent_ids = got_object_commit_get_parent_ids(commit);
9074 pid = SIMPLEQ_FIRST(parent_ids);
9075 if (pid == NULL) {
9076 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9077 goto done;
9079 error = collect_commits(&commits, head_commit_id, pid->id,
9080 base_commit_id, got_worktree_get_path_prefix(worktree),
9081 GOT_ERR_HISTEDIT_PATH, repo);
9082 got_object_commit_close(commit);
9083 commit = NULL;
9084 if (error)
9085 goto done;
9086 } else {
9087 if (edit_in_progress) {
9088 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9089 goto done;
9092 error = got_ref_open(&branch, repo,
9093 got_worktree_get_head_ref_name(worktree), 0);
9094 if (error != NULL)
9095 goto done;
9097 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
9098 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
9099 "will not edit commit history of a branch outside "
9100 "the \"refs/heads/\" reference namespace");
9101 goto done;
9104 error = got_ref_resolve(&head_commit_id, repo, branch);
9105 got_ref_close(branch);
9106 branch = NULL;
9107 if (error)
9108 goto done;
9110 error = got_object_open_as_commit(&commit, repo,
9111 head_commit_id);
9112 if (error)
9113 goto done;
9114 parent_ids = got_object_commit_get_parent_ids(commit);
9115 pid = SIMPLEQ_FIRST(parent_ids);
9116 if (pid == NULL) {
9117 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9118 goto done;
9120 error = collect_commits(&commits, head_commit_id, pid->id,
9121 got_worktree_get_base_commit_id(worktree),
9122 got_worktree_get_path_prefix(worktree),
9123 GOT_ERR_HISTEDIT_PATH, repo);
9124 got_object_commit_close(commit);
9125 commit = NULL;
9126 if (error)
9127 goto done;
9129 if (SIMPLEQ_EMPTY(&commits)) {
9130 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9131 goto done;
9134 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
9135 &base_commit_id, &fileindex, worktree, repo);
9136 if (error)
9137 goto done;
9139 if (edit_script_path) {
9140 error = histedit_load_list(&histedit_cmds,
9141 edit_script_path, repo);
9142 if (error) {
9143 got_worktree_histedit_abort(worktree, fileindex,
9144 repo, branch, base_commit_id,
9145 update_progress, &upa);
9146 print_update_progress_stats(&upa);
9147 goto done;
9149 } else {
9150 const char *branch_name;
9151 branch_name = got_ref_get_symref_target(branch);
9152 if (strncmp(branch_name, "refs/heads/", 11) == 0)
9153 branch_name += 11;
9154 error = histedit_edit_script(&histedit_cmds, &commits,
9155 branch_name, edit_logmsg_only, fold_only, repo);
9156 if (error) {
9157 got_worktree_histedit_abort(worktree, fileindex,
9158 repo, branch, base_commit_id,
9159 update_progress, &upa);
9160 print_update_progress_stats(&upa);
9161 goto done;
9166 error = histedit_save_list(&histedit_cmds, worktree,
9167 repo);
9168 if (error) {
9169 got_worktree_histedit_abort(worktree, fileindex,
9170 repo, branch, base_commit_id,
9171 update_progress, &upa);
9172 print_update_progress_stats(&upa);
9173 goto done;
9178 error = histedit_check_script(&histedit_cmds, &commits, repo);
9179 if (error)
9180 goto done;
9182 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9183 if (resume_commit_id) {
9184 if (got_object_id_cmp(hle->commit_id,
9185 resume_commit_id) != 0)
9186 continue;
9188 resume_commit_id = NULL;
9189 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9190 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9191 error = histedit_skip_commit(hle, worktree,
9192 repo);
9193 if (error)
9194 goto done;
9195 } else {
9196 struct got_pathlist_head paths;
9197 int have_changes = 0;
9199 TAILQ_INIT(&paths);
9200 error = got_pathlist_append(&paths, "", NULL);
9201 if (error)
9202 goto done;
9203 error = got_worktree_status(worktree, &paths,
9204 repo, check_local_changes, &have_changes,
9205 check_cancelled, NULL);
9206 got_pathlist_free(&paths);
9207 if (error) {
9208 if (error->code != GOT_ERR_CANCELLED)
9209 goto done;
9210 if (sigint_received || sigpipe_received)
9211 goto done;
9213 if (have_changes) {
9214 error = histedit_commit(NULL, worktree,
9215 fileindex, tmp_branch, hle, repo);
9216 if (error)
9217 goto done;
9218 } else {
9219 error = got_object_open_as_commit(
9220 &commit, repo, hle->commit_id);
9221 if (error)
9222 goto done;
9223 error = show_histedit_progress(commit,
9224 hle, NULL);
9225 got_object_commit_close(commit);
9226 commit = NULL;
9227 if (error)
9228 goto done;
9231 continue;
9234 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9235 error = histedit_skip_commit(hle, worktree, repo);
9236 if (error)
9237 goto done;
9238 continue;
9241 error = got_object_open_as_commit(&commit, repo,
9242 hle->commit_id);
9243 if (error)
9244 goto done;
9245 parent_ids = got_object_commit_get_parent_ids(commit);
9246 pid = SIMPLEQ_FIRST(parent_ids);
9248 error = got_worktree_histedit_merge_files(&merged_paths,
9249 worktree, fileindex, pid->id, hle->commit_id, repo,
9250 update_progress, &upa, check_cancelled, NULL);
9251 if (error)
9252 goto done;
9253 got_object_commit_close(commit);
9254 commit = NULL;
9256 print_update_progress_stats(&upa);
9257 if (upa.conflicts > 0)
9258 rebase_status = GOT_STATUS_CONFLICT;
9260 if (rebase_status == GOT_STATUS_CONFLICT) {
9261 error = show_rebase_merge_conflict(hle->commit_id,
9262 repo);
9263 if (error)
9264 goto done;
9265 got_worktree_rebase_pathlist_free(&merged_paths);
9266 break;
9269 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9270 char *id_str;
9271 error = got_object_id_str(&id_str, hle->commit_id);
9272 if (error)
9273 goto done;
9274 printf("Stopping histedit for amending commit %s\n",
9275 id_str);
9276 free(id_str);
9277 got_worktree_rebase_pathlist_free(&merged_paths);
9278 error = got_worktree_histedit_postpone(worktree,
9279 fileindex);
9280 goto done;
9283 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9284 error = histedit_skip_commit(hle, worktree, repo);
9285 if (error)
9286 goto done;
9287 continue;
9290 error = histedit_commit(&merged_paths, worktree, fileindex,
9291 tmp_branch, hle, repo);
9292 got_worktree_rebase_pathlist_free(&merged_paths);
9293 if (error)
9294 goto done;
9297 if (rebase_status == GOT_STATUS_CONFLICT) {
9298 error = got_worktree_histedit_postpone(worktree, fileindex);
9299 if (error)
9300 goto done;
9301 error = got_error_msg(GOT_ERR_CONFLICTS,
9302 "conflicts must be resolved before histedit can continue");
9303 } else
9304 error = histedit_complete(worktree, fileindex, tmp_branch,
9305 branch, repo);
9306 done:
9307 got_object_id_queue_free(&commits);
9308 histedit_free_list(&histedit_cmds);
9309 free(head_commit_id);
9310 free(base_commit_id);
9311 free(resume_commit_id);
9312 if (commit)
9313 got_object_commit_close(commit);
9314 if (branch)
9315 got_ref_close(branch);
9316 if (tmp_branch)
9317 got_ref_close(tmp_branch);
9318 if (worktree)
9319 got_worktree_close(worktree);
9320 if (repo)
9321 got_repo_close(repo);
9322 return error;
9325 __dead static void
9326 usage_integrate(void)
9328 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9329 exit(1);
9332 static const struct got_error *
9333 cmd_integrate(int argc, char *argv[])
9335 const struct got_error *error = NULL;
9336 struct got_repository *repo = NULL;
9337 struct got_worktree *worktree = NULL;
9338 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9339 const char *branch_arg = NULL;
9340 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9341 struct got_fileindex *fileindex = NULL;
9342 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9343 int ch;
9344 struct got_update_progress_arg upa;
9346 while ((ch = getopt(argc, argv, "")) != -1) {
9347 switch (ch) {
9348 default:
9349 usage_integrate();
9350 /* NOTREACHED */
9354 argc -= optind;
9355 argv += optind;
9357 if (argc != 1)
9358 usage_integrate();
9359 branch_arg = argv[0];
9360 #ifndef PROFILE
9361 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9362 "unveil", NULL) == -1)
9363 err(1, "pledge");
9364 #endif
9365 cwd = getcwd(NULL, 0);
9366 if (cwd == NULL) {
9367 error = got_error_from_errno("getcwd");
9368 goto done;
9371 error = got_worktree_open(&worktree, cwd);
9372 if (error) {
9373 if (error->code == GOT_ERR_NOT_WORKTREE)
9374 error = wrap_not_worktree_error(error, "integrate",
9375 cwd);
9376 goto done;
9379 error = check_rebase_or_histedit_in_progress(worktree);
9380 if (error)
9381 goto done;
9383 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9384 NULL);
9385 if (error != NULL)
9386 goto done;
9388 error = apply_unveil(got_repo_get_path(repo), 0,
9389 got_worktree_get_root_path(worktree));
9390 if (error)
9391 goto done;
9393 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9394 error = got_error_from_errno("asprintf");
9395 goto done;
9398 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9399 &base_branch_ref, worktree, refname, repo);
9400 if (error)
9401 goto done;
9403 refname = strdup(got_ref_get_name(branch_ref));
9404 if (refname == NULL) {
9405 error = got_error_from_errno("strdup");
9406 got_worktree_integrate_abort(worktree, fileindex, repo,
9407 branch_ref, base_branch_ref);
9408 goto done;
9410 base_refname = strdup(got_ref_get_name(base_branch_ref));
9411 if (base_refname == NULL) {
9412 error = got_error_from_errno("strdup");
9413 got_worktree_integrate_abort(worktree, fileindex, repo,
9414 branch_ref, base_branch_ref);
9415 goto done;
9418 error = got_ref_resolve(&commit_id, repo, branch_ref);
9419 if (error)
9420 goto done;
9422 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9423 if (error)
9424 goto done;
9426 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9427 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9428 "specified branch has already been integrated");
9429 got_worktree_integrate_abort(worktree, fileindex, repo,
9430 branch_ref, base_branch_ref);
9431 goto done;
9434 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9435 if (error) {
9436 if (error->code == GOT_ERR_ANCESTRY)
9437 error = got_error(GOT_ERR_REBASE_REQUIRED);
9438 got_worktree_integrate_abort(worktree, fileindex, repo,
9439 branch_ref, base_branch_ref);
9440 goto done;
9443 memset(&upa, 0, sizeof(upa));
9444 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9445 branch_ref, base_branch_ref, update_progress, &upa,
9446 check_cancelled, NULL);
9447 if (error)
9448 goto done;
9450 printf("Integrated %s into %s\n", refname, base_refname);
9451 print_update_progress_stats(&upa);
9452 done:
9453 if (repo)
9454 got_repo_close(repo);
9455 if (worktree)
9456 got_worktree_close(worktree);
9457 free(cwd);
9458 free(base_commit_id);
9459 free(commit_id);
9460 free(refname);
9461 free(base_refname);
9462 return error;
9465 __dead static void
9466 usage_stage(void)
9468 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9469 "[-S] [file-path ...]\n",
9470 getprogname());
9471 exit(1);
9474 static const struct got_error *
9475 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9476 const char *path, struct got_object_id *blob_id,
9477 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9478 int dirfd, const char *de_name)
9480 const struct got_error *err = NULL;
9481 char *id_str = NULL;
9483 if (staged_status != GOT_STATUS_ADD &&
9484 staged_status != GOT_STATUS_MODIFY &&
9485 staged_status != GOT_STATUS_DELETE)
9486 return NULL;
9488 if (staged_status == GOT_STATUS_ADD ||
9489 staged_status == GOT_STATUS_MODIFY)
9490 err = got_object_id_str(&id_str, staged_blob_id);
9491 else
9492 err = got_object_id_str(&id_str, blob_id);
9493 if (err)
9494 return err;
9496 printf("%s %c %s\n", id_str, staged_status, path);
9497 free(id_str);
9498 return NULL;
9501 static const struct got_error *
9502 cmd_stage(int argc, char *argv[])
9504 const struct got_error *error = NULL;
9505 struct got_repository *repo = NULL;
9506 struct got_worktree *worktree = NULL;
9507 char *cwd = NULL;
9508 struct got_pathlist_head paths;
9509 struct got_pathlist_entry *pe;
9510 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9511 FILE *patch_script_file = NULL;
9512 const char *patch_script_path = NULL;
9513 struct choose_patch_arg cpa;
9515 TAILQ_INIT(&paths);
9517 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9518 switch (ch) {
9519 case 'l':
9520 list_stage = 1;
9521 break;
9522 case 'p':
9523 pflag = 1;
9524 break;
9525 case 'F':
9526 patch_script_path = optarg;
9527 break;
9528 case 'S':
9529 allow_bad_symlinks = 1;
9530 break;
9531 default:
9532 usage_stage();
9533 /* NOTREACHED */
9537 argc -= optind;
9538 argv += optind;
9540 #ifndef PROFILE
9541 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9542 "unveil", NULL) == -1)
9543 err(1, "pledge");
9544 #endif
9545 if (list_stage && (pflag || patch_script_path))
9546 errx(1, "-l option cannot be used with other options");
9547 if (patch_script_path && !pflag)
9548 errx(1, "-F option can only be used together with -p option");
9550 cwd = getcwd(NULL, 0);
9551 if (cwd == NULL) {
9552 error = got_error_from_errno("getcwd");
9553 goto done;
9556 error = got_worktree_open(&worktree, cwd);
9557 if (error) {
9558 if (error->code == GOT_ERR_NOT_WORKTREE)
9559 error = wrap_not_worktree_error(error, "stage", cwd);
9560 goto done;
9563 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9564 NULL);
9565 if (error != NULL)
9566 goto done;
9568 if (patch_script_path) {
9569 patch_script_file = fopen(patch_script_path, "r");
9570 if (patch_script_file == NULL) {
9571 error = got_error_from_errno2("fopen",
9572 patch_script_path);
9573 goto done;
9576 error = apply_unveil(got_repo_get_path(repo), 0,
9577 got_worktree_get_root_path(worktree));
9578 if (error)
9579 goto done;
9581 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9582 if (error)
9583 goto done;
9585 if (list_stage)
9586 error = got_worktree_status(worktree, &paths, repo,
9587 print_stage, NULL, check_cancelled, NULL);
9588 else {
9589 cpa.patch_script_file = patch_script_file;
9590 cpa.action = "stage";
9591 error = got_worktree_stage(worktree, &paths,
9592 pflag ? NULL : print_status, NULL,
9593 pflag ? choose_patch : NULL, &cpa,
9594 allow_bad_symlinks, repo);
9596 done:
9597 if (patch_script_file && fclose(patch_script_file) == EOF &&
9598 error == NULL)
9599 error = got_error_from_errno2("fclose", patch_script_path);
9600 if (repo)
9601 got_repo_close(repo);
9602 if (worktree)
9603 got_worktree_close(worktree);
9604 TAILQ_FOREACH(pe, &paths, entry)
9605 free((char *)pe->path);
9606 got_pathlist_free(&paths);
9607 free(cwd);
9608 return error;
9611 __dead static void
9612 usage_unstage(void)
9614 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9615 "[file-path ...]\n",
9616 getprogname());
9617 exit(1);
9621 static const struct got_error *
9622 cmd_unstage(int argc, char *argv[])
9624 const struct got_error *error = NULL;
9625 struct got_repository *repo = NULL;
9626 struct got_worktree *worktree = NULL;
9627 char *cwd = NULL;
9628 struct got_pathlist_head paths;
9629 struct got_pathlist_entry *pe;
9630 int ch, pflag = 0;
9631 struct got_update_progress_arg upa;
9632 FILE *patch_script_file = NULL;
9633 const char *patch_script_path = NULL;
9634 struct choose_patch_arg cpa;
9636 TAILQ_INIT(&paths);
9638 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9639 switch (ch) {
9640 case 'p':
9641 pflag = 1;
9642 break;
9643 case 'F':
9644 patch_script_path = optarg;
9645 break;
9646 default:
9647 usage_unstage();
9648 /* NOTREACHED */
9652 argc -= optind;
9653 argv += optind;
9655 #ifndef PROFILE
9656 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9657 "unveil", NULL) == -1)
9658 err(1, "pledge");
9659 #endif
9660 if (patch_script_path && !pflag)
9661 errx(1, "-F option can only be used together with -p option");
9663 cwd = getcwd(NULL, 0);
9664 if (cwd == NULL) {
9665 error = got_error_from_errno("getcwd");
9666 goto done;
9669 error = got_worktree_open(&worktree, cwd);
9670 if (error) {
9671 if (error->code == GOT_ERR_NOT_WORKTREE)
9672 error = wrap_not_worktree_error(error, "unstage", cwd);
9673 goto done;
9676 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9677 NULL);
9678 if (error != NULL)
9679 goto done;
9681 if (patch_script_path) {
9682 patch_script_file = fopen(patch_script_path, "r");
9683 if (patch_script_file == NULL) {
9684 error = got_error_from_errno2("fopen",
9685 patch_script_path);
9686 goto done;
9690 error = apply_unveil(got_repo_get_path(repo), 0,
9691 got_worktree_get_root_path(worktree));
9692 if (error)
9693 goto done;
9695 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9696 if (error)
9697 goto done;
9699 cpa.patch_script_file = patch_script_file;
9700 cpa.action = "unstage";
9701 memset(&upa, 0, sizeof(upa));
9702 error = got_worktree_unstage(worktree, &paths, update_progress,
9703 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9704 if (!error)
9705 print_update_progress_stats(&upa);
9706 done:
9707 if (patch_script_file && fclose(patch_script_file) == EOF &&
9708 error == NULL)
9709 error = got_error_from_errno2("fclose", patch_script_path);
9710 if (repo)
9711 got_repo_close(repo);
9712 if (worktree)
9713 got_worktree_close(worktree);
9714 TAILQ_FOREACH(pe, &paths, entry)
9715 free((char *)pe->path);
9716 got_pathlist_free(&paths);
9717 free(cwd);
9718 return error;
9721 __dead static void
9722 usage_cat(void)
9724 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9725 "arg1 [arg2 ...]\n", getprogname());
9726 exit(1);
9729 static const struct got_error *
9730 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9732 const struct got_error *err;
9733 struct got_blob_object *blob;
9735 err = got_object_open_as_blob(&blob, repo, id, 8192);
9736 if (err)
9737 return err;
9739 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9740 got_object_blob_close(blob);
9741 return err;
9744 static const struct got_error *
9745 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9747 const struct got_error *err;
9748 struct got_tree_object *tree;
9749 int nentries, i;
9751 err = got_object_open_as_tree(&tree, repo, id);
9752 if (err)
9753 return err;
9755 nentries = got_object_tree_get_nentries(tree);
9756 for (i = 0; i < nentries; i++) {
9757 struct got_tree_entry *te;
9758 char *id_str;
9759 if (sigint_received || sigpipe_received)
9760 break;
9761 te = got_object_tree_get_entry(tree, i);
9762 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9763 if (err)
9764 break;
9765 fprintf(outfile, "%s %.7o %s\n", id_str,
9766 got_tree_entry_get_mode(te),
9767 got_tree_entry_get_name(te));
9768 free(id_str);
9771 got_object_tree_close(tree);
9772 return err;
9775 static const struct got_error *
9776 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9778 const struct got_error *err;
9779 struct got_commit_object *commit;
9780 const struct got_object_id_queue *parent_ids;
9781 struct got_object_qid *pid;
9782 char *id_str = NULL;
9783 const char *logmsg = NULL;
9785 err = got_object_open_as_commit(&commit, repo, id);
9786 if (err)
9787 return err;
9789 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9790 if (err)
9791 goto done;
9793 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9794 parent_ids = got_object_commit_get_parent_ids(commit);
9795 fprintf(outfile, "numparents %d\n",
9796 got_object_commit_get_nparents(commit));
9797 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9798 char *pid_str;
9799 err = got_object_id_str(&pid_str, pid->id);
9800 if (err)
9801 goto done;
9802 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9803 free(pid_str);
9805 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9806 got_object_commit_get_author(commit),
9807 (long long)got_object_commit_get_author_time(commit));
9809 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9810 got_object_commit_get_author(commit),
9811 (long long)got_object_commit_get_committer_time(commit));
9813 logmsg = got_object_commit_get_logmsg_raw(commit);
9814 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9815 fprintf(outfile, "%s", logmsg);
9816 done:
9817 free(id_str);
9818 got_object_commit_close(commit);
9819 return err;
9822 static const struct got_error *
9823 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9825 const struct got_error *err;
9826 struct got_tag_object *tag;
9827 char *id_str = NULL;
9828 const char *tagmsg = NULL;
9830 err = got_object_open_as_tag(&tag, repo, id);
9831 if (err)
9832 return err;
9834 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9835 if (err)
9836 goto done;
9838 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9840 switch (got_object_tag_get_object_type(tag)) {
9841 case GOT_OBJ_TYPE_BLOB:
9842 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9843 GOT_OBJ_LABEL_BLOB);
9844 break;
9845 case GOT_OBJ_TYPE_TREE:
9846 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9847 GOT_OBJ_LABEL_TREE);
9848 break;
9849 case GOT_OBJ_TYPE_COMMIT:
9850 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9851 GOT_OBJ_LABEL_COMMIT);
9852 break;
9853 case GOT_OBJ_TYPE_TAG:
9854 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9855 GOT_OBJ_LABEL_TAG);
9856 break;
9857 default:
9858 break;
9861 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9862 got_object_tag_get_name(tag));
9864 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9865 got_object_tag_get_tagger(tag),
9866 (long long)got_object_tag_get_tagger_time(tag));
9868 tagmsg = got_object_tag_get_message(tag);
9869 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9870 fprintf(outfile, "%s", tagmsg);
9871 done:
9872 free(id_str);
9873 got_object_tag_close(tag);
9874 return err;
9877 static const struct got_error *
9878 cmd_cat(int argc, char *argv[])
9880 const struct got_error *error;
9881 struct got_repository *repo = NULL;
9882 struct got_worktree *worktree = NULL;
9883 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9884 const char *commit_id_str = NULL;
9885 struct got_object_id *id = NULL, *commit_id = NULL;
9886 int ch, obj_type, i, force_path = 0;
9887 struct got_reflist_head refs;
9889 TAILQ_INIT(&refs);
9891 #ifndef PROFILE
9892 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9893 NULL) == -1)
9894 err(1, "pledge");
9895 #endif
9897 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9898 switch (ch) {
9899 case 'c':
9900 commit_id_str = optarg;
9901 break;
9902 case 'r':
9903 repo_path = realpath(optarg, NULL);
9904 if (repo_path == NULL)
9905 return got_error_from_errno2("realpath",
9906 optarg);
9907 got_path_strip_trailing_slashes(repo_path);
9908 break;
9909 case 'P':
9910 force_path = 1;
9911 break;
9912 default:
9913 usage_cat();
9914 /* NOTREACHED */
9918 argc -= optind;
9919 argv += optind;
9921 cwd = getcwd(NULL, 0);
9922 if (cwd == NULL) {
9923 error = got_error_from_errno("getcwd");
9924 goto done;
9926 error = got_worktree_open(&worktree, cwd);
9927 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9928 goto done;
9929 if (worktree) {
9930 if (repo_path == NULL) {
9931 repo_path = strdup(
9932 got_worktree_get_repo_path(worktree));
9933 if (repo_path == NULL) {
9934 error = got_error_from_errno("strdup");
9935 goto done;
9940 if (repo_path == NULL) {
9941 repo_path = getcwd(NULL, 0);
9942 if (repo_path == NULL)
9943 return got_error_from_errno("getcwd");
9946 error = got_repo_open(&repo, repo_path, NULL);
9947 free(repo_path);
9948 if (error != NULL)
9949 goto done;
9951 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9952 if (error)
9953 goto done;
9955 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9956 if (error)
9957 goto done;
9959 if (commit_id_str == NULL)
9960 commit_id_str = GOT_REF_HEAD;
9961 error = got_repo_match_object_id(&commit_id, NULL,
9962 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
9963 if (error)
9964 goto done;
9966 for (i = 0; i < argc; i++) {
9967 if (force_path) {
9968 error = got_object_id_by_path(&id, repo, commit_id,
9969 argv[i]);
9970 if (error)
9971 break;
9972 } else {
9973 error = got_repo_match_object_id(&id, &label, argv[i],
9974 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
9975 repo);
9976 if (error) {
9977 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9978 error->code != GOT_ERR_NOT_REF)
9979 break;
9980 error = got_object_id_by_path(&id, repo,
9981 commit_id, argv[i]);
9982 if (error)
9983 break;
9987 error = got_object_get_type(&obj_type, repo, id);
9988 if (error)
9989 break;
9991 switch (obj_type) {
9992 case GOT_OBJ_TYPE_BLOB:
9993 error = cat_blob(id, repo, stdout);
9994 break;
9995 case GOT_OBJ_TYPE_TREE:
9996 error = cat_tree(id, repo, stdout);
9997 break;
9998 case GOT_OBJ_TYPE_COMMIT:
9999 error = cat_commit(id, repo, stdout);
10000 break;
10001 case GOT_OBJ_TYPE_TAG:
10002 error = cat_tag(id, repo, stdout);
10003 break;
10004 default:
10005 error = got_error(GOT_ERR_OBJ_TYPE);
10006 break;
10008 if (error)
10009 break;
10010 free(label);
10011 label = NULL;
10012 free(id);
10013 id = NULL;
10015 done:
10016 free(label);
10017 free(id);
10018 free(commit_id);
10019 if (worktree)
10020 got_worktree_close(worktree);
10021 if (repo) {
10022 const struct got_error *repo_error;
10023 repo_error = got_repo_close(repo);
10024 if (error == NULL)
10025 error = repo_error;
10027 got_ref_list_free(&refs);
10028 return error;
10031 __dead static void
10032 usage_info(void)
10034 fprintf(stderr, "usage: %s info [path ...]\n",
10035 getprogname());
10036 exit(1);
10039 static const struct got_error *
10040 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
10041 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10042 struct got_object_id *commit_id)
10044 const struct got_error *err = NULL;
10045 char *id_str = NULL;
10046 char datebuf[128];
10047 struct tm mytm, *tm;
10048 struct got_pathlist_head *paths = arg;
10049 struct got_pathlist_entry *pe;
10052 * Clear error indication from any of the path arguments which
10053 * would cause this file index entry to be displayed.
10055 TAILQ_FOREACH(pe, paths, entry) {
10056 if (got_path_cmp(path, pe->path, strlen(path),
10057 pe->path_len) == 0 ||
10058 got_path_is_child(path, pe->path, pe->path_len))
10059 pe->data = NULL; /* no error */
10062 printf(GOT_COMMIT_SEP_STR);
10063 if (S_ISLNK(mode))
10064 printf("symlink: %s\n", path);
10065 else if (S_ISREG(mode)) {
10066 printf("file: %s\n", path);
10067 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
10068 } else if (S_ISDIR(mode))
10069 printf("directory: %s\n", path);
10070 else
10071 printf("something: %s\n", path);
10073 tm = localtime_r(&mtime, &mytm);
10074 if (tm == NULL)
10075 return NULL;
10076 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
10077 return got_error(GOT_ERR_NO_SPACE);
10078 printf("timestamp: %s\n", datebuf);
10080 if (blob_id) {
10081 err = got_object_id_str(&id_str, blob_id);
10082 if (err)
10083 return err;
10084 printf("based on blob: %s\n", id_str);
10085 free(id_str);
10088 if (staged_blob_id) {
10089 err = got_object_id_str(&id_str, staged_blob_id);
10090 if (err)
10091 return err;
10092 printf("based on staged blob: %s\n", id_str);
10093 free(id_str);
10096 if (commit_id) {
10097 err = got_object_id_str(&id_str, commit_id);
10098 if (err)
10099 return err;
10100 printf("based on commit: %s\n", id_str);
10101 free(id_str);
10104 return NULL;
10107 static const struct got_error *
10108 cmd_info(int argc, char *argv[])
10110 const struct got_error *error = NULL;
10111 struct got_worktree *worktree = NULL;
10112 char *cwd = NULL, *id_str = NULL;
10113 struct got_pathlist_head paths;
10114 struct got_pathlist_entry *pe;
10115 char *uuidstr = NULL;
10116 int ch, show_files = 0;
10118 TAILQ_INIT(&paths);
10120 while ((ch = getopt(argc, argv, "")) != -1) {
10121 switch (ch) {
10122 default:
10123 usage_info();
10124 /* NOTREACHED */
10128 argc -= optind;
10129 argv += optind;
10131 #ifndef PROFILE
10132 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
10133 NULL) == -1)
10134 err(1, "pledge");
10135 #endif
10136 cwd = getcwd(NULL, 0);
10137 if (cwd == NULL) {
10138 error = got_error_from_errno("getcwd");
10139 goto done;
10142 error = got_worktree_open(&worktree, cwd);
10143 if (error) {
10144 if (error->code == GOT_ERR_NOT_WORKTREE)
10145 error = wrap_not_worktree_error(error, "info", cwd);
10146 goto done;
10149 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
10150 if (error)
10151 goto done;
10153 if (argc >= 1) {
10154 error = get_worktree_paths_from_argv(&paths, argc, argv,
10155 worktree);
10156 if (error)
10157 goto done;
10158 show_files = 1;
10161 error = got_object_id_str(&id_str,
10162 got_worktree_get_base_commit_id(worktree));
10163 if (error)
10164 goto done;
10166 error = got_worktree_get_uuid(&uuidstr, worktree);
10167 if (error)
10168 goto done;
10170 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
10171 printf("work tree base commit: %s\n", id_str);
10172 printf("work tree path prefix: %s\n",
10173 got_worktree_get_path_prefix(worktree));
10174 printf("work tree branch reference: %s\n",
10175 got_worktree_get_head_ref_name(worktree));
10176 printf("work tree UUID: %s\n", uuidstr);
10177 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10179 if (show_files) {
10180 struct got_pathlist_entry *pe;
10181 TAILQ_FOREACH(pe, &paths, entry) {
10182 if (pe->path_len == 0)
10183 continue;
10185 * Assume this path will fail. This will be corrected
10186 * in print_path_info() in case the path does suceeed.
10188 pe->data = (void *)got_error_path(pe->path,
10189 GOT_ERR_BAD_PATH);
10191 error = got_worktree_path_info(worktree, &paths,
10192 print_path_info, &paths, check_cancelled, NULL);
10193 if (error)
10194 goto done;
10195 TAILQ_FOREACH(pe, &paths, entry) {
10196 if (pe->data != NULL) {
10197 error = pe->data; /* bad path */
10198 break;
10202 done:
10203 TAILQ_FOREACH(pe, &paths, entry)
10204 free((char *)pe->path);
10205 got_pathlist_free(&paths);
10206 free(cwd);
10207 free(id_str);
10208 free(uuidstr);
10209 return error;