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 const struct got_error *close_err = got_repo_close(repo);
1805 if (error == NULL)
1806 error = close_err;
1808 TAILQ_FOREACH(pe, &refs, entry) {
1809 free((void *)pe->path);
1810 free(pe->data);
1812 got_pathlist_free(&refs);
1813 TAILQ_FOREACH(pe, &symrefs, entry) {
1814 free((void *)pe->path);
1815 free(pe->data);
1817 got_pathlist_free(&symrefs);
1818 got_pathlist_free(&wanted_branches);
1819 got_pathlist_free(&wanted_refs);
1820 free(pack_hash);
1821 free(proto);
1822 free(host);
1823 free(port);
1824 free(server_path);
1825 free(repo_name);
1826 free(default_destdir);
1827 free(git_url);
1828 return error;
1831 static const struct got_error *
1832 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1833 int replace_tags, int verbosity, struct got_repository *repo)
1835 const struct got_error *err = NULL;
1836 char *new_id_str = NULL;
1837 struct got_object_id *old_id = NULL;
1839 err = got_object_id_str(&new_id_str, new_id);
1840 if (err)
1841 goto done;
1843 if (!replace_tags &&
1844 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1845 err = got_ref_resolve(&old_id, repo, ref);
1846 if (err)
1847 goto done;
1848 if (got_object_id_cmp(old_id, new_id) == 0)
1849 goto done;
1850 if (verbosity >= 0) {
1851 printf("Rejecting update of existing tag %s: %s\n",
1852 got_ref_get_name(ref), new_id_str);
1854 goto done;
1857 if (got_ref_is_symbolic(ref)) {
1858 if (verbosity >= 0) {
1859 printf("Replacing reference %s: %s\n",
1860 got_ref_get_name(ref),
1861 got_ref_get_symref_target(ref));
1863 err = got_ref_change_symref_to_ref(ref, new_id);
1864 if (err)
1865 goto done;
1866 err = got_ref_write(ref, repo);
1867 if (err)
1868 goto done;
1869 } else {
1870 err = got_ref_resolve(&old_id, repo, ref);
1871 if (err)
1872 goto done;
1873 if (got_object_id_cmp(old_id, new_id) == 0)
1874 goto done;
1876 err = got_ref_change_ref(ref, new_id);
1877 if (err)
1878 goto done;
1879 err = got_ref_write(ref, repo);
1880 if (err)
1881 goto done;
1884 if (verbosity >= 0)
1885 printf("Updated %s: %s\n", got_ref_get_name(ref),
1886 new_id_str);
1887 done:
1888 free(old_id);
1889 free(new_id_str);
1890 return err;
1893 static const struct got_error *
1894 update_symref(const char *refname, struct got_reference *target_ref,
1895 int verbosity, struct got_repository *repo)
1897 const struct got_error *err = NULL, *unlock_err;
1898 struct got_reference *symref;
1899 int symref_is_locked = 0;
1901 err = got_ref_open(&symref, repo, refname, 1);
1902 if (err) {
1903 if (err->code != GOT_ERR_NOT_REF)
1904 return err;
1905 err = got_ref_alloc_symref(&symref, refname, target_ref);
1906 if (err)
1907 goto done;
1909 err = got_ref_write(symref, repo);
1910 if (err)
1911 goto done;
1913 if (verbosity >= 0)
1914 printf("Created reference %s: %s\n",
1915 got_ref_get_name(symref),
1916 got_ref_get_symref_target(symref));
1917 } else {
1918 symref_is_locked = 1;
1920 if (strcmp(got_ref_get_symref_target(symref),
1921 got_ref_get_name(target_ref)) == 0)
1922 goto done;
1924 err = got_ref_change_symref(symref,
1925 got_ref_get_name(target_ref));
1926 if (err)
1927 goto done;
1929 err = got_ref_write(symref, repo);
1930 if (err)
1931 goto done;
1933 if (verbosity >= 0)
1934 printf("Updated %s: %s\n", got_ref_get_name(symref),
1935 got_ref_get_symref_target(symref));
1938 done:
1939 if (symref_is_locked) {
1940 unlock_err = got_ref_unlock(symref);
1941 if (unlock_err && err == NULL)
1942 err = unlock_err;
1944 got_ref_close(symref);
1945 return err;
1948 __dead static void
1949 usage_fetch(void)
1951 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1952 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1953 "[remote-repository-name]\n",
1954 getprogname());
1955 exit(1);
1958 static const struct got_error *
1959 delete_missing_ref(struct got_reference *ref,
1960 int verbosity, struct got_repository *repo)
1962 const struct got_error *err = NULL;
1963 struct got_object_id *id = NULL;
1964 char *id_str = NULL;
1966 if (got_ref_is_symbolic(ref)) {
1967 err = got_ref_delete(ref, repo);
1968 if (err)
1969 return err;
1970 if (verbosity >= 0) {
1971 printf("Deleted reference %s: %s\n",
1972 got_ref_get_name(ref),
1973 got_ref_get_symref_target(ref));
1975 } else {
1976 err = got_ref_resolve(&id, repo, ref);
1977 if (err)
1978 return err;
1979 err = got_object_id_str(&id_str, id);
1980 if (err)
1981 goto done;
1983 err = got_ref_delete(ref, repo);
1984 if (err)
1985 goto done;
1986 if (verbosity >= 0) {
1987 printf("Deleted reference %s: %s\n",
1988 got_ref_get_name(ref), id_str);
1991 done:
1992 free(id);
1993 free(id_str);
1994 return NULL;
1997 static const struct got_error *
1998 delete_missing_refs(struct got_pathlist_head *their_refs,
1999 struct got_pathlist_head *their_symrefs,
2000 const struct got_remote_repo *remote,
2001 int verbosity, struct got_repository *repo)
2003 const struct got_error *err = NULL, *unlock_err;
2004 struct got_reflist_head my_refs;
2005 struct got_reflist_entry *re;
2006 struct got_pathlist_entry *pe;
2007 char *remote_namespace = NULL;
2008 char *local_refname = NULL;
2010 TAILQ_INIT(&my_refs);
2012 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2013 == -1)
2014 return got_error_from_errno("asprintf");
2016 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2017 if (err)
2018 goto done;
2020 TAILQ_FOREACH(re, &my_refs, entry) {
2021 const char *refname = got_ref_get_name(re->ref);
2023 if (!remote->mirror_references) {
2024 if (strncmp(refname, remote_namespace,
2025 strlen(remote_namespace)) == 0) {
2026 if (strcmp(refname + strlen(remote_namespace),
2027 GOT_REF_HEAD) == 0)
2028 continue;
2029 if (asprintf(&local_refname, "refs/heads/%s",
2030 refname + strlen(remote_namespace)) == -1) {
2031 err = got_error_from_errno("asprintf");
2032 goto done;
2034 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2035 continue;
2038 TAILQ_FOREACH(pe, their_refs, entry) {
2039 if (strcmp(local_refname, pe->path) == 0)
2040 break;
2042 if (pe != NULL)
2043 continue;
2045 TAILQ_FOREACH(pe, their_symrefs, entry) {
2046 if (strcmp(local_refname, pe->path) == 0)
2047 break;
2049 if (pe != NULL)
2050 continue;
2052 err = delete_missing_ref(re->ref, verbosity, repo);
2053 if (err)
2054 break;
2056 if (local_refname) {
2057 struct got_reference *ref;
2058 err = got_ref_open(&ref, repo, local_refname, 1);
2059 if (err) {
2060 if (err->code != GOT_ERR_NOT_REF)
2061 break;
2062 free(local_refname);
2063 local_refname = NULL;
2064 continue;
2066 err = delete_missing_ref(ref, verbosity, repo);
2067 if (err)
2068 break;
2069 unlock_err = got_ref_unlock(ref);
2070 got_ref_close(ref);
2071 if (unlock_err && err == NULL) {
2072 err = unlock_err;
2073 break;
2076 free(local_refname);
2077 local_refname = NULL;
2080 done:
2081 free(remote_namespace);
2082 free(local_refname);
2083 return err;
2086 static const struct got_error *
2087 update_wanted_ref(const char *refname, struct got_object_id *id,
2088 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2090 const struct got_error *err, *unlock_err;
2091 char *remote_refname;
2092 struct got_reference *ref;
2094 if (strncmp("refs/", refname, 5) == 0)
2095 refname += 5;
2097 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2098 remote_repo_name, refname) == -1)
2099 return got_error_from_errno("asprintf");
2101 err = got_ref_open(&ref, repo, remote_refname, 1);
2102 if (err) {
2103 if (err->code != GOT_ERR_NOT_REF)
2104 goto done;
2105 err = create_ref(remote_refname, id, verbosity, repo);
2106 } else {
2107 err = update_ref(ref, id, 0, verbosity, repo);
2108 unlock_err = got_ref_unlock(ref);
2109 if (unlock_err && err == NULL)
2110 err = unlock_err;
2111 got_ref_close(ref);
2113 done:
2114 free(remote_refname);
2115 return err;
2118 static const struct got_error *
2119 cmd_fetch(int argc, char *argv[])
2121 const struct got_error *error = NULL, *unlock_err;
2122 char *cwd = NULL, *repo_path = NULL;
2123 const char *remote_name;
2124 char *proto = NULL, *host = NULL, *port = NULL;
2125 char *repo_name = NULL, *server_path = NULL;
2126 const struct got_remote_repo *remotes, *remote = NULL;
2127 int nremotes;
2128 char *id_str = NULL;
2129 struct got_repository *repo = NULL;
2130 struct got_worktree *worktree = NULL;
2131 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2132 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2133 struct got_pathlist_entry *pe;
2134 struct got_object_id *pack_hash = NULL;
2135 int i, ch, fetchfd = -1, fetchstatus;
2136 pid_t fetchpid = -1;
2137 struct got_fetch_progress_arg fpa;
2138 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2139 int delete_refs = 0, replace_tags = 0;
2141 TAILQ_INIT(&refs);
2142 TAILQ_INIT(&symrefs);
2143 TAILQ_INIT(&wanted_branches);
2144 TAILQ_INIT(&wanted_refs);
2146 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
2147 switch (ch) {
2148 case 'a':
2149 fetch_all_branches = 1;
2150 break;
2151 case 'b':
2152 error = got_pathlist_append(&wanted_branches,
2153 optarg, NULL);
2154 if (error)
2155 return error;
2156 break;
2157 case 'd':
2158 delete_refs = 1;
2159 break;
2160 case 'l':
2161 list_refs_only = 1;
2162 break;
2163 case 'r':
2164 repo_path = realpath(optarg, NULL);
2165 if (repo_path == NULL)
2166 return got_error_from_errno2("realpath",
2167 optarg);
2168 got_path_strip_trailing_slashes(repo_path);
2169 break;
2170 case 't':
2171 replace_tags = 1;
2172 break;
2173 case 'v':
2174 if (verbosity < 0)
2175 verbosity = 0;
2176 else if (verbosity < 3)
2177 verbosity++;
2178 break;
2179 case 'q':
2180 verbosity = -1;
2181 break;
2182 case 'R':
2183 error = got_pathlist_append(&wanted_refs,
2184 optarg, NULL);
2185 if (error)
2186 return error;
2187 break;
2188 default:
2189 usage_fetch();
2190 break;
2193 argc -= optind;
2194 argv += optind;
2196 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2197 option_conflict('a', 'b');
2198 if (list_refs_only) {
2199 if (!TAILQ_EMPTY(&wanted_branches))
2200 option_conflict('l', 'b');
2201 if (fetch_all_branches)
2202 option_conflict('l', 'a');
2203 if (delete_refs)
2204 option_conflict('l', 'd');
2207 if (argc == 0)
2208 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2209 else if (argc == 1)
2210 remote_name = argv[0];
2211 else
2212 usage_fetch();
2214 cwd = getcwd(NULL, 0);
2215 if (cwd == NULL) {
2216 error = got_error_from_errno("getcwd");
2217 goto done;
2220 if (repo_path == NULL) {
2221 error = got_worktree_open(&worktree, cwd);
2222 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2223 goto done;
2224 else
2225 error = NULL;
2226 if (worktree) {
2227 repo_path =
2228 strdup(got_worktree_get_repo_path(worktree));
2229 if (repo_path == NULL)
2230 error = got_error_from_errno("strdup");
2231 if (error)
2232 goto done;
2233 } else {
2234 repo_path = strdup(cwd);
2235 if (repo_path == NULL) {
2236 error = got_error_from_errno("strdup");
2237 goto done;
2242 error = got_repo_open(&repo, repo_path, NULL);
2243 if (error)
2244 goto done;
2246 if (worktree) {
2247 worktree_conf = got_worktree_get_gotconfig(worktree);
2248 if (worktree_conf) {
2249 got_gotconfig_get_remotes(&nremotes, &remotes,
2250 worktree_conf);
2251 for (i = 0; i < nremotes; i++) {
2252 if (strcmp(remotes[i].name, remote_name) == 0) {
2253 remote = &remotes[i];
2254 break;
2259 if (remote == NULL) {
2260 repo_conf = got_repo_get_gotconfig(repo);
2261 if (repo_conf) {
2262 got_gotconfig_get_remotes(&nremotes, &remotes,
2263 repo_conf);
2264 for (i = 0; i < nremotes; i++) {
2265 if (strcmp(remotes[i].name, remote_name) == 0) {
2266 remote = &remotes[i];
2267 break;
2272 if (remote == NULL) {
2273 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2274 for (i = 0; i < nremotes; i++) {
2275 if (strcmp(remotes[i].name, remote_name) == 0) {
2276 remote = &remotes[i];
2277 break;
2281 if (remote == NULL) {
2282 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2283 goto done;
2286 if (TAILQ_EMPTY(&wanted_branches)) {
2287 if (!fetch_all_branches)
2288 fetch_all_branches = remote->fetch_all_branches;
2289 for (i = 0; i < remote->nbranches; i++) {
2290 got_pathlist_append(&wanted_branches,
2291 remote->branches[i], NULL);
2294 if (TAILQ_EMPTY(&wanted_refs)) {
2295 for (i = 0; i < remote->nrefs; i++) {
2296 got_pathlist_append(&wanted_refs,
2297 remote->refs[i], NULL);
2301 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2302 &repo_name, remote->url);
2303 if (error)
2304 goto done;
2306 if (strcmp(proto, "git") == 0) {
2307 #ifndef PROFILE
2308 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2309 "sendfd dns inet unveil", NULL) == -1)
2310 err(1, "pledge");
2311 #endif
2312 } else if (strcmp(proto, "git+ssh") == 0 ||
2313 strcmp(proto, "ssh") == 0) {
2314 #ifndef PROFILE
2315 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2316 "sendfd unveil", NULL) == -1)
2317 err(1, "pledge");
2318 #endif
2319 } else if (strcmp(proto, "http") == 0 ||
2320 strcmp(proto, "git+http") == 0) {
2321 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2322 goto done;
2323 } else {
2324 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2325 goto done;
2328 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2329 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2330 error = got_error_from_errno2("unveil",
2331 GOT_FETCH_PATH_SSH);
2332 goto done;
2335 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2336 if (error)
2337 goto done;
2339 if (verbosity >= 0)
2340 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2341 port ? ":" : "", port ? port : "");
2343 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2344 server_path, verbosity);
2345 if (error)
2346 goto done;
2348 fpa.last_scaled_size[0] = '\0';
2349 fpa.last_p_indexed = -1;
2350 fpa.last_p_resolved = -1;
2351 fpa.verbosity = verbosity;
2352 fpa.repo = repo;
2353 fpa.create_configs = 0;
2354 fpa.configs_created = 0;
2355 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2356 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2357 remote->mirror_references, fetch_all_branches, &wanted_branches,
2358 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2359 fetch_progress, &fpa);
2360 if (error)
2361 goto done;
2363 if (list_refs_only) {
2364 error = list_remote_refs(&symrefs, &refs);
2365 goto done;
2368 if (pack_hash == NULL) {
2369 if (verbosity >= 0)
2370 printf("Already up-to-date\n");
2371 } else if (verbosity >= 0) {
2372 error = got_object_id_str(&id_str, pack_hash);
2373 if (error)
2374 goto done;
2375 printf("\nFetched %s.pack\n", id_str);
2376 free(id_str);
2377 id_str = NULL;
2380 /* Update references provided with the pack file. */
2381 TAILQ_FOREACH(pe, &refs, entry) {
2382 const char *refname = pe->path;
2383 struct got_object_id *id = pe->data;
2384 struct got_reference *ref;
2385 char *remote_refname;
2387 if (is_wanted_ref(&wanted_refs, refname) &&
2388 !remote->mirror_references) {
2389 error = update_wanted_ref(refname, id,
2390 remote->name, verbosity, repo);
2391 if (error)
2392 goto done;
2393 continue;
2396 if (remote->mirror_references ||
2397 strncmp("refs/tags/", refname, 10) == 0) {
2398 error = got_ref_open(&ref, repo, refname, 1);
2399 if (error) {
2400 if (error->code != GOT_ERR_NOT_REF)
2401 goto done;
2402 error = create_ref(refname, id, verbosity,
2403 repo);
2404 if (error)
2405 goto done;
2406 } else {
2407 error = update_ref(ref, id, replace_tags,
2408 verbosity, repo);
2409 unlock_err = got_ref_unlock(ref);
2410 if (unlock_err && error == NULL)
2411 error = unlock_err;
2412 got_ref_close(ref);
2413 if (error)
2414 goto done;
2416 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2417 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2418 remote_name, refname + 11) == -1) {
2419 error = got_error_from_errno("asprintf");
2420 goto done;
2423 error = got_ref_open(&ref, repo, remote_refname, 1);
2424 if (error) {
2425 if (error->code != GOT_ERR_NOT_REF)
2426 goto done;
2427 error = create_ref(remote_refname, id,
2428 verbosity, repo);
2429 if (error)
2430 goto done;
2431 } else {
2432 error = update_ref(ref, id, replace_tags,
2433 verbosity, repo);
2434 unlock_err = got_ref_unlock(ref);
2435 if (unlock_err && error == NULL)
2436 error = unlock_err;
2437 got_ref_close(ref);
2438 if (error)
2439 goto done;
2442 /* Also create a local branch if none exists yet. */
2443 error = got_ref_open(&ref, repo, refname, 1);
2444 if (error) {
2445 if (error->code != GOT_ERR_NOT_REF)
2446 goto done;
2447 error = create_ref(refname, id, verbosity,
2448 repo);
2449 if (error)
2450 goto done;
2451 } else {
2452 unlock_err = got_ref_unlock(ref);
2453 if (unlock_err && error == NULL)
2454 error = unlock_err;
2455 got_ref_close(ref);
2459 if (delete_refs) {
2460 error = delete_missing_refs(&refs, &symrefs, remote,
2461 verbosity, repo);
2462 if (error)
2463 goto done;
2466 if (!remote->mirror_references) {
2467 /* Update remote HEAD reference if the server provided one. */
2468 TAILQ_FOREACH(pe, &symrefs, entry) {
2469 struct got_reference *target_ref;
2470 const char *refname = pe->path;
2471 const char *target = pe->data;
2472 char *remote_refname = NULL, *remote_target = NULL;
2474 if (strcmp(refname, GOT_REF_HEAD) != 0)
2475 continue;
2477 if (strncmp("refs/heads/", target, 11) != 0)
2478 continue;
2480 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2481 remote->name, refname) == -1) {
2482 error = got_error_from_errno("asprintf");
2483 goto done;
2485 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2486 remote->name, target + 11) == -1) {
2487 error = got_error_from_errno("asprintf");
2488 free(remote_refname);
2489 goto done;
2492 error = got_ref_open(&target_ref, repo, remote_target,
2493 0);
2494 if (error) {
2495 free(remote_refname);
2496 free(remote_target);
2497 if (error->code == GOT_ERR_NOT_REF) {
2498 error = NULL;
2499 continue;
2501 goto done;
2503 error = update_symref(remote_refname, target_ref,
2504 verbosity, repo);
2505 free(remote_refname);
2506 free(remote_target);
2507 got_ref_close(target_ref);
2508 if (error)
2509 goto done;
2512 done:
2513 if (fetchpid > 0) {
2514 if (kill(fetchpid, SIGTERM) == -1)
2515 error = got_error_from_errno("kill");
2516 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2517 error = got_error_from_errno("waitpid");
2519 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2520 error = got_error_from_errno("close");
2521 if (repo) {
2522 const struct got_error *close_err = got_repo_close(repo);
2523 if (error == NULL)
2524 error = close_err;
2526 if (worktree)
2527 got_worktree_close(worktree);
2528 TAILQ_FOREACH(pe, &refs, entry) {
2529 free((void *)pe->path);
2530 free(pe->data);
2532 got_pathlist_free(&refs);
2533 TAILQ_FOREACH(pe, &symrefs, entry) {
2534 free((void *)pe->path);
2535 free(pe->data);
2537 got_pathlist_free(&symrefs);
2538 got_pathlist_free(&wanted_branches);
2539 got_pathlist_free(&wanted_refs);
2540 free(id_str);
2541 free(cwd);
2542 free(repo_path);
2543 free(pack_hash);
2544 free(proto);
2545 free(host);
2546 free(port);
2547 free(server_path);
2548 free(repo_name);
2549 return error;
2553 __dead static void
2554 usage_checkout(void)
2556 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2557 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2558 exit(1);
2561 static void
2562 show_worktree_base_ref_warning(void)
2564 fprintf(stderr, "%s: warning: could not create a reference "
2565 "to the work tree's base commit; the commit could be "
2566 "garbage-collected by Git; making the repository "
2567 "writable and running 'got update' will prevent this\n",
2568 getprogname());
2571 struct got_checkout_progress_arg {
2572 const char *worktree_path;
2573 int had_base_commit_ref_error;
2576 static const struct got_error *
2577 checkout_progress(void *arg, unsigned char status, const char *path)
2579 struct got_checkout_progress_arg *a = arg;
2581 /* Base commit bump happens silently. */
2582 if (status == GOT_STATUS_BUMP_BASE)
2583 return NULL;
2585 if (status == GOT_STATUS_BASE_REF_ERR) {
2586 a->had_base_commit_ref_error = 1;
2587 return NULL;
2590 while (path[0] == '/')
2591 path++;
2593 printf("%c %s/%s\n", status, a->worktree_path, path);
2594 return NULL;
2597 static const struct got_error *
2598 check_cancelled(void *arg)
2600 if (sigint_received || sigpipe_received)
2601 return got_error(GOT_ERR_CANCELLED);
2602 return NULL;
2605 static const struct got_error *
2606 check_linear_ancestry(struct got_object_id *commit_id,
2607 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2608 struct got_repository *repo)
2610 const struct got_error *err = NULL;
2611 struct got_object_id *yca_id;
2613 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2614 commit_id, base_commit_id, repo, check_cancelled, NULL);
2615 if (err)
2616 return err;
2618 if (yca_id == NULL)
2619 return got_error(GOT_ERR_ANCESTRY);
2622 * Require a straight line of history between the target commit
2623 * and the work tree's base commit.
2625 * Non-linear situations such as this require a rebase:
2627 * (commit) D F (base_commit)
2628 * \ /
2629 * C E
2630 * \ /
2631 * B (yca)
2632 * |
2633 * A
2635 * 'got update' only handles linear cases:
2636 * Update forwards in time: A (base/yca) - B - C - D (commit)
2637 * Update backwards in time: D (base) - C - B - A (commit/yca)
2639 if (allow_forwards_in_time_only) {
2640 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2641 return got_error(GOT_ERR_ANCESTRY);
2642 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2643 got_object_id_cmp(base_commit_id, yca_id) != 0)
2644 return got_error(GOT_ERR_ANCESTRY);
2646 free(yca_id);
2647 return NULL;
2650 static const struct got_error *
2651 check_same_branch(struct got_object_id *commit_id,
2652 struct got_reference *head_ref, struct got_object_id *yca_id,
2653 struct got_repository *repo)
2655 const struct got_error *err = NULL;
2656 struct got_commit_graph *graph = NULL;
2657 struct got_object_id *head_commit_id = NULL;
2658 int is_same_branch = 0;
2660 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2661 if (err)
2662 goto done;
2664 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2665 is_same_branch = 1;
2666 goto done;
2668 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2669 is_same_branch = 1;
2670 goto done;
2673 err = got_commit_graph_open(&graph, "/", 1);
2674 if (err)
2675 goto done;
2677 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2678 check_cancelled, NULL);
2679 if (err)
2680 goto done;
2682 for (;;) {
2683 struct got_object_id *id;
2684 err = got_commit_graph_iter_next(&id, graph, repo,
2685 check_cancelled, NULL);
2686 if (err) {
2687 if (err->code == GOT_ERR_ITER_COMPLETED)
2688 err = NULL;
2689 break;
2692 if (id) {
2693 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2694 break;
2695 if (got_object_id_cmp(id, commit_id) == 0) {
2696 is_same_branch = 1;
2697 break;
2701 done:
2702 if (graph)
2703 got_commit_graph_close(graph);
2704 free(head_commit_id);
2705 if (!err && !is_same_branch)
2706 err = got_error(GOT_ERR_ANCESTRY);
2707 return err;
2710 static const struct got_error *
2711 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2713 static char msg[512];
2714 const char *branch_name;
2716 if (got_ref_is_symbolic(ref))
2717 branch_name = got_ref_get_symref_target(ref);
2718 else
2719 branch_name = got_ref_get_name(ref);
2721 if (strncmp("refs/heads/", branch_name, 11) == 0)
2722 branch_name += 11;
2724 snprintf(msg, sizeof(msg),
2725 "target commit is not contained in branch '%s'; "
2726 "the branch to use must be specified with -b; "
2727 "if necessary a new branch can be created for "
2728 "this commit with 'got branch -c %s BRANCH_NAME'",
2729 branch_name, commit_id_str);
2731 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2734 static const struct got_error *
2735 cmd_checkout(int argc, char *argv[])
2737 const struct got_error *error = NULL;
2738 struct got_repository *repo = NULL;
2739 struct got_reference *head_ref = NULL;
2740 struct got_worktree *worktree = NULL;
2741 char *repo_path = NULL;
2742 char *worktree_path = NULL;
2743 const char *path_prefix = "";
2744 const char *branch_name = GOT_REF_HEAD;
2745 char *commit_id_str = NULL;
2746 char *cwd = NULL;
2747 int ch, same_path_prefix, allow_nonempty = 0;
2748 struct got_pathlist_head paths;
2749 struct got_checkout_progress_arg cpa;
2751 TAILQ_INIT(&paths);
2753 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2754 switch (ch) {
2755 case 'b':
2756 branch_name = optarg;
2757 break;
2758 case 'c':
2759 commit_id_str = strdup(optarg);
2760 if (commit_id_str == NULL)
2761 return got_error_from_errno("strdup");
2762 break;
2763 case 'E':
2764 allow_nonempty = 1;
2765 break;
2766 case 'p':
2767 path_prefix = optarg;
2768 break;
2769 default:
2770 usage_checkout();
2771 /* NOTREACHED */
2775 argc -= optind;
2776 argv += optind;
2778 #ifndef PROFILE
2779 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2780 "unveil", NULL) == -1)
2781 err(1, "pledge");
2782 #endif
2783 if (argc == 1) {
2784 char *base, *dotgit;
2785 const char *path;
2786 repo_path = realpath(argv[0], NULL);
2787 if (repo_path == NULL)
2788 return got_error_from_errno2("realpath", argv[0]);
2789 cwd = getcwd(NULL, 0);
2790 if (cwd == NULL) {
2791 error = got_error_from_errno("getcwd");
2792 goto done;
2794 if (path_prefix[0])
2795 path = path_prefix;
2796 else
2797 path = repo_path;
2798 error = got_path_basename(&base, path);
2799 if (error)
2800 goto done;
2801 dotgit = strstr(base, ".git");
2802 if (dotgit)
2803 *dotgit = '\0';
2804 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2805 error = got_error_from_errno("asprintf");
2806 free(base);
2807 goto done;
2809 free(base);
2810 } else if (argc == 2) {
2811 repo_path = realpath(argv[0], NULL);
2812 if (repo_path == NULL) {
2813 error = got_error_from_errno2("realpath", argv[0]);
2814 goto done;
2816 worktree_path = realpath(argv[1], NULL);
2817 if (worktree_path == NULL) {
2818 if (errno != ENOENT) {
2819 error = got_error_from_errno2("realpath",
2820 argv[1]);
2821 goto done;
2823 worktree_path = strdup(argv[1]);
2824 if (worktree_path == NULL) {
2825 error = got_error_from_errno("strdup");
2826 goto done;
2829 } else
2830 usage_checkout();
2832 got_path_strip_trailing_slashes(repo_path);
2833 got_path_strip_trailing_slashes(worktree_path);
2835 error = got_repo_open(&repo, repo_path, NULL);
2836 if (error != NULL)
2837 goto done;
2839 /* Pre-create work tree path for unveil(2) */
2840 error = got_path_mkdir(worktree_path);
2841 if (error) {
2842 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2843 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2844 goto done;
2845 if (!allow_nonempty &&
2846 !got_path_dir_is_empty(worktree_path)) {
2847 error = got_error_path(worktree_path,
2848 GOT_ERR_DIR_NOT_EMPTY);
2849 goto done;
2853 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2854 if (error)
2855 goto done;
2857 error = got_ref_open(&head_ref, repo, branch_name, 0);
2858 if (error != NULL)
2859 goto done;
2861 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2862 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2863 goto done;
2865 error = got_worktree_open(&worktree, worktree_path);
2866 if (error != NULL)
2867 goto done;
2869 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2870 path_prefix);
2871 if (error != NULL)
2872 goto done;
2873 if (!same_path_prefix) {
2874 error = got_error(GOT_ERR_PATH_PREFIX);
2875 goto done;
2878 if (commit_id_str) {
2879 struct got_object_id *commit_id;
2880 struct got_reflist_head refs;
2881 TAILQ_INIT(&refs);
2882 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2883 NULL);
2884 if (error)
2885 goto done;
2886 error = got_repo_match_object_id(&commit_id, NULL,
2887 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2888 got_ref_list_free(&refs);
2889 if (error)
2890 goto done;
2891 error = check_linear_ancestry(commit_id,
2892 got_worktree_get_base_commit_id(worktree), 0, repo);
2893 if (error != NULL) {
2894 free(commit_id);
2895 if (error->code == GOT_ERR_ANCESTRY) {
2896 error = checkout_ancestry_error(
2897 head_ref, commit_id_str);
2899 goto done;
2901 error = check_same_branch(commit_id, head_ref, NULL, repo);
2902 if (error) {
2903 if (error->code == GOT_ERR_ANCESTRY) {
2904 error = checkout_ancestry_error(
2905 head_ref, commit_id_str);
2907 goto done;
2909 error = got_worktree_set_base_commit_id(worktree, repo,
2910 commit_id);
2911 free(commit_id);
2912 if (error)
2913 goto done;
2916 error = got_pathlist_append(&paths, "", NULL);
2917 if (error)
2918 goto done;
2919 cpa.worktree_path = worktree_path;
2920 cpa.had_base_commit_ref_error = 0;
2921 error = got_worktree_checkout_files(worktree, &paths, repo,
2922 checkout_progress, &cpa, check_cancelled, NULL);
2923 if (error != NULL)
2924 goto done;
2926 printf("Now shut up and hack\n");
2927 if (cpa.had_base_commit_ref_error)
2928 show_worktree_base_ref_warning();
2929 done:
2930 got_pathlist_free(&paths);
2931 free(commit_id_str);
2932 free(repo_path);
2933 free(worktree_path);
2934 free(cwd);
2935 return error;
2938 struct got_update_progress_arg {
2939 int did_something;
2940 int conflicts;
2941 int obstructed;
2942 int not_updated;
2945 void
2946 print_update_progress_stats(struct got_update_progress_arg *upa)
2948 if (!upa->did_something)
2949 return;
2951 if (upa->conflicts > 0)
2952 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2953 if (upa->obstructed > 0)
2954 printf("File paths obstructed by a non-regular file: %d\n",
2955 upa->obstructed);
2956 if (upa->not_updated > 0)
2957 printf("Files not updated because of existing merge "
2958 "conflicts: %d\n", upa->not_updated);
2961 __dead static void
2962 usage_update(void)
2964 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2965 getprogname());
2966 exit(1);
2969 static const struct got_error *
2970 update_progress(void *arg, unsigned char status, const char *path)
2972 struct got_update_progress_arg *upa = arg;
2974 if (status == GOT_STATUS_EXISTS ||
2975 status == GOT_STATUS_BASE_REF_ERR)
2976 return NULL;
2978 upa->did_something = 1;
2980 /* Base commit bump happens silently. */
2981 if (status == GOT_STATUS_BUMP_BASE)
2982 return NULL;
2984 if (status == GOT_STATUS_CONFLICT)
2985 upa->conflicts++;
2986 if (status == GOT_STATUS_OBSTRUCTED)
2987 upa->obstructed++;
2988 if (status == GOT_STATUS_CANNOT_UPDATE)
2989 upa->not_updated++;
2991 while (path[0] == '/')
2992 path++;
2993 printf("%c %s\n", status, path);
2994 return NULL;
2997 static const struct got_error *
2998 switch_head_ref(struct got_reference *head_ref,
2999 struct got_object_id *commit_id, struct got_worktree *worktree,
3000 struct got_repository *repo)
3002 const struct got_error *err = NULL;
3003 char *base_id_str;
3004 int ref_has_moved = 0;
3006 /* Trivial case: switching between two different references. */
3007 if (strcmp(got_ref_get_name(head_ref),
3008 got_worktree_get_head_ref_name(worktree)) != 0) {
3009 printf("Switching work tree from %s to %s\n",
3010 got_worktree_get_head_ref_name(worktree),
3011 got_ref_get_name(head_ref));
3012 return got_worktree_set_head_ref(worktree, head_ref);
3015 err = check_linear_ancestry(commit_id,
3016 got_worktree_get_base_commit_id(worktree), 0, repo);
3017 if (err) {
3018 if (err->code != GOT_ERR_ANCESTRY)
3019 return err;
3020 ref_has_moved = 1;
3022 if (!ref_has_moved)
3023 return NULL;
3025 /* Switching to a rebased branch with the same reference name. */
3026 err = got_object_id_str(&base_id_str,
3027 got_worktree_get_base_commit_id(worktree));
3028 if (err)
3029 return err;
3030 printf("Reference %s now points at a different branch\n",
3031 got_worktree_get_head_ref_name(worktree));
3032 printf("Switching work tree from %s to %s\n", base_id_str,
3033 got_worktree_get_head_ref_name(worktree));
3034 return NULL;
3037 static const struct got_error *
3038 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3040 const struct got_error *err;
3041 int in_progress;
3043 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3044 if (err)
3045 return err;
3046 if (in_progress)
3047 return got_error(GOT_ERR_REBASING);
3049 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3050 if (err)
3051 return err;
3052 if (in_progress)
3053 return got_error(GOT_ERR_HISTEDIT_BUSY);
3055 return NULL;
3058 static const struct got_error *
3059 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3060 char *argv[], struct got_worktree *worktree)
3062 const struct got_error *err = NULL;
3063 char *path;
3064 int i;
3066 if (argc == 0) {
3067 path = strdup("");
3068 if (path == NULL)
3069 return got_error_from_errno("strdup");
3070 return got_pathlist_append(paths, path, NULL);
3073 for (i = 0; i < argc; i++) {
3074 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3075 if (err)
3076 break;
3077 err = got_pathlist_append(paths, path, NULL);
3078 if (err) {
3079 free(path);
3080 break;
3084 return err;
3087 static const struct got_error *
3088 wrap_not_worktree_error(const struct got_error *orig_err,
3089 const char *cmdname, const char *path)
3091 const struct got_error *err;
3092 struct got_repository *repo;
3093 static char msg[512];
3095 err = got_repo_open(&repo, path, NULL);
3096 if (err)
3097 return orig_err;
3099 snprintf(msg, sizeof(msg),
3100 "'got %s' needs a work tree in addition to a git repository\n"
3101 "Work trees can be checked out from this Git repository with "
3102 "'got checkout'.\n"
3103 "The got(1) manual page contains more information.", cmdname);
3104 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3105 got_repo_close(repo);
3106 return err;
3109 static const struct got_error *
3110 cmd_update(int argc, char *argv[])
3112 const struct got_error *error = NULL;
3113 struct got_repository *repo = NULL;
3114 struct got_worktree *worktree = NULL;
3115 char *worktree_path = NULL;
3116 struct got_object_id *commit_id = NULL;
3117 char *commit_id_str = NULL;
3118 const char *branch_name = NULL;
3119 struct got_reference *head_ref = NULL;
3120 struct got_pathlist_head paths;
3121 struct got_pathlist_entry *pe;
3122 int ch;
3123 struct got_update_progress_arg upa;
3125 TAILQ_INIT(&paths);
3127 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3128 switch (ch) {
3129 case 'b':
3130 branch_name = optarg;
3131 break;
3132 case 'c':
3133 commit_id_str = strdup(optarg);
3134 if (commit_id_str == NULL)
3135 return got_error_from_errno("strdup");
3136 break;
3137 default:
3138 usage_update();
3139 /* NOTREACHED */
3143 argc -= optind;
3144 argv += optind;
3146 #ifndef PROFILE
3147 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3148 "unveil", NULL) == -1)
3149 err(1, "pledge");
3150 #endif
3151 worktree_path = getcwd(NULL, 0);
3152 if (worktree_path == NULL) {
3153 error = got_error_from_errno("getcwd");
3154 goto done;
3156 error = got_worktree_open(&worktree, worktree_path);
3157 if (error) {
3158 if (error->code == GOT_ERR_NOT_WORKTREE)
3159 error = wrap_not_worktree_error(error, "update",
3160 worktree_path);
3161 goto done;
3164 error = check_rebase_or_histedit_in_progress(worktree);
3165 if (error)
3166 goto done;
3168 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3169 NULL);
3170 if (error != NULL)
3171 goto done;
3173 error = apply_unveil(got_repo_get_path(repo), 0,
3174 got_worktree_get_root_path(worktree));
3175 if (error)
3176 goto done;
3178 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3179 if (error)
3180 goto done;
3182 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3183 got_worktree_get_head_ref_name(worktree), 0);
3184 if (error != NULL)
3185 goto done;
3186 if (commit_id_str == NULL) {
3187 error = got_ref_resolve(&commit_id, repo, head_ref);
3188 if (error != NULL)
3189 goto done;
3190 error = got_object_id_str(&commit_id_str, commit_id);
3191 if (error != NULL)
3192 goto done;
3193 } else {
3194 struct got_reflist_head refs;
3195 TAILQ_INIT(&refs);
3196 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3197 NULL);
3198 if (error)
3199 goto done;
3200 error = got_repo_match_object_id(&commit_id, NULL,
3201 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3202 got_ref_list_free(&refs);
3203 free(commit_id_str);
3204 commit_id_str = NULL;
3205 if (error)
3206 goto done;
3207 error = got_object_id_str(&commit_id_str, commit_id);
3208 if (error)
3209 goto done;
3212 if (branch_name) {
3213 struct got_object_id *head_commit_id;
3214 TAILQ_FOREACH(pe, &paths, entry) {
3215 if (pe->path_len == 0)
3216 continue;
3217 error = got_error_msg(GOT_ERR_BAD_PATH,
3218 "switching between branches requires that "
3219 "the entire work tree gets updated");
3220 goto done;
3222 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3223 if (error)
3224 goto done;
3225 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3226 repo);
3227 free(head_commit_id);
3228 if (error != NULL)
3229 goto done;
3230 error = check_same_branch(commit_id, head_ref, NULL, repo);
3231 if (error)
3232 goto done;
3233 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3234 if (error)
3235 goto done;
3236 } else {
3237 error = check_linear_ancestry(commit_id,
3238 got_worktree_get_base_commit_id(worktree), 0, repo);
3239 if (error != NULL) {
3240 if (error->code == GOT_ERR_ANCESTRY)
3241 error = got_error(GOT_ERR_BRANCH_MOVED);
3242 goto done;
3244 error = check_same_branch(commit_id, head_ref, NULL, repo);
3245 if (error)
3246 goto done;
3249 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3250 commit_id) != 0) {
3251 error = got_worktree_set_base_commit_id(worktree, repo,
3252 commit_id);
3253 if (error)
3254 goto done;
3257 memset(&upa, 0, sizeof(upa));
3258 error = got_worktree_checkout_files(worktree, &paths, repo,
3259 update_progress, &upa, check_cancelled, NULL);
3260 if (error != NULL)
3261 goto done;
3263 if (upa.did_something)
3264 printf("Updated to commit %s\n", commit_id_str);
3265 else
3266 printf("Already up-to-date\n");
3267 print_update_progress_stats(&upa);
3268 done:
3269 free(worktree_path);
3270 TAILQ_FOREACH(pe, &paths, entry)
3271 free((char *)pe->path);
3272 got_pathlist_free(&paths);
3273 free(commit_id);
3274 free(commit_id_str);
3275 return error;
3278 static const struct got_error *
3279 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3280 const char *path, int diff_context, int ignore_whitespace,
3281 int force_text_diff, struct got_repository *repo)
3283 const struct got_error *err = NULL;
3284 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3286 if (blob_id1) {
3287 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3288 if (err)
3289 goto done;
3292 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3293 if (err)
3294 goto done;
3296 while (path[0] == '/')
3297 path++;
3298 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3299 diff_context, ignore_whitespace, force_text_diff, stdout);
3300 done:
3301 if (blob1)
3302 got_object_blob_close(blob1);
3303 got_object_blob_close(blob2);
3304 return err;
3307 static const struct got_error *
3308 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3309 const char *path, int diff_context, int ignore_whitespace,
3310 int force_text_diff, struct got_repository *repo)
3312 const struct got_error *err = NULL;
3313 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3314 struct got_diff_blob_output_unidiff_arg arg;
3316 if (tree_id1) {
3317 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3318 if (err)
3319 goto done;
3322 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3323 if (err)
3324 goto done;
3326 arg.diff_context = diff_context;
3327 arg.ignore_whitespace = ignore_whitespace;
3328 arg.force_text_diff = force_text_diff;
3329 arg.outfile = stdout;
3330 arg.line_offsets = NULL;
3331 arg.nlines = 0;
3332 while (path[0] == '/')
3333 path++;
3334 err = got_diff_tree(tree1, tree2, path, path, repo,
3335 got_diff_blob_output_unidiff, &arg, 1);
3336 done:
3337 if (tree1)
3338 got_object_tree_close(tree1);
3339 if (tree2)
3340 got_object_tree_close(tree2);
3341 return err;
3344 static const struct got_error *
3345 get_changed_paths(struct got_pathlist_head *paths,
3346 struct got_commit_object *commit, struct got_repository *repo)
3348 const struct got_error *err = NULL;
3349 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3350 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3351 struct got_object_qid *qid;
3353 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3354 if (qid != NULL) {
3355 struct got_commit_object *pcommit;
3356 err = got_object_open_as_commit(&pcommit, repo,
3357 qid->id);
3358 if (err)
3359 return err;
3361 tree_id1 = got_object_commit_get_tree_id(pcommit);
3362 got_object_commit_close(pcommit);
3366 if (tree_id1) {
3367 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3368 if (err)
3369 goto done;
3372 tree_id2 = got_object_commit_get_tree_id(commit);
3373 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3374 if (err)
3375 goto done;
3377 err = got_diff_tree(tree1, tree2, "", "", repo,
3378 got_diff_tree_collect_changed_paths, paths, 0);
3379 done:
3380 if (tree1)
3381 got_object_tree_close(tree1);
3382 if (tree2)
3383 got_object_tree_close(tree2);
3384 return err;
3387 static const struct got_error *
3388 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3389 const char *path, int diff_context, struct got_repository *repo)
3391 const struct got_error *err = NULL;
3392 struct got_commit_object *pcommit = NULL;
3393 char *id_str1 = NULL, *id_str2 = NULL;
3394 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3395 struct got_object_qid *qid;
3397 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3398 if (qid != NULL) {
3399 err = got_object_open_as_commit(&pcommit, repo,
3400 qid->id);
3401 if (err)
3402 return err;
3405 if (path && path[0] != '\0') {
3406 int obj_type;
3407 err = got_object_id_by_path(&obj_id2, repo, id, path);
3408 if (err)
3409 goto done;
3410 err = got_object_id_str(&id_str2, obj_id2);
3411 if (err) {
3412 free(obj_id2);
3413 goto done;
3415 if (pcommit) {
3416 err = got_object_id_by_path(&obj_id1, repo,
3417 qid->id, path);
3418 if (err) {
3419 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3420 free(obj_id2);
3421 goto done;
3423 } else {
3424 err = got_object_id_str(&id_str1, obj_id1);
3425 if (err) {
3426 free(obj_id2);
3427 goto done;
3431 err = got_object_get_type(&obj_type, repo, obj_id2);
3432 if (err) {
3433 free(obj_id2);
3434 goto done;
3436 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3437 switch (obj_type) {
3438 case GOT_OBJ_TYPE_BLOB:
3439 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3440 0, 0, repo);
3441 break;
3442 case GOT_OBJ_TYPE_TREE:
3443 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3444 0, 0, repo);
3445 break;
3446 default:
3447 err = got_error(GOT_ERR_OBJ_TYPE);
3448 break;
3450 free(obj_id1);
3451 free(obj_id2);
3452 } else {
3453 obj_id2 = got_object_commit_get_tree_id(commit);
3454 err = got_object_id_str(&id_str2, obj_id2);
3455 if (err)
3456 goto done;
3457 if (pcommit) {
3458 obj_id1 = got_object_commit_get_tree_id(pcommit);
3459 err = got_object_id_str(&id_str1, obj_id1);
3460 if (err)
3461 goto done;
3463 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3464 id_str2);
3465 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3466 repo);
3468 done:
3469 free(id_str1);
3470 free(id_str2);
3471 if (pcommit)
3472 got_object_commit_close(pcommit);
3473 return err;
3476 static char *
3477 get_datestr(time_t *time, char *datebuf)
3479 struct tm mytm, *tm;
3480 char *p, *s;
3482 tm = gmtime_r(time, &mytm);
3483 if (tm == NULL)
3484 return NULL;
3485 s = asctime_r(tm, datebuf);
3486 if (s == NULL)
3487 return NULL;
3488 p = strchr(s, '\n');
3489 if (p)
3490 *p = '\0';
3491 return s;
3494 static const struct got_error *
3495 match_logmsg(int *have_match, struct got_object_id *id,
3496 struct got_commit_object *commit, regex_t *regex)
3498 const struct got_error *err = NULL;
3499 regmatch_t regmatch;
3500 char *id_str = NULL, *logmsg = NULL;
3502 *have_match = 0;
3504 err = got_object_id_str(&id_str, id);
3505 if (err)
3506 return err;
3508 err = got_object_commit_get_logmsg(&logmsg, commit);
3509 if (err)
3510 goto done;
3512 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3513 *have_match = 1;
3514 done:
3515 free(id_str);
3516 free(logmsg);
3517 return err;
3520 static void
3521 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3522 regex_t *regex)
3524 regmatch_t regmatch;
3525 struct got_pathlist_entry *pe;
3527 *have_match = 0;
3529 TAILQ_FOREACH(pe, changed_paths, entry) {
3530 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3531 *have_match = 1;
3532 break;
3537 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3539 static const struct got_error*
3540 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3541 struct got_object_id *id, struct got_repository *repo)
3543 static const struct got_error *err = NULL;
3544 struct got_reflist_entry *re;
3545 char *s;
3546 const char *name;
3548 *refs_str = NULL;
3550 TAILQ_FOREACH(re, refs, entry) {
3551 struct got_tag_object *tag = NULL;
3552 struct got_object_id *ref_id;
3553 int cmp;
3555 name = got_ref_get_name(re->ref);
3556 if (strcmp(name, GOT_REF_HEAD) == 0)
3557 continue;
3558 if (strncmp(name, "refs/", 5) == 0)
3559 name += 5;
3560 if (strncmp(name, "got/", 4) == 0)
3561 continue;
3562 if (strncmp(name, "heads/", 6) == 0)
3563 name += 6;
3564 if (strncmp(name, "remotes/", 8) == 0) {
3565 name += 8;
3566 s = strstr(name, "/" GOT_REF_HEAD);
3567 if (s != NULL && s[strlen(s)] == '\0')
3568 continue;
3570 err = got_ref_resolve(&ref_id, repo, re->ref);
3571 if (err)
3572 break;
3573 if (strncmp(name, "tags/", 5) == 0) {
3574 err = got_object_open_as_tag(&tag, repo, ref_id);
3575 if (err) {
3576 if (err->code != GOT_ERR_OBJ_TYPE) {
3577 free(ref_id);
3578 break;
3580 /* Ref points at something other than a tag. */
3581 err = NULL;
3582 tag = NULL;
3585 cmp = got_object_id_cmp(tag ?
3586 got_object_tag_get_object_id(tag) : ref_id, id);
3587 free(ref_id);
3588 if (tag)
3589 got_object_tag_close(tag);
3590 if (cmp != 0)
3591 continue;
3592 s = *refs_str;
3593 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3594 s ? ", " : "", name) == -1) {
3595 err = got_error_from_errno("asprintf");
3596 free(s);
3597 *refs_str = NULL;
3598 break;
3600 free(s);
3603 return err;
3606 static const struct got_error *
3607 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3608 struct got_repository *repo, const char *path,
3609 struct got_pathlist_head *changed_paths, int show_patch,
3610 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3611 const char *custom_refs_str)
3613 const struct got_error *err = NULL;
3614 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3615 char datebuf[26];
3616 time_t committer_time;
3617 const char *author, *committer;
3618 char *refs_str = NULL;
3620 err = got_object_id_str(&id_str, id);
3621 if (err)
3622 return err;
3624 if (custom_refs_str == NULL) {
3625 struct got_reflist_head *refs;
3626 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3627 if (refs) {
3628 err = build_refs_str(&refs_str, refs, id, repo);
3629 if (err)
3630 goto done;
3634 printf(GOT_COMMIT_SEP_STR);
3635 if (custom_refs_str)
3636 printf("commit %s (%s)\n", id_str, custom_refs_str);
3637 else
3638 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3639 refs_str ? refs_str : "", refs_str ? ")" : "");
3640 free(id_str);
3641 id_str = NULL;
3642 free(refs_str);
3643 refs_str = NULL;
3644 printf("from: %s\n", got_object_commit_get_author(commit));
3645 committer_time = got_object_commit_get_committer_time(commit);
3646 datestr = get_datestr(&committer_time, datebuf);
3647 if (datestr)
3648 printf("date: %s UTC\n", datestr);
3649 author = got_object_commit_get_author(commit);
3650 committer = got_object_commit_get_committer(commit);
3651 if (strcmp(author, committer) != 0)
3652 printf("via: %s\n", committer);
3653 if (got_object_commit_get_nparents(commit) > 1) {
3654 const struct got_object_id_queue *parent_ids;
3655 struct got_object_qid *qid;
3656 int n = 1;
3657 parent_ids = got_object_commit_get_parent_ids(commit);
3658 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3659 err = got_object_id_str(&id_str, qid->id);
3660 if (err)
3661 goto done;
3662 printf("parent %d: %s\n", n++, id_str);
3663 free(id_str);
3664 id_str = NULL;
3668 err = got_object_commit_get_logmsg(&logmsg0, commit);
3669 if (err)
3670 goto done;
3672 logmsg = logmsg0;
3673 do {
3674 line = strsep(&logmsg, "\n");
3675 if (line)
3676 printf(" %s\n", line);
3677 } while (line);
3678 free(logmsg0);
3680 if (changed_paths) {
3681 struct got_pathlist_entry *pe;
3682 TAILQ_FOREACH(pe, changed_paths, entry) {
3683 struct got_diff_changed_path *cp = pe->data;
3684 printf(" %c %s\n", cp->status, pe->path);
3686 printf("\n");
3688 if (show_patch) {
3689 err = print_patch(commit, id, path, diff_context, repo);
3690 if (err == 0)
3691 printf("\n");
3694 if (fflush(stdout) != 0 && err == NULL)
3695 err = got_error_from_errno("fflush");
3696 done:
3697 free(id_str);
3698 free(refs_str);
3699 return err;
3702 static const struct got_error *
3703 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3704 struct got_repository *repo, const char *path, int show_changed_paths,
3705 int show_patch, const char *search_pattern, int diff_context, int limit,
3706 int log_branches, int reverse_display_order,
3707 struct got_reflist_object_id_map *refs_idmap)
3709 const struct got_error *err;
3710 struct got_commit_graph *graph;
3711 regex_t regex;
3712 int have_match;
3713 struct got_object_id_queue reversed_commits;
3714 struct got_object_qid *qid;
3715 struct got_commit_object *commit;
3716 struct got_pathlist_head changed_paths;
3717 struct got_pathlist_entry *pe;
3719 SIMPLEQ_INIT(&reversed_commits);
3720 TAILQ_INIT(&changed_paths);
3722 if (search_pattern && regcomp(&regex, search_pattern,
3723 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3724 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3726 err = got_commit_graph_open(&graph, path, !log_branches);
3727 if (err)
3728 return err;
3729 err = got_commit_graph_iter_start(graph, root_id, repo,
3730 check_cancelled, NULL);
3731 if (err)
3732 goto done;
3733 for (;;) {
3734 struct got_object_id *id;
3736 if (sigint_received || sigpipe_received)
3737 break;
3739 err = got_commit_graph_iter_next(&id, graph, repo,
3740 check_cancelled, NULL);
3741 if (err) {
3742 if (err->code == GOT_ERR_ITER_COMPLETED)
3743 err = NULL;
3744 break;
3746 if (id == NULL)
3747 break;
3749 err = got_object_open_as_commit(&commit, repo, id);
3750 if (err)
3751 break;
3753 if (show_changed_paths && !reverse_display_order) {
3754 err = get_changed_paths(&changed_paths, commit, repo);
3755 if (err)
3756 break;
3759 if (search_pattern) {
3760 err = match_logmsg(&have_match, id, commit, &regex);
3761 if (err) {
3762 got_object_commit_close(commit);
3763 break;
3765 if (have_match == 0 && show_changed_paths)
3766 match_changed_paths(&have_match,
3767 &changed_paths, &regex);
3768 if (have_match == 0) {
3769 got_object_commit_close(commit);
3770 TAILQ_FOREACH(pe, &changed_paths, entry) {
3771 free((char *)pe->path);
3772 free(pe->data);
3774 got_pathlist_free(&changed_paths);
3775 continue;
3779 if (reverse_display_order) {
3780 err = got_object_qid_alloc(&qid, id);
3781 if (err)
3782 break;
3783 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3784 got_object_commit_close(commit);
3785 } else {
3786 err = print_commit(commit, id, repo, path,
3787 show_changed_paths ? &changed_paths : NULL,
3788 show_patch, diff_context, refs_idmap, NULL);
3789 got_object_commit_close(commit);
3790 if (err)
3791 break;
3793 if ((limit && --limit == 0) ||
3794 (end_id && got_object_id_cmp(id, end_id) == 0))
3795 break;
3797 TAILQ_FOREACH(pe, &changed_paths, entry) {
3798 free((char *)pe->path);
3799 free(pe->data);
3801 got_pathlist_free(&changed_paths);
3803 if (reverse_display_order) {
3804 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3805 err = got_object_open_as_commit(&commit, repo, qid->id);
3806 if (err)
3807 break;
3808 if (show_changed_paths) {
3809 err = get_changed_paths(&changed_paths,
3810 commit, repo);
3811 if (err)
3812 break;
3814 err = print_commit(commit, qid->id, repo, path,
3815 show_changed_paths ? &changed_paths : NULL,
3816 show_patch, diff_context, refs_idmap, NULL);
3817 got_object_commit_close(commit);
3818 if (err)
3819 break;
3820 TAILQ_FOREACH(pe, &changed_paths, entry) {
3821 free((char *)pe->path);
3822 free(pe->data);
3824 got_pathlist_free(&changed_paths);
3827 done:
3828 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3829 qid = SIMPLEQ_FIRST(&reversed_commits);
3830 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3831 got_object_qid_free(qid);
3833 TAILQ_FOREACH(pe, &changed_paths, entry) {
3834 free((char *)pe->path);
3835 free(pe->data);
3837 got_pathlist_free(&changed_paths);
3838 if (search_pattern)
3839 regfree(&regex);
3840 got_commit_graph_close(graph);
3841 return err;
3844 __dead static void
3845 usage_log(void)
3847 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3848 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3849 "[-R] [path]\n", getprogname());
3850 exit(1);
3853 static int
3854 get_default_log_limit(void)
3856 const char *got_default_log_limit;
3857 long long n;
3858 const char *errstr;
3860 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3861 if (got_default_log_limit == NULL)
3862 return 0;
3863 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3864 if (errstr != NULL)
3865 return 0;
3866 return n;
3869 static const struct got_error *
3870 cmd_log(int argc, char *argv[])
3872 const struct got_error *error;
3873 struct got_repository *repo = NULL;
3874 struct got_worktree *worktree = NULL;
3875 struct got_object_id *start_id = NULL, *end_id = NULL;
3876 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3877 const char *start_commit = NULL, *end_commit = NULL;
3878 const char *search_pattern = NULL;
3879 int diff_context = -1, ch;
3880 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3881 int reverse_display_order = 0;
3882 const char *errstr;
3883 struct got_reflist_head refs;
3884 struct got_reflist_object_id_map *refs_idmap = NULL;
3886 TAILQ_INIT(&refs);
3888 #ifndef PROFILE
3889 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3890 NULL)
3891 == -1)
3892 err(1, "pledge");
3893 #endif
3895 limit = get_default_log_limit();
3897 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3898 switch (ch) {
3899 case 'p':
3900 show_patch = 1;
3901 break;
3902 case 'P':
3903 show_changed_paths = 1;
3904 break;
3905 case 'c':
3906 start_commit = optarg;
3907 break;
3908 case 'C':
3909 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3910 &errstr);
3911 if (errstr != NULL)
3912 err(1, "-C option %s", errstr);
3913 break;
3914 case 'l':
3915 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3916 if (errstr != NULL)
3917 err(1, "-l option %s", errstr);
3918 break;
3919 case 'b':
3920 log_branches = 1;
3921 break;
3922 case 'r':
3923 repo_path = realpath(optarg, NULL);
3924 if (repo_path == NULL)
3925 return got_error_from_errno2("realpath",
3926 optarg);
3927 got_path_strip_trailing_slashes(repo_path);
3928 break;
3929 case 'R':
3930 reverse_display_order = 1;
3931 break;
3932 case 's':
3933 search_pattern = optarg;
3934 break;
3935 case 'x':
3936 end_commit = optarg;
3937 break;
3938 default:
3939 usage_log();
3940 /* NOTREACHED */
3944 argc -= optind;
3945 argv += optind;
3947 if (diff_context == -1)
3948 diff_context = 3;
3949 else if (!show_patch)
3950 errx(1, "-C requires -p");
3952 cwd = getcwd(NULL, 0);
3953 if (cwd == NULL) {
3954 error = got_error_from_errno("getcwd");
3955 goto done;
3958 if (repo_path == NULL) {
3959 error = got_worktree_open(&worktree, cwd);
3960 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3961 goto done;
3962 error = NULL;
3965 if (argc == 1) {
3966 if (worktree) {
3967 error = got_worktree_resolve_path(&path, worktree,
3968 argv[0]);
3969 if (error)
3970 goto done;
3971 } else {
3972 path = strdup(argv[0]);
3973 if (path == NULL) {
3974 error = got_error_from_errno("strdup");
3975 goto done;
3978 } else if (argc != 0)
3979 usage_log();
3981 if (repo_path == NULL) {
3982 repo_path = worktree ?
3983 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3985 if (repo_path == NULL) {
3986 error = got_error_from_errno("strdup");
3987 goto done;
3990 error = got_repo_open(&repo, repo_path, NULL);
3991 if (error != NULL)
3992 goto done;
3994 error = apply_unveil(got_repo_get_path(repo), 1,
3995 worktree ? got_worktree_get_root_path(worktree) : NULL);
3996 if (error)
3997 goto done;
3999 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4000 if (error)
4001 goto done;
4003 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4004 if (error)
4005 goto done;
4007 if (start_commit == NULL) {
4008 struct got_reference *head_ref;
4009 struct got_commit_object *commit = NULL;
4010 error = got_ref_open(&head_ref, repo,
4011 worktree ? got_worktree_get_head_ref_name(worktree)
4012 : GOT_REF_HEAD, 0);
4013 if (error != NULL)
4014 goto done;
4015 error = got_ref_resolve(&start_id, repo, head_ref);
4016 got_ref_close(head_ref);
4017 if (error != NULL)
4018 goto done;
4019 error = got_object_open_as_commit(&commit, repo,
4020 start_id);
4021 if (error != NULL)
4022 goto done;
4023 got_object_commit_close(commit);
4024 } else {
4025 error = got_repo_match_object_id(&start_id, NULL,
4026 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4027 if (error != NULL)
4028 goto done;
4030 if (end_commit != NULL) {
4031 error = got_repo_match_object_id(&end_id, NULL,
4032 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4033 if (error != NULL)
4034 goto done;
4037 if (worktree) {
4039 * If a path was specified on the command line it was resolved
4040 * to a path in the work tree above. Prepend the work tree's
4041 * path prefix to obtain the corresponding in-repository path.
4043 if (path) {
4044 const char *prefix;
4045 prefix = got_worktree_get_path_prefix(worktree);
4046 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4047 (path[0] != '\0') ? "/" : "", path) == -1) {
4048 error = got_error_from_errno("asprintf");
4049 goto done;
4052 } else
4053 error = got_repo_map_path(&in_repo_path, repo,
4054 path ? path : "");
4055 if (error != NULL)
4056 goto done;
4057 if (in_repo_path) {
4058 free(path);
4059 path = in_repo_path;
4062 error = print_commits(start_id, end_id, repo, path ? path : "",
4063 show_changed_paths, show_patch, search_pattern, diff_context,
4064 limit, log_branches, reverse_display_order, refs_idmap);
4065 done:
4066 free(path);
4067 free(repo_path);
4068 free(cwd);
4069 if (worktree)
4070 got_worktree_close(worktree);
4071 if (repo) {
4072 const struct got_error *close_err = got_repo_close(repo);
4073 if (error == NULL)
4074 error = close_err;
4076 if (refs_idmap)
4077 got_reflist_object_id_map_free(refs_idmap);
4078 got_ref_list_free(&refs);
4079 return error;
4082 __dead static void
4083 usage_diff(void)
4085 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4086 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4087 exit(1);
4090 struct print_diff_arg {
4091 struct got_repository *repo;
4092 struct got_worktree *worktree;
4093 int diff_context;
4094 const char *id_str;
4095 int header_shown;
4096 int diff_staged;
4097 int ignore_whitespace;
4098 int force_text_diff;
4102 * Create a file which contains the target path of a symlink so we can feed
4103 * it as content to the diff engine.
4105 static const struct got_error *
4106 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4107 const char *abspath)
4109 const struct got_error *err = NULL;
4110 char target_path[PATH_MAX];
4111 ssize_t target_len, outlen;
4113 *fd = -1;
4115 if (dirfd != -1) {
4116 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4117 if (target_len == -1)
4118 return got_error_from_errno2("readlinkat", abspath);
4119 } else {
4120 target_len = readlink(abspath, target_path, PATH_MAX);
4121 if (target_len == -1)
4122 return got_error_from_errno2("readlink", abspath);
4125 *fd = got_opentempfd();
4126 if (*fd == -1)
4127 return got_error_from_errno("got_opentempfd");
4129 outlen = write(*fd, target_path, target_len);
4130 if (outlen == -1) {
4131 err = got_error_from_errno("got_opentempfd");
4132 goto done;
4135 if (lseek(*fd, 0, SEEK_SET) == -1) {
4136 err = got_error_from_errno2("lseek", abspath);
4137 goto done;
4139 done:
4140 if (err) {
4141 close(*fd);
4142 *fd = -1;
4144 return err;
4147 static const struct got_error *
4148 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4149 const char *path, struct got_object_id *blob_id,
4150 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4151 int dirfd, const char *de_name)
4153 struct print_diff_arg *a = arg;
4154 const struct got_error *err = NULL;
4155 struct got_blob_object *blob1 = NULL;
4156 int fd = -1;
4157 FILE *f2 = NULL;
4158 char *abspath = NULL, *label1 = NULL;
4159 struct stat sb;
4161 if (a->diff_staged) {
4162 if (staged_status != GOT_STATUS_MODIFY &&
4163 staged_status != GOT_STATUS_ADD &&
4164 staged_status != GOT_STATUS_DELETE)
4165 return NULL;
4166 } else {
4167 if (staged_status == GOT_STATUS_DELETE)
4168 return NULL;
4169 if (status == GOT_STATUS_NONEXISTENT)
4170 return got_error_set_errno(ENOENT, path);
4171 if (status != GOT_STATUS_MODIFY &&
4172 status != GOT_STATUS_ADD &&
4173 status != GOT_STATUS_DELETE &&
4174 status != GOT_STATUS_CONFLICT)
4175 return NULL;
4178 if (!a->header_shown) {
4179 printf("diff %s %s%s\n", a->id_str,
4180 got_worktree_get_root_path(a->worktree),
4181 a->diff_staged ? " (staged changes)" : "");
4182 a->header_shown = 1;
4185 if (a->diff_staged) {
4186 const char *label1 = NULL, *label2 = NULL;
4187 switch (staged_status) {
4188 case GOT_STATUS_MODIFY:
4189 label1 = path;
4190 label2 = path;
4191 break;
4192 case GOT_STATUS_ADD:
4193 label2 = path;
4194 break;
4195 case GOT_STATUS_DELETE:
4196 label1 = path;
4197 break;
4198 default:
4199 return got_error(GOT_ERR_FILE_STATUS);
4201 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4202 staged_blob_id, label1, label2, a->diff_context,
4203 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4206 if (staged_status == GOT_STATUS_ADD ||
4207 staged_status == GOT_STATUS_MODIFY) {
4208 char *id_str;
4209 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4210 8192);
4211 if (err)
4212 goto done;
4213 err = got_object_id_str(&id_str, staged_blob_id);
4214 if (err)
4215 goto done;
4216 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4217 err = got_error_from_errno("asprintf");
4218 free(id_str);
4219 goto done;
4221 free(id_str);
4222 } else if (status != GOT_STATUS_ADD) {
4223 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4224 if (err)
4225 goto done;
4228 if (status != GOT_STATUS_DELETE) {
4229 if (asprintf(&abspath, "%s/%s",
4230 got_worktree_get_root_path(a->worktree), path) == -1) {
4231 err = got_error_from_errno("asprintf");
4232 goto done;
4235 if (dirfd != -1) {
4236 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4237 if (fd == -1) {
4238 if (errno != ELOOP) {
4239 err = got_error_from_errno2("openat",
4240 abspath);
4241 goto done;
4243 err = get_symlink_target_file(&fd, dirfd,
4244 de_name, abspath);
4245 if (err)
4246 goto done;
4248 } else {
4249 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4250 if (fd == -1) {
4251 if (errno != ELOOP) {
4252 err = got_error_from_errno2("open",
4253 abspath);
4254 goto done;
4256 err = get_symlink_target_file(&fd, dirfd,
4257 de_name, abspath);
4258 if (err)
4259 goto done;
4262 if (fstat(fd, &sb) == -1) {
4263 err = got_error_from_errno2("fstat", abspath);
4264 goto done;
4266 f2 = fdopen(fd, "r");
4267 if (f2 == NULL) {
4268 err = got_error_from_errno2("fdopen", abspath);
4269 goto done;
4271 fd = -1;
4272 } else
4273 sb.st_size = 0;
4275 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4276 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4277 done:
4278 if (blob1)
4279 got_object_blob_close(blob1);
4280 if (f2 && fclose(f2) == EOF && err == NULL)
4281 err = got_error_from_errno("fclose");
4282 if (fd != -1 && close(fd) == -1 && err == NULL)
4283 err = got_error_from_errno("close");
4284 free(abspath);
4285 return err;
4288 static const struct got_error *
4289 cmd_diff(int argc, char *argv[])
4291 const struct got_error *error;
4292 struct got_repository *repo = NULL;
4293 struct got_worktree *worktree = NULL;
4294 char *cwd = NULL, *repo_path = NULL;
4295 struct got_object_id *id1 = NULL, *id2 = NULL;
4296 const char *id_str1 = NULL, *id_str2 = NULL;
4297 char *label1 = NULL, *label2 = NULL;
4298 int type1, type2;
4299 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4300 int force_text_diff = 0;
4301 const char *errstr;
4302 char *path = NULL;
4303 struct got_reflist_head refs;
4305 TAILQ_INIT(&refs);
4307 #ifndef PROFILE
4308 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4309 NULL) == -1)
4310 err(1, "pledge");
4311 #endif
4313 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4314 switch (ch) {
4315 case 'a':
4316 force_text_diff = 1;
4317 break;
4318 case 'C':
4319 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4320 &errstr);
4321 if (errstr != NULL)
4322 err(1, "-C option %s", errstr);
4323 break;
4324 case 'r':
4325 repo_path = realpath(optarg, NULL);
4326 if (repo_path == NULL)
4327 return got_error_from_errno2("realpath",
4328 optarg);
4329 got_path_strip_trailing_slashes(repo_path);
4330 break;
4331 case 's':
4332 diff_staged = 1;
4333 break;
4334 case 'w':
4335 ignore_whitespace = 1;
4336 break;
4337 default:
4338 usage_diff();
4339 /* NOTREACHED */
4343 argc -= optind;
4344 argv += optind;
4346 cwd = getcwd(NULL, 0);
4347 if (cwd == NULL) {
4348 error = got_error_from_errno("getcwd");
4349 goto done;
4351 if (argc <= 1) {
4352 if (repo_path)
4353 errx(1,
4354 "-r option can't be used when diffing a work tree");
4355 error = got_worktree_open(&worktree, cwd);
4356 if (error) {
4357 if (error->code == GOT_ERR_NOT_WORKTREE)
4358 error = wrap_not_worktree_error(error, "diff",
4359 cwd);
4360 goto done;
4362 repo_path = strdup(got_worktree_get_repo_path(worktree));
4363 if (repo_path == NULL) {
4364 error = got_error_from_errno("strdup");
4365 goto done;
4367 if (argc == 1) {
4368 error = got_worktree_resolve_path(&path, worktree,
4369 argv[0]);
4370 if (error)
4371 goto done;
4372 } else {
4373 path = strdup("");
4374 if (path == NULL) {
4375 error = got_error_from_errno("strdup");
4376 goto done;
4379 } else if (argc == 2) {
4380 if (diff_staged)
4381 errx(1, "-s option can't be used when diffing "
4382 "objects in repository");
4383 id_str1 = argv[0];
4384 id_str2 = argv[1];
4385 if (repo_path == NULL) {
4386 error = got_worktree_open(&worktree, cwd);
4387 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4388 goto done;
4389 repo_path = strdup(worktree ?
4390 got_worktree_get_repo_path(worktree) : cwd);
4391 if (repo_path == NULL) {
4392 error = got_error_from_errno("strdup");
4393 goto done;
4396 } else
4397 usage_diff();
4399 error = got_repo_open(&repo, repo_path, NULL);
4400 free(repo_path);
4401 if (error != NULL)
4402 goto done;
4404 error = apply_unveil(got_repo_get_path(repo), 1,
4405 worktree ? got_worktree_get_root_path(worktree) : NULL);
4406 if (error)
4407 goto done;
4409 if (argc <= 1) {
4410 struct print_diff_arg arg;
4411 struct got_pathlist_head paths;
4412 char *id_str;
4414 TAILQ_INIT(&paths);
4416 error = got_object_id_str(&id_str,
4417 got_worktree_get_base_commit_id(worktree));
4418 if (error)
4419 goto done;
4420 arg.repo = repo;
4421 arg.worktree = worktree;
4422 arg.diff_context = diff_context;
4423 arg.id_str = id_str;
4424 arg.header_shown = 0;
4425 arg.diff_staged = diff_staged;
4426 arg.ignore_whitespace = ignore_whitespace;
4427 arg.force_text_diff = force_text_diff;
4429 error = got_pathlist_append(&paths, path, NULL);
4430 if (error)
4431 goto done;
4433 error = got_worktree_status(worktree, &paths, repo, 0,
4434 print_diff, &arg, check_cancelled, NULL);
4435 free(id_str);
4436 got_pathlist_free(&paths);
4437 goto done;
4440 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4441 if (error)
4442 return error;
4444 error = got_repo_match_object_id(&id1, &label1, id_str1,
4445 GOT_OBJ_TYPE_ANY, &refs, repo);
4446 if (error)
4447 goto done;
4449 error = got_repo_match_object_id(&id2, &label2, id_str2,
4450 GOT_OBJ_TYPE_ANY, &refs, repo);
4451 if (error)
4452 goto done;
4454 error = got_object_get_type(&type1, repo, id1);
4455 if (error)
4456 goto done;
4458 error = got_object_get_type(&type2, repo, id2);
4459 if (error)
4460 goto done;
4462 if (type1 != type2) {
4463 error = got_error(GOT_ERR_OBJ_TYPE);
4464 goto done;
4467 switch (type1) {
4468 case GOT_OBJ_TYPE_BLOB:
4469 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4470 NULL, NULL, diff_context, ignore_whitespace,
4471 force_text_diff, repo, stdout);
4472 break;
4473 case GOT_OBJ_TYPE_TREE:
4474 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4475 "", "", diff_context, ignore_whitespace, force_text_diff,
4476 repo, stdout);
4477 break;
4478 case GOT_OBJ_TYPE_COMMIT:
4479 printf("diff %s %s\n", label1, label2);
4480 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4481 diff_context, ignore_whitespace, force_text_diff, repo,
4482 stdout);
4483 break;
4484 default:
4485 error = got_error(GOT_ERR_OBJ_TYPE);
4487 done:
4488 free(label1);
4489 free(label2);
4490 free(id1);
4491 free(id2);
4492 free(path);
4493 if (worktree)
4494 got_worktree_close(worktree);
4495 if (repo) {
4496 const struct got_error *close_err = got_repo_close(repo);
4497 if (error == NULL)
4498 error = close_err;
4500 got_ref_list_free(&refs);
4501 return error;
4504 __dead static void
4505 usage_blame(void)
4507 fprintf(stderr,
4508 "usage: %s blame [-c commit] [-r repository-path] path\n",
4509 getprogname());
4510 exit(1);
4513 struct blame_line {
4514 int annotated;
4515 char *id_str;
4516 char *committer;
4517 char datebuf[11]; /* YYYY-MM-DD + NUL */
4520 struct blame_cb_args {
4521 struct blame_line *lines;
4522 int nlines;
4523 int nlines_prec;
4524 int lineno_cur;
4525 off_t *line_offsets;
4526 FILE *f;
4527 struct got_repository *repo;
4530 static const struct got_error *
4531 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4533 const struct got_error *err = NULL;
4534 struct blame_cb_args *a = arg;
4535 struct blame_line *bline;
4536 char *line = NULL;
4537 size_t linesize = 0;
4538 struct got_commit_object *commit = NULL;
4539 off_t offset;
4540 struct tm tm;
4541 time_t committer_time;
4543 if (nlines != a->nlines ||
4544 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4545 return got_error(GOT_ERR_RANGE);
4547 if (sigint_received)
4548 return got_error(GOT_ERR_ITER_COMPLETED);
4550 if (lineno == -1)
4551 return NULL; /* no change in this commit */
4553 /* Annotate this line. */
4554 bline = &a->lines[lineno - 1];
4555 if (bline->annotated)
4556 return NULL;
4557 err = got_object_id_str(&bline->id_str, id);
4558 if (err)
4559 return err;
4561 err = got_object_open_as_commit(&commit, a->repo, id);
4562 if (err)
4563 goto done;
4565 bline->committer = strdup(got_object_commit_get_committer(commit));
4566 if (bline->committer == NULL) {
4567 err = got_error_from_errno("strdup");
4568 goto done;
4571 committer_time = got_object_commit_get_committer_time(commit);
4572 if (localtime_r(&committer_time, &tm) == NULL)
4573 return got_error_from_errno("localtime_r");
4574 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4575 &tm) == 0) {
4576 err = got_error(GOT_ERR_NO_SPACE);
4577 goto done;
4579 bline->annotated = 1;
4581 /* Print lines annotated so far. */
4582 bline = &a->lines[a->lineno_cur - 1];
4583 if (!bline->annotated)
4584 goto done;
4586 offset = a->line_offsets[a->lineno_cur - 1];
4587 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4588 err = got_error_from_errno("fseeko");
4589 goto done;
4592 while (bline->annotated) {
4593 char *smallerthan, *at, *nl, *committer;
4594 size_t len;
4596 if (getline(&line, &linesize, a->f) == -1) {
4597 if (ferror(a->f))
4598 err = got_error_from_errno("getline");
4599 break;
4602 committer = bline->committer;
4603 smallerthan = strchr(committer, '<');
4604 if (smallerthan && smallerthan[1] != '\0')
4605 committer = smallerthan + 1;
4606 at = strchr(committer, '@');
4607 if (at)
4608 *at = '\0';
4609 len = strlen(committer);
4610 if (len >= 9)
4611 committer[8] = '\0';
4613 nl = strchr(line, '\n');
4614 if (nl)
4615 *nl = '\0';
4616 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4617 bline->id_str, bline->datebuf, committer, line);
4619 a->lineno_cur++;
4620 bline = &a->lines[a->lineno_cur - 1];
4622 done:
4623 if (commit)
4624 got_object_commit_close(commit);
4625 free(line);
4626 return err;
4629 static const struct got_error *
4630 cmd_blame(int argc, char *argv[])
4632 const struct got_error *error;
4633 struct got_repository *repo = NULL;
4634 struct got_worktree *worktree = NULL;
4635 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4636 char *link_target = NULL;
4637 struct got_object_id *obj_id = NULL;
4638 struct got_object_id *commit_id = NULL;
4639 struct got_blob_object *blob = NULL;
4640 char *commit_id_str = NULL;
4641 struct blame_cb_args bca;
4642 int ch, obj_type, i;
4643 off_t filesize;
4645 memset(&bca, 0, sizeof(bca));
4647 #ifndef PROFILE
4648 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4649 NULL) == -1)
4650 err(1, "pledge");
4651 #endif
4653 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4654 switch (ch) {
4655 case 'c':
4656 commit_id_str = optarg;
4657 break;
4658 case 'r':
4659 repo_path = realpath(optarg, NULL);
4660 if (repo_path == NULL)
4661 return got_error_from_errno2("realpath",
4662 optarg);
4663 got_path_strip_trailing_slashes(repo_path);
4664 break;
4665 default:
4666 usage_blame();
4667 /* NOTREACHED */
4671 argc -= optind;
4672 argv += optind;
4674 if (argc == 1)
4675 path = argv[0];
4676 else
4677 usage_blame();
4679 cwd = getcwd(NULL, 0);
4680 if (cwd == NULL) {
4681 error = got_error_from_errno("getcwd");
4682 goto done;
4684 if (repo_path == NULL) {
4685 error = got_worktree_open(&worktree, cwd);
4686 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4687 goto done;
4688 else
4689 error = NULL;
4690 if (worktree) {
4691 repo_path =
4692 strdup(got_worktree_get_repo_path(worktree));
4693 if (repo_path == NULL) {
4694 error = got_error_from_errno("strdup");
4695 if (error)
4696 goto done;
4698 } else {
4699 repo_path = strdup(cwd);
4700 if (repo_path == NULL) {
4701 error = got_error_from_errno("strdup");
4702 goto done;
4707 error = got_repo_open(&repo, repo_path, NULL);
4708 if (error != NULL)
4709 goto done;
4711 if (worktree) {
4712 const char *prefix = got_worktree_get_path_prefix(worktree);
4713 char *p;
4715 error = got_worktree_resolve_path(&p, worktree, path);
4716 if (error)
4717 goto done;
4718 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4719 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4720 p) == -1) {
4721 error = got_error_from_errno("asprintf");
4722 free(p);
4723 goto done;
4725 free(p);
4726 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4727 } else {
4728 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4729 if (error)
4730 goto done;
4731 error = got_repo_map_path(&in_repo_path, repo, path);
4733 if (error)
4734 goto done;
4736 if (commit_id_str == NULL) {
4737 struct got_reference *head_ref;
4738 error = got_ref_open(&head_ref, repo, worktree ?
4739 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4740 if (error != NULL)
4741 goto done;
4742 error = got_ref_resolve(&commit_id, repo, head_ref);
4743 got_ref_close(head_ref);
4744 if (error != NULL)
4745 goto done;
4746 } else {
4747 struct got_reflist_head refs;
4748 TAILQ_INIT(&refs);
4749 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4750 NULL);
4751 if (error)
4752 goto done;
4753 error = got_repo_match_object_id(&commit_id, NULL,
4754 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4755 got_ref_list_free(&refs);
4756 if (error)
4757 goto done;
4760 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4761 commit_id, repo);
4762 if (error)
4763 goto done;
4765 error = got_object_id_by_path(&obj_id, repo, commit_id,
4766 link_target ? link_target : in_repo_path);
4767 if (error)
4768 goto done;
4770 error = got_object_get_type(&obj_type, repo, obj_id);
4771 if (error)
4772 goto done;
4774 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4775 error = got_error_path(link_target ? link_target : in_repo_path,
4776 GOT_ERR_OBJ_TYPE);
4777 goto done;
4780 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4781 if (error)
4782 goto done;
4783 bca.f = got_opentemp();
4784 if (bca.f == NULL) {
4785 error = got_error_from_errno("got_opentemp");
4786 goto done;
4788 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4789 &bca.line_offsets, bca.f, blob);
4790 if (error || bca.nlines == 0)
4791 goto done;
4793 /* Don't include \n at EOF in the blame line count. */
4794 if (bca.line_offsets[bca.nlines - 1] == filesize)
4795 bca.nlines--;
4797 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4798 if (bca.lines == NULL) {
4799 error = got_error_from_errno("calloc");
4800 goto done;
4802 bca.lineno_cur = 1;
4803 bca.nlines_prec = 0;
4804 i = bca.nlines;
4805 while (i > 0) {
4806 i /= 10;
4807 bca.nlines_prec++;
4809 bca.repo = repo;
4811 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4812 repo, blame_cb, &bca, check_cancelled, NULL);
4813 done:
4814 free(in_repo_path);
4815 free(link_target);
4816 free(repo_path);
4817 free(cwd);
4818 free(commit_id);
4819 free(obj_id);
4820 if (blob)
4821 got_object_blob_close(blob);
4822 if (worktree)
4823 got_worktree_close(worktree);
4824 if (repo) {
4825 const struct got_error *close_err = got_repo_close(repo);
4826 if (error == NULL)
4827 error = close_err;
4829 if (bca.lines) {
4830 for (i = 0; i < bca.nlines; i++) {
4831 struct blame_line *bline = &bca.lines[i];
4832 free(bline->id_str);
4833 free(bline->committer);
4835 free(bca.lines);
4837 free(bca.line_offsets);
4838 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4839 error = got_error_from_errno("fclose");
4840 return error;
4843 __dead static void
4844 usage_tree(void)
4846 fprintf(stderr,
4847 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4848 getprogname());
4849 exit(1);
4852 static const struct got_error *
4853 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4854 const char *root_path, struct got_repository *repo)
4856 const struct got_error *err = NULL;
4857 int is_root_path = (strcmp(path, root_path) == 0);
4858 const char *modestr = "";
4859 mode_t mode = got_tree_entry_get_mode(te);
4860 char *link_target = NULL;
4862 path += strlen(root_path);
4863 while (path[0] == '/')
4864 path++;
4866 if (got_object_tree_entry_is_submodule(te))
4867 modestr = "$";
4868 else if (S_ISLNK(mode)) {
4869 int i;
4871 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4872 if (err)
4873 return err;
4874 for (i = 0; i < strlen(link_target); i++) {
4875 if (!isprint((unsigned char)link_target[i]))
4876 link_target[i] = '?';
4879 modestr = "@";
4881 else if (S_ISDIR(mode))
4882 modestr = "/";
4883 else if (mode & S_IXUSR)
4884 modestr = "*";
4886 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4887 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4888 link_target ? " -> ": "", link_target ? link_target : "");
4890 free(link_target);
4891 return NULL;
4894 static const struct got_error *
4895 print_tree(const char *path, struct got_object_id *commit_id,
4896 int show_ids, int recurse, const char *root_path,
4897 struct got_repository *repo)
4899 const struct got_error *err = NULL;
4900 struct got_object_id *tree_id = NULL;
4901 struct got_tree_object *tree = NULL;
4902 int nentries, i;
4904 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4905 if (err)
4906 goto done;
4908 err = got_object_open_as_tree(&tree, repo, tree_id);
4909 if (err)
4910 goto done;
4911 nentries = got_object_tree_get_nentries(tree);
4912 for (i = 0; i < nentries; i++) {
4913 struct got_tree_entry *te;
4914 char *id = NULL;
4916 if (sigint_received || sigpipe_received)
4917 break;
4919 te = got_object_tree_get_entry(tree, i);
4920 if (show_ids) {
4921 char *id_str;
4922 err = got_object_id_str(&id_str,
4923 got_tree_entry_get_id(te));
4924 if (err)
4925 goto done;
4926 if (asprintf(&id, "%s ", id_str) == -1) {
4927 err = got_error_from_errno("asprintf");
4928 free(id_str);
4929 goto done;
4931 free(id_str);
4933 err = print_entry(te, id, path, root_path, repo);
4934 free(id);
4935 if (err)
4936 goto done;
4938 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4939 char *child_path;
4940 if (asprintf(&child_path, "%s%s%s", path,
4941 path[0] == '/' && path[1] == '\0' ? "" : "/",
4942 got_tree_entry_get_name(te)) == -1) {
4943 err = got_error_from_errno("asprintf");
4944 goto done;
4946 err = print_tree(child_path, commit_id, show_ids, 1,
4947 root_path, repo);
4948 free(child_path);
4949 if (err)
4950 goto done;
4953 done:
4954 if (tree)
4955 got_object_tree_close(tree);
4956 free(tree_id);
4957 return err;
4960 static const struct got_error *
4961 cmd_tree(int argc, char *argv[])
4963 const struct got_error *error;
4964 struct got_repository *repo = NULL;
4965 struct got_worktree *worktree = NULL;
4966 const char *path, *refname = NULL;
4967 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4968 struct got_object_id *commit_id = NULL;
4969 char *commit_id_str = NULL;
4970 int show_ids = 0, recurse = 0;
4971 int ch;
4973 #ifndef PROFILE
4974 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4975 NULL) == -1)
4976 err(1, "pledge");
4977 #endif
4979 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4980 switch (ch) {
4981 case 'c':
4982 commit_id_str = optarg;
4983 break;
4984 case 'r':
4985 repo_path = realpath(optarg, NULL);
4986 if (repo_path == NULL)
4987 return got_error_from_errno2("realpath",
4988 optarg);
4989 got_path_strip_trailing_slashes(repo_path);
4990 break;
4991 case 'i':
4992 show_ids = 1;
4993 break;
4994 case 'R':
4995 recurse = 1;
4996 break;
4997 default:
4998 usage_tree();
4999 /* NOTREACHED */
5003 argc -= optind;
5004 argv += optind;
5006 if (argc == 1)
5007 path = argv[0];
5008 else if (argc > 1)
5009 usage_tree();
5010 else
5011 path = NULL;
5013 cwd = getcwd(NULL, 0);
5014 if (cwd == NULL) {
5015 error = got_error_from_errno("getcwd");
5016 goto done;
5018 if (repo_path == NULL) {
5019 error = got_worktree_open(&worktree, cwd);
5020 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5021 goto done;
5022 else
5023 error = NULL;
5024 if (worktree) {
5025 repo_path =
5026 strdup(got_worktree_get_repo_path(worktree));
5027 if (repo_path == NULL)
5028 error = got_error_from_errno("strdup");
5029 if (error)
5030 goto done;
5031 } else {
5032 repo_path = strdup(cwd);
5033 if (repo_path == NULL) {
5034 error = got_error_from_errno("strdup");
5035 goto done;
5040 error = got_repo_open(&repo, repo_path, NULL);
5041 if (error != NULL)
5042 goto done;
5044 if (worktree) {
5045 const char *prefix = got_worktree_get_path_prefix(worktree);
5046 char *p;
5048 if (path == NULL)
5049 path = "";
5050 error = got_worktree_resolve_path(&p, worktree, path);
5051 if (error)
5052 goto done;
5053 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5054 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5055 p) == -1) {
5056 error = got_error_from_errno("asprintf");
5057 free(p);
5058 goto done;
5060 free(p);
5061 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5062 if (error)
5063 goto done;
5064 } else {
5065 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5066 if (error)
5067 goto done;
5068 if (path == NULL)
5069 path = "/";
5070 error = got_repo_map_path(&in_repo_path, repo, path);
5071 if (error != NULL)
5072 goto done;
5075 if (commit_id_str == NULL) {
5076 struct got_reference *head_ref;
5077 if (worktree)
5078 refname = got_worktree_get_head_ref_name(worktree);
5079 else
5080 refname = GOT_REF_HEAD;
5081 error = got_ref_open(&head_ref, repo, refname, 0);
5082 if (error != NULL)
5083 goto done;
5084 error = got_ref_resolve(&commit_id, repo, head_ref);
5085 got_ref_close(head_ref);
5086 if (error != NULL)
5087 goto done;
5088 } else {
5089 struct got_reflist_head refs;
5090 TAILQ_INIT(&refs);
5091 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5092 NULL);
5093 if (error)
5094 goto done;
5095 error = got_repo_match_object_id(&commit_id, NULL,
5096 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5097 got_ref_list_free(&refs);
5098 if (error)
5099 goto done;
5102 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5103 in_repo_path, repo);
5104 done:
5105 free(in_repo_path);
5106 free(repo_path);
5107 free(cwd);
5108 free(commit_id);
5109 if (worktree)
5110 got_worktree_close(worktree);
5111 if (repo) {
5112 const struct got_error *close_err = got_repo_close(repo);
5113 if (error == NULL)
5114 error = close_err;
5116 return error;
5119 __dead static void
5120 usage_status(void)
5122 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5123 getprogname());
5124 exit(1);
5127 static const struct got_error *
5128 print_status(void *arg, unsigned char status, unsigned char staged_status,
5129 const char *path, struct got_object_id *blob_id,
5130 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5131 int dirfd, const char *de_name)
5133 if (status == staged_status && (status == GOT_STATUS_DELETE))
5134 status = GOT_STATUS_NO_CHANGE;
5135 if (arg) {
5136 char *status_codes = arg;
5137 size_t ncodes = strlen(status_codes);
5138 int i;
5139 for (i = 0; i < ncodes ; i++) {
5140 if (status == status_codes[i] ||
5141 staged_status == status_codes[i])
5142 break;
5144 if (i == ncodes)
5145 return NULL;
5147 printf("%c%c %s\n", status, staged_status, path);
5148 return NULL;
5151 static const struct got_error *
5152 cmd_status(int argc, char *argv[])
5154 const struct got_error *error = NULL;
5155 struct got_repository *repo = NULL;
5156 struct got_worktree *worktree = NULL;
5157 char *cwd = NULL, *status_codes = NULL;;
5158 struct got_pathlist_head paths;
5159 struct got_pathlist_entry *pe;
5160 int ch, i, no_ignores = 0;
5162 TAILQ_INIT(&paths);
5164 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5165 switch (ch) {
5166 case 'I':
5167 no_ignores = 1;
5168 break;
5169 case 's':
5170 for (i = 0; i < strlen(optarg); i++) {
5171 switch (optarg[i]) {
5172 case GOT_STATUS_MODIFY:
5173 case GOT_STATUS_ADD:
5174 case GOT_STATUS_DELETE:
5175 case GOT_STATUS_CONFLICT:
5176 case GOT_STATUS_MISSING:
5177 case GOT_STATUS_OBSTRUCTED:
5178 case GOT_STATUS_UNVERSIONED:
5179 case GOT_STATUS_MODE_CHANGE:
5180 case GOT_STATUS_NONEXISTENT:
5181 break;
5182 default:
5183 errx(1, "invalid status code '%c'",
5184 optarg[i]);
5187 status_codes = optarg;
5188 break;
5189 default:
5190 usage_status();
5191 /* NOTREACHED */
5195 argc -= optind;
5196 argv += optind;
5198 #ifndef PROFILE
5199 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5200 NULL) == -1)
5201 err(1, "pledge");
5202 #endif
5203 cwd = getcwd(NULL, 0);
5204 if (cwd == NULL) {
5205 error = got_error_from_errno("getcwd");
5206 goto done;
5209 error = got_worktree_open(&worktree, cwd);
5210 if (error) {
5211 if (error->code == GOT_ERR_NOT_WORKTREE)
5212 error = wrap_not_worktree_error(error, "status", cwd);
5213 goto done;
5216 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5217 NULL);
5218 if (error != NULL)
5219 goto done;
5221 error = apply_unveil(got_repo_get_path(repo), 1,
5222 got_worktree_get_root_path(worktree));
5223 if (error)
5224 goto done;
5226 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5227 if (error)
5228 goto done;
5230 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5231 print_status, status_codes, check_cancelled, NULL);
5232 done:
5233 TAILQ_FOREACH(pe, &paths, entry)
5234 free((char *)pe->path);
5235 got_pathlist_free(&paths);
5236 free(cwd);
5237 return error;
5240 __dead static void
5241 usage_ref(void)
5243 fprintf(stderr,
5244 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5245 "[-d] [name]\n",
5246 getprogname());
5247 exit(1);
5250 static const struct got_error *
5251 list_refs(struct got_repository *repo, const char *refname)
5253 static const struct got_error *err = NULL;
5254 struct got_reflist_head refs;
5255 struct got_reflist_entry *re;
5257 TAILQ_INIT(&refs);
5258 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5259 if (err)
5260 return err;
5262 TAILQ_FOREACH(re, &refs, entry) {
5263 char *refstr;
5264 refstr = got_ref_to_str(re->ref);
5265 if (refstr == NULL)
5266 return got_error_from_errno("got_ref_to_str");
5267 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5268 free(refstr);
5271 got_ref_list_free(&refs);
5272 return NULL;
5275 static const struct got_error *
5276 delete_ref(struct got_repository *repo, const char *refname)
5278 const struct got_error *err = NULL;
5279 struct got_reference *ref;
5281 err = got_ref_open(&ref, repo, refname, 0);
5282 if (err)
5283 return err;
5285 err = got_ref_delete(ref, repo);
5286 got_ref_close(ref);
5287 return err;
5290 static const struct got_error *
5291 add_ref(struct got_repository *repo, const char *refname, const char *target)
5293 const struct got_error *err = NULL;
5294 struct got_object_id *id;
5295 struct got_reference *ref = NULL;
5298 * Don't let the user create a reference name with a leading '-'.
5299 * While technically a valid reference name, this case is usually
5300 * an unintended typo.
5302 if (refname[0] == '-')
5303 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5305 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5306 repo);
5307 if (err) {
5308 struct got_reference *target_ref;
5310 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5311 return err;
5312 err = got_ref_open(&target_ref, repo, target, 0);
5313 if (err)
5314 return err;
5315 err = got_ref_resolve(&id, repo, target_ref);
5316 got_ref_close(target_ref);
5317 if (err)
5318 return err;
5321 err = got_ref_alloc(&ref, refname, id);
5322 if (err)
5323 goto done;
5325 err = got_ref_write(ref, repo);
5326 done:
5327 if (ref)
5328 got_ref_close(ref);
5329 free(id);
5330 return err;
5333 static const struct got_error *
5334 add_symref(struct got_repository *repo, const char *refname, const char *target)
5336 const struct got_error *err = NULL;
5337 struct got_reference *ref = NULL;
5338 struct got_reference *target_ref = NULL;
5341 * Don't let the user create a reference name with a leading '-'.
5342 * While technically a valid reference name, this case is usually
5343 * an unintended typo.
5345 if (refname[0] == '-')
5346 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5348 err = got_ref_open(&target_ref, repo, target, 0);
5349 if (err)
5350 return err;
5352 err = got_ref_alloc_symref(&ref, refname, target_ref);
5353 if (err)
5354 goto done;
5356 err = got_ref_write(ref, repo);
5357 done:
5358 if (target_ref)
5359 got_ref_close(target_ref);
5360 if (ref)
5361 got_ref_close(ref);
5362 return err;
5365 static const struct got_error *
5366 cmd_ref(int argc, char *argv[])
5368 const struct got_error *error = NULL;
5369 struct got_repository *repo = NULL;
5370 struct got_worktree *worktree = NULL;
5371 char *cwd = NULL, *repo_path = NULL;
5372 int ch, do_list = 0, do_delete = 0;
5373 const char *obj_arg = NULL, *symref_target= NULL;
5374 char *refname = NULL;
5376 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5377 switch (ch) {
5378 case 'c':
5379 obj_arg = optarg;
5380 break;
5381 case 'd':
5382 do_delete = 1;
5383 break;
5384 case 'r':
5385 repo_path = realpath(optarg, NULL);
5386 if (repo_path == NULL)
5387 return got_error_from_errno2("realpath",
5388 optarg);
5389 got_path_strip_trailing_slashes(repo_path);
5390 break;
5391 case 'l':
5392 do_list = 1;
5393 break;
5394 case 's':
5395 symref_target = optarg;
5396 break;
5397 default:
5398 usage_ref();
5399 /* NOTREACHED */
5403 if (obj_arg && do_list)
5404 option_conflict('c', 'l');
5405 if (obj_arg && do_delete)
5406 option_conflict('c', 'd');
5407 if (obj_arg && symref_target)
5408 option_conflict('c', 's');
5409 if (symref_target && do_delete)
5410 option_conflict('s', 'd');
5411 if (symref_target && do_list)
5412 option_conflict('s', 'l');
5413 if (do_delete && do_list)
5414 option_conflict('d', 'l');
5416 argc -= optind;
5417 argv += optind;
5419 if (do_list) {
5420 if (argc != 0 && argc != 1)
5421 usage_ref();
5422 if (argc == 1) {
5423 refname = strdup(argv[0]);
5424 if (refname == NULL) {
5425 error = got_error_from_errno("strdup");
5426 goto done;
5429 } else {
5430 if (argc != 1)
5431 usage_ref();
5432 refname = strdup(argv[0]);
5433 if (refname == NULL) {
5434 error = got_error_from_errno("strdup");
5435 goto done;
5439 if (refname)
5440 got_path_strip_trailing_slashes(refname);
5442 #ifndef PROFILE
5443 if (do_list) {
5444 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5445 NULL) == -1)
5446 err(1, "pledge");
5447 } else {
5448 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5449 "sendfd unveil", NULL) == -1)
5450 err(1, "pledge");
5452 #endif
5453 cwd = getcwd(NULL, 0);
5454 if (cwd == NULL) {
5455 error = got_error_from_errno("getcwd");
5456 goto done;
5459 if (repo_path == NULL) {
5460 error = got_worktree_open(&worktree, cwd);
5461 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5462 goto done;
5463 else
5464 error = NULL;
5465 if (worktree) {
5466 repo_path =
5467 strdup(got_worktree_get_repo_path(worktree));
5468 if (repo_path == NULL)
5469 error = got_error_from_errno("strdup");
5470 if (error)
5471 goto done;
5472 } else {
5473 repo_path = strdup(cwd);
5474 if (repo_path == NULL) {
5475 error = got_error_from_errno("strdup");
5476 goto done;
5481 error = got_repo_open(&repo, repo_path, NULL);
5482 if (error != NULL)
5483 goto done;
5485 error = apply_unveil(got_repo_get_path(repo), do_list,
5486 worktree ? got_worktree_get_root_path(worktree) : NULL);
5487 if (error)
5488 goto done;
5490 if (do_list)
5491 error = list_refs(repo, refname);
5492 else if (do_delete)
5493 error = delete_ref(repo, refname);
5494 else if (symref_target)
5495 error = add_symref(repo, refname, symref_target);
5496 else {
5497 if (obj_arg == NULL)
5498 usage_ref();
5499 error = add_ref(repo, refname, obj_arg);
5501 done:
5502 free(refname);
5503 if (repo) {
5504 const struct got_error *close_err = got_repo_close(repo);
5505 if (error == NULL)
5506 error = close_err;
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 const struct got_error *close_err = got_repo_close(repo);
5890 if (error == NULL)
5891 error = close_err;
5893 if (worktree)
5894 got_worktree_close(worktree);
5895 free(cwd);
5896 free(repo_path);
5897 free(commit_id);
5898 free(commit_id_str);
5899 TAILQ_FOREACH(pe, &paths, entry)
5900 free((char *)pe->path);
5901 got_pathlist_free(&paths);
5902 return error;
5906 __dead static void
5907 usage_tag(void)
5909 fprintf(stderr,
5910 "usage: %s tag [-c commit] [-r repository] [-l] "
5911 "[-m message] name\n", getprogname());
5912 exit(1);
5915 #if 0
5916 static const struct got_error *
5917 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5919 const struct got_error *err = NULL;
5920 struct got_reflist_entry *re, *se, *new;
5921 struct got_object_id *re_id, *se_id;
5922 struct got_tag_object *re_tag, *se_tag;
5923 time_t re_time, se_time;
5925 SIMPLEQ_FOREACH(re, tags, entry) {
5926 se = SIMPLEQ_FIRST(sorted);
5927 if (se == NULL) {
5928 err = got_reflist_entry_dup(&new, re);
5929 if (err)
5930 return err;
5931 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5932 continue;
5933 } else {
5934 err = got_ref_resolve(&re_id, repo, re->ref);
5935 if (err)
5936 break;
5937 err = got_object_open_as_tag(&re_tag, repo, re_id);
5938 free(re_id);
5939 if (err)
5940 break;
5941 re_time = got_object_tag_get_tagger_time(re_tag);
5942 got_object_tag_close(re_tag);
5945 while (se) {
5946 err = got_ref_resolve(&se_id, repo, re->ref);
5947 if (err)
5948 break;
5949 err = got_object_open_as_tag(&se_tag, repo, se_id);
5950 free(se_id);
5951 if (err)
5952 break;
5953 se_time = got_object_tag_get_tagger_time(se_tag);
5954 got_object_tag_close(se_tag);
5956 if (se_time > re_time) {
5957 err = got_reflist_entry_dup(&new, re);
5958 if (err)
5959 return err;
5960 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5961 break;
5963 se = SIMPLEQ_NEXT(se, entry);
5964 continue;
5967 done:
5968 return err;
5970 #endif
5972 static const struct got_error *
5973 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5975 static const struct got_error *err = NULL;
5976 struct got_reflist_head refs;
5977 struct got_reflist_entry *re;
5979 TAILQ_INIT(&refs);
5981 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5982 if (err)
5983 return err;
5985 TAILQ_FOREACH(re, &refs, entry) {
5986 const char *refname;
5987 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5988 char datebuf[26];
5989 const char *tagger;
5990 time_t tagger_time;
5991 struct got_object_id *id;
5992 struct got_tag_object *tag;
5993 struct got_commit_object *commit = NULL;
5995 refname = got_ref_get_name(re->ref);
5996 if (strncmp(refname, "refs/tags/", 10) != 0)
5997 continue;
5998 refname += 10;
5999 refstr = got_ref_to_str(re->ref);
6000 if (refstr == NULL) {
6001 err = got_error_from_errno("got_ref_to_str");
6002 break;
6004 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6005 free(refstr);
6007 err = got_ref_resolve(&id, repo, re->ref);
6008 if (err)
6009 break;
6010 err = got_object_open_as_tag(&tag, repo, id);
6011 if (err) {
6012 if (err->code != GOT_ERR_OBJ_TYPE) {
6013 free(id);
6014 break;
6016 /* "lightweight" tag */
6017 err = got_object_open_as_commit(&commit, repo, id);
6018 if (err) {
6019 free(id);
6020 break;
6022 tagger = got_object_commit_get_committer(commit);
6023 tagger_time =
6024 got_object_commit_get_committer_time(commit);
6025 err = got_object_id_str(&id_str, id);
6026 free(id);
6027 if (err)
6028 break;
6029 } else {
6030 free(id);
6031 tagger = got_object_tag_get_tagger(tag);
6032 tagger_time = got_object_tag_get_tagger_time(tag);
6033 err = got_object_id_str(&id_str,
6034 got_object_tag_get_object_id(tag));
6035 if (err)
6036 break;
6038 printf("from: %s\n", tagger);
6039 datestr = get_datestr(&tagger_time, datebuf);
6040 if (datestr)
6041 printf("date: %s UTC\n", datestr);
6042 if (commit)
6043 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6044 else {
6045 switch (got_object_tag_get_object_type(tag)) {
6046 case GOT_OBJ_TYPE_BLOB:
6047 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6048 id_str);
6049 break;
6050 case GOT_OBJ_TYPE_TREE:
6051 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6052 id_str);
6053 break;
6054 case GOT_OBJ_TYPE_COMMIT:
6055 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6056 id_str);
6057 break;
6058 case GOT_OBJ_TYPE_TAG:
6059 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6060 id_str);
6061 break;
6062 default:
6063 break;
6066 free(id_str);
6067 if (commit) {
6068 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6069 if (err)
6070 break;
6071 got_object_commit_close(commit);
6072 } else {
6073 tagmsg0 = strdup(got_object_tag_get_message(tag));
6074 got_object_tag_close(tag);
6075 if (tagmsg0 == NULL) {
6076 err = got_error_from_errno("strdup");
6077 break;
6081 tagmsg = tagmsg0;
6082 do {
6083 line = strsep(&tagmsg, "\n");
6084 if (line)
6085 printf(" %s\n", line);
6086 } while (line);
6087 free(tagmsg0);
6090 got_ref_list_free(&refs);
6091 return NULL;
6094 static const struct got_error *
6095 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6096 const char *tag_name, const char *repo_path)
6098 const struct got_error *err = NULL;
6099 char *template = NULL, *initial_content = NULL;
6100 char *editor = NULL;
6101 int initial_content_len;
6102 int fd = -1;
6104 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6105 err = got_error_from_errno("asprintf");
6106 goto done;
6109 initial_content_len = asprintf(&initial_content,
6110 "\n# tagging commit %s as %s\n",
6111 commit_id_str, tag_name);
6112 if (initial_content_len == -1) {
6113 err = got_error_from_errno("asprintf");
6114 goto done;
6117 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6118 if (err)
6119 goto done;
6121 if (write(fd, initial_content, initial_content_len) == -1) {
6122 err = got_error_from_errno2("write", *tagmsg_path);
6123 goto done;
6126 err = get_editor(&editor);
6127 if (err)
6128 goto done;
6129 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6130 initial_content_len, 1);
6131 done:
6132 free(initial_content);
6133 free(template);
6134 free(editor);
6136 if (fd != -1 && close(fd) == -1 && err == NULL)
6137 err = got_error_from_errno2("close", *tagmsg_path);
6139 /* Editor is done; we can now apply unveil(2) */
6140 if (err == NULL)
6141 err = apply_unveil(repo_path, 0, NULL);
6142 if (err) {
6143 free(*tagmsg);
6144 *tagmsg = NULL;
6146 return err;
6149 static const struct got_error *
6150 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6151 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6153 const struct got_error *err = NULL;
6154 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6155 char *label = NULL, *commit_id_str = NULL;
6156 struct got_reference *ref = NULL;
6157 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6158 char *tagmsg_path = NULL, *tag_id_str = NULL;
6159 int preserve_tagmsg = 0;
6160 struct got_reflist_head refs;
6162 TAILQ_INIT(&refs);
6165 * Don't let the user create a tag name with a leading '-'.
6166 * While technically a valid reference name, this case is usually
6167 * an unintended typo.
6169 if (tag_name[0] == '-')
6170 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6172 err = get_author(&tagger, repo, worktree);
6173 if (err)
6174 return err;
6176 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6177 if (err)
6178 goto done;
6180 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6181 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6182 if (err)
6183 goto done;
6185 err = got_object_id_str(&commit_id_str, commit_id);
6186 if (err)
6187 goto done;
6189 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6190 refname = strdup(tag_name);
6191 if (refname == NULL) {
6192 err = got_error_from_errno("strdup");
6193 goto done;
6195 tag_name += 10;
6196 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6197 err = got_error_from_errno("asprintf");
6198 goto done;
6201 err = got_ref_open(&ref, repo, refname, 0);
6202 if (err == NULL) {
6203 err = got_error(GOT_ERR_TAG_EXISTS);
6204 goto done;
6205 } else if (err->code != GOT_ERR_NOT_REF)
6206 goto done;
6208 if (tagmsg_arg == NULL) {
6209 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6210 tag_name, got_repo_get_path(repo));
6211 if (err) {
6212 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6213 tagmsg_path != NULL)
6214 preserve_tagmsg = 1;
6215 goto done;
6219 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6220 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6221 if (err) {
6222 if (tagmsg_path)
6223 preserve_tagmsg = 1;
6224 goto done;
6227 err = got_ref_alloc(&ref, refname, tag_id);
6228 if (err) {
6229 if (tagmsg_path)
6230 preserve_tagmsg = 1;
6231 goto done;
6234 err = got_ref_write(ref, repo);
6235 if (err) {
6236 if (tagmsg_path)
6237 preserve_tagmsg = 1;
6238 goto done;
6241 err = got_object_id_str(&tag_id_str, tag_id);
6242 if (err) {
6243 if (tagmsg_path)
6244 preserve_tagmsg = 1;
6245 goto done;
6247 printf("Created tag %s\n", tag_id_str);
6248 done:
6249 if (preserve_tagmsg) {
6250 fprintf(stderr, "%s: tag message preserved in %s\n",
6251 getprogname(), tagmsg_path);
6252 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6253 err = got_error_from_errno2("unlink", tagmsg_path);
6254 free(tag_id_str);
6255 if (ref)
6256 got_ref_close(ref);
6257 free(commit_id);
6258 free(commit_id_str);
6259 free(refname);
6260 free(tagmsg);
6261 free(tagmsg_path);
6262 free(tagger);
6263 got_ref_list_free(&refs);
6264 return err;
6267 static const struct got_error *
6268 cmd_tag(int argc, char *argv[])
6270 const struct got_error *error = NULL;
6271 struct got_repository *repo = NULL;
6272 struct got_worktree *worktree = NULL;
6273 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6274 char *gitconfig_path = NULL;
6275 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6276 int ch, do_list = 0;
6278 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6279 switch (ch) {
6280 case 'c':
6281 commit_id_arg = optarg;
6282 break;
6283 case 'm':
6284 tagmsg = optarg;
6285 break;
6286 case 'r':
6287 repo_path = realpath(optarg, NULL);
6288 if (repo_path == NULL)
6289 return got_error_from_errno2("realpath",
6290 optarg);
6291 got_path_strip_trailing_slashes(repo_path);
6292 break;
6293 case 'l':
6294 do_list = 1;
6295 break;
6296 default:
6297 usage_tag();
6298 /* NOTREACHED */
6302 argc -= optind;
6303 argv += optind;
6305 if (do_list) {
6306 if (commit_id_arg != NULL)
6307 errx(1,
6308 "-c option can only be used when creating a tag");
6309 if (tagmsg)
6310 option_conflict('l', 'm');
6311 if (argc > 0)
6312 usage_tag();
6313 } else if (argc != 1)
6314 usage_tag();
6316 tag_name = argv[0];
6318 #ifndef PROFILE
6319 if (do_list) {
6320 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6321 NULL) == -1)
6322 err(1, "pledge");
6323 } else {
6324 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6325 "sendfd unveil", NULL) == -1)
6326 err(1, "pledge");
6328 #endif
6329 cwd = getcwd(NULL, 0);
6330 if (cwd == NULL) {
6331 error = got_error_from_errno("getcwd");
6332 goto done;
6335 if (repo_path == NULL) {
6336 error = got_worktree_open(&worktree, cwd);
6337 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6338 goto done;
6339 else
6340 error = NULL;
6341 if (worktree) {
6342 repo_path =
6343 strdup(got_worktree_get_repo_path(worktree));
6344 if (repo_path == NULL)
6345 error = got_error_from_errno("strdup");
6346 if (error)
6347 goto done;
6348 } else {
6349 repo_path = strdup(cwd);
6350 if (repo_path == NULL) {
6351 error = got_error_from_errno("strdup");
6352 goto done;
6357 if (do_list) {
6358 error = got_repo_open(&repo, repo_path, NULL);
6359 if (error != NULL)
6360 goto done;
6361 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6362 if (error)
6363 goto done;
6364 error = list_tags(repo, worktree);
6365 } else {
6366 error = get_gitconfig_path(&gitconfig_path);
6367 if (error)
6368 goto done;
6369 error = got_repo_open(&repo, repo_path, gitconfig_path);
6370 if (error != NULL)
6371 goto done;
6373 if (tagmsg) {
6374 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6375 if (error)
6376 goto done;
6379 if (commit_id_arg == NULL) {
6380 struct got_reference *head_ref;
6381 struct got_object_id *commit_id;
6382 error = got_ref_open(&head_ref, repo,
6383 worktree ? got_worktree_get_head_ref_name(worktree)
6384 : GOT_REF_HEAD, 0);
6385 if (error)
6386 goto done;
6387 error = got_ref_resolve(&commit_id, repo, head_ref);
6388 got_ref_close(head_ref);
6389 if (error)
6390 goto done;
6391 error = got_object_id_str(&commit_id_str, commit_id);
6392 free(commit_id);
6393 if (error)
6394 goto done;
6397 error = add_tag(repo, worktree, tag_name,
6398 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6400 done:
6401 if (repo) {
6402 const struct got_error *close_err = got_repo_close(repo);
6403 if (error == NULL)
6404 error = close_err;
6406 if (worktree)
6407 got_worktree_close(worktree);
6408 free(cwd);
6409 free(repo_path);
6410 free(gitconfig_path);
6411 free(commit_id_str);
6412 return error;
6415 __dead static void
6416 usage_add(void)
6418 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6419 getprogname());
6420 exit(1);
6423 static const struct got_error *
6424 add_progress(void *arg, unsigned char status, const char *path)
6426 while (path[0] == '/')
6427 path++;
6428 printf("%c %s\n", status, path);
6429 return NULL;
6432 static const struct got_error *
6433 cmd_add(int argc, char *argv[])
6435 const struct got_error *error = NULL;
6436 struct got_repository *repo = NULL;
6437 struct got_worktree *worktree = NULL;
6438 char *cwd = NULL;
6439 struct got_pathlist_head paths;
6440 struct got_pathlist_entry *pe;
6441 int ch, can_recurse = 0, no_ignores = 0;
6443 TAILQ_INIT(&paths);
6445 while ((ch = getopt(argc, argv, "IR")) != -1) {
6446 switch (ch) {
6447 case 'I':
6448 no_ignores = 1;
6449 break;
6450 case 'R':
6451 can_recurse = 1;
6452 break;
6453 default:
6454 usage_add();
6455 /* NOTREACHED */
6459 argc -= optind;
6460 argv += optind;
6462 #ifndef PROFILE
6463 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6464 NULL) == -1)
6465 err(1, "pledge");
6466 #endif
6467 if (argc < 1)
6468 usage_add();
6470 cwd = getcwd(NULL, 0);
6471 if (cwd == NULL) {
6472 error = got_error_from_errno("getcwd");
6473 goto done;
6476 error = got_worktree_open(&worktree, cwd);
6477 if (error) {
6478 if (error->code == GOT_ERR_NOT_WORKTREE)
6479 error = wrap_not_worktree_error(error, "add", cwd);
6480 goto done;
6483 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6484 NULL);
6485 if (error != NULL)
6486 goto done;
6488 error = apply_unveil(got_repo_get_path(repo), 1,
6489 got_worktree_get_root_path(worktree));
6490 if (error)
6491 goto done;
6493 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6494 if (error)
6495 goto done;
6497 if (!can_recurse && no_ignores) {
6498 error = got_error_msg(GOT_ERR_BAD_PATH,
6499 "disregarding ignores requires -R option");
6500 goto done;
6504 if (!can_recurse) {
6505 char *ondisk_path;
6506 struct stat sb;
6507 TAILQ_FOREACH(pe, &paths, entry) {
6508 if (asprintf(&ondisk_path, "%s/%s",
6509 got_worktree_get_root_path(worktree),
6510 pe->path) == -1) {
6511 error = got_error_from_errno("asprintf");
6512 goto done;
6514 if (lstat(ondisk_path, &sb) == -1) {
6515 if (errno == ENOENT) {
6516 free(ondisk_path);
6517 continue;
6519 error = got_error_from_errno2("lstat",
6520 ondisk_path);
6521 free(ondisk_path);
6522 goto done;
6524 free(ondisk_path);
6525 if (S_ISDIR(sb.st_mode)) {
6526 error = got_error_msg(GOT_ERR_BAD_PATH,
6527 "adding directories requires -R option");
6528 goto done;
6533 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6534 NULL, repo, no_ignores);
6535 done:
6536 if (repo) {
6537 const struct got_error *close_err = got_repo_close(repo);
6538 if (error == NULL)
6539 error = close_err;
6541 if (worktree)
6542 got_worktree_close(worktree);
6543 TAILQ_FOREACH(pe, &paths, entry)
6544 free((char *)pe->path);
6545 got_pathlist_free(&paths);
6546 free(cwd);
6547 return error;
6550 __dead static void
6551 usage_remove(void)
6553 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6554 "path ...\n", getprogname());
6555 exit(1);
6558 static const struct got_error *
6559 print_remove_status(void *arg, unsigned char status,
6560 unsigned char staged_status, const char *path)
6562 while (path[0] == '/')
6563 path++;
6564 if (status == GOT_STATUS_NONEXISTENT)
6565 return NULL;
6566 if (status == staged_status && (status == GOT_STATUS_DELETE))
6567 status = GOT_STATUS_NO_CHANGE;
6568 printf("%c%c %s\n", status, staged_status, path);
6569 return NULL;
6572 static const struct got_error *
6573 cmd_remove(int argc, char *argv[])
6575 const struct got_error *error = NULL;
6576 struct got_worktree *worktree = NULL;
6577 struct got_repository *repo = NULL;
6578 const char *status_codes = NULL;
6579 char *cwd = NULL;
6580 struct got_pathlist_head paths;
6581 struct got_pathlist_entry *pe;
6582 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6584 TAILQ_INIT(&paths);
6586 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6587 switch (ch) {
6588 case 'f':
6589 delete_local_mods = 1;
6590 break;
6591 case 'k':
6592 keep_on_disk = 1;
6593 break;
6594 case 'R':
6595 can_recurse = 1;
6596 break;
6597 case 's':
6598 for (i = 0; i < strlen(optarg); i++) {
6599 switch (optarg[i]) {
6600 case GOT_STATUS_MODIFY:
6601 delete_local_mods = 1;
6602 break;
6603 case GOT_STATUS_MISSING:
6604 break;
6605 default:
6606 errx(1, "invalid status code '%c'",
6607 optarg[i]);
6610 status_codes = optarg;
6611 break;
6612 default:
6613 usage_remove();
6614 /* NOTREACHED */
6618 argc -= optind;
6619 argv += optind;
6621 #ifndef PROFILE
6622 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6623 NULL) == -1)
6624 err(1, "pledge");
6625 #endif
6626 if (argc < 1)
6627 usage_remove();
6629 cwd = getcwd(NULL, 0);
6630 if (cwd == NULL) {
6631 error = got_error_from_errno("getcwd");
6632 goto done;
6634 error = got_worktree_open(&worktree, cwd);
6635 if (error) {
6636 if (error->code == GOT_ERR_NOT_WORKTREE)
6637 error = wrap_not_worktree_error(error, "remove", cwd);
6638 goto done;
6641 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6642 NULL);
6643 if (error)
6644 goto done;
6646 error = apply_unveil(got_repo_get_path(repo), 1,
6647 got_worktree_get_root_path(worktree));
6648 if (error)
6649 goto done;
6651 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6652 if (error)
6653 goto done;
6655 if (!can_recurse) {
6656 char *ondisk_path;
6657 struct stat sb;
6658 TAILQ_FOREACH(pe, &paths, entry) {
6659 if (asprintf(&ondisk_path, "%s/%s",
6660 got_worktree_get_root_path(worktree),
6661 pe->path) == -1) {
6662 error = got_error_from_errno("asprintf");
6663 goto done;
6665 if (lstat(ondisk_path, &sb) == -1) {
6666 if (errno == ENOENT) {
6667 free(ondisk_path);
6668 continue;
6670 error = got_error_from_errno2("lstat",
6671 ondisk_path);
6672 free(ondisk_path);
6673 goto done;
6675 free(ondisk_path);
6676 if (S_ISDIR(sb.st_mode)) {
6677 error = got_error_msg(GOT_ERR_BAD_PATH,
6678 "removing directories requires -R option");
6679 goto done;
6684 error = got_worktree_schedule_delete(worktree, &paths,
6685 delete_local_mods, status_codes, print_remove_status, NULL,
6686 repo, keep_on_disk);
6687 done:
6688 if (repo) {
6689 const struct got_error *close_err = got_repo_close(repo);
6690 if (error == NULL)
6691 error = close_err;
6693 if (worktree)
6694 got_worktree_close(worktree);
6695 TAILQ_FOREACH(pe, &paths, entry)
6696 free((char *)pe->path);
6697 got_pathlist_free(&paths);
6698 free(cwd);
6699 return error;
6702 __dead static void
6703 usage_revert(void)
6705 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6706 "path ...\n", getprogname());
6707 exit(1);
6710 static const struct got_error *
6711 revert_progress(void *arg, unsigned char status, const char *path)
6713 if (status == GOT_STATUS_UNVERSIONED)
6714 return NULL;
6716 while (path[0] == '/')
6717 path++;
6718 printf("%c %s\n", status, path);
6719 return NULL;
6722 struct choose_patch_arg {
6723 FILE *patch_script_file;
6724 const char *action;
6727 static const struct got_error *
6728 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6729 int nchanges, const char *action)
6731 char *line = NULL;
6732 size_t linesize = 0;
6733 ssize_t linelen;
6735 switch (status) {
6736 case GOT_STATUS_ADD:
6737 printf("A %s\n%s this addition? [y/n] ", path, action);
6738 break;
6739 case GOT_STATUS_DELETE:
6740 printf("D %s\n%s this deletion? [y/n] ", path, action);
6741 break;
6742 case GOT_STATUS_MODIFY:
6743 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6744 return got_error_from_errno("fseek");
6745 printf(GOT_COMMIT_SEP_STR);
6746 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6747 printf("%s", line);
6748 if (ferror(patch_file))
6749 return got_error_from_errno("getline");
6750 printf(GOT_COMMIT_SEP_STR);
6751 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6752 path, n, nchanges, action);
6753 break;
6754 default:
6755 return got_error_path(path, GOT_ERR_FILE_STATUS);
6758 return NULL;
6761 static const struct got_error *
6762 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6763 FILE *patch_file, int n, int nchanges)
6765 const struct got_error *err = NULL;
6766 char *line = NULL;
6767 size_t linesize = 0;
6768 ssize_t linelen;
6769 int resp = ' ';
6770 struct choose_patch_arg *a = arg;
6772 *choice = GOT_PATCH_CHOICE_NONE;
6774 if (a->patch_script_file) {
6775 char *nl;
6776 err = show_change(status, path, patch_file, n, nchanges,
6777 a->action);
6778 if (err)
6779 return err;
6780 linelen = getline(&line, &linesize, a->patch_script_file);
6781 if (linelen == -1) {
6782 if (ferror(a->patch_script_file))
6783 return got_error_from_errno("getline");
6784 return NULL;
6786 nl = strchr(line, '\n');
6787 if (nl)
6788 *nl = '\0';
6789 if (strcmp(line, "y") == 0) {
6790 *choice = GOT_PATCH_CHOICE_YES;
6791 printf("y\n");
6792 } else if (strcmp(line, "n") == 0) {
6793 *choice = GOT_PATCH_CHOICE_NO;
6794 printf("n\n");
6795 } else if (strcmp(line, "q") == 0 &&
6796 status == GOT_STATUS_MODIFY) {
6797 *choice = GOT_PATCH_CHOICE_QUIT;
6798 printf("q\n");
6799 } else
6800 printf("invalid response '%s'\n", line);
6801 free(line);
6802 return NULL;
6805 while (resp != 'y' && resp != 'n' && resp != 'q') {
6806 err = show_change(status, path, patch_file, n, nchanges,
6807 a->action);
6808 if (err)
6809 return err;
6810 resp = getchar();
6811 if (resp == '\n')
6812 resp = getchar();
6813 if (status == GOT_STATUS_MODIFY) {
6814 if (resp != 'y' && resp != 'n' && resp != 'q') {
6815 printf("invalid response '%c'\n", resp);
6816 resp = ' ';
6818 } else if (resp != 'y' && resp != 'n') {
6819 printf("invalid response '%c'\n", resp);
6820 resp = ' ';
6824 if (resp == 'y')
6825 *choice = GOT_PATCH_CHOICE_YES;
6826 else if (resp == 'n')
6827 *choice = GOT_PATCH_CHOICE_NO;
6828 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6829 *choice = GOT_PATCH_CHOICE_QUIT;
6831 return NULL;
6835 static const struct got_error *
6836 cmd_revert(int argc, char *argv[])
6838 const struct got_error *error = NULL;
6839 struct got_worktree *worktree = NULL;
6840 struct got_repository *repo = NULL;
6841 char *cwd = NULL, *path = NULL;
6842 struct got_pathlist_head paths;
6843 struct got_pathlist_entry *pe;
6844 int ch, can_recurse = 0, pflag = 0;
6845 FILE *patch_script_file = NULL;
6846 const char *patch_script_path = NULL;
6847 struct choose_patch_arg cpa;
6849 TAILQ_INIT(&paths);
6851 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6852 switch (ch) {
6853 case 'p':
6854 pflag = 1;
6855 break;
6856 case 'F':
6857 patch_script_path = optarg;
6858 break;
6859 case 'R':
6860 can_recurse = 1;
6861 break;
6862 default:
6863 usage_revert();
6864 /* NOTREACHED */
6868 argc -= optind;
6869 argv += optind;
6871 #ifndef PROFILE
6872 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6873 "unveil", NULL) == -1)
6874 err(1, "pledge");
6875 #endif
6876 if (argc < 1)
6877 usage_revert();
6878 if (patch_script_path && !pflag)
6879 errx(1, "-F option can only be used together with -p option");
6881 cwd = getcwd(NULL, 0);
6882 if (cwd == NULL) {
6883 error = got_error_from_errno("getcwd");
6884 goto done;
6886 error = got_worktree_open(&worktree, cwd);
6887 if (error) {
6888 if (error->code == GOT_ERR_NOT_WORKTREE)
6889 error = wrap_not_worktree_error(error, "revert", cwd);
6890 goto done;
6893 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6894 NULL);
6895 if (error != NULL)
6896 goto done;
6898 if (patch_script_path) {
6899 patch_script_file = fopen(patch_script_path, "r");
6900 if (patch_script_file == NULL) {
6901 error = got_error_from_errno2("fopen",
6902 patch_script_path);
6903 goto done;
6906 error = apply_unveil(got_repo_get_path(repo), 1,
6907 got_worktree_get_root_path(worktree));
6908 if (error)
6909 goto done;
6911 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6912 if (error)
6913 goto done;
6915 if (!can_recurse) {
6916 char *ondisk_path;
6917 struct stat sb;
6918 TAILQ_FOREACH(pe, &paths, entry) {
6919 if (asprintf(&ondisk_path, "%s/%s",
6920 got_worktree_get_root_path(worktree),
6921 pe->path) == -1) {
6922 error = got_error_from_errno("asprintf");
6923 goto done;
6925 if (lstat(ondisk_path, &sb) == -1) {
6926 if (errno == ENOENT) {
6927 free(ondisk_path);
6928 continue;
6930 error = got_error_from_errno2("lstat",
6931 ondisk_path);
6932 free(ondisk_path);
6933 goto done;
6935 free(ondisk_path);
6936 if (S_ISDIR(sb.st_mode)) {
6937 error = got_error_msg(GOT_ERR_BAD_PATH,
6938 "reverting directories requires -R option");
6939 goto done;
6944 cpa.patch_script_file = patch_script_file;
6945 cpa.action = "revert";
6946 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6947 pflag ? choose_patch : NULL, &cpa, repo);
6948 done:
6949 if (patch_script_file && fclose(patch_script_file) == EOF &&
6950 error == NULL)
6951 error = got_error_from_errno2("fclose", patch_script_path);
6952 if (repo) {
6953 const struct got_error *close_err = got_repo_close(repo);
6954 if (error == NULL)
6955 error = close_err;
6957 if (worktree)
6958 got_worktree_close(worktree);
6959 free(path);
6960 free(cwd);
6961 return error;
6964 __dead static void
6965 usage_commit(void)
6967 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
6968 "[path ...]\n", getprogname());
6969 exit(1);
6972 struct collect_commit_logmsg_arg {
6973 const char *cmdline_log;
6974 const char *prepared_log;
6975 int non_interactive;
6976 const char *editor;
6977 const char *worktree_path;
6978 const char *branch_name;
6979 const char *repo_path;
6980 char *logmsg_path;
6984 static const struct got_error *
6985 read_prepared_logmsg(char **logmsg, const char *path)
6987 const struct got_error *err = NULL;
6988 FILE *f = NULL;
6989 struct stat sb;
6990 size_t r;
6992 *logmsg = NULL;
6993 memset(&sb, 0, sizeof(sb));
6995 f = fopen(path, "r");
6996 if (f == NULL)
6997 return got_error_from_errno2("fopen", path);
6999 if (fstat(fileno(f), &sb) == -1) {
7000 err = got_error_from_errno2("fstat", path);
7001 goto done;
7003 if (sb.st_size == 0) {
7004 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7005 goto done;
7008 *logmsg = malloc(sb.st_size + 1);
7009 if (*logmsg == NULL) {
7010 err = got_error_from_errno("malloc");
7011 goto done;
7014 r = fread(*logmsg, 1, sb.st_size, f);
7015 if (r != sb.st_size) {
7016 if (ferror(f))
7017 err = got_error_from_errno2("fread", path);
7018 else
7019 err = got_error(GOT_ERR_IO);
7020 goto done;
7022 (*logmsg)[sb.st_size] = '\0';
7023 done:
7024 if (fclose(f) == EOF && err == NULL)
7025 err = got_error_from_errno2("fclose", path);
7026 if (err) {
7027 free(*logmsg);
7028 *logmsg = NULL;
7030 return err;
7034 static const struct got_error *
7035 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7036 void *arg)
7038 char *initial_content = NULL;
7039 struct got_pathlist_entry *pe;
7040 const struct got_error *err = NULL;
7041 char *template = NULL;
7042 struct collect_commit_logmsg_arg *a = arg;
7043 int initial_content_len;
7044 int fd = -1;
7045 size_t len;
7047 /* if a message was specified on the command line, just use it */
7048 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7049 len = strlen(a->cmdline_log) + 1;
7050 *logmsg = malloc(len + 1);
7051 if (*logmsg == NULL)
7052 return got_error_from_errno("malloc");
7053 strlcpy(*logmsg, a->cmdline_log, len);
7054 return NULL;
7055 } else if (a->prepared_log != NULL && a->non_interactive)
7056 return read_prepared_logmsg(logmsg, a->prepared_log);
7058 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7059 return got_error_from_errno("asprintf");
7061 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7062 if (err)
7063 goto done;
7065 if (a->prepared_log) {
7066 char *msg;
7067 err = read_prepared_logmsg(&msg, a->prepared_log);
7068 if (err)
7069 goto done;
7070 if (write(fd, msg, strlen(msg)) == -1) {
7071 err = got_error_from_errno2("write", a->logmsg_path);
7072 free(msg);
7073 goto done;
7075 free(msg);
7078 initial_content_len = asprintf(&initial_content,
7079 "\n# changes to be committed on branch %s:\n",
7080 a->branch_name);
7081 if (initial_content_len == -1) {
7082 err = got_error_from_errno("asprintf");
7083 goto done;
7086 if (write(fd, initial_content, initial_content_len) == -1) {
7087 err = got_error_from_errno2("write", a->logmsg_path);
7088 goto done;
7091 TAILQ_FOREACH(pe, commitable_paths, entry) {
7092 struct got_commitable *ct = pe->data;
7093 dprintf(fd, "# %c %s\n",
7094 got_commitable_get_status(ct),
7095 got_commitable_get_path(ct));
7098 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7099 initial_content_len, a->prepared_log ? 0 : 1);
7100 done:
7101 free(initial_content);
7102 free(template);
7104 if (fd != -1 && close(fd) == -1 && err == NULL)
7105 err = got_error_from_errno2("close", a->logmsg_path);
7107 /* Editor is done; we can now apply unveil(2) */
7108 if (err == NULL)
7109 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7110 if (err) {
7111 free(*logmsg);
7112 *logmsg = NULL;
7114 return err;
7117 static const struct got_error *
7118 cmd_commit(int argc, char *argv[])
7120 const struct got_error *error = NULL;
7121 struct got_worktree *worktree = NULL;
7122 struct got_repository *repo = NULL;
7123 char *cwd = NULL, *id_str = NULL;
7124 struct got_object_id *id = NULL;
7125 const char *logmsg = NULL;
7126 char *prepared_logmsg = NULL;
7127 struct collect_commit_logmsg_arg cl_arg;
7128 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7129 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7130 int allow_bad_symlinks = 0, non_interactive = 0;
7131 struct got_pathlist_head paths;
7133 TAILQ_INIT(&paths);
7134 cl_arg.logmsg_path = NULL;
7136 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7137 switch (ch) {
7138 case 'F':
7139 if (logmsg != NULL)
7140 option_conflict('F', 'm');
7141 prepared_logmsg = realpath(optarg, NULL);
7142 if (prepared_logmsg == NULL)
7143 return got_error_from_errno2("realpath",
7144 optarg);
7145 break;
7146 case 'm':
7147 if (prepared_logmsg)
7148 option_conflict('m', 'F');
7149 logmsg = optarg;
7150 break;
7151 case 'N':
7152 non_interactive = 1;
7153 break;
7154 case 'S':
7155 allow_bad_symlinks = 1;
7156 break;
7157 default:
7158 usage_commit();
7159 /* NOTREACHED */
7163 argc -= optind;
7164 argv += optind;
7166 #ifndef PROFILE
7167 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7168 "unveil", NULL) == -1)
7169 err(1, "pledge");
7170 #endif
7171 cwd = getcwd(NULL, 0);
7172 if (cwd == NULL) {
7173 error = got_error_from_errno("getcwd");
7174 goto done;
7176 error = got_worktree_open(&worktree, cwd);
7177 if (error) {
7178 if (error->code == GOT_ERR_NOT_WORKTREE)
7179 error = wrap_not_worktree_error(error, "commit", cwd);
7180 goto done;
7183 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7184 if (error)
7185 goto done;
7186 if (rebase_in_progress) {
7187 error = got_error(GOT_ERR_REBASING);
7188 goto done;
7191 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7192 worktree);
7193 if (error)
7194 goto done;
7196 error = get_gitconfig_path(&gitconfig_path);
7197 if (error)
7198 goto done;
7199 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7200 gitconfig_path);
7201 if (error != NULL)
7202 goto done;
7204 error = get_author(&author, repo, worktree);
7205 if (error)
7206 return error;
7209 * unveil(2) traverses exec(2); if an editor is used we have
7210 * to apply unveil after the log message has been written.
7212 if (logmsg == NULL || strlen(logmsg) == 0)
7213 error = get_editor(&editor);
7214 else
7215 error = apply_unveil(got_repo_get_path(repo), 0,
7216 got_worktree_get_root_path(worktree));
7217 if (error)
7218 goto done;
7220 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7221 if (error)
7222 goto done;
7224 cl_arg.editor = editor;
7225 cl_arg.cmdline_log = logmsg;
7226 cl_arg.prepared_log = prepared_logmsg;
7227 cl_arg.non_interactive = non_interactive;
7228 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7229 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7230 if (!histedit_in_progress) {
7231 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7232 error = got_error(GOT_ERR_COMMIT_BRANCH);
7233 goto done;
7235 cl_arg.branch_name += 11;
7237 cl_arg.repo_path = got_repo_get_path(repo);
7238 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7239 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7240 print_status, NULL, repo);
7241 if (error) {
7242 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7243 cl_arg.logmsg_path != NULL)
7244 preserve_logmsg = 1;
7245 goto done;
7248 error = got_object_id_str(&id_str, id);
7249 if (error)
7250 goto done;
7251 printf("Created commit %s\n", id_str);
7252 done:
7253 if (preserve_logmsg) {
7254 fprintf(stderr, "%s: log message preserved in %s\n",
7255 getprogname(), cl_arg.logmsg_path);
7256 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7257 error == NULL)
7258 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7259 free(cl_arg.logmsg_path);
7260 if (repo) {
7261 const struct got_error *close_err = got_repo_close(repo);
7262 if (error == NULL)
7263 error = close_err;
7265 if (worktree)
7266 got_worktree_close(worktree);
7267 free(cwd);
7268 free(id_str);
7269 free(gitconfig_path);
7270 free(editor);
7271 free(author);
7272 free(prepared_logmsg);
7273 return error;
7276 __dead static void
7277 usage_cherrypick(void)
7279 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7280 exit(1);
7283 static const struct got_error *
7284 cmd_cherrypick(int argc, char *argv[])
7286 const struct got_error *error = NULL;
7287 struct got_worktree *worktree = NULL;
7288 struct got_repository *repo = NULL;
7289 char *cwd = NULL, *commit_id_str = NULL;
7290 struct got_object_id *commit_id = NULL;
7291 struct got_commit_object *commit = NULL;
7292 struct got_object_qid *pid;
7293 struct got_reference *head_ref = NULL;
7294 int ch;
7295 struct got_update_progress_arg upa;
7297 while ((ch = getopt(argc, argv, "")) != -1) {
7298 switch (ch) {
7299 default:
7300 usage_cherrypick();
7301 /* NOTREACHED */
7305 argc -= optind;
7306 argv += optind;
7308 #ifndef PROFILE
7309 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7310 "unveil", NULL) == -1)
7311 err(1, "pledge");
7312 #endif
7313 if (argc != 1)
7314 usage_cherrypick();
7316 cwd = getcwd(NULL, 0);
7317 if (cwd == NULL) {
7318 error = got_error_from_errno("getcwd");
7319 goto done;
7321 error = got_worktree_open(&worktree, cwd);
7322 if (error) {
7323 if (error->code == GOT_ERR_NOT_WORKTREE)
7324 error = wrap_not_worktree_error(error, "cherrypick",
7325 cwd);
7326 goto done;
7329 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7330 NULL);
7331 if (error != NULL)
7332 goto done;
7334 error = apply_unveil(got_repo_get_path(repo), 0,
7335 got_worktree_get_root_path(worktree));
7336 if (error)
7337 goto done;
7339 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7340 GOT_OBJ_TYPE_COMMIT, repo);
7341 if (error != NULL) {
7342 struct got_reference *ref;
7343 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7344 goto done;
7345 error = got_ref_open(&ref, repo, argv[0], 0);
7346 if (error != NULL)
7347 goto done;
7348 error = got_ref_resolve(&commit_id, repo, ref);
7349 got_ref_close(ref);
7350 if (error != NULL)
7351 goto done;
7353 error = got_object_id_str(&commit_id_str, commit_id);
7354 if (error)
7355 goto done;
7357 error = got_ref_open(&head_ref, repo,
7358 got_worktree_get_head_ref_name(worktree), 0);
7359 if (error != NULL)
7360 goto done;
7362 error = check_same_branch(commit_id, head_ref, NULL, repo);
7363 if (error) {
7364 if (error->code != GOT_ERR_ANCESTRY)
7365 goto done;
7366 error = NULL;
7367 } else {
7368 error = got_error(GOT_ERR_SAME_BRANCH);
7369 goto done;
7372 error = got_object_open_as_commit(&commit, repo, commit_id);
7373 if (error)
7374 goto done;
7375 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7376 memset(&upa, 0, sizeof(upa));
7377 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7378 commit_id, repo, update_progress, &upa, check_cancelled,
7379 NULL);
7380 if (error != NULL)
7381 goto done;
7383 if (upa.did_something)
7384 printf("Merged commit %s\n", commit_id_str);
7385 print_update_progress_stats(&upa);
7386 done:
7387 if (commit)
7388 got_object_commit_close(commit);
7389 free(commit_id_str);
7390 if (head_ref)
7391 got_ref_close(head_ref);
7392 if (worktree)
7393 got_worktree_close(worktree);
7394 if (repo) {
7395 const struct got_error *close_err = got_repo_close(repo);
7396 if (error == NULL)
7397 error = close_err;
7399 return error;
7402 __dead static void
7403 usage_backout(void)
7405 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7406 exit(1);
7409 static const struct got_error *
7410 cmd_backout(int argc, char *argv[])
7412 const struct got_error *error = NULL;
7413 struct got_worktree *worktree = NULL;
7414 struct got_repository *repo = NULL;
7415 char *cwd = NULL, *commit_id_str = NULL;
7416 struct got_object_id *commit_id = NULL;
7417 struct got_commit_object *commit = NULL;
7418 struct got_object_qid *pid;
7419 struct got_reference *head_ref = NULL;
7420 int ch;
7421 struct got_update_progress_arg upa;
7423 while ((ch = getopt(argc, argv, "")) != -1) {
7424 switch (ch) {
7425 default:
7426 usage_backout();
7427 /* NOTREACHED */
7431 argc -= optind;
7432 argv += optind;
7434 #ifndef PROFILE
7435 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7436 "unveil", NULL) == -1)
7437 err(1, "pledge");
7438 #endif
7439 if (argc != 1)
7440 usage_backout();
7442 cwd = getcwd(NULL, 0);
7443 if (cwd == NULL) {
7444 error = got_error_from_errno("getcwd");
7445 goto done;
7447 error = got_worktree_open(&worktree, cwd);
7448 if (error) {
7449 if (error->code == GOT_ERR_NOT_WORKTREE)
7450 error = wrap_not_worktree_error(error, "backout", cwd);
7451 goto done;
7454 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7455 NULL);
7456 if (error != NULL)
7457 goto done;
7459 error = apply_unveil(got_repo_get_path(repo), 0,
7460 got_worktree_get_root_path(worktree));
7461 if (error)
7462 goto done;
7464 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7465 GOT_OBJ_TYPE_COMMIT, repo);
7466 if (error != NULL) {
7467 struct got_reference *ref;
7468 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7469 goto done;
7470 error = got_ref_open(&ref, repo, argv[0], 0);
7471 if (error != NULL)
7472 goto done;
7473 error = got_ref_resolve(&commit_id, repo, ref);
7474 got_ref_close(ref);
7475 if (error != NULL)
7476 goto done;
7478 error = got_object_id_str(&commit_id_str, commit_id);
7479 if (error)
7480 goto done;
7482 error = got_ref_open(&head_ref, repo,
7483 got_worktree_get_head_ref_name(worktree), 0);
7484 if (error != NULL)
7485 goto done;
7487 error = check_same_branch(commit_id, head_ref, NULL, repo);
7488 if (error)
7489 goto done;
7491 error = got_object_open_as_commit(&commit, repo, commit_id);
7492 if (error)
7493 goto done;
7494 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7495 if (pid == NULL) {
7496 error = got_error(GOT_ERR_ROOT_COMMIT);
7497 goto done;
7500 memset(&upa, 0, sizeof(upa));
7501 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7502 update_progress, &upa, check_cancelled, NULL);
7503 if (error != NULL)
7504 goto done;
7506 if (upa.did_something)
7507 printf("Backed out commit %s\n", commit_id_str);
7508 print_update_progress_stats(&upa);
7509 done:
7510 if (commit)
7511 got_object_commit_close(commit);
7512 free(commit_id_str);
7513 if (head_ref)
7514 got_ref_close(head_ref);
7515 if (worktree)
7516 got_worktree_close(worktree);
7517 if (repo) {
7518 const struct got_error *close_err = got_repo_close(repo);
7519 if (error == NULL)
7520 error = close_err;
7522 return error;
7525 __dead static void
7526 usage_rebase(void)
7528 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [branch]\n",
7529 getprogname());
7530 exit(1);
7533 void
7534 trim_logmsg(char *logmsg, int limit)
7536 char *nl;
7537 size_t len;
7539 len = strlen(logmsg);
7540 if (len > limit)
7541 len = limit;
7542 logmsg[len] = '\0';
7543 nl = strchr(logmsg, '\n');
7544 if (nl)
7545 *nl = '\0';
7548 static const struct got_error *
7549 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7551 const struct got_error *err;
7552 char *logmsg0 = NULL;
7553 const char *s;
7555 err = got_object_commit_get_logmsg(&logmsg0, commit);
7556 if (err)
7557 return err;
7559 s = logmsg0;
7560 while (isspace((unsigned char)s[0]))
7561 s++;
7563 *logmsg = strdup(s);
7564 if (*logmsg == NULL) {
7565 err = got_error_from_errno("strdup");
7566 goto done;
7569 trim_logmsg(*logmsg, limit);
7570 done:
7571 free(logmsg0);
7572 return err;
7575 static const struct got_error *
7576 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7578 const struct got_error *err;
7579 struct got_commit_object *commit = NULL;
7580 char *id_str = NULL, *logmsg = NULL;
7582 err = got_object_open_as_commit(&commit, repo, id);
7583 if (err)
7584 return err;
7586 err = got_object_id_str(&id_str, id);
7587 if (err)
7588 goto done;
7590 id_str[12] = '\0';
7592 err = get_short_logmsg(&logmsg, 42, commit);
7593 if (err)
7594 goto done;
7596 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7597 done:
7598 free(id_str);
7599 got_object_commit_close(commit);
7600 free(logmsg);
7601 return err;
7604 static const struct got_error *
7605 show_rebase_progress(struct got_commit_object *commit,
7606 struct got_object_id *old_id, struct got_object_id *new_id)
7608 const struct got_error *err;
7609 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7611 err = got_object_id_str(&old_id_str, old_id);
7612 if (err)
7613 goto done;
7615 if (new_id) {
7616 err = got_object_id_str(&new_id_str, new_id);
7617 if (err)
7618 goto done;
7621 old_id_str[12] = '\0';
7622 if (new_id_str)
7623 new_id_str[12] = '\0';
7625 err = get_short_logmsg(&logmsg, 42, commit);
7626 if (err)
7627 goto done;
7629 printf("%s -> %s: %s\n", old_id_str,
7630 new_id_str ? new_id_str : "no-op change", logmsg);
7631 done:
7632 free(old_id_str);
7633 free(new_id_str);
7634 free(logmsg);
7635 return err;
7638 static const struct got_error *
7639 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7640 struct got_reference *branch, struct got_reference *new_base_branch,
7641 struct got_reference *tmp_branch, struct got_repository *repo,
7642 int create_backup)
7644 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7645 return got_worktree_rebase_complete(worktree, fileindex,
7646 new_base_branch, tmp_branch, branch, repo, create_backup);
7649 static const struct got_error *
7650 rebase_commit(struct got_pathlist_head *merged_paths,
7651 struct got_worktree *worktree, struct got_fileindex *fileindex,
7652 struct got_reference *tmp_branch,
7653 struct got_object_id *commit_id, struct got_repository *repo)
7655 const struct got_error *error;
7656 struct got_commit_object *commit;
7657 struct got_object_id *new_commit_id;
7659 error = got_object_open_as_commit(&commit, repo, commit_id);
7660 if (error)
7661 return error;
7663 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7664 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7665 if (error) {
7666 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7667 goto done;
7668 error = show_rebase_progress(commit, commit_id, NULL);
7669 } else {
7670 error = show_rebase_progress(commit, commit_id, new_commit_id);
7671 free(new_commit_id);
7673 done:
7674 got_object_commit_close(commit);
7675 return error;
7678 struct check_path_prefix_arg {
7679 const char *path_prefix;
7680 size_t len;
7681 int errcode;
7684 static const struct got_error *
7685 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7686 struct got_blob_object *blob2, struct got_object_id *id1,
7687 struct got_object_id *id2, const char *path1, const char *path2,
7688 mode_t mode1, mode_t mode2, struct got_repository *repo)
7690 struct check_path_prefix_arg *a = arg;
7692 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7693 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7694 return got_error(a->errcode);
7696 return NULL;
7699 static const struct got_error *
7700 check_path_prefix(struct got_object_id *parent_id,
7701 struct got_object_id *commit_id, const char *path_prefix,
7702 int errcode, struct got_repository *repo)
7704 const struct got_error *err;
7705 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7706 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7707 struct check_path_prefix_arg cpp_arg;
7709 if (got_path_is_root_dir(path_prefix))
7710 return NULL;
7712 err = got_object_open_as_commit(&commit, repo, commit_id);
7713 if (err)
7714 goto done;
7716 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7717 if (err)
7718 goto done;
7720 err = got_object_open_as_tree(&tree1, repo,
7721 got_object_commit_get_tree_id(parent_commit));
7722 if (err)
7723 goto done;
7725 err = got_object_open_as_tree(&tree2, repo,
7726 got_object_commit_get_tree_id(commit));
7727 if (err)
7728 goto done;
7730 cpp_arg.path_prefix = path_prefix;
7731 while (cpp_arg.path_prefix[0] == '/')
7732 cpp_arg.path_prefix++;
7733 cpp_arg.len = strlen(cpp_arg.path_prefix);
7734 cpp_arg.errcode = errcode;
7735 err = got_diff_tree(tree1, tree2, "", "", repo,
7736 check_path_prefix_in_diff, &cpp_arg, 0);
7737 done:
7738 if (tree1)
7739 got_object_tree_close(tree1);
7740 if (tree2)
7741 got_object_tree_close(tree2);
7742 if (commit)
7743 got_object_commit_close(commit);
7744 if (parent_commit)
7745 got_object_commit_close(parent_commit);
7746 return err;
7749 static const struct got_error *
7750 collect_commits(struct got_object_id_queue *commits,
7751 struct got_object_id *initial_commit_id,
7752 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7753 const char *path_prefix, int path_prefix_errcode,
7754 struct got_repository *repo)
7756 const struct got_error *err = NULL;
7757 struct got_commit_graph *graph = NULL;
7758 struct got_object_id *parent_id = NULL;
7759 struct got_object_qid *qid;
7760 struct got_object_id *commit_id = initial_commit_id;
7762 err = got_commit_graph_open(&graph, "/", 1);
7763 if (err)
7764 return err;
7766 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7767 check_cancelled, NULL);
7768 if (err)
7769 goto done;
7770 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7771 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7772 check_cancelled, NULL);
7773 if (err) {
7774 if (err->code == GOT_ERR_ITER_COMPLETED) {
7775 err = got_error_msg(GOT_ERR_ANCESTRY,
7776 "ran out of commits to rebase before "
7777 "youngest common ancestor commit has "
7778 "been reached?!?");
7780 goto done;
7781 } else {
7782 err = check_path_prefix(parent_id, commit_id,
7783 path_prefix, path_prefix_errcode, repo);
7784 if (err)
7785 goto done;
7787 err = got_object_qid_alloc(&qid, commit_id);
7788 if (err)
7789 goto done;
7790 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7791 commit_id = parent_id;
7794 done:
7795 got_commit_graph_close(graph);
7796 return err;
7799 static const struct got_error *
7800 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
7802 const struct got_error *err = NULL;
7803 time_t committer_time;
7804 struct tm tm;
7805 char datebuf[11]; /* YYYY-MM-DD + NUL */
7806 char *author0 = NULL, *author, *smallerthan;
7807 char *logmsg0 = NULL, *logmsg, *newline;
7809 committer_time = got_object_commit_get_committer_time(commit);
7810 if (localtime_r(&committer_time, &tm) == NULL)
7811 return got_error_from_errno("localtime_r");
7812 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
7813 return got_error(GOT_ERR_NO_SPACE);
7815 author0 = strdup(got_object_commit_get_author(commit));
7816 if (author0 == NULL)
7817 return got_error_from_errno("strdup");
7818 author = author0;
7819 smallerthan = strchr(author, '<');
7820 if (smallerthan && smallerthan[1] != '\0')
7821 author = smallerthan + 1;
7822 author[strcspn(author, "@>")] = '\0';
7824 err = got_object_commit_get_logmsg(&logmsg0, commit);
7825 if (err)
7826 goto done;
7827 logmsg = logmsg0;
7828 while (*logmsg == '\n')
7829 logmsg++;
7830 newline = strchr(logmsg, '\n');
7831 if (newline)
7832 *newline = '\0';
7834 if (asprintf(brief_str, "%s %s %s",
7835 datebuf, author, logmsg) == -1)
7836 err = got_error_from_errno("asprintf");
7837 done:
7838 free(author0);
7839 free(logmsg0);
7840 return err;
7843 static const struct got_error *
7844 print_backup_ref(const char *branch_name, const char *new_id_str,
7845 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
7846 struct got_reflist_object_id_map *refs_idmap,
7847 struct got_repository *repo)
7849 const struct got_error *err = NULL;
7850 struct got_reflist_head *refs;
7851 char *refs_str = NULL;
7852 struct got_object_id *new_commit_id = NULL;
7853 struct got_commit_object *new_commit = NULL;
7854 char *new_commit_brief_str = NULL;
7855 struct got_object_id *yca_id = NULL;
7856 struct got_commit_object *yca_commit = NULL;
7857 char *yca_id_str = NULL, *yca_brief_str = NULL;
7858 char *custom_refs_str;
7860 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
7861 return got_error_from_errno("asprintf");
7863 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
7864 0, 0, refs_idmap, custom_refs_str);
7865 if (err)
7866 goto done;
7868 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
7869 if (err)
7870 goto done;
7872 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
7873 if (refs) {
7874 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
7875 if (err)
7876 goto done;
7879 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
7880 if (err)
7881 goto done;
7883 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
7884 if (err)
7885 goto done;
7887 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7888 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
7889 if (err)
7890 goto done;
7892 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
7893 refs_str ? " (" : "", refs_str ? refs_str : "",
7894 refs_str ? ")" : "", new_commit_brief_str);
7895 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
7896 got_object_id_cmp(yca_id, old_commit_id) != 0) {
7897 free(refs_str);
7898 refs_str = NULL;
7900 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
7901 if (err)
7902 goto done;
7904 err = get_commit_brief_str(&yca_brief_str, yca_commit);
7905 if (err)
7906 goto done;
7908 err = got_object_id_str(&yca_id_str, yca_id);
7909 if (err)
7910 goto done;
7912 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
7913 if (refs) {
7914 err = build_refs_str(&refs_str, refs, yca_id, repo);
7915 if (err)
7916 goto done;
7918 printf("history forked at %s%s%s%s\n %s\n",
7919 yca_id_str,
7920 refs_str ? " (" : "", refs_str ? refs_str : "",
7921 refs_str ? ")" : "", yca_brief_str);
7923 done:
7924 free(custom_refs_str);
7925 free(new_commit_id);
7926 free(refs_str);
7927 free(yca_id);
7928 free(yca_id_str);
7929 free(yca_brief_str);
7930 if (new_commit)
7931 got_object_commit_close(new_commit);
7932 if (yca_commit)
7933 got_object_commit_close(yca_commit);
7935 return NULL;
7938 static const struct got_error *
7939 list_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
7940 struct got_repository *repo)
7942 const struct got_error *err;
7943 struct got_reflist_head refs, backup_refs;
7944 struct got_reflist_entry *re;
7945 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
7946 struct got_object_id *old_commit_id = NULL;
7947 char *branch_name = NULL;
7948 struct got_commit_object *old_commit = NULL;
7949 struct got_reflist_object_id_map *refs_idmap = NULL;
7950 int wanted_branch_found = 0;
7952 TAILQ_INIT(&refs);
7953 TAILQ_INIT(&backup_refs);
7955 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7956 if (err)
7957 return err;
7959 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
7960 if (err)
7961 goto done;
7963 if (wanted_branch_name) {
7964 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
7965 wanted_branch_name += 11;
7968 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
7969 got_ref_cmp_by_commit_timestamp_descending, repo);
7970 if (err)
7971 goto done;
7973 TAILQ_FOREACH(re, &backup_refs, entry) {
7974 const char *refname = got_ref_get_name(re->ref);
7975 char *slash;
7977 err = got_ref_resolve(&old_commit_id, repo, re->ref);
7978 if (err)
7979 break;
7981 err = got_object_open_as_commit(&old_commit, repo,
7982 old_commit_id);
7983 if (err)
7984 break;
7986 if (strncmp(backup_ref_prefix, refname,
7987 backup_ref_prefix_len) == 0)
7988 refname += backup_ref_prefix_len;
7990 while (refname[0] == '/')
7991 refname++;
7993 branch_name = strdup(refname);
7994 if (branch_name == NULL) {
7995 err = got_error_from_errno("strdup");
7996 break;
7998 slash = strrchr(branch_name, '/');
7999 if (slash) {
8000 *slash = '\0';
8001 refname += strlen(branch_name) + 1;
8004 if (wanted_branch_name == NULL ||
8005 strcmp(wanted_branch_name, branch_name) == 0) {
8006 wanted_branch_found = 1;
8007 err = print_backup_ref(branch_name, refname,
8008 old_commit_id, old_commit, refs_idmap, repo);
8009 if (err)
8010 break;
8013 free(old_commit_id);
8014 old_commit_id = NULL;
8015 free(branch_name);
8016 branch_name = NULL;
8017 got_object_commit_close(old_commit);
8018 old_commit = NULL;
8021 if (wanted_branch_name && !wanted_branch_found) {
8022 err = got_error_fmt(GOT_ERR_NOT_REF,
8023 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8025 done:
8026 if (refs_idmap)
8027 got_reflist_object_id_map_free(refs_idmap);
8028 got_ref_list_free(&refs);
8029 got_ref_list_free(&backup_refs);
8030 free(old_commit_id);
8031 free(branch_name);
8032 if (old_commit)
8033 got_object_commit_close(old_commit);
8034 return err;
8037 static const struct got_error *
8038 cmd_rebase(int argc, char *argv[])
8040 const struct got_error *error = NULL;
8041 struct got_worktree *worktree = NULL;
8042 struct got_repository *repo = NULL;
8043 struct got_fileindex *fileindex = NULL;
8044 char *cwd = NULL;
8045 struct got_reference *branch = NULL;
8046 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8047 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8048 struct got_object_id *resume_commit_id = NULL;
8049 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8050 struct got_commit_object *commit = NULL;
8051 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8052 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8053 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8054 struct got_object_id_queue commits;
8055 struct got_pathlist_head merged_paths;
8056 const struct got_object_id_queue *parent_ids;
8057 struct got_object_qid *qid, *pid;
8059 SIMPLEQ_INIT(&commits);
8060 TAILQ_INIT(&merged_paths);
8062 while ((ch = getopt(argc, argv, "acl")) != -1) {
8063 switch (ch) {
8064 case 'a':
8065 abort_rebase = 1;
8066 break;
8067 case 'c':
8068 continue_rebase = 1;
8069 break;
8070 case 'l':
8071 list_backups = 1;
8072 break;
8073 default:
8074 usage_rebase();
8075 /* NOTREACHED */
8079 argc -= optind;
8080 argv += optind;
8082 #ifndef PROFILE
8083 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8084 "unveil", NULL) == -1)
8085 err(1, "pledge");
8086 #endif
8087 if (list_backups) {
8088 if (abort_rebase)
8089 option_conflict('l', 'a');
8090 if (continue_rebase)
8091 option_conflict('l', 'c');
8092 if (argc != 0 && argc != 1)
8093 usage_rebase();
8094 } else {
8095 if (abort_rebase && continue_rebase)
8096 usage_rebase();
8097 else if (abort_rebase || continue_rebase) {
8098 if (argc != 0)
8099 usage_rebase();
8100 } else if (argc != 1)
8101 usage_rebase();
8104 cwd = getcwd(NULL, 0);
8105 if (cwd == NULL) {
8106 error = got_error_from_errno("getcwd");
8107 goto done;
8109 error = got_worktree_open(&worktree, cwd);
8110 if (error) {
8111 if (list_backups) {
8112 if (error->code != GOT_ERR_NOT_WORKTREE)
8113 goto done;
8114 } else {
8115 if (error->code == GOT_ERR_NOT_WORKTREE)
8116 error = wrap_not_worktree_error(error,
8117 "rebase", cwd);
8118 goto done;
8122 error = got_repo_open(&repo,
8123 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8124 if (error != NULL)
8125 goto done;
8127 error = apply_unveil(got_repo_get_path(repo), 0,
8128 worktree ? got_worktree_get_root_path(worktree) : NULL);
8129 if (error)
8130 goto done;
8132 if (list_backups) {
8133 error = list_backup_refs(GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8134 argc == 1 ? argv[0] : NULL, repo);
8135 goto done; /* nothing else to do */
8138 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8139 worktree);
8140 if (error)
8141 goto done;
8142 if (histedit_in_progress) {
8143 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8144 goto done;
8147 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8148 if (error)
8149 goto done;
8151 if (abort_rebase) {
8152 struct got_update_progress_arg upa;
8153 if (!rebase_in_progress) {
8154 error = got_error(GOT_ERR_NOT_REBASING);
8155 goto done;
8157 error = got_worktree_rebase_continue(&resume_commit_id,
8158 &new_base_branch, &tmp_branch, &branch, &fileindex,
8159 worktree, repo);
8160 if (error)
8161 goto done;
8162 printf("Switching work tree to %s\n",
8163 got_ref_get_symref_target(new_base_branch));
8164 memset(&upa, 0, sizeof(upa));
8165 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8166 new_base_branch, update_progress, &upa);
8167 if (error)
8168 goto done;
8169 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8170 print_update_progress_stats(&upa);
8171 goto done; /* nothing else to do */
8174 if (continue_rebase) {
8175 if (!rebase_in_progress) {
8176 error = got_error(GOT_ERR_NOT_REBASING);
8177 goto done;
8179 error = got_worktree_rebase_continue(&resume_commit_id,
8180 &new_base_branch, &tmp_branch, &branch, &fileindex,
8181 worktree, repo);
8182 if (error)
8183 goto done;
8185 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8186 resume_commit_id, repo);
8187 if (error)
8188 goto done;
8190 yca_id = got_object_id_dup(resume_commit_id);
8191 if (yca_id == NULL) {
8192 error = got_error_from_errno("got_object_id_dup");
8193 goto done;
8195 } else {
8196 error = got_ref_open(&branch, repo, argv[0], 0);
8197 if (error != NULL)
8198 goto done;
8201 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8202 if (error)
8203 goto done;
8205 if (!continue_rebase) {
8206 struct got_object_id *base_commit_id;
8208 base_commit_id = got_worktree_get_base_commit_id(worktree);
8209 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8210 base_commit_id, branch_head_commit_id, repo,
8211 check_cancelled, NULL);
8212 if (error)
8213 goto done;
8214 if (yca_id == NULL) {
8215 error = got_error_msg(GOT_ERR_ANCESTRY,
8216 "specified branch shares no common ancestry "
8217 "with work tree's branch");
8218 goto done;
8221 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8222 if (error) {
8223 if (error->code != GOT_ERR_ANCESTRY)
8224 goto done;
8225 error = NULL;
8226 } else {
8227 static char msg[128];
8228 snprintf(msg, sizeof(msg),
8229 "%s is already based on %s",
8230 got_ref_get_name(branch),
8231 got_worktree_get_head_ref_name(worktree));
8232 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8233 goto done;
8235 error = got_worktree_rebase_prepare(&new_base_branch,
8236 &tmp_branch, &fileindex, worktree, branch, repo);
8237 if (error)
8238 goto done;
8241 commit_id = branch_head_commit_id;
8242 error = got_object_open_as_commit(&commit, repo, commit_id);
8243 if (error)
8244 goto done;
8246 parent_ids = got_object_commit_get_parent_ids(commit);
8247 pid = SIMPLEQ_FIRST(parent_ids);
8248 if (pid == NULL) {
8249 if (!continue_rebase) {
8250 struct got_update_progress_arg upa;
8251 memset(&upa, 0, sizeof(upa));
8252 error = got_worktree_rebase_abort(worktree, fileindex,
8253 repo, new_base_branch, update_progress, &upa);
8254 if (error)
8255 goto done;
8256 printf("Rebase of %s aborted\n",
8257 got_ref_get_name(branch));
8258 print_update_progress_stats(&upa);
8261 error = got_error(GOT_ERR_EMPTY_REBASE);
8262 goto done;
8264 error = collect_commits(&commits, commit_id, pid->id,
8265 yca_id, got_worktree_get_path_prefix(worktree),
8266 GOT_ERR_REBASE_PATH, repo);
8267 got_object_commit_close(commit);
8268 commit = NULL;
8269 if (error)
8270 goto done;
8272 if (SIMPLEQ_EMPTY(&commits)) {
8273 if (continue_rebase) {
8274 error = rebase_complete(worktree, fileindex,
8275 branch, new_base_branch, tmp_branch, repo,
8276 create_backup);
8277 goto done;
8278 } else {
8279 /* Fast-forward the reference of the branch. */
8280 struct got_object_id *new_head_commit_id;
8281 char *id_str;
8282 error = got_ref_resolve(&new_head_commit_id, repo,
8283 new_base_branch);
8284 if (error)
8285 goto done;
8286 error = got_object_id_str(&id_str, new_head_commit_id);
8287 printf("Forwarding %s to commit %s\n",
8288 got_ref_get_name(branch), id_str);
8289 free(id_str);
8290 error = got_ref_change_ref(branch,
8291 new_head_commit_id);
8292 if (error)
8293 goto done;
8294 /* No backup needed since objects did not change. */
8295 create_backup = 0;
8299 pid = NULL;
8300 SIMPLEQ_FOREACH(qid, &commits, entry) {
8301 struct got_update_progress_arg upa;
8303 commit_id = qid->id;
8304 parent_id = pid ? pid->id : yca_id;
8305 pid = qid;
8307 memset(&upa, 0, sizeof(upa));
8308 error = got_worktree_rebase_merge_files(&merged_paths,
8309 worktree, fileindex, parent_id, commit_id, repo,
8310 update_progress, &upa, check_cancelled, NULL);
8311 if (error)
8312 goto done;
8314 print_update_progress_stats(&upa);
8315 if (upa.conflicts > 0)
8316 rebase_status = GOT_STATUS_CONFLICT;
8318 if (rebase_status == GOT_STATUS_CONFLICT) {
8319 error = show_rebase_merge_conflict(qid->id, repo);
8320 if (error)
8321 goto done;
8322 got_worktree_rebase_pathlist_free(&merged_paths);
8323 break;
8326 error = rebase_commit(&merged_paths, worktree, fileindex,
8327 tmp_branch, commit_id, repo);
8328 got_worktree_rebase_pathlist_free(&merged_paths);
8329 if (error)
8330 goto done;
8333 if (rebase_status == GOT_STATUS_CONFLICT) {
8334 error = got_worktree_rebase_postpone(worktree, fileindex);
8335 if (error)
8336 goto done;
8337 error = got_error_msg(GOT_ERR_CONFLICTS,
8338 "conflicts must be resolved before rebasing can continue");
8339 } else
8340 error = rebase_complete(worktree, fileindex, branch,
8341 new_base_branch, tmp_branch, repo, create_backup);
8342 done:
8343 got_object_id_queue_free(&commits);
8344 free(branch_head_commit_id);
8345 free(resume_commit_id);
8346 free(yca_id);
8347 if (commit)
8348 got_object_commit_close(commit);
8349 if (branch)
8350 got_ref_close(branch);
8351 if (new_base_branch)
8352 got_ref_close(new_base_branch);
8353 if (tmp_branch)
8354 got_ref_close(tmp_branch);
8355 if (worktree)
8356 got_worktree_close(worktree);
8357 if (repo) {
8358 const struct got_error *close_err = got_repo_close(repo);
8359 if (error == NULL)
8360 error = close_err;
8362 return error;
8365 __dead static void
8366 usage_histedit(void)
8368 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8369 "[-F histedit-script] [-m] [-l] [branch]\n", getprogname());
8370 exit(1);
8373 #define GOT_HISTEDIT_PICK 'p'
8374 #define GOT_HISTEDIT_EDIT 'e'
8375 #define GOT_HISTEDIT_FOLD 'f'
8376 #define GOT_HISTEDIT_DROP 'd'
8377 #define GOT_HISTEDIT_MESG 'm'
8379 static struct got_histedit_cmd {
8380 unsigned char code;
8381 const char *name;
8382 const char *desc;
8383 } got_histedit_cmds[] = {
8384 { GOT_HISTEDIT_PICK, "pick", "use commit" },
8385 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
8386 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
8387 "be used" },
8388 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
8389 { GOT_HISTEDIT_MESG, "mesg",
8390 "single-line log message for commit above (open editor if empty)" },
8393 struct got_histedit_list_entry {
8394 TAILQ_ENTRY(got_histedit_list_entry) entry;
8395 struct got_object_id *commit_id;
8396 const struct got_histedit_cmd *cmd;
8397 char *logmsg;
8399 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
8401 static const struct got_error *
8402 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
8403 FILE *f, struct got_repository *repo)
8405 const struct got_error *err = NULL;
8406 char *logmsg = NULL, *id_str = NULL;
8407 struct got_commit_object *commit = NULL;
8408 int n;
8410 err = got_object_open_as_commit(&commit, repo, commit_id);
8411 if (err)
8412 goto done;
8414 err = get_short_logmsg(&logmsg, 34, commit);
8415 if (err)
8416 goto done;
8418 err = got_object_id_str(&id_str, commit_id);
8419 if (err)
8420 goto done;
8422 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
8423 if (n < 0)
8424 err = got_ferror(f, GOT_ERR_IO);
8425 done:
8426 if (commit)
8427 got_object_commit_close(commit);
8428 free(id_str);
8429 free(logmsg);
8430 return err;
8433 static const struct got_error *
8434 histedit_write_commit_list(struct got_object_id_queue *commits,
8435 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
8437 const struct got_error *err = NULL;
8438 struct got_object_qid *qid;
8439 const char *histedit_cmd = NULL;
8441 if (SIMPLEQ_EMPTY(commits))
8442 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8444 SIMPLEQ_FOREACH(qid, commits, entry) {
8445 histedit_cmd = got_histedit_cmds[0].name;
8446 if (fold_only && SIMPLEQ_NEXT(qid, entry) != NULL)
8447 histedit_cmd = "fold";
8448 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
8449 if (err)
8450 break;
8451 if (edit_logmsg_only) {
8452 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
8453 if (n < 0) {
8454 err = got_ferror(f, GOT_ERR_IO);
8455 break;
8460 return err;
8463 static const struct got_error *
8464 write_cmd_list(FILE *f, const char *branch_name,
8465 struct got_object_id_queue *commits)
8467 const struct got_error *err = NULL;
8468 size_t i;
8469 int n;
8470 char *id_str;
8471 struct got_object_qid *qid;
8473 qid = SIMPLEQ_FIRST(commits);
8474 err = got_object_id_str(&id_str, qid->id);
8475 if (err)
8476 return err;
8478 n = fprintf(f,
8479 "# Editing the history of branch '%s' starting at\n"
8480 "# commit %s\n"
8481 "# Commits will be processed in order from top to "
8482 "bottom of this file.\n", branch_name, id_str);
8483 if (n < 0) {
8484 err = got_ferror(f, GOT_ERR_IO);
8485 goto done;
8488 n = fprintf(f, "# Available histedit commands:\n");
8489 if (n < 0) {
8490 err = got_ferror(f, GOT_ERR_IO);
8491 goto done;
8494 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8495 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8496 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8497 cmd->desc);
8498 if (n < 0) {
8499 err = got_ferror(f, GOT_ERR_IO);
8500 break;
8503 done:
8504 free(id_str);
8505 return err;
8508 static const struct got_error *
8509 histedit_syntax_error(int lineno)
8511 static char msg[42];
8512 int ret;
8514 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8515 lineno);
8516 if (ret == -1 || ret >= sizeof(msg))
8517 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8519 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8522 static const struct got_error *
8523 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8524 char *logmsg, struct got_repository *repo)
8526 const struct got_error *err;
8527 struct got_commit_object *folded_commit = NULL;
8528 char *id_str, *folded_logmsg = NULL;
8530 err = got_object_id_str(&id_str, hle->commit_id);
8531 if (err)
8532 return err;
8534 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8535 if (err)
8536 goto done;
8538 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8539 if (err)
8540 goto done;
8541 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8542 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8543 folded_logmsg) == -1) {
8544 err = got_error_from_errno("asprintf");
8546 done:
8547 if (folded_commit)
8548 got_object_commit_close(folded_commit);
8549 free(id_str);
8550 free(folded_logmsg);
8551 return err;
8554 static struct got_histedit_list_entry *
8555 get_folded_commits(struct got_histedit_list_entry *hle)
8557 struct got_histedit_list_entry *prev, *folded = NULL;
8559 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8560 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8561 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8562 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8563 folded = prev;
8564 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8567 return folded;
8570 static const struct got_error *
8571 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8572 struct got_repository *repo)
8574 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8575 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8576 const struct got_error *err = NULL;
8577 struct got_commit_object *commit = NULL;
8578 int logmsg_len;
8579 int fd;
8580 struct got_histedit_list_entry *folded = NULL;
8582 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8583 if (err)
8584 return err;
8586 folded = get_folded_commits(hle);
8587 if (folded) {
8588 while (folded != hle) {
8589 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8590 folded = TAILQ_NEXT(folded, entry);
8591 continue;
8593 err = append_folded_commit_msg(&new_msg, folded,
8594 logmsg, repo);
8595 if (err)
8596 goto done;
8597 free(logmsg);
8598 logmsg = new_msg;
8599 folded = TAILQ_NEXT(folded, entry);
8603 err = got_object_id_str(&id_str, hle->commit_id);
8604 if (err)
8605 goto done;
8606 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8607 if (err)
8608 goto done;
8609 logmsg_len = asprintf(&new_msg,
8610 "%s\n# original log message of commit %s: %s",
8611 logmsg ? logmsg : "", id_str, orig_logmsg);
8612 if (logmsg_len == -1) {
8613 err = got_error_from_errno("asprintf");
8614 goto done;
8616 free(logmsg);
8617 logmsg = new_msg;
8619 err = got_object_id_str(&id_str, hle->commit_id);
8620 if (err)
8621 goto done;
8623 err = got_opentemp_named_fd(&logmsg_path, &fd,
8624 GOT_TMPDIR_STR "/got-logmsg");
8625 if (err)
8626 goto done;
8628 write(fd, logmsg, logmsg_len);
8629 close(fd);
8631 err = get_editor(&editor);
8632 if (err)
8633 goto done;
8635 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8636 logmsg_len, 0);
8637 if (err) {
8638 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8639 goto done;
8640 err = NULL;
8641 hle->logmsg = strdup(new_msg);
8642 if (hle->logmsg == NULL)
8643 err = got_error_from_errno("strdup");
8645 done:
8646 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8647 err = got_error_from_errno2("unlink", logmsg_path);
8648 free(logmsg_path);
8649 free(logmsg);
8650 free(orig_logmsg);
8651 free(editor);
8652 if (commit)
8653 got_object_commit_close(commit);
8654 return err;
8657 static const struct got_error *
8658 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8659 FILE *f, struct got_repository *repo)
8661 const struct got_error *err = NULL;
8662 char *line = NULL, *p, *end;
8663 size_t i, size;
8664 ssize_t len;
8665 int lineno = 0;
8666 const struct got_histedit_cmd *cmd;
8667 struct got_object_id *commit_id = NULL;
8668 struct got_histedit_list_entry *hle = NULL;
8670 for (;;) {
8671 len = getline(&line, &size, f);
8672 if (len == -1) {
8673 const struct got_error *getline_err;
8674 if (feof(f))
8675 break;
8676 getline_err = got_error_from_errno("getline");
8677 err = got_ferror(f, getline_err->code);
8678 break;
8680 lineno++;
8681 p = line;
8682 while (isspace((unsigned char)p[0]))
8683 p++;
8684 if (p[0] == '#' || p[0] == '\0') {
8685 free(line);
8686 line = NULL;
8687 continue;
8689 cmd = NULL;
8690 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8691 cmd = &got_histedit_cmds[i];
8692 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8693 isspace((unsigned char)p[strlen(cmd->name)])) {
8694 p += strlen(cmd->name);
8695 break;
8697 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8698 p++;
8699 break;
8702 if (i == nitems(got_histedit_cmds)) {
8703 err = histedit_syntax_error(lineno);
8704 break;
8706 while (isspace((unsigned char)p[0]))
8707 p++;
8708 if (cmd->code == GOT_HISTEDIT_MESG) {
8709 if (hle == NULL || hle->logmsg != NULL) {
8710 err = got_error(GOT_ERR_HISTEDIT_CMD);
8711 break;
8713 if (p[0] == '\0') {
8714 err = histedit_edit_logmsg(hle, repo);
8715 if (err)
8716 break;
8717 } else {
8718 hle->logmsg = strdup(p);
8719 if (hle->logmsg == NULL) {
8720 err = got_error_from_errno("strdup");
8721 break;
8724 free(line);
8725 line = NULL;
8726 continue;
8727 } else {
8728 end = p;
8729 while (end[0] && !isspace((unsigned char)end[0]))
8730 end++;
8731 *end = '\0';
8733 err = got_object_resolve_id_str(&commit_id, repo, p);
8734 if (err) {
8735 /* override error code */
8736 err = histedit_syntax_error(lineno);
8737 break;
8740 hle = malloc(sizeof(*hle));
8741 if (hle == NULL) {
8742 err = got_error_from_errno("malloc");
8743 break;
8745 hle->cmd = cmd;
8746 hle->commit_id = commit_id;
8747 hle->logmsg = NULL;
8748 commit_id = NULL;
8749 free(line);
8750 line = NULL;
8751 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8754 free(line);
8755 free(commit_id);
8756 return err;
8759 static const struct got_error *
8760 histedit_check_script(struct got_histedit_list *histedit_cmds,
8761 struct got_object_id_queue *commits, struct got_repository *repo)
8763 const struct got_error *err = NULL;
8764 struct got_object_qid *qid;
8765 struct got_histedit_list_entry *hle;
8766 static char msg[92];
8767 char *id_str;
8769 if (TAILQ_EMPTY(histedit_cmds))
8770 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8771 "histedit script contains no commands");
8772 if (SIMPLEQ_EMPTY(commits))
8773 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8775 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8776 struct got_histedit_list_entry *hle2;
8777 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8778 if (hle == hle2)
8779 continue;
8780 if (got_object_id_cmp(hle->commit_id,
8781 hle2->commit_id) != 0)
8782 continue;
8783 err = got_object_id_str(&id_str, hle->commit_id);
8784 if (err)
8785 return err;
8786 snprintf(msg, sizeof(msg), "commit %s is listed "
8787 "more than once in histedit script", id_str);
8788 free(id_str);
8789 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8793 SIMPLEQ_FOREACH(qid, commits, entry) {
8794 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8795 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8796 break;
8798 if (hle == NULL) {
8799 err = got_object_id_str(&id_str, qid->id);
8800 if (err)
8801 return err;
8802 snprintf(msg, sizeof(msg),
8803 "commit %s missing from histedit script", id_str);
8804 free(id_str);
8805 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8809 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8810 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8811 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8812 "last commit in histedit script cannot be folded");
8814 return NULL;
8817 static const struct got_error *
8818 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8819 const char *path, struct got_object_id_queue *commits,
8820 struct got_repository *repo)
8822 const struct got_error *err = NULL;
8823 char *editor;
8824 FILE *f = NULL;
8826 err = get_editor(&editor);
8827 if (err)
8828 return err;
8830 if (spawn_editor(editor, path) == -1) {
8831 err = got_error_from_errno("failed spawning editor");
8832 goto done;
8835 f = fopen(path, "r");
8836 if (f == NULL) {
8837 err = got_error_from_errno("fopen");
8838 goto done;
8840 err = histedit_parse_list(histedit_cmds, f, repo);
8841 if (err)
8842 goto done;
8844 err = histedit_check_script(histedit_cmds, commits, repo);
8845 done:
8846 if (f && fclose(f) == EOF && err == NULL)
8847 err = got_error_from_errno("fclose");
8848 free(editor);
8849 return err;
8852 static const struct got_error *
8853 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8854 struct got_object_id_queue *, const char *, const char *,
8855 struct got_repository *);
8857 static const struct got_error *
8858 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8859 struct got_object_id_queue *commits, const char *branch_name,
8860 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8862 const struct got_error *err;
8863 FILE *f = NULL;
8864 char *path = NULL;
8866 err = got_opentemp_named(&path, &f, "got-histedit");
8867 if (err)
8868 return err;
8870 err = write_cmd_list(f, branch_name, commits);
8871 if (err)
8872 goto done;
8874 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8875 fold_only, repo);
8876 if (err)
8877 goto done;
8879 if (edit_logmsg_only || fold_only) {
8880 rewind(f);
8881 err = histedit_parse_list(histedit_cmds, f, repo);
8882 } else {
8883 if (fclose(f) == EOF) {
8884 err = got_error_from_errno("fclose");
8885 goto done;
8887 f = NULL;
8888 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8889 if (err) {
8890 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8891 err->code != GOT_ERR_HISTEDIT_CMD)
8892 goto done;
8893 err = histedit_edit_list_retry(histedit_cmds, err,
8894 commits, path, branch_name, repo);
8897 done:
8898 if (f && fclose(f) == EOF && err == NULL)
8899 err = got_error_from_errno("fclose");
8900 if (path && unlink(path) != 0 && err == NULL)
8901 err = got_error_from_errno2("unlink", path);
8902 free(path);
8903 return err;
8906 static const struct got_error *
8907 histedit_save_list(struct got_histedit_list *histedit_cmds,
8908 struct got_worktree *worktree, struct got_repository *repo)
8910 const struct got_error *err = NULL;
8911 char *path = NULL;
8912 FILE *f = NULL;
8913 struct got_histedit_list_entry *hle;
8914 struct got_commit_object *commit = NULL;
8916 err = got_worktree_get_histedit_script_path(&path, worktree);
8917 if (err)
8918 return err;
8920 f = fopen(path, "w");
8921 if (f == NULL) {
8922 err = got_error_from_errno2("fopen", path);
8923 goto done;
8925 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8926 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8927 repo);
8928 if (err)
8929 break;
8931 if (hle->logmsg) {
8932 int n = fprintf(f, "%c %s\n",
8933 GOT_HISTEDIT_MESG, hle->logmsg);
8934 if (n < 0) {
8935 err = got_ferror(f, GOT_ERR_IO);
8936 break;
8940 done:
8941 if (f && fclose(f) == EOF && err == NULL)
8942 err = got_error_from_errno("fclose");
8943 free(path);
8944 if (commit)
8945 got_object_commit_close(commit);
8946 return err;
8949 void
8950 histedit_free_list(struct got_histedit_list *histedit_cmds)
8952 struct got_histedit_list_entry *hle;
8954 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8955 TAILQ_REMOVE(histedit_cmds, hle, entry);
8956 free(hle);
8960 static const struct got_error *
8961 histedit_load_list(struct got_histedit_list *histedit_cmds,
8962 const char *path, struct got_repository *repo)
8964 const struct got_error *err = NULL;
8965 FILE *f = NULL;
8967 f = fopen(path, "r");
8968 if (f == NULL) {
8969 err = got_error_from_errno2("fopen", path);
8970 goto done;
8973 err = histedit_parse_list(histedit_cmds, f, repo);
8974 done:
8975 if (f && fclose(f) == EOF && err == NULL)
8976 err = got_error_from_errno("fclose");
8977 return err;
8980 static const struct got_error *
8981 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8982 const struct got_error *edit_err, struct got_object_id_queue *commits,
8983 const char *path, const char *branch_name, struct got_repository *repo)
8985 const struct got_error *err = NULL, *prev_err = edit_err;
8986 int resp = ' ';
8988 while (resp != 'c' && resp != 'r' && resp != 'a') {
8989 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8990 "or (a)bort: ", getprogname(), prev_err->msg);
8991 resp = getchar();
8992 if (resp == '\n')
8993 resp = getchar();
8994 if (resp == 'c') {
8995 histedit_free_list(histedit_cmds);
8996 err = histedit_run_editor(histedit_cmds, path, commits,
8997 repo);
8998 if (err) {
8999 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9000 err->code != GOT_ERR_HISTEDIT_CMD)
9001 break;
9002 prev_err = err;
9003 resp = ' ';
9004 continue;
9006 break;
9007 } else if (resp == 'r') {
9008 histedit_free_list(histedit_cmds);
9009 err = histedit_edit_script(histedit_cmds,
9010 commits, branch_name, 0, 0, repo);
9011 if (err) {
9012 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9013 err->code != GOT_ERR_HISTEDIT_CMD)
9014 break;
9015 prev_err = err;
9016 resp = ' ';
9017 continue;
9019 break;
9020 } else if (resp == 'a') {
9021 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9022 break;
9023 } else
9024 printf("invalid response '%c'\n", resp);
9027 return err;
9030 static const struct got_error *
9031 histedit_complete(struct got_worktree *worktree,
9032 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9033 struct got_reference *branch, struct got_repository *repo)
9035 printf("Switching work tree to %s\n",
9036 got_ref_get_symref_target(branch));
9037 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9038 branch, repo);
9041 static const struct got_error *
9042 show_histedit_progress(struct got_commit_object *commit,
9043 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9045 const struct got_error *err;
9046 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9048 err = got_object_id_str(&old_id_str, hle->commit_id);
9049 if (err)
9050 goto done;
9052 if (new_id) {
9053 err = got_object_id_str(&new_id_str, new_id);
9054 if (err)
9055 goto done;
9058 old_id_str[12] = '\0';
9059 if (new_id_str)
9060 new_id_str[12] = '\0';
9062 if (hle->logmsg) {
9063 logmsg = strdup(hle->logmsg);
9064 if (logmsg == NULL) {
9065 err = got_error_from_errno("strdup");
9066 goto done;
9068 trim_logmsg(logmsg, 42);
9069 } else {
9070 err = get_short_logmsg(&logmsg, 42, commit);
9071 if (err)
9072 goto done;
9075 switch (hle->cmd->code) {
9076 case GOT_HISTEDIT_PICK:
9077 case GOT_HISTEDIT_EDIT:
9078 printf("%s -> %s: %s\n", old_id_str,
9079 new_id_str ? new_id_str : "no-op change", logmsg);
9080 break;
9081 case GOT_HISTEDIT_DROP:
9082 case GOT_HISTEDIT_FOLD:
9083 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9084 logmsg);
9085 break;
9086 default:
9087 break;
9089 done:
9090 free(old_id_str);
9091 free(new_id_str);
9092 return err;
9095 static const struct got_error *
9096 histedit_commit(struct got_pathlist_head *merged_paths,
9097 struct got_worktree *worktree, struct got_fileindex *fileindex,
9098 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9099 struct got_repository *repo)
9101 const struct got_error *err;
9102 struct got_commit_object *commit;
9103 struct got_object_id *new_commit_id;
9105 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9106 && hle->logmsg == NULL) {
9107 err = histedit_edit_logmsg(hle, repo);
9108 if (err)
9109 return err;
9112 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9113 if (err)
9114 return err;
9116 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9117 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9118 hle->logmsg, repo);
9119 if (err) {
9120 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9121 goto done;
9122 err = show_histedit_progress(commit, hle, NULL);
9123 } else {
9124 err = show_histedit_progress(commit, hle, new_commit_id);
9125 free(new_commit_id);
9127 done:
9128 got_object_commit_close(commit);
9129 return err;
9132 static const struct got_error *
9133 histedit_skip_commit(struct got_histedit_list_entry *hle,
9134 struct got_worktree *worktree, struct got_repository *repo)
9136 const struct got_error *error;
9137 struct got_commit_object *commit;
9139 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9140 repo);
9141 if (error)
9142 return error;
9144 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9145 if (error)
9146 return error;
9148 error = show_histedit_progress(commit, hle, NULL);
9149 got_object_commit_close(commit);
9150 return error;
9153 static const struct got_error *
9154 check_local_changes(void *arg, unsigned char status,
9155 unsigned char staged_status, const char *path,
9156 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9157 struct got_object_id *commit_id, int dirfd, const char *de_name)
9159 int *have_local_changes = arg;
9161 switch (status) {
9162 case GOT_STATUS_ADD:
9163 case GOT_STATUS_DELETE:
9164 case GOT_STATUS_MODIFY:
9165 case GOT_STATUS_CONFLICT:
9166 *have_local_changes = 1;
9167 return got_error(GOT_ERR_CANCELLED);
9168 default:
9169 break;
9172 switch (staged_status) {
9173 case GOT_STATUS_ADD:
9174 case GOT_STATUS_DELETE:
9175 case GOT_STATUS_MODIFY:
9176 *have_local_changes = 1;
9177 return got_error(GOT_ERR_CANCELLED);
9178 default:
9179 break;
9182 return NULL;
9185 static const struct got_error *
9186 cmd_histedit(int argc, char *argv[])
9188 const struct got_error *error = NULL;
9189 struct got_worktree *worktree = NULL;
9190 struct got_fileindex *fileindex = NULL;
9191 struct got_repository *repo = NULL;
9192 char *cwd = NULL;
9193 struct got_reference *branch = NULL;
9194 struct got_reference *tmp_branch = NULL;
9195 struct got_object_id *resume_commit_id = NULL;
9196 struct got_object_id *base_commit_id = NULL;
9197 struct got_object_id *head_commit_id = NULL;
9198 struct got_commit_object *commit = NULL;
9199 int ch, rebase_in_progress = 0;
9200 struct got_update_progress_arg upa;
9201 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9202 int edit_logmsg_only = 0, fold_only = 0;
9203 int list_backups = 0;
9204 const char *edit_script_path = NULL;
9205 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9206 struct got_object_id_queue commits;
9207 struct got_pathlist_head merged_paths;
9208 const struct got_object_id_queue *parent_ids;
9209 struct got_object_qid *pid;
9210 struct got_histedit_list histedit_cmds;
9211 struct got_histedit_list_entry *hle;
9213 SIMPLEQ_INIT(&commits);
9214 TAILQ_INIT(&histedit_cmds);
9215 TAILQ_INIT(&merged_paths);
9216 memset(&upa, 0, sizeof(upa));
9218 while ((ch = getopt(argc, argv, "acfF:ml")) != -1) {
9219 switch (ch) {
9220 case 'a':
9221 abort_edit = 1;
9222 break;
9223 case 'c':
9224 continue_edit = 1;
9225 break;
9226 case 'f':
9227 fold_only = 1;
9228 break;
9229 case 'F':
9230 edit_script_path = optarg;
9231 break;
9232 case 'm':
9233 edit_logmsg_only = 1;
9234 break;
9235 case 'l':
9236 list_backups = 1;
9237 break;
9238 default:
9239 usage_histedit();
9240 /* NOTREACHED */
9244 argc -= optind;
9245 argv += optind;
9247 #ifndef PROFILE
9248 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9249 "unveil", NULL) == -1)
9250 err(1, "pledge");
9251 #endif
9252 if (abort_edit && continue_edit)
9253 option_conflict('a', 'c');
9254 if (edit_script_path && edit_logmsg_only)
9255 option_conflict('F', 'm');
9256 if (abort_edit && edit_logmsg_only)
9257 option_conflict('a', 'm');
9258 if (continue_edit && edit_logmsg_only)
9259 option_conflict('c', 'm');
9260 if (abort_edit && fold_only)
9261 option_conflict('a', 'f');
9262 if (continue_edit && fold_only)
9263 option_conflict('c', 'f');
9264 if (fold_only && edit_logmsg_only)
9265 option_conflict('f', 'm');
9266 if (edit_script_path && fold_only)
9267 option_conflict('F', 'f');
9268 if (list_backups) {
9269 if (abort_edit)
9270 option_conflict('l', 'a');
9271 if (continue_edit)
9272 option_conflict('l', 'c');
9273 if (edit_script_path)
9274 option_conflict('l', 'F');
9275 if (edit_logmsg_only)
9276 option_conflict('l', 'm');
9277 if (fold_only)
9278 option_conflict('l', 'f');
9279 if (argc != 0 && argc != 1)
9280 usage_histedit();
9281 } else if (argc != 0)
9282 usage_histedit();
9285 * This command cannot apply unveil(2) in all cases because the
9286 * user may choose to run an editor to edit the histedit script
9287 * and to edit individual commit log messages.
9288 * unveil(2) traverses exec(2); if an editor is used we have to
9289 * apply unveil after edit script and log messages have been written.
9290 * XXX TODO: Make use of unveil(2) where possible.
9293 cwd = getcwd(NULL, 0);
9294 if (cwd == NULL) {
9295 error = got_error_from_errno("getcwd");
9296 goto done;
9298 error = got_worktree_open(&worktree, cwd);
9299 if (error) {
9300 if (list_backups) {
9301 if (error->code != GOT_ERR_NOT_WORKTREE)
9302 goto done;
9303 } else {
9304 if (error->code == GOT_ERR_NOT_WORKTREE)
9305 error = wrap_not_worktree_error(error,
9306 "histedit", cwd);
9307 goto done;
9311 if (list_backups) {
9312 error = got_repo_open(&repo,
9313 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9314 NULL);
9315 if (error != NULL)
9316 goto done;
9317 error = apply_unveil(got_repo_get_path(repo), 0,
9318 worktree ? got_worktree_get_root_path(worktree) : NULL);
9319 if (error)
9320 goto done;
9321 error = list_backup_refs(
9322 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9323 argc == 1 ? argv[0] : NULL, repo);
9324 goto done; /* nothing else to do */
9327 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9328 NULL);
9329 if (error != NULL)
9330 goto done;
9332 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9333 if (error)
9334 goto done;
9335 if (rebase_in_progress) {
9336 error = got_error(GOT_ERR_REBASING);
9337 goto done;
9340 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9341 if (error)
9342 goto done;
9344 if (edit_in_progress && edit_logmsg_only) {
9345 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9346 "histedit operation is in progress in this "
9347 "work tree and must be continued or aborted "
9348 "before the -m option can be used");
9349 goto done;
9351 if (edit_in_progress && fold_only) {
9352 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9353 "histedit operation is in progress in this "
9354 "work tree and must be continued or aborted "
9355 "before the -f option can be used");
9356 goto done;
9359 if (edit_in_progress && abort_edit) {
9360 error = got_worktree_histedit_continue(&resume_commit_id,
9361 &tmp_branch, &branch, &base_commit_id, &fileindex,
9362 worktree, repo);
9363 if (error)
9364 goto done;
9365 printf("Switching work tree to %s\n",
9366 got_ref_get_symref_target(branch));
9367 error = got_worktree_histedit_abort(worktree, fileindex, repo,
9368 branch, base_commit_id, update_progress, &upa);
9369 if (error)
9370 goto done;
9371 printf("Histedit of %s aborted\n",
9372 got_ref_get_symref_target(branch));
9373 print_update_progress_stats(&upa);
9374 goto done; /* nothing else to do */
9375 } else if (abort_edit) {
9376 error = got_error(GOT_ERR_NOT_HISTEDIT);
9377 goto done;
9380 if (continue_edit) {
9381 char *path;
9383 if (!edit_in_progress) {
9384 error = got_error(GOT_ERR_NOT_HISTEDIT);
9385 goto done;
9388 error = got_worktree_get_histedit_script_path(&path, worktree);
9389 if (error)
9390 goto done;
9392 error = histedit_load_list(&histedit_cmds, path, repo);
9393 free(path);
9394 if (error)
9395 goto done;
9397 error = got_worktree_histedit_continue(&resume_commit_id,
9398 &tmp_branch, &branch, &base_commit_id, &fileindex,
9399 worktree, repo);
9400 if (error)
9401 goto done;
9403 error = got_ref_resolve(&head_commit_id, repo, branch);
9404 if (error)
9405 goto done;
9407 error = got_object_open_as_commit(&commit, repo,
9408 head_commit_id);
9409 if (error)
9410 goto done;
9411 parent_ids = got_object_commit_get_parent_ids(commit);
9412 pid = SIMPLEQ_FIRST(parent_ids);
9413 if (pid == NULL) {
9414 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9415 goto done;
9417 error = collect_commits(&commits, head_commit_id, pid->id,
9418 base_commit_id, got_worktree_get_path_prefix(worktree),
9419 GOT_ERR_HISTEDIT_PATH, repo);
9420 got_object_commit_close(commit);
9421 commit = NULL;
9422 if (error)
9423 goto done;
9424 } else {
9425 if (edit_in_progress) {
9426 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9427 goto done;
9430 error = got_ref_open(&branch, repo,
9431 got_worktree_get_head_ref_name(worktree), 0);
9432 if (error != NULL)
9433 goto done;
9435 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
9436 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
9437 "will not edit commit history of a branch outside "
9438 "the \"refs/heads/\" reference namespace");
9439 goto done;
9442 error = got_ref_resolve(&head_commit_id, repo, branch);
9443 got_ref_close(branch);
9444 branch = NULL;
9445 if (error)
9446 goto done;
9448 error = got_object_open_as_commit(&commit, repo,
9449 head_commit_id);
9450 if (error)
9451 goto done;
9452 parent_ids = got_object_commit_get_parent_ids(commit);
9453 pid = SIMPLEQ_FIRST(parent_ids);
9454 if (pid == NULL) {
9455 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9456 goto done;
9458 error = collect_commits(&commits, head_commit_id, pid->id,
9459 got_worktree_get_base_commit_id(worktree),
9460 got_worktree_get_path_prefix(worktree),
9461 GOT_ERR_HISTEDIT_PATH, repo);
9462 got_object_commit_close(commit);
9463 commit = NULL;
9464 if (error)
9465 goto done;
9467 if (SIMPLEQ_EMPTY(&commits)) {
9468 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9469 goto done;
9472 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
9473 &base_commit_id, &fileindex, worktree, repo);
9474 if (error)
9475 goto done;
9477 if (edit_script_path) {
9478 error = histedit_load_list(&histedit_cmds,
9479 edit_script_path, repo);
9480 if (error) {
9481 got_worktree_histedit_abort(worktree, fileindex,
9482 repo, branch, base_commit_id,
9483 update_progress, &upa);
9484 print_update_progress_stats(&upa);
9485 goto done;
9487 } else {
9488 const char *branch_name;
9489 branch_name = got_ref_get_symref_target(branch);
9490 if (strncmp(branch_name, "refs/heads/", 11) == 0)
9491 branch_name += 11;
9492 error = histedit_edit_script(&histedit_cmds, &commits,
9493 branch_name, edit_logmsg_only, fold_only, repo);
9494 if (error) {
9495 got_worktree_histedit_abort(worktree, fileindex,
9496 repo, branch, base_commit_id,
9497 update_progress, &upa);
9498 print_update_progress_stats(&upa);
9499 goto done;
9504 error = histedit_save_list(&histedit_cmds, worktree,
9505 repo);
9506 if (error) {
9507 got_worktree_histedit_abort(worktree, fileindex,
9508 repo, branch, base_commit_id,
9509 update_progress, &upa);
9510 print_update_progress_stats(&upa);
9511 goto done;
9516 error = histedit_check_script(&histedit_cmds, &commits, repo);
9517 if (error)
9518 goto done;
9520 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9521 if (resume_commit_id) {
9522 if (got_object_id_cmp(hle->commit_id,
9523 resume_commit_id) != 0)
9524 continue;
9526 resume_commit_id = NULL;
9527 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9528 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9529 error = histedit_skip_commit(hle, worktree,
9530 repo);
9531 if (error)
9532 goto done;
9533 } else {
9534 struct got_pathlist_head paths;
9535 int have_changes = 0;
9537 TAILQ_INIT(&paths);
9538 error = got_pathlist_append(&paths, "", NULL);
9539 if (error)
9540 goto done;
9541 error = got_worktree_status(worktree, &paths,
9542 repo, 0, check_local_changes, &have_changes,
9543 check_cancelled, NULL);
9544 got_pathlist_free(&paths);
9545 if (error) {
9546 if (error->code != GOT_ERR_CANCELLED)
9547 goto done;
9548 if (sigint_received || sigpipe_received)
9549 goto done;
9551 if (have_changes) {
9552 error = histedit_commit(NULL, worktree,
9553 fileindex, tmp_branch, hle, repo);
9554 if (error)
9555 goto done;
9556 } else {
9557 error = got_object_open_as_commit(
9558 &commit, repo, hle->commit_id);
9559 if (error)
9560 goto done;
9561 error = show_histedit_progress(commit,
9562 hle, NULL);
9563 got_object_commit_close(commit);
9564 commit = NULL;
9565 if (error)
9566 goto done;
9569 continue;
9572 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9573 error = histedit_skip_commit(hle, worktree, repo);
9574 if (error)
9575 goto done;
9576 continue;
9579 error = got_object_open_as_commit(&commit, repo,
9580 hle->commit_id);
9581 if (error)
9582 goto done;
9583 parent_ids = got_object_commit_get_parent_ids(commit);
9584 pid = SIMPLEQ_FIRST(parent_ids);
9586 error = got_worktree_histedit_merge_files(&merged_paths,
9587 worktree, fileindex, pid->id, hle->commit_id, repo,
9588 update_progress, &upa, check_cancelled, NULL);
9589 if (error)
9590 goto done;
9591 got_object_commit_close(commit);
9592 commit = NULL;
9594 print_update_progress_stats(&upa);
9595 if (upa.conflicts > 0)
9596 rebase_status = GOT_STATUS_CONFLICT;
9598 if (rebase_status == GOT_STATUS_CONFLICT) {
9599 error = show_rebase_merge_conflict(hle->commit_id,
9600 repo);
9601 if (error)
9602 goto done;
9603 got_worktree_rebase_pathlist_free(&merged_paths);
9604 break;
9607 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9608 char *id_str;
9609 error = got_object_id_str(&id_str, hle->commit_id);
9610 if (error)
9611 goto done;
9612 printf("Stopping histedit for amending commit %s\n",
9613 id_str);
9614 free(id_str);
9615 got_worktree_rebase_pathlist_free(&merged_paths);
9616 error = got_worktree_histedit_postpone(worktree,
9617 fileindex);
9618 goto done;
9621 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9622 error = histedit_skip_commit(hle, worktree, repo);
9623 if (error)
9624 goto done;
9625 continue;
9628 error = histedit_commit(&merged_paths, worktree, fileindex,
9629 tmp_branch, hle, repo);
9630 got_worktree_rebase_pathlist_free(&merged_paths);
9631 if (error)
9632 goto done;
9635 if (rebase_status == GOT_STATUS_CONFLICT) {
9636 error = got_worktree_histedit_postpone(worktree, fileindex);
9637 if (error)
9638 goto done;
9639 error = got_error_msg(GOT_ERR_CONFLICTS,
9640 "conflicts must be resolved before histedit can continue");
9641 } else
9642 error = histedit_complete(worktree, fileindex, tmp_branch,
9643 branch, repo);
9644 done:
9645 got_object_id_queue_free(&commits);
9646 histedit_free_list(&histedit_cmds);
9647 free(head_commit_id);
9648 free(base_commit_id);
9649 free(resume_commit_id);
9650 if (commit)
9651 got_object_commit_close(commit);
9652 if (branch)
9653 got_ref_close(branch);
9654 if (tmp_branch)
9655 got_ref_close(tmp_branch);
9656 if (worktree)
9657 got_worktree_close(worktree);
9658 if (repo) {
9659 const struct got_error *close_err = got_repo_close(repo);
9660 if (error == NULL)
9661 error = close_err;
9663 return error;
9666 __dead static void
9667 usage_integrate(void)
9669 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9670 exit(1);
9673 static const struct got_error *
9674 cmd_integrate(int argc, char *argv[])
9676 const struct got_error *error = NULL;
9677 struct got_repository *repo = NULL;
9678 struct got_worktree *worktree = NULL;
9679 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9680 const char *branch_arg = NULL;
9681 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9682 struct got_fileindex *fileindex = NULL;
9683 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9684 int ch;
9685 struct got_update_progress_arg upa;
9687 while ((ch = getopt(argc, argv, "")) != -1) {
9688 switch (ch) {
9689 default:
9690 usage_integrate();
9691 /* NOTREACHED */
9695 argc -= optind;
9696 argv += optind;
9698 if (argc != 1)
9699 usage_integrate();
9700 branch_arg = argv[0];
9701 #ifndef PROFILE
9702 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9703 "unveil", NULL) == -1)
9704 err(1, "pledge");
9705 #endif
9706 cwd = getcwd(NULL, 0);
9707 if (cwd == NULL) {
9708 error = got_error_from_errno("getcwd");
9709 goto done;
9712 error = got_worktree_open(&worktree, cwd);
9713 if (error) {
9714 if (error->code == GOT_ERR_NOT_WORKTREE)
9715 error = wrap_not_worktree_error(error, "integrate",
9716 cwd);
9717 goto done;
9720 error = check_rebase_or_histedit_in_progress(worktree);
9721 if (error)
9722 goto done;
9724 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9725 NULL);
9726 if (error != NULL)
9727 goto done;
9729 error = apply_unveil(got_repo_get_path(repo), 0,
9730 got_worktree_get_root_path(worktree));
9731 if (error)
9732 goto done;
9734 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9735 error = got_error_from_errno("asprintf");
9736 goto done;
9739 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9740 &base_branch_ref, worktree, refname, repo);
9741 if (error)
9742 goto done;
9744 refname = strdup(got_ref_get_name(branch_ref));
9745 if (refname == NULL) {
9746 error = got_error_from_errno("strdup");
9747 got_worktree_integrate_abort(worktree, fileindex, repo,
9748 branch_ref, base_branch_ref);
9749 goto done;
9751 base_refname = strdup(got_ref_get_name(base_branch_ref));
9752 if (base_refname == NULL) {
9753 error = got_error_from_errno("strdup");
9754 got_worktree_integrate_abort(worktree, fileindex, repo,
9755 branch_ref, base_branch_ref);
9756 goto done;
9759 error = got_ref_resolve(&commit_id, repo, branch_ref);
9760 if (error)
9761 goto done;
9763 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9764 if (error)
9765 goto done;
9767 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9768 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9769 "specified branch has already been integrated");
9770 got_worktree_integrate_abort(worktree, fileindex, repo,
9771 branch_ref, base_branch_ref);
9772 goto done;
9775 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9776 if (error) {
9777 if (error->code == GOT_ERR_ANCESTRY)
9778 error = got_error(GOT_ERR_REBASE_REQUIRED);
9779 got_worktree_integrate_abort(worktree, fileindex, repo,
9780 branch_ref, base_branch_ref);
9781 goto done;
9784 memset(&upa, 0, sizeof(upa));
9785 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9786 branch_ref, base_branch_ref, update_progress, &upa,
9787 check_cancelled, NULL);
9788 if (error)
9789 goto done;
9791 printf("Integrated %s into %s\n", refname, base_refname);
9792 print_update_progress_stats(&upa);
9793 done:
9794 if (repo) {
9795 const struct got_error *close_err = got_repo_close(repo);
9796 if (error == NULL)
9797 error = close_err;
9799 if (worktree)
9800 got_worktree_close(worktree);
9801 free(cwd);
9802 free(base_commit_id);
9803 free(commit_id);
9804 free(refname);
9805 free(base_refname);
9806 return error;
9809 __dead static void
9810 usage_stage(void)
9812 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9813 "[-S] [file-path ...]\n",
9814 getprogname());
9815 exit(1);
9818 static const struct got_error *
9819 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9820 const char *path, struct got_object_id *blob_id,
9821 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9822 int dirfd, const char *de_name)
9824 const struct got_error *err = NULL;
9825 char *id_str = NULL;
9827 if (staged_status != GOT_STATUS_ADD &&
9828 staged_status != GOT_STATUS_MODIFY &&
9829 staged_status != GOT_STATUS_DELETE)
9830 return NULL;
9832 if (staged_status == GOT_STATUS_ADD ||
9833 staged_status == GOT_STATUS_MODIFY)
9834 err = got_object_id_str(&id_str, staged_blob_id);
9835 else
9836 err = got_object_id_str(&id_str, blob_id);
9837 if (err)
9838 return err;
9840 printf("%s %c %s\n", id_str, staged_status, path);
9841 free(id_str);
9842 return NULL;
9845 static const struct got_error *
9846 cmd_stage(int argc, char *argv[])
9848 const struct got_error *error = NULL;
9849 struct got_repository *repo = NULL;
9850 struct got_worktree *worktree = NULL;
9851 char *cwd = NULL;
9852 struct got_pathlist_head paths;
9853 struct got_pathlist_entry *pe;
9854 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9855 FILE *patch_script_file = NULL;
9856 const char *patch_script_path = NULL;
9857 struct choose_patch_arg cpa;
9859 TAILQ_INIT(&paths);
9861 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9862 switch (ch) {
9863 case 'l':
9864 list_stage = 1;
9865 break;
9866 case 'p':
9867 pflag = 1;
9868 break;
9869 case 'F':
9870 patch_script_path = optarg;
9871 break;
9872 case 'S':
9873 allow_bad_symlinks = 1;
9874 break;
9875 default:
9876 usage_stage();
9877 /* NOTREACHED */
9881 argc -= optind;
9882 argv += optind;
9884 #ifndef PROFILE
9885 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9886 "unveil", NULL) == -1)
9887 err(1, "pledge");
9888 #endif
9889 if (list_stage && (pflag || patch_script_path))
9890 errx(1, "-l option cannot be used with other options");
9891 if (patch_script_path && !pflag)
9892 errx(1, "-F option can only be used together with -p option");
9894 cwd = getcwd(NULL, 0);
9895 if (cwd == NULL) {
9896 error = got_error_from_errno("getcwd");
9897 goto done;
9900 error = got_worktree_open(&worktree, cwd);
9901 if (error) {
9902 if (error->code == GOT_ERR_NOT_WORKTREE)
9903 error = wrap_not_worktree_error(error, "stage", cwd);
9904 goto done;
9907 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9908 NULL);
9909 if (error != NULL)
9910 goto done;
9912 if (patch_script_path) {
9913 patch_script_file = fopen(patch_script_path, "r");
9914 if (patch_script_file == NULL) {
9915 error = got_error_from_errno2("fopen",
9916 patch_script_path);
9917 goto done;
9920 error = apply_unveil(got_repo_get_path(repo), 0,
9921 got_worktree_get_root_path(worktree));
9922 if (error)
9923 goto done;
9925 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9926 if (error)
9927 goto done;
9929 if (list_stage)
9930 error = got_worktree_status(worktree, &paths, repo, 0,
9931 print_stage, NULL, check_cancelled, NULL);
9932 else {
9933 cpa.patch_script_file = patch_script_file;
9934 cpa.action = "stage";
9935 error = got_worktree_stage(worktree, &paths,
9936 pflag ? NULL : print_status, NULL,
9937 pflag ? choose_patch : NULL, &cpa,
9938 allow_bad_symlinks, repo);
9940 done:
9941 if (patch_script_file && fclose(patch_script_file) == EOF &&
9942 error == NULL)
9943 error = got_error_from_errno2("fclose", patch_script_path);
9944 if (repo) {
9945 const struct got_error *close_err = got_repo_close(repo);
9946 if (error == NULL)
9947 error = close_err;
9949 if (worktree)
9950 got_worktree_close(worktree);
9951 TAILQ_FOREACH(pe, &paths, entry)
9952 free((char *)pe->path);
9953 got_pathlist_free(&paths);
9954 free(cwd);
9955 return error;
9958 __dead static void
9959 usage_unstage(void)
9961 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9962 "[file-path ...]\n",
9963 getprogname());
9964 exit(1);
9968 static const struct got_error *
9969 cmd_unstage(int argc, char *argv[])
9971 const struct got_error *error = NULL;
9972 struct got_repository *repo = NULL;
9973 struct got_worktree *worktree = NULL;
9974 char *cwd = NULL;
9975 struct got_pathlist_head paths;
9976 struct got_pathlist_entry *pe;
9977 int ch, pflag = 0;
9978 struct got_update_progress_arg upa;
9979 FILE *patch_script_file = NULL;
9980 const char *patch_script_path = NULL;
9981 struct choose_patch_arg cpa;
9983 TAILQ_INIT(&paths);
9985 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9986 switch (ch) {
9987 case 'p':
9988 pflag = 1;
9989 break;
9990 case 'F':
9991 patch_script_path = optarg;
9992 break;
9993 default:
9994 usage_unstage();
9995 /* NOTREACHED */
9999 argc -= optind;
10000 argv += optind;
10002 #ifndef PROFILE
10003 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10004 "unveil", NULL) == -1)
10005 err(1, "pledge");
10006 #endif
10007 if (patch_script_path && !pflag)
10008 errx(1, "-F option can only be used together with -p option");
10010 cwd = getcwd(NULL, 0);
10011 if (cwd == NULL) {
10012 error = got_error_from_errno("getcwd");
10013 goto done;
10016 error = got_worktree_open(&worktree, cwd);
10017 if (error) {
10018 if (error->code == GOT_ERR_NOT_WORKTREE)
10019 error = wrap_not_worktree_error(error, "unstage", cwd);
10020 goto done;
10023 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10024 NULL);
10025 if (error != NULL)
10026 goto done;
10028 if (patch_script_path) {
10029 patch_script_file = fopen(patch_script_path, "r");
10030 if (patch_script_file == NULL) {
10031 error = got_error_from_errno2("fopen",
10032 patch_script_path);
10033 goto done;
10037 error = apply_unveil(got_repo_get_path(repo), 0,
10038 got_worktree_get_root_path(worktree));
10039 if (error)
10040 goto done;
10042 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10043 if (error)
10044 goto done;
10046 cpa.patch_script_file = patch_script_file;
10047 cpa.action = "unstage";
10048 memset(&upa, 0, sizeof(upa));
10049 error = got_worktree_unstage(worktree, &paths, update_progress,
10050 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10051 if (!error)
10052 print_update_progress_stats(&upa);
10053 done:
10054 if (patch_script_file && fclose(patch_script_file) == EOF &&
10055 error == NULL)
10056 error = got_error_from_errno2("fclose", patch_script_path);
10057 if (repo) {
10058 const struct got_error *close_err = got_repo_close(repo);
10059 if (error == NULL)
10060 error = close_err;
10062 if (worktree)
10063 got_worktree_close(worktree);
10064 TAILQ_FOREACH(pe, &paths, entry)
10065 free((char *)pe->path);
10066 got_pathlist_free(&paths);
10067 free(cwd);
10068 return error;
10071 __dead static void
10072 usage_cat(void)
10074 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10075 "arg1 [arg2 ...]\n", getprogname());
10076 exit(1);
10079 static const struct got_error *
10080 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10082 const struct got_error *err;
10083 struct got_blob_object *blob;
10085 err = got_object_open_as_blob(&blob, repo, id, 8192);
10086 if (err)
10087 return err;
10089 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10090 got_object_blob_close(blob);
10091 return err;
10094 static const struct got_error *
10095 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10097 const struct got_error *err;
10098 struct got_tree_object *tree;
10099 int nentries, i;
10101 err = got_object_open_as_tree(&tree, repo, id);
10102 if (err)
10103 return err;
10105 nentries = got_object_tree_get_nentries(tree);
10106 for (i = 0; i < nentries; i++) {
10107 struct got_tree_entry *te;
10108 char *id_str;
10109 if (sigint_received || sigpipe_received)
10110 break;
10111 te = got_object_tree_get_entry(tree, i);
10112 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10113 if (err)
10114 break;
10115 fprintf(outfile, "%s %.7o %s\n", id_str,
10116 got_tree_entry_get_mode(te),
10117 got_tree_entry_get_name(te));
10118 free(id_str);
10121 got_object_tree_close(tree);
10122 return err;
10125 static const struct got_error *
10126 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10128 const struct got_error *err;
10129 struct got_commit_object *commit;
10130 const struct got_object_id_queue *parent_ids;
10131 struct got_object_qid *pid;
10132 char *id_str = NULL;
10133 const char *logmsg = NULL;
10135 err = got_object_open_as_commit(&commit, repo, id);
10136 if (err)
10137 return err;
10139 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10140 if (err)
10141 goto done;
10143 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10144 parent_ids = got_object_commit_get_parent_ids(commit);
10145 fprintf(outfile, "numparents %d\n",
10146 got_object_commit_get_nparents(commit));
10147 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
10148 char *pid_str;
10149 err = got_object_id_str(&pid_str, pid->id);
10150 if (err)
10151 goto done;
10152 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10153 free(pid_str);
10155 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10156 got_object_commit_get_author(commit),
10157 (long long)got_object_commit_get_author_time(commit));
10159 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10160 got_object_commit_get_author(commit),
10161 (long long)got_object_commit_get_committer_time(commit));
10163 logmsg = got_object_commit_get_logmsg_raw(commit);
10164 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10165 fprintf(outfile, "%s", logmsg);
10166 done:
10167 free(id_str);
10168 got_object_commit_close(commit);
10169 return err;
10172 static const struct got_error *
10173 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10175 const struct got_error *err;
10176 struct got_tag_object *tag;
10177 char *id_str = NULL;
10178 const char *tagmsg = NULL;
10180 err = got_object_open_as_tag(&tag, repo, id);
10181 if (err)
10182 return err;
10184 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10185 if (err)
10186 goto done;
10188 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10190 switch (got_object_tag_get_object_type(tag)) {
10191 case GOT_OBJ_TYPE_BLOB:
10192 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10193 GOT_OBJ_LABEL_BLOB);
10194 break;
10195 case GOT_OBJ_TYPE_TREE:
10196 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10197 GOT_OBJ_LABEL_TREE);
10198 break;
10199 case GOT_OBJ_TYPE_COMMIT:
10200 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10201 GOT_OBJ_LABEL_COMMIT);
10202 break;
10203 case GOT_OBJ_TYPE_TAG:
10204 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10205 GOT_OBJ_LABEL_TAG);
10206 break;
10207 default:
10208 break;
10211 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10212 got_object_tag_get_name(tag));
10214 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10215 got_object_tag_get_tagger(tag),
10216 (long long)got_object_tag_get_tagger_time(tag));
10218 tagmsg = got_object_tag_get_message(tag);
10219 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10220 fprintf(outfile, "%s", tagmsg);
10221 done:
10222 free(id_str);
10223 got_object_tag_close(tag);
10224 return err;
10227 static const struct got_error *
10228 cmd_cat(int argc, char *argv[])
10230 const struct got_error *error;
10231 struct got_repository *repo = NULL;
10232 struct got_worktree *worktree = NULL;
10233 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10234 const char *commit_id_str = NULL;
10235 struct got_object_id *id = NULL, *commit_id = NULL;
10236 int ch, obj_type, i, force_path = 0;
10237 struct got_reflist_head refs;
10239 TAILQ_INIT(&refs);
10241 #ifndef PROFILE
10242 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10243 NULL) == -1)
10244 err(1, "pledge");
10245 #endif
10247 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10248 switch (ch) {
10249 case 'c':
10250 commit_id_str = optarg;
10251 break;
10252 case 'r':
10253 repo_path = realpath(optarg, NULL);
10254 if (repo_path == NULL)
10255 return got_error_from_errno2("realpath",
10256 optarg);
10257 got_path_strip_trailing_slashes(repo_path);
10258 break;
10259 case 'P':
10260 force_path = 1;
10261 break;
10262 default:
10263 usage_cat();
10264 /* NOTREACHED */
10268 argc -= optind;
10269 argv += optind;
10271 cwd = getcwd(NULL, 0);
10272 if (cwd == NULL) {
10273 error = got_error_from_errno("getcwd");
10274 goto done;
10276 error = got_worktree_open(&worktree, cwd);
10277 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10278 goto done;
10279 if (worktree) {
10280 if (repo_path == NULL) {
10281 repo_path = strdup(
10282 got_worktree_get_repo_path(worktree));
10283 if (repo_path == NULL) {
10284 error = got_error_from_errno("strdup");
10285 goto done;
10290 if (repo_path == NULL) {
10291 repo_path = getcwd(NULL, 0);
10292 if (repo_path == NULL)
10293 return got_error_from_errno("getcwd");
10296 error = got_repo_open(&repo, repo_path, NULL);
10297 free(repo_path);
10298 if (error != NULL)
10299 goto done;
10301 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10302 if (error)
10303 goto done;
10305 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10306 if (error)
10307 goto done;
10309 if (commit_id_str == NULL)
10310 commit_id_str = GOT_REF_HEAD;
10311 error = got_repo_match_object_id(&commit_id, NULL,
10312 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10313 if (error)
10314 goto done;
10316 for (i = 0; i < argc; i++) {
10317 if (force_path) {
10318 error = got_object_id_by_path(&id, repo, commit_id,
10319 argv[i]);
10320 if (error)
10321 break;
10322 } else {
10323 error = got_repo_match_object_id(&id, &label, argv[i],
10324 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10325 repo);
10326 if (error) {
10327 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10328 error->code != GOT_ERR_NOT_REF)
10329 break;
10330 error = got_object_id_by_path(&id, repo,
10331 commit_id, argv[i]);
10332 if (error)
10333 break;
10337 error = got_object_get_type(&obj_type, repo, id);
10338 if (error)
10339 break;
10341 switch (obj_type) {
10342 case GOT_OBJ_TYPE_BLOB:
10343 error = cat_blob(id, repo, stdout);
10344 break;
10345 case GOT_OBJ_TYPE_TREE:
10346 error = cat_tree(id, repo, stdout);
10347 break;
10348 case GOT_OBJ_TYPE_COMMIT:
10349 error = cat_commit(id, repo, stdout);
10350 break;
10351 case GOT_OBJ_TYPE_TAG:
10352 error = cat_tag(id, repo, stdout);
10353 break;
10354 default:
10355 error = got_error(GOT_ERR_OBJ_TYPE);
10356 break;
10358 if (error)
10359 break;
10360 free(label);
10361 label = NULL;
10362 free(id);
10363 id = NULL;
10365 done:
10366 free(label);
10367 free(id);
10368 free(commit_id);
10369 if (worktree)
10370 got_worktree_close(worktree);
10371 if (repo) {
10372 const struct got_error *close_err = got_repo_close(repo);
10373 if (error == NULL)
10374 error = close_err;
10376 got_ref_list_free(&refs);
10377 return error;
10380 __dead static void
10381 usage_info(void)
10383 fprintf(stderr, "usage: %s info [path ...]\n",
10384 getprogname());
10385 exit(1);
10388 static const struct got_error *
10389 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
10390 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10391 struct got_object_id *commit_id)
10393 const struct got_error *err = NULL;
10394 char *id_str = NULL;
10395 char datebuf[128];
10396 struct tm mytm, *tm;
10397 struct got_pathlist_head *paths = arg;
10398 struct got_pathlist_entry *pe;
10401 * Clear error indication from any of the path arguments which
10402 * would cause this file index entry to be displayed.
10404 TAILQ_FOREACH(pe, paths, entry) {
10405 if (got_path_cmp(path, pe->path, strlen(path),
10406 pe->path_len) == 0 ||
10407 got_path_is_child(path, pe->path, pe->path_len))
10408 pe->data = NULL; /* no error */
10411 printf(GOT_COMMIT_SEP_STR);
10412 if (S_ISLNK(mode))
10413 printf("symlink: %s\n", path);
10414 else if (S_ISREG(mode)) {
10415 printf("file: %s\n", path);
10416 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
10417 } else if (S_ISDIR(mode))
10418 printf("directory: %s\n", path);
10419 else
10420 printf("something: %s\n", path);
10422 tm = localtime_r(&mtime, &mytm);
10423 if (tm == NULL)
10424 return NULL;
10425 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
10426 return got_error(GOT_ERR_NO_SPACE);
10427 printf("timestamp: %s\n", datebuf);
10429 if (blob_id) {
10430 err = got_object_id_str(&id_str, blob_id);
10431 if (err)
10432 return err;
10433 printf("based on blob: %s\n", id_str);
10434 free(id_str);
10437 if (staged_blob_id) {
10438 err = got_object_id_str(&id_str, staged_blob_id);
10439 if (err)
10440 return err;
10441 printf("based on staged blob: %s\n", id_str);
10442 free(id_str);
10445 if (commit_id) {
10446 err = got_object_id_str(&id_str, commit_id);
10447 if (err)
10448 return err;
10449 printf("based on commit: %s\n", id_str);
10450 free(id_str);
10453 return NULL;
10456 static const struct got_error *
10457 cmd_info(int argc, char *argv[])
10459 const struct got_error *error = NULL;
10460 struct got_worktree *worktree = NULL;
10461 char *cwd = NULL, *id_str = NULL;
10462 struct got_pathlist_head paths;
10463 struct got_pathlist_entry *pe;
10464 char *uuidstr = NULL;
10465 int ch, show_files = 0;
10467 TAILQ_INIT(&paths);
10469 while ((ch = getopt(argc, argv, "")) != -1) {
10470 switch (ch) {
10471 default:
10472 usage_info();
10473 /* NOTREACHED */
10477 argc -= optind;
10478 argv += optind;
10480 #ifndef PROFILE
10481 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
10482 NULL) == -1)
10483 err(1, "pledge");
10484 #endif
10485 cwd = getcwd(NULL, 0);
10486 if (cwd == NULL) {
10487 error = got_error_from_errno("getcwd");
10488 goto done;
10491 error = got_worktree_open(&worktree, cwd);
10492 if (error) {
10493 if (error->code == GOT_ERR_NOT_WORKTREE)
10494 error = wrap_not_worktree_error(error, "info", cwd);
10495 goto done;
10498 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
10499 if (error)
10500 goto done;
10502 if (argc >= 1) {
10503 error = get_worktree_paths_from_argv(&paths, argc, argv,
10504 worktree);
10505 if (error)
10506 goto done;
10507 show_files = 1;
10510 error = got_object_id_str(&id_str,
10511 got_worktree_get_base_commit_id(worktree));
10512 if (error)
10513 goto done;
10515 error = got_worktree_get_uuid(&uuidstr, worktree);
10516 if (error)
10517 goto done;
10519 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
10520 printf("work tree base commit: %s\n", id_str);
10521 printf("work tree path prefix: %s\n",
10522 got_worktree_get_path_prefix(worktree));
10523 printf("work tree branch reference: %s\n",
10524 got_worktree_get_head_ref_name(worktree));
10525 printf("work tree UUID: %s\n", uuidstr);
10526 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10528 if (show_files) {
10529 struct got_pathlist_entry *pe;
10530 TAILQ_FOREACH(pe, &paths, entry) {
10531 if (pe->path_len == 0)
10532 continue;
10534 * Assume this path will fail. This will be corrected
10535 * in print_path_info() in case the path does suceeed.
10537 pe->data = (void *)got_error_path(pe->path,
10538 GOT_ERR_BAD_PATH);
10540 error = got_worktree_path_info(worktree, &paths,
10541 print_path_info, &paths, check_cancelled, NULL);
10542 if (error)
10543 goto done;
10544 TAILQ_FOREACH(pe, &paths, entry) {
10545 if (pe->data != NULL) {
10546 error = pe->data; /* bad path */
10547 break;
10551 done:
10552 TAILQ_FOREACH(pe, &paths, entry)
10553 free((char *)pe->path);
10554 got_pathlist_free(&paths);
10555 free(cwd);
10556 free(id_str);
10557 free(uuidstr);
10558 return error;