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_id_dup(
3442 got_object_commit_get_tree_id(pcommit));
3443 if (tree_id1 == NULL) {
3444 got_object_commit_close(pcommit);
3445 return got_error_from_errno("got_object_id_dup");
3447 got_object_commit_close(pcommit);
3451 if (tree_id1) {
3452 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3453 if (err)
3454 goto done;
3457 tree_id2 = got_object_commit_get_tree_id(commit);
3458 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3459 if (err)
3460 goto done;
3462 err = got_diff_tree(tree1, tree2, "", "", repo,
3463 got_diff_tree_collect_changed_paths, paths, 0);
3464 done:
3465 if (tree1)
3466 got_object_tree_close(tree1);
3467 if (tree2)
3468 got_object_tree_close(tree2);
3469 free(tree_id1);
3470 return err;
3473 static const struct got_error *
3474 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3475 const char *path, int diff_context, struct got_repository *repo)
3477 const struct got_error *err = NULL;
3478 struct got_commit_object *pcommit = NULL;
3479 char *id_str1 = NULL, *id_str2 = NULL;
3480 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3481 struct got_object_qid *qid;
3483 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3484 if (qid != NULL) {
3485 err = got_object_open_as_commit(&pcommit, repo,
3486 qid->id);
3487 if (err)
3488 return err;
3491 if (path && path[0] != '\0') {
3492 int obj_type;
3493 err = got_object_id_by_path(&obj_id2, repo, id, path);
3494 if (err)
3495 goto done;
3496 err = got_object_id_str(&id_str2, obj_id2);
3497 if (err) {
3498 free(obj_id2);
3499 goto done;
3501 if (pcommit) {
3502 err = got_object_id_by_path(&obj_id1, repo,
3503 qid->id, path);
3504 if (err) {
3505 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3506 free(obj_id2);
3507 goto done;
3509 } else {
3510 err = got_object_id_str(&id_str1, obj_id1);
3511 if (err) {
3512 free(obj_id2);
3513 goto done;
3517 err = got_object_get_type(&obj_type, repo, obj_id2);
3518 if (err) {
3519 free(obj_id2);
3520 goto done;
3522 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3523 switch (obj_type) {
3524 case GOT_OBJ_TYPE_BLOB:
3525 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3526 0, 0, repo);
3527 break;
3528 case GOT_OBJ_TYPE_TREE:
3529 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3530 0, 0, repo);
3531 break;
3532 default:
3533 err = got_error(GOT_ERR_OBJ_TYPE);
3534 break;
3536 free(obj_id1);
3537 free(obj_id2);
3538 } else {
3539 obj_id2 = got_object_commit_get_tree_id(commit);
3540 err = got_object_id_str(&id_str2, obj_id2);
3541 if (err)
3542 goto done;
3543 if (pcommit) {
3544 obj_id1 = got_object_commit_get_tree_id(pcommit);
3545 err = got_object_id_str(&id_str1, obj_id1);
3546 if (err)
3547 goto done;
3549 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3550 id_str2);
3551 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3552 repo);
3554 done:
3555 free(id_str1);
3556 free(id_str2);
3557 if (pcommit)
3558 got_object_commit_close(pcommit);
3559 return err;
3562 static char *
3563 get_datestr(time_t *time, char *datebuf)
3565 struct tm mytm, *tm;
3566 char *p, *s;
3568 tm = gmtime_r(time, &mytm);
3569 if (tm == NULL)
3570 return NULL;
3571 s = asctime_r(tm, datebuf);
3572 if (s == NULL)
3573 return NULL;
3574 p = strchr(s, '\n');
3575 if (p)
3576 *p = '\0';
3577 return s;
3580 static const struct got_error *
3581 match_logmsg(int *have_match, struct got_object_id *id,
3582 struct got_commit_object *commit, regex_t *regex)
3584 const struct got_error *err = NULL;
3585 regmatch_t regmatch;
3586 char *id_str = NULL, *logmsg = NULL;
3588 *have_match = 0;
3590 err = got_object_id_str(&id_str, id);
3591 if (err)
3592 return err;
3594 err = got_object_commit_get_logmsg(&logmsg, commit);
3595 if (err)
3596 goto done;
3598 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3599 *have_match = 1;
3600 done:
3601 free(id_str);
3602 free(logmsg);
3603 return err;
3606 static void
3607 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3608 regex_t *regex)
3610 regmatch_t regmatch;
3611 struct got_pathlist_entry *pe;
3613 *have_match = 0;
3615 TAILQ_FOREACH(pe, changed_paths, entry) {
3616 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3617 *have_match = 1;
3618 break;
3623 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3625 static const struct got_error*
3626 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3627 struct got_object_id *id, struct got_repository *repo)
3629 static const struct got_error *err = NULL;
3630 struct got_reflist_entry *re;
3631 char *s;
3632 const char *name;
3634 *refs_str = NULL;
3636 TAILQ_FOREACH(re, refs, entry) {
3637 struct got_tag_object *tag = NULL;
3638 struct got_object_id *ref_id;
3639 int cmp;
3641 name = got_ref_get_name(re->ref);
3642 if (strcmp(name, GOT_REF_HEAD) == 0)
3643 continue;
3644 if (strncmp(name, "refs/", 5) == 0)
3645 name += 5;
3646 if (strncmp(name, "got/", 4) == 0)
3647 continue;
3648 if (strncmp(name, "heads/", 6) == 0)
3649 name += 6;
3650 if (strncmp(name, "remotes/", 8) == 0) {
3651 name += 8;
3652 s = strstr(name, "/" GOT_REF_HEAD);
3653 if (s != NULL && s[strlen(s)] == '\0')
3654 continue;
3656 err = got_ref_resolve(&ref_id, repo, re->ref);
3657 if (err)
3658 break;
3659 if (strncmp(name, "tags/", 5) == 0) {
3660 err = got_object_open_as_tag(&tag, repo, ref_id);
3661 if (err) {
3662 if (err->code != GOT_ERR_OBJ_TYPE) {
3663 free(ref_id);
3664 break;
3666 /* Ref points at something other than a tag. */
3667 err = NULL;
3668 tag = NULL;
3671 cmp = got_object_id_cmp(tag ?
3672 got_object_tag_get_object_id(tag) : ref_id, id);
3673 free(ref_id);
3674 if (tag)
3675 got_object_tag_close(tag);
3676 if (cmp != 0)
3677 continue;
3678 s = *refs_str;
3679 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3680 s ? ", " : "", name) == -1) {
3681 err = got_error_from_errno("asprintf");
3682 free(s);
3683 *refs_str = NULL;
3684 break;
3686 free(s);
3689 return err;
3692 static const struct got_error *
3693 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3694 struct got_repository *repo, const char *path,
3695 struct got_pathlist_head *changed_paths, int show_patch,
3696 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3697 const char *custom_refs_str)
3699 const struct got_error *err = NULL;
3700 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3701 char datebuf[26];
3702 time_t committer_time;
3703 const char *author, *committer;
3704 char *refs_str = NULL;
3706 err = got_object_id_str(&id_str, id);
3707 if (err)
3708 return err;
3710 if (custom_refs_str == NULL) {
3711 struct got_reflist_head *refs;
3712 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3713 if (refs) {
3714 err = build_refs_str(&refs_str, refs, id, repo);
3715 if (err)
3716 goto done;
3720 printf(GOT_COMMIT_SEP_STR);
3721 if (custom_refs_str)
3722 printf("commit %s (%s)\n", id_str, custom_refs_str);
3723 else
3724 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3725 refs_str ? refs_str : "", refs_str ? ")" : "");
3726 free(id_str);
3727 id_str = NULL;
3728 free(refs_str);
3729 refs_str = NULL;
3730 printf("from: %s\n", got_object_commit_get_author(commit));
3731 committer_time = got_object_commit_get_committer_time(commit);
3732 datestr = get_datestr(&committer_time, datebuf);
3733 if (datestr)
3734 printf("date: %s UTC\n", datestr);
3735 author = got_object_commit_get_author(commit);
3736 committer = got_object_commit_get_committer(commit);
3737 if (strcmp(author, committer) != 0)
3738 printf("via: %s\n", committer);
3739 if (got_object_commit_get_nparents(commit) > 1) {
3740 const struct got_object_id_queue *parent_ids;
3741 struct got_object_qid *qid;
3742 int n = 1;
3743 parent_ids = got_object_commit_get_parent_ids(commit);
3744 STAILQ_FOREACH(qid, parent_ids, entry) {
3745 err = got_object_id_str(&id_str, qid->id);
3746 if (err)
3747 goto done;
3748 printf("parent %d: %s\n", n++, id_str);
3749 free(id_str);
3750 id_str = NULL;
3754 err = got_object_commit_get_logmsg(&logmsg0, commit);
3755 if (err)
3756 goto done;
3758 logmsg = logmsg0;
3759 do {
3760 line = strsep(&logmsg, "\n");
3761 if (line)
3762 printf(" %s\n", line);
3763 } while (line);
3764 free(logmsg0);
3766 if (changed_paths) {
3767 struct got_pathlist_entry *pe;
3768 TAILQ_FOREACH(pe, changed_paths, entry) {
3769 struct got_diff_changed_path *cp = pe->data;
3770 printf(" %c %s\n", cp->status, pe->path);
3772 printf("\n");
3774 if (show_patch) {
3775 err = print_patch(commit, id, path, diff_context, repo);
3776 if (err == 0)
3777 printf("\n");
3780 if (fflush(stdout) != 0 && err == NULL)
3781 err = got_error_from_errno("fflush");
3782 done:
3783 free(id_str);
3784 free(refs_str);
3785 return err;
3788 static const struct got_error *
3789 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3790 struct got_repository *repo, const char *path, int show_changed_paths,
3791 int show_patch, const char *search_pattern, int diff_context, int limit,
3792 int log_branches, int reverse_display_order,
3793 struct got_reflist_object_id_map *refs_idmap)
3795 const struct got_error *err;
3796 struct got_commit_graph *graph;
3797 regex_t regex;
3798 int have_match;
3799 struct got_object_id_queue reversed_commits;
3800 struct got_object_qid *qid;
3801 struct got_commit_object *commit;
3802 struct got_pathlist_head changed_paths;
3803 struct got_pathlist_entry *pe;
3805 STAILQ_INIT(&reversed_commits);
3806 TAILQ_INIT(&changed_paths);
3808 if (search_pattern && regcomp(&regex, search_pattern,
3809 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3810 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3812 err = got_commit_graph_open(&graph, path, !log_branches);
3813 if (err)
3814 return err;
3815 err = got_commit_graph_iter_start(graph, root_id, repo,
3816 check_cancelled, NULL);
3817 if (err)
3818 goto done;
3819 for (;;) {
3820 struct got_object_id *id;
3822 if (sigint_received || sigpipe_received)
3823 break;
3825 err = got_commit_graph_iter_next(&id, graph, repo,
3826 check_cancelled, NULL);
3827 if (err) {
3828 if (err->code == GOT_ERR_ITER_COMPLETED)
3829 err = NULL;
3830 break;
3832 if (id == NULL)
3833 break;
3835 err = got_object_open_as_commit(&commit, repo, id);
3836 if (err)
3837 break;
3839 if (show_changed_paths && !reverse_display_order) {
3840 err = get_changed_paths(&changed_paths, commit, repo);
3841 if (err)
3842 break;
3845 if (search_pattern) {
3846 err = match_logmsg(&have_match, id, commit, &regex);
3847 if (err) {
3848 got_object_commit_close(commit);
3849 break;
3851 if (have_match == 0 && show_changed_paths)
3852 match_changed_paths(&have_match,
3853 &changed_paths, &regex);
3854 if (have_match == 0) {
3855 got_object_commit_close(commit);
3856 TAILQ_FOREACH(pe, &changed_paths, entry) {
3857 free((char *)pe->path);
3858 free(pe->data);
3860 got_pathlist_free(&changed_paths);
3861 continue;
3865 if (reverse_display_order) {
3866 err = got_object_qid_alloc(&qid, id);
3867 if (err)
3868 break;
3869 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3870 got_object_commit_close(commit);
3871 } else {
3872 err = print_commit(commit, id, repo, path,
3873 show_changed_paths ? &changed_paths : NULL,
3874 show_patch, diff_context, refs_idmap, NULL);
3875 got_object_commit_close(commit);
3876 if (err)
3877 break;
3879 if ((limit && --limit == 0) ||
3880 (end_id && got_object_id_cmp(id, end_id) == 0))
3881 break;
3883 TAILQ_FOREACH(pe, &changed_paths, entry) {
3884 free((char *)pe->path);
3885 free(pe->data);
3887 got_pathlist_free(&changed_paths);
3889 if (reverse_display_order) {
3890 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3891 err = got_object_open_as_commit(&commit, repo, qid->id);
3892 if (err)
3893 break;
3894 if (show_changed_paths) {
3895 err = get_changed_paths(&changed_paths,
3896 commit, repo);
3897 if (err)
3898 break;
3900 err = print_commit(commit, qid->id, repo, path,
3901 show_changed_paths ? &changed_paths : NULL,
3902 show_patch, diff_context, refs_idmap, NULL);
3903 got_object_commit_close(commit);
3904 if (err)
3905 break;
3906 TAILQ_FOREACH(pe, &changed_paths, entry) {
3907 free((char *)pe->path);
3908 free(pe->data);
3910 got_pathlist_free(&changed_paths);
3913 done:
3914 while (!STAILQ_EMPTY(&reversed_commits)) {
3915 qid = STAILQ_FIRST(&reversed_commits);
3916 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3917 got_object_qid_free(qid);
3919 TAILQ_FOREACH(pe, &changed_paths, entry) {
3920 free((char *)pe->path);
3921 free(pe->data);
3923 got_pathlist_free(&changed_paths);
3924 if (search_pattern)
3925 regfree(&regex);
3926 got_commit_graph_close(graph);
3927 return err;
3930 __dead static void
3931 usage_log(void)
3933 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3934 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3935 "[-R] [path]\n", getprogname());
3936 exit(1);
3939 static int
3940 get_default_log_limit(void)
3942 const char *got_default_log_limit;
3943 long long n;
3944 const char *errstr;
3946 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3947 if (got_default_log_limit == NULL)
3948 return 0;
3949 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3950 if (errstr != NULL)
3951 return 0;
3952 return n;
3955 static const struct got_error *
3956 cmd_log(int argc, char *argv[])
3958 const struct got_error *error;
3959 struct got_repository *repo = NULL;
3960 struct got_worktree *worktree = NULL;
3961 struct got_object_id *start_id = NULL, *end_id = NULL;
3962 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3963 const char *start_commit = NULL, *end_commit = NULL;
3964 const char *search_pattern = NULL;
3965 int diff_context = -1, ch;
3966 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3967 int reverse_display_order = 0;
3968 const char *errstr;
3969 struct got_reflist_head refs;
3970 struct got_reflist_object_id_map *refs_idmap = NULL;
3972 TAILQ_INIT(&refs);
3974 #ifndef PROFILE
3975 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3976 NULL)
3977 == -1)
3978 err(1, "pledge");
3979 #endif
3981 limit = get_default_log_limit();
3983 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3984 switch (ch) {
3985 case 'p':
3986 show_patch = 1;
3987 break;
3988 case 'P':
3989 show_changed_paths = 1;
3990 break;
3991 case 'c':
3992 start_commit = optarg;
3993 break;
3994 case 'C':
3995 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3996 &errstr);
3997 if (errstr != NULL)
3998 err(1, "-C option %s", errstr);
3999 break;
4000 case 'l':
4001 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4002 if (errstr != NULL)
4003 err(1, "-l option %s", errstr);
4004 break;
4005 case 'b':
4006 log_branches = 1;
4007 break;
4008 case 'r':
4009 repo_path = realpath(optarg, NULL);
4010 if (repo_path == NULL)
4011 return got_error_from_errno2("realpath",
4012 optarg);
4013 got_path_strip_trailing_slashes(repo_path);
4014 break;
4015 case 'R':
4016 reverse_display_order = 1;
4017 break;
4018 case 's':
4019 search_pattern = optarg;
4020 break;
4021 case 'x':
4022 end_commit = optarg;
4023 break;
4024 default:
4025 usage_log();
4026 /* NOTREACHED */
4030 argc -= optind;
4031 argv += optind;
4033 if (diff_context == -1)
4034 diff_context = 3;
4035 else if (!show_patch)
4036 errx(1, "-C requires -p");
4038 cwd = getcwd(NULL, 0);
4039 if (cwd == NULL) {
4040 error = got_error_from_errno("getcwd");
4041 goto done;
4044 if (repo_path == NULL) {
4045 error = got_worktree_open(&worktree, cwd);
4046 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4047 goto done;
4048 error = NULL;
4051 if (argc == 1) {
4052 if (worktree) {
4053 error = got_worktree_resolve_path(&path, worktree,
4054 argv[0]);
4055 if (error)
4056 goto done;
4057 } else {
4058 path = strdup(argv[0]);
4059 if (path == NULL) {
4060 error = got_error_from_errno("strdup");
4061 goto done;
4064 } else if (argc != 0)
4065 usage_log();
4067 if (repo_path == NULL) {
4068 repo_path = worktree ?
4069 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4071 if (repo_path == NULL) {
4072 error = got_error_from_errno("strdup");
4073 goto done;
4076 error = got_repo_open(&repo, repo_path, NULL);
4077 if (error != NULL)
4078 goto done;
4080 error = apply_unveil(got_repo_get_path(repo), 1,
4081 worktree ? got_worktree_get_root_path(worktree) : NULL);
4082 if (error)
4083 goto done;
4085 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4086 if (error)
4087 goto done;
4089 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4090 if (error)
4091 goto done;
4093 if (start_commit == NULL) {
4094 struct got_reference *head_ref;
4095 struct got_commit_object *commit = NULL;
4096 error = got_ref_open(&head_ref, repo,
4097 worktree ? got_worktree_get_head_ref_name(worktree)
4098 : GOT_REF_HEAD, 0);
4099 if (error != NULL)
4100 goto done;
4101 error = got_ref_resolve(&start_id, repo, head_ref);
4102 got_ref_close(head_ref);
4103 if (error != NULL)
4104 goto done;
4105 error = got_object_open_as_commit(&commit, repo,
4106 start_id);
4107 if (error != NULL)
4108 goto done;
4109 got_object_commit_close(commit);
4110 } else {
4111 error = got_repo_match_object_id(&start_id, NULL,
4112 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4113 if (error != NULL)
4114 goto done;
4116 if (end_commit != NULL) {
4117 error = got_repo_match_object_id(&end_id, NULL,
4118 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4119 if (error != NULL)
4120 goto done;
4123 if (worktree) {
4125 * If a path was specified on the command line it was resolved
4126 * to a path in the work tree above. Prepend the work tree's
4127 * path prefix to obtain the corresponding in-repository path.
4129 if (path) {
4130 const char *prefix;
4131 prefix = got_worktree_get_path_prefix(worktree);
4132 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4133 (path[0] != '\0') ? "/" : "", path) == -1) {
4134 error = got_error_from_errno("asprintf");
4135 goto done;
4138 } else
4139 error = got_repo_map_path(&in_repo_path, repo,
4140 path ? path : "");
4141 if (error != NULL)
4142 goto done;
4143 if (in_repo_path) {
4144 free(path);
4145 path = in_repo_path;
4148 error = print_commits(start_id, end_id, repo, path ? path : "",
4149 show_changed_paths, show_patch, search_pattern, diff_context,
4150 limit, log_branches, reverse_display_order, refs_idmap);
4151 done:
4152 free(path);
4153 free(repo_path);
4154 free(cwd);
4155 if (worktree)
4156 got_worktree_close(worktree);
4157 if (repo) {
4158 const struct got_error *close_err = got_repo_close(repo);
4159 if (error == NULL)
4160 error = close_err;
4162 if (refs_idmap)
4163 got_reflist_object_id_map_free(refs_idmap);
4164 got_ref_list_free(&refs);
4165 return error;
4168 __dead static void
4169 usage_diff(void)
4171 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4172 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4173 exit(1);
4176 struct print_diff_arg {
4177 struct got_repository *repo;
4178 struct got_worktree *worktree;
4179 int diff_context;
4180 const char *id_str;
4181 int header_shown;
4182 int diff_staged;
4183 int ignore_whitespace;
4184 int force_text_diff;
4188 * Create a file which contains the target path of a symlink so we can feed
4189 * it as content to the diff engine.
4191 static const struct got_error *
4192 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4193 const char *abspath)
4195 const struct got_error *err = NULL;
4196 char target_path[PATH_MAX];
4197 ssize_t target_len, outlen;
4199 *fd = -1;
4201 if (dirfd != -1) {
4202 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4203 if (target_len == -1)
4204 return got_error_from_errno2("readlinkat", abspath);
4205 } else {
4206 target_len = readlink(abspath, target_path, PATH_MAX);
4207 if (target_len == -1)
4208 return got_error_from_errno2("readlink", abspath);
4211 *fd = got_opentempfd();
4212 if (*fd == -1)
4213 return got_error_from_errno("got_opentempfd");
4215 outlen = write(*fd, target_path, target_len);
4216 if (outlen == -1) {
4217 err = got_error_from_errno("got_opentempfd");
4218 goto done;
4221 if (lseek(*fd, 0, SEEK_SET) == -1) {
4222 err = got_error_from_errno2("lseek", abspath);
4223 goto done;
4225 done:
4226 if (err) {
4227 close(*fd);
4228 *fd = -1;
4230 return err;
4233 static const struct got_error *
4234 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4235 const char *path, struct got_object_id *blob_id,
4236 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4237 int dirfd, const char *de_name)
4239 struct print_diff_arg *a = arg;
4240 const struct got_error *err = NULL;
4241 struct got_blob_object *blob1 = NULL;
4242 int fd = -1;
4243 FILE *f2 = NULL;
4244 char *abspath = NULL, *label1 = NULL;
4245 struct stat sb;
4247 if (a->diff_staged) {
4248 if (staged_status != GOT_STATUS_MODIFY &&
4249 staged_status != GOT_STATUS_ADD &&
4250 staged_status != GOT_STATUS_DELETE)
4251 return NULL;
4252 } else {
4253 if (staged_status == GOT_STATUS_DELETE)
4254 return NULL;
4255 if (status == GOT_STATUS_NONEXISTENT)
4256 return got_error_set_errno(ENOENT, path);
4257 if (status != GOT_STATUS_MODIFY &&
4258 status != GOT_STATUS_ADD &&
4259 status != GOT_STATUS_DELETE &&
4260 status != GOT_STATUS_CONFLICT)
4261 return NULL;
4264 if (!a->header_shown) {
4265 printf("diff %s %s%s\n", a->id_str,
4266 got_worktree_get_root_path(a->worktree),
4267 a->diff_staged ? " (staged changes)" : "");
4268 a->header_shown = 1;
4271 if (a->diff_staged) {
4272 const char *label1 = NULL, *label2 = NULL;
4273 switch (staged_status) {
4274 case GOT_STATUS_MODIFY:
4275 label1 = path;
4276 label2 = path;
4277 break;
4278 case GOT_STATUS_ADD:
4279 label2 = path;
4280 break;
4281 case GOT_STATUS_DELETE:
4282 label1 = path;
4283 break;
4284 default:
4285 return got_error(GOT_ERR_FILE_STATUS);
4287 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4288 staged_blob_id, label1, label2, a->diff_context,
4289 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4292 if (staged_status == GOT_STATUS_ADD ||
4293 staged_status == GOT_STATUS_MODIFY) {
4294 char *id_str;
4295 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4296 8192);
4297 if (err)
4298 goto done;
4299 err = got_object_id_str(&id_str, staged_blob_id);
4300 if (err)
4301 goto done;
4302 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4303 err = got_error_from_errno("asprintf");
4304 free(id_str);
4305 goto done;
4307 free(id_str);
4308 } else if (status != GOT_STATUS_ADD) {
4309 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4310 if (err)
4311 goto done;
4314 if (status != GOT_STATUS_DELETE) {
4315 if (asprintf(&abspath, "%s/%s",
4316 got_worktree_get_root_path(a->worktree), path) == -1) {
4317 err = got_error_from_errno("asprintf");
4318 goto done;
4321 if (dirfd != -1) {
4322 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4323 if (fd == -1) {
4324 if (errno != ELOOP) {
4325 err = got_error_from_errno2("openat",
4326 abspath);
4327 goto done;
4329 err = get_symlink_target_file(&fd, dirfd,
4330 de_name, abspath);
4331 if (err)
4332 goto done;
4334 } else {
4335 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4336 if (fd == -1) {
4337 if (errno != ELOOP) {
4338 err = got_error_from_errno2("open",
4339 abspath);
4340 goto done;
4342 err = get_symlink_target_file(&fd, dirfd,
4343 de_name, abspath);
4344 if (err)
4345 goto done;
4348 if (fstat(fd, &sb) == -1) {
4349 err = got_error_from_errno2("fstat", abspath);
4350 goto done;
4352 f2 = fdopen(fd, "r");
4353 if (f2 == NULL) {
4354 err = got_error_from_errno2("fdopen", abspath);
4355 goto done;
4357 fd = -1;
4358 } else
4359 sb.st_size = 0;
4361 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4362 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4363 done:
4364 if (blob1)
4365 got_object_blob_close(blob1);
4366 if (f2 && fclose(f2) == EOF && err == NULL)
4367 err = got_error_from_errno("fclose");
4368 if (fd != -1 && close(fd) == -1 && err == NULL)
4369 err = got_error_from_errno("close");
4370 free(abspath);
4371 return err;
4374 static const struct got_error *
4375 cmd_diff(int argc, char *argv[])
4377 const struct got_error *error;
4378 struct got_repository *repo = NULL;
4379 struct got_worktree *worktree = NULL;
4380 char *cwd = NULL, *repo_path = NULL;
4381 struct got_object_id *id1 = NULL, *id2 = NULL;
4382 const char *id_str1 = NULL, *id_str2 = NULL;
4383 char *label1 = NULL, *label2 = NULL;
4384 int type1, type2;
4385 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4386 int force_text_diff = 0;
4387 const char *errstr;
4388 char *path = NULL;
4389 struct got_reflist_head refs;
4391 TAILQ_INIT(&refs);
4393 #ifndef PROFILE
4394 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4395 NULL) == -1)
4396 err(1, "pledge");
4397 #endif
4399 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4400 switch (ch) {
4401 case 'a':
4402 force_text_diff = 1;
4403 break;
4404 case 'C':
4405 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4406 &errstr);
4407 if (errstr != NULL)
4408 err(1, "-C option %s", errstr);
4409 break;
4410 case 'r':
4411 repo_path = realpath(optarg, NULL);
4412 if (repo_path == NULL)
4413 return got_error_from_errno2("realpath",
4414 optarg);
4415 got_path_strip_trailing_slashes(repo_path);
4416 break;
4417 case 's':
4418 diff_staged = 1;
4419 break;
4420 case 'w':
4421 ignore_whitespace = 1;
4422 break;
4423 default:
4424 usage_diff();
4425 /* NOTREACHED */
4429 argc -= optind;
4430 argv += optind;
4432 cwd = getcwd(NULL, 0);
4433 if (cwd == NULL) {
4434 error = got_error_from_errno("getcwd");
4435 goto done;
4437 if (argc <= 1) {
4438 if (repo_path)
4439 errx(1,
4440 "-r option can't be used when diffing a work tree");
4441 error = got_worktree_open(&worktree, cwd);
4442 if (error) {
4443 if (error->code == GOT_ERR_NOT_WORKTREE)
4444 error = wrap_not_worktree_error(error, "diff",
4445 cwd);
4446 goto done;
4448 repo_path = strdup(got_worktree_get_repo_path(worktree));
4449 if (repo_path == NULL) {
4450 error = got_error_from_errno("strdup");
4451 goto done;
4453 if (argc == 1) {
4454 error = got_worktree_resolve_path(&path, worktree,
4455 argv[0]);
4456 if (error)
4457 goto done;
4458 } else {
4459 path = strdup("");
4460 if (path == NULL) {
4461 error = got_error_from_errno("strdup");
4462 goto done;
4465 } else if (argc == 2) {
4466 if (diff_staged)
4467 errx(1, "-s option can't be used when diffing "
4468 "objects in repository");
4469 id_str1 = argv[0];
4470 id_str2 = argv[1];
4471 if (repo_path == NULL) {
4472 error = got_worktree_open(&worktree, cwd);
4473 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4474 goto done;
4475 repo_path = strdup(worktree ?
4476 got_worktree_get_repo_path(worktree) : cwd);
4477 if (repo_path == NULL) {
4478 error = got_error_from_errno("strdup");
4479 goto done;
4482 } else
4483 usage_diff();
4485 error = got_repo_open(&repo, repo_path, NULL);
4486 free(repo_path);
4487 if (error != NULL)
4488 goto done;
4490 error = apply_unveil(got_repo_get_path(repo), 1,
4491 worktree ? got_worktree_get_root_path(worktree) : NULL);
4492 if (error)
4493 goto done;
4495 if (argc <= 1) {
4496 struct print_diff_arg arg;
4497 struct got_pathlist_head paths;
4498 char *id_str;
4500 TAILQ_INIT(&paths);
4502 error = got_object_id_str(&id_str,
4503 got_worktree_get_base_commit_id(worktree));
4504 if (error)
4505 goto done;
4506 arg.repo = repo;
4507 arg.worktree = worktree;
4508 arg.diff_context = diff_context;
4509 arg.id_str = id_str;
4510 arg.header_shown = 0;
4511 arg.diff_staged = diff_staged;
4512 arg.ignore_whitespace = ignore_whitespace;
4513 arg.force_text_diff = force_text_diff;
4515 error = got_pathlist_append(&paths, path, NULL);
4516 if (error)
4517 goto done;
4519 error = got_worktree_status(worktree, &paths, repo, 0,
4520 print_diff, &arg, check_cancelled, NULL);
4521 free(id_str);
4522 got_pathlist_free(&paths);
4523 goto done;
4526 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4527 if (error)
4528 return error;
4530 error = got_repo_match_object_id(&id1, &label1, id_str1,
4531 GOT_OBJ_TYPE_ANY, &refs, repo);
4532 if (error)
4533 goto done;
4535 error = got_repo_match_object_id(&id2, &label2, id_str2,
4536 GOT_OBJ_TYPE_ANY, &refs, repo);
4537 if (error)
4538 goto done;
4540 error = got_object_get_type(&type1, repo, id1);
4541 if (error)
4542 goto done;
4544 error = got_object_get_type(&type2, repo, id2);
4545 if (error)
4546 goto done;
4548 if (type1 != type2) {
4549 error = got_error(GOT_ERR_OBJ_TYPE);
4550 goto done;
4553 switch (type1) {
4554 case GOT_OBJ_TYPE_BLOB:
4555 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4556 NULL, NULL, diff_context, ignore_whitespace,
4557 force_text_diff, repo, stdout);
4558 break;
4559 case GOT_OBJ_TYPE_TREE:
4560 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4561 "", "", diff_context, ignore_whitespace, force_text_diff,
4562 repo, stdout);
4563 break;
4564 case GOT_OBJ_TYPE_COMMIT:
4565 printf("diff %s %s\n", label1, label2);
4566 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4567 diff_context, ignore_whitespace, force_text_diff, repo,
4568 stdout);
4569 break;
4570 default:
4571 error = got_error(GOT_ERR_OBJ_TYPE);
4573 done:
4574 free(label1);
4575 free(label2);
4576 free(id1);
4577 free(id2);
4578 free(path);
4579 if (worktree)
4580 got_worktree_close(worktree);
4581 if (repo) {
4582 const struct got_error *close_err = got_repo_close(repo);
4583 if (error == NULL)
4584 error = close_err;
4586 got_ref_list_free(&refs);
4587 return error;
4590 __dead static void
4591 usage_blame(void)
4593 fprintf(stderr,
4594 "usage: %s blame [-c commit] [-r repository-path] path\n",
4595 getprogname());
4596 exit(1);
4599 struct blame_line {
4600 int annotated;
4601 char *id_str;
4602 char *committer;
4603 char datebuf[11]; /* YYYY-MM-DD + NUL */
4606 struct blame_cb_args {
4607 struct blame_line *lines;
4608 int nlines;
4609 int nlines_prec;
4610 int lineno_cur;
4611 off_t *line_offsets;
4612 FILE *f;
4613 struct got_repository *repo;
4616 static const struct got_error *
4617 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4619 const struct got_error *err = NULL;
4620 struct blame_cb_args *a = arg;
4621 struct blame_line *bline;
4622 char *line = NULL;
4623 size_t linesize = 0;
4624 struct got_commit_object *commit = NULL;
4625 off_t offset;
4626 struct tm tm;
4627 time_t committer_time;
4629 if (nlines != a->nlines ||
4630 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4631 return got_error(GOT_ERR_RANGE);
4633 if (sigint_received)
4634 return got_error(GOT_ERR_ITER_COMPLETED);
4636 if (lineno == -1)
4637 return NULL; /* no change in this commit */
4639 /* Annotate this line. */
4640 bline = &a->lines[lineno - 1];
4641 if (bline->annotated)
4642 return NULL;
4643 err = got_object_id_str(&bline->id_str, id);
4644 if (err)
4645 return err;
4647 err = got_object_open_as_commit(&commit, a->repo, id);
4648 if (err)
4649 goto done;
4651 bline->committer = strdup(got_object_commit_get_committer(commit));
4652 if (bline->committer == NULL) {
4653 err = got_error_from_errno("strdup");
4654 goto done;
4657 committer_time = got_object_commit_get_committer_time(commit);
4658 if (localtime_r(&committer_time, &tm) == NULL)
4659 return got_error_from_errno("localtime_r");
4660 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4661 &tm) == 0) {
4662 err = got_error(GOT_ERR_NO_SPACE);
4663 goto done;
4665 bline->annotated = 1;
4667 /* Print lines annotated so far. */
4668 bline = &a->lines[a->lineno_cur - 1];
4669 if (!bline->annotated)
4670 goto done;
4672 offset = a->line_offsets[a->lineno_cur - 1];
4673 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4674 err = got_error_from_errno("fseeko");
4675 goto done;
4678 while (bline->annotated) {
4679 char *smallerthan, *at, *nl, *committer;
4680 size_t len;
4682 if (getline(&line, &linesize, a->f) == -1) {
4683 if (ferror(a->f))
4684 err = got_error_from_errno("getline");
4685 break;
4688 committer = bline->committer;
4689 smallerthan = strchr(committer, '<');
4690 if (smallerthan && smallerthan[1] != '\0')
4691 committer = smallerthan + 1;
4692 at = strchr(committer, '@');
4693 if (at)
4694 *at = '\0';
4695 len = strlen(committer);
4696 if (len >= 9)
4697 committer[8] = '\0';
4699 nl = strchr(line, '\n');
4700 if (nl)
4701 *nl = '\0';
4702 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4703 bline->id_str, bline->datebuf, committer, line);
4705 a->lineno_cur++;
4706 bline = &a->lines[a->lineno_cur - 1];
4708 done:
4709 if (commit)
4710 got_object_commit_close(commit);
4711 free(line);
4712 return err;
4715 static const struct got_error *
4716 cmd_blame(int argc, char *argv[])
4718 const struct got_error *error;
4719 struct got_repository *repo = NULL;
4720 struct got_worktree *worktree = NULL;
4721 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4722 char *link_target = NULL;
4723 struct got_object_id *obj_id = NULL;
4724 struct got_object_id *commit_id = NULL;
4725 struct got_blob_object *blob = NULL;
4726 char *commit_id_str = NULL;
4727 struct blame_cb_args bca;
4728 int ch, obj_type, i;
4729 off_t filesize;
4731 memset(&bca, 0, sizeof(bca));
4733 #ifndef PROFILE
4734 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4735 NULL) == -1)
4736 err(1, "pledge");
4737 #endif
4739 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4740 switch (ch) {
4741 case 'c':
4742 commit_id_str = optarg;
4743 break;
4744 case 'r':
4745 repo_path = realpath(optarg, NULL);
4746 if (repo_path == NULL)
4747 return got_error_from_errno2("realpath",
4748 optarg);
4749 got_path_strip_trailing_slashes(repo_path);
4750 break;
4751 default:
4752 usage_blame();
4753 /* NOTREACHED */
4757 argc -= optind;
4758 argv += optind;
4760 if (argc == 1)
4761 path = argv[0];
4762 else
4763 usage_blame();
4765 cwd = getcwd(NULL, 0);
4766 if (cwd == NULL) {
4767 error = got_error_from_errno("getcwd");
4768 goto done;
4770 if (repo_path == NULL) {
4771 error = got_worktree_open(&worktree, cwd);
4772 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4773 goto done;
4774 else
4775 error = NULL;
4776 if (worktree) {
4777 repo_path =
4778 strdup(got_worktree_get_repo_path(worktree));
4779 if (repo_path == NULL) {
4780 error = got_error_from_errno("strdup");
4781 if (error)
4782 goto done;
4784 } else {
4785 repo_path = strdup(cwd);
4786 if (repo_path == NULL) {
4787 error = got_error_from_errno("strdup");
4788 goto done;
4793 error = got_repo_open(&repo, repo_path, NULL);
4794 if (error != NULL)
4795 goto done;
4797 if (worktree) {
4798 const char *prefix = got_worktree_get_path_prefix(worktree);
4799 char *p;
4801 error = got_worktree_resolve_path(&p, worktree, path);
4802 if (error)
4803 goto done;
4804 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4805 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4806 p) == -1) {
4807 error = got_error_from_errno("asprintf");
4808 free(p);
4809 goto done;
4811 free(p);
4812 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4813 } else {
4814 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4815 if (error)
4816 goto done;
4817 error = got_repo_map_path(&in_repo_path, repo, path);
4819 if (error)
4820 goto done;
4822 if (commit_id_str == NULL) {
4823 struct got_reference *head_ref;
4824 error = got_ref_open(&head_ref, repo, worktree ?
4825 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4826 if (error != NULL)
4827 goto done;
4828 error = got_ref_resolve(&commit_id, repo, head_ref);
4829 got_ref_close(head_ref);
4830 if (error != NULL)
4831 goto done;
4832 } else {
4833 struct got_reflist_head refs;
4834 TAILQ_INIT(&refs);
4835 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4836 NULL);
4837 if (error)
4838 goto done;
4839 error = got_repo_match_object_id(&commit_id, NULL,
4840 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4841 got_ref_list_free(&refs);
4842 if (error)
4843 goto done;
4846 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4847 commit_id, repo);
4848 if (error)
4849 goto done;
4851 error = got_object_id_by_path(&obj_id, repo, commit_id,
4852 link_target ? link_target : in_repo_path);
4853 if (error)
4854 goto done;
4856 error = got_object_get_type(&obj_type, repo, obj_id);
4857 if (error)
4858 goto done;
4860 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4861 error = got_error_path(link_target ? link_target : in_repo_path,
4862 GOT_ERR_OBJ_TYPE);
4863 goto done;
4866 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4867 if (error)
4868 goto done;
4869 bca.f = got_opentemp();
4870 if (bca.f == NULL) {
4871 error = got_error_from_errno("got_opentemp");
4872 goto done;
4874 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4875 &bca.line_offsets, bca.f, blob);
4876 if (error || bca.nlines == 0)
4877 goto done;
4879 /* Don't include \n at EOF in the blame line count. */
4880 if (bca.line_offsets[bca.nlines - 1] == filesize)
4881 bca.nlines--;
4883 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4884 if (bca.lines == NULL) {
4885 error = got_error_from_errno("calloc");
4886 goto done;
4888 bca.lineno_cur = 1;
4889 bca.nlines_prec = 0;
4890 i = bca.nlines;
4891 while (i > 0) {
4892 i /= 10;
4893 bca.nlines_prec++;
4895 bca.repo = repo;
4897 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4898 repo, blame_cb, &bca, check_cancelled, NULL);
4899 done:
4900 free(in_repo_path);
4901 free(link_target);
4902 free(repo_path);
4903 free(cwd);
4904 free(commit_id);
4905 free(obj_id);
4906 if (blob)
4907 got_object_blob_close(blob);
4908 if (worktree)
4909 got_worktree_close(worktree);
4910 if (repo) {
4911 const struct got_error *close_err = got_repo_close(repo);
4912 if (error == NULL)
4913 error = close_err;
4915 if (bca.lines) {
4916 for (i = 0; i < bca.nlines; i++) {
4917 struct blame_line *bline = &bca.lines[i];
4918 free(bline->id_str);
4919 free(bline->committer);
4921 free(bca.lines);
4923 free(bca.line_offsets);
4924 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4925 error = got_error_from_errno("fclose");
4926 return error;
4929 __dead static void
4930 usage_tree(void)
4932 fprintf(stderr,
4933 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4934 getprogname());
4935 exit(1);
4938 static const struct got_error *
4939 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4940 const char *root_path, struct got_repository *repo)
4942 const struct got_error *err = NULL;
4943 int is_root_path = (strcmp(path, root_path) == 0);
4944 const char *modestr = "";
4945 mode_t mode = got_tree_entry_get_mode(te);
4946 char *link_target = NULL;
4948 path += strlen(root_path);
4949 while (path[0] == '/')
4950 path++;
4952 if (got_object_tree_entry_is_submodule(te))
4953 modestr = "$";
4954 else if (S_ISLNK(mode)) {
4955 int i;
4957 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4958 if (err)
4959 return err;
4960 for (i = 0; i < strlen(link_target); i++) {
4961 if (!isprint((unsigned char)link_target[i]))
4962 link_target[i] = '?';
4965 modestr = "@";
4967 else if (S_ISDIR(mode))
4968 modestr = "/";
4969 else if (mode & S_IXUSR)
4970 modestr = "*";
4972 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4973 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4974 link_target ? " -> ": "", link_target ? link_target : "");
4976 free(link_target);
4977 return NULL;
4980 static const struct got_error *
4981 print_tree(const char *path, struct got_object_id *commit_id,
4982 int show_ids, int recurse, const char *root_path,
4983 struct got_repository *repo)
4985 const struct got_error *err = NULL;
4986 struct got_object_id *tree_id = NULL;
4987 struct got_tree_object *tree = NULL;
4988 int nentries, i;
4990 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4991 if (err)
4992 goto done;
4994 err = got_object_open_as_tree(&tree, repo, tree_id);
4995 if (err)
4996 goto done;
4997 nentries = got_object_tree_get_nentries(tree);
4998 for (i = 0; i < nentries; i++) {
4999 struct got_tree_entry *te;
5000 char *id = NULL;
5002 if (sigint_received || sigpipe_received)
5003 break;
5005 te = got_object_tree_get_entry(tree, i);
5006 if (show_ids) {
5007 char *id_str;
5008 err = got_object_id_str(&id_str,
5009 got_tree_entry_get_id(te));
5010 if (err)
5011 goto done;
5012 if (asprintf(&id, "%s ", id_str) == -1) {
5013 err = got_error_from_errno("asprintf");
5014 free(id_str);
5015 goto done;
5017 free(id_str);
5019 err = print_entry(te, id, path, root_path, repo);
5020 free(id);
5021 if (err)
5022 goto done;
5024 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5025 char *child_path;
5026 if (asprintf(&child_path, "%s%s%s", path,
5027 path[0] == '/' && path[1] == '\0' ? "" : "/",
5028 got_tree_entry_get_name(te)) == -1) {
5029 err = got_error_from_errno("asprintf");
5030 goto done;
5032 err = print_tree(child_path, commit_id, show_ids, 1,
5033 root_path, repo);
5034 free(child_path);
5035 if (err)
5036 goto done;
5039 done:
5040 if (tree)
5041 got_object_tree_close(tree);
5042 free(tree_id);
5043 return err;
5046 static const struct got_error *
5047 cmd_tree(int argc, char *argv[])
5049 const struct got_error *error;
5050 struct got_repository *repo = NULL;
5051 struct got_worktree *worktree = NULL;
5052 const char *path, *refname = NULL;
5053 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5054 struct got_object_id *commit_id = NULL;
5055 char *commit_id_str = NULL;
5056 int show_ids = 0, recurse = 0;
5057 int ch;
5059 #ifndef PROFILE
5060 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5061 NULL) == -1)
5062 err(1, "pledge");
5063 #endif
5065 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5066 switch (ch) {
5067 case 'c':
5068 commit_id_str = optarg;
5069 break;
5070 case 'r':
5071 repo_path = realpath(optarg, NULL);
5072 if (repo_path == NULL)
5073 return got_error_from_errno2("realpath",
5074 optarg);
5075 got_path_strip_trailing_slashes(repo_path);
5076 break;
5077 case 'i':
5078 show_ids = 1;
5079 break;
5080 case 'R':
5081 recurse = 1;
5082 break;
5083 default:
5084 usage_tree();
5085 /* NOTREACHED */
5089 argc -= optind;
5090 argv += optind;
5092 if (argc == 1)
5093 path = argv[0];
5094 else if (argc > 1)
5095 usage_tree();
5096 else
5097 path = NULL;
5099 cwd = getcwd(NULL, 0);
5100 if (cwd == NULL) {
5101 error = got_error_from_errno("getcwd");
5102 goto done;
5104 if (repo_path == NULL) {
5105 error = got_worktree_open(&worktree, cwd);
5106 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5107 goto done;
5108 else
5109 error = NULL;
5110 if (worktree) {
5111 repo_path =
5112 strdup(got_worktree_get_repo_path(worktree));
5113 if (repo_path == NULL)
5114 error = got_error_from_errno("strdup");
5115 if (error)
5116 goto done;
5117 } else {
5118 repo_path = strdup(cwd);
5119 if (repo_path == NULL) {
5120 error = got_error_from_errno("strdup");
5121 goto done;
5126 error = got_repo_open(&repo, repo_path, NULL);
5127 if (error != NULL)
5128 goto done;
5130 if (worktree) {
5131 const char *prefix = got_worktree_get_path_prefix(worktree);
5132 char *p;
5134 if (path == NULL)
5135 path = "";
5136 error = got_worktree_resolve_path(&p, worktree, path);
5137 if (error)
5138 goto done;
5139 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5140 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5141 p) == -1) {
5142 error = got_error_from_errno("asprintf");
5143 free(p);
5144 goto done;
5146 free(p);
5147 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5148 if (error)
5149 goto done;
5150 } else {
5151 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5152 if (error)
5153 goto done;
5154 if (path == NULL)
5155 path = "/";
5156 error = got_repo_map_path(&in_repo_path, repo, path);
5157 if (error != NULL)
5158 goto done;
5161 if (commit_id_str == NULL) {
5162 struct got_reference *head_ref;
5163 if (worktree)
5164 refname = got_worktree_get_head_ref_name(worktree);
5165 else
5166 refname = GOT_REF_HEAD;
5167 error = got_ref_open(&head_ref, repo, refname, 0);
5168 if (error != NULL)
5169 goto done;
5170 error = got_ref_resolve(&commit_id, repo, head_ref);
5171 got_ref_close(head_ref);
5172 if (error != NULL)
5173 goto done;
5174 } else {
5175 struct got_reflist_head refs;
5176 TAILQ_INIT(&refs);
5177 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5178 NULL);
5179 if (error)
5180 goto done;
5181 error = got_repo_match_object_id(&commit_id, NULL,
5182 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5183 got_ref_list_free(&refs);
5184 if (error)
5185 goto done;
5188 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5189 in_repo_path, repo);
5190 done:
5191 free(in_repo_path);
5192 free(repo_path);
5193 free(cwd);
5194 free(commit_id);
5195 if (worktree)
5196 got_worktree_close(worktree);
5197 if (repo) {
5198 const struct got_error *close_err = got_repo_close(repo);
5199 if (error == NULL)
5200 error = close_err;
5202 return error;
5205 __dead static void
5206 usage_status(void)
5208 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5209 getprogname());
5210 exit(1);
5213 static const struct got_error *
5214 print_status(void *arg, unsigned char status, unsigned char staged_status,
5215 const char *path, struct got_object_id *blob_id,
5216 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5217 int dirfd, const char *de_name)
5219 if (status == staged_status && (status == GOT_STATUS_DELETE))
5220 status = GOT_STATUS_NO_CHANGE;
5221 if (arg) {
5222 char *status_codes = arg;
5223 size_t ncodes = strlen(status_codes);
5224 int i;
5225 for (i = 0; i < ncodes ; i++) {
5226 if (status == status_codes[i] ||
5227 staged_status == status_codes[i])
5228 break;
5230 if (i == ncodes)
5231 return NULL;
5233 printf("%c%c %s\n", status, staged_status, path);
5234 return NULL;
5237 static const struct got_error *
5238 cmd_status(int argc, char *argv[])
5240 const struct got_error *error = NULL;
5241 struct got_repository *repo = NULL;
5242 struct got_worktree *worktree = NULL;
5243 char *cwd = NULL, *status_codes = NULL;;
5244 struct got_pathlist_head paths;
5245 struct got_pathlist_entry *pe;
5246 int ch, i, no_ignores = 0;
5248 TAILQ_INIT(&paths);
5250 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5251 switch (ch) {
5252 case 'I':
5253 no_ignores = 1;
5254 break;
5255 case 's':
5256 for (i = 0; i < strlen(optarg); i++) {
5257 switch (optarg[i]) {
5258 case GOT_STATUS_MODIFY:
5259 case GOT_STATUS_ADD:
5260 case GOT_STATUS_DELETE:
5261 case GOT_STATUS_CONFLICT:
5262 case GOT_STATUS_MISSING:
5263 case GOT_STATUS_OBSTRUCTED:
5264 case GOT_STATUS_UNVERSIONED:
5265 case GOT_STATUS_MODE_CHANGE:
5266 case GOT_STATUS_NONEXISTENT:
5267 break;
5268 default:
5269 errx(1, "invalid status code '%c'",
5270 optarg[i]);
5273 status_codes = optarg;
5274 break;
5275 default:
5276 usage_status();
5277 /* NOTREACHED */
5281 argc -= optind;
5282 argv += optind;
5284 #ifndef PROFILE
5285 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5286 NULL) == -1)
5287 err(1, "pledge");
5288 #endif
5289 cwd = getcwd(NULL, 0);
5290 if (cwd == NULL) {
5291 error = got_error_from_errno("getcwd");
5292 goto done;
5295 error = got_worktree_open(&worktree, cwd);
5296 if (error) {
5297 if (error->code == GOT_ERR_NOT_WORKTREE)
5298 error = wrap_not_worktree_error(error, "status", cwd);
5299 goto done;
5302 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5303 NULL);
5304 if (error != NULL)
5305 goto done;
5307 error = apply_unveil(got_repo_get_path(repo), 1,
5308 got_worktree_get_root_path(worktree));
5309 if (error)
5310 goto done;
5312 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5313 if (error)
5314 goto done;
5316 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5317 print_status, status_codes, check_cancelled, NULL);
5318 done:
5319 TAILQ_FOREACH(pe, &paths, entry)
5320 free((char *)pe->path);
5321 got_pathlist_free(&paths);
5322 free(cwd);
5323 return error;
5326 __dead static void
5327 usage_ref(void)
5329 fprintf(stderr,
5330 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5331 "[-d] [name]\n",
5332 getprogname());
5333 exit(1);
5336 static const struct got_error *
5337 list_refs(struct got_repository *repo, const char *refname)
5339 static const struct got_error *err = NULL;
5340 struct got_reflist_head refs;
5341 struct got_reflist_entry *re;
5343 TAILQ_INIT(&refs);
5344 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5345 if (err)
5346 return err;
5348 TAILQ_FOREACH(re, &refs, entry) {
5349 char *refstr;
5350 refstr = got_ref_to_str(re->ref);
5351 if (refstr == NULL)
5352 return got_error_from_errno("got_ref_to_str");
5353 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5354 free(refstr);
5357 got_ref_list_free(&refs);
5358 return NULL;
5361 static const struct got_error *
5362 delete_ref_by_name(struct got_repository *repo, const char *refname)
5364 const struct got_error *err;
5365 struct got_reference *ref;
5367 err = got_ref_open(&ref, repo, refname, 0);
5368 if (err)
5369 return err;
5371 err = delete_ref(repo, ref);
5372 got_ref_close(ref);
5373 return err;
5376 static const struct got_error *
5377 add_ref(struct got_repository *repo, const char *refname, const char *target)
5379 const struct got_error *err = NULL;
5380 struct got_object_id *id;
5381 struct got_reference *ref = NULL;
5384 * Don't let the user create a reference name with a leading '-'.
5385 * While technically a valid reference name, this case is usually
5386 * an unintended typo.
5388 if (refname[0] == '-')
5389 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5391 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5392 repo);
5393 if (err) {
5394 struct got_reference *target_ref;
5396 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5397 return err;
5398 err = got_ref_open(&target_ref, repo, target, 0);
5399 if (err)
5400 return err;
5401 err = got_ref_resolve(&id, repo, target_ref);
5402 got_ref_close(target_ref);
5403 if (err)
5404 return err;
5407 err = got_ref_alloc(&ref, refname, id);
5408 if (err)
5409 goto done;
5411 err = got_ref_write(ref, repo);
5412 done:
5413 if (ref)
5414 got_ref_close(ref);
5415 free(id);
5416 return err;
5419 static const struct got_error *
5420 add_symref(struct got_repository *repo, const char *refname, const char *target)
5422 const struct got_error *err = NULL;
5423 struct got_reference *ref = NULL;
5424 struct got_reference *target_ref = NULL;
5427 * Don't let the user create a reference name with a leading '-'.
5428 * While technically a valid reference name, this case is usually
5429 * an unintended typo.
5431 if (refname[0] == '-')
5432 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5434 err = got_ref_open(&target_ref, repo, target, 0);
5435 if (err)
5436 return err;
5438 err = got_ref_alloc_symref(&ref, refname, target_ref);
5439 if (err)
5440 goto done;
5442 err = got_ref_write(ref, repo);
5443 done:
5444 if (target_ref)
5445 got_ref_close(target_ref);
5446 if (ref)
5447 got_ref_close(ref);
5448 return err;
5451 static const struct got_error *
5452 cmd_ref(int argc, char *argv[])
5454 const struct got_error *error = NULL;
5455 struct got_repository *repo = NULL;
5456 struct got_worktree *worktree = NULL;
5457 char *cwd = NULL, *repo_path = NULL;
5458 int ch, do_list = 0, do_delete = 0;
5459 const char *obj_arg = NULL, *symref_target= NULL;
5460 char *refname = NULL;
5462 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5463 switch (ch) {
5464 case 'c':
5465 obj_arg = optarg;
5466 break;
5467 case 'd':
5468 do_delete = 1;
5469 break;
5470 case 'r':
5471 repo_path = realpath(optarg, NULL);
5472 if (repo_path == NULL)
5473 return got_error_from_errno2("realpath",
5474 optarg);
5475 got_path_strip_trailing_slashes(repo_path);
5476 break;
5477 case 'l':
5478 do_list = 1;
5479 break;
5480 case 's':
5481 symref_target = optarg;
5482 break;
5483 default:
5484 usage_ref();
5485 /* NOTREACHED */
5489 if (obj_arg && do_list)
5490 option_conflict('c', 'l');
5491 if (obj_arg && do_delete)
5492 option_conflict('c', 'd');
5493 if (obj_arg && symref_target)
5494 option_conflict('c', 's');
5495 if (symref_target && do_delete)
5496 option_conflict('s', 'd');
5497 if (symref_target && do_list)
5498 option_conflict('s', 'l');
5499 if (do_delete && do_list)
5500 option_conflict('d', 'l');
5502 argc -= optind;
5503 argv += optind;
5505 if (do_list) {
5506 if (argc != 0 && argc != 1)
5507 usage_ref();
5508 if (argc == 1) {
5509 refname = strdup(argv[0]);
5510 if (refname == NULL) {
5511 error = got_error_from_errno("strdup");
5512 goto done;
5515 } else {
5516 if (argc != 1)
5517 usage_ref();
5518 refname = strdup(argv[0]);
5519 if (refname == NULL) {
5520 error = got_error_from_errno("strdup");
5521 goto done;
5525 if (refname)
5526 got_path_strip_trailing_slashes(refname);
5528 #ifndef PROFILE
5529 if (do_list) {
5530 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5531 NULL) == -1)
5532 err(1, "pledge");
5533 } else {
5534 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5535 "sendfd unveil", NULL) == -1)
5536 err(1, "pledge");
5538 #endif
5539 cwd = getcwd(NULL, 0);
5540 if (cwd == NULL) {
5541 error = got_error_from_errno("getcwd");
5542 goto done;
5545 if (repo_path == NULL) {
5546 error = got_worktree_open(&worktree, cwd);
5547 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5548 goto done;
5549 else
5550 error = NULL;
5551 if (worktree) {
5552 repo_path =
5553 strdup(got_worktree_get_repo_path(worktree));
5554 if (repo_path == NULL)
5555 error = got_error_from_errno("strdup");
5556 if (error)
5557 goto done;
5558 } else {
5559 repo_path = strdup(cwd);
5560 if (repo_path == NULL) {
5561 error = got_error_from_errno("strdup");
5562 goto done;
5567 error = got_repo_open(&repo, repo_path, NULL);
5568 if (error != NULL)
5569 goto done;
5571 error = apply_unveil(got_repo_get_path(repo), do_list,
5572 worktree ? got_worktree_get_root_path(worktree) : NULL);
5573 if (error)
5574 goto done;
5576 if (do_list)
5577 error = list_refs(repo, refname);
5578 else if (do_delete)
5579 error = delete_ref_by_name(repo, refname);
5580 else if (symref_target)
5581 error = add_symref(repo, refname, symref_target);
5582 else {
5583 if (obj_arg == NULL)
5584 usage_ref();
5585 error = add_ref(repo, refname, obj_arg);
5587 done:
5588 free(refname);
5589 if (repo) {
5590 const struct got_error *close_err = got_repo_close(repo);
5591 if (error == NULL)
5592 error = close_err;
5594 if (worktree)
5595 got_worktree_close(worktree);
5596 free(cwd);
5597 free(repo_path);
5598 return error;
5601 __dead static void
5602 usage_branch(void)
5604 fprintf(stderr,
5605 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5606 "[name]\n", getprogname());
5607 exit(1);
5610 static const struct got_error *
5611 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5612 struct got_reference *ref)
5614 const struct got_error *err = NULL;
5615 const char *refname, *marker = " ";
5616 char *refstr;
5618 refname = got_ref_get_name(ref);
5619 if (worktree && strcmp(refname,
5620 got_worktree_get_head_ref_name(worktree)) == 0) {
5621 struct got_object_id *id = NULL;
5623 err = got_ref_resolve(&id, repo, ref);
5624 if (err)
5625 return err;
5626 if (got_object_id_cmp(id,
5627 got_worktree_get_base_commit_id(worktree)) == 0)
5628 marker = "* ";
5629 else
5630 marker = "~ ";
5631 free(id);
5634 if (strncmp(refname, "refs/heads/", 11) == 0)
5635 refname += 11;
5636 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5637 refname += 18;
5638 if (strncmp(refname, "refs/remotes/", 13) == 0)
5639 refname += 13;
5641 refstr = got_ref_to_str(ref);
5642 if (refstr == NULL)
5643 return got_error_from_errno("got_ref_to_str");
5645 printf("%s%s: %s\n", marker, refname, refstr);
5646 free(refstr);
5647 return NULL;
5650 static const struct got_error *
5651 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5653 const char *refname;
5655 if (worktree == NULL)
5656 return got_error(GOT_ERR_NOT_WORKTREE);
5658 refname = got_worktree_get_head_ref_name(worktree);
5660 if (strncmp(refname, "refs/heads/", 11) == 0)
5661 refname += 11;
5662 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5663 refname += 18;
5665 printf("%s\n", refname);
5667 return NULL;
5670 static const struct got_error *
5671 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5673 static const struct got_error *err = NULL;
5674 struct got_reflist_head refs;
5675 struct got_reflist_entry *re;
5676 struct got_reference *temp_ref = NULL;
5677 int rebase_in_progress, histedit_in_progress;
5679 TAILQ_INIT(&refs);
5681 if (worktree) {
5682 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5683 worktree);
5684 if (err)
5685 return err;
5687 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5688 worktree);
5689 if (err)
5690 return err;
5692 if (rebase_in_progress || histedit_in_progress) {
5693 err = got_ref_open(&temp_ref, repo,
5694 got_worktree_get_head_ref_name(worktree), 0);
5695 if (err)
5696 return err;
5697 list_branch(repo, worktree, temp_ref);
5698 got_ref_close(temp_ref);
5702 err = got_ref_list(&refs, repo, "refs/heads",
5703 got_ref_cmp_by_name, NULL);
5704 if (err)
5705 return err;
5707 TAILQ_FOREACH(re, &refs, entry)
5708 list_branch(repo, worktree, re->ref);
5710 got_ref_list_free(&refs);
5712 err = got_ref_list(&refs, repo, "refs/remotes",
5713 got_ref_cmp_by_name, NULL);
5714 if (err)
5715 return err;
5717 TAILQ_FOREACH(re, &refs, entry)
5718 list_branch(repo, worktree, re->ref);
5720 got_ref_list_free(&refs);
5722 return NULL;
5725 static const struct got_error *
5726 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5727 const char *branch_name)
5729 const struct got_error *err = NULL;
5730 struct got_reference *ref = NULL;
5731 char *refname;
5733 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5734 return got_error_from_errno("asprintf");
5736 err = got_ref_open(&ref, repo, refname, 0);
5737 if (err)
5738 goto done;
5740 if (worktree &&
5741 strcmp(got_worktree_get_head_ref_name(worktree),
5742 got_ref_get_name(ref)) == 0) {
5743 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5744 "will not delete this work tree's current branch");
5745 goto done;
5748 err = got_ref_delete(ref, repo);
5749 done:
5750 if (ref)
5751 got_ref_close(ref);
5752 free(refname);
5753 return err;
5756 static const struct got_error *
5757 add_branch(struct got_repository *repo, const char *branch_name,
5758 struct got_object_id *base_commit_id)
5760 const struct got_error *err = NULL;
5761 struct got_reference *ref = NULL;
5762 char *base_refname = NULL, *refname = NULL;
5765 * Don't let the user create a branch name with a leading '-'.
5766 * While technically a valid reference name, this case is usually
5767 * an unintended typo.
5769 if (branch_name[0] == '-')
5770 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5772 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5773 err = got_error_from_errno("asprintf");
5774 goto done;
5777 err = got_ref_open(&ref, repo, refname, 0);
5778 if (err == NULL) {
5779 err = got_error(GOT_ERR_BRANCH_EXISTS);
5780 goto done;
5781 } else if (err->code != GOT_ERR_NOT_REF)
5782 goto done;
5784 err = got_ref_alloc(&ref, refname, base_commit_id);
5785 if (err)
5786 goto done;
5788 err = got_ref_write(ref, repo);
5789 done:
5790 if (ref)
5791 got_ref_close(ref);
5792 free(base_refname);
5793 free(refname);
5794 return err;
5797 static const struct got_error *
5798 cmd_branch(int argc, char *argv[])
5800 const struct got_error *error = NULL;
5801 struct got_repository *repo = NULL;
5802 struct got_worktree *worktree = NULL;
5803 char *cwd = NULL, *repo_path = NULL;
5804 int ch, do_list = 0, do_show = 0, do_update = 1;
5805 const char *delref = NULL, *commit_id_arg = NULL;
5806 struct got_reference *ref = NULL;
5807 struct got_pathlist_head paths;
5808 struct got_pathlist_entry *pe;
5809 struct got_object_id *commit_id = NULL;
5810 char *commit_id_str = NULL;
5812 TAILQ_INIT(&paths);
5814 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5815 switch (ch) {
5816 case 'c':
5817 commit_id_arg = optarg;
5818 break;
5819 case 'd':
5820 delref = optarg;
5821 break;
5822 case 'r':
5823 repo_path = realpath(optarg, NULL);
5824 if (repo_path == NULL)
5825 return got_error_from_errno2("realpath",
5826 optarg);
5827 got_path_strip_trailing_slashes(repo_path);
5828 break;
5829 case 'l':
5830 do_list = 1;
5831 break;
5832 case 'n':
5833 do_update = 0;
5834 break;
5835 default:
5836 usage_branch();
5837 /* NOTREACHED */
5841 if (do_list && delref)
5842 option_conflict('l', 'd');
5844 argc -= optind;
5845 argv += optind;
5847 if (!do_list && !delref && argc == 0)
5848 do_show = 1;
5850 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5851 errx(1, "-c option can only be used when creating a branch");
5853 if (do_list || delref) {
5854 if (argc > 0)
5855 usage_branch();
5856 } else if (!do_show && argc != 1)
5857 usage_branch();
5859 #ifndef PROFILE
5860 if (do_list || do_show) {
5861 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5862 NULL) == -1)
5863 err(1, "pledge");
5864 } else {
5865 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5866 "sendfd unveil", NULL) == -1)
5867 err(1, "pledge");
5869 #endif
5870 cwd = getcwd(NULL, 0);
5871 if (cwd == NULL) {
5872 error = got_error_from_errno("getcwd");
5873 goto done;
5876 if (repo_path == NULL) {
5877 error = got_worktree_open(&worktree, cwd);
5878 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5879 goto done;
5880 else
5881 error = NULL;
5882 if (worktree) {
5883 repo_path =
5884 strdup(got_worktree_get_repo_path(worktree));
5885 if (repo_path == NULL)
5886 error = got_error_from_errno("strdup");
5887 if (error)
5888 goto done;
5889 } else {
5890 repo_path = strdup(cwd);
5891 if (repo_path == NULL) {
5892 error = got_error_from_errno("strdup");
5893 goto done;
5898 error = got_repo_open(&repo, repo_path, NULL);
5899 if (error != NULL)
5900 goto done;
5902 error = apply_unveil(got_repo_get_path(repo), do_list,
5903 worktree ? got_worktree_get_root_path(worktree) : NULL);
5904 if (error)
5905 goto done;
5907 if (do_show)
5908 error = show_current_branch(repo, worktree);
5909 else if (do_list)
5910 error = list_branches(repo, worktree);
5911 else if (delref)
5912 error = delete_branch(repo, worktree, delref);
5913 else {
5914 struct got_reflist_head refs;
5915 TAILQ_INIT(&refs);
5916 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5917 NULL);
5918 if (error)
5919 goto done;
5920 if (commit_id_arg == NULL)
5921 commit_id_arg = worktree ?
5922 got_worktree_get_head_ref_name(worktree) :
5923 GOT_REF_HEAD;
5924 error = got_repo_match_object_id(&commit_id, NULL,
5925 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5926 got_ref_list_free(&refs);
5927 if (error)
5928 goto done;
5929 error = add_branch(repo, argv[0], commit_id);
5930 if (error)
5931 goto done;
5932 if (worktree && do_update) {
5933 struct got_update_progress_arg upa;
5934 char *branch_refname = NULL;
5936 error = got_object_id_str(&commit_id_str, commit_id);
5937 if (error)
5938 goto done;
5939 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5940 worktree);
5941 if (error)
5942 goto done;
5943 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5944 == -1) {
5945 error = got_error_from_errno("asprintf");
5946 goto done;
5948 error = got_ref_open(&ref, repo, branch_refname, 0);
5949 free(branch_refname);
5950 if (error)
5951 goto done;
5952 error = switch_head_ref(ref, commit_id, worktree,
5953 repo);
5954 if (error)
5955 goto done;
5956 error = got_worktree_set_base_commit_id(worktree, repo,
5957 commit_id);
5958 if (error)
5959 goto done;
5960 memset(&upa, 0, sizeof(upa));
5961 error = got_worktree_checkout_files(worktree, &paths,
5962 repo, update_progress, &upa, check_cancelled,
5963 NULL);
5964 if (error)
5965 goto done;
5966 if (upa.did_something)
5967 printf("Updated to commit %s\n", commit_id_str);
5968 print_update_progress_stats(&upa);
5971 done:
5972 if (ref)
5973 got_ref_close(ref);
5974 if (repo) {
5975 const struct got_error *close_err = got_repo_close(repo);
5976 if (error == NULL)
5977 error = close_err;
5979 if (worktree)
5980 got_worktree_close(worktree);
5981 free(cwd);
5982 free(repo_path);
5983 free(commit_id);
5984 free(commit_id_str);
5985 TAILQ_FOREACH(pe, &paths, entry)
5986 free((char *)pe->path);
5987 got_pathlist_free(&paths);
5988 return error;
5992 __dead static void
5993 usage_tag(void)
5995 fprintf(stderr,
5996 "usage: %s tag [-c commit] [-r repository] [-l] "
5997 "[-m message] name\n", getprogname());
5998 exit(1);
6001 #if 0
6002 static const struct got_error *
6003 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6005 const struct got_error *err = NULL;
6006 struct got_reflist_entry *re, *se, *new;
6007 struct got_object_id *re_id, *se_id;
6008 struct got_tag_object *re_tag, *se_tag;
6009 time_t re_time, se_time;
6011 STAILQ_FOREACH(re, tags, entry) {
6012 se = STAILQ_FIRST(sorted);
6013 if (se == NULL) {
6014 err = got_reflist_entry_dup(&new, re);
6015 if (err)
6016 return err;
6017 STAILQ_INSERT_HEAD(sorted, new, entry);
6018 continue;
6019 } else {
6020 err = got_ref_resolve(&re_id, repo, re->ref);
6021 if (err)
6022 break;
6023 err = got_object_open_as_tag(&re_tag, repo, re_id);
6024 free(re_id);
6025 if (err)
6026 break;
6027 re_time = got_object_tag_get_tagger_time(re_tag);
6028 got_object_tag_close(re_tag);
6031 while (se) {
6032 err = got_ref_resolve(&se_id, repo, re->ref);
6033 if (err)
6034 break;
6035 err = got_object_open_as_tag(&se_tag, repo, se_id);
6036 free(se_id);
6037 if (err)
6038 break;
6039 se_time = got_object_tag_get_tagger_time(se_tag);
6040 got_object_tag_close(se_tag);
6042 if (se_time > re_time) {
6043 err = got_reflist_entry_dup(&new, re);
6044 if (err)
6045 return err;
6046 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6047 break;
6049 se = STAILQ_NEXT(se, entry);
6050 continue;
6053 done:
6054 return err;
6056 #endif
6058 static const struct got_error *
6059 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6061 static const struct got_error *err = NULL;
6062 struct got_reflist_head refs;
6063 struct got_reflist_entry *re;
6065 TAILQ_INIT(&refs);
6067 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6068 if (err)
6069 return err;
6071 TAILQ_FOREACH(re, &refs, entry) {
6072 const char *refname;
6073 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6074 char datebuf[26];
6075 const char *tagger;
6076 time_t tagger_time;
6077 struct got_object_id *id;
6078 struct got_tag_object *tag;
6079 struct got_commit_object *commit = NULL;
6081 refname = got_ref_get_name(re->ref);
6082 if (strncmp(refname, "refs/tags/", 10) != 0)
6083 continue;
6084 refname += 10;
6085 refstr = got_ref_to_str(re->ref);
6086 if (refstr == NULL) {
6087 err = got_error_from_errno("got_ref_to_str");
6088 break;
6090 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6091 free(refstr);
6093 err = got_ref_resolve(&id, repo, re->ref);
6094 if (err)
6095 break;
6096 err = got_object_open_as_tag(&tag, repo, id);
6097 if (err) {
6098 if (err->code != GOT_ERR_OBJ_TYPE) {
6099 free(id);
6100 break;
6102 /* "lightweight" tag */
6103 err = got_object_open_as_commit(&commit, repo, id);
6104 if (err) {
6105 free(id);
6106 break;
6108 tagger = got_object_commit_get_committer(commit);
6109 tagger_time =
6110 got_object_commit_get_committer_time(commit);
6111 err = got_object_id_str(&id_str, id);
6112 free(id);
6113 if (err)
6114 break;
6115 } else {
6116 free(id);
6117 tagger = got_object_tag_get_tagger(tag);
6118 tagger_time = got_object_tag_get_tagger_time(tag);
6119 err = got_object_id_str(&id_str,
6120 got_object_tag_get_object_id(tag));
6121 if (err)
6122 break;
6124 printf("from: %s\n", tagger);
6125 datestr = get_datestr(&tagger_time, datebuf);
6126 if (datestr)
6127 printf("date: %s UTC\n", datestr);
6128 if (commit)
6129 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6130 else {
6131 switch (got_object_tag_get_object_type(tag)) {
6132 case GOT_OBJ_TYPE_BLOB:
6133 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6134 id_str);
6135 break;
6136 case GOT_OBJ_TYPE_TREE:
6137 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6138 id_str);
6139 break;
6140 case GOT_OBJ_TYPE_COMMIT:
6141 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6142 id_str);
6143 break;
6144 case GOT_OBJ_TYPE_TAG:
6145 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6146 id_str);
6147 break;
6148 default:
6149 break;
6152 free(id_str);
6153 if (commit) {
6154 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6155 if (err)
6156 break;
6157 got_object_commit_close(commit);
6158 } else {
6159 tagmsg0 = strdup(got_object_tag_get_message(tag));
6160 got_object_tag_close(tag);
6161 if (tagmsg0 == NULL) {
6162 err = got_error_from_errno("strdup");
6163 break;
6167 tagmsg = tagmsg0;
6168 do {
6169 line = strsep(&tagmsg, "\n");
6170 if (line)
6171 printf(" %s\n", line);
6172 } while (line);
6173 free(tagmsg0);
6176 got_ref_list_free(&refs);
6177 return NULL;
6180 static const struct got_error *
6181 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6182 const char *tag_name, const char *repo_path)
6184 const struct got_error *err = NULL;
6185 char *template = NULL, *initial_content = NULL;
6186 char *editor = NULL;
6187 int initial_content_len;
6188 int fd = -1;
6190 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6191 err = got_error_from_errno("asprintf");
6192 goto done;
6195 initial_content_len = asprintf(&initial_content,
6196 "\n# tagging commit %s as %s\n",
6197 commit_id_str, tag_name);
6198 if (initial_content_len == -1) {
6199 err = got_error_from_errno("asprintf");
6200 goto done;
6203 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6204 if (err)
6205 goto done;
6207 if (write(fd, initial_content, initial_content_len) == -1) {
6208 err = got_error_from_errno2("write", *tagmsg_path);
6209 goto done;
6212 err = get_editor(&editor);
6213 if (err)
6214 goto done;
6215 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6216 initial_content_len, 1);
6217 done:
6218 free(initial_content);
6219 free(template);
6220 free(editor);
6222 if (fd != -1 && close(fd) == -1 && err == NULL)
6223 err = got_error_from_errno2("close", *tagmsg_path);
6225 /* Editor is done; we can now apply unveil(2) */
6226 if (err == NULL)
6227 err = apply_unveil(repo_path, 0, NULL);
6228 if (err) {
6229 free(*tagmsg);
6230 *tagmsg = NULL;
6232 return err;
6235 static const struct got_error *
6236 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6237 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6239 const struct got_error *err = NULL;
6240 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6241 char *label = NULL, *commit_id_str = NULL;
6242 struct got_reference *ref = NULL;
6243 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6244 char *tagmsg_path = NULL, *tag_id_str = NULL;
6245 int preserve_tagmsg = 0;
6246 struct got_reflist_head refs;
6248 TAILQ_INIT(&refs);
6251 * Don't let the user create a tag name with a leading '-'.
6252 * While technically a valid reference name, this case is usually
6253 * an unintended typo.
6255 if (tag_name[0] == '-')
6256 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6258 err = get_author(&tagger, repo, worktree);
6259 if (err)
6260 return err;
6262 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6263 if (err)
6264 goto done;
6266 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6267 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6268 if (err)
6269 goto done;
6271 err = got_object_id_str(&commit_id_str, commit_id);
6272 if (err)
6273 goto done;
6275 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6276 refname = strdup(tag_name);
6277 if (refname == NULL) {
6278 err = got_error_from_errno("strdup");
6279 goto done;
6281 tag_name += 10;
6282 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6283 err = got_error_from_errno("asprintf");
6284 goto done;
6287 err = got_ref_open(&ref, repo, refname, 0);
6288 if (err == NULL) {
6289 err = got_error(GOT_ERR_TAG_EXISTS);
6290 goto done;
6291 } else if (err->code != GOT_ERR_NOT_REF)
6292 goto done;
6294 if (tagmsg_arg == NULL) {
6295 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6296 tag_name, got_repo_get_path(repo));
6297 if (err) {
6298 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6299 tagmsg_path != NULL)
6300 preserve_tagmsg = 1;
6301 goto done;
6305 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6306 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6307 if (err) {
6308 if (tagmsg_path)
6309 preserve_tagmsg = 1;
6310 goto done;
6313 err = got_ref_alloc(&ref, refname, tag_id);
6314 if (err) {
6315 if (tagmsg_path)
6316 preserve_tagmsg = 1;
6317 goto done;
6320 err = got_ref_write(ref, repo);
6321 if (err) {
6322 if (tagmsg_path)
6323 preserve_tagmsg = 1;
6324 goto done;
6327 err = got_object_id_str(&tag_id_str, tag_id);
6328 if (err) {
6329 if (tagmsg_path)
6330 preserve_tagmsg = 1;
6331 goto done;
6333 printf("Created tag %s\n", tag_id_str);
6334 done:
6335 if (preserve_tagmsg) {
6336 fprintf(stderr, "%s: tag message preserved in %s\n",
6337 getprogname(), tagmsg_path);
6338 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6339 err = got_error_from_errno2("unlink", tagmsg_path);
6340 free(tag_id_str);
6341 if (ref)
6342 got_ref_close(ref);
6343 free(commit_id);
6344 free(commit_id_str);
6345 free(refname);
6346 free(tagmsg);
6347 free(tagmsg_path);
6348 free(tagger);
6349 got_ref_list_free(&refs);
6350 return err;
6353 static const struct got_error *
6354 cmd_tag(int argc, char *argv[])
6356 const struct got_error *error = NULL;
6357 struct got_repository *repo = NULL;
6358 struct got_worktree *worktree = NULL;
6359 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6360 char *gitconfig_path = NULL;
6361 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6362 int ch, do_list = 0;
6364 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6365 switch (ch) {
6366 case 'c':
6367 commit_id_arg = optarg;
6368 break;
6369 case 'm':
6370 tagmsg = optarg;
6371 break;
6372 case 'r':
6373 repo_path = realpath(optarg, NULL);
6374 if (repo_path == NULL)
6375 return got_error_from_errno2("realpath",
6376 optarg);
6377 got_path_strip_trailing_slashes(repo_path);
6378 break;
6379 case 'l':
6380 do_list = 1;
6381 break;
6382 default:
6383 usage_tag();
6384 /* NOTREACHED */
6388 argc -= optind;
6389 argv += optind;
6391 if (do_list) {
6392 if (commit_id_arg != NULL)
6393 errx(1,
6394 "-c option can only be used when creating a tag");
6395 if (tagmsg)
6396 option_conflict('l', 'm');
6397 if (argc > 0)
6398 usage_tag();
6399 } else if (argc != 1)
6400 usage_tag();
6402 tag_name = argv[0];
6404 #ifndef PROFILE
6405 if (do_list) {
6406 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6407 NULL) == -1)
6408 err(1, "pledge");
6409 } else {
6410 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6411 "sendfd unveil", NULL) == -1)
6412 err(1, "pledge");
6414 #endif
6415 cwd = getcwd(NULL, 0);
6416 if (cwd == NULL) {
6417 error = got_error_from_errno("getcwd");
6418 goto done;
6421 if (repo_path == NULL) {
6422 error = got_worktree_open(&worktree, cwd);
6423 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6424 goto done;
6425 else
6426 error = NULL;
6427 if (worktree) {
6428 repo_path =
6429 strdup(got_worktree_get_repo_path(worktree));
6430 if (repo_path == NULL)
6431 error = got_error_from_errno("strdup");
6432 if (error)
6433 goto done;
6434 } else {
6435 repo_path = strdup(cwd);
6436 if (repo_path == NULL) {
6437 error = got_error_from_errno("strdup");
6438 goto done;
6443 if (do_list) {
6444 error = got_repo_open(&repo, repo_path, NULL);
6445 if (error != NULL)
6446 goto done;
6447 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6448 if (error)
6449 goto done;
6450 error = list_tags(repo, worktree);
6451 } else {
6452 error = get_gitconfig_path(&gitconfig_path);
6453 if (error)
6454 goto done;
6455 error = got_repo_open(&repo, repo_path, gitconfig_path);
6456 if (error != NULL)
6457 goto done;
6459 if (tagmsg) {
6460 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6461 if (error)
6462 goto done;
6465 if (commit_id_arg == NULL) {
6466 struct got_reference *head_ref;
6467 struct got_object_id *commit_id;
6468 error = got_ref_open(&head_ref, repo,
6469 worktree ? got_worktree_get_head_ref_name(worktree)
6470 : GOT_REF_HEAD, 0);
6471 if (error)
6472 goto done;
6473 error = got_ref_resolve(&commit_id, repo, head_ref);
6474 got_ref_close(head_ref);
6475 if (error)
6476 goto done;
6477 error = got_object_id_str(&commit_id_str, commit_id);
6478 free(commit_id);
6479 if (error)
6480 goto done;
6483 error = add_tag(repo, worktree, tag_name,
6484 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6486 done:
6487 if (repo) {
6488 const struct got_error *close_err = got_repo_close(repo);
6489 if (error == NULL)
6490 error = close_err;
6492 if (worktree)
6493 got_worktree_close(worktree);
6494 free(cwd);
6495 free(repo_path);
6496 free(gitconfig_path);
6497 free(commit_id_str);
6498 return error;
6501 __dead static void
6502 usage_add(void)
6504 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6505 getprogname());
6506 exit(1);
6509 static const struct got_error *
6510 add_progress(void *arg, unsigned char status, const char *path)
6512 while (path[0] == '/')
6513 path++;
6514 printf("%c %s\n", status, path);
6515 return NULL;
6518 static const struct got_error *
6519 cmd_add(int argc, char *argv[])
6521 const struct got_error *error = NULL;
6522 struct got_repository *repo = NULL;
6523 struct got_worktree *worktree = NULL;
6524 char *cwd = NULL;
6525 struct got_pathlist_head paths;
6526 struct got_pathlist_entry *pe;
6527 int ch, can_recurse = 0, no_ignores = 0;
6529 TAILQ_INIT(&paths);
6531 while ((ch = getopt(argc, argv, "IR")) != -1) {
6532 switch (ch) {
6533 case 'I':
6534 no_ignores = 1;
6535 break;
6536 case 'R':
6537 can_recurse = 1;
6538 break;
6539 default:
6540 usage_add();
6541 /* NOTREACHED */
6545 argc -= optind;
6546 argv += optind;
6548 #ifndef PROFILE
6549 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6550 NULL) == -1)
6551 err(1, "pledge");
6552 #endif
6553 if (argc < 1)
6554 usage_add();
6556 cwd = getcwd(NULL, 0);
6557 if (cwd == NULL) {
6558 error = got_error_from_errno("getcwd");
6559 goto done;
6562 error = got_worktree_open(&worktree, cwd);
6563 if (error) {
6564 if (error->code == GOT_ERR_NOT_WORKTREE)
6565 error = wrap_not_worktree_error(error, "add", cwd);
6566 goto done;
6569 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6570 NULL);
6571 if (error != NULL)
6572 goto done;
6574 error = apply_unveil(got_repo_get_path(repo), 1,
6575 got_worktree_get_root_path(worktree));
6576 if (error)
6577 goto done;
6579 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6580 if (error)
6581 goto done;
6583 if (!can_recurse) {
6584 char *ondisk_path;
6585 struct stat sb;
6586 TAILQ_FOREACH(pe, &paths, entry) {
6587 if (asprintf(&ondisk_path, "%s/%s",
6588 got_worktree_get_root_path(worktree),
6589 pe->path) == -1) {
6590 error = got_error_from_errno("asprintf");
6591 goto done;
6593 if (lstat(ondisk_path, &sb) == -1) {
6594 if (errno == ENOENT) {
6595 free(ondisk_path);
6596 continue;
6598 error = got_error_from_errno2("lstat",
6599 ondisk_path);
6600 free(ondisk_path);
6601 goto done;
6603 free(ondisk_path);
6604 if (S_ISDIR(sb.st_mode)) {
6605 error = got_error_msg(GOT_ERR_BAD_PATH,
6606 "adding directories requires -R option");
6607 goto done;
6612 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6613 NULL, repo, no_ignores);
6614 done:
6615 if (repo) {
6616 const struct got_error *close_err = got_repo_close(repo);
6617 if (error == NULL)
6618 error = close_err;
6620 if (worktree)
6621 got_worktree_close(worktree);
6622 TAILQ_FOREACH(pe, &paths, entry)
6623 free((char *)pe->path);
6624 got_pathlist_free(&paths);
6625 free(cwd);
6626 return error;
6629 __dead static void
6630 usage_remove(void)
6632 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6633 "path ...\n", getprogname());
6634 exit(1);
6637 static const struct got_error *
6638 print_remove_status(void *arg, unsigned char status,
6639 unsigned char staged_status, const char *path)
6641 while (path[0] == '/')
6642 path++;
6643 if (status == GOT_STATUS_NONEXISTENT)
6644 return NULL;
6645 if (status == staged_status && (status == GOT_STATUS_DELETE))
6646 status = GOT_STATUS_NO_CHANGE;
6647 printf("%c%c %s\n", status, staged_status, path);
6648 return NULL;
6651 static const struct got_error *
6652 cmd_remove(int argc, char *argv[])
6654 const struct got_error *error = NULL;
6655 struct got_worktree *worktree = NULL;
6656 struct got_repository *repo = NULL;
6657 const char *status_codes = NULL;
6658 char *cwd = NULL;
6659 struct got_pathlist_head paths;
6660 struct got_pathlist_entry *pe;
6661 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6663 TAILQ_INIT(&paths);
6665 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6666 switch (ch) {
6667 case 'f':
6668 delete_local_mods = 1;
6669 break;
6670 case 'k':
6671 keep_on_disk = 1;
6672 break;
6673 case 'R':
6674 can_recurse = 1;
6675 break;
6676 case 's':
6677 for (i = 0; i < strlen(optarg); i++) {
6678 switch (optarg[i]) {
6679 case GOT_STATUS_MODIFY:
6680 delete_local_mods = 1;
6681 break;
6682 case GOT_STATUS_MISSING:
6683 break;
6684 default:
6685 errx(1, "invalid status code '%c'",
6686 optarg[i]);
6689 status_codes = optarg;
6690 break;
6691 default:
6692 usage_remove();
6693 /* NOTREACHED */
6697 argc -= optind;
6698 argv += optind;
6700 #ifndef PROFILE
6701 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6702 NULL) == -1)
6703 err(1, "pledge");
6704 #endif
6705 if (argc < 1)
6706 usage_remove();
6708 cwd = getcwd(NULL, 0);
6709 if (cwd == NULL) {
6710 error = got_error_from_errno("getcwd");
6711 goto done;
6713 error = got_worktree_open(&worktree, cwd);
6714 if (error) {
6715 if (error->code == GOT_ERR_NOT_WORKTREE)
6716 error = wrap_not_worktree_error(error, "remove", cwd);
6717 goto done;
6720 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6721 NULL);
6722 if (error)
6723 goto done;
6725 error = apply_unveil(got_repo_get_path(repo), 1,
6726 got_worktree_get_root_path(worktree));
6727 if (error)
6728 goto done;
6730 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6731 if (error)
6732 goto done;
6734 if (!can_recurse) {
6735 char *ondisk_path;
6736 struct stat sb;
6737 TAILQ_FOREACH(pe, &paths, entry) {
6738 if (asprintf(&ondisk_path, "%s/%s",
6739 got_worktree_get_root_path(worktree),
6740 pe->path) == -1) {
6741 error = got_error_from_errno("asprintf");
6742 goto done;
6744 if (lstat(ondisk_path, &sb) == -1) {
6745 if (errno == ENOENT) {
6746 free(ondisk_path);
6747 continue;
6749 error = got_error_from_errno2("lstat",
6750 ondisk_path);
6751 free(ondisk_path);
6752 goto done;
6754 free(ondisk_path);
6755 if (S_ISDIR(sb.st_mode)) {
6756 error = got_error_msg(GOT_ERR_BAD_PATH,
6757 "removing directories requires -R option");
6758 goto done;
6763 error = got_worktree_schedule_delete(worktree, &paths,
6764 delete_local_mods, status_codes, print_remove_status, NULL,
6765 repo, keep_on_disk);
6766 done:
6767 if (repo) {
6768 const struct got_error *close_err = got_repo_close(repo);
6769 if (error == NULL)
6770 error = close_err;
6772 if (worktree)
6773 got_worktree_close(worktree);
6774 TAILQ_FOREACH(pe, &paths, entry)
6775 free((char *)pe->path);
6776 got_pathlist_free(&paths);
6777 free(cwd);
6778 return error;
6781 __dead static void
6782 usage_revert(void)
6784 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6785 "path ...\n", getprogname());
6786 exit(1);
6789 static const struct got_error *
6790 revert_progress(void *arg, unsigned char status, const char *path)
6792 if (status == GOT_STATUS_UNVERSIONED)
6793 return NULL;
6795 while (path[0] == '/')
6796 path++;
6797 printf("%c %s\n", status, path);
6798 return NULL;
6801 struct choose_patch_arg {
6802 FILE *patch_script_file;
6803 const char *action;
6806 static const struct got_error *
6807 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6808 int nchanges, const char *action)
6810 char *line = NULL;
6811 size_t linesize = 0;
6812 ssize_t linelen;
6814 switch (status) {
6815 case GOT_STATUS_ADD:
6816 printf("A %s\n%s this addition? [y/n] ", path, action);
6817 break;
6818 case GOT_STATUS_DELETE:
6819 printf("D %s\n%s this deletion? [y/n] ", path, action);
6820 break;
6821 case GOT_STATUS_MODIFY:
6822 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6823 return got_error_from_errno("fseek");
6824 printf(GOT_COMMIT_SEP_STR);
6825 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6826 printf("%s", line);
6827 if (ferror(patch_file))
6828 return got_error_from_errno("getline");
6829 printf(GOT_COMMIT_SEP_STR);
6830 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6831 path, n, nchanges, action);
6832 break;
6833 default:
6834 return got_error_path(path, GOT_ERR_FILE_STATUS);
6837 return NULL;
6840 static const struct got_error *
6841 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6842 FILE *patch_file, int n, int nchanges)
6844 const struct got_error *err = NULL;
6845 char *line = NULL;
6846 size_t linesize = 0;
6847 ssize_t linelen;
6848 int resp = ' ';
6849 struct choose_patch_arg *a = arg;
6851 *choice = GOT_PATCH_CHOICE_NONE;
6853 if (a->patch_script_file) {
6854 char *nl;
6855 err = show_change(status, path, patch_file, n, nchanges,
6856 a->action);
6857 if (err)
6858 return err;
6859 linelen = getline(&line, &linesize, a->patch_script_file);
6860 if (linelen == -1) {
6861 if (ferror(a->patch_script_file))
6862 return got_error_from_errno("getline");
6863 return NULL;
6865 nl = strchr(line, '\n');
6866 if (nl)
6867 *nl = '\0';
6868 if (strcmp(line, "y") == 0) {
6869 *choice = GOT_PATCH_CHOICE_YES;
6870 printf("y\n");
6871 } else if (strcmp(line, "n") == 0) {
6872 *choice = GOT_PATCH_CHOICE_NO;
6873 printf("n\n");
6874 } else if (strcmp(line, "q") == 0 &&
6875 status == GOT_STATUS_MODIFY) {
6876 *choice = GOT_PATCH_CHOICE_QUIT;
6877 printf("q\n");
6878 } else
6879 printf("invalid response '%s'\n", line);
6880 free(line);
6881 return NULL;
6884 while (resp != 'y' && resp != 'n' && resp != 'q') {
6885 err = show_change(status, path, patch_file, n, nchanges,
6886 a->action);
6887 if (err)
6888 return err;
6889 resp = getchar();
6890 if (resp == '\n')
6891 resp = getchar();
6892 if (status == GOT_STATUS_MODIFY) {
6893 if (resp != 'y' && resp != 'n' && resp != 'q') {
6894 printf("invalid response '%c'\n", resp);
6895 resp = ' ';
6897 } else if (resp != 'y' && resp != 'n') {
6898 printf("invalid response '%c'\n", resp);
6899 resp = ' ';
6903 if (resp == 'y')
6904 *choice = GOT_PATCH_CHOICE_YES;
6905 else if (resp == 'n')
6906 *choice = GOT_PATCH_CHOICE_NO;
6907 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6908 *choice = GOT_PATCH_CHOICE_QUIT;
6910 return NULL;
6914 static const struct got_error *
6915 cmd_revert(int argc, char *argv[])
6917 const struct got_error *error = NULL;
6918 struct got_worktree *worktree = NULL;
6919 struct got_repository *repo = NULL;
6920 char *cwd = NULL, *path = NULL;
6921 struct got_pathlist_head paths;
6922 struct got_pathlist_entry *pe;
6923 int ch, can_recurse = 0, pflag = 0;
6924 FILE *patch_script_file = NULL;
6925 const char *patch_script_path = NULL;
6926 struct choose_patch_arg cpa;
6928 TAILQ_INIT(&paths);
6930 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6931 switch (ch) {
6932 case 'p':
6933 pflag = 1;
6934 break;
6935 case 'F':
6936 patch_script_path = optarg;
6937 break;
6938 case 'R':
6939 can_recurse = 1;
6940 break;
6941 default:
6942 usage_revert();
6943 /* NOTREACHED */
6947 argc -= optind;
6948 argv += optind;
6950 #ifndef PROFILE
6951 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6952 "unveil", NULL) == -1)
6953 err(1, "pledge");
6954 #endif
6955 if (argc < 1)
6956 usage_revert();
6957 if (patch_script_path && !pflag)
6958 errx(1, "-F option can only be used together with -p option");
6960 cwd = getcwd(NULL, 0);
6961 if (cwd == NULL) {
6962 error = got_error_from_errno("getcwd");
6963 goto done;
6965 error = got_worktree_open(&worktree, cwd);
6966 if (error) {
6967 if (error->code == GOT_ERR_NOT_WORKTREE)
6968 error = wrap_not_worktree_error(error, "revert", cwd);
6969 goto done;
6972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6973 NULL);
6974 if (error != NULL)
6975 goto done;
6977 if (patch_script_path) {
6978 patch_script_file = fopen(patch_script_path, "r");
6979 if (patch_script_file == NULL) {
6980 error = got_error_from_errno2("fopen",
6981 patch_script_path);
6982 goto done;
6985 error = apply_unveil(got_repo_get_path(repo), 1,
6986 got_worktree_get_root_path(worktree));
6987 if (error)
6988 goto done;
6990 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6991 if (error)
6992 goto done;
6994 if (!can_recurse) {
6995 char *ondisk_path;
6996 struct stat sb;
6997 TAILQ_FOREACH(pe, &paths, entry) {
6998 if (asprintf(&ondisk_path, "%s/%s",
6999 got_worktree_get_root_path(worktree),
7000 pe->path) == -1) {
7001 error = got_error_from_errno("asprintf");
7002 goto done;
7004 if (lstat(ondisk_path, &sb) == -1) {
7005 if (errno == ENOENT) {
7006 free(ondisk_path);
7007 continue;
7009 error = got_error_from_errno2("lstat",
7010 ondisk_path);
7011 free(ondisk_path);
7012 goto done;
7014 free(ondisk_path);
7015 if (S_ISDIR(sb.st_mode)) {
7016 error = got_error_msg(GOT_ERR_BAD_PATH,
7017 "reverting directories requires -R option");
7018 goto done;
7023 cpa.patch_script_file = patch_script_file;
7024 cpa.action = "revert";
7025 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7026 pflag ? choose_patch : NULL, &cpa, repo);
7027 done:
7028 if (patch_script_file && fclose(patch_script_file) == EOF &&
7029 error == NULL)
7030 error = got_error_from_errno2("fclose", patch_script_path);
7031 if (repo) {
7032 const struct got_error *close_err = got_repo_close(repo);
7033 if (error == NULL)
7034 error = close_err;
7036 if (worktree)
7037 got_worktree_close(worktree);
7038 free(path);
7039 free(cwd);
7040 return error;
7043 __dead static void
7044 usage_commit(void)
7046 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7047 "[path ...]\n", getprogname());
7048 exit(1);
7051 struct collect_commit_logmsg_arg {
7052 const char *cmdline_log;
7053 const char *prepared_log;
7054 int non_interactive;
7055 const char *editor;
7056 const char *worktree_path;
7057 const char *branch_name;
7058 const char *repo_path;
7059 char *logmsg_path;
7063 static const struct got_error *
7064 read_prepared_logmsg(char **logmsg, const char *path)
7066 const struct got_error *err = NULL;
7067 FILE *f = NULL;
7068 struct stat sb;
7069 size_t r;
7071 *logmsg = NULL;
7072 memset(&sb, 0, sizeof(sb));
7074 f = fopen(path, "r");
7075 if (f == NULL)
7076 return got_error_from_errno2("fopen", path);
7078 if (fstat(fileno(f), &sb) == -1) {
7079 err = got_error_from_errno2("fstat", path);
7080 goto done;
7082 if (sb.st_size == 0) {
7083 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7084 goto done;
7087 *logmsg = malloc(sb.st_size + 1);
7088 if (*logmsg == NULL) {
7089 err = got_error_from_errno("malloc");
7090 goto done;
7093 r = fread(*logmsg, 1, sb.st_size, f);
7094 if (r != sb.st_size) {
7095 if (ferror(f))
7096 err = got_error_from_errno2("fread", path);
7097 else
7098 err = got_error(GOT_ERR_IO);
7099 goto done;
7101 (*logmsg)[sb.st_size] = '\0';
7102 done:
7103 if (fclose(f) == EOF && err == NULL)
7104 err = got_error_from_errno2("fclose", path);
7105 if (err) {
7106 free(*logmsg);
7107 *logmsg = NULL;
7109 return err;
7113 static const struct got_error *
7114 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7115 void *arg)
7117 char *initial_content = NULL;
7118 struct got_pathlist_entry *pe;
7119 const struct got_error *err = NULL;
7120 char *template = NULL;
7121 struct collect_commit_logmsg_arg *a = arg;
7122 int initial_content_len;
7123 int fd = -1;
7124 size_t len;
7126 /* if a message was specified on the command line, just use it */
7127 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7128 len = strlen(a->cmdline_log) + 1;
7129 *logmsg = malloc(len + 1);
7130 if (*logmsg == NULL)
7131 return got_error_from_errno("malloc");
7132 strlcpy(*logmsg, a->cmdline_log, len);
7133 return NULL;
7134 } else if (a->prepared_log != NULL && a->non_interactive)
7135 return read_prepared_logmsg(logmsg, a->prepared_log);
7137 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7138 return got_error_from_errno("asprintf");
7140 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7141 if (err)
7142 goto done;
7144 if (a->prepared_log) {
7145 char *msg;
7146 err = read_prepared_logmsg(&msg, a->prepared_log);
7147 if (err)
7148 goto done;
7149 if (write(fd, msg, strlen(msg)) == -1) {
7150 err = got_error_from_errno2("write", a->logmsg_path);
7151 free(msg);
7152 goto done;
7154 free(msg);
7157 initial_content_len = asprintf(&initial_content,
7158 "\n# changes to be committed on branch %s:\n",
7159 a->branch_name);
7160 if (initial_content_len == -1) {
7161 err = got_error_from_errno("asprintf");
7162 goto done;
7165 if (write(fd, initial_content, initial_content_len) == -1) {
7166 err = got_error_from_errno2("write", a->logmsg_path);
7167 goto done;
7170 TAILQ_FOREACH(pe, commitable_paths, entry) {
7171 struct got_commitable *ct = pe->data;
7172 dprintf(fd, "# %c %s\n",
7173 got_commitable_get_status(ct),
7174 got_commitable_get_path(ct));
7177 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7178 initial_content_len, a->prepared_log ? 0 : 1);
7179 done:
7180 free(initial_content);
7181 free(template);
7183 if (fd != -1 && close(fd) == -1 && err == NULL)
7184 err = got_error_from_errno2("close", a->logmsg_path);
7186 /* Editor is done; we can now apply unveil(2) */
7187 if (err == NULL)
7188 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7189 if (err) {
7190 free(*logmsg);
7191 *logmsg = NULL;
7193 return err;
7196 static const struct got_error *
7197 cmd_commit(int argc, char *argv[])
7199 const struct got_error *error = NULL;
7200 struct got_worktree *worktree = NULL;
7201 struct got_repository *repo = NULL;
7202 char *cwd = NULL, *id_str = NULL;
7203 struct got_object_id *id = NULL;
7204 const char *logmsg = NULL;
7205 char *prepared_logmsg = NULL;
7206 struct collect_commit_logmsg_arg cl_arg;
7207 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7208 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7209 int allow_bad_symlinks = 0, non_interactive = 0;
7210 struct got_pathlist_head paths;
7212 TAILQ_INIT(&paths);
7213 cl_arg.logmsg_path = NULL;
7215 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7216 switch (ch) {
7217 case 'F':
7218 if (logmsg != NULL)
7219 option_conflict('F', 'm');
7220 prepared_logmsg = realpath(optarg, NULL);
7221 if (prepared_logmsg == NULL)
7222 return got_error_from_errno2("realpath",
7223 optarg);
7224 break;
7225 case 'm':
7226 if (prepared_logmsg)
7227 option_conflict('m', 'F');
7228 logmsg = optarg;
7229 break;
7230 case 'N':
7231 non_interactive = 1;
7232 break;
7233 case 'S':
7234 allow_bad_symlinks = 1;
7235 break;
7236 default:
7237 usage_commit();
7238 /* NOTREACHED */
7242 argc -= optind;
7243 argv += optind;
7245 #ifndef PROFILE
7246 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7247 "unveil", NULL) == -1)
7248 err(1, "pledge");
7249 #endif
7250 cwd = getcwd(NULL, 0);
7251 if (cwd == NULL) {
7252 error = got_error_from_errno("getcwd");
7253 goto done;
7255 error = got_worktree_open(&worktree, cwd);
7256 if (error) {
7257 if (error->code == GOT_ERR_NOT_WORKTREE)
7258 error = wrap_not_worktree_error(error, "commit", cwd);
7259 goto done;
7262 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7263 if (error)
7264 goto done;
7265 if (rebase_in_progress) {
7266 error = got_error(GOT_ERR_REBASING);
7267 goto done;
7270 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7271 worktree);
7272 if (error)
7273 goto done;
7275 error = get_gitconfig_path(&gitconfig_path);
7276 if (error)
7277 goto done;
7278 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7279 gitconfig_path);
7280 if (error != NULL)
7281 goto done;
7283 error = get_author(&author, repo, worktree);
7284 if (error)
7285 return error;
7288 * unveil(2) traverses exec(2); if an editor is used we have
7289 * to apply unveil after the log message has been written.
7291 if (logmsg == NULL || strlen(logmsg) == 0)
7292 error = get_editor(&editor);
7293 else
7294 error = apply_unveil(got_repo_get_path(repo), 0,
7295 got_worktree_get_root_path(worktree));
7296 if (error)
7297 goto done;
7299 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7300 if (error)
7301 goto done;
7303 cl_arg.editor = editor;
7304 cl_arg.cmdline_log = logmsg;
7305 cl_arg.prepared_log = prepared_logmsg;
7306 cl_arg.non_interactive = non_interactive;
7307 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7308 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7309 if (!histedit_in_progress) {
7310 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7311 error = got_error(GOT_ERR_COMMIT_BRANCH);
7312 goto done;
7314 cl_arg.branch_name += 11;
7316 cl_arg.repo_path = got_repo_get_path(repo);
7317 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7318 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7319 print_status, NULL, repo);
7320 if (error) {
7321 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7322 cl_arg.logmsg_path != NULL)
7323 preserve_logmsg = 1;
7324 goto done;
7327 error = got_object_id_str(&id_str, id);
7328 if (error)
7329 goto done;
7330 printf("Created commit %s\n", id_str);
7331 done:
7332 if (preserve_logmsg) {
7333 fprintf(stderr, "%s: log message preserved in %s\n",
7334 getprogname(), cl_arg.logmsg_path);
7335 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7336 error == NULL)
7337 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7338 free(cl_arg.logmsg_path);
7339 if (repo) {
7340 const struct got_error *close_err = got_repo_close(repo);
7341 if (error == NULL)
7342 error = close_err;
7344 if (worktree)
7345 got_worktree_close(worktree);
7346 free(cwd);
7347 free(id_str);
7348 free(gitconfig_path);
7349 free(editor);
7350 free(author);
7351 free(prepared_logmsg);
7352 return error;
7355 __dead static void
7356 usage_cherrypick(void)
7358 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7359 exit(1);
7362 static const struct got_error *
7363 cmd_cherrypick(int argc, char *argv[])
7365 const struct got_error *error = NULL;
7366 struct got_worktree *worktree = NULL;
7367 struct got_repository *repo = NULL;
7368 char *cwd = NULL, *commit_id_str = NULL;
7369 struct got_object_id *commit_id = NULL;
7370 struct got_commit_object *commit = NULL;
7371 struct got_object_qid *pid;
7372 struct got_reference *head_ref = NULL;
7373 int ch;
7374 struct got_update_progress_arg upa;
7376 while ((ch = getopt(argc, argv, "")) != -1) {
7377 switch (ch) {
7378 default:
7379 usage_cherrypick();
7380 /* NOTREACHED */
7384 argc -= optind;
7385 argv += optind;
7387 #ifndef PROFILE
7388 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7389 "unveil", NULL) == -1)
7390 err(1, "pledge");
7391 #endif
7392 if (argc != 1)
7393 usage_cherrypick();
7395 cwd = getcwd(NULL, 0);
7396 if (cwd == NULL) {
7397 error = got_error_from_errno("getcwd");
7398 goto done;
7400 error = got_worktree_open(&worktree, cwd);
7401 if (error) {
7402 if (error->code == GOT_ERR_NOT_WORKTREE)
7403 error = wrap_not_worktree_error(error, "cherrypick",
7404 cwd);
7405 goto done;
7408 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7409 NULL);
7410 if (error != NULL)
7411 goto done;
7413 error = apply_unveil(got_repo_get_path(repo), 0,
7414 got_worktree_get_root_path(worktree));
7415 if (error)
7416 goto done;
7418 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7419 GOT_OBJ_TYPE_COMMIT, repo);
7420 if (error != NULL) {
7421 struct got_reference *ref;
7422 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7423 goto done;
7424 error = got_ref_open(&ref, repo, argv[0], 0);
7425 if (error != NULL)
7426 goto done;
7427 error = got_ref_resolve(&commit_id, repo, ref);
7428 got_ref_close(ref);
7429 if (error != NULL)
7430 goto done;
7432 error = got_object_id_str(&commit_id_str, commit_id);
7433 if (error)
7434 goto done;
7436 error = got_ref_open(&head_ref, repo,
7437 got_worktree_get_head_ref_name(worktree), 0);
7438 if (error != NULL)
7439 goto done;
7441 error = check_same_branch(commit_id, head_ref, NULL, repo);
7442 if (error) {
7443 if (error->code != GOT_ERR_ANCESTRY)
7444 goto done;
7445 error = NULL;
7446 } else {
7447 error = got_error(GOT_ERR_SAME_BRANCH);
7448 goto done;
7451 error = got_object_open_as_commit(&commit, repo, commit_id);
7452 if (error)
7453 goto done;
7454 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7455 memset(&upa, 0, sizeof(upa));
7456 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7457 commit_id, repo, update_progress, &upa, check_cancelled,
7458 NULL);
7459 if (error != NULL)
7460 goto done;
7462 if (upa.did_something)
7463 printf("Merged commit %s\n", commit_id_str);
7464 print_update_progress_stats(&upa);
7465 done:
7466 if (commit)
7467 got_object_commit_close(commit);
7468 free(commit_id_str);
7469 if (head_ref)
7470 got_ref_close(head_ref);
7471 if (worktree)
7472 got_worktree_close(worktree);
7473 if (repo) {
7474 const struct got_error *close_err = got_repo_close(repo);
7475 if (error == NULL)
7476 error = close_err;
7478 return error;
7481 __dead static void
7482 usage_backout(void)
7484 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7485 exit(1);
7488 static const struct got_error *
7489 cmd_backout(int argc, char *argv[])
7491 const struct got_error *error = NULL;
7492 struct got_worktree *worktree = NULL;
7493 struct got_repository *repo = NULL;
7494 char *cwd = NULL, *commit_id_str = NULL;
7495 struct got_object_id *commit_id = NULL;
7496 struct got_commit_object *commit = NULL;
7497 struct got_object_qid *pid;
7498 struct got_reference *head_ref = NULL;
7499 int ch;
7500 struct got_update_progress_arg upa;
7502 while ((ch = getopt(argc, argv, "")) != -1) {
7503 switch (ch) {
7504 default:
7505 usage_backout();
7506 /* NOTREACHED */
7510 argc -= optind;
7511 argv += optind;
7513 #ifndef PROFILE
7514 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7515 "unveil", NULL) == -1)
7516 err(1, "pledge");
7517 #endif
7518 if (argc != 1)
7519 usage_backout();
7521 cwd = getcwd(NULL, 0);
7522 if (cwd == NULL) {
7523 error = got_error_from_errno("getcwd");
7524 goto done;
7526 error = got_worktree_open(&worktree, cwd);
7527 if (error) {
7528 if (error->code == GOT_ERR_NOT_WORKTREE)
7529 error = wrap_not_worktree_error(error, "backout", cwd);
7530 goto done;
7533 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7534 NULL);
7535 if (error != NULL)
7536 goto done;
7538 error = apply_unveil(got_repo_get_path(repo), 0,
7539 got_worktree_get_root_path(worktree));
7540 if (error)
7541 goto done;
7543 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7544 GOT_OBJ_TYPE_COMMIT, repo);
7545 if (error != NULL) {
7546 struct got_reference *ref;
7547 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7548 goto done;
7549 error = got_ref_open(&ref, repo, argv[0], 0);
7550 if (error != NULL)
7551 goto done;
7552 error = got_ref_resolve(&commit_id, repo, ref);
7553 got_ref_close(ref);
7554 if (error != NULL)
7555 goto done;
7557 error = got_object_id_str(&commit_id_str, commit_id);
7558 if (error)
7559 goto done;
7561 error = got_ref_open(&head_ref, repo,
7562 got_worktree_get_head_ref_name(worktree), 0);
7563 if (error != NULL)
7564 goto done;
7566 error = check_same_branch(commit_id, head_ref, NULL, repo);
7567 if (error)
7568 goto done;
7570 error = got_object_open_as_commit(&commit, repo, commit_id);
7571 if (error)
7572 goto done;
7573 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7574 if (pid == NULL) {
7575 error = got_error(GOT_ERR_ROOT_COMMIT);
7576 goto done;
7579 memset(&upa, 0, sizeof(upa));
7580 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7581 update_progress, &upa, check_cancelled, NULL);
7582 if (error != NULL)
7583 goto done;
7585 if (upa.did_something)
7586 printf("Backed out commit %s\n", commit_id_str);
7587 print_update_progress_stats(&upa);
7588 done:
7589 if (commit)
7590 got_object_commit_close(commit);
7591 free(commit_id_str);
7592 if (head_ref)
7593 got_ref_close(head_ref);
7594 if (worktree)
7595 got_worktree_close(worktree);
7596 if (repo) {
7597 const struct got_error *close_err = got_repo_close(repo);
7598 if (error == NULL)
7599 error = close_err;
7601 return error;
7604 __dead static void
7605 usage_rebase(void)
7607 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
7608 getprogname());
7609 exit(1);
7612 void
7613 trim_logmsg(char *logmsg, int limit)
7615 char *nl;
7616 size_t len;
7618 len = strlen(logmsg);
7619 if (len > limit)
7620 len = limit;
7621 logmsg[len] = '\0';
7622 nl = strchr(logmsg, '\n');
7623 if (nl)
7624 *nl = '\0';
7627 static const struct got_error *
7628 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7630 const struct got_error *err;
7631 char *logmsg0 = NULL;
7632 const char *s;
7634 err = got_object_commit_get_logmsg(&logmsg0, commit);
7635 if (err)
7636 return err;
7638 s = logmsg0;
7639 while (isspace((unsigned char)s[0]))
7640 s++;
7642 *logmsg = strdup(s);
7643 if (*logmsg == NULL) {
7644 err = got_error_from_errno("strdup");
7645 goto done;
7648 trim_logmsg(*logmsg, limit);
7649 done:
7650 free(logmsg0);
7651 return err;
7654 static const struct got_error *
7655 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7657 const struct got_error *err;
7658 struct got_commit_object *commit = NULL;
7659 char *id_str = NULL, *logmsg = NULL;
7661 err = got_object_open_as_commit(&commit, repo, id);
7662 if (err)
7663 return err;
7665 err = got_object_id_str(&id_str, id);
7666 if (err)
7667 goto done;
7669 id_str[12] = '\0';
7671 err = get_short_logmsg(&logmsg, 42, commit);
7672 if (err)
7673 goto done;
7675 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7676 done:
7677 free(id_str);
7678 got_object_commit_close(commit);
7679 free(logmsg);
7680 return err;
7683 static const struct got_error *
7684 show_rebase_progress(struct got_commit_object *commit,
7685 struct got_object_id *old_id, struct got_object_id *new_id)
7687 const struct got_error *err;
7688 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7690 err = got_object_id_str(&old_id_str, old_id);
7691 if (err)
7692 goto done;
7694 if (new_id) {
7695 err = got_object_id_str(&new_id_str, new_id);
7696 if (err)
7697 goto done;
7700 old_id_str[12] = '\0';
7701 if (new_id_str)
7702 new_id_str[12] = '\0';
7704 err = get_short_logmsg(&logmsg, 42, commit);
7705 if (err)
7706 goto done;
7708 printf("%s -> %s: %s\n", old_id_str,
7709 new_id_str ? new_id_str : "no-op change", logmsg);
7710 done:
7711 free(old_id_str);
7712 free(new_id_str);
7713 free(logmsg);
7714 return err;
7717 static const struct got_error *
7718 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7719 struct got_reference *branch, struct got_reference *new_base_branch,
7720 struct got_reference *tmp_branch, struct got_repository *repo,
7721 int create_backup)
7723 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7724 return got_worktree_rebase_complete(worktree, fileindex,
7725 new_base_branch, tmp_branch, branch, repo, create_backup);
7728 static const struct got_error *
7729 rebase_commit(struct got_pathlist_head *merged_paths,
7730 struct got_worktree *worktree, struct got_fileindex *fileindex,
7731 struct got_reference *tmp_branch,
7732 struct got_object_id *commit_id, struct got_repository *repo)
7734 const struct got_error *error;
7735 struct got_commit_object *commit;
7736 struct got_object_id *new_commit_id;
7738 error = got_object_open_as_commit(&commit, repo, commit_id);
7739 if (error)
7740 return error;
7742 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7743 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7744 if (error) {
7745 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7746 goto done;
7747 error = show_rebase_progress(commit, commit_id, NULL);
7748 } else {
7749 error = show_rebase_progress(commit, commit_id, new_commit_id);
7750 free(new_commit_id);
7752 done:
7753 got_object_commit_close(commit);
7754 return error;
7757 struct check_path_prefix_arg {
7758 const char *path_prefix;
7759 size_t len;
7760 int errcode;
7763 static const struct got_error *
7764 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7765 struct got_blob_object *blob2, struct got_object_id *id1,
7766 struct got_object_id *id2, const char *path1, const char *path2,
7767 mode_t mode1, mode_t mode2, struct got_repository *repo)
7769 struct check_path_prefix_arg *a = arg;
7771 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7772 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7773 return got_error(a->errcode);
7775 return NULL;
7778 static const struct got_error *
7779 check_path_prefix(struct got_object_id *parent_id,
7780 struct got_object_id *commit_id, const char *path_prefix,
7781 int errcode, struct got_repository *repo)
7783 const struct got_error *err;
7784 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7785 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7786 struct check_path_prefix_arg cpp_arg;
7788 if (got_path_is_root_dir(path_prefix))
7789 return NULL;
7791 err = got_object_open_as_commit(&commit, repo, commit_id);
7792 if (err)
7793 goto done;
7795 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7796 if (err)
7797 goto done;
7799 err = got_object_open_as_tree(&tree1, repo,
7800 got_object_commit_get_tree_id(parent_commit));
7801 if (err)
7802 goto done;
7804 err = got_object_open_as_tree(&tree2, repo,
7805 got_object_commit_get_tree_id(commit));
7806 if (err)
7807 goto done;
7809 cpp_arg.path_prefix = path_prefix;
7810 while (cpp_arg.path_prefix[0] == '/')
7811 cpp_arg.path_prefix++;
7812 cpp_arg.len = strlen(cpp_arg.path_prefix);
7813 cpp_arg.errcode = errcode;
7814 err = got_diff_tree(tree1, tree2, "", "", repo,
7815 check_path_prefix_in_diff, &cpp_arg, 0);
7816 done:
7817 if (tree1)
7818 got_object_tree_close(tree1);
7819 if (tree2)
7820 got_object_tree_close(tree2);
7821 if (commit)
7822 got_object_commit_close(commit);
7823 if (parent_commit)
7824 got_object_commit_close(parent_commit);
7825 return err;
7828 static const struct got_error *
7829 collect_commits(struct got_object_id_queue *commits,
7830 struct got_object_id *initial_commit_id,
7831 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7832 const char *path_prefix, int path_prefix_errcode,
7833 struct got_repository *repo)
7835 const struct got_error *err = NULL;
7836 struct got_commit_graph *graph = NULL;
7837 struct got_object_id *parent_id = NULL;
7838 struct got_object_qid *qid;
7839 struct got_object_id *commit_id = initial_commit_id;
7841 err = got_commit_graph_open(&graph, "/", 1);
7842 if (err)
7843 return err;
7845 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7846 check_cancelled, NULL);
7847 if (err)
7848 goto done;
7849 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7850 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7851 check_cancelled, NULL);
7852 if (err) {
7853 if (err->code == GOT_ERR_ITER_COMPLETED) {
7854 err = got_error_msg(GOT_ERR_ANCESTRY,
7855 "ran out of commits to rebase before "
7856 "youngest common ancestor commit has "
7857 "been reached?!?");
7859 goto done;
7860 } else {
7861 err = check_path_prefix(parent_id, commit_id,
7862 path_prefix, path_prefix_errcode, repo);
7863 if (err)
7864 goto done;
7866 err = got_object_qid_alloc(&qid, commit_id);
7867 if (err)
7868 goto done;
7869 STAILQ_INSERT_HEAD(commits, qid, entry);
7870 commit_id = parent_id;
7873 done:
7874 got_commit_graph_close(graph);
7875 return err;
7878 static const struct got_error *
7879 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
7881 const struct got_error *err = NULL;
7882 time_t committer_time;
7883 struct tm tm;
7884 char datebuf[11]; /* YYYY-MM-DD + NUL */
7885 char *author0 = NULL, *author, *smallerthan;
7886 char *logmsg0 = NULL, *logmsg, *newline;
7888 committer_time = got_object_commit_get_committer_time(commit);
7889 if (localtime_r(&committer_time, &tm) == NULL)
7890 return got_error_from_errno("localtime_r");
7891 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
7892 return got_error(GOT_ERR_NO_SPACE);
7894 author0 = strdup(got_object_commit_get_author(commit));
7895 if (author0 == NULL)
7896 return got_error_from_errno("strdup");
7897 author = author0;
7898 smallerthan = strchr(author, '<');
7899 if (smallerthan && smallerthan[1] != '\0')
7900 author = smallerthan + 1;
7901 author[strcspn(author, "@>")] = '\0';
7903 err = got_object_commit_get_logmsg(&logmsg0, commit);
7904 if (err)
7905 goto done;
7906 logmsg = logmsg0;
7907 while (*logmsg == '\n')
7908 logmsg++;
7909 newline = strchr(logmsg, '\n');
7910 if (newline)
7911 *newline = '\0';
7913 if (asprintf(brief_str, "%s %s %s",
7914 datebuf, author, logmsg) == -1)
7915 err = got_error_from_errno("asprintf");
7916 done:
7917 free(author0);
7918 free(logmsg0);
7919 return err;
7922 static const struct got_error *
7923 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
7924 struct got_repository *repo)
7926 const struct got_error *err;
7927 char *id_str;
7929 err = got_object_id_str(&id_str, id);
7930 if (err)
7931 return err;
7933 err = got_ref_delete(ref, repo);
7934 if (err)
7935 goto done;
7937 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
7938 done:
7939 free(id_str);
7940 return err;
7943 static const struct got_error *
7944 print_backup_ref(const char *branch_name, const char *new_id_str,
7945 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
7946 struct got_reflist_object_id_map *refs_idmap,
7947 struct got_repository *repo)
7949 const struct got_error *err = NULL;
7950 struct got_reflist_head *refs;
7951 char *refs_str = NULL;
7952 struct got_object_id *new_commit_id = NULL;
7953 struct got_commit_object *new_commit = NULL;
7954 char *new_commit_brief_str = NULL;
7955 struct got_object_id *yca_id = NULL;
7956 struct got_commit_object *yca_commit = NULL;
7957 char *yca_id_str = NULL, *yca_brief_str = NULL;
7958 char *custom_refs_str;
7960 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
7961 return got_error_from_errno("asprintf");
7963 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
7964 0, 0, refs_idmap, custom_refs_str);
7965 if (err)
7966 goto done;
7968 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
7969 if (err)
7970 goto done;
7972 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
7973 if (refs) {
7974 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
7975 if (err)
7976 goto done;
7979 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
7980 if (err)
7981 goto done;
7983 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
7984 if (err)
7985 goto done;
7987 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7988 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
7989 if (err)
7990 goto done;
7992 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
7993 refs_str ? " (" : "", refs_str ? refs_str : "",
7994 refs_str ? ")" : "", new_commit_brief_str);
7995 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
7996 got_object_id_cmp(yca_id, old_commit_id) != 0) {
7997 free(refs_str);
7998 refs_str = NULL;
8000 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8001 if (err)
8002 goto done;
8004 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8005 if (err)
8006 goto done;
8008 err = got_object_id_str(&yca_id_str, yca_id);
8009 if (err)
8010 goto done;
8012 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8013 if (refs) {
8014 err = build_refs_str(&refs_str, refs, yca_id, repo);
8015 if (err)
8016 goto done;
8018 printf("history forked at %s%s%s%s\n %s\n",
8019 yca_id_str,
8020 refs_str ? " (" : "", refs_str ? refs_str : "",
8021 refs_str ? ")" : "", yca_brief_str);
8023 done:
8024 free(custom_refs_str);
8025 free(new_commit_id);
8026 free(refs_str);
8027 free(yca_id);
8028 free(yca_id_str);
8029 free(yca_brief_str);
8030 if (new_commit)
8031 got_object_commit_close(new_commit);
8032 if (yca_commit)
8033 got_object_commit_close(yca_commit);
8035 return NULL;
8038 static const struct got_error *
8039 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8040 int delete, struct got_repository *repo)
8042 const struct got_error *err;
8043 struct got_reflist_head refs, backup_refs;
8044 struct got_reflist_entry *re;
8045 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8046 struct got_object_id *old_commit_id = NULL;
8047 char *branch_name = NULL;
8048 struct got_commit_object *old_commit = NULL;
8049 struct got_reflist_object_id_map *refs_idmap = NULL;
8050 int wanted_branch_found = 0;
8052 TAILQ_INIT(&refs);
8053 TAILQ_INIT(&backup_refs);
8055 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8056 if (err)
8057 return err;
8059 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8060 if (err)
8061 goto done;
8063 if (wanted_branch_name) {
8064 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8065 wanted_branch_name += 11;
8068 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8069 got_ref_cmp_by_commit_timestamp_descending, repo);
8070 if (err)
8071 goto done;
8073 TAILQ_FOREACH(re, &backup_refs, entry) {
8074 const char *refname = got_ref_get_name(re->ref);
8075 char *slash;
8077 err = check_cancelled(NULL);
8078 if (err)
8079 break;
8081 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8082 if (err)
8083 break;
8085 err = got_object_open_as_commit(&old_commit, repo,
8086 old_commit_id);
8087 if (err)
8088 break;
8090 if (strncmp(backup_ref_prefix, refname,
8091 backup_ref_prefix_len) == 0)
8092 refname += backup_ref_prefix_len;
8094 while (refname[0] == '/')
8095 refname++;
8097 branch_name = strdup(refname);
8098 if (branch_name == NULL) {
8099 err = got_error_from_errno("strdup");
8100 break;
8102 slash = strrchr(branch_name, '/');
8103 if (slash) {
8104 *slash = '\0';
8105 refname += strlen(branch_name) + 1;
8108 if (wanted_branch_name == NULL ||
8109 strcmp(wanted_branch_name, branch_name) == 0) {
8110 wanted_branch_found = 1;
8111 if (delete) {
8112 err = delete_backup_ref(re->ref,
8113 old_commit_id, repo);
8114 } else {
8115 err = print_backup_ref(branch_name, refname,
8116 old_commit_id, old_commit, refs_idmap,
8117 repo);
8119 if (err)
8120 break;
8123 free(old_commit_id);
8124 old_commit_id = NULL;
8125 free(branch_name);
8126 branch_name = NULL;
8127 got_object_commit_close(old_commit);
8128 old_commit = NULL;
8131 if (wanted_branch_name && !wanted_branch_found) {
8132 err = got_error_fmt(GOT_ERR_NOT_REF,
8133 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8135 done:
8136 if (refs_idmap)
8137 got_reflist_object_id_map_free(refs_idmap);
8138 got_ref_list_free(&refs);
8139 got_ref_list_free(&backup_refs);
8140 free(old_commit_id);
8141 free(branch_name);
8142 if (old_commit)
8143 got_object_commit_close(old_commit);
8144 return err;
8147 static const struct got_error *
8148 cmd_rebase(int argc, char *argv[])
8150 const struct got_error *error = NULL;
8151 struct got_worktree *worktree = NULL;
8152 struct got_repository *repo = NULL;
8153 struct got_fileindex *fileindex = NULL;
8154 char *cwd = NULL;
8155 struct got_reference *branch = NULL;
8156 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8157 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8158 struct got_object_id *resume_commit_id = NULL;
8159 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8160 struct got_commit_object *commit = NULL;
8161 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8162 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8163 int delete_backups = 0;
8164 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8165 struct got_object_id_queue commits;
8166 struct got_pathlist_head merged_paths;
8167 const struct got_object_id_queue *parent_ids;
8168 struct got_object_qid *qid, *pid;
8170 STAILQ_INIT(&commits);
8171 TAILQ_INIT(&merged_paths);
8173 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8174 switch (ch) {
8175 case 'a':
8176 abort_rebase = 1;
8177 break;
8178 case 'c':
8179 continue_rebase = 1;
8180 break;
8181 case 'l':
8182 list_backups = 1;
8183 break;
8184 case 'X':
8185 delete_backups = 1;
8186 break;
8187 default:
8188 usage_rebase();
8189 /* NOTREACHED */
8193 argc -= optind;
8194 argv += optind;
8196 #ifndef PROFILE
8197 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8198 "unveil", NULL) == -1)
8199 err(1, "pledge");
8200 #endif
8201 if (list_backups) {
8202 if (abort_rebase)
8203 option_conflict('l', 'a');
8204 if (continue_rebase)
8205 option_conflict('l', 'c');
8206 if (delete_backups)
8207 option_conflict('l', 'X');
8208 if (argc != 0 && argc != 1)
8209 usage_rebase();
8210 } else if (delete_backups) {
8211 if (abort_rebase)
8212 option_conflict('X', 'a');
8213 if (continue_rebase)
8214 option_conflict('X', 'c');
8215 if (list_backups)
8216 option_conflict('l', 'X');
8217 if (argc != 0 && argc != 1)
8218 usage_rebase();
8219 } else {
8220 if (abort_rebase && continue_rebase)
8221 usage_rebase();
8222 else if (abort_rebase || continue_rebase) {
8223 if (argc != 0)
8224 usage_rebase();
8225 } else if (argc != 1)
8226 usage_rebase();
8229 cwd = getcwd(NULL, 0);
8230 if (cwd == NULL) {
8231 error = got_error_from_errno("getcwd");
8232 goto done;
8234 error = got_worktree_open(&worktree, cwd);
8235 if (error) {
8236 if (list_backups || delete_backups) {
8237 if (error->code != GOT_ERR_NOT_WORKTREE)
8238 goto done;
8239 } else {
8240 if (error->code == GOT_ERR_NOT_WORKTREE)
8241 error = wrap_not_worktree_error(error,
8242 "rebase", cwd);
8243 goto done;
8247 error = got_repo_open(&repo,
8248 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8249 if (error != NULL)
8250 goto done;
8252 error = apply_unveil(got_repo_get_path(repo), 0,
8253 worktree ? got_worktree_get_root_path(worktree) : NULL);
8254 if (error)
8255 goto done;
8257 if (list_backups || delete_backups) {
8258 error = process_backup_refs(
8259 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8260 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8261 goto done; /* nothing else to do */
8264 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8265 worktree);
8266 if (error)
8267 goto done;
8268 if (histedit_in_progress) {
8269 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8270 goto done;
8273 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8274 if (error)
8275 goto done;
8277 if (abort_rebase) {
8278 struct got_update_progress_arg upa;
8279 if (!rebase_in_progress) {
8280 error = got_error(GOT_ERR_NOT_REBASING);
8281 goto done;
8283 error = got_worktree_rebase_continue(&resume_commit_id,
8284 &new_base_branch, &tmp_branch, &branch, &fileindex,
8285 worktree, repo);
8286 if (error)
8287 goto done;
8288 printf("Switching work tree to %s\n",
8289 got_ref_get_symref_target(new_base_branch));
8290 memset(&upa, 0, sizeof(upa));
8291 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8292 new_base_branch, update_progress, &upa);
8293 if (error)
8294 goto done;
8295 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8296 print_update_progress_stats(&upa);
8297 goto done; /* nothing else to do */
8300 if (continue_rebase) {
8301 if (!rebase_in_progress) {
8302 error = got_error(GOT_ERR_NOT_REBASING);
8303 goto done;
8305 error = got_worktree_rebase_continue(&resume_commit_id,
8306 &new_base_branch, &tmp_branch, &branch, &fileindex,
8307 worktree, repo);
8308 if (error)
8309 goto done;
8311 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8312 resume_commit_id, repo);
8313 if (error)
8314 goto done;
8316 yca_id = got_object_id_dup(resume_commit_id);
8317 if (yca_id == NULL) {
8318 error = got_error_from_errno("got_object_id_dup");
8319 goto done;
8321 } else {
8322 error = got_ref_open(&branch, repo, argv[0], 0);
8323 if (error != NULL)
8324 goto done;
8327 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8328 if (error)
8329 goto done;
8331 if (!continue_rebase) {
8332 struct got_object_id *base_commit_id;
8334 base_commit_id = got_worktree_get_base_commit_id(worktree);
8335 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8336 base_commit_id, branch_head_commit_id, repo,
8337 check_cancelled, NULL);
8338 if (error)
8339 goto done;
8340 if (yca_id == NULL) {
8341 error = got_error_msg(GOT_ERR_ANCESTRY,
8342 "specified branch shares no common ancestry "
8343 "with work tree's branch");
8344 goto done;
8347 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8348 if (error) {
8349 if (error->code != GOT_ERR_ANCESTRY)
8350 goto done;
8351 error = NULL;
8352 } else {
8353 static char msg[128];
8354 snprintf(msg, sizeof(msg),
8355 "%s is already based on %s",
8356 got_ref_get_name(branch),
8357 got_worktree_get_head_ref_name(worktree));
8358 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8359 goto done;
8361 error = got_worktree_rebase_prepare(&new_base_branch,
8362 &tmp_branch, &fileindex, worktree, branch, repo);
8363 if (error)
8364 goto done;
8367 commit_id = branch_head_commit_id;
8368 error = got_object_open_as_commit(&commit, repo, commit_id);
8369 if (error)
8370 goto done;
8372 parent_ids = got_object_commit_get_parent_ids(commit);
8373 pid = STAILQ_FIRST(parent_ids);
8374 if (pid == NULL) {
8375 if (!continue_rebase) {
8376 struct got_update_progress_arg upa;
8377 memset(&upa, 0, sizeof(upa));
8378 error = got_worktree_rebase_abort(worktree, fileindex,
8379 repo, new_base_branch, update_progress, &upa);
8380 if (error)
8381 goto done;
8382 printf("Rebase of %s aborted\n",
8383 got_ref_get_name(branch));
8384 print_update_progress_stats(&upa);
8387 error = got_error(GOT_ERR_EMPTY_REBASE);
8388 goto done;
8390 error = collect_commits(&commits, commit_id, pid->id,
8391 yca_id, got_worktree_get_path_prefix(worktree),
8392 GOT_ERR_REBASE_PATH, repo);
8393 got_object_commit_close(commit);
8394 commit = NULL;
8395 if (error)
8396 goto done;
8398 if (STAILQ_EMPTY(&commits)) {
8399 if (continue_rebase) {
8400 error = rebase_complete(worktree, fileindex,
8401 branch, new_base_branch, tmp_branch, repo,
8402 create_backup);
8403 goto done;
8404 } else {
8405 /* Fast-forward the reference of the branch. */
8406 struct got_object_id *new_head_commit_id;
8407 char *id_str;
8408 error = got_ref_resolve(&new_head_commit_id, repo,
8409 new_base_branch);
8410 if (error)
8411 goto done;
8412 error = got_object_id_str(&id_str, new_head_commit_id);
8413 printf("Forwarding %s to commit %s\n",
8414 got_ref_get_name(branch), id_str);
8415 free(id_str);
8416 error = got_ref_change_ref(branch,
8417 new_head_commit_id);
8418 if (error)
8419 goto done;
8420 /* No backup needed since objects did not change. */
8421 create_backup = 0;
8425 pid = NULL;
8426 STAILQ_FOREACH(qid, &commits, entry) {
8427 struct got_update_progress_arg upa;
8429 commit_id = qid->id;
8430 parent_id = pid ? pid->id : yca_id;
8431 pid = qid;
8433 memset(&upa, 0, sizeof(upa));
8434 error = got_worktree_rebase_merge_files(&merged_paths,
8435 worktree, fileindex, parent_id, commit_id, repo,
8436 update_progress, &upa, check_cancelled, NULL);
8437 if (error)
8438 goto done;
8440 print_update_progress_stats(&upa);
8441 if (upa.conflicts > 0)
8442 rebase_status = GOT_STATUS_CONFLICT;
8444 if (rebase_status == GOT_STATUS_CONFLICT) {
8445 error = show_rebase_merge_conflict(qid->id, repo);
8446 if (error)
8447 goto done;
8448 got_worktree_rebase_pathlist_free(&merged_paths);
8449 break;
8452 error = rebase_commit(&merged_paths, worktree, fileindex,
8453 tmp_branch, commit_id, repo);
8454 got_worktree_rebase_pathlist_free(&merged_paths);
8455 if (error)
8456 goto done;
8459 if (rebase_status == GOT_STATUS_CONFLICT) {
8460 error = got_worktree_rebase_postpone(worktree, fileindex);
8461 if (error)
8462 goto done;
8463 error = got_error_msg(GOT_ERR_CONFLICTS,
8464 "conflicts must be resolved before rebasing can continue");
8465 } else
8466 error = rebase_complete(worktree, fileindex, branch,
8467 new_base_branch, tmp_branch, repo, create_backup);
8468 done:
8469 got_object_id_queue_free(&commits);
8470 free(branch_head_commit_id);
8471 free(resume_commit_id);
8472 free(yca_id);
8473 if (commit)
8474 got_object_commit_close(commit);
8475 if (branch)
8476 got_ref_close(branch);
8477 if (new_base_branch)
8478 got_ref_close(new_base_branch);
8479 if (tmp_branch)
8480 got_ref_close(tmp_branch);
8481 if (worktree)
8482 got_worktree_close(worktree);
8483 if (repo) {
8484 const struct got_error *close_err = got_repo_close(repo);
8485 if (error == NULL)
8486 error = close_err;
8488 return error;
8491 __dead static void
8492 usage_histedit(void)
8494 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8495 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
8496 getprogname());
8497 exit(1);
8500 #define GOT_HISTEDIT_PICK 'p'
8501 #define GOT_HISTEDIT_EDIT 'e'
8502 #define GOT_HISTEDIT_FOLD 'f'
8503 #define GOT_HISTEDIT_DROP 'd'
8504 #define GOT_HISTEDIT_MESG 'm'
8506 static struct got_histedit_cmd {
8507 unsigned char code;
8508 const char *name;
8509 const char *desc;
8510 } got_histedit_cmds[] = {
8511 { GOT_HISTEDIT_PICK, "pick", "use commit" },
8512 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
8513 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
8514 "be used" },
8515 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
8516 { GOT_HISTEDIT_MESG, "mesg",
8517 "single-line log message for commit above (open editor if empty)" },
8520 struct got_histedit_list_entry {
8521 TAILQ_ENTRY(got_histedit_list_entry) entry;
8522 struct got_object_id *commit_id;
8523 const struct got_histedit_cmd *cmd;
8524 char *logmsg;
8526 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
8528 static const struct got_error *
8529 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
8530 FILE *f, struct got_repository *repo)
8532 const struct got_error *err = NULL;
8533 char *logmsg = NULL, *id_str = NULL;
8534 struct got_commit_object *commit = NULL;
8535 int n;
8537 err = got_object_open_as_commit(&commit, repo, commit_id);
8538 if (err)
8539 goto done;
8541 err = get_short_logmsg(&logmsg, 34, commit);
8542 if (err)
8543 goto done;
8545 err = got_object_id_str(&id_str, commit_id);
8546 if (err)
8547 goto done;
8549 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
8550 if (n < 0)
8551 err = got_ferror(f, GOT_ERR_IO);
8552 done:
8553 if (commit)
8554 got_object_commit_close(commit);
8555 free(id_str);
8556 free(logmsg);
8557 return err;
8560 static const struct got_error *
8561 histedit_write_commit_list(struct got_object_id_queue *commits,
8562 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
8564 const struct got_error *err = NULL;
8565 struct got_object_qid *qid;
8566 const char *histedit_cmd = NULL;
8568 if (STAILQ_EMPTY(commits))
8569 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8571 STAILQ_FOREACH(qid, commits, entry) {
8572 histedit_cmd = got_histedit_cmds[0].name;
8573 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
8574 histedit_cmd = "fold";
8575 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
8576 if (err)
8577 break;
8578 if (edit_logmsg_only) {
8579 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
8580 if (n < 0) {
8581 err = got_ferror(f, GOT_ERR_IO);
8582 break;
8587 return err;
8590 static const struct got_error *
8591 write_cmd_list(FILE *f, const char *branch_name,
8592 struct got_object_id_queue *commits)
8594 const struct got_error *err = NULL;
8595 size_t i;
8596 int n;
8597 char *id_str;
8598 struct got_object_qid *qid;
8600 qid = STAILQ_FIRST(commits);
8601 err = got_object_id_str(&id_str, qid->id);
8602 if (err)
8603 return err;
8605 n = fprintf(f,
8606 "# Editing the history of branch '%s' starting at\n"
8607 "# commit %s\n"
8608 "# Commits will be processed in order from top to "
8609 "bottom of this file.\n", branch_name, id_str);
8610 if (n < 0) {
8611 err = got_ferror(f, GOT_ERR_IO);
8612 goto done;
8615 n = fprintf(f, "# Available histedit commands:\n");
8616 if (n < 0) {
8617 err = got_ferror(f, GOT_ERR_IO);
8618 goto done;
8621 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8622 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
8623 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
8624 cmd->desc);
8625 if (n < 0) {
8626 err = got_ferror(f, GOT_ERR_IO);
8627 break;
8630 done:
8631 free(id_str);
8632 return err;
8635 static const struct got_error *
8636 histedit_syntax_error(int lineno)
8638 static char msg[42];
8639 int ret;
8641 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
8642 lineno);
8643 if (ret == -1 || ret >= sizeof(msg))
8644 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
8646 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
8649 static const struct got_error *
8650 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
8651 char *logmsg, struct got_repository *repo)
8653 const struct got_error *err;
8654 struct got_commit_object *folded_commit = NULL;
8655 char *id_str, *folded_logmsg = NULL;
8657 err = got_object_id_str(&id_str, hle->commit_id);
8658 if (err)
8659 return err;
8661 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
8662 if (err)
8663 goto done;
8665 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
8666 if (err)
8667 goto done;
8668 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
8669 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
8670 folded_logmsg) == -1) {
8671 err = got_error_from_errno("asprintf");
8673 done:
8674 if (folded_commit)
8675 got_object_commit_close(folded_commit);
8676 free(id_str);
8677 free(folded_logmsg);
8678 return err;
8681 static struct got_histedit_list_entry *
8682 get_folded_commits(struct got_histedit_list_entry *hle)
8684 struct got_histedit_list_entry *prev, *folded = NULL;
8686 prev = TAILQ_PREV(hle, got_histedit_list, entry);
8687 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
8688 prev->cmd->code == GOT_HISTEDIT_DROP)) {
8689 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
8690 folded = prev;
8691 prev = TAILQ_PREV(prev, got_histedit_list, entry);
8694 return folded;
8697 static const struct got_error *
8698 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
8699 struct got_repository *repo)
8701 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
8702 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
8703 const struct got_error *err = NULL;
8704 struct got_commit_object *commit = NULL;
8705 int logmsg_len;
8706 int fd;
8707 struct got_histedit_list_entry *folded = NULL;
8709 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8710 if (err)
8711 return err;
8713 folded = get_folded_commits(hle);
8714 if (folded) {
8715 while (folded != hle) {
8716 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
8717 folded = TAILQ_NEXT(folded, entry);
8718 continue;
8720 err = append_folded_commit_msg(&new_msg, folded,
8721 logmsg, repo);
8722 if (err)
8723 goto done;
8724 free(logmsg);
8725 logmsg = new_msg;
8726 folded = TAILQ_NEXT(folded, entry);
8730 err = got_object_id_str(&id_str, hle->commit_id);
8731 if (err)
8732 goto done;
8733 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
8734 if (err)
8735 goto done;
8736 logmsg_len = asprintf(&new_msg,
8737 "%s\n# original log message of commit %s: %s",
8738 logmsg ? logmsg : "", id_str, orig_logmsg);
8739 if (logmsg_len == -1) {
8740 err = got_error_from_errno("asprintf");
8741 goto done;
8743 free(logmsg);
8744 logmsg = new_msg;
8746 err = got_object_id_str(&id_str, hle->commit_id);
8747 if (err)
8748 goto done;
8750 err = got_opentemp_named_fd(&logmsg_path, &fd,
8751 GOT_TMPDIR_STR "/got-logmsg");
8752 if (err)
8753 goto done;
8755 write(fd, logmsg, logmsg_len);
8756 close(fd);
8758 err = get_editor(&editor);
8759 if (err)
8760 goto done;
8762 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
8763 logmsg_len, 0);
8764 if (err) {
8765 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
8766 goto done;
8767 err = NULL;
8768 hle->logmsg = strdup(new_msg);
8769 if (hle->logmsg == NULL)
8770 err = got_error_from_errno("strdup");
8772 done:
8773 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
8774 err = got_error_from_errno2("unlink", logmsg_path);
8775 free(logmsg_path);
8776 free(logmsg);
8777 free(orig_logmsg);
8778 free(editor);
8779 if (commit)
8780 got_object_commit_close(commit);
8781 return err;
8784 static const struct got_error *
8785 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8786 FILE *f, struct got_repository *repo)
8788 const struct got_error *err = NULL;
8789 char *line = NULL, *p, *end;
8790 size_t i, size;
8791 ssize_t len;
8792 int lineno = 0;
8793 const struct got_histedit_cmd *cmd;
8794 struct got_object_id *commit_id = NULL;
8795 struct got_histedit_list_entry *hle = NULL;
8797 for (;;) {
8798 len = getline(&line, &size, f);
8799 if (len == -1) {
8800 const struct got_error *getline_err;
8801 if (feof(f))
8802 break;
8803 getline_err = got_error_from_errno("getline");
8804 err = got_ferror(f, getline_err->code);
8805 break;
8807 lineno++;
8808 p = line;
8809 while (isspace((unsigned char)p[0]))
8810 p++;
8811 if (p[0] == '#' || p[0] == '\0') {
8812 free(line);
8813 line = NULL;
8814 continue;
8816 cmd = NULL;
8817 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8818 cmd = &got_histedit_cmds[i];
8819 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8820 isspace((unsigned char)p[strlen(cmd->name)])) {
8821 p += strlen(cmd->name);
8822 break;
8824 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8825 p++;
8826 break;
8829 if (i == nitems(got_histedit_cmds)) {
8830 err = histedit_syntax_error(lineno);
8831 break;
8833 while (isspace((unsigned char)p[0]))
8834 p++;
8835 if (cmd->code == GOT_HISTEDIT_MESG) {
8836 if (hle == NULL || hle->logmsg != NULL) {
8837 err = got_error(GOT_ERR_HISTEDIT_CMD);
8838 break;
8840 if (p[0] == '\0') {
8841 err = histedit_edit_logmsg(hle, repo);
8842 if (err)
8843 break;
8844 } else {
8845 hle->logmsg = strdup(p);
8846 if (hle->logmsg == NULL) {
8847 err = got_error_from_errno("strdup");
8848 break;
8851 free(line);
8852 line = NULL;
8853 continue;
8854 } else {
8855 end = p;
8856 while (end[0] && !isspace((unsigned char)end[0]))
8857 end++;
8858 *end = '\0';
8860 err = got_object_resolve_id_str(&commit_id, repo, p);
8861 if (err) {
8862 /* override error code */
8863 err = histedit_syntax_error(lineno);
8864 break;
8867 hle = malloc(sizeof(*hle));
8868 if (hle == NULL) {
8869 err = got_error_from_errno("malloc");
8870 break;
8872 hle->cmd = cmd;
8873 hle->commit_id = commit_id;
8874 hle->logmsg = NULL;
8875 commit_id = NULL;
8876 free(line);
8877 line = NULL;
8878 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8881 free(line);
8882 free(commit_id);
8883 return err;
8886 static const struct got_error *
8887 histedit_check_script(struct got_histedit_list *histedit_cmds,
8888 struct got_object_id_queue *commits, struct got_repository *repo)
8890 const struct got_error *err = NULL;
8891 struct got_object_qid *qid;
8892 struct got_histedit_list_entry *hle;
8893 static char msg[92];
8894 char *id_str;
8896 if (TAILQ_EMPTY(histedit_cmds))
8897 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8898 "histedit script contains no commands");
8899 if (STAILQ_EMPTY(commits))
8900 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8902 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8903 struct got_histedit_list_entry *hle2;
8904 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8905 if (hle == hle2)
8906 continue;
8907 if (got_object_id_cmp(hle->commit_id,
8908 hle2->commit_id) != 0)
8909 continue;
8910 err = got_object_id_str(&id_str, hle->commit_id);
8911 if (err)
8912 return err;
8913 snprintf(msg, sizeof(msg), "commit %s is listed "
8914 "more than once in histedit script", id_str);
8915 free(id_str);
8916 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8920 STAILQ_FOREACH(qid, commits, entry) {
8921 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8922 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8923 break;
8925 if (hle == NULL) {
8926 err = got_object_id_str(&id_str, qid->id);
8927 if (err)
8928 return err;
8929 snprintf(msg, sizeof(msg),
8930 "commit %s missing from histedit script", id_str);
8931 free(id_str);
8932 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8936 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8937 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8938 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8939 "last commit in histedit script cannot be folded");
8941 return NULL;
8944 static const struct got_error *
8945 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8946 const char *path, struct got_object_id_queue *commits,
8947 struct got_repository *repo)
8949 const struct got_error *err = NULL;
8950 char *editor;
8951 FILE *f = NULL;
8953 err = get_editor(&editor);
8954 if (err)
8955 return err;
8957 if (spawn_editor(editor, path) == -1) {
8958 err = got_error_from_errno("failed spawning editor");
8959 goto done;
8962 f = fopen(path, "r");
8963 if (f == NULL) {
8964 err = got_error_from_errno("fopen");
8965 goto done;
8967 err = histedit_parse_list(histedit_cmds, f, repo);
8968 if (err)
8969 goto done;
8971 err = histedit_check_script(histedit_cmds, commits, repo);
8972 done:
8973 if (f && fclose(f) == EOF && err == NULL)
8974 err = got_error_from_errno("fclose");
8975 free(editor);
8976 return err;
8979 static const struct got_error *
8980 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8981 struct got_object_id_queue *, const char *, const char *,
8982 struct got_repository *);
8984 static const struct got_error *
8985 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8986 struct got_object_id_queue *commits, const char *branch_name,
8987 int edit_logmsg_only, int fold_only, struct got_repository *repo)
8989 const struct got_error *err;
8990 FILE *f = NULL;
8991 char *path = NULL;
8993 err = got_opentemp_named(&path, &f, "got-histedit");
8994 if (err)
8995 return err;
8997 err = write_cmd_list(f, branch_name, commits);
8998 if (err)
8999 goto done;
9001 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9002 fold_only, repo);
9003 if (err)
9004 goto done;
9006 if (edit_logmsg_only || fold_only) {
9007 rewind(f);
9008 err = histedit_parse_list(histedit_cmds, f, repo);
9009 } else {
9010 if (fclose(f) == EOF) {
9011 err = got_error_from_errno("fclose");
9012 goto done;
9014 f = NULL;
9015 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9016 if (err) {
9017 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9018 err->code != GOT_ERR_HISTEDIT_CMD)
9019 goto done;
9020 err = histedit_edit_list_retry(histedit_cmds, err,
9021 commits, path, branch_name, repo);
9024 done:
9025 if (f && fclose(f) == EOF && err == NULL)
9026 err = got_error_from_errno("fclose");
9027 if (path && unlink(path) != 0 && err == NULL)
9028 err = got_error_from_errno2("unlink", path);
9029 free(path);
9030 return err;
9033 static const struct got_error *
9034 histedit_save_list(struct got_histedit_list *histedit_cmds,
9035 struct got_worktree *worktree, struct got_repository *repo)
9037 const struct got_error *err = NULL;
9038 char *path = NULL;
9039 FILE *f = NULL;
9040 struct got_histedit_list_entry *hle;
9041 struct got_commit_object *commit = NULL;
9043 err = got_worktree_get_histedit_script_path(&path, worktree);
9044 if (err)
9045 return err;
9047 f = fopen(path, "w");
9048 if (f == NULL) {
9049 err = got_error_from_errno2("fopen", path);
9050 goto done;
9052 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9053 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9054 repo);
9055 if (err)
9056 break;
9058 if (hle->logmsg) {
9059 int n = fprintf(f, "%c %s\n",
9060 GOT_HISTEDIT_MESG, hle->logmsg);
9061 if (n < 0) {
9062 err = got_ferror(f, GOT_ERR_IO);
9063 break;
9067 done:
9068 if (f && fclose(f) == EOF && err == NULL)
9069 err = got_error_from_errno("fclose");
9070 free(path);
9071 if (commit)
9072 got_object_commit_close(commit);
9073 return err;
9076 void
9077 histedit_free_list(struct got_histedit_list *histedit_cmds)
9079 struct got_histedit_list_entry *hle;
9081 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9082 TAILQ_REMOVE(histedit_cmds, hle, entry);
9083 free(hle);
9087 static const struct got_error *
9088 histedit_load_list(struct got_histedit_list *histedit_cmds,
9089 const char *path, struct got_repository *repo)
9091 const struct got_error *err = NULL;
9092 FILE *f = NULL;
9094 f = fopen(path, "r");
9095 if (f == NULL) {
9096 err = got_error_from_errno2("fopen", path);
9097 goto done;
9100 err = histedit_parse_list(histedit_cmds, f, repo);
9101 done:
9102 if (f && fclose(f) == EOF && err == NULL)
9103 err = got_error_from_errno("fclose");
9104 return err;
9107 static const struct got_error *
9108 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9109 const struct got_error *edit_err, struct got_object_id_queue *commits,
9110 const char *path, const char *branch_name, struct got_repository *repo)
9112 const struct got_error *err = NULL, *prev_err = edit_err;
9113 int resp = ' ';
9115 while (resp != 'c' && resp != 'r' && resp != 'a') {
9116 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9117 "or (a)bort: ", getprogname(), prev_err->msg);
9118 resp = getchar();
9119 if (resp == '\n')
9120 resp = getchar();
9121 if (resp == 'c') {
9122 histedit_free_list(histedit_cmds);
9123 err = histedit_run_editor(histedit_cmds, path, commits,
9124 repo);
9125 if (err) {
9126 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9127 err->code != GOT_ERR_HISTEDIT_CMD)
9128 break;
9129 prev_err = err;
9130 resp = ' ';
9131 continue;
9133 break;
9134 } else if (resp == 'r') {
9135 histedit_free_list(histedit_cmds);
9136 err = histedit_edit_script(histedit_cmds,
9137 commits, branch_name, 0, 0, repo);
9138 if (err) {
9139 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9140 err->code != GOT_ERR_HISTEDIT_CMD)
9141 break;
9142 prev_err = err;
9143 resp = ' ';
9144 continue;
9146 break;
9147 } else if (resp == 'a') {
9148 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9149 break;
9150 } else
9151 printf("invalid response '%c'\n", resp);
9154 return err;
9157 static const struct got_error *
9158 histedit_complete(struct got_worktree *worktree,
9159 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9160 struct got_reference *branch, struct got_repository *repo)
9162 printf("Switching work tree to %s\n",
9163 got_ref_get_symref_target(branch));
9164 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9165 branch, repo);
9168 static const struct got_error *
9169 show_histedit_progress(struct got_commit_object *commit,
9170 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9172 const struct got_error *err;
9173 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9175 err = got_object_id_str(&old_id_str, hle->commit_id);
9176 if (err)
9177 goto done;
9179 if (new_id) {
9180 err = got_object_id_str(&new_id_str, new_id);
9181 if (err)
9182 goto done;
9185 old_id_str[12] = '\0';
9186 if (new_id_str)
9187 new_id_str[12] = '\0';
9189 if (hle->logmsg) {
9190 logmsg = strdup(hle->logmsg);
9191 if (logmsg == NULL) {
9192 err = got_error_from_errno("strdup");
9193 goto done;
9195 trim_logmsg(logmsg, 42);
9196 } else {
9197 err = get_short_logmsg(&logmsg, 42, commit);
9198 if (err)
9199 goto done;
9202 switch (hle->cmd->code) {
9203 case GOT_HISTEDIT_PICK:
9204 case GOT_HISTEDIT_EDIT:
9205 printf("%s -> %s: %s\n", old_id_str,
9206 new_id_str ? new_id_str : "no-op change", logmsg);
9207 break;
9208 case GOT_HISTEDIT_DROP:
9209 case GOT_HISTEDIT_FOLD:
9210 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9211 logmsg);
9212 break;
9213 default:
9214 break;
9216 done:
9217 free(old_id_str);
9218 free(new_id_str);
9219 return err;
9222 static const struct got_error *
9223 histedit_commit(struct got_pathlist_head *merged_paths,
9224 struct got_worktree *worktree, struct got_fileindex *fileindex,
9225 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9226 struct got_repository *repo)
9228 const struct got_error *err;
9229 struct got_commit_object *commit;
9230 struct got_object_id *new_commit_id;
9232 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9233 && hle->logmsg == NULL) {
9234 err = histedit_edit_logmsg(hle, repo);
9235 if (err)
9236 return err;
9239 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9240 if (err)
9241 return err;
9243 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9244 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9245 hle->logmsg, repo);
9246 if (err) {
9247 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9248 goto done;
9249 err = show_histedit_progress(commit, hle, NULL);
9250 } else {
9251 err = show_histedit_progress(commit, hle, new_commit_id);
9252 free(new_commit_id);
9254 done:
9255 got_object_commit_close(commit);
9256 return err;
9259 static const struct got_error *
9260 histedit_skip_commit(struct got_histedit_list_entry *hle,
9261 struct got_worktree *worktree, struct got_repository *repo)
9263 const struct got_error *error;
9264 struct got_commit_object *commit;
9266 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9267 repo);
9268 if (error)
9269 return error;
9271 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9272 if (error)
9273 return error;
9275 error = show_histedit_progress(commit, hle, NULL);
9276 got_object_commit_close(commit);
9277 return error;
9280 static const struct got_error *
9281 check_local_changes(void *arg, unsigned char status,
9282 unsigned char staged_status, const char *path,
9283 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9284 struct got_object_id *commit_id, int dirfd, const char *de_name)
9286 int *have_local_changes = arg;
9288 switch (status) {
9289 case GOT_STATUS_ADD:
9290 case GOT_STATUS_DELETE:
9291 case GOT_STATUS_MODIFY:
9292 case GOT_STATUS_CONFLICT:
9293 *have_local_changes = 1;
9294 return got_error(GOT_ERR_CANCELLED);
9295 default:
9296 break;
9299 switch (staged_status) {
9300 case GOT_STATUS_ADD:
9301 case GOT_STATUS_DELETE:
9302 case GOT_STATUS_MODIFY:
9303 *have_local_changes = 1;
9304 return got_error(GOT_ERR_CANCELLED);
9305 default:
9306 break;
9309 return NULL;
9312 static const struct got_error *
9313 cmd_histedit(int argc, char *argv[])
9315 const struct got_error *error = NULL;
9316 struct got_worktree *worktree = NULL;
9317 struct got_fileindex *fileindex = NULL;
9318 struct got_repository *repo = NULL;
9319 char *cwd = NULL;
9320 struct got_reference *branch = NULL;
9321 struct got_reference *tmp_branch = NULL;
9322 struct got_object_id *resume_commit_id = NULL;
9323 struct got_object_id *base_commit_id = NULL;
9324 struct got_object_id *head_commit_id = NULL;
9325 struct got_commit_object *commit = NULL;
9326 int ch, rebase_in_progress = 0;
9327 struct got_update_progress_arg upa;
9328 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9329 int edit_logmsg_only = 0, fold_only = 0;
9330 int list_backups = 0, delete_backups = 0;
9331 const char *edit_script_path = NULL;
9332 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9333 struct got_object_id_queue commits;
9334 struct got_pathlist_head merged_paths;
9335 const struct got_object_id_queue *parent_ids;
9336 struct got_object_qid *pid;
9337 struct got_histedit_list histedit_cmds;
9338 struct got_histedit_list_entry *hle;
9340 STAILQ_INIT(&commits);
9341 TAILQ_INIT(&histedit_cmds);
9342 TAILQ_INIT(&merged_paths);
9343 memset(&upa, 0, sizeof(upa));
9345 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9346 switch (ch) {
9347 case 'a':
9348 abort_edit = 1;
9349 break;
9350 case 'c':
9351 continue_edit = 1;
9352 break;
9353 case 'f':
9354 fold_only = 1;
9355 break;
9356 case 'F':
9357 edit_script_path = optarg;
9358 break;
9359 case 'm':
9360 edit_logmsg_only = 1;
9361 break;
9362 case 'l':
9363 list_backups = 1;
9364 break;
9365 case 'X':
9366 delete_backups = 1;
9367 break;
9368 default:
9369 usage_histedit();
9370 /* NOTREACHED */
9374 argc -= optind;
9375 argv += optind;
9377 #ifndef PROFILE
9378 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9379 "unveil", NULL) == -1)
9380 err(1, "pledge");
9381 #endif
9382 if (abort_edit && continue_edit)
9383 option_conflict('a', 'c');
9384 if (edit_script_path && edit_logmsg_only)
9385 option_conflict('F', 'm');
9386 if (abort_edit && edit_logmsg_only)
9387 option_conflict('a', 'm');
9388 if (continue_edit && edit_logmsg_only)
9389 option_conflict('c', 'm');
9390 if (abort_edit && fold_only)
9391 option_conflict('a', 'f');
9392 if (continue_edit && fold_only)
9393 option_conflict('c', 'f');
9394 if (fold_only && edit_logmsg_only)
9395 option_conflict('f', 'm');
9396 if (edit_script_path && fold_only)
9397 option_conflict('F', 'f');
9398 if (list_backups) {
9399 if (abort_edit)
9400 option_conflict('l', 'a');
9401 if (continue_edit)
9402 option_conflict('l', 'c');
9403 if (edit_script_path)
9404 option_conflict('l', 'F');
9405 if (edit_logmsg_only)
9406 option_conflict('l', 'm');
9407 if (fold_only)
9408 option_conflict('l', 'f');
9409 if (delete_backups)
9410 option_conflict('l', 'X');
9411 if (argc != 0 && argc != 1)
9412 usage_histedit();
9413 } else if (delete_backups) {
9414 if (abort_edit)
9415 option_conflict('X', 'a');
9416 if (continue_edit)
9417 option_conflict('X', 'c');
9418 if (edit_script_path)
9419 option_conflict('X', 'F');
9420 if (edit_logmsg_only)
9421 option_conflict('X', 'm');
9422 if (fold_only)
9423 option_conflict('X', 'f');
9424 if (list_backups)
9425 option_conflict('X', 'l');
9426 if (argc != 0 && argc != 1)
9427 usage_histedit();
9428 } else if (argc != 0)
9429 usage_histedit();
9432 * This command cannot apply unveil(2) in all cases because the
9433 * user may choose to run an editor to edit the histedit script
9434 * and to edit individual commit log messages.
9435 * unveil(2) traverses exec(2); if an editor is used we have to
9436 * apply unveil after edit script and log messages have been written.
9437 * XXX TODO: Make use of unveil(2) where possible.
9440 cwd = getcwd(NULL, 0);
9441 if (cwd == NULL) {
9442 error = got_error_from_errno("getcwd");
9443 goto done;
9445 error = got_worktree_open(&worktree, cwd);
9446 if (error) {
9447 if (list_backups || delete_backups) {
9448 if (error->code != GOT_ERR_NOT_WORKTREE)
9449 goto done;
9450 } else {
9451 if (error->code == GOT_ERR_NOT_WORKTREE)
9452 error = wrap_not_worktree_error(error,
9453 "histedit", cwd);
9454 goto done;
9458 if (list_backups || delete_backups) {
9459 error = got_repo_open(&repo,
9460 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9461 NULL);
9462 if (error != NULL)
9463 goto done;
9464 error = apply_unveil(got_repo_get_path(repo), 0,
9465 worktree ? got_worktree_get_root_path(worktree) : NULL);
9466 if (error)
9467 goto done;
9468 error = process_backup_refs(
9469 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9470 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9471 goto done; /* nothing else to do */
9474 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9475 NULL);
9476 if (error != NULL)
9477 goto done;
9479 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9480 if (error)
9481 goto done;
9482 if (rebase_in_progress) {
9483 error = got_error(GOT_ERR_REBASING);
9484 goto done;
9487 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9488 if (error)
9489 goto done;
9491 if (edit_in_progress && edit_logmsg_only) {
9492 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9493 "histedit operation is in progress in this "
9494 "work tree and must be continued or aborted "
9495 "before the -m option can be used");
9496 goto done;
9498 if (edit_in_progress && fold_only) {
9499 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9500 "histedit operation is in progress in this "
9501 "work tree and must be continued or aborted "
9502 "before the -f option can be used");
9503 goto done;
9506 if (edit_in_progress && abort_edit) {
9507 error = got_worktree_histedit_continue(&resume_commit_id,
9508 &tmp_branch, &branch, &base_commit_id, &fileindex,
9509 worktree, repo);
9510 if (error)
9511 goto done;
9512 printf("Switching work tree to %s\n",
9513 got_ref_get_symref_target(branch));
9514 error = got_worktree_histedit_abort(worktree, fileindex, repo,
9515 branch, base_commit_id, update_progress, &upa);
9516 if (error)
9517 goto done;
9518 printf("Histedit of %s aborted\n",
9519 got_ref_get_symref_target(branch));
9520 print_update_progress_stats(&upa);
9521 goto done; /* nothing else to do */
9522 } else if (abort_edit) {
9523 error = got_error(GOT_ERR_NOT_HISTEDIT);
9524 goto done;
9527 if (continue_edit) {
9528 char *path;
9530 if (!edit_in_progress) {
9531 error = got_error(GOT_ERR_NOT_HISTEDIT);
9532 goto done;
9535 error = got_worktree_get_histedit_script_path(&path, worktree);
9536 if (error)
9537 goto done;
9539 error = histedit_load_list(&histedit_cmds, path, repo);
9540 free(path);
9541 if (error)
9542 goto done;
9544 error = got_worktree_histedit_continue(&resume_commit_id,
9545 &tmp_branch, &branch, &base_commit_id, &fileindex,
9546 worktree, repo);
9547 if (error)
9548 goto done;
9550 error = got_ref_resolve(&head_commit_id, repo, branch);
9551 if (error)
9552 goto done;
9554 error = got_object_open_as_commit(&commit, repo,
9555 head_commit_id);
9556 if (error)
9557 goto done;
9558 parent_ids = got_object_commit_get_parent_ids(commit);
9559 pid = STAILQ_FIRST(parent_ids);
9560 if (pid == NULL) {
9561 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9562 goto done;
9564 error = collect_commits(&commits, head_commit_id, pid->id,
9565 base_commit_id, got_worktree_get_path_prefix(worktree),
9566 GOT_ERR_HISTEDIT_PATH, repo);
9567 got_object_commit_close(commit);
9568 commit = NULL;
9569 if (error)
9570 goto done;
9571 } else {
9572 if (edit_in_progress) {
9573 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9574 goto done;
9577 error = got_ref_open(&branch, repo,
9578 got_worktree_get_head_ref_name(worktree), 0);
9579 if (error != NULL)
9580 goto done;
9582 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
9583 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
9584 "will not edit commit history of a branch outside "
9585 "the \"refs/heads/\" reference namespace");
9586 goto done;
9589 error = got_ref_resolve(&head_commit_id, repo, branch);
9590 got_ref_close(branch);
9591 branch = NULL;
9592 if (error)
9593 goto done;
9595 error = got_object_open_as_commit(&commit, repo,
9596 head_commit_id);
9597 if (error)
9598 goto done;
9599 parent_ids = got_object_commit_get_parent_ids(commit);
9600 pid = STAILQ_FIRST(parent_ids);
9601 if (pid == NULL) {
9602 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9603 goto done;
9605 error = collect_commits(&commits, head_commit_id, pid->id,
9606 got_worktree_get_base_commit_id(worktree),
9607 got_worktree_get_path_prefix(worktree),
9608 GOT_ERR_HISTEDIT_PATH, repo);
9609 got_object_commit_close(commit);
9610 commit = NULL;
9611 if (error)
9612 goto done;
9614 if (STAILQ_EMPTY(&commits)) {
9615 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
9616 goto done;
9619 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
9620 &base_commit_id, &fileindex, worktree, repo);
9621 if (error)
9622 goto done;
9624 if (edit_script_path) {
9625 error = histedit_load_list(&histedit_cmds,
9626 edit_script_path, repo);
9627 if (error) {
9628 got_worktree_histedit_abort(worktree, fileindex,
9629 repo, branch, base_commit_id,
9630 update_progress, &upa);
9631 print_update_progress_stats(&upa);
9632 goto done;
9634 } else {
9635 const char *branch_name;
9636 branch_name = got_ref_get_symref_target(branch);
9637 if (strncmp(branch_name, "refs/heads/", 11) == 0)
9638 branch_name += 11;
9639 error = histedit_edit_script(&histedit_cmds, &commits,
9640 branch_name, edit_logmsg_only, fold_only, repo);
9641 if (error) {
9642 got_worktree_histedit_abort(worktree, fileindex,
9643 repo, branch, base_commit_id,
9644 update_progress, &upa);
9645 print_update_progress_stats(&upa);
9646 goto done;
9651 error = histedit_save_list(&histedit_cmds, worktree,
9652 repo);
9653 if (error) {
9654 got_worktree_histedit_abort(worktree, fileindex,
9655 repo, branch, base_commit_id,
9656 update_progress, &upa);
9657 print_update_progress_stats(&upa);
9658 goto done;
9663 error = histedit_check_script(&histedit_cmds, &commits, repo);
9664 if (error)
9665 goto done;
9667 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
9668 if (resume_commit_id) {
9669 if (got_object_id_cmp(hle->commit_id,
9670 resume_commit_id) != 0)
9671 continue;
9673 resume_commit_id = NULL;
9674 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
9675 hle->cmd->code == GOT_HISTEDIT_FOLD) {
9676 error = histedit_skip_commit(hle, worktree,
9677 repo);
9678 if (error)
9679 goto done;
9680 } else {
9681 struct got_pathlist_head paths;
9682 int have_changes = 0;
9684 TAILQ_INIT(&paths);
9685 error = got_pathlist_append(&paths, "", NULL);
9686 if (error)
9687 goto done;
9688 error = got_worktree_status(worktree, &paths,
9689 repo, 0, check_local_changes, &have_changes,
9690 check_cancelled, NULL);
9691 got_pathlist_free(&paths);
9692 if (error) {
9693 if (error->code != GOT_ERR_CANCELLED)
9694 goto done;
9695 if (sigint_received || sigpipe_received)
9696 goto done;
9698 if (have_changes) {
9699 error = histedit_commit(NULL, worktree,
9700 fileindex, tmp_branch, hle, repo);
9701 if (error)
9702 goto done;
9703 } else {
9704 error = got_object_open_as_commit(
9705 &commit, repo, hle->commit_id);
9706 if (error)
9707 goto done;
9708 error = show_histedit_progress(commit,
9709 hle, NULL);
9710 got_object_commit_close(commit);
9711 commit = NULL;
9712 if (error)
9713 goto done;
9716 continue;
9719 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
9720 error = histedit_skip_commit(hle, worktree, repo);
9721 if (error)
9722 goto done;
9723 continue;
9726 error = got_object_open_as_commit(&commit, repo,
9727 hle->commit_id);
9728 if (error)
9729 goto done;
9730 parent_ids = got_object_commit_get_parent_ids(commit);
9731 pid = STAILQ_FIRST(parent_ids);
9733 error = got_worktree_histedit_merge_files(&merged_paths,
9734 worktree, fileindex, pid->id, hle->commit_id, repo,
9735 update_progress, &upa, check_cancelled, NULL);
9736 if (error)
9737 goto done;
9738 got_object_commit_close(commit);
9739 commit = NULL;
9741 print_update_progress_stats(&upa);
9742 if (upa.conflicts > 0)
9743 rebase_status = GOT_STATUS_CONFLICT;
9745 if (rebase_status == GOT_STATUS_CONFLICT) {
9746 error = show_rebase_merge_conflict(hle->commit_id,
9747 repo);
9748 if (error)
9749 goto done;
9750 got_worktree_rebase_pathlist_free(&merged_paths);
9751 break;
9754 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
9755 char *id_str;
9756 error = got_object_id_str(&id_str, hle->commit_id);
9757 if (error)
9758 goto done;
9759 printf("Stopping histedit for amending commit %s\n",
9760 id_str);
9761 free(id_str);
9762 got_worktree_rebase_pathlist_free(&merged_paths);
9763 error = got_worktree_histedit_postpone(worktree,
9764 fileindex);
9765 goto done;
9768 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
9769 error = histedit_skip_commit(hle, worktree, repo);
9770 if (error)
9771 goto done;
9772 continue;
9775 error = histedit_commit(&merged_paths, worktree, fileindex,
9776 tmp_branch, hle, repo);
9777 got_worktree_rebase_pathlist_free(&merged_paths);
9778 if (error)
9779 goto done;
9782 if (rebase_status == GOT_STATUS_CONFLICT) {
9783 error = got_worktree_histedit_postpone(worktree, fileindex);
9784 if (error)
9785 goto done;
9786 error = got_error_msg(GOT_ERR_CONFLICTS,
9787 "conflicts must be resolved before histedit can continue");
9788 } else
9789 error = histedit_complete(worktree, fileindex, tmp_branch,
9790 branch, repo);
9791 done:
9792 got_object_id_queue_free(&commits);
9793 histedit_free_list(&histedit_cmds);
9794 free(head_commit_id);
9795 free(base_commit_id);
9796 free(resume_commit_id);
9797 if (commit)
9798 got_object_commit_close(commit);
9799 if (branch)
9800 got_ref_close(branch);
9801 if (tmp_branch)
9802 got_ref_close(tmp_branch);
9803 if (worktree)
9804 got_worktree_close(worktree);
9805 if (repo) {
9806 const struct got_error *close_err = got_repo_close(repo);
9807 if (error == NULL)
9808 error = close_err;
9810 return error;
9813 __dead static void
9814 usage_integrate(void)
9816 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
9817 exit(1);
9820 static const struct got_error *
9821 cmd_integrate(int argc, char *argv[])
9823 const struct got_error *error = NULL;
9824 struct got_repository *repo = NULL;
9825 struct got_worktree *worktree = NULL;
9826 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
9827 const char *branch_arg = NULL;
9828 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
9829 struct got_fileindex *fileindex = NULL;
9830 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
9831 int ch;
9832 struct got_update_progress_arg upa;
9834 while ((ch = getopt(argc, argv, "")) != -1) {
9835 switch (ch) {
9836 default:
9837 usage_integrate();
9838 /* NOTREACHED */
9842 argc -= optind;
9843 argv += optind;
9845 if (argc != 1)
9846 usage_integrate();
9847 branch_arg = argv[0];
9848 #ifndef PROFILE
9849 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9850 "unveil", NULL) == -1)
9851 err(1, "pledge");
9852 #endif
9853 cwd = getcwd(NULL, 0);
9854 if (cwd == NULL) {
9855 error = got_error_from_errno("getcwd");
9856 goto done;
9859 error = got_worktree_open(&worktree, cwd);
9860 if (error) {
9861 if (error->code == GOT_ERR_NOT_WORKTREE)
9862 error = wrap_not_worktree_error(error, "integrate",
9863 cwd);
9864 goto done;
9867 error = check_rebase_or_histedit_in_progress(worktree);
9868 if (error)
9869 goto done;
9871 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9872 NULL);
9873 if (error != NULL)
9874 goto done;
9876 error = apply_unveil(got_repo_get_path(repo), 0,
9877 got_worktree_get_root_path(worktree));
9878 if (error)
9879 goto done;
9881 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9882 error = got_error_from_errno("asprintf");
9883 goto done;
9886 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9887 &base_branch_ref, worktree, refname, repo);
9888 if (error)
9889 goto done;
9891 refname = strdup(got_ref_get_name(branch_ref));
9892 if (refname == NULL) {
9893 error = got_error_from_errno("strdup");
9894 got_worktree_integrate_abort(worktree, fileindex, repo,
9895 branch_ref, base_branch_ref);
9896 goto done;
9898 base_refname = strdup(got_ref_get_name(base_branch_ref));
9899 if (base_refname == NULL) {
9900 error = got_error_from_errno("strdup");
9901 got_worktree_integrate_abort(worktree, fileindex, repo,
9902 branch_ref, base_branch_ref);
9903 goto done;
9906 error = got_ref_resolve(&commit_id, repo, branch_ref);
9907 if (error)
9908 goto done;
9910 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9911 if (error)
9912 goto done;
9914 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9915 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9916 "specified branch has already been integrated");
9917 got_worktree_integrate_abort(worktree, fileindex, repo,
9918 branch_ref, base_branch_ref);
9919 goto done;
9922 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9923 if (error) {
9924 if (error->code == GOT_ERR_ANCESTRY)
9925 error = got_error(GOT_ERR_REBASE_REQUIRED);
9926 got_worktree_integrate_abort(worktree, fileindex, repo,
9927 branch_ref, base_branch_ref);
9928 goto done;
9931 memset(&upa, 0, sizeof(upa));
9932 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9933 branch_ref, base_branch_ref, update_progress, &upa,
9934 check_cancelled, NULL);
9935 if (error)
9936 goto done;
9938 printf("Integrated %s into %s\n", refname, base_refname);
9939 print_update_progress_stats(&upa);
9940 done:
9941 if (repo) {
9942 const struct got_error *close_err = got_repo_close(repo);
9943 if (error == NULL)
9944 error = close_err;
9946 if (worktree)
9947 got_worktree_close(worktree);
9948 free(cwd);
9949 free(base_commit_id);
9950 free(commit_id);
9951 free(refname);
9952 free(base_refname);
9953 return error;
9956 __dead static void
9957 usage_stage(void)
9959 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9960 "[-S] [file-path ...]\n",
9961 getprogname());
9962 exit(1);
9965 static const struct got_error *
9966 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9967 const char *path, struct got_object_id *blob_id,
9968 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9969 int dirfd, const char *de_name)
9971 const struct got_error *err = NULL;
9972 char *id_str = NULL;
9974 if (staged_status != GOT_STATUS_ADD &&
9975 staged_status != GOT_STATUS_MODIFY &&
9976 staged_status != GOT_STATUS_DELETE)
9977 return NULL;
9979 if (staged_status == GOT_STATUS_ADD ||
9980 staged_status == GOT_STATUS_MODIFY)
9981 err = got_object_id_str(&id_str, staged_blob_id);
9982 else
9983 err = got_object_id_str(&id_str, blob_id);
9984 if (err)
9985 return err;
9987 printf("%s %c %s\n", id_str, staged_status, path);
9988 free(id_str);
9989 return NULL;
9992 static const struct got_error *
9993 cmd_stage(int argc, char *argv[])
9995 const struct got_error *error = NULL;
9996 struct got_repository *repo = NULL;
9997 struct got_worktree *worktree = NULL;
9998 char *cwd = NULL;
9999 struct got_pathlist_head paths;
10000 struct got_pathlist_entry *pe;
10001 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10002 FILE *patch_script_file = NULL;
10003 const char *patch_script_path = NULL;
10004 struct choose_patch_arg cpa;
10006 TAILQ_INIT(&paths);
10008 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10009 switch (ch) {
10010 case 'l':
10011 list_stage = 1;
10012 break;
10013 case 'p':
10014 pflag = 1;
10015 break;
10016 case 'F':
10017 patch_script_path = optarg;
10018 break;
10019 case 'S':
10020 allow_bad_symlinks = 1;
10021 break;
10022 default:
10023 usage_stage();
10024 /* NOTREACHED */
10028 argc -= optind;
10029 argv += optind;
10031 #ifndef PROFILE
10032 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10033 "unveil", NULL) == -1)
10034 err(1, "pledge");
10035 #endif
10036 if (list_stage && (pflag || patch_script_path))
10037 errx(1, "-l option cannot be used with other options");
10038 if (patch_script_path && !pflag)
10039 errx(1, "-F option can only be used together with -p option");
10041 cwd = getcwd(NULL, 0);
10042 if (cwd == NULL) {
10043 error = got_error_from_errno("getcwd");
10044 goto done;
10047 error = got_worktree_open(&worktree, cwd);
10048 if (error) {
10049 if (error->code == GOT_ERR_NOT_WORKTREE)
10050 error = wrap_not_worktree_error(error, "stage", cwd);
10051 goto done;
10054 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10055 NULL);
10056 if (error != NULL)
10057 goto done;
10059 if (patch_script_path) {
10060 patch_script_file = fopen(patch_script_path, "r");
10061 if (patch_script_file == NULL) {
10062 error = got_error_from_errno2("fopen",
10063 patch_script_path);
10064 goto done;
10067 error = apply_unveil(got_repo_get_path(repo), 0,
10068 got_worktree_get_root_path(worktree));
10069 if (error)
10070 goto done;
10072 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10073 if (error)
10074 goto done;
10076 if (list_stage)
10077 error = got_worktree_status(worktree, &paths, repo, 0,
10078 print_stage, NULL, check_cancelled, NULL);
10079 else {
10080 cpa.patch_script_file = patch_script_file;
10081 cpa.action = "stage";
10082 error = got_worktree_stage(worktree, &paths,
10083 pflag ? NULL : print_status, NULL,
10084 pflag ? choose_patch : NULL, &cpa,
10085 allow_bad_symlinks, repo);
10087 done:
10088 if (patch_script_file && fclose(patch_script_file) == EOF &&
10089 error == NULL)
10090 error = got_error_from_errno2("fclose", patch_script_path);
10091 if (repo) {
10092 const struct got_error *close_err = got_repo_close(repo);
10093 if (error == NULL)
10094 error = close_err;
10096 if (worktree)
10097 got_worktree_close(worktree);
10098 TAILQ_FOREACH(pe, &paths, entry)
10099 free((char *)pe->path);
10100 got_pathlist_free(&paths);
10101 free(cwd);
10102 return error;
10105 __dead static void
10106 usage_unstage(void)
10108 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10109 "[file-path ...]\n",
10110 getprogname());
10111 exit(1);
10115 static const struct got_error *
10116 cmd_unstage(int argc, char *argv[])
10118 const struct got_error *error = NULL;
10119 struct got_repository *repo = NULL;
10120 struct got_worktree *worktree = NULL;
10121 char *cwd = NULL;
10122 struct got_pathlist_head paths;
10123 struct got_pathlist_entry *pe;
10124 int ch, pflag = 0;
10125 struct got_update_progress_arg upa;
10126 FILE *patch_script_file = NULL;
10127 const char *patch_script_path = NULL;
10128 struct choose_patch_arg cpa;
10130 TAILQ_INIT(&paths);
10132 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10133 switch (ch) {
10134 case 'p':
10135 pflag = 1;
10136 break;
10137 case 'F':
10138 patch_script_path = optarg;
10139 break;
10140 default:
10141 usage_unstage();
10142 /* NOTREACHED */
10146 argc -= optind;
10147 argv += optind;
10149 #ifndef PROFILE
10150 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10151 "unveil", NULL) == -1)
10152 err(1, "pledge");
10153 #endif
10154 if (patch_script_path && !pflag)
10155 errx(1, "-F option can only be used together with -p option");
10157 cwd = getcwd(NULL, 0);
10158 if (cwd == NULL) {
10159 error = got_error_from_errno("getcwd");
10160 goto done;
10163 error = got_worktree_open(&worktree, cwd);
10164 if (error) {
10165 if (error->code == GOT_ERR_NOT_WORKTREE)
10166 error = wrap_not_worktree_error(error, "unstage", cwd);
10167 goto done;
10170 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10171 NULL);
10172 if (error != NULL)
10173 goto done;
10175 if (patch_script_path) {
10176 patch_script_file = fopen(patch_script_path, "r");
10177 if (patch_script_file == NULL) {
10178 error = got_error_from_errno2("fopen",
10179 patch_script_path);
10180 goto done;
10184 error = apply_unveil(got_repo_get_path(repo), 0,
10185 got_worktree_get_root_path(worktree));
10186 if (error)
10187 goto done;
10189 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10190 if (error)
10191 goto done;
10193 cpa.patch_script_file = patch_script_file;
10194 cpa.action = "unstage";
10195 memset(&upa, 0, sizeof(upa));
10196 error = got_worktree_unstage(worktree, &paths, update_progress,
10197 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10198 if (!error)
10199 print_update_progress_stats(&upa);
10200 done:
10201 if (patch_script_file && fclose(patch_script_file) == EOF &&
10202 error == NULL)
10203 error = got_error_from_errno2("fclose", patch_script_path);
10204 if (repo) {
10205 const struct got_error *close_err = got_repo_close(repo);
10206 if (error == NULL)
10207 error = close_err;
10209 if (worktree)
10210 got_worktree_close(worktree);
10211 TAILQ_FOREACH(pe, &paths, entry)
10212 free((char *)pe->path);
10213 got_pathlist_free(&paths);
10214 free(cwd);
10215 return error;
10218 __dead static void
10219 usage_cat(void)
10221 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10222 "arg1 [arg2 ...]\n", getprogname());
10223 exit(1);
10226 static const struct got_error *
10227 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10229 const struct got_error *err;
10230 struct got_blob_object *blob;
10232 err = got_object_open_as_blob(&blob, repo, id, 8192);
10233 if (err)
10234 return err;
10236 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10237 got_object_blob_close(blob);
10238 return err;
10241 static const struct got_error *
10242 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10244 const struct got_error *err;
10245 struct got_tree_object *tree;
10246 int nentries, i;
10248 err = got_object_open_as_tree(&tree, repo, id);
10249 if (err)
10250 return err;
10252 nentries = got_object_tree_get_nentries(tree);
10253 for (i = 0; i < nentries; i++) {
10254 struct got_tree_entry *te;
10255 char *id_str;
10256 if (sigint_received || sigpipe_received)
10257 break;
10258 te = got_object_tree_get_entry(tree, i);
10259 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10260 if (err)
10261 break;
10262 fprintf(outfile, "%s %.7o %s\n", id_str,
10263 got_tree_entry_get_mode(te),
10264 got_tree_entry_get_name(te));
10265 free(id_str);
10268 got_object_tree_close(tree);
10269 return err;
10272 static const struct got_error *
10273 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10275 const struct got_error *err;
10276 struct got_commit_object *commit;
10277 const struct got_object_id_queue *parent_ids;
10278 struct got_object_qid *pid;
10279 char *id_str = NULL;
10280 const char *logmsg = NULL;
10282 err = got_object_open_as_commit(&commit, repo, id);
10283 if (err)
10284 return err;
10286 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10287 if (err)
10288 goto done;
10290 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10291 parent_ids = got_object_commit_get_parent_ids(commit);
10292 fprintf(outfile, "numparents %d\n",
10293 got_object_commit_get_nparents(commit));
10294 STAILQ_FOREACH(pid, parent_ids, entry) {
10295 char *pid_str;
10296 err = got_object_id_str(&pid_str, pid->id);
10297 if (err)
10298 goto done;
10299 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10300 free(pid_str);
10302 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10303 got_object_commit_get_author(commit),
10304 (long long)got_object_commit_get_author_time(commit));
10306 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10307 got_object_commit_get_author(commit),
10308 (long long)got_object_commit_get_committer_time(commit));
10310 logmsg = got_object_commit_get_logmsg_raw(commit);
10311 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10312 fprintf(outfile, "%s", logmsg);
10313 done:
10314 free(id_str);
10315 got_object_commit_close(commit);
10316 return err;
10319 static const struct got_error *
10320 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10322 const struct got_error *err;
10323 struct got_tag_object *tag;
10324 char *id_str = NULL;
10325 const char *tagmsg = NULL;
10327 err = got_object_open_as_tag(&tag, repo, id);
10328 if (err)
10329 return err;
10331 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10332 if (err)
10333 goto done;
10335 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10337 switch (got_object_tag_get_object_type(tag)) {
10338 case GOT_OBJ_TYPE_BLOB:
10339 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10340 GOT_OBJ_LABEL_BLOB);
10341 break;
10342 case GOT_OBJ_TYPE_TREE:
10343 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10344 GOT_OBJ_LABEL_TREE);
10345 break;
10346 case GOT_OBJ_TYPE_COMMIT:
10347 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10348 GOT_OBJ_LABEL_COMMIT);
10349 break;
10350 case GOT_OBJ_TYPE_TAG:
10351 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10352 GOT_OBJ_LABEL_TAG);
10353 break;
10354 default:
10355 break;
10358 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10359 got_object_tag_get_name(tag));
10361 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10362 got_object_tag_get_tagger(tag),
10363 (long long)got_object_tag_get_tagger_time(tag));
10365 tagmsg = got_object_tag_get_message(tag);
10366 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10367 fprintf(outfile, "%s", tagmsg);
10368 done:
10369 free(id_str);
10370 got_object_tag_close(tag);
10371 return err;
10374 static const struct got_error *
10375 cmd_cat(int argc, char *argv[])
10377 const struct got_error *error;
10378 struct got_repository *repo = NULL;
10379 struct got_worktree *worktree = NULL;
10380 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10381 const char *commit_id_str = NULL;
10382 struct got_object_id *id = NULL, *commit_id = NULL;
10383 int ch, obj_type, i, force_path = 0;
10384 struct got_reflist_head refs;
10386 TAILQ_INIT(&refs);
10388 #ifndef PROFILE
10389 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10390 NULL) == -1)
10391 err(1, "pledge");
10392 #endif
10394 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10395 switch (ch) {
10396 case 'c':
10397 commit_id_str = optarg;
10398 break;
10399 case 'r':
10400 repo_path = realpath(optarg, NULL);
10401 if (repo_path == NULL)
10402 return got_error_from_errno2("realpath",
10403 optarg);
10404 got_path_strip_trailing_slashes(repo_path);
10405 break;
10406 case 'P':
10407 force_path = 1;
10408 break;
10409 default:
10410 usage_cat();
10411 /* NOTREACHED */
10415 argc -= optind;
10416 argv += optind;
10418 cwd = getcwd(NULL, 0);
10419 if (cwd == NULL) {
10420 error = got_error_from_errno("getcwd");
10421 goto done;
10423 error = got_worktree_open(&worktree, cwd);
10424 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10425 goto done;
10426 if (worktree) {
10427 if (repo_path == NULL) {
10428 repo_path = strdup(
10429 got_worktree_get_repo_path(worktree));
10430 if (repo_path == NULL) {
10431 error = got_error_from_errno("strdup");
10432 goto done;
10437 if (repo_path == NULL) {
10438 repo_path = getcwd(NULL, 0);
10439 if (repo_path == NULL)
10440 return got_error_from_errno("getcwd");
10443 error = got_repo_open(&repo, repo_path, NULL);
10444 free(repo_path);
10445 if (error != NULL)
10446 goto done;
10448 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10449 if (error)
10450 goto done;
10452 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10453 if (error)
10454 goto done;
10456 if (commit_id_str == NULL)
10457 commit_id_str = GOT_REF_HEAD;
10458 error = got_repo_match_object_id(&commit_id, NULL,
10459 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10460 if (error)
10461 goto done;
10463 for (i = 0; i < argc; i++) {
10464 if (force_path) {
10465 error = got_object_id_by_path(&id, repo, commit_id,
10466 argv[i]);
10467 if (error)
10468 break;
10469 } else {
10470 error = got_repo_match_object_id(&id, &label, argv[i],
10471 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10472 repo);
10473 if (error) {
10474 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10475 error->code != GOT_ERR_NOT_REF)
10476 break;
10477 error = got_object_id_by_path(&id, repo,
10478 commit_id, argv[i]);
10479 if (error)
10480 break;
10484 error = got_object_get_type(&obj_type, repo, id);
10485 if (error)
10486 break;
10488 switch (obj_type) {
10489 case GOT_OBJ_TYPE_BLOB:
10490 error = cat_blob(id, repo, stdout);
10491 break;
10492 case GOT_OBJ_TYPE_TREE:
10493 error = cat_tree(id, repo, stdout);
10494 break;
10495 case GOT_OBJ_TYPE_COMMIT:
10496 error = cat_commit(id, repo, stdout);
10497 break;
10498 case GOT_OBJ_TYPE_TAG:
10499 error = cat_tag(id, repo, stdout);
10500 break;
10501 default:
10502 error = got_error(GOT_ERR_OBJ_TYPE);
10503 break;
10505 if (error)
10506 break;
10507 free(label);
10508 label = NULL;
10509 free(id);
10510 id = NULL;
10512 done:
10513 free(label);
10514 free(id);
10515 free(commit_id);
10516 if (worktree)
10517 got_worktree_close(worktree);
10518 if (repo) {
10519 const struct got_error *close_err = got_repo_close(repo);
10520 if (error == NULL)
10521 error = close_err;
10523 got_ref_list_free(&refs);
10524 return error;
10527 __dead static void
10528 usage_info(void)
10530 fprintf(stderr, "usage: %s info [path ...]\n",
10531 getprogname());
10532 exit(1);
10535 static const struct got_error *
10536 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
10537 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10538 struct got_object_id *commit_id)
10540 const struct got_error *err = NULL;
10541 char *id_str = NULL;
10542 char datebuf[128];
10543 struct tm mytm, *tm;
10544 struct got_pathlist_head *paths = arg;
10545 struct got_pathlist_entry *pe;
10548 * Clear error indication from any of the path arguments which
10549 * would cause this file index entry to be displayed.
10551 TAILQ_FOREACH(pe, paths, entry) {
10552 if (got_path_cmp(path, pe->path, strlen(path),
10553 pe->path_len) == 0 ||
10554 got_path_is_child(path, pe->path, pe->path_len))
10555 pe->data = NULL; /* no error */
10558 printf(GOT_COMMIT_SEP_STR);
10559 if (S_ISLNK(mode))
10560 printf("symlink: %s\n", path);
10561 else if (S_ISREG(mode)) {
10562 printf("file: %s\n", path);
10563 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
10564 } else if (S_ISDIR(mode))
10565 printf("directory: %s\n", path);
10566 else
10567 printf("something: %s\n", path);
10569 tm = localtime_r(&mtime, &mytm);
10570 if (tm == NULL)
10571 return NULL;
10572 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
10573 return got_error(GOT_ERR_NO_SPACE);
10574 printf("timestamp: %s\n", datebuf);
10576 if (blob_id) {
10577 err = got_object_id_str(&id_str, blob_id);
10578 if (err)
10579 return err;
10580 printf("based on blob: %s\n", id_str);
10581 free(id_str);
10584 if (staged_blob_id) {
10585 err = got_object_id_str(&id_str, staged_blob_id);
10586 if (err)
10587 return err;
10588 printf("based on staged blob: %s\n", id_str);
10589 free(id_str);
10592 if (commit_id) {
10593 err = got_object_id_str(&id_str, commit_id);
10594 if (err)
10595 return err;
10596 printf("based on commit: %s\n", id_str);
10597 free(id_str);
10600 return NULL;
10603 static const struct got_error *
10604 cmd_info(int argc, char *argv[])
10606 const struct got_error *error = NULL;
10607 struct got_worktree *worktree = NULL;
10608 char *cwd = NULL, *id_str = NULL;
10609 struct got_pathlist_head paths;
10610 struct got_pathlist_entry *pe;
10611 char *uuidstr = NULL;
10612 int ch, show_files = 0;
10614 TAILQ_INIT(&paths);
10616 while ((ch = getopt(argc, argv, "")) != -1) {
10617 switch (ch) {
10618 default:
10619 usage_info();
10620 /* NOTREACHED */
10624 argc -= optind;
10625 argv += optind;
10627 #ifndef PROFILE
10628 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
10629 NULL) == -1)
10630 err(1, "pledge");
10631 #endif
10632 cwd = getcwd(NULL, 0);
10633 if (cwd == NULL) {
10634 error = got_error_from_errno("getcwd");
10635 goto done;
10638 error = got_worktree_open(&worktree, cwd);
10639 if (error) {
10640 if (error->code == GOT_ERR_NOT_WORKTREE)
10641 error = wrap_not_worktree_error(error, "info", cwd);
10642 goto done;
10645 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
10646 if (error)
10647 goto done;
10649 if (argc >= 1) {
10650 error = get_worktree_paths_from_argv(&paths, argc, argv,
10651 worktree);
10652 if (error)
10653 goto done;
10654 show_files = 1;
10657 error = got_object_id_str(&id_str,
10658 got_worktree_get_base_commit_id(worktree));
10659 if (error)
10660 goto done;
10662 error = got_worktree_get_uuid(&uuidstr, worktree);
10663 if (error)
10664 goto done;
10666 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
10667 printf("work tree base commit: %s\n", id_str);
10668 printf("work tree path prefix: %s\n",
10669 got_worktree_get_path_prefix(worktree));
10670 printf("work tree branch reference: %s\n",
10671 got_worktree_get_head_ref_name(worktree));
10672 printf("work tree UUID: %s\n", uuidstr);
10673 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
10675 if (show_files) {
10676 struct got_pathlist_entry *pe;
10677 TAILQ_FOREACH(pe, &paths, entry) {
10678 if (pe->path_len == 0)
10679 continue;
10681 * Assume this path will fail. This will be corrected
10682 * in print_path_info() in case the path does suceeed.
10684 pe->data = (void *)got_error_path(pe->path,
10685 GOT_ERR_BAD_PATH);
10687 error = got_worktree_path_info(worktree, &paths,
10688 print_path_info, &paths, check_cancelled, NULL);
10689 if (error)
10690 goto done;
10691 TAILQ_FOREACH(pe, &paths, entry) {
10692 if (pe->data != NULL) {
10693 error = pe->data; /* bad path */
10694 break;
10698 done:
10699 TAILQ_FOREACH(pe, &paths, entry)
10700 free((char *)pe->path);
10701 got_pathlist_free(&paths);
10702 free(cwd);
10703 free(id_str);
10704 free(uuidstr);
10705 return error;