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,
3605 const char *custom_refs_str)
3607 const struct got_error *err = NULL;
3608 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3609 char datebuf[26];
3610 time_t committer_time;
3611 const char *author, *committer;
3612 char *refs_str = NULL;
3614 err = got_object_id_str(&id_str, id);
3615 if (err)
3616 return err;
3618 if (custom_refs_str == NULL) {
3619 struct got_reflist_head *refs;
3620 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3621 if (refs) {
3622 err = build_refs_str(&refs_str, refs, id, repo);
3623 if (err)
3624 goto done;
3628 printf(GOT_COMMIT_SEP_STR);
3629 if (custom_refs_str)
3630 printf("commit %s (%s)\n", id_str, custom_refs_str);
3631 else
3632 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3633 refs_str ? refs_str : "", refs_str ? ")" : "");
3634 free(id_str);
3635 id_str = NULL;
3636 free(refs_str);
3637 refs_str = NULL;
3638 printf("from: %s\n", got_object_commit_get_author(commit));
3639 committer_time = got_object_commit_get_committer_time(commit);
3640 datestr = get_datestr(&committer_time, datebuf);
3641 if (datestr)
3642 printf("date: %s UTC\n", datestr);
3643 author = got_object_commit_get_author(commit);
3644 committer = got_object_commit_get_committer(commit);
3645 if (strcmp(author, committer) != 0)
3646 printf("via: %s\n", committer);
3647 if (got_object_commit_get_nparents(commit) > 1) {
3648 const struct got_object_id_queue *parent_ids;
3649 struct got_object_qid *qid;
3650 int n = 1;
3651 parent_ids = got_object_commit_get_parent_ids(commit);
3652 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3653 err = got_object_id_str(&id_str, qid->id);
3654 if (err)
3655 goto done;
3656 printf("parent %d: %s\n", n++, id_str);
3657 free(id_str);
3658 id_str = NULL;
3662 err = got_object_commit_get_logmsg(&logmsg0, commit);
3663 if (err)
3664 goto done;
3666 logmsg = logmsg0;
3667 do {
3668 line = strsep(&logmsg, "\n");
3669 if (line)
3670 printf(" %s\n", line);
3671 } while (line);
3672 free(logmsg0);
3674 if (changed_paths) {
3675 struct got_pathlist_entry *pe;
3676 TAILQ_FOREACH(pe, changed_paths, entry) {
3677 struct got_diff_changed_path *cp = pe->data;
3678 printf(" %c %s\n", cp->status, pe->path);
3680 printf("\n");
3682 if (show_patch) {
3683 err = print_patch(commit, id, path, diff_context, repo);
3684 if (err == 0)
3685 printf("\n");
3688 if (fflush(stdout) != 0 && err == NULL)
3689 err = got_error_from_errno("fflush");
3690 done:
3691 free(id_str);
3692 free(refs_str);
3693 return err;
3696 static const struct got_error *
3697 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3698 struct got_repository *repo, const char *path, int show_changed_paths,
3699 int show_patch, const char *search_pattern, int diff_context, int limit,
3700 int log_branches, int reverse_display_order,
3701 struct got_reflist_object_id_map *refs_idmap)
3703 const struct got_error *err;
3704 struct got_commit_graph *graph;
3705 regex_t regex;
3706 int have_match;
3707 struct got_object_id_queue reversed_commits;
3708 struct got_object_qid *qid;
3709 struct got_commit_object *commit;
3710 struct got_pathlist_head changed_paths;
3711 struct got_pathlist_entry *pe;
3713 SIMPLEQ_INIT(&reversed_commits);
3714 TAILQ_INIT(&changed_paths);
3716 if (search_pattern && regcomp(&regex, search_pattern,
3717 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3718 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3720 err = got_commit_graph_open(&graph, path, !log_branches);
3721 if (err)
3722 return err;
3723 err = got_commit_graph_iter_start(graph, root_id, repo,
3724 check_cancelled, NULL);
3725 if (err)
3726 goto done;
3727 for (;;) {
3728 struct got_object_id *id;
3730 if (sigint_received || sigpipe_received)
3731 break;
3733 err = got_commit_graph_iter_next(&id, graph, repo,
3734 check_cancelled, NULL);
3735 if (err) {
3736 if (err->code == GOT_ERR_ITER_COMPLETED)
3737 err = NULL;
3738 break;
3740 if (id == NULL)
3741 break;
3743 err = got_object_open_as_commit(&commit, repo, id);
3744 if (err)
3745 break;
3747 if (show_changed_paths && !reverse_display_order) {
3748 err = get_changed_paths(&changed_paths, commit, repo);
3749 if (err)
3750 break;
3753 if (search_pattern) {
3754 err = match_logmsg(&have_match, id, commit, &regex);
3755 if (err) {
3756 got_object_commit_close(commit);
3757 break;
3759 if (have_match == 0 && show_changed_paths)
3760 match_changed_paths(&have_match,
3761 &changed_paths, &regex);
3762 if (have_match == 0) {
3763 got_object_commit_close(commit);
3764 TAILQ_FOREACH(pe, &changed_paths, entry) {
3765 free((char *)pe->path);
3766 free(pe->data);
3768 got_pathlist_free(&changed_paths);
3769 continue;
3773 if (reverse_display_order) {
3774 err = got_object_qid_alloc(&qid, id);
3775 if (err)
3776 break;
3777 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3778 got_object_commit_close(commit);
3779 } else {
3780 err = print_commit(commit, id, repo, path,
3781 show_changed_paths ? &changed_paths : NULL,
3782 show_patch, diff_context, refs_idmap, NULL);
3783 got_object_commit_close(commit);
3784 if (err)
3785 break;
3787 if ((limit && --limit == 0) ||
3788 (end_id && got_object_id_cmp(id, end_id) == 0))
3789 break;
3791 TAILQ_FOREACH(pe, &changed_paths, entry) {
3792 free((char *)pe->path);
3793 free(pe->data);
3795 got_pathlist_free(&changed_paths);
3797 if (reverse_display_order) {
3798 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3799 err = got_object_open_as_commit(&commit, repo, qid->id);
3800 if (err)
3801 break;
3802 if (show_changed_paths) {
3803 err = get_changed_paths(&changed_paths,
3804 commit, repo);
3805 if (err)
3806 break;
3808 err = print_commit(commit, qid->id, repo, path,
3809 show_changed_paths ? &changed_paths : NULL,
3810 show_patch, diff_context, refs_idmap, NULL);
3811 got_object_commit_close(commit);
3812 if (err)
3813 break;
3814 TAILQ_FOREACH(pe, &changed_paths, entry) {
3815 free((char *)pe->path);
3816 free(pe->data);
3818 got_pathlist_free(&changed_paths);
3821 done:
3822 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3823 qid = SIMPLEQ_FIRST(&reversed_commits);
3824 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3825 got_object_qid_free(qid);
3827 TAILQ_FOREACH(pe, &changed_paths, entry) {
3828 free((char *)pe->path);
3829 free(pe->data);
3831 got_pathlist_free(&changed_paths);
3832 if (search_pattern)
3833 regfree(&regex);
3834 got_commit_graph_close(graph);
3835 return err;
3838 __dead static void
3839 usage_log(void)
3841 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3842 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3843 "[-R] [path]\n", getprogname());
3844 exit(1);
3847 static int
3848 get_default_log_limit(void)
3850 const char *got_default_log_limit;
3851 long long n;
3852 const char *errstr;
3854 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3855 if (got_default_log_limit == NULL)
3856 return 0;
3857 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3858 if (errstr != NULL)
3859 return 0;
3860 return n;
3863 static const struct got_error *
3864 cmd_log(int argc, char *argv[])
3866 const struct got_error *error;
3867 struct got_repository *repo = NULL;
3868 struct got_worktree *worktree = NULL;
3869 struct got_object_id *start_id = NULL, *end_id = NULL;
3870 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3871 const char *start_commit = NULL, *end_commit = NULL;
3872 const char *search_pattern = NULL;
3873 int diff_context = -1, ch;
3874 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3875 int reverse_display_order = 0;
3876 const char *errstr;
3877 struct got_reflist_head refs;
3878 struct got_reflist_object_id_map *refs_idmap = NULL;
3880 TAILQ_INIT(&refs);
3882 #ifndef PROFILE
3883 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3884 NULL)
3885 == -1)
3886 err(1, "pledge");
3887 #endif
3889 limit = get_default_log_limit();
3891 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3892 switch (ch) {
3893 case 'p':
3894 show_patch = 1;
3895 break;
3896 case 'P':
3897 show_changed_paths = 1;
3898 break;
3899 case 'c':
3900 start_commit = optarg;
3901 break;
3902 case 'C':
3903 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3904 &errstr);
3905 if (errstr != NULL)
3906 err(1, "-C option %s", errstr);
3907 break;
3908 case 'l':
3909 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3910 if (errstr != NULL)
3911 err(1, "-l option %s", errstr);
3912 break;
3913 case 'b':
3914 log_branches = 1;
3915 break;
3916 case 'r':
3917 repo_path = realpath(optarg, NULL);
3918 if (repo_path == NULL)
3919 return got_error_from_errno2("realpath",
3920 optarg);
3921 got_path_strip_trailing_slashes(repo_path);
3922 break;
3923 case 'R':
3924 reverse_display_order = 1;
3925 break;
3926 case 's':
3927 search_pattern = optarg;
3928 break;
3929 case 'x':
3930 end_commit = optarg;
3931 break;
3932 default:
3933 usage_log();
3934 /* NOTREACHED */
3938 argc -= optind;
3939 argv += optind;
3941 if (diff_context == -1)
3942 diff_context = 3;
3943 else if (!show_patch)
3944 errx(1, "-C requires -p");
3946 cwd = getcwd(NULL, 0);
3947 if (cwd == NULL) {
3948 error = got_error_from_errno("getcwd");
3949 goto done;
3952 if (repo_path == NULL) {
3953 error = got_worktree_open(&worktree, cwd);
3954 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3955 goto done;
3956 error = NULL;
3959 if (argc == 1) {
3960 if (worktree) {
3961 error = got_worktree_resolve_path(&path, worktree,
3962 argv[0]);
3963 if (error)
3964 goto done;
3965 } else {
3966 path = strdup(argv[0]);
3967 if (path == NULL) {
3968 error = got_error_from_errno("strdup");
3969 goto done;
3972 } else if (argc != 0)
3973 usage_log();
3975 if (repo_path == NULL) {
3976 repo_path = worktree ?
3977 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3979 if (repo_path == NULL) {
3980 error = got_error_from_errno("strdup");
3981 goto done;
3984 error = got_repo_open(&repo, repo_path, NULL);
3985 if (error != NULL)
3986 goto done;
3988 error = apply_unveil(got_repo_get_path(repo), 1,
3989 worktree ? got_worktree_get_root_path(worktree) : NULL);
3990 if (error)
3991 goto done;
3993 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3994 if (error)
3995 goto done;
3997 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
3998 if (error)
3999 goto done;
4001 if (start_commit == NULL) {
4002 struct got_reference *head_ref;
4003 struct got_commit_object *commit = NULL;
4004 error = got_ref_open(&head_ref, repo,
4005 worktree ? got_worktree_get_head_ref_name(worktree)
4006 : GOT_REF_HEAD, 0);
4007 if (error != NULL)
4008 goto done;
4009 error = got_ref_resolve(&start_id, repo, head_ref);
4010 got_ref_close(head_ref);
4011 if (error != NULL)
4012 goto done;
4013 error = got_object_open_as_commit(&commit, repo,
4014 start_id);
4015 if (error != NULL)
4016 goto done;
4017 got_object_commit_close(commit);
4018 } else {
4019 error = got_repo_match_object_id(&start_id, NULL,
4020 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4021 if (error != NULL)
4022 goto done;
4024 if (end_commit != NULL) {
4025 error = got_repo_match_object_id(&end_id, NULL,
4026 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4027 if (error != NULL)
4028 goto done;
4031 if (worktree) {
4033 * If a path was specified on the command line it was resolved
4034 * to a path in the work tree above. Prepend the work tree's
4035 * path prefix to obtain the corresponding in-repository path.
4037 if (path) {
4038 const char *prefix;
4039 prefix = got_worktree_get_path_prefix(worktree);
4040 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4041 (path[0] != '\0') ? "/" : "", path) == -1) {
4042 error = got_error_from_errno("asprintf");
4043 goto done;
4046 } else
4047 error = got_repo_map_path(&in_repo_path, repo,
4048 path ? path : "");
4049 if (error != NULL)
4050 goto done;
4051 if (in_repo_path) {
4052 free(path);
4053 path = in_repo_path;
4056 error = print_commits(start_id, end_id, repo, path ? path : "",
4057 show_changed_paths, show_patch, search_pattern, diff_context,
4058 limit, log_branches, reverse_display_order, refs_idmap);
4059 done:
4060 free(path);
4061 free(repo_path);
4062 free(cwd);
4063 if (worktree)
4064 got_worktree_close(worktree);
4065 if (repo) {
4066 const struct got_error *repo_error;
4067 repo_error = got_repo_close(repo);
4068 if (error == NULL)
4069 error = repo_error;
4071 if (refs_idmap)
4072 got_reflist_object_id_map_free(refs_idmap);
4073 got_ref_list_free(&refs);
4074 return error;
4077 __dead static void
4078 usage_diff(void)
4080 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4081 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4082 exit(1);
4085 struct print_diff_arg {
4086 struct got_repository *repo;
4087 struct got_worktree *worktree;
4088 int diff_context;
4089 const char *id_str;
4090 int header_shown;
4091 int diff_staged;
4092 int ignore_whitespace;
4093 int force_text_diff;
4097 * Create a file which contains the target path of a symlink so we can feed
4098 * it as content to the diff engine.
4100 static const struct got_error *
4101 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4102 const char *abspath)
4104 const struct got_error *err = NULL;
4105 char target_path[PATH_MAX];
4106 ssize_t target_len, outlen;
4108 *fd = -1;
4110 if (dirfd != -1) {
4111 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4112 if (target_len == -1)
4113 return got_error_from_errno2("readlinkat", abspath);
4114 } else {
4115 target_len = readlink(abspath, target_path, PATH_MAX);
4116 if (target_len == -1)
4117 return got_error_from_errno2("readlink", abspath);
4120 *fd = got_opentempfd();
4121 if (*fd == -1)
4122 return got_error_from_errno("got_opentempfd");
4124 outlen = write(*fd, target_path, target_len);
4125 if (outlen == -1) {
4126 err = got_error_from_errno("got_opentempfd");
4127 goto done;
4130 if (lseek(*fd, 0, SEEK_SET) == -1) {
4131 err = got_error_from_errno2("lseek", abspath);
4132 goto done;
4134 done:
4135 if (err) {
4136 close(*fd);
4137 *fd = -1;
4139 return err;
4142 static const struct got_error *
4143 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4144 const char *path, struct got_object_id *blob_id,
4145 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4146 int dirfd, const char *de_name)
4148 struct print_diff_arg *a = arg;
4149 const struct got_error *err = NULL;
4150 struct got_blob_object *blob1 = NULL;
4151 int fd = -1;
4152 FILE *f2 = NULL;
4153 char *abspath = NULL, *label1 = NULL;
4154 struct stat sb;
4156 if (a->diff_staged) {
4157 if (staged_status != GOT_STATUS_MODIFY &&
4158 staged_status != GOT_STATUS_ADD &&
4159 staged_status != GOT_STATUS_DELETE)
4160 return NULL;
4161 } else {
4162 if (staged_status == GOT_STATUS_DELETE)
4163 return NULL;
4164 if (status == GOT_STATUS_NONEXISTENT)
4165 return got_error_set_errno(ENOENT, path);
4166 if (status != GOT_STATUS_MODIFY &&
4167 status != GOT_STATUS_ADD &&
4168 status != GOT_STATUS_DELETE &&
4169 status != GOT_STATUS_CONFLICT)
4170 return NULL;
4173 if (!a->header_shown) {
4174 printf("diff %s %s%s\n", a->id_str,
4175 got_worktree_get_root_path(a->worktree),
4176 a->diff_staged ? " (staged changes)" : "");
4177 a->header_shown = 1;
4180 if (a->diff_staged) {
4181 const char *label1 = NULL, *label2 = NULL;
4182 switch (staged_status) {
4183 case GOT_STATUS_MODIFY:
4184 label1 = path;
4185 label2 = path;
4186 break;
4187 case GOT_STATUS_ADD:
4188 label2 = path;
4189 break;
4190 case GOT_STATUS_DELETE:
4191 label1 = path;
4192 break;
4193 default:
4194 return got_error(GOT_ERR_FILE_STATUS);
4196 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4197 staged_blob_id, label1, label2, a->diff_context,
4198 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4201 if (staged_status == GOT_STATUS_ADD ||
4202 staged_status == GOT_STATUS_MODIFY) {
4203 char *id_str;
4204 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4205 8192);
4206 if (err)
4207 goto done;
4208 err = got_object_id_str(&id_str, staged_blob_id);
4209 if (err)
4210 goto done;
4211 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4212 err = got_error_from_errno("asprintf");
4213 free(id_str);
4214 goto done;
4216 free(id_str);
4217 } else if (status != GOT_STATUS_ADD) {
4218 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4219 if (err)
4220 goto done;
4223 if (status != GOT_STATUS_DELETE) {
4224 if (asprintf(&abspath, "%s/%s",
4225 got_worktree_get_root_path(a->worktree), path) == -1) {
4226 err = got_error_from_errno("asprintf");
4227 goto done;
4230 if (dirfd != -1) {
4231 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4232 if (fd == -1) {
4233 if (errno != ELOOP) {
4234 err = got_error_from_errno2("openat",
4235 abspath);
4236 goto done;
4238 err = get_symlink_target_file(&fd, dirfd,
4239 de_name, abspath);
4240 if (err)
4241 goto done;
4243 } else {
4244 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4245 if (fd == -1) {
4246 if (errno != ELOOP) {
4247 err = got_error_from_errno2("open",
4248 abspath);
4249 goto done;
4251 err = get_symlink_target_file(&fd, dirfd,
4252 de_name, abspath);
4253 if (err)
4254 goto done;
4257 if (fstat(fd, &sb) == -1) {
4258 err = got_error_from_errno2("fstat", abspath);
4259 goto done;
4261 f2 = fdopen(fd, "r");
4262 if (f2 == NULL) {
4263 err = got_error_from_errno2("fdopen", abspath);
4264 goto done;
4266 fd = -1;
4267 } else
4268 sb.st_size = 0;
4270 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4271 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4272 done:
4273 if (blob1)
4274 got_object_blob_close(blob1);
4275 if (f2 && fclose(f2) == EOF && err == NULL)
4276 err = got_error_from_errno("fclose");
4277 if (fd != -1 && close(fd) == -1 && err == NULL)
4278 err = got_error_from_errno("close");
4279 free(abspath);
4280 return err;
4283 static const struct got_error *
4284 cmd_diff(int argc, char *argv[])
4286 const struct got_error *error;
4287 struct got_repository *repo = NULL;
4288 struct got_worktree *worktree = NULL;
4289 char *cwd = NULL, *repo_path = NULL;
4290 struct got_object_id *id1 = NULL, *id2 = NULL;
4291 const char *id_str1 = NULL, *id_str2 = NULL;
4292 char *label1 = NULL, *label2 = NULL;
4293 int type1, type2;
4294 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4295 int force_text_diff = 0;
4296 const char *errstr;
4297 char *path = NULL;
4298 struct got_reflist_head refs;
4300 TAILQ_INIT(&refs);
4302 #ifndef PROFILE
4303 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4304 NULL) == -1)
4305 err(1, "pledge");
4306 #endif
4308 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4309 switch (ch) {
4310 case 'a':
4311 force_text_diff = 1;
4312 break;
4313 case 'C':
4314 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4315 &errstr);
4316 if (errstr != NULL)
4317 err(1, "-C option %s", errstr);
4318 break;
4319 case 'r':
4320 repo_path = realpath(optarg, NULL);
4321 if (repo_path == NULL)
4322 return got_error_from_errno2("realpath",
4323 optarg);
4324 got_path_strip_trailing_slashes(repo_path);
4325 break;
4326 case 's':
4327 diff_staged = 1;
4328 break;
4329 case 'w':
4330 ignore_whitespace = 1;
4331 break;
4332 default:
4333 usage_diff();
4334 /* NOTREACHED */
4338 argc -= optind;
4339 argv += optind;
4341 cwd = getcwd(NULL, 0);
4342 if (cwd == NULL) {
4343 error = got_error_from_errno("getcwd");
4344 goto done;
4346 if (argc <= 1) {
4347 if (repo_path)
4348 errx(1,
4349 "-r option can't be used when diffing a work tree");
4350 error = got_worktree_open(&worktree, cwd);
4351 if (error) {
4352 if (error->code == GOT_ERR_NOT_WORKTREE)
4353 error = wrap_not_worktree_error(error, "diff",
4354 cwd);
4355 goto done;
4357 repo_path = strdup(got_worktree_get_repo_path(worktree));
4358 if (repo_path == NULL) {
4359 error = got_error_from_errno("strdup");
4360 goto done;
4362 if (argc == 1) {
4363 error = got_worktree_resolve_path(&path, worktree,
4364 argv[0]);
4365 if (error)
4366 goto done;
4367 } else {
4368 path = strdup("");
4369 if (path == NULL) {
4370 error = got_error_from_errno("strdup");
4371 goto done;
4374 } else if (argc == 2) {
4375 if (diff_staged)
4376 errx(1, "-s option can't be used when diffing "
4377 "objects in repository");
4378 id_str1 = argv[0];
4379 id_str2 = argv[1];
4380 if (repo_path == NULL) {
4381 error = got_worktree_open(&worktree, cwd);
4382 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4383 goto done;
4384 if (worktree) {
4385 repo_path = strdup(
4386 got_worktree_get_repo_path(worktree));
4387 if (repo_path == NULL) {
4388 error = got_error_from_errno("strdup");
4389 goto done;
4391 } else {
4392 repo_path = strdup(cwd);
4393 if (repo_path == NULL) {
4394 error = got_error_from_errno("strdup");
4395 goto done;
4399 } else
4400 usage_diff();
4402 error = got_repo_open(&repo, repo_path, NULL);
4403 free(repo_path);
4404 if (error != NULL)
4405 goto done;
4407 error = apply_unveil(got_repo_get_path(repo), 1,
4408 worktree ? got_worktree_get_root_path(worktree) : NULL);
4409 if (error)
4410 goto done;
4412 if (argc <= 1) {
4413 struct print_diff_arg arg;
4414 struct got_pathlist_head paths;
4415 char *id_str;
4417 TAILQ_INIT(&paths);
4419 error = got_object_id_str(&id_str,
4420 got_worktree_get_base_commit_id(worktree));
4421 if (error)
4422 goto done;
4423 arg.repo = repo;
4424 arg.worktree = worktree;
4425 arg.diff_context = diff_context;
4426 arg.id_str = id_str;
4427 arg.header_shown = 0;
4428 arg.diff_staged = diff_staged;
4429 arg.ignore_whitespace = ignore_whitespace;
4430 arg.force_text_diff = force_text_diff;
4432 error = got_pathlist_append(&paths, path, NULL);
4433 if (error)
4434 goto done;
4436 error = got_worktree_status(worktree, &paths, repo, print_diff,
4437 &arg, check_cancelled, NULL);
4438 free(id_str);
4439 got_pathlist_free(&paths);
4440 goto done;
4443 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4444 if (error)
4445 return error;
4447 error = got_repo_match_object_id(&id1, &label1, id_str1,
4448 GOT_OBJ_TYPE_ANY, &refs, repo);
4449 if (error)
4450 goto done;
4452 error = got_repo_match_object_id(&id2, &label2, id_str2,
4453 GOT_OBJ_TYPE_ANY, &refs, repo);
4454 if (error)
4455 goto done;
4457 error = got_object_get_type(&type1, repo, id1);
4458 if (error)
4459 goto done;
4461 error = got_object_get_type(&type2, repo, id2);
4462 if (error)
4463 goto done;
4465 if (type1 != type2) {
4466 error = got_error(GOT_ERR_OBJ_TYPE);
4467 goto done;
4470 switch (type1) {
4471 case GOT_OBJ_TYPE_BLOB:
4472 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4473 NULL, NULL, diff_context, ignore_whitespace,
4474 force_text_diff, repo, stdout);
4475 break;
4476 case GOT_OBJ_TYPE_TREE:
4477 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4478 "", "", diff_context, ignore_whitespace, force_text_diff,
4479 repo, stdout);
4480 break;
4481 case GOT_OBJ_TYPE_COMMIT:
4482 printf("diff %s %s\n", label1, label2);
4483 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4484 diff_context, ignore_whitespace, force_text_diff, repo,
4485 stdout);
4486 break;
4487 default:
4488 error = got_error(GOT_ERR_OBJ_TYPE);
4490 done:
4491 free(label1);
4492 free(label2);
4493 free(id1);
4494 free(id2);
4495 free(path);
4496 if (worktree)
4497 got_worktree_close(worktree);
4498 if (repo) {
4499 const struct got_error *repo_error;
4500 repo_error = got_repo_close(repo);
4501 if (error == NULL)
4502 error = repo_error;
4504 got_ref_list_free(&refs);
4505 return error;
4508 __dead static void
4509 usage_blame(void)
4511 fprintf(stderr,
4512 "usage: %s blame [-c commit] [-r repository-path] path\n",
4513 getprogname());
4514 exit(1);
4517 struct blame_line {
4518 int annotated;
4519 char *id_str;
4520 char *committer;
4521 char datebuf[11]; /* YYYY-MM-DD + NUL */
4524 struct blame_cb_args {
4525 struct blame_line *lines;
4526 int nlines;
4527 int nlines_prec;
4528 int lineno_cur;
4529 off_t *line_offsets;
4530 FILE *f;
4531 struct got_repository *repo;
4534 static const struct got_error *
4535 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4537 const struct got_error *err = NULL;
4538 struct blame_cb_args *a = arg;
4539 struct blame_line *bline;
4540 char *line = NULL;
4541 size_t linesize = 0;
4542 struct got_commit_object *commit = NULL;
4543 off_t offset;
4544 struct tm tm;
4545 time_t committer_time;
4547 if (nlines != a->nlines ||
4548 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4549 return got_error(GOT_ERR_RANGE);
4551 if (sigint_received)
4552 return got_error(GOT_ERR_ITER_COMPLETED);
4554 if (lineno == -1)
4555 return NULL; /* no change in this commit */
4557 /* Annotate this line. */
4558 bline = &a->lines[lineno - 1];
4559 if (bline->annotated)
4560 return NULL;
4561 err = got_object_id_str(&bline->id_str, id);
4562 if (err)
4563 return err;
4565 err = got_object_open_as_commit(&commit, a->repo, id);
4566 if (err)
4567 goto done;
4569 bline->committer = strdup(got_object_commit_get_committer(commit));
4570 if (bline->committer == NULL) {
4571 err = got_error_from_errno("strdup");
4572 goto done;
4575 committer_time = got_object_commit_get_committer_time(commit);
4576 if (localtime_r(&committer_time, &tm) == NULL)
4577 return got_error_from_errno("localtime_r");
4578 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4579 &tm) == 0) {
4580 err = got_error(GOT_ERR_NO_SPACE);
4581 goto done;
4583 bline->annotated = 1;
4585 /* Print lines annotated so far. */
4586 bline = &a->lines[a->lineno_cur - 1];
4587 if (!bline->annotated)
4588 goto done;
4590 offset = a->line_offsets[a->lineno_cur - 1];
4591 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4592 err = got_error_from_errno("fseeko");
4593 goto done;
4596 while (bline->annotated) {
4597 char *smallerthan, *at, *nl, *committer;
4598 size_t len;
4600 if (getline(&line, &linesize, a->f) == -1) {
4601 if (ferror(a->f))
4602 err = got_error_from_errno("getline");
4603 break;
4606 committer = bline->committer;
4607 smallerthan = strchr(committer, '<');
4608 if (smallerthan && smallerthan[1] != '\0')
4609 committer = smallerthan + 1;
4610 at = strchr(committer, '@');
4611 if (at)
4612 *at = '\0';
4613 len = strlen(committer);
4614 if (len >= 9)
4615 committer[8] = '\0';
4617 nl = strchr(line, '\n');
4618 if (nl)
4619 *nl = '\0';
4620 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4621 bline->id_str, bline->datebuf, committer, line);
4623 a->lineno_cur++;
4624 bline = &a->lines[a->lineno_cur - 1];
4626 done:
4627 if (commit)
4628 got_object_commit_close(commit);
4629 free(line);
4630 return err;
4633 static const struct got_error *
4634 cmd_blame(int argc, char *argv[])
4636 const struct got_error *error;
4637 struct got_repository *repo = NULL;
4638 struct got_worktree *worktree = NULL;
4639 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4640 char *link_target = NULL;
4641 struct got_object_id *obj_id = NULL;
4642 struct got_object_id *commit_id = NULL;
4643 struct got_blob_object *blob = NULL;
4644 char *commit_id_str = NULL;
4645 struct blame_cb_args bca;
4646 int ch, obj_type, i;
4647 off_t filesize;
4649 memset(&bca, 0, sizeof(bca));
4651 #ifndef PROFILE
4652 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4653 NULL) == -1)
4654 err(1, "pledge");
4655 #endif
4657 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4658 switch (ch) {
4659 case 'c':
4660 commit_id_str = optarg;
4661 break;
4662 case 'r':
4663 repo_path = realpath(optarg, NULL);
4664 if (repo_path == NULL)
4665 return got_error_from_errno2("realpath",
4666 optarg);
4667 got_path_strip_trailing_slashes(repo_path);
4668 break;
4669 default:
4670 usage_blame();
4671 /* NOTREACHED */
4675 argc -= optind;
4676 argv += optind;
4678 if (argc == 1)
4679 path = argv[0];
4680 else
4681 usage_blame();
4683 cwd = getcwd(NULL, 0);
4684 if (cwd == NULL) {
4685 error = got_error_from_errno("getcwd");
4686 goto done;
4688 if (repo_path == NULL) {
4689 error = got_worktree_open(&worktree, cwd);
4690 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4691 goto done;
4692 else
4693 error = NULL;
4694 if (worktree) {
4695 repo_path =
4696 strdup(got_worktree_get_repo_path(worktree));
4697 if (repo_path == NULL) {
4698 error = got_error_from_errno("strdup");
4699 if (error)
4700 goto done;
4702 } else {
4703 repo_path = strdup(cwd);
4704 if (repo_path == NULL) {
4705 error = got_error_from_errno("strdup");
4706 goto done;
4711 error = got_repo_open(&repo, repo_path, NULL);
4712 if (error != NULL)
4713 goto done;
4715 if (worktree) {
4716 const char *prefix = got_worktree_get_path_prefix(worktree);
4717 char *p;
4719 error = got_worktree_resolve_path(&p, worktree, path);
4720 if (error)
4721 goto done;
4722 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4723 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4724 p) == -1) {
4725 error = got_error_from_errno("asprintf");
4726 free(p);
4727 goto done;
4729 free(p);
4730 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4731 } else {
4732 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4733 if (error)
4734 goto done;
4735 error = got_repo_map_path(&in_repo_path, repo, path);
4737 if (error)
4738 goto done;
4740 if (commit_id_str == NULL) {
4741 struct got_reference *head_ref;
4742 error = got_ref_open(&head_ref, repo, worktree ?
4743 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4744 if (error != NULL)
4745 goto done;
4746 error = got_ref_resolve(&commit_id, repo, head_ref);
4747 got_ref_close(head_ref);
4748 if (error != NULL)
4749 goto done;
4750 } else {
4751 struct got_reflist_head refs;
4752 TAILQ_INIT(&refs);
4753 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4754 NULL);
4755 if (error)
4756 goto done;
4757 error = got_repo_match_object_id(&commit_id, NULL,
4758 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4759 got_ref_list_free(&refs);
4760 if (error)
4761 goto done;
4764 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4765 commit_id, repo);
4766 if (error)
4767 goto done;
4769 error = got_object_id_by_path(&obj_id, repo, commit_id,
4770 link_target ? link_target : in_repo_path);
4771 if (error)
4772 goto done;
4774 error = got_object_get_type(&obj_type, repo, obj_id);
4775 if (error)
4776 goto done;
4778 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4779 error = got_error_path(link_target ? link_target : in_repo_path,
4780 GOT_ERR_OBJ_TYPE);
4781 goto done;
4784 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4785 if (error)
4786 goto done;
4787 bca.f = got_opentemp();
4788 if (bca.f == NULL) {
4789 error = got_error_from_errno("got_opentemp");
4790 goto done;
4792 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4793 &bca.line_offsets, bca.f, blob);
4794 if (error || bca.nlines == 0)
4795 goto done;
4797 /* Don't include \n at EOF in the blame line count. */
4798 if (bca.line_offsets[bca.nlines - 1] == filesize)
4799 bca.nlines--;
4801 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4802 if (bca.lines == NULL) {
4803 error = got_error_from_errno("calloc");
4804 goto done;
4806 bca.lineno_cur = 1;
4807 bca.nlines_prec = 0;
4808 i = bca.nlines;
4809 while (i > 0) {
4810 i /= 10;
4811 bca.nlines_prec++;
4813 bca.repo = repo;
4815 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4816 repo, blame_cb, &bca, check_cancelled, NULL);
4817 done:
4818 free(in_repo_path);
4819 free(link_target);
4820 free(repo_path);
4821 free(cwd);
4822 free(commit_id);
4823 free(obj_id);
4824 if (blob)
4825 got_object_blob_close(blob);
4826 if (worktree)
4827 got_worktree_close(worktree);
4828 if (repo) {
4829 const struct got_error *repo_error;
4830 repo_error = got_repo_close(repo);
4831 if (error == NULL)
4832 error = repo_error;
4834 if (bca.lines) {
4835 for (i = 0; i < bca.nlines; i++) {
4836 struct blame_line *bline = &bca.lines[i];
4837 free(bline->id_str);
4838 free(bline->committer);
4840 free(bca.lines);
4842 free(bca.line_offsets);
4843 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4844 error = got_error_from_errno("fclose");
4845 return error;
4848 __dead static void
4849 usage_tree(void)
4851 fprintf(stderr,
4852 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4853 getprogname());
4854 exit(1);
4857 static const struct got_error *
4858 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4859 const char *root_path, struct got_repository *repo)
4861 const struct got_error *err = NULL;
4862 int is_root_path = (strcmp(path, root_path) == 0);
4863 const char *modestr = "";
4864 mode_t mode = got_tree_entry_get_mode(te);
4865 char *link_target = NULL;
4867 path += strlen(root_path);
4868 while (path[0] == '/')
4869 path++;
4871 if (got_object_tree_entry_is_submodule(te))
4872 modestr = "$";
4873 else if (S_ISLNK(mode)) {
4874 int i;
4876 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4877 if (err)
4878 return err;
4879 for (i = 0; i < strlen(link_target); i++) {
4880 if (!isprint((unsigned char)link_target[i]))
4881 link_target[i] = '?';
4884 modestr = "@";
4886 else if (S_ISDIR(mode))
4887 modestr = "/";
4888 else if (mode & S_IXUSR)
4889 modestr = "*";
4891 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4892 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4893 link_target ? " -> ": "", link_target ? link_target : "");
4895 free(link_target);
4896 return NULL;
4899 static const struct got_error *
4900 print_tree(const char *path, struct got_object_id *commit_id,
4901 int show_ids, int recurse, const char *root_path,
4902 struct got_repository *repo)
4904 const struct got_error *err = NULL;
4905 struct got_object_id *tree_id = NULL;
4906 struct got_tree_object *tree = NULL;
4907 int nentries, i;
4909 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4910 if (err)
4911 goto done;
4913 err = got_object_open_as_tree(&tree, repo, tree_id);
4914 if (err)
4915 goto done;
4916 nentries = got_object_tree_get_nentries(tree);
4917 for (i = 0; i < nentries; i++) {
4918 struct got_tree_entry *te;
4919 char *id = NULL;
4921 if (sigint_received || sigpipe_received)
4922 break;
4924 te = got_object_tree_get_entry(tree, i);
4925 if (show_ids) {
4926 char *id_str;
4927 err = got_object_id_str(&id_str,
4928 got_tree_entry_get_id(te));
4929 if (err)
4930 goto done;
4931 if (asprintf(&id, "%s ", id_str) == -1) {
4932 err = got_error_from_errno("asprintf");
4933 free(id_str);
4934 goto done;
4936 free(id_str);
4938 err = print_entry(te, id, path, root_path, repo);
4939 free(id);
4940 if (err)
4941 goto done;
4943 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4944 char *child_path;
4945 if (asprintf(&child_path, "%s%s%s", path,
4946 path[0] == '/' && path[1] == '\0' ? "" : "/",
4947 got_tree_entry_get_name(te)) == -1) {
4948 err = got_error_from_errno("asprintf");
4949 goto done;
4951 err = print_tree(child_path, commit_id, show_ids, 1,
4952 root_path, repo);
4953 free(child_path);
4954 if (err)
4955 goto done;
4958 done:
4959 if (tree)
4960 got_object_tree_close(tree);
4961 free(tree_id);
4962 return err;
4965 static const struct got_error *
4966 cmd_tree(int argc, char *argv[])
4968 const struct got_error *error;
4969 struct got_repository *repo = NULL;
4970 struct got_worktree *worktree = NULL;
4971 const char *path, *refname = NULL;
4972 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4973 struct got_object_id *commit_id = NULL;
4974 char *commit_id_str = NULL;
4975 int show_ids = 0, recurse = 0;
4976 int ch;
4978 #ifndef PROFILE
4979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4980 NULL) == -1)
4981 err(1, "pledge");
4982 #endif
4984 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4985 switch (ch) {
4986 case 'c':
4987 commit_id_str = optarg;
4988 break;
4989 case 'r':
4990 repo_path = realpath(optarg, NULL);
4991 if (repo_path == NULL)
4992 return got_error_from_errno2("realpath",
4993 optarg);
4994 got_path_strip_trailing_slashes(repo_path);
4995 break;
4996 case 'i':
4997 show_ids = 1;
4998 break;
4999 case 'R':
5000 recurse = 1;
5001 break;
5002 default:
5003 usage_tree();
5004 /* NOTREACHED */
5008 argc -= optind;
5009 argv += optind;
5011 if (argc == 1)
5012 path = argv[0];
5013 else if (argc > 1)
5014 usage_tree();
5015 else
5016 path = NULL;
5018 cwd = getcwd(NULL, 0);
5019 if (cwd == NULL) {
5020 error = got_error_from_errno("getcwd");
5021 goto done;
5023 if (repo_path == NULL) {
5024 error = got_worktree_open(&worktree, cwd);
5025 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5026 goto done;
5027 else
5028 error = NULL;
5029 if (worktree) {
5030 repo_path =
5031 strdup(got_worktree_get_repo_path(worktree));
5032 if (repo_path == NULL)
5033 error = got_error_from_errno("strdup");
5034 if (error)
5035 goto done;
5036 } else {
5037 repo_path = strdup(cwd);
5038 if (repo_path == NULL) {
5039 error = got_error_from_errno("strdup");
5040 goto done;
5045 error = got_repo_open(&repo, repo_path, NULL);
5046 if (error != NULL)
5047 goto done;
5049 if (worktree) {
5050 const char *prefix = got_worktree_get_path_prefix(worktree);
5051 char *p;
5053 if (path == NULL)
5054 path = "";
5055 error = got_worktree_resolve_path(&p, worktree, path);
5056 if (error)
5057 goto done;
5058 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5059 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5060 p) == -1) {
5061 error = got_error_from_errno("asprintf");
5062 free(p);
5063 goto done;
5065 free(p);
5066 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5067 if (error)
5068 goto done;
5069 } else {
5070 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5071 if (error)
5072 goto done;
5073 if (path == NULL)
5074 path = "/";
5075 error = got_repo_map_path(&in_repo_path, repo, path);
5076 if (error != NULL)
5077 goto done;
5080 if (commit_id_str == NULL) {
5081 struct got_reference *head_ref;
5082 if (worktree)
5083 refname = got_worktree_get_head_ref_name(worktree);
5084 else
5085 refname = GOT_REF_HEAD;
5086 error = got_ref_open(&head_ref, repo, refname, 0);
5087 if (error != NULL)
5088 goto done;
5089 error = got_ref_resolve(&commit_id, repo, head_ref);
5090 got_ref_close(head_ref);
5091 if (error != NULL)
5092 goto done;
5093 } else {
5094 struct got_reflist_head refs;
5095 TAILQ_INIT(&refs);
5096 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5097 NULL);
5098 if (error)
5099 goto done;
5100 error = got_repo_match_object_id(&commit_id, NULL,
5101 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5102 got_ref_list_free(&refs);
5103 if (error)
5104 goto done;
5107 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5108 in_repo_path, repo);
5109 done:
5110 free(in_repo_path);
5111 free(repo_path);
5112 free(cwd);
5113 free(commit_id);
5114 if (worktree)
5115 got_worktree_close(worktree);
5116 if (repo) {
5117 const struct got_error *repo_error;
5118 repo_error = got_repo_close(repo);
5119 if (error == NULL)
5120 error = repo_error;
5122 return error;
5125 __dead static void
5126 usage_status(void)
5128 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
5129 getprogname());
5130 exit(1);
5133 static const struct got_error *
5134 print_status(void *arg, unsigned char status, unsigned char staged_status,
5135 const char *path, struct got_object_id *blob_id,
5136 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5137 int dirfd, const char *de_name)
5139 if (status == staged_status && (status == GOT_STATUS_DELETE))
5140 status = GOT_STATUS_NO_CHANGE;
5141 if (arg) {
5142 char *status_codes = arg;
5143 size_t ncodes = strlen(status_codes);
5144 int i;
5145 for (i = 0; i < ncodes ; i++) {
5146 if (status == status_codes[i] ||
5147 staged_status == status_codes[i])
5148 break;
5150 if (i == ncodes)
5151 return NULL;
5153 printf("%c%c %s\n", status, staged_status, path);
5154 return NULL;
5157 static const struct got_error *
5158 cmd_status(int argc, char *argv[])
5160 const struct got_error *error = NULL;
5161 struct got_repository *repo = NULL;
5162 struct got_worktree *worktree = NULL;
5163 char *cwd = NULL, *status_codes = NULL;;
5164 struct got_pathlist_head paths;
5165 struct got_pathlist_entry *pe;
5166 int ch, i;
5168 TAILQ_INIT(&paths);
5170 while ((ch = getopt(argc, argv, "s:")) != -1) {
5171 switch (ch) {
5172 case 's':
5173 for (i = 0; i < strlen(optarg); i++) {
5174 switch (optarg[i]) {
5175 case GOT_STATUS_MODIFY:
5176 case GOT_STATUS_ADD:
5177 case GOT_STATUS_DELETE:
5178 case GOT_STATUS_CONFLICT:
5179 case GOT_STATUS_MISSING:
5180 case GOT_STATUS_OBSTRUCTED:
5181 case GOT_STATUS_UNVERSIONED:
5182 case GOT_STATUS_MODE_CHANGE:
5183 case GOT_STATUS_NONEXISTENT:
5184 break;
5185 default:
5186 errx(1, "invalid status code '%c'",
5187 optarg[i]);
5190 status_codes = optarg;
5191 break;
5192 default:
5193 usage_status();
5194 /* NOTREACHED */
5198 argc -= optind;
5199 argv += optind;
5201 #ifndef PROFILE
5202 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5203 NULL) == -1)
5204 err(1, "pledge");
5205 #endif
5206 cwd = getcwd(NULL, 0);
5207 if (cwd == NULL) {
5208 error = got_error_from_errno("getcwd");
5209 goto done;
5212 error = got_worktree_open(&worktree, cwd);
5213 if (error) {
5214 if (error->code == GOT_ERR_NOT_WORKTREE)
5215 error = wrap_not_worktree_error(error, "status", cwd);
5216 goto done;
5219 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5220 NULL);
5221 if (error != NULL)
5222 goto done;
5224 error = apply_unveil(got_repo_get_path(repo), 1,
5225 got_worktree_get_root_path(worktree));
5226 if (error)
5227 goto done;
5229 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5230 if (error)
5231 goto done;
5233 error = got_worktree_status(worktree, &paths, repo, print_status,
5234 status_codes, check_cancelled, NULL);
5235 done:
5236 TAILQ_FOREACH(pe, &paths, entry)
5237 free((char *)pe->path);
5238 got_pathlist_free(&paths);
5239 free(cwd);
5240 return error;
5243 __dead static void
5244 usage_ref(void)
5246 fprintf(stderr,
5247 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5248 "[-d] [name]\n",
5249 getprogname());
5250 exit(1);
5253 static const struct got_error *
5254 list_refs(struct got_repository *repo, const char *refname)
5256 static const struct got_error *err = NULL;
5257 struct got_reflist_head refs;
5258 struct got_reflist_entry *re;
5260 TAILQ_INIT(&refs);
5261 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5262 if (err)
5263 return err;
5265 TAILQ_FOREACH(re, &refs, entry) {
5266 char *refstr;
5267 refstr = got_ref_to_str(re->ref);
5268 if (refstr == NULL)
5269 return got_error_from_errno("got_ref_to_str");
5270 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5271 free(refstr);
5274 got_ref_list_free(&refs);
5275 return NULL;
5278 static const struct got_error *
5279 delete_ref(struct got_repository *repo, const char *refname)
5281 const struct got_error *err = NULL;
5282 struct got_reference *ref;
5284 err = got_ref_open(&ref, repo, refname, 0);
5285 if (err)
5286 return err;
5288 err = got_ref_delete(ref, repo);
5289 got_ref_close(ref);
5290 return err;
5293 static const struct got_error *
5294 add_ref(struct got_repository *repo, const char *refname, const char *target)
5296 const struct got_error *err = NULL;
5297 struct got_object_id *id;
5298 struct got_reference *ref = NULL;
5301 * Don't let the user create a reference name with a leading '-'.
5302 * While technically a valid reference name, this case is usually
5303 * an unintended typo.
5305 if (refname[0] == '-')
5306 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5308 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5309 repo);
5310 if (err) {
5311 struct got_reference *target_ref;
5313 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5314 return err;
5315 err = got_ref_open(&target_ref, repo, target, 0);
5316 if (err)
5317 return err;
5318 err = got_ref_resolve(&id, repo, target_ref);
5319 got_ref_close(target_ref);
5320 if (err)
5321 return err;
5324 err = got_ref_alloc(&ref, refname, id);
5325 if (err)
5326 goto done;
5328 err = got_ref_write(ref, repo);
5329 done:
5330 if (ref)
5331 got_ref_close(ref);
5332 free(id);
5333 return err;
5336 static const struct got_error *
5337 add_symref(struct got_repository *repo, const char *refname, const char *target)
5339 const struct got_error *err = NULL;
5340 struct got_reference *ref = NULL;
5341 struct got_reference *target_ref = NULL;
5344 * Don't let the user create a reference name with a leading '-'.
5345 * While technically a valid reference name, this case is usually
5346 * an unintended typo.
5348 if (refname[0] == '-')
5349 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5351 err = got_ref_open(&target_ref, repo, target, 0);
5352 if (err)
5353 return err;
5355 err = got_ref_alloc_symref(&ref, refname, target_ref);
5356 if (err)
5357 goto done;
5359 err = got_ref_write(ref, repo);
5360 done:
5361 if (target_ref)
5362 got_ref_close(target_ref);
5363 if (ref)
5364 got_ref_close(ref);
5365 return err;
5368 static const struct got_error *
5369 cmd_ref(int argc, char *argv[])
5371 const struct got_error *error = NULL;
5372 struct got_repository *repo = NULL;
5373 struct got_worktree *worktree = NULL;
5374 char *cwd = NULL, *repo_path = NULL;
5375 int ch, do_list = 0, do_delete = 0;
5376 const char *obj_arg = NULL, *symref_target= NULL;
5377 char *refname = NULL;
5379 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5380 switch (ch) {
5381 case 'c':
5382 obj_arg = optarg;
5383 break;
5384 case 'd':
5385 do_delete = 1;
5386 break;
5387 case 'r':
5388 repo_path = realpath(optarg, NULL);
5389 if (repo_path == NULL)
5390 return got_error_from_errno2("realpath",
5391 optarg);
5392 got_path_strip_trailing_slashes(repo_path);
5393 break;
5394 case 'l':
5395 do_list = 1;
5396 break;
5397 case 's':
5398 symref_target = optarg;
5399 break;
5400 default:
5401 usage_ref();
5402 /* NOTREACHED */
5406 if (obj_arg && do_list)
5407 option_conflict('c', 'l');
5408 if (obj_arg && do_delete)
5409 option_conflict('c', 'd');
5410 if (obj_arg && symref_target)
5411 option_conflict('c', 's');
5412 if (symref_target && do_delete)
5413 option_conflict('s', 'd');
5414 if (symref_target && do_list)
5415 option_conflict('s', 'l');
5416 if (do_delete && do_list)
5417 option_conflict('d', 'l');
5419 argc -= optind;
5420 argv += optind;
5422 if (do_list) {
5423 if (argc != 0 && argc != 1)
5424 usage_ref();
5425 if (argc == 1) {
5426 refname = strdup(argv[0]);
5427 if (refname == NULL) {
5428 error = got_error_from_errno("strdup");
5429 goto done;
5432 } else {
5433 if (argc != 1)
5434 usage_ref();
5435 refname = strdup(argv[0]);
5436 if (refname == NULL) {
5437 error = got_error_from_errno("strdup");
5438 goto done;
5442 if (refname)
5443 got_path_strip_trailing_slashes(refname);
5445 #ifndef PROFILE
5446 if (do_list) {
5447 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5448 NULL) == -1)
5449 err(1, "pledge");
5450 } else {
5451 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5452 "sendfd unveil", NULL) == -1)
5453 err(1, "pledge");
5455 #endif
5456 cwd = getcwd(NULL, 0);
5457 if (cwd == NULL) {
5458 error = got_error_from_errno("getcwd");
5459 goto done;
5462 if (repo_path == NULL) {
5463 error = got_worktree_open(&worktree, cwd);
5464 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5465 goto done;
5466 else
5467 error = NULL;
5468 if (worktree) {
5469 repo_path =
5470 strdup(got_worktree_get_repo_path(worktree));
5471 if (repo_path == NULL)
5472 error = got_error_from_errno("strdup");
5473 if (error)
5474 goto done;
5475 } else {
5476 repo_path = strdup(cwd);
5477 if (repo_path == NULL) {
5478 error = got_error_from_errno("strdup");
5479 goto done;
5484 error = got_repo_open(&repo, repo_path, NULL);
5485 if (error != NULL)
5486 goto done;
5488 error = apply_unveil(got_repo_get_path(repo), do_list,
5489 worktree ? got_worktree_get_root_path(worktree) : NULL);
5490 if (error)
5491 goto done;
5493 if (do_list)
5494 error = list_refs(repo, refname);
5495 else if (do_delete)
5496 error = delete_ref(repo, refname);
5497 else if (symref_target)
5498 error = add_symref(repo, refname, symref_target);
5499 else {
5500 if (obj_arg == NULL)
5501 usage_ref();
5502 error = add_ref(repo, refname, obj_arg);
5504 done:
5505 free(refname);
5506 if (repo)
5507 got_repo_close(repo);
5508 if (worktree)
5509 got_worktree_close(worktree);
5510 free(cwd);
5511 free(repo_path);
5512 return error;
5515 __dead static void
5516 usage_branch(void)
5518 fprintf(stderr,
5519 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5520 "[name]\n", getprogname());
5521 exit(1);
5524 static const struct got_error *
5525 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5526 struct got_reference *ref)
5528 const struct got_error *err = NULL;
5529 const char *refname, *marker = " ";
5530 char *refstr;
5532 refname = got_ref_get_name(ref);
5533 if (worktree && strcmp(refname,
5534 got_worktree_get_head_ref_name(worktree)) == 0) {
5535 struct got_object_id *id = NULL;
5537 err = got_ref_resolve(&id, repo, ref);
5538 if (err)
5539 return err;
5540 if (got_object_id_cmp(id,
5541 got_worktree_get_base_commit_id(worktree)) == 0)
5542 marker = "* ";
5543 else
5544 marker = "~ ";
5545 free(id);
5548 if (strncmp(refname, "refs/heads/", 11) == 0)
5549 refname += 11;
5550 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5551 refname += 18;
5552 if (strncmp(refname, "refs/remotes/", 13) == 0)
5553 refname += 13;
5555 refstr = got_ref_to_str(ref);
5556 if (refstr == NULL)
5557 return got_error_from_errno("got_ref_to_str");
5559 printf("%s%s: %s\n", marker, refname, refstr);
5560 free(refstr);
5561 return NULL;
5564 static const struct got_error *
5565 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5567 const char *refname;
5569 if (worktree == NULL)
5570 return got_error(GOT_ERR_NOT_WORKTREE);
5572 refname = got_worktree_get_head_ref_name(worktree);
5574 if (strncmp(refname, "refs/heads/", 11) == 0)
5575 refname += 11;
5576 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5577 refname += 18;
5579 printf("%s\n", refname);
5581 return NULL;
5584 static const struct got_error *
5585 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5587 static const struct got_error *err = NULL;
5588 struct got_reflist_head refs;
5589 struct got_reflist_entry *re;
5590 struct got_reference *temp_ref = NULL;
5591 int rebase_in_progress, histedit_in_progress;
5593 TAILQ_INIT(&refs);
5595 if (worktree) {
5596 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5597 worktree);
5598 if (err)
5599 return err;
5601 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5602 worktree);
5603 if (err)
5604 return err;
5606 if (rebase_in_progress || histedit_in_progress) {
5607 err = got_ref_open(&temp_ref, repo,
5608 got_worktree_get_head_ref_name(worktree), 0);
5609 if (err)
5610 return err;
5611 list_branch(repo, worktree, temp_ref);
5612 got_ref_close(temp_ref);
5616 err = got_ref_list(&refs, repo, "refs/heads",
5617 got_ref_cmp_by_name, NULL);
5618 if (err)
5619 return err;
5621 TAILQ_FOREACH(re, &refs, entry)
5622 list_branch(repo, worktree, re->ref);
5624 got_ref_list_free(&refs);
5626 err = got_ref_list(&refs, repo, "refs/remotes",
5627 got_ref_cmp_by_name, NULL);
5628 if (err)
5629 return err;
5631 TAILQ_FOREACH(re, &refs, entry)
5632 list_branch(repo, worktree, re->ref);
5634 got_ref_list_free(&refs);
5636 return NULL;
5639 static const struct got_error *
5640 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5641 const char *branch_name)
5643 const struct got_error *err = NULL;
5644 struct got_reference *ref = NULL;
5645 char *refname;
5647 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5648 return got_error_from_errno("asprintf");
5650 err = got_ref_open(&ref, repo, refname, 0);
5651 if (err)
5652 goto done;
5654 if (worktree &&
5655 strcmp(got_worktree_get_head_ref_name(worktree),
5656 got_ref_get_name(ref)) == 0) {
5657 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5658 "will not delete this work tree's current branch");
5659 goto done;
5662 err = got_ref_delete(ref, repo);
5663 done:
5664 if (ref)
5665 got_ref_close(ref);
5666 free(refname);
5667 return err;
5670 static const struct got_error *
5671 add_branch(struct got_repository *repo, const char *branch_name,
5672 struct got_object_id *base_commit_id)
5674 const struct got_error *err = NULL;
5675 struct got_reference *ref = NULL;
5676 char *base_refname = NULL, *refname = NULL;
5679 * Don't let the user create a branch name with a leading '-'.
5680 * While technically a valid reference name, this case is usually
5681 * an unintended typo.
5683 if (branch_name[0] == '-')
5684 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5686 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5687 err = got_error_from_errno("asprintf");
5688 goto done;
5691 err = got_ref_open(&ref, repo, refname, 0);
5692 if (err == NULL) {
5693 err = got_error(GOT_ERR_BRANCH_EXISTS);
5694 goto done;
5695 } else if (err->code != GOT_ERR_NOT_REF)
5696 goto done;
5698 err = got_ref_alloc(&ref, refname, base_commit_id);
5699 if (err)
5700 goto done;
5702 err = got_ref_write(ref, repo);
5703 done:
5704 if (ref)
5705 got_ref_close(ref);
5706 free(base_refname);
5707 free(refname);
5708 return err;
5711 static const struct got_error *
5712 cmd_branch(int argc, char *argv[])
5714 const struct got_error *error = NULL;
5715 struct got_repository *repo = NULL;
5716 struct got_worktree *worktree = NULL;
5717 char *cwd = NULL, *repo_path = NULL;
5718 int ch, do_list = 0, do_show = 0, do_update = 1;
5719 const char *delref = NULL, *commit_id_arg = NULL;
5720 struct got_reference *ref = NULL;
5721 struct got_pathlist_head paths;
5722 struct got_pathlist_entry *pe;
5723 struct got_object_id *commit_id = NULL;
5724 char *commit_id_str = NULL;
5726 TAILQ_INIT(&paths);
5728 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5729 switch (ch) {
5730 case 'c':
5731 commit_id_arg = optarg;
5732 break;
5733 case 'd':
5734 delref = optarg;
5735 break;
5736 case 'r':
5737 repo_path = realpath(optarg, NULL);
5738 if (repo_path == NULL)
5739 return got_error_from_errno2("realpath",
5740 optarg);
5741 got_path_strip_trailing_slashes(repo_path);
5742 break;
5743 case 'l':
5744 do_list = 1;
5745 break;
5746 case 'n':
5747 do_update = 0;
5748 break;
5749 default:
5750 usage_branch();
5751 /* NOTREACHED */
5755 if (do_list && delref)
5756 option_conflict('l', 'd');
5758 argc -= optind;
5759 argv += optind;
5761 if (!do_list && !delref && argc == 0)
5762 do_show = 1;
5764 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5765 errx(1, "-c option can only be used when creating a branch");
5767 if (do_list || delref) {
5768 if (argc > 0)
5769 usage_branch();
5770 } else if (!do_show && argc != 1)
5771 usage_branch();
5773 #ifndef PROFILE
5774 if (do_list || do_show) {
5775 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5776 NULL) == -1)
5777 err(1, "pledge");
5778 } else {
5779 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5780 "sendfd unveil", NULL) == -1)
5781 err(1, "pledge");
5783 #endif
5784 cwd = getcwd(NULL, 0);
5785 if (cwd == NULL) {
5786 error = got_error_from_errno("getcwd");
5787 goto done;
5790 if (repo_path == NULL) {
5791 error = got_worktree_open(&worktree, cwd);
5792 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5793 goto done;
5794 else
5795 error = NULL;
5796 if (worktree) {
5797 repo_path =
5798 strdup(got_worktree_get_repo_path(worktree));
5799 if (repo_path == NULL)
5800 error = got_error_from_errno("strdup");
5801 if (error)
5802 goto done;
5803 } else {
5804 repo_path = strdup(cwd);
5805 if (repo_path == NULL) {
5806 error = got_error_from_errno("strdup");
5807 goto done;
5812 error = got_repo_open(&repo, repo_path, NULL);
5813 if (error != NULL)
5814 goto done;
5816 error = apply_unveil(got_repo_get_path(repo), do_list,
5817 worktree ? got_worktree_get_root_path(worktree) : NULL);
5818 if (error)
5819 goto done;
5821 if (do_show)
5822 error = show_current_branch(repo, worktree);
5823 else if (do_list)
5824 error = list_branches(repo, worktree);
5825 else if (delref)
5826 error = delete_branch(repo, worktree, delref);
5827 else {
5828 struct got_reflist_head refs;
5829 TAILQ_INIT(&refs);
5830 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5831 NULL);
5832 if (error)
5833 goto done;
5834 if (commit_id_arg == NULL)
5835 commit_id_arg = worktree ?
5836 got_worktree_get_head_ref_name(worktree) :
5837 GOT_REF_HEAD;
5838 error = got_repo_match_object_id(&commit_id, NULL,
5839 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5840 got_ref_list_free(&refs);
5841 if (error)
5842 goto done;
5843 error = add_branch(repo, argv[0], commit_id);
5844 if (error)
5845 goto done;
5846 if (worktree && do_update) {
5847 struct got_update_progress_arg upa;
5848 char *branch_refname = NULL;
5850 error = got_object_id_str(&commit_id_str, commit_id);
5851 if (error)
5852 goto done;
5853 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5854 worktree);
5855 if (error)
5856 goto done;
5857 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5858 == -1) {
5859 error = got_error_from_errno("asprintf");
5860 goto done;
5862 error = got_ref_open(&ref, repo, branch_refname, 0);
5863 free(branch_refname);
5864 if (error)
5865 goto done;
5866 error = switch_head_ref(ref, commit_id, worktree,
5867 repo);
5868 if (error)
5869 goto done;
5870 error = got_worktree_set_base_commit_id(worktree, repo,
5871 commit_id);
5872 if (error)
5873 goto done;
5874 memset(&upa, 0, sizeof(upa));
5875 error = got_worktree_checkout_files(worktree, &paths,
5876 repo, update_progress, &upa, check_cancelled,
5877 NULL);
5878 if (error)
5879 goto done;
5880 if (upa.did_something)
5881 printf("Updated to commit %s\n", commit_id_str);
5882 print_update_progress_stats(&upa);
5885 done:
5886 if (ref)
5887 got_ref_close(ref);
5888 if (repo)
5889 got_repo_close(repo);
5890 if (worktree)
5891 got_worktree_close(worktree);
5892 free(cwd);
5893 free(repo_path);
5894 free(commit_id);
5895 free(commit_id_str);
5896 TAILQ_FOREACH(pe, &paths, entry)
5897 free((char *)pe->path);
5898 got_pathlist_free(&paths);
5899 return error;
5903 __dead static void
5904 usage_tag(void)
5906 fprintf(stderr,
5907 "usage: %s tag [-c commit] [-r repository] [-l] "
5908 "[-m message] name\n", getprogname());
5909 exit(1);
5912 #if 0
5913 static const struct got_error *
5914 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5916 const struct got_error *err = NULL;
5917 struct got_reflist_entry *re, *se, *new;
5918 struct got_object_id *re_id, *se_id;
5919 struct got_tag_object *re_tag, *se_tag;
5920 time_t re_time, se_time;
5922 SIMPLEQ_FOREACH(re, tags, entry) {
5923 se = SIMPLEQ_FIRST(sorted);
5924 if (se == NULL) {
5925 err = got_reflist_entry_dup(&new, re);
5926 if (err)
5927 return err;
5928 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5929 continue;
5930 } else {
5931 err = got_ref_resolve(&re_id, repo, re->ref);
5932 if (err)
5933 break;
5934 err = got_object_open_as_tag(&re_tag, repo, re_id);
5935 free(re_id);
5936 if (err)
5937 break;
5938 re_time = got_object_tag_get_tagger_time(re_tag);
5939 got_object_tag_close(re_tag);
5942 while (se) {
5943 err = got_ref_resolve(&se_id, repo, re->ref);
5944 if (err)
5945 break;
5946 err = got_object_open_as_tag(&se_tag, repo, se_id);
5947 free(se_id);
5948 if (err)
5949 break;
5950 se_time = got_object_tag_get_tagger_time(se_tag);
5951 got_object_tag_close(se_tag);
5953 if (se_time > re_time) {
5954 err = got_reflist_entry_dup(&new, re);
5955 if (err)
5956 return err;
5957 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5958 break;
5960 se = SIMPLEQ_NEXT(se, entry);
5961 continue;
5964 done:
5965 return err;
5967 #endif
5969 static const struct got_error *
5970 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5972 static const struct got_error *err = NULL;
5973 struct got_reflist_head refs;
5974 struct got_reflist_entry *re;
5976 TAILQ_INIT(&refs);
5978 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5979 if (err)
5980 return err;
5982 TAILQ_FOREACH(re, &refs, entry) {
5983 const char *refname;
5984 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5985 char datebuf[26];
5986 const char *tagger;
5987 time_t tagger_time;
5988 struct got_object_id *id;
5989 struct got_tag_object *tag;
5990 struct got_commit_object *commit = NULL;
5992 refname = got_ref_get_name(re->ref);
5993 if (strncmp(refname, "refs/tags/", 10) != 0)
5994 continue;
5995 refname += 10;
5996 refstr = got_ref_to_str(re->ref);
5997 if (refstr == NULL) {
5998 err = got_error_from_errno("got_ref_to_str");
5999 break;
6001 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6002 free(refstr);
6004 err = got_ref_resolve(&id, repo, re->ref);
6005 if (err)
6006 break;
6007 err = got_object_open_as_tag(&tag, repo, id);
6008 if (err) {
6009 if (err->code != GOT_ERR_OBJ_TYPE) {
6010 free(id);
6011 break;
6013 /* "lightweight" tag */
6014 err = got_object_open_as_commit(&commit, repo, id);
6015 if (err) {
6016 free(id);
6017 break;
6019 tagger = got_object_commit_get_committer(commit);
6020 tagger_time =
6021 got_object_commit_get_committer_time(commit);
6022 err = got_object_id_str(&id_str, id);
6023 free(id);
6024 if (err)
6025 break;
6026 } else {
6027 free(id);
6028 tagger = got_object_tag_get_tagger(tag);
6029 tagger_time = got_object_tag_get_tagger_time(tag);
6030 err = got_object_id_str(&id_str,
6031 got_object_tag_get_object_id(tag));
6032 if (err)
6033 break;
6035 printf("from: %s\n", tagger);
6036 datestr = get_datestr(&tagger_time, datebuf);
6037 if (datestr)
6038 printf("date: %s UTC\n", datestr);
6039 if (commit)
6040 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6041 else {
6042 switch (got_object_tag_get_object_type(tag)) {
6043 case GOT_OBJ_TYPE_BLOB:
6044 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6045 id_str);
6046 break;
6047 case GOT_OBJ_TYPE_TREE:
6048 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6049 id_str);
6050 break;
6051 case GOT_OBJ_TYPE_COMMIT:
6052 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6053 id_str);
6054 break;
6055 case GOT_OBJ_TYPE_TAG:
6056 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6057 id_str);
6058 break;
6059 default:
6060 break;
6063 free(id_str);
6064 if (commit) {
6065 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6066 if (err)
6067 break;
6068 got_object_commit_close(commit);
6069 } else {
6070 tagmsg0 = strdup(got_object_tag_get_message(tag));
6071 got_object_tag_close(tag);
6072 if (tagmsg0 == NULL) {
6073 err = got_error_from_errno("strdup");
6074 break;
6078 tagmsg = tagmsg0;
6079 do {
6080 line = strsep(&tagmsg, "\n");
6081 if (line)
6082 printf(" %s\n", line);
6083 } while (line);
6084 free(tagmsg0);
6087 got_ref_list_free(&refs);
6088 return NULL;
6091 static const struct got_error *
6092 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6093 const char *tag_name, const char *repo_path)
6095 const struct got_error *err = NULL;
6096 char *template = NULL, *initial_content = NULL;
6097 char *editor = NULL;
6098 int initial_content_len;
6099 int fd = -1;
6101 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6102 err = got_error_from_errno("asprintf");
6103 goto done;
6106 initial_content_len = asprintf(&initial_content,
6107 "\n# tagging commit %s as %s\n",
6108 commit_id_str, tag_name);
6109 if (initial_content_len == -1) {
6110 err = got_error_from_errno("asprintf");
6111 goto done;
6114 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6115 if (err)
6116 goto done;
6118 if (write(fd, initial_content, initial_content_len) == -1) {
6119 err = got_error_from_errno2("write", *tagmsg_path);
6120 goto done;
6123 err = get_editor(&editor);
6124 if (err)
6125 goto done;
6126 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6127 initial_content_len, 1);
6128 done:
6129 free(initial_content);
6130 free(template);
6131 free(editor);
6133 if (fd != -1 && close(fd) == -1 && err == NULL)
6134 err = got_error_from_errno2("close", *tagmsg_path);
6136 /* Editor is done; we can now apply unveil(2) */
6137 if (err == NULL)
6138 err = apply_unveil(repo_path, 0, NULL);
6139 if (err) {
6140 free(*tagmsg);
6141 *tagmsg = NULL;
6143 return err;
6146 static const struct got_error *
6147 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6148 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6150 const struct got_error *err = NULL;
6151 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6152 char *label = NULL, *commit_id_str = NULL;
6153 struct got_reference *ref = NULL;
6154 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6155 char *tagmsg_path = NULL, *tag_id_str = NULL;
6156 int preserve_tagmsg = 0;
6157 struct got_reflist_head refs;
6159 TAILQ_INIT(&refs);
6162 * Don't let the user create a tag name with a leading '-'.
6163 * While technically a valid reference name, this case is usually
6164 * an unintended typo.
6166 if (tag_name[0] == '-')
6167 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6169 err = get_author(&tagger, repo, worktree);
6170 if (err)
6171 return err;
6173 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6174 if (err)
6175 goto done;
6177 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6178 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6179 if (err)
6180 goto done;
6182 err = got_object_id_str(&commit_id_str, commit_id);
6183 if (err)
6184 goto done;
6186 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6187 refname = strdup(tag_name);
6188 if (refname == NULL) {
6189 err = got_error_from_errno("strdup");
6190 goto done;
6192 tag_name += 10;
6193 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6194 err = got_error_from_errno("asprintf");
6195 goto done;
6198 err = got_ref_open(&ref, repo, refname, 0);
6199 if (err == NULL) {
6200 err = got_error(GOT_ERR_TAG_EXISTS);
6201 goto done;
6202 } else if (err->code != GOT_ERR_NOT_REF)
6203 goto done;
6205 if (tagmsg_arg == NULL) {
6206 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6207 tag_name, got_repo_get_path(repo));
6208 if (err) {
6209 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6210 tagmsg_path != NULL)
6211 preserve_tagmsg = 1;
6212 goto done;
6216 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6217 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6218 if (err) {
6219 if (tagmsg_path)
6220 preserve_tagmsg = 1;
6221 goto done;
6224 err = got_ref_alloc(&ref, refname, tag_id);
6225 if (err) {
6226 if (tagmsg_path)
6227 preserve_tagmsg = 1;
6228 goto done;
6231 err = got_ref_write(ref, repo);
6232 if (err) {
6233 if (tagmsg_path)
6234 preserve_tagmsg = 1;
6235 goto done;
6238 err = got_object_id_str(&tag_id_str, tag_id);
6239 if (err) {
6240 if (tagmsg_path)
6241 preserve_tagmsg = 1;
6242 goto done;
6244 printf("Created tag %s\n", tag_id_str);
6245 done:
6246 if (preserve_tagmsg) {
6247 fprintf(stderr, "%s: tag message preserved in %s\n",
6248 getprogname(), tagmsg_path);
6249 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6250 err = got_error_from_errno2("unlink", tagmsg_path);
6251 free(tag_id_str);
6252 if (ref)
6253 got_ref_close(ref);
6254 free(commit_id);
6255 free(commit_id_str);
6256 free(refname);
6257 free(tagmsg);
6258 free(tagmsg_path);
6259 free(tagger);
6260 got_ref_list_free(&refs);
6261 return err;
6264 static const struct got_error *
6265 cmd_tag(int argc, char *argv[])
6267 const struct got_error *error = NULL;
6268 struct got_repository *repo = NULL;
6269 struct got_worktree *worktree = NULL;
6270 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6271 char *gitconfig_path = NULL;
6272 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6273 int ch, do_list = 0;
6275 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6276 switch (ch) {
6277 case 'c':
6278 commit_id_arg = optarg;
6279 break;
6280 case 'm':
6281 tagmsg = optarg;
6282 break;
6283 case 'r':
6284 repo_path = realpath(optarg, NULL);
6285 if (repo_path == NULL)
6286 return got_error_from_errno2("realpath",
6287 optarg);
6288 got_path_strip_trailing_slashes(repo_path);
6289 break;
6290 case 'l':
6291 do_list = 1;
6292 break;
6293 default:
6294 usage_tag();
6295 /* NOTREACHED */
6299 argc -= optind;
6300 argv += optind;
6302 if (do_list) {
6303 if (commit_id_arg != NULL)
6304 errx(1,
6305 "-c option can only be used when creating a tag");
6306 if (tagmsg)
6307 option_conflict('l', 'm');
6308 if (argc > 0)
6309 usage_tag();
6310 } else if (argc != 1)
6311 usage_tag();
6313 tag_name = argv[0];
6315 #ifndef PROFILE
6316 if (do_list) {
6317 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6318 NULL) == -1)
6319 err(1, "pledge");
6320 } else {
6321 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6322 "sendfd unveil", NULL) == -1)
6323 err(1, "pledge");
6325 #endif
6326 cwd = getcwd(NULL, 0);
6327 if (cwd == NULL) {
6328 error = got_error_from_errno("getcwd");
6329 goto done;
6332 if (repo_path == NULL) {
6333 error = got_worktree_open(&worktree, cwd);
6334 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6335 goto done;
6336 else
6337 error = NULL;
6338 if (worktree) {
6339 repo_path =
6340 strdup(got_worktree_get_repo_path(worktree));
6341 if (repo_path == NULL)
6342 error = got_error_from_errno("strdup");
6343 if (error)
6344 goto done;
6345 } else {
6346 repo_path = strdup(cwd);
6347 if (repo_path == NULL) {
6348 error = got_error_from_errno("strdup");
6349 goto done;
6354 if (do_list) {
6355 error = got_repo_open(&repo, repo_path, NULL);
6356 if (error != NULL)
6357 goto done;
6358 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6359 if (error)
6360 goto done;
6361 error = list_tags(repo, worktree);
6362 } else {
6363 error = get_gitconfig_path(&gitconfig_path);
6364 if (error)
6365 goto done;
6366 error = got_repo_open(&repo, repo_path, gitconfig_path);
6367 if (error != NULL)
6368 goto done;
6370 if (tagmsg) {
6371 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6372 if (error)
6373 goto done;
6376 if (commit_id_arg == NULL) {
6377 struct got_reference *head_ref;
6378 struct got_object_id *commit_id;
6379 error = got_ref_open(&head_ref, repo,
6380 worktree ? got_worktree_get_head_ref_name(worktree)
6381 : GOT_REF_HEAD, 0);
6382 if (error)
6383 goto done;
6384 error = got_ref_resolve(&commit_id, repo, head_ref);
6385 got_ref_close(head_ref);
6386 if (error)
6387 goto done;
6388 error = got_object_id_str(&commit_id_str, commit_id);
6389 free(commit_id);
6390 if (error)
6391 goto done;
6394 error = add_tag(repo, worktree, tag_name,
6395 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6397 done:
6398 if (repo)
6399 got_repo_close(repo);
6400 if (worktree)
6401 got_worktree_close(worktree);
6402 free(cwd);
6403 free(repo_path);
6404 free(gitconfig_path);
6405 free(commit_id_str);
6406 return error;
6409 __dead static void
6410 usage_add(void)
6412 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6413 getprogname());
6414 exit(1);
6417 static const struct got_error *
6418 add_progress(void *arg, unsigned char status, const char *path)
6420 while (path[0] == '/')
6421 path++;
6422 printf("%c %s\n", status, path);
6423 return NULL;
6426 static const struct got_error *
6427 cmd_add(int argc, char *argv[])
6429 const struct got_error *error = NULL;
6430 struct got_repository *repo = NULL;
6431 struct got_worktree *worktree = NULL;
6432 char *cwd = NULL;
6433 struct got_pathlist_head paths;
6434 struct got_pathlist_entry *pe;
6435 int ch, can_recurse = 0, no_ignores = 0;
6437 TAILQ_INIT(&paths);
6439 while ((ch = getopt(argc, argv, "IR")) != -1) {
6440 switch (ch) {
6441 case 'I':
6442 no_ignores = 1;
6443 break;
6444 case 'R':
6445 can_recurse = 1;
6446 break;
6447 default:
6448 usage_add();
6449 /* NOTREACHED */
6453 argc -= optind;
6454 argv += optind;
6456 #ifndef PROFILE
6457 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6458 NULL) == -1)
6459 err(1, "pledge");
6460 #endif
6461 if (argc < 1)
6462 usage_add();
6464 cwd = getcwd(NULL, 0);
6465 if (cwd == NULL) {
6466 error = got_error_from_errno("getcwd");
6467 goto done;
6470 error = got_worktree_open(&worktree, cwd);
6471 if (error) {
6472 if (error->code == GOT_ERR_NOT_WORKTREE)
6473 error = wrap_not_worktree_error(error, "add", cwd);
6474 goto done;
6477 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6478 NULL);
6479 if (error != NULL)
6480 goto done;
6482 error = apply_unveil(got_repo_get_path(repo), 1,
6483 got_worktree_get_root_path(worktree));
6484 if (error)
6485 goto done;
6487 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6488 if (error)
6489 goto done;
6491 if (!can_recurse && no_ignores) {
6492 error = got_error_msg(GOT_ERR_BAD_PATH,
6493 "disregarding ignores requires -R option");
6494 goto done;
6498 if (!can_recurse) {
6499 char *ondisk_path;
6500 struct stat sb;
6501 TAILQ_FOREACH(pe, &paths, entry) {
6502 if (asprintf(&ondisk_path, "%s/%s",
6503 got_worktree_get_root_path(worktree),
6504 pe->path) == -1) {
6505 error = got_error_from_errno("asprintf");
6506 goto done;
6508 if (lstat(ondisk_path, &sb) == -1) {
6509 if (errno == ENOENT) {
6510 free(ondisk_path);
6511 continue;
6513 error = got_error_from_errno2("lstat",
6514 ondisk_path);
6515 free(ondisk_path);
6516 goto done;
6518 free(ondisk_path);
6519 if (S_ISDIR(sb.st_mode)) {
6520 error = got_error_msg(GOT_ERR_BAD_PATH,
6521 "adding directories requires -R option");
6522 goto done;
6527 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6528 NULL, repo, no_ignores);
6529 done:
6530 if (repo)
6531 got_repo_close(repo);
6532 if (worktree)
6533 got_worktree_close(worktree);
6534 TAILQ_FOREACH(pe, &paths, entry)
6535 free((char *)pe->path);
6536 got_pathlist_free(&paths);
6537 free(cwd);
6538 return error;
6541 __dead static void
6542 usage_remove(void)
6544 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6545 "path ...\n", getprogname());
6546 exit(1);
6549 static const struct got_error *
6550 print_remove_status(void *arg, unsigned char status,
6551 unsigned char staged_status, const char *path)
6553 while (path[0] == '/')
6554 path++;
6555 if (status == GOT_STATUS_NONEXISTENT)
6556 return NULL;
6557 if (status == staged_status && (status == GOT_STATUS_DELETE))
6558 status = GOT_STATUS_NO_CHANGE;
6559 printf("%c%c %s\n", status, staged_status, path);
6560 return NULL;
6563 static const struct got_error *
6564 cmd_remove(int argc, char *argv[])
6566 const struct got_error *error = NULL;
6567 struct got_worktree *worktree = NULL;
6568 struct got_repository *repo = NULL;
6569 const char *status_codes = NULL;
6570 char *cwd = NULL;
6571 struct got_pathlist_head paths;
6572 struct got_pathlist_entry *pe;
6573 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6575 TAILQ_INIT(&paths);
6577 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6578 switch (ch) {
6579 case 'f':
6580 delete_local_mods = 1;
6581 break;
6582 case 'k':
6583 keep_on_disk = 1;
6584 break;
6585 case 'R':
6586 can_recurse = 1;
6587 break;
6588 case 's':
6589 for (i = 0; i < strlen(optarg); i++) {
6590 switch (optarg[i]) {
6591 case GOT_STATUS_MODIFY:
6592 delete_local_mods = 1;
6593 break;
6594 case GOT_STATUS_MISSING:
6595 break;
6596 default:
6597 errx(1, "invalid status code '%c'",
6598 optarg[i]);
6601 status_codes = optarg;
6602 break;
6603 default:
6604 usage_remove();
6605 /* NOTREACHED */
6609 argc -= optind;
6610 argv += optind;
6612 #ifndef PROFILE
6613 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6614 NULL) == -1)
6615 err(1, "pledge");
6616 #endif
6617 if (argc < 1)
6618 usage_remove();
6620 cwd = getcwd(NULL, 0);
6621 if (cwd == NULL) {
6622 error = got_error_from_errno("getcwd");
6623 goto done;
6625 error = got_worktree_open(&worktree, cwd);
6626 if (error) {
6627 if (error->code == GOT_ERR_NOT_WORKTREE)
6628 error = wrap_not_worktree_error(error, "remove", cwd);
6629 goto done;
6632 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6633 NULL);
6634 if (error)
6635 goto done;
6637 error = apply_unveil(got_repo_get_path(repo), 1,
6638 got_worktree_get_root_path(worktree));
6639 if (error)
6640 goto done;
6642 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6643 if (error)
6644 goto done;
6646 if (!can_recurse) {
6647 char *ondisk_path;
6648 struct stat sb;
6649 TAILQ_FOREACH(pe, &paths, entry) {
6650 if (asprintf(&ondisk_path, "%s/%s",
6651 got_worktree_get_root_path(worktree),
6652 pe->path) == -1) {
6653 error = got_error_from_errno("asprintf");
6654 goto done;
6656 if (lstat(ondisk_path, &sb) == -1) {
6657 if (errno == ENOENT) {
6658 free(ondisk_path);
6659 continue;
6661 error = got_error_from_errno2("lstat",
6662 ondisk_path);
6663 free(ondisk_path);
6664 goto done;
6666 free(ondisk_path);
6667 if (S_ISDIR(sb.st_mode)) {
6668 error = got_error_msg(GOT_ERR_BAD_PATH,
6669 "removing directories requires -R option");
6670 goto done;
6675 error = got_worktree_schedule_delete(worktree, &paths,
6676 delete_local_mods, status_codes, print_remove_status, NULL,
6677 repo, keep_on_disk);
6678 done:
6679 if (repo)
6680 got_repo_close(repo);
6681 if (worktree)
6682 got_worktree_close(worktree);
6683 TAILQ_FOREACH(pe, &paths, entry)
6684 free((char *)pe->path);
6685 got_pathlist_free(&paths);
6686 free(cwd);
6687 return error;
6690 __dead static void
6691 usage_revert(void)
6693 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6694 "path ...\n", getprogname());
6695 exit(1);
6698 static const struct got_error *
6699 revert_progress(void *arg, unsigned char status, const char *path)
6701 if (status == GOT_STATUS_UNVERSIONED)
6702 return NULL;
6704 while (path[0] == '/')
6705 path++;
6706 printf("%c %s\n", status, path);
6707 return NULL;
6710 struct choose_patch_arg {
6711 FILE *patch_script_file;
6712 const char *action;
6715 static const struct got_error *
6716 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6717 int nchanges, const char *action)
6719 char *line = NULL;
6720 size_t linesize = 0;
6721 ssize_t linelen;
6723 switch (status) {
6724 case GOT_STATUS_ADD:
6725 printf("A %s\n%s this addition? [y/n] ", path, action);
6726 break;
6727 case GOT_STATUS_DELETE:
6728 printf("D %s\n%s this deletion? [y/n] ", path, action);
6729 break;
6730 case GOT_STATUS_MODIFY:
6731 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6732 return got_error_from_errno("fseek");
6733 printf(GOT_COMMIT_SEP_STR);
6734 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6735 printf("%s", line);
6736 if (ferror(patch_file))
6737 return got_error_from_errno("getline");
6738 printf(GOT_COMMIT_SEP_STR);
6739 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6740 path, n, nchanges, action);
6741 break;
6742 default:
6743 return got_error_path(path, GOT_ERR_FILE_STATUS);
6746 return NULL;
6749 static const struct got_error *
6750 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6751 FILE *patch_file, int n, int nchanges)
6753 const struct got_error *err = NULL;
6754 char *line = NULL;
6755 size_t linesize = 0;
6756 ssize_t linelen;
6757 int resp = ' ';
6758 struct choose_patch_arg *a = arg;
6760 *choice = GOT_PATCH_CHOICE_NONE;
6762 if (a->patch_script_file) {
6763 char *nl;
6764 err = show_change(status, path, patch_file, n, nchanges,
6765 a->action);
6766 if (err)
6767 return err;
6768 linelen = getline(&line, &linesize, a->patch_script_file);
6769 if (linelen == -1) {
6770 if (ferror(a->patch_script_file))
6771 return got_error_from_errno("getline");
6772 return NULL;
6774 nl = strchr(line, '\n');
6775 if (nl)
6776 *nl = '\0';
6777 if (strcmp(line, "y") == 0) {
6778 *choice = GOT_PATCH_CHOICE_YES;
6779 printf("y\n");
6780 } else if (strcmp(line, "n") == 0) {
6781 *choice = GOT_PATCH_CHOICE_NO;
6782 printf("n\n");
6783 } else if (strcmp(line, "q") == 0 &&
6784 status == GOT_STATUS_MODIFY) {
6785 *choice = GOT_PATCH_CHOICE_QUIT;
6786 printf("q\n");
6787 } else
6788 printf("invalid response '%s'\n", line);
6789 free(line);
6790 return NULL;
6793 while (resp != 'y' && resp != 'n' && resp != 'q') {
6794 err = show_change(status, path, patch_file, n, nchanges,
6795 a->action);
6796 if (err)
6797 return err;
6798 resp = getchar();
6799 if (resp == '\n')
6800 resp = getchar();
6801 if (status == GOT_STATUS_MODIFY) {
6802 if (resp != 'y' && resp != 'n' && resp != 'q') {
6803 printf("invalid response '%c'\n", resp);
6804 resp = ' ';
6806 } else if (resp != 'y' && resp != 'n') {
6807 printf("invalid response '%c'\n", resp);
6808 resp = ' ';
6812 if (resp == 'y')
6813 *choice = GOT_PATCH_CHOICE_YES;
6814 else if (resp == 'n')
6815 *choice = GOT_PATCH_CHOICE_NO;
6816 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6817 *choice = GOT_PATCH_CHOICE_QUIT;
6819 return NULL;
6823 static const struct got_error *
6824 cmd_revert(int argc, char *argv[])
6826 const struct got_error *error = NULL;
6827 struct got_worktree *worktree = NULL;
6828 struct got_repository *repo = NULL;
6829 char *cwd = NULL, *path = NULL;
6830 struct got_pathlist_head paths;
6831 struct got_pathlist_entry *pe;
6832 int ch, can_recurse = 0, pflag = 0;
6833 FILE *patch_script_file = NULL;
6834 const char *patch_script_path = NULL;
6835 struct choose_patch_arg cpa;
6837 TAILQ_INIT(&paths);
6839 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6840 switch (ch) {
6841 case 'p':
6842 pflag = 1;
6843 break;
6844 case 'F':
6845 patch_script_path = optarg;
6846 break;
6847 case 'R':
6848 can_recurse = 1;
6849 break;
6850 default:
6851 usage_revert();
6852 /* NOTREACHED */
6856 argc -= optind;
6857 argv += optind;
6859 #ifndef PROFILE
6860 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6861 "unveil", NULL) == -1)
6862 err(1, "pledge");
6863 #endif
6864 if (argc < 1)
6865 usage_revert();
6866 if (patch_script_path && !pflag)
6867 errx(1, "-F option can only be used together with -p option");
6869 cwd = getcwd(NULL, 0);
6870 if (cwd == NULL) {
6871 error = got_error_from_errno("getcwd");
6872 goto done;
6874 error = got_worktree_open(&worktree, cwd);
6875 if (error) {
6876 if (error->code == GOT_ERR_NOT_WORKTREE)
6877 error = wrap_not_worktree_error(error, "revert", cwd);
6878 goto done;
6881 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6882 NULL);
6883 if (error != NULL)
6884 goto done;
6886 if (patch_script_path) {
6887 patch_script_file = fopen(patch_script_path, "r");
6888 if (patch_script_file == NULL) {
6889 error = got_error_from_errno2("fopen",
6890 patch_script_path);
6891 goto done;
6894 error = apply_unveil(got_repo_get_path(repo), 1,
6895 got_worktree_get_root_path(worktree));
6896 if (error)
6897 goto done;
6899 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6900 if (error)
6901 goto done;
6903 if (!can_recurse) {
6904 char *ondisk_path;
6905 struct stat sb;
6906 TAILQ_FOREACH(pe, &paths, entry) {
6907 if (asprintf(&ondisk_path, "%s/%s",
6908 got_worktree_get_root_path(worktree),
6909 pe->path) == -1) {
6910 error = got_error_from_errno("asprintf");
6911 goto done;
6913 if (lstat(ondisk_path, &sb) == -1) {
6914 if (errno == ENOENT) {
6915 free(ondisk_path);
6916 continue;
6918 error = got_error_from_errno2("lstat",
6919 ondisk_path);
6920 free(ondisk_path);
6921 goto done;
6923 free(ondisk_path);
6924 if (S_ISDIR(sb.st_mode)) {
6925 error = got_error_msg(GOT_ERR_BAD_PATH,
6926 "reverting directories requires -R option");
6927 goto done;
6932 cpa.patch_script_file = patch_script_file;
6933 cpa.action = "revert";
6934 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6935 pflag ? choose_patch : NULL, &cpa, repo);
6936 done:
6937 if (patch_script_file && fclose(patch_script_file) == EOF &&
6938 error == NULL)
6939 error = got_error_from_errno2("fclose", patch_script_path);
6940 if (repo)
6941 got_repo_close(repo);
6942 if (worktree)
6943 got_worktree_close(worktree);
6944 free(path);
6945 free(cwd);
6946 return error;
6949 __dead static void
6950 usage_commit(void)
6952 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
6953 "[path ...]\n", getprogname());
6954 exit(1);
6957 struct collect_commit_logmsg_arg {
6958 const char *cmdline_log;
6959 const char *prepared_log;
6960 int non_interactive;
6961 const char *editor;
6962 const char *worktree_path;
6963 const char *branch_name;
6964 const char *repo_path;
6965 char *logmsg_path;
6969 static const struct got_error *
6970 read_prepared_logmsg(char **logmsg, const char *path)
6972 const struct got_error *err = NULL;
6973 FILE *f = NULL;
6974 struct stat sb;
6975 size_t r;
6977 *logmsg = NULL;
6978 memset(&sb, 0, sizeof(sb));
6980 f = fopen(path, "r");
6981 if (f == NULL)
6982 return got_error_from_errno2("fopen", path);
6984 if (fstat(fileno(f), &sb) == -1) {
6985 err = got_error_from_errno2("fstat", path);
6986 goto done;
6988 if (sb.st_size == 0) {
6989 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
6990 goto done;
6993 *logmsg = malloc(sb.st_size + 1);
6994 if (*logmsg == NULL) {
6995 err = got_error_from_errno("malloc");
6996 goto done;
6999 r = fread(*logmsg, 1, sb.st_size, f);
7000 if (r != sb.st_size) {
7001 if (ferror(f))
7002 err = got_error_from_errno2("fread", path);
7003 else
7004 err = got_error(GOT_ERR_IO);
7005 goto done;
7007 (*logmsg)[sb.st_size] = '\0';
7008 done:
7009 if (fclose(f) == EOF && err == NULL)
7010 err = got_error_from_errno2("fclose", path);
7011 if (err) {
7012 free(*logmsg);
7013 *logmsg = NULL;
7015 return err;
7019 static const struct got_error *
7020 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7021 void *arg)
7023 char *initial_content = NULL;
7024 struct got_pathlist_entry *pe;
7025 const struct got_error *err = NULL;
7026 char *template = NULL;
7027 struct collect_commit_logmsg_arg *a = arg;
7028 int initial_content_len;
7029 int fd = -1;
7030 size_t len;
7032 /* if a message was specified on the command line, just use it */
7033 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7034 len = strlen(a->cmdline_log) + 1;
7035 *logmsg = malloc(len + 1);
7036 if (*logmsg == NULL)
7037 return got_error_from_errno("malloc");
7038 strlcpy(*logmsg, a->cmdline_log, len);
7039 return NULL;
7040 } else if (a->prepared_log != NULL && a->non_interactive)
7041 return read_prepared_logmsg(logmsg, a->prepared_log);
7043 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7044 return got_error_from_errno("asprintf");
7046 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7047 if (err)
7048 goto done;
7050 if (a->prepared_log) {
7051 char *msg;
7052 err = read_prepared_logmsg(&msg, a->prepared_log);
7053 if (err)
7054 goto done;
7055 if (write(fd, msg, strlen(msg)) == -1) {
7056 err = got_error_from_errno2("write", a->logmsg_path);
7057 free(msg);
7058 goto done;
7060 free(msg);
7063 initial_content_len = asprintf(&initial_content,
7064 "\n# changes to be committed on branch %s:\n",
7065 a->branch_name);
7066 if (initial_content_len == -1) {
7067 err = got_error_from_errno("asprintf");
7068 goto done;
7071 if (write(fd, initial_content, initial_content_len) == -1) {
7072 err = got_error_from_errno2("write", a->logmsg_path);
7073 goto done;
7076 TAILQ_FOREACH(pe, commitable_paths, entry) {
7077 struct got_commitable *ct = pe->data;
7078 dprintf(fd, "# %c %s\n",
7079 got_commitable_get_status(ct),
7080 got_commitable_get_path(ct));
7083 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7084 initial_content_len, a->prepared_log ? 0 : 1);
7085 done:
7086 free(initial_content);
7087 free(template);
7089 if (fd != -1 && close(fd) == -1 && err == NULL)
7090 err = got_error_from_errno2("close", a->logmsg_path);
7092 /* Editor is done; we can now apply unveil(2) */
7093 if (err == NULL)
7094 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7095 if (err) {
7096 free(*logmsg);
7097 *logmsg = NULL;
7099 return err;
7102 static const struct got_error *
7103 cmd_commit(int argc, char *argv[])
7105 const struct got_error *error = NULL;
7106 struct got_worktree *worktree = NULL;
7107 struct got_repository *repo = NULL;
7108 char *cwd = NULL, *id_str = NULL;
7109 struct got_object_id *id = NULL;
7110 const char *logmsg = NULL;
7111 char *prepared_logmsg = NULL;
7112 struct collect_commit_logmsg_arg cl_arg;
7113 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7114 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7115 int allow_bad_symlinks = 0, non_interactive = 0;
7116 struct got_pathlist_head paths;
7118 TAILQ_INIT(&paths);
7119 cl_arg.logmsg_path = NULL;
7121 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7122 switch (ch) {
7123 case 'F':
7124 if (logmsg != NULL)
7125 option_conflict('F', 'm');
7126 prepared_logmsg = realpath(optarg, NULL);
7127 if (prepared_logmsg == NULL)
7128 return got_error_from_errno2("realpath",
7129 optarg);
7130 break;
7131 case 'm':
7132 if (prepared_logmsg)
7133 option_conflict('m', 'F');
7134 logmsg = optarg;
7135 break;
7136 case 'N':
7137 non_interactive = 1;
7138 break;
7139 case 'S':
7140 allow_bad_symlinks = 1;
7141 break;
7142 default:
7143 usage_commit();
7144 /* NOTREACHED */
7148 argc -= optind;
7149 argv += optind;
7151 #ifndef PROFILE
7152 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7153 "unveil", NULL) == -1)
7154 err(1, "pledge");
7155 #endif
7156 cwd = getcwd(NULL, 0);
7157 if (cwd == NULL) {
7158 error = got_error_from_errno("getcwd");
7159 goto done;
7161 error = got_worktree_open(&worktree, cwd);
7162 if (error) {
7163 if (error->code == GOT_ERR_NOT_WORKTREE)
7164 error = wrap_not_worktree_error(error, "commit", cwd);
7165 goto done;
7168 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7169 if (error)
7170 goto done;
7171 if (rebase_in_progress) {
7172 error = got_error(GOT_ERR_REBASING);
7173 goto done;
7176 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7177 worktree);
7178 if (error)
7179 goto done;
7181 error = get_gitconfig_path(&gitconfig_path);
7182 if (error)
7183 goto done;
7184 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7185 gitconfig_path);
7186 if (error != NULL)
7187 goto done;
7189 error = get_author(&author, repo, worktree);
7190 if (error)
7191 return error;
7194 * unveil(2) traverses exec(2); if an editor is used we have
7195 * to apply unveil after the log message has been written.
7197 if (logmsg == NULL || strlen(logmsg) == 0)
7198 error = get_editor(&editor);
7199 else
7200 error = apply_unveil(got_repo_get_path(repo), 0,
7201 got_worktree_get_root_path(worktree));
7202 if (error)
7203 goto done;
7205 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7206 if (error)
7207 goto done;
7209 cl_arg.editor = editor;
7210 cl_arg.cmdline_log = logmsg;
7211 cl_arg.prepared_log = prepared_logmsg;
7212 cl_arg.non_interactive = non_interactive;
7213 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7214 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7215 if (!histedit_in_progress) {
7216 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7217 error = got_error(GOT_ERR_COMMIT_BRANCH);
7218 goto done;
7220 cl_arg.branch_name += 11;
7222 cl_arg.repo_path = got_repo_get_path(repo);
7223 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7224 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7225 print_status, NULL, repo);
7226 if (error) {
7227 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7228 cl_arg.logmsg_path != NULL)
7229 preserve_logmsg = 1;
7230 goto done;
7233 error = got_object_id_str(&id_str, id);
7234 if (error)
7235 goto done;
7236 printf("Created commit %s\n", id_str);
7237 done:
7238 if (preserve_logmsg) {
7239 fprintf(stderr, "%s: log message preserved in %s\n",
7240 getprogname(), cl_arg.logmsg_path);
7241 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7242 error == NULL)
7243 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7244 free(cl_arg.logmsg_path);
7245 if (repo)
7246 got_repo_close(repo);
7247 if (worktree)
7248 got_worktree_close(worktree);
7249 free(cwd);
7250 free(id_str);
7251 free(gitconfig_path);
7252 free(editor);
7253 free(author);
7254 free(prepared_logmsg);
7255 return error;
7258 __dead static void
7259 usage_cherrypick(void)
7261 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7262 exit(1);
7265 static const struct got_error *
7266 cmd_cherrypick(int argc, char *argv[])
7268 const struct got_error *error = NULL;
7269 struct got_worktree *worktree = NULL;
7270 struct got_repository *repo = NULL;
7271 char *cwd = NULL, *commit_id_str = NULL;
7272 struct got_object_id *commit_id = NULL;
7273 struct got_commit_object *commit = NULL;
7274 struct got_object_qid *pid;
7275 struct got_reference *head_ref = NULL;
7276 int ch;
7277 struct got_update_progress_arg upa;
7279 while ((ch = getopt(argc, argv, "")) != -1) {
7280 switch (ch) {
7281 default:
7282 usage_cherrypick();
7283 /* NOTREACHED */
7287 argc -= optind;
7288 argv += optind;
7290 #ifndef PROFILE
7291 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7292 "unveil", NULL) == -1)
7293 err(1, "pledge");
7294 #endif
7295 if (argc != 1)
7296 usage_cherrypick();
7298 cwd = getcwd(NULL, 0);
7299 if (cwd == NULL) {
7300 error = got_error_from_errno("getcwd");
7301 goto done;
7303 error = got_worktree_open(&worktree, cwd);
7304 if (error) {
7305 if (error->code == GOT_ERR_NOT_WORKTREE)
7306 error = wrap_not_worktree_error(error, "cherrypick",
7307 cwd);
7308 goto done;
7311 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7312 NULL);
7313 if (error != NULL)
7314 goto done;
7316 error = apply_unveil(got_repo_get_path(repo), 0,
7317 got_worktree_get_root_path(worktree));
7318 if (error)
7319 goto done;
7321 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7322 GOT_OBJ_TYPE_COMMIT, repo);
7323 if (error != NULL) {
7324 struct got_reference *ref;
7325 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7326 goto done;
7327 error = got_ref_open(&ref, repo, argv[0], 0);
7328 if (error != NULL)
7329 goto done;
7330 error = got_ref_resolve(&commit_id, repo, ref);
7331 got_ref_close(ref);
7332 if (error != NULL)
7333 goto done;
7335 error = got_object_id_str(&commit_id_str, commit_id);
7336 if (error)
7337 goto done;
7339 error = got_ref_open(&head_ref, repo,
7340 got_worktree_get_head_ref_name(worktree), 0);
7341 if (error != NULL)
7342 goto done;
7344 error = check_same_branch(commit_id, head_ref, NULL, repo);
7345 if (error) {
7346 if (error->code != GOT_ERR_ANCESTRY)
7347 goto done;
7348 error = NULL;
7349 } else {
7350 error = got_error(GOT_ERR_SAME_BRANCH);
7351 goto done;
7354 error = got_object_open_as_commit(&commit, repo, commit_id);
7355 if (error)
7356 goto done;
7357 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7358 memset(&upa, 0, sizeof(upa));
7359 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7360 commit_id, repo, update_progress, &upa, check_cancelled,
7361 NULL);
7362 if (error != NULL)
7363 goto done;
7365 if (upa.did_something)
7366 printf("Merged commit %s\n", commit_id_str);
7367 print_update_progress_stats(&upa);
7368 done:
7369 if (commit)
7370 got_object_commit_close(commit);
7371 free(commit_id_str);
7372 if (head_ref)
7373 got_ref_close(head_ref);
7374 if (worktree)
7375 got_worktree_close(worktree);
7376 if (repo)
7377 got_repo_close(repo);
7378 return error;
7381 __dead static void
7382 usage_backout(void)
7384 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7385 exit(1);
7388 static const struct got_error *
7389 cmd_backout(int argc, char *argv[])
7391 const struct got_error *error = NULL;
7392 struct got_worktree *worktree = NULL;
7393 struct got_repository *repo = NULL;
7394 char *cwd = NULL, *commit_id_str = NULL;
7395 struct got_object_id *commit_id = NULL;
7396 struct got_commit_object *commit = NULL;
7397 struct got_object_qid *pid;
7398 struct got_reference *head_ref = NULL;
7399 int ch;
7400 struct got_update_progress_arg upa;
7402 while ((ch = getopt(argc, argv, "")) != -1) {
7403 switch (ch) {
7404 default:
7405 usage_backout();
7406 /* NOTREACHED */
7410 argc -= optind;
7411 argv += optind;
7413 #ifndef PROFILE
7414 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7415 "unveil", NULL) == -1)
7416 err(1, "pledge");
7417 #endif
7418 if (argc != 1)
7419 usage_backout();
7421 cwd = getcwd(NULL, 0);
7422 if (cwd == NULL) {
7423 error = got_error_from_errno("getcwd");
7424 goto done;
7426 error = got_worktree_open(&worktree, cwd);
7427 if (error) {
7428 if (error->code == GOT_ERR_NOT_WORKTREE)
7429 error = wrap_not_worktree_error(error, "backout", cwd);
7430 goto done;
7433 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7434 NULL);
7435 if (error != NULL)
7436 goto done;
7438 error = apply_unveil(got_repo_get_path(repo), 0,
7439 got_worktree_get_root_path(worktree));
7440 if (error)
7441 goto done;
7443 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7444 GOT_OBJ_TYPE_COMMIT, repo);
7445 if (error != NULL) {
7446 struct got_reference *ref;
7447 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7448 goto done;
7449 error = got_ref_open(&ref, repo, argv[0], 0);
7450 if (error != NULL)
7451 goto done;
7452 error = got_ref_resolve(&commit_id, repo, ref);
7453 got_ref_close(ref);
7454 if (error != NULL)
7455 goto done;
7457 error = got_object_id_str(&commit_id_str, commit_id);
7458 if (error)
7459 goto done;
7461 error = got_ref_open(&head_ref, repo,
7462 got_worktree_get_head_ref_name(worktree), 0);
7463 if (error != NULL)
7464 goto done;
7466 error = check_same_branch(commit_id, head_ref, NULL, repo);
7467 if (error)
7468 goto done;
7470 error = got_object_open_as_commit(&commit, repo, commit_id);
7471 if (error)
7472 goto done;
7473 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7474 if (pid == NULL) {
7475 error = got_error(GOT_ERR_ROOT_COMMIT);
7476 goto done;
7479 memset(&upa, 0, sizeof(upa));
7480 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7481 update_progress, &upa, check_cancelled, NULL);
7482 if (error != NULL)
7483 goto done;
7485 if (upa.did_something)
7486 printf("Backed out commit %s\n", commit_id_str);
7487 print_update_progress_stats(&upa);
7488 done:
7489 if (commit)
7490 got_object_commit_close(commit);
7491 free(commit_id_str);
7492 if (head_ref)
7493 got_ref_close(head_ref);
7494 if (worktree)
7495 got_worktree_close(worktree);
7496 if (repo)
7497 got_repo_close(repo);
7498 return error;
7501 __dead static void
7502 usage_rebase(void)
7504 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [branch]\n",
7505 getprogname());
7506 exit(1);
7509 void
7510 trim_logmsg(char *logmsg, int limit)
7512 char *nl;
7513 size_t len;
7515 len = strlen(logmsg);
7516 if (len > limit)
7517 len = limit;
7518 logmsg[len] = '\0';
7519 nl = strchr(logmsg, '\n');
7520 if (nl)
7521 *nl = '\0';
7524 static const struct got_error *
7525 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7527 const struct got_error *err;
7528 char *logmsg0 = NULL;
7529 const char *s;
7531 err = got_object_commit_get_logmsg(&logmsg0, commit);
7532 if (err)
7533 return err;
7535 s = logmsg0;
7536 while (isspace((unsigned char)s[0]))
7537 s++;
7539 *logmsg = strdup(s);
7540 if (*logmsg == NULL) {
7541 err = got_error_from_errno("strdup");
7542 goto done;
7545 trim_logmsg(*logmsg, limit);
7546 done:
7547 free(logmsg0);
7548 return err;
7551 static const struct got_error *
7552 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7554 const struct got_error *err;
7555 struct got_commit_object *commit = NULL;
7556 char *id_str = NULL, *logmsg = NULL;
7558 err = got_object_open_as_commit(&commit, repo, id);
7559 if (err)
7560 return err;
7562 err = got_object_id_str(&id_str, id);
7563 if (err)
7564 goto done;
7566 id_str[12] = '\0';
7568 err = get_short_logmsg(&logmsg, 42, commit);
7569 if (err)
7570 goto done;
7572 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7573 done:
7574 free(id_str);
7575 got_object_commit_close(commit);
7576 free(logmsg);
7577 return err;
7580 static const struct got_error *
7581 show_rebase_progress(struct got_commit_object *commit,
7582 struct got_object_id *old_id, struct got_object_id *new_id)
7584 const struct got_error *err;
7585 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7587 err = got_object_id_str(&old_id_str, old_id);
7588 if (err)
7589 goto done;
7591 if (new_id) {
7592 err = got_object_id_str(&new_id_str, new_id);
7593 if (err)
7594 goto done;
7597 old_id_str[12] = '\0';
7598 if (new_id_str)
7599 new_id_str[12] = '\0';
7601 err = get_short_logmsg(&logmsg, 42, commit);
7602 if (err)
7603 goto done;
7605 printf("%s -> %s: %s\n", old_id_str,
7606 new_id_str ? new_id_str : "no-op change", logmsg);
7607 done:
7608 free(old_id_str);
7609 free(new_id_str);
7610 free(logmsg);
7611 return err;
7614 static const struct got_error *
7615 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7616 struct got_reference *branch, struct got_reference *new_base_branch,
7617 struct got_reference *tmp_branch, struct got_repository *repo,
7618 int create_backup)
7620 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7621 return got_worktree_rebase_complete(worktree, fileindex,
7622 new_base_branch, tmp_branch, branch, repo, create_backup);
7625 static const struct got_error *
7626 rebase_commit(struct got_pathlist_head *merged_paths,
7627 struct got_worktree *worktree, struct got_fileindex *fileindex,
7628 struct got_reference *tmp_branch,
7629 struct got_object_id *commit_id, struct got_repository *repo)
7631 const struct got_error *error;
7632 struct got_commit_object *commit;
7633 struct got_object_id *new_commit_id;
7635 error = got_object_open_as_commit(&commit, repo, commit_id);
7636 if (error)
7637 return error;
7639 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7640 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7641 if (error) {
7642 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7643 goto done;
7644 error = show_rebase_progress(commit, commit_id, NULL);
7645 } else {
7646 error = show_rebase_progress(commit, commit_id, new_commit_id);
7647 free(new_commit_id);
7649 done:
7650 got_object_commit_close(commit);
7651 return error;
7654 struct check_path_prefix_arg {
7655 const char *path_prefix;
7656 size_t len;
7657 int errcode;
7660 static const struct got_error *
7661 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7662 struct got_blob_object *blob2, struct got_object_id *id1,
7663 struct got_object_id *id2, const char *path1, const char *path2,
7664 mode_t mode1, mode_t mode2, struct got_repository *repo)
7666 struct check_path_prefix_arg *a = arg;
7668 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7669 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7670 return got_error(a->errcode);
7672 return NULL;
7675 static const struct got_error *
7676 check_path_prefix(struct got_object_id *parent_id,
7677 struct got_object_id *commit_id, const char *path_prefix,
7678 int errcode, struct got_repository *repo)
7680 const struct got_error *err;
7681 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7682 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7683 struct check_path_prefix_arg cpp_arg;
7685 if (got_path_is_root_dir(path_prefix))
7686 return NULL;
7688 err = got_object_open_as_commit(&commit, repo, commit_id);
7689 if (err)
7690 goto done;
7692 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7693 if (err)
7694 goto done;
7696 err = got_object_open_as_tree(&tree1, repo,
7697 got_object_commit_get_tree_id(parent_commit));
7698 if (err)
7699 goto done;
7701 err = got_object_open_as_tree(&tree2, repo,
7702 got_object_commit_get_tree_id(commit));
7703 if (err)
7704 goto done;
7706 cpp_arg.path_prefix = path_prefix;
7707 while (cpp_arg.path_prefix[0] == '/')
7708 cpp_arg.path_prefix++;
7709 cpp_arg.len = strlen(cpp_arg.path_prefix);
7710 cpp_arg.errcode = errcode;
7711 err = got_diff_tree(tree1, tree2, "", "", repo,
7712 check_path_prefix_in_diff, &cpp_arg, 0);
7713 done:
7714 if (tree1)
7715 got_object_tree_close(tree1);
7716 if (tree2)
7717 got_object_tree_close(tree2);
7718 if (commit)
7719 got_object_commit_close(commit);
7720 if (parent_commit)
7721 got_object_commit_close(parent_commit);
7722 return err;
7725 static const struct got_error *
7726 collect_commits(struct got_object_id_queue *commits,
7727 struct got_object_id *initial_commit_id,
7728 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7729 const char *path_prefix, int path_prefix_errcode,
7730 struct got_repository *repo)
7732 const struct got_error *err = NULL;
7733 struct got_commit_graph *graph = NULL;
7734 struct got_object_id *parent_id = NULL;
7735 struct got_object_qid *qid;
7736 struct got_object_id *commit_id = initial_commit_id;
7738 err = got_commit_graph_open(&graph, "/", 1);
7739 if (err)
7740 return err;
7742 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7743 check_cancelled, NULL);
7744 if (err)
7745 goto done;
7746 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7747 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7748 check_cancelled, NULL);
7749 if (err) {
7750 if (err->code == GOT_ERR_ITER_COMPLETED) {
7751 err = got_error_msg(GOT_ERR_ANCESTRY,
7752 "ran out of commits to rebase before "
7753 "youngest common ancestor commit has "
7754 "been reached?!?");
7756 goto done;
7757 } else {
7758 err = check_path_prefix(parent_id, commit_id,
7759 path_prefix, path_prefix_errcode, repo);
7760 if (err)
7761 goto done;
7763 err = got_object_qid_alloc(&qid, commit_id);
7764 if (err)
7765 goto done;
7766 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7767 commit_id = parent_id;
7770 done:
7771 got_commit_graph_close(graph);
7772 return err;
7775 static const struct got_error *
7776 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
7778 const struct got_error *err = NULL;
7779 time_t committer_time;
7780 struct tm tm;
7781 char datebuf[11]; /* YYYY-MM-DD + NUL */
7782 char *author0 = NULL, *author, *smallerthan;
7783 char *logmsg0 = NULL, *logmsg, *newline;
7785 committer_time = got_object_commit_get_committer_time(commit);
7786 if (localtime_r(&committer_time, &tm) == NULL)
7787 return got_error_from_errno("localtime_r");
7788 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
7789 return got_error(GOT_ERR_NO_SPACE);
7791 author0 = strdup(got_object_commit_get_author(commit));
7792 if (author0 == NULL)
7793 return got_error_from_errno("strdup");
7794 author = author0;
7795 smallerthan = strchr(author, '<');
7796 if (smallerthan && smallerthan[1] != '\0')
7797 author = smallerthan + 1;
7798 author[strcspn(author, "@>")] = '\0';
7800 err = got_object_commit_get_logmsg(&logmsg0, commit);
7801 if (err)
7802 goto done;
7803 logmsg = logmsg0;
7804 while (*logmsg == '\n')
7805 logmsg++;
7806 newline = strchr(logmsg, '\n');
7807 if (newline)
7808 *newline = '\0';
7810 if (asprintf(brief_str, "%s %s %s",
7811 datebuf, author, logmsg) == -1)
7812 err = got_error_from_errno("asprintf");
7813 done:
7814 free(author0);
7815 free(logmsg0);
7816 return err;
7819 static const struct got_error *
7820 print_backup_ref(const char *branch_name, const char *new_id_str,
7821 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
7822 struct got_reflist_object_id_map *refs_idmap,
7823 struct got_repository *repo)
7825 const struct got_error *err = NULL;
7826 struct got_reflist_head *refs;
7827 char *refs_str = NULL;
7828 struct got_object_id *new_commit_id = NULL;
7829 struct got_commit_object *new_commit = NULL;
7830 char *new_commit_brief_str = NULL;
7831 struct got_object_id *yca_id = NULL;
7832 struct got_commit_object *yca_commit = NULL;
7833 char *yca_id_str = NULL, *yca_brief_str = NULL;
7834 char *custom_refs_str;
7836 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
7837 return got_error_from_errno("asprintf");
7839 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
7840 0, 0, refs_idmap, custom_refs_str);
7841 if (err)
7842 goto done;
7844 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
7845 if (err)
7846 goto done;
7848 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
7849 if (refs) {
7850 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
7851 if (err)
7852 goto done;
7855 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
7856 if (err)
7857 goto done;
7859 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
7860 if (err)
7861 goto done;
7863 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7864 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
7865 if (err)
7866 goto done;
7868 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
7869 refs_str ? " (" : "", refs_str ? refs_str : "",
7870 refs_str ? ")" : "", new_commit_brief_str);
7871 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
7872 got_object_id_cmp(yca_id, old_commit_id) != 0) {
7873 free(refs_str);
7874 refs_str = NULL;
7876 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
7877 if (err)
7878 goto done;
7880 err = get_commit_brief_str(&yca_brief_str, yca_commit);
7881 if (err)
7882 goto done;
7884 err = got_object_id_str(&yca_id_str, yca_id);
7885 if (err)
7886 goto done;
7888 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
7889 if (refs) {
7890 err = build_refs_str(&refs_str, refs, yca_id, repo);
7891 if (err)
7892 goto done;
7894 printf("history forked at %s%s%s%s\n %s\n",
7895 yca_id_str,
7896 refs_str ? " (" : "", refs_str ? refs_str : "",
7897 refs_str ? ")" : "", yca_brief_str);
7899 done:
7900 free(custom_refs_str);
7901 free(new_commit_id);
7902 free(refs_str);
7903 free(yca_id);
7904 free(yca_id_str);
7905 free(yca_brief_str);
7906 if (new_commit)
7907 got_object_commit_close(new_commit);
7908 if (yca_commit)
7909 got_object_commit_close(yca_commit);
7911 return NULL;
7914 static const struct got_error *
7915 list_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
7916 struct got_repository *repo)
7918 const struct got_error *err;
7919 struct got_reflist_head refs, backup_refs;
7920 struct got_reflist_entry *re;
7921 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
7922 struct got_object_id *old_commit_id = NULL;
7923 char *branch_name = NULL;
7924 struct got_commit_object *old_commit = NULL;
7925 struct got_reflist_object_id_map *refs_idmap = NULL;
7926 int wanted_branch_found = 0;
7928 TAILQ_INIT(&refs);
7929 TAILQ_INIT(&backup_refs);
7931 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7932 if (err)
7933 return err;
7935 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
7936 if (err)
7937 goto done;
7939 if (wanted_branch_name) {
7940 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
7941 wanted_branch_name += 11;
7944 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
7945 got_ref_cmp_by_commit_timestamp_descending, repo);
7946 if (err)
7947 goto done;
7949 TAILQ_FOREACH(re, &backup_refs, entry) {
7950 const char *refname = got_ref_get_name(re->ref);
7951 char *slash;
7953 err = got_ref_resolve(&old_commit_id, repo, re->ref);
7954 if (err)
7955 break;
7957 err = got_object_open_as_commit(&old_commit, repo,
7958 old_commit_id);
7959 if (err)
7960 break;
7962 if (strncmp(backup_ref_prefix, refname,
7963 backup_ref_prefix_len) == 0)
7964 refname += backup_ref_prefix_len;
7966 while (refname[0] == '/')
7967 refname++;
7969 branch_name = strdup(refname);
7970 if (branch_name == NULL) {
7971 err = got_error_from_errno("strdup");
7972 break;
7974 slash = strrchr(branch_name, '/');
7975 if (slash) {
7976 *slash = '\0';
7977 refname += strlen(branch_name) + 1;
7980 if (wanted_branch_name == NULL ||
7981 strcmp(wanted_branch_name, branch_name) == 0) {
7982 wanted_branch_found = 1;
7983 err = print_backup_ref(branch_name, refname,
7984 old_commit_id, old_commit, refs_idmap, repo);
7985 if (err)
7986 break;
7989 free(old_commit_id);
7990 old_commit_id = NULL;
7991 free(branch_name);
7992 branch_name = NULL;
7993 got_object_commit_close(old_commit);
7994 old_commit = NULL;
7997 if (wanted_branch_name && !wanted_branch_found) {
7998 err = got_error_fmt(GOT_ERR_NOT_REF,
7999 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8001 done:
8002 if (refs_idmap)
8003 got_reflist_object_id_map_free(refs_idmap);
8004 got_ref_list_free(&refs);
8005 got_ref_list_free(&backup_refs);
8006 free(old_commit_id);
8007 free(branch_name);
8008 if (old_commit)
8009 got_object_commit_close(old_commit);
8010 return err;
8013 static const struct got_error *
8014 cmd_rebase(int argc, char *argv[])
8016 const struct got_error *error = NULL;
8017 struct got_worktree *worktree = NULL;
8018 struct got_repository *repo = NULL;
8019 struct got_fileindex *fileindex = NULL;
8020 char *cwd = NULL;
8021 struct got_reference *branch = NULL;
8022 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8023 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8024 struct got_object_id *resume_commit_id = NULL;
8025 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8026 struct got_commit_object *commit = NULL;
8027 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8028 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8029 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8030 struct got_object_id_queue commits;
8031 struct got_pathlist_head merged_paths;
8032 const struct got_object_id_queue *parent_ids;
8033 struct got_object_qid *qid, *pid;
8035 SIMPLEQ_INIT(&commits);
8036 TAILQ_INIT(&merged_paths);
8038 while ((ch = getopt(argc, argv, "acl")) != -1) {
8039 switch (ch) {
8040 case 'a':
8041 abort_rebase = 1;
8042 break;
8043 case 'c':
8044 continue_rebase = 1;
8045 break;
8046 case 'l':
8047 list_backups = 1;
8048 break;
8049 default:
8050 usage_rebase();
8051 /* NOTREACHED */
8055 argc -= optind;
8056 argv += optind;
8058 #ifndef PROFILE
8059 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8060 "unveil", NULL) == -1)
8061 err(1, "pledge");
8062 #endif
8063 if (list_backups) {
8064 if (abort_rebase)
8065 option_conflict('l', 'a');
8066 if (continue_rebase)
8067 option_conflict('l', 'c');
8068 if (argc != 0 && argc != 1)
8069 usage_rebase();
8070 } else {
8071 if (abort_rebase && continue_rebase)
8072 usage_rebase();
8073 else if (abort_rebase || continue_rebase) {
8074 if (argc != 0)
8075 usage_rebase();
8076 } else if (argc != 1)
8077 usage_rebase();
8080 cwd = getcwd(NULL, 0);
8081 if (cwd == NULL) {
8082 error = got_error_from_errno("getcwd");
8083 goto done;
8085 error = got_worktree_open(&worktree, cwd);
8086 if (error) {
8087 if (list_backups) {
8088 if (error->code != GOT_ERR_NOT_WORKTREE)
8089 goto done;
8090 } else {
8091 if (error->code == GOT_ERR_NOT_WORKTREE)
8092 error = wrap_not_worktree_error(error,
8093 "rebase", cwd);
8094 goto done;
8098 error = got_repo_open(&repo,
8099 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8100 if (error != NULL)
8101 goto done;
8103 error = apply_unveil(got_repo_get_path(repo), 0,
8104 worktree ? got_worktree_get_root_path(worktree) : NULL);
8105 if (error)
8106 goto done;
8108 if (list_backups) {
8109 error = list_backup_refs(GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8110 argc == 1 ? argv[0] : NULL, repo);
8111 goto done; /* nothing else to do */
8114 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8115 worktree);
8116 if (error)
8117 goto done;
8118 if (histedit_in_progress) {
8119 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8120 goto done;
8123 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8124 if (error)
8125 goto done;
8127 if (abort_rebase) {
8128 struct got_update_progress_arg upa;
8129 if (!rebase_in_progress) {
8130 error = got_error(GOT_ERR_NOT_REBASING);
8131 goto done;
8133 error = got_worktree_rebase_continue(&resume_commit_id,
8134 &new_base_branch, &tmp_branch, &branch, &fileindex,
8135 worktree, repo);
8136 if (error)
8137 goto done;
8138 printf("Switching work tree to %s\n",
8139 got_ref_get_symref_target(new_base_branch));
8140 memset(&upa, 0, sizeof(upa));
8141 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8142 new_base_branch, update_progress, &upa);
8143 if (error)
8144 goto done;
8145 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8146 print_update_progress_stats(&upa);
8147 goto done; /* nothing else to do */
8150 if (continue_rebase) {
8151 if (!rebase_in_progress) {
8152 error = got_error(GOT_ERR_NOT_REBASING);
8153 goto done;
8155 error = got_worktree_rebase_continue(&resume_commit_id,
8156 &new_base_branch, &tmp_branch, &branch, &fileindex,
8157 worktree, repo);
8158 if (error)
8159 goto done;
8161 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8162 resume_commit_id, repo);
8163 if (error)
8164 goto done;
8166 yca_id = got_object_id_dup(resume_commit_id);
8167 if (yca_id == NULL) {
8168 error = got_error_from_errno("got_object_id_dup");
8169 goto done;
8171 } else {
8172 error = got_ref_open(&branch, repo, argv[0], 0);
8173 if (error != NULL)
8174 goto done;
8177 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8178 if (error)
8179 goto done;
8181 if (!continue_rebase) {
8182 struct got_object_id *base_commit_id;
8184 base_commit_id = got_worktree_get_base_commit_id(worktree);
8185 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8186 base_commit_id, branch_head_commit_id, repo,
8187 check_cancelled, NULL);
8188 if (error)
8189 goto done;
8190 if (yca_id == NULL) {
8191 error = got_error_msg(GOT_ERR_ANCESTRY,
8192 "specified branch shares no common ancestry "
8193 "with work tree's branch");
8194 goto done;
8197 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8198 if (error) {
8199 if (error->code != GOT_ERR_ANCESTRY)
8200 goto done;
8201 error = NULL;
8202 } else {
8203 static char msg[128];
8204 snprintf(msg, sizeof(msg),
8205 "%s is already based on %s",
8206 got_ref_get_name(branch),
8207 got_worktree_get_head_ref_name(worktree));
8208 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8209 goto done;
8211 error = got_worktree_rebase_prepare(&new_base_branch,
8212 &tmp_branch, &fileindex, worktree, branch, repo);
8213 if (error)
8214 goto done;
8217 commit_id = branch_head_commit_id;
8218 error = got_object_open_as_commit(&commit, repo, commit_id);
8219 if (error)
8220 goto done;
8222 parent_ids = got_object_commit_get_parent_ids(commit);
8223 pid = SIMPLEQ_FIRST(parent_ids);
8224 if (pid == NULL) {
8225 if (!continue_rebase) {
8226 struct got_update_progress_arg upa;
8227 memset(&upa, 0, sizeof(upa));
8228 error = got_worktree_rebase_abort(worktree, fileindex,
8229 repo, new_base_branch, update_progress, &upa);
8230 if (error)
8231 goto done;
8232 printf("Rebase of %s aborted\n",
8233 got_ref_get_name(branch));
8234 print_update_progress_stats(&upa);
8237 error = got_error(GOT_ERR_EMPTY_REBASE);
8238 goto done;
8240 error = collect_commits(&commits, commit_id, pid->id,
8241 yca_id, got_worktree_get_path_prefix(worktree),
8242 GOT_ERR_REBASE_PATH, repo);
8243 got_object_commit_close(commit);
8244 commit = NULL;
8245 if (error)
8246 goto done;
8248 if (SIMPLEQ_EMPTY(&commits)) {
8249 if (continue_rebase) {
8250 error = rebase_complete(worktree, fileindex,
8251 branch, new_base_branch, tmp_branch, repo,
8252 create_backup);
8253 goto done;
8254 } else {
8255 /* Fast-forward the reference of the branch. */
8256 struct got_object_id *new_head_commit_id;
8257 char *id_str;
8258 error = got_ref_resolve(&new_head_commit_id, repo,
8259 new_base_branch);
8260 if (error)
8261 goto done;
8262 error = got_object_id_str(&id_str, new_head_commit_id);
8263 printf("Forwarding %s to commit %s\n",
8264 got_ref_get_name(branch), id_str);
8265 free(id_str);
8266 error = got_ref_change_ref(branch,
8267 new_head_commit_id);
8268 if (error)
8269 goto done;
8270 /* No backup needed since objects did not change. */
8271 create_backup = 0;
8275 pid = NULL;
8276 SIMPLEQ_FOREACH(qid, &commits, entry) {
8277 struct got_update_progress_arg upa;
8279 commit_id = qid->id;
8280 parent_id = pid ? pid->id : yca_id;
8281 pid = qid;
8283 memset(&upa, 0, sizeof(upa));
8284 error = got_worktree_rebase_merge_files(&merged_paths,
8285 worktree, fileindex, parent_id, commit_id, repo,
8286 update_progress, &upa, check_cancelled, NULL);
8287 if (error)
8288 goto done;
8290 print_update_progress_stats(&upa);
8291 if (upa.conflicts > 0)
8292 rebase_status = GOT_STATUS_CONFLICT;
8294 if (rebase_status == GOT_STATUS_CONFLICT) {
8295 error = show_rebase_merge_conflict(qid->id, repo);
8296 if (error)
8297 goto done;
8298 got_worktree_rebase_pathlist_free(&merged_paths);
8299 break;
8302 error = rebase_commit(&merged_paths, worktree, fileindex,
8303 tmp_branch, commit_id, repo);
8304 got_worktree_rebase_pathlist_free(&merged_paths);
8305 if (error)
8306 goto done;
8309 if (rebase_status == GOT_STATUS_CONFLICT) {
8310 error = got_worktree_rebase_postpone(worktree, fileindex);
8311 if (error)
8312 goto done;
8313 error = got_error_msg(GOT_ERR_CONFLICTS,
8314 "conflicts must be resolved before rebasing can continue");
8315 } else
8316 error = rebase_complete(worktree, fileindex, branch,
8317 new_base_branch, tmp_branch, repo, create_backup);
8318 done:
8319 got_object_id_queue_free(&commits);
8320 free(branch_head_commit_id);
8321 free(resume_commit_id);
8322 free(yca_id);
8323 if (commit)
8324 got_object_commit_close(commit);
8325 if (branch)
8326 got_ref_close(branch);
8327 if (new_base_branch)
8328 got_ref_close(new_base_branch);
8329 if (tmp_branch)
8330 got_ref_close(tmp_branch);
8331 if (worktree)
8332 got_worktree_close(worktree);
8333 if (repo)
8334 got_repo_close(repo);
8335 return error;
8338 __dead static void
8339 usage_histedit(void)
8341 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8342 "[-F histedit-script] [-m] [-l] [branch]\n", getprogname());
8343 exit(1);
8346 #define GOT_HISTEDIT_PICK 'p'
8347 #define GOT_HISTEDIT_EDIT 'e'
8348 #define GOT_HISTEDIT_FOLD 'f'
8349 #define GOT_HISTEDIT_DROP 'd'
8350 #define GOT_HISTEDIT_MESG 'm'
8352 static struct got_histedit_cmd {
8353 unsigned char code;
8354 const char *name;
8355 const char *desc;
8356 } got_histedit_cmds[] = {
8357 { GOT_HISTEDIT_PICK, "pick", "use commit" },
8358 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
8359 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
8360 "be used" },
8361 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
8362 { GOT_HISTEDIT_MESG, "mesg",
8363 "single-line log message for commit above (open editor if empty)" },
8366 struct got_histedit_list_entry {
8367 TAILQ_ENTRY(got_histedit_list_entry) entry;
8368 struct got_object_id *commit_id;
8369 const struct got_histedit_cmd *cmd;
8370 char *logmsg;
8372 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
8374 static const struct got_error *
8375 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
8376 FILE *f, struct got_repository *repo)
8378 const struct got_error *err = NULL;
8379 char *logmsg = NULL, *id_str = NULL;
8380 struct got_commit_object *commit = NULL;
8381 int n;
8383 err = got_object_open_as_commit(&commit, repo, commit_id);
8384 if (err)
8385 goto done;
8387 err = get_short_logmsg(&logmsg, 34, commit);
8388 if (err)
8389 goto done;
8391 err = got_object_id_str(&id_str, commit_id);
8392 if (err)
8393 goto done;
8395 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
8396 if (n < 0)
8397 err = got_ferror(f, GOT_ERR_IO);
8398 done:
8399 if (commit)
8400 got_object_commit_close(commit);
8401 free(id_str);
8402 free(logmsg);
8403 return err;
8406 static const struct got_error *
8407 histedit_write_commit_list(struct got_object_id_queue *commits,
8408 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
8410 const struct got_error *err = NULL;
8411 struct got_object_qid *qid;
8412 const char *histedit_cmd = NULL;
8414 if (SIMPLEQ_EMPTY(commits))
8415 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8417 SIMPLEQ_FOREACH(qid, commits, entry) {
8418 histedit_cmd = got_histedit_cmds[0].name;
8419 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
8420 histedit_cmd = "fold";
8421 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
8422 if (err)
8423 break;
8424 if (edit_logmsg_only) {
8425 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
8426 if (n < 0) {
8427 err = got_ferror(f, GOT_ERR_IO);
8428 break;
8433 return err;
8436 static const struct got_error *
8437 write_cmd_list(FILE *f, const char *branch_name,
8438 struct got_object_id_queue *commits)
8440 const struct got_error *err = NULL;
8441 size_t i;
8442 int n;
8443 char *id_str;
8444 struct got_object_qid *qid;
8446 qid = SIMPLEQ_FIRST(commits);
8447 err = got_object_id_str(&id_str, qid->id);
8448 if (err)
8449 return err;
8451 n = fprintf(f,
8452 "# Editing the history of branch '%s' starting at\n"
8453 "# commit %s\n"
8454 "# Commits will be processed in order from top to "
8455 "bottom of this file.\n", branch_name, id_str);
8456 if (n < 0) {
8457 err = got_ferror(f, GOT_ERR_IO);
8458 goto done;
8461 n = fprintf(f, "# Available histedit commands:\n");
8462 if (n < 0) {
8463 err = got_ferror(f, GOT_ERR_IO);
8464 goto done;
8467 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8468 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8469 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8470 cmd->desc);
8471 if (n < 0) {
8472 err = got_ferror(f, GOT_ERR_IO);
8473 break;
8476 done:
8477 free(id_str);
8478 return err;
8481 static const struct got_error *
8482 histedit_syntax_error(int lineno)
8484 static char msg[42];
8485 int ret;
8487 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8488 lineno);
8489 if (ret == -1 || ret >= sizeof(msg))
8490 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8492 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8495 static const struct got_error *
8496 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8497 char *logmsg, struct got_repository *repo)
8499 const struct got_error *err;
8500 struct got_commit_object *folded_commit = NULL;
8501 char *id_str, *folded_logmsg = NULL;
8503 err = got_object_id_str(&id_str, hle->commit_id);
8504 if (err)
8505 return err;
8507 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8508 if (err)
8509 goto done;
8511 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8512 if (err)
8513 goto done;
8514 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8515 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8516 folded_logmsg) == -1) {
8517 err = got_error_from_errno("asprintf");
8519 done:
8520 if (folded_commit)
8521 got_object_commit_close(folded_commit);
8522 free(id_str);
8523 free(folded_logmsg);
8524 return err;
8527 static struct got_histedit_list_entry *
8528 get_folded_commits(struct got_histedit_list_entry *hle)
8530 struct got_histedit_list_entry *prev, *folded = NULL;
8532 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8533 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8534 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8535 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8536 folded = prev;
8537 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8540 return folded;
8543 static const struct got_error *
8544 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8545 struct got_repository *repo)
8547 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8548 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8549 const struct got_error *err = NULL;
8550 struct got_commit_object *commit = NULL;
8551 int logmsg_len;
8552 int fd;
8553 struct got_histedit_list_entry *folded = NULL;
8555 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8556 if (err)
8557 return err;
8559 folded = get_folded_commits(hle);
8560 if (folded) {
8561 while (folded != hle) {
8562 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8563 folded = TAILQ_NEXT(folded, entry);
8564 continue;
8566 err = append_folded_commit_msg(&new_msg, folded,
8567 logmsg, repo);
8568 if (err)
8569 goto done;
8570 free(logmsg);
8571 logmsg = new_msg;
8572 folded = TAILQ_NEXT(folded, entry);
8576 err = got_object_id_str(&id_str, hle->commit_id);
8577 if (err)
8578 goto done;
8579 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8580 if (err)
8581 goto done;
8582 logmsg_len = asprintf(&new_msg,
8583 "%s\n# original log message of commit %s: %s",
8584 logmsg ? logmsg : "", id_str, orig_logmsg);
8585 if (logmsg_len == -1) {
8586 err = got_error_from_errno("asprintf");
8587 goto done;
8589 free(logmsg);
8590 logmsg = new_msg;
8592 err = got_object_id_str(&id_str, hle->commit_id);
8593 if (err)
8594 goto done;
8596 err = got_opentemp_named_fd(&logmsg_path, &fd,
8597 GOT_TMPDIR_STR "/got-logmsg");
8598 if (err)
8599 goto done;
8601 write(fd, logmsg, logmsg_len);
8602 close(fd);
8604 err = get_editor(&editor);
8605 if (err)
8606 goto done;
8608 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8609 logmsg_len, 0);
8610 if (err) {
8611 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8612 goto done;
8613 err = NULL;
8614 hle->logmsg = strdup(new_msg);
8615 if (hle->logmsg == NULL)
8616 err = got_error_from_errno("strdup");
8618 done:
8619 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8620 err = got_error_from_errno2("unlink", logmsg_path);
8621 free(logmsg_path);
8622 free(logmsg);
8623 free(orig_logmsg);
8624 free(editor);
8625 if (commit)
8626 got_object_commit_close(commit);
8627 return err;
8630 static const struct got_error *
8631 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8632 FILE *f, struct got_repository *repo)
8634 const struct got_error *err = NULL;
8635 char *line = NULL, *p, *end;
8636 size_t i, size;
8637 ssize_t len;
8638 int lineno = 0;
8639 const struct got_histedit_cmd *cmd;
8640 struct got_object_id *commit_id = NULL;
8641 struct got_histedit_list_entry *hle = NULL;
8643 for (;;) {
8644 len = getline(&line, &size, f);
8645 if (len == -1) {
8646 const struct got_error *getline_err;
8647 if (feof(f))
8648 break;
8649 getline_err = got_error_from_errno("getline");
8650 err = got_ferror(f, getline_err->code);
8651 break;
8653 lineno++;
8654 p = line;
8655 while (isspace((unsigned char)p[0]))
8656 p++;
8657 if (p[0] == '#' || p[0] == '\0') {
8658 free(line);
8659 line = NULL;
8660 continue;
8662 cmd = NULL;
8663 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8664 cmd = &got_histedit_cmds[i];
8665 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8666 isspace((unsigned char)p[strlen(cmd->name)])) {
8667 p += strlen(cmd->name);
8668 break;
8670 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8671 p++;
8672 break;
8675 if (i == nitems(got_histedit_cmds)) {
8676 err = histedit_syntax_error(lineno);
8677 break;
8679 while (isspace((unsigned char)p[0]))
8680 p++;
8681 if (cmd->code == GOT_HISTEDIT_MESG) {
8682 if (hle == NULL || hle->logmsg != NULL) {
8683 err = got_error(GOT_ERR_HISTEDIT_CMD);
8684 break;
8686 if (p[0] == '\0') {
8687 err = histedit_edit_logmsg(hle, repo);
8688 if (err)
8689 break;
8690 } else {
8691 hle->logmsg = strdup(p);
8692 if (hle->logmsg == NULL) {
8693 err = got_error_from_errno("strdup");
8694 break;
8697 free(line);
8698 line = NULL;
8699 continue;
8700 } else {
8701 end = p;
8702 while (end[0] && !isspace((unsigned char)end[0]))
8703 end++;
8704 *end = '\0';
8706 err = got_object_resolve_id_str(&commit_id, repo, p);
8707 if (err) {
8708 /* override error code */
8709 err = histedit_syntax_error(lineno);
8710 break;
8713 hle = malloc(sizeof(*hle));
8714 if (hle == NULL) {
8715 err = got_error_from_errno("malloc");
8716 break;
8718 hle->cmd = cmd;
8719 hle->commit_id = commit_id;
8720 hle->logmsg = NULL;
8721 commit_id = NULL;
8722 free(line);
8723 line = NULL;
8724 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8727 free(line);
8728 free(commit_id);
8729 return err;
8732 static const struct got_error *
8733 histedit_check_script(struct got_histedit_list *histedit_cmds,
8734 struct got_object_id_queue *commits, struct got_repository *repo)
8736 const struct got_error *err = NULL;
8737 struct got_object_qid *qid;
8738 struct got_histedit_list_entry *hle;
8739 static char msg[92];
8740 char *id_str;
8742 if (TAILQ_EMPTY(histedit_cmds))
8743 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8744 "histedit script contains no commands");
8745 if (SIMPLEQ_EMPTY(commits))
8746 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8748 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8749 struct got_histedit_list_entry *hle2;
8750 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8751 if (hle == hle2)
8752 continue;
8753 if (got_object_id_cmp(hle->commit_id,
8754 hle2->commit_id) != 0)
8755 continue;
8756 err = got_object_id_str(&id_str, hle->commit_id);
8757 if (err)
8758 return err;
8759 snprintf(msg, sizeof(msg), "commit %s is listed "
8760 "more than once in histedit script", id_str);
8761 free(id_str);
8762 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8766 SIMPLEQ_FOREACH(qid, commits, entry) {
8767 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8768 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8769 break;
8771 if (hle == NULL) {
8772 err = got_object_id_str(&id_str, qid->id);
8773 if (err)
8774 return err;
8775 snprintf(msg, sizeof(msg),
8776 "commit %s missing from histedit script", id_str);
8777 free(id_str);
8778 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8782 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8783 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8784 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8785 "last commit in histedit script cannot be folded");
8787 return NULL;
8790 static const struct got_error *
8791 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8792 const char *path, struct got_object_id_queue *commits,
8793 struct got_repository *repo)
8795 const struct got_error *err = NULL;
8796 char *editor;
8797 FILE *f = NULL;
8799 err = get_editor(&editor);
8800 if (err)
8801 return err;
8803 if (spawn_editor(editor, path) == -1) {
8804 err = got_error_from_errno("failed spawning editor");
8805 goto done;
8808 f = fopen(path, "r");
8809 if (f == NULL) {
8810 err = got_error_from_errno("fopen");
8811 goto done;
8813 err = histedit_parse_list(histedit_cmds, f, repo);
8814 if (err)
8815 goto done;
8817 err = histedit_check_script(histedit_cmds, commits, repo);
8818 done:
8819 if (f && fclose(f) == EOF && err == NULL)
8820 err = got_error_from_errno("fclose");
8821 free(editor);
8822 return err;
8825 static const struct got_error *
8826 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8827 struct got_object_id_queue *, const char *, const char *,
8828 struct got_repository *);
8830 static const struct got_error *
8831 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8832 struct got_object_id_queue *commits, const char *branch_name,
8833 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8835 const struct got_error *err;
8836 FILE *f = NULL;
8837 char *path = NULL;
8839 err = got_opentemp_named(&path, &f, "got-histedit");
8840 if (err)
8841 return err;
8843 err = write_cmd_list(f, branch_name, commits);
8844 if (err)
8845 goto done;
8847 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8848 fold_only, repo);
8849 if (err)
8850 goto done;
8852 if (edit_logmsg_only || fold_only) {
8853 rewind(f);
8854 err = histedit_parse_list(histedit_cmds, f, repo);
8855 } else {
8856 if (fclose(f) == EOF) {
8857 err = got_error_from_errno("fclose");
8858 goto done;
8860 f = NULL;
8861 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8862 if (err) {
8863 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8864 err->code != GOT_ERR_HISTEDIT_CMD)
8865 goto done;
8866 err = histedit_edit_list_retry(histedit_cmds, err,
8867 commits, path, branch_name, repo);
8870 done:
8871 if (f && fclose(f) == EOF && err == NULL)
8872 err = got_error_from_errno("fclose");
8873 if (path && unlink(path) != 0 && err == NULL)
8874 err = got_error_from_errno2("unlink", path);
8875 free(path);
8876 return err;
8879 static const struct got_error *
8880 histedit_save_list(struct got_histedit_list *histedit_cmds,
8881 struct got_worktree *worktree, struct got_repository *repo)
8883 const struct got_error *err = NULL;
8884 char *path = NULL;
8885 FILE *f = NULL;
8886 struct got_histedit_list_entry *hle;
8887 struct got_commit_object *commit = NULL;
8889 err = got_worktree_get_histedit_script_path(&path, worktree);
8890 if (err)
8891 return err;
8893 f = fopen(path, "w");
8894 if (f == NULL) {
8895 err = got_error_from_errno2("fopen", path);
8896 goto done;
8898 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8899 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8900 repo);
8901 if (err)
8902 break;
8904 if (hle->logmsg) {
8905 int n = fprintf(f, "%c %s\n",
8906 GOT_HISTEDIT_MESG, hle->logmsg);
8907 if (n < 0) {
8908 err = got_ferror(f, GOT_ERR_IO);
8909 break;
8913 done:
8914 if (f && fclose(f) == EOF && err == NULL)
8915 err = got_error_from_errno("fclose");
8916 free(path);
8917 if (commit)
8918 got_object_commit_close(commit);
8919 return err;
8922 void
8923 histedit_free_list(struct got_histedit_list *histedit_cmds)
8925 struct got_histedit_list_entry *hle;
8927 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8928 TAILQ_REMOVE(histedit_cmds, hle, entry);
8929 free(hle);
8933 static const struct got_error *
8934 histedit_load_list(struct got_histedit_list *histedit_cmds,
8935 const char *path, struct got_repository *repo)
8937 const struct got_error *err = NULL;
8938 FILE *f = NULL;
8940 f = fopen(path, "r");
8941 if (f == NULL) {
8942 err = got_error_from_errno2("fopen", path);
8943 goto done;
8946 err = histedit_parse_list(histedit_cmds, f, repo);
8947 done:
8948 if (f && fclose(f) == EOF && err == NULL)
8949 err = got_error_from_errno("fclose");
8950 return err;
8953 static const struct got_error *
8954 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8955 const struct got_error *edit_err, struct got_object_id_queue *commits,
8956 const char *path, const char *branch_name, struct got_repository *repo)
8958 const struct got_error *err = NULL, *prev_err = edit_err;
8959 int resp = ' ';
8961 while (resp != 'c' && resp != 'r' && resp != 'a') {
8962 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8963 "or (a)bort: ", getprogname(), prev_err->msg);
8964 resp = getchar();
8965 if (resp == '\n')
8966 resp = getchar();
8967 if (resp == 'c') {
8968 histedit_free_list(histedit_cmds);
8969 err = histedit_run_editor(histedit_cmds, path, commits,
8970 repo);
8971 if (err) {
8972 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8973 err->code != GOT_ERR_HISTEDIT_CMD)
8974 break;
8975 prev_err = err;
8976 resp = ' ';
8977 continue;
8979 break;
8980 } else if (resp == 'r') {
8981 histedit_free_list(histedit_cmds);
8982 err = histedit_edit_script(histedit_cmds,
8983 commits, branch_name, 0, 0, repo);
8984 if (err) {
8985 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8986 err->code != GOT_ERR_HISTEDIT_CMD)
8987 break;
8988 prev_err = err;
8989 resp = ' ';
8990 continue;
8992 break;
8993 } else if (resp == 'a') {
8994 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8995 break;
8996 } else
8997 printf("invalid response '%c'\n", resp);
9000 return err;
9003 static const struct got_error *
9004 histedit_complete(struct got_worktree *worktree,
9005 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9006 struct got_reference *branch, struct got_repository *repo)
9008 printf("Switching work tree to %s\n",
9009 got_ref_get_symref_target(branch));
9010 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9011 branch, repo);
9014 static const struct got_error *
9015 show_histedit_progress(struct got_commit_object *commit,
9016 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9018 const struct got_error *err;
9019 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9021 err = got_object_id_str(&old_id_str, hle->commit_id);
9022 if (err)
9023 goto done;
9025 if (new_id) {
9026 err = got_object_id_str(&new_id_str, new_id);
9027 if (err)
9028 goto done;
9031 old_id_str[12] = '\0';
9032 if (new_id_str)
9033 new_id_str[12] = '\0';
9035 if (hle->logmsg) {
9036 logmsg = strdup(hle->logmsg);
9037 if (logmsg == NULL) {
9038 err = got_error_from_errno("strdup");
9039 goto done;
9041 trim_logmsg(logmsg, 42);
9042 } else {
9043 err = get_short_logmsg(&logmsg, 42, commit);
9044 if (err)
9045 goto done;
9048 switch (hle->cmd->code) {
9049 case GOT_HISTEDIT_PICK:
9050 case GOT_HISTEDIT_EDIT:
9051 printf("%s -> %s: %s\n", old_id_str,
9052 new_id_str ? new_id_str : "no-op change", logmsg);
9053 break;
9054 case GOT_HISTEDIT_DROP:
9055 case GOT_HISTEDIT_FOLD:
9056 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9057 logmsg);
9058 break;
9059 default:
9060 break;
9062 done:
9063 free(old_id_str);
9064 free(new_id_str);
9065 return err;
9068 static const struct got_error *
9069 histedit_commit(struct got_pathlist_head *merged_paths,
9070 struct got_worktree *worktree, struct got_fileindex *fileindex,
9071 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9072 struct got_repository *repo)
9074 const struct got_error *err;
9075 struct got_commit_object *commit;
9076 struct got_object_id *new_commit_id;
9078 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9079 && hle->logmsg == NULL) {
9080 err = histedit_edit_logmsg(hle, repo);
9081 if (err)
9082 return err;
9085 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9086 if (err)
9087 return err;
9089 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9090 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9091 hle->logmsg, repo);
9092 if (err) {
9093 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9094 goto done;
9095 err = show_histedit_progress(commit, hle, NULL);
9096 } else {
9097 err = show_histedit_progress(commit, hle, new_commit_id);
9098 free(new_commit_id);
9100 done:
9101 got_object_commit_close(commit);
9102 return err;
9105 static const struct got_error *
9106 histedit_skip_commit(struct got_histedit_list_entry *hle,
9107 struct got_worktree *worktree, struct got_repository *repo)
9109 const struct got_error *error;
9110 struct got_commit_object *commit;
9112 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9113 repo);
9114 if (error)
9115 return error;
9117 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9118 if (error)
9119 return error;
9121 error = show_histedit_progress(commit, hle, NULL);
9122 got_object_commit_close(commit);
9123 return error;
9126 static const struct got_error *
9127 check_local_changes(void *arg, unsigned char status,
9128 unsigned char staged_status, const char *path,
9129 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9130 struct got_object_id *commit_id, int dirfd, const char *de_name)
9132 int *have_local_changes = arg;
9134 switch (status) {
9135 case GOT_STATUS_ADD:
9136 case GOT_STATUS_DELETE:
9137 case GOT_STATUS_MODIFY:
9138 case GOT_STATUS_CONFLICT:
9139 *have_local_changes = 1;
9140 return got_error(GOT_ERR_CANCELLED);
9141 default:
9142 break;
9145 switch (staged_status) {
9146 case GOT_STATUS_ADD:
9147 case GOT_STATUS_DELETE:
9148 case GOT_STATUS_MODIFY:
9149 *have_local_changes = 1;
9150 return got_error(GOT_ERR_CANCELLED);
9151 default:
9152 break;
9155 return NULL;
9158 static const struct got_error *
9159 cmd_histedit(int argc, char *argv[])
9161 const struct got_error *error = NULL;
9162 struct got_worktree *worktree = NULL;
9163 struct got_fileindex *fileindex = NULL;
9164 struct got_repository *repo = NULL;
9165 char *cwd = NULL;
9166 struct got_reference *branch = NULL;
9167 struct got_reference *tmp_branch = NULL;
9168 struct got_object_id *resume_commit_id = NULL;
9169 struct got_object_id *base_commit_id = NULL;
9170 struct got_object_id *head_commit_id = NULL;
9171 struct got_commit_object *commit = NULL;
9172 int ch, rebase_in_progress = 0;
9173 struct got_update_progress_arg upa;
9174 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9175 int edit_logmsg_only = 0, fold_only = 0;
9176 int list_backups = 0;
9177 const char *edit_script_path = NULL;
9178 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9179 struct got_object_id_queue commits;
9180 struct got_pathlist_head merged_paths;
9181 const struct got_object_id_queue *parent_ids;
9182 struct got_object_qid *pid;
9183 struct got_histedit_list histedit_cmds;
9184 struct got_histedit_list_entry *hle;
9186 SIMPLEQ_INIT(&commits);
9187 TAILQ_INIT(&histedit_cmds);
9188 TAILQ_INIT(&merged_paths);
9189 memset(&upa, 0, sizeof(upa));
9191 while ((ch = getopt(argc, argv, "acfF:ml")) != -1) {
9192 switch (ch) {
9193 case 'a':
9194 abort_edit = 1;
9195 break;
9196 case 'c':
9197 continue_edit = 1;
9198 break;
9199 case 'f':
9200 fold_only = 1;
9201 break;
9202 case 'F':
9203 edit_script_path = optarg;
9204 break;
9205 case 'm':
9206 edit_logmsg_only = 1;
9207 break;
9208 case 'l':
9209 list_backups = 1;
9210 break;
9211 default:
9212 usage_histedit();
9213 /* NOTREACHED */
9217 argc -= optind;
9218 argv += optind;
9220 #ifndef PROFILE
9221 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9222 "unveil", NULL) == -1)
9223 err(1, "pledge");
9224 #endif
9225 if (abort_edit && continue_edit)
9226 option_conflict('a', 'c');
9227 if (edit_script_path && edit_logmsg_only)
9228 option_conflict('F', 'm');
9229 if (abort_edit && edit_logmsg_only)
9230 option_conflict('a', 'm');
9231 if (continue_edit && edit_logmsg_only)
9232 option_conflict('c', 'm');
9233 if (abort_edit && fold_only)
9234 option_conflict('a', 'f');
9235 if (continue_edit && fold_only)
9236 option_conflict('c', 'f');
9237 if (fold_only && edit_logmsg_only)
9238 option_conflict('f', 'm');
9239 if (edit_script_path && fold_only)
9240 option_conflict('F', 'f');
9241 if (list_backups) {
9242 if (abort_edit)
9243 option_conflict('l', 'a');
9244 if (continue_edit)
9245 option_conflict('l', 'c');
9246 if (edit_script_path)
9247 option_conflict('l', 'F');
9248 if (edit_logmsg_only)
9249 option_conflict('l', 'm');
9250 if (fold_only)
9251 option_conflict('l', 'f');
9252 if (argc != 0 && argc != 1)
9253 usage_histedit();
9254 } else if (argc != 0)
9255 usage_histedit();
9258 * This command cannot apply unveil(2) in all cases because the
9259 * user may choose to run an editor to edit the histedit script
9260 * and to edit individual commit log messages.
9261 * unveil(2) traverses exec(2); if an editor is used we have to
9262 * apply unveil after edit script and log messages have been written.
9263 * XXX TODO: Make use of unveil(2) where possible.
9266 cwd = getcwd(NULL, 0);
9267 if (cwd == NULL) {
9268 error = got_error_from_errno("getcwd");
9269 goto done;
9271 error = got_worktree_open(&worktree, cwd);
9272 if (error) {
9273 if (list_backups) {
9274 if (error->code != GOT_ERR_NOT_WORKTREE)
9275 goto done;
9276 } else {
9277 if (error->code == GOT_ERR_NOT_WORKTREE)
9278 error = wrap_not_worktree_error(error,
9279 "histedit", cwd);
9280 goto done;
9284 if (list_backups) {
9285 error = got_repo_open(&repo,
9286 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9287 NULL);
9288 if (error != NULL)
9289 goto done;
9290 error = apply_unveil(got_repo_get_path(repo), 0,
9291 worktree ? got_worktree_get_root_path(worktree) : NULL);
9292 if (error)
9293 goto done;
9294 error = list_backup_refs(
9295 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9296 argc == 1 ? argv[0] : NULL, repo);
9297 goto done; /* nothing else to do */
9300 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9301 NULL);
9302 if (error != NULL)
9303 goto done;
9305 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9306 if (error)
9307 goto done;
9308 if (rebase_in_progress) {
9309 error = got_error(GOT_ERR_REBASING);
9310 goto done;
9313 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9314 if (error)
9315 goto done;
9317 if (edit_in_progress && edit_logmsg_only) {
9318 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9319 "histedit operation is in progress in this "
9320 "work tree and must be continued or aborted "
9321 "before the -m option can be used");
9322 goto done;
9324 if (edit_in_progress && fold_only) {
9325 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9326 "histedit operation is in progress in this "
9327 "work tree and must be continued or aborted "
9328 "before the -f option can be used");
9329 goto done;
9332 if (edit_in_progress && abort_edit) {
9333 error = got_worktree_histedit_continue(&resume_commit_id,
9334 &tmp_branch, &branch, &base_commit_id, &fileindex,
9335 worktree, repo);
9336 if (error)
9337 goto done;
9338 printf("Switching work tree to %s\n",
9339 got_ref_get_symref_target(branch));
9340 error = got_worktree_histedit_abort(worktree, fileindex, repo,
9341 branch, base_commit_id, update_progress, &upa);
9342 if (error)
9343 goto done;
9344 printf("Histedit of %s aborted\n",
9345 got_ref_get_symref_target(branch));
9346 print_update_progress_stats(&upa);
9347 goto done; /* nothing else to do */
9348 } else if (abort_edit) {
9349 error = got_error(GOT_ERR_NOT_HISTEDIT);
9350 goto done;
9353 if (continue_edit) {
9354 char *path;
9356 if (!edit_in_progress) {
9357 error = got_error(GOT_ERR_NOT_HISTEDIT);
9358 goto done;
9361 error = got_worktree_get_histedit_script_path(&path, worktree);
9362 if (error)
9363 goto done;
9365 error = histedit_load_list(&histedit_cmds, path, repo);
9366 free(path);
9367 if (error)
9368 goto done;
9370 error = got_worktree_histedit_continue(&resume_commit_id,
9371 &tmp_branch, &branch, &base_commit_id, &fileindex,
9372 worktree, repo);
9373 if (error)
9374 goto done;
9376 error = got_ref_resolve(&head_commit_id, repo, branch);
9377 if (error)
9378 goto done;
9380 error = got_object_open_as_commit(&commit, repo,
9381 head_commit_id);
9382 if (error)
9383 goto done;
9384 parent_ids = got_object_commit_get_parent_ids(commit);
9385 pid = SIMPLEQ_FIRST(parent_ids);
9386 if (pid == NULL) {
9387 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9388 goto done;
9390 error = collect_commits(&commits, head_commit_id, pid->id,
9391 base_commit_id, got_worktree_get_path_prefix(worktree),
9392 GOT_ERR_HISTEDIT_PATH, repo);
9393 got_object_commit_close(commit);
9394 commit = NULL;
9395 if (error)
9396 goto done;
9397 } else {
9398 if (edit_in_progress) {
9399 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9400 goto done;
9403 error = got_ref_open(&branch, repo,
9404 got_worktree_get_head_ref_name(worktree), 0);
9405 if (error != NULL)
9406 goto done;
9408 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
9409 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
9410 "will not edit commit history of a branch outside "
9411 "the \"refs/heads/\" reference namespace");
9412 goto done;
9415 error = got_ref_resolve(&head_commit_id, repo, branch);
9416 got_ref_close(branch);
9417 branch = NULL;
9418 if (error)
9419 goto done;
9421 error = got_object_open_as_commit(&commit, repo,
9422 head_commit_id);
9423 if (error)
9424 goto done;
9425 parent_ids = got_object_commit_get_parent_ids(commit);
9426 pid = SIMPLEQ_FIRST(parent_ids);
9427 if (pid == NULL) {
9428 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9429 goto done;
9431 error = collect_commits(&commits, head_commit_id, pid->id,
9432 got_worktree_get_base_commit_id(worktree),
9433 got_worktree_get_path_prefix(worktree),
9434 GOT_ERR_HISTEDIT_PATH, repo);
9435 got_object_commit_close(commit);
9436 commit = NULL;
9437 if (error)
9438 goto done;
9440 if (SIMPLEQ_EMPTY(&commits)) {
9441 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9442 goto done;
9445 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
9446 &base_commit_id, &fileindex, worktree, repo);
9447 if (error)
9448 goto done;
9450 if (edit_script_path) {
9451 error = histedit_load_list(&histedit_cmds,
9452 edit_script_path, repo);
9453 if (error) {
9454 got_worktree_histedit_abort(worktree, fileindex,
9455 repo, branch, base_commit_id,
9456 update_progress, &upa);
9457 print_update_progress_stats(&upa);
9458 goto done;
9460 } else {
9461 const char *branch_name;
9462 branch_name = got_ref_get_symref_target(branch);
9463 if (strncmp(branch_name, "refs/heads/", 11) == 0)
9464 branch_name += 11;
9465 error = histedit_edit_script(&histedit_cmds, &commits,
9466 branch_name, edit_logmsg_only, fold_only, repo);
9467 if (error) {
9468 got_worktree_histedit_abort(worktree, fileindex,
9469 repo, branch, base_commit_id,
9470 update_progress, &upa);
9471 print_update_progress_stats(&upa);
9472 goto done;
9477 error = histedit_save_list(&histedit_cmds, worktree,
9478 repo);
9479 if (error) {
9480 got_worktree_histedit_abort(worktree, fileindex,
9481 repo, branch, base_commit_id,
9482 update_progress, &upa);
9483 print_update_progress_stats(&upa);
9484 goto done;
9489 error = histedit_check_script(&histedit_cmds, &commits, repo);
9490 if (error)
9491 goto done;
9493 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9494 if (resume_commit_id) {
9495 if (got_object_id_cmp(hle->commit_id,
9496 resume_commit_id) != 0)
9497 continue;
9499 resume_commit_id = NULL;
9500 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9501 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9502 error = histedit_skip_commit(hle, worktree,
9503 repo);
9504 if (error)
9505 goto done;
9506 } else {
9507 struct got_pathlist_head paths;
9508 int have_changes = 0;
9510 TAILQ_INIT(&paths);
9511 error = got_pathlist_append(&paths, "", NULL);
9512 if (error)
9513 goto done;
9514 error = got_worktree_status(worktree, &paths,
9515 repo, check_local_changes, &have_changes,
9516 check_cancelled, NULL);
9517 got_pathlist_free(&paths);
9518 if (error) {
9519 if (error->code != GOT_ERR_CANCELLED)
9520 goto done;
9521 if (sigint_received || sigpipe_received)
9522 goto done;
9524 if (have_changes) {
9525 error = histedit_commit(NULL, worktree,
9526 fileindex, tmp_branch, hle, repo);
9527 if (error)
9528 goto done;
9529 } else {
9530 error = got_object_open_as_commit(
9531 &commit, repo, hle->commit_id);
9532 if (error)
9533 goto done;
9534 error = show_histedit_progress(commit,
9535 hle, NULL);
9536 got_object_commit_close(commit);
9537 commit = NULL;
9538 if (error)
9539 goto done;
9542 continue;
9545 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9546 error = histedit_skip_commit(hle, worktree, repo);
9547 if (error)
9548 goto done;
9549 continue;
9552 error = got_object_open_as_commit(&commit, repo,
9553 hle->commit_id);
9554 if (error)
9555 goto done;
9556 parent_ids = got_object_commit_get_parent_ids(commit);
9557 pid = SIMPLEQ_FIRST(parent_ids);
9559 error = got_worktree_histedit_merge_files(&merged_paths,
9560 worktree, fileindex, pid->id, hle->commit_id, repo,
9561 update_progress, &upa, check_cancelled, NULL);
9562 if (error)
9563 goto done;
9564 got_object_commit_close(commit);
9565 commit = NULL;
9567 print_update_progress_stats(&upa);
9568 if (upa.conflicts > 0)
9569 rebase_status = GOT_STATUS_CONFLICT;
9571 if (rebase_status == GOT_STATUS_CONFLICT) {
9572 error = show_rebase_merge_conflict(hle->commit_id,
9573 repo);
9574 if (error)
9575 goto done;
9576 got_worktree_rebase_pathlist_free(&merged_paths);
9577 break;
9580 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9581 char *id_str;
9582 error = got_object_id_str(&id_str, hle->commit_id);
9583 if (error)
9584 goto done;
9585 printf("Stopping histedit for amending commit %s\n",
9586 id_str);
9587 free(id_str);
9588 got_worktree_rebase_pathlist_free(&merged_paths);
9589 error = got_worktree_histedit_postpone(worktree,
9590 fileindex);
9591 goto done;
9594 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9595 error = histedit_skip_commit(hle, worktree, repo);
9596 if (error)
9597 goto done;
9598 continue;
9601 error = histedit_commit(&merged_paths, worktree, fileindex,
9602 tmp_branch, hle, repo);
9603 got_worktree_rebase_pathlist_free(&merged_paths);
9604 if (error)
9605 goto done;
9608 if (rebase_status == GOT_STATUS_CONFLICT) {
9609 error = got_worktree_histedit_postpone(worktree, fileindex);
9610 if (error)
9611 goto done;
9612 error = got_error_msg(GOT_ERR_CONFLICTS,
9613 "conflicts must be resolved before histedit can continue");
9614 } else
9615 error = histedit_complete(worktree, fileindex, tmp_branch,
9616 branch, repo);
9617 done:
9618 got_object_id_queue_free(&commits);
9619 histedit_free_list(&histedit_cmds);
9620 free(head_commit_id);
9621 free(base_commit_id);
9622 free(resume_commit_id);
9623 if (commit)
9624 got_object_commit_close(commit);
9625 if (branch)
9626 got_ref_close(branch);
9627 if (tmp_branch)
9628 got_ref_close(tmp_branch);
9629 if (worktree)
9630 got_worktree_close(worktree);
9631 if (repo)
9632 got_repo_close(repo);
9633 return error;
9636 __dead static void
9637 usage_integrate(void)
9639 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9640 exit(1);
9643 static const struct got_error *
9644 cmd_integrate(int argc, char *argv[])
9646 const struct got_error *error = NULL;
9647 struct got_repository *repo = NULL;
9648 struct got_worktree *worktree = NULL;
9649 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9650 const char *branch_arg = NULL;
9651 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9652 struct got_fileindex *fileindex = NULL;
9653 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9654 int ch;
9655 struct got_update_progress_arg upa;
9657 while ((ch = getopt(argc, argv, "")) != -1) {
9658 switch (ch) {
9659 default:
9660 usage_integrate();
9661 /* NOTREACHED */
9665 argc -= optind;
9666 argv += optind;
9668 if (argc != 1)
9669 usage_integrate();
9670 branch_arg = argv[0];
9671 #ifndef PROFILE
9672 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9673 "unveil", NULL) == -1)
9674 err(1, "pledge");
9675 #endif
9676 cwd = getcwd(NULL, 0);
9677 if (cwd == NULL) {
9678 error = got_error_from_errno("getcwd");
9679 goto done;
9682 error = got_worktree_open(&worktree, cwd);
9683 if (error) {
9684 if (error->code == GOT_ERR_NOT_WORKTREE)
9685 error = wrap_not_worktree_error(error, "integrate",
9686 cwd);
9687 goto done;
9690 error = check_rebase_or_histedit_in_progress(worktree);
9691 if (error)
9692 goto done;
9694 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9695 NULL);
9696 if (error != NULL)
9697 goto done;
9699 error = apply_unveil(got_repo_get_path(repo), 0,
9700 got_worktree_get_root_path(worktree));
9701 if (error)
9702 goto done;
9704 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9705 error = got_error_from_errno("asprintf");
9706 goto done;
9709 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9710 &base_branch_ref, worktree, refname, repo);
9711 if (error)
9712 goto done;
9714 refname = strdup(got_ref_get_name(branch_ref));
9715 if (refname == NULL) {
9716 error = got_error_from_errno("strdup");
9717 got_worktree_integrate_abort(worktree, fileindex, repo,
9718 branch_ref, base_branch_ref);
9719 goto done;
9721 base_refname = strdup(got_ref_get_name(base_branch_ref));
9722 if (base_refname == NULL) {
9723 error = got_error_from_errno("strdup");
9724 got_worktree_integrate_abort(worktree, fileindex, repo,
9725 branch_ref, base_branch_ref);
9726 goto done;
9729 error = got_ref_resolve(&commit_id, repo, branch_ref);
9730 if (error)
9731 goto done;
9733 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9734 if (error)
9735 goto done;
9737 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9738 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9739 "specified branch has already been integrated");
9740 got_worktree_integrate_abort(worktree, fileindex, repo,
9741 branch_ref, base_branch_ref);
9742 goto done;
9745 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9746 if (error) {
9747 if (error->code == GOT_ERR_ANCESTRY)
9748 error = got_error(GOT_ERR_REBASE_REQUIRED);
9749 got_worktree_integrate_abort(worktree, fileindex, repo,
9750 branch_ref, base_branch_ref);
9751 goto done;
9754 memset(&upa, 0, sizeof(upa));
9755 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9756 branch_ref, base_branch_ref, update_progress, &upa,
9757 check_cancelled, NULL);
9758 if (error)
9759 goto done;
9761 printf("Integrated %s into %s\n", refname, base_refname);
9762 print_update_progress_stats(&upa);
9763 done:
9764 if (repo)
9765 got_repo_close(repo);
9766 if (worktree)
9767 got_worktree_close(worktree);
9768 free(cwd);
9769 free(base_commit_id);
9770 free(commit_id);
9771 free(refname);
9772 free(base_refname);
9773 return error;
9776 __dead static void
9777 usage_stage(void)
9779 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9780 "[-S] [file-path ...]\n",
9781 getprogname());
9782 exit(1);
9785 static const struct got_error *
9786 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9787 const char *path, struct got_object_id *blob_id,
9788 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9789 int dirfd, const char *de_name)
9791 const struct got_error *err = NULL;
9792 char *id_str = NULL;
9794 if (staged_status != GOT_STATUS_ADD &&
9795 staged_status != GOT_STATUS_MODIFY &&
9796 staged_status != GOT_STATUS_DELETE)
9797 return NULL;
9799 if (staged_status == GOT_STATUS_ADD ||
9800 staged_status == GOT_STATUS_MODIFY)
9801 err = got_object_id_str(&id_str, staged_blob_id);
9802 else
9803 err = got_object_id_str(&id_str, blob_id);
9804 if (err)
9805 return err;
9807 printf("%s %c %s\n", id_str, staged_status, path);
9808 free(id_str);
9809 return NULL;
9812 static const struct got_error *
9813 cmd_stage(int argc, char *argv[])
9815 const struct got_error *error = NULL;
9816 struct got_repository *repo = NULL;
9817 struct got_worktree *worktree = NULL;
9818 char *cwd = NULL;
9819 struct got_pathlist_head paths;
9820 struct got_pathlist_entry *pe;
9821 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9822 FILE *patch_script_file = NULL;
9823 const char *patch_script_path = NULL;
9824 struct choose_patch_arg cpa;
9826 TAILQ_INIT(&paths);
9828 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9829 switch (ch) {
9830 case 'l':
9831 list_stage = 1;
9832 break;
9833 case 'p':
9834 pflag = 1;
9835 break;
9836 case 'F':
9837 patch_script_path = optarg;
9838 break;
9839 case 'S':
9840 allow_bad_symlinks = 1;
9841 break;
9842 default:
9843 usage_stage();
9844 /* NOTREACHED */
9848 argc -= optind;
9849 argv += optind;
9851 #ifndef PROFILE
9852 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9853 "unveil", NULL) == -1)
9854 err(1, "pledge");
9855 #endif
9856 if (list_stage && (pflag || patch_script_path))
9857 errx(1, "-l option cannot be used with other options");
9858 if (patch_script_path && !pflag)
9859 errx(1, "-F option can only be used together with -p option");
9861 cwd = getcwd(NULL, 0);
9862 if (cwd == NULL) {
9863 error = got_error_from_errno("getcwd");
9864 goto done;
9867 error = got_worktree_open(&worktree, cwd);
9868 if (error) {
9869 if (error->code == GOT_ERR_NOT_WORKTREE)
9870 error = wrap_not_worktree_error(error, "stage", cwd);
9871 goto done;
9874 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9875 NULL);
9876 if (error != NULL)
9877 goto done;
9879 if (patch_script_path) {
9880 patch_script_file = fopen(patch_script_path, "r");
9881 if (patch_script_file == NULL) {
9882 error = got_error_from_errno2("fopen",
9883 patch_script_path);
9884 goto done;
9887 error = apply_unveil(got_repo_get_path(repo), 0,
9888 got_worktree_get_root_path(worktree));
9889 if (error)
9890 goto done;
9892 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9893 if (error)
9894 goto done;
9896 if (list_stage)
9897 error = got_worktree_status(worktree, &paths, repo,
9898 print_stage, NULL, check_cancelled, NULL);
9899 else {
9900 cpa.patch_script_file = patch_script_file;
9901 cpa.action = "stage";
9902 error = got_worktree_stage(worktree, &paths,
9903 pflag ? NULL : print_status, NULL,
9904 pflag ? choose_patch : NULL, &cpa,
9905 allow_bad_symlinks, repo);
9907 done:
9908 if (patch_script_file && fclose(patch_script_file) == EOF &&
9909 error == NULL)
9910 error = got_error_from_errno2("fclose", patch_script_path);
9911 if (repo)
9912 got_repo_close(repo);
9913 if (worktree)
9914 got_worktree_close(worktree);
9915 TAILQ_FOREACH(pe, &paths, entry)
9916 free((char *)pe->path);
9917 got_pathlist_free(&paths);
9918 free(cwd);
9919 return error;
9922 __dead static void
9923 usage_unstage(void)
9925 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9926 "[file-path ...]\n",
9927 getprogname());
9928 exit(1);
9932 static const struct got_error *
9933 cmd_unstage(int argc, char *argv[])
9935 const struct got_error *error = NULL;
9936 struct got_repository *repo = NULL;
9937 struct got_worktree *worktree = NULL;
9938 char *cwd = NULL;
9939 struct got_pathlist_head paths;
9940 struct got_pathlist_entry *pe;
9941 int ch, pflag = 0;
9942 struct got_update_progress_arg upa;
9943 FILE *patch_script_file = NULL;
9944 const char *patch_script_path = NULL;
9945 struct choose_patch_arg cpa;
9947 TAILQ_INIT(&paths);
9949 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9950 switch (ch) {
9951 case 'p':
9952 pflag = 1;
9953 break;
9954 case 'F':
9955 patch_script_path = optarg;
9956 break;
9957 default:
9958 usage_unstage();
9959 /* NOTREACHED */
9963 argc -= optind;
9964 argv += optind;
9966 #ifndef PROFILE
9967 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9968 "unveil", NULL) == -1)
9969 err(1, "pledge");
9970 #endif
9971 if (patch_script_path && !pflag)
9972 errx(1, "-F option can only be used together with -p option");
9974 cwd = getcwd(NULL, 0);
9975 if (cwd == NULL) {
9976 error = got_error_from_errno("getcwd");
9977 goto done;
9980 error = got_worktree_open(&worktree, cwd);
9981 if (error) {
9982 if (error->code == GOT_ERR_NOT_WORKTREE)
9983 error = wrap_not_worktree_error(error, "unstage", cwd);
9984 goto done;
9987 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9988 NULL);
9989 if (error != NULL)
9990 goto done;
9992 if (patch_script_path) {
9993 patch_script_file = fopen(patch_script_path, "r");
9994 if (patch_script_file == NULL) {
9995 error = got_error_from_errno2("fopen",
9996 patch_script_path);
9997 goto done;
10001 error = apply_unveil(got_repo_get_path(repo), 0,
10002 got_worktree_get_root_path(worktree));
10003 if (error)
10004 goto done;
10006 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10007 if (error)
10008 goto done;
10010 cpa.patch_script_file = patch_script_file;
10011 cpa.action = "unstage";
10012 memset(&upa, 0, sizeof(upa));
10013 error = got_worktree_unstage(worktree, &paths, update_progress,
10014 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10015 if (!error)
10016 print_update_progress_stats(&upa);
10017 done:
10018 if (patch_script_file && fclose(patch_script_file) == EOF &&
10019 error == NULL)
10020 error = got_error_from_errno2("fclose", patch_script_path);
10021 if (repo)
10022 got_repo_close(repo);
10023 if (worktree)
10024 got_worktree_close(worktree);
10025 TAILQ_FOREACH(pe, &paths, entry)
10026 free((char *)pe->path);
10027 got_pathlist_free(&paths);
10028 free(cwd);
10029 return error;
10032 __dead static void
10033 usage_cat(void)
10035 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10036 "arg1 [arg2 ...]\n", getprogname());
10037 exit(1);
10040 static const struct got_error *
10041 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10043 const struct got_error *err;
10044 struct got_blob_object *blob;
10046 err = got_object_open_as_blob(&blob, repo, id, 8192);
10047 if (err)
10048 return err;
10050 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10051 got_object_blob_close(blob);
10052 return err;
10055 static const struct got_error *
10056 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10058 const struct got_error *err;
10059 struct got_tree_object *tree;
10060 int nentries, i;
10062 err = got_object_open_as_tree(&tree, repo, id);
10063 if (err)
10064 return err;
10066 nentries = got_object_tree_get_nentries(tree);
10067 for (i = 0; i < nentries; i++) {
10068 struct got_tree_entry *te;
10069 char *id_str;
10070 if (sigint_received || sigpipe_received)
10071 break;
10072 te = got_object_tree_get_entry(tree, i);
10073 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10074 if (err)
10075 break;
10076 fprintf(outfile, "%s %.7o %s\n", id_str,
10077 got_tree_entry_get_mode(te),
10078 got_tree_entry_get_name(te));
10079 free(id_str);
10082 got_object_tree_close(tree);
10083 return err;
10086 static const struct got_error *
10087 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10089 const struct got_error *err;
10090 struct got_commit_object *commit;
10091 const struct got_object_id_queue *parent_ids;
10092 struct got_object_qid *pid;
10093 char *id_str = NULL;
10094 const char *logmsg = NULL;
10096 err = got_object_open_as_commit(&commit, repo, id);
10097 if (err)
10098 return err;
10100 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10101 if (err)
10102 goto done;
10104 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10105 parent_ids = got_object_commit_get_parent_ids(commit);
10106 fprintf(outfile, "numparents %d\n",
10107 got_object_commit_get_nparents(commit));
10108 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
10109 char *pid_str;
10110 err = got_object_id_str(&pid_str, pid->id);
10111 if (err)
10112 goto done;
10113 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10114 free(pid_str);
10116 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10117 got_object_commit_get_author(commit),
10118 (long long)got_object_commit_get_author_time(commit));
10120 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10121 got_object_commit_get_author(commit),
10122 (long long)got_object_commit_get_committer_time(commit));
10124 logmsg = got_object_commit_get_logmsg_raw(commit);
10125 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10126 fprintf(outfile, "%s", logmsg);
10127 done:
10128 free(id_str);
10129 got_object_commit_close(commit);
10130 return err;
10133 static const struct got_error *
10134 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10136 const struct got_error *err;
10137 struct got_tag_object *tag;
10138 char *id_str = NULL;
10139 const char *tagmsg = NULL;
10141 err = got_object_open_as_tag(&tag, repo, id);
10142 if (err)
10143 return err;
10145 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10146 if (err)
10147 goto done;
10149 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10151 switch (got_object_tag_get_object_type(tag)) {
10152 case GOT_OBJ_TYPE_BLOB:
10153 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10154 GOT_OBJ_LABEL_BLOB);
10155 break;
10156 case GOT_OBJ_TYPE_TREE:
10157 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10158 GOT_OBJ_LABEL_TREE);
10159 break;
10160 case GOT_OBJ_TYPE_COMMIT:
10161 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10162 GOT_OBJ_LABEL_COMMIT);
10163 break;
10164 case GOT_OBJ_TYPE_TAG:
10165 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10166 GOT_OBJ_LABEL_TAG);
10167 break;
10168 default:
10169 break;
10172 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10173 got_object_tag_get_name(tag));
10175 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10176 got_object_tag_get_tagger(tag),
10177 (long long)got_object_tag_get_tagger_time(tag));
10179 tagmsg = got_object_tag_get_message(tag);
10180 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10181 fprintf(outfile, "%s", tagmsg);
10182 done:
10183 free(id_str);
10184 got_object_tag_close(tag);
10185 return err;
10188 static const struct got_error *
10189 cmd_cat(int argc, char *argv[])
10191 const struct got_error *error;
10192 struct got_repository *repo = NULL;
10193 struct got_worktree *worktree = NULL;
10194 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10195 const char *commit_id_str = NULL;
10196 struct got_object_id *id = NULL, *commit_id = NULL;
10197 int ch, obj_type, i, force_path = 0;
10198 struct got_reflist_head refs;
10200 TAILQ_INIT(&refs);
10202 #ifndef PROFILE
10203 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10204 NULL) == -1)
10205 err(1, "pledge");
10206 #endif
10208 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10209 switch (ch) {
10210 case 'c':
10211 commit_id_str = optarg;
10212 break;
10213 case 'r':
10214 repo_path = realpath(optarg, NULL);
10215 if (repo_path == NULL)
10216 return got_error_from_errno2("realpath",
10217 optarg);
10218 got_path_strip_trailing_slashes(repo_path);
10219 break;
10220 case 'P':
10221 force_path = 1;
10222 break;
10223 default:
10224 usage_cat();
10225 /* NOTREACHED */
10229 argc -= optind;
10230 argv += optind;
10232 cwd = getcwd(NULL, 0);
10233 if (cwd == NULL) {
10234 error = got_error_from_errno("getcwd");
10235 goto done;
10237 error = got_worktree_open(&worktree, cwd);
10238 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10239 goto done;
10240 if (worktree) {
10241 if (repo_path == NULL) {
10242 repo_path = strdup(
10243 got_worktree_get_repo_path(worktree));
10244 if (repo_path == NULL) {
10245 error = got_error_from_errno("strdup");
10246 goto done;
10251 if (repo_path == NULL) {
10252 repo_path = getcwd(NULL, 0);
10253 if (repo_path == NULL)
10254 return got_error_from_errno("getcwd");
10257 error = got_repo_open(&repo, repo_path, NULL);
10258 free(repo_path);
10259 if (error != NULL)
10260 goto done;
10262 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10263 if (error)
10264 goto done;
10266 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10267 if (error)
10268 goto done;
10270 if (commit_id_str == NULL)
10271 commit_id_str = GOT_REF_HEAD;
10272 error = got_repo_match_object_id(&commit_id, NULL,
10273 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10274 if (error)
10275 goto done;
10277 for (i = 0; i < argc; i++) {
10278 if (force_path) {
10279 error = got_object_id_by_path(&id, repo, commit_id,
10280 argv[i]);
10281 if (error)
10282 break;
10283 } else {
10284 error = got_repo_match_object_id(&id, &label, argv[i],
10285 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10286 repo);
10287 if (error) {
10288 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10289 error->code != GOT_ERR_NOT_REF)
10290 break;
10291 error = got_object_id_by_path(&id, repo,
10292 commit_id, argv[i]);
10293 if (error)
10294 break;
10298 error = got_object_get_type(&obj_type, repo, id);
10299 if (error)
10300 break;
10302 switch (obj_type) {
10303 case GOT_OBJ_TYPE_BLOB:
10304 error = cat_blob(id, repo, stdout);
10305 break;
10306 case GOT_OBJ_TYPE_TREE:
10307 error = cat_tree(id, repo, stdout);
10308 break;
10309 case GOT_OBJ_TYPE_COMMIT:
10310 error = cat_commit(id, repo, stdout);
10311 break;
10312 case GOT_OBJ_TYPE_TAG:
10313 error = cat_tag(id, repo, stdout);
10314 break;
10315 default:
10316 error = got_error(GOT_ERR_OBJ_TYPE);
10317 break;
10319 if (error)
10320 break;
10321 free(label);
10322 label = NULL;
10323 free(id);
10324 id = NULL;
10326 done:
10327 free(label);
10328 free(id);
10329 free(commit_id);
10330 if (worktree)
10331 got_worktree_close(worktree);
10332 if (repo) {
10333 const struct got_error *repo_error;
10334 repo_error = got_repo_close(repo);
10335 if (error == NULL)
10336 error = repo_error;
10338 got_ref_list_free(&refs);
10339 return error;
10342 __dead static void
10343 usage_info(void)
10345 fprintf(stderr, "usage: %s info [path ...]\n",
10346 getprogname());
10347 exit(1);
10350 static const struct got_error *
10351 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
10352 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10353 struct got_object_id *commit_id)
10355 const struct got_error *err = NULL;
10356 char *id_str = NULL;
10357 char datebuf[128];
10358 struct tm mytm, *tm;
10359 struct got_pathlist_head *paths = arg;
10360 struct got_pathlist_entry *pe;
10363 * Clear error indication from any of the path arguments which
10364 * would cause this file index entry to be displayed.
10366 TAILQ_FOREACH(pe, paths, entry) {
10367 if (got_path_cmp(path, pe->path, strlen(path),
10368 pe->path_len) == 0 ||
10369 got_path_is_child(path, pe->path, pe->path_len))
10370 pe->data = NULL; /* no error */
10373 printf(GOT_COMMIT_SEP_STR);
10374 if (S_ISLNK(mode))
10375 printf("symlink: %s\n", path);
10376 else if (S_ISREG(mode)) {
10377 printf("file: %s\n", path);
10378 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
10379 } else if (S_ISDIR(mode))
10380 printf("directory: %s\n", path);
10381 else
10382 printf("something: %s\n", path);
10384 tm = localtime_r(&mtime, &mytm);
10385 if (tm == NULL)
10386 return NULL;
10387 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
10388 return got_error(GOT_ERR_NO_SPACE);
10389 printf("timestamp: %s\n", datebuf);
10391 if (blob_id) {
10392 err = got_object_id_str(&id_str, blob_id);
10393 if (err)
10394 return err;
10395 printf("based on blob: %s\n", id_str);
10396 free(id_str);
10399 if (staged_blob_id) {
10400 err = got_object_id_str(&id_str, staged_blob_id);
10401 if (err)
10402 return err;
10403 printf("based on staged blob: %s\n", id_str);
10404 free(id_str);
10407 if (commit_id) {
10408 err = got_object_id_str(&id_str, commit_id);
10409 if (err)
10410 return err;
10411 printf("based on commit: %s\n", id_str);
10412 free(id_str);
10415 return NULL;
10418 static const struct got_error *
10419 cmd_info(int argc, char *argv[])
10421 const struct got_error *error = NULL;
10422 struct got_worktree *worktree = NULL;
10423 char *cwd = NULL, *id_str = NULL;
10424 struct got_pathlist_head paths;
10425 struct got_pathlist_entry *pe;
10426 char *uuidstr = NULL;
10427 int ch, show_files = 0;
10429 TAILQ_INIT(&paths);
10431 while ((ch = getopt(argc, argv, "")) != -1) {
10432 switch (ch) {
10433 default:
10434 usage_info();
10435 /* NOTREACHED */
10439 argc -= optind;
10440 argv += optind;
10442 #ifndef PROFILE
10443 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
10444 NULL) == -1)
10445 err(1, "pledge");
10446 #endif
10447 cwd = getcwd(NULL, 0);
10448 if (cwd == NULL) {
10449 error = got_error_from_errno("getcwd");
10450 goto done;
10453 error = got_worktree_open(&worktree, cwd);
10454 if (error) {
10455 if (error->code == GOT_ERR_NOT_WORKTREE)
10456 error = wrap_not_worktree_error(error, "info", cwd);
10457 goto done;
10460 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
10461 if (error)
10462 goto done;
10464 if (argc >= 1) {
10465 error = get_worktree_paths_from_argv(&paths, argc, argv,
10466 worktree);
10467 if (error)
10468 goto done;
10469 show_files = 1;
10472 error = got_object_id_str(&id_str,
10473 got_worktree_get_base_commit_id(worktree));
10474 if (error)
10475 goto done;
10477 error = got_worktree_get_uuid(&uuidstr, worktree);
10478 if (error)
10479 goto done;
10481 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
10482 printf("work tree base commit: %s\n", id_str);
10483 printf("work tree path prefix: %s\n",
10484 got_worktree_get_path_prefix(worktree));
10485 printf("work tree branch reference: %s\n",
10486 got_worktree_get_head_ref_name(worktree));
10487 printf("work tree UUID: %s\n", uuidstr);
10488 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10490 if (show_files) {
10491 struct got_pathlist_entry *pe;
10492 TAILQ_FOREACH(pe, &paths, entry) {
10493 if (pe->path_len == 0)
10494 continue;
10496 * Assume this path will fail. This will be corrected
10497 * in print_path_info() in case the path does suceeed.
10499 pe->data = (void *)got_error_path(pe->path,
10500 GOT_ERR_BAD_PATH);
10502 error = got_worktree_path_info(worktree, &paths,
10503 print_path_info, &paths, check_cancelled, NULL);
10504 if (error)
10505 goto done;
10506 TAILQ_FOREACH(pe, &paths, entry) {
10507 if (pe->data != NULL) {
10508 error = pe->data; /* bad path */
10509 break;
10513 done:
10514 TAILQ_FOREACH(pe, &paths, entry)
10515 free((char *)pe->path);
10516 got_pathlist_free(&paths);
10517 free(cwd);
10518 free(id_str);
10519 free(uuidstr);
10520 return error;