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 %s: %s\n",
3391 got_worktree_get_head_ref_name(worktree), commit_id_str);
3392 } else
3393 printf("Already up-to-date\n");
3394 print_update_progress_stats(&upa);
3395 done:
3396 free(worktree_path);
3397 TAILQ_FOREACH(pe, &paths, entry)
3398 free((char *)pe->path);
3399 got_pathlist_free(&paths);
3400 free(commit_id);
3401 free(commit_id_str);
3402 return error;
3405 static const struct got_error *
3406 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3407 const char *path, int diff_context, int ignore_whitespace,
3408 int force_text_diff, struct got_repository *repo)
3410 const struct got_error *err = NULL;
3411 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3413 if (blob_id1) {
3414 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3415 if (err)
3416 goto done;
3419 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3420 if (err)
3421 goto done;
3423 while (path[0] == '/')
3424 path++;
3425 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3426 diff_context, ignore_whitespace, force_text_diff, stdout);
3427 done:
3428 if (blob1)
3429 got_object_blob_close(blob1);
3430 got_object_blob_close(blob2);
3431 return err;
3434 static const struct got_error *
3435 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3436 const char *path, int diff_context, int ignore_whitespace,
3437 int force_text_diff, struct got_repository *repo)
3439 const struct got_error *err = NULL;
3440 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3441 struct got_diff_blob_output_unidiff_arg arg;
3443 if (tree_id1) {
3444 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3445 if (err)
3446 goto done;
3449 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3450 if (err)
3451 goto done;
3453 arg.diff_context = diff_context;
3454 arg.ignore_whitespace = ignore_whitespace;
3455 arg.force_text_diff = force_text_diff;
3456 arg.outfile = stdout;
3457 arg.line_offsets = NULL;
3458 arg.nlines = 0;
3459 while (path[0] == '/')
3460 path++;
3461 err = got_diff_tree(tree1, tree2, path, path, repo,
3462 got_diff_blob_output_unidiff, &arg, 1);
3463 done:
3464 if (tree1)
3465 got_object_tree_close(tree1);
3466 if (tree2)
3467 got_object_tree_close(tree2);
3468 return err;
3471 static const struct got_error *
3472 get_changed_paths(struct got_pathlist_head *paths,
3473 struct got_commit_object *commit, struct got_repository *repo)
3475 const struct got_error *err = NULL;
3476 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3477 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3478 struct got_object_qid *qid;
3480 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3481 if (qid != NULL) {
3482 struct got_commit_object *pcommit;
3483 err = got_object_open_as_commit(&pcommit, repo,
3484 qid->id);
3485 if (err)
3486 return err;
3488 tree_id1 = got_object_id_dup(
3489 got_object_commit_get_tree_id(pcommit));
3490 if (tree_id1 == NULL) {
3491 got_object_commit_close(pcommit);
3492 return got_error_from_errno("got_object_id_dup");
3494 got_object_commit_close(pcommit);
3498 if (tree_id1) {
3499 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3500 if (err)
3501 goto done;
3504 tree_id2 = got_object_commit_get_tree_id(commit);
3505 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3506 if (err)
3507 goto done;
3509 err = got_diff_tree(tree1, tree2, "", "", repo,
3510 got_diff_tree_collect_changed_paths, paths, 0);
3511 done:
3512 if (tree1)
3513 got_object_tree_close(tree1);
3514 if (tree2)
3515 got_object_tree_close(tree2);
3516 free(tree_id1);
3517 return err;
3520 static const struct got_error *
3521 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3522 const char *path, int diff_context, struct got_repository *repo)
3524 const struct got_error *err = NULL;
3525 struct got_commit_object *pcommit = NULL;
3526 char *id_str1 = NULL, *id_str2 = NULL;
3527 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3528 struct got_object_qid *qid;
3530 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3531 if (qid != NULL) {
3532 err = got_object_open_as_commit(&pcommit, repo,
3533 qid->id);
3534 if (err)
3535 return err;
3538 if (path && path[0] != '\0') {
3539 int obj_type;
3540 err = got_object_id_by_path(&obj_id2, repo, id, path);
3541 if (err)
3542 goto done;
3543 err = got_object_id_str(&id_str2, obj_id2);
3544 if (err) {
3545 free(obj_id2);
3546 goto done;
3548 if (pcommit) {
3549 err = got_object_id_by_path(&obj_id1, repo,
3550 qid->id, path);
3551 if (err) {
3552 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3553 free(obj_id2);
3554 goto done;
3556 } else {
3557 err = got_object_id_str(&id_str1, obj_id1);
3558 if (err) {
3559 free(obj_id2);
3560 goto done;
3564 err = got_object_get_type(&obj_type, repo, obj_id2);
3565 if (err) {
3566 free(obj_id2);
3567 goto done;
3569 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3570 switch (obj_type) {
3571 case GOT_OBJ_TYPE_BLOB:
3572 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3573 0, 0, repo);
3574 break;
3575 case GOT_OBJ_TYPE_TREE:
3576 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3577 0, 0, repo);
3578 break;
3579 default:
3580 err = got_error(GOT_ERR_OBJ_TYPE);
3581 break;
3583 free(obj_id1);
3584 free(obj_id2);
3585 } else {
3586 obj_id2 = got_object_commit_get_tree_id(commit);
3587 err = got_object_id_str(&id_str2, obj_id2);
3588 if (err)
3589 goto done;
3590 if (pcommit) {
3591 obj_id1 = got_object_commit_get_tree_id(pcommit);
3592 err = got_object_id_str(&id_str1, obj_id1);
3593 if (err)
3594 goto done;
3596 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3597 id_str2);
3598 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3599 repo);
3601 done:
3602 free(id_str1);
3603 free(id_str2);
3604 if (pcommit)
3605 got_object_commit_close(pcommit);
3606 return err;
3609 static char *
3610 get_datestr(time_t *time, char *datebuf)
3612 struct tm mytm, *tm;
3613 char *p, *s;
3615 tm = gmtime_r(time, &mytm);
3616 if (tm == NULL)
3617 return NULL;
3618 s = asctime_r(tm, datebuf);
3619 if (s == NULL)
3620 return NULL;
3621 p = strchr(s, '\n');
3622 if (p)
3623 *p = '\0';
3624 return s;
3627 static const struct got_error *
3628 match_logmsg(int *have_match, struct got_object_id *id,
3629 struct got_commit_object *commit, regex_t *regex)
3631 const struct got_error *err = NULL;
3632 regmatch_t regmatch;
3633 char *id_str = NULL, *logmsg = NULL;
3635 *have_match = 0;
3637 err = got_object_id_str(&id_str, id);
3638 if (err)
3639 return err;
3641 err = got_object_commit_get_logmsg(&logmsg, commit);
3642 if (err)
3643 goto done;
3645 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3646 *have_match = 1;
3647 done:
3648 free(id_str);
3649 free(logmsg);
3650 return err;
3653 static void
3654 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3655 regex_t *regex)
3657 regmatch_t regmatch;
3658 struct got_pathlist_entry *pe;
3660 *have_match = 0;
3662 TAILQ_FOREACH(pe, changed_paths, entry) {
3663 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3664 *have_match = 1;
3665 break;
3670 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3672 static const struct got_error*
3673 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3674 struct got_object_id *id, struct got_repository *repo)
3676 static const struct got_error *err = NULL;
3677 struct got_reflist_entry *re;
3678 char *s;
3679 const char *name;
3681 *refs_str = NULL;
3683 TAILQ_FOREACH(re, refs, entry) {
3684 struct got_tag_object *tag = NULL;
3685 struct got_object_id *ref_id;
3686 int cmp;
3688 name = got_ref_get_name(re->ref);
3689 if (strcmp(name, GOT_REF_HEAD) == 0)
3690 continue;
3691 if (strncmp(name, "refs/", 5) == 0)
3692 name += 5;
3693 if (strncmp(name, "got/", 4) == 0)
3694 continue;
3695 if (strncmp(name, "heads/", 6) == 0)
3696 name += 6;
3697 if (strncmp(name, "remotes/", 8) == 0) {
3698 name += 8;
3699 s = strstr(name, "/" GOT_REF_HEAD);
3700 if (s != NULL && s[strlen(s)] == '\0')
3701 continue;
3703 err = got_ref_resolve(&ref_id, repo, re->ref);
3704 if (err)
3705 break;
3706 if (strncmp(name, "tags/", 5) == 0) {
3707 err = got_object_open_as_tag(&tag, repo, ref_id);
3708 if (err) {
3709 if (err->code != GOT_ERR_OBJ_TYPE) {
3710 free(ref_id);
3711 break;
3713 /* Ref points at something other than a tag. */
3714 err = NULL;
3715 tag = NULL;
3718 cmp = got_object_id_cmp(tag ?
3719 got_object_tag_get_object_id(tag) : ref_id, id);
3720 free(ref_id);
3721 if (tag)
3722 got_object_tag_close(tag);
3723 if (cmp != 0)
3724 continue;
3725 s = *refs_str;
3726 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3727 s ? ", " : "", name) == -1) {
3728 err = got_error_from_errno("asprintf");
3729 free(s);
3730 *refs_str = NULL;
3731 break;
3733 free(s);
3736 return err;
3739 static const struct got_error *
3740 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3741 struct got_repository *repo, const char *path,
3742 struct got_pathlist_head *changed_paths, int show_patch,
3743 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3744 const char *custom_refs_str)
3746 const struct got_error *err = NULL;
3747 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3748 char datebuf[26];
3749 time_t committer_time;
3750 const char *author, *committer;
3751 char *refs_str = NULL;
3753 err = got_object_id_str(&id_str, id);
3754 if (err)
3755 return err;
3757 if (custom_refs_str == NULL) {
3758 struct got_reflist_head *refs;
3759 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3760 if (refs) {
3761 err = build_refs_str(&refs_str, refs, id, repo);
3762 if (err)
3763 goto done;
3767 printf(GOT_COMMIT_SEP_STR);
3768 if (custom_refs_str)
3769 printf("commit %s (%s)\n", id_str, custom_refs_str);
3770 else
3771 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3772 refs_str ? refs_str : "", refs_str ? ")" : "");
3773 free(id_str);
3774 id_str = NULL;
3775 free(refs_str);
3776 refs_str = NULL;
3777 printf("from: %s\n", got_object_commit_get_author(commit));
3778 committer_time = got_object_commit_get_committer_time(commit);
3779 datestr = get_datestr(&committer_time, datebuf);
3780 if (datestr)
3781 printf("date: %s UTC\n", datestr);
3782 author = got_object_commit_get_author(commit);
3783 committer = got_object_commit_get_committer(commit);
3784 if (strcmp(author, committer) != 0)
3785 printf("via: %s\n", committer);
3786 if (got_object_commit_get_nparents(commit) > 1) {
3787 const struct got_object_id_queue *parent_ids;
3788 struct got_object_qid *qid;
3789 int n = 1;
3790 parent_ids = got_object_commit_get_parent_ids(commit);
3791 STAILQ_FOREACH(qid, parent_ids, entry) {
3792 err = got_object_id_str(&id_str, qid->id);
3793 if (err)
3794 goto done;
3795 printf("parent %d: %s\n", n++, id_str);
3796 free(id_str);
3797 id_str = NULL;
3801 err = got_object_commit_get_logmsg(&logmsg0, commit);
3802 if (err)
3803 goto done;
3805 logmsg = logmsg0;
3806 do {
3807 line = strsep(&logmsg, "\n");
3808 if (line)
3809 printf(" %s\n", line);
3810 } while (line);
3811 free(logmsg0);
3813 if (changed_paths) {
3814 struct got_pathlist_entry *pe;
3815 TAILQ_FOREACH(pe, changed_paths, entry) {
3816 struct got_diff_changed_path *cp = pe->data;
3817 printf(" %c %s\n", cp->status, pe->path);
3819 printf("\n");
3821 if (show_patch) {
3822 err = print_patch(commit, id, path, diff_context, repo);
3823 if (err == 0)
3824 printf("\n");
3827 if (fflush(stdout) != 0 && err == NULL)
3828 err = got_error_from_errno("fflush");
3829 done:
3830 free(id_str);
3831 free(refs_str);
3832 return err;
3835 static const struct got_error *
3836 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3837 struct got_repository *repo, const char *path, int show_changed_paths,
3838 int show_patch, const char *search_pattern, int diff_context, int limit,
3839 int log_branches, int reverse_display_order,
3840 struct got_reflist_object_id_map *refs_idmap)
3842 const struct got_error *err;
3843 struct got_commit_graph *graph;
3844 regex_t regex;
3845 int have_match;
3846 struct got_object_id_queue reversed_commits;
3847 struct got_object_qid *qid;
3848 struct got_commit_object *commit;
3849 struct got_pathlist_head changed_paths;
3850 struct got_pathlist_entry *pe;
3852 STAILQ_INIT(&reversed_commits);
3853 TAILQ_INIT(&changed_paths);
3855 if (search_pattern && regcomp(&regex, search_pattern,
3856 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3857 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3859 err = got_commit_graph_open(&graph, path, !log_branches);
3860 if (err)
3861 return err;
3862 err = got_commit_graph_iter_start(graph, root_id, repo,
3863 check_cancelled, NULL);
3864 if (err)
3865 goto done;
3866 for (;;) {
3867 struct got_object_id *id;
3869 if (sigint_received || sigpipe_received)
3870 break;
3872 err = got_commit_graph_iter_next(&id, graph, repo,
3873 check_cancelled, NULL);
3874 if (err) {
3875 if (err->code == GOT_ERR_ITER_COMPLETED)
3876 err = NULL;
3877 break;
3879 if (id == NULL)
3880 break;
3882 err = got_object_open_as_commit(&commit, repo, id);
3883 if (err)
3884 break;
3886 if (show_changed_paths && !reverse_display_order) {
3887 err = get_changed_paths(&changed_paths, commit, repo);
3888 if (err)
3889 break;
3892 if (search_pattern) {
3893 err = match_logmsg(&have_match, id, commit, &regex);
3894 if (err) {
3895 got_object_commit_close(commit);
3896 break;
3898 if (have_match == 0 && show_changed_paths)
3899 match_changed_paths(&have_match,
3900 &changed_paths, &regex);
3901 if (have_match == 0) {
3902 got_object_commit_close(commit);
3903 TAILQ_FOREACH(pe, &changed_paths, entry) {
3904 free((char *)pe->path);
3905 free(pe->data);
3907 got_pathlist_free(&changed_paths);
3908 continue;
3912 if (reverse_display_order) {
3913 err = got_object_qid_alloc(&qid, id);
3914 if (err)
3915 break;
3916 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3917 got_object_commit_close(commit);
3918 } else {
3919 err = print_commit(commit, id, repo, path,
3920 show_changed_paths ? &changed_paths : NULL,
3921 show_patch, diff_context, refs_idmap, NULL);
3922 got_object_commit_close(commit);
3923 if (err)
3924 break;
3926 if ((limit && --limit == 0) ||
3927 (end_id && got_object_id_cmp(id, end_id) == 0))
3928 break;
3930 TAILQ_FOREACH(pe, &changed_paths, entry) {
3931 free((char *)pe->path);
3932 free(pe->data);
3934 got_pathlist_free(&changed_paths);
3936 if (reverse_display_order) {
3937 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3938 err = got_object_open_as_commit(&commit, repo, qid->id);
3939 if (err)
3940 break;
3941 if (show_changed_paths) {
3942 err = get_changed_paths(&changed_paths,
3943 commit, repo);
3944 if (err)
3945 break;
3947 err = print_commit(commit, qid->id, repo, path,
3948 show_changed_paths ? &changed_paths : NULL,
3949 show_patch, diff_context, refs_idmap, NULL);
3950 got_object_commit_close(commit);
3951 if (err)
3952 break;
3953 TAILQ_FOREACH(pe, &changed_paths, entry) {
3954 free((char *)pe->path);
3955 free(pe->data);
3957 got_pathlist_free(&changed_paths);
3960 done:
3961 while (!STAILQ_EMPTY(&reversed_commits)) {
3962 qid = STAILQ_FIRST(&reversed_commits);
3963 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3964 got_object_qid_free(qid);
3966 TAILQ_FOREACH(pe, &changed_paths, entry) {
3967 free((char *)pe->path);
3968 free(pe->data);
3970 got_pathlist_free(&changed_paths);
3971 if (search_pattern)
3972 regfree(&regex);
3973 got_commit_graph_close(graph);
3974 return err;
3977 __dead static void
3978 usage_log(void)
3980 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3981 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3982 "[-R] [path]\n", getprogname());
3983 exit(1);
3986 static int
3987 get_default_log_limit(void)
3989 const char *got_default_log_limit;
3990 long long n;
3991 const char *errstr;
3993 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3994 if (got_default_log_limit == NULL)
3995 return 0;
3996 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3997 if (errstr != NULL)
3998 return 0;
3999 return n;
4002 static const struct got_error *
4003 cmd_log(int argc, char *argv[])
4005 const struct got_error *error;
4006 struct got_repository *repo = NULL;
4007 struct got_worktree *worktree = NULL;
4008 struct got_object_id *start_id = NULL, *end_id = NULL;
4009 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4010 const char *start_commit = NULL, *end_commit = NULL;
4011 const char *search_pattern = NULL;
4012 int diff_context = -1, ch;
4013 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4014 int reverse_display_order = 0;
4015 const char *errstr;
4016 struct got_reflist_head refs;
4017 struct got_reflist_object_id_map *refs_idmap = NULL;
4019 TAILQ_INIT(&refs);
4021 #ifndef PROFILE
4022 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4023 NULL)
4024 == -1)
4025 err(1, "pledge");
4026 #endif
4028 limit = get_default_log_limit();
4030 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4031 switch (ch) {
4032 case 'p':
4033 show_patch = 1;
4034 break;
4035 case 'P':
4036 show_changed_paths = 1;
4037 break;
4038 case 'c':
4039 start_commit = optarg;
4040 break;
4041 case 'C':
4042 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4043 &errstr);
4044 if (errstr != NULL)
4045 err(1, "-C option %s", errstr);
4046 break;
4047 case 'l':
4048 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4049 if (errstr != NULL)
4050 err(1, "-l option %s", errstr);
4051 break;
4052 case 'b':
4053 log_branches = 1;
4054 break;
4055 case 'r':
4056 repo_path = realpath(optarg, NULL);
4057 if (repo_path == NULL)
4058 return got_error_from_errno2("realpath",
4059 optarg);
4060 got_path_strip_trailing_slashes(repo_path);
4061 break;
4062 case 'R':
4063 reverse_display_order = 1;
4064 break;
4065 case 's':
4066 search_pattern = optarg;
4067 break;
4068 case 'x':
4069 end_commit = optarg;
4070 break;
4071 default:
4072 usage_log();
4073 /* NOTREACHED */
4077 argc -= optind;
4078 argv += optind;
4080 if (diff_context == -1)
4081 diff_context = 3;
4082 else if (!show_patch)
4083 errx(1, "-C requires -p");
4085 cwd = getcwd(NULL, 0);
4086 if (cwd == NULL) {
4087 error = got_error_from_errno("getcwd");
4088 goto done;
4091 if (repo_path == NULL) {
4092 error = got_worktree_open(&worktree, cwd);
4093 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4094 goto done;
4095 error = NULL;
4098 if (argc == 1) {
4099 if (worktree) {
4100 error = got_worktree_resolve_path(&path, worktree,
4101 argv[0]);
4102 if (error)
4103 goto done;
4104 } else {
4105 path = strdup(argv[0]);
4106 if (path == NULL) {
4107 error = got_error_from_errno("strdup");
4108 goto done;
4111 } else if (argc != 0)
4112 usage_log();
4114 if (repo_path == NULL) {
4115 repo_path = worktree ?
4116 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4118 if (repo_path == NULL) {
4119 error = got_error_from_errno("strdup");
4120 goto done;
4123 error = got_repo_open(&repo, repo_path, NULL);
4124 if (error != NULL)
4125 goto done;
4127 error = apply_unveil(got_repo_get_path(repo), 1,
4128 worktree ? got_worktree_get_root_path(worktree) : NULL);
4129 if (error)
4130 goto done;
4132 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4133 if (error)
4134 goto done;
4136 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4137 if (error)
4138 goto done;
4140 if (start_commit == NULL) {
4141 struct got_reference *head_ref;
4142 struct got_commit_object *commit = NULL;
4143 error = got_ref_open(&head_ref, repo,
4144 worktree ? got_worktree_get_head_ref_name(worktree)
4145 : GOT_REF_HEAD, 0);
4146 if (error != NULL)
4147 goto done;
4148 error = got_ref_resolve(&start_id, repo, head_ref);
4149 got_ref_close(head_ref);
4150 if (error != NULL)
4151 goto done;
4152 error = got_object_open_as_commit(&commit, repo,
4153 start_id);
4154 if (error != NULL)
4155 goto done;
4156 got_object_commit_close(commit);
4157 } else {
4158 error = got_repo_match_object_id(&start_id, NULL,
4159 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4160 if (error != NULL)
4161 goto done;
4163 if (end_commit != NULL) {
4164 error = got_repo_match_object_id(&end_id, NULL,
4165 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4166 if (error != NULL)
4167 goto done;
4170 if (worktree) {
4172 * If a path was specified on the command line it was resolved
4173 * to a path in the work tree above. Prepend the work tree's
4174 * path prefix to obtain the corresponding in-repository path.
4176 if (path) {
4177 const char *prefix;
4178 prefix = got_worktree_get_path_prefix(worktree);
4179 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4180 (path[0] != '\0') ? "/" : "", path) == -1) {
4181 error = got_error_from_errno("asprintf");
4182 goto done;
4185 } else
4186 error = got_repo_map_path(&in_repo_path, repo,
4187 path ? path : "");
4188 if (error != NULL)
4189 goto done;
4190 if (in_repo_path) {
4191 free(path);
4192 path = in_repo_path;
4195 error = print_commits(start_id, end_id, repo, path ? path : "",
4196 show_changed_paths, show_patch, search_pattern, diff_context,
4197 limit, log_branches, reverse_display_order, refs_idmap);
4198 done:
4199 free(path);
4200 free(repo_path);
4201 free(cwd);
4202 if (worktree)
4203 got_worktree_close(worktree);
4204 if (repo) {
4205 const struct got_error *close_err = got_repo_close(repo);
4206 if (error == NULL)
4207 error = close_err;
4209 if (refs_idmap)
4210 got_reflist_object_id_map_free(refs_idmap);
4211 got_ref_list_free(&refs);
4212 return error;
4215 __dead static void
4216 usage_diff(void)
4218 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4219 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4220 exit(1);
4223 struct print_diff_arg {
4224 struct got_repository *repo;
4225 struct got_worktree *worktree;
4226 int diff_context;
4227 const char *id_str;
4228 int header_shown;
4229 int diff_staged;
4230 int ignore_whitespace;
4231 int force_text_diff;
4235 * Create a file which contains the target path of a symlink so we can feed
4236 * it as content to the diff engine.
4238 static const struct got_error *
4239 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4240 const char *abspath)
4242 const struct got_error *err = NULL;
4243 char target_path[PATH_MAX];
4244 ssize_t target_len, outlen;
4246 *fd = -1;
4248 if (dirfd != -1) {
4249 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4250 if (target_len == -1)
4251 return got_error_from_errno2("readlinkat", abspath);
4252 } else {
4253 target_len = readlink(abspath, target_path, PATH_MAX);
4254 if (target_len == -1)
4255 return got_error_from_errno2("readlink", abspath);
4258 *fd = got_opentempfd();
4259 if (*fd == -1)
4260 return got_error_from_errno("got_opentempfd");
4262 outlen = write(*fd, target_path, target_len);
4263 if (outlen == -1) {
4264 err = got_error_from_errno("got_opentempfd");
4265 goto done;
4268 if (lseek(*fd, 0, SEEK_SET) == -1) {
4269 err = got_error_from_errno2("lseek", abspath);
4270 goto done;
4272 done:
4273 if (err) {
4274 close(*fd);
4275 *fd = -1;
4277 return err;
4280 static const struct got_error *
4281 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4282 const char *path, struct got_object_id *blob_id,
4283 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4284 int dirfd, const char *de_name)
4286 struct print_diff_arg *a = arg;
4287 const struct got_error *err = NULL;
4288 struct got_blob_object *blob1 = NULL;
4289 int fd = -1;
4290 FILE *f2 = NULL;
4291 char *abspath = NULL, *label1 = NULL;
4292 struct stat sb;
4294 if (a->diff_staged) {
4295 if (staged_status != GOT_STATUS_MODIFY &&
4296 staged_status != GOT_STATUS_ADD &&
4297 staged_status != GOT_STATUS_DELETE)
4298 return NULL;
4299 } else {
4300 if (staged_status == GOT_STATUS_DELETE)
4301 return NULL;
4302 if (status == GOT_STATUS_NONEXISTENT)
4303 return got_error_set_errno(ENOENT, path);
4304 if (status != GOT_STATUS_MODIFY &&
4305 status != GOT_STATUS_ADD &&
4306 status != GOT_STATUS_DELETE &&
4307 status != GOT_STATUS_CONFLICT)
4308 return NULL;
4311 if (!a->header_shown) {
4312 printf("diff %s %s%s\n", a->id_str,
4313 got_worktree_get_root_path(a->worktree),
4314 a->diff_staged ? " (staged changes)" : "");
4315 a->header_shown = 1;
4318 if (a->diff_staged) {
4319 const char *label1 = NULL, *label2 = NULL;
4320 switch (staged_status) {
4321 case GOT_STATUS_MODIFY:
4322 label1 = path;
4323 label2 = path;
4324 break;
4325 case GOT_STATUS_ADD:
4326 label2 = path;
4327 break;
4328 case GOT_STATUS_DELETE:
4329 label1 = path;
4330 break;
4331 default:
4332 return got_error(GOT_ERR_FILE_STATUS);
4334 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4335 staged_blob_id, label1, label2, a->diff_context,
4336 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4339 if (staged_status == GOT_STATUS_ADD ||
4340 staged_status == GOT_STATUS_MODIFY) {
4341 char *id_str;
4342 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4343 8192);
4344 if (err)
4345 goto done;
4346 err = got_object_id_str(&id_str, staged_blob_id);
4347 if (err)
4348 goto done;
4349 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4350 err = got_error_from_errno("asprintf");
4351 free(id_str);
4352 goto done;
4354 free(id_str);
4355 } else if (status != GOT_STATUS_ADD) {
4356 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4357 if (err)
4358 goto done;
4361 if (status != GOT_STATUS_DELETE) {
4362 if (asprintf(&abspath, "%s/%s",
4363 got_worktree_get_root_path(a->worktree), path) == -1) {
4364 err = got_error_from_errno("asprintf");
4365 goto done;
4368 if (dirfd != -1) {
4369 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4370 if (fd == -1) {
4371 if (errno != ELOOP) {
4372 err = got_error_from_errno2("openat",
4373 abspath);
4374 goto done;
4376 err = get_symlink_target_file(&fd, dirfd,
4377 de_name, abspath);
4378 if (err)
4379 goto done;
4381 } else {
4382 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4383 if (fd == -1) {
4384 if (errno != ELOOP) {
4385 err = got_error_from_errno2("open",
4386 abspath);
4387 goto done;
4389 err = get_symlink_target_file(&fd, dirfd,
4390 de_name, abspath);
4391 if (err)
4392 goto done;
4395 if (fstat(fd, &sb) == -1) {
4396 err = got_error_from_errno2("fstat", abspath);
4397 goto done;
4399 f2 = fdopen(fd, "r");
4400 if (f2 == NULL) {
4401 err = got_error_from_errno2("fdopen", abspath);
4402 goto done;
4404 fd = -1;
4405 } else
4406 sb.st_size = 0;
4408 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4409 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4410 done:
4411 if (blob1)
4412 got_object_blob_close(blob1);
4413 if (f2 && fclose(f2) == EOF && err == NULL)
4414 err = got_error_from_errno("fclose");
4415 if (fd != -1 && close(fd) == -1 && err == NULL)
4416 err = got_error_from_errno("close");
4417 free(abspath);
4418 return err;
4421 static const struct got_error *
4422 cmd_diff(int argc, char *argv[])
4424 const struct got_error *error;
4425 struct got_repository *repo = NULL;
4426 struct got_worktree *worktree = NULL;
4427 char *cwd = NULL, *repo_path = NULL;
4428 struct got_object_id *id1 = NULL, *id2 = NULL;
4429 const char *id_str1 = NULL, *id_str2 = NULL;
4430 char *label1 = NULL, *label2 = NULL;
4431 int type1, type2;
4432 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4433 int force_text_diff = 0;
4434 const char *errstr;
4435 char *path = NULL;
4436 struct got_reflist_head refs;
4438 TAILQ_INIT(&refs);
4440 #ifndef PROFILE
4441 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4442 NULL) == -1)
4443 err(1, "pledge");
4444 #endif
4446 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4447 switch (ch) {
4448 case 'a':
4449 force_text_diff = 1;
4450 break;
4451 case 'C':
4452 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4453 &errstr);
4454 if (errstr != NULL)
4455 err(1, "-C option %s", errstr);
4456 break;
4457 case 'r':
4458 repo_path = realpath(optarg, NULL);
4459 if (repo_path == NULL)
4460 return got_error_from_errno2("realpath",
4461 optarg);
4462 got_path_strip_trailing_slashes(repo_path);
4463 break;
4464 case 's':
4465 diff_staged = 1;
4466 break;
4467 case 'w':
4468 ignore_whitespace = 1;
4469 break;
4470 default:
4471 usage_diff();
4472 /* NOTREACHED */
4476 argc -= optind;
4477 argv += optind;
4479 cwd = getcwd(NULL, 0);
4480 if (cwd == NULL) {
4481 error = got_error_from_errno("getcwd");
4482 goto done;
4484 if (argc <= 1) {
4485 if (repo_path)
4486 errx(1,
4487 "-r option can't be used when diffing a work tree");
4488 error = got_worktree_open(&worktree, cwd);
4489 if (error) {
4490 if (error->code == GOT_ERR_NOT_WORKTREE)
4491 error = wrap_not_worktree_error(error, "diff",
4492 cwd);
4493 goto done;
4495 repo_path = strdup(got_worktree_get_repo_path(worktree));
4496 if (repo_path == NULL) {
4497 error = got_error_from_errno("strdup");
4498 goto done;
4500 if (argc == 1) {
4501 error = got_worktree_resolve_path(&path, worktree,
4502 argv[0]);
4503 if (error)
4504 goto done;
4505 } else {
4506 path = strdup("");
4507 if (path == NULL) {
4508 error = got_error_from_errno("strdup");
4509 goto done;
4512 } else if (argc == 2) {
4513 if (diff_staged)
4514 errx(1, "-s option can't be used when diffing "
4515 "objects in repository");
4516 id_str1 = argv[0];
4517 id_str2 = argv[1];
4518 if (repo_path == NULL) {
4519 error = got_worktree_open(&worktree, cwd);
4520 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4521 goto done;
4522 repo_path = strdup(worktree ?
4523 got_worktree_get_repo_path(worktree) : cwd);
4524 if (repo_path == NULL) {
4525 error = got_error_from_errno("strdup");
4526 goto done;
4529 } else
4530 usage_diff();
4532 error = got_repo_open(&repo, repo_path, NULL);
4533 free(repo_path);
4534 if (error != NULL)
4535 goto done;
4537 error = apply_unveil(got_repo_get_path(repo), 1,
4538 worktree ? got_worktree_get_root_path(worktree) : NULL);
4539 if (error)
4540 goto done;
4542 if (argc <= 1) {
4543 struct print_diff_arg arg;
4544 struct got_pathlist_head paths;
4545 char *id_str;
4547 TAILQ_INIT(&paths);
4549 error = got_object_id_str(&id_str,
4550 got_worktree_get_base_commit_id(worktree));
4551 if (error)
4552 goto done;
4553 arg.repo = repo;
4554 arg.worktree = worktree;
4555 arg.diff_context = diff_context;
4556 arg.id_str = id_str;
4557 arg.header_shown = 0;
4558 arg.diff_staged = diff_staged;
4559 arg.ignore_whitespace = ignore_whitespace;
4560 arg.force_text_diff = force_text_diff;
4562 error = got_pathlist_append(&paths, path, NULL);
4563 if (error)
4564 goto done;
4566 error = got_worktree_status(worktree, &paths, repo, 0,
4567 print_diff, &arg, check_cancelled, NULL);
4568 free(id_str);
4569 got_pathlist_free(&paths);
4570 goto done;
4573 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4574 if (error)
4575 return error;
4577 error = got_repo_match_object_id(&id1, &label1, id_str1,
4578 GOT_OBJ_TYPE_ANY, &refs, repo);
4579 if (error)
4580 goto done;
4582 error = got_repo_match_object_id(&id2, &label2, id_str2,
4583 GOT_OBJ_TYPE_ANY, &refs, repo);
4584 if (error)
4585 goto done;
4587 error = got_object_get_type(&type1, repo, id1);
4588 if (error)
4589 goto done;
4591 error = got_object_get_type(&type2, repo, id2);
4592 if (error)
4593 goto done;
4595 if (type1 != type2) {
4596 error = got_error(GOT_ERR_OBJ_TYPE);
4597 goto done;
4600 switch (type1) {
4601 case GOT_OBJ_TYPE_BLOB:
4602 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4603 NULL, NULL, diff_context, ignore_whitespace,
4604 force_text_diff, repo, stdout);
4605 break;
4606 case GOT_OBJ_TYPE_TREE:
4607 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4608 "", "", diff_context, ignore_whitespace, force_text_diff,
4609 repo, stdout);
4610 break;
4611 case GOT_OBJ_TYPE_COMMIT:
4612 printf("diff %s %s\n", label1, label2);
4613 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4614 diff_context, ignore_whitespace, force_text_diff, repo,
4615 stdout);
4616 break;
4617 default:
4618 error = got_error(GOT_ERR_OBJ_TYPE);
4620 done:
4621 free(label1);
4622 free(label2);
4623 free(id1);
4624 free(id2);
4625 free(path);
4626 if (worktree)
4627 got_worktree_close(worktree);
4628 if (repo) {
4629 const struct got_error *close_err = got_repo_close(repo);
4630 if (error == NULL)
4631 error = close_err;
4633 got_ref_list_free(&refs);
4634 return error;
4637 __dead static void
4638 usage_blame(void)
4640 fprintf(stderr,
4641 "usage: %s blame [-c commit] [-r repository-path] path\n",
4642 getprogname());
4643 exit(1);
4646 struct blame_line {
4647 int annotated;
4648 char *id_str;
4649 char *committer;
4650 char datebuf[11]; /* YYYY-MM-DD + NUL */
4653 struct blame_cb_args {
4654 struct blame_line *lines;
4655 int nlines;
4656 int nlines_prec;
4657 int lineno_cur;
4658 off_t *line_offsets;
4659 FILE *f;
4660 struct got_repository *repo;
4663 static const struct got_error *
4664 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4666 const struct got_error *err = NULL;
4667 struct blame_cb_args *a = arg;
4668 struct blame_line *bline;
4669 char *line = NULL;
4670 size_t linesize = 0;
4671 struct got_commit_object *commit = NULL;
4672 off_t offset;
4673 struct tm tm;
4674 time_t committer_time;
4676 if (nlines != a->nlines ||
4677 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4678 return got_error(GOT_ERR_RANGE);
4680 if (sigint_received)
4681 return got_error(GOT_ERR_ITER_COMPLETED);
4683 if (lineno == -1)
4684 return NULL; /* no change in this commit */
4686 /* Annotate this line. */
4687 bline = &a->lines[lineno - 1];
4688 if (bline->annotated)
4689 return NULL;
4690 err = got_object_id_str(&bline->id_str, id);
4691 if (err)
4692 return err;
4694 err = got_object_open_as_commit(&commit, a->repo, id);
4695 if (err)
4696 goto done;
4698 bline->committer = strdup(got_object_commit_get_committer(commit));
4699 if (bline->committer == NULL) {
4700 err = got_error_from_errno("strdup");
4701 goto done;
4704 committer_time = got_object_commit_get_committer_time(commit);
4705 if (gmtime_r(&committer_time, &tm) == NULL)
4706 return got_error_from_errno("gmtime_r");
4707 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4708 &tm) == 0) {
4709 err = got_error(GOT_ERR_NO_SPACE);
4710 goto done;
4712 bline->annotated = 1;
4714 /* Print lines annotated so far. */
4715 bline = &a->lines[a->lineno_cur - 1];
4716 if (!bline->annotated)
4717 goto done;
4719 offset = a->line_offsets[a->lineno_cur - 1];
4720 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4721 err = got_error_from_errno("fseeko");
4722 goto done;
4725 while (bline->annotated) {
4726 char *smallerthan, *at, *nl, *committer;
4727 size_t len;
4729 if (getline(&line, &linesize, a->f) == -1) {
4730 if (ferror(a->f))
4731 err = got_error_from_errno("getline");
4732 break;
4735 committer = bline->committer;
4736 smallerthan = strchr(committer, '<');
4737 if (smallerthan && smallerthan[1] != '\0')
4738 committer = smallerthan + 1;
4739 at = strchr(committer, '@');
4740 if (at)
4741 *at = '\0';
4742 len = strlen(committer);
4743 if (len >= 9)
4744 committer[8] = '\0';
4746 nl = strchr(line, '\n');
4747 if (nl)
4748 *nl = '\0';
4749 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4750 bline->id_str, bline->datebuf, committer, line);
4752 a->lineno_cur++;
4753 bline = &a->lines[a->lineno_cur - 1];
4755 done:
4756 if (commit)
4757 got_object_commit_close(commit);
4758 free(line);
4759 return err;
4762 static const struct got_error *
4763 cmd_blame(int argc, char *argv[])
4765 const struct got_error *error;
4766 struct got_repository *repo = NULL;
4767 struct got_worktree *worktree = NULL;
4768 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4769 char *link_target = NULL;
4770 struct got_object_id *obj_id = NULL;
4771 struct got_object_id *commit_id = NULL;
4772 struct got_blob_object *blob = NULL;
4773 char *commit_id_str = NULL;
4774 struct blame_cb_args bca;
4775 int ch, obj_type, i;
4776 off_t filesize;
4778 memset(&bca, 0, sizeof(bca));
4780 #ifndef PROFILE
4781 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4782 NULL) == -1)
4783 err(1, "pledge");
4784 #endif
4786 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4787 switch (ch) {
4788 case 'c':
4789 commit_id_str = optarg;
4790 break;
4791 case 'r':
4792 repo_path = realpath(optarg, NULL);
4793 if (repo_path == NULL)
4794 return got_error_from_errno2("realpath",
4795 optarg);
4796 got_path_strip_trailing_slashes(repo_path);
4797 break;
4798 default:
4799 usage_blame();
4800 /* NOTREACHED */
4804 argc -= optind;
4805 argv += optind;
4807 if (argc == 1)
4808 path = argv[0];
4809 else
4810 usage_blame();
4812 cwd = getcwd(NULL, 0);
4813 if (cwd == NULL) {
4814 error = got_error_from_errno("getcwd");
4815 goto done;
4817 if (repo_path == NULL) {
4818 error = got_worktree_open(&worktree, cwd);
4819 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4820 goto done;
4821 else
4822 error = NULL;
4823 if (worktree) {
4824 repo_path =
4825 strdup(got_worktree_get_repo_path(worktree));
4826 if (repo_path == NULL) {
4827 error = got_error_from_errno("strdup");
4828 if (error)
4829 goto done;
4831 } else {
4832 repo_path = strdup(cwd);
4833 if (repo_path == NULL) {
4834 error = got_error_from_errno("strdup");
4835 goto done;
4840 error = got_repo_open(&repo, repo_path, NULL);
4841 if (error != NULL)
4842 goto done;
4844 if (worktree) {
4845 const char *prefix = got_worktree_get_path_prefix(worktree);
4846 char *p;
4848 error = got_worktree_resolve_path(&p, worktree, path);
4849 if (error)
4850 goto done;
4851 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4852 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4853 p) == -1) {
4854 error = got_error_from_errno("asprintf");
4855 free(p);
4856 goto done;
4858 free(p);
4859 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4860 } else {
4861 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4862 if (error)
4863 goto done;
4864 error = got_repo_map_path(&in_repo_path, repo, path);
4866 if (error)
4867 goto done;
4869 if (commit_id_str == NULL) {
4870 struct got_reference *head_ref;
4871 error = got_ref_open(&head_ref, repo, worktree ?
4872 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4873 if (error != NULL)
4874 goto done;
4875 error = got_ref_resolve(&commit_id, repo, head_ref);
4876 got_ref_close(head_ref);
4877 if (error != NULL)
4878 goto done;
4879 } else {
4880 struct got_reflist_head refs;
4881 TAILQ_INIT(&refs);
4882 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4883 NULL);
4884 if (error)
4885 goto done;
4886 error = got_repo_match_object_id(&commit_id, NULL,
4887 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4888 got_ref_list_free(&refs);
4889 if (error)
4890 goto done;
4893 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4894 commit_id, repo);
4895 if (error)
4896 goto done;
4898 error = got_object_id_by_path(&obj_id, repo, commit_id,
4899 link_target ? link_target : in_repo_path);
4900 if (error)
4901 goto done;
4903 error = got_object_get_type(&obj_type, repo, obj_id);
4904 if (error)
4905 goto done;
4907 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4908 error = got_error_path(link_target ? link_target : in_repo_path,
4909 GOT_ERR_OBJ_TYPE);
4910 goto done;
4913 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4914 if (error)
4915 goto done;
4916 bca.f = got_opentemp();
4917 if (bca.f == NULL) {
4918 error = got_error_from_errno("got_opentemp");
4919 goto done;
4921 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4922 &bca.line_offsets, bca.f, blob);
4923 if (error || bca.nlines == 0)
4924 goto done;
4926 /* Don't include \n at EOF in the blame line count. */
4927 if (bca.line_offsets[bca.nlines - 1] == filesize)
4928 bca.nlines--;
4930 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4931 if (bca.lines == NULL) {
4932 error = got_error_from_errno("calloc");
4933 goto done;
4935 bca.lineno_cur = 1;
4936 bca.nlines_prec = 0;
4937 i = bca.nlines;
4938 while (i > 0) {
4939 i /= 10;
4940 bca.nlines_prec++;
4942 bca.repo = repo;
4944 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4945 repo, blame_cb, &bca, check_cancelled, NULL);
4946 done:
4947 free(in_repo_path);
4948 free(link_target);
4949 free(repo_path);
4950 free(cwd);
4951 free(commit_id);
4952 free(obj_id);
4953 if (blob)
4954 got_object_blob_close(blob);
4955 if (worktree)
4956 got_worktree_close(worktree);
4957 if (repo) {
4958 const struct got_error *close_err = got_repo_close(repo);
4959 if (error == NULL)
4960 error = close_err;
4962 if (bca.lines) {
4963 for (i = 0; i < bca.nlines; i++) {
4964 struct blame_line *bline = &bca.lines[i];
4965 free(bline->id_str);
4966 free(bline->committer);
4968 free(bca.lines);
4970 free(bca.line_offsets);
4971 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4972 error = got_error_from_errno("fclose");
4973 return error;
4976 __dead static void
4977 usage_tree(void)
4979 fprintf(stderr,
4980 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4981 getprogname());
4982 exit(1);
4985 static const struct got_error *
4986 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4987 const char *root_path, struct got_repository *repo)
4989 const struct got_error *err = NULL;
4990 int is_root_path = (strcmp(path, root_path) == 0);
4991 const char *modestr = "";
4992 mode_t mode = got_tree_entry_get_mode(te);
4993 char *link_target = NULL;
4995 path += strlen(root_path);
4996 while (path[0] == '/')
4997 path++;
4999 if (got_object_tree_entry_is_submodule(te))
5000 modestr = "$";
5001 else if (S_ISLNK(mode)) {
5002 int i;
5004 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5005 if (err)
5006 return err;
5007 for (i = 0; i < strlen(link_target); i++) {
5008 if (!isprint((unsigned char)link_target[i]))
5009 link_target[i] = '?';
5012 modestr = "@";
5014 else if (S_ISDIR(mode))
5015 modestr = "/";
5016 else if (mode & S_IXUSR)
5017 modestr = "*";
5019 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5020 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5021 link_target ? " -> ": "", link_target ? link_target : "");
5023 free(link_target);
5024 return NULL;
5027 static const struct got_error *
5028 print_tree(const char *path, struct got_object_id *commit_id,
5029 int show_ids, int recurse, const char *root_path,
5030 struct got_repository *repo)
5032 const struct got_error *err = NULL;
5033 struct got_object_id *tree_id = NULL;
5034 struct got_tree_object *tree = NULL;
5035 int nentries, i;
5037 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5038 if (err)
5039 goto done;
5041 err = got_object_open_as_tree(&tree, repo, tree_id);
5042 if (err)
5043 goto done;
5044 nentries = got_object_tree_get_nentries(tree);
5045 for (i = 0; i < nentries; i++) {
5046 struct got_tree_entry *te;
5047 char *id = NULL;
5049 if (sigint_received || sigpipe_received)
5050 break;
5052 te = got_object_tree_get_entry(tree, i);
5053 if (show_ids) {
5054 char *id_str;
5055 err = got_object_id_str(&id_str,
5056 got_tree_entry_get_id(te));
5057 if (err)
5058 goto done;
5059 if (asprintf(&id, "%s ", id_str) == -1) {
5060 err = got_error_from_errno("asprintf");
5061 free(id_str);
5062 goto done;
5064 free(id_str);
5066 err = print_entry(te, id, path, root_path, repo);
5067 free(id);
5068 if (err)
5069 goto done;
5071 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5072 char *child_path;
5073 if (asprintf(&child_path, "%s%s%s", path,
5074 path[0] == '/' && path[1] == '\0' ? "" : "/",
5075 got_tree_entry_get_name(te)) == -1) {
5076 err = got_error_from_errno("asprintf");
5077 goto done;
5079 err = print_tree(child_path, commit_id, show_ids, 1,
5080 root_path, repo);
5081 free(child_path);
5082 if (err)
5083 goto done;
5086 done:
5087 if (tree)
5088 got_object_tree_close(tree);
5089 free(tree_id);
5090 return err;
5093 static const struct got_error *
5094 cmd_tree(int argc, char *argv[])
5096 const struct got_error *error;
5097 struct got_repository *repo = NULL;
5098 struct got_worktree *worktree = NULL;
5099 const char *path, *refname = NULL;
5100 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5101 struct got_object_id *commit_id = NULL;
5102 char *commit_id_str = NULL;
5103 int show_ids = 0, recurse = 0;
5104 int ch;
5106 #ifndef PROFILE
5107 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5108 NULL) == -1)
5109 err(1, "pledge");
5110 #endif
5112 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5113 switch (ch) {
5114 case 'c':
5115 commit_id_str = optarg;
5116 break;
5117 case 'r':
5118 repo_path = realpath(optarg, NULL);
5119 if (repo_path == NULL)
5120 return got_error_from_errno2("realpath",
5121 optarg);
5122 got_path_strip_trailing_slashes(repo_path);
5123 break;
5124 case 'i':
5125 show_ids = 1;
5126 break;
5127 case 'R':
5128 recurse = 1;
5129 break;
5130 default:
5131 usage_tree();
5132 /* NOTREACHED */
5136 argc -= optind;
5137 argv += optind;
5139 if (argc == 1)
5140 path = argv[0];
5141 else if (argc > 1)
5142 usage_tree();
5143 else
5144 path = NULL;
5146 cwd = getcwd(NULL, 0);
5147 if (cwd == NULL) {
5148 error = got_error_from_errno("getcwd");
5149 goto done;
5151 if (repo_path == NULL) {
5152 error = got_worktree_open(&worktree, cwd);
5153 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5154 goto done;
5155 else
5156 error = NULL;
5157 if (worktree) {
5158 repo_path =
5159 strdup(got_worktree_get_repo_path(worktree));
5160 if (repo_path == NULL)
5161 error = got_error_from_errno("strdup");
5162 if (error)
5163 goto done;
5164 } else {
5165 repo_path = strdup(cwd);
5166 if (repo_path == NULL) {
5167 error = got_error_from_errno("strdup");
5168 goto done;
5173 error = got_repo_open(&repo, repo_path, NULL);
5174 if (error != NULL)
5175 goto done;
5177 if (worktree) {
5178 const char *prefix = got_worktree_get_path_prefix(worktree);
5179 char *p;
5181 if (path == NULL)
5182 path = "";
5183 error = got_worktree_resolve_path(&p, worktree, path);
5184 if (error)
5185 goto done;
5186 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5187 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5188 p) == -1) {
5189 error = got_error_from_errno("asprintf");
5190 free(p);
5191 goto done;
5193 free(p);
5194 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5195 if (error)
5196 goto done;
5197 } else {
5198 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5199 if (error)
5200 goto done;
5201 if (path == NULL)
5202 path = "/";
5203 error = got_repo_map_path(&in_repo_path, repo, path);
5204 if (error != NULL)
5205 goto done;
5208 if (commit_id_str == NULL) {
5209 struct got_reference *head_ref;
5210 if (worktree)
5211 refname = got_worktree_get_head_ref_name(worktree);
5212 else
5213 refname = GOT_REF_HEAD;
5214 error = got_ref_open(&head_ref, repo, refname, 0);
5215 if (error != NULL)
5216 goto done;
5217 error = got_ref_resolve(&commit_id, repo, head_ref);
5218 got_ref_close(head_ref);
5219 if (error != NULL)
5220 goto done;
5221 } else {
5222 struct got_reflist_head refs;
5223 TAILQ_INIT(&refs);
5224 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5225 NULL);
5226 if (error)
5227 goto done;
5228 error = got_repo_match_object_id(&commit_id, NULL,
5229 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5230 got_ref_list_free(&refs);
5231 if (error)
5232 goto done;
5235 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5236 in_repo_path, repo);
5237 done:
5238 free(in_repo_path);
5239 free(repo_path);
5240 free(cwd);
5241 free(commit_id);
5242 if (worktree)
5243 got_worktree_close(worktree);
5244 if (repo) {
5245 const struct got_error *close_err = got_repo_close(repo);
5246 if (error == NULL)
5247 error = close_err;
5249 return error;
5252 __dead static void
5253 usage_status(void)
5255 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5256 "[-S status-codes] [path ...]\n", getprogname());
5257 exit(1);
5260 struct got_status_arg {
5261 char *status_codes;
5262 int suppress;
5265 static const struct got_error *
5266 print_status(void *arg, unsigned char status, unsigned char staged_status,
5267 const char *path, struct got_object_id *blob_id,
5268 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5269 int dirfd, const char *de_name)
5271 struct got_status_arg *st = arg;
5273 if (status == staged_status && (status == GOT_STATUS_DELETE))
5274 status = GOT_STATUS_NO_CHANGE;
5275 if (st != NULL && st->status_codes) {
5276 size_t ncodes = strlen(st->status_codes);
5277 int i, j = 0;
5279 for (i = 0; i < ncodes ; i++) {
5280 if (st->suppress) {
5281 if (status == st->status_codes[i] ||
5282 staged_status == st->status_codes[i]) {
5283 j++;
5284 continue;
5286 } else {
5287 if (status == st->status_codes[i] ||
5288 staged_status == st->status_codes[i])
5289 break;
5293 if (st->suppress && j == 0)
5294 goto print;
5296 if (i == ncodes)
5297 return NULL;
5299 print:
5300 printf("%c%c %s\n", status, staged_status, path);
5301 return NULL;
5304 static const struct got_error *
5305 cmd_status(int argc, char *argv[])
5307 const struct got_error *error = NULL;
5308 struct got_repository *repo = NULL;
5309 struct got_worktree *worktree = NULL;
5310 struct got_status_arg st;
5311 char *cwd = NULL;
5312 struct got_pathlist_head paths;
5313 struct got_pathlist_entry *pe;
5314 int ch, i, no_ignores = 0;
5316 TAILQ_INIT(&paths);
5318 memset(&st, 0, sizeof(st));
5319 st.status_codes = NULL;
5320 st.suppress = 0;
5322 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5323 switch (ch) {
5324 case 'I':
5325 no_ignores = 1;
5326 break;
5327 case 'S':
5328 if (st.status_codes != NULL && st.suppress == 0)
5329 option_conflict('S', 's');
5330 st.suppress = 1;
5331 /* fallthrough */
5332 case 's':
5333 for (i = 0; i < strlen(optarg); i++) {
5334 switch (optarg[i]) {
5335 case GOT_STATUS_MODIFY:
5336 case GOT_STATUS_ADD:
5337 case GOT_STATUS_DELETE:
5338 case GOT_STATUS_CONFLICT:
5339 case GOT_STATUS_MISSING:
5340 case GOT_STATUS_OBSTRUCTED:
5341 case GOT_STATUS_UNVERSIONED:
5342 case GOT_STATUS_MODE_CHANGE:
5343 case GOT_STATUS_NONEXISTENT:
5344 break;
5345 default:
5346 errx(1, "invalid status code '%c'",
5347 optarg[i]);
5350 if (ch == 's' && st.suppress)
5351 option_conflict('s', 'S');
5352 st.status_codes = optarg;
5353 break;
5354 default:
5355 usage_status();
5356 /* NOTREACHED */
5360 argc -= optind;
5361 argv += optind;
5363 #ifndef PROFILE
5364 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5365 NULL) == -1)
5366 err(1, "pledge");
5367 #endif
5368 cwd = getcwd(NULL, 0);
5369 if (cwd == NULL) {
5370 error = got_error_from_errno("getcwd");
5371 goto done;
5374 error = got_worktree_open(&worktree, cwd);
5375 if (error) {
5376 if (error->code == GOT_ERR_NOT_WORKTREE)
5377 error = wrap_not_worktree_error(error, "status", cwd);
5378 goto done;
5381 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5382 NULL);
5383 if (error != NULL)
5384 goto done;
5386 error = apply_unveil(got_repo_get_path(repo), 1,
5387 got_worktree_get_root_path(worktree));
5388 if (error)
5389 goto done;
5391 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5392 if (error)
5393 goto done;
5395 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5396 print_status, &st, check_cancelled, NULL);
5397 done:
5398 TAILQ_FOREACH(pe, &paths, entry)
5399 free((char *)pe->path);
5400 got_pathlist_free(&paths);
5401 free(cwd);
5402 return error;
5405 __dead static void
5406 usage_ref(void)
5408 fprintf(stderr,
5409 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5410 "[-d] [name]\n",
5411 getprogname());
5412 exit(1);
5415 static const struct got_error *
5416 list_refs(struct got_repository *repo, const char *refname)
5418 static const struct got_error *err = NULL;
5419 struct got_reflist_head refs;
5420 struct got_reflist_entry *re;
5422 TAILQ_INIT(&refs);
5423 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5424 if (err)
5425 return err;
5427 TAILQ_FOREACH(re, &refs, entry) {
5428 char *refstr;
5429 refstr = got_ref_to_str(re->ref);
5430 if (refstr == NULL)
5431 return got_error_from_errno("got_ref_to_str");
5432 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5433 free(refstr);
5436 got_ref_list_free(&refs);
5437 return NULL;
5440 static const struct got_error *
5441 delete_ref_by_name(struct got_repository *repo, const char *refname)
5443 const struct got_error *err;
5444 struct got_reference *ref;
5446 err = got_ref_open(&ref, repo, refname, 0);
5447 if (err)
5448 return err;
5450 err = delete_ref(repo, ref);
5451 got_ref_close(ref);
5452 return err;
5455 static const struct got_error *
5456 add_ref(struct got_repository *repo, const char *refname, const char *target)
5458 const struct got_error *err = NULL;
5459 struct got_object_id *id;
5460 struct got_reference *ref = NULL;
5463 * Don't let the user create a reference name with a leading '-'.
5464 * While technically a valid reference name, this case is usually
5465 * an unintended typo.
5467 if (refname[0] == '-')
5468 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5470 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5471 repo);
5472 if (err) {
5473 struct got_reference *target_ref;
5475 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5476 return err;
5477 err = got_ref_open(&target_ref, repo, target, 0);
5478 if (err)
5479 return err;
5480 err = got_ref_resolve(&id, repo, target_ref);
5481 got_ref_close(target_ref);
5482 if (err)
5483 return err;
5486 err = got_ref_alloc(&ref, refname, id);
5487 if (err)
5488 goto done;
5490 err = got_ref_write(ref, repo);
5491 done:
5492 if (ref)
5493 got_ref_close(ref);
5494 free(id);
5495 return err;
5498 static const struct got_error *
5499 add_symref(struct got_repository *repo, const char *refname, const char *target)
5501 const struct got_error *err = NULL;
5502 struct got_reference *ref = NULL;
5503 struct got_reference *target_ref = NULL;
5506 * Don't let the user create a reference name with a leading '-'.
5507 * While technically a valid reference name, this case is usually
5508 * an unintended typo.
5510 if (refname[0] == '-')
5511 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5513 err = got_ref_open(&target_ref, repo, target, 0);
5514 if (err)
5515 return err;
5517 err = got_ref_alloc_symref(&ref, refname, target_ref);
5518 if (err)
5519 goto done;
5521 err = got_ref_write(ref, repo);
5522 done:
5523 if (target_ref)
5524 got_ref_close(target_ref);
5525 if (ref)
5526 got_ref_close(ref);
5527 return err;
5530 static const struct got_error *
5531 cmd_ref(int argc, char *argv[])
5533 const struct got_error *error = NULL;
5534 struct got_repository *repo = NULL;
5535 struct got_worktree *worktree = NULL;
5536 char *cwd = NULL, *repo_path = NULL;
5537 int ch, do_list = 0, do_delete = 0;
5538 const char *obj_arg = NULL, *symref_target= NULL;
5539 char *refname = NULL;
5541 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5542 switch (ch) {
5543 case 'c':
5544 obj_arg = optarg;
5545 break;
5546 case 'd':
5547 do_delete = 1;
5548 break;
5549 case 'r':
5550 repo_path = realpath(optarg, NULL);
5551 if (repo_path == NULL)
5552 return got_error_from_errno2("realpath",
5553 optarg);
5554 got_path_strip_trailing_slashes(repo_path);
5555 break;
5556 case 'l':
5557 do_list = 1;
5558 break;
5559 case 's':
5560 symref_target = optarg;
5561 break;
5562 default:
5563 usage_ref();
5564 /* NOTREACHED */
5568 if (obj_arg && do_list)
5569 option_conflict('c', 'l');
5570 if (obj_arg && do_delete)
5571 option_conflict('c', 'd');
5572 if (obj_arg && symref_target)
5573 option_conflict('c', 's');
5574 if (symref_target && do_delete)
5575 option_conflict('s', 'd');
5576 if (symref_target && do_list)
5577 option_conflict('s', 'l');
5578 if (do_delete && do_list)
5579 option_conflict('d', 'l');
5581 argc -= optind;
5582 argv += optind;
5584 if (do_list) {
5585 if (argc != 0 && argc != 1)
5586 usage_ref();
5587 if (argc == 1) {
5588 refname = strdup(argv[0]);
5589 if (refname == NULL) {
5590 error = got_error_from_errno("strdup");
5591 goto done;
5594 } else {
5595 if (argc != 1)
5596 usage_ref();
5597 refname = strdup(argv[0]);
5598 if (refname == NULL) {
5599 error = got_error_from_errno("strdup");
5600 goto done;
5604 if (refname)
5605 got_path_strip_trailing_slashes(refname);
5607 #ifndef PROFILE
5608 if (do_list) {
5609 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5610 NULL) == -1)
5611 err(1, "pledge");
5612 } else {
5613 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5614 "sendfd unveil", NULL) == -1)
5615 err(1, "pledge");
5617 #endif
5618 cwd = getcwd(NULL, 0);
5619 if (cwd == NULL) {
5620 error = got_error_from_errno("getcwd");
5621 goto done;
5624 if (repo_path == NULL) {
5625 error = got_worktree_open(&worktree, cwd);
5626 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5627 goto done;
5628 else
5629 error = NULL;
5630 if (worktree) {
5631 repo_path =
5632 strdup(got_worktree_get_repo_path(worktree));
5633 if (repo_path == NULL)
5634 error = got_error_from_errno("strdup");
5635 if (error)
5636 goto done;
5637 } else {
5638 repo_path = strdup(cwd);
5639 if (repo_path == NULL) {
5640 error = got_error_from_errno("strdup");
5641 goto done;
5646 error = got_repo_open(&repo, repo_path, NULL);
5647 if (error != NULL)
5648 goto done;
5650 error = apply_unveil(got_repo_get_path(repo), do_list,
5651 worktree ? got_worktree_get_root_path(worktree) : NULL);
5652 if (error)
5653 goto done;
5655 if (do_list)
5656 error = list_refs(repo, refname);
5657 else if (do_delete)
5658 error = delete_ref_by_name(repo, refname);
5659 else if (symref_target)
5660 error = add_symref(repo, refname, symref_target);
5661 else {
5662 if (obj_arg == NULL)
5663 usage_ref();
5664 error = add_ref(repo, refname, obj_arg);
5666 done:
5667 free(refname);
5668 if (repo) {
5669 const struct got_error *close_err = got_repo_close(repo);
5670 if (error == NULL)
5671 error = close_err;
5673 if (worktree)
5674 got_worktree_close(worktree);
5675 free(cwd);
5676 free(repo_path);
5677 return error;
5680 __dead static void
5681 usage_branch(void)
5683 fprintf(stderr,
5684 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5685 "[name]\n", getprogname());
5686 exit(1);
5689 static const struct got_error *
5690 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5691 struct got_reference *ref)
5693 const struct got_error *err = NULL;
5694 const char *refname, *marker = " ";
5695 char *refstr;
5697 refname = got_ref_get_name(ref);
5698 if (worktree && strcmp(refname,
5699 got_worktree_get_head_ref_name(worktree)) == 0) {
5700 struct got_object_id *id = NULL;
5702 err = got_ref_resolve(&id, repo, ref);
5703 if (err)
5704 return err;
5705 if (got_object_id_cmp(id,
5706 got_worktree_get_base_commit_id(worktree)) == 0)
5707 marker = "* ";
5708 else
5709 marker = "~ ";
5710 free(id);
5713 if (strncmp(refname, "refs/heads/", 11) == 0)
5714 refname += 11;
5715 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5716 refname += 18;
5717 if (strncmp(refname, "refs/remotes/", 13) == 0)
5718 refname += 13;
5720 refstr = got_ref_to_str(ref);
5721 if (refstr == NULL)
5722 return got_error_from_errno("got_ref_to_str");
5724 printf("%s%s: %s\n", marker, refname, refstr);
5725 free(refstr);
5726 return NULL;
5729 static const struct got_error *
5730 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5732 const char *refname;
5734 if (worktree == NULL)
5735 return got_error(GOT_ERR_NOT_WORKTREE);
5737 refname = got_worktree_get_head_ref_name(worktree);
5739 if (strncmp(refname, "refs/heads/", 11) == 0)
5740 refname += 11;
5741 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5742 refname += 18;
5744 printf("%s\n", refname);
5746 return NULL;
5749 static const struct got_error *
5750 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5752 static const struct got_error *err = NULL;
5753 struct got_reflist_head refs;
5754 struct got_reflist_entry *re;
5755 struct got_reference *temp_ref = NULL;
5756 int rebase_in_progress, histedit_in_progress;
5758 TAILQ_INIT(&refs);
5760 if (worktree) {
5761 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5762 worktree);
5763 if (err)
5764 return err;
5766 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5767 worktree);
5768 if (err)
5769 return err;
5771 if (rebase_in_progress || histedit_in_progress) {
5772 err = got_ref_open(&temp_ref, repo,
5773 got_worktree_get_head_ref_name(worktree), 0);
5774 if (err)
5775 return err;
5776 list_branch(repo, worktree, temp_ref);
5777 got_ref_close(temp_ref);
5781 err = got_ref_list(&refs, repo, "refs/heads",
5782 got_ref_cmp_by_name, NULL);
5783 if (err)
5784 return err;
5786 TAILQ_FOREACH(re, &refs, entry)
5787 list_branch(repo, worktree, re->ref);
5789 got_ref_list_free(&refs);
5791 err = got_ref_list(&refs, repo, "refs/remotes",
5792 got_ref_cmp_by_name, NULL);
5793 if (err)
5794 return err;
5796 TAILQ_FOREACH(re, &refs, entry)
5797 list_branch(repo, worktree, re->ref);
5799 got_ref_list_free(&refs);
5801 return NULL;
5804 static const struct got_error *
5805 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5806 const char *branch_name)
5808 const struct got_error *err = NULL;
5809 struct got_reference *ref = NULL;
5810 char *refname, *remote_refname = NULL;
5812 if (strncmp(branch_name, "refs/", 5) == 0)
5813 branch_name += 5;
5814 if (strncmp(branch_name, "heads/", 6) == 0)
5815 branch_name += 6;
5816 else if (strncmp(branch_name, "remotes/", 8) == 0)
5817 branch_name += 8;
5819 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5820 return got_error_from_errno("asprintf");
5822 if (asprintf(&remote_refname, "refs/remotes/%s",
5823 branch_name) == -1) {
5824 err = got_error_from_errno("asprintf");
5825 goto done;
5828 err = got_ref_open(&ref, repo, refname, 0);
5829 if (err) {
5830 const struct got_error *err2;
5831 if (err->code != GOT_ERR_NOT_REF)
5832 goto done;
5834 * Keep 'err' intact such that if neither branch exists
5835 * we report "refs/heads" rather than "refs/remotes" in
5836 * our error message.
5838 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5839 if (err2)
5840 goto done;
5841 err = NULL;
5844 if (worktree &&
5845 strcmp(got_worktree_get_head_ref_name(worktree),
5846 got_ref_get_name(ref)) == 0) {
5847 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5848 "will not delete this work tree's current branch");
5849 goto done;
5852 err = delete_ref(repo, ref);
5853 done:
5854 if (ref)
5855 got_ref_close(ref);
5856 free(refname);
5857 free(remote_refname);
5858 return err;
5861 static const struct got_error *
5862 add_branch(struct got_repository *repo, const char *branch_name,
5863 struct got_object_id *base_commit_id)
5865 const struct got_error *err = NULL;
5866 struct got_reference *ref = NULL;
5867 char *base_refname = NULL, *refname = NULL;
5870 * Don't let the user create a branch name with a leading '-'.
5871 * While technically a valid reference name, this case is usually
5872 * an unintended typo.
5874 if (branch_name[0] == '-')
5875 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5877 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5878 branch_name += 11;
5880 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5881 err = got_error_from_errno("asprintf");
5882 goto done;
5885 err = got_ref_open(&ref, repo, refname, 0);
5886 if (err == NULL) {
5887 err = got_error(GOT_ERR_BRANCH_EXISTS);
5888 goto done;
5889 } else if (err->code != GOT_ERR_NOT_REF)
5890 goto done;
5892 err = got_ref_alloc(&ref, refname, base_commit_id);
5893 if (err)
5894 goto done;
5896 err = got_ref_write(ref, repo);
5897 done:
5898 if (ref)
5899 got_ref_close(ref);
5900 free(base_refname);
5901 free(refname);
5902 return err;
5905 static const struct got_error *
5906 cmd_branch(int argc, char *argv[])
5908 const struct got_error *error = NULL;
5909 struct got_repository *repo = NULL;
5910 struct got_worktree *worktree = NULL;
5911 char *cwd = NULL, *repo_path = NULL;
5912 int ch, do_list = 0, do_show = 0, do_update = 1;
5913 const char *delref = NULL, *commit_id_arg = NULL;
5914 struct got_reference *ref = NULL;
5915 struct got_pathlist_head paths;
5916 struct got_pathlist_entry *pe;
5917 struct got_object_id *commit_id = NULL;
5918 char *commit_id_str = NULL;
5920 TAILQ_INIT(&paths);
5922 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5923 switch (ch) {
5924 case 'c':
5925 commit_id_arg = optarg;
5926 break;
5927 case 'd':
5928 delref = optarg;
5929 break;
5930 case 'r':
5931 repo_path = realpath(optarg, NULL);
5932 if (repo_path == NULL)
5933 return got_error_from_errno2("realpath",
5934 optarg);
5935 got_path_strip_trailing_slashes(repo_path);
5936 break;
5937 case 'l':
5938 do_list = 1;
5939 break;
5940 case 'n':
5941 do_update = 0;
5942 break;
5943 default:
5944 usage_branch();
5945 /* NOTREACHED */
5949 if (do_list && delref)
5950 option_conflict('l', 'd');
5952 argc -= optind;
5953 argv += optind;
5955 if (!do_list && !delref && argc == 0)
5956 do_show = 1;
5958 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5959 errx(1, "-c option can only be used when creating a branch");
5961 if (do_list || delref) {
5962 if (argc > 0)
5963 usage_branch();
5964 } else if (!do_show && argc != 1)
5965 usage_branch();
5967 #ifndef PROFILE
5968 if (do_list || do_show) {
5969 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5970 NULL) == -1)
5971 err(1, "pledge");
5972 } else {
5973 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5974 "sendfd unveil", NULL) == -1)
5975 err(1, "pledge");
5977 #endif
5978 cwd = getcwd(NULL, 0);
5979 if (cwd == NULL) {
5980 error = got_error_from_errno("getcwd");
5981 goto done;
5984 if (repo_path == NULL) {
5985 error = got_worktree_open(&worktree, cwd);
5986 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5987 goto done;
5988 else
5989 error = NULL;
5990 if (worktree) {
5991 repo_path =
5992 strdup(got_worktree_get_repo_path(worktree));
5993 if (repo_path == NULL)
5994 error = got_error_from_errno("strdup");
5995 if (error)
5996 goto done;
5997 } else {
5998 repo_path = strdup(cwd);
5999 if (repo_path == NULL) {
6000 error = got_error_from_errno("strdup");
6001 goto done;
6006 error = got_repo_open(&repo, repo_path, NULL);
6007 if (error != NULL)
6008 goto done;
6010 error = apply_unveil(got_repo_get_path(repo), do_list,
6011 worktree ? got_worktree_get_root_path(worktree) : NULL);
6012 if (error)
6013 goto done;
6015 if (do_show)
6016 error = show_current_branch(repo, worktree);
6017 else if (do_list)
6018 error = list_branches(repo, worktree);
6019 else if (delref)
6020 error = delete_branch(repo, worktree, delref);
6021 else {
6022 struct got_reflist_head refs;
6023 TAILQ_INIT(&refs);
6024 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6025 NULL);
6026 if (error)
6027 goto done;
6028 if (commit_id_arg == NULL)
6029 commit_id_arg = worktree ?
6030 got_worktree_get_head_ref_name(worktree) :
6031 GOT_REF_HEAD;
6032 error = got_repo_match_object_id(&commit_id, NULL,
6033 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6034 got_ref_list_free(&refs);
6035 if (error)
6036 goto done;
6037 error = add_branch(repo, argv[0], commit_id);
6038 if (error)
6039 goto done;
6040 if (worktree && do_update) {
6041 struct got_update_progress_arg upa;
6042 char *branch_refname = NULL;
6044 error = got_object_id_str(&commit_id_str, commit_id);
6045 if (error)
6046 goto done;
6047 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6048 worktree);
6049 if (error)
6050 goto done;
6051 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6052 == -1) {
6053 error = got_error_from_errno("asprintf");
6054 goto done;
6056 error = got_ref_open(&ref, repo, branch_refname, 0);
6057 free(branch_refname);
6058 if (error)
6059 goto done;
6060 error = switch_head_ref(ref, commit_id, worktree,
6061 repo);
6062 if (error)
6063 goto done;
6064 error = got_worktree_set_base_commit_id(worktree, repo,
6065 commit_id);
6066 if (error)
6067 goto done;
6068 memset(&upa, 0, sizeof(upa));
6069 error = got_worktree_checkout_files(worktree, &paths,
6070 repo, update_progress, &upa, check_cancelled,
6071 NULL);
6072 if (error)
6073 goto done;
6074 if (upa.did_something) {
6075 printf("Updated to %s: %s\n",
6076 got_worktree_get_head_ref_name(worktree),
6077 commit_id_str);
6079 print_update_progress_stats(&upa);
6082 done:
6083 if (ref)
6084 got_ref_close(ref);
6085 if (repo) {
6086 const struct got_error *close_err = got_repo_close(repo);
6087 if (error == NULL)
6088 error = close_err;
6090 if (worktree)
6091 got_worktree_close(worktree);
6092 free(cwd);
6093 free(repo_path);
6094 free(commit_id);
6095 free(commit_id_str);
6096 TAILQ_FOREACH(pe, &paths, entry)
6097 free((char *)pe->path);
6098 got_pathlist_free(&paths);
6099 return error;
6103 __dead static void
6104 usage_tag(void)
6106 fprintf(stderr,
6107 "usage: %s tag [-c commit] [-r repository] [-l] "
6108 "[-m message] name\n", getprogname());
6109 exit(1);
6112 #if 0
6113 static const struct got_error *
6114 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6116 const struct got_error *err = NULL;
6117 struct got_reflist_entry *re, *se, *new;
6118 struct got_object_id *re_id, *se_id;
6119 struct got_tag_object *re_tag, *se_tag;
6120 time_t re_time, se_time;
6122 STAILQ_FOREACH(re, tags, entry) {
6123 se = STAILQ_FIRST(sorted);
6124 if (se == NULL) {
6125 err = got_reflist_entry_dup(&new, re);
6126 if (err)
6127 return err;
6128 STAILQ_INSERT_HEAD(sorted, new, entry);
6129 continue;
6130 } else {
6131 err = got_ref_resolve(&re_id, repo, re->ref);
6132 if (err)
6133 break;
6134 err = got_object_open_as_tag(&re_tag, repo, re_id);
6135 free(re_id);
6136 if (err)
6137 break;
6138 re_time = got_object_tag_get_tagger_time(re_tag);
6139 got_object_tag_close(re_tag);
6142 while (se) {
6143 err = got_ref_resolve(&se_id, repo, re->ref);
6144 if (err)
6145 break;
6146 err = got_object_open_as_tag(&se_tag, repo, se_id);
6147 free(se_id);
6148 if (err)
6149 break;
6150 se_time = got_object_tag_get_tagger_time(se_tag);
6151 got_object_tag_close(se_tag);
6153 if (se_time > re_time) {
6154 err = got_reflist_entry_dup(&new, re);
6155 if (err)
6156 return err;
6157 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6158 break;
6160 se = STAILQ_NEXT(se, entry);
6161 continue;
6164 done:
6165 return err;
6167 #endif
6169 static const struct got_error *
6170 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6172 static const struct got_error *err = NULL;
6173 struct got_reflist_head refs;
6174 struct got_reflist_entry *re;
6176 TAILQ_INIT(&refs);
6178 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6179 if (err)
6180 return err;
6182 TAILQ_FOREACH(re, &refs, entry) {
6183 const char *refname;
6184 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6185 char datebuf[26];
6186 const char *tagger;
6187 time_t tagger_time;
6188 struct got_object_id *id;
6189 struct got_tag_object *tag;
6190 struct got_commit_object *commit = NULL;
6192 refname = got_ref_get_name(re->ref);
6193 if (strncmp(refname, "refs/tags/", 10) != 0)
6194 continue;
6195 refname += 10;
6196 refstr = got_ref_to_str(re->ref);
6197 if (refstr == NULL) {
6198 err = got_error_from_errno("got_ref_to_str");
6199 break;
6201 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6202 free(refstr);
6204 err = got_ref_resolve(&id, repo, re->ref);
6205 if (err)
6206 break;
6207 err = got_object_open_as_tag(&tag, repo, id);
6208 if (err) {
6209 if (err->code != GOT_ERR_OBJ_TYPE) {
6210 free(id);
6211 break;
6213 /* "lightweight" tag */
6214 err = got_object_open_as_commit(&commit, repo, id);
6215 if (err) {
6216 free(id);
6217 break;
6219 tagger = got_object_commit_get_committer(commit);
6220 tagger_time =
6221 got_object_commit_get_committer_time(commit);
6222 err = got_object_id_str(&id_str, id);
6223 free(id);
6224 if (err)
6225 break;
6226 } else {
6227 free(id);
6228 tagger = got_object_tag_get_tagger(tag);
6229 tagger_time = got_object_tag_get_tagger_time(tag);
6230 err = got_object_id_str(&id_str,
6231 got_object_tag_get_object_id(tag));
6232 if (err)
6233 break;
6235 printf("from: %s\n", tagger);
6236 datestr = get_datestr(&tagger_time, datebuf);
6237 if (datestr)
6238 printf("date: %s UTC\n", datestr);
6239 if (commit)
6240 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6241 else {
6242 switch (got_object_tag_get_object_type(tag)) {
6243 case GOT_OBJ_TYPE_BLOB:
6244 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6245 id_str);
6246 break;
6247 case GOT_OBJ_TYPE_TREE:
6248 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6249 id_str);
6250 break;
6251 case GOT_OBJ_TYPE_COMMIT:
6252 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6253 id_str);
6254 break;
6255 case GOT_OBJ_TYPE_TAG:
6256 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6257 id_str);
6258 break;
6259 default:
6260 break;
6263 free(id_str);
6264 if (commit) {
6265 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6266 if (err)
6267 break;
6268 got_object_commit_close(commit);
6269 } else {
6270 tagmsg0 = strdup(got_object_tag_get_message(tag));
6271 got_object_tag_close(tag);
6272 if (tagmsg0 == NULL) {
6273 err = got_error_from_errno("strdup");
6274 break;
6278 tagmsg = tagmsg0;
6279 do {
6280 line = strsep(&tagmsg, "\n");
6281 if (line)
6282 printf(" %s\n", line);
6283 } while (line);
6284 free(tagmsg0);
6287 got_ref_list_free(&refs);
6288 return NULL;
6291 static const struct got_error *
6292 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6293 const char *tag_name, const char *repo_path)
6295 const struct got_error *err = NULL;
6296 char *template = NULL, *initial_content = NULL;
6297 char *editor = NULL;
6298 int initial_content_len;
6299 int fd = -1;
6301 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6302 err = got_error_from_errno("asprintf");
6303 goto done;
6306 initial_content_len = asprintf(&initial_content,
6307 "\n# tagging commit %s as %s\n",
6308 commit_id_str, tag_name);
6309 if (initial_content_len == -1) {
6310 err = got_error_from_errno("asprintf");
6311 goto done;
6314 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6315 if (err)
6316 goto done;
6318 if (write(fd, initial_content, initial_content_len) == -1) {
6319 err = got_error_from_errno2("write", *tagmsg_path);
6320 goto done;
6323 err = get_editor(&editor);
6324 if (err)
6325 goto done;
6326 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6327 initial_content_len, 1);
6328 done:
6329 free(initial_content);
6330 free(template);
6331 free(editor);
6333 if (fd != -1 && close(fd) == -1 && err == NULL)
6334 err = got_error_from_errno2("close", *tagmsg_path);
6336 /* Editor is done; we can now apply unveil(2) */
6337 if (err == NULL)
6338 err = apply_unveil(repo_path, 0, NULL);
6339 if (err) {
6340 free(*tagmsg);
6341 *tagmsg = NULL;
6343 return err;
6346 static const struct got_error *
6347 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6348 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6350 const struct got_error *err = NULL;
6351 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6352 char *label = NULL, *commit_id_str = NULL;
6353 struct got_reference *ref = NULL;
6354 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6355 char *tagmsg_path = NULL, *tag_id_str = NULL;
6356 int preserve_tagmsg = 0;
6357 struct got_reflist_head refs;
6359 TAILQ_INIT(&refs);
6362 * Don't let the user create a tag name with a leading '-'.
6363 * While technically a valid reference name, this case is usually
6364 * an unintended typo.
6366 if (tag_name[0] == '-')
6367 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6369 err = get_author(&tagger, repo, worktree);
6370 if (err)
6371 return err;
6373 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6374 if (err)
6375 goto done;
6377 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6378 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6379 if (err)
6380 goto done;
6382 err = got_object_id_str(&commit_id_str, commit_id);
6383 if (err)
6384 goto done;
6386 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6387 refname = strdup(tag_name);
6388 if (refname == NULL) {
6389 err = got_error_from_errno("strdup");
6390 goto done;
6392 tag_name += 10;
6393 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6394 err = got_error_from_errno("asprintf");
6395 goto done;
6398 err = got_ref_open(&ref, repo, refname, 0);
6399 if (err == NULL) {
6400 err = got_error(GOT_ERR_TAG_EXISTS);
6401 goto done;
6402 } else if (err->code != GOT_ERR_NOT_REF)
6403 goto done;
6405 if (tagmsg_arg == NULL) {
6406 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6407 tag_name, got_repo_get_path(repo));
6408 if (err) {
6409 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6410 tagmsg_path != NULL)
6411 preserve_tagmsg = 1;
6412 goto done;
6416 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6417 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6418 if (err) {
6419 if (tagmsg_path)
6420 preserve_tagmsg = 1;
6421 goto done;
6424 err = got_ref_alloc(&ref, refname, tag_id);
6425 if (err) {
6426 if (tagmsg_path)
6427 preserve_tagmsg = 1;
6428 goto done;
6431 err = got_ref_write(ref, repo);
6432 if (err) {
6433 if (tagmsg_path)
6434 preserve_tagmsg = 1;
6435 goto done;
6438 err = got_object_id_str(&tag_id_str, tag_id);
6439 if (err) {
6440 if (tagmsg_path)
6441 preserve_tagmsg = 1;
6442 goto done;
6444 printf("Created tag %s\n", tag_id_str);
6445 done:
6446 if (preserve_tagmsg) {
6447 fprintf(stderr, "%s: tag message preserved in %s\n",
6448 getprogname(), tagmsg_path);
6449 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6450 err = got_error_from_errno2("unlink", tagmsg_path);
6451 free(tag_id_str);
6452 if (ref)
6453 got_ref_close(ref);
6454 free(commit_id);
6455 free(commit_id_str);
6456 free(refname);
6457 free(tagmsg);
6458 free(tagmsg_path);
6459 free(tagger);
6460 got_ref_list_free(&refs);
6461 return err;
6464 static const struct got_error *
6465 cmd_tag(int argc, char *argv[])
6467 const struct got_error *error = NULL;
6468 struct got_repository *repo = NULL;
6469 struct got_worktree *worktree = NULL;
6470 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6471 char *gitconfig_path = NULL;
6472 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6473 int ch, do_list = 0;
6475 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6476 switch (ch) {
6477 case 'c':
6478 commit_id_arg = optarg;
6479 break;
6480 case 'm':
6481 tagmsg = optarg;
6482 break;
6483 case 'r':
6484 repo_path = realpath(optarg, NULL);
6485 if (repo_path == NULL)
6486 return got_error_from_errno2("realpath",
6487 optarg);
6488 got_path_strip_trailing_slashes(repo_path);
6489 break;
6490 case 'l':
6491 do_list = 1;
6492 break;
6493 default:
6494 usage_tag();
6495 /* NOTREACHED */
6499 argc -= optind;
6500 argv += optind;
6502 if (do_list) {
6503 if (commit_id_arg != NULL)
6504 errx(1,
6505 "-c option can only be used when creating a tag");
6506 if (tagmsg)
6507 option_conflict('l', 'm');
6508 if (argc > 0)
6509 usage_tag();
6510 } else if (argc != 1)
6511 usage_tag();
6513 tag_name = argv[0];
6515 #ifndef PROFILE
6516 if (do_list) {
6517 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6518 NULL) == -1)
6519 err(1, "pledge");
6520 } else {
6521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6522 "sendfd unveil", NULL) == -1)
6523 err(1, "pledge");
6525 #endif
6526 cwd = getcwd(NULL, 0);
6527 if (cwd == NULL) {
6528 error = got_error_from_errno("getcwd");
6529 goto done;
6532 if (repo_path == NULL) {
6533 error = got_worktree_open(&worktree, cwd);
6534 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6535 goto done;
6536 else
6537 error = NULL;
6538 if (worktree) {
6539 repo_path =
6540 strdup(got_worktree_get_repo_path(worktree));
6541 if (repo_path == NULL)
6542 error = got_error_from_errno("strdup");
6543 if (error)
6544 goto done;
6545 } else {
6546 repo_path = strdup(cwd);
6547 if (repo_path == NULL) {
6548 error = got_error_from_errno("strdup");
6549 goto done;
6554 if (do_list) {
6555 error = got_repo_open(&repo, repo_path, NULL);
6556 if (error != NULL)
6557 goto done;
6558 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6559 if (error)
6560 goto done;
6561 error = list_tags(repo, worktree);
6562 } else {
6563 error = get_gitconfig_path(&gitconfig_path);
6564 if (error)
6565 goto done;
6566 error = got_repo_open(&repo, repo_path, gitconfig_path);
6567 if (error != NULL)
6568 goto done;
6570 if (tagmsg) {
6571 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6572 if (error)
6573 goto done;
6576 if (commit_id_arg == NULL) {
6577 struct got_reference *head_ref;
6578 struct got_object_id *commit_id;
6579 error = got_ref_open(&head_ref, repo,
6580 worktree ? got_worktree_get_head_ref_name(worktree)
6581 : GOT_REF_HEAD, 0);
6582 if (error)
6583 goto done;
6584 error = got_ref_resolve(&commit_id, repo, head_ref);
6585 got_ref_close(head_ref);
6586 if (error)
6587 goto done;
6588 error = got_object_id_str(&commit_id_str, commit_id);
6589 free(commit_id);
6590 if (error)
6591 goto done;
6594 error = add_tag(repo, worktree, tag_name,
6595 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6597 done:
6598 if (repo) {
6599 const struct got_error *close_err = got_repo_close(repo);
6600 if (error == NULL)
6601 error = close_err;
6603 if (worktree)
6604 got_worktree_close(worktree);
6605 free(cwd);
6606 free(repo_path);
6607 free(gitconfig_path);
6608 free(commit_id_str);
6609 return error;
6612 __dead static void
6613 usage_add(void)
6615 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6616 getprogname());
6617 exit(1);
6620 static const struct got_error *
6621 add_progress(void *arg, unsigned char status, const char *path)
6623 while (path[0] == '/')
6624 path++;
6625 printf("%c %s\n", status, path);
6626 return NULL;
6629 static const struct got_error *
6630 cmd_add(int argc, char *argv[])
6632 const struct got_error *error = NULL;
6633 struct got_repository *repo = NULL;
6634 struct got_worktree *worktree = NULL;
6635 char *cwd = NULL;
6636 struct got_pathlist_head paths;
6637 struct got_pathlist_entry *pe;
6638 int ch, can_recurse = 0, no_ignores = 0;
6640 TAILQ_INIT(&paths);
6642 while ((ch = getopt(argc, argv, "IR")) != -1) {
6643 switch (ch) {
6644 case 'I':
6645 no_ignores = 1;
6646 break;
6647 case 'R':
6648 can_recurse = 1;
6649 break;
6650 default:
6651 usage_add();
6652 /* NOTREACHED */
6656 argc -= optind;
6657 argv += optind;
6659 #ifndef PROFILE
6660 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6661 NULL) == -1)
6662 err(1, "pledge");
6663 #endif
6664 if (argc < 1)
6665 usage_add();
6667 cwd = getcwd(NULL, 0);
6668 if (cwd == NULL) {
6669 error = got_error_from_errno("getcwd");
6670 goto done;
6673 error = got_worktree_open(&worktree, cwd);
6674 if (error) {
6675 if (error->code == GOT_ERR_NOT_WORKTREE)
6676 error = wrap_not_worktree_error(error, "add", cwd);
6677 goto done;
6680 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6681 NULL);
6682 if (error != NULL)
6683 goto done;
6685 error = apply_unveil(got_repo_get_path(repo), 1,
6686 got_worktree_get_root_path(worktree));
6687 if (error)
6688 goto done;
6690 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6691 if (error)
6692 goto done;
6694 if (!can_recurse) {
6695 char *ondisk_path;
6696 struct stat sb;
6697 TAILQ_FOREACH(pe, &paths, entry) {
6698 if (asprintf(&ondisk_path, "%s/%s",
6699 got_worktree_get_root_path(worktree),
6700 pe->path) == -1) {
6701 error = got_error_from_errno("asprintf");
6702 goto done;
6704 if (lstat(ondisk_path, &sb) == -1) {
6705 if (errno == ENOENT) {
6706 free(ondisk_path);
6707 continue;
6709 error = got_error_from_errno2("lstat",
6710 ondisk_path);
6711 free(ondisk_path);
6712 goto done;
6714 free(ondisk_path);
6715 if (S_ISDIR(sb.st_mode)) {
6716 error = got_error_msg(GOT_ERR_BAD_PATH,
6717 "adding directories requires -R option");
6718 goto done;
6723 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6724 NULL, repo, no_ignores);
6725 done:
6726 if (repo) {
6727 const struct got_error *close_err = got_repo_close(repo);
6728 if (error == NULL)
6729 error = close_err;
6731 if (worktree)
6732 got_worktree_close(worktree);
6733 TAILQ_FOREACH(pe, &paths, entry)
6734 free((char *)pe->path);
6735 got_pathlist_free(&paths);
6736 free(cwd);
6737 return error;
6740 __dead static void
6741 usage_remove(void)
6743 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6744 "path ...\n", getprogname());
6745 exit(1);
6748 static const struct got_error *
6749 print_remove_status(void *arg, unsigned char status,
6750 unsigned char staged_status, const char *path)
6752 while (path[0] == '/')
6753 path++;
6754 if (status == GOT_STATUS_NONEXISTENT)
6755 return NULL;
6756 if (status == staged_status && (status == GOT_STATUS_DELETE))
6757 status = GOT_STATUS_NO_CHANGE;
6758 printf("%c%c %s\n", status, staged_status, path);
6759 return NULL;
6762 static const struct got_error *
6763 cmd_remove(int argc, char *argv[])
6765 const struct got_error *error = NULL;
6766 struct got_worktree *worktree = NULL;
6767 struct got_repository *repo = NULL;
6768 const char *status_codes = NULL;
6769 char *cwd = NULL;
6770 struct got_pathlist_head paths;
6771 struct got_pathlist_entry *pe;
6772 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6774 TAILQ_INIT(&paths);
6776 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6777 switch (ch) {
6778 case 'f':
6779 delete_local_mods = 1;
6780 break;
6781 case 'k':
6782 keep_on_disk = 1;
6783 break;
6784 case 'R':
6785 can_recurse = 1;
6786 break;
6787 case 's':
6788 for (i = 0; i < strlen(optarg); i++) {
6789 switch (optarg[i]) {
6790 case GOT_STATUS_MODIFY:
6791 delete_local_mods = 1;
6792 break;
6793 case GOT_STATUS_MISSING:
6794 break;
6795 default:
6796 errx(1, "invalid status code '%c'",
6797 optarg[i]);
6800 status_codes = optarg;
6801 break;
6802 default:
6803 usage_remove();
6804 /* NOTREACHED */
6808 argc -= optind;
6809 argv += optind;
6811 #ifndef PROFILE
6812 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6813 NULL) == -1)
6814 err(1, "pledge");
6815 #endif
6816 if (argc < 1)
6817 usage_remove();
6819 cwd = getcwd(NULL, 0);
6820 if (cwd == NULL) {
6821 error = got_error_from_errno("getcwd");
6822 goto done;
6824 error = got_worktree_open(&worktree, cwd);
6825 if (error) {
6826 if (error->code == GOT_ERR_NOT_WORKTREE)
6827 error = wrap_not_worktree_error(error, "remove", cwd);
6828 goto done;
6831 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6832 NULL);
6833 if (error)
6834 goto done;
6836 error = apply_unveil(got_repo_get_path(repo), 1,
6837 got_worktree_get_root_path(worktree));
6838 if (error)
6839 goto done;
6841 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6842 if (error)
6843 goto done;
6845 if (!can_recurse) {
6846 char *ondisk_path;
6847 struct stat sb;
6848 TAILQ_FOREACH(pe, &paths, entry) {
6849 if (asprintf(&ondisk_path, "%s/%s",
6850 got_worktree_get_root_path(worktree),
6851 pe->path) == -1) {
6852 error = got_error_from_errno("asprintf");
6853 goto done;
6855 if (lstat(ondisk_path, &sb) == -1) {
6856 if (errno == ENOENT) {
6857 free(ondisk_path);
6858 continue;
6860 error = got_error_from_errno2("lstat",
6861 ondisk_path);
6862 free(ondisk_path);
6863 goto done;
6865 free(ondisk_path);
6866 if (S_ISDIR(sb.st_mode)) {
6867 error = got_error_msg(GOT_ERR_BAD_PATH,
6868 "removing directories requires -R option");
6869 goto done;
6874 error = got_worktree_schedule_delete(worktree, &paths,
6875 delete_local_mods, status_codes, print_remove_status, NULL,
6876 repo, keep_on_disk);
6877 done:
6878 if (repo) {
6879 const struct got_error *close_err = got_repo_close(repo);
6880 if (error == NULL)
6881 error = close_err;
6883 if (worktree)
6884 got_worktree_close(worktree);
6885 TAILQ_FOREACH(pe, &paths, entry)
6886 free((char *)pe->path);
6887 got_pathlist_free(&paths);
6888 free(cwd);
6889 return error;
6892 __dead static void
6893 usage_revert(void)
6895 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6896 "path ...\n", getprogname());
6897 exit(1);
6900 static const struct got_error *
6901 revert_progress(void *arg, unsigned char status, const char *path)
6903 if (status == GOT_STATUS_UNVERSIONED)
6904 return NULL;
6906 while (path[0] == '/')
6907 path++;
6908 printf("%c %s\n", status, path);
6909 return NULL;
6912 struct choose_patch_arg {
6913 FILE *patch_script_file;
6914 const char *action;
6917 static const struct got_error *
6918 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6919 int nchanges, const char *action)
6921 char *line = NULL;
6922 size_t linesize = 0;
6923 ssize_t linelen;
6925 switch (status) {
6926 case GOT_STATUS_ADD:
6927 printf("A %s\n%s this addition? [y/n] ", path, action);
6928 break;
6929 case GOT_STATUS_DELETE:
6930 printf("D %s\n%s this deletion? [y/n] ", path, action);
6931 break;
6932 case GOT_STATUS_MODIFY:
6933 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6934 return got_error_from_errno("fseek");
6935 printf(GOT_COMMIT_SEP_STR);
6936 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6937 printf("%s", line);
6938 if (ferror(patch_file))
6939 return got_error_from_errno("getline");
6940 printf(GOT_COMMIT_SEP_STR);
6941 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6942 path, n, nchanges, action);
6943 break;
6944 default:
6945 return got_error_path(path, GOT_ERR_FILE_STATUS);
6948 return NULL;
6951 static const struct got_error *
6952 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6953 FILE *patch_file, int n, int nchanges)
6955 const struct got_error *err = NULL;
6956 char *line = NULL;
6957 size_t linesize = 0;
6958 ssize_t linelen;
6959 int resp = ' ';
6960 struct choose_patch_arg *a = arg;
6962 *choice = GOT_PATCH_CHOICE_NONE;
6964 if (a->patch_script_file) {
6965 char *nl;
6966 err = show_change(status, path, patch_file, n, nchanges,
6967 a->action);
6968 if (err)
6969 return err;
6970 linelen = getline(&line, &linesize, a->patch_script_file);
6971 if (linelen == -1) {
6972 if (ferror(a->patch_script_file))
6973 return got_error_from_errno("getline");
6974 return NULL;
6976 nl = strchr(line, '\n');
6977 if (nl)
6978 *nl = '\0';
6979 if (strcmp(line, "y") == 0) {
6980 *choice = GOT_PATCH_CHOICE_YES;
6981 printf("y\n");
6982 } else if (strcmp(line, "n") == 0) {
6983 *choice = GOT_PATCH_CHOICE_NO;
6984 printf("n\n");
6985 } else if (strcmp(line, "q") == 0 &&
6986 status == GOT_STATUS_MODIFY) {
6987 *choice = GOT_PATCH_CHOICE_QUIT;
6988 printf("q\n");
6989 } else
6990 printf("invalid response '%s'\n", line);
6991 free(line);
6992 return NULL;
6995 while (resp != 'y' && resp != 'n' && resp != 'q') {
6996 err = show_change(status, path, patch_file, n, nchanges,
6997 a->action);
6998 if (err)
6999 return err;
7000 resp = getchar();
7001 if (resp == '\n')
7002 resp = getchar();
7003 if (status == GOT_STATUS_MODIFY) {
7004 if (resp != 'y' && resp != 'n' && resp != 'q') {
7005 printf("invalid response '%c'\n", resp);
7006 resp = ' ';
7008 } else if (resp != 'y' && resp != 'n') {
7009 printf("invalid response '%c'\n", resp);
7010 resp = ' ';
7014 if (resp == 'y')
7015 *choice = GOT_PATCH_CHOICE_YES;
7016 else if (resp == 'n')
7017 *choice = GOT_PATCH_CHOICE_NO;
7018 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7019 *choice = GOT_PATCH_CHOICE_QUIT;
7021 return NULL;
7025 static const struct got_error *
7026 cmd_revert(int argc, char *argv[])
7028 const struct got_error *error = NULL;
7029 struct got_worktree *worktree = NULL;
7030 struct got_repository *repo = NULL;
7031 char *cwd = NULL, *path = NULL;
7032 struct got_pathlist_head paths;
7033 struct got_pathlist_entry *pe;
7034 int ch, can_recurse = 0, pflag = 0;
7035 FILE *patch_script_file = NULL;
7036 const char *patch_script_path = NULL;
7037 struct choose_patch_arg cpa;
7039 TAILQ_INIT(&paths);
7041 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7042 switch (ch) {
7043 case 'p':
7044 pflag = 1;
7045 break;
7046 case 'F':
7047 patch_script_path = optarg;
7048 break;
7049 case 'R':
7050 can_recurse = 1;
7051 break;
7052 default:
7053 usage_revert();
7054 /* NOTREACHED */
7058 argc -= optind;
7059 argv += optind;
7061 #ifndef PROFILE
7062 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7063 "unveil", NULL) == -1)
7064 err(1, "pledge");
7065 #endif
7066 if (argc < 1)
7067 usage_revert();
7068 if (patch_script_path && !pflag)
7069 errx(1, "-F option can only be used together with -p option");
7071 cwd = getcwd(NULL, 0);
7072 if (cwd == NULL) {
7073 error = got_error_from_errno("getcwd");
7074 goto done;
7076 error = got_worktree_open(&worktree, cwd);
7077 if (error) {
7078 if (error->code == GOT_ERR_NOT_WORKTREE)
7079 error = wrap_not_worktree_error(error, "revert", cwd);
7080 goto done;
7083 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7084 NULL);
7085 if (error != NULL)
7086 goto done;
7088 if (patch_script_path) {
7089 patch_script_file = fopen(patch_script_path, "r");
7090 if (patch_script_file == NULL) {
7091 error = got_error_from_errno2("fopen",
7092 patch_script_path);
7093 goto done;
7096 error = apply_unveil(got_repo_get_path(repo), 1,
7097 got_worktree_get_root_path(worktree));
7098 if (error)
7099 goto done;
7101 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7102 if (error)
7103 goto done;
7105 if (!can_recurse) {
7106 char *ondisk_path;
7107 struct stat sb;
7108 TAILQ_FOREACH(pe, &paths, entry) {
7109 if (asprintf(&ondisk_path, "%s/%s",
7110 got_worktree_get_root_path(worktree),
7111 pe->path) == -1) {
7112 error = got_error_from_errno("asprintf");
7113 goto done;
7115 if (lstat(ondisk_path, &sb) == -1) {
7116 if (errno == ENOENT) {
7117 free(ondisk_path);
7118 continue;
7120 error = got_error_from_errno2("lstat",
7121 ondisk_path);
7122 free(ondisk_path);
7123 goto done;
7125 free(ondisk_path);
7126 if (S_ISDIR(sb.st_mode)) {
7127 error = got_error_msg(GOT_ERR_BAD_PATH,
7128 "reverting directories requires -R option");
7129 goto done;
7134 cpa.patch_script_file = patch_script_file;
7135 cpa.action = "revert";
7136 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7137 pflag ? choose_patch : NULL, &cpa, repo);
7138 done:
7139 if (patch_script_file && fclose(patch_script_file) == EOF &&
7140 error == NULL)
7141 error = got_error_from_errno2("fclose", patch_script_path);
7142 if (repo) {
7143 const struct got_error *close_err = got_repo_close(repo);
7144 if (error == NULL)
7145 error = close_err;
7147 if (worktree)
7148 got_worktree_close(worktree);
7149 free(path);
7150 free(cwd);
7151 return error;
7154 __dead static void
7155 usage_commit(void)
7157 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7158 "[path ...]\n", getprogname());
7159 exit(1);
7162 struct collect_commit_logmsg_arg {
7163 const char *cmdline_log;
7164 const char *prepared_log;
7165 int non_interactive;
7166 const char *editor;
7167 const char *worktree_path;
7168 const char *branch_name;
7169 const char *repo_path;
7170 char *logmsg_path;
7174 static const struct got_error *
7175 read_prepared_logmsg(char **logmsg, const char *path)
7177 const struct got_error *err = NULL;
7178 FILE *f = NULL;
7179 struct stat sb;
7180 size_t r;
7182 *logmsg = NULL;
7183 memset(&sb, 0, sizeof(sb));
7185 f = fopen(path, "r");
7186 if (f == NULL)
7187 return got_error_from_errno2("fopen", path);
7189 if (fstat(fileno(f), &sb) == -1) {
7190 err = got_error_from_errno2("fstat", path);
7191 goto done;
7193 if (sb.st_size == 0) {
7194 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7195 goto done;
7198 *logmsg = malloc(sb.st_size + 1);
7199 if (*logmsg == NULL) {
7200 err = got_error_from_errno("malloc");
7201 goto done;
7204 r = fread(*logmsg, 1, sb.st_size, f);
7205 if (r != sb.st_size) {
7206 if (ferror(f))
7207 err = got_error_from_errno2("fread", path);
7208 else
7209 err = got_error(GOT_ERR_IO);
7210 goto done;
7212 (*logmsg)[sb.st_size] = '\0';
7213 done:
7214 if (fclose(f) == EOF && err == NULL)
7215 err = got_error_from_errno2("fclose", path);
7216 if (err) {
7217 free(*logmsg);
7218 *logmsg = NULL;
7220 return err;
7224 static const struct got_error *
7225 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7226 void *arg)
7228 char *initial_content = NULL;
7229 struct got_pathlist_entry *pe;
7230 const struct got_error *err = NULL;
7231 char *template = NULL;
7232 struct collect_commit_logmsg_arg *a = arg;
7233 int initial_content_len;
7234 int fd = -1;
7235 size_t len;
7237 /* if a message was specified on the command line, just use it */
7238 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7239 len = strlen(a->cmdline_log) + 1;
7240 *logmsg = malloc(len + 1);
7241 if (*logmsg == NULL)
7242 return got_error_from_errno("malloc");
7243 strlcpy(*logmsg, a->cmdline_log, len);
7244 return NULL;
7245 } else if (a->prepared_log != NULL && a->non_interactive)
7246 return read_prepared_logmsg(logmsg, a->prepared_log);
7248 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7249 return got_error_from_errno("asprintf");
7251 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7252 if (err)
7253 goto done;
7255 if (a->prepared_log) {
7256 char *msg;
7257 err = read_prepared_logmsg(&msg, a->prepared_log);
7258 if (err)
7259 goto done;
7260 if (write(fd, msg, strlen(msg)) == -1) {
7261 err = got_error_from_errno2("write", a->logmsg_path);
7262 free(msg);
7263 goto done;
7265 free(msg);
7268 initial_content_len = asprintf(&initial_content,
7269 "\n# changes to be committed on branch %s:\n",
7270 a->branch_name);
7271 if (initial_content_len == -1) {
7272 err = got_error_from_errno("asprintf");
7273 goto done;
7276 if (write(fd, initial_content, initial_content_len) == -1) {
7277 err = got_error_from_errno2("write", a->logmsg_path);
7278 goto done;
7281 TAILQ_FOREACH(pe, commitable_paths, entry) {
7282 struct got_commitable *ct = pe->data;
7283 dprintf(fd, "# %c %s\n",
7284 got_commitable_get_status(ct),
7285 got_commitable_get_path(ct));
7288 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7289 initial_content_len, a->prepared_log ? 0 : 1);
7290 done:
7291 free(initial_content);
7292 free(template);
7294 if (fd != -1 && close(fd) == -1 && err == NULL)
7295 err = got_error_from_errno2("close", a->logmsg_path);
7297 /* Editor is done; we can now apply unveil(2) */
7298 if (err == NULL)
7299 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7300 if (err) {
7301 free(*logmsg);
7302 *logmsg = NULL;
7304 return err;
7307 static const struct got_error *
7308 cmd_commit(int argc, char *argv[])
7310 const struct got_error *error = NULL;
7311 struct got_worktree *worktree = NULL;
7312 struct got_repository *repo = NULL;
7313 char *cwd = NULL, *id_str = NULL;
7314 struct got_object_id *id = NULL;
7315 const char *logmsg = NULL;
7316 char *prepared_logmsg = NULL;
7317 struct collect_commit_logmsg_arg cl_arg;
7318 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7319 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7320 int allow_bad_symlinks = 0, non_interactive = 0;
7321 struct got_pathlist_head paths;
7323 TAILQ_INIT(&paths);
7324 cl_arg.logmsg_path = NULL;
7326 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7327 switch (ch) {
7328 case 'F':
7329 if (logmsg != NULL)
7330 option_conflict('F', 'm');
7331 prepared_logmsg = realpath(optarg, NULL);
7332 if (prepared_logmsg == NULL)
7333 return got_error_from_errno2("realpath",
7334 optarg);
7335 break;
7336 case 'm':
7337 if (prepared_logmsg)
7338 option_conflict('m', 'F');
7339 logmsg = optarg;
7340 break;
7341 case 'N':
7342 non_interactive = 1;
7343 break;
7344 case 'S':
7345 allow_bad_symlinks = 1;
7346 break;
7347 default:
7348 usage_commit();
7349 /* NOTREACHED */
7353 argc -= optind;
7354 argv += optind;
7356 #ifndef PROFILE
7357 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7358 "unveil", NULL) == -1)
7359 err(1, "pledge");
7360 #endif
7361 cwd = getcwd(NULL, 0);
7362 if (cwd == NULL) {
7363 error = got_error_from_errno("getcwd");
7364 goto done;
7366 error = got_worktree_open(&worktree, cwd);
7367 if (error) {
7368 if (error->code == GOT_ERR_NOT_WORKTREE)
7369 error = wrap_not_worktree_error(error, "commit", cwd);
7370 goto done;
7373 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7374 if (error)
7375 goto done;
7376 if (rebase_in_progress) {
7377 error = got_error(GOT_ERR_REBASING);
7378 goto done;
7381 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7382 worktree);
7383 if (error)
7384 goto done;
7386 error = get_gitconfig_path(&gitconfig_path);
7387 if (error)
7388 goto done;
7389 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7390 gitconfig_path);
7391 if (error != NULL)
7392 goto done;
7394 error = get_author(&author, repo, worktree);
7395 if (error)
7396 return error;
7399 * unveil(2) traverses exec(2); if an editor is used we have
7400 * to apply unveil after the log message has been written.
7402 if (logmsg == NULL || strlen(logmsg) == 0)
7403 error = get_editor(&editor);
7404 else
7405 error = apply_unveil(got_repo_get_path(repo), 0,
7406 got_worktree_get_root_path(worktree));
7407 if (error)
7408 goto done;
7410 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7411 if (error)
7412 goto done;
7414 cl_arg.editor = editor;
7415 cl_arg.cmdline_log = logmsg;
7416 cl_arg.prepared_log = prepared_logmsg;
7417 cl_arg.non_interactive = non_interactive;
7418 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7419 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7420 if (!histedit_in_progress) {
7421 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7422 error = got_error(GOT_ERR_COMMIT_BRANCH);
7423 goto done;
7425 cl_arg.branch_name += 11;
7427 cl_arg.repo_path = got_repo_get_path(repo);
7428 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7429 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7430 print_status, NULL, repo);
7431 if (error) {
7432 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7433 cl_arg.logmsg_path != NULL)
7434 preserve_logmsg = 1;
7435 goto done;
7438 error = got_object_id_str(&id_str, id);
7439 if (error)
7440 goto done;
7441 printf("Created commit %s\n", id_str);
7442 done:
7443 if (preserve_logmsg) {
7444 fprintf(stderr, "%s: log message preserved in %s\n",
7445 getprogname(), cl_arg.logmsg_path);
7446 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7447 error == NULL)
7448 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7449 free(cl_arg.logmsg_path);
7450 if (repo) {
7451 const struct got_error *close_err = got_repo_close(repo);
7452 if (error == NULL)
7453 error = close_err;
7455 if (worktree)
7456 got_worktree_close(worktree);
7457 free(cwd);
7458 free(id_str);
7459 free(gitconfig_path);
7460 free(editor);
7461 free(author);
7462 free(prepared_logmsg);
7463 return error;
7466 __dead static void
7467 usage_send(void)
7469 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7470 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7471 "[remote-repository]\n", getprogname());
7472 exit(1);
7475 struct got_send_progress_arg {
7476 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7477 int verbosity;
7478 int last_ncommits;
7479 int last_nobj_total;
7480 int last_p_deltify;
7481 int last_p_written;
7482 int last_p_sent;
7483 int printed_something;
7484 int sent_something;
7485 struct got_pathlist_head *delete_branches;
7488 static const struct got_error *
7489 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7490 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7491 int success)
7493 struct got_send_progress_arg *a = arg;
7494 char scaled_packsize[FMT_SCALED_STRSIZE];
7495 char scaled_sent[FMT_SCALED_STRSIZE];
7496 int p_deltify = 0, p_written = 0, p_sent = 0;
7497 int print_searching = 0, print_total = 0;
7498 int print_deltify = 0, print_written = 0, print_sent = 0;
7500 if (a->verbosity < 0)
7501 return NULL;
7503 if (refname) {
7504 const char *status = success ? "accepted" : "rejected";
7506 if (success) {
7507 struct got_pathlist_entry *pe;
7508 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7509 const char *branchname = pe->path;
7510 if (got_path_cmp(branchname, refname,
7511 strlen(branchname), strlen(refname)) == 0) {
7512 status = "deleted";
7513 a->sent_something = 1;
7514 break;
7519 if (a->printed_something)
7520 putchar('\n');
7521 printf("Server has %s %s", status, refname);
7522 a->printed_something = 1;
7523 return NULL;
7526 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7527 return got_error_from_errno("fmt_scaled");
7528 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7529 return got_error_from_errno("fmt_scaled");
7531 if (a->last_ncommits != ncommits) {
7532 print_searching = 1;
7533 a->last_ncommits = ncommits;
7536 if (a->last_nobj_total != nobj_total) {
7537 print_searching = 1;
7538 print_total = 1;
7539 a->last_nobj_total = nobj_total;
7542 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7543 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7544 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7545 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7546 return got_error(GOT_ERR_NO_SPACE);
7549 if (nobj_deltify > 0 || nobj_written > 0) {
7550 if (nobj_deltify > 0) {
7551 p_deltify = (nobj_deltify * 100) / nobj_total;
7552 if (p_deltify != a->last_p_deltify) {
7553 a->last_p_deltify = p_deltify;
7554 print_searching = 1;
7555 print_total = 1;
7556 print_deltify = 1;
7559 if (nobj_written > 0) {
7560 p_written = (nobj_written * 100) / nobj_total;
7561 if (p_written != a->last_p_written) {
7562 a->last_p_written = p_written;
7563 print_searching = 1;
7564 print_total = 1;
7565 print_deltify = 1;
7566 print_written = 1;
7571 if (bytes_sent > 0) {
7572 p_sent = (bytes_sent * 100) / packfile_size;
7573 if (p_sent != a->last_p_sent) {
7574 a->last_p_sent = p_sent;
7575 print_searching = 1;
7576 print_total = 1;
7577 print_deltify = 1;
7578 print_written = 1;
7579 print_sent = 1;
7581 a->sent_something = 1;
7584 if (print_searching || print_total || print_deltify || print_written ||
7585 print_sent)
7586 printf("\r");
7587 if (print_searching)
7588 printf("packing %d reference%s", ncommits,
7589 ncommits == 1 ? "" : "s");
7590 if (print_total)
7591 printf("; %d object%s", nobj_total,
7592 nobj_total == 1 ? "" : "s");
7593 if (print_deltify)
7594 printf("; deltify: %d%%", p_deltify);
7595 if (print_sent)
7596 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7597 scaled_packsize, p_sent);
7598 else if (print_written)
7599 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7600 scaled_packsize, p_written);
7601 if (print_searching || print_total || print_deltify ||
7602 print_written || print_sent) {
7603 a->printed_something = 1;
7604 fflush(stdout);
7606 return NULL;
7609 static const struct got_error *
7610 cmd_send(int argc, char *argv[])
7612 const struct got_error *error = NULL;
7613 char *cwd = NULL, *repo_path = NULL;
7614 const char *remote_name;
7615 char *proto = NULL, *host = NULL, *port = NULL;
7616 char *repo_name = NULL, *server_path = NULL;
7617 const struct got_remote_repo *remotes, *remote = NULL;
7618 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7619 struct got_repository *repo = NULL;
7620 struct got_worktree *worktree = NULL;
7621 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7622 struct got_pathlist_head branches;
7623 struct got_pathlist_head tags;
7624 struct got_reflist_head all_branches;
7625 struct got_reflist_head all_tags;
7626 struct got_pathlist_head delete_args;
7627 struct got_pathlist_head delete_branches;
7628 struct got_reflist_entry *re;
7629 struct got_pathlist_entry *pe;
7630 int i, ch, sendfd = -1, sendstatus;
7631 pid_t sendpid = -1;
7632 struct got_send_progress_arg spa;
7633 int verbosity = 0, overwrite_refs = 0;
7634 int send_all_branches = 0, send_all_tags = 0;
7635 struct got_reference *ref = NULL;
7637 TAILQ_INIT(&branches);
7638 TAILQ_INIT(&tags);
7639 TAILQ_INIT(&all_branches);
7640 TAILQ_INIT(&all_tags);
7641 TAILQ_INIT(&delete_args);
7642 TAILQ_INIT(&delete_branches);
7644 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7645 switch (ch) {
7646 case 'a':
7647 send_all_branches = 1;
7648 break;
7649 case 'b':
7650 error = got_pathlist_append(&branches, optarg, NULL);
7651 if (error)
7652 return error;
7653 nbranches++;
7654 break;
7655 case 'd':
7656 error = got_pathlist_append(&delete_args, optarg, NULL);
7657 if (error)
7658 return error;
7659 break;
7660 case 'f':
7661 overwrite_refs = 1;
7662 break;
7663 case 'r':
7664 repo_path = realpath(optarg, NULL);
7665 if (repo_path == NULL)
7666 return got_error_from_errno2("realpath",
7667 optarg);
7668 got_path_strip_trailing_slashes(repo_path);
7669 break;
7670 case 't':
7671 error = got_pathlist_append(&tags, optarg, NULL);
7672 if (error)
7673 return error;
7674 ntags++;
7675 break;
7676 case 'T':
7677 send_all_tags = 1;
7678 break;
7679 case 'v':
7680 if (verbosity < 0)
7681 verbosity = 0;
7682 else if (verbosity < 3)
7683 verbosity++;
7684 break;
7685 case 'q':
7686 verbosity = -1;
7687 break;
7688 default:
7689 usage_send();
7690 /* NOTREACHED */
7693 argc -= optind;
7694 argv += optind;
7696 if (send_all_branches && !TAILQ_EMPTY(&branches))
7697 option_conflict('a', 'b');
7698 if (send_all_tags && !TAILQ_EMPTY(&tags))
7699 option_conflict('T', 't');
7702 if (argc == 0)
7703 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7704 else if (argc == 1)
7705 remote_name = argv[0];
7706 else
7707 usage_send();
7709 cwd = getcwd(NULL, 0);
7710 if (cwd == NULL) {
7711 error = got_error_from_errno("getcwd");
7712 goto done;
7715 if (repo_path == NULL) {
7716 error = got_worktree_open(&worktree, cwd);
7717 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7718 goto done;
7719 else
7720 error = NULL;
7721 if (worktree) {
7722 repo_path =
7723 strdup(got_worktree_get_repo_path(worktree));
7724 if (repo_path == NULL)
7725 error = got_error_from_errno("strdup");
7726 if (error)
7727 goto done;
7728 } else {
7729 repo_path = strdup(cwd);
7730 if (repo_path == NULL) {
7731 error = got_error_from_errno("strdup");
7732 goto done;
7737 error = got_repo_open(&repo, repo_path, NULL);
7738 if (error)
7739 goto done;
7741 if (worktree) {
7742 worktree_conf = got_worktree_get_gotconfig(worktree);
7743 if (worktree_conf) {
7744 got_gotconfig_get_remotes(&nremotes, &remotes,
7745 worktree_conf);
7746 for (i = 0; i < nremotes; i++) {
7747 if (strcmp(remotes[i].name, remote_name) == 0) {
7748 remote = &remotes[i];
7749 break;
7754 if (remote == NULL) {
7755 repo_conf = got_repo_get_gotconfig(repo);
7756 if (repo_conf) {
7757 got_gotconfig_get_remotes(&nremotes, &remotes,
7758 repo_conf);
7759 for (i = 0; i < nremotes; i++) {
7760 if (strcmp(remotes[i].name, remote_name) == 0) {
7761 remote = &remotes[i];
7762 break;
7767 if (remote == NULL) {
7768 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7769 for (i = 0; i < nremotes; i++) {
7770 if (strcmp(remotes[i].name, remote_name) == 0) {
7771 remote = &remotes[i];
7772 break;
7776 if (remote == NULL) {
7777 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7778 goto done;
7781 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7782 &repo_name, remote->send_url);
7783 if (error)
7784 goto done;
7786 if (strcmp(proto, "git") == 0) {
7787 #ifndef PROFILE
7788 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7789 "sendfd dns inet unveil", NULL) == -1)
7790 err(1, "pledge");
7791 #endif
7792 } else if (strcmp(proto, "git+ssh") == 0 ||
7793 strcmp(proto, "ssh") == 0) {
7794 #ifndef PROFILE
7795 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7796 "sendfd unveil", NULL) == -1)
7797 err(1, "pledge");
7798 #endif
7799 } else if (strcmp(proto, "http") == 0 ||
7800 strcmp(proto, "git+http") == 0) {
7801 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7802 goto done;
7803 } else {
7804 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7805 goto done;
7808 error = got_dial_apply_unveil(proto);
7809 if (error)
7810 goto done;
7812 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7813 if (error)
7814 goto done;
7816 if (send_all_branches) {
7817 error = got_ref_list(&all_branches, repo, "refs/heads",
7818 got_ref_cmp_by_name, NULL);
7819 if (error)
7820 goto done;
7821 TAILQ_FOREACH(re, &all_branches, entry) {
7822 const char *branchname = got_ref_get_name(re->ref);
7823 error = got_pathlist_append(&branches,
7824 branchname, NULL);
7825 if (error)
7826 goto done;
7827 nbranches++;
7829 } else if (nbranches == 0) {
7830 for (i = 0; i < remote->nsend_branches; i++) {
7831 got_pathlist_append(&branches,
7832 remote->send_branches[i], NULL);
7836 if (send_all_tags) {
7837 error = got_ref_list(&all_tags, repo, "refs/tags",
7838 got_ref_cmp_by_name, NULL);
7839 if (error)
7840 goto done;
7841 TAILQ_FOREACH(re, &all_tags, entry) {
7842 const char *tagname = got_ref_get_name(re->ref);
7843 error = got_pathlist_append(&tags,
7844 tagname, NULL);
7845 if (error)
7846 goto done;
7847 ntags++;
7852 * To prevent accidents only branches in refs/heads/ can be deleted
7853 * with 'got send -d'.
7854 * Deleting anything else requires local repository access or Git.
7856 TAILQ_FOREACH(pe, &delete_args, entry) {
7857 const char *branchname = pe->path;
7858 char *s;
7859 struct got_pathlist_entry *new;
7860 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7861 s = strdup(branchname);
7862 if (s == NULL) {
7863 error = got_error_from_errno("strdup");
7864 goto done;
7866 } else {
7867 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7868 error = got_error_from_errno("asprintf");
7869 goto done;
7872 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7873 if (error || new == NULL /* duplicate */)
7874 free(s);
7875 if (error)
7876 goto done;
7877 ndelete_branches++;
7880 if (nbranches == 0 && ndelete_branches == 0) {
7881 struct got_reference *head_ref;
7882 if (worktree)
7883 error = got_ref_open(&head_ref, repo,
7884 got_worktree_get_head_ref_name(worktree), 0);
7885 else
7886 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7887 if (error)
7888 goto done;
7889 if (got_ref_is_symbolic(head_ref)) {
7890 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7891 got_ref_close(head_ref);
7892 if (error)
7893 goto done;
7894 } else
7895 ref = head_ref;
7896 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7897 NULL);
7898 if (error)
7899 goto done;
7900 nbranches++;
7903 if (verbosity >= 0)
7904 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7905 port ? ":" : "", port ? port : "");
7907 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7908 server_path, verbosity);
7909 if (error)
7910 goto done;
7912 memset(&spa, 0, sizeof(spa));
7913 spa.last_scaled_packsize[0] = '\0';
7914 spa.last_p_deltify = -1;
7915 spa.last_p_written = -1;
7916 spa.verbosity = verbosity;
7917 spa.delete_branches = &delete_branches;
7918 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7919 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7920 check_cancelled, NULL);
7921 if (spa.printed_something)
7922 putchar('\n');
7923 if (error)
7924 goto done;
7925 if (!spa.sent_something && verbosity >= 0)
7926 printf("Already up-to-date\n");
7927 done:
7928 if (sendpid > 0) {
7929 if (kill(sendpid, SIGTERM) == -1)
7930 error = got_error_from_errno("kill");
7931 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7932 error = got_error_from_errno("waitpid");
7934 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7935 error = got_error_from_errno("close");
7936 if (repo) {
7937 const struct got_error *close_err = got_repo_close(repo);
7938 if (error == NULL)
7939 error = close_err;
7941 if (worktree)
7942 got_worktree_close(worktree);
7943 if (ref)
7944 got_ref_close(ref);
7945 got_pathlist_free(&branches);
7946 got_pathlist_free(&tags);
7947 got_ref_list_free(&all_branches);
7948 got_ref_list_free(&all_tags);
7949 got_pathlist_free(&delete_args);
7950 TAILQ_FOREACH(pe, &delete_branches, entry)
7951 free((char *)pe->path);
7952 got_pathlist_free(&delete_branches);
7953 free(cwd);
7954 free(repo_path);
7955 free(proto);
7956 free(host);
7957 free(port);
7958 free(server_path);
7959 free(repo_name);
7960 return error;
7963 __dead static void
7964 usage_cherrypick(void)
7966 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7967 exit(1);
7970 static const struct got_error *
7971 cmd_cherrypick(int argc, char *argv[])
7973 const struct got_error *error = NULL;
7974 struct got_worktree *worktree = NULL;
7975 struct got_repository *repo = NULL;
7976 char *cwd = NULL, *commit_id_str = NULL;
7977 struct got_object_id *commit_id = NULL;
7978 struct got_commit_object *commit = NULL;
7979 struct got_object_qid *pid;
7980 int ch;
7981 struct got_update_progress_arg upa;
7983 while ((ch = getopt(argc, argv, "")) != -1) {
7984 switch (ch) {
7985 default:
7986 usage_cherrypick();
7987 /* NOTREACHED */
7991 argc -= optind;
7992 argv += optind;
7994 #ifndef PROFILE
7995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7996 "unveil", NULL) == -1)
7997 err(1, "pledge");
7998 #endif
7999 if (argc != 1)
8000 usage_cherrypick();
8002 cwd = getcwd(NULL, 0);
8003 if (cwd == NULL) {
8004 error = got_error_from_errno("getcwd");
8005 goto done;
8007 error = got_worktree_open(&worktree, cwd);
8008 if (error) {
8009 if (error->code == GOT_ERR_NOT_WORKTREE)
8010 error = wrap_not_worktree_error(error, "cherrypick",
8011 cwd);
8012 goto done;
8015 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8016 NULL);
8017 if (error != NULL)
8018 goto done;
8020 error = apply_unveil(got_repo_get_path(repo), 0,
8021 got_worktree_get_root_path(worktree));
8022 if (error)
8023 goto done;
8025 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8026 GOT_OBJ_TYPE_COMMIT, repo);
8027 if (error != NULL) {
8028 struct got_reference *ref;
8029 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8030 goto done;
8031 error = got_ref_open(&ref, repo, argv[0], 0);
8032 if (error != NULL)
8033 goto done;
8034 error = got_ref_resolve(&commit_id, repo, ref);
8035 got_ref_close(ref);
8036 if (error != NULL)
8037 goto done;
8039 error = got_object_id_str(&commit_id_str, commit_id);
8040 if (error)
8041 goto done;
8043 error = got_object_open_as_commit(&commit, repo, commit_id);
8044 if (error)
8045 goto done;
8046 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8047 memset(&upa, 0, sizeof(upa));
8048 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8049 commit_id, repo, update_progress, &upa, check_cancelled,
8050 NULL);
8051 if (error != NULL)
8052 goto done;
8054 if (upa.did_something)
8055 printf("Merged commit %s\n", commit_id_str);
8056 print_update_progress_stats(&upa);
8057 done:
8058 if (commit)
8059 got_object_commit_close(commit);
8060 free(commit_id_str);
8061 if (worktree)
8062 got_worktree_close(worktree);
8063 if (repo) {
8064 const struct got_error *close_err = got_repo_close(repo);
8065 if (error == NULL)
8066 error = close_err;
8068 return error;
8071 __dead static void
8072 usage_backout(void)
8074 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8075 exit(1);
8078 static const struct got_error *
8079 cmd_backout(int argc, char *argv[])
8081 const struct got_error *error = NULL;
8082 struct got_worktree *worktree = NULL;
8083 struct got_repository *repo = NULL;
8084 char *cwd = NULL, *commit_id_str = NULL;
8085 struct got_object_id *commit_id = NULL;
8086 struct got_commit_object *commit = NULL;
8087 struct got_object_qid *pid;
8088 int ch;
8089 struct got_update_progress_arg upa;
8091 while ((ch = getopt(argc, argv, "")) != -1) {
8092 switch (ch) {
8093 default:
8094 usage_backout();
8095 /* NOTREACHED */
8099 argc -= optind;
8100 argv += optind;
8102 #ifndef PROFILE
8103 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8104 "unveil", NULL) == -1)
8105 err(1, "pledge");
8106 #endif
8107 if (argc != 1)
8108 usage_backout();
8110 cwd = getcwd(NULL, 0);
8111 if (cwd == NULL) {
8112 error = got_error_from_errno("getcwd");
8113 goto done;
8115 error = got_worktree_open(&worktree, cwd);
8116 if (error) {
8117 if (error->code == GOT_ERR_NOT_WORKTREE)
8118 error = wrap_not_worktree_error(error, "backout", cwd);
8119 goto done;
8122 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8123 NULL);
8124 if (error != NULL)
8125 goto done;
8127 error = apply_unveil(got_repo_get_path(repo), 0,
8128 got_worktree_get_root_path(worktree));
8129 if (error)
8130 goto done;
8132 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8133 GOT_OBJ_TYPE_COMMIT, repo);
8134 if (error != NULL) {
8135 struct got_reference *ref;
8136 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8137 goto done;
8138 error = got_ref_open(&ref, repo, argv[0], 0);
8139 if (error != NULL)
8140 goto done;
8141 error = got_ref_resolve(&commit_id, repo, ref);
8142 got_ref_close(ref);
8143 if (error != NULL)
8144 goto done;
8146 error = got_object_id_str(&commit_id_str, commit_id);
8147 if (error)
8148 goto done;
8150 error = got_object_open_as_commit(&commit, repo, commit_id);
8151 if (error)
8152 goto done;
8153 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8154 if (pid == NULL) {
8155 error = got_error(GOT_ERR_ROOT_COMMIT);
8156 goto done;
8159 memset(&upa, 0, sizeof(upa));
8160 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8161 update_progress, &upa, check_cancelled, NULL);
8162 if (error != NULL)
8163 goto done;
8165 if (upa.did_something)
8166 printf("Backed out commit %s\n", commit_id_str);
8167 print_update_progress_stats(&upa);
8168 done:
8169 if (commit)
8170 got_object_commit_close(commit);
8171 free(commit_id_str);
8172 if (worktree)
8173 got_worktree_close(worktree);
8174 if (repo) {
8175 const struct got_error *close_err = got_repo_close(repo);
8176 if (error == NULL)
8177 error = close_err;
8179 return error;
8182 __dead static void
8183 usage_rebase(void)
8185 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8186 getprogname());
8187 exit(1);
8190 void
8191 trim_logmsg(char *logmsg, int limit)
8193 char *nl;
8194 size_t len;
8196 len = strlen(logmsg);
8197 if (len > limit)
8198 len = limit;
8199 logmsg[len] = '\0';
8200 nl = strchr(logmsg, '\n');
8201 if (nl)
8202 *nl = '\0';
8205 static const struct got_error *
8206 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8208 const struct got_error *err;
8209 char *logmsg0 = NULL;
8210 const char *s;
8212 err = got_object_commit_get_logmsg(&logmsg0, commit);
8213 if (err)
8214 return err;
8216 s = logmsg0;
8217 while (isspace((unsigned char)s[0]))
8218 s++;
8220 *logmsg = strdup(s);
8221 if (*logmsg == NULL) {
8222 err = got_error_from_errno("strdup");
8223 goto done;
8226 trim_logmsg(*logmsg, limit);
8227 done:
8228 free(logmsg0);
8229 return err;
8232 static const struct got_error *
8233 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8235 const struct got_error *err;
8236 struct got_commit_object *commit = NULL;
8237 char *id_str = NULL, *logmsg = NULL;
8239 err = got_object_open_as_commit(&commit, repo, id);
8240 if (err)
8241 return err;
8243 err = got_object_id_str(&id_str, id);
8244 if (err)
8245 goto done;
8247 id_str[12] = '\0';
8249 err = get_short_logmsg(&logmsg, 42, commit);
8250 if (err)
8251 goto done;
8253 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8254 done:
8255 free(id_str);
8256 got_object_commit_close(commit);
8257 free(logmsg);
8258 return err;
8261 static const struct got_error *
8262 show_rebase_progress(struct got_commit_object *commit,
8263 struct got_object_id *old_id, struct got_object_id *new_id)
8265 const struct got_error *err;
8266 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8268 err = got_object_id_str(&old_id_str, old_id);
8269 if (err)
8270 goto done;
8272 if (new_id) {
8273 err = got_object_id_str(&new_id_str, new_id);
8274 if (err)
8275 goto done;
8278 old_id_str[12] = '\0';
8279 if (new_id_str)
8280 new_id_str[12] = '\0';
8282 err = get_short_logmsg(&logmsg, 42, commit);
8283 if (err)
8284 goto done;
8286 printf("%s -> %s: %s\n", old_id_str,
8287 new_id_str ? new_id_str : "no-op change", logmsg);
8288 done:
8289 free(old_id_str);
8290 free(new_id_str);
8291 free(logmsg);
8292 return err;
8295 static const struct got_error *
8296 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8297 struct got_reference *branch, struct got_reference *new_base_branch,
8298 struct got_reference *tmp_branch, struct got_repository *repo,
8299 int create_backup)
8301 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8302 return got_worktree_rebase_complete(worktree, fileindex,
8303 new_base_branch, tmp_branch, branch, repo, create_backup);
8306 static const struct got_error *
8307 rebase_commit(struct got_pathlist_head *merged_paths,
8308 struct got_worktree *worktree, struct got_fileindex *fileindex,
8309 struct got_reference *tmp_branch,
8310 struct got_object_id *commit_id, struct got_repository *repo)
8312 const struct got_error *error;
8313 struct got_commit_object *commit;
8314 struct got_object_id *new_commit_id;
8316 error = got_object_open_as_commit(&commit, repo, commit_id);
8317 if (error)
8318 return error;
8320 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8321 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8322 if (error) {
8323 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8324 goto done;
8325 error = show_rebase_progress(commit, commit_id, NULL);
8326 } else {
8327 error = show_rebase_progress(commit, commit_id, new_commit_id);
8328 free(new_commit_id);
8330 done:
8331 got_object_commit_close(commit);
8332 return error;
8335 struct check_path_prefix_arg {
8336 const char *path_prefix;
8337 size_t len;
8338 int errcode;
8341 static const struct got_error *
8342 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8343 struct got_blob_object *blob2, struct got_object_id *id1,
8344 struct got_object_id *id2, const char *path1, const char *path2,
8345 mode_t mode1, mode_t mode2, struct got_repository *repo)
8347 struct check_path_prefix_arg *a = arg;
8349 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8350 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8351 return got_error(a->errcode);
8353 return NULL;
8356 static const struct got_error *
8357 check_path_prefix(struct got_object_id *parent_id,
8358 struct got_object_id *commit_id, const char *path_prefix,
8359 int errcode, struct got_repository *repo)
8361 const struct got_error *err;
8362 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8363 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8364 struct check_path_prefix_arg cpp_arg;
8366 if (got_path_is_root_dir(path_prefix))
8367 return NULL;
8369 err = got_object_open_as_commit(&commit, repo, commit_id);
8370 if (err)
8371 goto done;
8373 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8374 if (err)
8375 goto done;
8377 err = got_object_open_as_tree(&tree1, repo,
8378 got_object_commit_get_tree_id(parent_commit));
8379 if (err)
8380 goto done;
8382 err = got_object_open_as_tree(&tree2, repo,
8383 got_object_commit_get_tree_id(commit));
8384 if (err)
8385 goto done;
8387 cpp_arg.path_prefix = path_prefix;
8388 while (cpp_arg.path_prefix[0] == '/')
8389 cpp_arg.path_prefix++;
8390 cpp_arg.len = strlen(cpp_arg.path_prefix);
8391 cpp_arg.errcode = errcode;
8392 err = got_diff_tree(tree1, tree2, "", "", repo,
8393 check_path_prefix_in_diff, &cpp_arg, 0);
8394 done:
8395 if (tree1)
8396 got_object_tree_close(tree1);
8397 if (tree2)
8398 got_object_tree_close(tree2);
8399 if (commit)
8400 got_object_commit_close(commit);
8401 if (parent_commit)
8402 got_object_commit_close(parent_commit);
8403 return err;
8406 static const struct got_error *
8407 collect_commits(struct got_object_id_queue *commits,
8408 struct got_object_id *initial_commit_id,
8409 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8410 const char *path_prefix, int path_prefix_errcode,
8411 struct got_repository *repo)
8413 const struct got_error *err = NULL;
8414 struct got_commit_graph *graph = NULL;
8415 struct got_object_id *parent_id = NULL;
8416 struct got_object_qid *qid;
8417 struct got_object_id *commit_id = initial_commit_id;
8419 err = got_commit_graph_open(&graph, "/", 1);
8420 if (err)
8421 return err;
8423 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8424 check_cancelled, NULL);
8425 if (err)
8426 goto done;
8427 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8428 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8429 check_cancelled, NULL);
8430 if (err) {
8431 if (err->code == GOT_ERR_ITER_COMPLETED) {
8432 err = got_error_msg(GOT_ERR_ANCESTRY,
8433 "ran out of commits to rebase before "
8434 "youngest common ancestor commit has "
8435 "been reached?!?");
8437 goto done;
8438 } else {
8439 err = check_path_prefix(parent_id, commit_id,
8440 path_prefix, path_prefix_errcode, repo);
8441 if (err)
8442 goto done;
8444 err = got_object_qid_alloc(&qid, commit_id);
8445 if (err)
8446 goto done;
8447 STAILQ_INSERT_HEAD(commits, qid, entry);
8448 commit_id = parent_id;
8451 done:
8452 got_commit_graph_close(graph);
8453 return err;
8456 static const struct got_error *
8457 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8459 const struct got_error *err = NULL;
8460 time_t committer_time;
8461 struct tm tm;
8462 char datebuf[11]; /* YYYY-MM-DD + NUL */
8463 char *author0 = NULL, *author, *smallerthan;
8464 char *logmsg0 = NULL, *logmsg, *newline;
8466 committer_time = got_object_commit_get_committer_time(commit);
8467 if (gmtime_r(&committer_time, &tm) == NULL)
8468 return got_error_from_errno("gmtime_r");
8469 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8470 return got_error(GOT_ERR_NO_SPACE);
8472 author0 = strdup(got_object_commit_get_author(commit));
8473 if (author0 == NULL)
8474 return got_error_from_errno("strdup");
8475 author = author0;
8476 smallerthan = strchr(author, '<');
8477 if (smallerthan && smallerthan[1] != '\0')
8478 author = smallerthan + 1;
8479 author[strcspn(author, "@>")] = '\0';
8481 err = got_object_commit_get_logmsg(&logmsg0, commit);
8482 if (err)
8483 goto done;
8484 logmsg = logmsg0;
8485 while (*logmsg == '\n')
8486 logmsg++;
8487 newline = strchr(logmsg, '\n');
8488 if (newline)
8489 *newline = '\0';
8491 if (asprintf(brief_str, "%s %s %s",
8492 datebuf, author, logmsg) == -1)
8493 err = got_error_from_errno("asprintf");
8494 done:
8495 free(author0);
8496 free(logmsg0);
8497 return err;
8500 static const struct got_error *
8501 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8502 struct got_repository *repo)
8504 const struct got_error *err;
8505 char *id_str;
8507 err = got_object_id_str(&id_str, id);
8508 if (err)
8509 return err;
8511 err = got_ref_delete(ref, repo);
8512 if (err)
8513 goto done;
8515 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8516 done:
8517 free(id_str);
8518 return err;
8521 static const struct got_error *
8522 print_backup_ref(const char *branch_name, const char *new_id_str,
8523 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8524 struct got_reflist_object_id_map *refs_idmap,
8525 struct got_repository *repo)
8527 const struct got_error *err = NULL;
8528 struct got_reflist_head *refs;
8529 char *refs_str = NULL;
8530 struct got_object_id *new_commit_id = NULL;
8531 struct got_commit_object *new_commit = NULL;
8532 char *new_commit_brief_str = NULL;
8533 struct got_object_id *yca_id = NULL;
8534 struct got_commit_object *yca_commit = NULL;
8535 char *yca_id_str = NULL, *yca_brief_str = NULL;
8536 char *custom_refs_str;
8538 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8539 return got_error_from_errno("asprintf");
8541 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8542 0, 0, refs_idmap, custom_refs_str);
8543 if (err)
8544 goto done;
8546 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8547 if (err)
8548 goto done;
8550 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8551 if (refs) {
8552 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8553 if (err)
8554 goto done;
8557 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8558 if (err)
8559 goto done;
8561 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8562 if (err)
8563 goto done;
8565 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8566 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8567 if (err)
8568 goto done;
8570 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8571 refs_str ? " (" : "", refs_str ? refs_str : "",
8572 refs_str ? ")" : "", new_commit_brief_str);
8573 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8574 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8575 free(refs_str);
8576 refs_str = NULL;
8578 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8579 if (err)
8580 goto done;
8582 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8583 if (err)
8584 goto done;
8586 err = got_object_id_str(&yca_id_str, yca_id);
8587 if (err)
8588 goto done;
8590 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8591 if (refs) {
8592 err = build_refs_str(&refs_str, refs, yca_id, repo);
8593 if (err)
8594 goto done;
8596 printf("history forked at %s%s%s%s\n %s\n",
8597 yca_id_str,
8598 refs_str ? " (" : "", refs_str ? refs_str : "",
8599 refs_str ? ")" : "", yca_brief_str);
8601 done:
8602 free(custom_refs_str);
8603 free(new_commit_id);
8604 free(refs_str);
8605 free(yca_id);
8606 free(yca_id_str);
8607 free(yca_brief_str);
8608 if (new_commit)
8609 got_object_commit_close(new_commit);
8610 if (yca_commit)
8611 got_object_commit_close(yca_commit);
8613 return NULL;
8616 static const struct got_error *
8617 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8618 int delete, struct got_repository *repo)
8620 const struct got_error *err;
8621 struct got_reflist_head refs, backup_refs;
8622 struct got_reflist_entry *re;
8623 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8624 struct got_object_id *old_commit_id = NULL;
8625 char *branch_name = NULL;
8626 struct got_commit_object *old_commit = NULL;
8627 struct got_reflist_object_id_map *refs_idmap = NULL;
8628 int wanted_branch_found = 0;
8630 TAILQ_INIT(&refs);
8631 TAILQ_INIT(&backup_refs);
8633 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8634 if (err)
8635 return err;
8637 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8638 if (err)
8639 goto done;
8641 if (wanted_branch_name) {
8642 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8643 wanted_branch_name += 11;
8646 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8647 got_ref_cmp_by_commit_timestamp_descending, repo);
8648 if (err)
8649 goto done;
8651 TAILQ_FOREACH(re, &backup_refs, entry) {
8652 const char *refname = got_ref_get_name(re->ref);
8653 char *slash;
8655 err = check_cancelled(NULL);
8656 if (err)
8657 break;
8659 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8660 if (err)
8661 break;
8663 err = got_object_open_as_commit(&old_commit, repo,
8664 old_commit_id);
8665 if (err)
8666 break;
8668 if (strncmp(backup_ref_prefix, refname,
8669 backup_ref_prefix_len) == 0)
8670 refname += backup_ref_prefix_len;
8672 while (refname[0] == '/')
8673 refname++;
8675 branch_name = strdup(refname);
8676 if (branch_name == NULL) {
8677 err = got_error_from_errno("strdup");
8678 break;
8680 slash = strrchr(branch_name, '/');
8681 if (slash) {
8682 *slash = '\0';
8683 refname += strlen(branch_name) + 1;
8686 if (wanted_branch_name == NULL ||
8687 strcmp(wanted_branch_name, branch_name) == 0) {
8688 wanted_branch_found = 1;
8689 if (delete) {
8690 err = delete_backup_ref(re->ref,
8691 old_commit_id, repo);
8692 } else {
8693 err = print_backup_ref(branch_name, refname,
8694 old_commit_id, old_commit, refs_idmap,
8695 repo);
8697 if (err)
8698 break;
8701 free(old_commit_id);
8702 old_commit_id = NULL;
8703 free(branch_name);
8704 branch_name = NULL;
8705 got_object_commit_close(old_commit);
8706 old_commit = NULL;
8709 if (wanted_branch_name && !wanted_branch_found) {
8710 err = got_error_fmt(GOT_ERR_NOT_REF,
8711 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8713 done:
8714 if (refs_idmap)
8715 got_reflist_object_id_map_free(refs_idmap);
8716 got_ref_list_free(&refs);
8717 got_ref_list_free(&backup_refs);
8718 free(old_commit_id);
8719 free(branch_name);
8720 if (old_commit)
8721 got_object_commit_close(old_commit);
8722 return err;
8725 static const struct got_error *
8726 cmd_rebase(int argc, char *argv[])
8728 const struct got_error *error = NULL;
8729 struct got_worktree *worktree = NULL;
8730 struct got_repository *repo = NULL;
8731 struct got_fileindex *fileindex = NULL;
8732 char *cwd = NULL;
8733 struct got_reference *branch = NULL;
8734 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8735 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8736 struct got_object_id *resume_commit_id = NULL;
8737 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8738 struct got_commit_object *commit = NULL;
8739 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8740 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8741 int delete_backups = 0;
8742 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8743 struct got_object_id_queue commits;
8744 struct got_pathlist_head merged_paths;
8745 const struct got_object_id_queue *parent_ids;
8746 struct got_object_qid *qid, *pid;
8748 STAILQ_INIT(&commits);
8749 TAILQ_INIT(&merged_paths);
8751 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8752 switch (ch) {
8753 case 'a':
8754 abort_rebase = 1;
8755 break;
8756 case 'c':
8757 continue_rebase = 1;
8758 break;
8759 case 'l':
8760 list_backups = 1;
8761 break;
8762 case 'X':
8763 delete_backups = 1;
8764 break;
8765 default:
8766 usage_rebase();
8767 /* NOTREACHED */
8771 argc -= optind;
8772 argv += optind;
8774 #ifndef PROFILE
8775 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8776 "unveil", NULL) == -1)
8777 err(1, "pledge");
8778 #endif
8779 if (list_backups) {
8780 if (abort_rebase)
8781 option_conflict('l', 'a');
8782 if (continue_rebase)
8783 option_conflict('l', 'c');
8784 if (delete_backups)
8785 option_conflict('l', 'X');
8786 if (argc != 0 && argc != 1)
8787 usage_rebase();
8788 } else if (delete_backups) {
8789 if (abort_rebase)
8790 option_conflict('X', 'a');
8791 if (continue_rebase)
8792 option_conflict('X', 'c');
8793 if (list_backups)
8794 option_conflict('l', 'X');
8795 if (argc != 0 && argc != 1)
8796 usage_rebase();
8797 } else {
8798 if (abort_rebase && continue_rebase)
8799 usage_rebase();
8800 else if (abort_rebase || continue_rebase) {
8801 if (argc != 0)
8802 usage_rebase();
8803 } else if (argc != 1)
8804 usage_rebase();
8807 cwd = getcwd(NULL, 0);
8808 if (cwd == NULL) {
8809 error = got_error_from_errno("getcwd");
8810 goto done;
8812 error = got_worktree_open(&worktree, cwd);
8813 if (error) {
8814 if (list_backups || delete_backups) {
8815 if (error->code != GOT_ERR_NOT_WORKTREE)
8816 goto done;
8817 } else {
8818 if (error->code == GOT_ERR_NOT_WORKTREE)
8819 error = wrap_not_worktree_error(error,
8820 "rebase", cwd);
8821 goto done;
8825 error = got_repo_open(&repo,
8826 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8827 if (error != NULL)
8828 goto done;
8830 error = apply_unveil(got_repo_get_path(repo), 0,
8831 worktree ? got_worktree_get_root_path(worktree) : NULL);
8832 if (error)
8833 goto done;
8835 if (list_backups || delete_backups) {
8836 error = process_backup_refs(
8837 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8838 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8839 goto done; /* nothing else to do */
8842 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8843 worktree);
8844 if (error)
8845 goto done;
8846 if (histedit_in_progress) {
8847 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8848 goto done;
8851 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8852 if (error)
8853 goto done;
8855 if (abort_rebase) {
8856 struct got_update_progress_arg upa;
8857 if (!rebase_in_progress) {
8858 error = got_error(GOT_ERR_NOT_REBASING);
8859 goto done;
8861 error = got_worktree_rebase_continue(&resume_commit_id,
8862 &new_base_branch, &tmp_branch, &branch, &fileindex,
8863 worktree, repo);
8864 if (error)
8865 goto done;
8866 printf("Switching work tree to %s\n",
8867 got_ref_get_symref_target(new_base_branch));
8868 memset(&upa, 0, sizeof(upa));
8869 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8870 new_base_branch, update_progress, &upa);
8871 if (error)
8872 goto done;
8873 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8874 print_update_progress_stats(&upa);
8875 goto done; /* nothing else to do */
8878 if (continue_rebase) {
8879 if (!rebase_in_progress) {
8880 error = got_error(GOT_ERR_NOT_REBASING);
8881 goto done;
8883 error = got_worktree_rebase_continue(&resume_commit_id,
8884 &new_base_branch, &tmp_branch, &branch, &fileindex,
8885 worktree, repo);
8886 if (error)
8887 goto done;
8889 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8890 resume_commit_id, repo);
8891 if (error)
8892 goto done;
8894 yca_id = got_object_id_dup(resume_commit_id);
8895 if (yca_id == NULL) {
8896 error = got_error_from_errno("got_object_id_dup");
8897 goto done;
8899 } else {
8900 error = got_ref_open(&branch, repo, argv[0], 0);
8901 if (error != NULL)
8902 goto done;
8905 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8906 if (error)
8907 goto done;
8909 if (!continue_rebase) {
8910 struct got_object_id *base_commit_id;
8912 base_commit_id = got_worktree_get_base_commit_id(worktree);
8913 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8914 base_commit_id, branch_head_commit_id, repo,
8915 check_cancelled, NULL);
8916 if (error)
8917 goto done;
8918 if (yca_id == NULL) {
8919 error = got_error_msg(GOT_ERR_ANCESTRY,
8920 "specified branch shares no common ancestry "
8921 "with work tree's branch");
8922 goto done;
8925 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8926 if (error) {
8927 if (error->code != GOT_ERR_ANCESTRY)
8928 goto done;
8929 error = NULL;
8930 } else {
8931 static char msg[128];
8932 snprintf(msg, sizeof(msg),
8933 "%s is already based on %s",
8934 got_ref_get_name(branch),
8935 got_worktree_get_head_ref_name(worktree));
8936 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8937 goto done;
8939 error = got_worktree_rebase_prepare(&new_base_branch,
8940 &tmp_branch, &fileindex, worktree, branch, repo);
8941 if (error)
8942 goto done;
8945 commit_id = branch_head_commit_id;
8946 error = got_object_open_as_commit(&commit, repo, commit_id);
8947 if (error)
8948 goto done;
8950 parent_ids = got_object_commit_get_parent_ids(commit);
8951 pid = STAILQ_FIRST(parent_ids);
8952 if (pid == NULL) {
8953 if (!continue_rebase) {
8954 struct got_update_progress_arg upa;
8955 memset(&upa, 0, sizeof(upa));
8956 error = got_worktree_rebase_abort(worktree, fileindex,
8957 repo, new_base_branch, update_progress, &upa);
8958 if (error)
8959 goto done;
8960 printf("Rebase of %s aborted\n",
8961 got_ref_get_name(branch));
8962 print_update_progress_stats(&upa);
8965 error = got_error(GOT_ERR_EMPTY_REBASE);
8966 goto done;
8968 error = collect_commits(&commits, commit_id, pid->id,
8969 yca_id, got_worktree_get_path_prefix(worktree),
8970 GOT_ERR_REBASE_PATH, repo);
8971 got_object_commit_close(commit);
8972 commit = NULL;
8973 if (error)
8974 goto done;
8976 if (STAILQ_EMPTY(&commits)) {
8977 if (continue_rebase) {
8978 error = rebase_complete(worktree, fileindex,
8979 branch, new_base_branch, tmp_branch, repo,
8980 create_backup);
8981 goto done;
8982 } else {
8983 /* Fast-forward the reference of the branch. */
8984 struct got_object_id *new_head_commit_id;
8985 char *id_str;
8986 error = got_ref_resolve(&new_head_commit_id, repo,
8987 new_base_branch);
8988 if (error)
8989 goto done;
8990 error = got_object_id_str(&id_str, new_head_commit_id);
8991 printf("Forwarding %s to commit %s\n",
8992 got_ref_get_name(branch), id_str);
8993 free(id_str);
8994 error = got_ref_change_ref(branch,
8995 new_head_commit_id);
8996 if (error)
8997 goto done;
8998 /* No backup needed since objects did not change. */
8999 create_backup = 0;
9003 pid = NULL;
9004 STAILQ_FOREACH(qid, &commits, entry) {
9005 struct got_update_progress_arg upa;
9007 commit_id = qid->id;
9008 parent_id = pid ? pid->id : yca_id;
9009 pid = qid;
9011 memset(&upa, 0, sizeof(upa));
9012 error = got_worktree_rebase_merge_files(&merged_paths,
9013 worktree, fileindex, parent_id, commit_id, repo,
9014 update_progress, &upa, check_cancelled, NULL);
9015 if (error)
9016 goto done;
9018 print_update_progress_stats(&upa);
9019 if (upa.conflicts > 0)
9020 rebase_status = GOT_STATUS_CONFLICT;
9022 if (rebase_status == GOT_STATUS_CONFLICT) {
9023 error = show_rebase_merge_conflict(qid->id, repo);
9024 if (error)
9025 goto done;
9026 got_worktree_rebase_pathlist_free(&merged_paths);
9027 break;
9030 error = rebase_commit(&merged_paths, worktree, fileindex,
9031 tmp_branch, commit_id, repo);
9032 got_worktree_rebase_pathlist_free(&merged_paths);
9033 if (error)
9034 goto done;
9037 if (rebase_status == GOT_STATUS_CONFLICT) {
9038 error = got_worktree_rebase_postpone(worktree, fileindex);
9039 if (error)
9040 goto done;
9041 error = got_error_msg(GOT_ERR_CONFLICTS,
9042 "conflicts must be resolved before rebasing can continue");
9043 } else
9044 error = rebase_complete(worktree, fileindex, branch,
9045 new_base_branch, tmp_branch, repo, create_backup);
9046 done:
9047 got_object_id_queue_free(&commits);
9048 free(branch_head_commit_id);
9049 free(resume_commit_id);
9050 free(yca_id);
9051 if (commit)
9052 got_object_commit_close(commit);
9053 if (branch)
9054 got_ref_close(branch);
9055 if (new_base_branch)
9056 got_ref_close(new_base_branch);
9057 if (tmp_branch)
9058 got_ref_close(tmp_branch);
9059 if (worktree)
9060 got_worktree_close(worktree);
9061 if (repo) {
9062 const struct got_error *close_err = got_repo_close(repo);
9063 if (error == NULL)
9064 error = close_err;
9066 return error;
9069 __dead static void
9070 usage_histedit(void)
9072 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
9073 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9074 getprogname());
9075 exit(1);
9078 #define GOT_HISTEDIT_PICK 'p'
9079 #define GOT_HISTEDIT_EDIT 'e'
9080 #define GOT_HISTEDIT_FOLD 'f'
9081 #define GOT_HISTEDIT_DROP 'd'
9082 #define GOT_HISTEDIT_MESG 'm'
9084 static struct got_histedit_cmd {
9085 unsigned char code;
9086 const char *name;
9087 const char *desc;
9088 } got_histedit_cmds[] = {
9089 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9090 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9091 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9092 "be used" },
9093 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9094 { GOT_HISTEDIT_MESG, "mesg",
9095 "single-line log message for commit above (open editor if empty)" },
9098 struct got_histedit_list_entry {
9099 TAILQ_ENTRY(got_histedit_list_entry) entry;
9100 struct got_object_id *commit_id;
9101 const struct got_histedit_cmd *cmd;
9102 char *logmsg;
9104 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9106 static const struct got_error *
9107 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9108 FILE *f, struct got_repository *repo)
9110 const struct got_error *err = NULL;
9111 char *logmsg = NULL, *id_str = NULL;
9112 struct got_commit_object *commit = NULL;
9113 int n;
9115 err = got_object_open_as_commit(&commit, repo, commit_id);
9116 if (err)
9117 goto done;
9119 err = get_short_logmsg(&logmsg, 34, commit);
9120 if (err)
9121 goto done;
9123 err = got_object_id_str(&id_str, commit_id);
9124 if (err)
9125 goto done;
9127 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9128 if (n < 0)
9129 err = got_ferror(f, GOT_ERR_IO);
9130 done:
9131 if (commit)
9132 got_object_commit_close(commit);
9133 free(id_str);
9134 free(logmsg);
9135 return err;
9138 static const struct got_error *
9139 histedit_write_commit_list(struct got_object_id_queue *commits,
9140 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9142 const struct got_error *err = NULL;
9143 struct got_object_qid *qid;
9144 const char *histedit_cmd = NULL;
9146 if (STAILQ_EMPTY(commits))
9147 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9149 STAILQ_FOREACH(qid, commits, entry) {
9150 histedit_cmd = got_histedit_cmds[0].name;
9151 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9152 histedit_cmd = "fold";
9153 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9154 if (err)
9155 break;
9156 if (edit_logmsg_only) {
9157 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9158 if (n < 0) {
9159 err = got_ferror(f, GOT_ERR_IO);
9160 break;
9165 return err;
9168 static const struct got_error *
9169 write_cmd_list(FILE *f, const char *branch_name,
9170 struct got_object_id_queue *commits)
9172 const struct got_error *err = NULL;
9173 size_t i;
9174 int n;
9175 char *id_str;
9176 struct got_object_qid *qid;
9178 qid = STAILQ_FIRST(commits);
9179 err = got_object_id_str(&id_str, qid->id);
9180 if (err)
9181 return err;
9183 n = fprintf(f,
9184 "# Editing the history of branch '%s' starting at\n"
9185 "# commit %s\n"
9186 "# Commits will be processed in order from top to "
9187 "bottom of this file.\n", branch_name, id_str);
9188 if (n < 0) {
9189 err = got_ferror(f, GOT_ERR_IO);
9190 goto done;
9193 n = fprintf(f, "# Available histedit commands:\n");
9194 if (n < 0) {
9195 err = got_ferror(f, GOT_ERR_IO);
9196 goto done;
9199 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9200 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9201 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9202 cmd->desc);
9203 if (n < 0) {
9204 err = got_ferror(f, GOT_ERR_IO);
9205 break;
9208 done:
9209 free(id_str);
9210 return err;
9213 static const struct got_error *
9214 histedit_syntax_error(int lineno)
9216 static char msg[42];
9217 int ret;
9219 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9220 lineno);
9221 if (ret == -1 || ret >= sizeof(msg))
9222 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9224 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9227 static const struct got_error *
9228 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9229 char *logmsg, struct got_repository *repo)
9231 const struct got_error *err;
9232 struct got_commit_object *folded_commit = NULL;
9233 char *id_str, *folded_logmsg = NULL;
9235 err = got_object_id_str(&id_str, hle->commit_id);
9236 if (err)
9237 return err;
9239 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9240 if (err)
9241 goto done;
9243 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9244 if (err)
9245 goto done;
9246 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9247 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9248 folded_logmsg) == -1) {
9249 err = got_error_from_errno("asprintf");
9251 done:
9252 if (folded_commit)
9253 got_object_commit_close(folded_commit);
9254 free(id_str);
9255 free(folded_logmsg);
9256 return err;
9259 static struct got_histedit_list_entry *
9260 get_folded_commits(struct got_histedit_list_entry *hle)
9262 struct got_histedit_list_entry *prev, *folded = NULL;
9264 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9265 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9266 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9267 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9268 folded = prev;
9269 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9272 return folded;
9275 static const struct got_error *
9276 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9277 struct got_repository *repo)
9279 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9280 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9281 const struct got_error *err = NULL;
9282 struct got_commit_object *commit = NULL;
9283 int logmsg_len;
9284 int fd;
9285 struct got_histedit_list_entry *folded = NULL;
9287 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9288 if (err)
9289 return err;
9291 folded = get_folded_commits(hle);
9292 if (folded) {
9293 while (folded != hle) {
9294 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9295 folded = TAILQ_NEXT(folded, entry);
9296 continue;
9298 err = append_folded_commit_msg(&new_msg, folded,
9299 logmsg, repo);
9300 if (err)
9301 goto done;
9302 free(logmsg);
9303 logmsg = new_msg;
9304 folded = TAILQ_NEXT(folded, entry);
9308 err = got_object_id_str(&id_str, hle->commit_id);
9309 if (err)
9310 goto done;
9311 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9312 if (err)
9313 goto done;
9314 logmsg_len = asprintf(&new_msg,
9315 "%s\n# original log message of commit %s: %s",
9316 logmsg ? logmsg : "", id_str, orig_logmsg);
9317 if (logmsg_len == -1) {
9318 err = got_error_from_errno("asprintf");
9319 goto done;
9321 free(logmsg);
9322 logmsg = new_msg;
9324 err = got_object_id_str(&id_str, hle->commit_id);
9325 if (err)
9326 goto done;
9328 err = got_opentemp_named_fd(&logmsg_path, &fd,
9329 GOT_TMPDIR_STR "/got-logmsg");
9330 if (err)
9331 goto done;
9333 write(fd, logmsg, logmsg_len);
9334 close(fd);
9336 err = get_editor(&editor);
9337 if (err)
9338 goto done;
9340 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9341 logmsg_len, 0);
9342 if (err) {
9343 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9344 goto done;
9345 err = NULL;
9346 hle->logmsg = strdup(new_msg);
9347 if (hle->logmsg == NULL)
9348 err = got_error_from_errno("strdup");
9350 done:
9351 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9352 err = got_error_from_errno2("unlink", logmsg_path);
9353 free(logmsg_path);
9354 free(logmsg);
9355 free(orig_logmsg);
9356 free(editor);
9357 if (commit)
9358 got_object_commit_close(commit);
9359 return err;
9362 static const struct got_error *
9363 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9364 FILE *f, struct got_repository *repo)
9366 const struct got_error *err = NULL;
9367 char *line = NULL, *p, *end;
9368 size_t i, size;
9369 ssize_t len;
9370 int lineno = 0;
9371 const struct got_histedit_cmd *cmd;
9372 struct got_object_id *commit_id = NULL;
9373 struct got_histedit_list_entry *hle = NULL;
9375 for (;;) {
9376 len = getline(&line, &size, f);
9377 if (len == -1) {
9378 const struct got_error *getline_err;
9379 if (feof(f))
9380 break;
9381 getline_err = got_error_from_errno("getline");
9382 err = got_ferror(f, getline_err->code);
9383 break;
9385 lineno++;
9386 p = line;
9387 while (isspace((unsigned char)p[0]))
9388 p++;
9389 if (p[0] == '#' || p[0] == '\0') {
9390 free(line);
9391 line = NULL;
9392 continue;
9394 cmd = NULL;
9395 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9396 cmd = &got_histedit_cmds[i];
9397 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9398 isspace((unsigned char)p[strlen(cmd->name)])) {
9399 p += strlen(cmd->name);
9400 break;
9402 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9403 p++;
9404 break;
9407 if (i == nitems(got_histedit_cmds)) {
9408 err = histedit_syntax_error(lineno);
9409 break;
9411 while (isspace((unsigned char)p[0]))
9412 p++;
9413 if (cmd->code == GOT_HISTEDIT_MESG) {
9414 if (hle == NULL || hle->logmsg != NULL) {
9415 err = got_error(GOT_ERR_HISTEDIT_CMD);
9416 break;
9418 if (p[0] == '\0') {
9419 err = histedit_edit_logmsg(hle, repo);
9420 if (err)
9421 break;
9422 } else {
9423 hle->logmsg = strdup(p);
9424 if (hle->logmsg == NULL) {
9425 err = got_error_from_errno("strdup");
9426 break;
9429 free(line);
9430 line = NULL;
9431 continue;
9432 } else {
9433 end = p;
9434 while (end[0] && !isspace((unsigned char)end[0]))
9435 end++;
9436 *end = '\0';
9438 err = got_object_resolve_id_str(&commit_id, repo, p);
9439 if (err) {
9440 /* override error code */
9441 err = histedit_syntax_error(lineno);
9442 break;
9445 hle = malloc(sizeof(*hle));
9446 if (hle == NULL) {
9447 err = got_error_from_errno("malloc");
9448 break;
9450 hle->cmd = cmd;
9451 hle->commit_id = commit_id;
9452 hle->logmsg = NULL;
9453 commit_id = NULL;
9454 free(line);
9455 line = NULL;
9456 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9459 free(line);
9460 free(commit_id);
9461 return err;
9464 static const struct got_error *
9465 histedit_check_script(struct got_histedit_list *histedit_cmds,
9466 struct got_object_id_queue *commits, struct got_repository *repo)
9468 const struct got_error *err = NULL;
9469 struct got_object_qid *qid;
9470 struct got_histedit_list_entry *hle;
9471 static char msg[92];
9472 char *id_str;
9474 if (TAILQ_EMPTY(histedit_cmds))
9475 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9476 "histedit script contains no commands");
9477 if (STAILQ_EMPTY(commits))
9478 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9480 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9481 struct got_histedit_list_entry *hle2;
9482 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9483 if (hle == hle2)
9484 continue;
9485 if (got_object_id_cmp(hle->commit_id,
9486 hle2->commit_id) != 0)
9487 continue;
9488 err = got_object_id_str(&id_str, hle->commit_id);
9489 if (err)
9490 return err;
9491 snprintf(msg, sizeof(msg), "commit %s is listed "
9492 "more than once in histedit script", id_str);
9493 free(id_str);
9494 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9498 STAILQ_FOREACH(qid, commits, entry) {
9499 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9500 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9501 break;
9503 if (hle == NULL) {
9504 err = got_object_id_str(&id_str, qid->id);
9505 if (err)
9506 return err;
9507 snprintf(msg, sizeof(msg),
9508 "commit %s missing from histedit script", id_str);
9509 free(id_str);
9510 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9514 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9515 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9516 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9517 "last commit in histedit script cannot be folded");
9519 return NULL;
9522 static const struct got_error *
9523 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9524 const char *path, struct got_object_id_queue *commits,
9525 struct got_repository *repo)
9527 const struct got_error *err = NULL;
9528 char *editor;
9529 FILE *f = NULL;
9531 err = get_editor(&editor);
9532 if (err)
9533 return err;
9535 if (spawn_editor(editor, path) == -1) {
9536 err = got_error_from_errno("failed spawning editor");
9537 goto done;
9540 f = fopen(path, "r");
9541 if (f == NULL) {
9542 err = got_error_from_errno("fopen");
9543 goto done;
9545 err = histedit_parse_list(histedit_cmds, f, repo);
9546 if (err)
9547 goto done;
9549 err = histedit_check_script(histedit_cmds, commits, repo);
9550 done:
9551 if (f && fclose(f) == EOF && err == NULL)
9552 err = got_error_from_errno("fclose");
9553 free(editor);
9554 return err;
9557 static const struct got_error *
9558 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9559 struct got_object_id_queue *, const char *, const char *,
9560 struct got_repository *);
9562 static const struct got_error *
9563 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9564 struct got_object_id_queue *commits, const char *branch_name,
9565 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9567 const struct got_error *err;
9568 FILE *f = NULL;
9569 char *path = NULL;
9571 err = got_opentemp_named(&path, &f, "got-histedit");
9572 if (err)
9573 return err;
9575 err = write_cmd_list(f, branch_name, commits);
9576 if (err)
9577 goto done;
9579 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9580 fold_only, repo);
9581 if (err)
9582 goto done;
9584 if (edit_logmsg_only || fold_only) {
9585 rewind(f);
9586 err = histedit_parse_list(histedit_cmds, f, repo);
9587 } else {
9588 if (fclose(f) == EOF) {
9589 err = got_error_from_errno("fclose");
9590 goto done;
9592 f = NULL;
9593 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9594 if (err) {
9595 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9596 err->code != GOT_ERR_HISTEDIT_CMD)
9597 goto done;
9598 err = histedit_edit_list_retry(histedit_cmds, err,
9599 commits, path, branch_name, repo);
9602 done:
9603 if (f && fclose(f) == EOF && err == NULL)
9604 err = got_error_from_errno("fclose");
9605 if (path && unlink(path) != 0 && err == NULL)
9606 err = got_error_from_errno2("unlink", path);
9607 free(path);
9608 return err;
9611 static const struct got_error *
9612 histedit_save_list(struct got_histedit_list *histedit_cmds,
9613 struct got_worktree *worktree, struct got_repository *repo)
9615 const struct got_error *err = NULL;
9616 char *path = NULL;
9617 FILE *f = NULL;
9618 struct got_histedit_list_entry *hle;
9619 struct got_commit_object *commit = NULL;
9621 err = got_worktree_get_histedit_script_path(&path, worktree);
9622 if (err)
9623 return err;
9625 f = fopen(path, "w");
9626 if (f == NULL) {
9627 err = got_error_from_errno2("fopen", path);
9628 goto done;
9630 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9631 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9632 repo);
9633 if (err)
9634 break;
9636 if (hle->logmsg) {
9637 int n = fprintf(f, "%c %s\n",
9638 GOT_HISTEDIT_MESG, hle->logmsg);
9639 if (n < 0) {
9640 err = got_ferror(f, GOT_ERR_IO);
9641 break;
9645 done:
9646 if (f && fclose(f) == EOF && err == NULL)
9647 err = got_error_from_errno("fclose");
9648 free(path);
9649 if (commit)
9650 got_object_commit_close(commit);
9651 return err;
9654 void
9655 histedit_free_list(struct got_histedit_list *histedit_cmds)
9657 struct got_histedit_list_entry *hle;
9659 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9660 TAILQ_REMOVE(histedit_cmds, hle, entry);
9661 free(hle);
9665 static const struct got_error *
9666 histedit_load_list(struct got_histedit_list *histedit_cmds,
9667 const char *path, struct got_repository *repo)
9669 const struct got_error *err = NULL;
9670 FILE *f = NULL;
9672 f = fopen(path, "r");
9673 if (f == NULL) {
9674 err = got_error_from_errno2("fopen", path);
9675 goto done;
9678 err = histedit_parse_list(histedit_cmds, f, repo);
9679 done:
9680 if (f && fclose(f) == EOF && err == NULL)
9681 err = got_error_from_errno("fclose");
9682 return err;
9685 static const struct got_error *
9686 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9687 const struct got_error *edit_err, struct got_object_id_queue *commits,
9688 const char *path, const char *branch_name, struct got_repository *repo)
9690 const struct got_error *err = NULL, *prev_err = edit_err;
9691 int resp = ' ';
9693 while (resp != 'c' && resp != 'r' && resp != 'a') {
9694 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9695 "or (a)bort: ", getprogname(), prev_err->msg);
9696 resp = getchar();
9697 if (resp == '\n')
9698 resp = getchar();
9699 if (resp == 'c') {
9700 histedit_free_list(histedit_cmds);
9701 err = histedit_run_editor(histedit_cmds, path, commits,
9702 repo);
9703 if (err) {
9704 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9705 err->code != GOT_ERR_HISTEDIT_CMD)
9706 break;
9707 prev_err = err;
9708 resp = ' ';
9709 continue;
9711 break;
9712 } else if (resp == 'r') {
9713 histedit_free_list(histedit_cmds);
9714 err = histedit_edit_script(histedit_cmds,
9715 commits, branch_name, 0, 0, repo);
9716 if (err) {
9717 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9718 err->code != GOT_ERR_HISTEDIT_CMD)
9719 break;
9720 prev_err = err;
9721 resp = ' ';
9722 continue;
9724 break;
9725 } else if (resp == 'a') {
9726 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9727 break;
9728 } else
9729 printf("invalid response '%c'\n", resp);
9732 return err;
9735 static const struct got_error *
9736 histedit_complete(struct got_worktree *worktree,
9737 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9738 struct got_reference *branch, struct got_repository *repo)
9740 printf("Switching work tree to %s\n",
9741 got_ref_get_symref_target(branch));
9742 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9743 branch, repo);
9746 static const struct got_error *
9747 show_histedit_progress(struct got_commit_object *commit,
9748 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9750 const struct got_error *err;
9751 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9753 err = got_object_id_str(&old_id_str, hle->commit_id);
9754 if (err)
9755 goto done;
9757 if (new_id) {
9758 err = got_object_id_str(&new_id_str, new_id);
9759 if (err)
9760 goto done;
9763 old_id_str[12] = '\0';
9764 if (new_id_str)
9765 new_id_str[12] = '\0';
9767 if (hle->logmsg) {
9768 logmsg = strdup(hle->logmsg);
9769 if (logmsg == NULL) {
9770 err = got_error_from_errno("strdup");
9771 goto done;
9773 trim_logmsg(logmsg, 42);
9774 } else {
9775 err = get_short_logmsg(&logmsg, 42, commit);
9776 if (err)
9777 goto done;
9780 switch (hle->cmd->code) {
9781 case GOT_HISTEDIT_PICK:
9782 case GOT_HISTEDIT_EDIT:
9783 printf("%s -> %s: %s\n", old_id_str,
9784 new_id_str ? new_id_str : "no-op change", logmsg);
9785 break;
9786 case GOT_HISTEDIT_DROP:
9787 case GOT_HISTEDIT_FOLD:
9788 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9789 logmsg);
9790 break;
9791 default:
9792 break;
9794 done:
9795 free(old_id_str);
9796 free(new_id_str);
9797 return err;
9800 static const struct got_error *
9801 histedit_commit(struct got_pathlist_head *merged_paths,
9802 struct got_worktree *worktree, struct got_fileindex *fileindex,
9803 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9804 struct got_repository *repo)
9806 const struct got_error *err;
9807 struct got_commit_object *commit;
9808 struct got_object_id *new_commit_id;
9810 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9811 && hle->logmsg == NULL) {
9812 err = histedit_edit_logmsg(hle, repo);
9813 if (err)
9814 return err;
9817 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9818 if (err)
9819 return err;
9821 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9822 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9823 hle->logmsg, repo);
9824 if (err) {
9825 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9826 goto done;
9827 err = show_histedit_progress(commit, hle, NULL);
9828 } else {
9829 err = show_histedit_progress(commit, hle, new_commit_id);
9830 free(new_commit_id);
9832 done:
9833 got_object_commit_close(commit);
9834 return err;
9837 static const struct got_error *
9838 histedit_skip_commit(struct got_histedit_list_entry *hle,
9839 struct got_worktree *worktree, struct got_repository *repo)
9841 const struct got_error *error;
9842 struct got_commit_object *commit;
9844 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9845 repo);
9846 if (error)
9847 return error;
9849 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9850 if (error)
9851 return error;
9853 error = show_histedit_progress(commit, hle, NULL);
9854 got_object_commit_close(commit);
9855 return error;
9858 static const struct got_error *
9859 check_local_changes(void *arg, unsigned char status,
9860 unsigned char staged_status, const char *path,
9861 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9862 struct got_object_id *commit_id, int dirfd, const char *de_name)
9864 int *have_local_changes = arg;
9866 switch (status) {
9867 case GOT_STATUS_ADD:
9868 case GOT_STATUS_DELETE:
9869 case GOT_STATUS_MODIFY:
9870 case GOT_STATUS_CONFLICT:
9871 *have_local_changes = 1;
9872 return got_error(GOT_ERR_CANCELLED);
9873 default:
9874 break;
9877 switch (staged_status) {
9878 case GOT_STATUS_ADD:
9879 case GOT_STATUS_DELETE:
9880 case GOT_STATUS_MODIFY:
9881 *have_local_changes = 1;
9882 return got_error(GOT_ERR_CANCELLED);
9883 default:
9884 break;
9887 return NULL;
9890 static const struct got_error *
9891 cmd_histedit(int argc, char *argv[])
9893 const struct got_error *error = NULL;
9894 struct got_worktree *worktree = NULL;
9895 struct got_fileindex *fileindex = NULL;
9896 struct got_repository *repo = NULL;
9897 char *cwd = NULL;
9898 struct got_reference *branch = NULL;
9899 struct got_reference *tmp_branch = NULL;
9900 struct got_object_id *resume_commit_id = NULL;
9901 struct got_object_id *base_commit_id = NULL;
9902 struct got_object_id *head_commit_id = NULL;
9903 struct got_commit_object *commit = NULL;
9904 int ch, rebase_in_progress = 0;
9905 struct got_update_progress_arg upa;
9906 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9907 int edit_logmsg_only = 0, fold_only = 0;
9908 int list_backups = 0, delete_backups = 0;
9909 const char *edit_script_path = NULL;
9910 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9911 struct got_object_id_queue commits;
9912 struct got_pathlist_head merged_paths;
9913 const struct got_object_id_queue *parent_ids;
9914 struct got_object_qid *pid;
9915 struct got_histedit_list histedit_cmds;
9916 struct got_histedit_list_entry *hle;
9918 STAILQ_INIT(&commits);
9919 TAILQ_INIT(&histedit_cmds);
9920 TAILQ_INIT(&merged_paths);
9921 memset(&upa, 0, sizeof(upa));
9923 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9924 switch (ch) {
9925 case 'a':
9926 abort_edit = 1;
9927 break;
9928 case 'c':
9929 continue_edit = 1;
9930 break;
9931 case 'f':
9932 fold_only = 1;
9933 break;
9934 case 'F':
9935 edit_script_path = optarg;
9936 break;
9937 case 'm':
9938 edit_logmsg_only = 1;
9939 break;
9940 case 'l':
9941 list_backups = 1;
9942 break;
9943 case 'X':
9944 delete_backups = 1;
9945 break;
9946 default:
9947 usage_histedit();
9948 /* NOTREACHED */
9952 argc -= optind;
9953 argv += optind;
9955 #ifndef PROFILE
9956 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9957 "unveil", NULL) == -1)
9958 err(1, "pledge");
9959 #endif
9960 if (abort_edit && continue_edit)
9961 option_conflict('a', 'c');
9962 if (edit_script_path && edit_logmsg_only)
9963 option_conflict('F', 'm');
9964 if (abort_edit && edit_logmsg_only)
9965 option_conflict('a', 'm');
9966 if (continue_edit && edit_logmsg_only)
9967 option_conflict('c', 'm');
9968 if (abort_edit && fold_only)
9969 option_conflict('a', 'f');
9970 if (continue_edit && fold_only)
9971 option_conflict('c', 'f');
9972 if (fold_only && edit_logmsg_only)
9973 option_conflict('f', 'm');
9974 if (edit_script_path && fold_only)
9975 option_conflict('F', 'f');
9976 if (list_backups) {
9977 if (abort_edit)
9978 option_conflict('l', 'a');
9979 if (continue_edit)
9980 option_conflict('l', 'c');
9981 if (edit_script_path)
9982 option_conflict('l', 'F');
9983 if (edit_logmsg_only)
9984 option_conflict('l', 'm');
9985 if (fold_only)
9986 option_conflict('l', 'f');
9987 if (delete_backups)
9988 option_conflict('l', 'X');
9989 if (argc != 0 && argc != 1)
9990 usage_histedit();
9991 } else if (delete_backups) {
9992 if (abort_edit)
9993 option_conflict('X', 'a');
9994 if (continue_edit)
9995 option_conflict('X', 'c');
9996 if (edit_script_path)
9997 option_conflict('X', 'F');
9998 if (edit_logmsg_only)
9999 option_conflict('X', 'm');
10000 if (fold_only)
10001 option_conflict('X', 'f');
10002 if (list_backups)
10003 option_conflict('X', 'l');
10004 if (argc != 0 && argc != 1)
10005 usage_histedit();
10006 } else if (argc != 0)
10007 usage_histedit();
10010 * This command cannot apply unveil(2) in all cases because the
10011 * user may choose to run an editor to edit the histedit script
10012 * and to edit individual commit log messages.
10013 * unveil(2) traverses exec(2); if an editor is used we have to
10014 * apply unveil after edit script and log messages have been written.
10015 * XXX TODO: Make use of unveil(2) where possible.
10018 cwd = getcwd(NULL, 0);
10019 if (cwd == NULL) {
10020 error = got_error_from_errno("getcwd");
10021 goto done;
10023 error = got_worktree_open(&worktree, cwd);
10024 if (error) {
10025 if (list_backups || delete_backups) {
10026 if (error->code != GOT_ERR_NOT_WORKTREE)
10027 goto done;
10028 } else {
10029 if (error->code == GOT_ERR_NOT_WORKTREE)
10030 error = wrap_not_worktree_error(error,
10031 "histedit", cwd);
10032 goto done;
10036 if (list_backups || delete_backups) {
10037 error = got_repo_open(&repo,
10038 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10039 NULL);
10040 if (error != NULL)
10041 goto done;
10042 error = apply_unveil(got_repo_get_path(repo), 0,
10043 worktree ? got_worktree_get_root_path(worktree) : NULL);
10044 if (error)
10045 goto done;
10046 error = process_backup_refs(
10047 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10048 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10049 goto done; /* nothing else to do */
10052 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10053 NULL);
10054 if (error != NULL)
10055 goto done;
10057 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10058 if (error)
10059 goto done;
10060 if (rebase_in_progress) {
10061 error = got_error(GOT_ERR_REBASING);
10062 goto done;
10065 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10066 if (error)
10067 goto done;
10069 if (edit_in_progress && edit_logmsg_only) {
10070 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10071 "histedit operation is in progress in this "
10072 "work tree and must be continued or aborted "
10073 "before the -m option can be used");
10074 goto done;
10076 if (edit_in_progress && fold_only) {
10077 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10078 "histedit operation is in progress in this "
10079 "work tree and must be continued or aborted "
10080 "before the -f option can be used");
10081 goto done;
10084 if (edit_in_progress && abort_edit) {
10085 error = got_worktree_histedit_continue(&resume_commit_id,
10086 &tmp_branch, &branch, &base_commit_id, &fileindex,
10087 worktree, repo);
10088 if (error)
10089 goto done;
10090 printf("Switching work tree to %s\n",
10091 got_ref_get_symref_target(branch));
10092 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10093 branch, base_commit_id, update_progress, &upa);
10094 if (error)
10095 goto done;
10096 printf("Histedit of %s aborted\n",
10097 got_ref_get_symref_target(branch));
10098 print_update_progress_stats(&upa);
10099 goto done; /* nothing else to do */
10100 } else if (abort_edit) {
10101 error = got_error(GOT_ERR_NOT_HISTEDIT);
10102 goto done;
10105 if (continue_edit) {
10106 char *path;
10108 if (!edit_in_progress) {
10109 error = got_error(GOT_ERR_NOT_HISTEDIT);
10110 goto done;
10113 error = got_worktree_get_histedit_script_path(&path, worktree);
10114 if (error)
10115 goto done;
10117 error = histedit_load_list(&histedit_cmds, path, repo);
10118 free(path);
10119 if (error)
10120 goto done;
10122 error = got_worktree_histedit_continue(&resume_commit_id,
10123 &tmp_branch, &branch, &base_commit_id, &fileindex,
10124 worktree, repo);
10125 if (error)
10126 goto done;
10128 error = got_ref_resolve(&head_commit_id, repo, branch);
10129 if (error)
10130 goto done;
10132 error = got_object_open_as_commit(&commit, repo,
10133 head_commit_id);
10134 if (error)
10135 goto done;
10136 parent_ids = got_object_commit_get_parent_ids(commit);
10137 pid = STAILQ_FIRST(parent_ids);
10138 if (pid == NULL) {
10139 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10140 goto done;
10142 error = collect_commits(&commits, head_commit_id, pid->id,
10143 base_commit_id, got_worktree_get_path_prefix(worktree),
10144 GOT_ERR_HISTEDIT_PATH, repo);
10145 got_object_commit_close(commit);
10146 commit = NULL;
10147 if (error)
10148 goto done;
10149 } else {
10150 if (edit_in_progress) {
10151 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10152 goto done;
10155 error = got_ref_open(&branch, repo,
10156 got_worktree_get_head_ref_name(worktree), 0);
10157 if (error != NULL)
10158 goto done;
10160 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10161 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10162 "will not edit commit history of a branch outside "
10163 "the \"refs/heads/\" reference namespace");
10164 goto done;
10167 error = got_ref_resolve(&head_commit_id, repo, branch);
10168 got_ref_close(branch);
10169 branch = NULL;
10170 if (error)
10171 goto done;
10173 error = got_object_open_as_commit(&commit, repo,
10174 head_commit_id);
10175 if (error)
10176 goto done;
10177 parent_ids = got_object_commit_get_parent_ids(commit);
10178 pid = STAILQ_FIRST(parent_ids);
10179 if (pid == NULL) {
10180 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10181 goto done;
10183 error = collect_commits(&commits, head_commit_id, pid->id,
10184 got_worktree_get_base_commit_id(worktree),
10185 got_worktree_get_path_prefix(worktree),
10186 GOT_ERR_HISTEDIT_PATH, repo);
10187 got_object_commit_close(commit);
10188 commit = NULL;
10189 if (error)
10190 goto done;
10192 if (STAILQ_EMPTY(&commits)) {
10193 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10194 goto done;
10197 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10198 &base_commit_id, &fileindex, worktree, repo);
10199 if (error)
10200 goto done;
10202 if (edit_script_path) {
10203 error = histedit_load_list(&histedit_cmds,
10204 edit_script_path, repo);
10205 if (error) {
10206 got_worktree_histedit_abort(worktree, fileindex,
10207 repo, branch, base_commit_id,
10208 update_progress, &upa);
10209 print_update_progress_stats(&upa);
10210 goto done;
10212 } else {
10213 const char *branch_name;
10214 branch_name = got_ref_get_symref_target(branch);
10215 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10216 branch_name += 11;
10217 error = histedit_edit_script(&histedit_cmds, &commits,
10218 branch_name, edit_logmsg_only, fold_only, repo);
10219 if (error) {
10220 got_worktree_histedit_abort(worktree, fileindex,
10221 repo, branch, base_commit_id,
10222 update_progress, &upa);
10223 print_update_progress_stats(&upa);
10224 goto done;
10229 error = histedit_save_list(&histedit_cmds, worktree,
10230 repo);
10231 if (error) {
10232 got_worktree_histedit_abort(worktree, fileindex,
10233 repo, branch, base_commit_id,
10234 update_progress, &upa);
10235 print_update_progress_stats(&upa);
10236 goto done;
10241 error = histedit_check_script(&histedit_cmds, &commits, repo);
10242 if (error)
10243 goto done;
10245 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10246 if (resume_commit_id) {
10247 if (got_object_id_cmp(hle->commit_id,
10248 resume_commit_id) != 0)
10249 continue;
10251 resume_commit_id = NULL;
10252 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10253 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10254 error = histedit_skip_commit(hle, worktree,
10255 repo);
10256 if (error)
10257 goto done;
10258 } else {
10259 struct got_pathlist_head paths;
10260 int have_changes = 0;
10262 TAILQ_INIT(&paths);
10263 error = got_pathlist_append(&paths, "", NULL);
10264 if (error)
10265 goto done;
10266 error = got_worktree_status(worktree, &paths,
10267 repo, 0, check_local_changes, &have_changes,
10268 check_cancelled, NULL);
10269 got_pathlist_free(&paths);
10270 if (error) {
10271 if (error->code != GOT_ERR_CANCELLED)
10272 goto done;
10273 if (sigint_received || sigpipe_received)
10274 goto done;
10276 if (have_changes) {
10277 error = histedit_commit(NULL, worktree,
10278 fileindex, tmp_branch, hle, repo);
10279 if (error)
10280 goto done;
10281 } else {
10282 error = got_object_open_as_commit(
10283 &commit, repo, hle->commit_id);
10284 if (error)
10285 goto done;
10286 error = show_histedit_progress(commit,
10287 hle, NULL);
10288 got_object_commit_close(commit);
10289 commit = NULL;
10290 if (error)
10291 goto done;
10294 continue;
10297 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10298 error = histedit_skip_commit(hle, worktree, repo);
10299 if (error)
10300 goto done;
10301 continue;
10304 error = got_object_open_as_commit(&commit, repo,
10305 hle->commit_id);
10306 if (error)
10307 goto done;
10308 parent_ids = got_object_commit_get_parent_ids(commit);
10309 pid = STAILQ_FIRST(parent_ids);
10311 error = got_worktree_histedit_merge_files(&merged_paths,
10312 worktree, fileindex, pid->id, hle->commit_id, repo,
10313 update_progress, &upa, check_cancelled, NULL);
10314 if (error)
10315 goto done;
10316 got_object_commit_close(commit);
10317 commit = NULL;
10319 print_update_progress_stats(&upa);
10320 if (upa.conflicts > 0)
10321 rebase_status = GOT_STATUS_CONFLICT;
10323 if (rebase_status == GOT_STATUS_CONFLICT) {
10324 error = show_rebase_merge_conflict(hle->commit_id,
10325 repo);
10326 if (error)
10327 goto done;
10328 got_worktree_rebase_pathlist_free(&merged_paths);
10329 break;
10332 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10333 char *id_str;
10334 error = got_object_id_str(&id_str, hle->commit_id);
10335 if (error)
10336 goto done;
10337 printf("Stopping histedit for amending commit %s\n",
10338 id_str);
10339 free(id_str);
10340 got_worktree_rebase_pathlist_free(&merged_paths);
10341 error = got_worktree_histedit_postpone(worktree,
10342 fileindex);
10343 goto done;
10346 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10347 error = histedit_skip_commit(hle, worktree, repo);
10348 if (error)
10349 goto done;
10350 continue;
10353 error = histedit_commit(&merged_paths, worktree, fileindex,
10354 tmp_branch, hle, repo);
10355 got_worktree_rebase_pathlist_free(&merged_paths);
10356 if (error)
10357 goto done;
10360 if (rebase_status == GOT_STATUS_CONFLICT) {
10361 error = got_worktree_histedit_postpone(worktree, fileindex);
10362 if (error)
10363 goto done;
10364 error = got_error_msg(GOT_ERR_CONFLICTS,
10365 "conflicts must be resolved before histedit can continue");
10366 } else
10367 error = histedit_complete(worktree, fileindex, tmp_branch,
10368 branch, repo);
10369 done:
10370 got_object_id_queue_free(&commits);
10371 histedit_free_list(&histedit_cmds);
10372 free(head_commit_id);
10373 free(base_commit_id);
10374 free(resume_commit_id);
10375 if (commit)
10376 got_object_commit_close(commit);
10377 if (branch)
10378 got_ref_close(branch);
10379 if (tmp_branch)
10380 got_ref_close(tmp_branch);
10381 if (worktree)
10382 got_worktree_close(worktree);
10383 if (repo) {
10384 const struct got_error *close_err = got_repo_close(repo);
10385 if (error == NULL)
10386 error = close_err;
10388 return error;
10391 __dead static void
10392 usage_integrate(void)
10394 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10395 exit(1);
10398 static const struct got_error *
10399 cmd_integrate(int argc, char *argv[])
10401 const struct got_error *error = NULL;
10402 struct got_repository *repo = NULL;
10403 struct got_worktree *worktree = NULL;
10404 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10405 const char *branch_arg = NULL;
10406 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10407 struct got_fileindex *fileindex = NULL;
10408 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10409 int ch;
10410 struct got_update_progress_arg upa;
10412 while ((ch = getopt(argc, argv, "")) != -1) {
10413 switch (ch) {
10414 default:
10415 usage_integrate();
10416 /* NOTREACHED */
10420 argc -= optind;
10421 argv += optind;
10423 if (argc != 1)
10424 usage_integrate();
10425 branch_arg = argv[0];
10426 #ifndef PROFILE
10427 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10428 "unveil", NULL) == -1)
10429 err(1, "pledge");
10430 #endif
10431 cwd = getcwd(NULL, 0);
10432 if (cwd == NULL) {
10433 error = got_error_from_errno("getcwd");
10434 goto done;
10437 error = got_worktree_open(&worktree, cwd);
10438 if (error) {
10439 if (error->code == GOT_ERR_NOT_WORKTREE)
10440 error = wrap_not_worktree_error(error, "integrate",
10441 cwd);
10442 goto done;
10445 error = check_rebase_or_histedit_in_progress(worktree);
10446 if (error)
10447 goto done;
10449 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10450 NULL);
10451 if (error != NULL)
10452 goto done;
10454 error = apply_unveil(got_repo_get_path(repo), 0,
10455 got_worktree_get_root_path(worktree));
10456 if (error)
10457 goto done;
10459 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10460 error = got_error_from_errno("asprintf");
10461 goto done;
10464 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10465 &base_branch_ref, worktree, refname, repo);
10466 if (error)
10467 goto done;
10469 refname = strdup(got_ref_get_name(branch_ref));
10470 if (refname == NULL) {
10471 error = got_error_from_errno("strdup");
10472 got_worktree_integrate_abort(worktree, fileindex, repo,
10473 branch_ref, base_branch_ref);
10474 goto done;
10476 base_refname = strdup(got_ref_get_name(base_branch_ref));
10477 if (base_refname == NULL) {
10478 error = got_error_from_errno("strdup");
10479 got_worktree_integrate_abort(worktree, fileindex, repo,
10480 branch_ref, base_branch_ref);
10481 goto done;
10484 error = got_ref_resolve(&commit_id, repo, branch_ref);
10485 if (error)
10486 goto done;
10488 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10489 if (error)
10490 goto done;
10492 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10493 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10494 "specified branch has already been integrated");
10495 got_worktree_integrate_abort(worktree, fileindex, repo,
10496 branch_ref, base_branch_ref);
10497 goto done;
10500 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10501 if (error) {
10502 if (error->code == GOT_ERR_ANCESTRY)
10503 error = got_error(GOT_ERR_REBASE_REQUIRED);
10504 got_worktree_integrate_abort(worktree, fileindex, repo,
10505 branch_ref, base_branch_ref);
10506 goto done;
10509 memset(&upa, 0, sizeof(upa));
10510 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10511 branch_ref, base_branch_ref, update_progress, &upa,
10512 check_cancelled, NULL);
10513 if (error)
10514 goto done;
10516 printf("Integrated %s into %s\n", refname, base_refname);
10517 print_update_progress_stats(&upa);
10518 done:
10519 if (repo) {
10520 const struct got_error *close_err = got_repo_close(repo);
10521 if (error == NULL)
10522 error = close_err;
10524 if (worktree)
10525 got_worktree_close(worktree);
10526 free(cwd);
10527 free(base_commit_id);
10528 free(commit_id);
10529 free(refname);
10530 free(base_refname);
10531 return error;
10534 __dead static void
10535 usage_stage(void)
10537 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10538 "[-S] [file-path ...]\n",
10539 getprogname());
10540 exit(1);
10543 static const struct got_error *
10544 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10545 const char *path, struct got_object_id *blob_id,
10546 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10547 int dirfd, const char *de_name)
10549 const struct got_error *err = NULL;
10550 char *id_str = NULL;
10552 if (staged_status != GOT_STATUS_ADD &&
10553 staged_status != GOT_STATUS_MODIFY &&
10554 staged_status != GOT_STATUS_DELETE)
10555 return NULL;
10557 if (staged_status == GOT_STATUS_ADD ||
10558 staged_status == GOT_STATUS_MODIFY)
10559 err = got_object_id_str(&id_str, staged_blob_id);
10560 else
10561 err = got_object_id_str(&id_str, blob_id);
10562 if (err)
10563 return err;
10565 printf("%s %c %s\n", id_str, staged_status, path);
10566 free(id_str);
10567 return NULL;
10570 static const struct got_error *
10571 cmd_stage(int argc, char *argv[])
10573 const struct got_error *error = NULL;
10574 struct got_repository *repo = NULL;
10575 struct got_worktree *worktree = NULL;
10576 char *cwd = NULL;
10577 struct got_pathlist_head paths;
10578 struct got_pathlist_entry *pe;
10579 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10580 FILE *patch_script_file = NULL;
10581 const char *patch_script_path = NULL;
10582 struct choose_patch_arg cpa;
10584 TAILQ_INIT(&paths);
10586 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10587 switch (ch) {
10588 case 'l':
10589 list_stage = 1;
10590 break;
10591 case 'p':
10592 pflag = 1;
10593 break;
10594 case 'F':
10595 patch_script_path = optarg;
10596 break;
10597 case 'S':
10598 allow_bad_symlinks = 1;
10599 break;
10600 default:
10601 usage_stage();
10602 /* NOTREACHED */
10606 argc -= optind;
10607 argv += optind;
10609 #ifndef PROFILE
10610 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10611 "unveil", NULL) == -1)
10612 err(1, "pledge");
10613 #endif
10614 if (list_stage && (pflag || patch_script_path))
10615 errx(1, "-l option cannot be used with other options");
10616 if (patch_script_path && !pflag)
10617 errx(1, "-F option can only be used together with -p option");
10619 cwd = getcwd(NULL, 0);
10620 if (cwd == NULL) {
10621 error = got_error_from_errno("getcwd");
10622 goto done;
10625 error = got_worktree_open(&worktree, cwd);
10626 if (error) {
10627 if (error->code == GOT_ERR_NOT_WORKTREE)
10628 error = wrap_not_worktree_error(error, "stage", cwd);
10629 goto done;
10632 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10633 NULL);
10634 if (error != NULL)
10635 goto done;
10637 if (patch_script_path) {
10638 patch_script_file = fopen(patch_script_path, "r");
10639 if (patch_script_file == NULL) {
10640 error = got_error_from_errno2("fopen",
10641 patch_script_path);
10642 goto done;
10645 error = apply_unveil(got_repo_get_path(repo), 0,
10646 got_worktree_get_root_path(worktree));
10647 if (error)
10648 goto done;
10650 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10651 if (error)
10652 goto done;
10654 if (list_stage)
10655 error = got_worktree_status(worktree, &paths, repo, 0,
10656 print_stage, NULL, check_cancelled, NULL);
10657 else {
10658 cpa.patch_script_file = patch_script_file;
10659 cpa.action = "stage";
10660 error = got_worktree_stage(worktree, &paths,
10661 pflag ? NULL : print_status, NULL,
10662 pflag ? choose_patch : NULL, &cpa,
10663 allow_bad_symlinks, repo);
10665 done:
10666 if (patch_script_file && fclose(patch_script_file) == EOF &&
10667 error == NULL)
10668 error = got_error_from_errno2("fclose", patch_script_path);
10669 if (repo) {
10670 const struct got_error *close_err = got_repo_close(repo);
10671 if (error == NULL)
10672 error = close_err;
10674 if (worktree)
10675 got_worktree_close(worktree);
10676 TAILQ_FOREACH(pe, &paths, entry)
10677 free((char *)pe->path);
10678 got_pathlist_free(&paths);
10679 free(cwd);
10680 return error;
10683 __dead static void
10684 usage_unstage(void)
10686 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10687 "[file-path ...]\n",
10688 getprogname());
10689 exit(1);
10693 static const struct got_error *
10694 cmd_unstage(int argc, char *argv[])
10696 const struct got_error *error = NULL;
10697 struct got_repository *repo = NULL;
10698 struct got_worktree *worktree = NULL;
10699 char *cwd = NULL;
10700 struct got_pathlist_head paths;
10701 struct got_pathlist_entry *pe;
10702 int ch, pflag = 0;
10703 struct got_update_progress_arg upa;
10704 FILE *patch_script_file = NULL;
10705 const char *patch_script_path = NULL;
10706 struct choose_patch_arg cpa;
10708 TAILQ_INIT(&paths);
10710 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10711 switch (ch) {
10712 case 'p':
10713 pflag = 1;
10714 break;
10715 case 'F':
10716 patch_script_path = optarg;
10717 break;
10718 default:
10719 usage_unstage();
10720 /* NOTREACHED */
10724 argc -= optind;
10725 argv += optind;
10727 #ifndef PROFILE
10728 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10729 "unveil", NULL) == -1)
10730 err(1, "pledge");
10731 #endif
10732 if (patch_script_path && !pflag)
10733 errx(1, "-F option can only be used together with -p option");
10735 cwd = getcwd(NULL, 0);
10736 if (cwd == NULL) {
10737 error = got_error_from_errno("getcwd");
10738 goto done;
10741 error = got_worktree_open(&worktree, cwd);
10742 if (error) {
10743 if (error->code == GOT_ERR_NOT_WORKTREE)
10744 error = wrap_not_worktree_error(error, "unstage", cwd);
10745 goto done;
10748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10749 NULL);
10750 if (error != NULL)
10751 goto done;
10753 if (patch_script_path) {
10754 patch_script_file = fopen(patch_script_path, "r");
10755 if (patch_script_file == NULL) {
10756 error = got_error_from_errno2("fopen",
10757 patch_script_path);
10758 goto done;
10762 error = apply_unveil(got_repo_get_path(repo), 0,
10763 got_worktree_get_root_path(worktree));
10764 if (error)
10765 goto done;
10767 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10768 if (error)
10769 goto done;
10771 cpa.patch_script_file = patch_script_file;
10772 cpa.action = "unstage";
10773 memset(&upa, 0, sizeof(upa));
10774 error = got_worktree_unstage(worktree, &paths, update_progress,
10775 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10776 if (!error)
10777 print_update_progress_stats(&upa);
10778 done:
10779 if (patch_script_file && fclose(patch_script_file) == EOF &&
10780 error == NULL)
10781 error = got_error_from_errno2("fclose", patch_script_path);
10782 if (repo) {
10783 const struct got_error *close_err = got_repo_close(repo);
10784 if (error == NULL)
10785 error = close_err;
10787 if (worktree)
10788 got_worktree_close(worktree);
10789 TAILQ_FOREACH(pe, &paths, entry)
10790 free((char *)pe->path);
10791 got_pathlist_free(&paths);
10792 free(cwd);
10793 return error;
10796 __dead static void
10797 usage_cat(void)
10799 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10800 "arg1 [arg2 ...]\n", getprogname());
10801 exit(1);
10804 static const struct got_error *
10805 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10807 const struct got_error *err;
10808 struct got_blob_object *blob;
10810 err = got_object_open_as_blob(&blob, repo, id, 8192);
10811 if (err)
10812 return err;
10814 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10815 got_object_blob_close(blob);
10816 return err;
10819 static const struct got_error *
10820 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10822 const struct got_error *err;
10823 struct got_tree_object *tree;
10824 int nentries, i;
10826 err = got_object_open_as_tree(&tree, repo, id);
10827 if (err)
10828 return err;
10830 nentries = got_object_tree_get_nentries(tree);
10831 for (i = 0; i < nentries; i++) {
10832 struct got_tree_entry *te;
10833 char *id_str;
10834 if (sigint_received || sigpipe_received)
10835 break;
10836 te = got_object_tree_get_entry(tree, i);
10837 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10838 if (err)
10839 break;
10840 fprintf(outfile, "%s %.7o %s\n", id_str,
10841 got_tree_entry_get_mode(te),
10842 got_tree_entry_get_name(te));
10843 free(id_str);
10846 got_object_tree_close(tree);
10847 return err;
10850 static const struct got_error *
10851 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10853 const struct got_error *err;
10854 struct got_commit_object *commit;
10855 const struct got_object_id_queue *parent_ids;
10856 struct got_object_qid *pid;
10857 char *id_str = NULL;
10858 const char *logmsg = NULL;
10860 err = got_object_open_as_commit(&commit, repo, id);
10861 if (err)
10862 return err;
10864 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10865 if (err)
10866 goto done;
10868 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10869 parent_ids = got_object_commit_get_parent_ids(commit);
10870 fprintf(outfile, "numparents %d\n",
10871 got_object_commit_get_nparents(commit));
10872 STAILQ_FOREACH(pid, parent_ids, entry) {
10873 char *pid_str;
10874 err = got_object_id_str(&pid_str, pid->id);
10875 if (err)
10876 goto done;
10877 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10878 free(pid_str);
10880 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10881 got_object_commit_get_author(commit),
10882 (long long)got_object_commit_get_author_time(commit));
10884 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10885 got_object_commit_get_author(commit),
10886 (long long)got_object_commit_get_committer_time(commit));
10888 logmsg = got_object_commit_get_logmsg_raw(commit);
10889 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10890 fprintf(outfile, "%s", logmsg);
10891 done:
10892 free(id_str);
10893 got_object_commit_close(commit);
10894 return err;
10897 static const struct got_error *
10898 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10900 const struct got_error *err;
10901 struct got_tag_object *tag;
10902 char *id_str = NULL;
10903 const char *tagmsg = NULL;
10905 err = got_object_open_as_tag(&tag, repo, id);
10906 if (err)
10907 return err;
10909 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10910 if (err)
10911 goto done;
10913 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10915 switch (got_object_tag_get_object_type(tag)) {
10916 case GOT_OBJ_TYPE_BLOB:
10917 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10918 GOT_OBJ_LABEL_BLOB);
10919 break;
10920 case GOT_OBJ_TYPE_TREE:
10921 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10922 GOT_OBJ_LABEL_TREE);
10923 break;
10924 case GOT_OBJ_TYPE_COMMIT:
10925 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10926 GOT_OBJ_LABEL_COMMIT);
10927 break;
10928 case GOT_OBJ_TYPE_TAG:
10929 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10930 GOT_OBJ_LABEL_TAG);
10931 break;
10932 default:
10933 break;
10936 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10937 got_object_tag_get_name(tag));
10939 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10940 got_object_tag_get_tagger(tag),
10941 (long long)got_object_tag_get_tagger_time(tag));
10943 tagmsg = got_object_tag_get_message(tag);
10944 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10945 fprintf(outfile, "%s", tagmsg);
10946 done:
10947 free(id_str);
10948 got_object_tag_close(tag);
10949 return err;
10952 static const struct got_error *
10953 cmd_cat(int argc, char *argv[])
10955 const struct got_error *error;
10956 struct got_repository *repo = NULL;
10957 struct got_worktree *worktree = NULL;
10958 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10959 const char *commit_id_str = NULL;
10960 struct got_object_id *id = NULL, *commit_id = NULL;
10961 int ch, obj_type, i, force_path = 0;
10962 struct got_reflist_head refs;
10964 TAILQ_INIT(&refs);
10966 #ifndef PROFILE
10967 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10968 NULL) == -1)
10969 err(1, "pledge");
10970 #endif
10972 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10973 switch (ch) {
10974 case 'c':
10975 commit_id_str = optarg;
10976 break;
10977 case 'r':
10978 repo_path = realpath(optarg, NULL);
10979 if (repo_path == NULL)
10980 return got_error_from_errno2("realpath",
10981 optarg);
10982 got_path_strip_trailing_slashes(repo_path);
10983 break;
10984 case 'P':
10985 force_path = 1;
10986 break;
10987 default:
10988 usage_cat();
10989 /* NOTREACHED */
10993 argc -= optind;
10994 argv += optind;
10996 cwd = getcwd(NULL, 0);
10997 if (cwd == NULL) {
10998 error = got_error_from_errno("getcwd");
10999 goto done;
11001 error = got_worktree_open(&worktree, cwd);
11002 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11003 goto done;
11004 if (worktree) {
11005 if (repo_path == NULL) {
11006 repo_path = strdup(
11007 got_worktree_get_repo_path(worktree));
11008 if (repo_path == NULL) {
11009 error = got_error_from_errno("strdup");
11010 goto done;
11015 if (repo_path == NULL) {
11016 repo_path = getcwd(NULL, 0);
11017 if (repo_path == NULL)
11018 return got_error_from_errno("getcwd");
11021 error = got_repo_open(&repo, repo_path, NULL);
11022 free(repo_path);
11023 if (error != NULL)
11024 goto done;
11026 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11027 if (error)
11028 goto done;
11030 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11031 if (error)
11032 goto done;
11034 if (commit_id_str == NULL)
11035 commit_id_str = GOT_REF_HEAD;
11036 error = got_repo_match_object_id(&commit_id, NULL,
11037 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11038 if (error)
11039 goto done;
11041 for (i = 0; i < argc; i++) {
11042 if (force_path) {
11043 error = got_object_id_by_path(&id, repo, commit_id,
11044 argv[i]);
11045 if (error)
11046 break;
11047 } else {
11048 error = got_repo_match_object_id(&id, &label, argv[i],
11049 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11050 repo);
11051 if (error) {
11052 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11053 error->code != GOT_ERR_NOT_REF)
11054 break;
11055 error = got_object_id_by_path(&id, repo,
11056 commit_id, argv[i]);
11057 if (error)
11058 break;
11062 error = got_object_get_type(&obj_type, repo, id);
11063 if (error)
11064 break;
11066 switch (obj_type) {
11067 case GOT_OBJ_TYPE_BLOB:
11068 error = cat_blob(id, repo, stdout);
11069 break;
11070 case GOT_OBJ_TYPE_TREE:
11071 error = cat_tree(id, repo, stdout);
11072 break;
11073 case GOT_OBJ_TYPE_COMMIT:
11074 error = cat_commit(id, repo, stdout);
11075 break;
11076 case GOT_OBJ_TYPE_TAG:
11077 error = cat_tag(id, repo, stdout);
11078 break;
11079 default:
11080 error = got_error(GOT_ERR_OBJ_TYPE);
11081 break;
11083 if (error)
11084 break;
11085 free(label);
11086 label = NULL;
11087 free(id);
11088 id = NULL;
11090 done:
11091 free(label);
11092 free(id);
11093 free(commit_id);
11094 if (worktree)
11095 got_worktree_close(worktree);
11096 if (repo) {
11097 const struct got_error *close_err = got_repo_close(repo);
11098 if (error == NULL)
11099 error = close_err;
11101 got_ref_list_free(&refs);
11102 return error;
11105 __dead static void
11106 usage_info(void)
11108 fprintf(stderr, "usage: %s info [path ...]\n",
11109 getprogname());
11110 exit(1);
11113 static const struct got_error *
11114 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11115 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11116 struct got_object_id *commit_id)
11118 const struct got_error *err = NULL;
11119 char *id_str = NULL;
11120 char datebuf[128];
11121 struct tm mytm, *tm;
11122 struct got_pathlist_head *paths = arg;
11123 struct got_pathlist_entry *pe;
11126 * Clear error indication from any of the path arguments which
11127 * would cause this file index entry to be displayed.
11129 TAILQ_FOREACH(pe, paths, entry) {
11130 if (got_path_cmp(path, pe->path, strlen(path),
11131 pe->path_len) == 0 ||
11132 got_path_is_child(path, pe->path, pe->path_len))
11133 pe->data = NULL; /* no error */
11136 printf(GOT_COMMIT_SEP_STR);
11137 if (S_ISLNK(mode))
11138 printf("symlink: %s\n", path);
11139 else if (S_ISREG(mode)) {
11140 printf("file: %s\n", path);
11141 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11142 } else if (S_ISDIR(mode))
11143 printf("directory: %s\n", path);
11144 else
11145 printf("something: %s\n", path);
11147 tm = localtime_r(&mtime, &mytm);
11148 if (tm == NULL)
11149 return NULL;
11150 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11151 return got_error(GOT_ERR_NO_SPACE);
11152 printf("timestamp: %s\n", datebuf);
11154 if (blob_id) {
11155 err = got_object_id_str(&id_str, blob_id);
11156 if (err)
11157 return err;
11158 printf("based on blob: %s\n", id_str);
11159 free(id_str);
11162 if (staged_blob_id) {
11163 err = got_object_id_str(&id_str, staged_blob_id);
11164 if (err)
11165 return err;
11166 printf("based on staged blob: %s\n", id_str);
11167 free(id_str);
11170 if (commit_id) {
11171 err = got_object_id_str(&id_str, commit_id);
11172 if (err)
11173 return err;
11174 printf("based on commit: %s\n", id_str);
11175 free(id_str);
11178 return NULL;
11181 static const struct got_error *
11182 cmd_info(int argc, char *argv[])
11184 const struct got_error *error = NULL;
11185 struct got_worktree *worktree = NULL;
11186 char *cwd = NULL, *id_str = NULL;
11187 struct got_pathlist_head paths;
11188 struct got_pathlist_entry *pe;
11189 char *uuidstr = NULL;
11190 int ch, show_files = 0;
11192 TAILQ_INIT(&paths);
11194 while ((ch = getopt(argc, argv, "")) != -1) {
11195 switch (ch) {
11196 default:
11197 usage_info();
11198 /* NOTREACHED */
11202 argc -= optind;
11203 argv += optind;
11205 #ifndef PROFILE
11206 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11207 NULL) == -1)
11208 err(1, "pledge");
11209 #endif
11210 cwd = getcwd(NULL, 0);
11211 if (cwd == NULL) {
11212 error = got_error_from_errno("getcwd");
11213 goto done;
11216 error = got_worktree_open(&worktree, cwd);
11217 if (error) {
11218 if (error->code == GOT_ERR_NOT_WORKTREE)
11219 error = wrap_not_worktree_error(error, "info", cwd);
11220 goto done;
11223 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11224 if (error)
11225 goto done;
11227 if (argc >= 1) {
11228 error = get_worktree_paths_from_argv(&paths, argc, argv,
11229 worktree);
11230 if (error)
11231 goto done;
11232 show_files = 1;
11235 error = got_object_id_str(&id_str,
11236 got_worktree_get_base_commit_id(worktree));
11237 if (error)
11238 goto done;
11240 error = got_worktree_get_uuid(&uuidstr, worktree);
11241 if (error)
11242 goto done;
11244 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11245 printf("work tree base commit: %s\n", id_str);
11246 printf("work tree path prefix: %s\n",
11247 got_worktree_get_path_prefix(worktree));
11248 printf("work tree branch reference: %s\n",
11249 got_worktree_get_head_ref_name(worktree));
11250 printf("work tree UUID: %s\n", uuidstr);
11251 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11253 if (show_files) {
11254 struct got_pathlist_entry *pe;
11255 TAILQ_FOREACH(pe, &paths, entry) {
11256 if (pe->path_len == 0)
11257 continue;
11259 * Assume this path will fail. This will be corrected
11260 * in print_path_info() in case the path does suceeed.
11262 pe->data = (void *)got_error_path(pe->path,
11263 GOT_ERR_BAD_PATH);
11265 error = got_worktree_path_info(worktree, &paths,
11266 print_path_info, &paths, check_cancelled, NULL);
11267 if (error)
11268 goto done;
11269 TAILQ_FOREACH(pe, &paths, entry) {
11270 if (pe->data != NULL) {
11271 error = pe->data; /* bad path */
11272 break;
11276 done:
11277 TAILQ_FOREACH(pe, &paths, entry)
11278 free((char *)pe->path);
11279 got_pathlist_free(&paths);
11280 free(cwd);
11281 free(id_str);
11282 free(uuidstr);
11283 return error;