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_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
60 #ifndef nitems
61 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
62 #endif
64 static volatile sig_atomic_t sigint_received;
65 static volatile sig_atomic_t sigpipe_received;
67 static void
68 catch_sigint(int signo)
69 {
70 sigint_received = 1;
71 }
73 static void
74 catch_sigpipe(int signo)
75 {
76 sigpipe_received = 1;
77 }
80 struct got_cmd {
81 const char *cmd_name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 const char *cmd_alias;
85 };
87 __dead static void usage(int, int);
88 __dead static void usage_init(void);
89 __dead static void usage_import(void);
90 __dead static void usage_clone(void);
91 __dead static void usage_fetch(void);
92 __dead static void usage_checkout(void);
93 __dead static void usage_update(void);
94 __dead static void usage_log(void);
95 __dead static void usage_diff(void);
96 __dead static void usage_blame(void);
97 __dead static void usage_tree(void);
98 __dead static void usage_status(void);
99 __dead static void usage_ref(void);
100 __dead static void usage_branch(void);
101 __dead static void usage_tag(void);
102 __dead static void usage_add(void);
103 __dead static void usage_remove(void);
104 __dead static void usage_revert(void);
105 __dead static void usage_commit(void);
106 __dead static void usage_send(void);
107 __dead static void usage_cherrypick(void);
108 __dead static void usage_backout(void);
109 __dead static void usage_rebase(void);
110 __dead static void usage_histedit(void);
111 __dead static void usage_integrate(void);
112 __dead static void usage_stage(void);
113 __dead static void usage_unstage(void);
114 __dead static void usage_cat(void);
115 __dead static void usage_info(void);
117 static const struct got_error* cmd_init(int, char *[]);
118 static const struct got_error* cmd_import(int, char *[]);
119 static const struct got_error* cmd_clone(int, char *[]);
120 static const struct got_error* cmd_fetch(int, char *[]);
121 static const struct got_error* cmd_checkout(int, char *[]);
122 static const struct got_error* cmd_update(int, char *[]);
123 static const struct got_error* cmd_log(int, char *[]);
124 static const struct got_error* cmd_diff(int, char *[]);
125 static const struct got_error* cmd_blame(int, char *[]);
126 static const struct got_error* cmd_tree(int, char *[]);
127 static const struct got_error* cmd_status(int, char *[]);
128 static const struct got_error* cmd_ref(int, char *[]);
129 static const struct got_error* cmd_branch(int, char *[]);
130 static const struct got_error* cmd_tag(int, char *[]);
131 static const struct got_error* cmd_add(int, char *[]);
132 static const struct got_error* cmd_remove(int, char *[]);
133 static const struct got_error* cmd_revert(int, char *[]);
134 static const struct got_error* cmd_commit(int, char *[]);
135 static const struct got_error* cmd_send(int, char *[]);
136 static const struct got_error* cmd_cherrypick(int, char *[]);
137 static const struct got_error* cmd_backout(int, char *[]);
138 static const struct got_error* cmd_rebase(int, char *[]);
139 static const struct got_error* cmd_histedit(int, char *[]);
140 static const struct got_error* cmd_integrate(int, char *[]);
141 static const struct got_error* cmd_stage(int, char *[]);
142 static const struct got_error* cmd_unstage(int, char *[]);
143 static const struct got_error* cmd_cat(int, char *[]);
144 static const struct got_error* cmd_info(int, char *[]);
146 static struct got_cmd got_commands[] = {
147 { "init", cmd_init, usage_init, "" },
148 { "import", cmd_import, usage_import, "im" },
149 { "clone", cmd_clone, usage_clone, "cl" },
150 { "fetch", cmd_fetch, usage_fetch, "fe" },
151 { "checkout", cmd_checkout, usage_checkout, "co" },
152 { "update", cmd_update, usage_update, "up" },
153 { "log", cmd_log, usage_log, "" },
154 { "diff", cmd_diff, usage_diff, "di" },
155 { "blame", cmd_blame, usage_blame, "bl" },
156 { "tree", cmd_tree, usage_tree, "tr" },
157 { "status", cmd_status, usage_status, "st" },
158 { "ref", cmd_ref, usage_ref, "" },
159 { "branch", cmd_branch, usage_branch, "br" },
160 { "tag", cmd_tag, usage_tag, "" },
161 { "add", cmd_add, usage_add, "" },
162 { "remove", cmd_remove, usage_remove, "rm" },
163 { "revert", cmd_revert, usage_revert, "rv" },
164 { "commit", cmd_commit, usage_commit, "ci" },
165 { "send", cmd_send, usage_send, "se" },
166 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
167 { "backout", cmd_backout, usage_backout, "bo" },
168 { "rebase", cmd_rebase, usage_rebase, "rb" },
169 { "histedit", cmd_histedit, usage_histedit, "he" },
170 { "integrate", cmd_integrate, usage_integrate,"ig" },
171 { "stage", cmd_stage, usage_stage, "sg" },
172 { "unstage", cmd_unstage, usage_unstage, "ug" },
173 { "cat", cmd_cat, usage_cat, "" },
174 { "info", cmd_info, usage_info, "" },
175 };
177 static void
178 list_commands(FILE *fp)
180 size_t i;
182 fprintf(fp, "commands:");
183 for (i = 0; i < nitems(got_commands); i++) {
184 struct got_cmd *cmd = &got_commands[i];
185 fprintf(fp, " %s", cmd->cmd_name);
187 fputc('\n', fp);
190 __dead static void
191 option_conflict(char a, char b)
193 errx(1, "-%c and -%c options are mutually exclusive", a, b);
196 int
197 main(int argc, char *argv[])
199 struct got_cmd *cmd;
200 size_t i;
201 int ch;
202 int hflag = 0, Vflag = 0;
203 static struct option longopts[] = {
204 { "version", no_argument, NULL, 'V' },
205 { NULL, 0, NULL, 0 }
206 };
208 setlocale(LC_CTYPE, "");
210 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
211 switch (ch) {
212 case 'h':
213 hflag = 1;
214 break;
215 case 'V':
216 Vflag = 1;
217 break;
218 default:
219 usage(hflag, 1);
220 /* NOTREACHED */
224 argc -= optind;
225 argv += optind;
226 optind = 1;
227 optreset = 1;
229 if (Vflag) {
230 got_version_print_str();
231 return 0;
234 if (argc <= 0)
235 usage(hflag, hflag ? 0 : 1);
237 signal(SIGINT, catch_sigint);
238 signal(SIGPIPE, catch_sigpipe);
240 for (i = 0; i < nitems(got_commands); i++) {
241 const struct got_error *error;
243 cmd = &got_commands[i];
245 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
246 strcmp(cmd->cmd_alias, argv[0]) != 0)
247 continue;
249 if (hflag)
250 got_commands[i].cmd_usage();
252 error = got_commands[i].cmd_main(argc, argv);
253 if (error && error->code != GOT_ERR_CANCELLED &&
254 error->code != GOT_ERR_PRIVSEP_EXIT &&
255 !(sigpipe_received &&
256 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
257 !(sigint_received &&
258 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
259 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
260 return 1;
263 return 0;
266 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
267 list_commands(stderr);
268 return 1;
271 __dead static void
272 usage(int hflag, int status)
274 FILE *fp = (status == 0) ? stdout : stderr;
276 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
277 getprogname());
278 if (hflag)
279 list_commands(fp);
280 exit(status);
283 static const struct got_error *
284 get_editor(char **abspath)
286 const struct got_error *err = NULL;
287 const char *editor;
289 *abspath = NULL;
291 editor = getenv("VISUAL");
292 if (editor == NULL)
293 editor = getenv("EDITOR");
295 if (editor) {
296 err = got_path_find_prog(abspath, editor);
297 if (err)
298 return err;
301 if (*abspath == NULL) {
302 *abspath = strdup("/bin/ed");
303 if (*abspath == NULL)
304 return got_error_from_errno("strdup");
307 return NULL;
310 static const struct got_error *
311 apply_unveil(const char *repo_path, int repo_read_only,
312 const char *worktree_path)
314 const struct got_error *err;
316 #ifdef PROFILE
317 if (unveil("gmon.out", "rwc") != 0)
318 return got_error_from_errno2("unveil", "gmon.out");
319 #endif
320 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
321 return got_error_from_errno2("unveil", repo_path);
323 if (worktree_path && unveil(worktree_path, "rwc") != 0)
324 return got_error_from_errno2("unveil", worktree_path);
326 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
327 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
329 err = got_privsep_unveil_exec_helpers();
330 if (err != NULL)
331 return err;
333 if (unveil(NULL, NULL) != 0)
334 return got_error_from_errno("unveil");
336 return NULL;
339 __dead static void
340 usage_init(void)
342 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
343 exit(1);
346 static const struct got_error *
347 cmd_init(int argc, char *argv[])
349 const struct got_error *error = NULL;
350 char *repo_path = NULL;
351 int ch;
353 while ((ch = getopt(argc, argv, "")) != -1) {
354 switch (ch) {
355 default:
356 usage_init();
357 /* NOTREACHED */
361 argc -= optind;
362 argv += optind;
364 #ifndef PROFILE
365 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
366 err(1, "pledge");
367 #endif
368 if (argc != 1)
369 usage_init();
371 repo_path = strdup(argv[0]);
372 if (repo_path == NULL)
373 return got_error_from_errno("strdup");
375 got_path_strip_trailing_slashes(repo_path);
377 error = got_path_mkdir(repo_path);
378 if (error &&
379 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
380 goto done;
382 error = apply_unveil(repo_path, 0, NULL);
383 if (error)
384 goto done;
386 error = got_repo_init(repo_path);
387 done:
388 free(repo_path);
389 return error;
392 __dead static void
393 usage_import(void)
395 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
396 "[-r repository-path] [-I pattern] path\n", getprogname());
397 exit(1);
400 int
401 spawn_editor(const char *editor, const char *file)
403 pid_t pid;
404 sig_t sighup, sigint, sigquit;
405 int st = -1;
407 sighup = signal(SIGHUP, SIG_IGN);
408 sigint = signal(SIGINT, SIG_IGN);
409 sigquit = signal(SIGQUIT, SIG_IGN);
411 switch (pid = fork()) {
412 case -1:
413 goto doneediting;
414 case 0:
415 execl(editor, editor, file, (char *)NULL);
416 _exit(127);
419 while (waitpid(pid, &st, 0) == -1)
420 if (errno != EINTR)
421 break;
423 doneediting:
424 (void)signal(SIGHUP, sighup);
425 (void)signal(SIGINT, sigint);
426 (void)signal(SIGQUIT, sigquit);
428 if (!WIFEXITED(st)) {
429 errno = EINTR;
430 return -1;
433 return WEXITSTATUS(st);
436 static const struct got_error *
437 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
438 const char *initial_content, size_t initial_content_len,
439 int require_modification)
441 const struct got_error *err = NULL;
442 char *line = NULL;
443 size_t linesize = 0;
444 ssize_t linelen;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t len, logmsg_len;
448 char *initial_content_stripped = NULL, *buf = NULL, *s;
450 *logmsg = NULL;
452 if (stat(logmsg_path, &st) == -1)
453 return got_error_from_errno2("stat", logmsg_path);
455 if (spawn_editor(editor, logmsg_path) == -1)
456 return got_error_from_errno("failed spawning editor");
458 if (stat(logmsg_path, &st2) == -1)
459 return got_error_from_errno("stat");
461 if (require_modification &&
462 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
463 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
464 "no changes made to commit message, aborting");
466 /*
467 * Set up a stripped version of the initial content without comments
468 * and blank lines. We need this in order to check if the message
469 * has in fact been edited.
470 */
471 initial_content_stripped = malloc(initial_content_len + 1);
472 if (initial_content_stripped == NULL)
473 return got_error_from_errno("malloc");
474 initial_content_stripped[0] = '\0';
476 buf = strdup(initial_content);
477 if (buf == NULL) {
478 err = got_error_from_errno("strdup");
479 goto done;
481 s = buf;
482 len = 0;
483 while ((line = strsep(&s, "\n")) != NULL) {
484 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
485 continue; /* remove comments and leading empty lines */
486 len = strlcat(initial_content_stripped, line,
487 initial_content_len + 1);
488 if (len >= initial_content_len + 1) {
489 err = got_error(GOT_ERR_NO_SPACE);
490 goto done;
493 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
494 initial_content_stripped[len - 1] = '\0';
495 len--;
498 logmsg_len = st2.st_size;
499 *logmsg = malloc(logmsg_len + 1);
500 if (*logmsg == NULL)
501 return got_error_from_errno("malloc");
502 (*logmsg)[0] = '\0';
504 fp = fopen(logmsg_path, "r");
505 if (fp == NULL) {
506 err = got_error_from_errno("fopen");
507 goto done;
510 len = 0;
511 while ((linelen = getline(&line, &linesize, fp)) != -1) {
512 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
513 continue; /* remove comments and leading empty lines */
514 len = strlcat(*logmsg, line, logmsg_len + 1);
515 if (len >= logmsg_len + 1) {
516 err = got_error(GOT_ERR_NO_SPACE);
517 goto done;
520 free(line);
521 if (ferror(fp)) {
522 err = got_ferror(fp, GOT_ERR_IO);
523 goto done;
525 while (len > 0 && (*logmsg)[len - 1] == '\n') {
526 (*logmsg)[len - 1] = '\0';
527 len--;
530 if (len == 0) {
531 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
532 "commit message cannot be empty, aborting");
533 goto done;
535 if (require_modification &&
536 strcmp(*logmsg, initial_content_stripped) == 0)
537 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
538 "no changes made to commit message, aborting");
539 done:
540 free(initial_content_stripped);
541 free(buf);
542 if (fp && fclose(fp) == EOF && err == NULL)
543 err = got_error_from_errno("fclose");
544 if (err) {
545 free(*logmsg);
546 *logmsg = NULL;
548 return err;
551 static const struct got_error *
552 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
553 const char *path_dir, const char *branch_name)
555 char *initial_content = NULL;
556 const struct got_error *err = NULL;
557 int initial_content_len;
558 int fd = -1;
560 initial_content_len = asprintf(&initial_content,
561 "\n# %s to be imported to branch %s\n", path_dir,
562 branch_name);
563 if (initial_content_len == -1)
564 return got_error_from_errno("asprintf");
566 err = got_opentemp_named_fd(logmsg_path, &fd,
567 GOT_TMPDIR_STR "/got-importmsg");
568 if (err)
569 goto done;
571 if (write(fd, initial_content, initial_content_len) == -1) {
572 err = got_error_from_errno2("write", *logmsg_path);
573 goto done;
576 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
577 initial_content_len, 1);
578 done:
579 if (fd != -1 && close(fd) == -1 && err == NULL)
580 err = got_error_from_errno2("close", *logmsg_path);
581 free(initial_content);
582 if (err) {
583 free(*logmsg_path);
584 *logmsg_path = NULL;
586 return err;
589 static const struct got_error *
590 import_progress(void *arg, const char *path)
592 printf("A %s\n", path);
593 return NULL;
596 static const struct got_error *
597 get_author(char **author, struct got_repository *repo,
598 struct got_worktree *worktree)
600 const struct got_error *err = NULL;
601 const char *got_author = NULL, *name, *email;
602 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
604 *author = NULL;
606 if (worktree)
607 worktree_conf = got_worktree_get_gotconfig(worktree);
608 repo_conf = got_repo_get_gotconfig(repo);
610 /*
611 * Priority of potential author information sources, from most
612 * significant to least significant:
613 * 1) work tree's .got/got.conf file
614 * 2) repository's got.conf file
615 * 3) repository's git config file
616 * 4) environment variables
617 * 5) global git config files (in user's home directory or /etc)
618 */
620 if (worktree_conf)
621 got_author = got_gotconfig_get_author(worktree_conf);
622 if (got_author == NULL)
623 got_author = got_gotconfig_get_author(repo_conf);
624 if (got_author == NULL) {
625 name = got_repo_get_gitconfig_author_name(repo);
626 email = got_repo_get_gitconfig_author_email(repo);
627 if (name && email) {
628 if (asprintf(author, "%s <%s>", name, email) == -1)
629 return got_error_from_errno("asprintf");
630 return NULL;
633 got_author = getenv("GOT_AUTHOR");
634 if (got_author == NULL) {
635 name = got_repo_get_global_gitconfig_author_name(repo);
636 email = got_repo_get_global_gitconfig_author_email(
637 repo);
638 if (name && email) {
639 if (asprintf(author, "%s <%s>", name, email)
640 == -1)
641 return got_error_from_errno("asprintf");
642 return NULL;
644 /* TODO: Look up user in password database? */
645 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
649 *author = strdup(got_author);
650 if (*author == NULL)
651 return got_error_from_errno("strdup");
653 /*
654 * Really dumb email address check; we're only doing this to
655 * avoid git's object parser breaking on commits we create.
656 */
657 while (*got_author && *got_author != '<')
658 got_author++;
659 if (*got_author != '<') {
660 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
661 goto done;
663 while (*got_author && *got_author != '@')
664 got_author++;
665 if (*got_author != '@') {
666 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
667 goto done;
669 while (*got_author && *got_author != '>')
670 got_author++;
671 if (*got_author != '>')
672 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
673 done:
674 if (err) {
675 free(*author);
676 *author = NULL;
678 return err;
681 static const struct got_error *
682 get_gitconfig_path(char **gitconfig_path)
684 const char *homedir = getenv("HOME");
686 *gitconfig_path = NULL;
687 if (homedir) {
688 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
689 return got_error_from_errno("asprintf");
692 return NULL;
695 static const struct got_error *
696 cmd_import(int argc, char *argv[])
698 const struct got_error *error = NULL;
699 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
700 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
701 const char *branch_name = "main";
702 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
703 struct got_repository *repo = NULL;
704 struct got_reference *branch_ref = NULL, *head_ref = NULL;
705 struct got_object_id *new_commit_id = NULL;
706 int ch;
707 struct got_pathlist_head ignores;
708 struct got_pathlist_entry *pe;
709 int preserve_logmsg = 0;
711 TAILQ_INIT(&ignores);
713 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
714 switch (ch) {
715 case 'b':
716 branch_name = optarg;
717 break;
718 case 'm':
719 logmsg = strdup(optarg);
720 if (logmsg == NULL) {
721 error = got_error_from_errno("strdup");
722 goto done;
724 break;
725 case 'r':
726 repo_path = realpath(optarg, NULL);
727 if (repo_path == NULL) {
728 error = got_error_from_errno2("realpath",
729 optarg);
730 goto done;
732 break;
733 case 'I':
734 if (optarg[0] == '\0')
735 break;
736 error = got_pathlist_insert(&pe, &ignores, optarg,
737 NULL);
738 if (error)
739 goto done;
740 break;
741 default:
742 usage_import();
743 /* NOTREACHED */
747 argc -= optind;
748 argv += optind;
750 #ifndef PROFILE
751 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
752 "unveil",
753 NULL) == -1)
754 err(1, "pledge");
755 #endif
756 if (argc != 1)
757 usage_import();
759 if (repo_path == NULL) {
760 repo_path = getcwd(NULL, 0);
761 if (repo_path == NULL)
762 return got_error_from_errno("getcwd");
764 got_path_strip_trailing_slashes(repo_path);
765 error = get_gitconfig_path(&gitconfig_path);
766 if (error)
767 goto done;
768 error = got_repo_open(&repo, repo_path, gitconfig_path);
769 if (error)
770 goto done;
772 error = get_author(&author, repo, NULL);
773 if (error)
774 return error;
776 /*
777 * Don't let the user create a branch name with a leading '-'.
778 * While technically a valid reference name, this case is usually
779 * an unintended typo.
780 */
781 if (branch_name[0] == '-')
782 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
784 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
785 error = got_error_from_errno("asprintf");
786 goto done;
789 error = got_ref_open(&branch_ref, repo, refname, 0);
790 if (error) {
791 if (error->code != GOT_ERR_NOT_REF)
792 goto done;
793 } else {
794 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
795 "import target branch already exists");
796 goto done;
799 path_dir = realpath(argv[0], NULL);
800 if (path_dir == NULL) {
801 error = got_error_from_errno2("realpath", argv[0]);
802 goto done;
804 got_path_strip_trailing_slashes(path_dir);
806 /*
807 * unveil(2) traverses exec(2); if an editor is used we have
808 * to apply unveil after the log message has been written.
809 */
810 if (logmsg == NULL || strlen(logmsg) == 0) {
811 error = get_editor(&editor);
812 if (error)
813 goto done;
814 free(logmsg);
815 error = collect_import_msg(&logmsg, &logmsg_path, editor,
816 path_dir, refname);
817 if (error) {
818 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
819 logmsg_path != NULL)
820 preserve_logmsg = 1;
821 goto done;
825 if (unveil(path_dir, "r") != 0) {
826 error = got_error_from_errno2("unveil", path_dir);
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
833 if (error) {
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = got_repo_import(&new_commit_id, path_dir, logmsg,
840 author, &ignores, repo, import_progress, NULL);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_write(branch_ref, repo);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_object_id_str(&id_str, new_commit_id);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
869 if (error) {
870 if (error->code != GOT_ERR_NOT_REF) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
877 branch_ref);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_ref_write(head_ref, repo);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
892 printf("Created branch %s with commit %s\n",
893 got_ref_get_name(branch_ref), id_str);
894 done:
895 if (preserve_logmsg) {
896 fprintf(stderr, "%s: log message preserved in %s\n",
897 getprogname(), logmsg_path);
898 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
899 error = got_error_from_errno2("unlink", logmsg_path);
900 free(logmsg);
901 free(logmsg_path);
902 free(repo_path);
903 free(editor);
904 free(refname);
905 free(new_commit_id);
906 free(id_str);
907 free(author);
908 free(gitconfig_path);
909 if (branch_ref)
910 got_ref_close(branch_ref);
911 if (head_ref)
912 got_ref_close(head_ref);
913 return error;
916 __dead static void
917 usage_clone(void)
919 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
920 "[-R reference] repository-url [directory]\n", getprogname());
921 exit(1);
924 struct got_fetch_progress_arg {
925 char last_scaled_size[FMT_SCALED_STRSIZE];
926 int last_p_indexed;
927 int last_p_resolved;
928 int verbosity;
930 struct got_repository *repo;
932 int create_configs;
933 int configs_created;
934 struct {
935 struct got_pathlist_head *symrefs;
936 struct got_pathlist_head *wanted_branches;
937 struct got_pathlist_head *wanted_refs;
938 const char *proto;
939 const char *host;
940 const char *port;
941 const char *remote_repo_path;
942 const char *git_url;
943 int fetch_all_branches;
944 int mirror_references;
945 } config_info;
946 };
948 /* XXX forward declaration */
949 static const struct got_error *
950 create_config_files(const char *proto, const char *host, const char *port,
951 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
952 int mirror_references, struct got_pathlist_head *symrefs,
953 struct got_pathlist_head *wanted_branches,
954 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
956 static const struct got_error *
957 fetch_progress(void *arg, const char *message, off_t packfile_size,
958 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
960 const struct got_error *err = NULL;
961 struct got_fetch_progress_arg *a = arg;
962 char scaled_size[FMT_SCALED_STRSIZE];
963 int p_indexed, p_resolved;
964 int print_size = 0, print_indexed = 0, print_resolved = 0;
966 /*
967 * In order to allow a failed clone to be resumed with 'got fetch'
968 * we try to create configuration files as soon as possible.
969 * Once the server has sent information about its default branch
970 * we have all required information.
971 */
972 if (a->create_configs && !a->configs_created &&
973 !TAILQ_EMPTY(a->config_info.symrefs)) {
974 err = create_config_files(a->config_info.proto,
975 a->config_info.host, a->config_info.port,
976 a->config_info.remote_repo_path,
977 a->config_info.git_url,
978 a->config_info.fetch_all_branches,
979 a->config_info.mirror_references,
980 a->config_info.symrefs,
981 a->config_info.wanted_branches,
982 a->config_info.wanted_refs, a->repo);
983 if (err)
984 return err;
985 a->configs_created = 1;
988 if (a->verbosity < 0)
989 return NULL;
991 if (message && message[0] != '\0') {
992 printf("\rserver: %s", message);
993 fflush(stdout);
994 return NULL;
997 if (packfile_size > 0 || nobj_indexed > 0) {
998 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
999 (a->last_scaled_size[0] == '\0' ||
1000 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1001 print_size = 1;
1002 if (strlcpy(a->last_scaled_size, scaled_size,
1003 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1004 return got_error(GOT_ERR_NO_SPACE);
1006 if (nobj_indexed > 0) {
1007 p_indexed = (nobj_indexed * 100) / nobj_total;
1008 if (p_indexed != a->last_p_indexed) {
1009 a->last_p_indexed = p_indexed;
1010 print_indexed = 1;
1011 print_size = 1;
1014 if (nobj_resolved > 0) {
1015 p_resolved = (nobj_resolved * 100) /
1016 (nobj_total - nobj_loose);
1017 if (p_resolved != a->last_p_resolved) {
1018 a->last_p_resolved = p_resolved;
1019 print_resolved = 1;
1020 print_indexed = 1;
1021 print_size = 1;
1026 if (print_size || print_indexed || print_resolved)
1027 printf("\r");
1028 if (print_size)
1029 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1030 if (print_indexed)
1031 printf("; indexing %d%%", p_indexed);
1032 if (print_resolved)
1033 printf("; resolving deltas %d%%", p_resolved);
1034 if (print_size || print_indexed || print_resolved)
1035 fflush(stdout);
1037 return NULL;
1040 static const struct got_error *
1041 create_symref(const char *refname, struct got_reference *target_ref,
1042 int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 struct got_reference *head_symref;
1047 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1048 if (err)
1049 return err;
1051 err = got_ref_write(head_symref, repo);
1052 if (err == NULL && verbosity > 0) {
1053 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1054 got_ref_get_name(target_ref));
1056 got_ref_close(head_symref);
1057 return err;
1060 static const struct got_error *
1061 list_remote_refs(struct got_pathlist_head *symrefs,
1062 struct got_pathlist_head *refs)
1064 const struct got_error *err;
1065 struct got_pathlist_entry *pe;
1067 TAILQ_FOREACH(pe, symrefs, entry) {
1068 const char *refname = pe->path;
1069 const char *targetref = pe->data;
1071 printf("%s: %s\n", refname, targetref);
1074 TAILQ_FOREACH(pe, refs, entry) {
1075 const char *refname = pe->path;
1076 struct got_object_id *id = pe->data;
1077 char *id_str;
1079 err = got_object_id_str(&id_str, id);
1080 if (err)
1081 return err;
1082 printf("%s: %s\n", refname, id_str);
1083 free(id_str);
1086 return NULL;
1089 static const struct got_error *
1090 create_ref(const char *refname, struct got_object_id *id,
1091 int verbosity, struct got_repository *repo)
1093 const struct got_error *err = NULL;
1094 struct got_reference *ref;
1095 char *id_str;
1097 err = got_object_id_str(&id_str, id);
1098 if (err)
1099 return err;
1101 err = got_ref_alloc(&ref, refname, id);
1102 if (err)
1103 goto done;
1105 err = got_ref_write(ref, repo);
1106 got_ref_close(ref);
1108 if (err == NULL && verbosity >= 0)
1109 printf("Created reference %s: %s\n", refname, id_str);
1110 done:
1111 free(id_str);
1112 return err;
1115 static int
1116 match_wanted_ref(const char *refname, const char *wanted_ref)
1118 if (strncmp(refname, "refs/", 5) != 0)
1119 return 0;
1120 refname += 5;
1123 * Prevent fetching of references that won't make any
1124 * sense outside of the remote repository's context.
1126 if (strncmp(refname, "got/", 4) == 0)
1127 return 0;
1128 if (strncmp(refname, "remotes/", 8) == 0)
1129 return 0;
1131 if (strncmp(wanted_ref, "refs/", 5) == 0)
1132 wanted_ref += 5;
1134 /* Allow prefix match. */
1135 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1136 return 1;
1138 /* Allow exact match. */
1139 return (strcmp(refname, wanted_ref) == 0);
1142 static int
1143 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1145 struct got_pathlist_entry *pe;
1147 TAILQ_FOREACH(pe, wanted_refs, entry) {
1148 if (match_wanted_ref(refname, pe->path))
1149 return 1;
1152 return 0;
1155 static const struct got_error *
1156 create_wanted_ref(const char *refname, struct got_object_id *id,
1157 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1159 const struct got_error *err;
1160 char *remote_refname;
1162 if (strncmp("refs/", refname, 5) == 0)
1163 refname += 5;
1165 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1166 remote_repo_name, refname) == -1)
1167 return got_error_from_errno("asprintf");
1169 err = create_ref(remote_refname, id, verbosity, repo);
1170 free(remote_refname);
1171 return err;
1174 static const struct got_error *
1175 create_gotconfig(const char *proto, const char *host, const char *port,
1176 const char *remote_repo_path, const char *default_branch,
1177 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1178 struct got_pathlist_head *wanted_refs, int mirror_references,
1179 struct got_repository *repo)
1181 const struct got_error *err = NULL;
1182 char *gotconfig_path = NULL;
1183 char *gotconfig = NULL;
1184 FILE *gotconfig_file = NULL;
1185 const char *branchname = NULL;
1186 char *branches = NULL, *refs = NULL;
1187 ssize_t n;
1189 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1190 struct got_pathlist_entry *pe;
1191 TAILQ_FOREACH(pe, wanted_branches, entry) {
1192 char *s;
1193 branchname = pe->path;
1194 if (strncmp(branchname, "refs/heads/", 11) == 0)
1195 branchname += 11;
1196 if (asprintf(&s, "%s\"%s\" ",
1197 branches ? branches : "", branchname) == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1201 free(branches);
1202 branches = s;
1204 } else if (!fetch_all_branches && default_branch) {
1205 branchname = default_branch;
1206 if (strncmp(branchname, "refs/heads/", 11) == 0)
1207 branchname += 11;
1208 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1209 err = got_error_from_errno("asprintf");
1210 goto done;
1213 if (!TAILQ_EMPTY(wanted_refs)) {
1214 struct got_pathlist_entry *pe;
1215 TAILQ_FOREACH(pe, wanted_refs, entry) {
1216 char *s;
1217 const char *refname = pe->path;
1218 if (strncmp(refname, "refs/", 5) == 0)
1219 branchname += 5;
1220 if (asprintf(&s, "%s\"%s\" ",
1221 refs ? refs : "", refname) == -1) {
1222 err = got_error_from_errno("asprintf");
1223 goto done;
1225 free(refs);
1226 refs = s;
1230 /* Create got.conf(5). */
1231 gotconfig_path = got_repo_get_path_gotconfig(repo);
1232 if (gotconfig_path == NULL) {
1233 err = got_error_from_errno("got_repo_get_path_gotconfig");
1234 goto done;
1236 gotconfig_file = fopen(gotconfig_path, "a");
1237 if (gotconfig_file == NULL) {
1238 err = got_error_from_errno2("fopen", gotconfig_path);
1239 goto done;
1241 if (asprintf(&gotconfig,
1242 "remote \"%s\" {\n"
1243 "\tserver %s\n"
1244 "\tprotocol %s\n"
1245 "%s%s%s"
1246 "\trepository \"%s\"\n"
1247 "%s%s%s"
1248 "%s%s%s"
1249 "%s"
1250 "%s"
1251 "}\n",
1252 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1253 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1254 remote_repo_path, branches ? "\tbranch { " : "",
1255 branches ? branches : "", branches ? "}\n" : "",
1256 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1257 mirror_references ? "\tmirror-references yes\n" : "",
1258 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1259 err = got_error_from_errno("asprintf");
1260 goto done;
1262 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1263 if (n != strlen(gotconfig)) {
1264 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1265 goto done;
1268 done:
1269 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1270 err = got_error_from_errno2("fclose", gotconfig_path);
1271 free(gotconfig_path);
1272 free(branches);
1273 return err;
1276 static const struct got_error *
1277 create_gitconfig(const char *git_url, const char *default_branch,
1278 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1279 struct got_pathlist_head *wanted_refs, int mirror_references,
1280 struct got_repository *repo)
1282 const struct got_error *err = NULL;
1283 char *gitconfig_path = NULL;
1284 char *gitconfig = NULL;
1285 FILE *gitconfig_file = NULL;
1286 char *branches = NULL, *refs = NULL;
1287 const char *branchname;
1288 ssize_t n;
1290 /* Create a config file Git can understand. */
1291 gitconfig_path = got_repo_get_path_gitconfig(repo);
1292 if (gitconfig_path == NULL) {
1293 err = got_error_from_errno("got_repo_get_path_gitconfig");
1294 goto done;
1296 gitconfig_file = fopen(gitconfig_path, "a");
1297 if (gitconfig_file == NULL) {
1298 err = got_error_from_errno2("fopen", gitconfig_path);
1299 goto done;
1301 if (fetch_all_branches) {
1302 if (mirror_references) {
1303 if (asprintf(&branches,
1304 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1305 err = got_error_from_errno("asprintf");
1306 goto done;
1308 } else if (asprintf(&branches,
1309 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1310 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1311 err = got_error_from_errno("asprintf");
1312 goto done;
1314 } else if (!TAILQ_EMPTY(wanted_branches)) {
1315 struct got_pathlist_entry *pe;
1316 TAILQ_FOREACH(pe, wanted_branches, entry) {
1317 char *s;
1318 branchname = pe->path;
1319 if (strncmp(branchname, "refs/heads/", 11) == 0)
1320 branchname += 11;
1321 if (mirror_references) {
1322 if (asprintf(&s,
1323 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1324 branches ? branches : "",
1325 branchname, branchname) == -1) {
1326 err = got_error_from_errno("asprintf");
1327 goto done;
1329 } else if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1331 branches ? branches : "",
1332 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1333 branchname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 free(branches);
1338 branches = s;
1340 } else {
1342 * If the server specified a default branch, use just that one.
1343 * Otherwise fall back to fetching all branches on next fetch.
1345 if (default_branch) {
1346 branchname = default_branch;
1347 if (strncmp(branchname, "refs/heads/", 11) == 0)
1348 branchname += 11;
1349 } else
1350 branchname = "*"; /* fall back to all branches */
1351 if (mirror_references) {
1352 if (asprintf(&branches,
1353 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1354 branchname, branchname) == -1) {
1355 err = got_error_from_errno("asprintf");
1356 goto done;
1358 } else if (asprintf(&branches,
1359 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1360 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1361 branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1366 if (!TAILQ_EMPTY(wanted_refs)) {
1367 struct got_pathlist_entry *pe;
1368 TAILQ_FOREACH(pe, wanted_refs, entry) {
1369 char *s;
1370 const char *refname = pe->path;
1371 if (strncmp(refname, "refs/", 5) == 0)
1372 refname += 5;
1373 if (mirror_references) {
1374 if (asprintf(&s,
1375 "%s\tfetch = refs/%s:refs/%s\n",
1376 refs ? refs : "", refname, refname) == -1) {
1377 err = got_error_from_errno("asprintf");
1378 goto done;
1380 } else if (asprintf(&s,
1381 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1382 refs ? refs : "",
1383 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1384 refname) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 free(refs);
1389 refs = s;
1393 if (asprintf(&gitconfig,
1394 "[remote \"%s\"]\n"
1395 "\turl = %s\n"
1396 "%s"
1397 "%s"
1398 "\tfetch = refs/tags/*:refs/tags/*\n",
1399 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1400 refs ? refs : "") == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1405 if (n != strlen(gitconfig)) {
1406 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1407 goto done;
1409 done:
1410 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1411 err = got_error_from_errno2("fclose", gitconfig_path);
1412 free(gitconfig_path);
1413 free(branches);
1414 return err;
1417 static const struct got_error *
1418 create_config_files(const char *proto, const char *host, const char *port,
1419 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1420 int mirror_references, struct got_pathlist_head *symrefs,
1421 struct got_pathlist_head *wanted_branches,
1422 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1424 const struct got_error *err = NULL;
1425 const char *default_branch = NULL;
1426 struct got_pathlist_entry *pe;
1429 * If we asked for a set of wanted branches then use the first
1430 * one of those.
1432 if (!TAILQ_EMPTY(wanted_branches)) {
1433 pe = TAILQ_FIRST(wanted_branches);
1434 default_branch = pe->path;
1435 } else {
1436 /* First HEAD ref listed by server is the default branch. */
1437 TAILQ_FOREACH(pe, symrefs, entry) {
1438 const char *refname = pe->path;
1439 const char *target = pe->data;
1441 if (strcmp(refname, GOT_REF_HEAD) != 0)
1442 continue;
1444 default_branch = target;
1445 break;
1449 /* Create got.conf(5). */
1450 err = create_gotconfig(proto, host, port, remote_repo_path,
1451 default_branch, fetch_all_branches, wanted_branches,
1452 wanted_refs, mirror_references, repo);
1453 if (err)
1454 return err;
1456 /* Create a config file Git can understand. */
1457 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1458 wanted_branches, wanted_refs, mirror_references, repo);
1461 static const struct got_error *
1462 cmd_clone(int argc, char *argv[])
1464 const struct got_error *error = NULL;
1465 const char *uri, *dirname;
1466 char *proto, *host, *port, *repo_name, *server_path;
1467 char *default_destdir = NULL, *id_str = NULL;
1468 const char *repo_path;
1469 struct got_repository *repo = NULL;
1470 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1471 struct got_pathlist_entry *pe;
1472 struct got_object_id *pack_hash = NULL;
1473 int ch, fetchfd = -1, fetchstatus;
1474 pid_t fetchpid = -1;
1475 struct got_fetch_progress_arg fpa;
1476 char *git_url = NULL;
1477 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1478 int list_refs_only = 0;
1480 TAILQ_INIT(&refs);
1481 TAILQ_INIT(&symrefs);
1482 TAILQ_INIT(&wanted_branches);
1483 TAILQ_INIT(&wanted_refs);
1485 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1486 switch (ch) {
1487 case 'a':
1488 fetch_all_branches = 1;
1489 break;
1490 case 'b':
1491 error = got_pathlist_append(&wanted_branches,
1492 optarg, NULL);
1493 if (error)
1494 return error;
1495 break;
1496 case 'l':
1497 list_refs_only = 1;
1498 break;
1499 case 'm':
1500 mirror_references = 1;
1501 break;
1502 case 'v':
1503 if (verbosity < 0)
1504 verbosity = 0;
1505 else if (verbosity < 3)
1506 verbosity++;
1507 break;
1508 case 'q':
1509 verbosity = -1;
1510 break;
1511 case 'R':
1512 error = got_pathlist_append(&wanted_refs,
1513 optarg, NULL);
1514 if (error)
1515 return error;
1516 break;
1517 default:
1518 usage_clone();
1519 break;
1522 argc -= optind;
1523 argv += optind;
1525 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1526 option_conflict('a', 'b');
1527 if (list_refs_only) {
1528 if (!TAILQ_EMPTY(&wanted_branches))
1529 option_conflict('l', 'b');
1530 if (fetch_all_branches)
1531 option_conflict('l', 'a');
1532 if (mirror_references)
1533 option_conflict('l', 'm');
1534 if (!TAILQ_EMPTY(&wanted_refs))
1535 option_conflict('l', 'R');
1538 uri = argv[0];
1540 if (argc == 1)
1541 dirname = NULL;
1542 else if (argc == 2)
1543 dirname = argv[1];
1544 else
1545 usage_clone();
1547 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1548 &repo_name, uri);
1549 if (error)
1550 goto done;
1552 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1553 host, port ? ":" : "", port ? port : "",
1554 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1555 error = got_error_from_errno("asprintf");
1556 goto done;
1559 if (strcmp(proto, "git") == 0) {
1560 #ifndef PROFILE
1561 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1562 "sendfd dns inet unveil", NULL) == -1)
1563 err(1, "pledge");
1564 #endif
1565 } else if (strcmp(proto, "git+ssh") == 0 ||
1566 strcmp(proto, "ssh") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "http") == 0 ||
1573 strcmp(proto, "git+http") == 0) {
1574 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1575 goto done;
1576 } else {
1577 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1578 goto done;
1580 if (dirname == NULL) {
1581 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1582 error = got_error_from_errno("asprintf");
1583 goto done;
1585 repo_path = default_destdir;
1586 } else
1587 repo_path = dirname;
1589 if (!list_refs_only) {
1590 error = got_path_mkdir(repo_path);
1591 if (error &&
1592 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1593 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1594 goto done;
1595 if (!got_path_dir_is_empty(repo_path)) {
1596 error = got_error_path(repo_path,
1597 GOT_ERR_DIR_NOT_EMPTY);
1598 goto done;
1602 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1603 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1604 error = got_error_from_errno2("unveil",
1605 GOT_FETCH_PATH_SSH);
1606 goto done;
1609 error = apply_unveil(repo_path, 0, NULL);
1610 if (error)
1611 goto done;
1613 if (verbosity >= 0)
1614 printf("Connecting to %s%s%s\n", host,
1615 port ? ":" : "", port ? port : "");
1617 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1618 server_path, verbosity);
1619 if (error)
1620 goto done;
1622 if (!list_refs_only) {
1623 error = got_repo_init(repo_path);
1624 if (error)
1625 goto done;
1626 error = got_repo_open(&repo, repo_path, NULL);
1627 if (error)
1628 goto done;
1631 fpa.last_scaled_size[0] = '\0';
1632 fpa.last_p_indexed = -1;
1633 fpa.last_p_resolved = -1;
1634 fpa.verbosity = verbosity;
1635 fpa.create_configs = 1;
1636 fpa.configs_created = 0;
1637 fpa.repo = repo;
1638 fpa.config_info.symrefs = &symrefs;
1639 fpa.config_info.wanted_branches = &wanted_branches;
1640 fpa.config_info.wanted_refs = &wanted_refs;
1641 fpa.config_info.proto = proto;
1642 fpa.config_info.host = host;
1643 fpa.config_info.port = port;
1644 fpa.config_info.remote_repo_path = server_path;
1645 fpa.config_info.git_url = git_url;
1646 fpa.config_info.fetch_all_branches = fetch_all_branches;
1647 fpa.config_info.mirror_references = mirror_references;
1648 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1649 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1650 fetch_all_branches, &wanted_branches, &wanted_refs,
1651 list_refs_only, verbosity, fetchfd, repo,
1652 fetch_progress, &fpa);
1653 if (error)
1654 goto done;
1656 if (list_refs_only) {
1657 error = list_remote_refs(&symrefs, &refs);
1658 goto done;
1661 error = got_object_id_str(&id_str, pack_hash);
1662 if (error)
1663 goto done;
1664 if (verbosity >= 0)
1665 printf("\nFetched %s.pack\n", id_str);
1666 free(id_str);
1668 /* Set up references provided with the pack file. */
1669 TAILQ_FOREACH(pe, &refs, entry) {
1670 const char *refname = pe->path;
1671 struct got_object_id *id = pe->data;
1672 char *remote_refname;
1674 if (is_wanted_ref(&wanted_refs, refname) &&
1675 !mirror_references) {
1676 error = create_wanted_ref(refname, id,
1677 GOT_FETCH_DEFAULT_REMOTE_NAME,
1678 verbosity - 1, repo);
1679 if (error)
1680 goto done;
1681 continue;
1684 error = create_ref(refname, id, verbosity - 1, repo);
1685 if (error)
1686 goto done;
1688 if (mirror_references)
1689 continue;
1691 if (strncmp("refs/heads/", refname, 11) != 0)
1692 continue;
1694 if (asprintf(&remote_refname,
1695 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1696 refname + 11) == -1) {
1697 error = got_error_from_errno("asprintf");
1698 goto done;
1700 error = create_ref(remote_refname, id, verbosity - 1, repo);
1701 free(remote_refname);
1702 if (error)
1703 goto done;
1706 /* Set the HEAD reference if the server provided one. */
1707 TAILQ_FOREACH(pe, &symrefs, entry) {
1708 struct got_reference *target_ref;
1709 const char *refname = pe->path;
1710 const char *target = pe->data;
1711 char *remote_refname = NULL, *remote_target = NULL;
1713 if (strcmp(refname, GOT_REF_HEAD) != 0)
1714 continue;
1716 error = got_ref_open(&target_ref, repo, target, 0);
1717 if (error) {
1718 if (error->code == GOT_ERR_NOT_REF) {
1719 error = NULL;
1720 continue;
1722 goto done;
1725 error = create_symref(refname, target_ref, verbosity, repo);
1726 got_ref_close(target_ref);
1727 if (error)
1728 goto done;
1730 if (mirror_references)
1731 continue;
1733 if (strncmp("refs/heads/", target, 11) != 0)
1734 continue;
1736 if (asprintf(&remote_refname,
1737 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1738 refname) == -1) {
1739 error = got_error_from_errno("asprintf");
1740 goto done;
1742 if (asprintf(&remote_target,
1743 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1744 target + 11) == -1) {
1745 error = got_error_from_errno("asprintf");
1746 free(remote_refname);
1747 goto done;
1749 error = got_ref_open(&target_ref, repo, remote_target, 0);
1750 if (error) {
1751 free(remote_refname);
1752 free(remote_target);
1753 if (error->code == GOT_ERR_NOT_REF) {
1754 error = NULL;
1755 continue;
1757 goto done;
1759 error = create_symref(remote_refname, target_ref,
1760 verbosity - 1, repo);
1761 free(remote_refname);
1762 free(remote_target);
1763 got_ref_close(target_ref);
1764 if (error)
1765 goto done;
1767 if (pe == NULL) {
1769 * We failed to set the HEAD reference. If we asked for
1770 * a set of wanted branches use the first of one of those
1771 * which could be fetched instead.
1773 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1774 const char *target = pe->path;
1775 struct got_reference *target_ref;
1777 error = got_ref_open(&target_ref, repo, target, 0);
1778 if (error) {
1779 if (error->code == GOT_ERR_NOT_REF) {
1780 error = NULL;
1781 continue;
1783 goto done;
1786 error = create_symref(GOT_REF_HEAD, target_ref,
1787 verbosity, repo);
1788 got_ref_close(target_ref);
1789 if (error)
1790 goto done;
1791 break;
1795 if (verbosity >= 0)
1796 printf("Created %s repository '%s'\n",
1797 mirror_references ? "mirrored" : "cloned", repo_path);
1798 done:
1799 if (fetchpid > 0) {
1800 if (kill(fetchpid, SIGTERM) == -1)
1801 error = got_error_from_errno("kill");
1802 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1803 error = got_error_from_errno("waitpid");
1805 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1806 error = got_error_from_errno("close");
1807 if (repo) {
1808 const struct got_error *close_err = got_repo_close(repo);
1809 if (error == NULL)
1810 error = close_err;
1812 TAILQ_FOREACH(pe, &refs, entry) {
1813 free((void *)pe->path);
1814 free(pe->data);
1816 got_pathlist_free(&refs);
1817 TAILQ_FOREACH(pe, &symrefs, entry) {
1818 free((void *)pe->path);
1819 free(pe->data);
1821 got_pathlist_free(&symrefs);
1822 got_pathlist_free(&wanted_branches);
1823 got_pathlist_free(&wanted_refs);
1824 free(pack_hash);
1825 free(proto);
1826 free(host);
1827 free(port);
1828 free(server_path);
1829 free(repo_name);
1830 free(default_destdir);
1831 free(git_url);
1832 return error;
1835 static const struct got_error *
1836 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1837 int replace_tags, int verbosity, struct got_repository *repo)
1839 const struct got_error *err = NULL;
1840 char *new_id_str = NULL;
1841 struct got_object_id *old_id = NULL;
1843 err = got_object_id_str(&new_id_str, new_id);
1844 if (err)
1845 goto done;
1847 if (!replace_tags &&
1848 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1849 err = got_ref_resolve(&old_id, repo, ref);
1850 if (err)
1851 goto done;
1852 if (got_object_id_cmp(old_id, new_id) == 0)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Rejecting update of existing tag %s: %s\n",
1856 got_ref_get_name(ref), new_id_str);
1858 goto done;
1861 if (got_ref_is_symbolic(ref)) {
1862 if (verbosity >= 0) {
1863 printf("Replacing reference %s: %s\n",
1864 got_ref_get_name(ref),
1865 got_ref_get_symref_target(ref));
1867 err = got_ref_change_symref_to_ref(ref, new_id);
1868 if (err)
1869 goto done;
1870 err = got_ref_write(ref, repo);
1871 if (err)
1872 goto done;
1873 } else {
1874 err = got_ref_resolve(&old_id, repo, ref);
1875 if (err)
1876 goto done;
1877 if (got_object_id_cmp(old_id, new_id) == 0)
1878 goto done;
1880 err = got_ref_change_ref(ref, new_id);
1881 if (err)
1882 goto done;
1883 err = got_ref_write(ref, repo);
1884 if (err)
1885 goto done;
1888 if (verbosity >= 0)
1889 printf("Updated %s: %s\n", got_ref_get_name(ref),
1890 new_id_str);
1891 done:
1892 free(old_id);
1893 free(new_id_str);
1894 return err;
1897 static const struct got_error *
1898 update_symref(const char *refname, struct got_reference *target_ref,
1899 int verbosity, struct got_repository *repo)
1901 const struct got_error *err = NULL, *unlock_err;
1902 struct got_reference *symref;
1903 int symref_is_locked = 0;
1905 err = got_ref_open(&symref, repo, refname, 1);
1906 if (err) {
1907 if (err->code != GOT_ERR_NOT_REF)
1908 return err;
1909 err = got_ref_alloc_symref(&symref, refname, target_ref);
1910 if (err)
1911 goto done;
1913 err = got_ref_write(symref, repo);
1914 if (err)
1915 goto done;
1917 if (verbosity >= 0)
1918 printf("Created reference %s: %s\n",
1919 got_ref_get_name(symref),
1920 got_ref_get_symref_target(symref));
1921 } else {
1922 symref_is_locked = 1;
1924 if (strcmp(got_ref_get_symref_target(symref),
1925 got_ref_get_name(target_ref)) == 0)
1926 goto done;
1928 err = got_ref_change_symref(symref,
1929 got_ref_get_name(target_ref));
1930 if (err)
1931 goto done;
1933 err = got_ref_write(symref, repo);
1934 if (err)
1935 goto done;
1937 if (verbosity >= 0)
1938 printf("Updated %s: %s\n", got_ref_get_name(symref),
1939 got_ref_get_symref_target(symref));
1942 done:
1943 if (symref_is_locked) {
1944 unlock_err = got_ref_unlock(symref);
1945 if (unlock_err && err == NULL)
1946 err = unlock_err;
1948 got_ref_close(symref);
1949 return err;
1952 __dead static void
1953 usage_fetch(void)
1955 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1956 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1957 "[remote-repository-name]\n",
1958 getprogname());
1959 exit(1);
1962 static const struct got_error *
1963 delete_missing_ref(struct got_reference *ref,
1964 int verbosity, struct got_repository *repo)
1966 const struct got_error *err = NULL;
1967 struct got_object_id *id = NULL;
1968 char *id_str = NULL;
1970 if (got_ref_is_symbolic(ref)) {
1971 err = got_ref_delete(ref, repo);
1972 if (err)
1973 return err;
1974 if (verbosity >= 0) {
1975 printf("Deleted %s: %s\n",
1976 got_ref_get_name(ref),
1977 got_ref_get_symref_target(ref));
1979 } else {
1980 err = got_ref_resolve(&id, repo, ref);
1981 if (err)
1982 return err;
1983 err = got_object_id_str(&id_str, id);
1984 if (err)
1985 goto done;
1987 err = got_ref_delete(ref, repo);
1988 if (err)
1989 goto done;
1990 if (verbosity >= 0) {
1991 printf("Deleted %s: %s\n",
1992 got_ref_get_name(ref), id_str);
1995 done:
1996 free(id);
1997 free(id_str);
1998 return NULL;
2001 static const struct got_error *
2002 delete_missing_refs(struct got_pathlist_head *their_refs,
2003 struct got_pathlist_head *their_symrefs,
2004 const struct got_remote_repo *remote,
2005 int verbosity, struct got_repository *repo)
2007 const struct got_error *err = NULL, *unlock_err;
2008 struct got_reflist_head my_refs;
2009 struct got_reflist_entry *re;
2010 struct got_pathlist_entry *pe;
2011 char *remote_namespace = NULL;
2012 char *local_refname = NULL;
2014 TAILQ_INIT(&my_refs);
2016 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2017 == -1)
2018 return got_error_from_errno("asprintf");
2020 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2021 if (err)
2022 goto done;
2024 TAILQ_FOREACH(re, &my_refs, entry) {
2025 const char *refname = got_ref_get_name(re->ref);
2027 if (!remote->mirror_references) {
2028 if (strncmp(refname, remote_namespace,
2029 strlen(remote_namespace)) == 0) {
2030 if (strcmp(refname + strlen(remote_namespace),
2031 GOT_REF_HEAD) == 0)
2032 continue;
2033 if (asprintf(&local_refname, "refs/heads/%s",
2034 refname + strlen(remote_namespace)) == -1) {
2035 err = got_error_from_errno("asprintf");
2036 goto done;
2038 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2039 continue;
2042 TAILQ_FOREACH(pe, their_refs, entry) {
2043 if (strcmp(local_refname, pe->path) == 0)
2044 break;
2046 if (pe != NULL)
2047 continue;
2049 TAILQ_FOREACH(pe, their_symrefs, entry) {
2050 if (strcmp(local_refname, pe->path) == 0)
2051 break;
2053 if (pe != NULL)
2054 continue;
2056 err = delete_missing_ref(re->ref, verbosity, repo);
2057 if (err)
2058 break;
2060 if (local_refname) {
2061 struct got_reference *ref;
2062 err = got_ref_open(&ref, repo, local_refname, 1);
2063 if (err) {
2064 if (err->code != GOT_ERR_NOT_REF)
2065 break;
2066 free(local_refname);
2067 local_refname = NULL;
2068 continue;
2070 err = delete_missing_ref(ref, verbosity, repo);
2071 if (err)
2072 break;
2073 unlock_err = got_ref_unlock(ref);
2074 got_ref_close(ref);
2075 if (unlock_err && err == NULL) {
2076 err = unlock_err;
2077 break;
2080 free(local_refname);
2081 local_refname = NULL;
2084 done:
2085 free(remote_namespace);
2086 free(local_refname);
2087 return err;
2090 static const struct got_error *
2091 update_wanted_ref(const char *refname, struct got_object_id *id,
2092 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2094 const struct got_error *err, *unlock_err;
2095 char *remote_refname;
2096 struct got_reference *ref;
2098 if (strncmp("refs/", refname, 5) == 0)
2099 refname += 5;
2101 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2102 remote_repo_name, refname) == -1)
2103 return got_error_from_errno("asprintf");
2105 err = got_ref_open(&ref, repo, remote_refname, 1);
2106 if (err) {
2107 if (err->code != GOT_ERR_NOT_REF)
2108 goto done;
2109 err = create_ref(remote_refname, id, verbosity, repo);
2110 } else {
2111 err = update_ref(ref, id, 0, verbosity, repo);
2112 unlock_err = got_ref_unlock(ref);
2113 if (unlock_err && err == NULL)
2114 err = unlock_err;
2115 got_ref_close(ref);
2117 done:
2118 free(remote_refname);
2119 return err;
2122 static const struct got_error *
2123 delete_ref(struct got_repository *repo, struct got_reference *ref)
2125 const struct got_error *err = NULL;
2126 struct got_object_id *id = NULL;
2127 char *id_str = NULL;
2128 const char *target;
2130 if (got_ref_is_symbolic(ref)) {
2131 target = got_ref_get_symref_target(ref);
2132 } else {
2133 err = got_ref_resolve(&id, repo, ref);
2134 if (err)
2135 goto done;
2136 err = got_object_id_str(&id_str, id);
2137 if (err)
2138 goto done;
2139 target = id_str;
2142 err = got_ref_delete(ref, repo);
2143 if (err)
2144 goto done;
2146 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2147 done:
2148 free(id);
2149 free(id_str);
2150 return err;
2153 static const struct got_error *
2154 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2156 const struct got_error *err = NULL;
2157 struct got_reflist_head refs;
2158 struct got_reflist_entry *re;
2159 char *prefix;
2161 TAILQ_INIT(&refs);
2163 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2164 err = got_error_from_errno("asprintf");
2165 goto done;
2167 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2168 if (err)
2169 goto done;
2171 TAILQ_FOREACH(re, &refs, entry)
2172 delete_ref(repo, re->ref);
2173 done:
2174 got_ref_list_free(&refs);
2175 return err;
2178 static const struct got_error *
2179 cmd_fetch(int argc, char *argv[])
2181 const struct got_error *error = NULL, *unlock_err;
2182 char *cwd = NULL, *repo_path = NULL;
2183 const char *remote_name;
2184 char *proto = NULL, *host = NULL, *port = NULL;
2185 char *repo_name = NULL, *server_path = NULL;
2186 const struct got_remote_repo *remotes, *remote = NULL;
2187 int nremotes;
2188 char *id_str = NULL;
2189 struct got_repository *repo = NULL;
2190 struct got_worktree *worktree = NULL;
2191 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2192 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2193 struct got_pathlist_entry *pe;
2194 struct got_object_id *pack_hash = NULL;
2195 int i, ch, fetchfd = -1, fetchstatus;
2196 pid_t fetchpid = -1;
2197 struct got_fetch_progress_arg fpa;
2198 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2199 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2201 TAILQ_INIT(&refs);
2202 TAILQ_INIT(&symrefs);
2203 TAILQ_INIT(&wanted_branches);
2204 TAILQ_INIT(&wanted_refs);
2206 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2207 switch (ch) {
2208 case 'a':
2209 fetch_all_branches = 1;
2210 break;
2211 case 'b':
2212 error = got_pathlist_append(&wanted_branches,
2213 optarg, NULL);
2214 if (error)
2215 return error;
2216 break;
2217 case 'd':
2218 delete_refs = 1;
2219 break;
2220 case 'l':
2221 list_refs_only = 1;
2222 break;
2223 case 'r':
2224 repo_path = realpath(optarg, NULL);
2225 if (repo_path == NULL)
2226 return got_error_from_errno2("realpath",
2227 optarg);
2228 got_path_strip_trailing_slashes(repo_path);
2229 break;
2230 case 't':
2231 replace_tags = 1;
2232 break;
2233 case 'v':
2234 if (verbosity < 0)
2235 verbosity = 0;
2236 else if (verbosity < 3)
2237 verbosity++;
2238 break;
2239 case 'q':
2240 verbosity = -1;
2241 break;
2242 case 'R':
2243 error = got_pathlist_append(&wanted_refs,
2244 optarg, NULL);
2245 if (error)
2246 return error;
2247 break;
2248 case 'X':
2249 delete_remote = 1;
2250 break;
2251 default:
2252 usage_fetch();
2253 break;
2256 argc -= optind;
2257 argv += optind;
2259 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2260 option_conflict('a', 'b');
2261 if (list_refs_only) {
2262 if (!TAILQ_EMPTY(&wanted_branches))
2263 option_conflict('l', 'b');
2264 if (fetch_all_branches)
2265 option_conflict('l', 'a');
2266 if (delete_refs)
2267 option_conflict('l', 'd');
2268 if (delete_remote)
2269 option_conflict('l', 'X');
2271 if (delete_remote) {
2272 if (fetch_all_branches)
2273 option_conflict('X', 'a');
2274 if (!TAILQ_EMPTY(&wanted_branches))
2275 option_conflict('X', 'b');
2276 if (delete_refs)
2277 option_conflict('X', 'd');
2278 if (replace_tags)
2279 option_conflict('X', 't');
2280 if (!TAILQ_EMPTY(&wanted_refs))
2281 option_conflict('X', 'R');
2284 if (argc == 0) {
2285 if (delete_remote)
2286 errx(1, "-X option requires a remote name");
2287 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2288 } else if (argc == 1)
2289 remote_name = argv[0];
2290 else
2291 usage_fetch();
2293 cwd = getcwd(NULL, 0);
2294 if (cwd == NULL) {
2295 error = got_error_from_errno("getcwd");
2296 goto done;
2299 if (repo_path == NULL) {
2300 error = got_worktree_open(&worktree, cwd);
2301 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2302 goto done;
2303 else
2304 error = NULL;
2305 if (worktree) {
2306 repo_path =
2307 strdup(got_worktree_get_repo_path(worktree));
2308 if (repo_path == NULL)
2309 error = got_error_from_errno("strdup");
2310 if (error)
2311 goto done;
2312 } else {
2313 repo_path = strdup(cwd);
2314 if (repo_path == NULL) {
2315 error = got_error_from_errno("strdup");
2316 goto done;
2321 error = got_repo_open(&repo, repo_path, NULL);
2322 if (error)
2323 goto done;
2325 if (delete_remote) {
2326 error = delete_refs_for_remote(repo, remote_name);
2327 goto done; /* nothing else to do */
2330 if (worktree) {
2331 worktree_conf = got_worktree_get_gotconfig(worktree);
2332 if (worktree_conf) {
2333 got_gotconfig_get_remotes(&nremotes, &remotes,
2334 worktree_conf);
2335 for (i = 0; i < nremotes; i++) {
2336 if (strcmp(remotes[i].name, remote_name) == 0) {
2337 remote = &remotes[i];
2338 break;
2343 if (remote == NULL) {
2344 repo_conf = got_repo_get_gotconfig(repo);
2345 if (repo_conf) {
2346 got_gotconfig_get_remotes(&nremotes, &remotes,
2347 repo_conf);
2348 for (i = 0; i < nremotes; i++) {
2349 if (strcmp(remotes[i].name, remote_name) == 0) {
2350 remote = &remotes[i];
2351 break;
2356 if (remote == NULL) {
2357 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2358 for (i = 0; i < nremotes; i++) {
2359 if (strcmp(remotes[i].name, remote_name) == 0) {
2360 remote = &remotes[i];
2361 break;
2365 if (remote == NULL) {
2366 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2367 goto done;
2370 if (TAILQ_EMPTY(&wanted_branches)) {
2371 if (!fetch_all_branches)
2372 fetch_all_branches = remote->fetch_all_branches;
2373 for (i = 0; i < remote->nfetch_branches; i++) {
2374 got_pathlist_append(&wanted_branches,
2375 remote->fetch_branches[i], NULL);
2378 if (TAILQ_EMPTY(&wanted_refs)) {
2379 for (i = 0; i < remote->nfetch_refs; i++) {
2380 got_pathlist_append(&wanted_refs,
2381 remote->fetch_refs[i], NULL);
2385 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2386 &repo_name, remote->fetch_url);
2387 if (error)
2388 goto done;
2390 if (strcmp(proto, "git") == 0) {
2391 #ifndef PROFILE
2392 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2393 "sendfd dns inet unveil", NULL) == -1)
2394 err(1, "pledge");
2395 #endif
2396 } else if (strcmp(proto, "git+ssh") == 0 ||
2397 strcmp(proto, "ssh") == 0) {
2398 #ifndef PROFILE
2399 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2400 "sendfd unveil", NULL) == -1)
2401 err(1, "pledge");
2402 #endif
2403 } else if (strcmp(proto, "http") == 0 ||
2404 strcmp(proto, "git+http") == 0) {
2405 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2406 goto done;
2407 } else {
2408 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2409 goto done;
2412 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2413 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2414 error = got_error_from_errno2("unveil",
2415 GOT_FETCH_PATH_SSH);
2416 goto done;
2419 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2420 if (error)
2421 goto done;
2423 if (verbosity >= 0)
2424 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2425 port ? ":" : "", port ? port : "");
2427 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2428 server_path, verbosity);
2429 if (error)
2430 goto done;
2432 fpa.last_scaled_size[0] = '\0';
2433 fpa.last_p_indexed = -1;
2434 fpa.last_p_resolved = -1;
2435 fpa.verbosity = verbosity;
2436 fpa.repo = repo;
2437 fpa.create_configs = 0;
2438 fpa.configs_created = 0;
2439 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2440 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2441 remote->mirror_references, fetch_all_branches, &wanted_branches,
2442 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2443 fetch_progress, &fpa);
2444 if (error)
2445 goto done;
2447 if (list_refs_only) {
2448 error = list_remote_refs(&symrefs, &refs);
2449 goto done;
2452 if (pack_hash == NULL) {
2453 if (verbosity >= 0)
2454 printf("Already up-to-date\n");
2455 } else if (verbosity >= 0) {
2456 error = got_object_id_str(&id_str, pack_hash);
2457 if (error)
2458 goto done;
2459 printf("\nFetched %s.pack\n", id_str);
2460 free(id_str);
2461 id_str = NULL;
2464 /* Update references provided with the pack file. */
2465 TAILQ_FOREACH(pe, &refs, entry) {
2466 const char *refname = pe->path;
2467 struct got_object_id *id = pe->data;
2468 struct got_reference *ref;
2469 char *remote_refname;
2471 if (is_wanted_ref(&wanted_refs, refname) &&
2472 !remote->mirror_references) {
2473 error = update_wanted_ref(refname, id,
2474 remote->name, verbosity, repo);
2475 if (error)
2476 goto done;
2477 continue;
2480 if (remote->mirror_references ||
2481 strncmp("refs/tags/", refname, 10) == 0) {
2482 error = got_ref_open(&ref, repo, refname, 1);
2483 if (error) {
2484 if (error->code != GOT_ERR_NOT_REF)
2485 goto done;
2486 error = create_ref(refname, id, verbosity,
2487 repo);
2488 if (error)
2489 goto done;
2490 } else {
2491 error = update_ref(ref, id, replace_tags,
2492 verbosity, repo);
2493 unlock_err = got_ref_unlock(ref);
2494 if (unlock_err && error == NULL)
2495 error = unlock_err;
2496 got_ref_close(ref);
2497 if (error)
2498 goto done;
2500 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2501 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2502 remote_name, refname + 11) == -1) {
2503 error = got_error_from_errno("asprintf");
2504 goto done;
2507 error = got_ref_open(&ref, repo, remote_refname, 1);
2508 if (error) {
2509 if (error->code != GOT_ERR_NOT_REF)
2510 goto done;
2511 error = create_ref(remote_refname, id,
2512 verbosity, repo);
2513 if (error)
2514 goto done;
2515 } else {
2516 error = update_ref(ref, id, replace_tags,
2517 verbosity, repo);
2518 unlock_err = got_ref_unlock(ref);
2519 if (unlock_err && error == NULL)
2520 error = unlock_err;
2521 got_ref_close(ref);
2522 if (error)
2523 goto done;
2526 /* Also create a local branch if none exists yet. */
2527 error = got_ref_open(&ref, repo, refname, 1);
2528 if (error) {
2529 if (error->code != GOT_ERR_NOT_REF)
2530 goto done;
2531 error = create_ref(refname, id, verbosity,
2532 repo);
2533 if (error)
2534 goto done;
2535 } else {
2536 unlock_err = got_ref_unlock(ref);
2537 if (unlock_err && error == NULL)
2538 error = unlock_err;
2539 got_ref_close(ref);
2543 if (delete_refs) {
2544 error = delete_missing_refs(&refs, &symrefs, remote,
2545 verbosity, repo);
2546 if (error)
2547 goto done;
2550 if (!remote->mirror_references) {
2551 /* Update remote HEAD reference if the server provided one. */
2552 TAILQ_FOREACH(pe, &symrefs, entry) {
2553 struct got_reference *target_ref;
2554 const char *refname = pe->path;
2555 const char *target = pe->data;
2556 char *remote_refname = NULL, *remote_target = NULL;
2558 if (strcmp(refname, GOT_REF_HEAD) != 0)
2559 continue;
2561 if (strncmp("refs/heads/", target, 11) != 0)
2562 continue;
2564 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2565 remote->name, refname) == -1) {
2566 error = got_error_from_errno("asprintf");
2567 goto done;
2569 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2570 remote->name, target + 11) == -1) {
2571 error = got_error_from_errno("asprintf");
2572 free(remote_refname);
2573 goto done;
2576 error = got_ref_open(&target_ref, repo, remote_target,
2577 0);
2578 if (error) {
2579 free(remote_refname);
2580 free(remote_target);
2581 if (error->code == GOT_ERR_NOT_REF) {
2582 error = NULL;
2583 continue;
2585 goto done;
2587 error = update_symref(remote_refname, target_ref,
2588 verbosity, repo);
2589 free(remote_refname);
2590 free(remote_target);
2591 got_ref_close(target_ref);
2592 if (error)
2593 goto done;
2596 done:
2597 if (fetchpid > 0) {
2598 if (kill(fetchpid, SIGTERM) == -1)
2599 error = got_error_from_errno("kill");
2600 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2601 error = got_error_from_errno("waitpid");
2603 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2604 error = got_error_from_errno("close");
2605 if (repo) {
2606 const struct got_error *close_err = got_repo_close(repo);
2607 if (error == NULL)
2608 error = close_err;
2610 if (worktree)
2611 got_worktree_close(worktree);
2612 TAILQ_FOREACH(pe, &refs, entry) {
2613 free((void *)pe->path);
2614 free(pe->data);
2616 got_pathlist_free(&refs);
2617 TAILQ_FOREACH(pe, &symrefs, entry) {
2618 free((void *)pe->path);
2619 free(pe->data);
2621 got_pathlist_free(&symrefs);
2622 got_pathlist_free(&wanted_branches);
2623 got_pathlist_free(&wanted_refs);
2624 free(id_str);
2625 free(cwd);
2626 free(repo_path);
2627 free(pack_hash);
2628 free(proto);
2629 free(host);
2630 free(port);
2631 free(server_path);
2632 free(repo_name);
2633 return error;
2637 __dead static void
2638 usage_checkout(void)
2640 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2641 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2642 exit(1);
2645 static void
2646 show_worktree_base_ref_warning(void)
2648 fprintf(stderr, "%s: warning: could not create a reference "
2649 "to the work tree's base commit; the commit could be "
2650 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2651 "repository writable and running 'got update' will prevent this\n",
2652 getprogname());
2655 struct got_checkout_progress_arg {
2656 const char *worktree_path;
2657 int had_base_commit_ref_error;
2660 static const struct got_error *
2661 checkout_progress(void *arg, unsigned char status, const char *path)
2663 struct got_checkout_progress_arg *a = arg;
2665 /* Base commit bump happens silently. */
2666 if (status == GOT_STATUS_BUMP_BASE)
2667 return NULL;
2669 if (status == GOT_STATUS_BASE_REF_ERR) {
2670 a->had_base_commit_ref_error = 1;
2671 return NULL;
2674 while (path[0] == '/')
2675 path++;
2677 printf("%c %s/%s\n", status, a->worktree_path, path);
2678 return NULL;
2681 static const struct got_error *
2682 check_cancelled(void *arg)
2684 if (sigint_received || sigpipe_received)
2685 return got_error(GOT_ERR_CANCELLED);
2686 return NULL;
2689 static const struct got_error *
2690 check_linear_ancestry(struct got_object_id *commit_id,
2691 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2692 struct got_repository *repo)
2694 const struct got_error *err = NULL;
2695 struct got_object_id *yca_id;
2697 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2698 commit_id, base_commit_id, repo, check_cancelled, NULL);
2699 if (err)
2700 return err;
2702 if (yca_id == NULL)
2703 return got_error(GOT_ERR_ANCESTRY);
2706 * Require a straight line of history between the target commit
2707 * and the work tree's base commit.
2709 * Non-linear situations such as this require a rebase:
2711 * (commit) D F (base_commit)
2712 * \ /
2713 * C E
2714 * \ /
2715 * B (yca)
2716 * |
2717 * A
2719 * 'got update' only handles linear cases:
2720 * Update forwards in time: A (base/yca) - B - C - D (commit)
2721 * Update backwards in time: D (base) - C - B - A (commit/yca)
2723 if (allow_forwards_in_time_only) {
2724 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2725 return got_error(GOT_ERR_ANCESTRY);
2726 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2727 got_object_id_cmp(base_commit_id, yca_id) != 0)
2728 return got_error(GOT_ERR_ANCESTRY);
2730 free(yca_id);
2731 return NULL;
2734 static const struct got_error *
2735 check_same_branch(struct got_object_id *commit_id,
2736 struct got_reference *head_ref, struct got_object_id *yca_id,
2737 struct got_repository *repo)
2739 const struct got_error *err = NULL;
2740 struct got_commit_graph *graph = NULL;
2741 struct got_object_id *head_commit_id = NULL;
2742 int is_same_branch = 0;
2744 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2745 if (err)
2746 goto done;
2748 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2749 is_same_branch = 1;
2750 goto done;
2752 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2753 is_same_branch = 1;
2754 goto done;
2757 err = got_commit_graph_open(&graph, "/", 1);
2758 if (err)
2759 goto done;
2761 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2762 check_cancelled, NULL);
2763 if (err)
2764 goto done;
2766 for (;;) {
2767 struct got_object_id *id;
2768 err = got_commit_graph_iter_next(&id, graph, repo,
2769 check_cancelled, NULL);
2770 if (err) {
2771 if (err->code == GOT_ERR_ITER_COMPLETED)
2772 err = NULL;
2773 break;
2776 if (id) {
2777 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2778 break;
2779 if (got_object_id_cmp(id, commit_id) == 0) {
2780 is_same_branch = 1;
2781 break;
2785 done:
2786 if (graph)
2787 got_commit_graph_close(graph);
2788 free(head_commit_id);
2789 if (!err && !is_same_branch)
2790 err = got_error(GOT_ERR_ANCESTRY);
2791 return err;
2794 static const struct got_error *
2795 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2797 static char msg[512];
2798 const char *branch_name;
2800 if (got_ref_is_symbolic(ref))
2801 branch_name = got_ref_get_symref_target(ref);
2802 else
2803 branch_name = got_ref_get_name(ref);
2805 if (strncmp("refs/heads/", branch_name, 11) == 0)
2806 branch_name += 11;
2808 snprintf(msg, sizeof(msg),
2809 "target commit is not contained in branch '%s'; "
2810 "the branch to use must be specified with -b; "
2811 "if necessary a new branch can be created for "
2812 "this commit with 'got branch -c %s BRANCH_NAME'",
2813 branch_name, commit_id_str);
2815 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2818 static const struct got_error *
2819 cmd_checkout(int argc, char *argv[])
2821 const struct got_error *error = NULL;
2822 struct got_repository *repo = NULL;
2823 struct got_reference *head_ref = NULL;
2824 struct got_worktree *worktree = NULL;
2825 char *repo_path = NULL;
2826 char *worktree_path = NULL;
2827 const char *path_prefix = "";
2828 const char *branch_name = GOT_REF_HEAD;
2829 char *commit_id_str = NULL;
2830 char *cwd = NULL;
2831 int ch, same_path_prefix, allow_nonempty = 0;
2832 struct got_pathlist_head paths;
2833 struct got_checkout_progress_arg cpa;
2835 TAILQ_INIT(&paths);
2837 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2838 switch (ch) {
2839 case 'b':
2840 branch_name = optarg;
2841 break;
2842 case 'c':
2843 commit_id_str = strdup(optarg);
2844 if (commit_id_str == NULL)
2845 return got_error_from_errno("strdup");
2846 break;
2847 case 'E':
2848 allow_nonempty = 1;
2849 break;
2850 case 'p':
2851 path_prefix = optarg;
2852 break;
2853 default:
2854 usage_checkout();
2855 /* NOTREACHED */
2859 argc -= optind;
2860 argv += optind;
2862 #ifndef PROFILE
2863 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2864 "unveil", NULL) == -1)
2865 err(1, "pledge");
2866 #endif
2867 if (argc == 1) {
2868 char *base, *dotgit;
2869 const char *path;
2870 repo_path = realpath(argv[0], NULL);
2871 if (repo_path == NULL)
2872 return got_error_from_errno2("realpath", argv[0]);
2873 cwd = getcwd(NULL, 0);
2874 if (cwd == NULL) {
2875 error = got_error_from_errno("getcwd");
2876 goto done;
2878 if (path_prefix[0])
2879 path = path_prefix;
2880 else
2881 path = repo_path;
2882 error = got_path_basename(&base, path);
2883 if (error)
2884 goto done;
2885 dotgit = strstr(base, ".git");
2886 if (dotgit)
2887 *dotgit = '\0';
2888 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2889 error = got_error_from_errno("asprintf");
2890 free(base);
2891 goto done;
2893 free(base);
2894 } else if (argc == 2) {
2895 repo_path = realpath(argv[0], NULL);
2896 if (repo_path == NULL) {
2897 error = got_error_from_errno2("realpath", argv[0]);
2898 goto done;
2900 worktree_path = realpath(argv[1], NULL);
2901 if (worktree_path == NULL) {
2902 if (errno != ENOENT) {
2903 error = got_error_from_errno2("realpath",
2904 argv[1]);
2905 goto done;
2907 worktree_path = strdup(argv[1]);
2908 if (worktree_path == NULL) {
2909 error = got_error_from_errno("strdup");
2910 goto done;
2913 } else
2914 usage_checkout();
2916 got_path_strip_trailing_slashes(repo_path);
2917 got_path_strip_trailing_slashes(worktree_path);
2919 error = got_repo_open(&repo, repo_path, NULL);
2920 if (error != NULL)
2921 goto done;
2923 /* Pre-create work tree path for unveil(2) */
2924 error = got_path_mkdir(worktree_path);
2925 if (error) {
2926 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2927 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2928 goto done;
2929 if (!allow_nonempty &&
2930 !got_path_dir_is_empty(worktree_path)) {
2931 error = got_error_path(worktree_path,
2932 GOT_ERR_DIR_NOT_EMPTY);
2933 goto done;
2937 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2938 if (error)
2939 goto done;
2941 error = got_ref_open(&head_ref, repo, branch_name, 0);
2942 if (error != NULL)
2943 goto done;
2945 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2946 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2947 goto done;
2949 error = got_worktree_open(&worktree, worktree_path);
2950 if (error != NULL)
2951 goto done;
2953 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2954 path_prefix);
2955 if (error != NULL)
2956 goto done;
2957 if (!same_path_prefix) {
2958 error = got_error(GOT_ERR_PATH_PREFIX);
2959 goto done;
2962 if (commit_id_str) {
2963 struct got_object_id *commit_id;
2964 struct got_reflist_head refs;
2965 TAILQ_INIT(&refs);
2966 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2967 NULL);
2968 if (error)
2969 goto done;
2970 error = got_repo_match_object_id(&commit_id, NULL,
2971 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2972 got_ref_list_free(&refs);
2973 if (error)
2974 goto done;
2975 error = check_linear_ancestry(commit_id,
2976 got_worktree_get_base_commit_id(worktree), 0, repo);
2977 if (error != NULL) {
2978 free(commit_id);
2979 if (error->code == GOT_ERR_ANCESTRY) {
2980 error = checkout_ancestry_error(
2981 head_ref, commit_id_str);
2983 goto done;
2985 error = check_same_branch(commit_id, head_ref, NULL, repo);
2986 if (error) {
2987 if (error->code == GOT_ERR_ANCESTRY) {
2988 error = checkout_ancestry_error(
2989 head_ref, commit_id_str);
2991 goto done;
2993 error = got_worktree_set_base_commit_id(worktree, repo,
2994 commit_id);
2995 free(commit_id);
2996 if (error)
2997 goto done;
3000 error = got_pathlist_append(&paths, "", NULL);
3001 if (error)
3002 goto done;
3003 cpa.worktree_path = worktree_path;
3004 cpa.had_base_commit_ref_error = 0;
3005 error = got_worktree_checkout_files(worktree, &paths, repo,
3006 checkout_progress, &cpa, check_cancelled, NULL);
3007 if (error != NULL)
3008 goto done;
3010 printf("Now shut up and hack\n");
3011 if (cpa.had_base_commit_ref_error)
3012 show_worktree_base_ref_warning();
3013 done:
3014 got_pathlist_free(&paths);
3015 free(commit_id_str);
3016 free(repo_path);
3017 free(worktree_path);
3018 free(cwd);
3019 return error;
3022 struct got_update_progress_arg {
3023 int did_something;
3024 int conflicts;
3025 int obstructed;
3026 int not_updated;
3029 void
3030 print_update_progress_stats(struct got_update_progress_arg *upa)
3032 if (!upa->did_something)
3033 return;
3035 if (upa->conflicts > 0)
3036 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3037 if (upa->obstructed > 0)
3038 printf("File paths obstructed by a non-regular file: %d\n",
3039 upa->obstructed);
3040 if (upa->not_updated > 0)
3041 printf("Files not updated because of existing merge "
3042 "conflicts: %d\n", upa->not_updated);
3045 __dead static void
3046 usage_update(void)
3048 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
3049 getprogname());
3050 exit(1);
3053 static const struct got_error *
3054 update_progress(void *arg, unsigned char status, const char *path)
3056 struct got_update_progress_arg *upa = arg;
3058 if (status == GOT_STATUS_EXISTS ||
3059 status == GOT_STATUS_BASE_REF_ERR)
3060 return NULL;
3062 upa->did_something = 1;
3064 /* Base commit bump happens silently. */
3065 if (status == GOT_STATUS_BUMP_BASE)
3066 return NULL;
3068 if (status == GOT_STATUS_CONFLICT)
3069 upa->conflicts++;
3070 if (status == GOT_STATUS_OBSTRUCTED)
3071 upa->obstructed++;
3072 if (status == GOT_STATUS_CANNOT_UPDATE)
3073 upa->not_updated++;
3075 while (path[0] == '/')
3076 path++;
3077 printf("%c %s\n", status, path);
3078 return NULL;
3081 static const struct got_error *
3082 switch_head_ref(struct got_reference *head_ref,
3083 struct got_object_id *commit_id, struct got_worktree *worktree,
3084 struct got_repository *repo)
3086 const struct got_error *err = NULL;
3087 char *base_id_str;
3088 int ref_has_moved = 0;
3090 /* Trivial case: switching between two different references. */
3091 if (strcmp(got_ref_get_name(head_ref),
3092 got_worktree_get_head_ref_name(worktree)) != 0) {
3093 printf("Switching work tree from %s to %s\n",
3094 got_worktree_get_head_ref_name(worktree),
3095 got_ref_get_name(head_ref));
3096 return got_worktree_set_head_ref(worktree, head_ref);
3099 err = check_linear_ancestry(commit_id,
3100 got_worktree_get_base_commit_id(worktree), 0, repo);
3101 if (err) {
3102 if (err->code != GOT_ERR_ANCESTRY)
3103 return err;
3104 ref_has_moved = 1;
3106 if (!ref_has_moved)
3107 return NULL;
3109 /* Switching to a rebased branch with the same reference name. */
3110 err = got_object_id_str(&base_id_str,
3111 got_worktree_get_base_commit_id(worktree));
3112 if (err)
3113 return err;
3114 printf("Reference %s now points at a different branch\n",
3115 got_worktree_get_head_ref_name(worktree));
3116 printf("Switching work tree from %s to %s\n", base_id_str,
3117 got_worktree_get_head_ref_name(worktree));
3118 return NULL;
3121 static const struct got_error *
3122 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3124 const struct got_error *err;
3125 int in_progress;
3127 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3128 if (err)
3129 return err;
3130 if (in_progress)
3131 return got_error(GOT_ERR_REBASING);
3133 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3134 if (err)
3135 return err;
3136 if (in_progress)
3137 return got_error(GOT_ERR_HISTEDIT_BUSY);
3139 return NULL;
3142 static const struct got_error *
3143 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3144 char *argv[], struct got_worktree *worktree)
3146 const struct got_error *err = NULL;
3147 char *path;
3148 int i;
3150 if (argc == 0) {
3151 path = strdup("");
3152 if (path == NULL)
3153 return got_error_from_errno("strdup");
3154 return got_pathlist_append(paths, path, NULL);
3157 for (i = 0; i < argc; i++) {
3158 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3159 if (err)
3160 break;
3161 err = got_pathlist_append(paths, path, NULL);
3162 if (err) {
3163 free(path);
3164 break;
3168 return err;
3171 static const struct got_error *
3172 wrap_not_worktree_error(const struct got_error *orig_err,
3173 const char *cmdname, const char *path)
3175 const struct got_error *err;
3176 struct got_repository *repo;
3177 static char msg[512];
3179 err = got_repo_open(&repo, path, NULL);
3180 if (err)
3181 return orig_err;
3183 snprintf(msg, sizeof(msg),
3184 "'got %s' needs a work tree in addition to a git repository\n"
3185 "Work trees can be checked out from this Git repository with "
3186 "'got checkout'.\n"
3187 "The got(1) manual page contains more information.", cmdname);
3188 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3189 got_repo_close(repo);
3190 return err;
3193 static const struct got_error *
3194 cmd_update(int argc, char *argv[])
3196 const struct got_error *error = NULL;
3197 struct got_repository *repo = NULL;
3198 struct got_worktree *worktree = NULL;
3199 char *worktree_path = NULL;
3200 struct got_object_id *commit_id = NULL;
3201 char *commit_id_str = NULL;
3202 const char *branch_name = NULL;
3203 struct got_reference *head_ref = NULL;
3204 struct got_pathlist_head paths;
3205 struct got_pathlist_entry *pe;
3206 int ch;
3207 struct got_update_progress_arg upa;
3209 TAILQ_INIT(&paths);
3211 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3212 switch (ch) {
3213 case 'b':
3214 branch_name = optarg;
3215 break;
3216 case 'c':
3217 commit_id_str = strdup(optarg);
3218 if (commit_id_str == NULL)
3219 return got_error_from_errno("strdup");
3220 break;
3221 default:
3222 usage_update();
3223 /* NOTREACHED */
3227 argc -= optind;
3228 argv += optind;
3230 #ifndef PROFILE
3231 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3232 "unveil", NULL) == -1)
3233 err(1, "pledge");
3234 #endif
3235 worktree_path = getcwd(NULL, 0);
3236 if (worktree_path == NULL) {
3237 error = got_error_from_errno("getcwd");
3238 goto done;
3240 error = got_worktree_open(&worktree, worktree_path);
3241 if (error) {
3242 if (error->code == GOT_ERR_NOT_WORKTREE)
3243 error = wrap_not_worktree_error(error, "update",
3244 worktree_path);
3245 goto done;
3248 error = check_rebase_or_histedit_in_progress(worktree);
3249 if (error)
3250 goto done;
3252 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3253 NULL);
3254 if (error != NULL)
3255 goto done;
3257 error = apply_unveil(got_repo_get_path(repo), 0,
3258 got_worktree_get_root_path(worktree));
3259 if (error)
3260 goto done;
3262 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3263 if (error)
3264 goto done;
3266 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3267 got_worktree_get_head_ref_name(worktree), 0);
3268 if (error != NULL)
3269 goto done;
3270 if (commit_id_str == NULL) {
3271 error = got_ref_resolve(&commit_id, repo, head_ref);
3272 if (error != NULL)
3273 goto done;
3274 error = got_object_id_str(&commit_id_str, commit_id);
3275 if (error != NULL)
3276 goto done;
3277 } else {
3278 struct got_reflist_head refs;
3279 TAILQ_INIT(&refs);
3280 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3281 NULL);
3282 if (error)
3283 goto done;
3284 error = got_repo_match_object_id(&commit_id, NULL,
3285 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3286 got_ref_list_free(&refs);
3287 free(commit_id_str);
3288 commit_id_str = NULL;
3289 if (error)
3290 goto done;
3291 error = got_object_id_str(&commit_id_str, commit_id);
3292 if (error)
3293 goto done;
3296 if (branch_name) {
3297 struct got_object_id *head_commit_id;
3298 TAILQ_FOREACH(pe, &paths, entry) {
3299 if (pe->path_len == 0)
3300 continue;
3301 error = got_error_msg(GOT_ERR_BAD_PATH,
3302 "switching between branches requires that "
3303 "the entire work tree gets updated");
3304 goto done;
3306 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3307 if (error)
3308 goto done;
3309 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3310 repo);
3311 free(head_commit_id);
3312 if (error != NULL)
3313 goto done;
3314 error = check_same_branch(commit_id, head_ref, NULL, repo);
3315 if (error)
3316 goto done;
3317 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3318 if (error)
3319 goto done;
3320 } else {
3321 error = check_linear_ancestry(commit_id,
3322 got_worktree_get_base_commit_id(worktree), 0, repo);
3323 if (error != NULL) {
3324 if (error->code == GOT_ERR_ANCESTRY)
3325 error = got_error(GOT_ERR_BRANCH_MOVED);
3326 goto done;
3328 error = check_same_branch(commit_id, head_ref, NULL, repo);
3329 if (error)
3330 goto done;
3333 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3334 commit_id) != 0) {
3335 error = got_worktree_set_base_commit_id(worktree, repo,
3336 commit_id);
3337 if (error)
3338 goto done;
3341 memset(&upa, 0, sizeof(upa));
3342 error = got_worktree_checkout_files(worktree, &paths, repo,
3343 update_progress, &upa, check_cancelled, NULL);
3344 if (error != NULL)
3345 goto done;
3347 if (upa.did_something)
3348 printf("Updated to commit %s\n", commit_id_str);
3349 else
3350 printf("Already up-to-date\n");
3351 print_update_progress_stats(&upa);
3352 done:
3353 free(worktree_path);
3354 TAILQ_FOREACH(pe, &paths, entry)
3355 free((char *)pe->path);
3356 got_pathlist_free(&paths);
3357 free(commit_id);
3358 free(commit_id_str);
3359 return error;
3362 static const struct got_error *
3363 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3364 const char *path, int diff_context, int ignore_whitespace,
3365 int force_text_diff, struct got_repository *repo)
3367 const struct got_error *err = NULL;
3368 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3370 if (blob_id1) {
3371 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3372 if (err)
3373 goto done;
3376 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3377 if (err)
3378 goto done;
3380 while (path[0] == '/')
3381 path++;
3382 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3383 diff_context, ignore_whitespace, force_text_diff, stdout);
3384 done:
3385 if (blob1)
3386 got_object_blob_close(blob1);
3387 got_object_blob_close(blob2);
3388 return err;
3391 static const struct got_error *
3392 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3393 const char *path, int diff_context, int ignore_whitespace,
3394 int force_text_diff, struct got_repository *repo)
3396 const struct got_error *err = NULL;
3397 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3398 struct got_diff_blob_output_unidiff_arg arg;
3400 if (tree_id1) {
3401 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3402 if (err)
3403 goto done;
3406 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3407 if (err)
3408 goto done;
3410 arg.diff_context = diff_context;
3411 arg.ignore_whitespace = ignore_whitespace;
3412 arg.force_text_diff = force_text_diff;
3413 arg.outfile = stdout;
3414 arg.line_offsets = NULL;
3415 arg.nlines = 0;
3416 while (path[0] == '/')
3417 path++;
3418 err = got_diff_tree(tree1, tree2, path, path, repo,
3419 got_diff_blob_output_unidiff, &arg, 1);
3420 done:
3421 if (tree1)
3422 got_object_tree_close(tree1);
3423 if (tree2)
3424 got_object_tree_close(tree2);
3425 return err;
3428 static const struct got_error *
3429 get_changed_paths(struct got_pathlist_head *paths,
3430 struct got_commit_object *commit, struct got_repository *repo)
3432 const struct got_error *err = NULL;
3433 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3434 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3435 struct got_object_qid *qid;
3437 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3438 if (qid != NULL) {
3439 struct got_commit_object *pcommit;
3440 err = got_object_open_as_commit(&pcommit, repo,
3441 qid->id);
3442 if (err)
3443 return err;
3445 tree_id1 = got_object_id_dup(
3446 got_object_commit_get_tree_id(pcommit));
3447 if (tree_id1 == NULL) {
3448 got_object_commit_close(pcommit);
3449 return got_error_from_errno("got_object_id_dup");
3451 got_object_commit_close(pcommit);
3455 if (tree_id1) {
3456 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3457 if (err)
3458 goto done;
3461 tree_id2 = got_object_commit_get_tree_id(commit);
3462 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3463 if (err)
3464 goto done;
3466 err = got_diff_tree(tree1, tree2, "", "", repo,
3467 got_diff_tree_collect_changed_paths, paths, 0);
3468 done:
3469 if (tree1)
3470 got_object_tree_close(tree1);
3471 if (tree2)
3472 got_object_tree_close(tree2);
3473 free(tree_id1);
3474 return err;
3477 static const struct got_error *
3478 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3479 const char *path, int diff_context, struct got_repository *repo)
3481 const struct got_error *err = NULL;
3482 struct got_commit_object *pcommit = NULL;
3483 char *id_str1 = NULL, *id_str2 = NULL;
3484 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3485 struct got_object_qid *qid;
3487 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3488 if (qid != NULL) {
3489 err = got_object_open_as_commit(&pcommit, repo,
3490 qid->id);
3491 if (err)
3492 return err;
3495 if (path && path[0] != '\0') {
3496 int obj_type;
3497 err = got_object_id_by_path(&obj_id2, repo, id, path);
3498 if (err)
3499 goto done;
3500 err = got_object_id_str(&id_str2, obj_id2);
3501 if (err) {
3502 free(obj_id2);
3503 goto done;
3505 if (pcommit) {
3506 err = got_object_id_by_path(&obj_id1, repo,
3507 qid->id, path);
3508 if (err) {
3509 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3510 free(obj_id2);
3511 goto done;
3513 } else {
3514 err = got_object_id_str(&id_str1, obj_id1);
3515 if (err) {
3516 free(obj_id2);
3517 goto done;
3521 err = got_object_get_type(&obj_type, repo, obj_id2);
3522 if (err) {
3523 free(obj_id2);
3524 goto done;
3526 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3527 switch (obj_type) {
3528 case GOT_OBJ_TYPE_BLOB:
3529 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3530 0, 0, repo);
3531 break;
3532 case GOT_OBJ_TYPE_TREE:
3533 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3534 0, 0, repo);
3535 break;
3536 default:
3537 err = got_error(GOT_ERR_OBJ_TYPE);
3538 break;
3540 free(obj_id1);
3541 free(obj_id2);
3542 } else {
3543 obj_id2 = got_object_commit_get_tree_id(commit);
3544 err = got_object_id_str(&id_str2, obj_id2);
3545 if (err)
3546 goto done;
3547 if (pcommit) {
3548 obj_id1 = got_object_commit_get_tree_id(pcommit);
3549 err = got_object_id_str(&id_str1, obj_id1);
3550 if (err)
3551 goto done;
3553 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3554 id_str2);
3555 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3556 repo);
3558 done:
3559 free(id_str1);
3560 free(id_str2);
3561 if (pcommit)
3562 got_object_commit_close(pcommit);
3563 return err;
3566 static char *
3567 get_datestr(time_t *time, char *datebuf)
3569 struct tm mytm, *tm;
3570 char *p, *s;
3572 tm = gmtime_r(time, &mytm);
3573 if (tm == NULL)
3574 return NULL;
3575 s = asctime_r(tm, datebuf);
3576 if (s == NULL)
3577 return NULL;
3578 p = strchr(s, '\n');
3579 if (p)
3580 *p = '\0';
3581 return s;
3584 static const struct got_error *
3585 match_logmsg(int *have_match, struct got_object_id *id,
3586 struct got_commit_object *commit, regex_t *regex)
3588 const struct got_error *err = NULL;
3589 regmatch_t regmatch;
3590 char *id_str = NULL, *logmsg = NULL;
3592 *have_match = 0;
3594 err = got_object_id_str(&id_str, id);
3595 if (err)
3596 return err;
3598 err = got_object_commit_get_logmsg(&logmsg, commit);
3599 if (err)
3600 goto done;
3602 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3603 *have_match = 1;
3604 done:
3605 free(id_str);
3606 free(logmsg);
3607 return err;
3610 static void
3611 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3612 regex_t *regex)
3614 regmatch_t regmatch;
3615 struct got_pathlist_entry *pe;
3617 *have_match = 0;
3619 TAILQ_FOREACH(pe, changed_paths, entry) {
3620 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3621 *have_match = 1;
3622 break;
3627 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3629 static const struct got_error*
3630 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3631 struct got_object_id *id, struct got_repository *repo)
3633 static const struct got_error *err = NULL;
3634 struct got_reflist_entry *re;
3635 char *s;
3636 const char *name;
3638 *refs_str = NULL;
3640 TAILQ_FOREACH(re, refs, entry) {
3641 struct got_tag_object *tag = NULL;
3642 struct got_object_id *ref_id;
3643 int cmp;
3645 name = got_ref_get_name(re->ref);
3646 if (strcmp(name, GOT_REF_HEAD) == 0)
3647 continue;
3648 if (strncmp(name, "refs/", 5) == 0)
3649 name += 5;
3650 if (strncmp(name, "got/", 4) == 0)
3651 continue;
3652 if (strncmp(name, "heads/", 6) == 0)
3653 name += 6;
3654 if (strncmp(name, "remotes/", 8) == 0) {
3655 name += 8;
3656 s = strstr(name, "/" GOT_REF_HEAD);
3657 if (s != NULL && s[strlen(s)] == '\0')
3658 continue;
3660 err = got_ref_resolve(&ref_id, repo, re->ref);
3661 if (err)
3662 break;
3663 if (strncmp(name, "tags/", 5) == 0) {
3664 err = got_object_open_as_tag(&tag, repo, ref_id);
3665 if (err) {
3666 if (err->code != GOT_ERR_OBJ_TYPE) {
3667 free(ref_id);
3668 break;
3670 /* Ref points at something other than a tag. */
3671 err = NULL;
3672 tag = NULL;
3675 cmp = got_object_id_cmp(tag ?
3676 got_object_tag_get_object_id(tag) : ref_id, id);
3677 free(ref_id);
3678 if (tag)
3679 got_object_tag_close(tag);
3680 if (cmp != 0)
3681 continue;
3682 s = *refs_str;
3683 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3684 s ? ", " : "", name) == -1) {
3685 err = got_error_from_errno("asprintf");
3686 free(s);
3687 *refs_str = NULL;
3688 break;
3690 free(s);
3693 return err;
3696 static const struct got_error *
3697 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3698 struct got_repository *repo, const char *path,
3699 struct got_pathlist_head *changed_paths, int show_patch,
3700 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3701 const char *custom_refs_str)
3703 const struct got_error *err = NULL;
3704 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3705 char datebuf[26];
3706 time_t committer_time;
3707 const char *author, *committer;
3708 char *refs_str = NULL;
3710 err = got_object_id_str(&id_str, id);
3711 if (err)
3712 return err;
3714 if (custom_refs_str == NULL) {
3715 struct got_reflist_head *refs;
3716 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3717 if (refs) {
3718 err = build_refs_str(&refs_str, refs, id, repo);
3719 if (err)
3720 goto done;
3724 printf(GOT_COMMIT_SEP_STR);
3725 if (custom_refs_str)
3726 printf("commit %s (%s)\n", id_str, custom_refs_str);
3727 else
3728 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3729 refs_str ? refs_str : "", refs_str ? ")" : "");
3730 free(id_str);
3731 id_str = NULL;
3732 free(refs_str);
3733 refs_str = NULL;
3734 printf("from: %s\n", got_object_commit_get_author(commit));
3735 committer_time = got_object_commit_get_committer_time(commit);
3736 datestr = get_datestr(&committer_time, datebuf);
3737 if (datestr)
3738 printf("date: %s UTC\n", datestr);
3739 author = got_object_commit_get_author(commit);
3740 committer = got_object_commit_get_committer(commit);
3741 if (strcmp(author, committer) != 0)
3742 printf("via: %s\n", committer);
3743 if (got_object_commit_get_nparents(commit) > 1) {
3744 const struct got_object_id_queue *parent_ids;
3745 struct got_object_qid *qid;
3746 int n = 1;
3747 parent_ids = got_object_commit_get_parent_ids(commit);
3748 STAILQ_FOREACH(qid, parent_ids, entry) {
3749 err = got_object_id_str(&id_str, qid->id);
3750 if (err)
3751 goto done;
3752 printf("parent %d: %s\n", n++, id_str);
3753 free(id_str);
3754 id_str = NULL;
3758 err = got_object_commit_get_logmsg(&logmsg0, commit);
3759 if (err)
3760 goto done;
3762 logmsg = logmsg0;
3763 do {
3764 line = strsep(&logmsg, "\n");
3765 if (line)
3766 printf(" %s\n", line);
3767 } while (line);
3768 free(logmsg0);
3770 if (changed_paths) {
3771 struct got_pathlist_entry *pe;
3772 TAILQ_FOREACH(pe, changed_paths, entry) {
3773 struct got_diff_changed_path *cp = pe->data;
3774 printf(" %c %s\n", cp->status, pe->path);
3776 printf("\n");
3778 if (show_patch) {
3779 err = print_patch(commit, id, path, diff_context, repo);
3780 if (err == 0)
3781 printf("\n");
3784 if (fflush(stdout) != 0 && err == NULL)
3785 err = got_error_from_errno("fflush");
3786 done:
3787 free(id_str);
3788 free(refs_str);
3789 return err;
3792 static const struct got_error *
3793 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3794 struct got_repository *repo, const char *path, int show_changed_paths,
3795 int show_patch, const char *search_pattern, int diff_context, int limit,
3796 int log_branches, int reverse_display_order,
3797 struct got_reflist_object_id_map *refs_idmap)
3799 const struct got_error *err;
3800 struct got_commit_graph *graph;
3801 regex_t regex;
3802 int have_match;
3803 struct got_object_id_queue reversed_commits;
3804 struct got_object_qid *qid;
3805 struct got_commit_object *commit;
3806 struct got_pathlist_head changed_paths;
3807 struct got_pathlist_entry *pe;
3809 STAILQ_INIT(&reversed_commits);
3810 TAILQ_INIT(&changed_paths);
3812 if (search_pattern && regcomp(&regex, search_pattern,
3813 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3814 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3816 err = got_commit_graph_open(&graph, path, !log_branches);
3817 if (err)
3818 return err;
3819 err = got_commit_graph_iter_start(graph, root_id, repo,
3820 check_cancelled, NULL);
3821 if (err)
3822 goto done;
3823 for (;;) {
3824 struct got_object_id *id;
3826 if (sigint_received || sigpipe_received)
3827 break;
3829 err = got_commit_graph_iter_next(&id, graph, repo,
3830 check_cancelled, NULL);
3831 if (err) {
3832 if (err->code == GOT_ERR_ITER_COMPLETED)
3833 err = NULL;
3834 break;
3836 if (id == NULL)
3837 break;
3839 err = got_object_open_as_commit(&commit, repo, id);
3840 if (err)
3841 break;
3843 if (show_changed_paths && !reverse_display_order) {
3844 err = get_changed_paths(&changed_paths, commit, repo);
3845 if (err)
3846 break;
3849 if (search_pattern) {
3850 err = match_logmsg(&have_match, id, commit, &regex);
3851 if (err) {
3852 got_object_commit_close(commit);
3853 break;
3855 if (have_match == 0 && show_changed_paths)
3856 match_changed_paths(&have_match,
3857 &changed_paths, &regex);
3858 if (have_match == 0) {
3859 got_object_commit_close(commit);
3860 TAILQ_FOREACH(pe, &changed_paths, entry) {
3861 free((char *)pe->path);
3862 free(pe->data);
3864 got_pathlist_free(&changed_paths);
3865 continue;
3869 if (reverse_display_order) {
3870 err = got_object_qid_alloc(&qid, id);
3871 if (err)
3872 break;
3873 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3874 got_object_commit_close(commit);
3875 } else {
3876 err = print_commit(commit, id, repo, path,
3877 show_changed_paths ? &changed_paths : NULL,
3878 show_patch, diff_context, refs_idmap, NULL);
3879 got_object_commit_close(commit);
3880 if (err)
3881 break;
3883 if ((limit && --limit == 0) ||
3884 (end_id && got_object_id_cmp(id, end_id) == 0))
3885 break;
3887 TAILQ_FOREACH(pe, &changed_paths, entry) {
3888 free((char *)pe->path);
3889 free(pe->data);
3891 got_pathlist_free(&changed_paths);
3893 if (reverse_display_order) {
3894 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3895 err = got_object_open_as_commit(&commit, repo, qid->id);
3896 if (err)
3897 break;
3898 if (show_changed_paths) {
3899 err = get_changed_paths(&changed_paths,
3900 commit, repo);
3901 if (err)
3902 break;
3904 err = print_commit(commit, qid->id, repo, path,
3905 show_changed_paths ? &changed_paths : NULL,
3906 show_patch, diff_context, refs_idmap, NULL);
3907 got_object_commit_close(commit);
3908 if (err)
3909 break;
3910 TAILQ_FOREACH(pe, &changed_paths, entry) {
3911 free((char *)pe->path);
3912 free(pe->data);
3914 got_pathlist_free(&changed_paths);
3917 done:
3918 while (!STAILQ_EMPTY(&reversed_commits)) {
3919 qid = STAILQ_FIRST(&reversed_commits);
3920 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3921 got_object_qid_free(qid);
3923 TAILQ_FOREACH(pe, &changed_paths, entry) {
3924 free((char *)pe->path);
3925 free(pe->data);
3927 got_pathlist_free(&changed_paths);
3928 if (search_pattern)
3929 regfree(&regex);
3930 got_commit_graph_close(graph);
3931 return err;
3934 __dead static void
3935 usage_log(void)
3937 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3938 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3939 "[-R] [path]\n", getprogname());
3940 exit(1);
3943 static int
3944 get_default_log_limit(void)
3946 const char *got_default_log_limit;
3947 long long n;
3948 const char *errstr;
3950 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3951 if (got_default_log_limit == NULL)
3952 return 0;
3953 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3954 if (errstr != NULL)
3955 return 0;
3956 return n;
3959 static const struct got_error *
3960 cmd_log(int argc, char *argv[])
3962 const struct got_error *error;
3963 struct got_repository *repo = NULL;
3964 struct got_worktree *worktree = NULL;
3965 struct got_object_id *start_id = NULL, *end_id = NULL;
3966 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3967 const char *start_commit = NULL, *end_commit = NULL;
3968 const char *search_pattern = NULL;
3969 int diff_context = -1, ch;
3970 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3971 int reverse_display_order = 0;
3972 const char *errstr;
3973 struct got_reflist_head refs;
3974 struct got_reflist_object_id_map *refs_idmap = NULL;
3976 TAILQ_INIT(&refs);
3978 #ifndef PROFILE
3979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3980 NULL)
3981 == -1)
3982 err(1, "pledge");
3983 #endif
3985 limit = get_default_log_limit();
3987 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3988 switch (ch) {
3989 case 'p':
3990 show_patch = 1;
3991 break;
3992 case 'P':
3993 show_changed_paths = 1;
3994 break;
3995 case 'c':
3996 start_commit = optarg;
3997 break;
3998 case 'C':
3999 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4000 &errstr);
4001 if (errstr != NULL)
4002 err(1, "-C option %s", errstr);
4003 break;
4004 case 'l':
4005 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4006 if (errstr != NULL)
4007 err(1, "-l option %s", errstr);
4008 break;
4009 case 'b':
4010 log_branches = 1;
4011 break;
4012 case 'r':
4013 repo_path = realpath(optarg, NULL);
4014 if (repo_path == NULL)
4015 return got_error_from_errno2("realpath",
4016 optarg);
4017 got_path_strip_trailing_slashes(repo_path);
4018 break;
4019 case 'R':
4020 reverse_display_order = 1;
4021 break;
4022 case 's':
4023 search_pattern = optarg;
4024 break;
4025 case 'x':
4026 end_commit = optarg;
4027 break;
4028 default:
4029 usage_log();
4030 /* NOTREACHED */
4034 argc -= optind;
4035 argv += optind;
4037 if (diff_context == -1)
4038 diff_context = 3;
4039 else if (!show_patch)
4040 errx(1, "-C requires -p");
4042 cwd = getcwd(NULL, 0);
4043 if (cwd == NULL) {
4044 error = got_error_from_errno("getcwd");
4045 goto done;
4048 if (repo_path == NULL) {
4049 error = got_worktree_open(&worktree, cwd);
4050 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4051 goto done;
4052 error = NULL;
4055 if (argc == 1) {
4056 if (worktree) {
4057 error = got_worktree_resolve_path(&path, worktree,
4058 argv[0]);
4059 if (error)
4060 goto done;
4061 } else {
4062 path = strdup(argv[0]);
4063 if (path == NULL) {
4064 error = got_error_from_errno("strdup");
4065 goto done;
4068 } else if (argc != 0)
4069 usage_log();
4071 if (repo_path == NULL) {
4072 repo_path = worktree ?
4073 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4075 if (repo_path == NULL) {
4076 error = got_error_from_errno("strdup");
4077 goto done;
4080 error = got_repo_open(&repo, repo_path, NULL);
4081 if (error != NULL)
4082 goto done;
4084 error = apply_unveil(got_repo_get_path(repo), 1,
4085 worktree ? got_worktree_get_root_path(worktree) : NULL);
4086 if (error)
4087 goto done;
4089 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4090 if (error)
4091 goto done;
4093 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4094 if (error)
4095 goto done;
4097 if (start_commit == NULL) {
4098 struct got_reference *head_ref;
4099 struct got_commit_object *commit = NULL;
4100 error = got_ref_open(&head_ref, repo,
4101 worktree ? got_worktree_get_head_ref_name(worktree)
4102 : GOT_REF_HEAD, 0);
4103 if (error != NULL)
4104 goto done;
4105 error = got_ref_resolve(&start_id, repo, head_ref);
4106 got_ref_close(head_ref);
4107 if (error != NULL)
4108 goto done;
4109 error = got_object_open_as_commit(&commit, repo,
4110 start_id);
4111 if (error != NULL)
4112 goto done;
4113 got_object_commit_close(commit);
4114 } else {
4115 error = got_repo_match_object_id(&start_id, NULL,
4116 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4117 if (error != NULL)
4118 goto done;
4120 if (end_commit != NULL) {
4121 error = got_repo_match_object_id(&end_id, NULL,
4122 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4123 if (error != NULL)
4124 goto done;
4127 if (worktree) {
4129 * If a path was specified on the command line it was resolved
4130 * to a path in the work tree above. Prepend the work tree's
4131 * path prefix to obtain the corresponding in-repository path.
4133 if (path) {
4134 const char *prefix;
4135 prefix = got_worktree_get_path_prefix(worktree);
4136 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4137 (path[0] != '\0') ? "/" : "", path) == -1) {
4138 error = got_error_from_errno("asprintf");
4139 goto done;
4142 } else
4143 error = got_repo_map_path(&in_repo_path, repo,
4144 path ? path : "");
4145 if (error != NULL)
4146 goto done;
4147 if (in_repo_path) {
4148 free(path);
4149 path = in_repo_path;
4152 error = print_commits(start_id, end_id, repo, path ? path : "",
4153 show_changed_paths, show_patch, search_pattern, diff_context,
4154 limit, log_branches, reverse_display_order, refs_idmap);
4155 done:
4156 free(path);
4157 free(repo_path);
4158 free(cwd);
4159 if (worktree)
4160 got_worktree_close(worktree);
4161 if (repo) {
4162 const struct got_error *close_err = got_repo_close(repo);
4163 if (error == NULL)
4164 error = close_err;
4166 if (refs_idmap)
4167 got_reflist_object_id_map_free(refs_idmap);
4168 got_ref_list_free(&refs);
4169 return error;
4172 __dead static void
4173 usage_diff(void)
4175 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4176 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4177 exit(1);
4180 struct print_diff_arg {
4181 struct got_repository *repo;
4182 struct got_worktree *worktree;
4183 int diff_context;
4184 const char *id_str;
4185 int header_shown;
4186 int diff_staged;
4187 int ignore_whitespace;
4188 int force_text_diff;
4192 * Create a file which contains the target path of a symlink so we can feed
4193 * it as content to the diff engine.
4195 static const struct got_error *
4196 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4197 const char *abspath)
4199 const struct got_error *err = NULL;
4200 char target_path[PATH_MAX];
4201 ssize_t target_len, outlen;
4203 *fd = -1;
4205 if (dirfd != -1) {
4206 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4207 if (target_len == -1)
4208 return got_error_from_errno2("readlinkat", abspath);
4209 } else {
4210 target_len = readlink(abspath, target_path, PATH_MAX);
4211 if (target_len == -1)
4212 return got_error_from_errno2("readlink", abspath);
4215 *fd = got_opentempfd();
4216 if (*fd == -1)
4217 return got_error_from_errno("got_opentempfd");
4219 outlen = write(*fd, target_path, target_len);
4220 if (outlen == -1) {
4221 err = got_error_from_errno("got_opentempfd");
4222 goto done;
4225 if (lseek(*fd, 0, SEEK_SET) == -1) {
4226 err = got_error_from_errno2("lseek", abspath);
4227 goto done;
4229 done:
4230 if (err) {
4231 close(*fd);
4232 *fd = -1;
4234 return err;
4237 static const struct got_error *
4238 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4239 const char *path, struct got_object_id *blob_id,
4240 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4241 int dirfd, const char *de_name)
4243 struct print_diff_arg *a = arg;
4244 const struct got_error *err = NULL;
4245 struct got_blob_object *blob1 = NULL;
4246 int fd = -1;
4247 FILE *f2 = NULL;
4248 char *abspath = NULL, *label1 = NULL;
4249 struct stat sb;
4251 if (a->diff_staged) {
4252 if (staged_status != GOT_STATUS_MODIFY &&
4253 staged_status != GOT_STATUS_ADD &&
4254 staged_status != GOT_STATUS_DELETE)
4255 return NULL;
4256 } else {
4257 if (staged_status == GOT_STATUS_DELETE)
4258 return NULL;
4259 if (status == GOT_STATUS_NONEXISTENT)
4260 return got_error_set_errno(ENOENT, path);
4261 if (status != GOT_STATUS_MODIFY &&
4262 status != GOT_STATUS_ADD &&
4263 status != GOT_STATUS_DELETE &&
4264 status != GOT_STATUS_CONFLICT)
4265 return NULL;
4268 if (!a->header_shown) {
4269 printf("diff %s %s%s\n", a->id_str,
4270 got_worktree_get_root_path(a->worktree),
4271 a->diff_staged ? " (staged changes)" : "");
4272 a->header_shown = 1;
4275 if (a->diff_staged) {
4276 const char *label1 = NULL, *label2 = NULL;
4277 switch (staged_status) {
4278 case GOT_STATUS_MODIFY:
4279 label1 = path;
4280 label2 = path;
4281 break;
4282 case GOT_STATUS_ADD:
4283 label2 = path;
4284 break;
4285 case GOT_STATUS_DELETE:
4286 label1 = path;
4287 break;
4288 default:
4289 return got_error(GOT_ERR_FILE_STATUS);
4291 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4292 staged_blob_id, label1, label2, a->diff_context,
4293 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4296 if (staged_status == GOT_STATUS_ADD ||
4297 staged_status == GOT_STATUS_MODIFY) {
4298 char *id_str;
4299 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4300 8192);
4301 if (err)
4302 goto done;
4303 err = got_object_id_str(&id_str, staged_blob_id);
4304 if (err)
4305 goto done;
4306 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4307 err = got_error_from_errno("asprintf");
4308 free(id_str);
4309 goto done;
4311 free(id_str);
4312 } else if (status != GOT_STATUS_ADD) {
4313 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4314 if (err)
4315 goto done;
4318 if (status != GOT_STATUS_DELETE) {
4319 if (asprintf(&abspath, "%s/%s",
4320 got_worktree_get_root_path(a->worktree), path) == -1) {
4321 err = got_error_from_errno("asprintf");
4322 goto done;
4325 if (dirfd != -1) {
4326 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4327 if (fd == -1) {
4328 if (errno != ELOOP) {
4329 err = got_error_from_errno2("openat",
4330 abspath);
4331 goto done;
4333 err = get_symlink_target_file(&fd, dirfd,
4334 de_name, abspath);
4335 if (err)
4336 goto done;
4338 } else {
4339 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4340 if (fd == -1) {
4341 if (errno != ELOOP) {
4342 err = got_error_from_errno2("open",
4343 abspath);
4344 goto done;
4346 err = get_symlink_target_file(&fd, dirfd,
4347 de_name, abspath);
4348 if (err)
4349 goto done;
4352 if (fstat(fd, &sb) == -1) {
4353 err = got_error_from_errno2("fstat", abspath);
4354 goto done;
4356 f2 = fdopen(fd, "r");
4357 if (f2 == NULL) {
4358 err = got_error_from_errno2("fdopen", abspath);
4359 goto done;
4361 fd = -1;
4362 } else
4363 sb.st_size = 0;
4365 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4366 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4367 done:
4368 if (blob1)
4369 got_object_blob_close(blob1);
4370 if (f2 && fclose(f2) == EOF && err == NULL)
4371 err = got_error_from_errno("fclose");
4372 if (fd != -1 && close(fd) == -1 && err == NULL)
4373 err = got_error_from_errno("close");
4374 free(abspath);
4375 return err;
4378 static const struct got_error *
4379 cmd_diff(int argc, char *argv[])
4381 const struct got_error *error;
4382 struct got_repository *repo = NULL;
4383 struct got_worktree *worktree = NULL;
4384 char *cwd = NULL, *repo_path = NULL;
4385 struct got_object_id *id1 = NULL, *id2 = NULL;
4386 const char *id_str1 = NULL, *id_str2 = NULL;
4387 char *label1 = NULL, *label2 = NULL;
4388 int type1, type2;
4389 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4390 int force_text_diff = 0;
4391 const char *errstr;
4392 char *path = NULL;
4393 struct got_reflist_head refs;
4395 TAILQ_INIT(&refs);
4397 #ifndef PROFILE
4398 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4399 NULL) == -1)
4400 err(1, "pledge");
4401 #endif
4403 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4404 switch (ch) {
4405 case 'a':
4406 force_text_diff = 1;
4407 break;
4408 case 'C':
4409 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4410 &errstr);
4411 if (errstr != NULL)
4412 err(1, "-C option %s", errstr);
4413 break;
4414 case 'r':
4415 repo_path = realpath(optarg, NULL);
4416 if (repo_path == NULL)
4417 return got_error_from_errno2("realpath",
4418 optarg);
4419 got_path_strip_trailing_slashes(repo_path);
4420 break;
4421 case 's':
4422 diff_staged = 1;
4423 break;
4424 case 'w':
4425 ignore_whitespace = 1;
4426 break;
4427 default:
4428 usage_diff();
4429 /* NOTREACHED */
4433 argc -= optind;
4434 argv += optind;
4436 cwd = getcwd(NULL, 0);
4437 if (cwd == NULL) {
4438 error = got_error_from_errno("getcwd");
4439 goto done;
4441 if (argc <= 1) {
4442 if (repo_path)
4443 errx(1,
4444 "-r option can't be used when diffing a work tree");
4445 error = got_worktree_open(&worktree, cwd);
4446 if (error) {
4447 if (error->code == GOT_ERR_NOT_WORKTREE)
4448 error = wrap_not_worktree_error(error, "diff",
4449 cwd);
4450 goto done;
4452 repo_path = strdup(got_worktree_get_repo_path(worktree));
4453 if (repo_path == NULL) {
4454 error = got_error_from_errno("strdup");
4455 goto done;
4457 if (argc == 1) {
4458 error = got_worktree_resolve_path(&path, worktree,
4459 argv[0]);
4460 if (error)
4461 goto done;
4462 } else {
4463 path = strdup("");
4464 if (path == NULL) {
4465 error = got_error_from_errno("strdup");
4466 goto done;
4469 } else if (argc == 2) {
4470 if (diff_staged)
4471 errx(1, "-s option can't be used when diffing "
4472 "objects in repository");
4473 id_str1 = argv[0];
4474 id_str2 = argv[1];
4475 if (repo_path == NULL) {
4476 error = got_worktree_open(&worktree, cwd);
4477 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4478 goto done;
4479 repo_path = strdup(worktree ?
4480 got_worktree_get_repo_path(worktree) : cwd);
4481 if (repo_path == NULL) {
4482 error = got_error_from_errno("strdup");
4483 goto done;
4486 } else
4487 usage_diff();
4489 error = got_repo_open(&repo, repo_path, NULL);
4490 free(repo_path);
4491 if (error != NULL)
4492 goto done;
4494 error = apply_unveil(got_repo_get_path(repo), 1,
4495 worktree ? got_worktree_get_root_path(worktree) : NULL);
4496 if (error)
4497 goto done;
4499 if (argc <= 1) {
4500 struct print_diff_arg arg;
4501 struct got_pathlist_head paths;
4502 char *id_str;
4504 TAILQ_INIT(&paths);
4506 error = got_object_id_str(&id_str,
4507 got_worktree_get_base_commit_id(worktree));
4508 if (error)
4509 goto done;
4510 arg.repo = repo;
4511 arg.worktree = worktree;
4512 arg.diff_context = diff_context;
4513 arg.id_str = id_str;
4514 arg.header_shown = 0;
4515 arg.diff_staged = diff_staged;
4516 arg.ignore_whitespace = ignore_whitespace;
4517 arg.force_text_diff = force_text_diff;
4519 error = got_pathlist_append(&paths, path, NULL);
4520 if (error)
4521 goto done;
4523 error = got_worktree_status(worktree, &paths, repo, 0,
4524 print_diff, &arg, check_cancelled, NULL);
4525 free(id_str);
4526 got_pathlist_free(&paths);
4527 goto done;
4530 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4531 if (error)
4532 return error;
4534 error = got_repo_match_object_id(&id1, &label1, id_str1,
4535 GOT_OBJ_TYPE_ANY, &refs, repo);
4536 if (error)
4537 goto done;
4539 error = got_repo_match_object_id(&id2, &label2, id_str2,
4540 GOT_OBJ_TYPE_ANY, &refs, repo);
4541 if (error)
4542 goto done;
4544 error = got_object_get_type(&type1, repo, id1);
4545 if (error)
4546 goto done;
4548 error = got_object_get_type(&type2, repo, id2);
4549 if (error)
4550 goto done;
4552 if (type1 != type2) {
4553 error = got_error(GOT_ERR_OBJ_TYPE);
4554 goto done;
4557 switch (type1) {
4558 case GOT_OBJ_TYPE_BLOB:
4559 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4560 NULL, NULL, diff_context, ignore_whitespace,
4561 force_text_diff, repo, stdout);
4562 break;
4563 case GOT_OBJ_TYPE_TREE:
4564 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4565 "", "", diff_context, ignore_whitespace, force_text_diff,
4566 repo, stdout);
4567 break;
4568 case GOT_OBJ_TYPE_COMMIT:
4569 printf("diff %s %s\n", label1, label2);
4570 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4571 diff_context, ignore_whitespace, force_text_diff, repo,
4572 stdout);
4573 break;
4574 default:
4575 error = got_error(GOT_ERR_OBJ_TYPE);
4577 done:
4578 free(label1);
4579 free(label2);
4580 free(id1);
4581 free(id2);
4582 free(path);
4583 if (worktree)
4584 got_worktree_close(worktree);
4585 if (repo) {
4586 const struct got_error *close_err = got_repo_close(repo);
4587 if (error == NULL)
4588 error = close_err;
4590 got_ref_list_free(&refs);
4591 return error;
4594 __dead static void
4595 usage_blame(void)
4597 fprintf(stderr,
4598 "usage: %s blame [-c commit] [-r repository-path] path\n",
4599 getprogname());
4600 exit(1);
4603 struct blame_line {
4604 int annotated;
4605 char *id_str;
4606 char *committer;
4607 char datebuf[11]; /* YYYY-MM-DD + NUL */
4610 struct blame_cb_args {
4611 struct blame_line *lines;
4612 int nlines;
4613 int nlines_prec;
4614 int lineno_cur;
4615 off_t *line_offsets;
4616 FILE *f;
4617 struct got_repository *repo;
4620 static const struct got_error *
4621 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4623 const struct got_error *err = NULL;
4624 struct blame_cb_args *a = arg;
4625 struct blame_line *bline;
4626 char *line = NULL;
4627 size_t linesize = 0;
4628 struct got_commit_object *commit = NULL;
4629 off_t offset;
4630 struct tm tm;
4631 time_t committer_time;
4633 if (nlines != a->nlines ||
4634 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4635 return got_error(GOT_ERR_RANGE);
4637 if (sigint_received)
4638 return got_error(GOT_ERR_ITER_COMPLETED);
4640 if (lineno == -1)
4641 return NULL; /* no change in this commit */
4643 /* Annotate this line. */
4644 bline = &a->lines[lineno - 1];
4645 if (bline->annotated)
4646 return NULL;
4647 err = got_object_id_str(&bline->id_str, id);
4648 if (err)
4649 return err;
4651 err = got_object_open_as_commit(&commit, a->repo, id);
4652 if (err)
4653 goto done;
4655 bline->committer = strdup(got_object_commit_get_committer(commit));
4656 if (bline->committer == NULL) {
4657 err = got_error_from_errno("strdup");
4658 goto done;
4661 committer_time = got_object_commit_get_committer_time(commit);
4662 if (gmtime_r(&committer_time, &tm) == NULL)
4663 return got_error_from_errno("gmtime_r");
4664 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4665 &tm) == 0) {
4666 err = got_error(GOT_ERR_NO_SPACE);
4667 goto done;
4669 bline->annotated = 1;
4671 /* Print lines annotated so far. */
4672 bline = &a->lines[a->lineno_cur - 1];
4673 if (!bline->annotated)
4674 goto done;
4676 offset = a->line_offsets[a->lineno_cur - 1];
4677 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4678 err = got_error_from_errno("fseeko");
4679 goto done;
4682 while (bline->annotated) {
4683 char *smallerthan, *at, *nl, *committer;
4684 size_t len;
4686 if (getline(&line, &linesize, a->f) == -1) {
4687 if (ferror(a->f))
4688 err = got_error_from_errno("getline");
4689 break;
4692 committer = bline->committer;
4693 smallerthan = strchr(committer, '<');
4694 if (smallerthan && smallerthan[1] != '\0')
4695 committer = smallerthan + 1;
4696 at = strchr(committer, '@');
4697 if (at)
4698 *at = '\0';
4699 len = strlen(committer);
4700 if (len >= 9)
4701 committer[8] = '\0';
4703 nl = strchr(line, '\n');
4704 if (nl)
4705 *nl = '\0';
4706 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4707 bline->id_str, bline->datebuf, committer, line);
4709 a->lineno_cur++;
4710 bline = &a->lines[a->lineno_cur - 1];
4712 done:
4713 if (commit)
4714 got_object_commit_close(commit);
4715 free(line);
4716 return err;
4719 static const struct got_error *
4720 cmd_blame(int argc, char *argv[])
4722 const struct got_error *error;
4723 struct got_repository *repo = NULL;
4724 struct got_worktree *worktree = NULL;
4725 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4726 char *link_target = NULL;
4727 struct got_object_id *obj_id = NULL;
4728 struct got_object_id *commit_id = NULL;
4729 struct got_blob_object *blob = NULL;
4730 char *commit_id_str = NULL;
4731 struct blame_cb_args bca;
4732 int ch, obj_type, i;
4733 off_t filesize;
4735 memset(&bca, 0, sizeof(bca));
4737 #ifndef PROFILE
4738 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4739 NULL) == -1)
4740 err(1, "pledge");
4741 #endif
4743 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4744 switch (ch) {
4745 case 'c':
4746 commit_id_str = optarg;
4747 break;
4748 case 'r':
4749 repo_path = realpath(optarg, NULL);
4750 if (repo_path == NULL)
4751 return got_error_from_errno2("realpath",
4752 optarg);
4753 got_path_strip_trailing_slashes(repo_path);
4754 break;
4755 default:
4756 usage_blame();
4757 /* NOTREACHED */
4761 argc -= optind;
4762 argv += optind;
4764 if (argc == 1)
4765 path = argv[0];
4766 else
4767 usage_blame();
4769 cwd = getcwd(NULL, 0);
4770 if (cwd == NULL) {
4771 error = got_error_from_errno("getcwd");
4772 goto done;
4774 if (repo_path == NULL) {
4775 error = got_worktree_open(&worktree, cwd);
4776 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4777 goto done;
4778 else
4779 error = NULL;
4780 if (worktree) {
4781 repo_path =
4782 strdup(got_worktree_get_repo_path(worktree));
4783 if (repo_path == NULL) {
4784 error = got_error_from_errno("strdup");
4785 if (error)
4786 goto done;
4788 } else {
4789 repo_path = strdup(cwd);
4790 if (repo_path == NULL) {
4791 error = got_error_from_errno("strdup");
4792 goto done;
4797 error = got_repo_open(&repo, repo_path, NULL);
4798 if (error != NULL)
4799 goto done;
4801 if (worktree) {
4802 const char *prefix = got_worktree_get_path_prefix(worktree);
4803 char *p;
4805 error = got_worktree_resolve_path(&p, worktree, path);
4806 if (error)
4807 goto done;
4808 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4809 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4810 p) == -1) {
4811 error = got_error_from_errno("asprintf");
4812 free(p);
4813 goto done;
4815 free(p);
4816 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4817 } else {
4818 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4819 if (error)
4820 goto done;
4821 error = got_repo_map_path(&in_repo_path, repo, path);
4823 if (error)
4824 goto done;
4826 if (commit_id_str == NULL) {
4827 struct got_reference *head_ref;
4828 error = got_ref_open(&head_ref, repo, worktree ?
4829 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4830 if (error != NULL)
4831 goto done;
4832 error = got_ref_resolve(&commit_id, repo, head_ref);
4833 got_ref_close(head_ref);
4834 if (error != NULL)
4835 goto done;
4836 } else {
4837 struct got_reflist_head refs;
4838 TAILQ_INIT(&refs);
4839 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4840 NULL);
4841 if (error)
4842 goto done;
4843 error = got_repo_match_object_id(&commit_id, NULL,
4844 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4845 got_ref_list_free(&refs);
4846 if (error)
4847 goto done;
4850 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4851 commit_id, repo);
4852 if (error)
4853 goto done;
4855 error = got_object_id_by_path(&obj_id, repo, commit_id,
4856 link_target ? link_target : in_repo_path);
4857 if (error)
4858 goto done;
4860 error = got_object_get_type(&obj_type, repo, obj_id);
4861 if (error)
4862 goto done;
4864 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4865 error = got_error_path(link_target ? link_target : in_repo_path,
4866 GOT_ERR_OBJ_TYPE);
4867 goto done;
4870 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4871 if (error)
4872 goto done;
4873 bca.f = got_opentemp();
4874 if (bca.f == NULL) {
4875 error = got_error_from_errno("got_opentemp");
4876 goto done;
4878 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4879 &bca.line_offsets, bca.f, blob);
4880 if (error || bca.nlines == 0)
4881 goto done;
4883 /* Don't include \n at EOF in the blame line count. */
4884 if (bca.line_offsets[bca.nlines - 1] == filesize)
4885 bca.nlines--;
4887 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4888 if (bca.lines == NULL) {
4889 error = got_error_from_errno("calloc");
4890 goto done;
4892 bca.lineno_cur = 1;
4893 bca.nlines_prec = 0;
4894 i = bca.nlines;
4895 while (i > 0) {
4896 i /= 10;
4897 bca.nlines_prec++;
4899 bca.repo = repo;
4901 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4902 repo, blame_cb, &bca, check_cancelled, NULL);
4903 done:
4904 free(in_repo_path);
4905 free(link_target);
4906 free(repo_path);
4907 free(cwd);
4908 free(commit_id);
4909 free(obj_id);
4910 if (blob)
4911 got_object_blob_close(blob);
4912 if (worktree)
4913 got_worktree_close(worktree);
4914 if (repo) {
4915 const struct got_error *close_err = got_repo_close(repo);
4916 if (error == NULL)
4917 error = close_err;
4919 if (bca.lines) {
4920 for (i = 0; i < bca.nlines; i++) {
4921 struct blame_line *bline = &bca.lines[i];
4922 free(bline->id_str);
4923 free(bline->committer);
4925 free(bca.lines);
4927 free(bca.line_offsets);
4928 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4929 error = got_error_from_errno("fclose");
4930 return error;
4933 __dead static void
4934 usage_tree(void)
4936 fprintf(stderr,
4937 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4938 getprogname());
4939 exit(1);
4942 static const struct got_error *
4943 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4944 const char *root_path, struct got_repository *repo)
4946 const struct got_error *err = NULL;
4947 int is_root_path = (strcmp(path, root_path) == 0);
4948 const char *modestr = "";
4949 mode_t mode = got_tree_entry_get_mode(te);
4950 char *link_target = NULL;
4952 path += strlen(root_path);
4953 while (path[0] == '/')
4954 path++;
4956 if (got_object_tree_entry_is_submodule(te))
4957 modestr = "$";
4958 else if (S_ISLNK(mode)) {
4959 int i;
4961 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4962 if (err)
4963 return err;
4964 for (i = 0; i < strlen(link_target); i++) {
4965 if (!isprint((unsigned char)link_target[i]))
4966 link_target[i] = '?';
4969 modestr = "@";
4971 else if (S_ISDIR(mode))
4972 modestr = "/";
4973 else if (mode & S_IXUSR)
4974 modestr = "*";
4976 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4977 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4978 link_target ? " -> ": "", link_target ? link_target : "");
4980 free(link_target);
4981 return NULL;
4984 static const struct got_error *
4985 print_tree(const char *path, struct got_object_id *commit_id,
4986 int show_ids, int recurse, const char *root_path,
4987 struct got_repository *repo)
4989 const struct got_error *err = NULL;
4990 struct got_object_id *tree_id = NULL;
4991 struct got_tree_object *tree = NULL;
4992 int nentries, i;
4994 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4995 if (err)
4996 goto done;
4998 err = got_object_open_as_tree(&tree, repo, tree_id);
4999 if (err)
5000 goto done;
5001 nentries = got_object_tree_get_nentries(tree);
5002 for (i = 0; i < nentries; i++) {
5003 struct got_tree_entry *te;
5004 char *id = NULL;
5006 if (sigint_received || sigpipe_received)
5007 break;
5009 te = got_object_tree_get_entry(tree, i);
5010 if (show_ids) {
5011 char *id_str;
5012 err = got_object_id_str(&id_str,
5013 got_tree_entry_get_id(te));
5014 if (err)
5015 goto done;
5016 if (asprintf(&id, "%s ", id_str) == -1) {
5017 err = got_error_from_errno("asprintf");
5018 free(id_str);
5019 goto done;
5021 free(id_str);
5023 err = print_entry(te, id, path, root_path, repo);
5024 free(id);
5025 if (err)
5026 goto done;
5028 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5029 char *child_path;
5030 if (asprintf(&child_path, "%s%s%s", path,
5031 path[0] == '/' && path[1] == '\0' ? "" : "/",
5032 got_tree_entry_get_name(te)) == -1) {
5033 err = got_error_from_errno("asprintf");
5034 goto done;
5036 err = print_tree(child_path, commit_id, show_ids, 1,
5037 root_path, repo);
5038 free(child_path);
5039 if (err)
5040 goto done;
5043 done:
5044 if (tree)
5045 got_object_tree_close(tree);
5046 free(tree_id);
5047 return err;
5050 static const struct got_error *
5051 cmd_tree(int argc, char *argv[])
5053 const struct got_error *error;
5054 struct got_repository *repo = NULL;
5055 struct got_worktree *worktree = NULL;
5056 const char *path, *refname = NULL;
5057 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5058 struct got_object_id *commit_id = NULL;
5059 char *commit_id_str = NULL;
5060 int show_ids = 0, recurse = 0;
5061 int ch;
5063 #ifndef PROFILE
5064 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5065 NULL) == -1)
5066 err(1, "pledge");
5067 #endif
5069 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5070 switch (ch) {
5071 case 'c':
5072 commit_id_str = optarg;
5073 break;
5074 case 'r':
5075 repo_path = realpath(optarg, NULL);
5076 if (repo_path == NULL)
5077 return got_error_from_errno2("realpath",
5078 optarg);
5079 got_path_strip_trailing_slashes(repo_path);
5080 break;
5081 case 'i':
5082 show_ids = 1;
5083 break;
5084 case 'R':
5085 recurse = 1;
5086 break;
5087 default:
5088 usage_tree();
5089 /* NOTREACHED */
5093 argc -= optind;
5094 argv += optind;
5096 if (argc == 1)
5097 path = argv[0];
5098 else if (argc > 1)
5099 usage_tree();
5100 else
5101 path = NULL;
5103 cwd = getcwd(NULL, 0);
5104 if (cwd == NULL) {
5105 error = got_error_from_errno("getcwd");
5106 goto done;
5108 if (repo_path == NULL) {
5109 error = got_worktree_open(&worktree, cwd);
5110 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5111 goto done;
5112 else
5113 error = NULL;
5114 if (worktree) {
5115 repo_path =
5116 strdup(got_worktree_get_repo_path(worktree));
5117 if (repo_path == NULL)
5118 error = got_error_from_errno("strdup");
5119 if (error)
5120 goto done;
5121 } else {
5122 repo_path = strdup(cwd);
5123 if (repo_path == NULL) {
5124 error = got_error_from_errno("strdup");
5125 goto done;
5130 error = got_repo_open(&repo, repo_path, NULL);
5131 if (error != NULL)
5132 goto done;
5134 if (worktree) {
5135 const char *prefix = got_worktree_get_path_prefix(worktree);
5136 char *p;
5138 if (path == NULL)
5139 path = "";
5140 error = got_worktree_resolve_path(&p, worktree, path);
5141 if (error)
5142 goto done;
5143 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5144 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5145 p) == -1) {
5146 error = got_error_from_errno("asprintf");
5147 free(p);
5148 goto done;
5150 free(p);
5151 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5152 if (error)
5153 goto done;
5154 } else {
5155 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5156 if (error)
5157 goto done;
5158 if (path == NULL)
5159 path = "/";
5160 error = got_repo_map_path(&in_repo_path, repo, path);
5161 if (error != NULL)
5162 goto done;
5165 if (commit_id_str == NULL) {
5166 struct got_reference *head_ref;
5167 if (worktree)
5168 refname = got_worktree_get_head_ref_name(worktree);
5169 else
5170 refname = GOT_REF_HEAD;
5171 error = got_ref_open(&head_ref, repo, refname, 0);
5172 if (error != NULL)
5173 goto done;
5174 error = got_ref_resolve(&commit_id, repo, head_ref);
5175 got_ref_close(head_ref);
5176 if (error != NULL)
5177 goto done;
5178 } else {
5179 struct got_reflist_head refs;
5180 TAILQ_INIT(&refs);
5181 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5182 NULL);
5183 if (error)
5184 goto done;
5185 error = got_repo_match_object_id(&commit_id, NULL,
5186 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5187 got_ref_list_free(&refs);
5188 if (error)
5189 goto done;
5192 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5193 in_repo_path, repo);
5194 done:
5195 free(in_repo_path);
5196 free(repo_path);
5197 free(cwd);
5198 free(commit_id);
5199 if (worktree)
5200 got_worktree_close(worktree);
5201 if (repo) {
5202 const struct got_error *close_err = got_repo_close(repo);
5203 if (error == NULL)
5204 error = close_err;
5206 return error;
5209 __dead static void
5210 usage_status(void)
5212 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5213 getprogname());
5214 exit(1);
5217 static const struct got_error *
5218 print_status(void *arg, unsigned char status, unsigned char staged_status,
5219 const char *path, struct got_object_id *blob_id,
5220 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5221 int dirfd, const char *de_name)
5223 if (status == staged_status && (status == GOT_STATUS_DELETE))
5224 status = GOT_STATUS_NO_CHANGE;
5225 if (arg) {
5226 char *status_codes = arg;
5227 size_t ncodes = strlen(status_codes);
5228 int i;
5229 for (i = 0; i < ncodes ; i++) {
5230 if (status == status_codes[i] ||
5231 staged_status == status_codes[i])
5232 break;
5234 if (i == ncodes)
5235 return NULL;
5237 printf("%c%c %s\n", status, staged_status, path);
5238 return NULL;
5241 static const struct got_error *
5242 cmd_status(int argc, char *argv[])
5244 const struct got_error *error = NULL;
5245 struct got_repository *repo = NULL;
5246 struct got_worktree *worktree = NULL;
5247 char *cwd = NULL, *status_codes = NULL;;
5248 struct got_pathlist_head paths;
5249 struct got_pathlist_entry *pe;
5250 int ch, i, no_ignores = 0;
5252 TAILQ_INIT(&paths);
5254 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5255 switch (ch) {
5256 case 'I':
5257 no_ignores = 1;
5258 break;
5259 case 's':
5260 for (i = 0; i < strlen(optarg); i++) {
5261 switch (optarg[i]) {
5262 case GOT_STATUS_MODIFY:
5263 case GOT_STATUS_ADD:
5264 case GOT_STATUS_DELETE:
5265 case GOT_STATUS_CONFLICT:
5266 case GOT_STATUS_MISSING:
5267 case GOT_STATUS_OBSTRUCTED:
5268 case GOT_STATUS_UNVERSIONED:
5269 case GOT_STATUS_MODE_CHANGE:
5270 case GOT_STATUS_NONEXISTENT:
5271 break;
5272 default:
5273 errx(1, "invalid status code '%c'",
5274 optarg[i]);
5277 status_codes = optarg;
5278 break;
5279 default:
5280 usage_status();
5281 /* NOTREACHED */
5285 argc -= optind;
5286 argv += optind;
5288 #ifndef PROFILE
5289 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5290 NULL) == -1)
5291 err(1, "pledge");
5292 #endif
5293 cwd = getcwd(NULL, 0);
5294 if (cwd == NULL) {
5295 error = got_error_from_errno("getcwd");
5296 goto done;
5299 error = got_worktree_open(&worktree, cwd);
5300 if (error) {
5301 if (error->code == GOT_ERR_NOT_WORKTREE)
5302 error = wrap_not_worktree_error(error, "status", cwd);
5303 goto done;
5306 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5307 NULL);
5308 if (error != NULL)
5309 goto done;
5311 error = apply_unveil(got_repo_get_path(repo), 1,
5312 got_worktree_get_root_path(worktree));
5313 if (error)
5314 goto done;
5316 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5317 if (error)
5318 goto done;
5320 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5321 print_status, status_codes, check_cancelled, NULL);
5322 done:
5323 TAILQ_FOREACH(pe, &paths, entry)
5324 free((char *)pe->path);
5325 got_pathlist_free(&paths);
5326 free(cwd);
5327 return error;
5330 __dead static void
5331 usage_ref(void)
5333 fprintf(stderr,
5334 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5335 "[-d] [name]\n",
5336 getprogname());
5337 exit(1);
5340 static const struct got_error *
5341 list_refs(struct got_repository *repo, const char *refname)
5343 static const struct got_error *err = NULL;
5344 struct got_reflist_head refs;
5345 struct got_reflist_entry *re;
5347 TAILQ_INIT(&refs);
5348 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5349 if (err)
5350 return err;
5352 TAILQ_FOREACH(re, &refs, entry) {
5353 char *refstr;
5354 refstr = got_ref_to_str(re->ref);
5355 if (refstr == NULL)
5356 return got_error_from_errno("got_ref_to_str");
5357 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5358 free(refstr);
5361 got_ref_list_free(&refs);
5362 return NULL;
5365 static const struct got_error *
5366 delete_ref_by_name(struct got_repository *repo, const char *refname)
5368 const struct got_error *err;
5369 struct got_reference *ref;
5371 err = got_ref_open(&ref, repo, refname, 0);
5372 if (err)
5373 return err;
5375 err = delete_ref(repo, ref);
5376 got_ref_close(ref);
5377 return err;
5380 static const struct got_error *
5381 add_ref(struct got_repository *repo, const char *refname, const char *target)
5383 const struct got_error *err = NULL;
5384 struct got_object_id *id;
5385 struct got_reference *ref = NULL;
5388 * Don't let the user create a reference name with a leading '-'.
5389 * While technically a valid reference name, this case is usually
5390 * an unintended typo.
5392 if (refname[0] == '-')
5393 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5395 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5396 repo);
5397 if (err) {
5398 struct got_reference *target_ref;
5400 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5401 return err;
5402 err = got_ref_open(&target_ref, repo, target, 0);
5403 if (err)
5404 return err;
5405 err = got_ref_resolve(&id, repo, target_ref);
5406 got_ref_close(target_ref);
5407 if (err)
5408 return err;
5411 err = got_ref_alloc(&ref, refname, id);
5412 if (err)
5413 goto done;
5415 err = got_ref_write(ref, repo);
5416 done:
5417 if (ref)
5418 got_ref_close(ref);
5419 free(id);
5420 return err;
5423 static const struct got_error *
5424 add_symref(struct got_repository *repo, const char *refname, const char *target)
5426 const struct got_error *err = NULL;
5427 struct got_reference *ref = NULL;
5428 struct got_reference *target_ref = NULL;
5431 * Don't let the user create a reference name with a leading '-'.
5432 * While technically a valid reference name, this case is usually
5433 * an unintended typo.
5435 if (refname[0] == '-')
5436 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5438 err = got_ref_open(&target_ref, repo, target, 0);
5439 if (err)
5440 return err;
5442 err = got_ref_alloc_symref(&ref, refname, target_ref);
5443 if (err)
5444 goto done;
5446 err = got_ref_write(ref, repo);
5447 done:
5448 if (target_ref)
5449 got_ref_close(target_ref);
5450 if (ref)
5451 got_ref_close(ref);
5452 return err;
5455 static const struct got_error *
5456 cmd_ref(int argc, char *argv[])
5458 const struct got_error *error = NULL;
5459 struct got_repository *repo = NULL;
5460 struct got_worktree *worktree = NULL;
5461 char *cwd = NULL, *repo_path = NULL;
5462 int ch, do_list = 0, do_delete = 0;
5463 const char *obj_arg = NULL, *symref_target= NULL;
5464 char *refname = NULL;
5466 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5467 switch (ch) {
5468 case 'c':
5469 obj_arg = optarg;
5470 break;
5471 case 'd':
5472 do_delete = 1;
5473 break;
5474 case 'r':
5475 repo_path = realpath(optarg, NULL);
5476 if (repo_path == NULL)
5477 return got_error_from_errno2("realpath",
5478 optarg);
5479 got_path_strip_trailing_slashes(repo_path);
5480 break;
5481 case 'l':
5482 do_list = 1;
5483 break;
5484 case 's':
5485 symref_target = optarg;
5486 break;
5487 default:
5488 usage_ref();
5489 /* NOTREACHED */
5493 if (obj_arg && do_list)
5494 option_conflict('c', 'l');
5495 if (obj_arg && do_delete)
5496 option_conflict('c', 'd');
5497 if (obj_arg && symref_target)
5498 option_conflict('c', 's');
5499 if (symref_target && do_delete)
5500 option_conflict('s', 'd');
5501 if (symref_target && do_list)
5502 option_conflict('s', 'l');
5503 if (do_delete && do_list)
5504 option_conflict('d', 'l');
5506 argc -= optind;
5507 argv += optind;
5509 if (do_list) {
5510 if (argc != 0 && argc != 1)
5511 usage_ref();
5512 if (argc == 1) {
5513 refname = strdup(argv[0]);
5514 if (refname == NULL) {
5515 error = got_error_from_errno("strdup");
5516 goto done;
5519 } else {
5520 if (argc != 1)
5521 usage_ref();
5522 refname = strdup(argv[0]);
5523 if (refname == NULL) {
5524 error = got_error_from_errno("strdup");
5525 goto done;
5529 if (refname)
5530 got_path_strip_trailing_slashes(refname);
5532 #ifndef PROFILE
5533 if (do_list) {
5534 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5535 NULL) == -1)
5536 err(1, "pledge");
5537 } else {
5538 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5539 "sendfd unveil", NULL) == -1)
5540 err(1, "pledge");
5542 #endif
5543 cwd = getcwd(NULL, 0);
5544 if (cwd == NULL) {
5545 error = got_error_from_errno("getcwd");
5546 goto done;
5549 if (repo_path == NULL) {
5550 error = got_worktree_open(&worktree, cwd);
5551 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5552 goto done;
5553 else
5554 error = NULL;
5555 if (worktree) {
5556 repo_path =
5557 strdup(got_worktree_get_repo_path(worktree));
5558 if (repo_path == NULL)
5559 error = got_error_from_errno("strdup");
5560 if (error)
5561 goto done;
5562 } else {
5563 repo_path = strdup(cwd);
5564 if (repo_path == NULL) {
5565 error = got_error_from_errno("strdup");
5566 goto done;
5571 error = got_repo_open(&repo, repo_path, NULL);
5572 if (error != NULL)
5573 goto done;
5575 error = apply_unveil(got_repo_get_path(repo), do_list,
5576 worktree ? got_worktree_get_root_path(worktree) : NULL);
5577 if (error)
5578 goto done;
5580 if (do_list)
5581 error = list_refs(repo, refname);
5582 else if (do_delete)
5583 error = delete_ref_by_name(repo, refname);
5584 else if (symref_target)
5585 error = add_symref(repo, refname, symref_target);
5586 else {
5587 if (obj_arg == NULL)
5588 usage_ref();
5589 error = add_ref(repo, refname, obj_arg);
5591 done:
5592 free(refname);
5593 if (repo) {
5594 const struct got_error *close_err = got_repo_close(repo);
5595 if (error == NULL)
5596 error = close_err;
5598 if (worktree)
5599 got_worktree_close(worktree);
5600 free(cwd);
5601 free(repo_path);
5602 return error;
5605 __dead static void
5606 usage_branch(void)
5608 fprintf(stderr,
5609 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5610 "[name]\n", getprogname());
5611 exit(1);
5614 static const struct got_error *
5615 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5616 struct got_reference *ref)
5618 const struct got_error *err = NULL;
5619 const char *refname, *marker = " ";
5620 char *refstr;
5622 refname = got_ref_get_name(ref);
5623 if (worktree && strcmp(refname,
5624 got_worktree_get_head_ref_name(worktree)) == 0) {
5625 struct got_object_id *id = NULL;
5627 err = got_ref_resolve(&id, repo, ref);
5628 if (err)
5629 return err;
5630 if (got_object_id_cmp(id,
5631 got_worktree_get_base_commit_id(worktree)) == 0)
5632 marker = "* ";
5633 else
5634 marker = "~ ";
5635 free(id);
5638 if (strncmp(refname, "refs/heads/", 11) == 0)
5639 refname += 11;
5640 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5641 refname += 18;
5642 if (strncmp(refname, "refs/remotes/", 13) == 0)
5643 refname += 13;
5645 refstr = got_ref_to_str(ref);
5646 if (refstr == NULL)
5647 return got_error_from_errno("got_ref_to_str");
5649 printf("%s%s: %s\n", marker, refname, refstr);
5650 free(refstr);
5651 return NULL;
5654 static const struct got_error *
5655 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5657 const char *refname;
5659 if (worktree == NULL)
5660 return got_error(GOT_ERR_NOT_WORKTREE);
5662 refname = got_worktree_get_head_ref_name(worktree);
5664 if (strncmp(refname, "refs/heads/", 11) == 0)
5665 refname += 11;
5666 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5667 refname += 18;
5669 printf("%s\n", refname);
5671 return NULL;
5674 static const struct got_error *
5675 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5677 static const struct got_error *err = NULL;
5678 struct got_reflist_head refs;
5679 struct got_reflist_entry *re;
5680 struct got_reference *temp_ref = NULL;
5681 int rebase_in_progress, histedit_in_progress;
5683 TAILQ_INIT(&refs);
5685 if (worktree) {
5686 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5687 worktree);
5688 if (err)
5689 return err;
5691 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5692 worktree);
5693 if (err)
5694 return err;
5696 if (rebase_in_progress || histedit_in_progress) {
5697 err = got_ref_open(&temp_ref, repo,
5698 got_worktree_get_head_ref_name(worktree), 0);
5699 if (err)
5700 return err;
5701 list_branch(repo, worktree, temp_ref);
5702 got_ref_close(temp_ref);
5706 err = got_ref_list(&refs, repo, "refs/heads",
5707 got_ref_cmp_by_name, NULL);
5708 if (err)
5709 return err;
5711 TAILQ_FOREACH(re, &refs, entry)
5712 list_branch(repo, worktree, re->ref);
5714 got_ref_list_free(&refs);
5716 err = got_ref_list(&refs, repo, "refs/remotes",
5717 got_ref_cmp_by_name, NULL);
5718 if (err)
5719 return err;
5721 TAILQ_FOREACH(re, &refs, entry)
5722 list_branch(repo, worktree, re->ref);
5724 got_ref_list_free(&refs);
5726 return NULL;
5729 static const struct got_error *
5730 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5731 const char *branch_name)
5733 const struct got_error *err = NULL;
5734 struct got_reference *ref = NULL;
5735 char *refname, *remote_refname = NULL;
5737 if (strncmp(branch_name, "refs/", 5) == 0)
5738 branch_name += 5;
5739 if (strncmp(branch_name, "heads/", 6) == 0)
5740 branch_name += 6;
5741 else if (strncmp(branch_name, "remotes/", 8) == 0)
5742 branch_name += 8;
5744 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5745 return got_error_from_errno("asprintf");
5747 if (asprintf(&remote_refname, "refs/remotes/%s",
5748 branch_name) == -1) {
5749 err = got_error_from_errno("asprintf");
5750 goto done;
5753 err = got_ref_open(&ref, repo, refname, 0);
5754 if (err) {
5755 const struct got_error *err2;
5756 if (err->code != GOT_ERR_NOT_REF)
5757 goto done;
5759 * Keep 'err' intact such that if neither branch exists
5760 * we report "refs/heads" rather than "refs/remotes" in
5761 * our error message.
5763 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5764 if (err2)
5765 goto done;
5766 err = NULL;
5769 if (worktree &&
5770 strcmp(got_worktree_get_head_ref_name(worktree),
5771 got_ref_get_name(ref)) == 0) {
5772 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5773 "will not delete this work tree's current branch");
5774 goto done;
5777 err = got_ref_delete(ref, repo);
5778 done:
5779 if (ref)
5780 got_ref_close(ref);
5781 free(refname);
5782 free(remote_refname);
5783 return err;
5786 static const struct got_error *
5787 add_branch(struct got_repository *repo, const char *branch_name,
5788 struct got_object_id *base_commit_id)
5790 const struct got_error *err = NULL;
5791 struct got_reference *ref = NULL;
5792 char *base_refname = NULL, *refname = NULL;
5795 * Don't let the user create a branch name with a leading '-'.
5796 * While technically a valid reference name, this case is usually
5797 * an unintended typo.
5799 if (branch_name[0] == '-')
5800 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5802 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5803 branch_name += 11;
5805 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5806 err = got_error_from_errno("asprintf");
5807 goto done;
5810 err = got_ref_open(&ref, repo, refname, 0);
5811 if (err == NULL) {
5812 err = got_error(GOT_ERR_BRANCH_EXISTS);
5813 goto done;
5814 } else if (err->code != GOT_ERR_NOT_REF)
5815 goto done;
5817 err = got_ref_alloc(&ref, refname, base_commit_id);
5818 if (err)
5819 goto done;
5821 err = got_ref_write(ref, repo);
5822 done:
5823 if (ref)
5824 got_ref_close(ref);
5825 free(base_refname);
5826 free(refname);
5827 return err;
5830 static const struct got_error *
5831 cmd_branch(int argc, char *argv[])
5833 const struct got_error *error = NULL;
5834 struct got_repository *repo = NULL;
5835 struct got_worktree *worktree = NULL;
5836 char *cwd = NULL, *repo_path = NULL;
5837 int ch, do_list = 0, do_show = 0, do_update = 1;
5838 const char *delref = NULL, *commit_id_arg = NULL;
5839 struct got_reference *ref = NULL;
5840 struct got_pathlist_head paths;
5841 struct got_pathlist_entry *pe;
5842 struct got_object_id *commit_id = NULL;
5843 char *commit_id_str = NULL;
5845 TAILQ_INIT(&paths);
5847 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5848 switch (ch) {
5849 case 'c':
5850 commit_id_arg = optarg;
5851 break;
5852 case 'd':
5853 delref = optarg;
5854 break;
5855 case 'r':
5856 repo_path = realpath(optarg, NULL);
5857 if (repo_path == NULL)
5858 return got_error_from_errno2("realpath",
5859 optarg);
5860 got_path_strip_trailing_slashes(repo_path);
5861 break;
5862 case 'l':
5863 do_list = 1;
5864 break;
5865 case 'n':
5866 do_update = 0;
5867 break;
5868 default:
5869 usage_branch();
5870 /* NOTREACHED */
5874 if (do_list && delref)
5875 option_conflict('l', 'd');
5877 argc -= optind;
5878 argv += optind;
5880 if (!do_list && !delref && argc == 0)
5881 do_show = 1;
5883 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5884 errx(1, "-c option can only be used when creating a branch");
5886 if (do_list || delref) {
5887 if (argc > 0)
5888 usage_branch();
5889 } else if (!do_show && argc != 1)
5890 usage_branch();
5892 #ifndef PROFILE
5893 if (do_list || do_show) {
5894 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5895 NULL) == -1)
5896 err(1, "pledge");
5897 } else {
5898 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5899 "sendfd unveil", NULL) == -1)
5900 err(1, "pledge");
5902 #endif
5903 cwd = getcwd(NULL, 0);
5904 if (cwd == NULL) {
5905 error = got_error_from_errno("getcwd");
5906 goto done;
5909 if (repo_path == NULL) {
5910 error = got_worktree_open(&worktree, cwd);
5911 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5912 goto done;
5913 else
5914 error = NULL;
5915 if (worktree) {
5916 repo_path =
5917 strdup(got_worktree_get_repo_path(worktree));
5918 if (repo_path == NULL)
5919 error = got_error_from_errno("strdup");
5920 if (error)
5921 goto done;
5922 } else {
5923 repo_path = strdup(cwd);
5924 if (repo_path == NULL) {
5925 error = got_error_from_errno("strdup");
5926 goto done;
5931 error = got_repo_open(&repo, repo_path, NULL);
5932 if (error != NULL)
5933 goto done;
5935 error = apply_unveil(got_repo_get_path(repo), do_list,
5936 worktree ? got_worktree_get_root_path(worktree) : NULL);
5937 if (error)
5938 goto done;
5940 if (do_show)
5941 error = show_current_branch(repo, worktree);
5942 else if (do_list)
5943 error = list_branches(repo, worktree);
5944 else if (delref)
5945 error = delete_branch(repo, worktree, delref);
5946 else {
5947 struct got_reflist_head refs;
5948 TAILQ_INIT(&refs);
5949 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5950 NULL);
5951 if (error)
5952 goto done;
5953 if (commit_id_arg == NULL)
5954 commit_id_arg = worktree ?
5955 got_worktree_get_head_ref_name(worktree) :
5956 GOT_REF_HEAD;
5957 error = got_repo_match_object_id(&commit_id, NULL,
5958 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5959 got_ref_list_free(&refs);
5960 if (error)
5961 goto done;
5962 error = add_branch(repo, argv[0], commit_id);
5963 if (error)
5964 goto done;
5965 if (worktree && do_update) {
5966 struct got_update_progress_arg upa;
5967 char *branch_refname = NULL;
5969 error = got_object_id_str(&commit_id_str, commit_id);
5970 if (error)
5971 goto done;
5972 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5973 worktree);
5974 if (error)
5975 goto done;
5976 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5977 == -1) {
5978 error = got_error_from_errno("asprintf");
5979 goto done;
5981 error = got_ref_open(&ref, repo, branch_refname, 0);
5982 free(branch_refname);
5983 if (error)
5984 goto done;
5985 error = switch_head_ref(ref, commit_id, worktree,
5986 repo);
5987 if (error)
5988 goto done;
5989 error = got_worktree_set_base_commit_id(worktree, repo,
5990 commit_id);
5991 if (error)
5992 goto done;
5993 memset(&upa, 0, sizeof(upa));
5994 error = got_worktree_checkout_files(worktree, &paths,
5995 repo, update_progress, &upa, check_cancelled,
5996 NULL);
5997 if (error)
5998 goto done;
5999 if (upa.did_something)
6000 printf("Updated to commit %s\n", commit_id_str);
6001 print_update_progress_stats(&upa);
6004 done:
6005 if (ref)
6006 got_ref_close(ref);
6007 if (repo) {
6008 const struct got_error *close_err = got_repo_close(repo);
6009 if (error == NULL)
6010 error = close_err;
6012 if (worktree)
6013 got_worktree_close(worktree);
6014 free(cwd);
6015 free(repo_path);
6016 free(commit_id);
6017 free(commit_id_str);
6018 TAILQ_FOREACH(pe, &paths, entry)
6019 free((char *)pe->path);
6020 got_pathlist_free(&paths);
6021 return error;
6025 __dead static void
6026 usage_tag(void)
6028 fprintf(stderr,
6029 "usage: %s tag [-c commit] [-r repository] [-l] "
6030 "[-m message] name\n", getprogname());
6031 exit(1);
6034 #if 0
6035 static const struct got_error *
6036 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6038 const struct got_error *err = NULL;
6039 struct got_reflist_entry *re, *se, *new;
6040 struct got_object_id *re_id, *se_id;
6041 struct got_tag_object *re_tag, *se_tag;
6042 time_t re_time, se_time;
6044 STAILQ_FOREACH(re, tags, entry) {
6045 se = STAILQ_FIRST(sorted);
6046 if (se == NULL) {
6047 err = got_reflist_entry_dup(&new, re);
6048 if (err)
6049 return err;
6050 STAILQ_INSERT_HEAD(sorted, new, entry);
6051 continue;
6052 } else {
6053 err = got_ref_resolve(&re_id, repo, re->ref);
6054 if (err)
6055 break;
6056 err = got_object_open_as_tag(&re_tag, repo, re_id);
6057 free(re_id);
6058 if (err)
6059 break;
6060 re_time = got_object_tag_get_tagger_time(re_tag);
6061 got_object_tag_close(re_tag);
6064 while (se) {
6065 err = got_ref_resolve(&se_id, repo, re->ref);
6066 if (err)
6067 break;
6068 err = got_object_open_as_tag(&se_tag, repo, se_id);
6069 free(se_id);
6070 if (err)
6071 break;
6072 se_time = got_object_tag_get_tagger_time(se_tag);
6073 got_object_tag_close(se_tag);
6075 if (se_time > re_time) {
6076 err = got_reflist_entry_dup(&new, re);
6077 if (err)
6078 return err;
6079 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6080 break;
6082 se = STAILQ_NEXT(se, entry);
6083 continue;
6086 done:
6087 return err;
6089 #endif
6091 static const struct got_error *
6092 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6094 static const struct got_error *err = NULL;
6095 struct got_reflist_head refs;
6096 struct got_reflist_entry *re;
6098 TAILQ_INIT(&refs);
6100 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6101 if (err)
6102 return err;
6104 TAILQ_FOREACH(re, &refs, entry) {
6105 const char *refname;
6106 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6107 char datebuf[26];
6108 const char *tagger;
6109 time_t tagger_time;
6110 struct got_object_id *id;
6111 struct got_tag_object *tag;
6112 struct got_commit_object *commit = NULL;
6114 refname = got_ref_get_name(re->ref);
6115 if (strncmp(refname, "refs/tags/", 10) != 0)
6116 continue;
6117 refname += 10;
6118 refstr = got_ref_to_str(re->ref);
6119 if (refstr == NULL) {
6120 err = got_error_from_errno("got_ref_to_str");
6121 break;
6123 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6124 free(refstr);
6126 err = got_ref_resolve(&id, repo, re->ref);
6127 if (err)
6128 break;
6129 err = got_object_open_as_tag(&tag, repo, id);
6130 if (err) {
6131 if (err->code != GOT_ERR_OBJ_TYPE) {
6132 free(id);
6133 break;
6135 /* "lightweight" tag */
6136 err = got_object_open_as_commit(&commit, repo, id);
6137 if (err) {
6138 free(id);
6139 break;
6141 tagger = got_object_commit_get_committer(commit);
6142 tagger_time =
6143 got_object_commit_get_committer_time(commit);
6144 err = got_object_id_str(&id_str, id);
6145 free(id);
6146 if (err)
6147 break;
6148 } else {
6149 free(id);
6150 tagger = got_object_tag_get_tagger(tag);
6151 tagger_time = got_object_tag_get_tagger_time(tag);
6152 err = got_object_id_str(&id_str,
6153 got_object_tag_get_object_id(tag));
6154 if (err)
6155 break;
6157 printf("from: %s\n", tagger);
6158 datestr = get_datestr(&tagger_time, datebuf);
6159 if (datestr)
6160 printf("date: %s UTC\n", datestr);
6161 if (commit)
6162 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6163 else {
6164 switch (got_object_tag_get_object_type(tag)) {
6165 case GOT_OBJ_TYPE_BLOB:
6166 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6167 id_str);
6168 break;
6169 case GOT_OBJ_TYPE_TREE:
6170 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6171 id_str);
6172 break;
6173 case GOT_OBJ_TYPE_COMMIT:
6174 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6175 id_str);
6176 break;
6177 case GOT_OBJ_TYPE_TAG:
6178 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6179 id_str);
6180 break;
6181 default:
6182 break;
6185 free(id_str);
6186 if (commit) {
6187 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6188 if (err)
6189 break;
6190 got_object_commit_close(commit);
6191 } else {
6192 tagmsg0 = strdup(got_object_tag_get_message(tag));
6193 got_object_tag_close(tag);
6194 if (tagmsg0 == NULL) {
6195 err = got_error_from_errno("strdup");
6196 break;
6200 tagmsg = tagmsg0;
6201 do {
6202 line = strsep(&tagmsg, "\n");
6203 if (line)
6204 printf(" %s\n", line);
6205 } while (line);
6206 free(tagmsg0);
6209 got_ref_list_free(&refs);
6210 return NULL;
6213 static const struct got_error *
6214 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6215 const char *tag_name, const char *repo_path)
6217 const struct got_error *err = NULL;
6218 char *template = NULL, *initial_content = NULL;
6219 char *editor = NULL;
6220 int initial_content_len;
6221 int fd = -1;
6223 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6224 err = got_error_from_errno("asprintf");
6225 goto done;
6228 initial_content_len = asprintf(&initial_content,
6229 "\n# tagging commit %s as %s\n",
6230 commit_id_str, tag_name);
6231 if (initial_content_len == -1) {
6232 err = got_error_from_errno("asprintf");
6233 goto done;
6236 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6237 if (err)
6238 goto done;
6240 if (write(fd, initial_content, initial_content_len) == -1) {
6241 err = got_error_from_errno2("write", *tagmsg_path);
6242 goto done;
6245 err = get_editor(&editor);
6246 if (err)
6247 goto done;
6248 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6249 initial_content_len, 1);
6250 done:
6251 free(initial_content);
6252 free(template);
6253 free(editor);
6255 if (fd != -1 && close(fd) == -1 && err == NULL)
6256 err = got_error_from_errno2("close", *tagmsg_path);
6258 /* Editor is done; we can now apply unveil(2) */
6259 if (err == NULL)
6260 err = apply_unveil(repo_path, 0, NULL);
6261 if (err) {
6262 free(*tagmsg);
6263 *tagmsg = NULL;
6265 return err;
6268 static const struct got_error *
6269 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6270 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6272 const struct got_error *err = NULL;
6273 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6274 char *label = NULL, *commit_id_str = NULL;
6275 struct got_reference *ref = NULL;
6276 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6277 char *tagmsg_path = NULL, *tag_id_str = NULL;
6278 int preserve_tagmsg = 0;
6279 struct got_reflist_head refs;
6281 TAILQ_INIT(&refs);
6284 * Don't let the user create a tag name with a leading '-'.
6285 * While technically a valid reference name, this case is usually
6286 * an unintended typo.
6288 if (tag_name[0] == '-')
6289 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6291 err = get_author(&tagger, repo, worktree);
6292 if (err)
6293 return err;
6295 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6296 if (err)
6297 goto done;
6299 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6300 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6301 if (err)
6302 goto done;
6304 err = got_object_id_str(&commit_id_str, commit_id);
6305 if (err)
6306 goto done;
6308 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6309 refname = strdup(tag_name);
6310 if (refname == NULL) {
6311 err = got_error_from_errno("strdup");
6312 goto done;
6314 tag_name += 10;
6315 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6316 err = got_error_from_errno("asprintf");
6317 goto done;
6320 err = got_ref_open(&ref, repo, refname, 0);
6321 if (err == NULL) {
6322 err = got_error(GOT_ERR_TAG_EXISTS);
6323 goto done;
6324 } else if (err->code != GOT_ERR_NOT_REF)
6325 goto done;
6327 if (tagmsg_arg == NULL) {
6328 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6329 tag_name, got_repo_get_path(repo));
6330 if (err) {
6331 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6332 tagmsg_path != NULL)
6333 preserve_tagmsg = 1;
6334 goto done;
6338 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6339 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6340 if (err) {
6341 if (tagmsg_path)
6342 preserve_tagmsg = 1;
6343 goto done;
6346 err = got_ref_alloc(&ref, refname, tag_id);
6347 if (err) {
6348 if (tagmsg_path)
6349 preserve_tagmsg = 1;
6350 goto done;
6353 err = got_ref_write(ref, repo);
6354 if (err) {
6355 if (tagmsg_path)
6356 preserve_tagmsg = 1;
6357 goto done;
6360 err = got_object_id_str(&tag_id_str, tag_id);
6361 if (err) {
6362 if (tagmsg_path)
6363 preserve_tagmsg = 1;
6364 goto done;
6366 printf("Created tag %s\n", tag_id_str);
6367 done:
6368 if (preserve_tagmsg) {
6369 fprintf(stderr, "%s: tag message preserved in %s\n",
6370 getprogname(), tagmsg_path);
6371 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6372 err = got_error_from_errno2("unlink", tagmsg_path);
6373 free(tag_id_str);
6374 if (ref)
6375 got_ref_close(ref);
6376 free(commit_id);
6377 free(commit_id_str);
6378 free(refname);
6379 free(tagmsg);
6380 free(tagmsg_path);
6381 free(tagger);
6382 got_ref_list_free(&refs);
6383 return err;
6386 static const struct got_error *
6387 cmd_tag(int argc, char *argv[])
6389 const struct got_error *error = NULL;
6390 struct got_repository *repo = NULL;
6391 struct got_worktree *worktree = NULL;
6392 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6393 char *gitconfig_path = NULL;
6394 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6395 int ch, do_list = 0;
6397 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6398 switch (ch) {
6399 case 'c':
6400 commit_id_arg = optarg;
6401 break;
6402 case 'm':
6403 tagmsg = optarg;
6404 break;
6405 case 'r':
6406 repo_path = realpath(optarg, NULL);
6407 if (repo_path == NULL)
6408 return got_error_from_errno2("realpath",
6409 optarg);
6410 got_path_strip_trailing_slashes(repo_path);
6411 break;
6412 case 'l':
6413 do_list = 1;
6414 break;
6415 default:
6416 usage_tag();
6417 /* NOTREACHED */
6421 argc -= optind;
6422 argv += optind;
6424 if (do_list) {
6425 if (commit_id_arg != NULL)
6426 errx(1,
6427 "-c option can only be used when creating a tag");
6428 if (tagmsg)
6429 option_conflict('l', 'm');
6430 if (argc > 0)
6431 usage_tag();
6432 } else if (argc != 1)
6433 usage_tag();
6435 tag_name = argv[0];
6437 #ifndef PROFILE
6438 if (do_list) {
6439 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6440 NULL) == -1)
6441 err(1, "pledge");
6442 } else {
6443 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6444 "sendfd unveil", NULL) == -1)
6445 err(1, "pledge");
6447 #endif
6448 cwd = getcwd(NULL, 0);
6449 if (cwd == NULL) {
6450 error = got_error_from_errno("getcwd");
6451 goto done;
6454 if (repo_path == NULL) {
6455 error = got_worktree_open(&worktree, cwd);
6456 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6457 goto done;
6458 else
6459 error = NULL;
6460 if (worktree) {
6461 repo_path =
6462 strdup(got_worktree_get_repo_path(worktree));
6463 if (repo_path == NULL)
6464 error = got_error_from_errno("strdup");
6465 if (error)
6466 goto done;
6467 } else {
6468 repo_path = strdup(cwd);
6469 if (repo_path == NULL) {
6470 error = got_error_from_errno("strdup");
6471 goto done;
6476 if (do_list) {
6477 error = got_repo_open(&repo, repo_path, NULL);
6478 if (error != NULL)
6479 goto done;
6480 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6481 if (error)
6482 goto done;
6483 error = list_tags(repo, worktree);
6484 } else {
6485 error = get_gitconfig_path(&gitconfig_path);
6486 if (error)
6487 goto done;
6488 error = got_repo_open(&repo, repo_path, gitconfig_path);
6489 if (error != NULL)
6490 goto done;
6492 if (tagmsg) {
6493 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6494 if (error)
6495 goto done;
6498 if (commit_id_arg == NULL) {
6499 struct got_reference *head_ref;
6500 struct got_object_id *commit_id;
6501 error = got_ref_open(&head_ref, repo,
6502 worktree ? got_worktree_get_head_ref_name(worktree)
6503 : GOT_REF_HEAD, 0);
6504 if (error)
6505 goto done;
6506 error = got_ref_resolve(&commit_id, repo, head_ref);
6507 got_ref_close(head_ref);
6508 if (error)
6509 goto done;
6510 error = got_object_id_str(&commit_id_str, commit_id);
6511 free(commit_id);
6512 if (error)
6513 goto done;
6516 error = add_tag(repo, worktree, tag_name,
6517 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6519 done:
6520 if (repo) {
6521 const struct got_error *close_err = got_repo_close(repo);
6522 if (error == NULL)
6523 error = close_err;
6525 if (worktree)
6526 got_worktree_close(worktree);
6527 free(cwd);
6528 free(repo_path);
6529 free(gitconfig_path);
6530 free(commit_id_str);
6531 return error;
6534 __dead static void
6535 usage_add(void)
6537 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6538 getprogname());
6539 exit(1);
6542 static const struct got_error *
6543 add_progress(void *arg, unsigned char status, const char *path)
6545 while (path[0] == '/')
6546 path++;
6547 printf("%c %s\n", status, path);
6548 return NULL;
6551 static const struct got_error *
6552 cmd_add(int argc, char *argv[])
6554 const struct got_error *error = NULL;
6555 struct got_repository *repo = NULL;
6556 struct got_worktree *worktree = NULL;
6557 char *cwd = NULL;
6558 struct got_pathlist_head paths;
6559 struct got_pathlist_entry *pe;
6560 int ch, can_recurse = 0, no_ignores = 0;
6562 TAILQ_INIT(&paths);
6564 while ((ch = getopt(argc, argv, "IR")) != -1) {
6565 switch (ch) {
6566 case 'I':
6567 no_ignores = 1;
6568 break;
6569 case 'R':
6570 can_recurse = 1;
6571 break;
6572 default:
6573 usage_add();
6574 /* NOTREACHED */
6578 argc -= optind;
6579 argv += optind;
6581 #ifndef PROFILE
6582 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6583 NULL) == -1)
6584 err(1, "pledge");
6585 #endif
6586 if (argc < 1)
6587 usage_add();
6589 cwd = getcwd(NULL, 0);
6590 if (cwd == NULL) {
6591 error = got_error_from_errno("getcwd");
6592 goto done;
6595 error = got_worktree_open(&worktree, cwd);
6596 if (error) {
6597 if (error->code == GOT_ERR_NOT_WORKTREE)
6598 error = wrap_not_worktree_error(error, "add", cwd);
6599 goto done;
6602 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6603 NULL);
6604 if (error != NULL)
6605 goto done;
6607 error = apply_unveil(got_repo_get_path(repo), 1,
6608 got_worktree_get_root_path(worktree));
6609 if (error)
6610 goto done;
6612 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6613 if (error)
6614 goto done;
6616 if (!can_recurse) {
6617 char *ondisk_path;
6618 struct stat sb;
6619 TAILQ_FOREACH(pe, &paths, entry) {
6620 if (asprintf(&ondisk_path, "%s/%s",
6621 got_worktree_get_root_path(worktree),
6622 pe->path) == -1) {
6623 error = got_error_from_errno("asprintf");
6624 goto done;
6626 if (lstat(ondisk_path, &sb) == -1) {
6627 if (errno == ENOENT) {
6628 free(ondisk_path);
6629 continue;
6631 error = got_error_from_errno2("lstat",
6632 ondisk_path);
6633 free(ondisk_path);
6634 goto done;
6636 free(ondisk_path);
6637 if (S_ISDIR(sb.st_mode)) {
6638 error = got_error_msg(GOT_ERR_BAD_PATH,
6639 "adding directories requires -R option");
6640 goto done;
6645 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6646 NULL, repo, no_ignores);
6647 done:
6648 if (repo) {
6649 const struct got_error *close_err = got_repo_close(repo);
6650 if (error == NULL)
6651 error = close_err;
6653 if (worktree)
6654 got_worktree_close(worktree);
6655 TAILQ_FOREACH(pe, &paths, entry)
6656 free((char *)pe->path);
6657 got_pathlist_free(&paths);
6658 free(cwd);
6659 return error;
6662 __dead static void
6663 usage_remove(void)
6665 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6666 "path ...\n", getprogname());
6667 exit(1);
6670 static const struct got_error *
6671 print_remove_status(void *arg, unsigned char status,
6672 unsigned char staged_status, const char *path)
6674 while (path[0] == '/')
6675 path++;
6676 if (status == GOT_STATUS_NONEXISTENT)
6677 return NULL;
6678 if (status == staged_status && (status == GOT_STATUS_DELETE))
6679 status = GOT_STATUS_NO_CHANGE;
6680 printf("%c%c %s\n", status, staged_status, path);
6681 return NULL;
6684 static const struct got_error *
6685 cmd_remove(int argc, char *argv[])
6687 const struct got_error *error = NULL;
6688 struct got_worktree *worktree = NULL;
6689 struct got_repository *repo = NULL;
6690 const char *status_codes = NULL;
6691 char *cwd = NULL;
6692 struct got_pathlist_head paths;
6693 struct got_pathlist_entry *pe;
6694 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6696 TAILQ_INIT(&paths);
6698 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6699 switch (ch) {
6700 case 'f':
6701 delete_local_mods = 1;
6702 break;
6703 case 'k':
6704 keep_on_disk = 1;
6705 break;
6706 case 'R':
6707 can_recurse = 1;
6708 break;
6709 case 's':
6710 for (i = 0; i < strlen(optarg); i++) {
6711 switch (optarg[i]) {
6712 case GOT_STATUS_MODIFY:
6713 delete_local_mods = 1;
6714 break;
6715 case GOT_STATUS_MISSING:
6716 break;
6717 default:
6718 errx(1, "invalid status code '%c'",
6719 optarg[i]);
6722 status_codes = optarg;
6723 break;
6724 default:
6725 usage_remove();
6726 /* NOTREACHED */
6730 argc -= optind;
6731 argv += optind;
6733 #ifndef PROFILE
6734 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6735 NULL) == -1)
6736 err(1, "pledge");
6737 #endif
6738 if (argc < 1)
6739 usage_remove();
6741 cwd = getcwd(NULL, 0);
6742 if (cwd == NULL) {
6743 error = got_error_from_errno("getcwd");
6744 goto done;
6746 error = got_worktree_open(&worktree, cwd);
6747 if (error) {
6748 if (error->code == GOT_ERR_NOT_WORKTREE)
6749 error = wrap_not_worktree_error(error, "remove", cwd);
6750 goto done;
6753 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6754 NULL);
6755 if (error)
6756 goto done;
6758 error = apply_unveil(got_repo_get_path(repo), 1,
6759 got_worktree_get_root_path(worktree));
6760 if (error)
6761 goto done;
6763 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6764 if (error)
6765 goto done;
6767 if (!can_recurse) {
6768 char *ondisk_path;
6769 struct stat sb;
6770 TAILQ_FOREACH(pe, &paths, entry) {
6771 if (asprintf(&ondisk_path, "%s/%s",
6772 got_worktree_get_root_path(worktree),
6773 pe->path) == -1) {
6774 error = got_error_from_errno("asprintf");
6775 goto done;
6777 if (lstat(ondisk_path, &sb) == -1) {
6778 if (errno == ENOENT) {
6779 free(ondisk_path);
6780 continue;
6782 error = got_error_from_errno2("lstat",
6783 ondisk_path);
6784 free(ondisk_path);
6785 goto done;
6787 free(ondisk_path);
6788 if (S_ISDIR(sb.st_mode)) {
6789 error = got_error_msg(GOT_ERR_BAD_PATH,
6790 "removing directories requires -R option");
6791 goto done;
6796 error = got_worktree_schedule_delete(worktree, &paths,
6797 delete_local_mods, status_codes, print_remove_status, NULL,
6798 repo, keep_on_disk);
6799 done:
6800 if (repo) {
6801 const struct got_error *close_err = got_repo_close(repo);
6802 if (error == NULL)
6803 error = close_err;
6805 if (worktree)
6806 got_worktree_close(worktree);
6807 TAILQ_FOREACH(pe, &paths, entry)
6808 free((char *)pe->path);
6809 got_pathlist_free(&paths);
6810 free(cwd);
6811 return error;
6814 __dead static void
6815 usage_revert(void)
6817 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6818 "path ...\n", getprogname());
6819 exit(1);
6822 static const struct got_error *
6823 revert_progress(void *arg, unsigned char status, const char *path)
6825 if (status == GOT_STATUS_UNVERSIONED)
6826 return NULL;
6828 while (path[0] == '/')
6829 path++;
6830 printf("%c %s\n", status, path);
6831 return NULL;
6834 struct choose_patch_arg {
6835 FILE *patch_script_file;
6836 const char *action;
6839 static const struct got_error *
6840 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6841 int nchanges, const char *action)
6843 char *line = NULL;
6844 size_t linesize = 0;
6845 ssize_t linelen;
6847 switch (status) {
6848 case GOT_STATUS_ADD:
6849 printf("A %s\n%s this addition? [y/n] ", path, action);
6850 break;
6851 case GOT_STATUS_DELETE:
6852 printf("D %s\n%s this deletion? [y/n] ", path, action);
6853 break;
6854 case GOT_STATUS_MODIFY:
6855 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6856 return got_error_from_errno("fseek");
6857 printf(GOT_COMMIT_SEP_STR);
6858 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6859 printf("%s", line);
6860 if (ferror(patch_file))
6861 return got_error_from_errno("getline");
6862 printf(GOT_COMMIT_SEP_STR);
6863 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6864 path, n, nchanges, action);
6865 break;
6866 default:
6867 return got_error_path(path, GOT_ERR_FILE_STATUS);
6870 return NULL;
6873 static const struct got_error *
6874 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6875 FILE *patch_file, int n, int nchanges)
6877 const struct got_error *err = NULL;
6878 char *line = NULL;
6879 size_t linesize = 0;
6880 ssize_t linelen;
6881 int resp = ' ';
6882 struct choose_patch_arg *a = arg;
6884 *choice = GOT_PATCH_CHOICE_NONE;
6886 if (a->patch_script_file) {
6887 char *nl;
6888 err = show_change(status, path, patch_file, n, nchanges,
6889 a->action);
6890 if (err)
6891 return err;
6892 linelen = getline(&line, &linesize, a->patch_script_file);
6893 if (linelen == -1) {
6894 if (ferror(a->patch_script_file))
6895 return got_error_from_errno("getline");
6896 return NULL;
6898 nl = strchr(line, '\n');
6899 if (nl)
6900 *nl = '\0';
6901 if (strcmp(line, "y") == 0) {
6902 *choice = GOT_PATCH_CHOICE_YES;
6903 printf("y\n");
6904 } else if (strcmp(line, "n") == 0) {
6905 *choice = GOT_PATCH_CHOICE_NO;
6906 printf("n\n");
6907 } else if (strcmp(line, "q") == 0 &&
6908 status == GOT_STATUS_MODIFY) {
6909 *choice = GOT_PATCH_CHOICE_QUIT;
6910 printf("q\n");
6911 } else
6912 printf("invalid response '%s'\n", line);
6913 free(line);
6914 return NULL;
6917 while (resp != 'y' && resp != 'n' && resp != 'q') {
6918 err = show_change(status, path, patch_file, n, nchanges,
6919 a->action);
6920 if (err)
6921 return err;
6922 resp = getchar();
6923 if (resp == '\n')
6924 resp = getchar();
6925 if (status == GOT_STATUS_MODIFY) {
6926 if (resp != 'y' && resp != 'n' && resp != 'q') {
6927 printf("invalid response '%c'\n", resp);
6928 resp = ' ';
6930 } else if (resp != 'y' && resp != 'n') {
6931 printf("invalid response '%c'\n", resp);
6932 resp = ' ';
6936 if (resp == 'y')
6937 *choice = GOT_PATCH_CHOICE_YES;
6938 else if (resp == 'n')
6939 *choice = GOT_PATCH_CHOICE_NO;
6940 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6941 *choice = GOT_PATCH_CHOICE_QUIT;
6943 return NULL;
6947 static const struct got_error *
6948 cmd_revert(int argc, char *argv[])
6950 const struct got_error *error = NULL;
6951 struct got_worktree *worktree = NULL;
6952 struct got_repository *repo = NULL;
6953 char *cwd = NULL, *path = NULL;
6954 struct got_pathlist_head paths;
6955 struct got_pathlist_entry *pe;
6956 int ch, can_recurse = 0, pflag = 0;
6957 FILE *patch_script_file = NULL;
6958 const char *patch_script_path = NULL;
6959 struct choose_patch_arg cpa;
6961 TAILQ_INIT(&paths);
6963 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6964 switch (ch) {
6965 case 'p':
6966 pflag = 1;
6967 break;
6968 case 'F':
6969 patch_script_path = optarg;
6970 break;
6971 case 'R':
6972 can_recurse = 1;
6973 break;
6974 default:
6975 usage_revert();
6976 /* NOTREACHED */
6980 argc -= optind;
6981 argv += optind;
6983 #ifndef PROFILE
6984 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6985 "unveil", NULL) == -1)
6986 err(1, "pledge");
6987 #endif
6988 if (argc < 1)
6989 usage_revert();
6990 if (patch_script_path && !pflag)
6991 errx(1, "-F option can only be used together with -p option");
6993 cwd = getcwd(NULL, 0);
6994 if (cwd == NULL) {
6995 error = got_error_from_errno("getcwd");
6996 goto done;
6998 error = got_worktree_open(&worktree, cwd);
6999 if (error) {
7000 if (error->code == GOT_ERR_NOT_WORKTREE)
7001 error = wrap_not_worktree_error(error, "revert", cwd);
7002 goto done;
7005 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7006 NULL);
7007 if (error != NULL)
7008 goto done;
7010 if (patch_script_path) {
7011 patch_script_file = fopen(patch_script_path, "r");
7012 if (patch_script_file == NULL) {
7013 error = got_error_from_errno2("fopen",
7014 patch_script_path);
7015 goto done;
7018 error = apply_unveil(got_repo_get_path(repo), 1,
7019 got_worktree_get_root_path(worktree));
7020 if (error)
7021 goto done;
7023 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7024 if (error)
7025 goto done;
7027 if (!can_recurse) {
7028 char *ondisk_path;
7029 struct stat sb;
7030 TAILQ_FOREACH(pe, &paths, entry) {
7031 if (asprintf(&ondisk_path, "%s/%s",
7032 got_worktree_get_root_path(worktree),
7033 pe->path) == -1) {
7034 error = got_error_from_errno("asprintf");
7035 goto done;
7037 if (lstat(ondisk_path, &sb) == -1) {
7038 if (errno == ENOENT) {
7039 free(ondisk_path);
7040 continue;
7042 error = got_error_from_errno2("lstat",
7043 ondisk_path);
7044 free(ondisk_path);
7045 goto done;
7047 free(ondisk_path);
7048 if (S_ISDIR(sb.st_mode)) {
7049 error = got_error_msg(GOT_ERR_BAD_PATH,
7050 "reverting directories requires -R option");
7051 goto done;
7056 cpa.patch_script_file = patch_script_file;
7057 cpa.action = "revert";
7058 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7059 pflag ? choose_patch : NULL, &cpa, repo);
7060 done:
7061 if (patch_script_file && fclose(patch_script_file) == EOF &&
7062 error == NULL)
7063 error = got_error_from_errno2("fclose", patch_script_path);
7064 if (repo) {
7065 const struct got_error *close_err = got_repo_close(repo);
7066 if (error == NULL)
7067 error = close_err;
7069 if (worktree)
7070 got_worktree_close(worktree);
7071 free(path);
7072 free(cwd);
7073 return error;
7076 __dead static void
7077 usage_commit(void)
7079 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7080 "[path ...]\n", getprogname());
7081 exit(1);
7084 struct collect_commit_logmsg_arg {
7085 const char *cmdline_log;
7086 const char *prepared_log;
7087 int non_interactive;
7088 const char *editor;
7089 const char *worktree_path;
7090 const char *branch_name;
7091 const char *repo_path;
7092 char *logmsg_path;
7096 static const struct got_error *
7097 read_prepared_logmsg(char **logmsg, const char *path)
7099 const struct got_error *err = NULL;
7100 FILE *f = NULL;
7101 struct stat sb;
7102 size_t r;
7104 *logmsg = NULL;
7105 memset(&sb, 0, sizeof(sb));
7107 f = fopen(path, "r");
7108 if (f == NULL)
7109 return got_error_from_errno2("fopen", path);
7111 if (fstat(fileno(f), &sb) == -1) {
7112 err = got_error_from_errno2("fstat", path);
7113 goto done;
7115 if (sb.st_size == 0) {
7116 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7117 goto done;
7120 *logmsg = malloc(sb.st_size + 1);
7121 if (*logmsg == NULL) {
7122 err = got_error_from_errno("malloc");
7123 goto done;
7126 r = fread(*logmsg, 1, sb.st_size, f);
7127 if (r != sb.st_size) {
7128 if (ferror(f))
7129 err = got_error_from_errno2("fread", path);
7130 else
7131 err = got_error(GOT_ERR_IO);
7132 goto done;
7134 (*logmsg)[sb.st_size] = '\0';
7135 done:
7136 if (fclose(f) == EOF && err == NULL)
7137 err = got_error_from_errno2("fclose", path);
7138 if (err) {
7139 free(*logmsg);
7140 *logmsg = NULL;
7142 return err;
7146 static const struct got_error *
7147 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7148 void *arg)
7150 char *initial_content = NULL;
7151 struct got_pathlist_entry *pe;
7152 const struct got_error *err = NULL;
7153 char *template = NULL;
7154 struct collect_commit_logmsg_arg *a = arg;
7155 int initial_content_len;
7156 int fd = -1;
7157 size_t len;
7159 /* if a message was specified on the command line, just use it */
7160 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7161 len = strlen(a->cmdline_log) + 1;
7162 *logmsg = malloc(len + 1);
7163 if (*logmsg == NULL)
7164 return got_error_from_errno("malloc");
7165 strlcpy(*logmsg, a->cmdline_log, len);
7166 return NULL;
7167 } else if (a->prepared_log != NULL && a->non_interactive)
7168 return read_prepared_logmsg(logmsg, a->prepared_log);
7170 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7171 return got_error_from_errno("asprintf");
7173 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7174 if (err)
7175 goto done;
7177 if (a->prepared_log) {
7178 char *msg;
7179 err = read_prepared_logmsg(&msg, a->prepared_log);
7180 if (err)
7181 goto done;
7182 if (write(fd, msg, strlen(msg)) == -1) {
7183 err = got_error_from_errno2("write", a->logmsg_path);
7184 free(msg);
7185 goto done;
7187 free(msg);
7190 initial_content_len = asprintf(&initial_content,
7191 "\n# changes to be committed on branch %s:\n",
7192 a->branch_name);
7193 if (initial_content_len == -1) {
7194 err = got_error_from_errno("asprintf");
7195 goto done;
7198 if (write(fd, initial_content, initial_content_len) == -1) {
7199 err = got_error_from_errno2("write", a->logmsg_path);
7200 goto done;
7203 TAILQ_FOREACH(pe, commitable_paths, entry) {
7204 struct got_commitable *ct = pe->data;
7205 dprintf(fd, "# %c %s\n",
7206 got_commitable_get_status(ct),
7207 got_commitable_get_path(ct));
7210 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7211 initial_content_len, a->prepared_log ? 0 : 1);
7212 done:
7213 free(initial_content);
7214 free(template);
7216 if (fd != -1 && close(fd) == -1 && err == NULL)
7217 err = got_error_from_errno2("close", a->logmsg_path);
7219 /* Editor is done; we can now apply unveil(2) */
7220 if (err == NULL)
7221 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7222 if (err) {
7223 free(*logmsg);
7224 *logmsg = NULL;
7226 return err;
7229 static const struct got_error *
7230 cmd_commit(int argc, char *argv[])
7232 const struct got_error *error = NULL;
7233 struct got_worktree *worktree = NULL;
7234 struct got_repository *repo = NULL;
7235 char *cwd = NULL, *id_str = NULL;
7236 struct got_object_id *id = NULL;
7237 const char *logmsg = NULL;
7238 char *prepared_logmsg = NULL;
7239 struct collect_commit_logmsg_arg cl_arg;
7240 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7241 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7242 int allow_bad_symlinks = 0, non_interactive = 0;
7243 struct got_pathlist_head paths;
7245 TAILQ_INIT(&paths);
7246 cl_arg.logmsg_path = NULL;
7248 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7249 switch (ch) {
7250 case 'F':
7251 if (logmsg != NULL)
7252 option_conflict('F', 'm');
7253 prepared_logmsg = realpath(optarg, NULL);
7254 if (prepared_logmsg == NULL)
7255 return got_error_from_errno2("realpath",
7256 optarg);
7257 break;
7258 case 'm':
7259 if (prepared_logmsg)
7260 option_conflict('m', 'F');
7261 logmsg = optarg;
7262 break;
7263 case 'N':
7264 non_interactive = 1;
7265 break;
7266 case 'S':
7267 allow_bad_symlinks = 1;
7268 break;
7269 default:
7270 usage_commit();
7271 /* NOTREACHED */
7275 argc -= optind;
7276 argv += optind;
7278 #ifndef PROFILE
7279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7280 "unveil", NULL) == -1)
7281 err(1, "pledge");
7282 #endif
7283 cwd = getcwd(NULL, 0);
7284 if (cwd == NULL) {
7285 error = got_error_from_errno("getcwd");
7286 goto done;
7288 error = got_worktree_open(&worktree, cwd);
7289 if (error) {
7290 if (error->code == GOT_ERR_NOT_WORKTREE)
7291 error = wrap_not_worktree_error(error, "commit", cwd);
7292 goto done;
7295 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7296 if (error)
7297 goto done;
7298 if (rebase_in_progress) {
7299 error = got_error(GOT_ERR_REBASING);
7300 goto done;
7303 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7304 worktree);
7305 if (error)
7306 goto done;
7308 error = get_gitconfig_path(&gitconfig_path);
7309 if (error)
7310 goto done;
7311 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7312 gitconfig_path);
7313 if (error != NULL)
7314 goto done;
7316 error = get_author(&author, repo, worktree);
7317 if (error)
7318 return error;
7321 * unveil(2) traverses exec(2); if an editor is used we have
7322 * to apply unveil after the log message has been written.
7324 if (logmsg == NULL || strlen(logmsg) == 0)
7325 error = get_editor(&editor);
7326 else
7327 error = apply_unveil(got_repo_get_path(repo), 0,
7328 got_worktree_get_root_path(worktree));
7329 if (error)
7330 goto done;
7332 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7333 if (error)
7334 goto done;
7336 cl_arg.editor = editor;
7337 cl_arg.cmdline_log = logmsg;
7338 cl_arg.prepared_log = prepared_logmsg;
7339 cl_arg.non_interactive = non_interactive;
7340 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7341 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7342 if (!histedit_in_progress) {
7343 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7344 error = got_error(GOT_ERR_COMMIT_BRANCH);
7345 goto done;
7347 cl_arg.branch_name += 11;
7349 cl_arg.repo_path = got_repo_get_path(repo);
7350 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7351 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7352 print_status, NULL, repo);
7353 if (error) {
7354 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7355 cl_arg.logmsg_path != NULL)
7356 preserve_logmsg = 1;
7357 goto done;
7360 error = got_object_id_str(&id_str, id);
7361 if (error)
7362 goto done;
7363 printf("Created commit %s\n", id_str);
7364 done:
7365 if (preserve_logmsg) {
7366 fprintf(stderr, "%s: log message preserved in %s\n",
7367 getprogname(), cl_arg.logmsg_path);
7368 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7369 error == NULL)
7370 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7371 free(cl_arg.logmsg_path);
7372 if (repo) {
7373 const struct got_error *close_err = got_repo_close(repo);
7374 if (error == NULL)
7375 error = close_err;
7377 if (worktree)
7378 got_worktree_close(worktree);
7379 free(cwd);
7380 free(id_str);
7381 free(gitconfig_path);
7382 free(editor);
7383 free(author);
7384 free(prepared_logmsg);
7385 return error;
7388 __dead static void
7389 usage_send(void)
7391 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7392 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7393 "[remote-repository]\n", getprogname());
7394 exit(1);
7397 struct got_send_progress_arg {
7398 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7399 int verbosity;
7400 int last_ncommits;
7401 int last_nobj_total;
7402 int last_p_deltify;
7403 int last_p_written;
7404 int last_p_sent;
7405 int printed_something;
7406 int sent_something;
7407 struct got_pathlist_head *delete_branches;
7410 static const struct got_error *
7411 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7412 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7413 int success)
7415 struct got_send_progress_arg *a = arg;
7416 char scaled_packsize[FMT_SCALED_STRSIZE];
7417 char scaled_sent[FMT_SCALED_STRSIZE];
7418 int p_deltify = 0, p_written = 0, p_sent = 0;
7419 int print_searching = 0, print_total = 0;
7420 int print_deltify = 0, print_written = 0, print_sent = 0;
7422 if (a->verbosity < 0)
7423 return NULL;
7425 if (refname) {
7426 const char *status = success ? "accepted" : "rejected";
7428 if (success) {
7429 struct got_pathlist_entry *pe;
7430 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7431 const char *branchname = pe->path;
7432 if (got_path_cmp(branchname, refname,
7433 strlen(branchname), strlen(refname)) == 0) {
7434 status = "deleted";
7435 a->sent_something = 1;
7436 break;
7441 if (a->printed_something)
7442 putchar('\n');
7443 printf("Server has %s %s", status, refname);
7444 a->printed_something = 1;
7445 return NULL;
7448 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7449 return got_error_from_errno("fmt_scaled");
7450 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7451 return got_error_from_errno("fmt_scaled");
7453 if (a->last_ncommits != ncommits) {
7454 print_searching = 1;
7455 a->last_ncommits = ncommits;
7458 if (a->last_nobj_total != nobj_total) {
7459 print_searching = 1;
7460 print_total = 1;
7461 a->last_nobj_total = nobj_total;
7464 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7465 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7466 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7467 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7468 return got_error(GOT_ERR_NO_SPACE);
7471 if (nobj_deltify > 0 || nobj_written > 0) {
7472 if (nobj_deltify > 0) {
7473 p_deltify = (nobj_deltify * 100) / nobj_total;
7474 if (p_deltify != a->last_p_deltify) {
7475 a->last_p_deltify = p_deltify;
7476 print_searching = 1;
7477 print_total = 1;
7478 print_deltify = 1;
7481 if (nobj_written > 0) {
7482 p_written = (nobj_written * 100) / nobj_total;
7483 if (p_written != a->last_p_written) {
7484 a->last_p_written = p_written;
7485 print_searching = 1;
7486 print_total = 1;
7487 print_deltify = 1;
7488 print_written = 1;
7493 if (bytes_sent > 0) {
7494 p_sent = (bytes_sent * 100) / packfile_size;
7495 if (p_sent != a->last_p_sent) {
7496 a->last_p_sent = p_sent;
7497 print_searching = 1;
7498 print_total = 1;
7499 print_deltify = 1;
7500 print_written = 1;
7501 print_sent = 1;
7503 a->sent_something = 1;
7506 if (print_searching || print_total || print_deltify || print_written ||
7507 print_sent)
7508 printf("\r");
7509 if (print_searching)
7510 printf("packing %d reference%s", ncommits,
7511 ncommits == 1 ? "" : "s");
7512 if (print_total)
7513 printf("; %d object%s", nobj_total,
7514 nobj_total == 1 ? "" : "s");
7515 if (print_deltify)
7516 printf("; deltify: %d%%", p_deltify);
7517 if (print_sent)
7518 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7519 scaled_packsize, p_sent);
7520 else if (print_written)
7521 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7522 scaled_packsize, p_written);
7523 if (print_searching || print_total || print_deltify ||
7524 print_written || print_sent) {
7525 a->printed_something = 1;
7526 fflush(stdout);
7528 return NULL;
7531 static const struct got_error *
7532 cmd_send(int argc, char *argv[])
7534 const struct got_error *error = NULL;
7535 char *cwd = NULL, *repo_path = NULL;
7536 const char *remote_name;
7537 char *proto = NULL, *host = NULL, *port = NULL;
7538 char *repo_name = NULL, *server_path = NULL;
7539 const struct got_remote_repo *remotes, *remote = NULL;
7540 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7541 struct got_repository *repo = NULL;
7542 struct got_worktree *worktree = NULL;
7543 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7544 struct got_pathlist_head branches;
7545 struct got_pathlist_head tags;
7546 struct got_reflist_head all_branches;
7547 struct got_reflist_head all_tags;
7548 struct got_pathlist_head delete_args;
7549 struct got_pathlist_head delete_branches;
7550 struct got_reflist_entry *re;
7551 struct got_pathlist_entry *pe;
7552 int i, ch, sendfd = -1, sendstatus;
7553 pid_t sendpid = -1;
7554 struct got_send_progress_arg spa;
7555 int verbosity = 0, overwrite_refs = 0;
7556 int send_all_branches = 0, send_all_tags = 0;
7557 struct got_reference *ref = NULL;
7559 TAILQ_INIT(&branches);
7560 TAILQ_INIT(&tags);
7561 TAILQ_INIT(&all_branches);
7562 TAILQ_INIT(&all_tags);
7563 TAILQ_INIT(&delete_args);
7564 TAILQ_INIT(&delete_branches);
7566 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7567 switch (ch) {
7568 case 'a':
7569 send_all_branches = 1;
7570 break;
7571 case 'b':
7572 error = got_pathlist_append(&branches, optarg, NULL);
7573 if (error)
7574 return error;
7575 nbranches++;
7576 break;
7577 case 'd':
7578 error = got_pathlist_append(&delete_args, optarg, NULL);
7579 if (error)
7580 return error;
7581 break;
7582 case 'f':
7583 overwrite_refs = 1;
7584 break;
7585 case 'r':
7586 repo_path = realpath(optarg, NULL);
7587 if (repo_path == NULL)
7588 return got_error_from_errno2("realpath",
7589 optarg);
7590 got_path_strip_trailing_slashes(repo_path);
7591 break;
7592 case 't':
7593 error = got_pathlist_append(&tags, optarg, NULL);
7594 if (error)
7595 return error;
7596 ntags++;
7597 break;
7598 case 'T':
7599 send_all_tags = 1;
7600 break;
7601 case 'v':
7602 if (verbosity < 0)
7603 verbosity = 0;
7604 else if (verbosity < 3)
7605 verbosity++;
7606 break;
7607 case 'q':
7608 verbosity = -1;
7609 break;
7610 default:
7611 usage_send();
7612 /* NOTREACHED */
7615 argc -= optind;
7616 argv += optind;
7618 if (send_all_branches && !TAILQ_EMPTY(&branches))
7619 option_conflict('a', 'b');
7620 if (send_all_tags && !TAILQ_EMPTY(&tags))
7621 option_conflict('T', 't');
7624 if (argc == 0)
7625 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7626 else if (argc == 1)
7627 remote_name = argv[0];
7628 else
7629 usage_send();
7631 cwd = getcwd(NULL, 0);
7632 if (cwd == NULL) {
7633 error = got_error_from_errno("getcwd");
7634 goto done;
7637 if (repo_path == NULL) {
7638 error = got_worktree_open(&worktree, cwd);
7639 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7640 goto done;
7641 else
7642 error = NULL;
7643 if (worktree) {
7644 repo_path =
7645 strdup(got_worktree_get_repo_path(worktree));
7646 if (repo_path == NULL)
7647 error = got_error_from_errno("strdup");
7648 if (error)
7649 goto done;
7650 } else {
7651 repo_path = strdup(cwd);
7652 if (repo_path == NULL) {
7653 error = got_error_from_errno("strdup");
7654 goto done;
7659 error = got_repo_open(&repo, repo_path, NULL);
7660 if (error)
7661 goto done;
7663 if (worktree) {
7664 worktree_conf = got_worktree_get_gotconfig(worktree);
7665 if (worktree_conf) {
7666 got_gotconfig_get_remotes(&nremotes, &remotes,
7667 worktree_conf);
7668 for (i = 0; i < nremotes; i++) {
7669 if (strcmp(remotes[i].name, remote_name) == 0) {
7670 remote = &remotes[i];
7671 break;
7676 if (remote == NULL) {
7677 repo_conf = got_repo_get_gotconfig(repo);
7678 if (repo_conf) {
7679 got_gotconfig_get_remotes(&nremotes, &remotes,
7680 repo_conf);
7681 for (i = 0; i < nremotes; i++) {
7682 if (strcmp(remotes[i].name, remote_name) == 0) {
7683 remote = &remotes[i];
7684 break;
7689 if (remote == NULL) {
7690 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7691 for (i = 0; i < nremotes; i++) {
7692 if (strcmp(remotes[i].name, remote_name) == 0) {
7693 remote = &remotes[i];
7694 break;
7698 if (remote == NULL) {
7699 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7700 goto done;
7703 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
7704 &repo_name, remote->send_url);
7705 if (error)
7706 goto done;
7708 if (strcmp(proto, "git") == 0) {
7709 #ifndef PROFILE
7710 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7711 "sendfd dns inet unveil", NULL) == -1)
7712 err(1, "pledge");
7713 #endif
7714 } else if (strcmp(proto, "git+ssh") == 0 ||
7715 strcmp(proto, "ssh") == 0) {
7716 #ifndef PROFILE
7717 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7718 "sendfd unveil", NULL) == -1)
7719 err(1, "pledge");
7720 #endif
7721 } else if (strcmp(proto, "http") == 0 ||
7722 strcmp(proto, "git+http") == 0) {
7723 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7724 goto done;
7725 } else {
7726 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7727 goto done;
7730 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
7731 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
7732 error = got_error_from_errno2("unveil",
7733 GOT_FETCH_PATH_SSH);
7734 goto done;
7737 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7738 if (error)
7739 goto done;
7741 if (send_all_branches) {
7742 error = got_ref_list(&all_branches, repo, "refs/heads",
7743 got_ref_cmp_by_name, NULL);
7744 if (error)
7745 goto done;
7746 TAILQ_FOREACH(re, &all_branches, entry) {
7747 const char *branchname = got_ref_get_name(re->ref);
7748 error = got_pathlist_append(&branches,
7749 branchname, NULL);
7750 if (error)
7751 goto done;
7752 nbranches++;
7754 } else if (nbranches == 0) {
7755 for (i = 0; i < remote->nsend_branches; i++) {
7756 got_pathlist_append(&branches,
7757 remote->send_branches[i], NULL);
7761 if (send_all_tags) {
7762 error = got_ref_list(&all_tags, repo, "refs/tags",
7763 got_ref_cmp_by_name, NULL);
7764 if (error)
7765 goto done;
7766 TAILQ_FOREACH(re, &all_tags, entry) {
7767 const char *tagname = got_ref_get_name(re->ref);
7768 error = got_pathlist_append(&tags,
7769 tagname, NULL);
7770 if (error)
7771 goto done;
7772 ntags++;
7777 * To prevent accidents only branches in refs/heads/ can be deleted
7778 * with 'got send -d'.
7779 * Deleting anything else requires local repository access or Git.
7781 TAILQ_FOREACH(pe, &delete_args, entry) {
7782 const char *branchname = pe->path;
7783 char *s;
7784 struct got_pathlist_entry *new;
7785 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7786 s = strdup(branchname);
7787 if (s == NULL) {
7788 error = got_error_from_errno("strdup");
7789 goto done;
7791 } else {
7792 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7793 error = got_error_from_errno("asprintf");
7794 goto done;
7797 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7798 if (error || new == NULL /* duplicate */)
7799 free(s);
7800 if (error)
7801 goto done;
7802 ndelete_branches++;
7805 if (nbranches == 0 && ndelete_branches == 0) {
7806 struct got_reference *head_ref;
7807 if (worktree)
7808 error = got_ref_open(&head_ref, repo,
7809 got_worktree_get_head_ref_name(worktree), 0);
7810 else
7811 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7812 if (error)
7813 goto done;
7814 if (got_ref_is_symbolic(head_ref)) {
7815 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7816 got_ref_close(head_ref);
7817 if (error)
7818 goto done;
7819 } else
7820 ref = head_ref;
7821 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7822 NULL);
7823 if (error)
7824 goto done;
7825 nbranches++;
7828 if (verbosity >= 0)
7829 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7830 port ? ":" : "", port ? port : "");
7832 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7833 server_path, verbosity);
7834 if (error)
7835 goto done;
7837 memset(&spa, 0, sizeof(spa));
7838 spa.last_scaled_packsize[0] = '\0';
7839 spa.last_p_deltify = -1;
7840 spa.last_p_written = -1;
7841 spa.verbosity = verbosity;
7842 spa.delete_branches = &delete_branches;
7843 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7844 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7845 check_cancelled, NULL);
7846 if (spa.printed_something)
7847 putchar('\n');
7848 if (error)
7849 goto done;
7850 if (!spa.sent_something && verbosity >= 0)
7851 printf("Already up-to-date\n");
7852 done:
7853 if (sendpid > 0) {
7854 if (kill(sendpid, SIGTERM) == -1)
7855 error = got_error_from_errno("kill");
7856 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7857 error = got_error_from_errno("waitpid");
7859 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7860 error = got_error_from_errno("close");
7861 if (repo) {
7862 const struct got_error *close_err = got_repo_close(repo);
7863 if (error == NULL)
7864 error = close_err;
7866 if (worktree)
7867 got_worktree_close(worktree);
7868 if (ref)
7869 got_ref_close(ref);
7870 got_pathlist_free(&branches);
7871 got_pathlist_free(&tags);
7872 got_ref_list_free(&all_branches);
7873 got_ref_list_free(&all_tags);
7874 got_pathlist_free(&delete_args);
7875 TAILQ_FOREACH(pe, &delete_branches, entry)
7876 free((char *)pe->path);
7877 got_pathlist_free(&delete_branches);
7878 free(cwd);
7879 free(repo_path);
7880 free(proto);
7881 free(host);
7882 free(port);
7883 free(server_path);
7884 free(repo_name);
7885 return error;
7888 __dead static void
7889 usage_cherrypick(void)
7891 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7892 exit(1);
7895 static const struct got_error *
7896 cmd_cherrypick(int argc, char *argv[])
7898 const struct got_error *error = NULL;
7899 struct got_worktree *worktree = NULL;
7900 struct got_repository *repo = NULL;
7901 char *cwd = NULL, *commit_id_str = NULL;
7902 struct got_object_id *commit_id = NULL;
7903 struct got_commit_object *commit = NULL;
7904 struct got_object_qid *pid;
7905 struct got_reference *head_ref = NULL;
7906 int ch;
7907 struct got_update_progress_arg upa;
7909 while ((ch = getopt(argc, argv, "")) != -1) {
7910 switch (ch) {
7911 default:
7912 usage_cherrypick();
7913 /* NOTREACHED */
7917 argc -= optind;
7918 argv += optind;
7920 #ifndef PROFILE
7921 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7922 "unveil", NULL) == -1)
7923 err(1, "pledge");
7924 #endif
7925 if (argc != 1)
7926 usage_cherrypick();
7928 cwd = getcwd(NULL, 0);
7929 if (cwd == NULL) {
7930 error = got_error_from_errno("getcwd");
7931 goto done;
7933 error = got_worktree_open(&worktree, cwd);
7934 if (error) {
7935 if (error->code == GOT_ERR_NOT_WORKTREE)
7936 error = wrap_not_worktree_error(error, "cherrypick",
7937 cwd);
7938 goto done;
7941 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7942 NULL);
7943 if (error != NULL)
7944 goto done;
7946 error = apply_unveil(got_repo_get_path(repo), 0,
7947 got_worktree_get_root_path(worktree));
7948 if (error)
7949 goto done;
7951 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7952 GOT_OBJ_TYPE_COMMIT, repo);
7953 if (error != NULL) {
7954 struct got_reference *ref;
7955 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7956 goto done;
7957 error = got_ref_open(&ref, repo, argv[0], 0);
7958 if (error != NULL)
7959 goto done;
7960 error = got_ref_resolve(&commit_id, repo, ref);
7961 got_ref_close(ref);
7962 if (error != NULL)
7963 goto done;
7965 error = got_object_id_str(&commit_id_str, commit_id);
7966 if (error)
7967 goto done;
7969 error = got_ref_open(&head_ref, repo,
7970 got_worktree_get_head_ref_name(worktree), 0);
7971 if (error != NULL)
7972 goto done;
7974 error = check_same_branch(commit_id, head_ref, NULL, repo);
7975 if (error) {
7976 if (error->code != GOT_ERR_ANCESTRY)
7977 goto done;
7978 error = NULL;
7979 } else {
7980 error = got_error(GOT_ERR_SAME_BRANCH);
7981 goto done;
7984 error = got_object_open_as_commit(&commit, repo, commit_id);
7985 if (error)
7986 goto done;
7987 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7988 memset(&upa, 0, sizeof(upa));
7989 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7990 commit_id, repo, update_progress, &upa, check_cancelled,
7991 NULL);
7992 if (error != NULL)
7993 goto done;
7995 if (upa.did_something)
7996 printf("Merged commit %s\n", commit_id_str);
7997 print_update_progress_stats(&upa);
7998 done:
7999 if (commit)
8000 got_object_commit_close(commit);
8001 free(commit_id_str);
8002 if (head_ref)
8003 got_ref_close(head_ref);
8004 if (worktree)
8005 got_worktree_close(worktree);
8006 if (repo) {
8007 const struct got_error *close_err = got_repo_close(repo);
8008 if (error == NULL)
8009 error = close_err;
8011 return error;
8014 __dead static void
8015 usage_backout(void)
8017 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8018 exit(1);
8021 static const struct got_error *
8022 cmd_backout(int argc, char *argv[])
8024 const struct got_error *error = NULL;
8025 struct got_worktree *worktree = NULL;
8026 struct got_repository *repo = NULL;
8027 char *cwd = NULL, *commit_id_str = NULL;
8028 struct got_object_id *commit_id = NULL;
8029 struct got_commit_object *commit = NULL;
8030 struct got_object_qid *pid;
8031 struct got_reference *head_ref = NULL;
8032 int ch;
8033 struct got_update_progress_arg upa;
8035 while ((ch = getopt(argc, argv, "")) != -1) {
8036 switch (ch) {
8037 default:
8038 usage_backout();
8039 /* NOTREACHED */
8043 argc -= optind;
8044 argv += optind;
8046 #ifndef PROFILE
8047 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8048 "unveil", NULL) == -1)
8049 err(1, "pledge");
8050 #endif
8051 if (argc != 1)
8052 usage_backout();
8054 cwd = getcwd(NULL, 0);
8055 if (cwd == NULL) {
8056 error = got_error_from_errno("getcwd");
8057 goto done;
8059 error = got_worktree_open(&worktree, cwd);
8060 if (error) {
8061 if (error->code == GOT_ERR_NOT_WORKTREE)
8062 error = wrap_not_worktree_error(error, "backout", cwd);
8063 goto done;
8066 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8067 NULL);
8068 if (error != NULL)
8069 goto done;
8071 error = apply_unveil(got_repo_get_path(repo), 0,
8072 got_worktree_get_root_path(worktree));
8073 if (error)
8074 goto done;
8076 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8077 GOT_OBJ_TYPE_COMMIT, repo);
8078 if (error != NULL) {
8079 struct got_reference *ref;
8080 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8081 goto done;
8082 error = got_ref_open(&ref, repo, argv[0], 0);
8083 if (error != NULL)
8084 goto done;
8085 error = got_ref_resolve(&commit_id, repo, ref);
8086 got_ref_close(ref);
8087 if (error != NULL)
8088 goto done;
8090 error = got_object_id_str(&commit_id_str, commit_id);
8091 if (error)
8092 goto done;
8094 error = got_ref_open(&head_ref, repo,
8095 got_worktree_get_head_ref_name(worktree), 0);
8096 if (error != NULL)
8097 goto done;
8099 error = check_same_branch(commit_id, head_ref, NULL, repo);
8100 if (error)
8101 goto done;
8103 error = got_object_open_as_commit(&commit, repo, commit_id);
8104 if (error)
8105 goto done;
8106 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8107 if (pid == NULL) {
8108 error = got_error(GOT_ERR_ROOT_COMMIT);
8109 goto done;
8112 memset(&upa, 0, sizeof(upa));
8113 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8114 update_progress, &upa, check_cancelled, NULL);
8115 if (error != NULL)
8116 goto done;
8118 if (upa.did_something)
8119 printf("Backed out commit %s\n", commit_id_str);
8120 print_update_progress_stats(&upa);
8121 done:
8122 if (commit)
8123 got_object_commit_close(commit);
8124 free(commit_id_str);
8125 if (head_ref)
8126 got_ref_close(head_ref);
8127 if (worktree)
8128 got_worktree_close(worktree);
8129 if (repo) {
8130 const struct got_error *close_err = got_repo_close(repo);
8131 if (error == NULL)
8132 error = close_err;
8134 return error;
8137 __dead static void
8138 usage_rebase(void)
8140 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8141 getprogname());
8142 exit(1);
8145 void
8146 trim_logmsg(char *logmsg, int limit)
8148 char *nl;
8149 size_t len;
8151 len = strlen(logmsg);
8152 if (len > limit)
8153 len = limit;
8154 logmsg[len] = '\0';
8155 nl = strchr(logmsg, '\n');
8156 if (nl)
8157 *nl = '\0';
8160 static const struct got_error *
8161 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8163 const struct got_error *err;
8164 char *logmsg0 = NULL;
8165 const char *s;
8167 err = got_object_commit_get_logmsg(&logmsg0, commit);
8168 if (err)
8169 return err;
8171 s = logmsg0;
8172 while (isspace((unsigned char)s[0]))
8173 s++;
8175 *logmsg = strdup(s);
8176 if (*logmsg == NULL) {
8177 err = got_error_from_errno("strdup");
8178 goto done;
8181 trim_logmsg(*logmsg, limit);
8182 done:
8183 free(logmsg0);
8184 return err;
8187 static const struct got_error *
8188 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8190 const struct got_error *err;
8191 struct got_commit_object *commit = NULL;
8192 char *id_str = NULL, *logmsg = NULL;
8194 err = got_object_open_as_commit(&commit, repo, id);
8195 if (err)
8196 return err;
8198 err = got_object_id_str(&id_str, id);
8199 if (err)
8200 goto done;
8202 id_str[12] = '\0';
8204 err = get_short_logmsg(&logmsg, 42, commit);
8205 if (err)
8206 goto done;
8208 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8209 done:
8210 free(id_str);
8211 got_object_commit_close(commit);
8212 free(logmsg);
8213 return err;
8216 static const struct got_error *
8217 show_rebase_progress(struct got_commit_object *commit,
8218 struct got_object_id *old_id, struct got_object_id *new_id)
8220 const struct got_error *err;
8221 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8223 err = got_object_id_str(&old_id_str, old_id);
8224 if (err)
8225 goto done;
8227 if (new_id) {
8228 err = got_object_id_str(&new_id_str, new_id);
8229 if (err)
8230 goto done;
8233 old_id_str[12] = '\0';
8234 if (new_id_str)
8235 new_id_str[12] = '\0';
8237 err = get_short_logmsg(&logmsg, 42, commit);
8238 if (err)
8239 goto done;
8241 printf("%s -> %s: %s\n", old_id_str,
8242 new_id_str ? new_id_str : "no-op change", logmsg);
8243 done:
8244 free(old_id_str);
8245 free(new_id_str);
8246 free(logmsg);
8247 return err;
8250 static const struct got_error *
8251 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8252 struct got_reference *branch, struct got_reference *new_base_branch,
8253 struct got_reference *tmp_branch, struct got_repository *repo,
8254 int create_backup)
8256 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8257 return got_worktree_rebase_complete(worktree, fileindex,
8258 new_base_branch, tmp_branch, branch, repo, create_backup);
8261 static const struct got_error *
8262 rebase_commit(struct got_pathlist_head *merged_paths,
8263 struct got_worktree *worktree, struct got_fileindex *fileindex,
8264 struct got_reference *tmp_branch,
8265 struct got_object_id *commit_id, struct got_repository *repo)
8267 const struct got_error *error;
8268 struct got_commit_object *commit;
8269 struct got_object_id *new_commit_id;
8271 error = got_object_open_as_commit(&commit, repo, commit_id);
8272 if (error)
8273 return error;
8275 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8276 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8277 if (error) {
8278 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8279 goto done;
8280 error = show_rebase_progress(commit, commit_id, NULL);
8281 } else {
8282 error = show_rebase_progress(commit, commit_id, new_commit_id);
8283 free(new_commit_id);
8285 done:
8286 got_object_commit_close(commit);
8287 return error;
8290 struct check_path_prefix_arg {
8291 const char *path_prefix;
8292 size_t len;
8293 int errcode;
8296 static const struct got_error *
8297 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8298 struct got_blob_object *blob2, struct got_object_id *id1,
8299 struct got_object_id *id2, const char *path1, const char *path2,
8300 mode_t mode1, mode_t mode2, struct got_repository *repo)
8302 struct check_path_prefix_arg *a = arg;
8304 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8305 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8306 return got_error(a->errcode);
8308 return NULL;
8311 static const struct got_error *
8312 check_path_prefix(struct got_object_id *parent_id,
8313 struct got_object_id *commit_id, const char *path_prefix,
8314 int errcode, struct got_repository *repo)
8316 const struct got_error *err;
8317 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8318 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8319 struct check_path_prefix_arg cpp_arg;
8321 if (got_path_is_root_dir(path_prefix))
8322 return NULL;
8324 err = got_object_open_as_commit(&commit, repo, commit_id);
8325 if (err)
8326 goto done;
8328 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8329 if (err)
8330 goto done;
8332 err = got_object_open_as_tree(&tree1, repo,
8333 got_object_commit_get_tree_id(parent_commit));
8334 if (err)
8335 goto done;
8337 err = got_object_open_as_tree(&tree2, repo,
8338 got_object_commit_get_tree_id(commit));
8339 if (err)
8340 goto done;
8342 cpp_arg.path_prefix = path_prefix;
8343 while (cpp_arg.path_prefix[0] == '/')
8344 cpp_arg.path_prefix++;
8345 cpp_arg.len = strlen(cpp_arg.path_prefix);
8346 cpp_arg.errcode = errcode;
8347 err = got_diff_tree(tree1, tree2, "", "", repo,
8348 check_path_prefix_in_diff, &cpp_arg, 0);
8349 done:
8350 if (tree1)
8351 got_object_tree_close(tree1);
8352 if (tree2)
8353 got_object_tree_close(tree2);
8354 if (commit)
8355 got_object_commit_close(commit);
8356 if (parent_commit)
8357 got_object_commit_close(parent_commit);
8358 return err;
8361 static const struct got_error *
8362 collect_commits(struct got_object_id_queue *commits,
8363 struct got_object_id *initial_commit_id,
8364 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8365 const char *path_prefix, int path_prefix_errcode,
8366 struct got_repository *repo)
8368 const struct got_error *err = NULL;
8369 struct got_commit_graph *graph = NULL;
8370 struct got_object_id *parent_id = NULL;
8371 struct got_object_qid *qid;
8372 struct got_object_id *commit_id = initial_commit_id;
8374 err = got_commit_graph_open(&graph, "/", 1);
8375 if (err)
8376 return err;
8378 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8379 check_cancelled, NULL);
8380 if (err)
8381 goto done;
8382 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8383 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8384 check_cancelled, NULL);
8385 if (err) {
8386 if (err->code == GOT_ERR_ITER_COMPLETED) {
8387 err = got_error_msg(GOT_ERR_ANCESTRY,
8388 "ran out of commits to rebase before "
8389 "youngest common ancestor commit has "
8390 "been reached?!?");
8392 goto done;
8393 } else {
8394 err = check_path_prefix(parent_id, commit_id,
8395 path_prefix, path_prefix_errcode, repo);
8396 if (err)
8397 goto done;
8399 err = got_object_qid_alloc(&qid, commit_id);
8400 if (err)
8401 goto done;
8402 STAILQ_INSERT_HEAD(commits, qid, entry);
8403 commit_id = parent_id;
8406 done:
8407 got_commit_graph_close(graph);
8408 return err;
8411 static const struct got_error *
8412 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8414 const struct got_error *err = NULL;
8415 time_t committer_time;
8416 struct tm tm;
8417 char datebuf[11]; /* YYYY-MM-DD + NUL */
8418 char *author0 = NULL, *author, *smallerthan;
8419 char *logmsg0 = NULL, *logmsg, *newline;
8421 committer_time = got_object_commit_get_committer_time(commit);
8422 if (gmtime_r(&committer_time, &tm) == NULL)
8423 return got_error_from_errno("gmtime_r");
8424 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8425 return got_error(GOT_ERR_NO_SPACE);
8427 author0 = strdup(got_object_commit_get_author(commit));
8428 if (author0 == NULL)
8429 return got_error_from_errno("strdup");
8430 author = author0;
8431 smallerthan = strchr(author, '<');
8432 if (smallerthan && smallerthan[1] != '\0')
8433 author = smallerthan + 1;
8434 author[strcspn(author, "@>")] = '\0';
8436 err = got_object_commit_get_logmsg(&logmsg0, commit);
8437 if (err)
8438 goto done;
8439 logmsg = logmsg0;
8440 while (*logmsg == '\n')
8441 logmsg++;
8442 newline = strchr(logmsg, '\n');
8443 if (newline)
8444 *newline = '\0';
8446 if (asprintf(brief_str, "%s %s %s",
8447 datebuf, author, logmsg) == -1)
8448 err = got_error_from_errno("asprintf");
8449 done:
8450 free(author0);
8451 free(logmsg0);
8452 return err;
8455 static const struct got_error *
8456 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8457 struct got_repository *repo)
8459 const struct got_error *err;
8460 char *id_str;
8462 err = got_object_id_str(&id_str, id);
8463 if (err)
8464 return err;
8466 err = got_ref_delete(ref, repo);
8467 if (err)
8468 goto done;
8470 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8471 done:
8472 free(id_str);
8473 return err;
8476 static const struct got_error *
8477 print_backup_ref(const char *branch_name, const char *new_id_str,
8478 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8479 struct got_reflist_object_id_map *refs_idmap,
8480 struct got_repository *repo)
8482 const struct got_error *err = NULL;
8483 struct got_reflist_head *refs;
8484 char *refs_str = NULL;
8485 struct got_object_id *new_commit_id = NULL;
8486 struct got_commit_object *new_commit = NULL;
8487 char *new_commit_brief_str = NULL;
8488 struct got_object_id *yca_id = NULL;
8489 struct got_commit_object *yca_commit = NULL;
8490 char *yca_id_str = NULL, *yca_brief_str = NULL;
8491 char *custom_refs_str;
8493 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8494 return got_error_from_errno("asprintf");
8496 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8497 0, 0, refs_idmap, custom_refs_str);
8498 if (err)
8499 goto done;
8501 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8502 if (err)
8503 goto done;
8505 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8506 if (refs) {
8507 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8508 if (err)
8509 goto done;
8512 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8513 if (err)
8514 goto done;
8516 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8517 if (err)
8518 goto done;
8520 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8521 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8522 if (err)
8523 goto done;
8525 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8526 refs_str ? " (" : "", refs_str ? refs_str : "",
8527 refs_str ? ")" : "", new_commit_brief_str);
8528 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8529 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8530 free(refs_str);
8531 refs_str = NULL;
8533 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8534 if (err)
8535 goto done;
8537 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8538 if (err)
8539 goto done;
8541 err = got_object_id_str(&yca_id_str, yca_id);
8542 if (err)
8543 goto done;
8545 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8546 if (refs) {
8547 err = build_refs_str(&refs_str, refs, yca_id, repo);
8548 if (err)
8549 goto done;
8551 printf("history forked at %s%s%s%s\n %s\n",
8552 yca_id_str,
8553 refs_str ? " (" : "", refs_str ? refs_str : "",
8554 refs_str ? ")" : "", yca_brief_str);
8556 done:
8557 free(custom_refs_str);
8558 free(new_commit_id);
8559 free(refs_str);
8560 free(yca_id);
8561 free(yca_id_str);
8562 free(yca_brief_str);
8563 if (new_commit)
8564 got_object_commit_close(new_commit);
8565 if (yca_commit)
8566 got_object_commit_close(yca_commit);
8568 return NULL;
8571 static const struct got_error *
8572 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8573 int delete, struct got_repository *repo)
8575 const struct got_error *err;
8576 struct got_reflist_head refs, backup_refs;
8577 struct got_reflist_entry *re;
8578 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8579 struct got_object_id *old_commit_id = NULL;
8580 char *branch_name = NULL;
8581 struct got_commit_object *old_commit = NULL;
8582 struct got_reflist_object_id_map *refs_idmap = NULL;
8583 int wanted_branch_found = 0;
8585 TAILQ_INIT(&refs);
8586 TAILQ_INIT(&backup_refs);
8588 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8589 if (err)
8590 return err;
8592 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8593 if (err)
8594 goto done;
8596 if (wanted_branch_name) {
8597 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8598 wanted_branch_name += 11;
8601 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8602 got_ref_cmp_by_commit_timestamp_descending, repo);
8603 if (err)
8604 goto done;
8606 TAILQ_FOREACH(re, &backup_refs, entry) {
8607 const char *refname = got_ref_get_name(re->ref);
8608 char *slash;
8610 err = check_cancelled(NULL);
8611 if (err)
8612 break;
8614 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8615 if (err)
8616 break;
8618 err = got_object_open_as_commit(&old_commit, repo,
8619 old_commit_id);
8620 if (err)
8621 break;
8623 if (strncmp(backup_ref_prefix, refname,
8624 backup_ref_prefix_len) == 0)
8625 refname += backup_ref_prefix_len;
8627 while (refname[0] == '/')
8628 refname++;
8630 branch_name = strdup(refname);
8631 if (branch_name == NULL) {
8632 err = got_error_from_errno("strdup");
8633 break;
8635 slash = strrchr(branch_name, '/');
8636 if (slash) {
8637 *slash = '\0';
8638 refname += strlen(branch_name) + 1;
8641 if (wanted_branch_name == NULL ||
8642 strcmp(wanted_branch_name, branch_name) == 0) {
8643 wanted_branch_found = 1;
8644 if (delete) {
8645 err = delete_backup_ref(re->ref,
8646 old_commit_id, repo);
8647 } else {
8648 err = print_backup_ref(branch_name, refname,
8649 old_commit_id, old_commit, refs_idmap,
8650 repo);
8652 if (err)
8653 break;
8656 free(old_commit_id);
8657 old_commit_id = NULL;
8658 free(branch_name);
8659 branch_name = NULL;
8660 got_object_commit_close(old_commit);
8661 old_commit = NULL;
8664 if (wanted_branch_name && !wanted_branch_found) {
8665 err = got_error_fmt(GOT_ERR_NOT_REF,
8666 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8668 done:
8669 if (refs_idmap)
8670 got_reflist_object_id_map_free(refs_idmap);
8671 got_ref_list_free(&refs);
8672 got_ref_list_free(&backup_refs);
8673 free(old_commit_id);
8674 free(branch_name);
8675 if (old_commit)
8676 got_object_commit_close(old_commit);
8677 return err;
8680 static const struct got_error *
8681 cmd_rebase(int argc, char *argv[])
8683 const struct got_error *error = NULL;
8684 struct got_worktree *worktree = NULL;
8685 struct got_repository *repo = NULL;
8686 struct got_fileindex *fileindex = NULL;
8687 char *cwd = NULL;
8688 struct got_reference *branch = NULL;
8689 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8690 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8691 struct got_object_id *resume_commit_id = NULL;
8692 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8693 struct got_commit_object *commit = NULL;
8694 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8695 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8696 int delete_backups = 0;
8697 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8698 struct got_object_id_queue commits;
8699 struct got_pathlist_head merged_paths;
8700 const struct got_object_id_queue *parent_ids;
8701 struct got_object_qid *qid, *pid;
8703 STAILQ_INIT(&commits);
8704 TAILQ_INIT(&merged_paths);
8706 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8707 switch (ch) {
8708 case 'a':
8709 abort_rebase = 1;
8710 break;
8711 case 'c':
8712 continue_rebase = 1;
8713 break;
8714 case 'l':
8715 list_backups = 1;
8716 break;
8717 case 'X':
8718 delete_backups = 1;
8719 break;
8720 default:
8721 usage_rebase();
8722 /* NOTREACHED */
8726 argc -= optind;
8727 argv += optind;
8729 #ifndef PROFILE
8730 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8731 "unveil", NULL) == -1)
8732 err(1, "pledge");
8733 #endif
8734 if (list_backups) {
8735 if (abort_rebase)
8736 option_conflict('l', 'a');
8737 if (continue_rebase)
8738 option_conflict('l', 'c');
8739 if (delete_backups)
8740 option_conflict('l', 'X');
8741 if (argc != 0 && argc != 1)
8742 usage_rebase();
8743 } else if (delete_backups) {
8744 if (abort_rebase)
8745 option_conflict('X', 'a');
8746 if (continue_rebase)
8747 option_conflict('X', 'c');
8748 if (list_backups)
8749 option_conflict('l', 'X');
8750 if (argc != 0 && argc != 1)
8751 usage_rebase();
8752 } else {
8753 if (abort_rebase && continue_rebase)
8754 usage_rebase();
8755 else if (abort_rebase || continue_rebase) {
8756 if (argc != 0)
8757 usage_rebase();
8758 } else if (argc != 1)
8759 usage_rebase();
8762 cwd = getcwd(NULL, 0);
8763 if (cwd == NULL) {
8764 error = got_error_from_errno("getcwd");
8765 goto done;
8767 error = got_worktree_open(&worktree, cwd);
8768 if (error) {
8769 if (list_backups || delete_backups) {
8770 if (error->code != GOT_ERR_NOT_WORKTREE)
8771 goto done;
8772 } else {
8773 if (error->code == GOT_ERR_NOT_WORKTREE)
8774 error = wrap_not_worktree_error(error,
8775 "rebase", cwd);
8776 goto done;
8780 error = got_repo_open(&repo,
8781 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8782 if (error != NULL)
8783 goto done;
8785 error = apply_unveil(got_repo_get_path(repo), 0,
8786 worktree ? got_worktree_get_root_path(worktree) : NULL);
8787 if (error)
8788 goto done;
8790 if (list_backups || delete_backups) {
8791 error = process_backup_refs(
8792 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8793 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8794 goto done; /* nothing else to do */
8797 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8798 worktree);
8799 if (error)
8800 goto done;
8801 if (histedit_in_progress) {
8802 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8803 goto done;
8806 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8807 if (error)
8808 goto done;
8810 if (abort_rebase) {
8811 struct got_update_progress_arg upa;
8812 if (!rebase_in_progress) {
8813 error = got_error(GOT_ERR_NOT_REBASING);
8814 goto done;
8816 error = got_worktree_rebase_continue(&resume_commit_id,
8817 &new_base_branch, &tmp_branch, &branch, &fileindex,
8818 worktree, repo);
8819 if (error)
8820 goto done;
8821 printf("Switching work tree to %s\n",
8822 got_ref_get_symref_target(new_base_branch));
8823 memset(&upa, 0, sizeof(upa));
8824 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8825 new_base_branch, update_progress, &upa);
8826 if (error)
8827 goto done;
8828 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8829 print_update_progress_stats(&upa);
8830 goto done; /* nothing else to do */
8833 if (continue_rebase) {
8834 if (!rebase_in_progress) {
8835 error = got_error(GOT_ERR_NOT_REBASING);
8836 goto done;
8838 error = got_worktree_rebase_continue(&resume_commit_id,
8839 &new_base_branch, &tmp_branch, &branch, &fileindex,
8840 worktree, repo);
8841 if (error)
8842 goto done;
8844 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8845 resume_commit_id, repo);
8846 if (error)
8847 goto done;
8849 yca_id = got_object_id_dup(resume_commit_id);
8850 if (yca_id == NULL) {
8851 error = got_error_from_errno("got_object_id_dup");
8852 goto done;
8854 } else {
8855 error = got_ref_open(&branch, repo, argv[0], 0);
8856 if (error != NULL)
8857 goto done;
8860 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8861 if (error)
8862 goto done;
8864 if (!continue_rebase) {
8865 struct got_object_id *base_commit_id;
8867 base_commit_id = got_worktree_get_base_commit_id(worktree);
8868 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8869 base_commit_id, branch_head_commit_id, repo,
8870 check_cancelled, NULL);
8871 if (error)
8872 goto done;
8873 if (yca_id == NULL) {
8874 error = got_error_msg(GOT_ERR_ANCESTRY,
8875 "specified branch shares no common ancestry "
8876 "with work tree's branch");
8877 goto done;
8880 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8881 if (error) {
8882 if (error->code != GOT_ERR_ANCESTRY)
8883 goto done;
8884 error = NULL;
8885 } else {
8886 static char msg[128];
8887 snprintf(msg, sizeof(msg),
8888 "%s is already based on %s",
8889 got_ref_get_name(branch),
8890 got_worktree_get_head_ref_name(worktree));
8891 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8892 goto done;
8894 error = got_worktree_rebase_prepare(&new_base_branch,
8895 &tmp_branch, &fileindex, worktree, branch, repo);
8896 if (error)
8897 goto done;
8900 commit_id = branch_head_commit_id;
8901 error = got_object_open_as_commit(&commit, repo, commit_id);
8902 if (error)
8903 goto done;
8905 parent_ids = got_object_commit_get_parent_ids(commit);
8906 pid = STAILQ_FIRST(parent_ids);
8907 if (pid == NULL) {
8908 if (!continue_rebase) {
8909 struct got_update_progress_arg upa;
8910 memset(&upa, 0, sizeof(upa));
8911 error = got_worktree_rebase_abort(worktree, fileindex,
8912 repo, new_base_branch, update_progress, &upa);
8913 if (error)
8914 goto done;
8915 printf("Rebase of %s aborted\n",
8916 got_ref_get_name(branch));
8917 print_update_progress_stats(&upa);
8920 error = got_error(GOT_ERR_EMPTY_REBASE);
8921 goto done;
8923 error = collect_commits(&commits, commit_id, pid->id,
8924 yca_id, got_worktree_get_path_prefix(worktree),
8925 GOT_ERR_REBASE_PATH, repo);
8926 got_object_commit_close(commit);
8927 commit = NULL;
8928 if (error)
8929 goto done;
8931 if (STAILQ_EMPTY(&commits)) {
8932 if (continue_rebase) {
8933 error = rebase_complete(worktree, fileindex,
8934 branch, new_base_branch, tmp_branch, repo,
8935 create_backup);
8936 goto done;
8937 } else {
8938 /* Fast-forward the reference of the branch. */
8939 struct got_object_id *new_head_commit_id;
8940 char *id_str;
8941 error = got_ref_resolve(&new_head_commit_id, repo,
8942 new_base_branch);
8943 if (error)
8944 goto done;
8945 error = got_object_id_str(&id_str, new_head_commit_id);
8946 printf("Forwarding %s to commit %s\n",
8947 got_ref_get_name(branch), id_str);
8948 free(id_str);
8949 error = got_ref_change_ref(branch,
8950 new_head_commit_id);
8951 if (error)
8952 goto done;
8953 /* No backup needed since objects did not change. */
8954 create_backup = 0;
8958 pid = NULL;
8959 STAILQ_FOREACH(qid, &commits, entry) {
8960 struct got_update_progress_arg upa;
8962 commit_id = qid->id;
8963 parent_id = pid ? pid->id : yca_id;
8964 pid = qid;
8966 memset(&upa, 0, sizeof(upa));
8967 error = got_worktree_rebase_merge_files(&merged_paths,
8968 worktree, fileindex, parent_id, commit_id, repo,
8969 update_progress, &upa, check_cancelled, NULL);
8970 if (error)
8971 goto done;
8973 print_update_progress_stats(&upa);
8974 if (upa.conflicts > 0)
8975 rebase_status = GOT_STATUS_CONFLICT;
8977 if (rebase_status == GOT_STATUS_CONFLICT) {
8978 error = show_rebase_merge_conflict(qid->id, repo);
8979 if (error)
8980 goto done;
8981 got_worktree_rebase_pathlist_free(&merged_paths);
8982 break;
8985 error = rebase_commit(&merged_paths, worktree, fileindex,
8986 tmp_branch, commit_id, repo);
8987 got_worktree_rebase_pathlist_free(&merged_paths);
8988 if (error)
8989 goto done;
8992 if (rebase_status == GOT_STATUS_CONFLICT) {
8993 error = got_worktree_rebase_postpone(worktree, fileindex);
8994 if (error)
8995 goto done;
8996 error = got_error_msg(GOT_ERR_CONFLICTS,
8997 "conflicts must be resolved before rebasing can continue");
8998 } else
8999 error = rebase_complete(worktree, fileindex, branch,
9000 new_base_branch, tmp_branch, repo, create_backup);
9001 done:
9002 got_object_id_queue_free(&commits);
9003 free(branch_head_commit_id);
9004 free(resume_commit_id);
9005 free(yca_id);
9006 if (commit)
9007 got_object_commit_close(commit);
9008 if (branch)
9009 got_ref_close(branch);
9010 if (new_base_branch)
9011 got_ref_close(new_base_branch);
9012 if (tmp_branch)
9013 got_ref_close(tmp_branch);
9014 if (worktree)
9015 got_worktree_close(worktree);
9016 if (repo) {
9017 const struct got_error *close_err = got_repo_close(repo);
9018 if (error == NULL)
9019 error = close_err;
9021 return error;
9024 __dead static void
9025 usage_histedit(void)
9027 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
9028 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9029 getprogname());
9030 exit(1);
9033 #define GOT_HISTEDIT_PICK 'p'
9034 #define GOT_HISTEDIT_EDIT 'e'
9035 #define GOT_HISTEDIT_FOLD 'f'
9036 #define GOT_HISTEDIT_DROP 'd'
9037 #define GOT_HISTEDIT_MESG 'm'
9039 static struct got_histedit_cmd {
9040 unsigned char code;
9041 const char *name;
9042 const char *desc;
9043 } got_histedit_cmds[] = {
9044 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9045 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9046 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9047 "be used" },
9048 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9049 { GOT_HISTEDIT_MESG, "mesg",
9050 "single-line log message for commit above (open editor if empty)" },
9053 struct got_histedit_list_entry {
9054 TAILQ_ENTRY(got_histedit_list_entry) entry;
9055 struct got_object_id *commit_id;
9056 const struct got_histedit_cmd *cmd;
9057 char *logmsg;
9059 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9061 static const struct got_error *
9062 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9063 FILE *f, struct got_repository *repo)
9065 const struct got_error *err = NULL;
9066 char *logmsg = NULL, *id_str = NULL;
9067 struct got_commit_object *commit = NULL;
9068 int n;
9070 err = got_object_open_as_commit(&commit, repo, commit_id);
9071 if (err)
9072 goto done;
9074 err = get_short_logmsg(&logmsg, 34, commit);
9075 if (err)
9076 goto done;
9078 err = got_object_id_str(&id_str, commit_id);
9079 if (err)
9080 goto done;
9082 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9083 if (n < 0)
9084 err = got_ferror(f, GOT_ERR_IO);
9085 done:
9086 if (commit)
9087 got_object_commit_close(commit);
9088 free(id_str);
9089 free(logmsg);
9090 return err;
9093 static const struct got_error *
9094 histedit_write_commit_list(struct got_object_id_queue *commits,
9095 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9097 const struct got_error *err = NULL;
9098 struct got_object_qid *qid;
9099 const char *histedit_cmd = NULL;
9101 if (STAILQ_EMPTY(commits))
9102 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9104 STAILQ_FOREACH(qid, commits, entry) {
9105 histedit_cmd = got_histedit_cmds[0].name;
9106 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9107 histedit_cmd = "fold";
9108 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9109 if (err)
9110 break;
9111 if (edit_logmsg_only) {
9112 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9113 if (n < 0) {
9114 err = got_ferror(f, GOT_ERR_IO);
9115 break;
9120 return err;
9123 static const struct got_error *
9124 write_cmd_list(FILE *f, const char *branch_name,
9125 struct got_object_id_queue *commits)
9127 const struct got_error *err = NULL;
9128 size_t i;
9129 int n;
9130 char *id_str;
9131 struct got_object_qid *qid;
9133 qid = STAILQ_FIRST(commits);
9134 err = got_object_id_str(&id_str, qid->id);
9135 if (err)
9136 return err;
9138 n = fprintf(f,
9139 "# Editing the history of branch '%s' starting at\n"
9140 "# commit %s\n"
9141 "# Commits will be processed in order from top to "
9142 "bottom of this file.\n", branch_name, id_str);
9143 if (n < 0) {
9144 err = got_ferror(f, GOT_ERR_IO);
9145 goto done;
9148 n = fprintf(f, "# Available histedit commands:\n");
9149 if (n < 0) {
9150 err = got_ferror(f, GOT_ERR_IO);
9151 goto done;
9154 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9155 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9156 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9157 cmd->desc);
9158 if (n < 0) {
9159 err = got_ferror(f, GOT_ERR_IO);
9160 break;
9163 done:
9164 free(id_str);
9165 return err;
9168 static const struct got_error *
9169 histedit_syntax_error(int lineno)
9171 static char msg[42];
9172 int ret;
9174 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9175 lineno);
9176 if (ret == -1 || ret >= sizeof(msg))
9177 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9179 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9182 static const struct got_error *
9183 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9184 char *logmsg, struct got_repository *repo)
9186 const struct got_error *err;
9187 struct got_commit_object *folded_commit = NULL;
9188 char *id_str, *folded_logmsg = NULL;
9190 err = got_object_id_str(&id_str, hle->commit_id);
9191 if (err)
9192 return err;
9194 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9195 if (err)
9196 goto done;
9198 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9199 if (err)
9200 goto done;
9201 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9202 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9203 folded_logmsg) == -1) {
9204 err = got_error_from_errno("asprintf");
9206 done:
9207 if (folded_commit)
9208 got_object_commit_close(folded_commit);
9209 free(id_str);
9210 free(folded_logmsg);
9211 return err;
9214 static struct got_histedit_list_entry *
9215 get_folded_commits(struct got_histedit_list_entry *hle)
9217 struct got_histedit_list_entry *prev, *folded = NULL;
9219 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9220 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9221 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9222 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9223 folded = prev;
9224 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9227 return folded;
9230 static const struct got_error *
9231 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9232 struct got_repository *repo)
9234 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9235 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9236 const struct got_error *err = NULL;
9237 struct got_commit_object *commit = NULL;
9238 int logmsg_len;
9239 int fd;
9240 struct got_histedit_list_entry *folded = NULL;
9242 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9243 if (err)
9244 return err;
9246 folded = get_folded_commits(hle);
9247 if (folded) {
9248 while (folded != hle) {
9249 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9250 folded = TAILQ_NEXT(folded, entry);
9251 continue;
9253 err = append_folded_commit_msg(&new_msg, folded,
9254 logmsg, repo);
9255 if (err)
9256 goto done;
9257 free(logmsg);
9258 logmsg = new_msg;
9259 folded = TAILQ_NEXT(folded, entry);
9263 err = got_object_id_str(&id_str, hle->commit_id);
9264 if (err)
9265 goto done;
9266 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9267 if (err)
9268 goto done;
9269 logmsg_len = asprintf(&new_msg,
9270 "%s\n# original log message of commit %s: %s",
9271 logmsg ? logmsg : "", id_str, orig_logmsg);
9272 if (logmsg_len == -1) {
9273 err = got_error_from_errno("asprintf");
9274 goto done;
9276 free(logmsg);
9277 logmsg = new_msg;
9279 err = got_object_id_str(&id_str, hle->commit_id);
9280 if (err)
9281 goto done;
9283 err = got_opentemp_named_fd(&logmsg_path, &fd,
9284 GOT_TMPDIR_STR "/got-logmsg");
9285 if (err)
9286 goto done;
9288 write(fd, logmsg, logmsg_len);
9289 close(fd);
9291 err = get_editor(&editor);
9292 if (err)
9293 goto done;
9295 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9296 logmsg_len, 0);
9297 if (err) {
9298 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9299 goto done;
9300 err = NULL;
9301 hle->logmsg = strdup(new_msg);
9302 if (hle->logmsg == NULL)
9303 err = got_error_from_errno("strdup");
9305 done:
9306 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9307 err = got_error_from_errno2("unlink", logmsg_path);
9308 free(logmsg_path);
9309 free(logmsg);
9310 free(orig_logmsg);
9311 free(editor);
9312 if (commit)
9313 got_object_commit_close(commit);
9314 return err;
9317 static const struct got_error *
9318 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9319 FILE *f, struct got_repository *repo)
9321 const struct got_error *err = NULL;
9322 char *line = NULL, *p, *end;
9323 size_t i, size;
9324 ssize_t len;
9325 int lineno = 0;
9326 const struct got_histedit_cmd *cmd;
9327 struct got_object_id *commit_id = NULL;
9328 struct got_histedit_list_entry *hle = NULL;
9330 for (;;) {
9331 len = getline(&line, &size, f);
9332 if (len == -1) {
9333 const struct got_error *getline_err;
9334 if (feof(f))
9335 break;
9336 getline_err = got_error_from_errno("getline");
9337 err = got_ferror(f, getline_err->code);
9338 break;
9340 lineno++;
9341 p = line;
9342 while (isspace((unsigned char)p[0]))
9343 p++;
9344 if (p[0] == '#' || p[0] == '\0') {
9345 free(line);
9346 line = NULL;
9347 continue;
9349 cmd = NULL;
9350 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9351 cmd = &got_histedit_cmds[i];
9352 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9353 isspace((unsigned char)p[strlen(cmd->name)])) {
9354 p += strlen(cmd->name);
9355 break;
9357 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9358 p++;
9359 break;
9362 if (i == nitems(got_histedit_cmds)) {
9363 err = histedit_syntax_error(lineno);
9364 break;
9366 while (isspace((unsigned char)p[0]))
9367 p++;
9368 if (cmd->code == GOT_HISTEDIT_MESG) {
9369 if (hle == NULL || hle->logmsg != NULL) {
9370 err = got_error(GOT_ERR_HISTEDIT_CMD);
9371 break;
9373 if (p[0] == '\0') {
9374 err = histedit_edit_logmsg(hle, repo);
9375 if (err)
9376 break;
9377 } else {
9378 hle->logmsg = strdup(p);
9379 if (hle->logmsg == NULL) {
9380 err = got_error_from_errno("strdup");
9381 break;
9384 free(line);
9385 line = NULL;
9386 continue;
9387 } else {
9388 end = p;
9389 while (end[0] && !isspace((unsigned char)end[0]))
9390 end++;
9391 *end = '\0';
9393 err = got_object_resolve_id_str(&commit_id, repo, p);
9394 if (err) {
9395 /* override error code */
9396 err = histedit_syntax_error(lineno);
9397 break;
9400 hle = malloc(sizeof(*hle));
9401 if (hle == NULL) {
9402 err = got_error_from_errno("malloc");
9403 break;
9405 hle->cmd = cmd;
9406 hle->commit_id = commit_id;
9407 hle->logmsg = NULL;
9408 commit_id = NULL;
9409 free(line);
9410 line = NULL;
9411 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9414 free(line);
9415 free(commit_id);
9416 return err;
9419 static const struct got_error *
9420 histedit_check_script(struct got_histedit_list *histedit_cmds,
9421 struct got_object_id_queue *commits, struct got_repository *repo)
9423 const struct got_error *err = NULL;
9424 struct got_object_qid *qid;
9425 struct got_histedit_list_entry *hle;
9426 static char msg[92];
9427 char *id_str;
9429 if (TAILQ_EMPTY(histedit_cmds))
9430 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9431 "histedit script contains no commands");
9432 if (STAILQ_EMPTY(commits))
9433 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9435 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9436 struct got_histedit_list_entry *hle2;
9437 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9438 if (hle == hle2)
9439 continue;
9440 if (got_object_id_cmp(hle->commit_id,
9441 hle2->commit_id) != 0)
9442 continue;
9443 err = got_object_id_str(&id_str, hle->commit_id);
9444 if (err)
9445 return err;
9446 snprintf(msg, sizeof(msg), "commit %s is listed "
9447 "more than once in histedit script", id_str);
9448 free(id_str);
9449 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9453 STAILQ_FOREACH(qid, commits, entry) {
9454 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9455 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9456 break;
9458 if (hle == NULL) {
9459 err = got_object_id_str(&id_str, qid->id);
9460 if (err)
9461 return err;
9462 snprintf(msg, sizeof(msg),
9463 "commit %s missing from histedit script", id_str);
9464 free(id_str);
9465 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9469 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9470 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9471 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9472 "last commit in histedit script cannot be folded");
9474 return NULL;
9477 static const struct got_error *
9478 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9479 const char *path, struct got_object_id_queue *commits,
9480 struct got_repository *repo)
9482 const struct got_error *err = NULL;
9483 char *editor;
9484 FILE *f = NULL;
9486 err = get_editor(&editor);
9487 if (err)
9488 return err;
9490 if (spawn_editor(editor, path) == -1) {
9491 err = got_error_from_errno("failed spawning editor");
9492 goto done;
9495 f = fopen(path, "r");
9496 if (f == NULL) {
9497 err = got_error_from_errno("fopen");
9498 goto done;
9500 err = histedit_parse_list(histedit_cmds, f, repo);
9501 if (err)
9502 goto done;
9504 err = histedit_check_script(histedit_cmds, commits, repo);
9505 done:
9506 if (f && fclose(f) == EOF && err == NULL)
9507 err = got_error_from_errno("fclose");
9508 free(editor);
9509 return err;
9512 static const struct got_error *
9513 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9514 struct got_object_id_queue *, const char *, const char *,
9515 struct got_repository *);
9517 static const struct got_error *
9518 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9519 struct got_object_id_queue *commits, const char *branch_name,
9520 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9522 const struct got_error *err;
9523 FILE *f = NULL;
9524 char *path = NULL;
9526 err = got_opentemp_named(&path, &f, "got-histedit");
9527 if (err)
9528 return err;
9530 err = write_cmd_list(f, branch_name, commits);
9531 if (err)
9532 goto done;
9534 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9535 fold_only, repo);
9536 if (err)
9537 goto done;
9539 if (edit_logmsg_only || fold_only) {
9540 rewind(f);
9541 err = histedit_parse_list(histedit_cmds, f, repo);
9542 } else {
9543 if (fclose(f) == EOF) {
9544 err = got_error_from_errno("fclose");
9545 goto done;
9547 f = NULL;
9548 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9549 if (err) {
9550 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9551 err->code != GOT_ERR_HISTEDIT_CMD)
9552 goto done;
9553 err = histedit_edit_list_retry(histedit_cmds, err,
9554 commits, path, branch_name, repo);
9557 done:
9558 if (f && fclose(f) == EOF && err == NULL)
9559 err = got_error_from_errno("fclose");
9560 if (path && unlink(path) != 0 && err == NULL)
9561 err = got_error_from_errno2("unlink", path);
9562 free(path);
9563 return err;
9566 static const struct got_error *
9567 histedit_save_list(struct got_histedit_list *histedit_cmds,
9568 struct got_worktree *worktree, struct got_repository *repo)
9570 const struct got_error *err = NULL;
9571 char *path = NULL;
9572 FILE *f = NULL;
9573 struct got_histedit_list_entry *hle;
9574 struct got_commit_object *commit = NULL;
9576 err = got_worktree_get_histedit_script_path(&path, worktree);
9577 if (err)
9578 return err;
9580 f = fopen(path, "w");
9581 if (f == NULL) {
9582 err = got_error_from_errno2("fopen", path);
9583 goto done;
9585 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9586 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9587 repo);
9588 if (err)
9589 break;
9591 if (hle->logmsg) {
9592 int n = fprintf(f, "%c %s\n",
9593 GOT_HISTEDIT_MESG, hle->logmsg);
9594 if (n < 0) {
9595 err = got_ferror(f, GOT_ERR_IO);
9596 break;
9600 done:
9601 if (f && fclose(f) == EOF && err == NULL)
9602 err = got_error_from_errno("fclose");
9603 free(path);
9604 if (commit)
9605 got_object_commit_close(commit);
9606 return err;
9609 void
9610 histedit_free_list(struct got_histedit_list *histedit_cmds)
9612 struct got_histedit_list_entry *hle;
9614 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9615 TAILQ_REMOVE(histedit_cmds, hle, entry);
9616 free(hle);
9620 static const struct got_error *
9621 histedit_load_list(struct got_histedit_list *histedit_cmds,
9622 const char *path, struct got_repository *repo)
9624 const struct got_error *err = NULL;
9625 FILE *f = NULL;
9627 f = fopen(path, "r");
9628 if (f == NULL) {
9629 err = got_error_from_errno2("fopen", path);
9630 goto done;
9633 err = histedit_parse_list(histedit_cmds, f, repo);
9634 done:
9635 if (f && fclose(f) == EOF && err == NULL)
9636 err = got_error_from_errno("fclose");
9637 return err;
9640 static const struct got_error *
9641 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9642 const struct got_error *edit_err, struct got_object_id_queue *commits,
9643 const char *path, const char *branch_name, struct got_repository *repo)
9645 const struct got_error *err = NULL, *prev_err = edit_err;
9646 int resp = ' ';
9648 while (resp != 'c' && resp != 'r' && resp != 'a') {
9649 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9650 "or (a)bort: ", getprogname(), prev_err->msg);
9651 resp = getchar();
9652 if (resp == '\n')
9653 resp = getchar();
9654 if (resp == 'c') {
9655 histedit_free_list(histedit_cmds);
9656 err = histedit_run_editor(histedit_cmds, path, commits,
9657 repo);
9658 if (err) {
9659 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9660 err->code != GOT_ERR_HISTEDIT_CMD)
9661 break;
9662 prev_err = err;
9663 resp = ' ';
9664 continue;
9666 break;
9667 } else if (resp == 'r') {
9668 histedit_free_list(histedit_cmds);
9669 err = histedit_edit_script(histedit_cmds,
9670 commits, branch_name, 0, 0, repo);
9671 if (err) {
9672 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9673 err->code != GOT_ERR_HISTEDIT_CMD)
9674 break;
9675 prev_err = err;
9676 resp = ' ';
9677 continue;
9679 break;
9680 } else if (resp == 'a') {
9681 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9682 break;
9683 } else
9684 printf("invalid response '%c'\n", resp);
9687 return err;
9690 static const struct got_error *
9691 histedit_complete(struct got_worktree *worktree,
9692 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9693 struct got_reference *branch, struct got_repository *repo)
9695 printf("Switching work tree to %s\n",
9696 got_ref_get_symref_target(branch));
9697 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9698 branch, repo);
9701 static const struct got_error *
9702 show_histedit_progress(struct got_commit_object *commit,
9703 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9705 const struct got_error *err;
9706 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9708 err = got_object_id_str(&old_id_str, hle->commit_id);
9709 if (err)
9710 goto done;
9712 if (new_id) {
9713 err = got_object_id_str(&new_id_str, new_id);
9714 if (err)
9715 goto done;
9718 old_id_str[12] = '\0';
9719 if (new_id_str)
9720 new_id_str[12] = '\0';
9722 if (hle->logmsg) {
9723 logmsg = strdup(hle->logmsg);
9724 if (logmsg == NULL) {
9725 err = got_error_from_errno("strdup");
9726 goto done;
9728 trim_logmsg(logmsg, 42);
9729 } else {
9730 err = get_short_logmsg(&logmsg, 42, commit);
9731 if (err)
9732 goto done;
9735 switch (hle->cmd->code) {
9736 case GOT_HISTEDIT_PICK:
9737 case GOT_HISTEDIT_EDIT:
9738 printf("%s -> %s: %s\n", old_id_str,
9739 new_id_str ? new_id_str : "no-op change", logmsg);
9740 break;
9741 case GOT_HISTEDIT_DROP:
9742 case GOT_HISTEDIT_FOLD:
9743 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9744 logmsg);
9745 break;
9746 default:
9747 break;
9749 done:
9750 free(old_id_str);
9751 free(new_id_str);
9752 return err;
9755 static const struct got_error *
9756 histedit_commit(struct got_pathlist_head *merged_paths,
9757 struct got_worktree *worktree, struct got_fileindex *fileindex,
9758 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9759 struct got_repository *repo)
9761 const struct got_error *err;
9762 struct got_commit_object *commit;
9763 struct got_object_id *new_commit_id;
9765 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9766 && hle->logmsg == NULL) {
9767 err = histedit_edit_logmsg(hle, repo);
9768 if (err)
9769 return err;
9772 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9773 if (err)
9774 return err;
9776 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9777 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9778 hle->logmsg, repo);
9779 if (err) {
9780 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9781 goto done;
9782 err = show_histedit_progress(commit, hle, NULL);
9783 } else {
9784 err = show_histedit_progress(commit, hle, new_commit_id);
9785 free(new_commit_id);
9787 done:
9788 got_object_commit_close(commit);
9789 return err;
9792 static const struct got_error *
9793 histedit_skip_commit(struct got_histedit_list_entry *hle,
9794 struct got_worktree *worktree, struct got_repository *repo)
9796 const struct got_error *error;
9797 struct got_commit_object *commit;
9799 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9800 repo);
9801 if (error)
9802 return error;
9804 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9805 if (error)
9806 return error;
9808 error = show_histedit_progress(commit, hle, NULL);
9809 got_object_commit_close(commit);
9810 return error;
9813 static const struct got_error *
9814 check_local_changes(void *arg, unsigned char status,
9815 unsigned char staged_status, const char *path,
9816 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9817 struct got_object_id *commit_id, int dirfd, const char *de_name)
9819 int *have_local_changes = arg;
9821 switch (status) {
9822 case GOT_STATUS_ADD:
9823 case GOT_STATUS_DELETE:
9824 case GOT_STATUS_MODIFY:
9825 case GOT_STATUS_CONFLICT:
9826 *have_local_changes = 1;
9827 return got_error(GOT_ERR_CANCELLED);
9828 default:
9829 break;
9832 switch (staged_status) {
9833 case GOT_STATUS_ADD:
9834 case GOT_STATUS_DELETE:
9835 case GOT_STATUS_MODIFY:
9836 *have_local_changes = 1;
9837 return got_error(GOT_ERR_CANCELLED);
9838 default:
9839 break;
9842 return NULL;
9845 static const struct got_error *
9846 cmd_histedit(int argc, char *argv[])
9848 const struct got_error *error = NULL;
9849 struct got_worktree *worktree = NULL;
9850 struct got_fileindex *fileindex = NULL;
9851 struct got_repository *repo = NULL;
9852 char *cwd = NULL;
9853 struct got_reference *branch = NULL;
9854 struct got_reference *tmp_branch = NULL;
9855 struct got_object_id *resume_commit_id = NULL;
9856 struct got_object_id *base_commit_id = NULL;
9857 struct got_object_id *head_commit_id = NULL;
9858 struct got_commit_object *commit = NULL;
9859 int ch, rebase_in_progress = 0;
9860 struct got_update_progress_arg upa;
9861 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9862 int edit_logmsg_only = 0, fold_only = 0;
9863 int list_backups = 0, delete_backups = 0;
9864 const char *edit_script_path = NULL;
9865 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9866 struct got_object_id_queue commits;
9867 struct got_pathlist_head merged_paths;
9868 const struct got_object_id_queue *parent_ids;
9869 struct got_object_qid *pid;
9870 struct got_histedit_list histedit_cmds;
9871 struct got_histedit_list_entry *hle;
9873 STAILQ_INIT(&commits);
9874 TAILQ_INIT(&histedit_cmds);
9875 TAILQ_INIT(&merged_paths);
9876 memset(&upa, 0, sizeof(upa));
9878 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9879 switch (ch) {
9880 case 'a':
9881 abort_edit = 1;
9882 break;
9883 case 'c':
9884 continue_edit = 1;
9885 break;
9886 case 'f':
9887 fold_only = 1;
9888 break;
9889 case 'F':
9890 edit_script_path = optarg;
9891 break;
9892 case 'm':
9893 edit_logmsg_only = 1;
9894 break;
9895 case 'l':
9896 list_backups = 1;
9897 break;
9898 case 'X':
9899 delete_backups = 1;
9900 break;
9901 default:
9902 usage_histedit();
9903 /* NOTREACHED */
9907 argc -= optind;
9908 argv += optind;
9910 #ifndef PROFILE
9911 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9912 "unveil", NULL) == -1)
9913 err(1, "pledge");
9914 #endif
9915 if (abort_edit && continue_edit)
9916 option_conflict('a', 'c');
9917 if (edit_script_path && edit_logmsg_only)
9918 option_conflict('F', 'm');
9919 if (abort_edit && edit_logmsg_only)
9920 option_conflict('a', 'm');
9921 if (continue_edit && edit_logmsg_only)
9922 option_conflict('c', 'm');
9923 if (abort_edit && fold_only)
9924 option_conflict('a', 'f');
9925 if (continue_edit && fold_only)
9926 option_conflict('c', 'f');
9927 if (fold_only && edit_logmsg_only)
9928 option_conflict('f', 'm');
9929 if (edit_script_path && fold_only)
9930 option_conflict('F', 'f');
9931 if (list_backups) {
9932 if (abort_edit)
9933 option_conflict('l', 'a');
9934 if (continue_edit)
9935 option_conflict('l', 'c');
9936 if (edit_script_path)
9937 option_conflict('l', 'F');
9938 if (edit_logmsg_only)
9939 option_conflict('l', 'm');
9940 if (fold_only)
9941 option_conflict('l', 'f');
9942 if (delete_backups)
9943 option_conflict('l', 'X');
9944 if (argc != 0 && argc != 1)
9945 usage_histedit();
9946 } else if (delete_backups) {
9947 if (abort_edit)
9948 option_conflict('X', 'a');
9949 if (continue_edit)
9950 option_conflict('X', 'c');
9951 if (edit_script_path)
9952 option_conflict('X', 'F');
9953 if (edit_logmsg_only)
9954 option_conflict('X', 'm');
9955 if (fold_only)
9956 option_conflict('X', 'f');
9957 if (list_backups)
9958 option_conflict('X', 'l');
9959 if (argc != 0 && argc != 1)
9960 usage_histedit();
9961 } else if (argc != 0)
9962 usage_histedit();
9965 * This command cannot apply unveil(2) in all cases because the
9966 * user may choose to run an editor to edit the histedit script
9967 * and to edit individual commit log messages.
9968 * unveil(2) traverses exec(2); if an editor is used we have to
9969 * apply unveil after edit script and log messages have been written.
9970 * XXX TODO: Make use of unveil(2) where possible.
9973 cwd = getcwd(NULL, 0);
9974 if (cwd == NULL) {
9975 error = got_error_from_errno("getcwd");
9976 goto done;
9978 error = got_worktree_open(&worktree, cwd);
9979 if (error) {
9980 if (list_backups || delete_backups) {
9981 if (error->code != GOT_ERR_NOT_WORKTREE)
9982 goto done;
9983 } else {
9984 if (error->code == GOT_ERR_NOT_WORKTREE)
9985 error = wrap_not_worktree_error(error,
9986 "histedit", cwd);
9987 goto done;
9991 if (list_backups || delete_backups) {
9992 error = got_repo_open(&repo,
9993 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9994 NULL);
9995 if (error != NULL)
9996 goto done;
9997 error = apply_unveil(got_repo_get_path(repo), 0,
9998 worktree ? got_worktree_get_root_path(worktree) : NULL);
9999 if (error)
10000 goto done;
10001 error = process_backup_refs(
10002 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10003 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10004 goto done; /* nothing else to do */
10007 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10008 NULL);
10009 if (error != NULL)
10010 goto done;
10012 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10013 if (error)
10014 goto done;
10015 if (rebase_in_progress) {
10016 error = got_error(GOT_ERR_REBASING);
10017 goto done;
10020 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10021 if (error)
10022 goto done;
10024 if (edit_in_progress && edit_logmsg_only) {
10025 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10026 "histedit operation is in progress in this "
10027 "work tree and must be continued or aborted "
10028 "before the -m option can be used");
10029 goto done;
10031 if (edit_in_progress && fold_only) {
10032 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10033 "histedit operation is in progress in this "
10034 "work tree and must be continued or aborted "
10035 "before the -f option can be used");
10036 goto done;
10039 if (edit_in_progress && abort_edit) {
10040 error = got_worktree_histedit_continue(&resume_commit_id,
10041 &tmp_branch, &branch, &base_commit_id, &fileindex,
10042 worktree, repo);
10043 if (error)
10044 goto done;
10045 printf("Switching work tree to %s\n",
10046 got_ref_get_symref_target(branch));
10047 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10048 branch, base_commit_id, update_progress, &upa);
10049 if (error)
10050 goto done;
10051 printf("Histedit of %s aborted\n",
10052 got_ref_get_symref_target(branch));
10053 print_update_progress_stats(&upa);
10054 goto done; /* nothing else to do */
10055 } else if (abort_edit) {
10056 error = got_error(GOT_ERR_NOT_HISTEDIT);
10057 goto done;
10060 if (continue_edit) {
10061 char *path;
10063 if (!edit_in_progress) {
10064 error = got_error(GOT_ERR_NOT_HISTEDIT);
10065 goto done;
10068 error = got_worktree_get_histedit_script_path(&path, worktree);
10069 if (error)
10070 goto done;
10072 error = histedit_load_list(&histedit_cmds, path, repo);
10073 free(path);
10074 if (error)
10075 goto done;
10077 error = got_worktree_histedit_continue(&resume_commit_id,
10078 &tmp_branch, &branch, &base_commit_id, &fileindex,
10079 worktree, repo);
10080 if (error)
10081 goto done;
10083 error = got_ref_resolve(&head_commit_id, repo, branch);
10084 if (error)
10085 goto done;
10087 error = got_object_open_as_commit(&commit, repo,
10088 head_commit_id);
10089 if (error)
10090 goto done;
10091 parent_ids = got_object_commit_get_parent_ids(commit);
10092 pid = STAILQ_FIRST(parent_ids);
10093 if (pid == NULL) {
10094 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10095 goto done;
10097 error = collect_commits(&commits, head_commit_id, pid->id,
10098 base_commit_id, got_worktree_get_path_prefix(worktree),
10099 GOT_ERR_HISTEDIT_PATH, repo);
10100 got_object_commit_close(commit);
10101 commit = NULL;
10102 if (error)
10103 goto done;
10104 } else {
10105 if (edit_in_progress) {
10106 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10107 goto done;
10110 error = got_ref_open(&branch, repo,
10111 got_worktree_get_head_ref_name(worktree), 0);
10112 if (error != NULL)
10113 goto done;
10115 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10116 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10117 "will not edit commit history of a branch outside "
10118 "the \"refs/heads/\" reference namespace");
10119 goto done;
10122 error = got_ref_resolve(&head_commit_id, repo, branch);
10123 got_ref_close(branch);
10124 branch = NULL;
10125 if (error)
10126 goto done;
10128 error = got_object_open_as_commit(&commit, repo,
10129 head_commit_id);
10130 if (error)
10131 goto done;
10132 parent_ids = got_object_commit_get_parent_ids(commit);
10133 pid = STAILQ_FIRST(parent_ids);
10134 if (pid == NULL) {
10135 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10136 goto done;
10138 error = collect_commits(&commits, head_commit_id, pid->id,
10139 got_worktree_get_base_commit_id(worktree),
10140 got_worktree_get_path_prefix(worktree),
10141 GOT_ERR_HISTEDIT_PATH, repo);
10142 got_object_commit_close(commit);
10143 commit = NULL;
10144 if (error)
10145 goto done;
10147 if (STAILQ_EMPTY(&commits)) {
10148 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10149 goto done;
10152 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10153 &base_commit_id, &fileindex, worktree, repo);
10154 if (error)
10155 goto done;
10157 if (edit_script_path) {
10158 error = histedit_load_list(&histedit_cmds,
10159 edit_script_path, repo);
10160 if (error) {
10161 got_worktree_histedit_abort(worktree, fileindex,
10162 repo, branch, base_commit_id,
10163 update_progress, &upa);
10164 print_update_progress_stats(&upa);
10165 goto done;
10167 } else {
10168 const char *branch_name;
10169 branch_name = got_ref_get_symref_target(branch);
10170 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10171 branch_name += 11;
10172 error = histedit_edit_script(&histedit_cmds, &commits,
10173 branch_name, edit_logmsg_only, fold_only, repo);
10174 if (error) {
10175 got_worktree_histedit_abort(worktree, fileindex,
10176 repo, branch, base_commit_id,
10177 update_progress, &upa);
10178 print_update_progress_stats(&upa);
10179 goto done;
10184 error = histedit_save_list(&histedit_cmds, worktree,
10185 repo);
10186 if (error) {
10187 got_worktree_histedit_abort(worktree, fileindex,
10188 repo, branch, base_commit_id,
10189 update_progress, &upa);
10190 print_update_progress_stats(&upa);
10191 goto done;
10196 error = histedit_check_script(&histedit_cmds, &commits, repo);
10197 if (error)
10198 goto done;
10200 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10201 if (resume_commit_id) {
10202 if (got_object_id_cmp(hle->commit_id,
10203 resume_commit_id) != 0)
10204 continue;
10206 resume_commit_id = NULL;
10207 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10208 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10209 error = histedit_skip_commit(hle, worktree,
10210 repo);
10211 if (error)
10212 goto done;
10213 } else {
10214 struct got_pathlist_head paths;
10215 int have_changes = 0;
10217 TAILQ_INIT(&paths);
10218 error = got_pathlist_append(&paths, "", NULL);
10219 if (error)
10220 goto done;
10221 error = got_worktree_status(worktree, &paths,
10222 repo, 0, check_local_changes, &have_changes,
10223 check_cancelled, NULL);
10224 got_pathlist_free(&paths);
10225 if (error) {
10226 if (error->code != GOT_ERR_CANCELLED)
10227 goto done;
10228 if (sigint_received || sigpipe_received)
10229 goto done;
10231 if (have_changes) {
10232 error = histedit_commit(NULL, worktree,
10233 fileindex, tmp_branch, hle, repo);
10234 if (error)
10235 goto done;
10236 } else {
10237 error = got_object_open_as_commit(
10238 &commit, repo, hle->commit_id);
10239 if (error)
10240 goto done;
10241 error = show_histedit_progress(commit,
10242 hle, NULL);
10243 got_object_commit_close(commit);
10244 commit = NULL;
10245 if (error)
10246 goto done;
10249 continue;
10252 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10253 error = histedit_skip_commit(hle, worktree, repo);
10254 if (error)
10255 goto done;
10256 continue;
10259 error = got_object_open_as_commit(&commit, repo,
10260 hle->commit_id);
10261 if (error)
10262 goto done;
10263 parent_ids = got_object_commit_get_parent_ids(commit);
10264 pid = STAILQ_FIRST(parent_ids);
10266 error = got_worktree_histedit_merge_files(&merged_paths,
10267 worktree, fileindex, pid->id, hle->commit_id, repo,
10268 update_progress, &upa, check_cancelled, NULL);
10269 if (error)
10270 goto done;
10271 got_object_commit_close(commit);
10272 commit = NULL;
10274 print_update_progress_stats(&upa);
10275 if (upa.conflicts > 0)
10276 rebase_status = GOT_STATUS_CONFLICT;
10278 if (rebase_status == GOT_STATUS_CONFLICT) {
10279 error = show_rebase_merge_conflict(hle->commit_id,
10280 repo);
10281 if (error)
10282 goto done;
10283 got_worktree_rebase_pathlist_free(&merged_paths);
10284 break;
10287 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10288 char *id_str;
10289 error = got_object_id_str(&id_str, hle->commit_id);
10290 if (error)
10291 goto done;
10292 printf("Stopping histedit for amending commit %s\n",
10293 id_str);
10294 free(id_str);
10295 got_worktree_rebase_pathlist_free(&merged_paths);
10296 error = got_worktree_histedit_postpone(worktree,
10297 fileindex);
10298 goto done;
10301 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10302 error = histedit_skip_commit(hle, worktree, repo);
10303 if (error)
10304 goto done;
10305 continue;
10308 error = histedit_commit(&merged_paths, worktree, fileindex,
10309 tmp_branch, hle, repo);
10310 got_worktree_rebase_pathlist_free(&merged_paths);
10311 if (error)
10312 goto done;
10315 if (rebase_status == GOT_STATUS_CONFLICT) {
10316 error = got_worktree_histedit_postpone(worktree, fileindex);
10317 if (error)
10318 goto done;
10319 error = got_error_msg(GOT_ERR_CONFLICTS,
10320 "conflicts must be resolved before histedit can continue");
10321 } else
10322 error = histedit_complete(worktree, fileindex, tmp_branch,
10323 branch, repo);
10324 done:
10325 got_object_id_queue_free(&commits);
10326 histedit_free_list(&histedit_cmds);
10327 free(head_commit_id);
10328 free(base_commit_id);
10329 free(resume_commit_id);
10330 if (commit)
10331 got_object_commit_close(commit);
10332 if (branch)
10333 got_ref_close(branch);
10334 if (tmp_branch)
10335 got_ref_close(tmp_branch);
10336 if (worktree)
10337 got_worktree_close(worktree);
10338 if (repo) {
10339 const struct got_error *close_err = got_repo_close(repo);
10340 if (error == NULL)
10341 error = close_err;
10343 return error;
10346 __dead static void
10347 usage_integrate(void)
10349 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10350 exit(1);
10353 static const struct got_error *
10354 cmd_integrate(int argc, char *argv[])
10356 const struct got_error *error = NULL;
10357 struct got_repository *repo = NULL;
10358 struct got_worktree *worktree = NULL;
10359 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10360 const char *branch_arg = NULL;
10361 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10362 struct got_fileindex *fileindex = NULL;
10363 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10364 int ch;
10365 struct got_update_progress_arg upa;
10367 while ((ch = getopt(argc, argv, "")) != -1) {
10368 switch (ch) {
10369 default:
10370 usage_integrate();
10371 /* NOTREACHED */
10375 argc -= optind;
10376 argv += optind;
10378 if (argc != 1)
10379 usage_integrate();
10380 branch_arg = argv[0];
10381 #ifndef PROFILE
10382 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10383 "unveil", NULL) == -1)
10384 err(1, "pledge");
10385 #endif
10386 cwd = getcwd(NULL, 0);
10387 if (cwd == NULL) {
10388 error = got_error_from_errno("getcwd");
10389 goto done;
10392 error = got_worktree_open(&worktree, cwd);
10393 if (error) {
10394 if (error->code == GOT_ERR_NOT_WORKTREE)
10395 error = wrap_not_worktree_error(error, "integrate",
10396 cwd);
10397 goto done;
10400 error = check_rebase_or_histedit_in_progress(worktree);
10401 if (error)
10402 goto done;
10404 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10405 NULL);
10406 if (error != NULL)
10407 goto done;
10409 error = apply_unveil(got_repo_get_path(repo), 0,
10410 got_worktree_get_root_path(worktree));
10411 if (error)
10412 goto done;
10414 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10415 error = got_error_from_errno("asprintf");
10416 goto done;
10419 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10420 &base_branch_ref, worktree, refname, repo);
10421 if (error)
10422 goto done;
10424 refname = strdup(got_ref_get_name(branch_ref));
10425 if (refname == NULL) {
10426 error = got_error_from_errno("strdup");
10427 got_worktree_integrate_abort(worktree, fileindex, repo,
10428 branch_ref, base_branch_ref);
10429 goto done;
10431 base_refname = strdup(got_ref_get_name(base_branch_ref));
10432 if (base_refname == NULL) {
10433 error = got_error_from_errno("strdup");
10434 got_worktree_integrate_abort(worktree, fileindex, repo,
10435 branch_ref, base_branch_ref);
10436 goto done;
10439 error = got_ref_resolve(&commit_id, repo, branch_ref);
10440 if (error)
10441 goto done;
10443 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10444 if (error)
10445 goto done;
10447 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10448 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10449 "specified branch has already been integrated");
10450 got_worktree_integrate_abort(worktree, fileindex, repo,
10451 branch_ref, base_branch_ref);
10452 goto done;
10455 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10456 if (error) {
10457 if (error->code == GOT_ERR_ANCESTRY)
10458 error = got_error(GOT_ERR_REBASE_REQUIRED);
10459 got_worktree_integrate_abort(worktree, fileindex, repo,
10460 branch_ref, base_branch_ref);
10461 goto done;
10464 memset(&upa, 0, sizeof(upa));
10465 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10466 branch_ref, base_branch_ref, update_progress, &upa,
10467 check_cancelled, NULL);
10468 if (error)
10469 goto done;
10471 printf("Integrated %s into %s\n", refname, base_refname);
10472 print_update_progress_stats(&upa);
10473 done:
10474 if (repo) {
10475 const struct got_error *close_err = got_repo_close(repo);
10476 if (error == NULL)
10477 error = close_err;
10479 if (worktree)
10480 got_worktree_close(worktree);
10481 free(cwd);
10482 free(base_commit_id);
10483 free(commit_id);
10484 free(refname);
10485 free(base_refname);
10486 return error;
10489 __dead static void
10490 usage_stage(void)
10492 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10493 "[-S] [file-path ...]\n",
10494 getprogname());
10495 exit(1);
10498 static const struct got_error *
10499 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10500 const char *path, struct got_object_id *blob_id,
10501 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10502 int dirfd, const char *de_name)
10504 const struct got_error *err = NULL;
10505 char *id_str = NULL;
10507 if (staged_status != GOT_STATUS_ADD &&
10508 staged_status != GOT_STATUS_MODIFY &&
10509 staged_status != GOT_STATUS_DELETE)
10510 return NULL;
10512 if (staged_status == GOT_STATUS_ADD ||
10513 staged_status == GOT_STATUS_MODIFY)
10514 err = got_object_id_str(&id_str, staged_blob_id);
10515 else
10516 err = got_object_id_str(&id_str, blob_id);
10517 if (err)
10518 return err;
10520 printf("%s %c %s\n", id_str, staged_status, path);
10521 free(id_str);
10522 return NULL;
10525 static const struct got_error *
10526 cmd_stage(int argc, char *argv[])
10528 const struct got_error *error = NULL;
10529 struct got_repository *repo = NULL;
10530 struct got_worktree *worktree = NULL;
10531 char *cwd = NULL;
10532 struct got_pathlist_head paths;
10533 struct got_pathlist_entry *pe;
10534 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10535 FILE *patch_script_file = NULL;
10536 const char *patch_script_path = NULL;
10537 struct choose_patch_arg cpa;
10539 TAILQ_INIT(&paths);
10541 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10542 switch (ch) {
10543 case 'l':
10544 list_stage = 1;
10545 break;
10546 case 'p':
10547 pflag = 1;
10548 break;
10549 case 'F':
10550 patch_script_path = optarg;
10551 break;
10552 case 'S':
10553 allow_bad_symlinks = 1;
10554 break;
10555 default:
10556 usage_stage();
10557 /* NOTREACHED */
10561 argc -= optind;
10562 argv += optind;
10564 #ifndef PROFILE
10565 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10566 "unveil", NULL) == -1)
10567 err(1, "pledge");
10568 #endif
10569 if (list_stage && (pflag || patch_script_path))
10570 errx(1, "-l option cannot be used with other options");
10571 if (patch_script_path && !pflag)
10572 errx(1, "-F option can only be used together with -p option");
10574 cwd = getcwd(NULL, 0);
10575 if (cwd == NULL) {
10576 error = got_error_from_errno("getcwd");
10577 goto done;
10580 error = got_worktree_open(&worktree, cwd);
10581 if (error) {
10582 if (error->code == GOT_ERR_NOT_WORKTREE)
10583 error = wrap_not_worktree_error(error, "stage", cwd);
10584 goto done;
10587 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10588 NULL);
10589 if (error != NULL)
10590 goto done;
10592 if (patch_script_path) {
10593 patch_script_file = fopen(patch_script_path, "r");
10594 if (patch_script_file == NULL) {
10595 error = got_error_from_errno2("fopen",
10596 patch_script_path);
10597 goto done;
10600 error = apply_unveil(got_repo_get_path(repo), 0,
10601 got_worktree_get_root_path(worktree));
10602 if (error)
10603 goto done;
10605 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10606 if (error)
10607 goto done;
10609 if (list_stage)
10610 error = got_worktree_status(worktree, &paths, repo, 0,
10611 print_stage, NULL, check_cancelled, NULL);
10612 else {
10613 cpa.patch_script_file = patch_script_file;
10614 cpa.action = "stage";
10615 error = got_worktree_stage(worktree, &paths,
10616 pflag ? NULL : print_status, NULL,
10617 pflag ? choose_patch : NULL, &cpa,
10618 allow_bad_symlinks, repo);
10620 done:
10621 if (patch_script_file && fclose(patch_script_file) == EOF &&
10622 error == NULL)
10623 error = got_error_from_errno2("fclose", patch_script_path);
10624 if (repo) {
10625 const struct got_error *close_err = got_repo_close(repo);
10626 if (error == NULL)
10627 error = close_err;
10629 if (worktree)
10630 got_worktree_close(worktree);
10631 TAILQ_FOREACH(pe, &paths, entry)
10632 free((char *)pe->path);
10633 got_pathlist_free(&paths);
10634 free(cwd);
10635 return error;
10638 __dead static void
10639 usage_unstage(void)
10641 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10642 "[file-path ...]\n",
10643 getprogname());
10644 exit(1);
10648 static const struct got_error *
10649 cmd_unstage(int argc, char *argv[])
10651 const struct got_error *error = NULL;
10652 struct got_repository *repo = NULL;
10653 struct got_worktree *worktree = NULL;
10654 char *cwd = NULL;
10655 struct got_pathlist_head paths;
10656 struct got_pathlist_entry *pe;
10657 int ch, pflag = 0;
10658 struct got_update_progress_arg upa;
10659 FILE *patch_script_file = NULL;
10660 const char *patch_script_path = NULL;
10661 struct choose_patch_arg cpa;
10663 TAILQ_INIT(&paths);
10665 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10666 switch (ch) {
10667 case 'p':
10668 pflag = 1;
10669 break;
10670 case 'F':
10671 patch_script_path = optarg;
10672 break;
10673 default:
10674 usage_unstage();
10675 /* NOTREACHED */
10679 argc -= optind;
10680 argv += optind;
10682 #ifndef PROFILE
10683 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10684 "unveil", NULL) == -1)
10685 err(1, "pledge");
10686 #endif
10687 if (patch_script_path && !pflag)
10688 errx(1, "-F option can only be used together with -p option");
10690 cwd = getcwd(NULL, 0);
10691 if (cwd == NULL) {
10692 error = got_error_from_errno("getcwd");
10693 goto done;
10696 error = got_worktree_open(&worktree, cwd);
10697 if (error) {
10698 if (error->code == GOT_ERR_NOT_WORKTREE)
10699 error = wrap_not_worktree_error(error, "unstage", cwd);
10700 goto done;
10703 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10704 NULL);
10705 if (error != NULL)
10706 goto done;
10708 if (patch_script_path) {
10709 patch_script_file = fopen(patch_script_path, "r");
10710 if (patch_script_file == NULL) {
10711 error = got_error_from_errno2("fopen",
10712 patch_script_path);
10713 goto done;
10717 error = apply_unveil(got_repo_get_path(repo), 0,
10718 got_worktree_get_root_path(worktree));
10719 if (error)
10720 goto done;
10722 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10723 if (error)
10724 goto done;
10726 cpa.patch_script_file = patch_script_file;
10727 cpa.action = "unstage";
10728 memset(&upa, 0, sizeof(upa));
10729 error = got_worktree_unstage(worktree, &paths, update_progress,
10730 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10731 if (!error)
10732 print_update_progress_stats(&upa);
10733 done:
10734 if (patch_script_file && fclose(patch_script_file) == EOF &&
10735 error == NULL)
10736 error = got_error_from_errno2("fclose", patch_script_path);
10737 if (repo) {
10738 const struct got_error *close_err = got_repo_close(repo);
10739 if (error == NULL)
10740 error = close_err;
10742 if (worktree)
10743 got_worktree_close(worktree);
10744 TAILQ_FOREACH(pe, &paths, entry)
10745 free((char *)pe->path);
10746 got_pathlist_free(&paths);
10747 free(cwd);
10748 return error;
10751 __dead static void
10752 usage_cat(void)
10754 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10755 "arg1 [arg2 ...]\n", getprogname());
10756 exit(1);
10759 static const struct got_error *
10760 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10762 const struct got_error *err;
10763 struct got_blob_object *blob;
10765 err = got_object_open_as_blob(&blob, repo, id, 8192);
10766 if (err)
10767 return err;
10769 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10770 got_object_blob_close(blob);
10771 return err;
10774 static const struct got_error *
10775 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10777 const struct got_error *err;
10778 struct got_tree_object *tree;
10779 int nentries, i;
10781 err = got_object_open_as_tree(&tree, repo, id);
10782 if (err)
10783 return err;
10785 nentries = got_object_tree_get_nentries(tree);
10786 for (i = 0; i < nentries; i++) {
10787 struct got_tree_entry *te;
10788 char *id_str;
10789 if (sigint_received || sigpipe_received)
10790 break;
10791 te = got_object_tree_get_entry(tree, i);
10792 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10793 if (err)
10794 break;
10795 fprintf(outfile, "%s %.7o %s\n", id_str,
10796 got_tree_entry_get_mode(te),
10797 got_tree_entry_get_name(te));
10798 free(id_str);
10801 got_object_tree_close(tree);
10802 return err;
10805 static const struct got_error *
10806 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10808 const struct got_error *err;
10809 struct got_commit_object *commit;
10810 const struct got_object_id_queue *parent_ids;
10811 struct got_object_qid *pid;
10812 char *id_str = NULL;
10813 const char *logmsg = NULL;
10815 err = got_object_open_as_commit(&commit, repo, id);
10816 if (err)
10817 return err;
10819 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10820 if (err)
10821 goto done;
10823 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10824 parent_ids = got_object_commit_get_parent_ids(commit);
10825 fprintf(outfile, "numparents %d\n",
10826 got_object_commit_get_nparents(commit));
10827 STAILQ_FOREACH(pid, parent_ids, entry) {
10828 char *pid_str;
10829 err = got_object_id_str(&pid_str, pid->id);
10830 if (err)
10831 goto done;
10832 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10833 free(pid_str);
10835 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10836 got_object_commit_get_author(commit),
10837 (long long)got_object_commit_get_author_time(commit));
10839 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10840 got_object_commit_get_author(commit),
10841 (long long)got_object_commit_get_committer_time(commit));
10843 logmsg = got_object_commit_get_logmsg_raw(commit);
10844 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10845 fprintf(outfile, "%s", logmsg);
10846 done:
10847 free(id_str);
10848 got_object_commit_close(commit);
10849 return err;
10852 static const struct got_error *
10853 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10855 const struct got_error *err;
10856 struct got_tag_object *tag;
10857 char *id_str = NULL;
10858 const char *tagmsg = NULL;
10860 err = got_object_open_as_tag(&tag, repo, id);
10861 if (err)
10862 return err;
10864 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10865 if (err)
10866 goto done;
10868 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10870 switch (got_object_tag_get_object_type(tag)) {
10871 case GOT_OBJ_TYPE_BLOB:
10872 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10873 GOT_OBJ_LABEL_BLOB);
10874 break;
10875 case GOT_OBJ_TYPE_TREE:
10876 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10877 GOT_OBJ_LABEL_TREE);
10878 break;
10879 case GOT_OBJ_TYPE_COMMIT:
10880 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10881 GOT_OBJ_LABEL_COMMIT);
10882 break;
10883 case GOT_OBJ_TYPE_TAG:
10884 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10885 GOT_OBJ_LABEL_TAG);
10886 break;
10887 default:
10888 break;
10891 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10892 got_object_tag_get_name(tag));
10894 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10895 got_object_tag_get_tagger(tag),
10896 (long long)got_object_tag_get_tagger_time(tag));
10898 tagmsg = got_object_tag_get_message(tag);
10899 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10900 fprintf(outfile, "%s", tagmsg);
10901 done:
10902 free(id_str);
10903 got_object_tag_close(tag);
10904 return err;
10907 static const struct got_error *
10908 cmd_cat(int argc, char *argv[])
10910 const struct got_error *error;
10911 struct got_repository *repo = NULL;
10912 struct got_worktree *worktree = NULL;
10913 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10914 const char *commit_id_str = NULL;
10915 struct got_object_id *id = NULL, *commit_id = NULL;
10916 int ch, obj_type, i, force_path = 0;
10917 struct got_reflist_head refs;
10919 TAILQ_INIT(&refs);
10921 #ifndef PROFILE
10922 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10923 NULL) == -1)
10924 err(1, "pledge");
10925 #endif
10927 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10928 switch (ch) {
10929 case 'c':
10930 commit_id_str = optarg;
10931 break;
10932 case 'r':
10933 repo_path = realpath(optarg, NULL);
10934 if (repo_path == NULL)
10935 return got_error_from_errno2("realpath",
10936 optarg);
10937 got_path_strip_trailing_slashes(repo_path);
10938 break;
10939 case 'P':
10940 force_path = 1;
10941 break;
10942 default:
10943 usage_cat();
10944 /* NOTREACHED */
10948 argc -= optind;
10949 argv += optind;
10951 cwd = getcwd(NULL, 0);
10952 if (cwd == NULL) {
10953 error = got_error_from_errno("getcwd");
10954 goto done;
10956 error = got_worktree_open(&worktree, cwd);
10957 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10958 goto done;
10959 if (worktree) {
10960 if (repo_path == NULL) {
10961 repo_path = strdup(
10962 got_worktree_get_repo_path(worktree));
10963 if (repo_path == NULL) {
10964 error = got_error_from_errno("strdup");
10965 goto done;
10970 if (repo_path == NULL) {
10971 repo_path = getcwd(NULL, 0);
10972 if (repo_path == NULL)
10973 return got_error_from_errno("getcwd");
10976 error = got_repo_open(&repo, repo_path, NULL);
10977 free(repo_path);
10978 if (error != NULL)
10979 goto done;
10981 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10982 if (error)
10983 goto done;
10985 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10986 if (error)
10987 goto done;
10989 if (commit_id_str == NULL)
10990 commit_id_str = GOT_REF_HEAD;
10991 error = got_repo_match_object_id(&commit_id, NULL,
10992 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10993 if (error)
10994 goto done;
10996 for (i = 0; i < argc; i++) {
10997 if (force_path) {
10998 error = got_object_id_by_path(&id, repo, commit_id,
10999 argv[i]);
11000 if (error)
11001 break;
11002 } else {
11003 error = got_repo_match_object_id(&id, &label, argv[i],
11004 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11005 repo);
11006 if (error) {
11007 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11008 error->code != GOT_ERR_NOT_REF)
11009 break;
11010 error = got_object_id_by_path(&id, repo,
11011 commit_id, argv[i]);
11012 if (error)
11013 break;
11017 error = got_object_get_type(&obj_type, repo, id);
11018 if (error)
11019 break;
11021 switch (obj_type) {
11022 case GOT_OBJ_TYPE_BLOB:
11023 error = cat_blob(id, repo, stdout);
11024 break;
11025 case GOT_OBJ_TYPE_TREE:
11026 error = cat_tree(id, repo, stdout);
11027 break;
11028 case GOT_OBJ_TYPE_COMMIT:
11029 error = cat_commit(id, repo, stdout);
11030 break;
11031 case GOT_OBJ_TYPE_TAG:
11032 error = cat_tag(id, repo, stdout);
11033 break;
11034 default:
11035 error = got_error(GOT_ERR_OBJ_TYPE);
11036 break;
11038 if (error)
11039 break;
11040 free(label);
11041 label = NULL;
11042 free(id);
11043 id = NULL;
11045 done:
11046 free(label);
11047 free(id);
11048 free(commit_id);
11049 if (worktree)
11050 got_worktree_close(worktree);
11051 if (repo) {
11052 const struct got_error *close_err = got_repo_close(repo);
11053 if (error == NULL)
11054 error = close_err;
11056 got_ref_list_free(&refs);
11057 return error;
11060 __dead static void
11061 usage_info(void)
11063 fprintf(stderr, "usage: %s info [path ...]\n",
11064 getprogname());
11065 exit(1);
11068 static const struct got_error *
11069 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11070 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11071 struct got_object_id *commit_id)
11073 const struct got_error *err = NULL;
11074 char *id_str = NULL;
11075 char datebuf[128];
11076 struct tm mytm, *tm;
11077 struct got_pathlist_head *paths = arg;
11078 struct got_pathlist_entry *pe;
11081 * Clear error indication from any of the path arguments which
11082 * would cause this file index entry to be displayed.
11084 TAILQ_FOREACH(pe, paths, entry) {
11085 if (got_path_cmp(path, pe->path, strlen(path),
11086 pe->path_len) == 0 ||
11087 got_path_is_child(path, pe->path, pe->path_len))
11088 pe->data = NULL; /* no error */
11091 printf(GOT_COMMIT_SEP_STR);
11092 if (S_ISLNK(mode))
11093 printf("symlink: %s\n", path);
11094 else if (S_ISREG(mode)) {
11095 printf("file: %s\n", path);
11096 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11097 } else if (S_ISDIR(mode))
11098 printf("directory: %s\n", path);
11099 else
11100 printf("something: %s\n", path);
11102 tm = localtime_r(&mtime, &mytm);
11103 if (tm == NULL)
11104 return NULL;
11105 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11106 return got_error(GOT_ERR_NO_SPACE);
11107 printf("timestamp: %s\n", datebuf);
11109 if (blob_id) {
11110 err = got_object_id_str(&id_str, blob_id);
11111 if (err)
11112 return err;
11113 printf("based on blob: %s\n", id_str);
11114 free(id_str);
11117 if (staged_blob_id) {
11118 err = got_object_id_str(&id_str, staged_blob_id);
11119 if (err)
11120 return err;
11121 printf("based on staged blob: %s\n", id_str);
11122 free(id_str);
11125 if (commit_id) {
11126 err = got_object_id_str(&id_str, commit_id);
11127 if (err)
11128 return err;
11129 printf("based on commit: %s\n", id_str);
11130 free(id_str);
11133 return NULL;
11136 static const struct got_error *
11137 cmd_info(int argc, char *argv[])
11139 const struct got_error *error = NULL;
11140 struct got_worktree *worktree = NULL;
11141 char *cwd = NULL, *id_str = NULL;
11142 struct got_pathlist_head paths;
11143 struct got_pathlist_entry *pe;
11144 char *uuidstr = NULL;
11145 int ch, show_files = 0;
11147 TAILQ_INIT(&paths);
11149 while ((ch = getopt(argc, argv, "")) != -1) {
11150 switch (ch) {
11151 default:
11152 usage_info();
11153 /* NOTREACHED */
11157 argc -= optind;
11158 argv += optind;
11160 #ifndef PROFILE
11161 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11162 NULL) == -1)
11163 err(1, "pledge");
11164 #endif
11165 cwd = getcwd(NULL, 0);
11166 if (cwd == NULL) {
11167 error = got_error_from_errno("getcwd");
11168 goto done;
11171 error = got_worktree_open(&worktree, cwd);
11172 if (error) {
11173 if (error->code == GOT_ERR_NOT_WORKTREE)
11174 error = wrap_not_worktree_error(error, "info", cwd);
11175 goto done;
11178 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11179 if (error)
11180 goto done;
11182 if (argc >= 1) {
11183 error = get_worktree_paths_from_argv(&paths, argc, argv,
11184 worktree);
11185 if (error)
11186 goto done;
11187 show_files = 1;
11190 error = got_object_id_str(&id_str,
11191 got_worktree_get_base_commit_id(worktree));
11192 if (error)
11193 goto done;
11195 error = got_worktree_get_uuid(&uuidstr, worktree);
11196 if (error)
11197 goto done;
11199 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11200 printf("work tree base commit: %s\n", id_str);
11201 printf("work tree path prefix: %s\n",
11202 got_worktree_get_path_prefix(worktree));
11203 printf("work tree branch reference: %s\n",
11204 got_worktree_get_head_ref_name(worktree));
11205 printf("work tree UUID: %s\n", uuidstr);
11206 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11208 if (show_files) {
11209 struct got_pathlist_entry *pe;
11210 TAILQ_FOREACH(pe, &paths, entry) {
11211 if (pe->path_len == 0)
11212 continue;
11214 * Assume this path will fail. This will be corrected
11215 * in print_path_info() in case the path does suceeed.
11217 pe->data = (void *)got_error_path(pe->path,
11218 GOT_ERR_BAD_PATH);
11220 error = got_worktree_path_info(worktree, &paths,
11221 print_path_info, &paths, check_cancelled, NULL);
11222 if (error)
11223 goto done;
11224 TAILQ_FOREACH(pe, &paths, entry) {
11225 if (pe->data != NULL) {
11226 error = pe->data; /* bad path */
11227 break;
11231 done:
11232 TAILQ_FOREACH(pe, &paths, entry)
11233 free((char *)pe->path);
11234 got_pathlist_free(&paths);
11235 free(cwd);
11236 free(id_str);
11237 free(uuidstr);
11238 return error;