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] [-X] "
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 %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 %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 delete_ref(struct got_repository *repo, struct got_reference *ref)
2121 const struct got_error *err = NULL;
2122 struct got_object_id *id = NULL;
2123 char *id_str = NULL;
2124 const char *target;
2126 if (got_ref_is_symbolic(ref)) {
2127 target = got_ref_get_symref_target(ref);
2128 } else {
2129 err = got_ref_resolve(&id, repo, ref);
2130 if (err)
2131 goto done;
2132 err = got_object_id_str(&id_str, id);
2133 if (err)
2134 goto done;
2135 target = id_str;
2138 err = got_ref_delete(ref, repo);
2139 if (err)
2140 goto done;
2142 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2143 done:
2144 free(id);
2145 free(id_str);
2146 return err;
2149 static const struct got_error *
2150 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2152 const struct got_error *err = NULL;
2153 struct got_reflist_head refs;
2154 struct got_reflist_entry *re;
2155 char *prefix;
2157 TAILQ_INIT(&refs);
2159 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2160 err = got_error_from_errno("asprintf");
2161 goto done;
2163 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2164 if (err)
2165 goto done;
2167 TAILQ_FOREACH(re, &refs, entry)
2168 delete_ref(repo, re->ref);
2169 done:
2170 got_ref_list_free(&refs);
2171 return err;
2174 static const struct got_error *
2175 cmd_fetch(int argc, char *argv[])
2177 const struct got_error *error = NULL, *unlock_err;
2178 char *cwd = NULL, *repo_path = NULL;
2179 const char *remote_name;
2180 char *proto = NULL, *host = NULL, *port = NULL;
2181 char *repo_name = NULL, *server_path = NULL;
2182 const struct got_remote_repo *remotes, *remote = NULL;
2183 int nremotes;
2184 char *id_str = NULL;
2185 struct got_repository *repo = NULL;
2186 struct got_worktree *worktree = NULL;
2187 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2188 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2189 struct got_pathlist_entry *pe;
2190 struct got_object_id *pack_hash = NULL;
2191 int i, ch, fetchfd = -1, fetchstatus;
2192 pid_t fetchpid = -1;
2193 struct got_fetch_progress_arg fpa;
2194 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2195 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2197 TAILQ_INIT(&refs);
2198 TAILQ_INIT(&symrefs);
2199 TAILQ_INIT(&wanted_branches);
2200 TAILQ_INIT(&wanted_refs);
2202 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2203 switch (ch) {
2204 case 'a':
2205 fetch_all_branches = 1;
2206 break;
2207 case 'b':
2208 error = got_pathlist_append(&wanted_branches,
2209 optarg, NULL);
2210 if (error)
2211 return error;
2212 break;
2213 case 'd':
2214 delete_refs = 1;
2215 break;
2216 case 'l':
2217 list_refs_only = 1;
2218 break;
2219 case 'r':
2220 repo_path = realpath(optarg, NULL);
2221 if (repo_path == NULL)
2222 return got_error_from_errno2("realpath",
2223 optarg);
2224 got_path_strip_trailing_slashes(repo_path);
2225 break;
2226 case 't':
2227 replace_tags = 1;
2228 break;
2229 case 'v':
2230 if (verbosity < 0)
2231 verbosity = 0;
2232 else if (verbosity < 3)
2233 verbosity++;
2234 break;
2235 case 'q':
2236 verbosity = -1;
2237 break;
2238 case 'R':
2239 error = got_pathlist_append(&wanted_refs,
2240 optarg, NULL);
2241 if (error)
2242 return error;
2243 break;
2244 case 'X':
2245 delete_remote = 1;
2246 break;
2247 default:
2248 usage_fetch();
2249 break;
2252 argc -= optind;
2253 argv += optind;
2255 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2256 option_conflict('a', 'b');
2257 if (list_refs_only) {
2258 if (!TAILQ_EMPTY(&wanted_branches))
2259 option_conflict('l', 'b');
2260 if (fetch_all_branches)
2261 option_conflict('l', 'a');
2262 if (delete_refs)
2263 option_conflict('l', 'd');
2264 if (delete_remote)
2265 option_conflict('l', 'X');
2267 if (delete_remote) {
2268 if (fetch_all_branches)
2269 option_conflict('X', 'a');
2270 if (!TAILQ_EMPTY(&wanted_branches))
2271 option_conflict('X', 'b');
2272 if (delete_refs)
2273 option_conflict('X', 'd');
2274 if (replace_tags)
2275 option_conflict('X', 't');
2276 if (!TAILQ_EMPTY(&wanted_refs))
2277 option_conflict('X', 'R');
2280 if (argc == 0) {
2281 if (delete_remote)
2282 errx(1, "-X option requires a remote name");
2283 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2284 } else if (argc == 1)
2285 remote_name = argv[0];
2286 else
2287 usage_fetch();
2289 cwd = getcwd(NULL, 0);
2290 if (cwd == NULL) {
2291 error = got_error_from_errno("getcwd");
2292 goto done;
2295 if (repo_path == NULL) {
2296 error = got_worktree_open(&worktree, cwd);
2297 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2298 goto done;
2299 else
2300 error = NULL;
2301 if (worktree) {
2302 repo_path =
2303 strdup(got_worktree_get_repo_path(worktree));
2304 if (repo_path == NULL)
2305 error = got_error_from_errno("strdup");
2306 if (error)
2307 goto done;
2308 } else {
2309 repo_path = strdup(cwd);
2310 if (repo_path == NULL) {
2311 error = got_error_from_errno("strdup");
2312 goto done;
2317 error = got_repo_open(&repo, repo_path, NULL);
2318 if (error)
2319 goto done;
2321 if (delete_remote) {
2322 error = delete_refs_for_remote(repo, remote_name);
2323 goto done; /* nothing else to do */
2326 if (worktree) {
2327 worktree_conf = got_worktree_get_gotconfig(worktree);
2328 if (worktree_conf) {
2329 got_gotconfig_get_remotes(&nremotes, &remotes,
2330 worktree_conf);
2331 for (i = 0; i < nremotes; i++) {
2332 if (strcmp(remotes[i].name, remote_name) == 0) {
2333 remote = &remotes[i];
2334 break;
2339 if (remote == NULL) {
2340 repo_conf = got_repo_get_gotconfig(repo);
2341 if (repo_conf) {
2342 got_gotconfig_get_remotes(&nremotes, &remotes,
2343 repo_conf);
2344 for (i = 0; i < nremotes; i++) {
2345 if (strcmp(remotes[i].name, remote_name) == 0) {
2346 remote = &remotes[i];
2347 break;
2352 if (remote == NULL) {
2353 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2354 for (i = 0; i < nremotes; i++) {
2355 if (strcmp(remotes[i].name, remote_name) == 0) {
2356 remote = &remotes[i];
2357 break;
2361 if (remote == NULL) {
2362 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2363 goto done;
2366 if (TAILQ_EMPTY(&wanted_branches)) {
2367 if (!fetch_all_branches)
2368 fetch_all_branches = remote->fetch_all_branches;
2369 for (i = 0; i < remote->nbranches; i++) {
2370 got_pathlist_append(&wanted_branches,
2371 remote->branches[i], NULL);
2374 if (TAILQ_EMPTY(&wanted_refs)) {
2375 for (i = 0; i < remote->nrefs; i++) {
2376 got_pathlist_append(&wanted_refs,
2377 remote->refs[i], NULL);
2381 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2382 &repo_name, remote->url);
2383 if (error)
2384 goto done;
2386 if (strcmp(proto, "git") == 0) {
2387 #ifndef PROFILE
2388 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2389 "sendfd dns inet unveil", NULL) == -1)
2390 err(1, "pledge");
2391 #endif
2392 } else if (strcmp(proto, "git+ssh") == 0 ||
2393 strcmp(proto, "ssh") == 0) {
2394 #ifndef PROFILE
2395 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2396 "sendfd unveil", NULL) == -1)
2397 err(1, "pledge");
2398 #endif
2399 } else if (strcmp(proto, "http") == 0 ||
2400 strcmp(proto, "git+http") == 0) {
2401 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2402 goto done;
2403 } else {
2404 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2405 goto done;
2408 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2409 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2410 error = got_error_from_errno2("unveil",
2411 GOT_FETCH_PATH_SSH);
2412 goto done;
2415 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2416 if (error)
2417 goto done;
2419 if (verbosity >= 0)
2420 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2421 port ? ":" : "", port ? port : "");
2423 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2424 server_path, verbosity);
2425 if (error)
2426 goto done;
2428 fpa.last_scaled_size[0] = '\0';
2429 fpa.last_p_indexed = -1;
2430 fpa.last_p_resolved = -1;
2431 fpa.verbosity = verbosity;
2432 fpa.repo = repo;
2433 fpa.create_configs = 0;
2434 fpa.configs_created = 0;
2435 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2436 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2437 remote->mirror_references, fetch_all_branches, &wanted_branches,
2438 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2439 fetch_progress, &fpa);
2440 if (error)
2441 goto done;
2443 if (list_refs_only) {
2444 error = list_remote_refs(&symrefs, &refs);
2445 goto done;
2448 if (pack_hash == NULL) {
2449 if (verbosity >= 0)
2450 printf("Already up-to-date\n");
2451 } else if (verbosity >= 0) {
2452 error = got_object_id_str(&id_str, pack_hash);
2453 if (error)
2454 goto done;
2455 printf("\nFetched %s.pack\n", id_str);
2456 free(id_str);
2457 id_str = NULL;
2460 /* Update references provided with the pack file. */
2461 TAILQ_FOREACH(pe, &refs, entry) {
2462 const char *refname = pe->path;
2463 struct got_object_id *id = pe->data;
2464 struct got_reference *ref;
2465 char *remote_refname;
2467 if (is_wanted_ref(&wanted_refs, refname) &&
2468 !remote->mirror_references) {
2469 error = update_wanted_ref(refname, id,
2470 remote->name, verbosity, repo);
2471 if (error)
2472 goto done;
2473 continue;
2476 if (remote->mirror_references ||
2477 strncmp("refs/tags/", refname, 10) == 0) {
2478 error = got_ref_open(&ref, repo, refname, 1);
2479 if (error) {
2480 if (error->code != GOT_ERR_NOT_REF)
2481 goto done;
2482 error = create_ref(refname, id, verbosity,
2483 repo);
2484 if (error)
2485 goto done;
2486 } else {
2487 error = update_ref(ref, id, replace_tags,
2488 verbosity, repo);
2489 unlock_err = got_ref_unlock(ref);
2490 if (unlock_err && error == NULL)
2491 error = unlock_err;
2492 got_ref_close(ref);
2493 if (error)
2494 goto done;
2496 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2497 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2498 remote_name, refname + 11) == -1) {
2499 error = got_error_from_errno("asprintf");
2500 goto done;
2503 error = got_ref_open(&ref, repo, remote_refname, 1);
2504 if (error) {
2505 if (error->code != GOT_ERR_NOT_REF)
2506 goto done;
2507 error = create_ref(remote_refname, id,
2508 verbosity, repo);
2509 if (error)
2510 goto done;
2511 } else {
2512 error = update_ref(ref, id, replace_tags,
2513 verbosity, repo);
2514 unlock_err = got_ref_unlock(ref);
2515 if (unlock_err && error == NULL)
2516 error = unlock_err;
2517 got_ref_close(ref);
2518 if (error)
2519 goto done;
2522 /* Also create a local branch if none exists yet. */
2523 error = got_ref_open(&ref, repo, refname, 1);
2524 if (error) {
2525 if (error->code != GOT_ERR_NOT_REF)
2526 goto done;
2527 error = create_ref(refname, id, verbosity,
2528 repo);
2529 if (error)
2530 goto done;
2531 } else {
2532 unlock_err = got_ref_unlock(ref);
2533 if (unlock_err && error == NULL)
2534 error = unlock_err;
2535 got_ref_close(ref);
2539 if (delete_refs) {
2540 error = delete_missing_refs(&refs, &symrefs, remote,
2541 verbosity, repo);
2542 if (error)
2543 goto done;
2546 if (!remote->mirror_references) {
2547 /* Update remote HEAD reference if the server provided one. */
2548 TAILQ_FOREACH(pe, &symrefs, entry) {
2549 struct got_reference *target_ref;
2550 const char *refname = pe->path;
2551 const char *target = pe->data;
2552 char *remote_refname = NULL, *remote_target = NULL;
2554 if (strcmp(refname, GOT_REF_HEAD) != 0)
2555 continue;
2557 if (strncmp("refs/heads/", target, 11) != 0)
2558 continue;
2560 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2561 remote->name, refname) == -1) {
2562 error = got_error_from_errno("asprintf");
2563 goto done;
2565 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2566 remote->name, target + 11) == -1) {
2567 error = got_error_from_errno("asprintf");
2568 free(remote_refname);
2569 goto done;
2572 error = got_ref_open(&target_ref, repo, remote_target,
2573 0);
2574 if (error) {
2575 free(remote_refname);
2576 free(remote_target);
2577 if (error->code == GOT_ERR_NOT_REF) {
2578 error = NULL;
2579 continue;
2581 goto done;
2583 error = update_symref(remote_refname, target_ref,
2584 verbosity, repo);
2585 free(remote_refname);
2586 free(remote_target);
2587 got_ref_close(target_ref);
2588 if (error)
2589 goto done;
2592 done:
2593 if (fetchpid > 0) {
2594 if (kill(fetchpid, SIGTERM) == -1)
2595 error = got_error_from_errno("kill");
2596 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2597 error = got_error_from_errno("waitpid");
2599 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2600 error = got_error_from_errno("close");
2601 if (repo) {
2602 const struct got_error *close_err = got_repo_close(repo);
2603 if (error == NULL)
2604 error = close_err;
2606 if (worktree)
2607 got_worktree_close(worktree);
2608 TAILQ_FOREACH(pe, &refs, entry) {
2609 free((void *)pe->path);
2610 free(pe->data);
2612 got_pathlist_free(&refs);
2613 TAILQ_FOREACH(pe, &symrefs, entry) {
2614 free((void *)pe->path);
2615 free(pe->data);
2617 got_pathlist_free(&symrefs);
2618 got_pathlist_free(&wanted_branches);
2619 got_pathlist_free(&wanted_refs);
2620 free(id_str);
2621 free(cwd);
2622 free(repo_path);
2623 free(pack_hash);
2624 free(proto);
2625 free(host);
2626 free(port);
2627 free(server_path);
2628 free(repo_name);
2629 return error;
2633 __dead static void
2634 usage_checkout(void)
2636 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2637 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2638 exit(1);
2641 static void
2642 show_worktree_base_ref_warning(void)
2644 fprintf(stderr, "%s: warning: could not create a reference "
2645 "to the work tree's base commit; the commit could be "
2646 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2647 "repository writable and running 'got update' will prevent this\n",
2648 getprogname());
2651 struct got_checkout_progress_arg {
2652 const char *worktree_path;
2653 int had_base_commit_ref_error;
2656 static const struct got_error *
2657 checkout_progress(void *arg, unsigned char status, const char *path)
2659 struct got_checkout_progress_arg *a = arg;
2661 /* Base commit bump happens silently. */
2662 if (status == GOT_STATUS_BUMP_BASE)
2663 return NULL;
2665 if (status == GOT_STATUS_BASE_REF_ERR) {
2666 a->had_base_commit_ref_error = 1;
2667 return NULL;
2670 while (path[0] == '/')
2671 path++;
2673 printf("%c %s/%s\n", status, a->worktree_path, path);
2674 return NULL;
2677 static const struct got_error *
2678 check_cancelled(void *arg)
2680 if (sigint_received || sigpipe_received)
2681 return got_error(GOT_ERR_CANCELLED);
2682 return NULL;
2685 static const struct got_error *
2686 check_linear_ancestry(struct got_object_id *commit_id,
2687 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2688 struct got_repository *repo)
2690 const struct got_error *err = NULL;
2691 struct got_object_id *yca_id;
2693 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2694 commit_id, base_commit_id, repo, check_cancelled, NULL);
2695 if (err)
2696 return err;
2698 if (yca_id == NULL)
2699 return got_error(GOT_ERR_ANCESTRY);
2702 * Require a straight line of history between the target commit
2703 * and the work tree's base commit.
2705 * Non-linear situations such as this require a rebase:
2707 * (commit) D F (base_commit)
2708 * \ /
2709 * C E
2710 * \ /
2711 * B (yca)
2712 * |
2713 * A
2715 * 'got update' only handles linear cases:
2716 * Update forwards in time: A (base/yca) - B - C - D (commit)
2717 * Update backwards in time: D (base) - C - B - A (commit/yca)
2719 if (allow_forwards_in_time_only) {
2720 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2721 return got_error(GOT_ERR_ANCESTRY);
2722 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2723 got_object_id_cmp(base_commit_id, yca_id) != 0)
2724 return got_error(GOT_ERR_ANCESTRY);
2726 free(yca_id);
2727 return NULL;
2730 static const struct got_error *
2731 check_same_branch(struct got_object_id *commit_id,
2732 struct got_reference *head_ref, struct got_object_id *yca_id,
2733 struct got_repository *repo)
2735 const struct got_error *err = NULL;
2736 struct got_commit_graph *graph = NULL;
2737 struct got_object_id *head_commit_id = NULL;
2738 int is_same_branch = 0;
2740 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2741 if (err)
2742 goto done;
2744 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2745 is_same_branch = 1;
2746 goto done;
2748 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2749 is_same_branch = 1;
2750 goto done;
2753 err = got_commit_graph_open(&graph, "/", 1);
2754 if (err)
2755 goto done;
2757 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2758 check_cancelled, NULL);
2759 if (err)
2760 goto done;
2762 for (;;) {
2763 struct got_object_id *id;
2764 err = got_commit_graph_iter_next(&id, graph, repo,
2765 check_cancelled, NULL);
2766 if (err) {
2767 if (err->code == GOT_ERR_ITER_COMPLETED)
2768 err = NULL;
2769 break;
2772 if (id) {
2773 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2774 break;
2775 if (got_object_id_cmp(id, commit_id) == 0) {
2776 is_same_branch = 1;
2777 break;
2781 done:
2782 if (graph)
2783 got_commit_graph_close(graph);
2784 free(head_commit_id);
2785 if (!err && !is_same_branch)
2786 err = got_error(GOT_ERR_ANCESTRY);
2787 return err;
2790 static const struct got_error *
2791 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2793 static char msg[512];
2794 const char *branch_name;
2796 if (got_ref_is_symbolic(ref))
2797 branch_name = got_ref_get_symref_target(ref);
2798 else
2799 branch_name = got_ref_get_name(ref);
2801 if (strncmp("refs/heads/", branch_name, 11) == 0)
2802 branch_name += 11;
2804 snprintf(msg, sizeof(msg),
2805 "target commit is not contained in branch '%s'; "
2806 "the branch to use must be specified with -b; "
2807 "if necessary a new branch can be created for "
2808 "this commit with 'got branch -c %s BRANCH_NAME'",
2809 branch_name, commit_id_str);
2811 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2814 static const struct got_error *
2815 cmd_checkout(int argc, char *argv[])
2817 const struct got_error *error = NULL;
2818 struct got_repository *repo = NULL;
2819 struct got_reference *head_ref = NULL;
2820 struct got_worktree *worktree = NULL;
2821 char *repo_path = NULL;
2822 char *worktree_path = NULL;
2823 const char *path_prefix = "";
2824 const char *branch_name = GOT_REF_HEAD;
2825 char *commit_id_str = NULL;
2826 char *cwd = NULL;
2827 int ch, same_path_prefix, allow_nonempty = 0;
2828 struct got_pathlist_head paths;
2829 struct got_checkout_progress_arg cpa;
2831 TAILQ_INIT(&paths);
2833 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2834 switch (ch) {
2835 case 'b':
2836 branch_name = optarg;
2837 break;
2838 case 'c':
2839 commit_id_str = strdup(optarg);
2840 if (commit_id_str == NULL)
2841 return got_error_from_errno("strdup");
2842 break;
2843 case 'E':
2844 allow_nonempty = 1;
2845 break;
2846 case 'p':
2847 path_prefix = optarg;
2848 break;
2849 default:
2850 usage_checkout();
2851 /* NOTREACHED */
2855 argc -= optind;
2856 argv += optind;
2858 #ifndef PROFILE
2859 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2860 "unveil", NULL) == -1)
2861 err(1, "pledge");
2862 #endif
2863 if (argc == 1) {
2864 char *base, *dotgit;
2865 const char *path;
2866 repo_path = realpath(argv[0], NULL);
2867 if (repo_path == NULL)
2868 return got_error_from_errno2("realpath", argv[0]);
2869 cwd = getcwd(NULL, 0);
2870 if (cwd == NULL) {
2871 error = got_error_from_errno("getcwd");
2872 goto done;
2874 if (path_prefix[0])
2875 path = path_prefix;
2876 else
2877 path = repo_path;
2878 error = got_path_basename(&base, path);
2879 if (error)
2880 goto done;
2881 dotgit = strstr(base, ".git");
2882 if (dotgit)
2883 *dotgit = '\0';
2884 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2885 error = got_error_from_errno("asprintf");
2886 free(base);
2887 goto done;
2889 free(base);
2890 } else if (argc == 2) {
2891 repo_path = realpath(argv[0], NULL);
2892 if (repo_path == NULL) {
2893 error = got_error_from_errno2("realpath", argv[0]);
2894 goto done;
2896 worktree_path = realpath(argv[1], NULL);
2897 if (worktree_path == NULL) {
2898 if (errno != ENOENT) {
2899 error = got_error_from_errno2("realpath",
2900 argv[1]);
2901 goto done;
2903 worktree_path = strdup(argv[1]);
2904 if (worktree_path == NULL) {
2905 error = got_error_from_errno("strdup");
2906 goto done;
2909 } else
2910 usage_checkout();
2912 got_path_strip_trailing_slashes(repo_path);
2913 got_path_strip_trailing_slashes(worktree_path);
2915 error = got_repo_open(&repo, repo_path, NULL);
2916 if (error != NULL)
2917 goto done;
2919 /* Pre-create work tree path for unveil(2) */
2920 error = got_path_mkdir(worktree_path);
2921 if (error) {
2922 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2923 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2924 goto done;
2925 if (!allow_nonempty &&
2926 !got_path_dir_is_empty(worktree_path)) {
2927 error = got_error_path(worktree_path,
2928 GOT_ERR_DIR_NOT_EMPTY);
2929 goto done;
2933 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2934 if (error)
2935 goto done;
2937 error = got_ref_open(&head_ref, repo, branch_name, 0);
2938 if (error != NULL)
2939 goto done;
2941 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2942 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2943 goto done;
2945 error = got_worktree_open(&worktree, worktree_path);
2946 if (error != NULL)
2947 goto done;
2949 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2950 path_prefix);
2951 if (error != NULL)
2952 goto done;
2953 if (!same_path_prefix) {
2954 error = got_error(GOT_ERR_PATH_PREFIX);
2955 goto done;
2958 if (commit_id_str) {
2959 struct got_object_id *commit_id;
2960 struct got_reflist_head refs;
2961 TAILQ_INIT(&refs);
2962 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2963 NULL);
2964 if (error)
2965 goto done;
2966 error = got_repo_match_object_id(&commit_id, NULL,
2967 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2968 got_ref_list_free(&refs);
2969 if (error)
2970 goto done;
2971 error = check_linear_ancestry(commit_id,
2972 got_worktree_get_base_commit_id(worktree), 0, repo);
2973 if (error != NULL) {
2974 free(commit_id);
2975 if (error->code == GOT_ERR_ANCESTRY) {
2976 error = checkout_ancestry_error(
2977 head_ref, commit_id_str);
2979 goto done;
2981 error = check_same_branch(commit_id, head_ref, NULL, repo);
2982 if (error) {
2983 if (error->code == GOT_ERR_ANCESTRY) {
2984 error = checkout_ancestry_error(
2985 head_ref, commit_id_str);
2987 goto done;
2989 error = got_worktree_set_base_commit_id(worktree, repo,
2990 commit_id);
2991 free(commit_id);
2992 if (error)
2993 goto done;
2996 error = got_pathlist_append(&paths, "", NULL);
2997 if (error)
2998 goto done;
2999 cpa.worktree_path = worktree_path;
3000 cpa.had_base_commit_ref_error = 0;
3001 error = got_worktree_checkout_files(worktree, &paths, repo,
3002 checkout_progress, &cpa, check_cancelled, NULL);
3003 if (error != NULL)
3004 goto done;
3006 printf("Now shut up and hack\n");
3007 if (cpa.had_base_commit_ref_error)
3008 show_worktree_base_ref_warning();
3009 done:
3010 got_pathlist_free(&paths);
3011 free(commit_id_str);
3012 free(repo_path);
3013 free(worktree_path);
3014 free(cwd);
3015 return error;
3018 struct got_update_progress_arg {
3019 int did_something;
3020 int conflicts;
3021 int obstructed;
3022 int not_updated;
3025 void
3026 print_update_progress_stats(struct got_update_progress_arg *upa)
3028 if (!upa->did_something)
3029 return;
3031 if (upa->conflicts > 0)
3032 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3033 if (upa->obstructed > 0)
3034 printf("File paths obstructed by a non-regular file: %d\n",
3035 upa->obstructed);
3036 if (upa->not_updated > 0)
3037 printf("Files not updated because of existing merge "
3038 "conflicts: %d\n", upa->not_updated);
3041 __dead static void
3042 usage_update(void)
3044 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
3045 getprogname());
3046 exit(1);
3049 static const struct got_error *
3050 update_progress(void *arg, unsigned char status, const char *path)
3052 struct got_update_progress_arg *upa = arg;
3054 if (status == GOT_STATUS_EXISTS ||
3055 status == GOT_STATUS_BASE_REF_ERR)
3056 return NULL;
3058 upa->did_something = 1;
3060 /* Base commit bump happens silently. */
3061 if (status == GOT_STATUS_BUMP_BASE)
3062 return NULL;
3064 if (status == GOT_STATUS_CONFLICT)
3065 upa->conflicts++;
3066 if (status == GOT_STATUS_OBSTRUCTED)
3067 upa->obstructed++;
3068 if (status == GOT_STATUS_CANNOT_UPDATE)
3069 upa->not_updated++;
3071 while (path[0] == '/')
3072 path++;
3073 printf("%c %s\n", status, path);
3074 return NULL;
3077 static const struct got_error *
3078 switch_head_ref(struct got_reference *head_ref,
3079 struct got_object_id *commit_id, struct got_worktree *worktree,
3080 struct got_repository *repo)
3082 const struct got_error *err = NULL;
3083 char *base_id_str;
3084 int ref_has_moved = 0;
3086 /* Trivial case: switching between two different references. */
3087 if (strcmp(got_ref_get_name(head_ref),
3088 got_worktree_get_head_ref_name(worktree)) != 0) {
3089 printf("Switching work tree from %s to %s\n",
3090 got_worktree_get_head_ref_name(worktree),
3091 got_ref_get_name(head_ref));
3092 return got_worktree_set_head_ref(worktree, head_ref);
3095 err = check_linear_ancestry(commit_id,
3096 got_worktree_get_base_commit_id(worktree), 0, repo);
3097 if (err) {
3098 if (err->code != GOT_ERR_ANCESTRY)
3099 return err;
3100 ref_has_moved = 1;
3102 if (!ref_has_moved)
3103 return NULL;
3105 /* Switching to a rebased branch with the same reference name. */
3106 err = got_object_id_str(&base_id_str,
3107 got_worktree_get_base_commit_id(worktree));
3108 if (err)
3109 return err;
3110 printf("Reference %s now points at a different branch\n",
3111 got_worktree_get_head_ref_name(worktree));
3112 printf("Switching work tree from %s to %s\n", base_id_str,
3113 got_worktree_get_head_ref_name(worktree));
3114 return NULL;
3117 static const struct got_error *
3118 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3120 const struct got_error *err;
3121 int in_progress;
3123 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3124 if (err)
3125 return err;
3126 if (in_progress)
3127 return got_error(GOT_ERR_REBASING);
3129 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3130 if (err)
3131 return err;
3132 if (in_progress)
3133 return got_error(GOT_ERR_HISTEDIT_BUSY);
3135 return NULL;
3138 static const struct got_error *
3139 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3140 char *argv[], struct got_worktree *worktree)
3142 const struct got_error *err = NULL;
3143 char *path;
3144 int i;
3146 if (argc == 0) {
3147 path = strdup("");
3148 if (path == NULL)
3149 return got_error_from_errno("strdup");
3150 return got_pathlist_append(paths, path, NULL);
3153 for (i = 0; i < argc; i++) {
3154 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3155 if (err)
3156 break;
3157 err = got_pathlist_append(paths, path, NULL);
3158 if (err) {
3159 free(path);
3160 break;
3164 return err;
3167 static const struct got_error *
3168 wrap_not_worktree_error(const struct got_error *orig_err,
3169 const char *cmdname, const char *path)
3171 const struct got_error *err;
3172 struct got_repository *repo;
3173 static char msg[512];
3175 err = got_repo_open(&repo, path, NULL);
3176 if (err)
3177 return orig_err;
3179 snprintf(msg, sizeof(msg),
3180 "'got %s' needs a work tree in addition to a git repository\n"
3181 "Work trees can be checked out from this Git repository with "
3182 "'got checkout'.\n"
3183 "The got(1) manual page contains more information.", cmdname);
3184 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3185 got_repo_close(repo);
3186 return err;
3189 static const struct got_error *
3190 cmd_update(int argc, char *argv[])
3192 const struct got_error *error = NULL;
3193 struct got_repository *repo = NULL;
3194 struct got_worktree *worktree = NULL;
3195 char *worktree_path = NULL;
3196 struct got_object_id *commit_id = NULL;
3197 char *commit_id_str = NULL;
3198 const char *branch_name = NULL;
3199 struct got_reference *head_ref = NULL;
3200 struct got_pathlist_head paths;
3201 struct got_pathlist_entry *pe;
3202 int ch;
3203 struct got_update_progress_arg upa;
3205 TAILQ_INIT(&paths);
3207 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3208 switch (ch) {
3209 case 'b':
3210 branch_name = optarg;
3211 break;
3212 case 'c':
3213 commit_id_str = strdup(optarg);
3214 if (commit_id_str == NULL)
3215 return got_error_from_errno("strdup");
3216 break;
3217 default:
3218 usage_update();
3219 /* NOTREACHED */
3223 argc -= optind;
3224 argv += optind;
3226 #ifndef PROFILE
3227 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3228 "unveil", NULL) == -1)
3229 err(1, "pledge");
3230 #endif
3231 worktree_path = getcwd(NULL, 0);
3232 if (worktree_path == NULL) {
3233 error = got_error_from_errno("getcwd");
3234 goto done;
3236 error = got_worktree_open(&worktree, worktree_path);
3237 if (error) {
3238 if (error->code == GOT_ERR_NOT_WORKTREE)
3239 error = wrap_not_worktree_error(error, "update",
3240 worktree_path);
3241 goto done;
3244 error = check_rebase_or_histedit_in_progress(worktree);
3245 if (error)
3246 goto done;
3248 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3249 NULL);
3250 if (error != NULL)
3251 goto done;
3253 error = apply_unveil(got_repo_get_path(repo), 0,
3254 got_worktree_get_root_path(worktree));
3255 if (error)
3256 goto done;
3258 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3259 if (error)
3260 goto done;
3262 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3263 got_worktree_get_head_ref_name(worktree), 0);
3264 if (error != NULL)
3265 goto done;
3266 if (commit_id_str == NULL) {
3267 error = got_ref_resolve(&commit_id, repo, head_ref);
3268 if (error != NULL)
3269 goto done;
3270 error = got_object_id_str(&commit_id_str, commit_id);
3271 if (error != NULL)
3272 goto done;
3273 } else {
3274 struct got_reflist_head refs;
3275 TAILQ_INIT(&refs);
3276 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3277 NULL);
3278 if (error)
3279 goto done;
3280 error = got_repo_match_object_id(&commit_id, NULL,
3281 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3282 got_ref_list_free(&refs);
3283 free(commit_id_str);
3284 commit_id_str = NULL;
3285 if (error)
3286 goto done;
3287 error = got_object_id_str(&commit_id_str, commit_id);
3288 if (error)
3289 goto done;
3292 if (branch_name) {
3293 struct got_object_id *head_commit_id;
3294 TAILQ_FOREACH(pe, &paths, entry) {
3295 if (pe->path_len == 0)
3296 continue;
3297 error = got_error_msg(GOT_ERR_BAD_PATH,
3298 "switching between branches requires that "
3299 "the entire work tree gets updated");
3300 goto done;
3302 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3303 if (error)
3304 goto done;
3305 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3306 repo);
3307 free(head_commit_id);
3308 if (error != NULL)
3309 goto done;
3310 error = check_same_branch(commit_id, head_ref, NULL, repo);
3311 if (error)
3312 goto done;
3313 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3314 if (error)
3315 goto done;
3316 } else {
3317 error = check_linear_ancestry(commit_id,
3318 got_worktree_get_base_commit_id(worktree), 0, repo);
3319 if (error != NULL) {
3320 if (error->code == GOT_ERR_ANCESTRY)
3321 error = got_error(GOT_ERR_BRANCH_MOVED);
3322 goto done;
3324 error = check_same_branch(commit_id, head_ref, NULL, repo);
3325 if (error)
3326 goto done;
3329 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3330 commit_id) != 0) {
3331 error = got_worktree_set_base_commit_id(worktree, repo,
3332 commit_id);
3333 if (error)
3334 goto done;
3337 memset(&upa, 0, sizeof(upa));
3338 error = got_worktree_checkout_files(worktree, &paths, repo,
3339 update_progress, &upa, check_cancelled, NULL);
3340 if (error != NULL)
3341 goto done;
3343 if (upa.did_something)
3344 printf("Updated to commit %s\n", commit_id_str);
3345 else
3346 printf("Already up-to-date\n");
3347 print_update_progress_stats(&upa);
3348 done:
3349 free(worktree_path);
3350 TAILQ_FOREACH(pe, &paths, entry)
3351 free((char *)pe->path);
3352 got_pathlist_free(&paths);
3353 free(commit_id);
3354 free(commit_id_str);
3355 return error;
3358 static const struct got_error *
3359 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3360 const char *path, int diff_context, int ignore_whitespace,
3361 int force_text_diff, struct got_repository *repo)
3363 const struct got_error *err = NULL;
3364 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3366 if (blob_id1) {
3367 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3368 if (err)
3369 goto done;
3372 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3373 if (err)
3374 goto done;
3376 while (path[0] == '/')
3377 path++;
3378 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3379 diff_context, ignore_whitespace, force_text_diff, stdout);
3380 done:
3381 if (blob1)
3382 got_object_blob_close(blob1);
3383 got_object_blob_close(blob2);
3384 return err;
3387 static const struct got_error *
3388 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3389 const char *path, int diff_context, int ignore_whitespace,
3390 int force_text_diff, struct got_repository *repo)
3392 const struct got_error *err = NULL;
3393 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3394 struct got_diff_blob_output_unidiff_arg arg;
3396 if (tree_id1) {
3397 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3398 if (err)
3399 goto done;
3402 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3403 if (err)
3404 goto done;
3406 arg.diff_context = diff_context;
3407 arg.ignore_whitespace = ignore_whitespace;
3408 arg.force_text_diff = force_text_diff;
3409 arg.outfile = stdout;
3410 arg.line_offsets = NULL;
3411 arg.nlines = 0;
3412 while (path[0] == '/')
3413 path++;
3414 err = got_diff_tree(tree1, tree2, path, path, repo,
3415 got_diff_blob_output_unidiff, &arg, 1);
3416 done:
3417 if (tree1)
3418 got_object_tree_close(tree1);
3419 if (tree2)
3420 got_object_tree_close(tree2);
3421 return err;
3424 static const struct got_error *
3425 get_changed_paths(struct got_pathlist_head *paths,
3426 struct got_commit_object *commit, struct got_repository *repo)
3428 const struct got_error *err = NULL;
3429 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3430 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3431 struct got_object_qid *qid;
3433 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3434 if (qid != NULL) {
3435 struct got_commit_object *pcommit;
3436 err = got_object_open_as_commit(&pcommit, repo,
3437 qid->id);
3438 if (err)
3439 return err;
3441 tree_id1 = got_object_commit_get_tree_id(pcommit);
3442 got_object_commit_close(pcommit);
3446 if (tree_id1) {
3447 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3448 if (err)
3449 goto done;
3452 tree_id2 = got_object_commit_get_tree_id(commit);
3453 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3454 if (err)
3455 goto done;
3457 err = got_diff_tree(tree1, tree2, "", "", repo,
3458 got_diff_tree_collect_changed_paths, paths, 0);
3459 done:
3460 if (tree1)
3461 got_object_tree_close(tree1);
3462 if (tree2)
3463 got_object_tree_close(tree2);
3464 return err;
3467 static const struct got_error *
3468 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3469 const char *path, int diff_context, struct got_repository *repo)
3471 const struct got_error *err = NULL;
3472 struct got_commit_object *pcommit = NULL;
3473 char *id_str1 = NULL, *id_str2 = NULL;
3474 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3475 struct got_object_qid *qid;
3477 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3478 if (qid != NULL) {
3479 err = got_object_open_as_commit(&pcommit, repo,
3480 qid->id);
3481 if (err)
3482 return err;
3485 if (path && path[0] != '\0') {
3486 int obj_type;
3487 err = got_object_id_by_path(&obj_id2, repo, id, path);
3488 if (err)
3489 goto done;
3490 err = got_object_id_str(&id_str2, obj_id2);
3491 if (err) {
3492 free(obj_id2);
3493 goto done;
3495 if (pcommit) {
3496 err = got_object_id_by_path(&obj_id1, repo,
3497 qid->id, path);
3498 if (err) {
3499 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3500 free(obj_id2);
3501 goto done;
3503 } else {
3504 err = got_object_id_str(&id_str1, obj_id1);
3505 if (err) {
3506 free(obj_id2);
3507 goto done;
3511 err = got_object_get_type(&obj_type, repo, obj_id2);
3512 if (err) {
3513 free(obj_id2);
3514 goto done;
3516 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3517 switch (obj_type) {
3518 case GOT_OBJ_TYPE_BLOB:
3519 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3520 0, 0, repo);
3521 break;
3522 case GOT_OBJ_TYPE_TREE:
3523 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3524 0, 0, repo);
3525 break;
3526 default:
3527 err = got_error(GOT_ERR_OBJ_TYPE);
3528 break;
3530 free(obj_id1);
3531 free(obj_id2);
3532 } else {
3533 obj_id2 = got_object_commit_get_tree_id(commit);
3534 err = got_object_id_str(&id_str2, obj_id2);
3535 if (err)
3536 goto done;
3537 if (pcommit) {
3538 obj_id1 = got_object_commit_get_tree_id(pcommit);
3539 err = got_object_id_str(&id_str1, obj_id1);
3540 if (err)
3541 goto done;
3543 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3544 id_str2);
3545 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3546 repo);
3548 done:
3549 free(id_str1);
3550 free(id_str2);
3551 if (pcommit)
3552 got_object_commit_close(pcommit);
3553 return err;
3556 static char *
3557 get_datestr(time_t *time, char *datebuf)
3559 struct tm mytm, *tm;
3560 char *p, *s;
3562 tm = gmtime_r(time, &mytm);
3563 if (tm == NULL)
3564 return NULL;
3565 s = asctime_r(tm, datebuf);
3566 if (s == NULL)
3567 return NULL;
3568 p = strchr(s, '\n');
3569 if (p)
3570 *p = '\0';
3571 return s;
3574 static const struct got_error *
3575 match_logmsg(int *have_match, struct got_object_id *id,
3576 struct got_commit_object *commit, regex_t *regex)
3578 const struct got_error *err = NULL;
3579 regmatch_t regmatch;
3580 char *id_str = NULL, *logmsg = NULL;
3582 *have_match = 0;
3584 err = got_object_id_str(&id_str, id);
3585 if (err)
3586 return err;
3588 err = got_object_commit_get_logmsg(&logmsg, commit);
3589 if (err)
3590 goto done;
3592 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3593 *have_match = 1;
3594 done:
3595 free(id_str);
3596 free(logmsg);
3597 return err;
3600 static void
3601 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3602 regex_t *regex)
3604 regmatch_t regmatch;
3605 struct got_pathlist_entry *pe;
3607 *have_match = 0;
3609 TAILQ_FOREACH(pe, changed_paths, entry) {
3610 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3611 *have_match = 1;
3612 break;
3617 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3619 static const struct got_error*
3620 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3621 struct got_object_id *id, struct got_repository *repo)
3623 static const struct got_error *err = NULL;
3624 struct got_reflist_entry *re;
3625 char *s;
3626 const char *name;
3628 *refs_str = NULL;
3630 TAILQ_FOREACH(re, refs, entry) {
3631 struct got_tag_object *tag = NULL;
3632 struct got_object_id *ref_id;
3633 int cmp;
3635 name = got_ref_get_name(re->ref);
3636 if (strcmp(name, GOT_REF_HEAD) == 0)
3637 continue;
3638 if (strncmp(name, "refs/", 5) == 0)
3639 name += 5;
3640 if (strncmp(name, "got/", 4) == 0)
3641 continue;
3642 if (strncmp(name, "heads/", 6) == 0)
3643 name += 6;
3644 if (strncmp(name, "remotes/", 8) == 0) {
3645 name += 8;
3646 s = strstr(name, "/" GOT_REF_HEAD);
3647 if (s != NULL && s[strlen(s)] == '\0')
3648 continue;
3650 err = got_ref_resolve(&ref_id, repo, re->ref);
3651 if (err)
3652 break;
3653 if (strncmp(name, "tags/", 5) == 0) {
3654 err = got_object_open_as_tag(&tag, repo, ref_id);
3655 if (err) {
3656 if (err->code != GOT_ERR_OBJ_TYPE) {
3657 free(ref_id);
3658 break;
3660 /* Ref points at something other than a tag. */
3661 err = NULL;
3662 tag = NULL;
3665 cmp = got_object_id_cmp(tag ?
3666 got_object_tag_get_object_id(tag) : ref_id, id);
3667 free(ref_id);
3668 if (tag)
3669 got_object_tag_close(tag);
3670 if (cmp != 0)
3671 continue;
3672 s = *refs_str;
3673 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3674 s ? ", " : "", name) == -1) {
3675 err = got_error_from_errno("asprintf");
3676 free(s);
3677 *refs_str = NULL;
3678 break;
3680 free(s);
3683 return err;
3686 static const struct got_error *
3687 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3688 struct got_repository *repo, const char *path,
3689 struct got_pathlist_head *changed_paths, int show_patch,
3690 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3691 const char *custom_refs_str)
3693 const struct got_error *err = NULL;
3694 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3695 char datebuf[26];
3696 time_t committer_time;
3697 const char *author, *committer;
3698 char *refs_str = NULL;
3700 err = got_object_id_str(&id_str, id);
3701 if (err)
3702 return err;
3704 if (custom_refs_str == NULL) {
3705 struct got_reflist_head *refs;
3706 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3707 if (refs) {
3708 err = build_refs_str(&refs_str, refs, id, repo);
3709 if (err)
3710 goto done;
3714 printf(GOT_COMMIT_SEP_STR);
3715 if (custom_refs_str)
3716 printf("commit %s (%s)\n", id_str, custom_refs_str);
3717 else
3718 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3719 refs_str ? refs_str : "", refs_str ? ")" : "");
3720 free(id_str);
3721 id_str = NULL;
3722 free(refs_str);
3723 refs_str = NULL;
3724 printf("from: %s\n", got_object_commit_get_author(commit));
3725 committer_time = got_object_commit_get_committer_time(commit);
3726 datestr = get_datestr(&committer_time, datebuf);
3727 if (datestr)
3728 printf("date: %s UTC\n", datestr);
3729 author = got_object_commit_get_author(commit);
3730 committer = got_object_commit_get_committer(commit);
3731 if (strcmp(author, committer) != 0)
3732 printf("via: %s\n", committer);
3733 if (got_object_commit_get_nparents(commit) > 1) {
3734 const struct got_object_id_queue *parent_ids;
3735 struct got_object_qid *qid;
3736 int n = 1;
3737 parent_ids = got_object_commit_get_parent_ids(commit);
3738 STAILQ_FOREACH(qid, parent_ids, entry) {
3739 err = got_object_id_str(&id_str, qid->id);
3740 if (err)
3741 goto done;
3742 printf("parent %d: %s\n", n++, id_str);
3743 free(id_str);
3744 id_str = NULL;
3748 err = got_object_commit_get_logmsg(&logmsg0, commit);
3749 if (err)
3750 goto done;
3752 logmsg = logmsg0;
3753 do {
3754 line = strsep(&logmsg, "\n");
3755 if (line)
3756 printf(" %s\n", line);
3757 } while (line);
3758 free(logmsg0);
3760 if (changed_paths) {
3761 struct got_pathlist_entry *pe;
3762 TAILQ_FOREACH(pe, changed_paths, entry) {
3763 struct got_diff_changed_path *cp = pe->data;
3764 printf(" %c %s\n", cp->status, pe->path);
3766 printf("\n");
3768 if (show_patch) {
3769 err = print_patch(commit, id, path, diff_context, repo);
3770 if (err == 0)
3771 printf("\n");
3774 if (fflush(stdout) != 0 && err == NULL)
3775 err = got_error_from_errno("fflush");
3776 done:
3777 free(id_str);
3778 free(refs_str);
3779 return err;
3782 static const struct got_error *
3783 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3784 struct got_repository *repo, const char *path, int show_changed_paths,
3785 int show_patch, const char *search_pattern, int diff_context, int limit,
3786 int log_branches, int reverse_display_order,
3787 struct got_reflist_object_id_map *refs_idmap)
3789 const struct got_error *err;
3790 struct got_commit_graph *graph;
3791 regex_t regex;
3792 int have_match;
3793 struct got_object_id_queue reversed_commits;
3794 struct got_object_qid *qid;
3795 struct got_commit_object *commit;
3796 struct got_pathlist_head changed_paths;
3797 struct got_pathlist_entry *pe;
3799 STAILQ_INIT(&reversed_commits);
3800 TAILQ_INIT(&changed_paths);
3802 if (search_pattern && regcomp(&regex, search_pattern,
3803 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3804 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3806 err = got_commit_graph_open(&graph, path, !log_branches);
3807 if (err)
3808 return err;
3809 err = got_commit_graph_iter_start(graph, root_id, repo,
3810 check_cancelled, NULL);
3811 if (err)
3812 goto done;
3813 for (;;) {
3814 struct got_object_id *id;
3816 if (sigint_received || sigpipe_received)
3817 break;
3819 err = got_commit_graph_iter_next(&id, graph, repo,
3820 check_cancelled, NULL);
3821 if (err) {
3822 if (err->code == GOT_ERR_ITER_COMPLETED)
3823 err = NULL;
3824 break;
3826 if (id == NULL)
3827 break;
3829 err = got_object_open_as_commit(&commit, repo, id);
3830 if (err)
3831 break;
3833 if (show_changed_paths && !reverse_display_order) {
3834 err = get_changed_paths(&changed_paths, commit, repo);
3835 if (err)
3836 break;
3839 if (search_pattern) {
3840 err = match_logmsg(&have_match, id, commit, &regex);
3841 if (err) {
3842 got_object_commit_close(commit);
3843 break;
3845 if (have_match == 0 && show_changed_paths)
3846 match_changed_paths(&have_match,
3847 &changed_paths, &regex);
3848 if (have_match == 0) {
3849 got_object_commit_close(commit);
3850 TAILQ_FOREACH(pe, &changed_paths, entry) {
3851 free((char *)pe->path);
3852 free(pe->data);
3854 got_pathlist_free(&changed_paths);
3855 continue;
3859 if (reverse_display_order) {
3860 err = got_object_qid_alloc(&qid, id);
3861 if (err)
3862 break;
3863 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3864 got_object_commit_close(commit);
3865 } else {
3866 err = print_commit(commit, id, repo, path,
3867 show_changed_paths ? &changed_paths : NULL,
3868 show_patch, diff_context, refs_idmap, NULL);
3869 got_object_commit_close(commit);
3870 if (err)
3871 break;
3873 if ((limit && --limit == 0) ||
3874 (end_id && got_object_id_cmp(id, end_id) == 0))
3875 break;
3877 TAILQ_FOREACH(pe, &changed_paths, entry) {
3878 free((char *)pe->path);
3879 free(pe->data);
3881 got_pathlist_free(&changed_paths);
3883 if (reverse_display_order) {
3884 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3885 err = got_object_open_as_commit(&commit, repo, qid->id);
3886 if (err)
3887 break;
3888 if (show_changed_paths) {
3889 err = get_changed_paths(&changed_paths,
3890 commit, repo);
3891 if (err)
3892 break;
3894 err = print_commit(commit, qid->id, repo, path,
3895 show_changed_paths ? &changed_paths : NULL,
3896 show_patch, diff_context, refs_idmap, NULL);
3897 got_object_commit_close(commit);
3898 if (err)
3899 break;
3900 TAILQ_FOREACH(pe, &changed_paths, entry) {
3901 free((char *)pe->path);
3902 free(pe->data);
3904 got_pathlist_free(&changed_paths);
3907 done:
3908 while (!STAILQ_EMPTY(&reversed_commits)) {
3909 qid = STAILQ_FIRST(&reversed_commits);
3910 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3911 got_object_qid_free(qid);
3913 TAILQ_FOREACH(pe, &changed_paths, entry) {
3914 free((char *)pe->path);
3915 free(pe->data);
3917 got_pathlist_free(&changed_paths);
3918 if (search_pattern)
3919 regfree(&regex);
3920 got_commit_graph_close(graph);
3921 return err;
3924 __dead static void
3925 usage_log(void)
3927 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3928 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3929 "[-R] [path]\n", getprogname());
3930 exit(1);
3933 static int
3934 get_default_log_limit(void)
3936 const char *got_default_log_limit;
3937 long long n;
3938 const char *errstr;
3940 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3941 if (got_default_log_limit == NULL)
3942 return 0;
3943 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3944 if (errstr != NULL)
3945 return 0;
3946 return n;
3949 static const struct got_error *
3950 cmd_log(int argc, char *argv[])
3952 const struct got_error *error;
3953 struct got_repository *repo = NULL;
3954 struct got_worktree *worktree = NULL;
3955 struct got_object_id *start_id = NULL, *end_id = NULL;
3956 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3957 const char *start_commit = NULL, *end_commit = NULL;
3958 const char *search_pattern = NULL;
3959 int diff_context = -1, ch;
3960 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3961 int reverse_display_order = 0;
3962 const char *errstr;
3963 struct got_reflist_head refs;
3964 struct got_reflist_object_id_map *refs_idmap = NULL;
3966 TAILQ_INIT(&refs);
3968 #ifndef PROFILE
3969 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3970 NULL)
3971 == -1)
3972 err(1, "pledge");
3973 #endif
3975 limit = get_default_log_limit();
3977 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3978 switch (ch) {
3979 case 'p':
3980 show_patch = 1;
3981 break;
3982 case 'P':
3983 show_changed_paths = 1;
3984 break;
3985 case 'c':
3986 start_commit = optarg;
3987 break;
3988 case 'C':
3989 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3990 &errstr);
3991 if (errstr != NULL)
3992 err(1, "-C option %s", errstr);
3993 break;
3994 case 'l':
3995 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3996 if (errstr != NULL)
3997 err(1, "-l option %s", errstr);
3998 break;
3999 case 'b':
4000 log_branches = 1;
4001 break;
4002 case 'r':
4003 repo_path = realpath(optarg, NULL);
4004 if (repo_path == NULL)
4005 return got_error_from_errno2("realpath",
4006 optarg);
4007 got_path_strip_trailing_slashes(repo_path);
4008 break;
4009 case 'R':
4010 reverse_display_order = 1;
4011 break;
4012 case 's':
4013 search_pattern = optarg;
4014 break;
4015 case 'x':
4016 end_commit = optarg;
4017 break;
4018 default:
4019 usage_log();
4020 /* NOTREACHED */
4024 argc -= optind;
4025 argv += optind;
4027 if (diff_context == -1)
4028 diff_context = 3;
4029 else if (!show_patch)
4030 errx(1, "-C requires -p");
4032 cwd = getcwd(NULL, 0);
4033 if (cwd == NULL) {
4034 error = got_error_from_errno("getcwd");
4035 goto done;
4038 if (repo_path == NULL) {
4039 error = got_worktree_open(&worktree, cwd);
4040 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4041 goto done;
4042 error = NULL;
4045 if (argc == 1) {
4046 if (worktree) {
4047 error = got_worktree_resolve_path(&path, worktree,
4048 argv[0]);
4049 if (error)
4050 goto done;
4051 } else {
4052 path = strdup(argv[0]);
4053 if (path == NULL) {
4054 error = got_error_from_errno("strdup");
4055 goto done;
4058 } else if (argc != 0)
4059 usage_log();
4061 if (repo_path == NULL) {
4062 repo_path = worktree ?
4063 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4065 if (repo_path == NULL) {
4066 error = got_error_from_errno("strdup");
4067 goto done;
4070 error = got_repo_open(&repo, repo_path, NULL);
4071 if (error != NULL)
4072 goto done;
4074 error = apply_unveil(got_repo_get_path(repo), 1,
4075 worktree ? got_worktree_get_root_path(worktree) : NULL);
4076 if (error)
4077 goto done;
4079 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4080 if (error)
4081 goto done;
4083 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4084 if (error)
4085 goto done;
4087 if (start_commit == NULL) {
4088 struct got_reference *head_ref;
4089 struct got_commit_object *commit = NULL;
4090 error = got_ref_open(&head_ref, repo,
4091 worktree ? got_worktree_get_head_ref_name(worktree)
4092 : GOT_REF_HEAD, 0);
4093 if (error != NULL)
4094 goto done;
4095 error = got_ref_resolve(&start_id, repo, head_ref);
4096 got_ref_close(head_ref);
4097 if (error != NULL)
4098 goto done;
4099 error = got_object_open_as_commit(&commit, repo,
4100 start_id);
4101 if (error != NULL)
4102 goto done;
4103 got_object_commit_close(commit);
4104 } else {
4105 error = got_repo_match_object_id(&start_id, NULL,
4106 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4107 if (error != NULL)
4108 goto done;
4110 if (end_commit != NULL) {
4111 error = got_repo_match_object_id(&end_id, NULL,
4112 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4113 if (error != NULL)
4114 goto done;
4117 if (worktree) {
4119 * If a path was specified on the command line it was resolved
4120 * to a path in the work tree above. Prepend the work tree's
4121 * path prefix to obtain the corresponding in-repository path.
4123 if (path) {
4124 const char *prefix;
4125 prefix = got_worktree_get_path_prefix(worktree);
4126 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4127 (path[0] != '\0') ? "/" : "", path) == -1) {
4128 error = got_error_from_errno("asprintf");
4129 goto done;
4132 } else
4133 error = got_repo_map_path(&in_repo_path, repo,
4134 path ? path : "");
4135 if (error != NULL)
4136 goto done;
4137 if (in_repo_path) {
4138 free(path);
4139 path = in_repo_path;
4142 error = print_commits(start_id, end_id, repo, path ? path : "",
4143 show_changed_paths, show_patch, search_pattern, diff_context,
4144 limit, log_branches, reverse_display_order, refs_idmap);
4145 done:
4146 free(path);
4147 free(repo_path);
4148 free(cwd);
4149 if (worktree)
4150 got_worktree_close(worktree);
4151 if (repo) {
4152 const struct got_error *close_err = got_repo_close(repo);
4153 if (error == NULL)
4154 error = close_err;
4156 if (refs_idmap)
4157 got_reflist_object_id_map_free(refs_idmap);
4158 got_ref_list_free(&refs);
4159 return error;
4162 __dead static void
4163 usage_diff(void)
4165 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4166 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4167 exit(1);
4170 struct print_diff_arg {
4171 struct got_repository *repo;
4172 struct got_worktree *worktree;
4173 int diff_context;
4174 const char *id_str;
4175 int header_shown;
4176 int diff_staged;
4177 int ignore_whitespace;
4178 int force_text_diff;
4182 * Create a file which contains the target path of a symlink so we can feed
4183 * it as content to the diff engine.
4185 static const struct got_error *
4186 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4187 const char *abspath)
4189 const struct got_error *err = NULL;
4190 char target_path[PATH_MAX];
4191 ssize_t target_len, outlen;
4193 *fd = -1;
4195 if (dirfd != -1) {
4196 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4197 if (target_len == -1)
4198 return got_error_from_errno2("readlinkat", abspath);
4199 } else {
4200 target_len = readlink(abspath, target_path, PATH_MAX);
4201 if (target_len == -1)
4202 return got_error_from_errno2("readlink", abspath);
4205 *fd = got_opentempfd();
4206 if (*fd == -1)
4207 return got_error_from_errno("got_opentempfd");
4209 outlen = write(*fd, target_path, target_len);
4210 if (outlen == -1) {
4211 err = got_error_from_errno("got_opentempfd");
4212 goto done;
4215 if (lseek(*fd, 0, SEEK_SET) == -1) {
4216 err = got_error_from_errno2("lseek", abspath);
4217 goto done;
4219 done:
4220 if (err) {
4221 close(*fd);
4222 *fd = -1;
4224 return err;
4227 static const struct got_error *
4228 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4229 const char *path, struct got_object_id *blob_id,
4230 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4231 int dirfd, const char *de_name)
4233 struct print_diff_arg *a = arg;
4234 const struct got_error *err = NULL;
4235 struct got_blob_object *blob1 = NULL;
4236 int fd = -1;
4237 FILE *f2 = NULL;
4238 char *abspath = NULL, *label1 = NULL;
4239 struct stat sb;
4241 if (a->diff_staged) {
4242 if (staged_status != GOT_STATUS_MODIFY &&
4243 staged_status != GOT_STATUS_ADD &&
4244 staged_status != GOT_STATUS_DELETE)
4245 return NULL;
4246 } else {
4247 if (staged_status == GOT_STATUS_DELETE)
4248 return NULL;
4249 if (status == GOT_STATUS_NONEXISTENT)
4250 return got_error_set_errno(ENOENT, path);
4251 if (status != GOT_STATUS_MODIFY &&
4252 status != GOT_STATUS_ADD &&
4253 status != GOT_STATUS_DELETE &&
4254 status != GOT_STATUS_CONFLICT)
4255 return NULL;
4258 if (!a->header_shown) {
4259 printf("diff %s %s%s\n", a->id_str,
4260 got_worktree_get_root_path(a->worktree),
4261 a->diff_staged ? " (staged changes)" : "");
4262 a->header_shown = 1;
4265 if (a->diff_staged) {
4266 const char *label1 = NULL, *label2 = NULL;
4267 switch (staged_status) {
4268 case GOT_STATUS_MODIFY:
4269 label1 = path;
4270 label2 = path;
4271 break;
4272 case GOT_STATUS_ADD:
4273 label2 = path;
4274 break;
4275 case GOT_STATUS_DELETE:
4276 label1 = path;
4277 break;
4278 default:
4279 return got_error(GOT_ERR_FILE_STATUS);
4281 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4282 staged_blob_id, label1, label2, a->diff_context,
4283 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4286 if (staged_status == GOT_STATUS_ADD ||
4287 staged_status == GOT_STATUS_MODIFY) {
4288 char *id_str;
4289 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4290 8192);
4291 if (err)
4292 goto done;
4293 err = got_object_id_str(&id_str, staged_blob_id);
4294 if (err)
4295 goto done;
4296 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4297 err = got_error_from_errno("asprintf");
4298 free(id_str);
4299 goto done;
4301 free(id_str);
4302 } else if (status != GOT_STATUS_ADD) {
4303 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4304 if (err)
4305 goto done;
4308 if (status != GOT_STATUS_DELETE) {
4309 if (asprintf(&abspath, "%s/%s",
4310 got_worktree_get_root_path(a->worktree), path) == -1) {
4311 err = got_error_from_errno("asprintf");
4312 goto done;
4315 if (dirfd != -1) {
4316 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4317 if (fd == -1) {
4318 if (errno != ELOOP) {
4319 err = got_error_from_errno2("openat",
4320 abspath);
4321 goto done;
4323 err = get_symlink_target_file(&fd, dirfd,
4324 de_name, abspath);
4325 if (err)
4326 goto done;
4328 } else {
4329 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4330 if (fd == -1) {
4331 if (errno != ELOOP) {
4332 err = got_error_from_errno2("open",
4333 abspath);
4334 goto done;
4336 err = get_symlink_target_file(&fd, dirfd,
4337 de_name, abspath);
4338 if (err)
4339 goto done;
4342 if (fstat(fd, &sb) == -1) {
4343 err = got_error_from_errno2("fstat", abspath);
4344 goto done;
4346 f2 = fdopen(fd, "r");
4347 if (f2 == NULL) {
4348 err = got_error_from_errno2("fdopen", abspath);
4349 goto done;
4351 fd = -1;
4352 } else
4353 sb.st_size = 0;
4355 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4356 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4357 done:
4358 if (blob1)
4359 got_object_blob_close(blob1);
4360 if (f2 && fclose(f2) == EOF && err == NULL)
4361 err = got_error_from_errno("fclose");
4362 if (fd != -1 && close(fd) == -1 && err == NULL)
4363 err = got_error_from_errno("close");
4364 free(abspath);
4365 return err;
4368 static const struct got_error *
4369 cmd_diff(int argc, char *argv[])
4371 const struct got_error *error;
4372 struct got_repository *repo = NULL;
4373 struct got_worktree *worktree = NULL;
4374 char *cwd = NULL, *repo_path = NULL;
4375 struct got_object_id *id1 = NULL, *id2 = NULL;
4376 const char *id_str1 = NULL, *id_str2 = NULL;
4377 char *label1 = NULL, *label2 = NULL;
4378 int type1, type2;
4379 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4380 int force_text_diff = 0;
4381 const char *errstr;
4382 char *path = NULL;
4383 struct got_reflist_head refs;
4385 TAILQ_INIT(&refs);
4387 #ifndef PROFILE
4388 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4389 NULL) == -1)
4390 err(1, "pledge");
4391 #endif
4393 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4394 switch (ch) {
4395 case 'a':
4396 force_text_diff = 1;
4397 break;
4398 case 'C':
4399 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4400 &errstr);
4401 if (errstr != NULL)
4402 err(1, "-C option %s", errstr);
4403 break;
4404 case 'r':
4405 repo_path = realpath(optarg, NULL);
4406 if (repo_path == NULL)
4407 return got_error_from_errno2("realpath",
4408 optarg);
4409 got_path_strip_trailing_slashes(repo_path);
4410 break;
4411 case 's':
4412 diff_staged = 1;
4413 break;
4414 case 'w':
4415 ignore_whitespace = 1;
4416 break;
4417 default:
4418 usage_diff();
4419 /* NOTREACHED */
4423 argc -= optind;
4424 argv += optind;
4426 cwd = getcwd(NULL, 0);
4427 if (cwd == NULL) {
4428 error = got_error_from_errno("getcwd");
4429 goto done;
4431 if (argc <= 1) {
4432 if (repo_path)
4433 errx(1,
4434 "-r option can't be used when diffing a work tree");
4435 error = got_worktree_open(&worktree, cwd);
4436 if (error) {
4437 if (error->code == GOT_ERR_NOT_WORKTREE)
4438 error = wrap_not_worktree_error(error, "diff",
4439 cwd);
4440 goto done;
4442 repo_path = strdup(got_worktree_get_repo_path(worktree));
4443 if (repo_path == NULL) {
4444 error = got_error_from_errno("strdup");
4445 goto done;
4447 if (argc == 1) {
4448 error = got_worktree_resolve_path(&path, worktree,
4449 argv[0]);
4450 if (error)
4451 goto done;
4452 } else {
4453 path = strdup("");
4454 if (path == NULL) {
4455 error = got_error_from_errno("strdup");
4456 goto done;
4459 } else if (argc == 2) {
4460 if (diff_staged)
4461 errx(1, "-s option can't be used when diffing "
4462 "objects in repository");
4463 id_str1 = argv[0];
4464 id_str2 = argv[1];
4465 if (repo_path == NULL) {
4466 error = got_worktree_open(&worktree, cwd);
4467 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4468 goto done;
4469 repo_path = strdup(worktree ?
4470 got_worktree_get_repo_path(worktree) : cwd);
4471 if (repo_path == NULL) {
4472 error = got_error_from_errno("strdup");
4473 goto done;
4476 } else
4477 usage_diff();
4479 error = got_repo_open(&repo, repo_path, NULL);
4480 free(repo_path);
4481 if (error != NULL)
4482 goto done;
4484 error = apply_unveil(got_repo_get_path(repo), 1,
4485 worktree ? got_worktree_get_root_path(worktree) : NULL);
4486 if (error)
4487 goto done;
4489 if (argc <= 1) {
4490 struct print_diff_arg arg;
4491 struct got_pathlist_head paths;
4492 char *id_str;
4494 TAILQ_INIT(&paths);
4496 error = got_object_id_str(&id_str,
4497 got_worktree_get_base_commit_id(worktree));
4498 if (error)
4499 goto done;
4500 arg.repo = repo;
4501 arg.worktree = worktree;
4502 arg.diff_context = diff_context;
4503 arg.id_str = id_str;
4504 arg.header_shown = 0;
4505 arg.diff_staged = diff_staged;
4506 arg.ignore_whitespace = ignore_whitespace;
4507 arg.force_text_diff = force_text_diff;
4509 error = got_pathlist_append(&paths, path, NULL);
4510 if (error)
4511 goto done;
4513 error = got_worktree_status(worktree, &paths, repo, 0,
4514 print_diff, &arg, check_cancelled, NULL);
4515 free(id_str);
4516 got_pathlist_free(&paths);
4517 goto done;
4520 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4521 if (error)
4522 return error;
4524 error = got_repo_match_object_id(&id1, &label1, id_str1,
4525 GOT_OBJ_TYPE_ANY, &refs, repo);
4526 if (error)
4527 goto done;
4529 error = got_repo_match_object_id(&id2, &label2, id_str2,
4530 GOT_OBJ_TYPE_ANY, &refs, repo);
4531 if (error)
4532 goto done;
4534 error = got_object_get_type(&type1, repo, id1);
4535 if (error)
4536 goto done;
4538 error = got_object_get_type(&type2, repo, id2);
4539 if (error)
4540 goto done;
4542 if (type1 != type2) {
4543 error = got_error(GOT_ERR_OBJ_TYPE);
4544 goto done;
4547 switch (type1) {
4548 case GOT_OBJ_TYPE_BLOB:
4549 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4550 NULL, NULL, diff_context, ignore_whitespace,
4551 force_text_diff, repo, stdout);
4552 break;
4553 case GOT_OBJ_TYPE_TREE:
4554 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4555 "", "", diff_context, ignore_whitespace, force_text_diff,
4556 repo, stdout);
4557 break;
4558 case GOT_OBJ_TYPE_COMMIT:
4559 printf("diff %s %s\n", label1, label2);
4560 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4561 diff_context, ignore_whitespace, force_text_diff, repo,
4562 stdout);
4563 break;
4564 default:
4565 error = got_error(GOT_ERR_OBJ_TYPE);
4567 done:
4568 free(label1);
4569 free(label2);
4570 free(id1);
4571 free(id2);
4572 free(path);
4573 if (worktree)
4574 got_worktree_close(worktree);
4575 if (repo) {
4576 const struct got_error *close_err = got_repo_close(repo);
4577 if (error == NULL)
4578 error = close_err;
4580 got_ref_list_free(&refs);
4581 return error;
4584 __dead static void
4585 usage_blame(void)
4587 fprintf(stderr,
4588 "usage: %s blame [-c commit] [-r repository-path] path\n",
4589 getprogname());
4590 exit(1);
4593 struct blame_line {
4594 int annotated;
4595 char *id_str;
4596 char *committer;
4597 char datebuf[11]; /* YYYY-MM-DD + NUL */
4600 struct blame_cb_args {
4601 struct blame_line *lines;
4602 int nlines;
4603 int nlines_prec;
4604 int lineno_cur;
4605 off_t *line_offsets;
4606 FILE *f;
4607 struct got_repository *repo;
4610 static const struct got_error *
4611 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4613 const struct got_error *err = NULL;
4614 struct blame_cb_args *a = arg;
4615 struct blame_line *bline;
4616 char *line = NULL;
4617 size_t linesize = 0;
4618 struct got_commit_object *commit = NULL;
4619 off_t offset;
4620 struct tm tm;
4621 time_t committer_time;
4623 if (nlines != a->nlines ||
4624 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4625 return got_error(GOT_ERR_RANGE);
4627 if (sigint_received)
4628 return got_error(GOT_ERR_ITER_COMPLETED);
4630 if (lineno == -1)
4631 return NULL; /* no change in this commit */
4633 /* Annotate this line. */
4634 bline = &a->lines[lineno - 1];
4635 if (bline->annotated)
4636 return NULL;
4637 err = got_object_id_str(&bline->id_str, id);
4638 if (err)
4639 return err;
4641 err = got_object_open_as_commit(&commit, a->repo, id);
4642 if (err)
4643 goto done;
4645 bline->committer = strdup(got_object_commit_get_committer(commit));
4646 if (bline->committer == NULL) {
4647 err = got_error_from_errno("strdup");
4648 goto done;
4651 committer_time = got_object_commit_get_committer_time(commit);
4652 if (localtime_r(&committer_time, &tm) == NULL)
4653 return got_error_from_errno("localtime_r");
4654 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4655 &tm) == 0) {
4656 err = got_error(GOT_ERR_NO_SPACE);
4657 goto done;
4659 bline->annotated = 1;
4661 /* Print lines annotated so far. */
4662 bline = &a->lines[a->lineno_cur - 1];
4663 if (!bline->annotated)
4664 goto done;
4666 offset = a->line_offsets[a->lineno_cur - 1];
4667 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4668 err = got_error_from_errno("fseeko");
4669 goto done;
4672 while (bline->annotated) {
4673 char *smallerthan, *at, *nl, *committer;
4674 size_t len;
4676 if (getline(&line, &linesize, a->f) == -1) {
4677 if (ferror(a->f))
4678 err = got_error_from_errno("getline");
4679 break;
4682 committer = bline->committer;
4683 smallerthan = strchr(committer, '<');
4684 if (smallerthan && smallerthan[1] != '\0')
4685 committer = smallerthan + 1;
4686 at = strchr(committer, '@');
4687 if (at)
4688 *at = '\0';
4689 len = strlen(committer);
4690 if (len >= 9)
4691 committer[8] = '\0';
4693 nl = strchr(line, '\n');
4694 if (nl)
4695 *nl = '\0';
4696 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4697 bline->id_str, bline->datebuf, committer, line);
4699 a->lineno_cur++;
4700 bline = &a->lines[a->lineno_cur - 1];
4702 done:
4703 if (commit)
4704 got_object_commit_close(commit);
4705 free(line);
4706 return err;
4709 static const struct got_error *
4710 cmd_blame(int argc, char *argv[])
4712 const struct got_error *error;
4713 struct got_repository *repo = NULL;
4714 struct got_worktree *worktree = NULL;
4715 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4716 char *link_target = NULL;
4717 struct got_object_id *obj_id = NULL;
4718 struct got_object_id *commit_id = NULL;
4719 struct got_blob_object *blob = NULL;
4720 char *commit_id_str = NULL;
4721 struct blame_cb_args bca;
4722 int ch, obj_type, i;
4723 off_t filesize;
4725 memset(&bca, 0, sizeof(bca));
4727 #ifndef PROFILE
4728 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4729 NULL) == -1)
4730 err(1, "pledge");
4731 #endif
4733 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4734 switch (ch) {
4735 case 'c':
4736 commit_id_str = optarg;
4737 break;
4738 case 'r':
4739 repo_path = realpath(optarg, NULL);
4740 if (repo_path == NULL)
4741 return got_error_from_errno2("realpath",
4742 optarg);
4743 got_path_strip_trailing_slashes(repo_path);
4744 break;
4745 default:
4746 usage_blame();
4747 /* NOTREACHED */
4751 argc -= optind;
4752 argv += optind;
4754 if (argc == 1)
4755 path = argv[0];
4756 else
4757 usage_blame();
4759 cwd = getcwd(NULL, 0);
4760 if (cwd == NULL) {
4761 error = got_error_from_errno("getcwd");
4762 goto done;
4764 if (repo_path == NULL) {
4765 error = got_worktree_open(&worktree, cwd);
4766 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4767 goto done;
4768 else
4769 error = NULL;
4770 if (worktree) {
4771 repo_path =
4772 strdup(got_worktree_get_repo_path(worktree));
4773 if (repo_path == NULL) {
4774 error = got_error_from_errno("strdup");
4775 if (error)
4776 goto done;
4778 } else {
4779 repo_path = strdup(cwd);
4780 if (repo_path == NULL) {
4781 error = got_error_from_errno("strdup");
4782 goto done;
4787 error = got_repo_open(&repo, repo_path, NULL);
4788 if (error != NULL)
4789 goto done;
4791 if (worktree) {
4792 const char *prefix = got_worktree_get_path_prefix(worktree);
4793 char *p;
4795 error = got_worktree_resolve_path(&p, worktree, path);
4796 if (error)
4797 goto done;
4798 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4799 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4800 p) == -1) {
4801 error = got_error_from_errno("asprintf");
4802 free(p);
4803 goto done;
4805 free(p);
4806 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4807 } else {
4808 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4809 if (error)
4810 goto done;
4811 error = got_repo_map_path(&in_repo_path, repo, path);
4813 if (error)
4814 goto done;
4816 if (commit_id_str == NULL) {
4817 struct got_reference *head_ref;
4818 error = got_ref_open(&head_ref, repo, worktree ?
4819 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4820 if (error != NULL)
4821 goto done;
4822 error = got_ref_resolve(&commit_id, repo, head_ref);
4823 got_ref_close(head_ref);
4824 if (error != NULL)
4825 goto done;
4826 } else {
4827 struct got_reflist_head refs;
4828 TAILQ_INIT(&refs);
4829 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4830 NULL);
4831 if (error)
4832 goto done;
4833 error = got_repo_match_object_id(&commit_id, NULL,
4834 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4835 got_ref_list_free(&refs);
4836 if (error)
4837 goto done;
4840 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4841 commit_id, repo);
4842 if (error)
4843 goto done;
4845 error = got_object_id_by_path(&obj_id, repo, commit_id,
4846 link_target ? link_target : in_repo_path);
4847 if (error)
4848 goto done;
4850 error = got_object_get_type(&obj_type, repo, obj_id);
4851 if (error)
4852 goto done;
4854 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4855 error = got_error_path(link_target ? link_target : in_repo_path,
4856 GOT_ERR_OBJ_TYPE);
4857 goto done;
4860 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4861 if (error)
4862 goto done;
4863 bca.f = got_opentemp();
4864 if (bca.f == NULL) {
4865 error = got_error_from_errno("got_opentemp");
4866 goto done;
4868 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4869 &bca.line_offsets, bca.f, blob);
4870 if (error || bca.nlines == 0)
4871 goto done;
4873 /* Don't include \n at EOF in the blame line count. */
4874 if (bca.line_offsets[bca.nlines - 1] == filesize)
4875 bca.nlines--;
4877 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4878 if (bca.lines == NULL) {
4879 error = got_error_from_errno("calloc");
4880 goto done;
4882 bca.lineno_cur = 1;
4883 bca.nlines_prec = 0;
4884 i = bca.nlines;
4885 while (i > 0) {
4886 i /= 10;
4887 bca.nlines_prec++;
4889 bca.repo = repo;
4891 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4892 repo, blame_cb, &bca, check_cancelled, NULL);
4893 done:
4894 free(in_repo_path);
4895 free(link_target);
4896 free(repo_path);
4897 free(cwd);
4898 free(commit_id);
4899 free(obj_id);
4900 if (blob)
4901 got_object_blob_close(blob);
4902 if (worktree)
4903 got_worktree_close(worktree);
4904 if (repo) {
4905 const struct got_error *close_err = got_repo_close(repo);
4906 if (error == NULL)
4907 error = close_err;
4909 if (bca.lines) {
4910 for (i = 0; i < bca.nlines; i++) {
4911 struct blame_line *bline = &bca.lines[i];
4912 free(bline->id_str);
4913 free(bline->committer);
4915 free(bca.lines);
4917 free(bca.line_offsets);
4918 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4919 error = got_error_from_errno("fclose");
4920 return error;
4923 __dead static void
4924 usage_tree(void)
4926 fprintf(stderr,
4927 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4928 getprogname());
4929 exit(1);
4932 static const struct got_error *
4933 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4934 const char *root_path, struct got_repository *repo)
4936 const struct got_error *err = NULL;
4937 int is_root_path = (strcmp(path, root_path) == 0);
4938 const char *modestr = "";
4939 mode_t mode = got_tree_entry_get_mode(te);
4940 char *link_target = NULL;
4942 path += strlen(root_path);
4943 while (path[0] == '/')
4944 path++;
4946 if (got_object_tree_entry_is_submodule(te))
4947 modestr = "$";
4948 else if (S_ISLNK(mode)) {
4949 int i;
4951 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4952 if (err)
4953 return err;
4954 for (i = 0; i < strlen(link_target); i++) {
4955 if (!isprint((unsigned char)link_target[i]))
4956 link_target[i] = '?';
4959 modestr = "@";
4961 else if (S_ISDIR(mode))
4962 modestr = "/";
4963 else if (mode & S_IXUSR)
4964 modestr = "*";
4966 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4967 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4968 link_target ? " -> ": "", link_target ? link_target : "");
4970 free(link_target);
4971 return NULL;
4974 static const struct got_error *
4975 print_tree(const char *path, struct got_object_id *commit_id,
4976 int show_ids, int recurse, const char *root_path,
4977 struct got_repository *repo)
4979 const struct got_error *err = NULL;
4980 struct got_object_id *tree_id = NULL;
4981 struct got_tree_object *tree = NULL;
4982 int nentries, i;
4984 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4985 if (err)
4986 goto done;
4988 err = got_object_open_as_tree(&tree, repo, tree_id);
4989 if (err)
4990 goto done;
4991 nentries = got_object_tree_get_nentries(tree);
4992 for (i = 0; i < nentries; i++) {
4993 struct got_tree_entry *te;
4994 char *id = NULL;
4996 if (sigint_received || sigpipe_received)
4997 break;
4999 te = got_object_tree_get_entry(tree, i);
5000 if (show_ids) {
5001 char *id_str;
5002 err = got_object_id_str(&id_str,
5003 got_tree_entry_get_id(te));
5004 if (err)
5005 goto done;
5006 if (asprintf(&id, "%s ", id_str) == -1) {
5007 err = got_error_from_errno("asprintf");
5008 free(id_str);
5009 goto done;
5011 free(id_str);
5013 err = print_entry(te, id, path, root_path, repo);
5014 free(id);
5015 if (err)
5016 goto done;
5018 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5019 char *child_path;
5020 if (asprintf(&child_path, "%s%s%s", path,
5021 path[0] == '/' && path[1] == '\0' ? "" : "/",
5022 got_tree_entry_get_name(te)) == -1) {
5023 err = got_error_from_errno("asprintf");
5024 goto done;
5026 err = print_tree(child_path, commit_id, show_ids, 1,
5027 root_path, repo);
5028 free(child_path);
5029 if (err)
5030 goto done;
5033 done:
5034 if (tree)
5035 got_object_tree_close(tree);
5036 free(tree_id);
5037 return err;
5040 static const struct got_error *
5041 cmd_tree(int argc, char *argv[])
5043 const struct got_error *error;
5044 struct got_repository *repo = NULL;
5045 struct got_worktree *worktree = NULL;
5046 const char *path, *refname = NULL;
5047 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5048 struct got_object_id *commit_id = NULL;
5049 char *commit_id_str = NULL;
5050 int show_ids = 0, recurse = 0;
5051 int ch;
5053 #ifndef PROFILE
5054 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5055 NULL) == -1)
5056 err(1, "pledge");
5057 #endif
5059 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5060 switch (ch) {
5061 case 'c':
5062 commit_id_str = optarg;
5063 break;
5064 case 'r':
5065 repo_path = realpath(optarg, NULL);
5066 if (repo_path == NULL)
5067 return got_error_from_errno2("realpath",
5068 optarg);
5069 got_path_strip_trailing_slashes(repo_path);
5070 break;
5071 case 'i':
5072 show_ids = 1;
5073 break;
5074 case 'R':
5075 recurse = 1;
5076 break;
5077 default:
5078 usage_tree();
5079 /* NOTREACHED */
5083 argc -= optind;
5084 argv += optind;
5086 if (argc == 1)
5087 path = argv[0];
5088 else if (argc > 1)
5089 usage_tree();
5090 else
5091 path = NULL;
5093 cwd = getcwd(NULL, 0);
5094 if (cwd == NULL) {
5095 error = got_error_from_errno("getcwd");
5096 goto done;
5098 if (repo_path == NULL) {
5099 error = got_worktree_open(&worktree, cwd);
5100 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5101 goto done;
5102 else
5103 error = NULL;
5104 if (worktree) {
5105 repo_path =
5106 strdup(got_worktree_get_repo_path(worktree));
5107 if (repo_path == NULL)
5108 error = got_error_from_errno("strdup");
5109 if (error)
5110 goto done;
5111 } else {
5112 repo_path = strdup(cwd);
5113 if (repo_path == NULL) {
5114 error = got_error_from_errno("strdup");
5115 goto done;
5120 error = got_repo_open(&repo, repo_path, NULL);
5121 if (error != NULL)
5122 goto done;
5124 if (worktree) {
5125 const char *prefix = got_worktree_get_path_prefix(worktree);
5126 char *p;
5128 if (path == NULL)
5129 path = "";
5130 error = got_worktree_resolve_path(&p, worktree, path);
5131 if (error)
5132 goto done;
5133 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5134 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5135 p) == -1) {
5136 error = got_error_from_errno("asprintf");
5137 free(p);
5138 goto done;
5140 free(p);
5141 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5142 if (error)
5143 goto done;
5144 } else {
5145 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5146 if (error)
5147 goto done;
5148 if (path == NULL)
5149 path = "/";
5150 error = got_repo_map_path(&in_repo_path, repo, path);
5151 if (error != NULL)
5152 goto done;
5155 if (commit_id_str == NULL) {
5156 struct got_reference *head_ref;
5157 if (worktree)
5158 refname = got_worktree_get_head_ref_name(worktree);
5159 else
5160 refname = GOT_REF_HEAD;
5161 error = got_ref_open(&head_ref, repo, refname, 0);
5162 if (error != NULL)
5163 goto done;
5164 error = got_ref_resolve(&commit_id, repo, head_ref);
5165 got_ref_close(head_ref);
5166 if (error != NULL)
5167 goto done;
5168 } else {
5169 struct got_reflist_head refs;
5170 TAILQ_INIT(&refs);
5171 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5172 NULL);
5173 if (error)
5174 goto done;
5175 error = got_repo_match_object_id(&commit_id, NULL,
5176 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5177 got_ref_list_free(&refs);
5178 if (error)
5179 goto done;
5182 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5183 in_repo_path, repo);
5184 done:
5185 free(in_repo_path);
5186 free(repo_path);
5187 free(cwd);
5188 free(commit_id);
5189 if (worktree)
5190 got_worktree_close(worktree);
5191 if (repo) {
5192 const struct got_error *close_err = got_repo_close(repo);
5193 if (error == NULL)
5194 error = close_err;
5196 return error;
5199 __dead static void
5200 usage_status(void)
5202 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5203 getprogname());
5204 exit(1);
5207 static const struct got_error *
5208 print_status(void *arg, unsigned char status, unsigned char staged_status,
5209 const char *path, struct got_object_id *blob_id,
5210 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5211 int dirfd, const char *de_name)
5213 if (status == staged_status && (status == GOT_STATUS_DELETE))
5214 status = GOT_STATUS_NO_CHANGE;
5215 if (arg) {
5216 char *status_codes = arg;
5217 size_t ncodes = strlen(status_codes);
5218 int i;
5219 for (i = 0; i < ncodes ; i++) {
5220 if (status == status_codes[i] ||
5221 staged_status == status_codes[i])
5222 break;
5224 if (i == ncodes)
5225 return NULL;
5227 printf("%c%c %s\n", status, staged_status, path);
5228 return NULL;
5231 static const struct got_error *
5232 cmd_status(int argc, char *argv[])
5234 const struct got_error *error = NULL;
5235 struct got_repository *repo = NULL;
5236 struct got_worktree *worktree = NULL;
5237 char *cwd = NULL, *status_codes = NULL;;
5238 struct got_pathlist_head paths;
5239 struct got_pathlist_entry *pe;
5240 int ch, i, no_ignores = 0;
5242 TAILQ_INIT(&paths);
5244 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5245 switch (ch) {
5246 case 'I':
5247 no_ignores = 1;
5248 break;
5249 case 's':
5250 for (i = 0; i < strlen(optarg); i++) {
5251 switch (optarg[i]) {
5252 case GOT_STATUS_MODIFY:
5253 case GOT_STATUS_ADD:
5254 case GOT_STATUS_DELETE:
5255 case GOT_STATUS_CONFLICT:
5256 case GOT_STATUS_MISSING:
5257 case GOT_STATUS_OBSTRUCTED:
5258 case GOT_STATUS_UNVERSIONED:
5259 case GOT_STATUS_MODE_CHANGE:
5260 case GOT_STATUS_NONEXISTENT:
5261 break;
5262 default:
5263 errx(1, "invalid status code '%c'",
5264 optarg[i]);
5267 status_codes = optarg;
5268 break;
5269 default:
5270 usage_status();
5271 /* NOTREACHED */
5275 argc -= optind;
5276 argv += optind;
5278 #ifndef PROFILE
5279 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5280 NULL) == -1)
5281 err(1, "pledge");
5282 #endif
5283 cwd = getcwd(NULL, 0);
5284 if (cwd == NULL) {
5285 error = got_error_from_errno("getcwd");
5286 goto done;
5289 error = got_worktree_open(&worktree, cwd);
5290 if (error) {
5291 if (error->code == GOT_ERR_NOT_WORKTREE)
5292 error = wrap_not_worktree_error(error, "status", cwd);
5293 goto done;
5296 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5297 NULL);
5298 if (error != NULL)
5299 goto done;
5301 error = apply_unveil(got_repo_get_path(repo), 1,
5302 got_worktree_get_root_path(worktree));
5303 if (error)
5304 goto done;
5306 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5307 if (error)
5308 goto done;
5310 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5311 print_status, status_codes, check_cancelled, NULL);
5312 done:
5313 TAILQ_FOREACH(pe, &paths, entry)
5314 free((char *)pe->path);
5315 got_pathlist_free(&paths);
5316 free(cwd);
5317 return error;
5320 __dead static void
5321 usage_ref(void)
5323 fprintf(stderr,
5324 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5325 "[-d] [name]\n",
5326 getprogname());
5327 exit(1);
5330 static const struct got_error *
5331 list_refs(struct got_repository *repo, const char *refname)
5333 static const struct got_error *err = NULL;
5334 struct got_reflist_head refs;
5335 struct got_reflist_entry *re;
5337 TAILQ_INIT(&refs);
5338 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5339 if (err)
5340 return err;
5342 TAILQ_FOREACH(re, &refs, entry) {
5343 char *refstr;
5344 refstr = got_ref_to_str(re->ref);
5345 if (refstr == NULL)
5346 return got_error_from_errno("got_ref_to_str");
5347 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5348 free(refstr);
5351 got_ref_list_free(&refs);
5352 return NULL;
5355 static const struct got_error *
5356 delete_ref_by_name(struct got_repository *repo, const char *refname)
5358 const struct got_error *err;
5359 struct got_reference *ref;
5361 err = got_ref_open(&ref, repo, refname, 0);
5362 if (err)
5363 return err;
5365 err = delete_ref(repo, ref);
5366 got_ref_close(ref);
5367 return err;
5370 static const struct got_error *
5371 add_ref(struct got_repository *repo, const char *refname, const char *target)
5373 const struct got_error *err = NULL;
5374 struct got_object_id *id;
5375 struct got_reference *ref = NULL;
5378 * Don't let the user create a reference name with a leading '-'.
5379 * While technically a valid reference name, this case is usually
5380 * an unintended typo.
5382 if (refname[0] == '-')
5383 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5385 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5386 repo);
5387 if (err) {
5388 struct got_reference *target_ref;
5390 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5391 return err;
5392 err = got_ref_open(&target_ref, repo, target, 0);
5393 if (err)
5394 return err;
5395 err = got_ref_resolve(&id, repo, target_ref);
5396 got_ref_close(target_ref);
5397 if (err)
5398 return err;
5401 err = got_ref_alloc(&ref, refname, id);
5402 if (err)
5403 goto done;
5405 err = got_ref_write(ref, repo);
5406 done:
5407 if (ref)
5408 got_ref_close(ref);
5409 free(id);
5410 return err;
5413 static const struct got_error *
5414 add_symref(struct got_repository *repo, const char *refname, const char *target)
5416 const struct got_error *err = NULL;
5417 struct got_reference *ref = NULL;
5418 struct got_reference *target_ref = NULL;
5421 * Don't let the user create a reference name with a leading '-'.
5422 * While technically a valid reference name, this case is usually
5423 * an unintended typo.
5425 if (refname[0] == '-')
5426 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5428 err = got_ref_open(&target_ref, repo, target, 0);
5429 if (err)
5430 return err;
5432 err = got_ref_alloc_symref(&ref, refname, target_ref);
5433 if (err)
5434 goto done;
5436 err = got_ref_write(ref, repo);
5437 done:
5438 if (target_ref)
5439 got_ref_close(target_ref);
5440 if (ref)
5441 got_ref_close(ref);
5442 return err;
5445 static const struct got_error *
5446 cmd_ref(int argc, char *argv[])
5448 const struct got_error *error = NULL;
5449 struct got_repository *repo = NULL;
5450 struct got_worktree *worktree = NULL;
5451 char *cwd = NULL, *repo_path = NULL;
5452 int ch, do_list = 0, do_delete = 0;
5453 const char *obj_arg = NULL, *symref_target= NULL;
5454 char *refname = NULL;
5456 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5457 switch (ch) {
5458 case 'c':
5459 obj_arg = optarg;
5460 break;
5461 case 'd':
5462 do_delete = 1;
5463 break;
5464 case 'r':
5465 repo_path = realpath(optarg, NULL);
5466 if (repo_path == NULL)
5467 return got_error_from_errno2("realpath",
5468 optarg);
5469 got_path_strip_trailing_slashes(repo_path);
5470 break;
5471 case 'l':
5472 do_list = 1;
5473 break;
5474 case 's':
5475 symref_target = optarg;
5476 break;
5477 default:
5478 usage_ref();
5479 /* NOTREACHED */
5483 if (obj_arg && do_list)
5484 option_conflict('c', 'l');
5485 if (obj_arg && do_delete)
5486 option_conflict('c', 'd');
5487 if (obj_arg && symref_target)
5488 option_conflict('c', 's');
5489 if (symref_target && do_delete)
5490 option_conflict('s', 'd');
5491 if (symref_target && do_list)
5492 option_conflict('s', 'l');
5493 if (do_delete && do_list)
5494 option_conflict('d', 'l');
5496 argc -= optind;
5497 argv += optind;
5499 if (do_list) {
5500 if (argc != 0 && argc != 1)
5501 usage_ref();
5502 if (argc == 1) {
5503 refname = strdup(argv[0]);
5504 if (refname == NULL) {
5505 error = got_error_from_errno("strdup");
5506 goto done;
5509 } else {
5510 if (argc != 1)
5511 usage_ref();
5512 refname = strdup(argv[0]);
5513 if (refname == NULL) {
5514 error = got_error_from_errno("strdup");
5515 goto done;
5519 if (refname)
5520 got_path_strip_trailing_slashes(refname);
5522 #ifndef PROFILE
5523 if (do_list) {
5524 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5525 NULL) == -1)
5526 err(1, "pledge");
5527 } else {
5528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5529 "sendfd unveil", NULL) == -1)
5530 err(1, "pledge");
5532 #endif
5533 cwd = getcwd(NULL, 0);
5534 if (cwd == NULL) {
5535 error = got_error_from_errno("getcwd");
5536 goto done;
5539 if (repo_path == NULL) {
5540 error = got_worktree_open(&worktree, cwd);
5541 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5542 goto done;
5543 else
5544 error = NULL;
5545 if (worktree) {
5546 repo_path =
5547 strdup(got_worktree_get_repo_path(worktree));
5548 if (repo_path == NULL)
5549 error = got_error_from_errno("strdup");
5550 if (error)
5551 goto done;
5552 } else {
5553 repo_path = strdup(cwd);
5554 if (repo_path == NULL) {
5555 error = got_error_from_errno("strdup");
5556 goto done;
5561 error = got_repo_open(&repo, repo_path, NULL);
5562 if (error != NULL)
5563 goto done;
5565 error = apply_unveil(got_repo_get_path(repo), do_list,
5566 worktree ? got_worktree_get_root_path(worktree) : NULL);
5567 if (error)
5568 goto done;
5570 if (do_list)
5571 error = list_refs(repo, refname);
5572 else if (do_delete)
5573 error = delete_ref_by_name(repo, refname);
5574 else if (symref_target)
5575 error = add_symref(repo, refname, symref_target);
5576 else {
5577 if (obj_arg == NULL)
5578 usage_ref();
5579 error = add_ref(repo, refname, obj_arg);
5581 done:
5582 free(refname);
5583 if (repo) {
5584 const struct got_error *close_err = got_repo_close(repo);
5585 if (error == NULL)
5586 error = close_err;
5588 if (worktree)
5589 got_worktree_close(worktree);
5590 free(cwd);
5591 free(repo_path);
5592 return error;
5595 __dead static void
5596 usage_branch(void)
5598 fprintf(stderr,
5599 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5600 "[name]\n", getprogname());
5601 exit(1);
5604 static const struct got_error *
5605 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5606 struct got_reference *ref)
5608 const struct got_error *err = NULL;
5609 const char *refname, *marker = " ";
5610 char *refstr;
5612 refname = got_ref_get_name(ref);
5613 if (worktree && strcmp(refname,
5614 got_worktree_get_head_ref_name(worktree)) == 0) {
5615 struct got_object_id *id = NULL;
5617 err = got_ref_resolve(&id, repo, ref);
5618 if (err)
5619 return err;
5620 if (got_object_id_cmp(id,
5621 got_worktree_get_base_commit_id(worktree)) == 0)
5622 marker = "* ";
5623 else
5624 marker = "~ ";
5625 free(id);
5628 if (strncmp(refname, "refs/heads/", 11) == 0)
5629 refname += 11;
5630 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5631 refname += 18;
5632 if (strncmp(refname, "refs/remotes/", 13) == 0)
5633 refname += 13;
5635 refstr = got_ref_to_str(ref);
5636 if (refstr == NULL)
5637 return got_error_from_errno("got_ref_to_str");
5639 printf("%s%s: %s\n", marker, refname, refstr);
5640 free(refstr);
5641 return NULL;
5644 static const struct got_error *
5645 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5647 const char *refname;
5649 if (worktree == NULL)
5650 return got_error(GOT_ERR_NOT_WORKTREE);
5652 refname = got_worktree_get_head_ref_name(worktree);
5654 if (strncmp(refname, "refs/heads/", 11) == 0)
5655 refname += 11;
5656 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5657 refname += 18;
5659 printf("%s\n", refname);
5661 return NULL;
5664 static const struct got_error *
5665 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5667 static const struct got_error *err = NULL;
5668 struct got_reflist_head refs;
5669 struct got_reflist_entry *re;
5670 struct got_reference *temp_ref = NULL;
5671 int rebase_in_progress, histedit_in_progress;
5673 TAILQ_INIT(&refs);
5675 if (worktree) {
5676 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5677 worktree);
5678 if (err)
5679 return err;
5681 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5682 worktree);
5683 if (err)
5684 return err;
5686 if (rebase_in_progress || histedit_in_progress) {
5687 err = got_ref_open(&temp_ref, repo,
5688 got_worktree_get_head_ref_name(worktree), 0);
5689 if (err)
5690 return err;
5691 list_branch(repo, worktree, temp_ref);
5692 got_ref_close(temp_ref);
5696 err = got_ref_list(&refs, repo, "refs/heads",
5697 got_ref_cmp_by_name, NULL);
5698 if (err)
5699 return err;
5701 TAILQ_FOREACH(re, &refs, entry)
5702 list_branch(repo, worktree, re->ref);
5704 got_ref_list_free(&refs);
5706 err = got_ref_list(&refs, repo, "refs/remotes",
5707 got_ref_cmp_by_name, NULL);
5708 if (err)
5709 return err;
5711 TAILQ_FOREACH(re, &refs, entry)
5712 list_branch(repo, worktree, re->ref);
5714 got_ref_list_free(&refs);
5716 return NULL;
5719 static const struct got_error *
5720 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5721 const char *branch_name)
5723 const struct got_error *err = NULL;
5724 struct got_reference *ref = NULL;
5725 char *refname;
5727 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5728 return got_error_from_errno("asprintf");
5730 err = got_ref_open(&ref, repo, refname, 0);
5731 if (err)
5732 goto done;
5734 if (worktree &&
5735 strcmp(got_worktree_get_head_ref_name(worktree),
5736 got_ref_get_name(ref)) == 0) {
5737 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5738 "will not delete this work tree's current branch");
5739 goto done;
5742 err = got_ref_delete(ref, repo);
5743 done:
5744 if (ref)
5745 got_ref_close(ref);
5746 free(refname);
5747 return err;
5750 static const struct got_error *
5751 add_branch(struct got_repository *repo, const char *branch_name,
5752 struct got_object_id *base_commit_id)
5754 const struct got_error *err = NULL;
5755 struct got_reference *ref = NULL;
5756 char *base_refname = NULL, *refname = NULL;
5759 * Don't let the user create a branch name with a leading '-'.
5760 * While technically a valid reference name, this case is usually
5761 * an unintended typo.
5763 if (branch_name[0] == '-')
5764 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5766 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5767 err = got_error_from_errno("asprintf");
5768 goto done;
5771 err = got_ref_open(&ref, repo, refname, 0);
5772 if (err == NULL) {
5773 err = got_error(GOT_ERR_BRANCH_EXISTS);
5774 goto done;
5775 } else if (err->code != GOT_ERR_NOT_REF)
5776 goto done;
5778 err = got_ref_alloc(&ref, refname, base_commit_id);
5779 if (err)
5780 goto done;
5782 err = got_ref_write(ref, repo);
5783 done:
5784 if (ref)
5785 got_ref_close(ref);
5786 free(base_refname);
5787 free(refname);
5788 return err;
5791 static const struct got_error *
5792 cmd_branch(int argc, char *argv[])
5794 const struct got_error *error = NULL;
5795 struct got_repository *repo = NULL;
5796 struct got_worktree *worktree = NULL;
5797 char *cwd = NULL, *repo_path = NULL;
5798 int ch, do_list = 0, do_show = 0, do_update = 1;
5799 const char *delref = NULL, *commit_id_arg = NULL;
5800 struct got_reference *ref = NULL;
5801 struct got_pathlist_head paths;
5802 struct got_pathlist_entry *pe;
5803 struct got_object_id *commit_id = NULL;
5804 char *commit_id_str = NULL;
5806 TAILQ_INIT(&paths);
5808 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5809 switch (ch) {
5810 case 'c':
5811 commit_id_arg = optarg;
5812 break;
5813 case 'd':
5814 delref = optarg;
5815 break;
5816 case 'r':
5817 repo_path = realpath(optarg, NULL);
5818 if (repo_path == NULL)
5819 return got_error_from_errno2("realpath",
5820 optarg);
5821 got_path_strip_trailing_slashes(repo_path);
5822 break;
5823 case 'l':
5824 do_list = 1;
5825 break;
5826 case 'n':
5827 do_update = 0;
5828 break;
5829 default:
5830 usage_branch();
5831 /* NOTREACHED */
5835 if (do_list && delref)
5836 option_conflict('l', 'd');
5838 argc -= optind;
5839 argv += optind;
5841 if (!do_list && !delref && argc == 0)
5842 do_show = 1;
5844 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5845 errx(1, "-c option can only be used when creating a branch");
5847 if (do_list || delref) {
5848 if (argc > 0)
5849 usage_branch();
5850 } else if (!do_show && argc != 1)
5851 usage_branch();
5853 #ifndef PROFILE
5854 if (do_list || do_show) {
5855 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5856 NULL) == -1)
5857 err(1, "pledge");
5858 } else {
5859 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5860 "sendfd unveil", NULL) == -1)
5861 err(1, "pledge");
5863 #endif
5864 cwd = getcwd(NULL, 0);
5865 if (cwd == NULL) {
5866 error = got_error_from_errno("getcwd");
5867 goto done;
5870 if (repo_path == NULL) {
5871 error = got_worktree_open(&worktree, cwd);
5872 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5873 goto done;
5874 else
5875 error = NULL;
5876 if (worktree) {
5877 repo_path =
5878 strdup(got_worktree_get_repo_path(worktree));
5879 if (repo_path == NULL)
5880 error = got_error_from_errno("strdup");
5881 if (error)
5882 goto done;
5883 } else {
5884 repo_path = strdup(cwd);
5885 if (repo_path == NULL) {
5886 error = got_error_from_errno("strdup");
5887 goto done;
5892 error = got_repo_open(&repo, repo_path, NULL);
5893 if (error != NULL)
5894 goto done;
5896 error = apply_unveil(got_repo_get_path(repo), do_list,
5897 worktree ? got_worktree_get_root_path(worktree) : NULL);
5898 if (error)
5899 goto done;
5901 if (do_show)
5902 error = show_current_branch(repo, worktree);
5903 else if (do_list)
5904 error = list_branches(repo, worktree);
5905 else if (delref)
5906 error = delete_branch(repo, worktree, delref);
5907 else {
5908 struct got_reflist_head refs;
5909 TAILQ_INIT(&refs);
5910 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5911 NULL);
5912 if (error)
5913 goto done;
5914 if (commit_id_arg == NULL)
5915 commit_id_arg = worktree ?
5916 got_worktree_get_head_ref_name(worktree) :
5917 GOT_REF_HEAD;
5918 error = got_repo_match_object_id(&commit_id, NULL,
5919 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5920 got_ref_list_free(&refs);
5921 if (error)
5922 goto done;
5923 error = add_branch(repo, argv[0], commit_id);
5924 if (error)
5925 goto done;
5926 if (worktree && do_update) {
5927 struct got_update_progress_arg upa;
5928 char *branch_refname = NULL;
5930 error = got_object_id_str(&commit_id_str, commit_id);
5931 if (error)
5932 goto done;
5933 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5934 worktree);
5935 if (error)
5936 goto done;
5937 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5938 == -1) {
5939 error = got_error_from_errno("asprintf");
5940 goto done;
5942 error = got_ref_open(&ref, repo, branch_refname, 0);
5943 free(branch_refname);
5944 if (error)
5945 goto done;
5946 error = switch_head_ref(ref, commit_id, worktree,
5947 repo);
5948 if (error)
5949 goto done;
5950 error = got_worktree_set_base_commit_id(worktree, repo,
5951 commit_id);
5952 if (error)
5953 goto done;
5954 memset(&upa, 0, sizeof(upa));
5955 error = got_worktree_checkout_files(worktree, &paths,
5956 repo, update_progress, &upa, check_cancelled,
5957 NULL);
5958 if (error)
5959 goto done;
5960 if (upa.did_something)
5961 printf("Updated to commit %s\n", commit_id_str);
5962 print_update_progress_stats(&upa);
5965 done:
5966 if (ref)
5967 got_ref_close(ref);
5968 if (repo) {
5969 const struct got_error *close_err = got_repo_close(repo);
5970 if (error == NULL)
5971 error = close_err;
5973 if (worktree)
5974 got_worktree_close(worktree);
5975 free(cwd);
5976 free(repo_path);
5977 free(commit_id);
5978 free(commit_id_str);
5979 TAILQ_FOREACH(pe, &paths, entry)
5980 free((char *)pe->path);
5981 got_pathlist_free(&paths);
5982 return error;
5986 __dead static void
5987 usage_tag(void)
5989 fprintf(stderr,
5990 "usage: %s tag [-c commit] [-r repository] [-l] "
5991 "[-m message] name\n", getprogname());
5992 exit(1);
5995 #if 0
5996 static const struct got_error *
5997 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5999 const struct got_error *err = NULL;
6000 struct got_reflist_entry *re, *se, *new;
6001 struct got_object_id *re_id, *se_id;
6002 struct got_tag_object *re_tag, *se_tag;
6003 time_t re_time, se_time;
6005 STAILQ_FOREACH(re, tags, entry) {
6006 se = STAILQ_FIRST(sorted);
6007 if (se == NULL) {
6008 err = got_reflist_entry_dup(&new, re);
6009 if (err)
6010 return err;
6011 STAILQ_INSERT_HEAD(sorted, new, entry);
6012 continue;
6013 } else {
6014 err = got_ref_resolve(&re_id, repo, re->ref);
6015 if (err)
6016 break;
6017 err = got_object_open_as_tag(&re_tag, repo, re_id);
6018 free(re_id);
6019 if (err)
6020 break;
6021 re_time = got_object_tag_get_tagger_time(re_tag);
6022 got_object_tag_close(re_tag);
6025 while (se) {
6026 err = got_ref_resolve(&se_id, repo, re->ref);
6027 if (err)
6028 break;
6029 err = got_object_open_as_tag(&se_tag, repo, se_id);
6030 free(se_id);
6031 if (err)
6032 break;
6033 se_time = got_object_tag_get_tagger_time(se_tag);
6034 got_object_tag_close(se_tag);
6036 if (se_time > re_time) {
6037 err = got_reflist_entry_dup(&new, re);
6038 if (err)
6039 return err;
6040 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6041 break;
6043 se = STAILQ_NEXT(se, entry);
6044 continue;
6047 done:
6048 return err;
6050 #endif
6052 static const struct got_error *
6053 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6055 static const struct got_error *err = NULL;
6056 struct got_reflist_head refs;
6057 struct got_reflist_entry *re;
6059 TAILQ_INIT(&refs);
6061 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6062 if (err)
6063 return err;
6065 TAILQ_FOREACH(re, &refs, entry) {
6066 const char *refname;
6067 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6068 char datebuf[26];
6069 const char *tagger;
6070 time_t tagger_time;
6071 struct got_object_id *id;
6072 struct got_tag_object *tag;
6073 struct got_commit_object *commit = NULL;
6075 refname = got_ref_get_name(re->ref);
6076 if (strncmp(refname, "refs/tags/", 10) != 0)
6077 continue;
6078 refname += 10;
6079 refstr = got_ref_to_str(re->ref);
6080 if (refstr == NULL) {
6081 err = got_error_from_errno("got_ref_to_str");
6082 break;
6084 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6085 free(refstr);
6087 err = got_ref_resolve(&id, repo, re->ref);
6088 if (err)
6089 break;
6090 err = got_object_open_as_tag(&tag, repo, id);
6091 if (err) {
6092 if (err->code != GOT_ERR_OBJ_TYPE) {
6093 free(id);
6094 break;
6096 /* "lightweight" tag */
6097 err = got_object_open_as_commit(&commit, repo, id);
6098 if (err) {
6099 free(id);
6100 break;
6102 tagger = got_object_commit_get_committer(commit);
6103 tagger_time =
6104 got_object_commit_get_committer_time(commit);
6105 err = got_object_id_str(&id_str, id);
6106 free(id);
6107 if (err)
6108 break;
6109 } else {
6110 free(id);
6111 tagger = got_object_tag_get_tagger(tag);
6112 tagger_time = got_object_tag_get_tagger_time(tag);
6113 err = got_object_id_str(&id_str,
6114 got_object_tag_get_object_id(tag));
6115 if (err)
6116 break;
6118 printf("from: %s\n", tagger);
6119 datestr = get_datestr(&tagger_time, datebuf);
6120 if (datestr)
6121 printf("date: %s UTC\n", datestr);
6122 if (commit)
6123 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6124 else {
6125 switch (got_object_tag_get_object_type(tag)) {
6126 case GOT_OBJ_TYPE_BLOB:
6127 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6128 id_str);
6129 break;
6130 case GOT_OBJ_TYPE_TREE:
6131 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6132 id_str);
6133 break;
6134 case GOT_OBJ_TYPE_COMMIT:
6135 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6136 id_str);
6137 break;
6138 case GOT_OBJ_TYPE_TAG:
6139 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6140 id_str);
6141 break;
6142 default:
6143 break;
6146 free(id_str);
6147 if (commit) {
6148 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6149 if (err)
6150 break;
6151 got_object_commit_close(commit);
6152 } else {
6153 tagmsg0 = strdup(got_object_tag_get_message(tag));
6154 got_object_tag_close(tag);
6155 if (tagmsg0 == NULL) {
6156 err = got_error_from_errno("strdup");
6157 break;
6161 tagmsg = tagmsg0;
6162 do {
6163 line = strsep(&tagmsg, "\n");
6164 if (line)
6165 printf(" %s\n", line);
6166 } while (line);
6167 free(tagmsg0);
6170 got_ref_list_free(&refs);
6171 return NULL;
6174 static const struct got_error *
6175 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6176 const char *tag_name, const char *repo_path)
6178 const struct got_error *err = NULL;
6179 char *template = NULL, *initial_content = NULL;
6180 char *editor = NULL;
6181 int initial_content_len;
6182 int fd = -1;
6184 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6185 err = got_error_from_errno("asprintf");
6186 goto done;
6189 initial_content_len = asprintf(&initial_content,
6190 "\n# tagging commit %s as %s\n",
6191 commit_id_str, tag_name);
6192 if (initial_content_len == -1) {
6193 err = got_error_from_errno("asprintf");
6194 goto done;
6197 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6198 if (err)
6199 goto done;
6201 if (write(fd, initial_content, initial_content_len) == -1) {
6202 err = got_error_from_errno2("write", *tagmsg_path);
6203 goto done;
6206 err = get_editor(&editor);
6207 if (err)
6208 goto done;
6209 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6210 initial_content_len, 1);
6211 done:
6212 free(initial_content);
6213 free(template);
6214 free(editor);
6216 if (fd != -1 && close(fd) == -1 && err == NULL)
6217 err = got_error_from_errno2("close", *tagmsg_path);
6219 /* Editor is done; we can now apply unveil(2) */
6220 if (err == NULL)
6221 err = apply_unveil(repo_path, 0, NULL);
6222 if (err) {
6223 free(*tagmsg);
6224 *tagmsg = NULL;
6226 return err;
6229 static const struct got_error *
6230 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6231 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6233 const struct got_error *err = NULL;
6234 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6235 char *label = NULL, *commit_id_str = NULL;
6236 struct got_reference *ref = NULL;
6237 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6238 char *tagmsg_path = NULL, *tag_id_str = NULL;
6239 int preserve_tagmsg = 0;
6240 struct got_reflist_head refs;
6242 TAILQ_INIT(&refs);
6245 * Don't let the user create a tag name with a leading '-'.
6246 * While technically a valid reference name, this case is usually
6247 * an unintended typo.
6249 if (tag_name[0] == '-')
6250 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6252 err = get_author(&tagger, repo, worktree);
6253 if (err)
6254 return err;
6256 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6257 if (err)
6258 goto done;
6260 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6261 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6262 if (err)
6263 goto done;
6265 err = got_object_id_str(&commit_id_str, commit_id);
6266 if (err)
6267 goto done;
6269 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6270 refname = strdup(tag_name);
6271 if (refname == NULL) {
6272 err = got_error_from_errno("strdup");
6273 goto done;
6275 tag_name += 10;
6276 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6277 err = got_error_from_errno("asprintf");
6278 goto done;
6281 err = got_ref_open(&ref, repo, refname, 0);
6282 if (err == NULL) {
6283 err = got_error(GOT_ERR_TAG_EXISTS);
6284 goto done;
6285 } else if (err->code != GOT_ERR_NOT_REF)
6286 goto done;
6288 if (tagmsg_arg == NULL) {
6289 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6290 tag_name, got_repo_get_path(repo));
6291 if (err) {
6292 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6293 tagmsg_path != NULL)
6294 preserve_tagmsg = 1;
6295 goto done;
6299 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6300 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6301 if (err) {
6302 if (tagmsg_path)
6303 preserve_tagmsg = 1;
6304 goto done;
6307 err = got_ref_alloc(&ref, refname, tag_id);
6308 if (err) {
6309 if (tagmsg_path)
6310 preserve_tagmsg = 1;
6311 goto done;
6314 err = got_ref_write(ref, repo);
6315 if (err) {
6316 if (tagmsg_path)
6317 preserve_tagmsg = 1;
6318 goto done;
6321 err = got_object_id_str(&tag_id_str, tag_id);
6322 if (err) {
6323 if (tagmsg_path)
6324 preserve_tagmsg = 1;
6325 goto done;
6327 printf("Created tag %s\n", tag_id_str);
6328 done:
6329 if (preserve_tagmsg) {
6330 fprintf(stderr, "%s: tag message preserved in %s\n",
6331 getprogname(), tagmsg_path);
6332 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6333 err = got_error_from_errno2("unlink", tagmsg_path);
6334 free(tag_id_str);
6335 if (ref)
6336 got_ref_close(ref);
6337 free(commit_id);
6338 free(commit_id_str);
6339 free(refname);
6340 free(tagmsg);
6341 free(tagmsg_path);
6342 free(tagger);
6343 got_ref_list_free(&refs);
6344 return err;
6347 static const struct got_error *
6348 cmd_tag(int argc, char *argv[])
6350 const struct got_error *error = NULL;
6351 struct got_repository *repo = NULL;
6352 struct got_worktree *worktree = NULL;
6353 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6354 char *gitconfig_path = NULL;
6355 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6356 int ch, do_list = 0;
6358 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6359 switch (ch) {
6360 case 'c':
6361 commit_id_arg = optarg;
6362 break;
6363 case 'm':
6364 tagmsg = optarg;
6365 break;
6366 case 'r':
6367 repo_path = realpath(optarg, NULL);
6368 if (repo_path == NULL)
6369 return got_error_from_errno2("realpath",
6370 optarg);
6371 got_path_strip_trailing_slashes(repo_path);
6372 break;
6373 case 'l':
6374 do_list = 1;
6375 break;
6376 default:
6377 usage_tag();
6378 /* NOTREACHED */
6382 argc -= optind;
6383 argv += optind;
6385 if (do_list) {
6386 if (commit_id_arg != NULL)
6387 errx(1,
6388 "-c option can only be used when creating a tag");
6389 if (tagmsg)
6390 option_conflict('l', 'm');
6391 if (argc > 0)
6392 usage_tag();
6393 } else if (argc != 1)
6394 usage_tag();
6396 tag_name = argv[0];
6398 #ifndef PROFILE
6399 if (do_list) {
6400 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6401 NULL) == -1)
6402 err(1, "pledge");
6403 } else {
6404 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6405 "sendfd unveil", NULL) == -1)
6406 err(1, "pledge");
6408 #endif
6409 cwd = getcwd(NULL, 0);
6410 if (cwd == NULL) {
6411 error = got_error_from_errno("getcwd");
6412 goto done;
6415 if (repo_path == NULL) {
6416 error = got_worktree_open(&worktree, cwd);
6417 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6418 goto done;
6419 else
6420 error = NULL;
6421 if (worktree) {
6422 repo_path =
6423 strdup(got_worktree_get_repo_path(worktree));
6424 if (repo_path == NULL)
6425 error = got_error_from_errno("strdup");
6426 if (error)
6427 goto done;
6428 } else {
6429 repo_path = strdup(cwd);
6430 if (repo_path == NULL) {
6431 error = got_error_from_errno("strdup");
6432 goto done;
6437 if (do_list) {
6438 error = got_repo_open(&repo, repo_path, NULL);
6439 if (error != NULL)
6440 goto done;
6441 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6442 if (error)
6443 goto done;
6444 error = list_tags(repo, worktree);
6445 } else {
6446 error = get_gitconfig_path(&gitconfig_path);
6447 if (error)
6448 goto done;
6449 error = got_repo_open(&repo, repo_path, gitconfig_path);
6450 if (error != NULL)
6451 goto done;
6453 if (tagmsg) {
6454 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6455 if (error)
6456 goto done;
6459 if (commit_id_arg == NULL) {
6460 struct got_reference *head_ref;
6461 struct got_object_id *commit_id;
6462 error = got_ref_open(&head_ref, repo,
6463 worktree ? got_worktree_get_head_ref_name(worktree)
6464 : GOT_REF_HEAD, 0);
6465 if (error)
6466 goto done;
6467 error = got_ref_resolve(&commit_id, repo, head_ref);
6468 got_ref_close(head_ref);
6469 if (error)
6470 goto done;
6471 error = got_object_id_str(&commit_id_str, commit_id);
6472 free(commit_id);
6473 if (error)
6474 goto done;
6477 error = add_tag(repo, worktree, tag_name,
6478 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6480 done:
6481 if (repo) {
6482 const struct got_error *close_err = got_repo_close(repo);
6483 if (error == NULL)
6484 error = close_err;
6486 if (worktree)
6487 got_worktree_close(worktree);
6488 free(cwd);
6489 free(repo_path);
6490 free(gitconfig_path);
6491 free(commit_id_str);
6492 return error;
6495 __dead static void
6496 usage_add(void)
6498 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6499 getprogname());
6500 exit(1);
6503 static const struct got_error *
6504 add_progress(void *arg, unsigned char status, const char *path)
6506 while (path[0] == '/')
6507 path++;
6508 printf("%c %s\n", status, path);
6509 return NULL;
6512 static const struct got_error *
6513 cmd_add(int argc, char *argv[])
6515 const struct got_error *error = NULL;
6516 struct got_repository *repo = NULL;
6517 struct got_worktree *worktree = NULL;
6518 char *cwd = NULL;
6519 struct got_pathlist_head paths;
6520 struct got_pathlist_entry *pe;
6521 int ch, can_recurse = 0, no_ignores = 0;
6523 TAILQ_INIT(&paths);
6525 while ((ch = getopt(argc, argv, "IR")) != -1) {
6526 switch (ch) {
6527 case 'I':
6528 no_ignores = 1;
6529 break;
6530 case 'R':
6531 can_recurse = 1;
6532 break;
6533 default:
6534 usage_add();
6535 /* NOTREACHED */
6539 argc -= optind;
6540 argv += optind;
6542 #ifndef PROFILE
6543 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6544 NULL) == -1)
6545 err(1, "pledge");
6546 #endif
6547 if (argc < 1)
6548 usage_add();
6550 cwd = getcwd(NULL, 0);
6551 if (cwd == NULL) {
6552 error = got_error_from_errno("getcwd");
6553 goto done;
6556 error = got_worktree_open(&worktree, cwd);
6557 if (error) {
6558 if (error->code == GOT_ERR_NOT_WORKTREE)
6559 error = wrap_not_worktree_error(error, "add", cwd);
6560 goto done;
6563 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6564 NULL);
6565 if (error != NULL)
6566 goto done;
6568 error = apply_unveil(got_repo_get_path(repo), 1,
6569 got_worktree_get_root_path(worktree));
6570 if (error)
6571 goto done;
6573 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6574 if (error)
6575 goto done;
6577 if (!can_recurse) {
6578 char *ondisk_path;
6579 struct stat sb;
6580 TAILQ_FOREACH(pe, &paths, entry) {
6581 if (asprintf(&ondisk_path, "%s/%s",
6582 got_worktree_get_root_path(worktree),
6583 pe->path) == -1) {
6584 error = got_error_from_errno("asprintf");
6585 goto done;
6587 if (lstat(ondisk_path, &sb) == -1) {
6588 if (errno == ENOENT) {
6589 free(ondisk_path);
6590 continue;
6592 error = got_error_from_errno2("lstat",
6593 ondisk_path);
6594 free(ondisk_path);
6595 goto done;
6597 free(ondisk_path);
6598 if (S_ISDIR(sb.st_mode)) {
6599 error = got_error_msg(GOT_ERR_BAD_PATH,
6600 "adding directories requires -R option");
6601 goto done;
6606 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6607 NULL, repo, no_ignores);
6608 done:
6609 if (repo) {
6610 const struct got_error *close_err = got_repo_close(repo);
6611 if (error == NULL)
6612 error = close_err;
6614 if (worktree)
6615 got_worktree_close(worktree);
6616 TAILQ_FOREACH(pe, &paths, entry)
6617 free((char *)pe->path);
6618 got_pathlist_free(&paths);
6619 free(cwd);
6620 return error;
6623 __dead static void
6624 usage_remove(void)
6626 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6627 "path ...\n", getprogname());
6628 exit(1);
6631 static const struct got_error *
6632 print_remove_status(void *arg, unsigned char status,
6633 unsigned char staged_status, const char *path)
6635 while (path[0] == '/')
6636 path++;
6637 if (status == GOT_STATUS_NONEXISTENT)
6638 return NULL;
6639 if (status == staged_status && (status == GOT_STATUS_DELETE))
6640 status = GOT_STATUS_NO_CHANGE;
6641 printf("%c%c %s\n", status, staged_status, path);
6642 return NULL;
6645 static const struct got_error *
6646 cmd_remove(int argc, char *argv[])
6648 const struct got_error *error = NULL;
6649 struct got_worktree *worktree = NULL;
6650 struct got_repository *repo = NULL;
6651 const char *status_codes = NULL;
6652 char *cwd = NULL;
6653 struct got_pathlist_head paths;
6654 struct got_pathlist_entry *pe;
6655 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6657 TAILQ_INIT(&paths);
6659 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6660 switch (ch) {
6661 case 'f':
6662 delete_local_mods = 1;
6663 break;
6664 case 'k':
6665 keep_on_disk = 1;
6666 break;
6667 case 'R':
6668 can_recurse = 1;
6669 break;
6670 case 's':
6671 for (i = 0; i < strlen(optarg); i++) {
6672 switch (optarg[i]) {
6673 case GOT_STATUS_MODIFY:
6674 delete_local_mods = 1;
6675 break;
6676 case GOT_STATUS_MISSING:
6677 break;
6678 default:
6679 errx(1, "invalid status code '%c'",
6680 optarg[i]);
6683 status_codes = optarg;
6684 break;
6685 default:
6686 usage_remove();
6687 /* NOTREACHED */
6691 argc -= optind;
6692 argv += optind;
6694 #ifndef PROFILE
6695 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6696 NULL) == -1)
6697 err(1, "pledge");
6698 #endif
6699 if (argc < 1)
6700 usage_remove();
6702 cwd = getcwd(NULL, 0);
6703 if (cwd == NULL) {
6704 error = got_error_from_errno("getcwd");
6705 goto done;
6707 error = got_worktree_open(&worktree, cwd);
6708 if (error) {
6709 if (error->code == GOT_ERR_NOT_WORKTREE)
6710 error = wrap_not_worktree_error(error, "remove", cwd);
6711 goto done;
6714 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6715 NULL);
6716 if (error)
6717 goto done;
6719 error = apply_unveil(got_repo_get_path(repo), 1,
6720 got_worktree_get_root_path(worktree));
6721 if (error)
6722 goto done;
6724 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6725 if (error)
6726 goto done;
6728 if (!can_recurse) {
6729 char *ondisk_path;
6730 struct stat sb;
6731 TAILQ_FOREACH(pe, &paths, entry) {
6732 if (asprintf(&ondisk_path, "%s/%s",
6733 got_worktree_get_root_path(worktree),
6734 pe->path) == -1) {
6735 error = got_error_from_errno("asprintf");
6736 goto done;
6738 if (lstat(ondisk_path, &sb) == -1) {
6739 if (errno == ENOENT) {
6740 free(ondisk_path);
6741 continue;
6743 error = got_error_from_errno2("lstat",
6744 ondisk_path);
6745 free(ondisk_path);
6746 goto done;
6748 free(ondisk_path);
6749 if (S_ISDIR(sb.st_mode)) {
6750 error = got_error_msg(GOT_ERR_BAD_PATH,
6751 "removing directories requires -R option");
6752 goto done;
6757 error = got_worktree_schedule_delete(worktree, &paths,
6758 delete_local_mods, status_codes, print_remove_status, NULL,
6759 repo, keep_on_disk);
6760 done:
6761 if (repo) {
6762 const struct got_error *close_err = got_repo_close(repo);
6763 if (error == NULL)
6764 error = close_err;
6766 if (worktree)
6767 got_worktree_close(worktree);
6768 TAILQ_FOREACH(pe, &paths, entry)
6769 free((char *)pe->path);
6770 got_pathlist_free(&paths);
6771 free(cwd);
6772 return error;
6775 __dead static void
6776 usage_revert(void)
6778 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6779 "path ...\n", getprogname());
6780 exit(1);
6783 static const struct got_error *
6784 revert_progress(void *arg, unsigned char status, const char *path)
6786 if (status == GOT_STATUS_UNVERSIONED)
6787 return NULL;
6789 while (path[0] == '/')
6790 path++;
6791 printf("%c %s\n", status, path);
6792 return NULL;
6795 struct choose_patch_arg {
6796 FILE *patch_script_file;
6797 const char *action;
6800 static const struct got_error *
6801 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6802 int nchanges, const char *action)
6804 char *line = NULL;
6805 size_t linesize = 0;
6806 ssize_t linelen;
6808 switch (status) {
6809 case GOT_STATUS_ADD:
6810 printf("A %s\n%s this addition? [y/n] ", path, action);
6811 break;
6812 case GOT_STATUS_DELETE:
6813 printf("D %s\n%s this deletion? [y/n] ", path, action);
6814 break;
6815 case GOT_STATUS_MODIFY:
6816 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6817 return got_error_from_errno("fseek");
6818 printf(GOT_COMMIT_SEP_STR);
6819 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6820 printf("%s", line);
6821 if (ferror(patch_file))
6822 return got_error_from_errno("getline");
6823 printf(GOT_COMMIT_SEP_STR);
6824 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6825 path, n, nchanges, action);
6826 break;
6827 default:
6828 return got_error_path(path, GOT_ERR_FILE_STATUS);
6831 return NULL;
6834 static const struct got_error *
6835 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6836 FILE *patch_file, int n, int nchanges)
6838 const struct got_error *err = NULL;
6839 char *line = NULL;
6840 size_t linesize = 0;
6841 ssize_t linelen;
6842 int resp = ' ';
6843 struct choose_patch_arg *a = arg;
6845 *choice = GOT_PATCH_CHOICE_NONE;
6847 if (a->patch_script_file) {
6848 char *nl;
6849 err = show_change(status, path, patch_file, n, nchanges,
6850 a->action);
6851 if (err)
6852 return err;
6853 linelen = getline(&line, &linesize, a->patch_script_file);
6854 if (linelen == -1) {
6855 if (ferror(a->patch_script_file))
6856 return got_error_from_errno("getline");
6857 return NULL;
6859 nl = strchr(line, '\n');
6860 if (nl)
6861 *nl = '\0';
6862 if (strcmp(line, "y") == 0) {
6863 *choice = GOT_PATCH_CHOICE_YES;
6864 printf("y\n");
6865 } else if (strcmp(line, "n") == 0) {
6866 *choice = GOT_PATCH_CHOICE_NO;
6867 printf("n\n");
6868 } else if (strcmp(line, "q") == 0 &&
6869 status == GOT_STATUS_MODIFY) {
6870 *choice = GOT_PATCH_CHOICE_QUIT;
6871 printf("q\n");
6872 } else
6873 printf("invalid response '%s'\n", line);
6874 free(line);
6875 return NULL;
6878 while (resp != 'y' && resp != 'n' && resp != 'q') {
6879 err = show_change(status, path, patch_file, n, nchanges,
6880 a->action);
6881 if (err)
6882 return err;
6883 resp = getchar();
6884 if (resp == '\n')
6885 resp = getchar();
6886 if (status == GOT_STATUS_MODIFY) {
6887 if (resp != 'y' && resp != 'n' && resp != 'q') {
6888 printf("invalid response '%c'\n", resp);
6889 resp = ' ';
6891 } else if (resp != 'y' && resp != 'n') {
6892 printf("invalid response '%c'\n", resp);
6893 resp = ' ';
6897 if (resp == 'y')
6898 *choice = GOT_PATCH_CHOICE_YES;
6899 else if (resp == 'n')
6900 *choice = GOT_PATCH_CHOICE_NO;
6901 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6902 *choice = GOT_PATCH_CHOICE_QUIT;
6904 return NULL;
6908 static const struct got_error *
6909 cmd_revert(int argc, char *argv[])
6911 const struct got_error *error = NULL;
6912 struct got_worktree *worktree = NULL;
6913 struct got_repository *repo = NULL;
6914 char *cwd = NULL, *path = NULL;
6915 struct got_pathlist_head paths;
6916 struct got_pathlist_entry *pe;
6917 int ch, can_recurse = 0, pflag = 0;
6918 FILE *patch_script_file = NULL;
6919 const char *patch_script_path = NULL;
6920 struct choose_patch_arg cpa;
6922 TAILQ_INIT(&paths);
6924 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6925 switch (ch) {
6926 case 'p':
6927 pflag = 1;
6928 break;
6929 case 'F':
6930 patch_script_path = optarg;
6931 break;
6932 case 'R':
6933 can_recurse = 1;
6934 break;
6935 default:
6936 usage_revert();
6937 /* NOTREACHED */
6941 argc -= optind;
6942 argv += optind;
6944 #ifndef PROFILE
6945 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6946 "unveil", NULL) == -1)
6947 err(1, "pledge");
6948 #endif
6949 if (argc < 1)
6950 usage_revert();
6951 if (patch_script_path && !pflag)
6952 errx(1, "-F option can only be used together with -p option");
6954 cwd = getcwd(NULL, 0);
6955 if (cwd == NULL) {
6956 error = got_error_from_errno("getcwd");
6957 goto done;
6959 error = got_worktree_open(&worktree, cwd);
6960 if (error) {
6961 if (error->code == GOT_ERR_NOT_WORKTREE)
6962 error = wrap_not_worktree_error(error, "revert", cwd);
6963 goto done;
6966 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6967 NULL);
6968 if (error != NULL)
6969 goto done;
6971 if (patch_script_path) {
6972 patch_script_file = fopen(patch_script_path, "r");
6973 if (patch_script_file == NULL) {
6974 error = got_error_from_errno2("fopen",
6975 patch_script_path);
6976 goto done;
6979 error = apply_unveil(got_repo_get_path(repo), 1,
6980 got_worktree_get_root_path(worktree));
6981 if (error)
6982 goto done;
6984 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6985 if (error)
6986 goto done;
6988 if (!can_recurse) {
6989 char *ondisk_path;
6990 struct stat sb;
6991 TAILQ_FOREACH(pe, &paths, entry) {
6992 if (asprintf(&ondisk_path, "%s/%s",
6993 got_worktree_get_root_path(worktree),
6994 pe->path) == -1) {
6995 error = got_error_from_errno("asprintf");
6996 goto done;
6998 if (lstat(ondisk_path, &sb) == -1) {
6999 if (errno == ENOENT) {
7000 free(ondisk_path);
7001 continue;
7003 error = got_error_from_errno2("lstat",
7004 ondisk_path);
7005 free(ondisk_path);
7006 goto done;
7008 free(ondisk_path);
7009 if (S_ISDIR(sb.st_mode)) {
7010 error = got_error_msg(GOT_ERR_BAD_PATH,
7011 "reverting directories requires -R option");
7012 goto done;
7017 cpa.patch_script_file = patch_script_file;
7018 cpa.action = "revert";
7019 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7020 pflag ? choose_patch : NULL, &cpa, repo);
7021 done:
7022 if (patch_script_file && fclose(patch_script_file) == EOF &&
7023 error == NULL)
7024 error = got_error_from_errno2("fclose", patch_script_path);
7025 if (repo) {
7026 const struct got_error *close_err = got_repo_close(repo);
7027 if (error == NULL)
7028 error = close_err;
7030 if (worktree)
7031 got_worktree_close(worktree);
7032 free(path);
7033 free(cwd);
7034 return error;
7037 __dead static void
7038 usage_commit(void)
7040 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7041 "[path ...]\n", getprogname());
7042 exit(1);
7045 struct collect_commit_logmsg_arg {
7046 const char *cmdline_log;
7047 const char *prepared_log;
7048 int non_interactive;
7049 const char *editor;
7050 const char *worktree_path;
7051 const char *branch_name;
7052 const char *repo_path;
7053 char *logmsg_path;
7057 static const struct got_error *
7058 read_prepared_logmsg(char **logmsg, const char *path)
7060 const struct got_error *err = NULL;
7061 FILE *f = NULL;
7062 struct stat sb;
7063 size_t r;
7065 *logmsg = NULL;
7066 memset(&sb, 0, sizeof(sb));
7068 f = fopen(path, "r");
7069 if (f == NULL)
7070 return got_error_from_errno2("fopen", path);
7072 if (fstat(fileno(f), &sb) == -1) {
7073 err = got_error_from_errno2("fstat", path);
7074 goto done;
7076 if (sb.st_size == 0) {
7077 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7078 goto done;
7081 *logmsg = malloc(sb.st_size + 1);
7082 if (*logmsg == NULL) {
7083 err = got_error_from_errno("malloc");
7084 goto done;
7087 r = fread(*logmsg, 1, sb.st_size, f);
7088 if (r != sb.st_size) {
7089 if (ferror(f))
7090 err = got_error_from_errno2("fread", path);
7091 else
7092 err = got_error(GOT_ERR_IO);
7093 goto done;
7095 (*logmsg)[sb.st_size] = '\0';
7096 done:
7097 if (fclose(f) == EOF && err == NULL)
7098 err = got_error_from_errno2("fclose", path);
7099 if (err) {
7100 free(*logmsg);
7101 *logmsg = NULL;
7103 return err;
7107 static const struct got_error *
7108 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7109 void *arg)
7111 char *initial_content = NULL;
7112 struct got_pathlist_entry *pe;
7113 const struct got_error *err = NULL;
7114 char *template = NULL;
7115 struct collect_commit_logmsg_arg *a = arg;
7116 int initial_content_len;
7117 int fd = -1;
7118 size_t len;
7120 /* if a message was specified on the command line, just use it */
7121 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7122 len = strlen(a->cmdline_log) + 1;
7123 *logmsg = malloc(len + 1);
7124 if (*logmsg == NULL)
7125 return got_error_from_errno("malloc");
7126 strlcpy(*logmsg, a->cmdline_log, len);
7127 return NULL;
7128 } else if (a->prepared_log != NULL && a->non_interactive)
7129 return read_prepared_logmsg(logmsg, a->prepared_log);
7131 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7132 return got_error_from_errno("asprintf");
7134 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7135 if (err)
7136 goto done;
7138 if (a->prepared_log) {
7139 char *msg;
7140 err = read_prepared_logmsg(&msg, a->prepared_log);
7141 if (err)
7142 goto done;
7143 if (write(fd, msg, strlen(msg)) == -1) {
7144 err = got_error_from_errno2("write", a->logmsg_path);
7145 free(msg);
7146 goto done;
7148 free(msg);
7151 initial_content_len = asprintf(&initial_content,
7152 "\n# changes to be committed on branch %s:\n",
7153 a->branch_name);
7154 if (initial_content_len == -1) {
7155 err = got_error_from_errno("asprintf");
7156 goto done;
7159 if (write(fd, initial_content, initial_content_len) == -1) {
7160 err = got_error_from_errno2("write", a->logmsg_path);
7161 goto done;
7164 TAILQ_FOREACH(pe, commitable_paths, entry) {
7165 struct got_commitable *ct = pe->data;
7166 dprintf(fd, "# %c %s\n",
7167 got_commitable_get_status(ct),
7168 got_commitable_get_path(ct));
7171 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7172 initial_content_len, a->prepared_log ? 0 : 1);
7173 done:
7174 free(initial_content);
7175 free(template);
7177 if (fd != -1 && close(fd) == -1 && err == NULL)
7178 err = got_error_from_errno2("close", a->logmsg_path);
7180 /* Editor is done; we can now apply unveil(2) */
7181 if (err == NULL)
7182 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7183 if (err) {
7184 free(*logmsg);
7185 *logmsg = NULL;
7187 return err;
7190 static const struct got_error *
7191 cmd_commit(int argc, char *argv[])
7193 const struct got_error *error = NULL;
7194 struct got_worktree *worktree = NULL;
7195 struct got_repository *repo = NULL;
7196 char *cwd = NULL, *id_str = NULL;
7197 struct got_object_id *id = NULL;
7198 const char *logmsg = NULL;
7199 char *prepared_logmsg = NULL;
7200 struct collect_commit_logmsg_arg cl_arg;
7201 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7202 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7203 int allow_bad_symlinks = 0, non_interactive = 0;
7204 struct got_pathlist_head paths;
7206 TAILQ_INIT(&paths);
7207 cl_arg.logmsg_path = NULL;
7209 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7210 switch (ch) {
7211 case 'F':
7212 if (logmsg != NULL)
7213 option_conflict('F', 'm');
7214 prepared_logmsg = realpath(optarg, NULL);
7215 if (prepared_logmsg == NULL)
7216 return got_error_from_errno2("realpath",
7217 optarg);
7218 break;
7219 case 'm':
7220 if (prepared_logmsg)
7221 option_conflict('m', 'F');
7222 logmsg = optarg;
7223 break;
7224 case 'N':
7225 non_interactive = 1;
7226 break;
7227 case 'S':
7228 allow_bad_symlinks = 1;
7229 break;
7230 default:
7231 usage_commit();
7232 /* NOTREACHED */
7236 argc -= optind;
7237 argv += optind;
7239 #ifndef PROFILE
7240 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7241 "unveil", NULL) == -1)
7242 err(1, "pledge");
7243 #endif
7244 cwd = getcwd(NULL, 0);
7245 if (cwd == NULL) {
7246 error = got_error_from_errno("getcwd");
7247 goto done;
7249 error = got_worktree_open(&worktree, cwd);
7250 if (error) {
7251 if (error->code == GOT_ERR_NOT_WORKTREE)
7252 error = wrap_not_worktree_error(error, "commit", cwd);
7253 goto done;
7256 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7257 if (error)
7258 goto done;
7259 if (rebase_in_progress) {
7260 error = got_error(GOT_ERR_REBASING);
7261 goto done;
7264 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7265 worktree);
7266 if (error)
7267 goto done;
7269 error = get_gitconfig_path(&gitconfig_path);
7270 if (error)
7271 goto done;
7272 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7273 gitconfig_path);
7274 if (error != NULL)
7275 goto done;
7277 error = get_author(&author, repo, worktree);
7278 if (error)
7279 return error;
7282 * unveil(2) traverses exec(2); if an editor is used we have
7283 * to apply unveil after the log message has been written.
7285 if (logmsg == NULL || strlen(logmsg) == 0)
7286 error = get_editor(&editor);
7287 else
7288 error = apply_unveil(got_repo_get_path(repo), 0,
7289 got_worktree_get_root_path(worktree));
7290 if (error)
7291 goto done;
7293 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7294 if (error)
7295 goto done;
7297 cl_arg.editor = editor;
7298 cl_arg.cmdline_log = logmsg;
7299 cl_arg.prepared_log = prepared_logmsg;
7300 cl_arg.non_interactive = non_interactive;
7301 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7302 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7303 if (!histedit_in_progress) {
7304 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7305 error = got_error(GOT_ERR_COMMIT_BRANCH);
7306 goto done;
7308 cl_arg.branch_name += 11;
7310 cl_arg.repo_path = got_repo_get_path(repo);
7311 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7312 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7313 print_status, NULL, repo);
7314 if (error) {
7315 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7316 cl_arg.logmsg_path != NULL)
7317 preserve_logmsg = 1;
7318 goto done;
7321 error = got_object_id_str(&id_str, id);
7322 if (error)
7323 goto done;
7324 printf("Created commit %s\n", id_str);
7325 done:
7326 if (preserve_logmsg) {
7327 fprintf(stderr, "%s: log message preserved in %s\n",
7328 getprogname(), cl_arg.logmsg_path);
7329 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7330 error == NULL)
7331 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7332 free(cl_arg.logmsg_path);
7333 if (repo) {
7334 const struct got_error *close_err = got_repo_close(repo);
7335 if (error == NULL)
7336 error = close_err;
7338 if (worktree)
7339 got_worktree_close(worktree);
7340 free(cwd);
7341 free(id_str);
7342 free(gitconfig_path);
7343 free(editor);
7344 free(author);
7345 free(prepared_logmsg);
7346 return error;
7349 __dead static void
7350 usage_cherrypick(void)
7352 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7353 exit(1);
7356 static const struct got_error *
7357 cmd_cherrypick(int argc, char *argv[])
7359 const struct got_error *error = NULL;
7360 struct got_worktree *worktree = NULL;
7361 struct got_repository *repo = NULL;
7362 char *cwd = NULL, *commit_id_str = NULL;
7363 struct got_object_id *commit_id = NULL;
7364 struct got_commit_object *commit = NULL;
7365 struct got_object_qid *pid;
7366 struct got_reference *head_ref = NULL;
7367 int ch;
7368 struct got_update_progress_arg upa;
7370 while ((ch = getopt(argc, argv, "")) != -1) {
7371 switch (ch) {
7372 default:
7373 usage_cherrypick();
7374 /* NOTREACHED */
7378 argc -= optind;
7379 argv += optind;
7381 #ifndef PROFILE
7382 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7383 "unveil", NULL) == -1)
7384 err(1, "pledge");
7385 #endif
7386 if (argc != 1)
7387 usage_cherrypick();
7389 cwd = getcwd(NULL, 0);
7390 if (cwd == NULL) {
7391 error = got_error_from_errno("getcwd");
7392 goto done;
7394 error = got_worktree_open(&worktree, cwd);
7395 if (error) {
7396 if (error->code == GOT_ERR_NOT_WORKTREE)
7397 error = wrap_not_worktree_error(error, "cherrypick",
7398 cwd);
7399 goto done;
7402 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7403 NULL);
7404 if (error != NULL)
7405 goto done;
7407 error = apply_unveil(got_repo_get_path(repo), 0,
7408 got_worktree_get_root_path(worktree));
7409 if (error)
7410 goto done;
7412 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7413 GOT_OBJ_TYPE_COMMIT, repo);
7414 if (error != NULL) {
7415 struct got_reference *ref;
7416 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7417 goto done;
7418 error = got_ref_open(&ref, repo, argv[0], 0);
7419 if (error != NULL)
7420 goto done;
7421 error = got_ref_resolve(&commit_id, repo, ref);
7422 got_ref_close(ref);
7423 if (error != NULL)
7424 goto done;
7426 error = got_object_id_str(&commit_id_str, commit_id);
7427 if (error)
7428 goto done;
7430 error = got_ref_open(&head_ref, repo,
7431 got_worktree_get_head_ref_name(worktree), 0);
7432 if (error != NULL)
7433 goto done;
7435 error = check_same_branch(commit_id, head_ref, NULL, repo);
7436 if (error) {
7437 if (error->code != GOT_ERR_ANCESTRY)
7438 goto done;
7439 error = NULL;
7440 } else {
7441 error = got_error(GOT_ERR_SAME_BRANCH);
7442 goto done;
7445 error = got_object_open_as_commit(&commit, repo, commit_id);
7446 if (error)
7447 goto done;
7448 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7449 memset(&upa, 0, sizeof(upa));
7450 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7451 commit_id, repo, update_progress, &upa, check_cancelled,
7452 NULL);
7453 if (error != NULL)
7454 goto done;
7456 if (upa.did_something)
7457 printf("Merged commit %s\n", commit_id_str);
7458 print_update_progress_stats(&upa);
7459 done:
7460 if (commit)
7461 got_object_commit_close(commit);
7462 free(commit_id_str);
7463 if (head_ref)
7464 got_ref_close(head_ref);
7465 if (worktree)
7466 got_worktree_close(worktree);
7467 if (repo) {
7468 const struct got_error *close_err = got_repo_close(repo);
7469 if (error == NULL)
7470 error = close_err;
7472 return error;
7475 __dead static void
7476 usage_backout(void)
7478 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7479 exit(1);
7482 static const struct got_error *
7483 cmd_backout(int argc, char *argv[])
7485 const struct got_error *error = NULL;
7486 struct got_worktree *worktree = NULL;
7487 struct got_repository *repo = NULL;
7488 char *cwd = NULL, *commit_id_str = NULL;
7489 struct got_object_id *commit_id = NULL;
7490 struct got_commit_object *commit = NULL;
7491 struct got_object_qid *pid;
7492 struct got_reference *head_ref = NULL;
7493 int ch;
7494 struct got_update_progress_arg upa;
7496 while ((ch = getopt(argc, argv, "")) != -1) {
7497 switch (ch) {
7498 default:
7499 usage_backout();
7500 /* NOTREACHED */
7504 argc -= optind;
7505 argv += optind;
7507 #ifndef PROFILE
7508 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7509 "unveil", NULL) == -1)
7510 err(1, "pledge");
7511 #endif
7512 if (argc != 1)
7513 usage_backout();
7515 cwd = getcwd(NULL, 0);
7516 if (cwd == NULL) {
7517 error = got_error_from_errno("getcwd");
7518 goto done;
7520 error = got_worktree_open(&worktree, cwd);
7521 if (error) {
7522 if (error->code == GOT_ERR_NOT_WORKTREE)
7523 error = wrap_not_worktree_error(error, "backout", cwd);
7524 goto done;
7527 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7528 NULL);
7529 if (error != NULL)
7530 goto done;
7532 error = apply_unveil(got_repo_get_path(repo), 0,
7533 got_worktree_get_root_path(worktree));
7534 if (error)
7535 goto done;
7537 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7538 GOT_OBJ_TYPE_COMMIT, repo);
7539 if (error != NULL) {
7540 struct got_reference *ref;
7541 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7542 goto done;
7543 error = got_ref_open(&ref, repo, argv[0], 0);
7544 if (error != NULL)
7545 goto done;
7546 error = got_ref_resolve(&commit_id, repo, ref);
7547 got_ref_close(ref);
7548 if (error != NULL)
7549 goto done;
7551 error = got_object_id_str(&commit_id_str, commit_id);
7552 if (error)
7553 goto done;
7555 error = got_ref_open(&head_ref, repo,
7556 got_worktree_get_head_ref_name(worktree), 0);
7557 if (error != NULL)
7558 goto done;
7560 error = check_same_branch(commit_id, head_ref, NULL, repo);
7561 if (error)
7562 goto done;
7564 error = got_object_open_as_commit(&commit, repo, commit_id);
7565 if (error)
7566 goto done;
7567 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7568 if (pid == NULL) {
7569 error = got_error(GOT_ERR_ROOT_COMMIT);
7570 goto done;
7573 memset(&upa, 0, sizeof(upa));
7574 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7575 update_progress, &upa, check_cancelled, NULL);
7576 if (error != NULL)
7577 goto done;
7579 if (upa.did_something)
7580 printf("Backed out commit %s\n", commit_id_str);
7581 print_update_progress_stats(&upa);
7582 done:
7583 if (commit)
7584 got_object_commit_close(commit);
7585 free(commit_id_str);
7586 if (head_ref)
7587 got_ref_close(head_ref);
7588 if (worktree)
7589 got_worktree_close(worktree);
7590 if (repo) {
7591 const struct got_error *close_err = got_repo_close(repo);
7592 if (error == NULL)
7593 error = close_err;
7595 return error;
7598 __dead static void
7599 usage_rebase(void)
7601 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
7602 getprogname());
7603 exit(1);
7606 void
7607 trim_logmsg(char *logmsg, int limit)
7609 char *nl;
7610 size_t len;
7612 len = strlen(logmsg);
7613 if (len > limit)
7614 len = limit;
7615 logmsg[len] = '\0';
7616 nl = strchr(logmsg, '\n');
7617 if (nl)
7618 *nl = '\0';
7621 static const struct got_error *
7622 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7624 const struct got_error *err;
7625 char *logmsg0 = NULL;
7626 const char *s;
7628 err = got_object_commit_get_logmsg(&logmsg0, commit);
7629 if (err)
7630 return err;
7632 s = logmsg0;
7633 while (isspace((unsigned char)s[0]))
7634 s++;
7636 *logmsg = strdup(s);
7637 if (*logmsg == NULL) {
7638 err = got_error_from_errno("strdup");
7639 goto done;
7642 trim_logmsg(*logmsg, limit);
7643 done:
7644 free(logmsg0);
7645 return err;
7648 static const struct got_error *
7649 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7651 const struct got_error *err;
7652 struct got_commit_object *commit = NULL;
7653 char *id_str = NULL, *logmsg = NULL;
7655 err = got_object_open_as_commit(&commit, repo, id);
7656 if (err)
7657 return err;
7659 err = got_object_id_str(&id_str, id);
7660 if (err)
7661 goto done;
7663 id_str[12] = '\0';
7665 err = get_short_logmsg(&logmsg, 42, commit);
7666 if (err)
7667 goto done;
7669 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7670 done:
7671 free(id_str);
7672 got_object_commit_close(commit);
7673 free(logmsg);
7674 return err;
7677 static const struct got_error *
7678 show_rebase_progress(struct got_commit_object *commit,
7679 struct got_object_id *old_id, struct got_object_id *new_id)
7681 const struct got_error *err;
7682 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7684 err = got_object_id_str(&old_id_str, old_id);
7685 if (err)
7686 goto done;
7688 if (new_id) {
7689 err = got_object_id_str(&new_id_str, new_id);
7690 if (err)
7691 goto done;
7694 old_id_str[12] = '\0';
7695 if (new_id_str)
7696 new_id_str[12] = '\0';
7698 err = get_short_logmsg(&logmsg, 42, commit);
7699 if (err)
7700 goto done;
7702 printf("%s -> %s: %s\n", old_id_str,
7703 new_id_str ? new_id_str : "no-op change", logmsg);
7704 done:
7705 free(old_id_str);
7706 free(new_id_str);
7707 free(logmsg);
7708 return err;
7711 static const struct got_error *
7712 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7713 struct got_reference *branch, struct got_reference *new_base_branch,
7714 struct got_reference *tmp_branch, struct got_repository *repo,
7715 int create_backup)
7717 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7718 return got_worktree_rebase_complete(worktree, fileindex,
7719 new_base_branch, tmp_branch, branch, repo, create_backup);
7722 static const struct got_error *
7723 rebase_commit(struct got_pathlist_head *merged_paths,
7724 struct got_worktree *worktree, struct got_fileindex *fileindex,
7725 struct got_reference *tmp_branch,
7726 struct got_object_id *commit_id, struct got_repository *repo)
7728 const struct got_error *error;
7729 struct got_commit_object *commit;
7730 struct got_object_id *new_commit_id;
7732 error = got_object_open_as_commit(&commit, repo, commit_id);
7733 if (error)
7734 return error;
7736 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7737 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7738 if (error) {
7739 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7740 goto done;
7741 error = show_rebase_progress(commit, commit_id, NULL);
7742 } else {
7743 error = show_rebase_progress(commit, commit_id, new_commit_id);
7744 free(new_commit_id);
7746 done:
7747 got_object_commit_close(commit);
7748 return error;
7751 struct check_path_prefix_arg {
7752 const char *path_prefix;
7753 size_t len;
7754 int errcode;
7757 static const struct got_error *
7758 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7759 struct got_blob_object *blob2, struct got_object_id *id1,
7760 struct got_object_id *id2, const char *path1, const char *path2,
7761 mode_t mode1, mode_t mode2, struct got_repository *repo)
7763 struct check_path_prefix_arg *a = arg;
7765 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7766 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7767 return got_error(a->errcode);
7769 return NULL;
7772 static const struct got_error *
7773 check_path_prefix(struct got_object_id *parent_id,
7774 struct got_object_id *commit_id, const char *path_prefix,
7775 int errcode, struct got_repository *repo)
7777 const struct got_error *err;
7778 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7779 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7780 struct check_path_prefix_arg cpp_arg;
7782 if (got_path_is_root_dir(path_prefix))
7783 return NULL;
7785 err = got_object_open_as_commit(&commit, repo, commit_id);
7786 if (err)
7787 goto done;
7789 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7790 if (err)
7791 goto done;
7793 err = got_object_open_as_tree(&tree1, repo,
7794 got_object_commit_get_tree_id(parent_commit));
7795 if (err)
7796 goto done;
7798 err = got_object_open_as_tree(&tree2, repo,
7799 got_object_commit_get_tree_id(commit));
7800 if (err)
7801 goto done;
7803 cpp_arg.path_prefix = path_prefix;
7804 while (cpp_arg.path_prefix[0] == '/')
7805 cpp_arg.path_prefix++;
7806 cpp_arg.len = strlen(cpp_arg.path_prefix);
7807 cpp_arg.errcode = errcode;
7808 err = got_diff_tree(tree1, tree2, "", "", repo,
7809 check_path_prefix_in_diff, &cpp_arg, 0);
7810 done:
7811 if (tree1)
7812 got_object_tree_close(tree1);
7813 if (tree2)
7814 got_object_tree_close(tree2);
7815 if (commit)
7816 got_object_commit_close(commit);
7817 if (parent_commit)
7818 got_object_commit_close(parent_commit);
7819 return err;
7822 static const struct got_error *
7823 collect_commits(struct got_object_id_queue *commits,
7824 struct got_object_id *initial_commit_id,
7825 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7826 const char *path_prefix, int path_prefix_errcode,
7827 struct got_repository *repo)
7829 const struct got_error *err = NULL;
7830 struct got_commit_graph *graph = NULL;
7831 struct got_object_id *parent_id = NULL;
7832 struct got_object_qid *qid;
7833 struct got_object_id *commit_id = initial_commit_id;
7835 err = got_commit_graph_open(&graph, "/", 1);
7836 if (err)
7837 return err;
7839 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7840 check_cancelled, NULL);
7841 if (err)
7842 goto done;
7843 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7844 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7845 check_cancelled, NULL);
7846 if (err) {
7847 if (err->code == GOT_ERR_ITER_COMPLETED) {
7848 err = got_error_msg(GOT_ERR_ANCESTRY,
7849 "ran out of commits to rebase before "
7850 "youngest common ancestor commit has "
7851 "been reached?!?");
7853 goto done;
7854 } else {
7855 err = check_path_prefix(parent_id, commit_id,
7856 path_prefix, path_prefix_errcode, repo);
7857 if (err)
7858 goto done;
7860 err = got_object_qid_alloc(&qid, commit_id);
7861 if (err)
7862 goto done;
7863 STAILQ_INSERT_HEAD(commits, qid, entry);
7864 commit_id = parent_id;
7867 done:
7868 got_commit_graph_close(graph);
7869 return err;
7872 static const struct got_error *
7873 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
7875 const struct got_error *err = NULL;
7876 time_t committer_time;
7877 struct tm tm;
7878 char datebuf[11]; /* YYYY-MM-DD + NUL */
7879 char *author0 = NULL, *author, *smallerthan;
7880 char *logmsg0 = NULL, *logmsg, *newline;
7882 committer_time = got_object_commit_get_committer_time(commit);
7883 if (localtime_r(&committer_time, &tm) == NULL)
7884 return got_error_from_errno("localtime_r");
7885 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
7886 return got_error(GOT_ERR_NO_SPACE);
7888 author0 = strdup(got_object_commit_get_author(commit));
7889 if (author0 == NULL)
7890 return got_error_from_errno("strdup");
7891 author = author0;
7892 smallerthan = strchr(author, '<');
7893 if (smallerthan && smallerthan[1] != '\0')
7894 author = smallerthan + 1;
7895 author[strcspn(author, "@>")] = '\0';
7897 err = got_object_commit_get_logmsg(&logmsg0, commit);
7898 if (err)
7899 goto done;
7900 logmsg = logmsg0;
7901 while (*logmsg == '\n')
7902 logmsg++;
7903 newline = strchr(logmsg, '\n');
7904 if (newline)
7905 *newline = '\0';
7907 if (asprintf(brief_str, "%s %s %s",
7908 datebuf, author, logmsg) == -1)
7909 err = got_error_from_errno("asprintf");
7910 done:
7911 free(author0);
7912 free(logmsg0);
7913 return err;
7916 static const struct got_error *
7917 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
7918 struct got_repository *repo)
7920 const struct got_error *err;
7921 char *id_str;
7923 err = got_object_id_str(&id_str, id);
7924 if (err)
7925 return err;
7927 err = got_ref_delete(ref, repo);
7928 if (err)
7929 goto done;
7931 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
7932 done:
7933 free(id_str);
7934 return err;
7937 static const struct got_error *
7938 print_backup_ref(const char *branch_name, const char *new_id_str,
7939 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
7940 struct got_reflist_object_id_map *refs_idmap,
7941 struct got_repository *repo)
7943 const struct got_error *err = NULL;
7944 struct got_reflist_head *refs;
7945 char *refs_str = NULL;
7946 struct got_object_id *new_commit_id = NULL;
7947 struct got_commit_object *new_commit = NULL;
7948 char *new_commit_brief_str = NULL;
7949 struct got_object_id *yca_id = NULL;
7950 struct got_commit_object *yca_commit = NULL;
7951 char *yca_id_str = NULL, *yca_brief_str = NULL;
7952 char *custom_refs_str;
7954 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
7955 return got_error_from_errno("asprintf");
7957 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
7958 0, 0, refs_idmap, custom_refs_str);
7959 if (err)
7960 goto done;
7962 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
7963 if (err)
7964 goto done;
7966 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
7967 if (refs) {
7968 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
7969 if (err)
7970 goto done;
7973 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
7974 if (err)
7975 goto done;
7977 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
7978 if (err)
7979 goto done;
7981 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7982 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
7983 if (err)
7984 goto done;
7986 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
7987 refs_str ? " (" : "", refs_str ? refs_str : "",
7988 refs_str ? ")" : "", new_commit_brief_str);
7989 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
7990 got_object_id_cmp(yca_id, old_commit_id) != 0) {
7991 free(refs_str);
7992 refs_str = NULL;
7994 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
7995 if (err)
7996 goto done;
7998 err = get_commit_brief_str(&yca_brief_str, yca_commit);
7999 if (err)
8000 goto done;
8002 err = got_object_id_str(&yca_id_str, yca_id);
8003 if (err)
8004 goto done;
8006 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8007 if (refs) {
8008 err = build_refs_str(&refs_str, refs, yca_id, repo);
8009 if (err)
8010 goto done;
8012 printf("history forked at %s%s%s%s\n %s\n",
8013 yca_id_str,
8014 refs_str ? " (" : "", refs_str ? refs_str : "",
8015 refs_str ? ")" : "", yca_brief_str);
8017 done:
8018 free(custom_refs_str);
8019 free(new_commit_id);
8020 free(refs_str);
8021 free(yca_id);
8022 free(yca_id_str);
8023 free(yca_brief_str);
8024 if (new_commit)
8025 got_object_commit_close(new_commit);
8026 if (yca_commit)
8027 got_object_commit_close(yca_commit);
8029 return NULL;
8032 static const struct got_error *
8033 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8034 int delete, struct got_repository *repo)
8036 const struct got_error *err;
8037 struct got_reflist_head refs, backup_refs;
8038 struct got_reflist_entry *re;
8039 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8040 struct got_object_id *old_commit_id = NULL;
8041 char *branch_name = NULL;
8042 struct got_commit_object *old_commit = NULL;
8043 struct got_reflist_object_id_map *refs_idmap = NULL;
8044 int wanted_branch_found = 0;
8046 TAILQ_INIT(&refs);
8047 TAILQ_INIT(&backup_refs);
8049 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8050 if (err)
8051 return err;
8053 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8054 if (err)
8055 goto done;
8057 if (wanted_branch_name) {
8058 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8059 wanted_branch_name += 11;
8062 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8063 got_ref_cmp_by_commit_timestamp_descending, repo);
8064 if (err)
8065 goto done;
8067 TAILQ_FOREACH(re, &backup_refs, entry) {
8068 const char *refname = got_ref_get_name(re->ref);
8069 char *slash;
8071 err = check_cancelled(NULL);
8072 if (err)
8073 break;
8075 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8076 if (err)
8077 break;
8079 err = got_object_open_as_commit(&old_commit, repo,
8080 old_commit_id);
8081 if (err)
8082 break;
8084 if (strncmp(backup_ref_prefix, refname,
8085 backup_ref_prefix_len) == 0)
8086 refname += backup_ref_prefix_len;
8088 while (refname[0] == '/')
8089 refname++;
8091 branch_name = strdup(refname);
8092 if (branch_name == NULL) {
8093 err = got_error_from_errno("strdup");
8094 break;
8096 slash = strrchr(branch_name, '/');
8097 if (slash) {
8098 *slash = '\0';
8099 refname += strlen(branch_name) + 1;
8102 if (wanted_branch_name == NULL ||
8103 strcmp(wanted_branch_name, branch_name) == 0) {
8104 wanted_branch_found = 1;
8105 if (delete) {
8106 err = delete_backup_ref(re->ref,
8107 old_commit_id, repo);
8108 } else {
8109 err = print_backup_ref(branch_name, refname,
8110 old_commit_id, old_commit, refs_idmap,
8111 repo);
8113 if (err)
8114 break;
8117 free(old_commit_id);
8118 old_commit_id = NULL;
8119 free(branch_name);
8120 branch_name = NULL;
8121 got_object_commit_close(old_commit);
8122 old_commit = NULL;
8125 if (wanted_branch_name && !wanted_branch_found) {
8126 err = got_error_fmt(GOT_ERR_NOT_REF,
8127 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8129 done:
8130 if (refs_idmap)
8131 got_reflist_object_id_map_free(refs_idmap);
8132 got_ref_list_free(&refs);
8133 got_ref_list_free(&backup_refs);
8134 free(old_commit_id);
8135 free(branch_name);
8136 if (old_commit)
8137 got_object_commit_close(old_commit);
8138 return err;
8141 static const struct got_error *
8142 cmd_rebase(int argc, char *argv[])
8144 const struct got_error *error = NULL;
8145 struct got_worktree *worktree = NULL;
8146 struct got_repository *repo = NULL;
8147 struct got_fileindex *fileindex = NULL;
8148 char *cwd = NULL;
8149 struct got_reference *branch = NULL;
8150 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8151 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8152 struct got_object_id *resume_commit_id = NULL;
8153 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8154 struct got_commit_object *commit = NULL;
8155 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8156 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8157 int delete_backups = 0;
8158 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8159 struct got_object_id_queue commits;
8160 struct got_pathlist_head merged_paths;
8161 const struct got_object_id_queue *parent_ids;
8162 struct got_object_qid *qid, *pid;
8164 STAILQ_INIT(&commits);
8165 TAILQ_INIT(&merged_paths);
8167 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8168 switch (ch) {
8169 case 'a':
8170 abort_rebase = 1;
8171 break;
8172 case 'c':
8173 continue_rebase = 1;
8174 break;
8175 case 'l':
8176 list_backups = 1;
8177 break;
8178 case 'X':
8179 delete_backups = 1;
8180 break;
8181 default:
8182 usage_rebase();
8183 /* NOTREACHED */
8187 argc -= optind;
8188 argv += optind;
8190 #ifndef PROFILE
8191 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8192 "unveil", NULL) == -1)
8193 err(1, "pledge");
8194 #endif
8195 if (list_backups) {
8196 if (abort_rebase)
8197 option_conflict('l', 'a');
8198 if (continue_rebase)
8199 option_conflict('l', 'c');
8200 if (delete_backups)
8201 option_conflict('l', 'X');
8202 if (argc != 0 && argc != 1)
8203 usage_rebase();
8204 } else if (delete_backups) {
8205 if (abort_rebase)
8206 option_conflict('X', 'a');
8207 if (continue_rebase)
8208 option_conflict('X', 'c');
8209 if (list_backups)
8210 option_conflict('l', 'X');
8211 if (argc != 0 && argc != 1)
8212 usage_rebase();
8213 } else {
8214 if (abort_rebase && continue_rebase)
8215 usage_rebase();
8216 else if (abort_rebase || continue_rebase) {
8217 if (argc != 0)
8218 usage_rebase();
8219 } else if (argc != 1)
8220 usage_rebase();
8223 cwd = getcwd(NULL, 0);
8224 if (cwd == NULL) {
8225 error = got_error_from_errno("getcwd");
8226 goto done;
8228 error = got_worktree_open(&worktree, cwd);
8229 if (error) {
8230 if (list_backups || delete_backups) {
8231 if (error->code != GOT_ERR_NOT_WORKTREE)
8232 goto done;
8233 } else {
8234 if (error->code == GOT_ERR_NOT_WORKTREE)
8235 error = wrap_not_worktree_error(error,
8236 "rebase", cwd);
8237 goto done;
8241 error = got_repo_open(&repo,
8242 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8243 if (error != NULL)
8244 goto done;
8246 error = apply_unveil(got_repo_get_path(repo), 0,
8247 worktree ? got_worktree_get_root_path(worktree) : NULL);
8248 if (error)
8249 goto done;
8251 if (list_backups || delete_backups) {
8252 error = process_backup_refs(
8253 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8254 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8255 goto done; /* nothing else to do */
8258 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8259 worktree);
8260 if (error)
8261 goto done;
8262 if (histedit_in_progress) {
8263 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8264 goto done;
8267 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8268 if (error)
8269 goto done;
8271 if (abort_rebase) {
8272 struct got_update_progress_arg upa;
8273 if (!rebase_in_progress) {
8274 error = got_error(GOT_ERR_NOT_REBASING);
8275 goto done;
8277 error = got_worktree_rebase_continue(&resume_commit_id,
8278 &new_base_branch, &tmp_branch, &branch, &fileindex,
8279 worktree, repo);
8280 if (error)
8281 goto done;
8282 printf("Switching work tree to %s\n",
8283 got_ref_get_symref_target(new_base_branch));
8284 memset(&upa, 0, sizeof(upa));
8285 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8286 new_base_branch, update_progress, &upa);
8287 if (error)
8288 goto done;
8289 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8290 print_update_progress_stats(&upa);
8291 goto done; /* nothing else to do */
8294 if (continue_rebase) {
8295 if (!rebase_in_progress) {
8296 error = got_error(GOT_ERR_NOT_REBASING);
8297 goto done;
8299 error = got_worktree_rebase_continue(&resume_commit_id,
8300 &new_base_branch, &tmp_branch, &branch, &fileindex,
8301 worktree, repo);
8302 if (error)
8303 goto done;
8305 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8306 resume_commit_id, repo);
8307 if (error)
8308 goto done;
8310 yca_id = got_object_id_dup(resume_commit_id);
8311 if (yca_id == NULL) {
8312 error = got_error_from_errno("got_object_id_dup");
8313 goto done;
8315 } else {
8316 error = got_ref_open(&branch, repo, argv[0], 0);
8317 if (error != NULL)
8318 goto done;
8321 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8322 if (error)
8323 goto done;
8325 if (!continue_rebase) {
8326 struct got_object_id *base_commit_id;
8328 base_commit_id = got_worktree_get_base_commit_id(worktree);
8329 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8330 base_commit_id, branch_head_commit_id, repo,
8331 check_cancelled, NULL);
8332 if (error)
8333 goto done;
8334 if (yca_id == NULL) {
8335 error = got_error_msg(GOT_ERR_ANCESTRY,
8336 "specified branch shares no common ancestry "
8337 "with work tree's branch");
8338 goto done;
8341 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8342 if (error) {
8343 if (error->code != GOT_ERR_ANCESTRY)
8344 goto done;
8345 error = NULL;
8346 } else {
8347 static char msg[128];
8348 snprintf(msg, sizeof(msg),
8349 "%s is already based on %s",
8350 got_ref_get_name(branch),
8351 got_worktree_get_head_ref_name(worktree));
8352 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8353 goto done;
8355 error = got_worktree_rebase_prepare(&new_base_branch,
8356 &tmp_branch, &fileindex, worktree, branch, repo);
8357 if (error)
8358 goto done;
8361 commit_id = branch_head_commit_id;
8362 error = got_object_open_as_commit(&commit, repo, commit_id);
8363 if (error)
8364 goto done;
8366 parent_ids = got_object_commit_get_parent_ids(commit);
8367 pid = STAILQ_FIRST(parent_ids);
8368 if (pid == NULL) {
8369 if (!continue_rebase) {
8370 struct got_update_progress_arg upa;
8371 memset(&upa, 0, sizeof(upa));
8372 error = got_worktree_rebase_abort(worktree, fileindex,
8373 repo, new_base_branch, update_progress, &upa);
8374 if (error)
8375 goto done;
8376 printf("Rebase of %s aborted\n",
8377 got_ref_get_name(branch));
8378 print_update_progress_stats(&upa);
8381 error = got_error(GOT_ERR_EMPTY_REBASE);
8382 goto done;
8384 error = collect_commits(&commits, commit_id, pid->id,
8385 yca_id, got_worktree_get_path_prefix(worktree),
8386 GOT_ERR_REBASE_PATH, repo);
8387 got_object_commit_close(commit);
8388 commit = NULL;
8389 if (error)
8390 goto done;
8392 if (STAILQ_EMPTY(&commits)) {
8393 if (continue_rebase) {
8394 error = rebase_complete(worktree, fileindex,
8395 branch, new_base_branch, tmp_branch, repo,
8396 create_backup);
8397 goto done;
8398 } else {
8399 /* Fast-forward the reference of the branch. */
8400 struct got_object_id *new_head_commit_id;
8401 char *id_str;
8402 error = got_ref_resolve(&new_head_commit_id, repo,
8403 new_base_branch);
8404 if (error)
8405 goto done;
8406 error = got_object_id_str(&id_str, new_head_commit_id);
8407 printf("Forwarding %s to commit %s\n",
8408 got_ref_get_name(branch), id_str);
8409 free(id_str);
8410 error = got_ref_change_ref(branch,
8411 new_head_commit_id);
8412 if (error)
8413 goto done;
8414 /* No backup needed since objects did not change. */
8415 create_backup = 0;
8419 pid = NULL;
8420 STAILQ_FOREACH(qid, &commits, entry) {
8421 struct got_update_progress_arg upa;
8423 commit_id = qid->id;
8424 parent_id = pid ? pid->id : yca_id;
8425 pid = qid;
8427 memset(&upa, 0, sizeof(upa));
8428 error = got_worktree_rebase_merge_files(&merged_paths,
8429 worktree, fileindex, parent_id, commit_id, repo,
8430 update_progress, &upa, check_cancelled, NULL);
8431 if (error)
8432 goto done;
8434 print_update_progress_stats(&upa);
8435 if (upa.conflicts > 0)
8436 rebase_status = GOT_STATUS_CONFLICT;
8438 if (rebase_status == GOT_STATUS_CONFLICT) {
8439 error = show_rebase_merge_conflict(qid->id, repo);
8440 if (error)
8441 goto done;
8442 got_worktree_rebase_pathlist_free(&merged_paths);
8443 break;
8446 error = rebase_commit(&merged_paths, worktree, fileindex,
8447 tmp_branch, commit_id, repo);
8448 got_worktree_rebase_pathlist_free(&merged_paths);
8449 if (error)
8450 goto done;
8453 if (rebase_status == GOT_STATUS_CONFLICT) {
8454 error = got_worktree_rebase_postpone(worktree, fileindex);
8455 if (error)
8456 goto done;
8457 error = got_error_msg(GOT_ERR_CONFLICTS,
8458 "conflicts must be resolved before rebasing can continue");
8459 } else
8460 error = rebase_complete(worktree, fileindex, branch,
8461 new_base_branch, tmp_branch, repo, create_backup);
8462 done:
8463 got_object_id_queue_free(&commits);
8464 free(branch_head_commit_id);
8465 free(resume_commit_id);
8466 free(yca_id);
8467 if (commit)
8468 got_object_commit_close(commit);
8469 if (branch)
8470 got_ref_close(branch);
8471 if (new_base_branch)
8472 got_ref_close(new_base_branch);
8473 if (tmp_branch)
8474 got_ref_close(tmp_branch);
8475 if (worktree)
8476 got_worktree_close(worktree);
8477 if (repo) {
8478 const struct got_error *close_err = got_repo_close(repo);
8479 if (error == NULL)
8480 error = close_err;
8482 return error;
8485 __dead static void
8486 usage_histedit(void)
8488 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8489 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
8490 getprogname());
8491 exit(1);
8494 #define GOT_HISTEDIT_PICK 'p'
8495 #define GOT_HISTEDIT_EDIT 'e'
8496 #define GOT_HISTEDIT_FOLD 'f'
8497 #define GOT_HISTEDIT_DROP 'd'
8498 #define GOT_HISTEDIT_MESG 'm'
8500 static struct got_histedit_cmd {
8501 unsigned char code;
8502 const char *name;
8503 const char *desc;
8504 } got_histedit_cmds[] = {
8505 { GOT_HISTEDIT_PICK, "pick", "use commit" },
8506 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
8507 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
8508 "be used" },
8509 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
8510 { GOT_HISTEDIT_MESG, "mesg",
8511 "single-line log message for commit above (open editor if empty)" },
8514 struct got_histedit_list_entry {
8515 TAILQ_ENTRY(got_histedit_list_entry) entry;
8516 struct got_object_id *commit_id;
8517 const struct got_histedit_cmd *cmd;
8518 char *logmsg;
8520 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
8522 static const struct got_error *
8523 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
8524 FILE *f, struct got_repository *repo)
8526 const struct got_error *err = NULL;
8527 char *logmsg = NULL, *id_str = NULL;
8528 struct got_commit_object *commit = NULL;
8529 int n;
8531 err = got_object_open_as_commit(&commit, repo, commit_id);
8532 if (err)
8533 goto done;
8535 err = get_short_logmsg(&logmsg, 34, commit);
8536 if (err)
8537 goto done;
8539 err = got_object_id_str(&id_str, commit_id);
8540 if (err)
8541 goto done;
8543 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
8544 if (n < 0)
8545 err = got_ferror(f, GOT_ERR_IO);
8546 done:
8547 if (commit)
8548 got_object_commit_close(commit);
8549 free(id_str);
8550 free(logmsg);
8551 return err;
8554 static const struct got_error *
8555 histedit_write_commit_list(struct got_object_id_queue *commits,
8556 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
8558 const struct got_error *err = NULL;
8559 struct got_object_qid *qid;
8560 const char *histedit_cmd = NULL;
8562 if (STAILQ_EMPTY(commits))
8563 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8565 STAILQ_FOREACH(qid, commits, entry) {
8566 histedit_cmd = got_histedit_cmds[0].name;
8567 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
8568 histedit_cmd = "fold";
8569 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
8570 if (err)
8571 break;
8572 if (edit_logmsg_only) {
8573 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
8574 if (n < 0) {
8575 err = got_ferror(f, GOT_ERR_IO);
8576 break;
8581 return err;
8584 static const struct got_error *
8585 write_cmd_list(FILE *f, const char *branch_name,
8586 struct got_object_id_queue *commits)
8588 const struct got_error *err = NULL;
8589 size_t i;
8590 int n;
8591 char *id_str;
8592 struct got_object_qid *qid;
8594 qid = STAILQ_FIRST(commits);
8595 err = got_object_id_str(&id_str, qid->id);
8596 if (err)
8597 return err;
8599 n = fprintf(f,
8600 "# Editing the history of branch '%s' starting at\n"
8601 "# commit %s\n"
8602 "# Commits will be processed in order from top to "
8603 "bottom of this file.\n", branch_name, id_str);
8604 if (n < 0) {
8605 err = got_ferror(f, GOT_ERR_IO);
8606 goto done;
8609 n = fprintf(f, "# Available histedit commands:\n");
8610 if (n < 0) {
8611 err = got_ferror(f, GOT_ERR_IO);
8612 goto done;
8615 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8616 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8617 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8618 cmd->desc);
8619 if (n < 0) {
8620 err = got_ferror(f, GOT_ERR_IO);
8621 break;
8624 done:
8625 free(id_str);
8626 return err;
8629 static const struct got_error *
8630 histedit_syntax_error(int lineno)
8632 static char msg[42];
8633 int ret;
8635 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8636 lineno);
8637 if (ret == -1 || ret >= sizeof(msg))
8638 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8640 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8643 static const struct got_error *
8644 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8645 char *logmsg, struct got_repository *repo)
8647 const struct got_error *err;
8648 struct got_commit_object *folded_commit = NULL;
8649 char *id_str, *folded_logmsg = NULL;
8651 err = got_object_id_str(&id_str, hle->commit_id);
8652 if (err)
8653 return err;
8655 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8656 if (err)
8657 goto done;
8659 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8660 if (err)
8661 goto done;
8662 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8663 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8664 folded_logmsg) == -1) {
8665 err = got_error_from_errno("asprintf");
8667 done:
8668 if (folded_commit)
8669 got_object_commit_close(folded_commit);
8670 free(id_str);
8671 free(folded_logmsg);
8672 return err;
8675 static struct got_histedit_list_entry *
8676 get_folded_commits(struct got_histedit_list_entry *hle)
8678 struct got_histedit_list_entry *prev, *folded = NULL;
8680 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8681 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8682 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8683 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8684 folded = prev;
8685 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8688 return folded;
8691 static const struct got_error *
8692 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8693 struct got_repository *repo)
8695 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8696 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8697 const struct got_error *err = NULL;
8698 struct got_commit_object *commit = NULL;
8699 int logmsg_len;
8700 int fd;
8701 struct got_histedit_list_entry *folded = NULL;
8703 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8704 if (err)
8705 return err;
8707 folded = get_folded_commits(hle);
8708 if (folded) {
8709 while (folded != hle) {
8710 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8711 folded = TAILQ_NEXT(folded, entry);
8712 continue;
8714 err = append_folded_commit_msg(&new_msg, folded,
8715 logmsg, repo);
8716 if (err)
8717 goto done;
8718 free(logmsg);
8719 logmsg = new_msg;
8720 folded = TAILQ_NEXT(folded, entry);
8724 err = got_object_id_str(&id_str, hle->commit_id);
8725 if (err)
8726 goto done;
8727 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8728 if (err)
8729 goto done;
8730 logmsg_len = asprintf(&new_msg,
8731 "%s\n# original log message of commit %s: %s",
8732 logmsg ? logmsg : "", id_str, orig_logmsg);
8733 if (logmsg_len == -1) {
8734 err = got_error_from_errno("asprintf");
8735 goto done;
8737 free(logmsg);
8738 logmsg = new_msg;
8740 err = got_object_id_str(&id_str, hle->commit_id);
8741 if (err)
8742 goto done;
8744 err = got_opentemp_named_fd(&logmsg_path, &fd,
8745 GOT_TMPDIR_STR "/got-logmsg");
8746 if (err)
8747 goto done;
8749 write(fd, logmsg, logmsg_len);
8750 close(fd);
8752 err = get_editor(&editor);
8753 if (err)
8754 goto done;
8756 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8757 logmsg_len, 0);
8758 if (err) {
8759 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8760 goto done;
8761 err = NULL;
8762 hle->logmsg = strdup(new_msg);
8763 if (hle->logmsg == NULL)
8764 err = got_error_from_errno("strdup");
8766 done:
8767 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8768 err = got_error_from_errno2("unlink", logmsg_path);
8769 free(logmsg_path);
8770 free(logmsg);
8771 free(orig_logmsg);
8772 free(editor);
8773 if (commit)
8774 got_object_commit_close(commit);
8775 return err;
8778 static const struct got_error *
8779 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8780 FILE *f, struct got_repository *repo)
8782 const struct got_error *err = NULL;
8783 char *line = NULL, *p, *end;
8784 size_t i, size;
8785 ssize_t len;
8786 int lineno = 0;
8787 const struct got_histedit_cmd *cmd;
8788 struct got_object_id *commit_id = NULL;
8789 struct got_histedit_list_entry *hle = NULL;
8791 for (;;) {
8792 len = getline(&line, &size, f);
8793 if (len == -1) {
8794 const struct got_error *getline_err;
8795 if (feof(f))
8796 break;
8797 getline_err = got_error_from_errno("getline");
8798 err = got_ferror(f, getline_err->code);
8799 break;
8801 lineno++;
8802 p = line;
8803 while (isspace((unsigned char)p[0]))
8804 p++;
8805 if (p[0] == '#' || p[0] == '\0') {
8806 free(line);
8807 line = NULL;
8808 continue;
8810 cmd = NULL;
8811 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8812 cmd = &got_histedit_cmds[i];
8813 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8814 isspace((unsigned char)p[strlen(cmd->name)])) {
8815 p += strlen(cmd->name);
8816 break;
8818 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8819 p++;
8820 break;
8823 if (i == nitems(got_histedit_cmds)) {
8824 err = histedit_syntax_error(lineno);
8825 break;
8827 while (isspace((unsigned char)p[0]))
8828 p++;
8829 if (cmd->code == GOT_HISTEDIT_MESG) {
8830 if (hle == NULL || hle->logmsg != NULL) {
8831 err = got_error(GOT_ERR_HISTEDIT_CMD);
8832 break;
8834 if (p[0] == '\0') {
8835 err = histedit_edit_logmsg(hle, repo);
8836 if (err)
8837 break;
8838 } else {
8839 hle->logmsg = strdup(p);
8840 if (hle->logmsg == NULL) {
8841 err = got_error_from_errno("strdup");
8842 break;
8845 free(line);
8846 line = NULL;
8847 continue;
8848 } else {
8849 end = p;
8850 while (end[0] && !isspace((unsigned char)end[0]))
8851 end++;
8852 *end = '\0';
8854 err = got_object_resolve_id_str(&commit_id, repo, p);
8855 if (err) {
8856 /* override error code */
8857 err = histedit_syntax_error(lineno);
8858 break;
8861 hle = malloc(sizeof(*hle));
8862 if (hle == NULL) {
8863 err = got_error_from_errno("malloc");
8864 break;
8866 hle->cmd = cmd;
8867 hle->commit_id = commit_id;
8868 hle->logmsg = NULL;
8869 commit_id = NULL;
8870 free(line);
8871 line = NULL;
8872 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8875 free(line);
8876 free(commit_id);
8877 return err;
8880 static const struct got_error *
8881 histedit_check_script(struct got_histedit_list *histedit_cmds,
8882 struct got_object_id_queue *commits, struct got_repository *repo)
8884 const struct got_error *err = NULL;
8885 struct got_object_qid *qid;
8886 struct got_histedit_list_entry *hle;
8887 static char msg[92];
8888 char *id_str;
8890 if (TAILQ_EMPTY(histedit_cmds))
8891 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8892 "histedit script contains no commands");
8893 if (STAILQ_EMPTY(commits))
8894 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8896 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8897 struct got_histedit_list_entry *hle2;
8898 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8899 if (hle == hle2)
8900 continue;
8901 if (got_object_id_cmp(hle->commit_id,
8902 hle2->commit_id) != 0)
8903 continue;
8904 err = got_object_id_str(&id_str, hle->commit_id);
8905 if (err)
8906 return err;
8907 snprintf(msg, sizeof(msg), "commit %s is listed "
8908 "more than once in histedit script", id_str);
8909 free(id_str);
8910 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8914 STAILQ_FOREACH(qid, commits, entry) {
8915 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8916 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8917 break;
8919 if (hle == NULL) {
8920 err = got_object_id_str(&id_str, qid->id);
8921 if (err)
8922 return err;
8923 snprintf(msg, sizeof(msg),
8924 "commit %s missing from histedit script", id_str);
8925 free(id_str);
8926 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8930 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8931 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8932 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8933 "last commit in histedit script cannot be folded");
8935 return NULL;
8938 static const struct got_error *
8939 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8940 const char *path, struct got_object_id_queue *commits,
8941 struct got_repository *repo)
8943 const struct got_error *err = NULL;
8944 char *editor;
8945 FILE *f = NULL;
8947 err = get_editor(&editor);
8948 if (err)
8949 return err;
8951 if (spawn_editor(editor, path) == -1) {
8952 err = got_error_from_errno("failed spawning editor");
8953 goto done;
8956 f = fopen(path, "r");
8957 if (f == NULL) {
8958 err = got_error_from_errno("fopen");
8959 goto done;
8961 err = histedit_parse_list(histedit_cmds, f, repo);
8962 if (err)
8963 goto done;
8965 err = histedit_check_script(histedit_cmds, commits, repo);
8966 done:
8967 if (f && fclose(f) == EOF && err == NULL)
8968 err = got_error_from_errno("fclose");
8969 free(editor);
8970 return err;
8973 static const struct got_error *
8974 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8975 struct got_object_id_queue *, const char *, const char *,
8976 struct got_repository *);
8978 static const struct got_error *
8979 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8980 struct got_object_id_queue *commits, const char *branch_name,
8981 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8983 const struct got_error *err;
8984 FILE *f = NULL;
8985 char *path = NULL;
8987 err = got_opentemp_named(&path, &f, "got-histedit");
8988 if (err)
8989 return err;
8991 err = write_cmd_list(f, branch_name, commits);
8992 if (err)
8993 goto done;
8995 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
8996 fold_only, repo);
8997 if (err)
8998 goto done;
9000 if (edit_logmsg_only || fold_only) {
9001 rewind(f);
9002 err = histedit_parse_list(histedit_cmds, f, repo);
9003 } else {
9004 if (fclose(f) == EOF) {
9005 err = got_error_from_errno("fclose");
9006 goto done;
9008 f = NULL;
9009 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9010 if (err) {
9011 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9012 err->code != GOT_ERR_HISTEDIT_CMD)
9013 goto done;
9014 err = histedit_edit_list_retry(histedit_cmds, err,
9015 commits, path, branch_name, repo);
9018 done:
9019 if (f && fclose(f) == EOF && err == NULL)
9020 err = got_error_from_errno("fclose");
9021 if (path && unlink(path) != 0 && err == NULL)
9022 err = got_error_from_errno2("unlink", path);
9023 free(path);
9024 return err;
9027 static const struct got_error *
9028 histedit_save_list(struct got_histedit_list *histedit_cmds,
9029 struct got_worktree *worktree, struct got_repository *repo)
9031 const struct got_error *err = NULL;
9032 char *path = NULL;
9033 FILE *f = NULL;
9034 struct got_histedit_list_entry *hle;
9035 struct got_commit_object *commit = NULL;
9037 err = got_worktree_get_histedit_script_path(&path, worktree);
9038 if (err)
9039 return err;
9041 f = fopen(path, "w");
9042 if (f == NULL) {
9043 err = got_error_from_errno2("fopen", path);
9044 goto done;
9046 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9047 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9048 repo);
9049 if (err)
9050 break;
9052 if (hle->logmsg) {
9053 int n = fprintf(f, "%c %s\n",
9054 GOT_HISTEDIT_MESG, hle->logmsg);
9055 if (n < 0) {
9056 err = got_ferror(f, GOT_ERR_IO);
9057 break;
9061 done:
9062 if (f && fclose(f) == EOF && err == NULL)
9063 err = got_error_from_errno("fclose");
9064 free(path);
9065 if (commit)
9066 got_object_commit_close(commit);
9067 return err;
9070 void
9071 histedit_free_list(struct got_histedit_list *histedit_cmds)
9073 struct got_histedit_list_entry *hle;
9075 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9076 TAILQ_REMOVE(histedit_cmds, hle, entry);
9077 free(hle);
9081 static const struct got_error *
9082 histedit_load_list(struct got_histedit_list *histedit_cmds,
9083 const char *path, struct got_repository *repo)
9085 const struct got_error *err = NULL;
9086 FILE *f = NULL;
9088 f = fopen(path, "r");
9089 if (f == NULL) {
9090 err = got_error_from_errno2("fopen", path);
9091 goto done;
9094 err = histedit_parse_list(histedit_cmds, f, repo);
9095 done:
9096 if (f && fclose(f) == EOF && err == NULL)
9097 err = got_error_from_errno("fclose");
9098 return err;
9101 static const struct got_error *
9102 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9103 const struct got_error *edit_err, struct got_object_id_queue *commits,
9104 const char *path, const char *branch_name, struct got_repository *repo)
9106 const struct got_error *err = NULL, *prev_err = edit_err;
9107 int resp = ' ';
9109 while (resp != 'c' && resp != 'r' && resp != 'a') {
9110 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9111 "or (a)bort: ", getprogname(), prev_err->msg);
9112 resp = getchar();
9113 if (resp == '\n')
9114 resp = getchar();
9115 if (resp == 'c') {
9116 histedit_free_list(histedit_cmds);
9117 err = histedit_run_editor(histedit_cmds, path, commits,
9118 repo);
9119 if (err) {
9120 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9121 err->code != GOT_ERR_HISTEDIT_CMD)
9122 break;
9123 prev_err = err;
9124 resp = ' ';
9125 continue;
9127 break;
9128 } else if (resp == 'r') {
9129 histedit_free_list(histedit_cmds);
9130 err = histedit_edit_script(histedit_cmds,
9131 commits, branch_name, 0, 0, repo);
9132 if (err) {
9133 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9134 err->code != GOT_ERR_HISTEDIT_CMD)
9135 break;
9136 prev_err = err;
9137 resp = ' ';
9138 continue;
9140 break;
9141 } else if (resp == 'a') {
9142 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9143 break;
9144 } else
9145 printf("invalid response '%c'\n", resp);
9148 return err;
9151 static const struct got_error *
9152 histedit_complete(struct got_worktree *worktree,
9153 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9154 struct got_reference *branch, struct got_repository *repo)
9156 printf("Switching work tree to %s\n",
9157 got_ref_get_symref_target(branch));
9158 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9159 branch, repo);
9162 static const struct got_error *
9163 show_histedit_progress(struct got_commit_object *commit,
9164 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9166 const struct got_error *err;
9167 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9169 err = got_object_id_str(&old_id_str, hle->commit_id);
9170 if (err)
9171 goto done;
9173 if (new_id) {
9174 err = got_object_id_str(&new_id_str, new_id);
9175 if (err)
9176 goto done;
9179 old_id_str[12] = '\0';
9180 if (new_id_str)
9181 new_id_str[12] = '\0';
9183 if (hle->logmsg) {
9184 logmsg = strdup(hle->logmsg);
9185 if (logmsg == NULL) {
9186 err = got_error_from_errno("strdup");
9187 goto done;
9189 trim_logmsg(logmsg, 42);
9190 } else {
9191 err = get_short_logmsg(&logmsg, 42, commit);
9192 if (err)
9193 goto done;
9196 switch (hle->cmd->code) {
9197 case GOT_HISTEDIT_PICK:
9198 case GOT_HISTEDIT_EDIT:
9199 printf("%s -> %s: %s\n", old_id_str,
9200 new_id_str ? new_id_str : "no-op change", logmsg);
9201 break;
9202 case GOT_HISTEDIT_DROP:
9203 case GOT_HISTEDIT_FOLD:
9204 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9205 logmsg);
9206 break;
9207 default:
9208 break;
9210 done:
9211 free(old_id_str);
9212 free(new_id_str);
9213 return err;
9216 static const struct got_error *
9217 histedit_commit(struct got_pathlist_head *merged_paths,
9218 struct got_worktree *worktree, struct got_fileindex *fileindex,
9219 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9220 struct got_repository *repo)
9222 const struct got_error *err;
9223 struct got_commit_object *commit;
9224 struct got_object_id *new_commit_id;
9226 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9227 && hle->logmsg == NULL) {
9228 err = histedit_edit_logmsg(hle, repo);
9229 if (err)
9230 return err;
9233 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9234 if (err)
9235 return err;
9237 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9238 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9239 hle->logmsg, repo);
9240 if (err) {
9241 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9242 goto done;
9243 err = show_histedit_progress(commit, hle, NULL);
9244 } else {
9245 err = show_histedit_progress(commit, hle, new_commit_id);
9246 free(new_commit_id);
9248 done:
9249 got_object_commit_close(commit);
9250 return err;
9253 static const struct got_error *
9254 histedit_skip_commit(struct got_histedit_list_entry *hle,
9255 struct got_worktree *worktree, struct got_repository *repo)
9257 const struct got_error *error;
9258 struct got_commit_object *commit;
9260 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9261 repo);
9262 if (error)
9263 return error;
9265 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9266 if (error)
9267 return error;
9269 error = show_histedit_progress(commit, hle, NULL);
9270 got_object_commit_close(commit);
9271 return error;
9274 static const struct got_error *
9275 check_local_changes(void *arg, unsigned char status,
9276 unsigned char staged_status, const char *path,
9277 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9278 struct got_object_id *commit_id, int dirfd, const char *de_name)
9280 int *have_local_changes = arg;
9282 switch (status) {
9283 case GOT_STATUS_ADD:
9284 case GOT_STATUS_DELETE:
9285 case GOT_STATUS_MODIFY:
9286 case GOT_STATUS_CONFLICT:
9287 *have_local_changes = 1;
9288 return got_error(GOT_ERR_CANCELLED);
9289 default:
9290 break;
9293 switch (staged_status) {
9294 case GOT_STATUS_ADD:
9295 case GOT_STATUS_DELETE:
9296 case GOT_STATUS_MODIFY:
9297 *have_local_changes = 1;
9298 return got_error(GOT_ERR_CANCELLED);
9299 default:
9300 break;
9303 return NULL;
9306 static const struct got_error *
9307 cmd_histedit(int argc, char *argv[])
9309 const struct got_error *error = NULL;
9310 struct got_worktree *worktree = NULL;
9311 struct got_fileindex *fileindex = NULL;
9312 struct got_repository *repo = NULL;
9313 char *cwd = NULL;
9314 struct got_reference *branch = NULL;
9315 struct got_reference *tmp_branch = NULL;
9316 struct got_object_id *resume_commit_id = NULL;
9317 struct got_object_id *base_commit_id = NULL;
9318 struct got_object_id *head_commit_id = NULL;
9319 struct got_commit_object *commit = NULL;
9320 int ch, rebase_in_progress = 0;
9321 struct got_update_progress_arg upa;
9322 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9323 int edit_logmsg_only = 0, fold_only = 0;
9324 int list_backups = 0, delete_backups = 0;
9325 const char *edit_script_path = NULL;
9326 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9327 struct got_object_id_queue commits;
9328 struct got_pathlist_head merged_paths;
9329 const struct got_object_id_queue *parent_ids;
9330 struct got_object_qid *pid;
9331 struct got_histedit_list histedit_cmds;
9332 struct got_histedit_list_entry *hle;
9334 STAILQ_INIT(&commits);
9335 TAILQ_INIT(&histedit_cmds);
9336 TAILQ_INIT(&merged_paths);
9337 memset(&upa, 0, sizeof(upa));
9339 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9340 switch (ch) {
9341 case 'a':
9342 abort_edit = 1;
9343 break;
9344 case 'c':
9345 continue_edit = 1;
9346 break;
9347 case 'f':
9348 fold_only = 1;
9349 break;
9350 case 'F':
9351 edit_script_path = optarg;
9352 break;
9353 case 'm':
9354 edit_logmsg_only = 1;
9355 break;
9356 case 'l':
9357 list_backups = 1;
9358 break;
9359 case 'X':
9360 delete_backups = 1;
9361 break;
9362 default:
9363 usage_histedit();
9364 /* NOTREACHED */
9368 argc -= optind;
9369 argv += optind;
9371 #ifndef PROFILE
9372 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9373 "unveil", NULL) == -1)
9374 err(1, "pledge");
9375 #endif
9376 if (abort_edit && continue_edit)
9377 option_conflict('a', 'c');
9378 if (edit_script_path && edit_logmsg_only)
9379 option_conflict('F', 'm');
9380 if (abort_edit && edit_logmsg_only)
9381 option_conflict('a', 'm');
9382 if (continue_edit && edit_logmsg_only)
9383 option_conflict('c', 'm');
9384 if (abort_edit && fold_only)
9385 option_conflict('a', 'f');
9386 if (continue_edit && fold_only)
9387 option_conflict('c', 'f');
9388 if (fold_only && edit_logmsg_only)
9389 option_conflict('f', 'm');
9390 if (edit_script_path && fold_only)
9391 option_conflict('F', 'f');
9392 if (list_backups) {
9393 if (abort_edit)
9394 option_conflict('l', 'a');
9395 if (continue_edit)
9396 option_conflict('l', 'c');
9397 if (edit_script_path)
9398 option_conflict('l', 'F');
9399 if (edit_logmsg_only)
9400 option_conflict('l', 'm');
9401 if (fold_only)
9402 option_conflict('l', 'f');
9403 if (delete_backups)
9404 option_conflict('l', 'X');
9405 if (argc != 0 && argc != 1)
9406 usage_histedit();
9407 } else if (delete_backups) {
9408 if (abort_edit)
9409 option_conflict('X', 'a');
9410 if (continue_edit)
9411 option_conflict('X', 'c');
9412 if (edit_script_path)
9413 option_conflict('X', 'F');
9414 if (edit_logmsg_only)
9415 option_conflict('X', 'm');
9416 if (fold_only)
9417 option_conflict('X', 'f');
9418 if (list_backups)
9419 option_conflict('X', 'l');
9420 if (argc != 0 && argc != 1)
9421 usage_histedit();
9422 } else if (argc != 0)
9423 usage_histedit();
9426 * This command cannot apply unveil(2) in all cases because the
9427 * user may choose to run an editor to edit the histedit script
9428 * and to edit individual commit log messages.
9429 * unveil(2) traverses exec(2); if an editor is used we have to
9430 * apply unveil after edit script and log messages have been written.
9431 * XXX TODO: Make use of unveil(2) where possible.
9434 cwd = getcwd(NULL, 0);
9435 if (cwd == NULL) {
9436 error = got_error_from_errno("getcwd");
9437 goto done;
9439 error = got_worktree_open(&worktree, cwd);
9440 if (error) {
9441 if (list_backups || delete_backups) {
9442 if (error->code != GOT_ERR_NOT_WORKTREE)
9443 goto done;
9444 } else {
9445 if (error->code == GOT_ERR_NOT_WORKTREE)
9446 error = wrap_not_worktree_error(error,
9447 "histedit", cwd);
9448 goto done;
9452 if (list_backups || delete_backups) {
9453 error = got_repo_open(&repo,
9454 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9455 NULL);
9456 if (error != NULL)
9457 goto done;
9458 error = apply_unveil(got_repo_get_path(repo), 0,
9459 worktree ? got_worktree_get_root_path(worktree) : NULL);
9460 if (error)
9461 goto done;
9462 error = process_backup_refs(
9463 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9464 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9465 goto done; /* nothing else to do */
9468 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9469 NULL);
9470 if (error != NULL)
9471 goto done;
9473 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9474 if (error)
9475 goto done;
9476 if (rebase_in_progress) {
9477 error = got_error(GOT_ERR_REBASING);
9478 goto done;
9481 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9482 if (error)
9483 goto done;
9485 if (edit_in_progress && edit_logmsg_only) {
9486 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9487 "histedit operation is in progress in this "
9488 "work tree and must be continued or aborted "
9489 "before the -m option can be used");
9490 goto done;
9492 if (edit_in_progress && fold_only) {
9493 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9494 "histedit operation is in progress in this "
9495 "work tree and must be continued or aborted "
9496 "before the -f option can be used");
9497 goto done;
9500 if (edit_in_progress && abort_edit) {
9501 error = got_worktree_histedit_continue(&resume_commit_id,
9502 &tmp_branch, &branch, &base_commit_id, &fileindex,
9503 worktree, repo);
9504 if (error)
9505 goto done;
9506 printf("Switching work tree to %s\n",
9507 got_ref_get_symref_target(branch));
9508 error = got_worktree_histedit_abort(worktree, fileindex, repo,
9509 branch, base_commit_id, update_progress, &upa);
9510 if (error)
9511 goto done;
9512 printf("Histedit of %s aborted\n",
9513 got_ref_get_symref_target(branch));
9514 print_update_progress_stats(&upa);
9515 goto done; /* nothing else to do */
9516 } else if (abort_edit) {
9517 error = got_error(GOT_ERR_NOT_HISTEDIT);
9518 goto done;
9521 if (continue_edit) {
9522 char *path;
9524 if (!edit_in_progress) {
9525 error = got_error(GOT_ERR_NOT_HISTEDIT);
9526 goto done;
9529 error = got_worktree_get_histedit_script_path(&path, worktree);
9530 if (error)
9531 goto done;
9533 error = histedit_load_list(&histedit_cmds, path, repo);
9534 free(path);
9535 if (error)
9536 goto done;
9538 error = got_worktree_histedit_continue(&resume_commit_id,
9539 &tmp_branch, &branch, &base_commit_id, &fileindex,
9540 worktree, repo);
9541 if (error)
9542 goto done;
9544 error = got_ref_resolve(&head_commit_id, repo, branch);
9545 if (error)
9546 goto done;
9548 error = got_object_open_as_commit(&commit, repo,
9549 head_commit_id);
9550 if (error)
9551 goto done;
9552 parent_ids = got_object_commit_get_parent_ids(commit);
9553 pid = STAILQ_FIRST(parent_ids);
9554 if (pid == NULL) {
9555 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9556 goto done;
9558 error = collect_commits(&commits, head_commit_id, pid->id,
9559 base_commit_id, got_worktree_get_path_prefix(worktree),
9560 GOT_ERR_HISTEDIT_PATH, repo);
9561 got_object_commit_close(commit);
9562 commit = NULL;
9563 if (error)
9564 goto done;
9565 } else {
9566 if (edit_in_progress) {
9567 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9568 goto done;
9571 error = got_ref_open(&branch, repo,
9572 got_worktree_get_head_ref_name(worktree), 0);
9573 if (error != NULL)
9574 goto done;
9576 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
9577 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
9578 "will not edit commit history of a branch outside "
9579 "the \"refs/heads/\" reference namespace");
9580 goto done;
9583 error = got_ref_resolve(&head_commit_id, repo, branch);
9584 got_ref_close(branch);
9585 branch = NULL;
9586 if (error)
9587 goto done;
9589 error = got_object_open_as_commit(&commit, repo,
9590 head_commit_id);
9591 if (error)
9592 goto done;
9593 parent_ids = got_object_commit_get_parent_ids(commit);
9594 pid = STAILQ_FIRST(parent_ids);
9595 if (pid == NULL) {
9596 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9597 goto done;
9599 error = collect_commits(&commits, head_commit_id, pid->id,
9600 got_worktree_get_base_commit_id(worktree),
9601 got_worktree_get_path_prefix(worktree),
9602 GOT_ERR_HISTEDIT_PATH, repo);
9603 got_object_commit_close(commit);
9604 commit = NULL;
9605 if (error)
9606 goto done;
9608 if (STAILQ_EMPTY(&commits)) {
9609 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9610 goto done;
9613 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
9614 &base_commit_id, &fileindex, worktree, repo);
9615 if (error)
9616 goto done;
9618 if (edit_script_path) {
9619 error = histedit_load_list(&histedit_cmds,
9620 edit_script_path, repo);
9621 if (error) {
9622 got_worktree_histedit_abort(worktree, fileindex,
9623 repo, branch, base_commit_id,
9624 update_progress, &upa);
9625 print_update_progress_stats(&upa);
9626 goto done;
9628 } else {
9629 const char *branch_name;
9630 branch_name = got_ref_get_symref_target(branch);
9631 if (strncmp(branch_name, "refs/heads/", 11) == 0)
9632 branch_name += 11;
9633 error = histedit_edit_script(&histedit_cmds, &commits,
9634 branch_name, edit_logmsg_only, fold_only, repo);
9635 if (error) {
9636 got_worktree_histedit_abort(worktree, fileindex,
9637 repo, branch, base_commit_id,
9638 update_progress, &upa);
9639 print_update_progress_stats(&upa);
9640 goto done;
9645 error = histedit_save_list(&histedit_cmds, worktree,
9646 repo);
9647 if (error) {
9648 got_worktree_histedit_abort(worktree, fileindex,
9649 repo, branch, base_commit_id,
9650 update_progress, &upa);
9651 print_update_progress_stats(&upa);
9652 goto done;
9657 error = histedit_check_script(&histedit_cmds, &commits, repo);
9658 if (error)
9659 goto done;
9661 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9662 if (resume_commit_id) {
9663 if (got_object_id_cmp(hle->commit_id,
9664 resume_commit_id) != 0)
9665 continue;
9667 resume_commit_id = NULL;
9668 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9669 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9670 error = histedit_skip_commit(hle, worktree,
9671 repo);
9672 if (error)
9673 goto done;
9674 } else {
9675 struct got_pathlist_head paths;
9676 int have_changes = 0;
9678 TAILQ_INIT(&paths);
9679 error = got_pathlist_append(&paths, "", NULL);
9680 if (error)
9681 goto done;
9682 error = got_worktree_status(worktree, &paths,
9683 repo, 0, check_local_changes, &have_changes,
9684 check_cancelled, NULL);
9685 got_pathlist_free(&paths);
9686 if (error) {
9687 if (error->code != GOT_ERR_CANCELLED)
9688 goto done;
9689 if (sigint_received || sigpipe_received)
9690 goto done;
9692 if (have_changes) {
9693 error = histedit_commit(NULL, worktree,
9694 fileindex, tmp_branch, hle, repo);
9695 if (error)
9696 goto done;
9697 } else {
9698 error = got_object_open_as_commit(
9699 &commit, repo, hle->commit_id);
9700 if (error)
9701 goto done;
9702 error = show_histedit_progress(commit,
9703 hle, NULL);
9704 got_object_commit_close(commit);
9705 commit = NULL;
9706 if (error)
9707 goto done;
9710 continue;
9713 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9714 error = histedit_skip_commit(hle, worktree, repo);
9715 if (error)
9716 goto done;
9717 continue;
9720 error = got_object_open_as_commit(&commit, repo,
9721 hle->commit_id);
9722 if (error)
9723 goto done;
9724 parent_ids = got_object_commit_get_parent_ids(commit);
9725 pid = STAILQ_FIRST(parent_ids);
9727 error = got_worktree_histedit_merge_files(&merged_paths,
9728 worktree, fileindex, pid->id, hle->commit_id, repo,
9729 update_progress, &upa, check_cancelled, NULL);
9730 if (error)
9731 goto done;
9732 got_object_commit_close(commit);
9733 commit = NULL;
9735 print_update_progress_stats(&upa);
9736 if (upa.conflicts > 0)
9737 rebase_status = GOT_STATUS_CONFLICT;
9739 if (rebase_status == GOT_STATUS_CONFLICT) {
9740 error = show_rebase_merge_conflict(hle->commit_id,
9741 repo);
9742 if (error)
9743 goto done;
9744 got_worktree_rebase_pathlist_free(&merged_paths);
9745 break;
9748 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9749 char *id_str;
9750 error = got_object_id_str(&id_str, hle->commit_id);
9751 if (error)
9752 goto done;
9753 printf("Stopping histedit for amending commit %s\n",
9754 id_str);
9755 free(id_str);
9756 got_worktree_rebase_pathlist_free(&merged_paths);
9757 error = got_worktree_histedit_postpone(worktree,
9758 fileindex);
9759 goto done;
9762 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9763 error = histedit_skip_commit(hle, worktree, repo);
9764 if (error)
9765 goto done;
9766 continue;
9769 error = histedit_commit(&merged_paths, worktree, fileindex,
9770 tmp_branch, hle, repo);
9771 got_worktree_rebase_pathlist_free(&merged_paths);
9772 if (error)
9773 goto done;
9776 if (rebase_status == GOT_STATUS_CONFLICT) {
9777 error = got_worktree_histedit_postpone(worktree, fileindex);
9778 if (error)
9779 goto done;
9780 error = got_error_msg(GOT_ERR_CONFLICTS,
9781 "conflicts must be resolved before histedit can continue");
9782 } else
9783 error = histedit_complete(worktree, fileindex, tmp_branch,
9784 branch, repo);
9785 done:
9786 got_object_id_queue_free(&commits);
9787 histedit_free_list(&histedit_cmds);
9788 free(head_commit_id);
9789 free(base_commit_id);
9790 free(resume_commit_id);
9791 if (commit)
9792 got_object_commit_close(commit);
9793 if (branch)
9794 got_ref_close(branch);
9795 if (tmp_branch)
9796 got_ref_close(tmp_branch);
9797 if (worktree)
9798 got_worktree_close(worktree);
9799 if (repo) {
9800 const struct got_error *close_err = got_repo_close(repo);
9801 if (error == NULL)
9802 error = close_err;
9804 return error;
9807 __dead static void
9808 usage_integrate(void)
9810 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9811 exit(1);
9814 static const struct got_error *
9815 cmd_integrate(int argc, char *argv[])
9817 const struct got_error *error = NULL;
9818 struct got_repository *repo = NULL;
9819 struct got_worktree *worktree = NULL;
9820 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9821 const char *branch_arg = NULL;
9822 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9823 struct got_fileindex *fileindex = NULL;
9824 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9825 int ch;
9826 struct got_update_progress_arg upa;
9828 while ((ch = getopt(argc, argv, "")) != -1) {
9829 switch (ch) {
9830 default:
9831 usage_integrate();
9832 /* NOTREACHED */
9836 argc -= optind;
9837 argv += optind;
9839 if (argc != 1)
9840 usage_integrate();
9841 branch_arg = argv[0];
9842 #ifndef PROFILE
9843 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9844 "unveil", NULL) == -1)
9845 err(1, "pledge");
9846 #endif
9847 cwd = getcwd(NULL, 0);
9848 if (cwd == NULL) {
9849 error = got_error_from_errno("getcwd");
9850 goto done;
9853 error = got_worktree_open(&worktree, cwd);
9854 if (error) {
9855 if (error->code == GOT_ERR_NOT_WORKTREE)
9856 error = wrap_not_worktree_error(error, "integrate",
9857 cwd);
9858 goto done;
9861 error = check_rebase_or_histedit_in_progress(worktree);
9862 if (error)
9863 goto done;
9865 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9866 NULL);
9867 if (error != NULL)
9868 goto done;
9870 error = apply_unveil(got_repo_get_path(repo), 0,
9871 got_worktree_get_root_path(worktree));
9872 if (error)
9873 goto done;
9875 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9876 error = got_error_from_errno("asprintf");
9877 goto done;
9880 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9881 &base_branch_ref, worktree, refname, repo);
9882 if (error)
9883 goto done;
9885 refname = strdup(got_ref_get_name(branch_ref));
9886 if (refname == NULL) {
9887 error = got_error_from_errno("strdup");
9888 got_worktree_integrate_abort(worktree, fileindex, repo,
9889 branch_ref, base_branch_ref);
9890 goto done;
9892 base_refname = strdup(got_ref_get_name(base_branch_ref));
9893 if (base_refname == NULL) {
9894 error = got_error_from_errno("strdup");
9895 got_worktree_integrate_abort(worktree, fileindex, repo,
9896 branch_ref, base_branch_ref);
9897 goto done;
9900 error = got_ref_resolve(&commit_id, repo, branch_ref);
9901 if (error)
9902 goto done;
9904 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9905 if (error)
9906 goto done;
9908 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9909 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9910 "specified branch has already been integrated");
9911 got_worktree_integrate_abort(worktree, fileindex, repo,
9912 branch_ref, base_branch_ref);
9913 goto done;
9916 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9917 if (error) {
9918 if (error->code == GOT_ERR_ANCESTRY)
9919 error = got_error(GOT_ERR_REBASE_REQUIRED);
9920 got_worktree_integrate_abort(worktree, fileindex, repo,
9921 branch_ref, base_branch_ref);
9922 goto done;
9925 memset(&upa, 0, sizeof(upa));
9926 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9927 branch_ref, base_branch_ref, update_progress, &upa,
9928 check_cancelled, NULL);
9929 if (error)
9930 goto done;
9932 printf("Integrated %s into %s\n", refname, base_refname);
9933 print_update_progress_stats(&upa);
9934 done:
9935 if (repo) {
9936 const struct got_error *close_err = got_repo_close(repo);
9937 if (error == NULL)
9938 error = close_err;
9940 if (worktree)
9941 got_worktree_close(worktree);
9942 free(cwd);
9943 free(base_commit_id);
9944 free(commit_id);
9945 free(refname);
9946 free(base_refname);
9947 return error;
9950 __dead static void
9951 usage_stage(void)
9953 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9954 "[-S] [file-path ...]\n",
9955 getprogname());
9956 exit(1);
9959 static const struct got_error *
9960 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9961 const char *path, struct got_object_id *blob_id,
9962 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9963 int dirfd, const char *de_name)
9965 const struct got_error *err = NULL;
9966 char *id_str = NULL;
9968 if (staged_status != GOT_STATUS_ADD &&
9969 staged_status != GOT_STATUS_MODIFY &&
9970 staged_status != GOT_STATUS_DELETE)
9971 return NULL;
9973 if (staged_status == GOT_STATUS_ADD ||
9974 staged_status == GOT_STATUS_MODIFY)
9975 err = got_object_id_str(&id_str, staged_blob_id);
9976 else
9977 err = got_object_id_str(&id_str, blob_id);
9978 if (err)
9979 return err;
9981 printf("%s %c %s\n", id_str, staged_status, path);
9982 free(id_str);
9983 return NULL;
9986 static const struct got_error *
9987 cmd_stage(int argc, char *argv[])
9989 const struct got_error *error = NULL;
9990 struct got_repository *repo = NULL;
9991 struct got_worktree *worktree = NULL;
9992 char *cwd = NULL;
9993 struct got_pathlist_head paths;
9994 struct got_pathlist_entry *pe;
9995 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9996 FILE *patch_script_file = NULL;
9997 const char *patch_script_path = NULL;
9998 struct choose_patch_arg cpa;
10000 TAILQ_INIT(&paths);
10002 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10003 switch (ch) {
10004 case 'l':
10005 list_stage = 1;
10006 break;
10007 case 'p':
10008 pflag = 1;
10009 break;
10010 case 'F':
10011 patch_script_path = optarg;
10012 break;
10013 case 'S':
10014 allow_bad_symlinks = 1;
10015 break;
10016 default:
10017 usage_stage();
10018 /* NOTREACHED */
10022 argc -= optind;
10023 argv += optind;
10025 #ifndef PROFILE
10026 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10027 "unveil", NULL) == -1)
10028 err(1, "pledge");
10029 #endif
10030 if (list_stage && (pflag || patch_script_path))
10031 errx(1, "-l option cannot be used with other options");
10032 if (patch_script_path && !pflag)
10033 errx(1, "-F option can only be used together with -p option");
10035 cwd = getcwd(NULL, 0);
10036 if (cwd == NULL) {
10037 error = got_error_from_errno("getcwd");
10038 goto done;
10041 error = got_worktree_open(&worktree, cwd);
10042 if (error) {
10043 if (error->code == GOT_ERR_NOT_WORKTREE)
10044 error = wrap_not_worktree_error(error, "stage", cwd);
10045 goto done;
10048 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10049 NULL);
10050 if (error != NULL)
10051 goto done;
10053 if (patch_script_path) {
10054 patch_script_file = fopen(patch_script_path, "r");
10055 if (patch_script_file == NULL) {
10056 error = got_error_from_errno2("fopen",
10057 patch_script_path);
10058 goto done;
10061 error = apply_unveil(got_repo_get_path(repo), 0,
10062 got_worktree_get_root_path(worktree));
10063 if (error)
10064 goto done;
10066 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10067 if (error)
10068 goto done;
10070 if (list_stage)
10071 error = got_worktree_status(worktree, &paths, repo, 0,
10072 print_stage, NULL, check_cancelled, NULL);
10073 else {
10074 cpa.patch_script_file = patch_script_file;
10075 cpa.action = "stage";
10076 error = got_worktree_stage(worktree, &paths,
10077 pflag ? NULL : print_status, NULL,
10078 pflag ? choose_patch : NULL, &cpa,
10079 allow_bad_symlinks, repo);
10081 done:
10082 if (patch_script_file && fclose(patch_script_file) == EOF &&
10083 error == NULL)
10084 error = got_error_from_errno2("fclose", patch_script_path);
10085 if (repo) {
10086 const struct got_error *close_err = got_repo_close(repo);
10087 if (error == NULL)
10088 error = close_err;
10090 if (worktree)
10091 got_worktree_close(worktree);
10092 TAILQ_FOREACH(pe, &paths, entry)
10093 free((char *)pe->path);
10094 got_pathlist_free(&paths);
10095 free(cwd);
10096 return error;
10099 __dead static void
10100 usage_unstage(void)
10102 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10103 "[file-path ...]\n",
10104 getprogname());
10105 exit(1);
10109 static const struct got_error *
10110 cmd_unstage(int argc, char *argv[])
10112 const struct got_error *error = NULL;
10113 struct got_repository *repo = NULL;
10114 struct got_worktree *worktree = NULL;
10115 char *cwd = NULL;
10116 struct got_pathlist_head paths;
10117 struct got_pathlist_entry *pe;
10118 int ch, pflag = 0;
10119 struct got_update_progress_arg upa;
10120 FILE *patch_script_file = NULL;
10121 const char *patch_script_path = NULL;
10122 struct choose_patch_arg cpa;
10124 TAILQ_INIT(&paths);
10126 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10127 switch (ch) {
10128 case 'p':
10129 pflag = 1;
10130 break;
10131 case 'F':
10132 patch_script_path = optarg;
10133 break;
10134 default:
10135 usage_unstage();
10136 /* NOTREACHED */
10140 argc -= optind;
10141 argv += optind;
10143 #ifndef PROFILE
10144 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10145 "unveil", NULL) == -1)
10146 err(1, "pledge");
10147 #endif
10148 if (patch_script_path && !pflag)
10149 errx(1, "-F option can only be used together with -p option");
10151 cwd = getcwd(NULL, 0);
10152 if (cwd == NULL) {
10153 error = got_error_from_errno("getcwd");
10154 goto done;
10157 error = got_worktree_open(&worktree, cwd);
10158 if (error) {
10159 if (error->code == GOT_ERR_NOT_WORKTREE)
10160 error = wrap_not_worktree_error(error, "unstage", cwd);
10161 goto done;
10164 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10165 NULL);
10166 if (error != NULL)
10167 goto done;
10169 if (patch_script_path) {
10170 patch_script_file = fopen(patch_script_path, "r");
10171 if (patch_script_file == NULL) {
10172 error = got_error_from_errno2("fopen",
10173 patch_script_path);
10174 goto done;
10178 error = apply_unveil(got_repo_get_path(repo), 0,
10179 got_worktree_get_root_path(worktree));
10180 if (error)
10181 goto done;
10183 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10184 if (error)
10185 goto done;
10187 cpa.patch_script_file = patch_script_file;
10188 cpa.action = "unstage";
10189 memset(&upa, 0, sizeof(upa));
10190 error = got_worktree_unstage(worktree, &paths, update_progress,
10191 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10192 if (!error)
10193 print_update_progress_stats(&upa);
10194 done:
10195 if (patch_script_file && fclose(patch_script_file) == EOF &&
10196 error == NULL)
10197 error = got_error_from_errno2("fclose", patch_script_path);
10198 if (repo) {
10199 const struct got_error *close_err = got_repo_close(repo);
10200 if (error == NULL)
10201 error = close_err;
10203 if (worktree)
10204 got_worktree_close(worktree);
10205 TAILQ_FOREACH(pe, &paths, entry)
10206 free((char *)pe->path);
10207 got_pathlist_free(&paths);
10208 free(cwd);
10209 return error;
10212 __dead static void
10213 usage_cat(void)
10215 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10216 "arg1 [arg2 ...]\n", getprogname());
10217 exit(1);
10220 static const struct got_error *
10221 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10223 const struct got_error *err;
10224 struct got_blob_object *blob;
10226 err = got_object_open_as_blob(&blob, repo, id, 8192);
10227 if (err)
10228 return err;
10230 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10231 got_object_blob_close(blob);
10232 return err;
10235 static const struct got_error *
10236 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10238 const struct got_error *err;
10239 struct got_tree_object *tree;
10240 int nentries, i;
10242 err = got_object_open_as_tree(&tree, repo, id);
10243 if (err)
10244 return err;
10246 nentries = got_object_tree_get_nentries(tree);
10247 for (i = 0; i < nentries; i++) {
10248 struct got_tree_entry *te;
10249 char *id_str;
10250 if (sigint_received || sigpipe_received)
10251 break;
10252 te = got_object_tree_get_entry(tree, i);
10253 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10254 if (err)
10255 break;
10256 fprintf(outfile, "%s %.7o %s\n", id_str,
10257 got_tree_entry_get_mode(te),
10258 got_tree_entry_get_name(te));
10259 free(id_str);
10262 got_object_tree_close(tree);
10263 return err;
10266 static const struct got_error *
10267 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10269 const struct got_error *err;
10270 struct got_commit_object *commit;
10271 const struct got_object_id_queue *parent_ids;
10272 struct got_object_qid *pid;
10273 char *id_str = NULL;
10274 const char *logmsg = NULL;
10276 err = got_object_open_as_commit(&commit, repo, id);
10277 if (err)
10278 return err;
10280 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10281 if (err)
10282 goto done;
10284 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10285 parent_ids = got_object_commit_get_parent_ids(commit);
10286 fprintf(outfile, "numparents %d\n",
10287 got_object_commit_get_nparents(commit));
10288 STAILQ_FOREACH(pid, parent_ids, entry) {
10289 char *pid_str;
10290 err = got_object_id_str(&pid_str, pid->id);
10291 if (err)
10292 goto done;
10293 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10294 free(pid_str);
10296 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10297 got_object_commit_get_author(commit),
10298 (long long)got_object_commit_get_author_time(commit));
10300 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10301 got_object_commit_get_author(commit),
10302 (long long)got_object_commit_get_committer_time(commit));
10304 logmsg = got_object_commit_get_logmsg_raw(commit);
10305 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10306 fprintf(outfile, "%s", logmsg);
10307 done:
10308 free(id_str);
10309 got_object_commit_close(commit);
10310 return err;
10313 static const struct got_error *
10314 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10316 const struct got_error *err;
10317 struct got_tag_object *tag;
10318 char *id_str = NULL;
10319 const char *tagmsg = NULL;
10321 err = got_object_open_as_tag(&tag, repo, id);
10322 if (err)
10323 return err;
10325 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10326 if (err)
10327 goto done;
10329 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10331 switch (got_object_tag_get_object_type(tag)) {
10332 case GOT_OBJ_TYPE_BLOB:
10333 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10334 GOT_OBJ_LABEL_BLOB);
10335 break;
10336 case GOT_OBJ_TYPE_TREE:
10337 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10338 GOT_OBJ_LABEL_TREE);
10339 break;
10340 case GOT_OBJ_TYPE_COMMIT:
10341 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10342 GOT_OBJ_LABEL_COMMIT);
10343 break;
10344 case GOT_OBJ_TYPE_TAG:
10345 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10346 GOT_OBJ_LABEL_TAG);
10347 break;
10348 default:
10349 break;
10352 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10353 got_object_tag_get_name(tag));
10355 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10356 got_object_tag_get_tagger(tag),
10357 (long long)got_object_tag_get_tagger_time(tag));
10359 tagmsg = got_object_tag_get_message(tag);
10360 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10361 fprintf(outfile, "%s", tagmsg);
10362 done:
10363 free(id_str);
10364 got_object_tag_close(tag);
10365 return err;
10368 static const struct got_error *
10369 cmd_cat(int argc, char *argv[])
10371 const struct got_error *error;
10372 struct got_repository *repo = NULL;
10373 struct got_worktree *worktree = NULL;
10374 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10375 const char *commit_id_str = NULL;
10376 struct got_object_id *id = NULL, *commit_id = NULL;
10377 int ch, obj_type, i, force_path = 0;
10378 struct got_reflist_head refs;
10380 TAILQ_INIT(&refs);
10382 #ifndef PROFILE
10383 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10384 NULL) == -1)
10385 err(1, "pledge");
10386 #endif
10388 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10389 switch (ch) {
10390 case 'c':
10391 commit_id_str = optarg;
10392 break;
10393 case 'r':
10394 repo_path = realpath(optarg, NULL);
10395 if (repo_path == NULL)
10396 return got_error_from_errno2("realpath",
10397 optarg);
10398 got_path_strip_trailing_slashes(repo_path);
10399 break;
10400 case 'P':
10401 force_path = 1;
10402 break;
10403 default:
10404 usage_cat();
10405 /* NOTREACHED */
10409 argc -= optind;
10410 argv += optind;
10412 cwd = getcwd(NULL, 0);
10413 if (cwd == NULL) {
10414 error = got_error_from_errno("getcwd");
10415 goto done;
10417 error = got_worktree_open(&worktree, cwd);
10418 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10419 goto done;
10420 if (worktree) {
10421 if (repo_path == NULL) {
10422 repo_path = strdup(
10423 got_worktree_get_repo_path(worktree));
10424 if (repo_path == NULL) {
10425 error = got_error_from_errno("strdup");
10426 goto done;
10431 if (repo_path == NULL) {
10432 repo_path = getcwd(NULL, 0);
10433 if (repo_path == NULL)
10434 return got_error_from_errno("getcwd");
10437 error = got_repo_open(&repo, repo_path, NULL);
10438 free(repo_path);
10439 if (error != NULL)
10440 goto done;
10442 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10443 if (error)
10444 goto done;
10446 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10447 if (error)
10448 goto done;
10450 if (commit_id_str == NULL)
10451 commit_id_str = GOT_REF_HEAD;
10452 error = got_repo_match_object_id(&commit_id, NULL,
10453 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10454 if (error)
10455 goto done;
10457 for (i = 0; i < argc; i++) {
10458 if (force_path) {
10459 error = got_object_id_by_path(&id, repo, commit_id,
10460 argv[i]);
10461 if (error)
10462 break;
10463 } else {
10464 error = got_repo_match_object_id(&id, &label, argv[i],
10465 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10466 repo);
10467 if (error) {
10468 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10469 error->code != GOT_ERR_NOT_REF)
10470 break;
10471 error = got_object_id_by_path(&id, repo,
10472 commit_id, argv[i]);
10473 if (error)
10474 break;
10478 error = got_object_get_type(&obj_type, repo, id);
10479 if (error)
10480 break;
10482 switch (obj_type) {
10483 case GOT_OBJ_TYPE_BLOB:
10484 error = cat_blob(id, repo, stdout);
10485 break;
10486 case GOT_OBJ_TYPE_TREE:
10487 error = cat_tree(id, repo, stdout);
10488 break;
10489 case GOT_OBJ_TYPE_COMMIT:
10490 error = cat_commit(id, repo, stdout);
10491 break;
10492 case GOT_OBJ_TYPE_TAG:
10493 error = cat_tag(id, repo, stdout);
10494 break;
10495 default:
10496 error = got_error(GOT_ERR_OBJ_TYPE);
10497 break;
10499 if (error)
10500 break;
10501 free(label);
10502 label = NULL;
10503 free(id);
10504 id = NULL;
10506 done:
10507 free(label);
10508 free(id);
10509 free(commit_id);
10510 if (worktree)
10511 got_worktree_close(worktree);
10512 if (repo) {
10513 const struct got_error *close_err = got_repo_close(repo);
10514 if (error == NULL)
10515 error = close_err;
10517 got_ref_list_free(&refs);
10518 return error;
10521 __dead static void
10522 usage_info(void)
10524 fprintf(stderr, "usage: %s info [path ...]\n",
10525 getprogname());
10526 exit(1);
10529 static const struct got_error *
10530 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
10531 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10532 struct got_object_id *commit_id)
10534 const struct got_error *err = NULL;
10535 char *id_str = NULL;
10536 char datebuf[128];
10537 struct tm mytm, *tm;
10538 struct got_pathlist_head *paths = arg;
10539 struct got_pathlist_entry *pe;
10542 * Clear error indication from any of the path arguments which
10543 * would cause this file index entry to be displayed.
10545 TAILQ_FOREACH(pe, paths, entry) {
10546 if (got_path_cmp(path, pe->path, strlen(path),
10547 pe->path_len) == 0 ||
10548 got_path_is_child(path, pe->path, pe->path_len))
10549 pe->data = NULL; /* no error */
10552 printf(GOT_COMMIT_SEP_STR);
10553 if (S_ISLNK(mode))
10554 printf("symlink: %s\n", path);
10555 else if (S_ISREG(mode)) {
10556 printf("file: %s\n", path);
10557 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
10558 } else if (S_ISDIR(mode))
10559 printf("directory: %s\n", path);
10560 else
10561 printf("something: %s\n", path);
10563 tm = localtime_r(&mtime, &mytm);
10564 if (tm == NULL)
10565 return NULL;
10566 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
10567 return got_error(GOT_ERR_NO_SPACE);
10568 printf("timestamp: %s\n", datebuf);
10570 if (blob_id) {
10571 err = got_object_id_str(&id_str, blob_id);
10572 if (err)
10573 return err;
10574 printf("based on blob: %s\n", id_str);
10575 free(id_str);
10578 if (staged_blob_id) {
10579 err = got_object_id_str(&id_str, staged_blob_id);
10580 if (err)
10581 return err;
10582 printf("based on staged blob: %s\n", id_str);
10583 free(id_str);
10586 if (commit_id) {
10587 err = got_object_id_str(&id_str, commit_id);
10588 if (err)
10589 return err;
10590 printf("based on commit: %s\n", id_str);
10591 free(id_str);
10594 return NULL;
10597 static const struct got_error *
10598 cmd_info(int argc, char *argv[])
10600 const struct got_error *error = NULL;
10601 struct got_worktree *worktree = NULL;
10602 char *cwd = NULL, *id_str = NULL;
10603 struct got_pathlist_head paths;
10604 struct got_pathlist_entry *pe;
10605 char *uuidstr = NULL;
10606 int ch, show_files = 0;
10608 TAILQ_INIT(&paths);
10610 while ((ch = getopt(argc, argv, "")) != -1) {
10611 switch (ch) {
10612 default:
10613 usage_info();
10614 /* NOTREACHED */
10618 argc -= optind;
10619 argv += optind;
10621 #ifndef PROFILE
10622 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
10623 NULL) == -1)
10624 err(1, "pledge");
10625 #endif
10626 cwd = getcwd(NULL, 0);
10627 if (cwd == NULL) {
10628 error = got_error_from_errno("getcwd");
10629 goto done;
10632 error = got_worktree_open(&worktree, cwd);
10633 if (error) {
10634 if (error->code == GOT_ERR_NOT_WORKTREE)
10635 error = wrap_not_worktree_error(error, "info", cwd);
10636 goto done;
10639 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
10640 if (error)
10641 goto done;
10643 if (argc >= 1) {
10644 error = get_worktree_paths_from_argv(&paths, argc, argv,
10645 worktree);
10646 if (error)
10647 goto done;
10648 show_files = 1;
10651 error = got_object_id_str(&id_str,
10652 got_worktree_get_base_commit_id(worktree));
10653 if (error)
10654 goto done;
10656 error = got_worktree_get_uuid(&uuidstr, worktree);
10657 if (error)
10658 goto done;
10660 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
10661 printf("work tree base commit: %s\n", id_str);
10662 printf("work tree path prefix: %s\n",
10663 got_worktree_get_path_prefix(worktree));
10664 printf("work tree branch reference: %s\n",
10665 got_worktree_get_head_ref_name(worktree));
10666 printf("work tree UUID: %s\n", uuidstr);
10667 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10669 if (show_files) {
10670 struct got_pathlist_entry *pe;
10671 TAILQ_FOREACH(pe, &paths, entry) {
10672 if (pe->path_len == 0)
10673 continue;
10675 * Assume this path will fail. This will be corrected
10676 * in print_path_info() in case the path does suceeed.
10678 pe->data = (void *)got_error_path(pe->path,
10679 GOT_ERR_BAD_PATH);
10681 error = got_worktree_path_info(worktree, &paths,
10682 print_path_info, &paths, check_cancelled, NULL);
10683 if (error)
10684 goto done;
10685 TAILQ_FOREACH(pe, &paths, entry) {
10686 if (pe->data != NULL) {
10687 error = pe->data; /* bad path */
10688 break;
10692 done:
10693 TAILQ_FOREACH(pe, &paths, entry)
10694 free((char *)pe->path);
10695 got_pathlist_free(&paths);
10696 free(cwd);
10697 free(id_str);
10698 free(uuidstr);
10699 return error;