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/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
40 #include <util.h>
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.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_dial_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 error = got_dial_apply_unveil(proto);
1603 if (error)
1604 goto done;
1606 error = apply_unveil(repo_path, 0, NULL);
1607 if (error)
1608 goto done;
1610 if (verbosity >= 0)
1611 printf("Connecting to %s%s%s\n", host,
1612 port ? ":" : "", port ? port : "");
1614 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1615 server_path, verbosity);
1616 if (error)
1617 goto done;
1619 if (!list_refs_only) {
1620 error = got_repo_init(repo_path);
1621 if (error)
1622 goto done;
1623 error = got_repo_open(&repo, repo_path, NULL);
1624 if (error)
1625 goto done;
1628 fpa.last_scaled_size[0] = '\0';
1629 fpa.last_p_indexed = -1;
1630 fpa.last_p_resolved = -1;
1631 fpa.verbosity = verbosity;
1632 fpa.create_configs = 1;
1633 fpa.configs_created = 0;
1634 fpa.repo = repo;
1635 fpa.config_info.symrefs = &symrefs;
1636 fpa.config_info.wanted_branches = &wanted_branches;
1637 fpa.config_info.wanted_refs = &wanted_refs;
1638 fpa.config_info.proto = proto;
1639 fpa.config_info.host = host;
1640 fpa.config_info.port = port;
1641 fpa.config_info.remote_repo_path = server_path;
1642 fpa.config_info.git_url = git_url;
1643 fpa.config_info.fetch_all_branches = fetch_all_branches;
1644 fpa.config_info.mirror_references = mirror_references;
1645 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1646 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1647 fetch_all_branches, &wanted_branches, &wanted_refs,
1648 list_refs_only, verbosity, fetchfd, repo,
1649 fetch_progress, &fpa);
1650 if (error)
1651 goto done;
1653 if (list_refs_only) {
1654 error = list_remote_refs(&symrefs, &refs);
1655 goto done;
1658 error = got_object_id_str(&id_str, pack_hash);
1659 if (error)
1660 goto done;
1661 if (verbosity >= 0)
1662 printf("\nFetched %s.pack\n", id_str);
1663 free(id_str);
1665 /* Set up references provided with the pack file. */
1666 TAILQ_FOREACH(pe, &refs, entry) {
1667 const char *refname = pe->path;
1668 struct got_object_id *id = pe->data;
1669 char *remote_refname;
1671 if (is_wanted_ref(&wanted_refs, refname) &&
1672 !mirror_references) {
1673 error = create_wanted_ref(refname, id,
1674 GOT_FETCH_DEFAULT_REMOTE_NAME,
1675 verbosity - 1, repo);
1676 if (error)
1677 goto done;
1678 continue;
1681 error = create_ref(refname, id, verbosity - 1, repo);
1682 if (error)
1683 goto done;
1685 if (mirror_references)
1686 continue;
1688 if (strncmp("refs/heads/", refname, 11) != 0)
1689 continue;
1691 if (asprintf(&remote_refname,
1692 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1693 refname + 11) == -1) {
1694 error = got_error_from_errno("asprintf");
1695 goto done;
1697 error = create_ref(remote_refname, id, verbosity - 1, repo);
1698 free(remote_refname);
1699 if (error)
1700 goto done;
1703 /* Set the HEAD reference if the server provided one. */
1704 TAILQ_FOREACH(pe, &symrefs, entry) {
1705 struct got_reference *target_ref;
1706 const char *refname = pe->path;
1707 const char *target = pe->data;
1708 char *remote_refname = NULL, *remote_target = NULL;
1710 if (strcmp(refname, GOT_REF_HEAD) != 0)
1711 continue;
1713 error = got_ref_open(&target_ref, repo, target, 0);
1714 if (error) {
1715 if (error->code == GOT_ERR_NOT_REF) {
1716 error = NULL;
1717 continue;
1719 goto done;
1722 error = create_symref(refname, target_ref, verbosity, repo);
1723 got_ref_close(target_ref);
1724 if (error)
1725 goto done;
1727 if (mirror_references)
1728 continue;
1730 if (strncmp("refs/heads/", target, 11) != 0)
1731 continue;
1733 if (asprintf(&remote_refname,
1734 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1735 refname) == -1) {
1736 error = got_error_from_errno("asprintf");
1737 goto done;
1739 if (asprintf(&remote_target,
1740 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1741 target + 11) == -1) {
1742 error = got_error_from_errno("asprintf");
1743 free(remote_refname);
1744 goto done;
1746 error = got_ref_open(&target_ref, repo, remote_target, 0);
1747 if (error) {
1748 free(remote_refname);
1749 free(remote_target);
1750 if (error->code == GOT_ERR_NOT_REF) {
1751 error = NULL;
1752 continue;
1754 goto done;
1756 error = create_symref(remote_refname, target_ref,
1757 verbosity - 1, repo);
1758 free(remote_refname);
1759 free(remote_target);
1760 got_ref_close(target_ref);
1761 if (error)
1762 goto done;
1764 if (pe == NULL) {
1766 * We failed to set the HEAD reference. If we asked for
1767 * a set of wanted branches use the first of one of those
1768 * which could be fetched instead.
1770 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1771 const char *target = pe->path;
1772 struct got_reference *target_ref;
1774 error = got_ref_open(&target_ref, repo, target, 0);
1775 if (error) {
1776 if (error->code == GOT_ERR_NOT_REF) {
1777 error = NULL;
1778 continue;
1780 goto done;
1783 error = create_symref(GOT_REF_HEAD, target_ref,
1784 verbosity, repo);
1785 got_ref_close(target_ref);
1786 if (error)
1787 goto done;
1788 break;
1792 if (verbosity >= 0)
1793 printf("Created %s repository '%s'\n",
1794 mirror_references ? "mirrored" : "cloned", repo_path);
1795 done:
1796 if (fetchpid > 0) {
1797 if (kill(fetchpid, SIGTERM) == -1)
1798 error = got_error_from_errno("kill");
1799 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1800 error = got_error_from_errno("waitpid");
1802 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1803 error = got_error_from_errno("close");
1804 if (repo) {
1805 const struct got_error *close_err = got_repo_close(repo);
1806 if (error == NULL)
1807 error = close_err;
1809 TAILQ_FOREACH(pe, &refs, entry) {
1810 free((void *)pe->path);
1811 free(pe->data);
1813 got_pathlist_free(&refs);
1814 TAILQ_FOREACH(pe, &symrefs, entry) {
1815 free((void *)pe->path);
1816 free(pe->data);
1818 got_pathlist_free(&symrefs);
1819 got_pathlist_free(&wanted_branches);
1820 got_pathlist_free(&wanted_refs);
1821 free(pack_hash);
1822 free(proto);
1823 free(host);
1824 free(port);
1825 free(server_path);
1826 free(repo_name);
1827 free(default_destdir);
1828 free(git_url);
1829 return error;
1832 static const struct got_error *
1833 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1834 int replace_tags, int verbosity, struct got_repository *repo)
1836 const struct got_error *err = NULL;
1837 char *new_id_str = NULL;
1838 struct got_object_id *old_id = NULL;
1840 err = got_object_id_str(&new_id_str, new_id);
1841 if (err)
1842 goto done;
1844 if (!replace_tags &&
1845 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1846 err = got_ref_resolve(&old_id, repo, ref);
1847 if (err)
1848 goto done;
1849 if (got_object_id_cmp(old_id, new_id) == 0)
1850 goto done;
1851 if (verbosity >= 0) {
1852 printf("Rejecting update of existing tag %s: %s\n",
1853 got_ref_get_name(ref), new_id_str);
1855 goto done;
1858 if (got_ref_is_symbolic(ref)) {
1859 if (verbosity >= 0) {
1860 printf("Replacing reference %s: %s\n",
1861 got_ref_get_name(ref),
1862 got_ref_get_symref_target(ref));
1864 err = got_ref_change_symref_to_ref(ref, new_id);
1865 if (err)
1866 goto done;
1867 err = got_ref_write(ref, repo);
1868 if (err)
1869 goto done;
1870 } else {
1871 err = got_ref_resolve(&old_id, repo, ref);
1872 if (err)
1873 goto done;
1874 if (got_object_id_cmp(old_id, new_id) == 0)
1875 goto done;
1877 err = got_ref_change_ref(ref, new_id);
1878 if (err)
1879 goto done;
1880 err = got_ref_write(ref, repo);
1881 if (err)
1882 goto done;
1885 if (verbosity >= 0)
1886 printf("Updated %s: %s\n", got_ref_get_name(ref),
1887 new_id_str);
1888 done:
1889 free(old_id);
1890 free(new_id_str);
1891 return err;
1894 static const struct got_error *
1895 update_symref(const char *refname, struct got_reference *target_ref,
1896 int verbosity, struct got_repository *repo)
1898 const struct got_error *err = NULL, *unlock_err;
1899 struct got_reference *symref;
1900 int symref_is_locked = 0;
1902 err = got_ref_open(&symref, repo, refname, 1);
1903 if (err) {
1904 if (err->code != GOT_ERR_NOT_REF)
1905 return err;
1906 err = got_ref_alloc_symref(&symref, refname, target_ref);
1907 if (err)
1908 goto done;
1910 err = got_ref_write(symref, repo);
1911 if (err)
1912 goto done;
1914 if (verbosity >= 0)
1915 printf("Created reference %s: %s\n",
1916 got_ref_get_name(symref),
1917 got_ref_get_symref_target(symref));
1918 } else {
1919 symref_is_locked = 1;
1921 if (strcmp(got_ref_get_symref_target(symref),
1922 got_ref_get_name(target_ref)) == 0)
1923 goto done;
1925 err = got_ref_change_symref(symref,
1926 got_ref_get_name(target_ref));
1927 if (err)
1928 goto done;
1930 err = got_ref_write(symref, repo);
1931 if (err)
1932 goto done;
1934 if (verbosity >= 0)
1935 printf("Updated %s: %s\n", got_ref_get_name(symref),
1936 got_ref_get_symref_target(symref));
1939 done:
1940 if (symref_is_locked) {
1941 unlock_err = got_ref_unlock(symref);
1942 if (unlock_err && err == NULL)
1943 err = unlock_err;
1945 got_ref_close(symref);
1946 return err;
1949 __dead static void
1950 usage_fetch(void)
1952 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1953 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1954 "[remote-repository-name]\n",
1955 getprogname());
1956 exit(1);
1959 static const struct got_error *
1960 delete_missing_ref(struct got_reference *ref,
1961 int verbosity, struct got_repository *repo)
1963 const struct got_error *err = NULL;
1964 struct got_object_id *id = NULL;
1965 char *id_str = NULL;
1967 if (got_ref_is_symbolic(ref)) {
1968 err = got_ref_delete(ref, repo);
1969 if (err)
1970 return err;
1971 if (verbosity >= 0) {
1972 printf("Deleted %s: %s\n",
1973 got_ref_get_name(ref),
1974 got_ref_get_symref_target(ref));
1976 } else {
1977 err = got_ref_resolve(&id, repo, ref);
1978 if (err)
1979 return err;
1980 err = got_object_id_str(&id_str, id);
1981 if (err)
1982 goto done;
1984 err = got_ref_delete(ref, repo);
1985 if (err)
1986 goto done;
1987 if (verbosity >= 0) {
1988 printf("Deleted %s: %s\n",
1989 got_ref_get_name(ref), id_str);
1992 done:
1993 free(id);
1994 free(id_str);
1995 return NULL;
1998 static const struct got_error *
1999 delete_missing_refs(struct got_pathlist_head *their_refs,
2000 struct got_pathlist_head *their_symrefs,
2001 const struct got_remote_repo *remote,
2002 int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL, *unlock_err;
2005 struct got_reflist_head my_refs;
2006 struct got_reflist_entry *re;
2007 struct got_pathlist_entry *pe;
2008 char *remote_namespace = NULL;
2009 char *local_refname = NULL;
2011 TAILQ_INIT(&my_refs);
2013 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2014 == -1)
2015 return got_error_from_errno("asprintf");
2017 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2018 if (err)
2019 goto done;
2021 TAILQ_FOREACH(re, &my_refs, entry) {
2022 const char *refname = got_ref_get_name(re->ref);
2023 const char *their_refname;
2025 if (remote->mirror_references) {
2026 their_refname = refname;
2027 } else {
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;
2041 their_refname = local_refname;
2044 TAILQ_FOREACH(pe, their_refs, entry) {
2045 if (strcmp(their_refname, pe->path) == 0)
2046 break;
2048 if (pe != NULL)
2049 continue;
2051 TAILQ_FOREACH(pe, their_symrefs, entry) {
2052 if (strcmp(their_refname, pe->path) == 0)
2053 break;
2055 if (pe != NULL)
2056 continue;
2058 err = delete_missing_ref(re->ref, verbosity, repo);
2059 if (err)
2060 break;
2062 if (local_refname) {
2063 struct got_reference *ref;
2064 err = got_ref_open(&ref, repo, local_refname, 1);
2065 if (err) {
2066 if (err->code != GOT_ERR_NOT_REF)
2067 break;
2068 free(local_refname);
2069 local_refname = NULL;
2070 continue;
2072 err = delete_missing_ref(ref, verbosity, repo);
2073 if (err)
2074 break;
2075 unlock_err = got_ref_unlock(ref);
2076 got_ref_close(ref);
2077 if (unlock_err && err == NULL) {
2078 err = unlock_err;
2079 break;
2082 free(local_refname);
2083 local_refname = NULL;
2086 done:
2087 free(remote_namespace);
2088 free(local_refname);
2089 return err;
2092 static const struct got_error *
2093 update_wanted_ref(const char *refname, struct got_object_id *id,
2094 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2096 const struct got_error *err, *unlock_err;
2097 char *remote_refname;
2098 struct got_reference *ref;
2100 if (strncmp("refs/", refname, 5) == 0)
2101 refname += 5;
2103 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2104 remote_repo_name, refname) == -1)
2105 return got_error_from_errno("asprintf");
2107 err = got_ref_open(&ref, repo, remote_refname, 1);
2108 if (err) {
2109 if (err->code != GOT_ERR_NOT_REF)
2110 goto done;
2111 err = create_ref(remote_refname, id, verbosity, repo);
2112 } else {
2113 err = update_ref(ref, id, 0, verbosity, repo);
2114 unlock_err = got_ref_unlock(ref);
2115 if (unlock_err && err == NULL)
2116 err = unlock_err;
2117 got_ref_close(ref);
2119 done:
2120 free(remote_refname);
2121 return err;
2124 static const struct got_error *
2125 delete_ref(struct got_repository *repo, struct got_reference *ref)
2127 const struct got_error *err = NULL;
2128 struct got_object_id *id = NULL;
2129 char *id_str = NULL;
2130 const char *target;
2132 if (got_ref_is_symbolic(ref)) {
2133 target = got_ref_get_symref_target(ref);
2134 } else {
2135 err = got_ref_resolve(&id, repo, ref);
2136 if (err)
2137 goto done;
2138 err = got_object_id_str(&id_str, id);
2139 if (err)
2140 goto done;
2141 target = id_str;
2144 err = got_ref_delete(ref, repo);
2145 if (err)
2146 goto done;
2148 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2149 done:
2150 free(id);
2151 free(id_str);
2152 return err;
2155 static const struct got_error *
2156 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2158 const struct got_error *err = NULL;
2159 struct got_reflist_head refs;
2160 struct got_reflist_entry *re;
2161 char *prefix;
2163 TAILQ_INIT(&refs);
2165 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2166 err = got_error_from_errno("asprintf");
2167 goto done;
2169 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2170 if (err)
2171 goto done;
2173 TAILQ_FOREACH(re, &refs, entry)
2174 delete_ref(repo, re->ref);
2175 done:
2176 got_ref_list_free(&refs);
2177 return err;
2180 static const struct got_error *
2181 cmd_fetch(int argc, char *argv[])
2183 const struct got_error *error = NULL, *unlock_err;
2184 char *cwd = NULL, *repo_path = NULL;
2185 const char *remote_name;
2186 char *proto = NULL, *host = NULL, *port = NULL;
2187 char *repo_name = NULL, *server_path = NULL;
2188 const struct got_remote_repo *remotes, *remote = NULL;
2189 int nremotes;
2190 char *id_str = NULL;
2191 struct got_repository *repo = NULL;
2192 struct got_worktree *worktree = NULL;
2193 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2194 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2195 struct got_pathlist_entry *pe;
2196 struct got_object_id *pack_hash = NULL;
2197 int i, ch, fetchfd = -1, fetchstatus;
2198 pid_t fetchpid = -1;
2199 struct got_fetch_progress_arg fpa;
2200 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2201 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2203 TAILQ_INIT(&refs);
2204 TAILQ_INIT(&symrefs);
2205 TAILQ_INIT(&wanted_branches);
2206 TAILQ_INIT(&wanted_refs);
2208 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2209 switch (ch) {
2210 case 'a':
2211 fetch_all_branches = 1;
2212 break;
2213 case 'b':
2214 error = got_pathlist_append(&wanted_branches,
2215 optarg, NULL);
2216 if (error)
2217 return error;
2218 break;
2219 case 'd':
2220 delete_refs = 1;
2221 break;
2222 case 'l':
2223 list_refs_only = 1;
2224 break;
2225 case 'r':
2226 repo_path = realpath(optarg, NULL);
2227 if (repo_path == NULL)
2228 return got_error_from_errno2("realpath",
2229 optarg);
2230 got_path_strip_trailing_slashes(repo_path);
2231 break;
2232 case 't':
2233 replace_tags = 1;
2234 break;
2235 case 'v':
2236 if (verbosity < 0)
2237 verbosity = 0;
2238 else if (verbosity < 3)
2239 verbosity++;
2240 break;
2241 case 'q':
2242 verbosity = -1;
2243 break;
2244 case 'R':
2245 error = got_pathlist_append(&wanted_refs,
2246 optarg, NULL);
2247 if (error)
2248 return error;
2249 break;
2250 case 'X':
2251 delete_remote = 1;
2252 break;
2253 default:
2254 usage_fetch();
2255 break;
2258 argc -= optind;
2259 argv += optind;
2261 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2262 option_conflict('a', 'b');
2263 if (list_refs_only) {
2264 if (!TAILQ_EMPTY(&wanted_branches))
2265 option_conflict('l', 'b');
2266 if (fetch_all_branches)
2267 option_conflict('l', 'a');
2268 if (delete_refs)
2269 option_conflict('l', 'd');
2270 if (delete_remote)
2271 option_conflict('l', 'X');
2273 if (delete_remote) {
2274 if (fetch_all_branches)
2275 option_conflict('X', 'a');
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('X', 'b');
2278 if (delete_refs)
2279 option_conflict('X', 'd');
2280 if (replace_tags)
2281 option_conflict('X', 't');
2282 if (!TAILQ_EMPTY(&wanted_refs))
2283 option_conflict('X', 'R');
2286 if (argc == 0) {
2287 if (delete_remote)
2288 errx(1, "-X option requires a remote name");
2289 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2290 } else if (argc == 1)
2291 remote_name = argv[0];
2292 else
2293 usage_fetch();
2295 cwd = getcwd(NULL, 0);
2296 if (cwd == NULL) {
2297 error = got_error_from_errno("getcwd");
2298 goto done;
2301 if (repo_path == NULL) {
2302 error = got_worktree_open(&worktree, cwd);
2303 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2304 goto done;
2305 else
2306 error = NULL;
2307 if (worktree) {
2308 repo_path =
2309 strdup(got_worktree_get_repo_path(worktree));
2310 if (repo_path == NULL)
2311 error = got_error_from_errno("strdup");
2312 if (error)
2313 goto done;
2314 } else {
2315 repo_path = strdup(cwd);
2316 if (repo_path == NULL) {
2317 error = got_error_from_errno("strdup");
2318 goto done;
2323 error = got_repo_open(&repo, repo_path, NULL);
2324 if (error)
2325 goto done;
2327 if (delete_remote) {
2328 error = delete_refs_for_remote(repo, remote_name);
2329 goto done; /* nothing else to do */
2332 if (worktree) {
2333 worktree_conf = got_worktree_get_gotconfig(worktree);
2334 if (worktree_conf) {
2335 got_gotconfig_get_remotes(&nremotes, &remotes,
2336 worktree_conf);
2337 for (i = 0; i < nremotes; i++) {
2338 if (strcmp(remotes[i].name, remote_name) == 0) {
2339 remote = &remotes[i];
2340 break;
2345 if (remote == NULL) {
2346 repo_conf = got_repo_get_gotconfig(repo);
2347 if (repo_conf) {
2348 got_gotconfig_get_remotes(&nremotes, &remotes,
2349 repo_conf);
2350 for (i = 0; i < nremotes; i++) {
2351 if (strcmp(remotes[i].name, remote_name) == 0) {
2352 remote = &remotes[i];
2353 break;
2358 if (remote == NULL) {
2359 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2360 for (i = 0; i < nremotes; i++) {
2361 if (strcmp(remotes[i].name, remote_name) == 0) {
2362 remote = &remotes[i];
2363 break;
2367 if (remote == NULL) {
2368 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2369 goto done;
2372 if (TAILQ_EMPTY(&wanted_branches)) {
2373 if (!fetch_all_branches)
2374 fetch_all_branches = remote->fetch_all_branches;
2375 for (i = 0; i < remote->nfetch_branches; i++) {
2376 got_pathlist_append(&wanted_branches,
2377 remote->fetch_branches[i], NULL);
2380 if (TAILQ_EMPTY(&wanted_refs)) {
2381 for (i = 0; i < remote->nfetch_refs; i++) {
2382 got_pathlist_append(&wanted_refs,
2383 remote->fetch_refs[i], NULL);
2387 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2388 &repo_name, remote->fetch_url);
2389 if (error)
2390 goto done;
2392 if (strcmp(proto, "git") == 0) {
2393 #ifndef PROFILE
2394 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2395 "sendfd dns inet unveil", NULL) == -1)
2396 err(1, "pledge");
2397 #endif
2398 } else if (strcmp(proto, "git+ssh") == 0 ||
2399 strcmp(proto, "ssh") == 0) {
2400 #ifndef PROFILE
2401 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2402 "sendfd unveil", NULL) == -1)
2403 err(1, "pledge");
2404 #endif
2405 } else if (strcmp(proto, "http") == 0 ||
2406 strcmp(proto, "git+http") == 0) {
2407 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2408 goto done;
2409 } else {
2410 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2411 goto done;
2414 error = got_dial_apply_unveil(proto);
2415 if (error)
2416 goto done;
2418 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2419 if (error)
2420 goto done;
2422 if (verbosity >= 0)
2423 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2424 port ? ":" : "", port ? port : "");
2426 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2427 server_path, verbosity);
2428 if (error)
2429 goto done;
2431 fpa.last_scaled_size[0] = '\0';
2432 fpa.last_p_indexed = -1;
2433 fpa.last_p_resolved = -1;
2434 fpa.verbosity = verbosity;
2435 fpa.repo = repo;
2436 fpa.create_configs = 0;
2437 fpa.configs_created = 0;
2438 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2439 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2440 remote->mirror_references, fetch_all_branches, &wanted_branches,
2441 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2442 fetch_progress, &fpa);
2443 if (error)
2444 goto done;
2446 if (list_refs_only) {
2447 error = list_remote_refs(&symrefs, &refs);
2448 goto done;
2451 if (pack_hash == NULL) {
2452 if (verbosity >= 0)
2453 printf("Already up-to-date\n");
2454 } else if (verbosity >= 0) {
2455 error = got_object_id_str(&id_str, pack_hash);
2456 if (error)
2457 goto done;
2458 printf("\nFetched %s.pack\n", id_str);
2459 free(id_str);
2460 id_str = NULL;
2463 /* Update references provided with the pack file. */
2464 TAILQ_FOREACH(pe, &refs, entry) {
2465 const char *refname = pe->path;
2466 struct got_object_id *id = pe->data;
2467 struct got_reference *ref;
2468 char *remote_refname;
2470 if (is_wanted_ref(&wanted_refs, refname) &&
2471 !remote->mirror_references) {
2472 error = update_wanted_ref(refname, id,
2473 remote->name, verbosity, repo);
2474 if (error)
2475 goto done;
2476 continue;
2479 if (remote->mirror_references ||
2480 strncmp("refs/tags/", refname, 10) == 0) {
2481 error = got_ref_open(&ref, repo, refname, 1);
2482 if (error) {
2483 if (error->code != GOT_ERR_NOT_REF)
2484 goto done;
2485 error = create_ref(refname, id, verbosity,
2486 repo);
2487 if (error)
2488 goto done;
2489 } else {
2490 error = update_ref(ref, id, replace_tags,
2491 verbosity, repo);
2492 unlock_err = got_ref_unlock(ref);
2493 if (unlock_err && error == NULL)
2494 error = unlock_err;
2495 got_ref_close(ref);
2496 if (error)
2497 goto done;
2499 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2500 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2501 remote_name, refname + 11) == -1) {
2502 error = got_error_from_errno("asprintf");
2503 goto done;
2506 error = got_ref_open(&ref, repo, remote_refname, 1);
2507 if (error) {
2508 if (error->code != GOT_ERR_NOT_REF)
2509 goto done;
2510 error = create_ref(remote_refname, id,
2511 verbosity, repo);
2512 if (error)
2513 goto done;
2514 } else {
2515 error = update_ref(ref, id, replace_tags,
2516 verbosity, repo);
2517 unlock_err = got_ref_unlock(ref);
2518 if (unlock_err && error == NULL)
2519 error = unlock_err;
2520 got_ref_close(ref);
2521 if (error)
2522 goto done;
2525 /* Also create a local branch if none exists yet. */
2526 error = got_ref_open(&ref, repo, refname, 1);
2527 if (error) {
2528 if (error->code != GOT_ERR_NOT_REF)
2529 goto done;
2530 error = create_ref(refname, id, verbosity,
2531 repo);
2532 if (error)
2533 goto done;
2534 } else {
2535 unlock_err = got_ref_unlock(ref);
2536 if (unlock_err && error == NULL)
2537 error = unlock_err;
2538 got_ref_close(ref);
2542 if (delete_refs) {
2543 error = delete_missing_refs(&refs, &symrefs, remote,
2544 verbosity, repo);
2545 if (error)
2546 goto done;
2549 if (!remote->mirror_references) {
2550 /* Update remote HEAD reference if the server provided one. */
2551 TAILQ_FOREACH(pe, &symrefs, entry) {
2552 struct got_reference *target_ref;
2553 const char *refname = pe->path;
2554 const char *target = pe->data;
2555 char *remote_refname = NULL, *remote_target = NULL;
2557 if (strcmp(refname, GOT_REF_HEAD) != 0)
2558 continue;
2560 if (strncmp("refs/heads/", target, 11) != 0)
2561 continue;
2563 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2564 remote->name, refname) == -1) {
2565 error = got_error_from_errno("asprintf");
2566 goto done;
2568 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2569 remote->name, target + 11) == -1) {
2570 error = got_error_from_errno("asprintf");
2571 free(remote_refname);
2572 goto done;
2575 error = got_ref_open(&target_ref, repo, remote_target,
2576 0);
2577 if (error) {
2578 free(remote_refname);
2579 free(remote_target);
2580 if (error->code == GOT_ERR_NOT_REF) {
2581 error = NULL;
2582 continue;
2584 goto done;
2586 error = update_symref(remote_refname, target_ref,
2587 verbosity, repo);
2588 free(remote_refname);
2589 free(remote_target);
2590 got_ref_close(target_ref);
2591 if (error)
2592 goto done;
2595 done:
2596 if (fetchpid > 0) {
2597 if (kill(fetchpid, SIGTERM) == -1)
2598 error = got_error_from_errno("kill");
2599 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2600 error = got_error_from_errno("waitpid");
2602 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2603 error = got_error_from_errno("close");
2604 if (repo) {
2605 const struct got_error *close_err = got_repo_close(repo);
2606 if (error == NULL)
2607 error = close_err;
2609 if (worktree)
2610 got_worktree_close(worktree);
2611 TAILQ_FOREACH(pe, &refs, entry) {
2612 free((void *)pe->path);
2613 free(pe->data);
2615 got_pathlist_free(&refs);
2616 TAILQ_FOREACH(pe, &symrefs, entry) {
2617 free((void *)pe->path);
2618 free(pe->data);
2620 got_pathlist_free(&symrefs);
2621 got_pathlist_free(&wanted_branches);
2622 got_pathlist_free(&wanted_refs);
2623 free(id_str);
2624 free(cwd);
2625 free(repo_path);
2626 free(pack_hash);
2627 free(proto);
2628 free(host);
2629 free(port);
2630 free(server_path);
2631 free(repo_name);
2632 return error;
2636 __dead static void
2637 usage_checkout(void)
2639 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2640 "[-p prefix] [-q] repository-path [worktree-path]\n",
2641 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;
2658 int verbosity;
2661 static const struct got_error *
2662 checkout_progress(void *arg, unsigned char status, const char *path)
2664 struct got_checkout_progress_arg *a = arg;
2666 /* Base commit bump happens silently. */
2667 if (status == GOT_STATUS_BUMP_BASE)
2668 return NULL;
2670 if (status == GOT_STATUS_BASE_REF_ERR) {
2671 a->had_base_commit_ref_error = 1;
2672 return NULL;
2675 while (path[0] == '/')
2676 path++;
2678 if (a->verbosity >= 0)
2679 printf("%c %s/%s\n", status, a->worktree_path, path);
2681 return NULL;
2684 static const struct got_error *
2685 check_cancelled(void *arg)
2687 if (sigint_received || sigpipe_received)
2688 return got_error(GOT_ERR_CANCELLED);
2689 return NULL;
2692 static const struct got_error *
2693 check_linear_ancestry(struct got_object_id *commit_id,
2694 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2695 struct got_repository *repo)
2697 const struct got_error *err = NULL;
2698 struct got_object_id *yca_id;
2700 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2701 commit_id, base_commit_id, repo, check_cancelled, NULL);
2702 if (err)
2703 return err;
2705 if (yca_id == NULL)
2706 return got_error(GOT_ERR_ANCESTRY);
2709 * Require a straight line of history between the target commit
2710 * and the work tree's base commit.
2712 * Non-linear situations such as this require a rebase:
2714 * (commit) D F (base_commit)
2715 * \ /
2716 * C E
2717 * \ /
2718 * B (yca)
2719 * |
2720 * A
2722 * 'got update' only handles linear cases:
2723 * Update forwards in time: A (base/yca) - B - C - D (commit)
2724 * Update backwards in time: D (base) - C - B - A (commit/yca)
2726 if (allow_forwards_in_time_only) {
2727 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2728 return got_error(GOT_ERR_ANCESTRY);
2729 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2730 got_object_id_cmp(base_commit_id, yca_id) != 0)
2731 return got_error(GOT_ERR_ANCESTRY);
2733 free(yca_id);
2734 return NULL;
2737 static const struct got_error *
2738 check_same_branch(struct got_object_id *commit_id,
2739 struct got_reference *head_ref, struct got_object_id *yca_id,
2740 struct got_repository *repo)
2742 const struct got_error *err = NULL;
2743 struct got_commit_graph *graph = NULL;
2744 struct got_object_id *head_commit_id = NULL;
2745 int is_same_branch = 0;
2747 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2748 if (err)
2749 goto done;
2751 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2752 is_same_branch = 1;
2753 goto done;
2755 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2756 is_same_branch = 1;
2757 goto done;
2760 err = got_commit_graph_open(&graph, "/", 1);
2761 if (err)
2762 goto done;
2764 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2765 check_cancelled, NULL);
2766 if (err)
2767 goto done;
2769 for (;;) {
2770 struct got_object_id *id;
2771 err = got_commit_graph_iter_next(&id, graph, repo,
2772 check_cancelled, NULL);
2773 if (err) {
2774 if (err->code == GOT_ERR_ITER_COMPLETED)
2775 err = NULL;
2776 break;
2779 if (id) {
2780 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2781 break;
2782 if (got_object_id_cmp(id, commit_id) == 0) {
2783 is_same_branch = 1;
2784 break;
2788 done:
2789 if (graph)
2790 got_commit_graph_close(graph);
2791 free(head_commit_id);
2792 if (!err && !is_same_branch)
2793 err = got_error(GOT_ERR_ANCESTRY);
2794 return err;
2797 static const struct got_error *
2798 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2800 static char msg[512];
2801 const char *branch_name;
2803 if (got_ref_is_symbolic(ref))
2804 branch_name = got_ref_get_symref_target(ref);
2805 else
2806 branch_name = got_ref_get_name(ref);
2808 if (strncmp("refs/heads/", branch_name, 11) == 0)
2809 branch_name += 11;
2811 snprintf(msg, sizeof(msg),
2812 "target commit is not contained in branch '%s'; "
2813 "the branch to use must be specified with -b; "
2814 "if necessary a new branch can be created for "
2815 "this commit with 'got branch -c %s BRANCH_NAME'",
2816 branch_name, commit_id_str);
2818 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2821 static const struct got_error *
2822 cmd_checkout(int argc, char *argv[])
2824 const struct got_error *error = NULL;
2825 struct got_repository *repo = NULL;
2826 struct got_reference *head_ref = NULL, *ref = NULL;
2827 struct got_worktree *worktree = NULL;
2828 char *repo_path = NULL;
2829 char *worktree_path = NULL;
2830 const char *path_prefix = "";
2831 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2832 char *commit_id_str = NULL;
2833 struct got_object_id *commit_id = NULL;
2834 char *cwd = NULL;
2835 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2836 struct got_pathlist_head paths;
2837 struct got_checkout_progress_arg cpa;
2839 TAILQ_INIT(&paths);
2841 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2842 switch (ch) {
2843 case 'b':
2844 branch_name = optarg;
2845 break;
2846 case 'c':
2847 commit_id_str = strdup(optarg);
2848 if (commit_id_str == NULL)
2849 return got_error_from_errno("strdup");
2850 break;
2851 case 'E':
2852 allow_nonempty = 1;
2853 break;
2854 case 'p':
2855 path_prefix = optarg;
2856 break;
2857 case 'q':
2858 verbosity = -1;
2859 break;
2860 default:
2861 usage_checkout();
2862 /* NOTREACHED */
2866 argc -= optind;
2867 argv += optind;
2869 #ifndef PROFILE
2870 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2871 "unveil", NULL) == -1)
2872 err(1, "pledge");
2873 #endif
2874 if (argc == 1) {
2875 char *base, *dotgit;
2876 const char *path;
2877 repo_path = realpath(argv[0], NULL);
2878 if (repo_path == NULL)
2879 return got_error_from_errno2("realpath", argv[0]);
2880 cwd = getcwd(NULL, 0);
2881 if (cwd == NULL) {
2882 error = got_error_from_errno("getcwd");
2883 goto done;
2885 if (path_prefix[0])
2886 path = path_prefix;
2887 else
2888 path = repo_path;
2889 error = got_path_basename(&base, path);
2890 if (error)
2891 goto done;
2892 dotgit = strstr(base, ".git");
2893 if (dotgit)
2894 *dotgit = '\0';
2895 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2896 error = got_error_from_errno("asprintf");
2897 free(base);
2898 goto done;
2900 free(base);
2901 } else if (argc == 2) {
2902 repo_path = realpath(argv[0], NULL);
2903 if (repo_path == NULL) {
2904 error = got_error_from_errno2("realpath", argv[0]);
2905 goto done;
2907 worktree_path = realpath(argv[1], NULL);
2908 if (worktree_path == NULL) {
2909 if (errno != ENOENT) {
2910 error = got_error_from_errno2("realpath",
2911 argv[1]);
2912 goto done;
2914 worktree_path = strdup(argv[1]);
2915 if (worktree_path == NULL) {
2916 error = got_error_from_errno("strdup");
2917 goto done;
2920 } else
2921 usage_checkout();
2923 got_path_strip_trailing_slashes(repo_path);
2924 got_path_strip_trailing_slashes(worktree_path);
2926 error = got_repo_open(&repo, repo_path, NULL);
2927 if (error != NULL)
2928 goto done;
2930 /* Pre-create work tree path for unveil(2) */
2931 error = got_path_mkdir(worktree_path);
2932 if (error) {
2933 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2934 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2935 goto done;
2936 if (!allow_nonempty &&
2937 !got_path_dir_is_empty(worktree_path)) {
2938 error = got_error_path(worktree_path,
2939 GOT_ERR_DIR_NOT_EMPTY);
2940 goto done;
2944 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2945 if (error)
2946 goto done;
2948 error = got_ref_open(&head_ref, repo, branch_name, 0);
2949 if (error != NULL)
2950 goto done;
2952 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2953 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2954 goto done;
2956 error = got_worktree_open(&worktree, worktree_path);
2957 if (error != NULL)
2958 goto done;
2960 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2961 path_prefix);
2962 if (error != NULL)
2963 goto done;
2964 if (!same_path_prefix) {
2965 error = got_error(GOT_ERR_PATH_PREFIX);
2966 goto done;
2969 if (commit_id_str) {
2970 struct got_reflist_head refs;
2971 TAILQ_INIT(&refs);
2972 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2973 NULL);
2974 if (error)
2975 goto done;
2976 error = got_repo_match_object_id(&commit_id, NULL,
2977 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2978 got_ref_list_free(&refs);
2979 if (error)
2980 goto done;
2981 error = check_linear_ancestry(commit_id,
2982 got_worktree_get_base_commit_id(worktree), 0, repo);
2983 if (error != NULL) {
2984 free(commit_id);
2985 if (error->code == GOT_ERR_ANCESTRY) {
2986 error = checkout_ancestry_error(
2987 head_ref, commit_id_str);
2989 goto done;
2991 error = check_same_branch(commit_id, head_ref, NULL, repo);
2992 if (error) {
2993 if (error->code == GOT_ERR_ANCESTRY) {
2994 error = checkout_ancestry_error(
2995 head_ref, commit_id_str);
2997 goto done;
2999 error = got_worktree_set_base_commit_id(worktree, repo,
3000 commit_id);
3001 if (error)
3002 goto done;
3003 /* Expand potentially abbreviated commit ID string. */
3004 free(commit_id_str);
3005 error = got_object_id_str(&commit_id_str, commit_id);
3006 if (error)
3007 goto done;
3008 } else {
3009 commit_id = got_object_id_dup(
3010 got_worktree_get_base_commit_id(worktree));
3011 if (commit_id == NULL) {
3012 error = got_error_from_errno("got_object_id_dup");
3013 goto done;
3015 error = got_object_id_str(&commit_id_str, commit_id);
3016 if (error)
3017 goto done;
3020 error = got_pathlist_append(&paths, "", NULL);
3021 if (error)
3022 goto done;
3023 cpa.worktree_path = worktree_path;
3024 cpa.had_base_commit_ref_error = 0;
3025 cpa.verbosity = verbosity;
3026 error = got_worktree_checkout_files(worktree, &paths, repo,
3027 checkout_progress, &cpa, check_cancelled, NULL);
3028 if (error != NULL)
3029 goto done;
3031 if (got_ref_is_symbolic(head_ref)) {
3032 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3033 if (error)
3034 goto done;
3035 refname = got_ref_get_name(ref);
3036 } else
3037 refname = got_ref_get_name(head_ref);
3038 printf("Checked out %s: %s\n", refname, commit_id_str);
3039 printf("Now shut up and hack\n");
3040 if (cpa.had_base_commit_ref_error)
3041 show_worktree_base_ref_warning();
3042 done:
3043 if (head_ref)
3044 got_ref_close(head_ref);
3045 if (ref)
3046 got_ref_close(ref);
3047 got_pathlist_free(&paths);
3048 free(commit_id_str);
3049 free(commit_id);
3050 free(repo_path);
3051 free(worktree_path);
3052 free(cwd);
3053 return error;
3056 struct got_update_progress_arg {
3057 int did_something;
3058 int conflicts;
3059 int obstructed;
3060 int not_updated;
3061 int verbosity;
3064 void
3065 print_update_progress_stats(struct got_update_progress_arg *upa)
3067 if (!upa->did_something)
3068 return;
3070 if (upa->conflicts > 0)
3071 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3072 if (upa->obstructed > 0)
3073 printf("File paths obstructed by a non-regular file: %d\n",
3074 upa->obstructed);
3075 if (upa->not_updated > 0)
3076 printf("Files not updated because of existing merge "
3077 "conflicts: %d\n", upa->not_updated);
3080 __dead static void
3081 usage_update(void)
3083 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3084 "[path ...]\n",
3085 getprogname());
3086 exit(1);
3089 static const struct got_error *
3090 update_progress(void *arg, unsigned char status, const char *path)
3092 struct got_update_progress_arg *upa = arg;
3094 if (status == GOT_STATUS_EXISTS ||
3095 status == GOT_STATUS_BASE_REF_ERR)
3096 return NULL;
3098 upa->did_something = 1;
3100 /* Base commit bump happens silently. */
3101 if (status == GOT_STATUS_BUMP_BASE)
3102 return NULL;
3104 if (status == GOT_STATUS_CONFLICT)
3105 upa->conflicts++;
3106 if (status == GOT_STATUS_OBSTRUCTED)
3107 upa->obstructed++;
3108 if (status == GOT_STATUS_CANNOT_UPDATE)
3109 upa->not_updated++;
3111 while (path[0] == '/')
3112 path++;
3113 if (upa->verbosity >= 0)
3114 printf("%c %s\n", status, path);
3116 return NULL;
3119 static const struct got_error *
3120 switch_head_ref(struct got_reference *head_ref,
3121 struct got_object_id *commit_id, struct got_worktree *worktree,
3122 struct got_repository *repo)
3124 const struct got_error *err = NULL;
3125 char *base_id_str;
3126 int ref_has_moved = 0;
3128 /* Trivial case: switching between two different references. */
3129 if (strcmp(got_ref_get_name(head_ref),
3130 got_worktree_get_head_ref_name(worktree)) != 0) {
3131 printf("Switching work tree from %s to %s\n",
3132 got_worktree_get_head_ref_name(worktree),
3133 got_ref_get_name(head_ref));
3134 return got_worktree_set_head_ref(worktree, head_ref);
3137 err = check_linear_ancestry(commit_id,
3138 got_worktree_get_base_commit_id(worktree), 0, repo);
3139 if (err) {
3140 if (err->code != GOT_ERR_ANCESTRY)
3141 return err;
3142 ref_has_moved = 1;
3144 if (!ref_has_moved)
3145 return NULL;
3147 /* Switching to a rebased branch with the same reference name. */
3148 err = got_object_id_str(&base_id_str,
3149 got_worktree_get_base_commit_id(worktree));
3150 if (err)
3151 return err;
3152 printf("Reference %s now points at a different branch\n",
3153 got_worktree_get_head_ref_name(worktree));
3154 printf("Switching work tree from %s to %s\n", base_id_str,
3155 got_worktree_get_head_ref_name(worktree));
3156 return NULL;
3159 static const struct got_error *
3160 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3162 const struct got_error *err;
3163 int in_progress;
3165 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3166 if (err)
3167 return err;
3168 if (in_progress)
3169 return got_error(GOT_ERR_REBASING);
3171 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3172 if (err)
3173 return err;
3174 if (in_progress)
3175 return got_error(GOT_ERR_HISTEDIT_BUSY);
3177 return NULL;
3180 static const struct got_error *
3181 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3182 char *argv[], struct got_worktree *worktree)
3184 const struct got_error *err = NULL;
3185 char *path;
3186 int i;
3188 if (argc == 0) {
3189 path = strdup("");
3190 if (path == NULL)
3191 return got_error_from_errno("strdup");
3192 return got_pathlist_append(paths, path, NULL);
3195 for (i = 0; i < argc; i++) {
3196 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3197 if (err)
3198 break;
3199 err = got_pathlist_append(paths, path, NULL);
3200 if (err) {
3201 free(path);
3202 break;
3206 return err;
3209 static const struct got_error *
3210 wrap_not_worktree_error(const struct got_error *orig_err,
3211 const char *cmdname, const char *path)
3213 const struct got_error *err;
3214 struct got_repository *repo;
3215 static char msg[512];
3217 err = got_repo_open(&repo, path, NULL);
3218 if (err)
3219 return orig_err;
3221 snprintf(msg, sizeof(msg),
3222 "'got %s' needs a work tree in addition to a git repository\n"
3223 "Work trees can be checked out from this Git repository with "
3224 "'got checkout'.\n"
3225 "The got(1) manual page contains more information.", cmdname);
3226 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3227 got_repo_close(repo);
3228 return err;
3231 static const struct got_error *
3232 cmd_update(int argc, char *argv[])
3234 const struct got_error *error = NULL;
3235 struct got_repository *repo = NULL;
3236 struct got_worktree *worktree = NULL;
3237 char *worktree_path = NULL;
3238 struct got_object_id *commit_id = NULL;
3239 char *commit_id_str = NULL;
3240 const char *branch_name = NULL;
3241 struct got_reference *head_ref = NULL;
3242 struct got_pathlist_head paths;
3243 struct got_pathlist_entry *pe;
3244 int ch, verbosity = 0;
3245 struct got_update_progress_arg upa;
3247 TAILQ_INIT(&paths);
3249 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3250 switch (ch) {
3251 case 'b':
3252 branch_name = optarg;
3253 break;
3254 case 'c':
3255 commit_id_str = strdup(optarg);
3256 if (commit_id_str == NULL)
3257 return got_error_from_errno("strdup");
3258 break;
3259 case 'q':
3260 verbosity = -1;
3261 break;
3262 default:
3263 usage_update();
3264 /* NOTREACHED */
3268 argc -= optind;
3269 argv += optind;
3271 #ifndef PROFILE
3272 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3273 "unveil", NULL) == -1)
3274 err(1, "pledge");
3275 #endif
3276 worktree_path = getcwd(NULL, 0);
3277 if (worktree_path == NULL) {
3278 error = got_error_from_errno("getcwd");
3279 goto done;
3281 error = got_worktree_open(&worktree, worktree_path);
3282 if (error) {
3283 if (error->code == GOT_ERR_NOT_WORKTREE)
3284 error = wrap_not_worktree_error(error, "update",
3285 worktree_path);
3286 goto done;
3289 error = check_rebase_or_histedit_in_progress(worktree);
3290 if (error)
3291 goto done;
3293 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3294 NULL);
3295 if (error != NULL)
3296 goto done;
3298 error = apply_unveil(got_repo_get_path(repo), 0,
3299 got_worktree_get_root_path(worktree));
3300 if (error)
3301 goto done;
3303 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3304 if (error)
3305 goto done;
3307 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3308 got_worktree_get_head_ref_name(worktree), 0);
3309 if (error != NULL)
3310 goto done;
3311 if (commit_id_str == NULL) {
3312 error = got_ref_resolve(&commit_id, repo, head_ref);
3313 if (error != NULL)
3314 goto done;
3315 error = got_object_id_str(&commit_id_str, commit_id);
3316 if (error != NULL)
3317 goto done;
3318 } else {
3319 struct got_reflist_head refs;
3320 TAILQ_INIT(&refs);
3321 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3322 NULL);
3323 if (error)
3324 goto done;
3325 error = got_repo_match_object_id(&commit_id, NULL,
3326 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3327 got_ref_list_free(&refs);
3328 free(commit_id_str);
3329 commit_id_str = NULL;
3330 if (error)
3331 goto done;
3332 error = got_object_id_str(&commit_id_str, commit_id);
3333 if (error)
3334 goto done;
3337 if (branch_name) {
3338 struct got_object_id *head_commit_id;
3339 TAILQ_FOREACH(pe, &paths, entry) {
3340 if (pe->path_len == 0)
3341 continue;
3342 error = got_error_msg(GOT_ERR_BAD_PATH,
3343 "switching between branches requires that "
3344 "the entire work tree gets updated");
3345 goto done;
3347 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3348 if (error)
3349 goto done;
3350 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3351 repo);
3352 free(head_commit_id);
3353 if (error != NULL)
3354 goto done;
3355 error = check_same_branch(commit_id, head_ref, NULL, repo);
3356 if (error)
3357 goto done;
3358 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3359 if (error)
3360 goto done;
3361 } else {
3362 error = check_linear_ancestry(commit_id,
3363 got_worktree_get_base_commit_id(worktree), 0, repo);
3364 if (error != NULL) {
3365 if (error->code == GOT_ERR_ANCESTRY)
3366 error = got_error(GOT_ERR_BRANCH_MOVED);
3367 goto done;
3369 error = check_same_branch(commit_id, head_ref, NULL, repo);
3370 if (error)
3371 goto done;
3374 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3375 commit_id) != 0) {
3376 error = got_worktree_set_base_commit_id(worktree, repo,
3377 commit_id);
3378 if (error)
3379 goto done;
3382 memset(&upa, 0, sizeof(upa));
3383 upa.verbosity = verbosity;
3384 error = got_worktree_checkout_files(worktree, &paths, repo,
3385 update_progress, &upa, check_cancelled, NULL);
3386 if (error != NULL)
3387 goto done;
3389 if (upa.did_something)
3390 printf("Updated to commit %s\n", commit_id_str);
3391 else
3392 printf("Already up-to-date\n");
3393 print_update_progress_stats(&upa);
3394 done:
3395 free(worktree_path);
3396 TAILQ_FOREACH(pe, &paths, entry)
3397 free((char *)pe->path);
3398 got_pathlist_free(&paths);
3399 free(commit_id);
3400 free(commit_id_str);
3401 return error;
3404 static const struct got_error *
3405 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3406 const char *path, int diff_context, int ignore_whitespace,
3407 int force_text_diff, struct got_repository *repo)
3409 const struct got_error *err = NULL;
3410 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3412 if (blob_id1) {
3413 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3414 if (err)
3415 goto done;
3418 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3419 if (err)
3420 goto done;
3422 while (path[0] == '/')
3423 path++;
3424 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3425 diff_context, ignore_whitespace, force_text_diff, stdout);
3426 done:
3427 if (blob1)
3428 got_object_blob_close(blob1);
3429 got_object_blob_close(blob2);
3430 return err;
3433 static const struct got_error *
3434 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3435 const char *path, int diff_context, int ignore_whitespace,
3436 int force_text_diff, struct got_repository *repo)
3438 const struct got_error *err = NULL;
3439 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3440 struct got_diff_blob_output_unidiff_arg arg;
3442 if (tree_id1) {
3443 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3444 if (err)
3445 goto done;
3448 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3449 if (err)
3450 goto done;
3452 arg.diff_context = diff_context;
3453 arg.ignore_whitespace = ignore_whitespace;
3454 arg.force_text_diff = force_text_diff;
3455 arg.outfile = stdout;
3456 arg.line_offsets = NULL;
3457 arg.nlines = 0;
3458 while (path[0] == '/')
3459 path++;
3460 err = got_diff_tree(tree1, tree2, path, path, repo,
3461 got_diff_blob_output_unidiff, &arg, 1);
3462 done:
3463 if (tree1)
3464 got_object_tree_close(tree1);
3465 if (tree2)
3466 got_object_tree_close(tree2);
3467 return err;
3470 static const struct got_error *
3471 get_changed_paths(struct got_pathlist_head *paths,
3472 struct got_commit_object *commit, struct got_repository *repo)
3474 const struct got_error *err = NULL;
3475 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3476 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3477 struct got_object_qid *qid;
3479 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3480 if (qid != NULL) {
3481 struct got_commit_object *pcommit;
3482 err = got_object_open_as_commit(&pcommit, repo,
3483 qid->id);
3484 if (err)
3485 return err;
3487 tree_id1 = got_object_id_dup(
3488 got_object_commit_get_tree_id(pcommit));
3489 if (tree_id1 == NULL) {
3490 got_object_commit_close(pcommit);
3491 return got_error_from_errno("got_object_id_dup");
3493 got_object_commit_close(pcommit);
3497 if (tree_id1) {
3498 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3499 if (err)
3500 goto done;
3503 tree_id2 = got_object_commit_get_tree_id(commit);
3504 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3505 if (err)
3506 goto done;
3508 err = got_diff_tree(tree1, tree2, "", "", repo,
3509 got_diff_tree_collect_changed_paths, paths, 0);
3510 done:
3511 if (tree1)
3512 got_object_tree_close(tree1);
3513 if (tree2)
3514 got_object_tree_close(tree2);
3515 free(tree_id1);
3516 return err;
3519 static const struct got_error *
3520 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3521 const char *path, int diff_context, struct got_repository *repo)
3523 const struct got_error *err = NULL;
3524 struct got_commit_object *pcommit = NULL;
3525 char *id_str1 = NULL, *id_str2 = NULL;
3526 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3527 struct got_object_qid *qid;
3529 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3530 if (qid != NULL) {
3531 err = got_object_open_as_commit(&pcommit, repo,
3532 qid->id);
3533 if (err)
3534 return err;
3537 if (path && path[0] != '\0') {
3538 int obj_type;
3539 err = got_object_id_by_path(&obj_id2, repo, id, path);
3540 if (err)
3541 goto done;
3542 err = got_object_id_str(&id_str2, obj_id2);
3543 if (err) {
3544 free(obj_id2);
3545 goto done;
3547 if (pcommit) {
3548 err = got_object_id_by_path(&obj_id1, repo,
3549 qid->id, path);
3550 if (err) {
3551 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3552 free(obj_id2);
3553 goto done;
3555 } else {
3556 err = got_object_id_str(&id_str1, obj_id1);
3557 if (err) {
3558 free(obj_id2);
3559 goto done;
3563 err = got_object_get_type(&obj_type, repo, obj_id2);
3564 if (err) {
3565 free(obj_id2);
3566 goto done;
3568 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3569 switch (obj_type) {
3570 case GOT_OBJ_TYPE_BLOB:
3571 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3572 0, 0, repo);
3573 break;
3574 case GOT_OBJ_TYPE_TREE:
3575 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3576 0, 0, repo);
3577 break;
3578 default:
3579 err = got_error(GOT_ERR_OBJ_TYPE);
3580 break;
3582 free(obj_id1);
3583 free(obj_id2);
3584 } else {
3585 obj_id2 = got_object_commit_get_tree_id(commit);
3586 err = got_object_id_str(&id_str2, obj_id2);
3587 if (err)
3588 goto done;
3589 if (pcommit) {
3590 obj_id1 = got_object_commit_get_tree_id(pcommit);
3591 err = got_object_id_str(&id_str1, obj_id1);
3592 if (err)
3593 goto done;
3595 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3596 id_str2);
3597 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3598 repo);
3600 done:
3601 free(id_str1);
3602 free(id_str2);
3603 if (pcommit)
3604 got_object_commit_close(pcommit);
3605 return err;
3608 static char *
3609 get_datestr(time_t *time, char *datebuf)
3611 struct tm mytm, *tm;
3612 char *p, *s;
3614 tm = gmtime_r(time, &mytm);
3615 if (tm == NULL)
3616 return NULL;
3617 s = asctime_r(tm, datebuf);
3618 if (s == NULL)
3619 return NULL;
3620 p = strchr(s, '\n');
3621 if (p)
3622 *p = '\0';
3623 return s;
3626 static const struct got_error *
3627 match_logmsg(int *have_match, struct got_object_id *id,
3628 struct got_commit_object *commit, regex_t *regex)
3630 const struct got_error *err = NULL;
3631 regmatch_t regmatch;
3632 char *id_str = NULL, *logmsg = NULL;
3634 *have_match = 0;
3636 err = got_object_id_str(&id_str, id);
3637 if (err)
3638 return err;
3640 err = got_object_commit_get_logmsg(&logmsg, commit);
3641 if (err)
3642 goto done;
3644 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3645 *have_match = 1;
3646 done:
3647 free(id_str);
3648 free(logmsg);
3649 return err;
3652 static void
3653 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3654 regex_t *regex)
3656 regmatch_t regmatch;
3657 struct got_pathlist_entry *pe;
3659 *have_match = 0;
3661 TAILQ_FOREACH(pe, changed_paths, entry) {
3662 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3663 *have_match = 1;
3664 break;
3669 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3671 static const struct got_error*
3672 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3673 struct got_object_id *id, struct got_repository *repo)
3675 static const struct got_error *err = NULL;
3676 struct got_reflist_entry *re;
3677 char *s;
3678 const char *name;
3680 *refs_str = NULL;
3682 TAILQ_FOREACH(re, refs, entry) {
3683 struct got_tag_object *tag = NULL;
3684 struct got_object_id *ref_id;
3685 int cmp;
3687 name = got_ref_get_name(re->ref);
3688 if (strcmp(name, GOT_REF_HEAD) == 0)
3689 continue;
3690 if (strncmp(name, "refs/", 5) == 0)
3691 name += 5;
3692 if (strncmp(name, "got/", 4) == 0)
3693 continue;
3694 if (strncmp(name, "heads/", 6) == 0)
3695 name += 6;
3696 if (strncmp(name, "remotes/", 8) == 0) {
3697 name += 8;
3698 s = strstr(name, "/" GOT_REF_HEAD);
3699 if (s != NULL && s[strlen(s)] == '\0')
3700 continue;
3702 err = got_ref_resolve(&ref_id, repo, re->ref);
3703 if (err)
3704 break;
3705 if (strncmp(name, "tags/", 5) == 0) {
3706 err = got_object_open_as_tag(&tag, repo, ref_id);
3707 if (err) {
3708 if (err->code != GOT_ERR_OBJ_TYPE) {
3709 free(ref_id);
3710 break;
3712 /* Ref points at something other than a tag. */
3713 err = NULL;
3714 tag = NULL;
3717 cmp = got_object_id_cmp(tag ?
3718 got_object_tag_get_object_id(tag) : ref_id, id);
3719 free(ref_id);
3720 if (tag)
3721 got_object_tag_close(tag);
3722 if (cmp != 0)
3723 continue;
3724 s = *refs_str;
3725 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3726 s ? ", " : "", name) == -1) {
3727 err = got_error_from_errno("asprintf");
3728 free(s);
3729 *refs_str = NULL;
3730 break;
3732 free(s);
3735 return err;
3738 static const struct got_error *
3739 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3740 struct got_repository *repo, const char *path,
3741 struct got_pathlist_head *changed_paths, int show_patch,
3742 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3743 const char *custom_refs_str)
3745 const struct got_error *err = NULL;
3746 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3747 char datebuf[26];
3748 time_t committer_time;
3749 const char *author, *committer;
3750 char *refs_str = NULL;
3752 err = got_object_id_str(&id_str, id);
3753 if (err)
3754 return err;
3756 if (custom_refs_str == NULL) {
3757 struct got_reflist_head *refs;
3758 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3759 if (refs) {
3760 err = build_refs_str(&refs_str, refs, id, repo);
3761 if (err)
3762 goto done;
3766 printf(GOT_COMMIT_SEP_STR);
3767 if (custom_refs_str)
3768 printf("commit %s (%s)\n", id_str, custom_refs_str);
3769 else
3770 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3771 refs_str ? refs_str : "", refs_str ? ")" : "");
3772 free(id_str);
3773 id_str = NULL;
3774 free(refs_str);
3775 refs_str = NULL;
3776 printf("from: %s\n", got_object_commit_get_author(commit));
3777 committer_time = got_object_commit_get_committer_time(commit);
3778 datestr = get_datestr(&committer_time, datebuf);
3779 if (datestr)
3780 printf("date: %s UTC\n", datestr);
3781 author = got_object_commit_get_author(commit);
3782 committer = got_object_commit_get_committer(commit);
3783 if (strcmp(author, committer) != 0)
3784 printf("via: %s\n", committer);
3785 if (got_object_commit_get_nparents(commit) > 1) {
3786 const struct got_object_id_queue *parent_ids;
3787 struct got_object_qid *qid;
3788 int n = 1;
3789 parent_ids = got_object_commit_get_parent_ids(commit);
3790 STAILQ_FOREACH(qid, parent_ids, entry) {
3791 err = got_object_id_str(&id_str, qid->id);
3792 if (err)
3793 goto done;
3794 printf("parent %d: %s\n", n++, id_str);
3795 free(id_str);
3796 id_str = NULL;
3800 err = got_object_commit_get_logmsg(&logmsg0, commit);
3801 if (err)
3802 goto done;
3804 logmsg = logmsg0;
3805 do {
3806 line = strsep(&logmsg, "\n");
3807 if (line)
3808 printf(" %s\n", line);
3809 } while (line);
3810 free(logmsg0);
3812 if (changed_paths) {
3813 struct got_pathlist_entry *pe;
3814 TAILQ_FOREACH(pe, changed_paths, entry) {
3815 struct got_diff_changed_path *cp = pe->data;
3816 printf(" %c %s\n", cp->status, pe->path);
3818 printf("\n");
3820 if (show_patch) {
3821 err = print_patch(commit, id, path, diff_context, repo);
3822 if (err == 0)
3823 printf("\n");
3826 if (fflush(stdout) != 0 && err == NULL)
3827 err = got_error_from_errno("fflush");
3828 done:
3829 free(id_str);
3830 free(refs_str);
3831 return err;
3834 static const struct got_error *
3835 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3836 struct got_repository *repo, const char *path, int show_changed_paths,
3837 int show_patch, const char *search_pattern, int diff_context, int limit,
3838 int log_branches, int reverse_display_order,
3839 struct got_reflist_object_id_map *refs_idmap)
3841 const struct got_error *err;
3842 struct got_commit_graph *graph;
3843 regex_t regex;
3844 int have_match;
3845 struct got_object_id_queue reversed_commits;
3846 struct got_object_qid *qid;
3847 struct got_commit_object *commit;
3848 struct got_pathlist_head changed_paths;
3849 struct got_pathlist_entry *pe;
3851 STAILQ_INIT(&reversed_commits);
3852 TAILQ_INIT(&changed_paths);
3854 if (search_pattern && regcomp(&regex, search_pattern,
3855 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3856 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3858 err = got_commit_graph_open(&graph, path, !log_branches);
3859 if (err)
3860 return err;
3861 err = got_commit_graph_iter_start(graph, root_id, repo,
3862 check_cancelled, NULL);
3863 if (err)
3864 goto done;
3865 for (;;) {
3866 struct got_object_id *id;
3868 if (sigint_received || sigpipe_received)
3869 break;
3871 err = got_commit_graph_iter_next(&id, graph, repo,
3872 check_cancelled, NULL);
3873 if (err) {
3874 if (err->code == GOT_ERR_ITER_COMPLETED)
3875 err = NULL;
3876 break;
3878 if (id == NULL)
3879 break;
3881 err = got_object_open_as_commit(&commit, repo, id);
3882 if (err)
3883 break;
3885 if (show_changed_paths && !reverse_display_order) {
3886 err = get_changed_paths(&changed_paths, commit, repo);
3887 if (err)
3888 break;
3891 if (search_pattern) {
3892 err = match_logmsg(&have_match, id, commit, &regex);
3893 if (err) {
3894 got_object_commit_close(commit);
3895 break;
3897 if (have_match == 0 && show_changed_paths)
3898 match_changed_paths(&have_match,
3899 &changed_paths, &regex);
3900 if (have_match == 0) {
3901 got_object_commit_close(commit);
3902 TAILQ_FOREACH(pe, &changed_paths, entry) {
3903 free((char *)pe->path);
3904 free(pe->data);
3906 got_pathlist_free(&changed_paths);
3907 continue;
3911 if (reverse_display_order) {
3912 err = got_object_qid_alloc(&qid, id);
3913 if (err)
3914 break;
3915 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3916 got_object_commit_close(commit);
3917 } else {
3918 err = print_commit(commit, id, repo, path,
3919 show_changed_paths ? &changed_paths : NULL,
3920 show_patch, diff_context, refs_idmap, NULL);
3921 got_object_commit_close(commit);
3922 if (err)
3923 break;
3925 if ((limit && --limit == 0) ||
3926 (end_id && got_object_id_cmp(id, end_id) == 0))
3927 break;
3929 TAILQ_FOREACH(pe, &changed_paths, entry) {
3930 free((char *)pe->path);
3931 free(pe->data);
3933 got_pathlist_free(&changed_paths);
3935 if (reverse_display_order) {
3936 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3937 err = got_object_open_as_commit(&commit, repo, qid->id);
3938 if (err)
3939 break;
3940 if (show_changed_paths) {
3941 err = get_changed_paths(&changed_paths,
3942 commit, repo);
3943 if (err)
3944 break;
3946 err = print_commit(commit, qid->id, repo, path,
3947 show_changed_paths ? &changed_paths : NULL,
3948 show_patch, diff_context, refs_idmap, NULL);
3949 got_object_commit_close(commit);
3950 if (err)
3951 break;
3952 TAILQ_FOREACH(pe, &changed_paths, entry) {
3953 free((char *)pe->path);
3954 free(pe->data);
3956 got_pathlist_free(&changed_paths);
3959 done:
3960 while (!STAILQ_EMPTY(&reversed_commits)) {
3961 qid = STAILQ_FIRST(&reversed_commits);
3962 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3963 got_object_qid_free(qid);
3965 TAILQ_FOREACH(pe, &changed_paths, entry) {
3966 free((char *)pe->path);
3967 free(pe->data);
3969 got_pathlist_free(&changed_paths);
3970 if (search_pattern)
3971 regfree(&regex);
3972 got_commit_graph_close(graph);
3973 return err;
3976 __dead static void
3977 usage_log(void)
3979 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3980 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3981 "[-R] [path]\n", getprogname());
3982 exit(1);
3985 static int
3986 get_default_log_limit(void)
3988 const char *got_default_log_limit;
3989 long long n;
3990 const char *errstr;
3992 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3993 if (got_default_log_limit == NULL)
3994 return 0;
3995 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3996 if (errstr != NULL)
3997 return 0;
3998 return n;
4001 static const struct got_error *
4002 cmd_log(int argc, char *argv[])
4004 const struct got_error *error;
4005 struct got_repository *repo = NULL;
4006 struct got_worktree *worktree = NULL;
4007 struct got_object_id *start_id = NULL, *end_id = NULL;
4008 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4009 const char *start_commit = NULL, *end_commit = NULL;
4010 const char *search_pattern = NULL;
4011 int diff_context = -1, ch;
4012 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4013 int reverse_display_order = 0;
4014 const char *errstr;
4015 struct got_reflist_head refs;
4016 struct got_reflist_object_id_map *refs_idmap = NULL;
4018 TAILQ_INIT(&refs);
4020 #ifndef PROFILE
4021 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4022 NULL)
4023 == -1)
4024 err(1, "pledge");
4025 #endif
4027 limit = get_default_log_limit();
4029 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4030 switch (ch) {
4031 case 'p':
4032 show_patch = 1;
4033 break;
4034 case 'P':
4035 show_changed_paths = 1;
4036 break;
4037 case 'c':
4038 start_commit = optarg;
4039 break;
4040 case 'C':
4041 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4042 &errstr);
4043 if (errstr != NULL)
4044 err(1, "-C option %s", errstr);
4045 break;
4046 case 'l':
4047 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4048 if (errstr != NULL)
4049 err(1, "-l option %s", errstr);
4050 break;
4051 case 'b':
4052 log_branches = 1;
4053 break;
4054 case 'r':
4055 repo_path = realpath(optarg, NULL);
4056 if (repo_path == NULL)
4057 return got_error_from_errno2("realpath",
4058 optarg);
4059 got_path_strip_trailing_slashes(repo_path);
4060 break;
4061 case 'R':
4062 reverse_display_order = 1;
4063 break;
4064 case 's':
4065 search_pattern = optarg;
4066 break;
4067 case 'x':
4068 end_commit = optarg;
4069 break;
4070 default:
4071 usage_log();
4072 /* NOTREACHED */
4076 argc -= optind;
4077 argv += optind;
4079 if (diff_context == -1)
4080 diff_context = 3;
4081 else if (!show_patch)
4082 errx(1, "-C requires -p");
4084 cwd = getcwd(NULL, 0);
4085 if (cwd == NULL) {
4086 error = got_error_from_errno("getcwd");
4087 goto done;
4090 if (repo_path == NULL) {
4091 error = got_worktree_open(&worktree, cwd);
4092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4093 goto done;
4094 error = NULL;
4097 if (argc == 1) {
4098 if (worktree) {
4099 error = got_worktree_resolve_path(&path, worktree,
4100 argv[0]);
4101 if (error)
4102 goto done;
4103 } else {
4104 path = strdup(argv[0]);
4105 if (path == NULL) {
4106 error = got_error_from_errno("strdup");
4107 goto done;
4110 } else if (argc != 0)
4111 usage_log();
4113 if (repo_path == NULL) {
4114 repo_path = worktree ?
4115 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4117 if (repo_path == NULL) {
4118 error = got_error_from_errno("strdup");
4119 goto done;
4122 error = got_repo_open(&repo, repo_path, NULL);
4123 if (error != NULL)
4124 goto done;
4126 error = apply_unveil(got_repo_get_path(repo), 1,
4127 worktree ? got_worktree_get_root_path(worktree) : NULL);
4128 if (error)
4129 goto done;
4131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4132 if (error)
4133 goto done;
4135 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4136 if (error)
4137 goto done;
4139 if (start_commit == NULL) {
4140 struct got_reference *head_ref;
4141 struct got_commit_object *commit = NULL;
4142 error = got_ref_open(&head_ref, repo,
4143 worktree ? got_worktree_get_head_ref_name(worktree)
4144 : GOT_REF_HEAD, 0);
4145 if (error != NULL)
4146 goto done;
4147 error = got_ref_resolve(&start_id, repo, head_ref);
4148 got_ref_close(head_ref);
4149 if (error != NULL)
4150 goto done;
4151 error = got_object_open_as_commit(&commit, repo,
4152 start_id);
4153 if (error != NULL)
4154 goto done;
4155 got_object_commit_close(commit);
4156 } else {
4157 error = got_repo_match_object_id(&start_id, NULL,
4158 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4159 if (error != NULL)
4160 goto done;
4162 if (end_commit != NULL) {
4163 error = got_repo_match_object_id(&end_id, NULL,
4164 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4165 if (error != NULL)
4166 goto done;
4169 if (worktree) {
4171 * If a path was specified on the command line it was resolved
4172 * to a path in the work tree above. Prepend the work tree's
4173 * path prefix to obtain the corresponding in-repository path.
4175 if (path) {
4176 const char *prefix;
4177 prefix = got_worktree_get_path_prefix(worktree);
4178 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4179 (path[0] != '\0') ? "/" : "", path) == -1) {
4180 error = got_error_from_errno("asprintf");
4181 goto done;
4184 } else
4185 error = got_repo_map_path(&in_repo_path, repo,
4186 path ? path : "");
4187 if (error != NULL)
4188 goto done;
4189 if (in_repo_path) {
4190 free(path);
4191 path = in_repo_path;
4194 error = print_commits(start_id, end_id, repo, path ? path : "",
4195 show_changed_paths, show_patch, search_pattern, diff_context,
4196 limit, log_branches, reverse_display_order, refs_idmap);
4197 done:
4198 free(path);
4199 free(repo_path);
4200 free(cwd);
4201 if (worktree)
4202 got_worktree_close(worktree);
4203 if (repo) {
4204 const struct got_error *close_err = got_repo_close(repo);
4205 if (error == NULL)
4206 error = close_err;
4208 if (refs_idmap)
4209 got_reflist_object_id_map_free(refs_idmap);
4210 got_ref_list_free(&refs);
4211 return error;
4214 __dead static void
4215 usage_diff(void)
4217 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4218 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4219 exit(1);
4222 struct print_diff_arg {
4223 struct got_repository *repo;
4224 struct got_worktree *worktree;
4225 int diff_context;
4226 const char *id_str;
4227 int header_shown;
4228 int diff_staged;
4229 int ignore_whitespace;
4230 int force_text_diff;
4234 * Create a file which contains the target path of a symlink so we can feed
4235 * it as content to the diff engine.
4237 static const struct got_error *
4238 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4239 const char *abspath)
4241 const struct got_error *err = NULL;
4242 char target_path[PATH_MAX];
4243 ssize_t target_len, outlen;
4245 *fd = -1;
4247 if (dirfd != -1) {
4248 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4249 if (target_len == -1)
4250 return got_error_from_errno2("readlinkat", abspath);
4251 } else {
4252 target_len = readlink(abspath, target_path, PATH_MAX);
4253 if (target_len == -1)
4254 return got_error_from_errno2("readlink", abspath);
4257 *fd = got_opentempfd();
4258 if (*fd == -1)
4259 return got_error_from_errno("got_opentempfd");
4261 outlen = write(*fd, target_path, target_len);
4262 if (outlen == -1) {
4263 err = got_error_from_errno("got_opentempfd");
4264 goto done;
4267 if (lseek(*fd, 0, SEEK_SET) == -1) {
4268 err = got_error_from_errno2("lseek", abspath);
4269 goto done;
4271 done:
4272 if (err) {
4273 close(*fd);
4274 *fd = -1;
4276 return err;
4279 static const struct got_error *
4280 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4281 const char *path, struct got_object_id *blob_id,
4282 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4283 int dirfd, const char *de_name)
4285 struct print_diff_arg *a = arg;
4286 const struct got_error *err = NULL;
4287 struct got_blob_object *blob1 = NULL;
4288 int fd = -1;
4289 FILE *f2 = NULL;
4290 char *abspath = NULL, *label1 = NULL;
4291 struct stat sb;
4293 if (a->diff_staged) {
4294 if (staged_status != GOT_STATUS_MODIFY &&
4295 staged_status != GOT_STATUS_ADD &&
4296 staged_status != GOT_STATUS_DELETE)
4297 return NULL;
4298 } else {
4299 if (staged_status == GOT_STATUS_DELETE)
4300 return NULL;
4301 if (status == GOT_STATUS_NONEXISTENT)
4302 return got_error_set_errno(ENOENT, path);
4303 if (status != GOT_STATUS_MODIFY &&
4304 status != GOT_STATUS_ADD &&
4305 status != GOT_STATUS_DELETE &&
4306 status != GOT_STATUS_CONFLICT)
4307 return NULL;
4310 if (!a->header_shown) {
4311 printf("diff %s %s%s\n", a->id_str,
4312 got_worktree_get_root_path(a->worktree),
4313 a->diff_staged ? " (staged changes)" : "");
4314 a->header_shown = 1;
4317 if (a->diff_staged) {
4318 const char *label1 = NULL, *label2 = NULL;
4319 switch (staged_status) {
4320 case GOT_STATUS_MODIFY:
4321 label1 = path;
4322 label2 = path;
4323 break;
4324 case GOT_STATUS_ADD:
4325 label2 = path;
4326 break;
4327 case GOT_STATUS_DELETE:
4328 label1 = path;
4329 break;
4330 default:
4331 return got_error(GOT_ERR_FILE_STATUS);
4333 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4334 staged_blob_id, label1, label2, a->diff_context,
4335 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4338 if (staged_status == GOT_STATUS_ADD ||
4339 staged_status == GOT_STATUS_MODIFY) {
4340 char *id_str;
4341 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4342 8192);
4343 if (err)
4344 goto done;
4345 err = got_object_id_str(&id_str, staged_blob_id);
4346 if (err)
4347 goto done;
4348 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4349 err = got_error_from_errno("asprintf");
4350 free(id_str);
4351 goto done;
4353 free(id_str);
4354 } else if (status != GOT_STATUS_ADD) {
4355 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4356 if (err)
4357 goto done;
4360 if (status != GOT_STATUS_DELETE) {
4361 if (asprintf(&abspath, "%s/%s",
4362 got_worktree_get_root_path(a->worktree), path) == -1) {
4363 err = got_error_from_errno("asprintf");
4364 goto done;
4367 if (dirfd != -1) {
4368 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4369 if (fd == -1) {
4370 if (errno != ELOOP) {
4371 err = got_error_from_errno2("openat",
4372 abspath);
4373 goto done;
4375 err = get_symlink_target_file(&fd, dirfd,
4376 de_name, abspath);
4377 if (err)
4378 goto done;
4380 } else {
4381 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4382 if (fd == -1) {
4383 if (errno != ELOOP) {
4384 err = got_error_from_errno2("open",
4385 abspath);
4386 goto done;
4388 err = get_symlink_target_file(&fd, dirfd,
4389 de_name, abspath);
4390 if (err)
4391 goto done;
4394 if (fstat(fd, &sb) == -1) {
4395 err = got_error_from_errno2("fstat", abspath);
4396 goto done;
4398 f2 = fdopen(fd, "r");
4399 if (f2 == NULL) {
4400 err = got_error_from_errno2("fdopen", abspath);
4401 goto done;
4403 fd = -1;
4404 } else
4405 sb.st_size = 0;
4407 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4408 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4409 done:
4410 if (blob1)
4411 got_object_blob_close(blob1);
4412 if (f2 && fclose(f2) == EOF && err == NULL)
4413 err = got_error_from_errno("fclose");
4414 if (fd != -1 && close(fd) == -1 && err == NULL)
4415 err = got_error_from_errno("close");
4416 free(abspath);
4417 return err;
4420 static const struct got_error *
4421 cmd_diff(int argc, char *argv[])
4423 const struct got_error *error;
4424 struct got_repository *repo = NULL;
4425 struct got_worktree *worktree = NULL;
4426 char *cwd = NULL, *repo_path = NULL;
4427 struct got_object_id *id1 = NULL, *id2 = NULL;
4428 const char *id_str1 = NULL, *id_str2 = NULL;
4429 char *label1 = NULL, *label2 = NULL;
4430 int type1, type2;
4431 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4432 int force_text_diff = 0;
4433 const char *errstr;
4434 char *path = NULL;
4435 struct got_reflist_head refs;
4437 TAILQ_INIT(&refs);
4439 #ifndef PROFILE
4440 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4441 NULL) == -1)
4442 err(1, "pledge");
4443 #endif
4445 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4446 switch (ch) {
4447 case 'a':
4448 force_text_diff = 1;
4449 break;
4450 case 'C':
4451 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4452 &errstr);
4453 if (errstr != NULL)
4454 err(1, "-C option %s", errstr);
4455 break;
4456 case 'r':
4457 repo_path = realpath(optarg, NULL);
4458 if (repo_path == NULL)
4459 return got_error_from_errno2("realpath",
4460 optarg);
4461 got_path_strip_trailing_slashes(repo_path);
4462 break;
4463 case 's':
4464 diff_staged = 1;
4465 break;
4466 case 'w':
4467 ignore_whitespace = 1;
4468 break;
4469 default:
4470 usage_diff();
4471 /* NOTREACHED */
4475 argc -= optind;
4476 argv += optind;
4478 cwd = getcwd(NULL, 0);
4479 if (cwd == NULL) {
4480 error = got_error_from_errno("getcwd");
4481 goto done;
4483 if (argc <= 1) {
4484 if (repo_path)
4485 errx(1,
4486 "-r option can't be used when diffing a work tree");
4487 error = got_worktree_open(&worktree, cwd);
4488 if (error) {
4489 if (error->code == GOT_ERR_NOT_WORKTREE)
4490 error = wrap_not_worktree_error(error, "diff",
4491 cwd);
4492 goto done;
4494 repo_path = strdup(got_worktree_get_repo_path(worktree));
4495 if (repo_path == NULL) {
4496 error = got_error_from_errno("strdup");
4497 goto done;
4499 if (argc == 1) {
4500 error = got_worktree_resolve_path(&path, worktree,
4501 argv[0]);
4502 if (error)
4503 goto done;
4504 } else {
4505 path = strdup("");
4506 if (path == NULL) {
4507 error = got_error_from_errno("strdup");
4508 goto done;
4511 } else if (argc == 2) {
4512 if (diff_staged)
4513 errx(1, "-s option can't be used when diffing "
4514 "objects in repository");
4515 id_str1 = argv[0];
4516 id_str2 = argv[1];
4517 if (repo_path == NULL) {
4518 error = got_worktree_open(&worktree, cwd);
4519 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4520 goto done;
4521 repo_path = strdup(worktree ?
4522 got_worktree_get_repo_path(worktree) : cwd);
4523 if (repo_path == NULL) {
4524 error = got_error_from_errno("strdup");
4525 goto done;
4528 } else
4529 usage_diff();
4531 error = got_repo_open(&repo, repo_path, NULL);
4532 free(repo_path);
4533 if (error != NULL)
4534 goto done;
4536 error = apply_unveil(got_repo_get_path(repo), 1,
4537 worktree ? got_worktree_get_root_path(worktree) : NULL);
4538 if (error)
4539 goto done;
4541 if (argc <= 1) {
4542 struct print_diff_arg arg;
4543 struct got_pathlist_head paths;
4544 char *id_str;
4546 TAILQ_INIT(&paths);
4548 error = got_object_id_str(&id_str,
4549 got_worktree_get_base_commit_id(worktree));
4550 if (error)
4551 goto done;
4552 arg.repo = repo;
4553 arg.worktree = worktree;
4554 arg.diff_context = diff_context;
4555 arg.id_str = id_str;
4556 arg.header_shown = 0;
4557 arg.diff_staged = diff_staged;
4558 arg.ignore_whitespace = ignore_whitespace;
4559 arg.force_text_diff = force_text_diff;
4561 error = got_pathlist_append(&paths, path, NULL);
4562 if (error)
4563 goto done;
4565 error = got_worktree_status(worktree, &paths, repo, 0,
4566 print_diff, &arg, check_cancelled, NULL);
4567 free(id_str);
4568 got_pathlist_free(&paths);
4569 goto done;
4572 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4573 if (error)
4574 return error;
4576 error = got_repo_match_object_id(&id1, &label1, id_str1,
4577 GOT_OBJ_TYPE_ANY, &refs, repo);
4578 if (error)
4579 goto done;
4581 error = got_repo_match_object_id(&id2, &label2, id_str2,
4582 GOT_OBJ_TYPE_ANY, &refs, repo);
4583 if (error)
4584 goto done;
4586 error = got_object_get_type(&type1, repo, id1);
4587 if (error)
4588 goto done;
4590 error = got_object_get_type(&type2, repo, id2);
4591 if (error)
4592 goto done;
4594 if (type1 != type2) {
4595 error = got_error(GOT_ERR_OBJ_TYPE);
4596 goto done;
4599 switch (type1) {
4600 case GOT_OBJ_TYPE_BLOB:
4601 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4602 NULL, NULL, diff_context, ignore_whitespace,
4603 force_text_diff, repo, stdout);
4604 break;
4605 case GOT_OBJ_TYPE_TREE:
4606 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4607 "", "", diff_context, ignore_whitespace, force_text_diff,
4608 repo, stdout);
4609 break;
4610 case GOT_OBJ_TYPE_COMMIT:
4611 printf("diff %s %s\n", label1, label2);
4612 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4613 diff_context, ignore_whitespace, force_text_diff, repo,
4614 stdout);
4615 break;
4616 default:
4617 error = got_error(GOT_ERR_OBJ_TYPE);
4619 done:
4620 free(label1);
4621 free(label2);
4622 free(id1);
4623 free(id2);
4624 free(path);
4625 if (worktree)
4626 got_worktree_close(worktree);
4627 if (repo) {
4628 const struct got_error *close_err = got_repo_close(repo);
4629 if (error == NULL)
4630 error = close_err;
4632 got_ref_list_free(&refs);
4633 return error;
4636 __dead static void
4637 usage_blame(void)
4639 fprintf(stderr,
4640 "usage: %s blame [-c commit] [-r repository-path] path\n",
4641 getprogname());
4642 exit(1);
4645 struct blame_line {
4646 int annotated;
4647 char *id_str;
4648 char *committer;
4649 char datebuf[11]; /* YYYY-MM-DD + NUL */
4652 struct blame_cb_args {
4653 struct blame_line *lines;
4654 int nlines;
4655 int nlines_prec;
4656 int lineno_cur;
4657 off_t *line_offsets;
4658 FILE *f;
4659 struct got_repository *repo;
4662 static const struct got_error *
4663 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4665 const struct got_error *err = NULL;
4666 struct blame_cb_args *a = arg;
4667 struct blame_line *bline;
4668 char *line = NULL;
4669 size_t linesize = 0;
4670 struct got_commit_object *commit = NULL;
4671 off_t offset;
4672 struct tm tm;
4673 time_t committer_time;
4675 if (nlines != a->nlines ||
4676 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4677 return got_error(GOT_ERR_RANGE);
4679 if (sigint_received)
4680 return got_error(GOT_ERR_ITER_COMPLETED);
4682 if (lineno == -1)
4683 return NULL; /* no change in this commit */
4685 /* Annotate this line. */
4686 bline = &a->lines[lineno - 1];
4687 if (bline->annotated)
4688 return NULL;
4689 err = got_object_id_str(&bline->id_str, id);
4690 if (err)
4691 return err;
4693 err = got_object_open_as_commit(&commit, a->repo, id);
4694 if (err)
4695 goto done;
4697 bline->committer = strdup(got_object_commit_get_committer(commit));
4698 if (bline->committer == NULL) {
4699 err = got_error_from_errno("strdup");
4700 goto done;
4703 committer_time = got_object_commit_get_committer_time(commit);
4704 if (gmtime_r(&committer_time, &tm) == NULL)
4705 return got_error_from_errno("gmtime_r");
4706 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4707 &tm) == 0) {
4708 err = got_error(GOT_ERR_NO_SPACE);
4709 goto done;
4711 bline->annotated = 1;
4713 /* Print lines annotated so far. */
4714 bline = &a->lines[a->lineno_cur - 1];
4715 if (!bline->annotated)
4716 goto done;
4718 offset = a->line_offsets[a->lineno_cur - 1];
4719 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4720 err = got_error_from_errno("fseeko");
4721 goto done;
4724 while (bline->annotated) {
4725 char *smallerthan, *at, *nl, *committer;
4726 size_t len;
4728 if (getline(&line, &linesize, a->f) == -1) {
4729 if (ferror(a->f))
4730 err = got_error_from_errno("getline");
4731 break;
4734 committer = bline->committer;
4735 smallerthan = strchr(committer, '<');
4736 if (smallerthan && smallerthan[1] != '\0')
4737 committer = smallerthan + 1;
4738 at = strchr(committer, '@');
4739 if (at)
4740 *at = '\0';
4741 len = strlen(committer);
4742 if (len >= 9)
4743 committer[8] = '\0';
4745 nl = strchr(line, '\n');
4746 if (nl)
4747 *nl = '\0';
4748 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4749 bline->id_str, bline->datebuf, committer, line);
4751 a->lineno_cur++;
4752 bline = &a->lines[a->lineno_cur - 1];
4754 done:
4755 if (commit)
4756 got_object_commit_close(commit);
4757 free(line);
4758 return err;
4761 static const struct got_error *
4762 cmd_blame(int argc, char *argv[])
4764 const struct got_error *error;
4765 struct got_repository *repo = NULL;
4766 struct got_worktree *worktree = NULL;
4767 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4768 char *link_target = NULL;
4769 struct got_object_id *obj_id = NULL;
4770 struct got_object_id *commit_id = NULL;
4771 struct got_blob_object *blob = NULL;
4772 char *commit_id_str = NULL;
4773 struct blame_cb_args bca;
4774 int ch, obj_type, i;
4775 off_t filesize;
4777 memset(&bca, 0, sizeof(bca));
4779 #ifndef PROFILE
4780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4781 NULL) == -1)
4782 err(1, "pledge");
4783 #endif
4785 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4786 switch (ch) {
4787 case 'c':
4788 commit_id_str = optarg;
4789 break;
4790 case 'r':
4791 repo_path = realpath(optarg, NULL);
4792 if (repo_path == NULL)
4793 return got_error_from_errno2("realpath",
4794 optarg);
4795 got_path_strip_trailing_slashes(repo_path);
4796 break;
4797 default:
4798 usage_blame();
4799 /* NOTREACHED */
4803 argc -= optind;
4804 argv += optind;
4806 if (argc == 1)
4807 path = argv[0];
4808 else
4809 usage_blame();
4811 cwd = getcwd(NULL, 0);
4812 if (cwd == NULL) {
4813 error = got_error_from_errno("getcwd");
4814 goto done;
4816 if (repo_path == NULL) {
4817 error = got_worktree_open(&worktree, cwd);
4818 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4819 goto done;
4820 else
4821 error = NULL;
4822 if (worktree) {
4823 repo_path =
4824 strdup(got_worktree_get_repo_path(worktree));
4825 if (repo_path == NULL) {
4826 error = got_error_from_errno("strdup");
4827 if (error)
4828 goto done;
4830 } else {
4831 repo_path = strdup(cwd);
4832 if (repo_path == NULL) {
4833 error = got_error_from_errno("strdup");
4834 goto done;
4839 error = got_repo_open(&repo, repo_path, NULL);
4840 if (error != NULL)
4841 goto done;
4843 if (worktree) {
4844 const char *prefix = got_worktree_get_path_prefix(worktree);
4845 char *p;
4847 error = got_worktree_resolve_path(&p, worktree, path);
4848 if (error)
4849 goto done;
4850 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4851 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4852 p) == -1) {
4853 error = got_error_from_errno("asprintf");
4854 free(p);
4855 goto done;
4857 free(p);
4858 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4859 } else {
4860 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4861 if (error)
4862 goto done;
4863 error = got_repo_map_path(&in_repo_path, repo, path);
4865 if (error)
4866 goto done;
4868 if (commit_id_str == NULL) {
4869 struct got_reference *head_ref;
4870 error = got_ref_open(&head_ref, repo, worktree ?
4871 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4872 if (error != NULL)
4873 goto done;
4874 error = got_ref_resolve(&commit_id, repo, head_ref);
4875 got_ref_close(head_ref);
4876 if (error != NULL)
4877 goto done;
4878 } else {
4879 struct got_reflist_head refs;
4880 TAILQ_INIT(&refs);
4881 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4882 NULL);
4883 if (error)
4884 goto done;
4885 error = got_repo_match_object_id(&commit_id, NULL,
4886 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4887 got_ref_list_free(&refs);
4888 if (error)
4889 goto done;
4892 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4893 commit_id, repo);
4894 if (error)
4895 goto done;
4897 error = got_object_id_by_path(&obj_id, repo, commit_id,
4898 link_target ? link_target : in_repo_path);
4899 if (error)
4900 goto done;
4902 error = got_object_get_type(&obj_type, repo, obj_id);
4903 if (error)
4904 goto done;
4906 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4907 error = got_error_path(link_target ? link_target : in_repo_path,
4908 GOT_ERR_OBJ_TYPE);
4909 goto done;
4912 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4913 if (error)
4914 goto done;
4915 bca.f = got_opentemp();
4916 if (bca.f == NULL) {
4917 error = got_error_from_errno("got_opentemp");
4918 goto done;
4920 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4921 &bca.line_offsets, bca.f, blob);
4922 if (error || bca.nlines == 0)
4923 goto done;
4925 /* Don't include \n at EOF in the blame line count. */
4926 if (bca.line_offsets[bca.nlines - 1] == filesize)
4927 bca.nlines--;
4929 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4930 if (bca.lines == NULL) {
4931 error = got_error_from_errno("calloc");
4932 goto done;
4934 bca.lineno_cur = 1;
4935 bca.nlines_prec = 0;
4936 i = bca.nlines;
4937 while (i > 0) {
4938 i /= 10;
4939 bca.nlines_prec++;
4941 bca.repo = repo;
4943 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4944 repo, blame_cb, &bca, check_cancelled, NULL);
4945 done:
4946 free(in_repo_path);
4947 free(link_target);
4948 free(repo_path);
4949 free(cwd);
4950 free(commit_id);
4951 free(obj_id);
4952 if (blob)
4953 got_object_blob_close(blob);
4954 if (worktree)
4955 got_worktree_close(worktree);
4956 if (repo) {
4957 const struct got_error *close_err = got_repo_close(repo);
4958 if (error == NULL)
4959 error = close_err;
4961 if (bca.lines) {
4962 for (i = 0; i < bca.nlines; i++) {
4963 struct blame_line *bline = &bca.lines[i];
4964 free(bline->id_str);
4965 free(bline->committer);
4967 free(bca.lines);
4969 free(bca.line_offsets);
4970 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4971 error = got_error_from_errno("fclose");
4972 return error;
4975 __dead static void
4976 usage_tree(void)
4978 fprintf(stderr,
4979 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4980 getprogname());
4981 exit(1);
4984 static const struct got_error *
4985 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4986 const char *root_path, struct got_repository *repo)
4988 const struct got_error *err = NULL;
4989 int is_root_path = (strcmp(path, root_path) == 0);
4990 const char *modestr = "";
4991 mode_t mode = got_tree_entry_get_mode(te);
4992 char *link_target = NULL;
4994 path += strlen(root_path);
4995 while (path[0] == '/')
4996 path++;
4998 if (got_object_tree_entry_is_submodule(te))
4999 modestr = "$";
5000 else if (S_ISLNK(mode)) {
5001 int i;
5003 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5004 if (err)
5005 return err;
5006 for (i = 0; i < strlen(link_target); i++) {
5007 if (!isprint((unsigned char)link_target[i]))
5008 link_target[i] = '?';
5011 modestr = "@";
5013 else if (S_ISDIR(mode))
5014 modestr = "/";
5015 else if (mode & S_IXUSR)
5016 modestr = "*";
5018 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5019 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5020 link_target ? " -> ": "", link_target ? link_target : "");
5022 free(link_target);
5023 return NULL;
5026 static const struct got_error *
5027 print_tree(const char *path, struct got_object_id *commit_id,
5028 int show_ids, int recurse, const char *root_path,
5029 struct got_repository *repo)
5031 const struct got_error *err = NULL;
5032 struct got_object_id *tree_id = NULL;
5033 struct got_tree_object *tree = NULL;
5034 int nentries, i;
5036 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5037 if (err)
5038 goto done;
5040 err = got_object_open_as_tree(&tree, repo, tree_id);
5041 if (err)
5042 goto done;
5043 nentries = got_object_tree_get_nentries(tree);
5044 for (i = 0; i < nentries; i++) {
5045 struct got_tree_entry *te;
5046 char *id = NULL;
5048 if (sigint_received || sigpipe_received)
5049 break;
5051 te = got_object_tree_get_entry(tree, i);
5052 if (show_ids) {
5053 char *id_str;
5054 err = got_object_id_str(&id_str,
5055 got_tree_entry_get_id(te));
5056 if (err)
5057 goto done;
5058 if (asprintf(&id, "%s ", id_str) == -1) {
5059 err = got_error_from_errno("asprintf");
5060 free(id_str);
5061 goto done;
5063 free(id_str);
5065 err = print_entry(te, id, path, root_path, repo);
5066 free(id);
5067 if (err)
5068 goto done;
5070 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5071 char *child_path;
5072 if (asprintf(&child_path, "%s%s%s", path,
5073 path[0] == '/' && path[1] == '\0' ? "" : "/",
5074 got_tree_entry_get_name(te)) == -1) {
5075 err = got_error_from_errno("asprintf");
5076 goto done;
5078 err = print_tree(child_path, commit_id, show_ids, 1,
5079 root_path, repo);
5080 free(child_path);
5081 if (err)
5082 goto done;
5085 done:
5086 if (tree)
5087 got_object_tree_close(tree);
5088 free(tree_id);
5089 return err;
5092 static const struct got_error *
5093 cmd_tree(int argc, char *argv[])
5095 const struct got_error *error;
5096 struct got_repository *repo = NULL;
5097 struct got_worktree *worktree = NULL;
5098 const char *path, *refname = NULL;
5099 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5100 struct got_object_id *commit_id = NULL;
5101 char *commit_id_str = NULL;
5102 int show_ids = 0, recurse = 0;
5103 int ch;
5105 #ifndef PROFILE
5106 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5107 NULL) == -1)
5108 err(1, "pledge");
5109 #endif
5111 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5112 switch (ch) {
5113 case 'c':
5114 commit_id_str = optarg;
5115 break;
5116 case 'r':
5117 repo_path = realpath(optarg, NULL);
5118 if (repo_path == NULL)
5119 return got_error_from_errno2("realpath",
5120 optarg);
5121 got_path_strip_trailing_slashes(repo_path);
5122 break;
5123 case 'i':
5124 show_ids = 1;
5125 break;
5126 case 'R':
5127 recurse = 1;
5128 break;
5129 default:
5130 usage_tree();
5131 /* NOTREACHED */
5135 argc -= optind;
5136 argv += optind;
5138 if (argc == 1)
5139 path = argv[0];
5140 else if (argc > 1)
5141 usage_tree();
5142 else
5143 path = NULL;
5145 cwd = getcwd(NULL, 0);
5146 if (cwd == NULL) {
5147 error = got_error_from_errno("getcwd");
5148 goto done;
5150 if (repo_path == NULL) {
5151 error = got_worktree_open(&worktree, cwd);
5152 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5153 goto done;
5154 else
5155 error = NULL;
5156 if (worktree) {
5157 repo_path =
5158 strdup(got_worktree_get_repo_path(worktree));
5159 if (repo_path == NULL)
5160 error = got_error_from_errno("strdup");
5161 if (error)
5162 goto done;
5163 } else {
5164 repo_path = strdup(cwd);
5165 if (repo_path == NULL) {
5166 error = got_error_from_errno("strdup");
5167 goto done;
5172 error = got_repo_open(&repo, repo_path, NULL);
5173 if (error != NULL)
5174 goto done;
5176 if (worktree) {
5177 const char *prefix = got_worktree_get_path_prefix(worktree);
5178 char *p;
5180 if (path == NULL)
5181 path = "";
5182 error = got_worktree_resolve_path(&p, worktree, path);
5183 if (error)
5184 goto done;
5185 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5186 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5187 p) == -1) {
5188 error = got_error_from_errno("asprintf");
5189 free(p);
5190 goto done;
5192 free(p);
5193 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5194 if (error)
5195 goto done;
5196 } else {
5197 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5198 if (error)
5199 goto done;
5200 if (path == NULL)
5201 path = "/";
5202 error = got_repo_map_path(&in_repo_path, repo, path);
5203 if (error != NULL)
5204 goto done;
5207 if (commit_id_str == NULL) {
5208 struct got_reference *head_ref;
5209 if (worktree)
5210 refname = got_worktree_get_head_ref_name(worktree);
5211 else
5212 refname = GOT_REF_HEAD;
5213 error = got_ref_open(&head_ref, repo, refname, 0);
5214 if (error != NULL)
5215 goto done;
5216 error = got_ref_resolve(&commit_id, repo, head_ref);
5217 got_ref_close(head_ref);
5218 if (error != NULL)
5219 goto done;
5220 } else {
5221 struct got_reflist_head refs;
5222 TAILQ_INIT(&refs);
5223 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5224 NULL);
5225 if (error)
5226 goto done;
5227 error = got_repo_match_object_id(&commit_id, NULL,
5228 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5229 got_ref_list_free(&refs);
5230 if (error)
5231 goto done;
5234 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5235 in_repo_path, repo);
5236 done:
5237 free(in_repo_path);
5238 free(repo_path);
5239 free(cwd);
5240 free(commit_id);
5241 if (worktree)
5242 got_worktree_close(worktree);
5243 if (repo) {
5244 const struct got_error *close_err = got_repo_close(repo);
5245 if (error == NULL)
5246 error = close_err;
5248 return error;
5251 __dead static void
5252 usage_status(void)
5254 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5255 "[-S status-codes] [path ...]\n", getprogname());
5256 exit(1);
5259 struct got_status_arg {
5260 char *status_codes;
5261 int suppress;
5264 static const struct got_error *
5265 print_status(void *arg, unsigned char status, unsigned char staged_status,
5266 const char *path, struct got_object_id *blob_id,
5267 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5268 int dirfd, const char *de_name)
5270 struct got_status_arg *st = arg;
5272 if (status == staged_status && (status == GOT_STATUS_DELETE))
5273 status = GOT_STATUS_NO_CHANGE;
5274 if (st != NULL && st->status_codes) {
5275 size_t ncodes = strlen(st->status_codes);
5276 int i, j = 0;
5278 for (i = 0; i < ncodes ; i++) {
5279 if (st->suppress) {
5280 if (status == st->status_codes[i] ||
5281 staged_status == st->status_codes[i]) {
5282 j++;
5283 continue;
5285 } else {
5286 if (status == st->status_codes[i] ||
5287 staged_status == st->status_codes[i])
5288 break;
5292 if (st->suppress && j == 0)
5293 goto print;
5295 if (i == ncodes)
5296 return NULL;
5298 print:
5299 printf("%c%c %s\n", status, staged_status, path);
5300 return NULL;
5303 static const struct got_error *
5304 cmd_status(int argc, char *argv[])
5306 const struct got_error *error = NULL;
5307 struct got_repository *repo = NULL;
5308 struct got_worktree *worktree = NULL;
5309 struct got_status_arg st;
5310 char *cwd = NULL;
5311 struct got_pathlist_head paths;
5312 struct got_pathlist_entry *pe;
5313 int ch, i, no_ignores = 0;
5315 TAILQ_INIT(&paths);
5317 memset(&st, 0, sizeof(st));
5318 st.status_codes = NULL;
5319 st.suppress = 0;
5321 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5322 switch (ch) {
5323 case 'I':
5324 no_ignores = 1;
5325 break;
5326 case 'S':
5327 if (st.status_codes != NULL && st.suppress == 0)
5328 option_conflict('S', 's');
5329 st.suppress = 1;
5330 /* fallthrough */
5331 case 's':
5332 for (i = 0; i < strlen(optarg); i++) {
5333 switch (optarg[i]) {
5334 case GOT_STATUS_MODIFY:
5335 case GOT_STATUS_ADD:
5336 case GOT_STATUS_DELETE:
5337 case GOT_STATUS_CONFLICT:
5338 case GOT_STATUS_MISSING:
5339 case GOT_STATUS_OBSTRUCTED:
5340 case GOT_STATUS_UNVERSIONED:
5341 case GOT_STATUS_MODE_CHANGE:
5342 case GOT_STATUS_NONEXISTENT:
5343 break;
5344 default:
5345 errx(1, "invalid status code '%c'",
5346 optarg[i]);
5349 if (ch == 's' && st.suppress)
5350 option_conflict('s', 'S');
5351 st.status_codes = optarg;
5352 break;
5353 default:
5354 usage_status();
5355 /* NOTREACHED */
5359 argc -= optind;
5360 argv += optind;
5362 #ifndef PROFILE
5363 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5364 NULL) == -1)
5365 err(1, "pledge");
5366 #endif
5367 cwd = getcwd(NULL, 0);
5368 if (cwd == NULL) {
5369 error = got_error_from_errno("getcwd");
5370 goto done;
5373 error = got_worktree_open(&worktree, cwd);
5374 if (error) {
5375 if (error->code == GOT_ERR_NOT_WORKTREE)
5376 error = wrap_not_worktree_error(error, "status", cwd);
5377 goto done;
5380 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5381 NULL);
5382 if (error != NULL)
5383 goto done;
5385 error = apply_unveil(got_repo_get_path(repo), 1,
5386 got_worktree_get_root_path(worktree));
5387 if (error)
5388 goto done;
5390 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5391 if (error)
5392 goto done;
5394 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5395 print_status, &st, check_cancelled, NULL);
5396 done:
5397 TAILQ_FOREACH(pe, &paths, entry)
5398 free((char *)pe->path);
5399 got_pathlist_free(&paths);
5400 free(cwd);
5401 return error;
5404 __dead static void
5405 usage_ref(void)
5407 fprintf(stderr,
5408 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5409 "[-d] [name]\n",
5410 getprogname());
5411 exit(1);
5414 static const struct got_error *
5415 list_refs(struct got_repository *repo, const char *refname)
5417 static const struct got_error *err = NULL;
5418 struct got_reflist_head refs;
5419 struct got_reflist_entry *re;
5421 TAILQ_INIT(&refs);
5422 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5423 if (err)
5424 return err;
5426 TAILQ_FOREACH(re, &refs, entry) {
5427 char *refstr;
5428 refstr = got_ref_to_str(re->ref);
5429 if (refstr == NULL)
5430 return got_error_from_errno("got_ref_to_str");
5431 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5432 free(refstr);
5435 got_ref_list_free(&refs);
5436 return NULL;
5439 static const struct got_error *
5440 delete_ref_by_name(struct got_repository *repo, const char *refname)
5442 const struct got_error *err;
5443 struct got_reference *ref;
5445 err = got_ref_open(&ref, repo, refname, 0);
5446 if (err)
5447 return err;
5449 err = delete_ref(repo, ref);
5450 got_ref_close(ref);
5451 return err;
5454 static const struct got_error *
5455 add_ref(struct got_repository *repo, const char *refname, const char *target)
5457 const struct got_error *err = NULL;
5458 struct got_object_id *id;
5459 struct got_reference *ref = NULL;
5462 * Don't let the user create a reference name with a leading '-'.
5463 * While technically a valid reference name, this case is usually
5464 * an unintended typo.
5466 if (refname[0] == '-')
5467 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5469 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5470 repo);
5471 if (err) {
5472 struct got_reference *target_ref;
5474 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5475 return err;
5476 err = got_ref_open(&target_ref, repo, target, 0);
5477 if (err)
5478 return err;
5479 err = got_ref_resolve(&id, repo, target_ref);
5480 got_ref_close(target_ref);
5481 if (err)
5482 return err;
5485 err = got_ref_alloc(&ref, refname, id);
5486 if (err)
5487 goto done;
5489 err = got_ref_write(ref, repo);
5490 done:
5491 if (ref)
5492 got_ref_close(ref);
5493 free(id);
5494 return err;
5497 static const struct got_error *
5498 add_symref(struct got_repository *repo, const char *refname, const char *target)
5500 const struct got_error *err = NULL;
5501 struct got_reference *ref = NULL;
5502 struct got_reference *target_ref = NULL;
5505 * Don't let the user create a reference name with a leading '-'.
5506 * While technically a valid reference name, this case is usually
5507 * an unintended typo.
5509 if (refname[0] == '-')
5510 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5512 err = got_ref_open(&target_ref, repo, target, 0);
5513 if (err)
5514 return err;
5516 err = got_ref_alloc_symref(&ref, refname, target_ref);
5517 if (err)
5518 goto done;
5520 err = got_ref_write(ref, repo);
5521 done:
5522 if (target_ref)
5523 got_ref_close(target_ref);
5524 if (ref)
5525 got_ref_close(ref);
5526 return err;
5529 static const struct got_error *
5530 cmd_ref(int argc, char *argv[])
5532 const struct got_error *error = NULL;
5533 struct got_repository *repo = NULL;
5534 struct got_worktree *worktree = NULL;
5535 char *cwd = NULL, *repo_path = NULL;
5536 int ch, do_list = 0, do_delete = 0;
5537 const char *obj_arg = NULL, *symref_target= NULL;
5538 char *refname = NULL;
5540 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5541 switch (ch) {
5542 case 'c':
5543 obj_arg = optarg;
5544 break;
5545 case 'd':
5546 do_delete = 1;
5547 break;
5548 case 'r':
5549 repo_path = realpath(optarg, NULL);
5550 if (repo_path == NULL)
5551 return got_error_from_errno2("realpath",
5552 optarg);
5553 got_path_strip_trailing_slashes(repo_path);
5554 break;
5555 case 'l':
5556 do_list = 1;
5557 break;
5558 case 's':
5559 symref_target = optarg;
5560 break;
5561 default:
5562 usage_ref();
5563 /* NOTREACHED */
5567 if (obj_arg && do_list)
5568 option_conflict('c', 'l');
5569 if (obj_arg && do_delete)
5570 option_conflict('c', 'd');
5571 if (obj_arg && symref_target)
5572 option_conflict('c', 's');
5573 if (symref_target && do_delete)
5574 option_conflict('s', 'd');
5575 if (symref_target && do_list)
5576 option_conflict('s', 'l');
5577 if (do_delete && do_list)
5578 option_conflict('d', 'l');
5580 argc -= optind;
5581 argv += optind;
5583 if (do_list) {
5584 if (argc != 0 && argc != 1)
5585 usage_ref();
5586 if (argc == 1) {
5587 refname = strdup(argv[0]);
5588 if (refname == NULL) {
5589 error = got_error_from_errno("strdup");
5590 goto done;
5593 } else {
5594 if (argc != 1)
5595 usage_ref();
5596 refname = strdup(argv[0]);
5597 if (refname == NULL) {
5598 error = got_error_from_errno("strdup");
5599 goto done;
5603 if (refname)
5604 got_path_strip_trailing_slashes(refname);
5606 #ifndef PROFILE
5607 if (do_list) {
5608 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5609 NULL) == -1)
5610 err(1, "pledge");
5611 } else {
5612 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5613 "sendfd unveil", NULL) == -1)
5614 err(1, "pledge");
5616 #endif
5617 cwd = getcwd(NULL, 0);
5618 if (cwd == NULL) {
5619 error = got_error_from_errno("getcwd");
5620 goto done;
5623 if (repo_path == NULL) {
5624 error = got_worktree_open(&worktree, cwd);
5625 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5626 goto done;
5627 else
5628 error = NULL;
5629 if (worktree) {
5630 repo_path =
5631 strdup(got_worktree_get_repo_path(worktree));
5632 if (repo_path == NULL)
5633 error = got_error_from_errno("strdup");
5634 if (error)
5635 goto done;
5636 } else {
5637 repo_path = strdup(cwd);
5638 if (repo_path == NULL) {
5639 error = got_error_from_errno("strdup");
5640 goto done;
5645 error = got_repo_open(&repo, repo_path, NULL);
5646 if (error != NULL)
5647 goto done;
5649 error = apply_unveil(got_repo_get_path(repo), do_list,
5650 worktree ? got_worktree_get_root_path(worktree) : NULL);
5651 if (error)
5652 goto done;
5654 if (do_list)
5655 error = list_refs(repo, refname);
5656 else if (do_delete)
5657 error = delete_ref_by_name(repo, refname);
5658 else if (symref_target)
5659 error = add_symref(repo, refname, symref_target);
5660 else {
5661 if (obj_arg == NULL)
5662 usage_ref();
5663 error = add_ref(repo, refname, obj_arg);
5665 done:
5666 free(refname);
5667 if (repo) {
5668 const struct got_error *close_err = got_repo_close(repo);
5669 if (error == NULL)
5670 error = close_err;
5672 if (worktree)
5673 got_worktree_close(worktree);
5674 free(cwd);
5675 free(repo_path);
5676 return error;
5679 __dead static void
5680 usage_branch(void)
5682 fprintf(stderr,
5683 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5684 "[name]\n", getprogname());
5685 exit(1);
5688 static const struct got_error *
5689 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5690 struct got_reference *ref)
5692 const struct got_error *err = NULL;
5693 const char *refname, *marker = " ";
5694 char *refstr;
5696 refname = got_ref_get_name(ref);
5697 if (worktree && strcmp(refname,
5698 got_worktree_get_head_ref_name(worktree)) == 0) {
5699 struct got_object_id *id = NULL;
5701 err = got_ref_resolve(&id, repo, ref);
5702 if (err)
5703 return err;
5704 if (got_object_id_cmp(id,
5705 got_worktree_get_base_commit_id(worktree)) == 0)
5706 marker = "* ";
5707 else
5708 marker = "~ ";
5709 free(id);
5712 if (strncmp(refname, "refs/heads/", 11) == 0)
5713 refname += 11;
5714 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5715 refname += 18;
5716 if (strncmp(refname, "refs/remotes/", 13) == 0)
5717 refname += 13;
5719 refstr = got_ref_to_str(ref);
5720 if (refstr == NULL)
5721 return got_error_from_errno("got_ref_to_str");
5723 printf("%s%s: %s\n", marker, refname, refstr);
5724 free(refstr);
5725 return NULL;
5728 static const struct got_error *
5729 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5731 const char *refname;
5733 if (worktree == NULL)
5734 return got_error(GOT_ERR_NOT_WORKTREE);
5736 refname = got_worktree_get_head_ref_name(worktree);
5738 if (strncmp(refname, "refs/heads/", 11) == 0)
5739 refname += 11;
5740 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5741 refname += 18;
5743 printf("%s\n", refname);
5745 return NULL;
5748 static const struct got_error *
5749 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5751 static const struct got_error *err = NULL;
5752 struct got_reflist_head refs;
5753 struct got_reflist_entry *re;
5754 struct got_reference *temp_ref = NULL;
5755 int rebase_in_progress, histedit_in_progress;
5757 TAILQ_INIT(&refs);
5759 if (worktree) {
5760 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5761 worktree);
5762 if (err)
5763 return err;
5765 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5766 worktree);
5767 if (err)
5768 return err;
5770 if (rebase_in_progress || histedit_in_progress) {
5771 err = got_ref_open(&temp_ref, repo,
5772 got_worktree_get_head_ref_name(worktree), 0);
5773 if (err)
5774 return err;
5775 list_branch(repo, worktree, temp_ref);
5776 got_ref_close(temp_ref);
5780 err = got_ref_list(&refs, repo, "refs/heads",
5781 got_ref_cmp_by_name, NULL);
5782 if (err)
5783 return err;
5785 TAILQ_FOREACH(re, &refs, entry)
5786 list_branch(repo, worktree, re->ref);
5788 got_ref_list_free(&refs);
5790 err = got_ref_list(&refs, repo, "refs/remotes",
5791 got_ref_cmp_by_name, NULL);
5792 if (err)
5793 return err;
5795 TAILQ_FOREACH(re, &refs, entry)
5796 list_branch(repo, worktree, re->ref);
5798 got_ref_list_free(&refs);
5800 return NULL;
5803 static const struct got_error *
5804 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5805 const char *branch_name)
5807 const struct got_error *err = NULL;
5808 struct got_reference *ref = NULL;
5809 char *refname, *remote_refname = NULL;
5811 if (strncmp(branch_name, "refs/", 5) == 0)
5812 branch_name += 5;
5813 if (strncmp(branch_name, "heads/", 6) == 0)
5814 branch_name += 6;
5815 else if (strncmp(branch_name, "remotes/", 8) == 0)
5816 branch_name += 8;
5818 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5819 return got_error_from_errno("asprintf");
5821 if (asprintf(&remote_refname, "refs/remotes/%s",
5822 branch_name) == -1) {
5823 err = got_error_from_errno("asprintf");
5824 goto done;
5827 err = got_ref_open(&ref, repo, refname, 0);
5828 if (err) {
5829 const struct got_error *err2;
5830 if (err->code != GOT_ERR_NOT_REF)
5831 goto done;
5833 * Keep 'err' intact such that if neither branch exists
5834 * we report "refs/heads" rather than "refs/remotes" in
5835 * our error message.
5837 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5838 if (err2)
5839 goto done;
5840 err = NULL;
5843 if (worktree &&
5844 strcmp(got_worktree_get_head_ref_name(worktree),
5845 got_ref_get_name(ref)) == 0) {
5846 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5847 "will not delete this work tree's current branch");
5848 goto done;
5851 err = delete_ref(repo, ref);
5852 done:
5853 if (ref)
5854 got_ref_close(ref);
5855 free(refname);
5856 free(remote_refname);
5857 return err;
5860 static const struct got_error *
5861 add_branch(struct got_repository *repo, const char *branch_name,
5862 struct got_object_id *base_commit_id)
5864 const struct got_error *err = NULL;
5865 struct got_reference *ref = NULL;
5866 char *base_refname = NULL, *refname = NULL;
5869 * Don't let the user create a branch name with a leading '-'.
5870 * While technically a valid reference name, this case is usually
5871 * an unintended typo.
5873 if (branch_name[0] == '-')
5874 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5876 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5877 branch_name += 11;
5879 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5880 err = got_error_from_errno("asprintf");
5881 goto done;
5884 err = got_ref_open(&ref, repo, refname, 0);
5885 if (err == NULL) {
5886 err = got_error(GOT_ERR_BRANCH_EXISTS);
5887 goto done;
5888 } else if (err->code != GOT_ERR_NOT_REF)
5889 goto done;
5891 err = got_ref_alloc(&ref, refname, base_commit_id);
5892 if (err)
5893 goto done;
5895 err = got_ref_write(ref, repo);
5896 done:
5897 if (ref)
5898 got_ref_close(ref);
5899 free(base_refname);
5900 free(refname);
5901 return err;
5904 static const struct got_error *
5905 cmd_branch(int argc, char *argv[])
5907 const struct got_error *error = NULL;
5908 struct got_repository *repo = NULL;
5909 struct got_worktree *worktree = NULL;
5910 char *cwd = NULL, *repo_path = NULL;
5911 int ch, do_list = 0, do_show = 0, do_update = 1;
5912 const char *delref = NULL, *commit_id_arg = NULL;
5913 struct got_reference *ref = NULL;
5914 struct got_pathlist_head paths;
5915 struct got_pathlist_entry *pe;
5916 struct got_object_id *commit_id = NULL;
5917 char *commit_id_str = NULL;
5919 TAILQ_INIT(&paths);
5921 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5922 switch (ch) {
5923 case 'c':
5924 commit_id_arg = optarg;
5925 break;
5926 case 'd':
5927 delref = optarg;
5928 break;
5929 case 'r':
5930 repo_path = realpath(optarg, NULL);
5931 if (repo_path == NULL)
5932 return got_error_from_errno2("realpath",
5933 optarg);
5934 got_path_strip_trailing_slashes(repo_path);
5935 break;
5936 case 'l':
5937 do_list = 1;
5938 break;
5939 case 'n':
5940 do_update = 0;
5941 break;
5942 default:
5943 usage_branch();
5944 /* NOTREACHED */
5948 if (do_list && delref)
5949 option_conflict('l', 'd');
5951 argc -= optind;
5952 argv += optind;
5954 if (!do_list && !delref && argc == 0)
5955 do_show = 1;
5957 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5958 errx(1, "-c option can only be used when creating a branch");
5960 if (do_list || delref) {
5961 if (argc > 0)
5962 usage_branch();
5963 } else if (!do_show && argc != 1)
5964 usage_branch();
5966 #ifndef PROFILE
5967 if (do_list || do_show) {
5968 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5969 NULL) == -1)
5970 err(1, "pledge");
5971 } else {
5972 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5973 "sendfd unveil", NULL) == -1)
5974 err(1, "pledge");
5976 #endif
5977 cwd = getcwd(NULL, 0);
5978 if (cwd == NULL) {
5979 error = got_error_from_errno("getcwd");
5980 goto done;
5983 if (repo_path == NULL) {
5984 error = got_worktree_open(&worktree, cwd);
5985 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5986 goto done;
5987 else
5988 error = NULL;
5989 if (worktree) {
5990 repo_path =
5991 strdup(got_worktree_get_repo_path(worktree));
5992 if (repo_path == NULL)
5993 error = got_error_from_errno("strdup");
5994 if (error)
5995 goto done;
5996 } else {
5997 repo_path = strdup(cwd);
5998 if (repo_path == NULL) {
5999 error = got_error_from_errno("strdup");
6000 goto done;
6005 error = got_repo_open(&repo, repo_path, NULL);
6006 if (error != NULL)
6007 goto done;
6009 error = apply_unveil(got_repo_get_path(repo), do_list,
6010 worktree ? got_worktree_get_root_path(worktree) : NULL);
6011 if (error)
6012 goto done;
6014 if (do_show)
6015 error = show_current_branch(repo, worktree);
6016 else if (do_list)
6017 error = list_branches(repo, worktree);
6018 else if (delref)
6019 error = delete_branch(repo, worktree, delref);
6020 else {
6021 struct got_reflist_head refs;
6022 TAILQ_INIT(&refs);
6023 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6024 NULL);
6025 if (error)
6026 goto done;
6027 if (commit_id_arg == NULL)
6028 commit_id_arg = worktree ?
6029 got_worktree_get_head_ref_name(worktree) :
6030 GOT_REF_HEAD;
6031 error = got_repo_match_object_id(&commit_id, NULL,
6032 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6033 got_ref_list_free(&refs);
6034 if (error)
6035 goto done;
6036 error = add_branch(repo, argv[0], commit_id);
6037 if (error)
6038 goto done;
6039 if (worktree && do_update) {
6040 struct got_update_progress_arg upa;
6041 char *branch_refname = NULL;
6043 error = got_object_id_str(&commit_id_str, commit_id);
6044 if (error)
6045 goto done;
6046 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6047 worktree);
6048 if (error)
6049 goto done;
6050 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6051 == -1) {
6052 error = got_error_from_errno("asprintf");
6053 goto done;
6055 error = got_ref_open(&ref, repo, branch_refname, 0);
6056 free(branch_refname);
6057 if (error)
6058 goto done;
6059 error = switch_head_ref(ref, commit_id, worktree,
6060 repo);
6061 if (error)
6062 goto done;
6063 error = got_worktree_set_base_commit_id(worktree, repo,
6064 commit_id);
6065 if (error)
6066 goto done;
6067 memset(&upa, 0, sizeof(upa));
6068 error = got_worktree_checkout_files(worktree, &paths,
6069 repo, update_progress, &upa, check_cancelled,
6070 NULL);
6071 if (error)
6072 goto done;
6073 if (upa.did_something)
6074 printf("Updated to commit %s\n", commit_id_str);
6075 print_update_progress_stats(&upa);
6078 done:
6079 if (ref)
6080 got_ref_close(ref);
6081 if (repo) {
6082 const struct got_error *close_err = got_repo_close(repo);
6083 if (error == NULL)
6084 error = close_err;
6086 if (worktree)
6087 got_worktree_close(worktree);
6088 free(cwd);
6089 free(repo_path);
6090 free(commit_id);
6091 free(commit_id_str);
6092 TAILQ_FOREACH(pe, &paths, entry)
6093 free((char *)pe->path);
6094 got_pathlist_free(&paths);
6095 return error;
6099 __dead static void
6100 usage_tag(void)
6102 fprintf(stderr,
6103 "usage: %s tag [-c commit] [-r repository] [-l] "
6104 "[-m message] name\n", getprogname());
6105 exit(1);
6108 #if 0
6109 static const struct got_error *
6110 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6112 const struct got_error *err = NULL;
6113 struct got_reflist_entry *re, *se, *new;
6114 struct got_object_id *re_id, *se_id;
6115 struct got_tag_object *re_tag, *se_tag;
6116 time_t re_time, se_time;
6118 STAILQ_FOREACH(re, tags, entry) {
6119 se = STAILQ_FIRST(sorted);
6120 if (se == NULL) {
6121 err = got_reflist_entry_dup(&new, re);
6122 if (err)
6123 return err;
6124 STAILQ_INSERT_HEAD(sorted, new, entry);
6125 continue;
6126 } else {
6127 err = got_ref_resolve(&re_id, repo, re->ref);
6128 if (err)
6129 break;
6130 err = got_object_open_as_tag(&re_tag, repo, re_id);
6131 free(re_id);
6132 if (err)
6133 break;
6134 re_time = got_object_tag_get_tagger_time(re_tag);
6135 got_object_tag_close(re_tag);
6138 while (se) {
6139 err = got_ref_resolve(&se_id, repo, re->ref);
6140 if (err)
6141 break;
6142 err = got_object_open_as_tag(&se_tag, repo, se_id);
6143 free(se_id);
6144 if (err)
6145 break;
6146 se_time = got_object_tag_get_tagger_time(se_tag);
6147 got_object_tag_close(se_tag);
6149 if (se_time > re_time) {
6150 err = got_reflist_entry_dup(&new, re);
6151 if (err)
6152 return err;
6153 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6154 break;
6156 se = STAILQ_NEXT(se, entry);
6157 continue;
6160 done:
6161 return err;
6163 #endif
6165 static const struct got_error *
6166 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6168 static const struct got_error *err = NULL;
6169 struct got_reflist_head refs;
6170 struct got_reflist_entry *re;
6172 TAILQ_INIT(&refs);
6174 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6175 if (err)
6176 return err;
6178 TAILQ_FOREACH(re, &refs, entry) {
6179 const char *refname;
6180 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6181 char datebuf[26];
6182 const char *tagger;
6183 time_t tagger_time;
6184 struct got_object_id *id;
6185 struct got_tag_object *tag;
6186 struct got_commit_object *commit = NULL;
6188 refname = got_ref_get_name(re->ref);
6189 if (strncmp(refname, "refs/tags/", 10) != 0)
6190 continue;
6191 refname += 10;
6192 refstr = got_ref_to_str(re->ref);
6193 if (refstr == NULL) {
6194 err = got_error_from_errno("got_ref_to_str");
6195 break;
6197 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6198 free(refstr);
6200 err = got_ref_resolve(&id, repo, re->ref);
6201 if (err)
6202 break;
6203 err = got_object_open_as_tag(&tag, repo, id);
6204 if (err) {
6205 if (err->code != GOT_ERR_OBJ_TYPE) {
6206 free(id);
6207 break;
6209 /* "lightweight" tag */
6210 err = got_object_open_as_commit(&commit, repo, id);
6211 if (err) {
6212 free(id);
6213 break;
6215 tagger = got_object_commit_get_committer(commit);
6216 tagger_time =
6217 got_object_commit_get_committer_time(commit);
6218 err = got_object_id_str(&id_str, id);
6219 free(id);
6220 if (err)
6221 break;
6222 } else {
6223 free(id);
6224 tagger = got_object_tag_get_tagger(tag);
6225 tagger_time = got_object_tag_get_tagger_time(tag);
6226 err = got_object_id_str(&id_str,
6227 got_object_tag_get_object_id(tag));
6228 if (err)
6229 break;
6231 printf("from: %s\n", tagger);
6232 datestr = get_datestr(&tagger_time, datebuf);
6233 if (datestr)
6234 printf("date: %s UTC\n", datestr);
6235 if (commit)
6236 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6237 else {
6238 switch (got_object_tag_get_object_type(tag)) {
6239 case GOT_OBJ_TYPE_BLOB:
6240 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6241 id_str);
6242 break;
6243 case GOT_OBJ_TYPE_TREE:
6244 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6245 id_str);
6246 break;
6247 case GOT_OBJ_TYPE_COMMIT:
6248 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6249 id_str);
6250 break;
6251 case GOT_OBJ_TYPE_TAG:
6252 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6253 id_str);
6254 break;
6255 default:
6256 break;
6259 free(id_str);
6260 if (commit) {
6261 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6262 if (err)
6263 break;
6264 got_object_commit_close(commit);
6265 } else {
6266 tagmsg0 = strdup(got_object_tag_get_message(tag));
6267 got_object_tag_close(tag);
6268 if (tagmsg0 == NULL) {
6269 err = got_error_from_errno("strdup");
6270 break;
6274 tagmsg = tagmsg0;
6275 do {
6276 line = strsep(&tagmsg, "\n");
6277 if (line)
6278 printf(" %s\n", line);
6279 } while (line);
6280 free(tagmsg0);
6283 got_ref_list_free(&refs);
6284 return NULL;
6287 static const struct got_error *
6288 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6289 const char *tag_name, const char *repo_path)
6291 const struct got_error *err = NULL;
6292 char *template = NULL, *initial_content = NULL;
6293 char *editor = NULL;
6294 int initial_content_len;
6295 int fd = -1;
6297 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6298 err = got_error_from_errno("asprintf");
6299 goto done;
6302 initial_content_len = asprintf(&initial_content,
6303 "\n# tagging commit %s as %s\n",
6304 commit_id_str, tag_name);
6305 if (initial_content_len == -1) {
6306 err = got_error_from_errno("asprintf");
6307 goto done;
6310 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6311 if (err)
6312 goto done;
6314 if (write(fd, initial_content, initial_content_len) == -1) {
6315 err = got_error_from_errno2("write", *tagmsg_path);
6316 goto done;
6319 err = get_editor(&editor);
6320 if (err)
6321 goto done;
6322 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6323 initial_content_len, 1);
6324 done:
6325 free(initial_content);
6326 free(template);
6327 free(editor);
6329 if (fd != -1 && close(fd) == -1 && err == NULL)
6330 err = got_error_from_errno2("close", *tagmsg_path);
6332 /* Editor is done; we can now apply unveil(2) */
6333 if (err == NULL)
6334 err = apply_unveil(repo_path, 0, NULL);
6335 if (err) {
6336 free(*tagmsg);
6337 *tagmsg = NULL;
6339 return err;
6342 static const struct got_error *
6343 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6344 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6346 const struct got_error *err = NULL;
6347 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6348 char *label = NULL, *commit_id_str = NULL;
6349 struct got_reference *ref = NULL;
6350 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6351 char *tagmsg_path = NULL, *tag_id_str = NULL;
6352 int preserve_tagmsg = 0;
6353 struct got_reflist_head refs;
6355 TAILQ_INIT(&refs);
6358 * Don't let the user create a tag name with a leading '-'.
6359 * While technically a valid reference name, this case is usually
6360 * an unintended typo.
6362 if (tag_name[0] == '-')
6363 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6365 err = get_author(&tagger, repo, worktree);
6366 if (err)
6367 return err;
6369 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6370 if (err)
6371 goto done;
6373 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6374 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6375 if (err)
6376 goto done;
6378 err = got_object_id_str(&commit_id_str, commit_id);
6379 if (err)
6380 goto done;
6382 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6383 refname = strdup(tag_name);
6384 if (refname == NULL) {
6385 err = got_error_from_errno("strdup");
6386 goto done;
6388 tag_name += 10;
6389 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6390 err = got_error_from_errno("asprintf");
6391 goto done;
6394 err = got_ref_open(&ref, repo, refname, 0);
6395 if (err == NULL) {
6396 err = got_error(GOT_ERR_TAG_EXISTS);
6397 goto done;
6398 } else if (err->code != GOT_ERR_NOT_REF)
6399 goto done;
6401 if (tagmsg_arg == NULL) {
6402 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6403 tag_name, got_repo_get_path(repo));
6404 if (err) {
6405 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6406 tagmsg_path != NULL)
6407 preserve_tagmsg = 1;
6408 goto done;
6412 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6413 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6414 if (err) {
6415 if (tagmsg_path)
6416 preserve_tagmsg = 1;
6417 goto done;
6420 err = got_ref_alloc(&ref, refname, tag_id);
6421 if (err) {
6422 if (tagmsg_path)
6423 preserve_tagmsg = 1;
6424 goto done;
6427 err = got_ref_write(ref, repo);
6428 if (err) {
6429 if (tagmsg_path)
6430 preserve_tagmsg = 1;
6431 goto done;
6434 err = got_object_id_str(&tag_id_str, tag_id);
6435 if (err) {
6436 if (tagmsg_path)
6437 preserve_tagmsg = 1;
6438 goto done;
6440 printf("Created tag %s\n", tag_id_str);
6441 done:
6442 if (preserve_tagmsg) {
6443 fprintf(stderr, "%s: tag message preserved in %s\n",
6444 getprogname(), tagmsg_path);
6445 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6446 err = got_error_from_errno2("unlink", tagmsg_path);
6447 free(tag_id_str);
6448 if (ref)
6449 got_ref_close(ref);
6450 free(commit_id);
6451 free(commit_id_str);
6452 free(refname);
6453 free(tagmsg);
6454 free(tagmsg_path);
6455 free(tagger);
6456 got_ref_list_free(&refs);
6457 return err;
6460 static const struct got_error *
6461 cmd_tag(int argc, char *argv[])
6463 const struct got_error *error = NULL;
6464 struct got_repository *repo = NULL;
6465 struct got_worktree *worktree = NULL;
6466 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6467 char *gitconfig_path = NULL;
6468 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6469 int ch, do_list = 0;
6471 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6472 switch (ch) {
6473 case 'c':
6474 commit_id_arg = optarg;
6475 break;
6476 case 'm':
6477 tagmsg = optarg;
6478 break;
6479 case 'r':
6480 repo_path = realpath(optarg, NULL);
6481 if (repo_path == NULL)
6482 return got_error_from_errno2("realpath",
6483 optarg);
6484 got_path_strip_trailing_slashes(repo_path);
6485 break;
6486 case 'l':
6487 do_list = 1;
6488 break;
6489 default:
6490 usage_tag();
6491 /* NOTREACHED */
6495 argc -= optind;
6496 argv += optind;
6498 if (do_list) {
6499 if (commit_id_arg != NULL)
6500 errx(1,
6501 "-c option can only be used when creating a tag");
6502 if (tagmsg)
6503 option_conflict('l', 'm');
6504 if (argc > 0)
6505 usage_tag();
6506 } else if (argc != 1)
6507 usage_tag();
6509 tag_name = argv[0];
6511 #ifndef PROFILE
6512 if (do_list) {
6513 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6514 NULL) == -1)
6515 err(1, "pledge");
6516 } else {
6517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6518 "sendfd unveil", NULL) == -1)
6519 err(1, "pledge");
6521 #endif
6522 cwd = getcwd(NULL, 0);
6523 if (cwd == NULL) {
6524 error = got_error_from_errno("getcwd");
6525 goto done;
6528 if (repo_path == NULL) {
6529 error = got_worktree_open(&worktree, cwd);
6530 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6531 goto done;
6532 else
6533 error = NULL;
6534 if (worktree) {
6535 repo_path =
6536 strdup(got_worktree_get_repo_path(worktree));
6537 if (repo_path == NULL)
6538 error = got_error_from_errno("strdup");
6539 if (error)
6540 goto done;
6541 } else {
6542 repo_path = strdup(cwd);
6543 if (repo_path == NULL) {
6544 error = got_error_from_errno("strdup");
6545 goto done;
6550 if (do_list) {
6551 error = got_repo_open(&repo, repo_path, NULL);
6552 if (error != NULL)
6553 goto done;
6554 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6555 if (error)
6556 goto done;
6557 error = list_tags(repo, worktree);
6558 } else {
6559 error = get_gitconfig_path(&gitconfig_path);
6560 if (error)
6561 goto done;
6562 error = got_repo_open(&repo, repo_path, gitconfig_path);
6563 if (error != NULL)
6564 goto done;
6566 if (tagmsg) {
6567 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6568 if (error)
6569 goto done;
6572 if (commit_id_arg == NULL) {
6573 struct got_reference *head_ref;
6574 struct got_object_id *commit_id;
6575 error = got_ref_open(&head_ref, repo,
6576 worktree ? got_worktree_get_head_ref_name(worktree)
6577 : GOT_REF_HEAD, 0);
6578 if (error)
6579 goto done;
6580 error = got_ref_resolve(&commit_id, repo, head_ref);
6581 got_ref_close(head_ref);
6582 if (error)
6583 goto done;
6584 error = got_object_id_str(&commit_id_str, commit_id);
6585 free(commit_id);
6586 if (error)
6587 goto done;
6590 error = add_tag(repo, worktree, tag_name,
6591 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6593 done:
6594 if (repo) {
6595 const struct got_error *close_err = got_repo_close(repo);
6596 if (error == NULL)
6597 error = close_err;
6599 if (worktree)
6600 got_worktree_close(worktree);
6601 free(cwd);
6602 free(repo_path);
6603 free(gitconfig_path);
6604 free(commit_id_str);
6605 return error;
6608 __dead static void
6609 usage_add(void)
6611 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6612 getprogname());
6613 exit(1);
6616 static const struct got_error *
6617 add_progress(void *arg, unsigned char status, const char *path)
6619 while (path[0] == '/')
6620 path++;
6621 printf("%c %s\n", status, path);
6622 return NULL;
6625 static const struct got_error *
6626 cmd_add(int argc, char *argv[])
6628 const struct got_error *error = NULL;
6629 struct got_repository *repo = NULL;
6630 struct got_worktree *worktree = NULL;
6631 char *cwd = NULL;
6632 struct got_pathlist_head paths;
6633 struct got_pathlist_entry *pe;
6634 int ch, can_recurse = 0, no_ignores = 0;
6636 TAILQ_INIT(&paths);
6638 while ((ch = getopt(argc, argv, "IR")) != -1) {
6639 switch (ch) {
6640 case 'I':
6641 no_ignores = 1;
6642 break;
6643 case 'R':
6644 can_recurse = 1;
6645 break;
6646 default:
6647 usage_add();
6648 /* NOTREACHED */
6652 argc -= optind;
6653 argv += optind;
6655 #ifndef PROFILE
6656 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6657 NULL) == -1)
6658 err(1, "pledge");
6659 #endif
6660 if (argc < 1)
6661 usage_add();
6663 cwd = getcwd(NULL, 0);
6664 if (cwd == NULL) {
6665 error = got_error_from_errno("getcwd");
6666 goto done;
6669 error = got_worktree_open(&worktree, cwd);
6670 if (error) {
6671 if (error->code == GOT_ERR_NOT_WORKTREE)
6672 error = wrap_not_worktree_error(error, "add", cwd);
6673 goto done;
6676 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6677 NULL);
6678 if (error != NULL)
6679 goto done;
6681 error = apply_unveil(got_repo_get_path(repo), 1,
6682 got_worktree_get_root_path(worktree));
6683 if (error)
6684 goto done;
6686 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6687 if (error)
6688 goto done;
6690 if (!can_recurse) {
6691 char *ondisk_path;
6692 struct stat sb;
6693 TAILQ_FOREACH(pe, &paths, entry) {
6694 if (asprintf(&ondisk_path, "%s/%s",
6695 got_worktree_get_root_path(worktree),
6696 pe->path) == -1) {
6697 error = got_error_from_errno("asprintf");
6698 goto done;
6700 if (lstat(ondisk_path, &sb) == -1) {
6701 if (errno == ENOENT) {
6702 free(ondisk_path);
6703 continue;
6705 error = got_error_from_errno2("lstat",
6706 ondisk_path);
6707 free(ondisk_path);
6708 goto done;
6710 free(ondisk_path);
6711 if (S_ISDIR(sb.st_mode)) {
6712 error = got_error_msg(GOT_ERR_BAD_PATH,
6713 "adding directories requires -R option");
6714 goto done;
6719 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6720 NULL, repo, no_ignores);
6721 done:
6722 if (repo) {
6723 const struct got_error *close_err = got_repo_close(repo);
6724 if (error == NULL)
6725 error = close_err;
6727 if (worktree)
6728 got_worktree_close(worktree);
6729 TAILQ_FOREACH(pe, &paths, entry)
6730 free((char *)pe->path);
6731 got_pathlist_free(&paths);
6732 free(cwd);
6733 return error;
6736 __dead static void
6737 usage_remove(void)
6739 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6740 "path ...\n", getprogname());
6741 exit(1);
6744 static const struct got_error *
6745 print_remove_status(void *arg, unsigned char status,
6746 unsigned char staged_status, const char *path)
6748 while (path[0] == '/')
6749 path++;
6750 if (status == GOT_STATUS_NONEXISTENT)
6751 return NULL;
6752 if (status == staged_status && (status == GOT_STATUS_DELETE))
6753 status = GOT_STATUS_NO_CHANGE;
6754 printf("%c%c %s\n", status, staged_status, path);
6755 return NULL;
6758 static const struct got_error *
6759 cmd_remove(int argc, char *argv[])
6761 const struct got_error *error = NULL;
6762 struct got_worktree *worktree = NULL;
6763 struct got_repository *repo = NULL;
6764 const char *status_codes = NULL;
6765 char *cwd = NULL;
6766 struct got_pathlist_head paths;
6767 struct got_pathlist_entry *pe;
6768 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6770 TAILQ_INIT(&paths);
6772 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6773 switch (ch) {
6774 case 'f':
6775 delete_local_mods = 1;
6776 break;
6777 case 'k':
6778 keep_on_disk = 1;
6779 break;
6780 case 'R':
6781 can_recurse = 1;
6782 break;
6783 case 's':
6784 for (i = 0; i < strlen(optarg); i++) {
6785 switch (optarg[i]) {
6786 case GOT_STATUS_MODIFY:
6787 delete_local_mods = 1;
6788 break;
6789 case GOT_STATUS_MISSING:
6790 break;
6791 default:
6792 errx(1, "invalid status code '%c'",
6793 optarg[i]);
6796 status_codes = optarg;
6797 break;
6798 default:
6799 usage_remove();
6800 /* NOTREACHED */
6804 argc -= optind;
6805 argv += optind;
6807 #ifndef PROFILE
6808 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6809 NULL) == -1)
6810 err(1, "pledge");
6811 #endif
6812 if (argc < 1)
6813 usage_remove();
6815 cwd = getcwd(NULL, 0);
6816 if (cwd == NULL) {
6817 error = got_error_from_errno("getcwd");
6818 goto done;
6820 error = got_worktree_open(&worktree, cwd);
6821 if (error) {
6822 if (error->code == GOT_ERR_NOT_WORKTREE)
6823 error = wrap_not_worktree_error(error, "remove", cwd);
6824 goto done;
6827 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6828 NULL);
6829 if (error)
6830 goto done;
6832 error = apply_unveil(got_repo_get_path(repo), 1,
6833 got_worktree_get_root_path(worktree));
6834 if (error)
6835 goto done;
6837 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6838 if (error)
6839 goto done;
6841 if (!can_recurse) {
6842 char *ondisk_path;
6843 struct stat sb;
6844 TAILQ_FOREACH(pe, &paths, entry) {
6845 if (asprintf(&ondisk_path, "%s/%s",
6846 got_worktree_get_root_path(worktree),
6847 pe->path) == -1) {
6848 error = got_error_from_errno("asprintf");
6849 goto done;
6851 if (lstat(ondisk_path, &sb) == -1) {
6852 if (errno == ENOENT) {
6853 free(ondisk_path);
6854 continue;
6856 error = got_error_from_errno2("lstat",
6857 ondisk_path);
6858 free(ondisk_path);
6859 goto done;
6861 free(ondisk_path);
6862 if (S_ISDIR(sb.st_mode)) {
6863 error = got_error_msg(GOT_ERR_BAD_PATH,
6864 "removing directories requires -R option");
6865 goto done;
6870 error = got_worktree_schedule_delete(worktree, &paths,
6871 delete_local_mods, status_codes, print_remove_status, NULL,
6872 repo, keep_on_disk);
6873 done:
6874 if (repo) {
6875 const struct got_error *close_err = got_repo_close(repo);
6876 if (error == NULL)
6877 error = close_err;
6879 if (worktree)
6880 got_worktree_close(worktree);
6881 TAILQ_FOREACH(pe, &paths, entry)
6882 free((char *)pe->path);
6883 got_pathlist_free(&paths);
6884 free(cwd);
6885 return error;
6888 __dead static void
6889 usage_revert(void)
6891 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6892 "path ...\n", getprogname());
6893 exit(1);
6896 static const struct got_error *
6897 revert_progress(void *arg, unsigned char status, const char *path)
6899 if (status == GOT_STATUS_UNVERSIONED)
6900 return NULL;
6902 while (path[0] == '/')
6903 path++;
6904 printf("%c %s\n", status, path);
6905 return NULL;
6908 struct choose_patch_arg {
6909 FILE *patch_script_file;
6910 const char *action;
6913 static const struct got_error *
6914 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6915 int nchanges, const char *action)
6917 char *line = NULL;
6918 size_t linesize = 0;
6919 ssize_t linelen;
6921 switch (status) {
6922 case GOT_STATUS_ADD:
6923 printf("A %s\n%s this addition? [y/n] ", path, action);
6924 break;
6925 case GOT_STATUS_DELETE:
6926 printf("D %s\n%s this deletion? [y/n] ", path, action);
6927 break;
6928 case GOT_STATUS_MODIFY:
6929 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6930 return got_error_from_errno("fseek");
6931 printf(GOT_COMMIT_SEP_STR);
6932 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6933 printf("%s", line);
6934 if (ferror(patch_file))
6935 return got_error_from_errno("getline");
6936 printf(GOT_COMMIT_SEP_STR);
6937 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6938 path, n, nchanges, action);
6939 break;
6940 default:
6941 return got_error_path(path, GOT_ERR_FILE_STATUS);
6944 return NULL;
6947 static const struct got_error *
6948 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6949 FILE *patch_file, int n, int nchanges)
6951 const struct got_error *err = NULL;
6952 char *line = NULL;
6953 size_t linesize = 0;
6954 ssize_t linelen;
6955 int resp = ' ';
6956 struct choose_patch_arg *a = arg;
6958 *choice = GOT_PATCH_CHOICE_NONE;
6960 if (a->patch_script_file) {
6961 char *nl;
6962 err = show_change(status, path, patch_file, n, nchanges,
6963 a->action);
6964 if (err)
6965 return err;
6966 linelen = getline(&line, &linesize, a->patch_script_file);
6967 if (linelen == -1) {
6968 if (ferror(a->patch_script_file))
6969 return got_error_from_errno("getline");
6970 return NULL;
6972 nl = strchr(line, '\n');
6973 if (nl)
6974 *nl = '\0';
6975 if (strcmp(line, "y") == 0) {
6976 *choice = GOT_PATCH_CHOICE_YES;
6977 printf("y\n");
6978 } else if (strcmp(line, "n") == 0) {
6979 *choice = GOT_PATCH_CHOICE_NO;
6980 printf("n\n");
6981 } else if (strcmp(line, "q") == 0 &&
6982 status == GOT_STATUS_MODIFY) {
6983 *choice = GOT_PATCH_CHOICE_QUIT;
6984 printf("q\n");
6985 } else
6986 printf("invalid response '%s'\n", line);
6987 free(line);
6988 return NULL;
6991 while (resp != 'y' && resp != 'n' && resp != 'q') {
6992 err = show_change(status, path, patch_file, n, nchanges,
6993 a->action);
6994 if (err)
6995 return err;
6996 resp = getchar();
6997 if (resp == '\n')
6998 resp = getchar();
6999 if (status == GOT_STATUS_MODIFY) {
7000 if (resp != 'y' && resp != 'n' && resp != 'q') {
7001 printf("invalid response '%c'\n", resp);
7002 resp = ' ';
7004 } else if (resp != 'y' && resp != 'n') {
7005 printf("invalid response '%c'\n", resp);
7006 resp = ' ';
7010 if (resp == 'y')
7011 *choice = GOT_PATCH_CHOICE_YES;
7012 else if (resp == 'n')
7013 *choice = GOT_PATCH_CHOICE_NO;
7014 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7015 *choice = GOT_PATCH_CHOICE_QUIT;
7017 return NULL;
7021 static const struct got_error *
7022 cmd_revert(int argc, char *argv[])
7024 const struct got_error *error = NULL;
7025 struct got_worktree *worktree = NULL;
7026 struct got_repository *repo = NULL;
7027 char *cwd = NULL, *path = NULL;
7028 struct got_pathlist_head paths;
7029 struct got_pathlist_entry *pe;
7030 int ch, can_recurse = 0, pflag = 0;
7031 FILE *patch_script_file = NULL;
7032 const char *patch_script_path = NULL;
7033 struct choose_patch_arg cpa;
7035 TAILQ_INIT(&paths);
7037 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7038 switch (ch) {
7039 case 'p':
7040 pflag = 1;
7041 break;
7042 case 'F':
7043 patch_script_path = optarg;
7044 break;
7045 case 'R':
7046 can_recurse = 1;
7047 break;
7048 default:
7049 usage_revert();
7050 /* NOTREACHED */
7054 argc -= optind;
7055 argv += optind;
7057 #ifndef PROFILE
7058 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7059 "unveil", NULL) == -1)
7060 err(1, "pledge");
7061 #endif
7062 if (argc < 1)
7063 usage_revert();
7064 if (patch_script_path && !pflag)
7065 errx(1, "-F option can only be used together with -p option");
7067 cwd = getcwd(NULL, 0);
7068 if (cwd == NULL) {
7069 error = got_error_from_errno("getcwd");
7070 goto done;
7072 error = got_worktree_open(&worktree, cwd);
7073 if (error) {
7074 if (error->code == GOT_ERR_NOT_WORKTREE)
7075 error = wrap_not_worktree_error(error, "revert", cwd);
7076 goto done;
7079 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7080 NULL);
7081 if (error != NULL)
7082 goto done;
7084 if (patch_script_path) {
7085 patch_script_file = fopen(patch_script_path, "r");
7086 if (patch_script_file == NULL) {
7087 error = got_error_from_errno2("fopen",
7088 patch_script_path);
7089 goto done;
7092 error = apply_unveil(got_repo_get_path(repo), 1,
7093 got_worktree_get_root_path(worktree));
7094 if (error)
7095 goto done;
7097 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7098 if (error)
7099 goto done;
7101 if (!can_recurse) {
7102 char *ondisk_path;
7103 struct stat sb;
7104 TAILQ_FOREACH(pe, &paths, entry) {
7105 if (asprintf(&ondisk_path, "%s/%s",
7106 got_worktree_get_root_path(worktree),
7107 pe->path) == -1) {
7108 error = got_error_from_errno("asprintf");
7109 goto done;
7111 if (lstat(ondisk_path, &sb) == -1) {
7112 if (errno == ENOENT) {
7113 free(ondisk_path);
7114 continue;
7116 error = got_error_from_errno2("lstat",
7117 ondisk_path);
7118 free(ondisk_path);
7119 goto done;
7121 free(ondisk_path);
7122 if (S_ISDIR(sb.st_mode)) {
7123 error = got_error_msg(GOT_ERR_BAD_PATH,
7124 "reverting directories requires -R option");
7125 goto done;
7130 cpa.patch_script_file = patch_script_file;
7131 cpa.action = "revert";
7132 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7133 pflag ? choose_patch : NULL, &cpa, repo);
7134 done:
7135 if (patch_script_file && fclose(patch_script_file) == EOF &&
7136 error == NULL)
7137 error = got_error_from_errno2("fclose", patch_script_path);
7138 if (repo) {
7139 const struct got_error *close_err = got_repo_close(repo);
7140 if (error == NULL)
7141 error = close_err;
7143 if (worktree)
7144 got_worktree_close(worktree);
7145 free(path);
7146 free(cwd);
7147 return error;
7150 __dead static void
7151 usage_commit(void)
7153 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7154 "[path ...]\n", getprogname());
7155 exit(1);
7158 struct collect_commit_logmsg_arg {
7159 const char *cmdline_log;
7160 const char *prepared_log;
7161 int non_interactive;
7162 const char *editor;
7163 const char *worktree_path;
7164 const char *branch_name;
7165 const char *repo_path;
7166 char *logmsg_path;
7170 static const struct got_error *
7171 read_prepared_logmsg(char **logmsg, const char *path)
7173 const struct got_error *err = NULL;
7174 FILE *f = NULL;
7175 struct stat sb;
7176 size_t r;
7178 *logmsg = NULL;
7179 memset(&sb, 0, sizeof(sb));
7181 f = fopen(path, "r");
7182 if (f == NULL)
7183 return got_error_from_errno2("fopen", path);
7185 if (fstat(fileno(f), &sb) == -1) {
7186 err = got_error_from_errno2("fstat", path);
7187 goto done;
7189 if (sb.st_size == 0) {
7190 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7191 goto done;
7194 *logmsg = malloc(sb.st_size + 1);
7195 if (*logmsg == NULL) {
7196 err = got_error_from_errno("malloc");
7197 goto done;
7200 r = fread(*logmsg, 1, sb.st_size, f);
7201 if (r != sb.st_size) {
7202 if (ferror(f))
7203 err = got_error_from_errno2("fread", path);
7204 else
7205 err = got_error(GOT_ERR_IO);
7206 goto done;
7208 (*logmsg)[sb.st_size] = '\0';
7209 done:
7210 if (fclose(f) == EOF && err == NULL)
7211 err = got_error_from_errno2("fclose", path);
7212 if (err) {
7213 free(*logmsg);
7214 *logmsg = NULL;
7216 return err;
7220 static const struct got_error *
7221 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7222 void *arg)
7224 char *initial_content = NULL;
7225 struct got_pathlist_entry *pe;
7226 const struct got_error *err = NULL;
7227 char *template = NULL;
7228 struct collect_commit_logmsg_arg *a = arg;
7229 int initial_content_len;
7230 int fd = -1;
7231 size_t len;
7233 /* if a message was specified on the command line, just use it */
7234 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7235 len = strlen(a->cmdline_log) + 1;
7236 *logmsg = malloc(len + 1);
7237 if (*logmsg == NULL)
7238 return got_error_from_errno("malloc");
7239 strlcpy(*logmsg, a->cmdline_log, len);
7240 return NULL;
7241 } else if (a->prepared_log != NULL && a->non_interactive)
7242 return read_prepared_logmsg(logmsg, a->prepared_log);
7244 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7245 return got_error_from_errno("asprintf");
7247 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7248 if (err)
7249 goto done;
7251 if (a->prepared_log) {
7252 char *msg;
7253 err = read_prepared_logmsg(&msg, a->prepared_log);
7254 if (err)
7255 goto done;
7256 if (write(fd, msg, strlen(msg)) == -1) {
7257 err = got_error_from_errno2("write", a->logmsg_path);
7258 free(msg);
7259 goto done;
7261 free(msg);
7264 initial_content_len = asprintf(&initial_content,
7265 "\n# changes to be committed on branch %s:\n",
7266 a->branch_name);
7267 if (initial_content_len == -1) {
7268 err = got_error_from_errno("asprintf");
7269 goto done;
7272 if (write(fd, initial_content, initial_content_len) == -1) {
7273 err = got_error_from_errno2("write", a->logmsg_path);
7274 goto done;
7277 TAILQ_FOREACH(pe, commitable_paths, entry) {
7278 struct got_commitable *ct = pe->data;
7279 dprintf(fd, "# %c %s\n",
7280 got_commitable_get_status(ct),
7281 got_commitable_get_path(ct));
7284 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7285 initial_content_len, a->prepared_log ? 0 : 1);
7286 done:
7287 free(initial_content);
7288 free(template);
7290 if (fd != -1 && close(fd) == -1 && err == NULL)
7291 err = got_error_from_errno2("close", a->logmsg_path);
7293 /* Editor is done; we can now apply unveil(2) */
7294 if (err == NULL)
7295 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7296 if (err) {
7297 free(*logmsg);
7298 *logmsg = NULL;
7300 return err;
7303 static const struct got_error *
7304 cmd_commit(int argc, char *argv[])
7306 const struct got_error *error = NULL;
7307 struct got_worktree *worktree = NULL;
7308 struct got_repository *repo = NULL;
7309 char *cwd = NULL, *id_str = NULL;
7310 struct got_object_id *id = NULL;
7311 const char *logmsg = NULL;
7312 char *prepared_logmsg = NULL;
7313 struct collect_commit_logmsg_arg cl_arg;
7314 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7315 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7316 int allow_bad_symlinks = 0, non_interactive = 0;
7317 struct got_pathlist_head paths;
7319 TAILQ_INIT(&paths);
7320 cl_arg.logmsg_path = NULL;
7322 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7323 switch (ch) {
7324 case 'F':
7325 if (logmsg != NULL)
7326 option_conflict('F', 'm');
7327 prepared_logmsg = realpath(optarg, NULL);
7328 if (prepared_logmsg == NULL)
7329 return got_error_from_errno2("realpath",
7330 optarg);
7331 break;
7332 case 'm':
7333 if (prepared_logmsg)
7334 option_conflict('m', 'F');
7335 logmsg = optarg;
7336 break;
7337 case 'N':
7338 non_interactive = 1;
7339 break;
7340 case 'S':
7341 allow_bad_symlinks = 1;
7342 break;
7343 default:
7344 usage_commit();
7345 /* NOTREACHED */
7349 argc -= optind;
7350 argv += optind;
7352 #ifndef PROFILE
7353 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7354 "unveil", NULL) == -1)
7355 err(1, "pledge");
7356 #endif
7357 cwd = getcwd(NULL, 0);
7358 if (cwd == NULL) {
7359 error = got_error_from_errno("getcwd");
7360 goto done;
7362 error = got_worktree_open(&worktree, cwd);
7363 if (error) {
7364 if (error->code == GOT_ERR_NOT_WORKTREE)
7365 error = wrap_not_worktree_error(error, "commit", cwd);
7366 goto done;
7369 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7370 if (error)
7371 goto done;
7372 if (rebase_in_progress) {
7373 error = got_error(GOT_ERR_REBASING);
7374 goto done;
7377 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7378 worktree);
7379 if (error)
7380 goto done;
7382 error = get_gitconfig_path(&gitconfig_path);
7383 if (error)
7384 goto done;
7385 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7386 gitconfig_path);
7387 if (error != NULL)
7388 goto done;
7390 error = get_author(&author, repo, worktree);
7391 if (error)
7392 return error;
7395 * unveil(2) traverses exec(2); if an editor is used we have
7396 * to apply unveil after the log message has been written.
7398 if (logmsg == NULL || strlen(logmsg) == 0)
7399 error = get_editor(&editor);
7400 else
7401 error = apply_unveil(got_repo_get_path(repo), 0,
7402 got_worktree_get_root_path(worktree));
7403 if (error)
7404 goto done;
7406 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7407 if (error)
7408 goto done;
7410 cl_arg.editor = editor;
7411 cl_arg.cmdline_log = logmsg;
7412 cl_arg.prepared_log = prepared_logmsg;
7413 cl_arg.non_interactive = non_interactive;
7414 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7415 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7416 if (!histedit_in_progress) {
7417 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7418 error = got_error(GOT_ERR_COMMIT_BRANCH);
7419 goto done;
7421 cl_arg.branch_name += 11;
7423 cl_arg.repo_path = got_repo_get_path(repo);
7424 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7425 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7426 print_status, NULL, repo);
7427 if (error) {
7428 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7429 cl_arg.logmsg_path != NULL)
7430 preserve_logmsg = 1;
7431 goto done;
7434 error = got_object_id_str(&id_str, id);
7435 if (error)
7436 goto done;
7437 printf("Created commit %s\n", id_str);
7438 done:
7439 if (preserve_logmsg) {
7440 fprintf(stderr, "%s: log message preserved in %s\n",
7441 getprogname(), cl_arg.logmsg_path);
7442 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7443 error == NULL)
7444 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7445 free(cl_arg.logmsg_path);
7446 if (repo) {
7447 const struct got_error *close_err = got_repo_close(repo);
7448 if (error == NULL)
7449 error = close_err;
7451 if (worktree)
7452 got_worktree_close(worktree);
7453 free(cwd);
7454 free(id_str);
7455 free(gitconfig_path);
7456 free(editor);
7457 free(author);
7458 free(prepared_logmsg);
7459 return error;
7462 __dead static void
7463 usage_send(void)
7465 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7466 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7467 "[remote-repository]\n", getprogname());
7468 exit(1);
7471 struct got_send_progress_arg {
7472 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7473 int verbosity;
7474 int last_ncommits;
7475 int last_nobj_total;
7476 int last_p_deltify;
7477 int last_p_written;
7478 int last_p_sent;
7479 int printed_something;
7480 int sent_something;
7481 struct got_pathlist_head *delete_branches;
7484 static const struct got_error *
7485 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7486 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7487 int success)
7489 struct got_send_progress_arg *a = arg;
7490 char scaled_packsize[FMT_SCALED_STRSIZE];
7491 char scaled_sent[FMT_SCALED_STRSIZE];
7492 int p_deltify = 0, p_written = 0, p_sent = 0;
7493 int print_searching = 0, print_total = 0;
7494 int print_deltify = 0, print_written = 0, print_sent = 0;
7496 if (a->verbosity < 0)
7497 return NULL;
7499 if (refname) {
7500 const char *status = success ? "accepted" : "rejected";
7502 if (success) {
7503 struct got_pathlist_entry *pe;
7504 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7505 const char *branchname = pe->path;
7506 if (got_path_cmp(branchname, refname,
7507 strlen(branchname), strlen(refname)) == 0) {
7508 status = "deleted";
7509 a->sent_something = 1;
7510 break;
7515 if (a->printed_something)
7516 putchar('\n');
7517 printf("Server has %s %s", status, refname);
7518 a->printed_something = 1;
7519 return NULL;
7522 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7523 return got_error_from_errno("fmt_scaled");
7524 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7525 return got_error_from_errno("fmt_scaled");
7527 if (a->last_ncommits != ncommits) {
7528 print_searching = 1;
7529 a->last_ncommits = ncommits;
7532 if (a->last_nobj_total != nobj_total) {
7533 print_searching = 1;
7534 print_total = 1;
7535 a->last_nobj_total = nobj_total;
7538 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7539 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7540 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7541 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7542 return got_error(GOT_ERR_NO_SPACE);
7545 if (nobj_deltify > 0 || nobj_written > 0) {
7546 if (nobj_deltify > 0) {
7547 p_deltify = (nobj_deltify * 100) / nobj_total;
7548 if (p_deltify != a->last_p_deltify) {
7549 a->last_p_deltify = p_deltify;
7550 print_searching = 1;
7551 print_total = 1;
7552 print_deltify = 1;
7555 if (nobj_written > 0) {
7556 p_written = (nobj_written * 100) / nobj_total;
7557 if (p_written != a->last_p_written) {
7558 a->last_p_written = p_written;
7559 print_searching = 1;
7560 print_total = 1;
7561 print_deltify = 1;
7562 print_written = 1;
7567 if (bytes_sent > 0) {
7568 p_sent = (bytes_sent * 100) / packfile_size;
7569 if (p_sent != a->last_p_sent) {
7570 a->last_p_sent = p_sent;
7571 print_searching = 1;
7572 print_total = 1;
7573 print_deltify = 1;
7574 print_written = 1;
7575 print_sent = 1;
7577 a->sent_something = 1;
7580 if (print_searching || print_total || print_deltify || print_written ||
7581 print_sent)
7582 printf("\r");
7583 if (print_searching)
7584 printf("packing %d reference%s", ncommits,
7585 ncommits == 1 ? "" : "s");
7586 if (print_total)
7587 printf("; %d object%s", nobj_total,
7588 nobj_total == 1 ? "" : "s");
7589 if (print_deltify)
7590 printf("; deltify: %d%%", p_deltify);
7591 if (print_sent)
7592 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7593 scaled_packsize, p_sent);
7594 else if (print_written)
7595 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7596 scaled_packsize, p_written);
7597 if (print_searching || print_total || print_deltify ||
7598 print_written || print_sent) {
7599 a->printed_something = 1;
7600 fflush(stdout);
7602 return NULL;
7605 static const struct got_error *
7606 cmd_send(int argc, char *argv[])
7608 const struct got_error *error = NULL;
7609 char *cwd = NULL, *repo_path = NULL;
7610 const char *remote_name;
7611 char *proto = NULL, *host = NULL, *port = NULL;
7612 char *repo_name = NULL, *server_path = NULL;
7613 const struct got_remote_repo *remotes, *remote = NULL;
7614 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7615 struct got_repository *repo = NULL;
7616 struct got_worktree *worktree = NULL;
7617 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7618 struct got_pathlist_head branches;
7619 struct got_pathlist_head tags;
7620 struct got_reflist_head all_branches;
7621 struct got_reflist_head all_tags;
7622 struct got_pathlist_head delete_args;
7623 struct got_pathlist_head delete_branches;
7624 struct got_reflist_entry *re;
7625 struct got_pathlist_entry *pe;
7626 int i, ch, sendfd = -1, sendstatus;
7627 pid_t sendpid = -1;
7628 struct got_send_progress_arg spa;
7629 int verbosity = 0, overwrite_refs = 0;
7630 int send_all_branches = 0, send_all_tags = 0;
7631 struct got_reference *ref = NULL;
7633 TAILQ_INIT(&branches);
7634 TAILQ_INIT(&tags);
7635 TAILQ_INIT(&all_branches);
7636 TAILQ_INIT(&all_tags);
7637 TAILQ_INIT(&delete_args);
7638 TAILQ_INIT(&delete_branches);
7640 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7641 switch (ch) {
7642 case 'a':
7643 send_all_branches = 1;
7644 break;
7645 case 'b':
7646 error = got_pathlist_append(&branches, optarg, NULL);
7647 if (error)
7648 return error;
7649 nbranches++;
7650 break;
7651 case 'd':
7652 error = got_pathlist_append(&delete_args, optarg, NULL);
7653 if (error)
7654 return error;
7655 break;
7656 case 'f':
7657 overwrite_refs = 1;
7658 break;
7659 case 'r':
7660 repo_path = realpath(optarg, NULL);
7661 if (repo_path == NULL)
7662 return got_error_from_errno2("realpath",
7663 optarg);
7664 got_path_strip_trailing_slashes(repo_path);
7665 break;
7666 case 't':
7667 error = got_pathlist_append(&tags, optarg, NULL);
7668 if (error)
7669 return error;
7670 ntags++;
7671 break;
7672 case 'T':
7673 send_all_tags = 1;
7674 break;
7675 case 'v':
7676 if (verbosity < 0)
7677 verbosity = 0;
7678 else if (verbosity < 3)
7679 verbosity++;
7680 break;
7681 case 'q':
7682 verbosity = -1;
7683 break;
7684 default:
7685 usage_send();
7686 /* NOTREACHED */
7689 argc -= optind;
7690 argv += optind;
7692 if (send_all_branches && !TAILQ_EMPTY(&branches))
7693 option_conflict('a', 'b');
7694 if (send_all_tags && !TAILQ_EMPTY(&tags))
7695 option_conflict('T', 't');
7698 if (argc == 0)
7699 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7700 else if (argc == 1)
7701 remote_name = argv[0];
7702 else
7703 usage_send();
7705 cwd = getcwd(NULL, 0);
7706 if (cwd == NULL) {
7707 error = got_error_from_errno("getcwd");
7708 goto done;
7711 if (repo_path == NULL) {
7712 error = got_worktree_open(&worktree, cwd);
7713 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7714 goto done;
7715 else
7716 error = NULL;
7717 if (worktree) {
7718 repo_path =
7719 strdup(got_worktree_get_repo_path(worktree));
7720 if (repo_path == NULL)
7721 error = got_error_from_errno("strdup");
7722 if (error)
7723 goto done;
7724 } else {
7725 repo_path = strdup(cwd);
7726 if (repo_path == NULL) {
7727 error = got_error_from_errno("strdup");
7728 goto done;
7733 error = got_repo_open(&repo, repo_path, NULL);
7734 if (error)
7735 goto done;
7737 if (worktree) {
7738 worktree_conf = got_worktree_get_gotconfig(worktree);
7739 if (worktree_conf) {
7740 got_gotconfig_get_remotes(&nremotes, &remotes,
7741 worktree_conf);
7742 for (i = 0; i < nremotes; i++) {
7743 if (strcmp(remotes[i].name, remote_name) == 0) {
7744 remote = &remotes[i];
7745 break;
7750 if (remote == NULL) {
7751 repo_conf = got_repo_get_gotconfig(repo);
7752 if (repo_conf) {
7753 got_gotconfig_get_remotes(&nremotes, &remotes,
7754 repo_conf);
7755 for (i = 0; i < nremotes; i++) {
7756 if (strcmp(remotes[i].name, remote_name) == 0) {
7757 remote = &remotes[i];
7758 break;
7763 if (remote == NULL) {
7764 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7765 for (i = 0; i < nremotes; i++) {
7766 if (strcmp(remotes[i].name, remote_name) == 0) {
7767 remote = &remotes[i];
7768 break;
7772 if (remote == NULL) {
7773 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7774 goto done;
7777 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7778 &repo_name, remote->send_url);
7779 if (error)
7780 goto done;
7782 if (strcmp(proto, "git") == 0) {
7783 #ifndef PROFILE
7784 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7785 "sendfd dns inet unveil", NULL) == -1)
7786 err(1, "pledge");
7787 #endif
7788 } else if (strcmp(proto, "git+ssh") == 0 ||
7789 strcmp(proto, "ssh") == 0) {
7790 #ifndef PROFILE
7791 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7792 "sendfd unveil", NULL) == -1)
7793 err(1, "pledge");
7794 #endif
7795 } else if (strcmp(proto, "http") == 0 ||
7796 strcmp(proto, "git+http") == 0) {
7797 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7798 goto done;
7799 } else {
7800 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7801 goto done;
7804 error = got_dial_apply_unveil(proto);
7805 if (error)
7806 goto done;
7808 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7809 if (error)
7810 goto done;
7812 if (send_all_branches) {
7813 error = got_ref_list(&all_branches, repo, "refs/heads",
7814 got_ref_cmp_by_name, NULL);
7815 if (error)
7816 goto done;
7817 TAILQ_FOREACH(re, &all_branches, entry) {
7818 const char *branchname = got_ref_get_name(re->ref);
7819 error = got_pathlist_append(&branches,
7820 branchname, NULL);
7821 if (error)
7822 goto done;
7823 nbranches++;
7825 } else if (nbranches == 0) {
7826 for (i = 0; i < remote->nsend_branches; i++) {
7827 got_pathlist_append(&branches,
7828 remote->send_branches[i], NULL);
7832 if (send_all_tags) {
7833 error = got_ref_list(&all_tags, repo, "refs/tags",
7834 got_ref_cmp_by_name, NULL);
7835 if (error)
7836 goto done;
7837 TAILQ_FOREACH(re, &all_tags, entry) {
7838 const char *tagname = got_ref_get_name(re->ref);
7839 error = got_pathlist_append(&tags,
7840 tagname, NULL);
7841 if (error)
7842 goto done;
7843 ntags++;
7848 * To prevent accidents only branches in refs/heads/ can be deleted
7849 * with 'got send -d'.
7850 * Deleting anything else requires local repository access or Git.
7852 TAILQ_FOREACH(pe, &delete_args, entry) {
7853 const char *branchname = pe->path;
7854 char *s;
7855 struct got_pathlist_entry *new;
7856 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7857 s = strdup(branchname);
7858 if (s == NULL) {
7859 error = got_error_from_errno("strdup");
7860 goto done;
7862 } else {
7863 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7864 error = got_error_from_errno("asprintf");
7865 goto done;
7868 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7869 if (error || new == NULL /* duplicate */)
7870 free(s);
7871 if (error)
7872 goto done;
7873 ndelete_branches++;
7876 if (nbranches == 0 && ndelete_branches == 0) {
7877 struct got_reference *head_ref;
7878 if (worktree)
7879 error = got_ref_open(&head_ref, repo,
7880 got_worktree_get_head_ref_name(worktree), 0);
7881 else
7882 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7883 if (error)
7884 goto done;
7885 if (got_ref_is_symbolic(head_ref)) {
7886 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7887 got_ref_close(head_ref);
7888 if (error)
7889 goto done;
7890 } else
7891 ref = head_ref;
7892 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7893 NULL);
7894 if (error)
7895 goto done;
7896 nbranches++;
7899 if (verbosity >= 0)
7900 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7901 port ? ":" : "", port ? port : "");
7903 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7904 server_path, verbosity);
7905 if (error)
7906 goto done;
7908 memset(&spa, 0, sizeof(spa));
7909 spa.last_scaled_packsize[0] = '\0';
7910 spa.last_p_deltify = -1;
7911 spa.last_p_written = -1;
7912 spa.verbosity = verbosity;
7913 spa.delete_branches = &delete_branches;
7914 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7915 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7916 check_cancelled, NULL);
7917 if (spa.printed_something)
7918 putchar('\n');
7919 if (error)
7920 goto done;
7921 if (!spa.sent_something && verbosity >= 0)
7922 printf("Already up-to-date\n");
7923 done:
7924 if (sendpid > 0) {
7925 if (kill(sendpid, SIGTERM) == -1)
7926 error = got_error_from_errno("kill");
7927 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7928 error = got_error_from_errno("waitpid");
7930 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7931 error = got_error_from_errno("close");
7932 if (repo) {
7933 const struct got_error *close_err = got_repo_close(repo);
7934 if (error == NULL)
7935 error = close_err;
7937 if (worktree)
7938 got_worktree_close(worktree);
7939 if (ref)
7940 got_ref_close(ref);
7941 got_pathlist_free(&branches);
7942 got_pathlist_free(&tags);
7943 got_ref_list_free(&all_branches);
7944 got_ref_list_free(&all_tags);
7945 got_pathlist_free(&delete_args);
7946 TAILQ_FOREACH(pe, &delete_branches, entry)
7947 free((char *)pe->path);
7948 got_pathlist_free(&delete_branches);
7949 free(cwd);
7950 free(repo_path);
7951 free(proto);
7952 free(host);
7953 free(port);
7954 free(server_path);
7955 free(repo_name);
7956 return error;
7959 __dead static void
7960 usage_cherrypick(void)
7962 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7963 exit(1);
7966 static const struct got_error *
7967 cmd_cherrypick(int argc, char *argv[])
7969 const struct got_error *error = NULL;
7970 struct got_worktree *worktree = NULL;
7971 struct got_repository *repo = NULL;
7972 char *cwd = NULL, *commit_id_str = NULL;
7973 struct got_object_id *commit_id = NULL;
7974 struct got_commit_object *commit = NULL;
7975 struct got_object_qid *pid;
7976 int ch;
7977 struct got_update_progress_arg upa;
7979 while ((ch = getopt(argc, argv, "")) != -1) {
7980 switch (ch) {
7981 default:
7982 usage_cherrypick();
7983 /* NOTREACHED */
7987 argc -= optind;
7988 argv += optind;
7990 #ifndef PROFILE
7991 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7992 "unveil", NULL) == -1)
7993 err(1, "pledge");
7994 #endif
7995 if (argc != 1)
7996 usage_cherrypick();
7998 cwd = getcwd(NULL, 0);
7999 if (cwd == NULL) {
8000 error = got_error_from_errno("getcwd");
8001 goto done;
8003 error = got_worktree_open(&worktree, cwd);
8004 if (error) {
8005 if (error->code == GOT_ERR_NOT_WORKTREE)
8006 error = wrap_not_worktree_error(error, "cherrypick",
8007 cwd);
8008 goto done;
8011 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8012 NULL);
8013 if (error != NULL)
8014 goto done;
8016 error = apply_unveil(got_repo_get_path(repo), 0,
8017 got_worktree_get_root_path(worktree));
8018 if (error)
8019 goto done;
8021 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8022 GOT_OBJ_TYPE_COMMIT, repo);
8023 if (error != NULL) {
8024 struct got_reference *ref;
8025 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8026 goto done;
8027 error = got_ref_open(&ref, repo, argv[0], 0);
8028 if (error != NULL)
8029 goto done;
8030 error = got_ref_resolve(&commit_id, repo, ref);
8031 got_ref_close(ref);
8032 if (error != NULL)
8033 goto done;
8035 error = got_object_id_str(&commit_id_str, commit_id);
8036 if (error)
8037 goto done;
8039 error = got_object_open_as_commit(&commit, repo, commit_id);
8040 if (error)
8041 goto done;
8042 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8043 memset(&upa, 0, sizeof(upa));
8044 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8045 commit_id, repo, update_progress, &upa, check_cancelled,
8046 NULL);
8047 if (error != NULL)
8048 goto done;
8050 if (upa.did_something)
8051 printf("Merged commit %s\n", commit_id_str);
8052 print_update_progress_stats(&upa);
8053 done:
8054 if (commit)
8055 got_object_commit_close(commit);
8056 free(commit_id_str);
8057 if (worktree)
8058 got_worktree_close(worktree);
8059 if (repo) {
8060 const struct got_error *close_err = got_repo_close(repo);
8061 if (error == NULL)
8062 error = close_err;
8064 return error;
8067 __dead static void
8068 usage_backout(void)
8070 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8071 exit(1);
8074 static const struct got_error *
8075 cmd_backout(int argc, char *argv[])
8077 const struct got_error *error = NULL;
8078 struct got_worktree *worktree = NULL;
8079 struct got_repository *repo = NULL;
8080 char *cwd = NULL, *commit_id_str = NULL;
8081 struct got_object_id *commit_id = NULL;
8082 struct got_commit_object *commit = NULL;
8083 struct got_object_qid *pid;
8084 int ch;
8085 struct got_update_progress_arg upa;
8087 while ((ch = getopt(argc, argv, "")) != -1) {
8088 switch (ch) {
8089 default:
8090 usage_backout();
8091 /* NOTREACHED */
8095 argc -= optind;
8096 argv += optind;
8098 #ifndef PROFILE
8099 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8100 "unveil", NULL) == -1)
8101 err(1, "pledge");
8102 #endif
8103 if (argc != 1)
8104 usage_backout();
8106 cwd = getcwd(NULL, 0);
8107 if (cwd == NULL) {
8108 error = got_error_from_errno("getcwd");
8109 goto done;
8111 error = got_worktree_open(&worktree, cwd);
8112 if (error) {
8113 if (error->code == GOT_ERR_NOT_WORKTREE)
8114 error = wrap_not_worktree_error(error, "backout", cwd);
8115 goto done;
8118 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8119 NULL);
8120 if (error != NULL)
8121 goto done;
8123 error = apply_unveil(got_repo_get_path(repo), 0,
8124 got_worktree_get_root_path(worktree));
8125 if (error)
8126 goto done;
8128 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8129 GOT_OBJ_TYPE_COMMIT, repo);
8130 if (error != NULL) {
8131 struct got_reference *ref;
8132 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8133 goto done;
8134 error = got_ref_open(&ref, repo, argv[0], 0);
8135 if (error != NULL)
8136 goto done;
8137 error = got_ref_resolve(&commit_id, repo, ref);
8138 got_ref_close(ref);
8139 if (error != NULL)
8140 goto done;
8142 error = got_object_id_str(&commit_id_str, commit_id);
8143 if (error)
8144 goto done;
8146 error = got_object_open_as_commit(&commit, repo, commit_id);
8147 if (error)
8148 goto done;
8149 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8150 if (pid == NULL) {
8151 error = got_error(GOT_ERR_ROOT_COMMIT);
8152 goto done;
8155 memset(&upa, 0, sizeof(upa));
8156 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8157 update_progress, &upa, check_cancelled, NULL);
8158 if (error != NULL)
8159 goto done;
8161 if (upa.did_something)
8162 printf("Backed out commit %s\n", commit_id_str);
8163 print_update_progress_stats(&upa);
8164 done:
8165 if (commit)
8166 got_object_commit_close(commit);
8167 free(commit_id_str);
8168 if (worktree)
8169 got_worktree_close(worktree);
8170 if (repo) {
8171 const struct got_error *close_err = got_repo_close(repo);
8172 if (error == NULL)
8173 error = close_err;
8175 return error;
8178 __dead static void
8179 usage_rebase(void)
8181 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8182 getprogname());
8183 exit(1);
8186 void
8187 trim_logmsg(char *logmsg, int limit)
8189 char *nl;
8190 size_t len;
8192 len = strlen(logmsg);
8193 if (len > limit)
8194 len = limit;
8195 logmsg[len] = '\0';
8196 nl = strchr(logmsg, '\n');
8197 if (nl)
8198 *nl = '\0';
8201 static const struct got_error *
8202 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8204 const struct got_error *err;
8205 char *logmsg0 = NULL;
8206 const char *s;
8208 err = got_object_commit_get_logmsg(&logmsg0, commit);
8209 if (err)
8210 return err;
8212 s = logmsg0;
8213 while (isspace((unsigned char)s[0]))
8214 s++;
8216 *logmsg = strdup(s);
8217 if (*logmsg == NULL) {
8218 err = got_error_from_errno("strdup");
8219 goto done;
8222 trim_logmsg(*logmsg, limit);
8223 done:
8224 free(logmsg0);
8225 return err;
8228 static const struct got_error *
8229 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8231 const struct got_error *err;
8232 struct got_commit_object *commit = NULL;
8233 char *id_str = NULL, *logmsg = NULL;
8235 err = got_object_open_as_commit(&commit, repo, id);
8236 if (err)
8237 return err;
8239 err = got_object_id_str(&id_str, id);
8240 if (err)
8241 goto done;
8243 id_str[12] = '\0';
8245 err = get_short_logmsg(&logmsg, 42, commit);
8246 if (err)
8247 goto done;
8249 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8250 done:
8251 free(id_str);
8252 got_object_commit_close(commit);
8253 free(logmsg);
8254 return err;
8257 static const struct got_error *
8258 show_rebase_progress(struct got_commit_object *commit,
8259 struct got_object_id *old_id, struct got_object_id *new_id)
8261 const struct got_error *err;
8262 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8264 err = got_object_id_str(&old_id_str, old_id);
8265 if (err)
8266 goto done;
8268 if (new_id) {
8269 err = got_object_id_str(&new_id_str, new_id);
8270 if (err)
8271 goto done;
8274 old_id_str[12] = '\0';
8275 if (new_id_str)
8276 new_id_str[12] = '\0';
8278 err = get_short_logmsg(&logmsg, 42, commit);
8279 if (err)
8280 goto done;
8282 printf("%s -> %s: %s\n", old_id_str,
8283 new_id_str ? new_id_str : "no-op change", logmsg);
8284 done:
8285 free(old_id_str);
8286 free(new_id_str);
8287 free(logmsg);
8288 return err;
8291 static const struct got_error *
8292 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8293 struct got_reference *branch, struct got_reference *new_base_branch,
8294 struct got_reference *tmp_branch, struct got_repository *repo,
8295 int create_backup)
8297 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8298 return got_worktree_rebase_complete(worktree, fileindex,
8299 new_base_branch, tmp_branch, branch, repo, create_backup);
8302 static const struct got_error *
8303 rebase_commit(struct got_pathlist_head *merged_paths,
8304 struct got_worktree *worktree, struct got_fileindex *fileindex,
8305 struct got_reference *tmp_branch,
8306 struct got_object_id *commit_id, struct got_repository *repo)
8308 const struct got_error *error;
8309 struct got_commit_object *commit;
8310 struct got_object_id *new_commit_id;
8312 error = got_object_open_as_commit(&commit, repo, commit_id);
8313 if (error)
8314 return error;
8316 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8317 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8318 if (error) {
8319 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8320 goto done;
8321 error = show_rebase_progress(commit, commit_id, NULL);
8322 } else {
8323 error = show_rebase_progress(commit, commit_id, new_commit_id);
8324 free(new_commit_id);
8326 done:
8327 got_object_commit_close(commit);
8328 return error;
8331 struct check_path_prefix_arg {
8332 const char *path_prefix;
8333 size_t len;
8334 int errcode;
8337 static const struct got_error *
8338 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8339 struct got_blob_object *blob2, struct got_object_id *id1,
8340 struct got_object_id *id2, const char *path1, const char *path2,
8341 mode_t mode1, mode_t mode2, struct got_repository *repo)
8343 struct check_path_prefix_arg *a = arg;
8345 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8346 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8347 return got_error(a->errcode);
8349 return NULL;
8352 static const struct got_error *
8353 check_path_prefix(struct got_object_id *parent_id,
8354 struct got_object_id *commit_id, const char *path_prefix,
8355 int errcode, struct got_repository *repo)
8357 const struct got_error *err;
8358 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8359 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8360 struct check_path_prefix_arg cpp_arg;
8362 if (got_path_is_root_dir(path_prefix))
8363 return NULL;
8365 err = got_object_open_as_commit(&commit, repo, commit_id);
8366 if (err)
8367 goto done;
8369 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8370 if (err)
8371 goto done;
8373 err = got_object_open_as_tree(&tree1, repo,
8374 got_object_commit_get_tree_id(parent_commit));
8375 if (err)
8376 goto done;
8378 err = got_object_open_as_tree(&tree2, repo,
8379 got_object_commit_get_tree_id(commit));
8380 if (err)
8381 goto done;
8383 cpp_arg.path_prefix = path_prefix;
8384 while (cpp_arg.path_prefix[0] == '/')
8385 cpp_arg.path_prefix++;
8386 cpp_arg.len = strlen(cpp_arg.path_prefix);
8387 cpp_arg.errcode = errcode;
8388 err = got_diff_tree(tree1, tree2, "", "", repo,
8389 check_path_prefix_in_diff, &cpp_arg, 0);
8390 done:
8391 if (tree1)
8392 got_object_tree_close(tree1);
8393 if (tree2)
8394 got_object_tree_close(tree2);
8395 if (commit)
8396 got_object_commit_close(commit);
8397 if (parent_commit)
8398 got_object_commit_close(parent_commit);
8399 return err;
8402 static const struct got_error *
8403 collect_commits(struct got_object_id_queue *commits,
8404 struct got_object_id *initial_commit_id,
8405 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8406 const char *path_prefix, int path_prefix_errcode,
8407 struct got_repository *repo)
8409 const struct got_error *err = NULL;
8410 struct got_commit_graph *graph = NULL;
8411 struct got_object_id *parent_id = NULL;
8412 struct got_object_qid *qid;
8413 struct got_object_id *commit_id = initial_commit_id;
8415 err = got_commit_graph_open(&graph, "/", 1);
8416 if (err)
8417 return err;
8419 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8420 check_cancelled, NULL);
8421 if (err)
8422 goto done;
8423 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8424 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8425 check_cancelled, NULL);
8426 if (err) {
8427 if (err->code == GOT_ERR_ITER_COMPLETED) {
8428 err = got_error_msg(GOT_ERR_ANCESTRY,
8429 "ran out of commits to rebase before "
8430 "youngest common ancestor commit has "
8431 "been reached?!?");
8433 goto done;
8434 } else {
8435 err = check_path_prefix(parent_id, commit_id,
8436 path_prefix, path_prefix_errcode, repo);
8437 if (err)
8438 goto done;
8440 err = got_object_qid_alloc(&qid, commit_id);
8441 if (err)
8442 goto done;
8443 STAILQ_INSERT_HEAD(commits, qid, entry);
8444 commit_id = parent_id;
8447 done:
8448 got_commit_graph_close(graph);
8449 return err;
8452 static const struct got_error *
8453 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8455 const struct got_error *err = NULL;
8456 time_t committer_time;
8457 struct tm tm;
8458 char datebuf[11]; /* YYYY-MM-DD + NUL */
8459 char *author0 = NULL, *author, *smallerthan;
8460 char *logmsg0 = NULL, *logmsg, *newline;
8462 committer_time = got_object_commit_get_committer_time(commit);
8463 if (gmtime_r(&committer_time, &tm) == NULL)
8464 return got_error_from_errno("gmtime_r");
8465 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8466 return got_error(GOT_ERR_NO_SPACE);
8468 author0 = strdup(got_object_commit_get_author(commit));
8469 if (author0 == NULL)
8470 return got_error_from_errno("strdup");
8471 author = author0;
8472 smallerthan = strchr(author, '<');
8473 if (smallerthan && smallerthan[1] != '\0')
8474 author = smallerthan + 1;
8475 author[strcspn(author, "@>")] = '\0';
8477 err = got_object_commit_get_logmsg(&logmsg0, commit);
8478 if (err)
8479 goto done;
8480 logmsg = logmsg0;
8481 while (*logmsg == '\n')
8482 logmsg++;
8483 newline = strchr(logmsg, '\n');
8484 if (newline)
8485 *newline = '\0';
8487 if (asprintf(brief_str, "%s %s %s",
8488 datebuf, author, logmsg) == -1)
8489 err = got_error_from_errno("asprintf");
8490 done:
8491 free(author0);
8492 free(logmsg0);
8493 return err;
8496 static const struct got_error *
8497 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8498 struct got_repository *repo)
8500 const struct got_error *err;
8501 char *id_str;
8503 err = got_object_id_str(&id_str, id);
8504 if (err)
8505 return err;
8507 err = got_ref_delete(ref, repo);
8508 if (err)
8509 goto done;
8511 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8512 done:
8513 free(id_str);
8514 return err;
8517 static const struct got_error *
8518 print_backup_ref(const char *branch_name, const char *new_id_str,
8519 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8520 struct got_reflist_object_id_map *refs_idmap,
8521 struct got_repository *repo)
8523 const struct got_error *err = NULL;
8524 struct got_reflist_head *refs;
8525 char *refs_str = NULL;
8526 struct got_object_id *new_commit_id = NULL;
8527 struct got_commit_object *new_commit = NULL;
8528 char *new_commit_brief_str = NULL;
8529 struct got_object_id *yca_id = NULL;
8530 struct got_commit_object *yca_commit = NULL;
8531 char *yca_id_str = NULL, *yca_brief_str = NULL;
8532 char *custom_refs_str;
8534 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8535 return got_error_from_errno("asprintf");
8537 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8538 0, 0, refs_idmap, custom_refs_str);
8539 if (err)
8540 goto done;
8542 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8543 if (err)
8544 goto done;
8546 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8547 if (refs) {
8548 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8549 if (err)
8550 goto done;
8553 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8554 if (err)
8555 goto done;
8557 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8558 if (err)
8559 goto done;
8561 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8562 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8563 if (err)
8564 goto done;
8566 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8567 refs_str ? " (" : "", refs_str ? refs_str : "",
8568 refs_str ? ")" : "", new_commit_brief_str);
8569 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8570 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8571 free(refs_str);
8572 refs_str = NULL;
8574 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8575 if (err)
8576 goto done;
8578 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8579 if (err)
8580 goto done;
8582 err = got_object_id_str(&yca_id_str, yca_id);
8583 if (err)
8584 goto done;
8586 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8587 if (refs) {
8588 err = build_refs_str(&refs_str, refs, yca_id, repo);
8589 if (err)
8590 goto done;
8592 printf("history forked at %s%s%s%s\n %s\n",
8593 yca_id_str,
8594 refs_str ? " (" : "", refs_str ? refs_str : "",
8595 refs_str ? ")" : "", yca_brief_str);
8597 done:
8598 free(custom_refs_str);
8599 free(new_commit_id);
8600 free(refs_str);
8601 free(yca_id);
8602 free(yca_id_str);
8603 free(yca_brief_str);
8604 if (new_commit)
8605 got_object_commit_close(new_commit);
8606 if (yca_commit)
8607 got_object_commit_close(yca_commit);
8609 return NULL;
8612 static const struct got_error *
8613 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8614 int delete, struct got_repository *repo)
8616 const struct got_error *err;
8617 struct got_reflist_head refs, backup_refs;
8618 struct got_reflist_entry *re;
8619 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8620 struct got_object_id *old_commit_id = NULL;
8621 char *branch_name = NULL;
8622 struct got_commit_object *old_commit = NULL;
8623 struct got_reflist_object_id_map *refs_idmap = NULL;
8624 int wanted_branch_found = 0;
8626 TAILQ_INIT(&refs);
8627 TAILQ_INIT(&backup_refs);
8629 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8630 if (err)
8631 return err;
8633 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8634 if (err)
8635 goto done;
8637 if (wanted_branch_name) {
8638 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8639 wanted_branch_name += 11;
8642 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8643 got_ref_cmp_by_commit_timestamp_descending, repo);
8644 if (err)
8645 goto done;
8647 TAILQ_FOREACH(re, &backup_refs, entry) {
8648 const char *refname = got_ref_get_name(re->ref);
8649 char *slash;
8651 err = check_cancelled(NULL);
8652 if (err)
8653 break;
8655 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8656 if (err)
8657 break;
8659 err = got_object_open_as_commit(&old_commit, repo,
8660 old_commit_id);
8661 if (err)
8662 break;
8664 if (strncmp(backup_ref_prefix, refname,
8665 backup_ref_prefix_len) == 0)
8666 refname += backup_ref_prefix_len;
8668 while (refname[0] == '/')
8669 refname++;
8671 branch_name = strdup(refname);
8672 if (branch_name == NULL) {
8673 err = got_error_from_errno("strdup");
8674 break;
8676 slash = strrchr(branch_name, '/');
8677 if (slash) {
8678 *slash = '\0';
8679 refname += strlen(branch_name) + 1;
8682 if (wanted_branch_name == NULL ||
8683 strcmp(wanted_branch_name, branch_name) == 0) {
8684 wanted_branch_found = 1;
8685 if (delete) {
8686 err = delete_backup_ref(re->ref,
8687 old_commit_id, repo);
8688 } else {
8689 err = print_backup_ref(branch_name, refname,
8690 old_commit_id, old_commit, refs_idmap,
8691 repo);
8693 if (err)
8694 break;
8697 free(old_commit_id);
8698 old_commit_id = NULL;
8699 free(branch_name);
8700 branch_name = NULL;
8701 got_object_commit_close(old_commit);
8702 old_commit = NULL;
8705 if (wanted_branch_name && !wanted_branch_found) {
8706 err = got_error_fmt(GOT_ERR_NOT_REF,
8707 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8709 done:
8710 if (refs_idmap)
8711 got_reflist_object_id_map_free(refs_idmap);
8712 got_ref_list_free(&refs);
8713 got_ref_list_free(&backup_refs);
8714 free(old_commit_id);
8715 free(branch_name);
8716 if (old_commit)
8717 got_object_commit_close(old_commit);
8718 return err;
8721 static const struct got_error *
8722 cmd_rebase(int argc, char *argv[])
8724 const struct got_error *error = NULL;
8725 struct got_worktree *worktree = NULL;
8726 struct got_repository *repo = NULL;
8727 struct got_fileindex *fileindex = NULL;
8728 char *cwd = NULL;
8729 struct got_reference *branch = NULL;
8730 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8731 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8732 struct got_object_id *resume_commit_id = NULL;
8733 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8734 struct got_commit_object *commit = NULL;
8735 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8736 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8737 int delete_backups = 0;
8738 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8739 struct got_object_id_queue commits;
8740 struct got_pathlist_head merged_paths;
8741 const struct got_object_id_queue *parent_ids;
8742 struct got_object_qid *qid, *pid;
8744 STAILQ_INIT(&commits);
8745 TAILQ_INIT(&merged_paths);
8747 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8748 switch (ch) {
8749 case 'a':
8750 abort_rebase = 1;
8751 break;
8752 case 'c':
8753 continue_rebase = 1;
8754 break;
8755 case 'l':
8756 list_backups = 1;
8757 break;
8758 case 'X':
8759 delete_backups = 1;
8760 break;
8761 default:
8762 usage_rebase();
8763 /* NOTREACHED */
8767 argc -= optind;
8768 argv += optind;
8770 #ifndef PROFILE
8771 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8772 "unveil", NULL) == -1)
8773 err(1, "pledge");
8774 #endif
8775 if (list_backups) {
8776 if (abort_rebase)
8777 option_conflict('l', 'a');
8778 if (continue_rebase)
8779 option_conflict('l', 'c');
8780 if (delete_backups)
8781 option_conflict('l', 'X');
8782 if (argc != 0 && argc != 1)
8783 usage_rebase();
8784 } else if (delete_backups) {
8785 if (abort_rebase)
8786 option_conflict('X', 'a');
8787 if (continue_rebase)
8788 option_conflict('X', 'c');
8789 if (list_backups)
8790 option_conflict('l', 'X');
8791 if (argc != 0 && argc != 1)
8792 usage_rebase();
8793 } else {
8794 if (abort_rebase && continue_rebase)
8795 usage_rebase();
8796 else if (abort_rebase || continue_rebase) {
8797 if (argc != 0)
8798 usage_rebase();
8799 } else if (argc != 1)
8800 usage_rebase();
8803 cwd = getcwd(NULL, 0);
8804 if (cwd == NULL) {
8805 error = got_error_from_errno("getcwd");
8806 goto done;
8808 error = got_worktree_open(&worktree, cwd);
8809 if (error) {
8810 if (list_backups || delete_backups) {
8811 if (error->code != GOT_ERR_NOT_WORKTREE)
8812 goto done;
8813 } else {
8814 if (error->code == GOT_ERR_NOT_WORKTREE)
8815 error = wrap_not_worktree_error(error,
8816 "rebase", cwd);
8817 goto done;
8821 error = got_repo_open(&repo,
8822 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8823 if (error != NULL)
8824 goto done;
8826 error = apply_unveil(got_repo_get_path(repo), 0,
8827 worktree ? got_worktree_get_root_path(worktree) : NULL);
8828 if (error)
8829 goto done;
8831 if (list_backups || delete_backups) {
8832 error = process_backup_refs(
8833 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8834 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8835 goto done; /* nothing else to do */
8838 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8839 worktree);
8840 if (error)
8841 goto done;
8842 if (histedit_in_progress) {
8843 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8844 goto done;
8847 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8848 if (error)
8849 goto done;
8851 if (abort_rebase) {
8852 struct got_update_progress_arg upa;
8853 if (!rebase_in_progress) {
8854 error = got_error(GOT_ERR_NOT_REBASING);
8855 goto done;
8857 error = got_worktree_rebase_continue(&resume_commit_id,
8858 &new_base_branch, &tmp_branch, &branch, &fileindex,
8859 worktree, repo);
8860 if (error)
8861 goto done;
8862 printf("Switching work tree to %s\n",
8863 got_ref_get_symref_target(new_base_branch));
8864 memset(&upa, 0, sizeof(upa));
8865 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8866 new_base_branch, update_progress, &upa);
8867 if (error)
8868 goto done;
8869 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8870 print_update_progress_stats(&upa);
8871 goto done; /* nothing else to do */
8874 if (continue_rebase) {
8875 if (!rebase_in_progress) {
8876 error = got_error(GOT_ERR_NOT_REBASING);
8877 goto done;
8879 error = got_worktree_rebase_continue(&resume_commit_id,
8880 &new_base_branch, &tmp_branch, &branch, &fileindex,
8881 worktree, repo);
8882 if (error)
8883 goto done;
8885 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8886 resume_commit_id, repo);
8887 if (error)
8888 goto done;
8890 yca_id = got_object_id_dup(resume_commit_id);
8891 if (yca_id == NULL) {
8892 error = got_error_from_errno("got_object_id_dup");
8893 goto done;
8895 } else {
8896 error = got_ref_open(&branch, repo, argv[0], 0);
8897 if (error != NULL)
8898 goto done;
8901 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8902 if (error)
8903 goto done;
8905 if (!continue_rebase) {
8906 struct got_object_id *base_commit_id;
8908 base_commit_id = got_worktree_get_base_commit_id(worktree);
8909 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8910 base_commit_id, branch_head_commit_id, repo,
8911 check_cancelled, NULL);
8912 if (error)
8913 goto done;
8914 if (yca_id == NULL) {
8915 error = got_error_msg(GOT_ERR_ANCESTRY,
8916 "specified branch shares no common ancestry "
8917 "with work tree's branch");
8918 goto done;
8921 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8922 if (error) {
8923 if (error->code != GOT_ERR_ANCESTRY)
8924 goto done;
8925 error = NULL;
8926 } else {
8927 static char msg[128];
8928 snprintf(msg, sizeof(msg),
8929 "%s is already based on %s",
8930 got_ref_get_name(branch),
8931 got_worktree_get_head_ref_name(worktree));
8932 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8933 goto done;
8935 error = got_worktree_rebase_prepare(&new_base_branch,
8936 &tmp_branch, &fileindex, worktree, branch, repo);
8937 if (error)
8938 goto done;
8941 commit_id = branch_head_commit_id;
8942 error = got_object_open_as_commit(&commit, repo, commit_id);
8943 if (error)
8944 goto done;
8946 parent_ids = got_object_commit_get_parent_ids(commit);
8947 pid = STAILQ_FIRST(parent_ids);
8948 if (pid == NULL) {
8949 if (!continue_rebase) {
8950 struct got_update_progress_arg upa;
8951 memset(&upa, 0, sizeof(upa));
8952 error = got_worktree_rebase_abort(worktree, fileindex,
8953 repo, new_base_branch, update_progress, &upa);
8954 if (error)
8955 goto done;
8956 printf("Rebase of %s aborted\n",
8957 got_ref_get_name(branch));
8958 print_update_progress_stats(&upa);
8961 error = got_error(GOT_ERR_EMPTY_REBASE);
8962 goto done;
8964 error = collect_commits(&commits, commit_id, pid->id,
8965 yca_id, got_worktree_get_path_prefix(worktree),
8966 GOT_ERR_REBASE_PATH, repo);
8967 got_object_commit_close(commit);
8968 commit = NULL;
8969 if (error)
8970 goto done;
8972 if (STAILQ_EMPTY(&commits)) {
8973 if (continue_rebase) {
8974 error = rebase_complete(worktree, fileindex,
8975 branch, new_base_branch, tmp_branch, repo,
8976 create_backup);
8977 goto done;
8978 } else {
8979 /* Fast-forward the reference of the branch. */
8980 struct got_object_id *new_head_commit_id;
8981 char *id_str;
8982 error = got_ref_resolve(&new_head_commit_id, repo,
8983 new_base_branch);
8984 if (error)
8985 goto done;
8986 error = got_object_id_str(&id_str, new_head_commit_id);
8987 printf("Forwarding %s to commit %s\n",
8988 got_ref_get_name(branch), id_str);
8989 free(id_str);
8990 error = got_ref_change_ref(branch,
8991 new_head_commit_id);
8992 if (error)
8993 goto done;
8994 /* No backup needed since objects did not change. */
8995 create_backup = 0;
8999 pid = NULL;
9000 STAILQ_FOREACH(qid, &commits, entry) {
9001 struct got_update_progress_arg upa;
9003 commit_id = qid->id;
9004 parent_id = pid ? pid->id : yca_id;
9005 pid = qid;
9007 memset(&upa, 0, sizeof(upa));
9008 error = got_worktree_rebase_merge_files(&merged_paths,
9009 worktree, fileindex, parent_id, commit_id, repo,
9010 update_progress, &upa, check_cancelled, NULL);
9011 if (error)
9012 goto done;
9014 print_update_progress_stats(&upa);
9015 if (upa.conflicts > 0)
9016 rebase_status = GOT_STATUS_CONFLICT;
9018 if (rebase_status == GOT_STATUS_CONFLICT) {
9019 error = show_rebase_merge_conflict(qid->id, repo);
9020 if (error)
9021 goto done;
9022 got_worktree_rebase_pathlist_free(&merged_paths);
9023 break;
9026 error = rebase_commit(&merged_paths, worktree, fileindex,
9027 tmp_branch, commit_id, repo);
9028 got_worktree_rebase_pathlist_free(&merged_paths);
9029 if (error)
9030 goto done;
9033 if (rebase_status == GOT_STATUS_CONFLICT) {
9034 error = got_worktree_rebase_postpone(worktree, fileindex);
9035 if (error)
9036 goto done;
9037 error = got_error_msg(GOT_ERR_CONFLICTS,
9038 "conflicts must be resolved before rebasing can continue");
9039 } else
9040 error = rebase_complete(worktree, fileindex, branch,
9041 new_base_branch, tmp_branch, repo, create_backup);
9042 done:
9043 got_object_id_queue_free(&commits);
9044 free(branch_head_commit_id);
9045 free(resume_commit_id);
9046 free(yca_id);
9047 if (commit)
9048 got_object_commit_close(commit);
9049 if (branch)
9050 got_ref_close(branch);
9051 if (new_base_branch)
9052 got_ref_close(new_base_branch);
9053 if (tmp_branch)
9054 got_ref_close(tmp_branch);
9055 if (worktree)
9056 got_worktree_close(worktree);
9057 if (repo) {
9058 const struct got_error *close_err = got_repo_close(repo);
9059 if (error == NULL)
9060 error = close_err;
9062 return error;
9065 __dead static void
9066 usage_histedit(void)
9068 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
9069 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9070 getprogname());
9071 exit(1);
9074 #define GOT_HISTEDIT_PICK 'p'
9075 #define GOT_HISTEDIT_EDIT 'e'
9076 #define GOT_HISTEDIT_FOLD 'f'
9077 #define GOT_HISTEDIT_DROP 'd'
9078 #define GOT_HISTEDIT_MESG 'm'
9080 static struct got_histedit_cmd {
9081 unsigned char code;
9082 const char *name;
9083 const char *desc;
9084 } got_histedit_cmds[] = {
9085 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9086 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9087 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9088 "be used" },
9089 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9090 { GOT_HISTEDIT_MESG, "mesg",
9091 "single-line log message for commit above (open editor if empty)" },
9094 struct got_histedit_list_entry {
9095 TAILQ_ENTRY(got_histedit_list_entry) entry;
9096 struct got_object_id *commit_id;
9097 const struct got_histedit_cmd *cmd;
9098 char *logmsg;
9100 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9102 static const struct got_error *
9103 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9104 FILE *f, struct got_repository *repo)
9106 const struct got_error *err = NULL;
9107 char *logmsg = NULL, *id_str = NULL;
9108 struct got_commit_object *commit = NULL;
9109 int n;
9111 err = got_object_open_as_commit(&commit, repo, commit_id);
9112 if (err)
9113 goto done;
9115 err = get_short_logmsg(&logmsg, 34, commit);
9116 if (err)
9117 goto done;
9119 err = got_object_id_str(&id_str, commit_id);
9120 if (err)
9121 goto done;
9123 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9124 if (n < 0)
9125 err = got_ferror(f, GOT_ERR_IO);
9126 done:
9127 if (commit)
9128 got_object_commit_close(commit);
9129 free(id_str);
9130 free(logmsg);
9131 return err;
9134 static const struct got_error *
9135 histedit_write_commit_list(struct got_object_id_queue *commits,
9136 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9138 const struct got_error *err = NULL;
9139 struct got_object_qid *qid;
9140 const char *histedit_cmd = NULL;
9142 if (STAILQ_EMPTY(commits))
9143 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9145 STAILQ_FOREACH(qid, commits, entry) {
9146 histedit_cmd = got_histedit_cmds[0].name;
9147 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9148 histedit_cmd = "fold";
9149 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9150 if (err)
9151 break;
9152 if (edit_logmsg_only) {
9153 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9154 if (n < 0) {
9155 err = got_ferror(f, GOT_ERR_IO);
9156 break;
9161 return err;
9164 static const struct got_error *
9165 write_cmd_list(FILE *f, const char *branch_name,
9166 struct got_object_id_queue *commits)
9168 const struct got_error *err = NULL;
9169 size_t i;
9170 int n;
9171 char *id_str;
9172 struct got_object_qid *qid;
9174 qid = STAILQ_FIRST(commits);
9175 err = got_object_id_str(&id_str, qid->id);
9176 if (err)
9177 return err;
9179 n = fprintf(f,
9180 "# Editing the history of branch '%s' starting at\n"
9181 "# commit %s\n"
9182 "# Commits will be processed in order from top to "
9183 "bottom of this file.\n", branch_name, id_str);
9184 if (n < 0) {
9185 err = got_ferror(f, GOT_ERR_IO);
9186 goto done;
9189 n = fprintf(f, "# Available histedit commands:\n");
9190 if (n < 0) {
9191 err = got_ferror(f, GOT_ERR_IO);
9192 goto done;
9195 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9196 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9197 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9198 cmd->desc);
9199 if (n < 0) {
9200 err = got_ferror(f, GOT_ERR_IO);
9201 break;
9204 done:
9205 free(id_str);
9206 return err;
9209 static const struct got_error *
9210 histedit_syntax_error(int lineno)
9212 static char msg[42];
9213 int ret;
9215 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9216 lineno);
9217 if (ret == -1 || ret >= sizeof(msg))
9218 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9220 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9223 static const struct got_error *
9224 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9225 char *logmsg, struct got_repository *repo)
9227 const struct got_error *err;
9228 struct got_commit_object *folded_commit = NULL;
9229 char *id_str, *folded_logmsg = NULL;
9231 err = got_object_id_str(&id_str, hle->commit_id);
9232 if (err)
9233 return err;
9235 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9236 if (err)
9237 goto done;
9239 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9240 if (err)
9241 goto done;
9242 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9243 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9244 folded_logmsg) == -1) {
9245 err = got_error_from_errno("asprintf");
9247 done:
9248 if (folded_commit)
9249 got_object_commit_close(folded_commit);
9250 free(id_str);
9251 free(folded_logmsg);
9252 return err;
9255 static struct got_histedit_list_entry *
9256 get_folded_commits(struct got_histedit_list_entry *hle)
9258 struct got_histedit_list_entry *prev, *folded = NULL;
9260 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9261 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9262 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9263 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9264 folded = prev;
9265 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9268 return folded;
9271 static const struct got_error *
9272 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9273 struct got_repository *repo)
9275 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9276 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9277 const struct got_error *err = NULL;
9278 struct got_commit_object *commit = NULL;
9279 int logmsg_len;
9280 int fd;
9281 struct got_histedit_list_entry *folded = NULL;
9283 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9284 if (err)
9285 return err;
9287 folded = get_folded_commits(hle);
9288 if (folded) {
9289 while (folded != hle) {
9290 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9291 folded = TAILQ_NEXT(folded, entry);
9292 continue;
9294 err = append_folded_commit_msg(&new_msg, folded,
9295 logmsg, repo);
9296 if (err)
9297 goto done;
9298 free(logmsg);
9299 logmsg = new_msg;
9300 folded = TAILQ_NEXT(folded, entry);
9304 err = got_object_id_str(&id_str, hle->commit_id);
9305 if (err)
9306 goto done;
9307 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9308 if (err)
9309 goto done;
9310 logmsg_len = asprintf(&new_msg,
9311 "%s\n# original log message of commit %s: %s",
9312 logmsg ? logmsg : "", id_str, orig_logmsg);
9313 if (logmsg_len == -1) {
9314 err = got_error_from_errno("asprintf");
9315 goto done;
9317 free(logmsg);
9318 logmsg = new_msg;
9320 err = got_object_id_str(&id_str, hle->commit_id);
9321 if (err)
9322 goto done;
9324 err = got_opentemp_named_fd(&logmsg_path, &fd,
9325 GOT_TMPDIR_STR "/got-logmsg");
9326 if (err)
9327 goto done;
9329 write(fd, logmsg, logmsg_len);
9330 close(fd);
9332 err = get_editor(&editor);
9333 if (err)
9334 goto done;
9336 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9337 logmsg_len, 0);
9338 if (err) {
9339 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9340 goto done;
9341 err = NULL;
9342 hle->logmsg = strdup(new_msg);
9343 if (hle->logmsg == NULL)
9344 err = got_error_from_errno("strdup");
9346 done:
9347 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9348 err = got_error_from_errno2("unlink", logmsg_path);
9349 free(logmsg_path);
9350 free(logmsg);
9351 free(orig_logmsg);
9352 free(editor);
9353 if (commit)
9354 got_object_commit_close(commit);
9355 return err;
9358 static const struct got_error *
9359 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9360 FILE *f, struct got_repository *repo)
9362 const struct got_error *err = NULL;
9363 char *line = NULL, *p, *end;
9364 size_t i, size;
9365 ssize_t len;
9366 int lineno = 0;
9367 const struct got_histedit_cmd *cmd;
9368 struct got_object_id *commit_id = NULL;
9369 struct got_histedit_list_entry *hle = NULL;
9371 for (;;) {
9372 len = getline(&line, &size, f);
9373 if (len == -1) {
9374 const struct got_error *getline_err;
9375 if (feof(f))
9376 break;
9377 getline_err = got_error_from_errno("getline");
9378 err = got_ferror(f, getline_err->code);
9379 break;
9381 lineno++;
9382 p = line;
9383 while (isspace((unsigned char)p[0]))
9384 p++;
9385 if (p[0] == '#' || p[0] == '\0') {
9386 free(line);
9387 line = NULL;
9388 continue;
9390 cmd = NULL;
9391 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9392 cmd = &got_histedit_cmds[i];
9393 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9394 isspace((unsigned char)p[strlen(cmd->name)])) {
9395 p += strlen(cmd->name);
9396 break;
9398 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9399 p++;
9400 break;
9403 if (i == nitems(got_histedit_cmds)) {
9404 err = histedit_syntax_error(lineno);
9405 break;
9407 while (isspace((unsigned char)p[0]))
9408 p++;
9409 if (cmd->code == GOT_HISTEDIT_MESG) {
9410 if (hle == NULL || hle->logmsg != NULL) {
9411 err = got_error(GOT_ERR_HISTEDIT_CMD);
9412 break;
9414 if (p[0] == '\0') {
9415 err = histedit_edit_logmsg(hle, repo);
9416 if (err)
9417 break;
9418 } else {
9419 hle->logmsg = strdup(p);
9420 if (hle->logmsg == NULL) {
9421 err = got_error_from_errno("strdup");
9422 break;
9425 free(line);
9426 line = NULL;
9427 continue;
9428 } else {
9429 end = p;
9430 while (end[0] && !isspace((unsigned char)end[0]))
9431 end++;
9432 *end = '\0';
9434 err = got_object_resolve_id_str(&commit_id, repo, p);
9435 if (err) {
9436 /* override error code */
9437 err = histedit_syntax_error(lineno);
9438 break;
9441 hle = malloc(sizeof(*hle));
9442 if (hle == NULL) {
9443 err = got_error_from_errno("malloc");
9444 break;
9446 hle->cmd = cmd;
9447 hle->commit_id = commit_id;
9448 hle->logmsg = NULL;
9449 commit_id = NULL;
9450 free(line);
9451 line = NULL;
9452 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9455 free(line);
9456 free(commit_id);
9457 return err;
9460 static const struct got_error *
9461 histedit_check_script(struct got_histedit_list *histedit_cmds,
9462 struct got_object_id_queue *commits, struct got_repository *repo)
9464 const struct got_error *err = NULL;
9465 struct got_object_qid *qid;
9466 struct got_histedit_list_entry *hle;
9467 static char msg[92];
9468 char *id_str;
9470 if (TAILQ_EMPTY(histedit_cmds))
9471 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9472 "histedit script contains no commands");
9473 if (STAILQ_EMPTY(commits))
9474 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9476 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9477 struct got_histedit_list_entry *hle2;
9478 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9479 if (hle == hle2)
9480 continue;
9481 if (got_object_id_cmp(hle->commit_id,
9482 hle2->commit_id) != 0)
9483 continue;
9484 err = got_object_id_str(&id_str, hle->commit_id);
9485 if (err)
9486 return err;
9487 snprintf(msg, sizeof(msg), "commit %s is listed "
9488 "more than once in histedit script", id_str);
9489 free(id_str);
9490 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9494 STAILQ_FOREACH(qid, commits, entry) {
9495 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9496 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9497 break;
9499 if (hle == NULL) {
9500 err = got_object_id_str(&id_str, qid->id);
9501 if (err)
9502 return err;
9503 snprintf(msg, sizeof(msg),
9504 "commit %s missing from histedit script", id_str);
9505 free(id_str);
9506 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9510 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9511 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9512 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9513 "last commit in histedit script cannot be folded");
9515 return NULL;
9518 static const struct got_error *
9519 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9520 const char *path, struct got_object_id_queue *commits,
9521 struct got_repository *repo)
9523 const struct got_error *err = NULL;
9524 char *editor;
9525 FILE *f = NULL;
9527 err = get_editor(&editor);
9528 if (err)
9529 return err;
9531 if (spawn_editor(editor, path) == -1) {
9532 err = got_error_from_errno("failed spawning editor");
9533 goto done;
9536 f = fopen(path, "r");
9537 if (f == NULL) {
9538 err = got_error_from_errno("fopen");
9539 goto done;
9541 err = histedit_parse_list(histedit_cmds, f, repo);
9542 if (err)
9543 goto done;
9545 err = histedit_check_script(histedit_cmds, commits, repo);
9546 done:
9547 if (f && fclose(f) == EOF && err == NULL)
9548 err = got_error_from_errno("fclose");
9549 free(editor);
9550 return err;
9553 static const struct got_error *
9554 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9555 struct got_object_id_queue *, const char *, const char *,
9556 struct got_repository *);
9558 static const struct got_error *
9559 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9560 struct got_object_id_queue *commits, const char *branch_name,
9561 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9563 const struct got_error *err;
9564 FILE *f = NULL;
9565 char *path = NULL;
9567 err = got_opentemp_named(&path, &f, "got-histedit");
9568 if (err)
9569 return err;
9571 err = write_cmd_list(f, branch_name, commits);
9572 if (err)
9573 goto done;
9575 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9576 fold_only, repo);
9577 if (err)
9578 goto done;
9580 if (edit_logmsg_only || fold_only) {
9581 rewind(f);
9582 err = histedit_parse_list(histedit_cmds, f, repo);
9583 } else {
9584 if (fclose(f) == EOF) {
9585 err = got_error_from_errno("fclose");
9586 goto done;
9588 f = NULL;
9589 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9590 if (err) {
9591 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9592 err->code != GOT_ERR_HISTEDIT_CMD)
9593 goto done;
9594 err = histedit_edit_list_retry(histedit_cmds, err,
9595 commits, path, branch_name, repo);
9598 done:
9599 if (f && fclose(f) == EOF && err == NULL)
9600 err = got_error_from_errno("fclose");
9601 if (path && unlink(path) != 0 && err == NULL)
9602 err = got_error_from_errno2("unlink", path);
9603 free(path);
9604 return err;
9607 static const struct got_error *
9608 histedit_save_list(struct got_histedit_list *histedit_cmds,
9609 struct got_worktree *worktree, struct got_repository *repo)
9611 const struct got_error *err = NULL;
9612 char *path = NULL;
9613 FILE *f = NULL;
9614 struct got_histedit_list_entry *hle;
9615 struct got_commit_object *commit = NULL;
9617 err = got_worktree_get_histedit_script_path(&path, worktree);
9618 if (err)
9619 return err;
9621 f = fopen(path, "w");
9622 if (f == NULL) {
9623 err = got_error_from_errno2("fopen", path);
9624 goto done;
9626 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9627 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9628 repo);
9629 if (err)
9630 break;
9632 if (hle->logmsg) {
9633 int n = fprintf(f, "%c %s\n",
9634 GOT_HISTEDIT_MESG, hle->logmsg);
9635 if (n < 0) {
9636 err = got_ferror(f, GOT_ERR_IO);
9637 break;
9641 done:
9642 if (f && fclose(f) == EOF && err == NULL)
9643 err = got_error_from_errno("fclose");
9644 free(path);
9645 if (commit)
9646 got_object_commit_close(commit);
9647 return err;
9650 void
9651 histedit_free_list(struct got_histedit_list *histedit_cmds)
9653 struct got_histedit_list_entry *hle;
9655 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9656 TAILQ_REMOVE(histedit_cmds, hle, entry);
9657 free(hle);
9661 static const struct got_error *
9662 histedit_load_list(struct got_histedit_list *histedit_cmds,
9663 const char *path, struct got_repository *repo)
9665 const struct got_error *err = NULL;
9666 FILE *f = NULL;
9668 f = fopen(path, "r");
9669 if (f == NULL) {
9670 err = got_error_from_errno2("fopen", path);
9671 goto done;
9674 err = histedit_parse_list(histedit_cmds, f, repo);
9675 done:
9676 if (f && fclose(f) == EOF && err == NULL)
9677 err = got_error_from_errno("fclose");
9678 return err;
9681 static const struct got_error *
9682 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9683 const struct got_error *edit_err, struct got_object_id_queue *commits,
9684 const char *path, const char *branch_name, struct got_repository *repo)
9686 const struct got_error *err = NULL, *prev_err = edit_err;
9687 int resp = ' ';
9689 while (resp != 'c' && resp != 'r' && resp != 'a') {
9690 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9691 "or (a)bort: ", getprogname(), prev_err->msg);
9692 resp = getchar();
9693 if (resp == '\n')
9694 resp = getchar();
9695 if (resp == 'c') {
9696 histedit_free_list(histedit_cmds);
9697 err = histedit_run_editor(histedit_cmds, path, commits,
9698 repo);
9699 if (err) {
9700 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9701 err->code != GOT_ERR_HISTEDIT_CMD)
9702 break;
9703 prev_err = err;
9704 resp = ' ';
9705 continue;
9707 break;
9708 } else if (resp == 'r') {
9709 histedit_free_list(histedit_cmds);
9710 err = histedit_edit_script(histedit_cmds,
9711 commits, branch_name, 0, 0, repo);
9712 if (err) {
9713 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9714 err->code != GOT_ERR_HISTEDIT_CMD)
9715 break;
9716 prev_err = err;
9717 resp = ' ';
9718 continue;
9720 break;
9721 } else if (resp == 'a') {
9722 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9723 break;
9724 } else
9725 printf("invalid response '%c'\n", resp);
9728 return err;
9731 static const struct got_error *
9732 histedit_complete(struct got_worktree *worktree,
9733 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9734 struct got_reference *branch, struct got_repository *repo)
9736 printf("Switching work tree to %s\n",
9737 got_ref_get_symref_target(branch));
9738 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9739 branch, repo);
9742 static const struct got_error *
9743 show_histedit_progress(struct got_commit_object *commit,
9744 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9746 const struct got_error *err;
9747 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9749 err = got_object_id_str(&old_id_str, hle->commit_id);
9750 if (err)
9751 goto done;
9753 if (new_id) {
9754 err = got_object_id_str(&new_id_str, new_id);
9755 if (err)
9756 goto done;
9759 old_id_str[12] = '\0';
9760 if (new_id_str)
9761 new_id_str[12] = '\0';
9763 if (hle->logmsg) {
9764 logmsg = strdup(hle->logmsg);
9765 if (logmsg == NULL) {
9766 err = got_error_from_errno("strdup");
9767 goto done;
9769 trim_logmsg(logmsg, 42);
9770 } else {
9771 err = get_short_logmsg(&logmsg, 42, commit);
9772 if (err)
9773 goto done;
9776 switch (hle->cmd->code) {
9777 case GOT_HISTEDIT_PICK:
9778 case GOT_HISTEDIT_EDIT:
9779 printf("%s -> %s: %s\n", old_id_str,
9780 new_id_str ? new_id_str : "no-op change", logmsg);
9781 break;
9782 case GOT_HISTEDIT_DROP:
9783 case GOT_HISTEDIT_FOLD:
9784 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9785 logmsg);
9786 break;
9787 default:
9788 break;
9790 done:
9791 free(old_id_str);
9792 free(new_id_str);
9793 return err;
9796 static const struct got_error *
9797 histedit_commit(struct got_pathlist_head *merged_paths,
9798 struct got_worktree *worktree, struct got_fileindex *fileindex,
9799 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9800 struct got_repository *repo)
9802 const struct got_error *err;
9803 struct got_commit_object *commit;
9804 struct got_object_id *new_commit_id;
9806 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9807 && hle->logmsg == NULL) {
9808 err = histedit_edit_logmsg(hle, repo);
9809 if (err)
9810 return err;
9813 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9814 if (err)
9815 return err;
9817 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9818 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9819 hle->logmsg, repo);
9820 if (err) {
9821 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9822 goto done;
9823 err = show_histedit_progress(commit, hle, NULL);
9824 } else {
9825 err = show_histedit_progress(commit, hle, new_commit_id);
9826 free(new_commit_id);
9828 done:
9829 got_object_commit_close(commit);
9830 return err;
9833 static const struct got_error *
9834 histedit_skip_commit(struct got_histedit_list_entry *hle,
9835 struct got_worktree *worktree, struct got_repository *repo)
9837 const struct got_error *error;
9838 struct got_commit_object *commit;
9840 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9841 repo);
9842 if (error)
9843 return error;
9845 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9846 if (error)
9847 return error;
9849 error = show_histedit_progress(commit, hle, NULL);
9850 got_object_commit_close(commit);
9851 return error;
9854 static const struct got_error *
9855 check_local_changes(void *arg, unsigned char status,
9856 unsigned char staged_status, const char *path,
9857 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9858 struct got_object_id *commit_id, int dirfd, const char *de_name)
9860 int *have_local_changes = arg;
9862 switch (status) {
9863 case GOT_STATUS_ADD:
9864 case GOT_STATUS_DELETE:
9865 case GOT_STATUS_MODIFY:
9866 case GOT_STATUS_CONFLICT:
9867 *have_local_changes = 1;
9868 return got_error(GOT_ERR_CANCELLED);
9869 default:
9870 break;
9873 switch (staged_status) {
9874 case GOT_STATUS_ADD:
9875 case GOT_STATUS_DELETE:
9876 case GOT_STATUS_MODIFY:
9877 *have_local_changes = 1;
9878 return got_error(GOT_ERR_CANCELLED);
9879 default:
9880 break;
9883 return NULL;
9886 static const struct got_error *
9887 cmd_histedit(int argc, char *argv[])
9889 const struct got_error *error = NULL;
9890 struct got_worktree *worktree = NULL;
9891 struct got_fileindex *fileindex = NULL;
9892 struct got_repository *repo = NULL;
9893 char *cwd = NULL;
9894 struct got_reference *branch = NULL;
9895 struct got_reference *tmp_branch = NULL;
9896 struct got_object_id *resume_commit_id = NULL;
9897 struct got_object_id *base_commit_id = NULL;
9898 struct got_object_id *head_commit_id = NULL;
9899 struct got_commit_object *commit = NULL;
9900 int ch, rebase_in_progress = 0;
9901 struct got_update_progress_arg upa;
9902 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9903 int edit_logmsg_only = 0, fold_only = 0;
9904 int list_backups = 0, delete_backups = 0;
9905 const char *edit_script_path = NULL;
9906 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9907 struct got_object_id_queue commits;
9908 struct got_pathlist_head merged_paths;
9909 const struct got_object_id_queue *parent_ids;
9910 struct got_object_qid *pid;
9911 struct got_histedit_list histedit_cmds;
9912 struct got_histedit_list_entry *hle;
9914 STAILQ_INIT(&commits);
9915 TAILQ_INIT(&histedit_cmds);
9916 TAILQ_INIT(&merged_paths);
9917 memset(&upa, 0, sizeof(upa));
9919 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9920 switch (ch) {
9921 case 'a':
9922 abort_edit = 1;
9923 break;
9924 case 'c':
9925 continue_edit = 1;
9926 break;
9927 case 'f':
9928 fold_only = 1;
9929 break;
9930 case 'F':
9931 edit_script_path = optarg;
9932 break;
9933 case 'm':
9934 edit_logmsg_only = 1;
9935 break;
9936 case 'l':
9937 list_backups = 1;
9938 break;
9939 case 'X':
9940 delete_backups = 1;
9941 break;
9942 default:
9943 usage_histedit();
9944 /* NOTREACHED */
9948 argc -= optind;
9949 argv += optind;
9951 #ifndef PROFILE
9952 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9953 "unveil", NULL) == -1)
9954 err(1, "pledge");
9955 #endif
9956 if (abort_edit && continue_edit)
9957 option_conflict('a', 'c');
9958 if (edit_script_path && edit_logmsg_only)
9959 option_conflict('F', 'm');
9960 if (abort_edit && edit_logmsg_only)
9961 option_conflict('a', 'm');
9962 if (continue_edit && edit_logmsg_only)
9963 option_conflict('c', 'm');
9964 if (abort_edit && fold_only)
9965 option_conflict('a', 'f');
9966 if (continue_edit && fold_only)
9967 option_conflict('c', 'f');
9968 if (fold_only && edit_logmsg_only)
9969 option_conflict('f', 'm');
9970 if (edit_script_path && fold_only)
9971 option_conflict('F', 'f');
9972 if (list_backups) {
9973 if (abort_edit)
9974 option_conflict('l', 'a');
9975 if (continue_edit)
9976 option_conflict('l', 'c');
9977 if (edit_script_path)
9978 option_conflict('l', 'F');
9979 if (edit_logmsg_only)
9980 option_conflict('l', 'm');
9981 if (fold_only)
9982 option_conflict('l', 'f');
9983 if (delete_backups)
9984 option_conflict('l', 'X');
9985 if (argc != 0 && argc != 1)
9986 usage_histedit();
9987 } else if (delete_backups) {
9988 if (abort_edit)
9989 option_conflict('X', 'a');
9990 if (continue_edit)
9991 option_conflict('X', 'c');
9992 if (edit_script_path)
9993 option_conflict('X', 'F');
9994 if (edit_logmsg_only)
9995 option_conflict('X', 'm');
9996 if (fold_only)
9997 option_conflict('X', 'f');
9998 if (list_backups)
9999 option_conflict('X', 'l');
10000 if (argc != 0 && argc != 1)
10001 usage_histedit();
10002 } else if (argc != 0)
10003 usage_histedit();
10006 * This command cannot apply unveil(2) in all cases because the
10007 * user may choose to run an editor to edit the histedit script
10008 * and to edit individual commit log messages.
10009 * unveil(2) traverses exec(2); if an editor is used we have to
10010 * apply unveil after edit script and log messages have been written.
10011 * XXX TODO: Make use of unveil(2) where possible.
10014 cwd = getcwd(NULL, 0);
10015 if (cwd == NULL) {
10016 error = got_error_from_errno("getcwd");
10017 goto done;
10019 error = got_worktree_open(&worktree, cwd);
10020 if (error) {
10021 if (list_backups || delete_backups) {
10022 if (error->code != GOT_ERR_NOT_WORKTREE)
10023 goto done;
10024 } else {
10025 if (error->code == GOT_ERR_NOT_WORKTREE)
10026 error = wrap_not_worktree_error(error,
10027 "histedit", cwd);
10028 goto done;
10032 if (list_backups || delete_backups) {
10033 error = got_repo_open(&repo,
10034 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10035 NULL);
10036 if (error != NULL)
10037 goto done;
10038 error = apply_unveil(got_repo_get_path(repo), 0,
10039 worktree ? got_worktree_get_root_path(worktree) : NULL);
10040 if (error)
10041 goto done;
10042 error = process_backup_refs(
10043 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10044 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10045 goto done; /* nothing else to do */
10048 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10049 NULL);
10050 if (error != NULL)
10051 goto done;
10053 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10054 if (error)
10055 goto done;
10056 if (rebase_in_progress) {
10057 error = got_error(GOT_ERR_REBASING);
10058 goto done;
10061 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10062 if (error)
10063 goto done;
10065 if (edit_in_progress && edit_logmsg_only) {
10066 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10067 "histedit operation is in progress in this "
10068 "work tree and must be continued or aborted "
10069 "before the -m option can be used");
10070 goto done;
10072 if (edit_in_progress && fold_only) {
10073 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10074 "histedit operation is in progress in this "
10075 "work tree and must be continued or aborted "
10076 "before the -f option can be used");
10077 goto done;
10080 if (edit_in_progress && abort_edit) {
10081 error = got_worktree_histedit_continue(&resume_commit_id,
10082 &tmp_branch, &branch, &base_commit_id, &fileindex,
10083 worktree, repo);
10084 if (error)
10085 goto done;
10086 printf("Switching work tree to %s\n",
10087 got_ref_get_symref_target(branch));
10088 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10089 branch, base_commit_id, update_progress, &upa);
10090 if (error)
10091 goto done;
10092 printf("Histedit of %s aborted\n",
10093 got_ref_get_symref_target(branch));
10094 print_update_progress_stats(&upa);
10095 goto done; /* nothing else to do */
10096 } else if (abort_edit) {
10097 error = got_error(GOT_ERR_NOT_HISTEDIT);
10098 goto done;
10101 if (continue_edit) {
10102 char *path;
10104 if (!edit_in_progress) {
10105 error = got_error(GOT_ERR_NOT_HISTEDIT);
10106 goto done;
10109 error = got_worktree_get_histedit_script_path(&path, worktree);
10110 if (error)
10111 goto done;
10113 error = histedit_load_list(&histedit_cmds, path, repo);
10114 free(path);
10115 if (error)
10116 goto done;
10118 error = got_worktree_histedit_continue(&resume_commit_id,
10119 &tmp_branch, &branch, &base_commit_id, &fileindex,
10120 worktree, repo);
10121 if (error)
10122 goto done;
10124 error = got_ref_resolve(&head_commit_id, repo, branch);
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 base_commit_id, got_worktree_get_path_prefix(worktree),
10140 GOT_ERR_HISTEDIT_PATH, repo);
10141 got_object_commit_close(commit);
10142 commit = NULL;
10143 if (error)
10144 goto done;
10145 } else {
10146 if (edit_in_progress) {
10147 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10148 goto done;
10151 error = got_ref_open(&branch, repo,
10152 got_worktree_get_head_ref_name(worktree), 0);
10153 if (error != NULL)
10154 goto done;
10156 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10157 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10158 "will not edit commit history of a branch outside "
10159 "the \"refs/heads/\" reference namespace");
10160 goto done;
10163 error = got_ref_resolve(&head_commit_id, repo, branch);
10164 got_ref_close(branch);
10165 branch = NULL;
10166 if (error)
10167 goto done;
10169 error = got_object_open_as_commit(&commit, repo,
10170 head_commit_id);
10171 if (error)
10172 goto done;
10173 parent_ids = got_object_commit_get_parent_ids(commit);
10174 pid = STAILQ_FIRST(parent_ids);
10175 if (pid == NULL) {
10176 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10177 goto done;
10179 error = collect_commits(&commits, head_commit_id, pid->id,
10180 got_worktree_get_base_commit_id(worktree),
10181 got_worktree_get_path_prefix(worktree),
10182 GOT_ERR_HISTEDIT_PATH, repo);
10183 got_object_commit_close(commit);
10184 commit = NULL;
10185 if (error)
10186 goto done;
10188 if (STAILQ_EMPTY(&commits)) {
10189 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10190 goto done;
10193 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10194 &base_commit_id, &fileindex, worktree, repo);
10195 if (error)
10196 goto done;
10198 if (edit_script_path) {
10199 error = histedit_load_list(&histedit_cmds,
10200 edit_script_path, repo);
10201 if (error) {
10202 got_worktree_histedit_abort(worktree, fileindex,
10203 repo, branch, base_commit_id,
10204 update_progress, &upa);
10205 print_update_progress_stats(&upa);
10206 goto done;
10208 } else {
10209 const char *branch_name;
10210 branch_name = got_ref_get_symref_target(branch);
10211 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10212 branch_name += 11;
10213 error = histedit_edit_script(&histedit_cmds, &commits,
10214 branch_name, edit_logmsg_only, fold_only, repo);
10215 if (error) {
10216 got_worktree_histedit_abort(worktree, fileindex,
10217 repo, branch, base_commit_id,
10218 update_progress, &upa);
10219 print_update_progress_stats(&upa);
10220 goto done;
10225 error = histedit_save_list(&histedit_cmds, worktree,
10226 repo);
10227 if (error) {
10228 got_worktree_histedit_abort(worktree, fileindex,
10229 repo, branch, base_commit_id,
10230 update_progress, &upa);
10231 print_update_progress_stats(&upa);
10232 goto done;
10237 error = histedit_check_script(&histedit_cmds, &commits, repo);
10238 if (error)
10239 goto done;
10241 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10242 if (resume_commit_id) {
10243 if (got_object_id_cmp(hle->commit_id,
10244 resume_commit_id) != 0)
10245 continue;
10247 resume_commit_id = NULL;
10248 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10249 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10250 error = histedit_skip_commit(hle, worktree,
10251 repo);
10252 if (error)
10253 goto done;
10254 } else {
10255 struct got_pathlist_head paths;
10256 int have_changes = 0;
10258 TAILQ_INIT(&paths);
10259 error = got_pathlist_append(&paths, "", NULL);
10260 if (error)
10261 goto done;
10262 error = got_worktree_status(worktree, &paths,
10263 repo, 0, check_local_changes, &have_changes,
10264 check_cancelled, NULL);
10265 got_pathlist_free(&paths);
10266 if (error) {
10267 if (error->code != GOT_ERR_CANCELLED)
10268 goto done;
10269 if (sigint_received || sigpipe_received)
10270 goto done;
10272 if (have_changes) {
10273 error = histedit_commit(NULL, worktree,
10274 fileindex, tmp_branch, hle, repo);
10275 if (error)
10276 goto done;
10277 } else {
10278 error = got_object_open_as_commit(
10279 &commit, repo, hle->commit_id);
10280 if (error)
10281 goto done;
10282 error = show_histedit_progress(commit,
10283 hle, NULL);
10284 got_object_commit_close(commit);
10285 commit = NULL;
10286 if (error)
10287 goto done;
10290 continue;
10293 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10294 error = histedit_skip_commit(hle, worktree, repo);
10295 if (error)
10296 goto done;
10297 continue;
10300 error = got_object_open_as_commit(&commit, repo,
10301 hle->commit_id);
10302 if (error)
10303 goto done;
10304 parent_ids = got_object_commit_get_parent_ids(commit);
10305 pid = STAILQ_FIRST(parent_ids);
10307 error = got_worktree_histedit_merge_files(&merged_paths,
10308 worktree, fileindex, pid->id, hle->commit_id, repo,
10309 update_progress, &upa, check_cancelled, NULL);
10310 if (error)
10311 goto done;
10312 got_object_commit_close(commit);
10313 commit = NULL;
10315 print_update_progress_stats(&upa);
10316 if (upa.conflicts > 0)
10317 rebase_status = GOT_STATUS_CONFLICT;
10319 if (rebase_status == GOT_STATUS_CONFLICT) {
10320 error = show_rebase_merge_conflict(hle->commit_id,
10321 repo);
10322 if (error)
10323 goto done;
10324 got_worktree_rebase_pathlist_free(&merged_paths);
10325 break;
10328 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10329 char *id_str;
10330 error = got_object_id_str(&id_str, hle->commit_id);
10331 if (error)
10332 goto done;
10333 printf("Stopping histedit for amending commit %s\n",
10334 id_str);
10335 free(id_str);
10336 got_worktree_rebase_pathlist_free(&merged_paths);
10337 error = got_worktree_histedit_postpone(worktree,
10338 fileindex);
10339 goto done;
10342 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10343 error = histedit_skip_commit(hle, worktree, repo);
10344 if (error)
10345 goto done;
10346 continue;
10349 error = histedit_commit(&merged_paths, worktree, fileindex,
10350 tmp_branch, hle, repo);
10351 got_worktree_rebase_pathlist_free(&merged_paths);
10352 if (error)
10353 goto done;
10356 if (rebase_status == GOT_STATUS_CONFLICT) {
10357 error = got_worktree_histedit_postpone(worktree, fileindex);
10358 if (error)
10359 goto done;
10360 error = got_error_msg(GOT_ERR_CONFLICTS,
10361 "conflicts must be resolved before histedit can continue");
10362 } else
10363 error = histedit_complete(worktree, fileindex, tmp_branch,
10364 branch, repo);
10365 done:
10366 got_object_id_queue_free(&commits);
10367 histedit_free_list(&histedit_cmds);
10368 free(head_commit_id);
10369 free(base_commit_id);
10370 free(resume_commit_id);
10371 if (commit)
10372 got_object_commit_close(commit);
10373 if (branch)
10374 got_ref_close(branch);
10375 if (tmp_branch)
10376 got_ref_close(tmp_branch);
10377 if (worktree)
10378 got_worktree_close(worktree);
10379 if (repo) {
10380 const struct got_error *close_err = got_repo_close(repo);
10381 if (error == NULL)
10382 error = close_err;
10384 return error;
10387 __dead static void
10388 usage_integrate(void)
10390 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10391 exit(1);
10394 static const struct got_error *
10395 cmd_integrate(int argc, char *argv[])
10397 const struct got_error *error = NULL;
10398 struct got_repository *repo = NULL;
10399 struct got_worktree *worktree = NULL;
10400 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10401 const char *branch_arg = NULL;
10402 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10403 struct got_fileindex *fileindex = NULL;
10404 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10405 int ch;
10406 struct got_update_progress_arg upa;
10408 while ((ch = getopt(argc, argv, "")) != -1) {
10409 switch (ch) {
10410 default:
10411 usage_integrate();
10412 /* NOTREACHED */
10416 argc -= optind;
10417 argv += optind;
10419 if (argc != 1)
10420 usage_integrate();
10421 branch_arg = argv[0];
10422 #ifndef PROFILE
10423 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10424 "unveil", NULL) == -1)
10425 err(1, "pledge");
10426 #endif
10427 cwd = getcwd(NULL, 0);
10428 if (cwd == NULL) {
10429 error = got_error_from_errno("getcwd");
10430 goto done;
10433 error = got_worktree_open(&worktree, cwd);
10434 if (error) {
10435 if (error->code == GOT_ERR_NOT_WORKTREE)
10436 error = wrap_not_worktree_error(error, "integrate",
10437 cwd);
10438 goto done;
10441 error = check_rebase_or_histedit_in_progress(worktree);
10442 if (error)
10443 goto done;
10445 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10446 NULL);
10447 if (error != NULL)
10448 goto done;
10450 error = apply_unveil(got_repo_get_path(repo), 0,
10451 got_worktree_get_root_path(worktree));
10452 if (error)
10453 goto done;
10455 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10456 error = got_error_from_errno("asprintf");
10457 goto done;
10460 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10461 &base_branch_ref, worktree, refname, repo);
10462 if (error)
10463 goto done;
10465 refname = strdup(got_ref_get_name(branch_ref));
10466 if (refname == NULL) {
10467 error = got_error_from_errno("strdup");
10468 got_worktree_integrate_abort(worktree, fileindex, repo,
10469 branch_ref, base_branch_ref);
10470 goto done;
10472 base_refname = strdup(got_ref_get_name(base_branch_ref));
10473 if (base_refname == NULL) {
10474 error = got_error_from_errno("strdup");
10475 got_worktree_integrate_abort(worktree, fileindex, repo,
10476 branch_ref, base_branch_ref);
10477 goto done;
10480 error = got_ref_resolve(&commit_id, repo, branch_ref);
10481 if (error)
10482 goto done;
10484 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10485 if (error)
10486 goto done;
10488 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10489 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10490 "specified branch has already been integrated");
10491 got_worktree_integrate_abort(worktree, fileindex, repo,
10492 branch_ref, base_branch_ref);
10493 goto done;
10496 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10497 if (error) {
10498 if (error->code == GOT_ERR_ANCESTRY)
10499 error = got_error(GOT_ERR_REBASE_REQUIRED);
10500 got_worktree_integrate_abort(worktree, fileindex, repo,
10501 branch_ref, base_branch_ref);
10502 goto done;
10505 memset(&upa, 0, sizeof(upa));
10506 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10507 branch_ref, base_branch_ref, update_progress, &upa,
10508 check_cancelled, NULL);
10509 if (error)
10510 goto done;
10512 printf("Integrated %s into %s\n", refname, base_refname);
10513 print_update_progress_stats(&upa);
10514 done:
10515 if (repo) {
10516 const struct got_error *close_err = got_repo_close(repo);
10517 if (error == NULL)
10518 error = close_err;
10520 if (worktree)
10521 got_worktree_close(worktree);
10522 free(cwd);
10523 free(base_commit_id);
10524 free(commit_id);
10525 free(refname);
10526 free(base_refname);
10527 return error;
10530 __dead static void
10531 usage_stage(void)
10533 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10534 "[-S] [file-path ...]\n",
10535 getprogname());
10536 exit(1);
10539 static const struct got_error *
10540 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10541 const char *path, struct got_object_id *blob_id,
10542 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10543 int dirfd, const char *de_name)
10545 const struct got_error *err = NULL;
10546 char *id_str = NULL;
10548 if (staged_status != GOT_STATUS_ADD &&
10549 staged_status != GOT_STATUS_MODIFY &&
10550 staged_status != GOT_STATUS_DELETE)
10551 return NULL;
10553 if (staged_status == GOT_STATUS_ADD ||
10554 staged_status == GOT_STATUS_MODIFY)
10555 err = got_object_id_str(&id_str, staged_blob_id);
10556 else
10557 err = got_object_id_str(&id_str, blob_id);
10558 if (err)
10559 return err;
10561 printf("%s %c %s\n", id_str, staged_status, path);
10562 free(id_str);
10563 return NULL;
10566 static const struct got_error *
10567 cmd_stage(int argc, char *argv[])
10569 const struct got_error *error = NULL;
10570 struct got_repository *repo = NULL;
10571 struct got_worktree *worktree = NULL;
10572 char *cwd = NULL;
10573 struct got_pathlist_head paths;
10574 struct got_pathlist_entry *pe;
10575 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10576 FILE *patch_script_file = NULL;
10577 const char *patch_script_path = NULL;
10578 struct choose_patch_arg cpa;
10580 TAILQ_INIT(&paths);
10582 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10583 switch (ch) {
10584 case 'l':
10585 list_stage = 1;
10586 break;
10587 case 'p':
10588 pflag = 1;
10589 break;
10590 case 'F':
10591 patch_script_path = optarg;
10592 break;
10593 case 'S':
10594 allow_bad_symlinks = 1;
10595 break;
10596 default:
10597 usage_stage();
10598 /* NOTREACHED */
10602 argc -= optind;
10603 argv += optind;
10605 #ifndef PROFILE
10606 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10607 "unveil", NULL) == -1)
10608 err(1, "pledge");
10609 #endif
10610 if (list_stage && (pflag || patch_script_path))
10611 errx(1, "-l option cannot be used with other options");
10612 if (patch_script_path && !pflag)
10613 errx(1, "-F option can only be used together with -p option");
10615 cwd = getcwd(NULL, 0);
10616 if (cwd == NULL) {
10617 error = got_error_from_errno("getcwd");
10618 goto done;
10621 error = got_worktree_open(&worktree, cwd);
10622 if (error) {
10623 if (error->code == GOT_ERR_NOT_WORKTREE)
10624 error = wrap_not_worktree_error(error, "stage", cwd);
10625 goto done;
10628 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10629 NULL);
10630 if (error != NULL)
10631 goto done;
10633 if (patch_script_path) {
10634 patch_script_file = fopen(patch_script_path, "r");
10635 if (patch_script_file == NULL) {
10636 error = got_error_from_errno2("fopen",
10637 patch_script_path);
10638 goto done;
10641 error = apply_unveil(got_repo_get_path(repo), 0,
10642 got_worktree_get_root_path(worktree));
10643 if (error)
10644 goto done;
10646 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10647 if (error)
10648 goto done;
10650 if (list_stage)
10651 error = got_worktree_status(worktree, &paths, repo, 0,
10652 print_stage, NULL, check_cancelled, NULL);
10653 else {
10654 cpa.patch_script_file = patch_script_file;
10655 cpa.action = "stage";
10656 error = got_worktree_stage(worktree, &paths,
10657 pflag ? NULL : print_status, NULL,
10658 pflag ? choose_patch : NULL, &cpa,
10659 allow_bad_symlinks, repo);
10661 done:
10662 if (patch_script_file && fclose(patch_script_file) == EOF &&
10663 error == NULL)
10664 error = got_error_from_errno2("fclose", patch_script_path);
10665 if (repo) {
10666 const struct got_error *close_err = got_repo_close(repo);
10667 if (error == NULL)
10668 error = close_err;
10670 if (worktree)
10671 got_worktree_close(worktree);
10672 TAILQ_FOREACH(pe, &paths, entry)
10673 free((char *)pe->path);
10674 got_pathlist_free(&paths);
10675 free(cwd);
10676 return error;
10679 __dead static void
10680 usage_unstage(void)
10682 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10683 "[file-path ...]\n",
10684 getprogname());
10685 exit(1);
10689 static const struct got_error *
10690 cmd_unstage(int argc, char *argv[])
10692 const struct got_error *error = NULL;
10693 struct got_repository *repo = NULL;
10694 struct got_worktree *worktree = NULL;
10695 char *cwd = NULL;
10696 struct got_pathlist_head paths;
10697 struct got_pathlist_entry *pe;
10698 int ch, pflag = 0;
10699 struct got_update_progress_arg upa;
10700 FILE *patch_script_file = NULL;
10701 const char *patch_script_path = NULL;
10702 struct choose_patch_arg cpa;
10704 TAILQ_INIT(&paths);
10706 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10707 switch (ch) {
10708 case 'p':
10709 pflag = 1;
10710 break;
10711 case 'F':
10712 patch_script_path = optarg;
10713 break;
10714 default:
10715 usage_unstage();
10716 /* NOTREACHED */
10720 argc -= optind;
10721 argv += optind;
10723 #ifndef PROFILE
10724 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10725 "unveil", NULL) == -1)
10726 err(1, "pledge");
10727 #endif
10728 if (patch_script_path && !pflag)
10729 errx(1, "-F option can only be used together with -p option");
10731 cwd = getcwd(NULL, 0);
10732 if (cwd == NULL) {
10733 error = got_error_from_errno("getcwd");
10734 goto done;
10737 error = got_worktree_open(&worktree, cwd);
10738 if (error) {
10739 if (error->code == GOT_ERR_NOT_WORKTREE)
10740 error = wrap_not_worktree_error(error, "unstage", cwd);
10741 goto done;
10744 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10745 NULL);
10746 if (error != NULL)
10747 goto done;
10749 if (patch_script_path) {
10750 patch_script_file = fopen(patch_script_path, "r");
10751 if (patch_script_file == NULL) {
10752 error = got_error_from_errno2("fopen",
10753 patch_script_path);
10754 goto done;
10758 error = apply_unveil(got_repo_get_path(repo), 0,
10759 got_worktree_get_root_path(worktree));
10760 if (error)
10761 goto done;
10763 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10764 if (error)
10765 goto done;
10767 cpa.patch_script_file = patch_script_file;
10768 cpa.action = "unstage";
10769 memset(&upa, 0, sizeof(upa));
10770 error = got_worktree_unstage(worktree, &paths, update_progress,
10771 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10772 if (!error)
10773 print_update_progress_stats(&upa);
10774 done:
10775 if (patch_script_file && fclose(patch_script_file) == EOF &&
10776 error == NULL)
10777 error = got_error_from_errno2("fclose", patch_script_path);
10778 if (repo) {
10779 const struct got_error *close_err = got_repo_close(repo);
10780 if (error == NULL)
10781 error = close_err;
10783 if (worktree)
10784 got_worktree_close(worktree);
10785 TAILQ_FOREACH(pe, &paths, entry)
10786 free((char *)pe->path);
10787 got_pathlist_free(&paths);
10788 free(cwd);
10789 return error;
10792 __dead static void
10793 usage_cat(void)
10795 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10796 "arg1 [arg2 ...]\n", getprogname());
10797 exit(1);
10800 static const struct got_error *
10801 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10803 const struct got_error *err;
10804 struct got_blob_object *blob;
10806 err = got_object_open_as_blob(&blob, repo, id, 8192);
10807 if (err)
10808 return err;
10810 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10811 got_object_blob_close(blob);
10812 return err;
10815 static const struct got_error *
10816 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10818 const struct got_error *err;
10819 struct got_tree_object *tree;
10820 int nentries, i;
10822 err = got_object_open_as_tree(&tree, repo, id);
10823 if (err)
10824 return err;
10826 nentries = got_object_tree_get_nentries(tree);
10827 for (i = 0; i < nentries; i++) {
10828 struct got_tree_entry *te;
10829 char *id_str;
10830 if (sigint_received || sigpipe_received)
10831 break;
10832 te = got_object_tree_get_entry(tree, i);
10833 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10834 if (err)
10835 break;
10836 fprintf(outfile, "%s %.7o %s\n", id_str,
10837 got_tree_entry_get_mode(te),
10838 got_tree_entry_get_name(te));
10839 free(id_str);
10842 got_object_tree_close(tree);
10843 return err;
10846 static const struct got_error *
10847 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10849 const struct got_error *err;
10850 struct got_commit_object *commit;
10851 const struct got_object_id_queue *parent_ids;
10852 struct got_object_qid *pid;
10853 char *id_str = NULL;
10854 const char *logmsg = NULL;
10856 err = got_object_open_as_commit(&commit, repo, id);
10857 if (err)
10858 return err;
10860 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10861 if (err)
10862 goto done;
10864 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10865 parent_ids = got_object_commit_get_parent_ids(commit);
10866 fprintf(outfile, "numparents %d\n",
10867 got_object_commit_get_nparents(commit));
10868 STAILQ_FOREACH(pid, parent_ids, entry) {
10869 char *pid_str;
10870 err = got_object_id_str(&pid_str, pid->id);
10871 if (err)
10872 goto done;
10873 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10874 free(pid_str);
10876 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10877 got_object_commit_get_author(commit),
10878 (long long)got_object_commit_get_author_time(commit));
10880 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10881 got_object_commit_get_author(commit),
10882 (long long)got_object_commit_get_committer_time(commit));
10884 logmsg = got_object_commit_get_logmsg_raw(commit);
10885 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10886 fprintf(outfile, "%s", logmsg);
10887 done:
10888 free(id_str);
10889 got_object_commit_close(commit);
10890 return err;
10893 static const struct got_error *
10894 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10896 const struct got_error *err;
10897 struct got_tag_object *tag;
10898 char *id_str = NULL;
10899 const char *tagmsg = NULL;
10901 err = got_object_open_as_tag(&tag, repo, id);
10902 if (err)
10903 return err;
10905 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10906 if (err)
10907 goto done;
10909 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10911 switch (got_object_tag_get_object_type(tag)) {
10912 case GOT_OBJ_TYPE_BLOB:
10913 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10914 GOT_OBJ_LABEL_BLOB);
10915 break;
10916 case GOT_OBJ_TYPE_TREE:
10917 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10918 GOT_OBJ_LABEL_TREE);
10919 break;
10920 case GOT_OBJ_TYPE_COMMIT:
10921 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10922 GOT_OBJ_LABEL_COMMIT);
10923 break;
10924 case GOT_OBJ_TYPE_TAG:
10925 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10926 GOT_OBJ_LABEL_TAG);
10927 break;
10928 default:
10929 break;
10932 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10933 got_object_tag_get_name(tag));
10935 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10936 got_object_tag_get_tagger(tag),
10937 (long long)got_object_tag_get_tagger_time(tag));
10939 tagmsg = got_object_tag_get_message(tag);
10940 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10941 fprintf(outfile, "%s", tagmsg);
10942 done:
10943 free(id_str);
10944 got_object_tag_close(tag);
10945 return err;
10948 static const struct got_error *
10949 cmd_cat(int argc, char *argv[])
10951 const struct got_error *error;
10952 struct got_repository *repo = NULL;
10953 struct got_worktree *worktree = NULL;
10954 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10955 const char *commit_id_str = NULL;
10956 struct got_object_id *id = NULL, *commit_id = NULL;
10957 int ch, obj_type, i, force_path = 0;
10958 struct got_reflist_head refs;
10960 TAILQ_INIT(&refs);
10962 #ifndef PROFILE
10963 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10964 NULL) == -1)
10965 err(1, "pledge");
10966 #endif
10968 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10969 switch (ch) {
10970 case 'c':
10971 commit_id_str = optarg;
10972 break;
10973 case 'r':
10974 repo_path = realpath(optarg, NULL);
10975 if (repo_path == NULL)
10976 return got_error_from_errno2("realpath",
10977 optarg);
10978 got_path_strip_trailing_slashes(repo_path);
10979 break;
10980 case 'P':
10981 force_path = 1;
10982 break;
10983 default:
10984 usage_cat();
10985 /* NOTREACHED */
10989 argc -= optind;
10990 argv += optind;
10992 cwd = getcwd(NULL, 0);
10993 if (cwd == NULL) {
10994 error = got_error_from_errno("getcwd");
10995 goto done;
10997 error = got_worktree_open(&worktree, cwd);
10998 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10999 goto done;
11000 if (worktree) {
11001 if (repo_path == NULL) {
11002 repo_path = strdup(
11003 got_worktree_get_repo_path(worktree));
11004 if (repo_path == NULL) {
11005 error = got_error_from_errno("strdup");
11006 goto done;
11011 if (repo_path == NULL) {
11012 repo_path = getcwd(NULL, 0);
11013 if (repo_path == NULL)
11014 return got_error_from_errno("getcwd");
11017 error = got_repo_open(&repo, repo_path, NULL);
11018 free(repo_path);
11019 if (error != NULL)
11020 goto done;
11022 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11023 if (error)
11024 goto done;
11026 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11027 if (error)
11028 goto done;
11030 if (commit_id_str == NULL)
11031 commit_id_str = GOT_REF_HEAD;
11032 error = got_repo_match_object_id(&commit_id, NULL,
11033 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11034 if (error)
11035 goto done;
11037 for (i = 0; i < argc; i++) {
11038 if (force_path) {
11039 error = got_object_id_by_path(&id, repo, commit_id,
11040 argv[i]);
11041 if (error)
11042 break;
11043 } else {
11044 error = got_repo_match_object_id(&id, &label, argv[i],
11045 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11046 repo);
11047 if (error) {
11048 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11049 error->code != GOT_ERR_NOT_REF)
11050 break;
11051 error = got_object_id_by_path(&id, repo,
11052 commit_id, argv[i]);
11053 if (error)
11054 break;
11058 error = got_object_get_type(&obj_type, repo, id);
11059 if (error)
11060 break;
11062 switch (obj_type) {
11063 case GOT_OBJ_TYPE_BLOB:
11064 error = cat_blob(id, repo, stdout);
11065 break;
11066 case GOT_OBJ_TYPE_TREE:
11067 error = cat_tree(id, repo, stdout);
11068 break;
11069 case GOT_OBJ_TYPE_COMMIT:
11070 error = cat_commit(id, repo, stdout);
11071 break;
11072 case GOT_OBJ_TYPE_TAG:
11073 error = cat_tag(id, repo, stdout);
11074 break;
11075 default:
11076 error = got_error(GOT_ERR_OBJ_TYPE);
11077 break;
11079 if (error)
11080 break;
11081 free(label);
11082 label = NULL;
11083 free(id);
11084 id = NULL;
11086 done:
11087 free(label);
11088 free(id);
11089 free(commit_id);
11090 if (worktree)
11091 got_worktree_close(worktree);
11092 if (repo) {
11093 const struct got_error *close_err = got_repo_close(repo);
11094 if (error == NULL)
11095 error = close_err;
11097 got_ref_list_free(&refs);
11098 return error;
11101 __dead static void
11102 usage_info(void)
11104 fprintf(stderr, "usage: %s info [path ...]\n",
11105 getprogname());
11106 exit(1);
11109 static const struct got_error *
11110 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11111 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11112 struct got_object_id *commit_id)
11114 const struct got_error *err = NULL;
11115 char *id_str = NULL;
11116 char datebuf[128];
11117 struct tm mytm, *tm;
11118 struct got_pathlist_head *paths = arg;
11119 struct got_pathlist_entry *pe;
11122 * Clear error indication from any of the path arguments which
11123 * would cause this file index entry to be displayed.
11125 TAILQ_FOREACH(pe, paths, entry) {
11126 if (got_path_cmp(path, pe->path, strlen(path),
11127 pe->path_len) == 0 ||
11128 got_path_is_child(path, pe->path, pe->path_len))
11129 pe->data = NULL; /* no error */
11132 printf(GOT_COMMIT_SEP_STR);
11133 if (S_ISLNK(mode))
11134 printf("symlink: %s\n", path);
11135 else if (S_ISREG(mode)) {
11136 printf("file: %s\n", path);
11137 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11138 } else if (S_ISDIR(mode))
11139 printf("directory: %s\n", path);
11140 else
11141 printf("something: %s\n", path);
11143 tm = localtime_r(&mtime, &mytm);
11144 if (tm == NULL)
11145 return NULL;
11146 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11147 return got_error(GOT_ERR_NO_SPACE);
11148 printf("timestamp: %s\n", datebuf);
11150 if (blob_id) {
11151 err = got_object_id_str(&id_str, blob_id);
11152 if (err)
11153 return err;
11154 printf("based on blob: %s\n", id_str);
11155 free(id_str);
11158 if (staged_blob_id) {
11159 err = got_object_id_str(&id_str, staged_blob_id);
11160 if (err)
11161 return err;
11162 printf("based on staged blob: %s\n", id_str);
11163 free(id_str);
11166 if (commit_id) {
11167 err = got_object_id_str(&id_str, commit_id);
11168 if (err)
11169 return err;
11170 printf("based on commit: %s\n", id_str);
11171 free(id_str);
11174 return NULL;
11177 static const struct got_error *
11178 cmd_info(int argc, char *argv[])
11180 const struct got_error *error = NULL;
11181 struct got_worktree *worktree = NULL;
11182 char *cwd = NULL, *id_str = NULL;
11183 struct got_pathlist_head paths;
11184 struct got_pathlist_entry *pe;
11185 char *uuidstr = NULL;
11186 int ch, show_files = 0;
11188 TAILQ_INIT(&paths);
11190 while ((ch = getopt(argc, argv, "")) != -1) {
11191 switch (ch) {
11192 default:
11193 usage_info();
11194 /* NOTREACHED */
11198 argc -= optind;
11199 argv += optind;
11201 #ifndef PROFILE
11202 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11203 NULL) == -1)
11204 err(1, "pledge");
11205 #endif
11206 cwd = getcwd(NULL, 0);
11207 if (cwd == NULL) {
11208 error = got_error_from_errno("getcwd");
11209 goto done;
11212 error = got_worktree_open(&worktree, cwd);
11213 if (error) {
11214 if (error->code == GOT_ERR_NOT_WORKTREE)
11215 error = wrap_not_worktree_error(error, "info", cwd);
11216 goto done;
11219 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11220 if (error)
11221 goto done;
11223 if (argc >= 1) {
11224 error = get_worktree_paths_from_argv(&paths, argc, argv,
11225 worktree);
11226 if (error)
11227 goto done;
11228 show_files = 1;
11231 error = got_object_id_str(&id_str,
11232 got_worktree_get_base_commit_id(worktree));
11233 if (error)
11234 goto done;
11236 error = got_worktree_get_uuid(&uuidstr, worktree);
11237 if (error)
11238 goto done;
11240 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11241 printf("work tree base commit: %s\n", id_str);
11242 printf("work tree path prefix: %s\n",
11243 got_worktree_get_path_prefix(worktree));
11244 printf("work tree branch reference: %s\n",
11245 got_worktree_get_head_ref_name(worktree));
11246 printf("work tree UUID: %s\n", uuidstr);
11247 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11249 if (show_files) {
11250 struct got_pathlist_entry *pe;
11251 TAILQ_FOREACH(pe, &paths, entry) {
11252 if (pe->path_len == 0)
11253 continue;
11255 * Assume this path will fail. This will be corrected
11256 * in print_path_info() in case the path does suceeed.
11258 pe->data = (void *)got_error_path(pe->path,
11259 GOT_ERR_BAD_PATH);
11261 error = got_worktree_path_info(worktree, &paths,
11262 print_path_info, &paths, check_cancelled, NULL);
11263 if (error)
11264 goto done;
11265 TAILQ_FOREACH(pe, &paths, entry) {
11266 if (pe->data != NULL) {
11267 error = pe->data; /* bad path */
11268 break;
11272 done:
11273 TAILQ_FOREACH(pe, &paths, entry)
11274 free((char *)pe->path);
11275 got_pathlist_free(&paths);
11276 free(cwd);
11277 free(id_str);
11278 free(uuidstr);
11279 return error;