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_fetch_parse_uri(&proto, &host, &port, &server_path,
1548 &repo_name, uri);
1549 if (error)
1550 goto done;
1552 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1553 host, port ? ":" : "", port ? port : "",
1554 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1555 error = got_error_from_errno("asprintf");
1556 goto done;
1559 if (strcmp(proto, "git") == 0) {
1560 #ifndef PROFILE
1561 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1562 "sendfd dns inet unveil", NULL) == -1)
1563 err(1, "pledge");
1564 #endif
1565 } else if (strcmp(proto, "git+ssh") == 0 ||
1566 strcmp(proto, "ssh") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "http") == 0 ||
1573 strcmp(proto, "git+http") == 0) {
1574 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1575 goto done;
1576 } else {
1577 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1578 goto done;
1580 if (dirname == NULL) {
1581 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1582 error = got_error_from_errno("asprintf");
1583 goto done;
1585 repo_path = default_destdir;
1586 } else
1587 repo_path = dirname;
1589 if (!list_refs_only) {
1590 error = got_path_mkdir(repo_path);
1591 if (error &&
1592 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1593 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1594 goto done;
1595 if (!got_path_dir_is_empty(repo_path)) {
1596 error = got_error_path(repo_path,
1597 GOT_ERR_DIR_NOT_EMPTY);
1598 goto done;
1602 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);
2024 if (!remote->mirror_references) {
2025 if (strncmp(refname, remote_namespace,
2026 strlen(remote_namespace)) == 0) {
2027 if (strcmp(refname + strlen(remote_namespace),
2028 GOT_REF_HEAD) == 0)
2029 continue;
2030 if (asprintf(&local_refname, "refs/heads/%s",
2031 refname + strlen(remote_namespace)) == -1) {
2032 err = got_error_from_errno("asprintf");
2033 goto done;
2035 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2036 continue;
2039 TAILQ_FOREACH(pe, their_refs, entry) {
2040 if (strcmp(local_refname, pe->path) == 0)
2041 break;
2043 if (pe != NULL)
2044 continue;
2046 TAILQ_FOREACH(pe, their_symrefs, entry) {
2047 if (strcmp(local_refname, pe->path) == 0)
2048 break;
2050 if (pe != NULL)
2051 continue;
2053 err = delete_missing_ref(re->ref, verbosity, repo);
2054 if (err)
2055 break;
2057 if (local_refname) {
2058 struct got_reference *ref;
2059 err = got_ref_open(&ref, repo, local_refname, 1);
2060 if (err) {
2061 if (err->code != GOT_ERR_NOT_REF)
2062 break;
2063 free(local_refname);
2064 local_refname = NULL;
2065 continue;
2067 err = delete_missing_ref(ref, verbosity, repo);
2068 if (err)
2069 break;
2070 unlock_err = got_ref_unlock(ref);
2071 got_ref_close(ref);
2072 if (unlock_err && err == NULL) {
2073 err = unlock_err;
2074 break;
2077 free(local_refname);
2078 local_refname = NULL;
2081 done:
2082 free(remote_namespace);
2083 free(local_refname);
2084 return err;
2087 static const struct got_error *
2088 update_wanted_ref(const char *refname, struct got_object_id *id,
2089 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2091 const struct got_error *err, *unlock_err;
2092 char *remote_refname;
2093 struct got_reference *ref;
2095 if (strncmp("refs/", refname, 5) == 0)
2096 refname += 5;
2098 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2099 remote_repo_name, refname) == -1)
2100 return got_error_from_errno("asprintf");
2102 err = got_ref_open(&ref, repo, remote_refname, 1);
2103 if (err) {
2104 if (err->code != GOT_ERR_NOT_REF)
2105 goto done;
2106 err = create_ref(remote_refname, id, verbosity, repo);
2107 } else {
2108 err = update_ref(ref, id, 0, verbosity, repo);
2109 unlock_err = got_ref_unlock(ref);
2110 if (unlock_err && err == NULL)
2111 err = unlock_err;
2112 got_ref_close(ref);
2114 done:
2115 free(remote_refname);
2116 return err;
2119 static const struct got_error *
2120 delete_ref(struct got_repository *repo, struct got_reference *ref)
2122 const struct got_error *err = NULL;
2123 struct got_object_id *id = NULL;
2124 char *id_str = NULL;
2125 const char *target;
2127 if (got_ref_is_symbolic(ref)) {
2128 target = got_ref_get_symref_target(ref);
2129 } else {
2130 err = got_ref_resolve(&id, repo, ref);
2131 if (err)
2132 goto done;
2133 err = got_object_id_str(&id_str, id);
2134 if (err)
2135 goto done;
2136 target = id_str;
2139 err = got_ref_delete(ref, repo);
2140 if (err)
2141 goto done;
2143 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2144 done:
2145 free(id);
2146 free(id_str);
2147 return err;
2150 static const struct got_error *
2151 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2153 const struct got_error *err = NULL;
2154 struct got_reflist_head refs;
2155 struct got_reflist_entry *re;
2156 char *prefix;
2158 TAILQ_INIT(&refs);
2160 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2161 err = got_error_from_errno("asprintf");
2162 goto done;
2164 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2165 if (err)
2166 goto done;
2168 TAILQ_FOREACH(re, &refs, entry)
2169 delete_ref(repo, re->ref);
2170 done:
2171 got_ref_list_free(&refs);
2172 return err;
2175 static const struct got_error *
2176 cmd_fetch(int argc, char *argv[])
2178 const struct got_error *error = NULL, *unlock_err;
2179 char *cwd = NULL, *repo_path = NULL;
2180 const char *remote_name;
2181 char *proto = NULL, *host = NULL, *port = NULL;
2182 char *repo_name = NULL, *server_path = NULL;
2183 const struct got_remote_repo *remotes, *remote = NULL;
2184 int nremotes;
2185 char *id_str = NULL;
2186 struct got_repository *repo = NULL;
2187 struct got_worktree *worktree = NULL;
2188 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2189 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2190 struct got_pathlist_entry *pe;
2191 struct got_object_id *pack_hash = NULL;
2192 int i, ch, fetchfd = -1, fetchstatus;
2193 pid_t fetchpid = -1;
2194 struct got_fetch_progress_arg fpa;
2195 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2196 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2198 TAILQ_INIT(&refs);
2199 TAILQ_INIT(&symrefs);
2200 TAILQ_INIT(&wanted_branches);
2201 TAILQ_INIT(&wanted_refs);
2203 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2204 switch (ch) {
2205 case 'a':
2206 fetch_all_branches = 1;
2207 break;
2208 case 'b':
2209 error = got_pathlist_append(&wanted_branches,
2210 optarg, NULL);
2211 if (error)
2212 return error;
2213 break;
2214 case 'd':
2215 delete_refs = 1;
2216 break;
2217 case 'l':
2218 list_refs_only = 1;
2219 break;
2220 case 'r':
2221 repo_path = realpath(optarg, NULL);
2222 if (repo_path == NULL)
2223 return got_error_from_errno2("realpath",
2224 optarg);
2225 got_path_strip_trailing_slashes(repo_path);
2226 break;
2227 case 't':
2228 replace_tags = 1;
2229 break;
2230 case 'v':
2231 if (verbosity < 0)
2232 verbosity = 0;
2233 else if (verbosity < 3)
2234 verbosity++;
2235 break;
2236 case 'q':
2237 verbosity = -1;
2238 break;
2239 case 'R':
2240 error = got_pathlist_append(&wanted_refs,
2241 optarg, NULL);
2242 if (error)
2243 return error;
2244 break;
2245 case 'X':
2246 delete_remote = 1;
2247 break;
2248 default:
2249 usage_fetch();
2250 break;
2253 argc -= optind;
2254 argv += optind;
2256 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2257 option_conflict('a', 'b');
2258 if (list_refs_only) {
2259 if (!TAILQ_EMPTY(&wanted_branches))
2260 option_conflict('l', 'b');
2261 if (fetch_all_branches)
2262 option_conflict('l', 'a');
2263 if (delete_refs)
2264 option_conflict('l', 'd');
2265 if (delete_remote)
2266 option_conflict('l', 'X');
2268 if (delete_remote) {
2269 if (fetch_all_branches)
2270 option_conflict('X', 'a');
2271 if (!TAILQ_EMPTY(&wanted_branches))
2272 option_conflict('X', 'b');
2273 if (delete_refs)
2274 option_conflict('X', 'd');
2275 if (replace_tags)
2276 option_conflict('X', 't');
2277 if (!TAILQ_EMPTY(&wanted_refs))
2278 option_conflict('X', 'R');
2281 if (argc == 0) {
2282 if (delete_remote)
2283 errx(1, "-X option requires a remote name");
2284 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2285 } else if (argc == 1)
2286 remote_name = argv[0];
2287 else
2288 usage_fetch();
2290 cwd = getcwd(NULL, 0);
2291 if (cwd == NULL) {
2292 error = got_error_from_errno("getcwd");
2293 goto done;
2296 if (repo_path == NULL) {
2297 error = got_worktree_open(&worktree, cwd);
2298 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2299 goto done;
2300 else
2301 error = NULL;
2302 if (worktree) {
2303 repo_path =
2304 strdup(got_worktree_get_repo_path(worktree));
2305 if (repo_path == NULL)
2306 error = got_error_from_errno("strdup");
2307 if (error)
2308 goto done;
2309 } else {
2310 repo_path = strdup(cwd);
2311 if (repo_path == NULL) {
2312 error = got_error_from_errno("strdup");
2313 goto done;
2318 error = got_repo_open(&repo, repo_path, NULL);
2319 if (error)
2320 goto done;
2322 if (delete_remote) {
2323 error = delete_refs_for_remote(repo, remote_name);
2324 goto done; /* nothing else to do */
2327 if (worktree) {
2328 worktree_conf = got_worktree_get_gotconfig(worktree);
2329 if (worktree_conf) {
2330 got_gotconfig_get_remotes(&nremotes, &remotes,
2331 worktree_conf);
2332 for (i = 0; i < nremotes; i++) {
2333 if (strcmp(remotes[i].name, remote_name) == 0) {
2334 remote = &remotes[i];
2335 break;
2340 if (remote == NULL) {
2341 repo_conf = got_repo_get_gotconfig(repo);
2342 if (repo_conf) {
2343 got_gotconfig_get_remotes(&nremotes, &remotes,
2344 repo_conf);
2345 for (i = 0; i < nremotes; i++) {
2346 if (strcmp(remotes[i].name, remote_name) == 0) {
2347 remote = &remotes[i];
2348 break;
2353 if (remote == NULL) {
2354 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2355 for (i = 0; i < nremotes; i++) {
2356 if (strcmp(remotes[i].name, remote_name) == 0) {
2357 remote = &remotes[i];
2358 break;
2362 if (remote == NULL) {
2363 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2364 goto done;
2367 if (TAILQ_EMPTY(&wanted_branches)) {
2368 if (!fetch_all_branches)
2369 fetch_all_branches = remote->fetch_all_branches;
2370 for (i = 0; i < remote->nfetch_branches; i++) {
2371 got_pathlist_append(&wanted_branches,
2372 remote->fetch_branches[i], NULL);
2375 if (TAILQ_EMPTY(&wanted_refs)) {
2376 for (i = 0; i < remote->nfetch_refs; i++) {
2377 got_pathlist_append(&wanted_refs,
2378 remote->fetch_refs[i], NULL);
2382 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2383 &repo_name, remote->fetch_url);
2384 if (error)
2385 goto done;
2387 if (strcmp(proto, "git") == 0) {
2388 #ifndef PROFILE
2389 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2390 "sendfd dns inet unveil", NULL) == -1)
2391 err(1, "pledge");
2392 #endif
2393 } else if (strcmp(proto, "git+ssh") == 0 ||
2394 strcmp(proto, "ssh") == 0) {
2395 #ifndef PROFILE
2396 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2397 "sendfd unveil", NULL) == -1)
2398 err(1, "pledge");
2399 #endif
2400 } else if (strcmp(proto, "http") == 0 ||
2401 strcmp(proto, "git+http") == 0) {
2402 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2403 goto done;
2404 } else {
2405 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2406 goto done;
2409 error = got_dial_apply_unveil(proto);
2410 if (error)
2411 goto done;
2413 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2414 if (error)
2415 goto done;
2417 if (verbosity >= 0)
2418 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2419 port ? ":" : "", port ? port : "");
2421 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2422 server_path, verbosity);
2423 if (error)
2424 goto done;
2426 fpa.last_scaled_size[0] = '\0';
2427 fpa.last_p_indexed = -1;
2428 fpa.last_p_resolved = -1;
2429 fpa.verbosity = verbosity;
2430 fpa.repo = repo;
2431 fpa.create_configs = 0;
2432 fpa.configs_created = 0;
2433 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2434 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2435 remote->mirror_references, fetch_all_branches, &wanted_branches,
2436 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2437 fetch_progress, &fpa);
2438 if (error)
2439 goto done;
2441 if (list_refs_only) {
2442 error = list_remote_refs(&symrefs, &refs);
2443 goto done;
2446 if (pack_hash == NULL) {
2447 if (verbosity >= 0)
2448 printf("Already up-to-date\n");
2449 } else if (verbosity >= 0) {
2450 error = got_object_id_str(&id_str, pack_hash);
2451 if (error)
2452 goto done;
2453 printf("\nFetched %s.pack\n", id_str);
2454 free(id_str);
2455 id_str = NULL;
2458 /* Update references provided with the pack file. */
2459 TAILQ_FOREACH(pe, &refs, entry) {
2460 const char *refname = pe->path;
2461 struct got_object_id *id = pe->data;
2462 struct got_reference *ref;
2463 char *remote_refname;
2465 if (is_wanted_ref(&wanted_refs, refname) &&
2466 !remote->mirror_references) {
2467 error = update_wanted_ref(refname, id,
2468 remote->name, verbosity, repo);
2469 if (error)
2470 goto done;
2471 continue;
2474 if (remote->mirror_references ||
2475 strncmp("refs/tags/", refname, 10) == 0) {
2476 error = got_ref_open(&ref, repo, refname, 1);
2477 if (error) {
2478 if (error->code != GOT_ERR_NOT_REF)
2479 goto done;
2480 error = create_ref(refname, id, verbosity,
2481 repo);
2482 if (error)
2483 goto done;
2484 } else {
2485 error = update_ref(ref, id, replace_tags,
2486 verbosity, repo);
2487 unlock_err = got_ref_unlock(ref);
2488 if (unlock_err && error == NULL)
2489 error = unlock_err;
2490 got_ref_close(ref);
2491 if (error)
2492 goto done;
2494 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2495 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2496 remote_name, refname + 11) == -1) {
2497 error = got_error_from_errno("asprintf");
2498 goto done;
2501 error = got_ref_open(&ref, repo, remote_refname, 1);
2502 if (error) {
2503 if (error->code != GOT_ERR_NOT_REF)
2504 goto done;
2505 error = create_ref(remote_refname, id,
2506 verbosity, repo);
2507 if (error)
2508 goto done;
2509 } else {
2510 error = update_ref(ref, id, replace_tags,
2511 verbosity, repo);
2512 unlock_err = got_ref_unlock(ref);
2513 if (unlock_err && error == NULL)
2514 error = unlock_err;
2515 got_ref_close(ref);
2516 if (error)
2517 goto done;
2520 /* Also create a local branch if none exists yet. */
2521 error = got_ref_open(&ref, repo, refname, 1);
2522 if (error) {
2523 if (error->code != GOT_ERR_NOT_REF)
2524 goto done;
2525 error = create_ref(refname, id, verbosity,
2526 repo);
2527 if (error)
2528 goto done;
2529 } else {
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2537 if (delete_refs) {
2538 error = delete_missing_refs(&refs, &symrefs, remote,
2539 verbosity, repo);
2540 if (error)
2541 goto done;
2544 if (!remote->mirror_references) {
2545 /* Update remote HEAD reference if the server provided one. */
2546 TAILQ_FOREACH(pe, &symrefs, entry) {
2547 struct got_reference *target_ref;
2548 const char *refname = pe->path;
2549 const char *target = pe->data;
2550 char *remote_refname = NULL, *remote_target = NULL;
2552 if (strcmp(refname, GOT_REF_HEAD) != 0)
2553 continue;
2555 if (strncmp("refs/heads/", target, 11) != 0)
2556 continue;
2558 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2559 remote->name, refname) == -1) {
2560 error = got_error_from_errno("asprintf");
2561 goto done;
2563 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2564 remote->name, target + 11) == -1) {
2565 error = got_error_from_errno("asprintf");
2566 free(remote_refname);
2567 goto done;
2570 error = got_ref_open(&target_ref, repo, remote_target,
2571 0);
2572 if (error) {
2573 free(remote_refname);
2574 free(remote_target);
2575 if (error->code == GOT_ERR_NOT_REF) {
2576 error = NULL;
2577 continue;
2579 goto done;
2581 error = update_symref(remote_refname, target_ref,
2582 verbosity, repo);
2583 free(remote_refname);
2584 free(remote_target);
2585 got_ref_close(target_ref);
2586 if (error)
2587 goto done;
2590 done:
2591 if (fetchpid > 0) {
2592 if (kill(fetchpid, SIGTERM) == -1)
2593 error = got_error_from_errno("kill");
2594 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2595 error = got_error_from_errno("waitpid");
2597 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2598 error = got_error_from_errno("close");
2599 if (repo) {
2600 const struct got_error *close_err = got_repo_close(repo);
2601 if (error == NULL)
2602 error = close_err;
2604 if (worktree)
2605 got_worktree_close(worktree);
2606 TAILQ_FOREACH(pe, &refs, entry) {
2607 free((void *)pe->path);
2608 free(pe->data);
2610 got_pathlist_free(&refs);
2611 TAILQ_FOREACH(pe, &symrefs, entry) {
2612 free((void *)pe->path);
2613 free(pe->data);
2615 got_pathlist_free(&symrefs);
2616 got_pathlist_free(&wanted_branches);
2617 got_pathlist_free(&wanted_refs);
2618 free(id_str);
2619 free(cwd);
2620 free(repo_path);
2621 free(pack_hash);
2622 free(proto);
2623 free(host);
2624 free(port);
2625 free(server_path);
2626 free(repo_name);
2627 return error;
2631 __dead static void
2632 usage_checkout(void)
2634 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2635 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2636 exit(1);
2639 static void
2640 show_worktree_base_ref_warning(void)
2642 fprintf(stderr, "%s: warning: could not create a reference "
2643 "to the work tree's base commit; the commit could be "
2644 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2645 "repository writable and running 'got update' will prevent this\n",
2646 getprogname());
2649 struct got_checkout_progress_arg {
2650 const char *worktree_path;
2651 int had_base_commit_ref_error;
2654 static const struct got_error *
2655 checkout_progress(void *arg, unsigned char status, const char *path)
2657 struct got_checkout_progress_arg *a = arg;
2659 /* Base commit bump happens silently. */
2660 if (status == GOT_STATUS_BUMP_BASE)
2661 return NULL;
2663 if (status == GOT_STATUS_BASE_REF_ERR) {
2664 a->had_base_commit_ref_error = 1;
2665 return NULL;
2668 while (path[0] == '/')
2669 path++;
2671 printf("%c %s/%s\n", status, a->worktree_path, path);
2672 return NULL;
2675 static const struct got_error *
2676 check_cancelled(void *arg)
2678 if (sigint_received || sigpipe_received)
2679 return got_error(GOT_ERR_CANCELLED);
2680 return NULL;
2683 static const struct got_error *
2684 check_linear_ancestry(struct got_object_id *commit_id,
2685 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2686 struct got_repository *repo)
2688 const struct got_error *err = NULL;
2689 struct got_object_id *yca_id;
2691 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2692 commit_id, base_commit_id, repo, check_cancelled, NULL);
2693 if (err)
2694 return err;
2696 if (yca_id == NULL)
2697 return got_error(GOT_ERR_ANCESTRY);
2700 * Require a straight line of history between the target commit
2701 * and the work tree's base commit.
2703 * Non-linear situations such as this require a rebase:
2705 * (commit) D F (base_commit)
2706 * \ /
2707 * C E
2708 * \ /
2709 * B (yca)
2710 * |
2711 * A
2713 * 'got update' only handles linear cases:
2714 * Update forwards in time: A (base/yca) - B - C - D (commit)
2715 * Update backwards in time: D (base) - C - B - A (commit/yca)
2717 if (allow_forwards_in_time_only) {
2718 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2719 return got_error(GOT_ERR_ANCESTRY);
2720 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2721 got_object_id_cmp(base_commit_id, yca_id) != 0)
2722 return got_error(GOT_ERR_ANCESTRY);
2724 free(yca_id);
2725 return NULL;
2728 static const struct got_error *
2729 check_same_branch(struct got_object_id *commit_id,
2730 struct got_reference *head_ref, struct got_object_id *yca_id,
2731 struct got_repository *repo)
2733 const struct got_error *err = NULL;
2734 struct got_commit_graph *graph = NULL;
2735 struct got_object_id *head_commit_id = NULL;
2736 int is_same_branch = 0;
2738 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2739 if (err)
2740 goto done;
2742 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2743 is_same_branch = 1;
2744 goto done;
2746 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2747 is_same_branch = 1;
2748 goto done;
2751 err = got_commit_graph_open(&graph, "/", 1);
2752 if (err)
2753 goto done;
2755 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2756 check_cancelled, NULL);
2757 if (err)
2758 goto done;
2760 for (;;) {
2761 struct got_object_id *id;
2762 err = got_commit_graph_iter_next(&id, graph, repo,
2763 check_cancelled, NULL);
2764 if (err) {
2765 if (err->code == GOT_ERR_ITER_COMPLETED)
2766 err = NULL;
2767 break;
2770 if (id) {
2771 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2772 break;
2773 if (got_object_id_cmp(id, commit_id) == 0) {
2774 is_same_branch = 1;
2775 break;
2779 done:
2780 if (graph)
2781 got_commit_graph_close(graph);
2782 free(head_commit_id);
2783 if (!err && !is_same_branch)
2784 err = got_error(GOT_ERR_ANCESTRY);
2785 return err;
2788 static const struct got_error *
2789 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2791 static char msg[512];
2792 const char *branch_name;
2794 if (got_ref_is_symbolic(ref))
2795 branch_name = got_ref_get_symref_target(ref);
2796 else
2797 branch_name = got_ref_get_name(ref);
2799 if (strncmp("refs/heads/", branch_name, 11) == 0)
2800 branch_name += 11;
2802 snprintf(msg, sizeof(msg),
2803 "target commit is not contained in branch '%s'; "
2804 "the branch to use must be specified with -b; "
2805 "if necessary a new branch can be created for "
2806 "this commit with 'got branch -c %s BRANCH_NAME'",
2807 branch_name, commit_id_str);
2809 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2812 static const struct got_error *
2813 cmd_checkout(int argc, char *argv[])
2815 const struct got_error *error = NULL;
2816 struct got_repository *repo = NULL;
2817 struct got_reference *head_ref = NULL;
2818 struct got_worktree *worktree = NULL;
2819 char *repo_path = NULL;
2820 char *worktree_path = NULL;
2821 const char *path_prefix = "";
2822 const char *branch_name = GOT_REF_HEAD;
2823 char *commit_id_str = NULL;
2824 char *cwd = NULL;
2825 int ch, same_path_prefix, allow_nonempty = 0;
2826 struct got_pathlist_head paths;
2827 struct got_checkout_progress_arg cpa;
2829 TAILQ_INIT(&paths);
2831 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2832 switch (ch) {
2833 case 'b':
2834 branch_name = optarg;
2835 break;
2836 case 'c':
2837 commit_id_str = strdup(optarg);
2838 if (commit_id_str == NULL)
2839 return got_error_from_errno("strdup");
2840 break;
2841 case 'E':
2842 allow_nonempty = 1;
2843 break;
2844 case 'p':
2845 path_prefix = optarg;
2846 break;
2847 default:
2848 usage_checkout();
2849 /* NOTREACHED */
2853 argc -= optind;
2854 argv += optind;
2856 #ifndef PROFILE
2857 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2858 "unveil", NULL) == -1)
2859 err(1, "pledge");
2860 #endif
2861 if (argc == 1) {
2862 char *base, *dotgit;
2863 const char *path;
2864 repo_path = realpath(argv[0], NULL);
2865 if (repo_path == NULL)
2866 return got_error_from_errno2("realpath", argv[0]);
2867 cwd = getcwd(NULL, 0);
2868 if (cwd == NULL) {
2869 error = got_error_from_errno("getcwd");
2870 goto done;
2872 if (path_prefix[0])
2873 path = path_prefix;
2874 else
2875 path = repo_path;
2876 error = got_path_basename(&base, path);
2877 if (error)
2878 goto done;
2879 dotgit = strstr(base, ".git");
2880 if (dotgit)
2881 *dotgit = '\0';
2882 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2883 error = got_error_from_errno("asprintf");
2884 free(base);
2885 goto done;
2887 free(base);
2888 } else if (argc == 2) {
2889 repo_path = realpath(argv[0], NULL);
2890 if (repo_path == NULL) {
2891 error = got_error_from_errno2("realpath", argv[0]);
2892 goto done;
2894 worktree_path = realpath(argv[1], NULL);
2895 if (worktree_path == NULL) {
2896 if (errno != ENOENT) {
2897 error = got_error_from_errno2("realpath",
2898 argv[1]);
2899 goto done;
2901 worktree_path = strdup(argv[1]);
2902 if (worktree_path == NULL) {
2903 error = got_error_from_errno("strdup");
2904 goto done;
2907 } else
2908 usage_checkout();
2910 got_path_strip_trailing_slashes(repo_path);
2911 got_path_strip_trailing_slashes(worktree_path);
2913 error = got_repo_open(&repo, repo_path, NULL);
2914 if (error != NULL)
2915 goto done;
2917 /* Pre-create work tree path for unveil(2) */
2918 error = got_path_mkdir(worktree_path);
2919 if (error) {
2920 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2921 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2922 goto done;
2923 if (!allow_nonempty &&
2924 !got_path_dir_is_empty(worktree_path)) {
2925 error = got_error_path(worktree_path,
2926 GOT_ERR_DIR_NOT_EMPTY);
2927 goto done;
2931 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2932 if (error)
2933 goto done;
2935 error = got_ref_open(&head_ref, repo, branch_name, 0);
2936 if (error != NULL)
2937 goto done;
2939 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2940 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2941 goto done;
2943 error = got_worktree_open(&worktree, worktree_path);
2944 if (error != NULL)
2945 goto done;
2947 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2948 path_prefix);
2949 if (error != NULL)
2950 goto done;
2951 if (!same_path_prefix) {
2952 error = got_error(GOT_ERR_PATH_PREFIX);
2953 goto done;
2956 if (commit_id_str) {
2957 struct got_object_id *commit_id;
2958 struct got_reflist_head refs;
2959 TAILQ_INIT(&refs);
2960 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2961 NULL);
2962 if (error)
2963 goto done;
2964 error = got_repo_match_object_id(&commit_id, NULL,
2965 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2966 got_ref_list_free(&refs);
2967 if (error)
2968 goto done;
2969 error = check_linear_ancestry(commit_id,
2970 got_worktree_get_base_commit_id(worktree), 0, repo);
2971 if (error != NULL) {
2972 free(commit_id);
2973 if (error->code == GOT_ERR_ANCESTRY) {
2974 error = checkout_ancestry_error(
2975 head_ref, commit_id_str);
2977 goto done;
2979 error = check_same_branch(commit_id, head_ref, NULL, repo);
2980 if (error) {
2981 if (error->code == GOT_ERR_ANCESTRY) {
2982 error = checkout_ancestry_error(
2983 head_ref, commit_id_str);
2985 goto done;
2987 error = got_worktree_set_base_commit_id(worktree, repo,
2988 commit_id);
2989 free(commit_id);
2990 if (error)
2991 goto done;
2994 error = got_pathlist_append(&paths, "", NULL);
2995 if (error)
2996 goto done;
2997 cpa.worktree_path = worktree_path;
2998 cpa.had_base_commit_ref_error = 0;
2999 error = got_worktree_checkout_files(worktree, &paths, repo,
3000 checkout_progress, &cpa, check_cancelled, NULL);
3001 if (error != NULL)
3002 goto done;
3004 printf("Now shut up and hack\n");
3005 if (cpa.had_base_commit_ref_error)
3006 show_worktree_base_ref_warning();
3007 done:
3008 got_pathlist_free(&paths);
3009 free(commit_id_str);
3010 free(repo_path);
3011 free(worktree_path);
3012 free(cwd);
3013 return error;
3016 struct got_update_progress_arg {
3017 int did_something;
3018 int conflicts;
3019 int obstructed;
3020 int not_updated;
3023 void
3024 print_update_progress_stats(struct got_update_progress_arg *upa)
3026 if (!upa->did_something)
3027 return;
3029 if (upa->conflicts > 0)
3030 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3031 if (upa->obstructed > 0)
3032 printf("File paths obstructed by a non-regular file: %d\n",
3033 upa->obstructed);
3034 if (upa->not_updated > 0)
3035 printf("Files not updated because of existing merge "
3036 "conflicts: %d\n", upa->not_updated);
3039 __dead static void
3040 usage_update(void)
3042 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
3043 getprogname());
3044 exit(1);
3047 static const struct got_error *
3048 update_progress(void *arg, unsigned char status, const char *path)
3050 struct got_update_progress_arg *upa = arg;
3052 if (status == GOT_STATUS_EXISTS ||
3053 status == GOT_STATUS_BASE_REF_ERR)
3054 return NULL;
3056 upa->did_something = 1;
3058 /* Base commit bump happens silently. */
3059 if (status == GOT_STATUS_BUMP_BASE)
3060 return NULL;
3062 if (status == GOT_STATUS_CONFLICT)
3063 upa->conflicts++;
3064 if (status == GOT_STATUS_OBSTRUCTED)
3065 upa->obstructed++;
3066 if (status == GOT_STATUS_CANNOT_UPDATE)
3067 upa->not_updated++;
3069 while (path[0] == '/')
3070 path++;
3071 printf("%c %s\n", status, path);
3072 return NULL;
3075 static const struct got_error *
3076 switch_head_ref(struct got_reference *head_ref,
3077 struct got_object_id *commit_id, struct got_worktree *worktree,
3078 struct got_repository *repo)
3080 const struct got_error *err = NULL;
3081 char *base_id_str;
3082 int ref_has_moved = 0;
3084 /* Trivial case: switching between two different references. */
3085 if (strcmp(got_ref_get_name(head_ref),
3086 got_worktree_get_head_ref_name(worktree)) != 0) {
3087 printf("Switching work tree from %s to %s\n",
3088 got_worktree_get_head_ref_name(worktree),
3089 got_ref_get_name(head_ref));
3090 return got_worktree_set_head_ref(worktree, head_ref);
3093 err = check_linear_ancestry(commit_id,
3094 got_worktree_get_base_commit_id(worktree), 0, repo);
3095 if (err) {
3096 if (err->code != GOT_ERR_ANCESTRY)
3097 return err;
3098 ref_has_moved = 1;
3100 if (!ref_has_moved)
3101 return NULL;
3103 /* Switching to a rebased branch with the same reference name. */
3104 err = got_object_id_str(&base_id_str,
3105 got_worktree_get_base_commit_id(worktree));
3106 if (err)
3107 return err;
3108 printf("Reference %s now points at a different branch\n",
3109 got_worktree_get_head_ref_name(worktree));
3110 printf("Switching work tree from %s to %s\n", base_id_str,
3111 got_worktree_get_head_ref_name(worktree));
3112 return NULL;
3115 static const struct got_error *
3116 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3118 const struct got_error *err;
3119 int in_progress;
3121 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3122 if (err)
3123 return err;
3124 if (in_progress)
3125 return got_error(GOT_ERR_REBASING);
3127 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3128 if (err)
3129 return err;
3130 if (in_progress)
3131 return got_error(GOT_ERR_HISTEDIT_BUSY);
3133 return NULL;
3136 static const struct got_error *
3137 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3138 char *argv[], struct got_worktree *worktree)
3140 const struct got_error *err = NULL;
3141 char *path;
3142 int i;
3144 if (argc == 0) {
3145 path = strdup("");
3146 if (path == NULL)
3147 return got_error_from_errno("strdup");
3148 return got_pathlist_append(paths, path, NULL);
3151 for (i = 0; i < argc; i++) {
3152 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3153 if (err)
3154 break;
3155 err = got_pathlist_append(paths, path, NULL);
3156 if (err) {
3157 free(path);
3158 break;
3162 return err;
3165 static const struct got_error *
3166 wrap_not_worktree_error(const struct got_error *orig_err,
3167 const char *cmdname, const char *path)
3169 const struct got_error *err;
3170 struct got_repository *repo;
3171 static char msg[512];
3173 err = got_repo_open(&repo, path, NULL);
3174 if (err)
3175 return orig_err;
3177 snprintf(msg, sizeof(msg),
3178 "'got %s' needs a work tree in addition to a git repository\n"
3179 "Work trees can be checked out from this Git repository with "
3180 "'got checkout'.\n"
3181 "The got(1) manual page contains more information.", cmdname);
3182 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3183 got_repo_close(repo);
3184 return err;
3187 static const struct got_error *
3188 cmd_update(int argc, char *argv[])
3190 const struct got_error *error = NULL;
3191 struct got_repository *repo = NULL;
3192 struct got_worktree *worktree = NULL;
3193 char *worktree_path = NULL;
3194 struct got_object_id *commit_id = NULL;
3195 char *commit_id_str = NULL;
3196 const char *branch_name = NULL;
3197 struct got_reference *head_ref = NULL;
3198 struct got_pathlist_head paths;
3199 struct got_pathlist_entry *pe;
3200 int ch;
3201 struct got_update_progress_arg upa;
3203 TAILQ_INIT(&paths);
3205 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3206 switch (ch) {
3207 case 'b':
3208 branch_name = optarg;
3209 break;
3210 case 'c':
3211 commit_id_str = strdup(optarg);
3212 if (commit_id_str == NULL)
3213 return got_error_from_errno("strdup");
3214 break;
3215 default:
3216 usage_update();
3217 /* NOTREACHED */
3221 argc -= optind;
3222 argv += optind;
3224 #ifndef PROFILE
3225 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3226 "unveil", NULL) == -1)
3227 err(1, "pledge");
3228 #endif
3229 worktree_path = getcwd(NULL, 0);
3230 if (worktree_path == NULL) {
3231 error = got_error_from_errno("getcwd");
3232 goto done;
3234 error = got_worktree_open(&worktree, worktree_path);
3235 if (error) {
3236 if (error->code == GOT_ERR_NOT_WORKTREE)
3237 error = wrap_not_worktree_error(error, "update",
3238 worktree_path);
3239 goto done;
3242 error = check_rebase_or_histedit_in_progress(worktree);
3243 if (error)
3244 goto done;
3246 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3247 NULL);
3248 if (error != NULL)
3249 goto done;
3251 error = apply_unveil(got_repo_get_path(repo), 0,
3252 got_worktree_get_root_path(worktree));
3253 if (error)
3254 goto done;
3256 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3257 if (error)
3258 goto done;
3260 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3261 got_worktree_get_head_ref_name(worktree), 0);
3262 if (error != NULL)
3263 goto done;
3264 if (commit_id_str == NULL) {
3265 error = got_ref_resolve(&commit_id, repo, head_ref);
3266 if (error != NULL)
3267 goto done;
3268 error = got_object_id_str(&commit_id_str, commit_id);
3269 if (error != NULL)
3270 goto done;
3271 } else {
3272 struct got_reflist_head refs;
3273 TAILQ_INIT(&refs);
3274 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3275 NULL);
3276 if (error)
3277 goto done;
3278 error = got_repo_match_object_id(&commit_id, NULL,
3279 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3280 got_ref_list_free(&refs);
3281 free(commit_id_str);
3282 commit_id_str = NULL;
3283 if (error)
3284 goto done;
3285 error = got_object_id_str(&commit_id_str, commit_id);
3286 if (error)
3287 goto done;
3290 if (branch_name) {
3291 struct got_object_id *head_commit_id;
3292 TAILQ_FOREACH(pe, &paths, entry) {
3293 if (pe->path_len == 0)
3294 continue;
3295 error = got_error_msg(GOT_ERR_BAD_PATH,
3296 "switching between branches requires that "
3297 "the entire work tree gets updated");
3298 goto done;
3300 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3301 if (error)
3302 goto done;
3303 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3304 repo);
3305 free(head_commit_id);
3306 if (error != NULL)
3307 goto done;
3308 error = check_same_branch(commit_id, head_ref, NULL, repo);
3309 if (error)
3310 goto done;
3311 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3312 if (error)
3313 goto done;
3314 } else {
3315 error = check_linear_ancestry(commit_id,
3316 got_worktree_get_base_commit_id(worktree), 0, repo);
3317 if (error != NULL) {
3318 if (error->code == GOT_ERR_ANCESTRY)
3319 error = got_error(GOT_ERR_BRANCH_MOVED);
3320 goto done;
3322 error = check_same_branch(commit_id, head_ref, NULL, repo);
3323 if (error)
3324 goto done;
3327 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3328 commit_id) != 0) {
3329 error = got_worktree_set_base_commit_id(worktree, repo,
3330 commit_id);
3331 if (error)
3332 goto done;
3335 memset(&upa, 0, sizeof(upa));
3336 error = got_worktree_checkout_files(worktree, &paths, repo,
3337 update_progress, &upa, check_cancelled, NULL);
3338 if (error != NULL)
3339 goto done;
3341 if (upa.did_something)
3342 printf("Updated to commit %s\n", commit_id_str);
3343 else
3344 printf("Already up-to-date\n");
3345 print_update_progress_stats(&upa);
3346 done:
3347 free(worktree_path);
3348 TAILQ_FOREACH(pe, &paths, entry)
3349 free((char *)pe->path);
3350 got_pathlist_free(&paths);
3351 free(commit_id);
3352 free(commit_id_str);
3353 return error;
3356 static const struct got_error *
3357 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3358 const char *path, int diff_context, int ignore_whitespace,
3359 int force_text_diff, struct got_repository *repo)
3361 const struct got_error *err = NULL;
3362 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3364 if (blob_id1) {
3365 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3366 if (err)
3367 goto done;
3370 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3371 if (err)
3372 goto done;
3374 while (path[0] == '/')
3375 path++;
3376 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3377 diff_context, ignore_whitespace, force_text_diff, stdout);
3378 done:
3379 if (blob1)
3380 got_object_blob_close(blob1);
3381 got_object_blob_close(blob2);
3382 return err;
3385 static const struct got_error *
3386 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3387 const char *path, int diff_context, int ignore_whitespace,
3388 int force_text_diff, struct got_repository *repo)
3390 const struct got_error *err = NULL;
3391 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3392 struct got_diff_blob_output_unidiff_arg arg;
3394 if (tree_id1) {
3395 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3396 if (err)
3397 goto done;
3400 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3401 if (err)
3402 goto done;
3404 arg.diff_context = diff_context;
3405 arg.ignore_whitespace = ignore_whitespace;
3406 arg.force_text_diff = force_text_diff;
3407 arg.outfile = stdout;
3408 arg.line_offsets = NULL;
3409 arg.nlines = 0;
3410 while (path[0] == '/')
3411 path++;
3412 err = got_diff_tree(tree1, tree2, path, path, repo,
3413 got_diff_blob_output_unidiff, &arg, 1);
3414 done:
3415 if (tree1)
3416 got_object_tree_close(tree1);
3417 if (tree2)
3418 got_object_tree_close(tree2);
3419 return err;
3422 static const struct got_error *
3423 get_changed_paths(struct got_pathlist_head *paths,
3424 struct got_commit_object *commit, struct got_repository *repo)
3426 const struct got_error *err = NULL;
3427 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3428 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3429 struct got_object_qid *qid;
3431 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3432 if (qid != NULL) {
3433 struct got_commit_object *pcommit;
3434 err = got_object_open_as_commit(&pcommit, repo,
3435 qid->id);
3436 if (err)
3437 return err;
3439 tree_id1 = got_object_id_dup(
3440 got_object_commit_get_tree_id(pcommit));
3441 if (tree_id1 == NULL) {
3442 got_object_commit_close(pcommit);
3443 return got_error_from_errno("got_object_id_dup");
3445 got_object_commit_close(pcommit);
3449 if (tree_id1) {
3450 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3451 if (err)
3452 goto done;
3455 tree_id2 = got_object_commit_get_tree_id(commit);
3456 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3457 if (err)
3458 goto done;
3460 err = got_diff_tree(tree1, tree2, "", "", repo,
3461 got_diff_tree_collect_changed_paths, paths, 0);
3462 done:
3463 if (tree1)
3464 got_object_tree_close(tree1);
3465 if (tree2)
3466 got_object_tree_close(tree2);
3467 free(tree_id1);
3468 return err;
3471 static const struct got_error *
3472 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3473 const char *path, int diff_context, struct got_repository *repo)
3475 const struct got_error *err = NULL;
3476 struct got_commit_object *pcommit = NULL;
3477 char *id_str1 = NULL, *id_str2 = NULL;
3478 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3479 struct got_object_qid *qid;
3481 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3482 if (qid != NULL) {
3483 err = got_object_open_as_commit(&pcommit, repo,
3484 qid->id);
3485 if (err)
3486 return err;
3489 if (path && path[0] != '\0') {
3490 int obj_type;
3491 err = got_object_id_by_path(&obj_id2, repo, id, path);
3492 if (err)
3493 goto done;
3494 err = got_object_id_str(&id_str2, obj_id2);
3495 if (err) {
3496 free(obj_id2);
3497 goto done;
3499 if (pcommit) {
3500 err = got_object_id_by_path(&obj_id1, repo,
3501 qid->id, path);
3502 if (err) {
3503 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3504 free(obj_id2);
3505 goto done;
3507 } else {
3508 err = got_object_id_str(&id_str1, obj_id1);
3509 if (err) {
3510 free(obj_id2);
3511 goto done;
3515 err = got_object_get_type(&obj_type, repo, obj_id2);
3516 if (err) {
3517 free(obj_id2);
3518 goto done;
3520 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3521 switch (obj_type) {
3522 case GOT_OBJ_TYPE_BLOB:
3523 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3524 0, 0, repo);
3525 break;
3526 case GOT_OBJ_TYPE_TREE:
3527 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3528 0, 0, repo);
3529 break;
3530 default:
3531 err = got_error(GOT_ERR_OBJ_TYPE);
3532 break;
3534 free(obj_id1);
3535 free(obj_id2);
3536 } else {
3537 obj_id2 = got_object_commit_get_tree_id(commit);
3538 err = got_object_id_str(&id_str2, obj_id2);
3539 if (err)
3540 goto done;
3541 if (pcommit) {
3542 obj_id1 = got_object_commit_get_tree_id(pcommit);
3543 err = got_object_id_str(&id_str1, obj_id1);
3544 if (err)
3545 goto done;
3547 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3548 id_str2);
3549 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3550 repo);
3552 done:
3553 free(id_str1);
3554 free(id_str2);
3555 if (pcommit)
3556 got_object_commit_close(pcommit);
3557 return err;
3560 static char *
3561 get_datestr(time_t *time, char *datebuf)
3563 struct tm mytm, *tm;
3564 char *p, *s;
3566 tm = gmtime_r(time, &mytm);
3567 if (tm == NULL)
3568 return NULL;
3569 s = asctime_r(tm, datebuf);
3570 if (s == NULL)
3571 return NULL;
3572 p = strchr(s, '\n');
3573 if (p)
3574 *p = '\0';
3575 return s;
3578 static const struct got_error *
3579 match_logmsg(int *have_match, struct got_object_id *id,
3580 struct got_commit_object *commit, regex_t *regex)
3582 const struct got_error *err = NULL;
3583 regmatch_t regmatch;
3584 char *id_str = NULL, *logmsg = NULL;
3586 *have_match = 0;
3588 err = got_object_id_str(&id_str, id);
3589 if (err)
3590 return err;
3592 err = got_object_commit_get_logmsg(&logmsg, commit);
3593 if (err)
3594 goto done;
3596 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3597 *have_match = 1;
3598 done:
3599 free(id_str);
3600 free(logmsg);
3601 return err;
3604 static void
3605 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3606 regex_t *regex)
3608 regmatch_t regmatch;
3609 struct got_pathlist_entry *pe;
3611 *have_match = 0;
3613 TAILQ_FOREACH(pe, changed_paths, entry) {
3614 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3615 *have_match = 1;
3616 break;
3621 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3623 static const struct got_error*
3624 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3625 struct got_object_id *id, struct got_repository *repo)
3627 static const struct got_error *err = NULL;
3628 struct got_reflist_entry *re;
3629 char *s;
3630 const char *name;
3632 *refs_str = NULL;
3634 TAILQ_FOREACH(re, refs, entry) {
3635 struct got_tag_object *tag = NULL;
3636 struct got_object_id *ref_id;
3637 int cmp;
3639 name = got_ref_get_name(re->ref);
3640 if (strcmp(name, GOT_REF_HEAD) == 0)
3641 continue;
3642 if (strncmp(name, "refs/", 5) == 0)
3643 name += 5;
3644 if (strncmp(name, "got/", 4) == 0)
3645 continue;
3646 if (strncmp(name, "heads/", 6) == 0)
3647 name += 6;
3648 if (strncmp(name, "remotes/", 8) == 0) {
3649 name += 8;
3650 s = strstr(name, "/" GOT_REF_HEAD);
3651 if (s != NULL && s[strlen(s)] == '\0')
3652 continue;
3654 err = got_ref_resolve(&ref_id, repo, re->ref);
3655 if (err)
3656 break;
3657 if (strncmp(name, "tags/", 5) == 0) {
3658 err = got_object_open_as_tag(&tag, repo, ref_id);
3659 if (err) {
3660 if (err->code != GOT_ERR_OBJ_TYPE) {
3661 free(ref_id);
3662 break;
3664 /* Ref points at something other than a tag. */
3665 err = NULL;
3666 tag = NULL;
3669 cmp = got_object_id_cmp(tag ?
3670 got_object_tag_get_object_id(tag) : ref_id, id);
3671 free(ref_id);
3672 if (tag)
3673 got_object_tag_close(tag);
3674 if (cmp != 0)
3675 continue;
3676 s = *refs_str;
3677 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3678 s ? ", " : "", name) == -1) {
3679 err = got_error_from_errno("asprintf");
3680 free(s);
3681 *refs_str = NULL;
3682 break;
3684 free(s);
3687 return err;
3690 static const struct got_error *
3691 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3692 struct got_repository *repo, const char *path,
3693 struct got_pathlist_head *changed_paths, int show_patch,
3694 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3695 const char *custom_refs_str)
3697 const struct got_error *err = NULL;
3698 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3699 char datebuf[26];
3700 time_t committer_time;
3701 const char *author, *committer;
3702 char *refs_str = NULL;
3704 err = got_object_id_str(&id_str, id);
3705 if (err)
3706 return err;
3708 if (custom_refs_str == NULL) {
3709 struct got_reflist_head *refs;
3710 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3711 if (refs) {
3712 err = build_refs_str(&refs_str, refs, id, repo);
3713 if (err)
3714 goto done;
3718 printf(GOT_COMMIT_SEP_STR);
3719 if (custom_refs_str)
3720 printf("commit %s (%s)\n", id_str, custom_refs_str);
3721 else
3722 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3723 refs_str ? refs_str : "", refs_str ? ")" : "");
3724 free(id_str);
3725 id_str = NULL;
3726 free(refs_str);
3727 refs_str = NULL;
3728 printf("from: %s\n", got_object_commit_get_author(commit));
3729 committer_time = got_object_commit_get_committer_time(commit);
3730 datestr = get_datestr(&committer_time, datebuf);
3731 if (datestr)
3732 printf("date: %s UTC\n", datestr);
3733 author = got_object_commit_get_author(commit);
3734 committer = got_object_commit_get_committer(commit);
3735 if (strcmp(author, committer) != 0)
3736 printf("via: %s\n", committer);
3737 if (got_object_commit_get_nparents(commit) > 1) {
3738 const struct got_object_id_queue *parent_ids;
3739 struct got_object_qid *qid;
3740 int n = 1;
3741 parent_ids = got_object_commit_get_parent_ids(commit);
3742 STAILQ_FOREACH(qid, parent_ids, entry) {
3743 err = got_object_id_str(&id_str, qid->id);
3744 if (err)
3745 goto done;
3746 printf("parent %d: %s\n", n++, id_str);
3747 free(id_str);
3748 id_str = NULL;
3752 err = got_object_commit_get_logmsg(&logmsg0, commit);
3753 if (err)
3754 goto done;
3756 logmsg = logmsg0;
3757 do {
3758 line = strsep(&logmsg, "\n");
3759 if (line)
3760 printf(" %s\n", line);
3761 } while (line);
3762 free(logmsg0);
3764 if (changed_paths) {
3765 struct got_pathlist_entry *pe;
3766 TAILQ_FOREACH(pe, changed_paths, entry) {
3767 struct got_diff_changed_path *cp = pe->data;
3768 printf(" %c %s\n", cp->status, pe->path);
3770 printf("\n");
3772 if (show_patch) {
3773 err = print_patch(commit, id, path, diff_context, repo);
3774 if (err == 0)
3775 printf("\n");
3778 if (fflush(stdout) != 0 && err == NULL)
3779 err = got_error_from_errno("fflush");
3780 done:
3781 free(id_str);
3782 free(refs_str);
3783 return err;
3786 static const struct got_error *
3787 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3788 struct got_repository *repo, const char *path, int show_changed_paths,
3789 int show_patch, const char *search_pattern, int diff_context, int limit,
3790 int log_branches, int reverse_display_order,
3791 struct got_reflist_object_id_map *refs_idmap)
3793 const struct got_error *err;
3794 struct got_commit_graph *graph;
3795 regex_t regex;
3796 int have_match;
3797 struct got_object_id_queue reversed_commits;
3798 struct got_object_qid *qid;
3799 struct got_commit_object *commit;
3800 struct got_pathlist_head changed_paths;
3801 struct got_pathlist_entry *pe;
3803 STAILQ_INIT(&reversed_commits);
3804 TAILQ_INIT(&changed_paths);
3806 if (search_pattern && regcomp(&regex, search_pattern,
3807 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3808 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3810 err = got_commit_graph_open(&graph, path, !log_branches);
3811 if (err)
3812 return err;
3813 err = got_commit_graph_iter_start(graph, root_id, repo,
3814 check_cancelled, NULL);
3815 if (err)
3816 goto done;
3817 for (;;) {
3818 struct got_object_id *id;
3820 if (sigint_received || sigpipe_received)
3821 break;
3823 err = got_commit_graph_iter_next(&id, graph, repo,
3824 check_cancelled, NULL);
3825 if (err) {
3826 if (err->code == GOT_ERR_ITER_COMPLETED)
3827 err = NULL;
3828 break;
3830 if (id == NULL)
3831 break;
3833 err = got_object_open_as_commit(&commit, repo, id);
3834 if (err)
3835 break;
3837 if (show_changed_paths && !reverse_display_order) {
3838 err = get_changed_paths(&changed_paths, commit, repo);
3839 if (err)
3840 break;
3843 if (search_pattern) {
3844 err = match_logmsg(&have_match, id, commit, &regex);
3845 if (err) {
3846 got_object_commit_close(commit);
3847 break;
3849 if (have_match == 0 && show_changed_paths)
3850 match_changed_paths(&have_match,
3851 &changed_paths, &regex);
3852 if (have_match == 0) {
3853 got_object_commit_close(commit);
3854 TAILQ_FOREACH(pe, &changed_paths, entry) {
3855 free((char *)pe->path);
3856 free(pe->data);
3858 got_pathlist_free(&changed_paths);
3859 continue;
3863 if (reverse_display_order) {
3864 err = got_object_qid_alloc(&qid, id);
3865 if (err)
3866 break;
3867 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3868 got_object_commit_close(commit);
3869 } else {
3870 err = print_commit(commit, id, repo, path,
3871 show_changed_paths ? &changed_paths : NULL,
3872 show_patch, diff_context, refs_idmap, NULL);
3873 got_object_commit_close(commit);
3874 if (err)
3875 break;
3877 if ((limit && --limit == 0) ||
3878 (end_id && got_object_id_cmp(id, end_id) == 0))
3879 break;
3881 TAILQ_FOREACH(pe, &changed_paths, entry) {
3882 free((char *)pe->path);
3883 free(pe->data);
3885 got_pathlist_free(&changed_paths);
3887 if (reverse_display_order) {
3888 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3889 err = got_object_open_as_commit(&commit, repo, qid->id);
3890 if (err)
3891 break;
3892 if (show_changed_paths) {
3893 err = get_changed_paths(&changed_paths,
3894 commit, repo);
3895 if (err)
3896 break;
3898 err = print_commit(commit, qid->id, repo, path,
3899 show_changed_paths ? &changed_paths : NULL,
3900 show_patch, diff_context, refs_idmap, NULL);
3901 got_object_commit_close(commit);
3902 if (err)
3903 break;
3904 TAILQ_FOREACH(pe, &changed_paths, entry) {
3905 free((char *)pe->path);
3906 free(pe->data);
3908 got_pathlist_free(&changed_paths);
3911 done:
3912 while (!STAILQ_EMPTY(&reversed_commits)) {
3913 qid = STAILQ_FIRST(&reversed_commits);
3914 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3915 got_object_qid_free(qid);
3917 TAILQ_FOREACH(pe, &changed_paths, entry) {
3918 free((char *)pe->path);
3919 free(pe->data);
3921 got_pathlist_free(&changed_paths);
3922 if (search_pattern)
3923 regfree(&regex);
3924 got_commit_graph_close(graph);
3925 return err;
3928 __dead static void
3929 usage_log(void)
3931 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3932 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3933 "[-R] [path]\n", getprogname());
3934 exit(1);
3937 static int
3938 get_default_log_limit(void)
3940 const char *got_default_log_limit;
3941 long long n;
3942 const char *errstr;
3944 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3945 if (got_default_log_limit == NULL)
3946 return 0;
3947 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3948 if (errstr != NULL)
3949 return 0;
3950 return n;
3953 static const struct got_error *
3954 cmd_log(int argc, char *argv[])
3956 const struct got_error *error;
3957 struct got_repository *repo = NULL;
3958 struct got_worktree *worktree = NULL;
3959 struct got_object_id *start_id = NULL, *end_id = NULL;
3960 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3961 const char *start_commit = NULL, *end_commit = NULL;
3962 const char *search_pattern = NULL;
3963 int diff_context = -1, ch;
3964 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3965 int reverse_display_order = 0;
3966 const char *errstr;
3967 struct got_reflist_head refs;
3968 struct got_reflist_object_id_map *refs_idmap = NULL;
3970 TAILQ_INIT(&refs);
3972 #ifndef PROFILE
3973 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3974 NULL)
3975 == -1)
3976 err(1, "pledge");
3977 #endif
3979 limit = get_default_log_limit();
3981 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3982 switch (ch) {
3983 case 'p':
3984 show_patch = 1;
3985 break;
3986 case 'P':
3987 show_changed_paths = 1;
3988 break;
3989 case 'c':
3990 start_commit = optarg;
3991 break;
3992 case 'C':
3993 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3994 &errstr);
3995 if (errstr != NULL)
3996 err(1, "-C option %s", errstr);
3997 break;
3998 case 'l':
3999 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4000 if (errstr != NULL)
4001 err(1, "-l option %s", errstr);
4002 break;
4003 case 'b':
4004 log_branches = 1;
4005 break;
4006 case 'r':
4007 repo_path = realpath(optarg, NULL);
4008 if (repo_path == NULL)
4009 return got_error_from_errno2("realpath",
4010 optarg);
4011 got_path_strip_trailing_slashes(repo_path);
4012 break;
4013 case 'R':
4014 reverse_display_order = 1;
4015 break;
4016 case 's':
4017 search_pattern = optarg;
4018 break;
4019 case 'x':
4020 end_commit = optarg;
4021 break;
4022 default:
4023 usage_log();
4024 /* NOTREACHED */
4028 argc -= optind;
4029 argv += optind;
4031 if (diff_context == -1)
4032 diff_context = 3;
4033 else if (!show_patch)
4034 errx(1, "-C requires -p");
4036 cwd = getcwd(NULL, 0);
4037 if (cwd == NULL) {
4038 error = got_error_from_errno("getcwd");
4039 goto done;
4042 if (repo_path == NULL) {
4043 error = got_worktree_open(&worktree, cwd);
4044 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4045 goto done;
4046 error = NULL;
4049 if (argc == 1) {
4050 if (worktree) {
4051 error = got_worktree_resolve_path(&path, worktree,
4052 argv[0]);
4053 if (error)
4054 goto done;
4055 } else {
4056 path = strdup(argv[0]);
4057 if (path == NULL) {
4058 error = got_error_from_errno("strdup");
4059 goto done;
4062 } else if (argc != 0)
4063 usage_log();
4065 if (repo_path == NULL) {
4066 repo_path = worktree ?
4067 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4069 if (repo_path == NULL) {
4070 error = got_error_from_errno("strdup");
4071 goto done;
4074 error = got_repo_open(&repo, repo_path, NULL);
4075 if (error != NULL)
4076 goto done;
4078 error = apply_unveil(got_repo_get_path(repo), 1,
4079 worktree ? got_worktree_get_root_path(worktree) : NULL);
4080 if (error)
4081 goto done;
4083 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4084 if (error)
4085 goto done;
4087 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4088 if (error)
4089 goto done;
4091 if (start_commit == NULL) {
4092 struct got_reference *head_ref;
4093 struct got_commit_object *commit = NULL;
4094 error = got_ref_open(&head_ref, repo,
4095 worktree ? got_worktree_get_head_ref_name(worktree)
4096 : GOT_REF_HEAD, 0);
4097 if (error != NULL)
4098 goto done;
4099 error = got_ref_resolve(&start_id, repo, head_ref);
4100 got_ref_close(head_ref);
4101 if (error != NULL)
4102 goto done;
4103 error = got_object_open_as_commit(&commit, repo,
4104 start_id);
4105 if (error != NULL)
4106 goto done;
4107 got_object_commit_close(commit);
4108 } else {
4109 error = got_repo_match_object_id(&start_id, NULL,
4110 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4111 if (error != NULL)
4112 goto done;
4114 if (end_commit != NULL) {
4115 error = got_repo_match_object_id(&end_id, NULL,
4116 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4117 if (error != NULL)
4118 goto done;
4121 if (worktree) {
4123 * If a path was specified on the command line it was resolved
4124 * to a path in the work tree above. Prepend the work tree's
4125 * path prefix to obtain the corresponding in-repository path.
4127 if (path) {
4128 const char *prefix;
4129 prefix = got_worktree_get_path_prefix(worktree);
4130 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4131 (path[0] != '\0') ? "/" : "", path) == -1) {
4132 error = got_error_from_errno("asprintf");
4133 goto done;
4136 } else
4137 error = got_repo_map_path(&in_repo_path, repo,
4138 path ? path : "");
4139 if (error != NULL)
4140 goto done;
4141 if (in_repo_path) {
4142 free(path);
4143 path = in_repo_path;
4146 error = print_commits(start_id, end_id, repo, path ? path : "",
4147 show_changed_paths, show_patch, search_pattern, diff_context,
4148 limit, log_branches, reverse_display_order, refs_idmap);
4149 done:
4150 free(path);
4151 free(repo_path);
4152 free(cwd);
4153 if (worktree)
4154 got_worktree_close(worktree);
4155 if (repo) {
4156 const struct got_error *close_err = got_repo_close(repo);
4157 if (error == NULL)
4158 error = close_err;
4160 if (refs_idmap)
4161 got_reflist_object_id_map_free(refs_idmap);
4162 got_ref_list_free(&refs);
4163 return error;
4166 __dead static void
4167 usage_diff(void)
4169 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4170 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4171 exit(1);
4174 struct print_diff_arg {
4175 struct got_repository *repo;
4176 struct got_worktree *worktree;
4177 int diff_context;
4178 const char *id_str;
4179 int header_shown;
4180 int diff_staged;
4181 int ignore_whitespace;
4182 int force_text_diff;
4186 * Create a file which contains the target path of a symlink so we can feed
4187 * it as content to the diff engine.
4189 static const struct got_error *
4190 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4191 const char *abspath)
4193 const struct got_error *err = NULL;
4194 char target_path[PATH_MAX];
4195 ssize_t target_len, outlen;
4197 *fd = -1;
4199 if (dirfd != -1) {
4200 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4201 if (target_len == -1)
4202 return got_error_from_errno2("readlinkat", abspath);
4203 } else {
4204 target_len = readlink(abspath, target_path, PATH_MAX);
4205 if (target_len == -1)
4206 return got_error_from_errno2("readlink", abspath);
4209 *fd = got_opentempfd();
4210 if (*fd == -1)
4211 return got_error_from_errno("got_opentempfd");
4213 outlen = write(*fd, target_path, target_len);
4214 if (outlen == -1) {
4215 err = got_error_from_errno("got_opentempfd");
4216 goto done;
4219 if (lseek(*fd, 0, SEEK_SET) == -1) {
4220 err = got_error_from_errno2("lseek", abspath);
4221 goto done;
4223 done:
4224 if (err) {
4225 close(*fd);
4226 *fd = -1;
4228 return err;
4231 static const struct got_error *
4232 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4233 const char *path, struct got_object_id *blob_id,
4234 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4235 int dirfd, const char *de_name)
4237 struct print_diff_arg *a = arg;
4238 const struct got_error *err = NULL;
4239 struct got_blob_object *blob1 = NULL;
4240 int fd = -1;
4241 FILE *f2 = NULL;
4242 char *abspath = NULL, *label1 = NULL;
4243 struct stat sb;
4245 if (a->diff_staged) {
4246 if (staged_status != GOT_STATUS_MODIFY &&
4247 staged_status != GOT_STATUS_ADD &&
4248 staged_status != GOT_STATUS_DELETE)
4249 return NULL;
4250 } else {
4251 if (staged_status == GOT_STATUS_DELETE)
4252 return NULL;
4253 if (status == GOT_STATUS_NONEXISTENT)
4254 return got_error_set_errno(ENOENT, path);
4255 if (status != GOT_STATUS_MODIFY &&
4256 status != GOT_STATUS_ADD &&
4257 status != GOT_STATUS_DELETE &&
4258 status != GOT_STATUS_CONFLICT)
4259 return NULL;
4262 if (!a->header_shown) {
4263 printf("diff %s %s%s\n", a->id_str,
4264 got_worktree_get_root_path(a->worktree),
4265 a->diff_staged ? " (staged changes)" : "");
4266 a->header_shown = 1;
4269 if (a->diff_staged) {
4270 const char *label1 = NULL, *label2 = NULL;
4271 switch (staged_status) {
4272 case GOT_STATUS_MODIFY:
4273 label1 = path;
4274 label2 = path;
4275 break;
4276 case GOT_STATUS_ADD:
4277 label2 = path;
4278 break;
4279 case GOT_STATUS_DELETE:
4280 label1 = path;
4281 break;
4282 default:
4283 return got_error(GOT_ERR_FILE_STATUS);
4285 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4286 staged_blob_id, label1, label2, a->diff_context,
4287 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4290 if (staged_status == GOT_STATUS_ADD ||
4291 staged_status == GOT_STATUS_MODIFY) {
4292 char *id_str;
4293 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4294 8192);
4295 if (err)
4296 goto done;
4297 err = got_object_id_str(&id_str, staged_blob_id);
4298 if (err)
4299 goto done;
4300 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4301 err = got_error_from_errno("asprintf");
4302 free(id_str);
4303 goto done;
4305 free(id_str);
4306 } else if (status != GOT_STATUS_ADD) {
4307 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4308 if (err)
4309 goto done;
4312 if (status != GOT_STATUS_DELETE) {
4313 if (asprintf(&abspath, "%s/%s",
4314 got_worktree_get_root_path(a->worktree), path) == -1) {
4315 err = got_error_from_errno("asprintf");
4316 goto done;
4319 if (dirfd != -1) {
4320 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4321 if (fd == -1) {
4322 if (errno != ELOOP) {
4323 err = got_error_from_errno2("openat",
4324 abspath);
4325 goto done;
4327 err = get_symlink_target_file(&fd, dirfd,
4328 de_name, abspath);
4329 if (err)
4330 goto done;
4332 } else {
4333 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4334 if (fd == -1) {
4335 if (errno != ELOOP) {
4336 err = got_error_from_errno2("open",
4337 abspath);
4338 goto done;
4340 err = get_symlink_target_file(&fd, dirfd,
4341 de_name, abspath);
4342 if (err)
4343 goto done;
4346 if (fstat(fd, &sb) == -1) {
4347 err = got_error_from_errno2("fstat", abspath);
4348 goto done;
4350 f2 = fdopen(fd, "r");
4351 if (f2 == NULL) {
4352 err = got_error_from_errno2("fdopen", abspath);
4353 goto done;
4355 fd = -1;
4356 } else
4357 sb.st_size = 0;
4359 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4360 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4361 done:
4362 if (blob1)
4363 got_object_blob_close(blob1);
4364 if (f2 && fclose(f2) == EOF && err == NULL)
4365 err = got_error_from_errno("fclose");
4366 if (fd != -1 && close(fd) == -1 && err == NULL)
4367 err = got_error_from_errno("close");
4368 free(abspath);
4369 return err;
4372 static const struct got_error *
4373 cmd_diff(int argc, char *argv[])
4375 const struct got_error *error;
4376 struct got_repository *repo = NULL;
4377 struct got_worktree *worktree = NULL;
4378 char *cwd = NULL, *repo_path = NULL;
4379 struct got_object_id *id1 = NULL, *id2 = NULL;
4380 const char *id_str1 = NULL, *id_str2 = NULL;
4381 char *label1 = NULL, *label2 = NULL;
4382 int type1, type2;
4383 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4384 int force_text_diff = 0;
4385 const char *errstr;
4386 char *path = NULL;
4387 struct got_reflist_head refs;
4389 TAILQ_INIT(&refs);
4391 #ifndef PROFILE
4392 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4393 NULL) == -1)
4394 err(1, "pledge");
4395 #endif
4397 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4398 switch (ch) {
4399 case 'a':
4400 force_text_diff = 1;
4401 break;
4402 case 'C':
4403 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4404 &errstr);
4405 if (errstr != NULL)
4406 err(1, "-C option %s", errstr);
4407 break;
4408 case 'r':
4409 repo_path = realpath(optarg, NULL);
4410 if (repo_path == NULL)
4411 return got_error_from_errno2("realpath",
4412 optarg);
4413 got_path_strip_trailing_slashes(repo_path);
4414 break;
4415 case 's':
4416 diff_staged = 1;
4417 break;
4418 case 'w':
4419 ignore_whitespace = 1;
4420 break;
4421 default:
4422 usage_diff();
4423 /* NOTREACHED */
4427 argc -= optind;
4428 argv += optind;
4430 cwd = getcwd(NULL, 0);
4431 if (cwd == NULL) {
4432 error = got_error_from_errno("getcwd");
4433 goto done;
4435 if (argc <= 1) {
4436 if (repo_path)
4437 errx(1,
4438 "-r option can't be used when diffing a work tree");
4439 error = got_worktree_open(&worktree, cwd);
4440 if (error) {
4441 if (error->code == GOT_ERR_NOT_WORKTREE)
4442 error = wrap_not_worktree_error(error, "diff",
4443 cwd);
4444 goto done;
4446 repo_path = strdup(got_worktree_get_repo_path(worktree));
4447 if (repo_path == NULL) {
4448 error = got_error_from_errno("strdup");
4449 goto done;
4451 if (argc == 1) {
4452 error = got_worktree_resolve_path(&path, worktree,
4453 argv[0]);
4454 if (error)
4455 goto done;
4456 } else {
4457 path = strdup("");
4458 if (path == NULL) {
4459 error = got_error_from_errno("strdup");
4460 goto done;
4463 } else if (argc == 2) {
4464 if (diff_staged)
4465 errx(1, "-s option can't be used when diffing "
4466 "objects in repository");
4467 id_str1 = argv[0];
4468 id_str2 = argv[1];
4469 if (repo_path == NULL) {
4470 error = got_worktree_open(&worktree, cwd);
4471 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4472 goto done;
4473 repo_path = strdup(worktree ?
4474 got_worktree_get_repo_path(worktree) : cwd);
4475 if (repo_path == NULL) {
4476 error = got_error_from_errno("strdup");
4477 goto done;
4480 } else
4481 usage_diff();
4483 error = got_repo_open(&repo, repo_path, NULL);
4484 free(repo_path);
4485 if (error != NULL)
4486 goto done;
4488 error = apply_unveil(got_repo_get_path(repo), 1,
4489 worktree ? got_worktree_get_root_path(worktree) : NULL);
4490 if (error)
4491 goto done;
4493 if (argc <= 1) {
4494 struct print_diff_arg arg;
4495 struct got_pathlist_head paths;
4496 char *id_str;
4498 TAILQ_INIT(&paths);
4500 error = got_object_id_str(&id_str,
4501 got_worktree_get_base_commit_id(worktree));
4502 if (error)
4503 goto done;
4504 arg.repo = repo;
4505 arg.worktree = worktree;
4506 arg.diff_context = diff_context;
4507 arg.id_str = id_str;
4508 arg.header_shown = 0;
4509 arg.diff_staged = diff_staged;
4510 arg.ignore_whitespace = ignore_whitespace;
4511 arg.force_text_diff = force_text_diff;
4513 error = got_pathlist_append(&paths, path, NULL);
4514 if (error)
4515 goto done;
4517 error = got_worktree_status(worktree, &paths, repo, 0,
4518 print_diff, &arg, check_cancelled, NULL);
4519 free(id_str);
4520 got_pathlist_free(&paths);
4521 goto done;
4524 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4525 if (error)
4526 return error;
4528 error = got_repo_match_object_id(&id1, &label1, id_str1,
4529 GOT_OBJ_TYPE_ANY, &refs, repo);
4530 if (error)
4531 goto done;
4533 error = got_repo_match_object_id(&id2, &label2, id_str2,
4534 GOT_OBJ_TYPE_ANY, &refs, repo);
4535 if (error)
4536 goto done;
4538 error = got_object_get_type(&type1, repo, id1);
4539 if (error)
4540 goto done;
4542 error = got_object_get_type(&type2, repo, id2);
4543 if (error)
4544 goto done;
4546 if (type1 != type2) {
4547 error = got_error(GOT_ERR_OBJ_TYPE);
4548 goto done;
4551 switch (type1) {
4552 case GOT_OBJ_TYPE_BLOB:
4553 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4554 NULL, NULL, diff_context, ignore_whitespace,
4555 force_text_diff, repo, stdout);
4556 break;
4557 case GOT_OBJ_TYPE_TREE:
4558 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4559 "", "", diff_context, ignore_whitespace, force_text_diff,
4560 repo, stdout);
4561 break;
4562 case GOT_OBJ_TYPE_COMMIT:
4563 printf("diff %s %s\n", label1, label2);
4564 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4565 diff_context, ignore_whitespace, force_text_diff, repo,
4566 stdout);
4567 break;
4568 default:
4569 error = got_error(GOT_ERR_OBJ_TYPE);
4571 done:
4572 free(label1);
4573 free(label2);
4574 free(id1);
4575 free(id2);
4576 free(path);
4577 if (worktree)
4578 got_worktree_close(worktree);
4579 if (repo) {
4580 const struct got_error *close_err = got_repo_close(repo);
4581 if (error == NULL)
4582 error = close_err;
4584 got_ref_list_free(&refs);
4585 return error;
4588 __dead static void
4589 usage_blame(void)
4591 fprintf(stderr,
4592 "usage: %s blame [-c commit] [-r repository-path] path\n",
4593 getprogname());
4594 exit(1);
4597 struct blame_line {
4598 int annotated;
4599 char *id_str;
4600 char *committer;
4601 char datebuf[11]; /* YYYY-MM-DD + NUL */
4604 struct blame_cb_args {
4605 struct blame_line *lines;
4606 int nlines;
4607 int nlines_prec;
4608 int lineno_cur;
4609 off_t *line_offsets;
4610 FILE *f;
4611 struct got_repository *repo;
4614 static const struct got_error *
4615 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4617 const struct got_error *err = NULL;
4618 struct blame_cb_args *a = arg;
4619 struct blame_line *bline;
4620 char *line = NULL;
4621 size_t linesize = 0;
4622 struct got_commit_object *commit = NULL;
4623 off_t offset;
4624 struct tm tm;
4625 time_t committer_time;
4627 if (nlines != a->nlines ||
4628 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4629 return got_error(GOT_ERR_RANGE);
4631 if (sigint_received)
4632 return got_error(GOT_ERR_ITER_COMPLETED);
4634 if (lineno == -1)
4635 return NULL; /* no change in this commit */
4637 /* Annotate this line. */
4638 bline = &a->lines[lineno - 1];
4639 if (bline->annotated)
4640 return NULL;
4641 err = got_object_id_str(&bline->id_str, id);
4642 if (err)
4643 return err;
4645 err = got_object_open_as_commit(&commit, a->repo, id);
4646 if (err)
4647 goto done;
4649 bline->committer = strdup(got_object_commit_get_committer(commit));
4650 if (bline->committer == NULL) {
4651 err = got_error_from_errno("strdup");
4652 goto done;
4655 committer_time = got_object_commit_get_committer_time(commit);
4656 if (gmtime_r(&committer_time, &tm) == NULL)
4657 return got_error_from_errno("gmtime_r");
4658 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4659 &tm) == 0) {
4660 err = got_error(GOT_ERR_NO_SPACE);
4661 goto done;
4663 bline->annotated = 1;
4665 /* Print lines annotated so far. */
4666 bline = &a->lines[a->lineno_cur - 1];
4667 if (!bline->annotated)
4668 goto done;
4670 offset = a->line_offsets[a->lineno_cur - 1];
4671 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4672 err = got_error_from_errno("fseeko");
4673 goto done;
4676 while (bline->annotated) {
4677 char *smallerthan, *at, *nl, *committer;
4678 size_t len;
4680 if (getline(&line, &linesize, a->f) == -1) {
4681 if (ferror(a->f))
4682 err = got_error_from_errno("getline");
4683 break;
4686 committer = bline->committer;
4687 smallerthan = strchr(committer, '<');
4688 if (smallerthan && smallerthan[1] != '\0')
4689 committer = smallerthan + 1;
4690 at = strchr(committer, '@');
4691 if (at)
4692 *at = '\0';
4693 len = strlen(committer);
4694 if (len >= 9)
4695 committer[8] = '\0';
4697 nl = strchr(line, '\n');
4698 if (nl)
4699 *nl = '\0';
4700 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4701 bline->id_str, bline->datebuf, committer, line);
4703 a->lineno_cur++;
4704 bline = &a->lines[a->lineno_cur - 1];
4706 done:
4707 if (commit)
4708 got_object_commit_close(commit);
4709 free(line);
4710 return err;
4713 static const struct got_error *
4714 cmd_blame(int argc, char *argv[])
4716 const struct got_error *error;
4717 struct got_repository *repo = NULL;
4718 struct got_worktree *worktree = NULL;
4719 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4720 char *link_target = NULL;
4721 struct got_object_id *obj_id = NULL;
4722 struct got_object_id *commit_id = NULL;
4723 struct got_blob_object *blob = NULL;
4724 char *commit_id_str = NULL;
4725 struct blame_cb_args bca;
4726 int ch, obj_type, i;
4727 off_t filesize;
4729 memset(&bca, 0, sizeof(bca));
4731 #ifndef PROFILE
4732 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4733 NULL) == -1)
4734 err(1, "pledge");
4735 #endif
4737 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4738 switch (ch) {
4739 case 'c':
4740 commit_id_str = optarg;
4741 break;
4742 case 'r':
4743 repo_path = realpath(optarg, NULL);
4744 if (repo_path == NULL)
4745 return got_error_from_errno2("realpath",
4746 optarg);
4747 got_path_strip_trailing_slashes(repo_path);
4748 break;
4749 default:
4750 usage_blame();
4751 /* NOTREACHED */
4755 argc -= optind;
4756 argv += optind;
4758 if (argc == 1)
4759 path = argv[0];
4760 else
4761 usage_blame();
4763 cwd = getcwd(NULL, 0);
4764 if (cwd == NULL) {
4765 error = got_error_from_errno("getcwd");
4766 goto done;
4768 if (repo_path == NULL) {
4769 error = got_worktree_open(&worktree, cwd);
4770 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4771 goto done;
4772 else
4773 error = NULL;
4774 if (worktree) {
4775 repo_path =
4776 strdup(got_worktree_get_repo_path(worktree));
4777 if (repo_path == NULL) {
4778 error = got_error_from_errno("strdup");
4779 if (error)
4780 goto done;
4782 } else {
4783 repo_path = strdup(cwd);
4784 if (repo_path == NULL) {
4785 error = got_error_from_errno("strdup");
4786 goto done;
4791 error = got_repo_open(&repo, repo_path, NULL);
4792 if (error != NULL)
4793 goto done;
4795 if (worktree) {
4796 const char *prefix = got_worktree_get_path_prefix(worktree);
4797 char *p;
4799 error = got_worktree_resolve_path(&p, worktree, path);
4800 if (error)
4801 goto done;
4802 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4803 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4804 p) == -1) {
4805 error = got_error_from_errno("asprintf");
4806 free(p);
4807 goto done;
4809 free(p);
4810 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4811 } else {
4812 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4813 if (error)
4814 goto done;
4815 error = got_repo_map_path(&in_repo_path, repo, path);
4817 if (error)
4818 goto done;
4820 if (commit_id_str == NULL) {
4821 struct got_reference *head_ref;
4822 error = got_ref_open(&head_ref, repo, worktree ?
4823 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4824 if (error != NULL)
4825 goto done;
4826 error = got_ref_resolve(&commit_id, repo, head_ref);
4827 got_ref_close(head_ref);
4828 if (error != NULL)
4829 goto done;
4830 } else {
4831 struct got_reflist_head refs;
4832 TAILQ_INIT(&refs);
4833 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4834 NULL);
4835 if (error)
4836 goto done;
4837 error = got_repo_match_object_id(&commit_id, NULL,
4838 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4839 got_ref_list_free(&refs);
4840 if (error)
4841 goto done;
4844 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4845 commit_id, repo);
4846 if (error)
4847 goto done;
4849 error = got_object_id_by_path(&obj_id, repo, commit_id,
4850 link_target ? link_target : in_repo_path);
4851 if (error)
4852 goto done;
4854 error = got_object_get_type(&obj_type, repo, obj_id);
4855 if (error)
4856 goto done;
4858 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4859 error = got_error_path(link_target ? link_target : in_repo_path,
4860 GOT_ERR_OBJ_TYPE);
4861 goto done;
4864 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4865 if (error)
4866 goto done;
4867 bca.f = got_opentemp();
4868 if (bca.f == NULL) {
4869 error = got_error_from_errno("got_opentemp");
4870 goto done;
4872 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4873 &bca.line_offsets, bca.f, blob);
4874 if (error || bca.nlines == 0)
4875 goto done;
4877 /* Don't include \n at EOF in the blame line count. */
4878 if (bca.line_offsets[bca.nlines - 1] == filesize)
4879 bca.nlines--;
4881 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4882 if (bca.lines == NULL) {
4883 error = got_error_from_errno("calloc");
4884 goto done;
4886 bca.lineno_cur = 1;
4887 bca.nlines_prec = 0;
4888 i = bca.nlines;
4889 while (i > 0) {
4890 i /= 10;
4891 bca.nlines_prec++;
4893 bca.repo = repo;
4895 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4896 repo, blame_cb, &bca, check_cancelled, NULL);
4897 done:
4898 free(in_repo_path);
4899 free(link_target);
4900 free(repo_path);
4901 free(cwd);
4902 free(commit_id);
4903 free(obj_id);
4904 if (blob)
4905 got_object_blob_close(blob);
4906 if (worktree)
4907 got_worktree_close(worktree);
4908 if (repo) {
4909 const struct got_error *close_err = got_repo_close(repo);
4910 if (error == NULL)
4911 error = close_err;
4913 if (bca.lines) {
4914 for (i = 0; i < bca.nlines; i++) {
4915 struct blame_line *bline = &bca.lines[i];
4916 free(bline->id_str);
4917 free(bline->committer);
4919 free(bca.lines);
4921 free(bca.line_offsets);
4922 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4923 error = got_error_from_errno("fclose");
4924 return error;
4927 __dead static void
4928 usage_tree(void)
4930 fprintf(stderr,
4931 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4932 getprogname());
4933 exit(1);
4936 static const struct got_error *
4937 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4938 const char *root_path, struct got_repository *repo)
4940 const struct got_error *err = NULL;
4941 int is_root_path = (strcmp(path, root_path) == 0);
4942 const char *modestr = "";
4943 mode_t mode = got_tree_entry_get_mode(te);
4944 char *link_target = NULL;
4946 path += strlen(root_path);
4947 while (path[0] == '/')
4948 path++;
4950 if (got_object_tree_entry_is_submodule(te))
4951 modestr = "$";
4952 else if (S_ISLNK(mode)) {
4953 int i;
4955 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4956 if (err)
4957 return err;
4958 for (i = 0; i < strlen(link_target); i++) {
4959 if (!isprint((unsigned char)link_target[i]))
4960 link_target[i] = '?';
4963 modestr = "@";
4965 else if (S_ISDIR(mode))
4966 modestr = "/";
4967 else if (mode & S_IXUSR)
4968 modestr = "*";
4970 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4971 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4972 link_target ? " -> ": "", link_target ? link_target : "");
4974 free(link_target);
4975 return NULL;
4978 static const struct got_error *
4979 print_tree(const char *path, struct got_object_id *commit_id,
4980 int show_ids, int recurse, const char *root_path,
4981 struct got_repository *repo)
4983 const struct got_error *err = NULL;
4984 struct got_object_id *tree_id = NULL;
4985 struct got_tree_object *tree = NULL;
4986 int nentries, i;
4988 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4989 if (err)
4990 goto done;
4992 err = got_object_open_as_tree(&tree, repo, tree_id);
4993 if (err)
4994 goto done;
4995 nentries = got_object_tree_get_nentries(tree);
4996 for (i = 0; i < nentries; i++) {
4997 struct got_tree_entry *te;
4998 char *id = NULL;
5000 if (sigint_received || sigpipe_received)
5001 break;
5003 te = got_object_tree_get_entry(tree, i);
5004 if (show_ids) {
5005 char *id_str;
5006 err = got_object_id_str(&id_str,
5007 got_tree_entry_get_id(te));
5008 if (err)
5009 goto done;
5010 if (asprintf(&id, "%s ", id_str) == -1) {
5011 err = got_error_from_errno("asprintf");
5012 free(id_str);
5013 goto done;
5015 free(id_str);
5017 err = print_entry(te, id, path, root_path, repo);
5018 free(id);
5019 if (err)
5020 goto done;
5022 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5023 char *child_path;
5024 if (asprintf(&child_path, "%s%s%s", path,
5025 path[0] == '/' && path[1] == '\0' ? "" : "/",
5026 got_tree_entry_get_name(te)) == -1) {
5027 err = got_error_from_errno("asprintf");
5028 goto done;
5030 err = print_tree(child_path, commit_id, show_ids, 1,
5031 root_path, repo);
5032 free(child_path);
5033 if (err)
5034 goto done;
5037 done:
5038 if (tree)
5039 got_object_tree_close(tree);
5040 free(tree_id);
5041 return err;
5044 static const struct got_error *
5045 cmd_tree(int argc, char *argv[])
5047 const struct got_error *error;
5048 struct got_repository *repo = NULL;
5049 struct got_worktree *worktree = NULL;
5050 const char *path, *refname = NULL;
5051 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5052 struct got_object_id *commit_id = NULL;
5053 char *commit_id_str = NULL;
5054 int show_ids = 0, recurse = 0;
5055 int ch;
5057 #ifndef PROFILE
5058 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5059 NULL) == -1)
5060 err(1, "pledge");
5061 #endif
5063 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5064 switch (ch) {
5065 case 'c':
5066 commit_id_str = optarg;
5067 break;
5068 case 'r':
5069 repo_path = realpath(optarg, NULL);
5070 if (repo_path == NULL)
5071 return got_error_from_errno2("realpath",
5072 optarg);
5073 got_path_strip_trailing_slashes(repo_path);
5074 break;
5075 case 'i':
5076 show_ids = 1;
5077 break;
5078 case 'R':
5079 recurse = 1;
5080 break;
5081 default:
5082 usage_tree();
5083 /* NOTREACHED */
5087 argc -= optind;
5088 argv += optind;
5090 if (argc == 1)
5091 path = argv[0];
5092 else if (argc > 1)
5093 usage_tree();
5094 else
5095 path = NULL;
5097 cwd = getcwd(NULL, 0);
5098 if (cwd == NULL) {
5099 error = got_error_from_errno("getcwd");
5100 goto done;
5102 if (repo_path == NULL) {
5103 error = got_worktree_open(&worktree, cwd);
5104 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5105 goto done;
5106 else
5107 error = NULL;
5108 if (worktree) {
5109 repo_path =
5110 strdup(got_worktree_get_repo_path(worktree));
5111 if (repo_path == NULL)
5112 error = got_error_from_errno("strdup");
5113 if (error)
5114 goto done;
5115 } else {
5116 repo_path = strdup(cwd);
5117 if (repo_path == NULL) {
5118 error = got_error_from_errno("strdup");
5119 goto done;
5124 error = got_repo_open(&repo, repo_path, NULL);
5125 if (error != NULL)
5126 goto done;
5128 if (worktree) {
5129 const char *prefix = got_worktree_get_path_prefix(worktree);
5130 char *p;
5132 if (path == NULL)
5133 path = "";
5134 error = got_worktree_resolve_path(&p, worktree, path);
5135 if (error)
5136 goto done;
5137 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5138 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5139 p) == -1) {
5140 error = got_error_from_errno("asprintf");
5141 free(p);
5142 goto done;
5144 free(p);
5145 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5146 if (error)
5147 goto done;
5148 } else {
5149 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5150 if (error)
5151 goto done;
5152 if (path == NULL)
5153 path = "/";
5154 error = got_repo_map_path(&in_repo_path, repo, path);
5155 if (error != NULL)
5156 goto done;
5159 if (commit_id_str == NULL) {
5160 struct got_reference *head_ref;
5161 if (worktree)
5162 refname = got_worktree_get_head_ref_name(worktree);
5163 else
5164 refname = GOT_REF_HEAD;
5165 error = got_ref_open(&head_ref, repo, refname, 0);
5166 if (error != NULL)
5167 goto done;
5168 error = got_ref_resolve(&commit_id, repo, head_ref);
5169 got_ref_close(head_ref);
5170 if (error != NULL)
5171 goto done;
5172 } else {
5173 struct got_reflist_head refs;
5174 TAILQ_INIT(&refs);
5175 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5176 NULL);
5177 if (error)
5178 goto done;
5179 error = got_repo_match_object_id(&commit_id, NULL,
5180 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5181 got_ref_list_free(&refs);
5182 if (error)
5183 goto done;
5186 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5187 in_repo_path, repo);
5188 done:
5189 free(in_repo_path);
5190 free(repo_path);
5191 free(cwd);
5192 free(commit_id);
5193 if (worktree)
5194 got_worktree_close(worktree);
5195 if (repo) {
5196 const struct got_error *close_err = got_repo_close(repo);
5197 if (error == NULL)
5198 error = close_err;
5200 return error;
5203 __dead static void
5204 usage_status(void)
5206 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5207 getprogname());
5208 exit(1);
5211 static const struct got_error *
5212 print_status(void *arg, unsigned char status, unsigned char staged_status,
5213 const char *path, struct got_object_id *blob_id,
5214 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5215 int dirfd, const char *de_name)
5217 if (status == staged_status && (status == GOT_STATUS_DELETE))
5218 status = GOT_STATUS_NO_CHANGE;
5219 if (arg) {
5220 char *status_codes = arg;
5221 size_t ncodes = strlen(status_codes);
5222 int i;
5223 for (i = 0; i < ncodes ; i++) {
5224 if (status == status_codes[i] ||
5225 staged_status == status_codes[i])
5226 break;
5228 if (i == ncodes)
5229 return NULL;
5231 printf("%c%c %s\n", status, staged_status, path);
5232 return NULL;
5235 static const struct got_error *
5236 cmd_status(int argc, char *argv[])
5238 const struct got_error *error = NULL;
5239 struct got_repository *repo = NULL;
5240 struct got_worktree *worktree = NULL;
5241 char *cwd = NULL, *status_codes = NULL;;
5242 struct got_pathlist_head paths;
5243 struct got_pathlist_entry *pe;
5244 int ch, i, no_ignores = 0;
5246 TAILQ_INIT(&paths);
5248 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5249 switch (ch) {
5250 case 'I':
5251 no_ignores = 1;
5252 break;
5253 case 's':
5254 for (i = 0; i < strlen(optarg); i++) {
5255 switch (optarg[i]) {
5256 case GOT_STATUS_MODIFY:
5257 case GOT_STATUS_ADD:
5258 case GOT_STATUS_DELETE:
5259 case GOT_STATUS_CONFLICT:
5260 case GOT_STATUS_MISSING:
5261 case GOT_STATUS_OBSTRUCTED:
5262 case GOT_STATUS_UNVERSIONED:
5263 case GOT_STATUS_MODE_CHANGE:
5264 case GOT_STATUS_NONEXISTENT:
5265 break;
5266 default:
5267 errx(1, "invalid status code '%c'",
5268 optarg[i]);
5271 status_codes = optarg;
5272 break;
5273 default:
5274 usage_status();
5275 /* NOTREACHED */
5279 argc -= optind;
5280 argv += optind;
5282 #ifndef PROFILE
5283 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5284 NULL) == -1)
5285 err(1, "pledge");
5286 #endif
5287 cwd = getcwd(NULL, 0);
5288 if (cwd == NULL) {
5289 error = got_error_from_errno("getcwd");
5290 goto done;
5293 error = got_worktree_open(&worktree, cwd);
5294 if (error) {
5295 if (error->code == GOT_ERR_NOT_WORKTREE)
5296 error = wrap_not_worktree_error(error, "status", cwd);
5297 goto done;
5300 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5301 NULL);
5302 if (error != NULL)
5303 goto done;
5305 error = apply_unveil(got_repo_get_path(repo), 1,
5306 got_worktree_get_root_path(worktree));
5307 if (error)
5308 goto done;
5310 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5311 if (error)
5312 goto done;
5314 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5315 print_status, status_codes, check_cancelled, NULL);
5316 done:
5317 TAILQ_FOREACH(pe, &paths, entry)
5318 free((char *)pe->path);
5319 got_pathlist_free(&paths);
5320 free(cwd);
5321 return error;
5324 __dead static void
5325 usage_ref(void)
5327 fprintf(stderr,
5328 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5329 "[-d] [name]\n",
5330 getprogname());
5331 exit(1);
5334 static const struct got_error *
5335 list_refs(struct got_repository *repo, const char *refname)
5337 static const struct got_error *err = NULL;
5338 struct got_reflist_head refs;
5339 struct got_reflist_entry *re;
5341 TAILQ_INIT(&refs);
5342 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5343 if (err)
5344 return err;
5346 TAILQ_FOREACH(re, &refs, entry) {
5347 char *refstr;
5348 refstr = got_ref_to_str(re->ref);
5349 if (refstr == NULL)
5350 return got_error_from_errno("got_ref_to_str");
5351 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5352 free(refstr);
5355 got_ref_list_free(&refs);
5356 return NULL;
5359 static const struct got_error *
5360 delete_ref_by_name(struct got_repository *repo, const char *refname)
5362 const struct got_error *err;
5363 struct got_reference *ref;
5365 err = got_ref_open(&ref, repo, refname, 0);
5366 if (err)
5367 return err;
5369 err = delete_ref(repo, ref);
5370 got_ref_close(ref);
5371 return err;
5374 static const struct got_error *
5375 add_ref(struct got_repository *repo, const char *refname, const char *target)
5377 const struct got_error *err = NULL;
5378 struct got_object_id *id;
5379 struct got_reference *ref = NULL;
5382 * Don't let the user create a reference name with a leading '-'.
5383 * While technically a valid reference name, this case is usually
5384 * an unintended typo.
5386 if (refname[0] == '-')
5387 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5389 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5390 repo);
5391 if (err) {
5392 struct got_reference *target_ref;
5394 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5395 return err;
5396 err = got_ref_open(&target_ref, repo, target, 0);
5397 if (err)
5398 return err;
5399 err = got_ref_resolve(&id, repo, target_ref);
5400 got_ref_close(target_ref);
5401 if (err)
5402 return err;
5405 err = got_ref_alloc(&ref, refname, id);
5406 if (err)
5407 goto done;
5409 err = got_ref_write(ref, repo);
5410 done:
5411 if (ref)
5412 got_ref_close(ref);
5413 free(id);
5414 return err;
5417 static const struct got_error *
5418 add_symref(struct got_repository *repo, const char *refname, const char *target)
5420 const struct got_error *err = NULL;
5421 struct got_reference *ref = NULL;
5422 struct got_reference *target_ref = NULL;
5425 * Don't let the user create a reference name with a leading '-'.
5426 * While technically a valid reference name, this case is usually
5427 * an unintended typo.
5429 if (refname[0] == '-')
5430 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5432 err = got_ref_open(&target_ref, repo, target, 0);
5433 if (err)
5434 return err;
5436 err = got_ref_alloc_symref(&ref, refname, target_ref);
5437 if (err)
5438 goto done;
5440 err = got_ref_write(ref, repo);
5441 done:
5442 if (target_ref)
5443 got_ref_close(target_ref);
5444 if (ref)
5445 got_ref_close(ref);
5446 return err;
5449 static const struct got_error *
5450 cmd_ref(int argc, char *argv[])
5452 const struct got_error *error = NULL;
5453 struct got_repository *repo = NULL;
5454 struct got_worktree *worktree = NULL;
5455 char *cwd = NULL, *repo_path = NULL;
5456 int ch, do_list = 0, do_delete = 0;
5457 const char *obj_arg = NULL, *symref_target= NULL;
5458 char *refname = NULL;
5460 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5461 switch (ch) {
5462 case 'c':
5463 obj_arg = optarg;
5464 break;
5465 case 'd':
5466 do_delete = 1;
5467 break;
5468 case 'r':
5469 repo_path = realpath(optarg, NULL);
5470 if (repo_path == NULL)
5471 return got_error_from_errno2("realpath",
5472 optarg);
5473 got_path_strip_trailing_slashes(repo_path);
5474 break;
5475 case 'l':
5476 do_list = 1;
5477 break;
5478 case 's':
5479 symref_target = optarg;
5480 break;
5481 default:
5482 usage_ref();
5483 /* NOTREACHED */
5487 if (obj_arg && do_list)
5488 option_conflict('c', 'l');
5489 if (obj_arg && do_delete)
5490 option_conflict('c', 'd');
5491 if (obj_arg && symref_target)
5492 option_conflict('c', 's');
5493 if (symref_target && do_delete)
5494 option_conflict('s', 'd');
5495 if (symref_target && do_list)
5496 option_conflict('s', 'l');
5497 if (do_delete && do_list)
5498 option_conflict('d', 'l');
5500 argc -= optind;
5501 argv += optind;
5503 if (do_list) {
5504 if (argc != 0 && argc != 1)
5505 usage_ref();
5506 if (argc == 1) {
5507 refname = strdup(argv[0]);
5508 if (refname == NULL) {
5509 error = got_error_from_errno("strdup");
5510 goto done;
5513 } else {
5514 if (argc != 1)
5515 usage_ref();
5516 refname = strdup(argv[0]);
5517 if (refname == NULL) {
5518 error = got_error_from_errno("strdup");
5519 goto done;
5523 if (refname)
5524 got_path_strip_trailing_slashes(refname);
5526 #ifndef PROFILE
5527 if (do_list) {
5528 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5529 NULL) == -1)
5530 err(1, "pledge");
5531 } else {
5532 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5533 "sendfd unveil", NULL) == -1)
5534 err(1, "pledge");
5536 #endif
5537 cwd = getcwd(NULL, 0);
5538 if (cwd == NULL) {
5539 error = got_error_from_errno("getcwd");
5540 goto done;
5543 if (repo_path == NULL) {
5544 error = got_worktree_open(&worktree, cwd);
5545 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5546 goto done;
5547 else
5548 error = NULL;
5549 if (worktree) {
5550 repo_path =
5551 strdup(got_worktree_get_repo_path(worktree));
5552 if (repo_path == NULL)
5553 error = got_error_from_errno("strdup");
5554 if (error)
5555 goto done;
5556 } else {
5557 repo_path = strdup(cwd);
5558 if (repo_path == NULL) {
5559 error = got_error_from_errno("strdup");
5560 goto done;
5565 error = got_repo_open(&repo, repo_path, NULL);
5566 if (error != NULL)
5567 goto done;
5569 error = apply_unveil(got_repo_get_path(repo), do_list,
5570 worktree ? got_worktree_get_root_path(worktree) : NULL);
5571 if (error)
5572 goto done;
5574 if (do_list)
5575 error = list_refs(repo, refname);
5576 else if (do_delete)
5577 error = delete_ref_by_name(repo, refname);
5578 else if (symref_target)
5579 error = add_symref(repo, refname, symref_target);
5580 else {
5581 if (obj_arg == NULL)
5582 usage_ref();
5583 error = add_ref(repo, refname, obj_arg);
5585 done:
5586 free(refname);
5587 if (repo) {
5588 const struct got_error *close_err = got_repo_close(repo);
5589 if (error == NULL)
5590 error = close_err;
5592 if (worktree)
5593 got_worktree_close(worktree);
5594 free(cwd);
5595 free(repo_path);
5596 return error;
5599 __dead static void
5600 usage_branch(void)
5602 fprintf(stderr,
5603 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5604 "[name]\n", getprogname());
5605 exit(1);
5608 static const struct got_error *
5609 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5610 struct got_reference *ref)
5612 const struct got_error *err = NULL;
5613 const char *refname, *marker = " ";
5614 char *refstr;
5616 refname = got_ref_get_name(ref);
5617 if (worktree && strcmp(refname,
5618 got_worktree_get_head_ref_name(worktree)) == 0) {
5619 struct got_object_id *id = NULL;
5621 err = got_ref_resolve(&id, repo, ref);
5622 if (err)
5623 return err;
5624 if (got_object_id_cmp(id,
5625 got_worktree_get_base_commit_id(worktree)) == 0)
5626 marker = "* ";
5627 else
5628 marker = "~ ";
5629 free(id);
5632 if (strncmp(refname, "refs/heads/", 11) == 0)
5633 refname += 11;
5634 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5635 refname += 18;
5636 if (strncmp(refname, "refs/remotes/", 13) == 0)
5637 refname += 13;
5639 refstr = got_ref_to_str(ref);
5640 if (refstr == NULL)
5641 return got_error_from_errno("got_ref_to_str");
5643 printf("%s%s: %s\n", marker, refname, refstr);
5644 free(refstr);
5645 return NULL;
5648 static const struct got_error *
5649 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5651 const char *refname;
5653 if (worktree == NULL)
5654 return got_error(GOT_ERR_NOT_WORKTREE);
5656 refname = got_worktree_get_head_ref_name(worktree);
5658 if (strncmp(refname, "refs/heads/", 11) == 0)
5659 refname += 11;
5660 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5661 refname += 18;
5663 printf("%s\n", refname);
5665 return NULL;
5668 static const struct got_error *
5669 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5671 static const struct got_error *err = NULL;
5672 struct got_reflist_head refs;
5673 struct got_reflist_entry *re;
5674 struct got_reference *temp_ref = NULL;
5675 int rebase_in_progress, histedit_in_progress;
5677 TAILQ_INIT(&refs);
5679 if (worktree) {
5680 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5681 worktree);
5682 if (err)
5683 return err;
5685 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5686 worktree);
5687 if (err)
5688 return err;
5690 if (rebase_in_progress || histedit_in_progress) {
5691 err = got_ref_open(&temp_ref, repo,
5692 got_worktree_get_head_ref_name(worktree), 0);
5693 if (err)
5694 return err;
5695 list_branch(repo, worktree, temp_ref);
5696 got_ref_close(temp_ref);
5700 err = got_ref_list(&refs, repo, "refs/heads",
5701 got_ref_cmp_by_name, NULL);
5702 if (err)
5703 return err;
5705 TAILQ_FOREACH(re, &refs, entry)
5706 list_branch(repo, worktree, re->ref);
5708 got_ref_list_free(&refs);
5710 err = got_ref_list(&refs, repo, "refs/remotes",
5711 got_ref_cmp_by_name, NULL);
5712 if (err)
5713 return err;
5715 TAILQ_FOREACH(re, &refs, entry)
5716 list_branch(repo, worktree, re->ref);
5718 got_ref_list_free(&refs);
5720 return NULL;
5723 static const struct got_error *
5724 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5725 const char *branch_name)
5727 const struct got_error *err = NULL;
5728 struct got_reference *ref = NULL;
5729 char *refname, *remote_refname = NULL;
5731 if (strncmp(branch_name, "refs/", 5) == 0)
5732 branch_name += 5;
5733 if (strncmp(branch_name, "heads/", 6) == 0)
5734 branch_name += 6;
5735 else if (strncmp(branch_name, "remotes/", 8) == 0)
5736 branch_name += 8;
5738 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5739 return got_error_from_errno("asprintf");
5741 if (asprintf(&remote_refname, "refs/remotes/%s",
5742 branch_name) == -1) {
5743 err = got_error_from_errno("asprintf");
5744 goto done;
5747 err = got_ref_open(&ref, repo, refname, 0);
5748 if (err) {
5749 const struct got_error *err2;
5750 if (err->code != GOT_ERR_NOT_REF)
5751 goto done;
5753 * Keep 'err' intact such that if neither branch exists
5754 * we report "refs/heads" rather than "refs/remotes" in
5755 * our error message.
5757 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5758 if (err2)
5759 goto done;
5760 err = NULL;
5763 if (worktree &&
5764 strcmp(got_worktree_get_head_ref_name(worktree),
5765 got_ref_get_name(ref)) == 0) {
5766 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5767 "will not delete this work tree's current branch");
5768 goto done;
5771 err = delete_ref(repo, ref);
5772 done:
5773 if (ref)
5774 got_ref_close(ref);
5775 free(refname);
5776 free(remote_refname);
5777 return err;
5780 static const struct got_error *
5781 add_branch(struct got_repository *repo, const char *branch_name,
5782 struct got_object_id *base_commit_id)
5784 const struct got_error *err = NULL;
5785 struct got_reference *ref = NULL;
5786 char *base_refname = NULL, *refname = NULL;
5789 * Don't let the user create a branch name with a leading '-'.
5790 * While technically a valid reference name, this case is usually
5791 * an unintended typo.
5793 if (branch_name[0] == '-')
5794 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5796 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5797 branch_name += 11;
5799 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5800 err = got_error_from_errno("asprintf");
5801 goto done;
5804 err = got_ref_open(&ref, repo, refname, 0);
5805 if (err == NULL) {
5806 err = got_error(GOT_ERR_BRANCH_EXISTS);
5807 goto done;
5808 } else if (err->code != GOT_ERR_NOT_REF)
5809 goto done;
5811 err = got_ref_alloc(&ref, refname, base_commit_id);
5812 if (err)
5813 goto done;
5815 err = got_ref_write(ref, repo);
5816 done:
5817 if (ref)
5818 got_ref_close(ref);
5819 free(base_refname);
5820 free(refname);
5821 return err;
5824 static const struct got_error *
5825 cmd_branch(int argc, char *argv[])
5827 const struct got_error *error = NULL;
5828 struct got_repository *repo = NULL;
5829 struct got_worktree *worktree = NULL;
5830 char *cwd = NULL, *repo_path = NULL;
5831 int ch, do_list = 0, do_show = 0, do_update = 1;
5832 const char *delref = NULL, *commit_id_arg = NULL;
5833 struct got_reference *ref = NULL;
5834 struct got_pathlist_head paths;
5835 struct got_pathlist_entry *pe;
5836 struct got_object_id *commit_id = NULL;
5837 char *commit_id_str = NULL;
5839 TAILQ_INIT(&paths);
5841 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5842 switch (ch) {
5843 case 'c':
5844 commit_id_arg = optarg;
5845 break;
5846 case 'd':
5847 delref = optarg;
5848 break;
5849 case 'r':
5850 repo_path = realpath(optarg, NULL);
5851 if (repo_path == NULL)
5852 return got_error_from_errno2("realpath",
5853 optarg);
5854 got_path_strip_trailing_slashes(repo_path);
5855 break;
5856 case 'l':
5857 do_list = 1;
5858 break;
5859 case 'n':
5860 do_update = 0;
5861 break;
5862 default:
5863 usage_branch();
5864 /* NOTREACHED */
5868 if (do_list && delref)
5869 option_conflict('l', 'd');
5871 argc -= optind;
5872 argv += optind;
5874 if (!do_list && !delref && argc == 0)
5875 do_show = 1;
5877 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5878 errx(1, "-c option can only be used when creating a branch");
5880 if (do_list || delref) {
5881 if (argc > 0)
5882 usage_branch();
5883 } else if (!do_show && argc != 1)
5884 usage_branch();
5886 #ifndef PROFILE
5887 if (do_list || do_show) {
5888 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5889 NULL) == -1)
5890 err(1, "pledge");
5891 } else {
5892 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5893 "sendfd unveil", NULL) == -1)
5894 err(1, "pledge");
5896 #endif
5897 cwd = getcwd(NULL, 0);
5898 if (cwd == NULL) {
5899 error = got_error_from_errno("getcwd");
5900 goto done;
5903 if (repo_path == NULL) {
5904 error = got_worktree_open(&worktree, cwd);
5905 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5906 goto done;
5907 else
5908 error = NULL;
5909 if (worktree) {
5910 repo_path =
5911 strdup(got_worktree_get_repo_path(worktree));
5912 if (repo_path == NULL)
5913 error = got_error_from_errno("strdup");
5914 if (error)
5915 goto done;
5916 } else {
5917 repo_path = strdup(cwd);
5918 if (repo_path == NULL) {
5919 error = got_error_from_errno("strdup");
5920 goto done;
5925 error = got_repo_open(&repo, repo_path, NULL);
5926 if (error != NULL)
5927 goto done;
5929 error = apply_unveil(got_repo_get_path(repo), do_list,
5930 worktree ? got_worktree_get_root_path(worktree) : NULL);
5931 if (error)
5932 goto done;
5934 if (do_show)
5935 error = show_current_branch(repo, worktree);
5936 else if (do_list)
5937 error = list_branches(repo, worktree);
5938 else if (delref)
5939 error = delete_branch(repo, worktree, delref);
5940 else {
5941 struct got_reflist_head refs;
5942 TAILQ_INIT(&refs);
5943 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5944 NULL);
5945 if (error)
5946 goto done;
5947 if (commit_id_arg == NULL)
5948 commit_id_arg = worktree ?
5949 got_worktree_get_head_ref_name(worktree) :
5950 GOT_REF_HEAD;
5951 error = got_repo_match_object_id(&commit_id, NULL,
5952 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5953 got_ref_list_free(&refs);
5954 if (error)
5955 goto done;
5956 error = add_branch(repo, argv[0], commit_id);
5957 if (error)
5958 goto done;
5959 if (worktree && do_update) {
5960 struct got_update_progress_arg upa;
5961 char *branch_refname = NULL;
5963 error = got_object_id_str(&commit_id_str, commit_id);
5964 if (error)
5965 goto done;
5966 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5967 worktree);
5968 if (error)
5969 goto done;
5970 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5971 == -1) {
5972 error = got_error_from_errno("asprintf");
5973 goto done;
5975 error = got_ref_open(&ref, repo, branch_refname, 0);
5976 free(branch_refname);
5977 if (error)
5978 goto done;
5979 error = switch_head_ref(ref, commit_id, worktree,
5980 repo);
5981 if (error)
5982 goto done;
5983 error = got_worktree_set_base_commit_id(worktree, repo,
5984 commit_id);
5985 if (error)
5986 goto done;
5987 memset(&upa, 0, sizeof(upa));
5988 error = got_worktree_checkout_files(worktree, &paths,
5989 repo, update_progress, &upa, check_cancelled,
5990 NULL);
5991 if (error)
5992 goto done;
5993 if (upa.did_something)
5994 printf("Updated to commit %s\n", commit_id_str);
5995 print_update_progress_stats(&upa);
5998 done:
5999 if (ref)
6000 got_ref_close(ref);
6001 if (repo) {
6002 const struct got_error *close_err = got_repo_close(repo);
6003 if (error == NULL)
6004 error = close_err;
6006 if (worktree)
6007 got_worktree_close(worktree);
6008 free(cwd);
6009 free(repo_path);
6010 free(commit_id);
6011 free(commit_id_str);
6012 TAILQ_FOREACH(pe, &paths, entry)
6013 free((char *)pe->path);
6014 got_pathlist_free(&paths);
6015 return error;
6019 __dead static void
6020 usage_tag(void)
6022 fprintf(stderr,
6023 "usage: %s tag [-c commit] [-r repository] [-l] "
6024 "[-m message] name\n", getprogname());
6025 exit(1);
6028 #if 0
6029 static const struct got_error *
6030 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6032 const struct got_error *err = NULL;
6033 struct got_reflist_entry *re, *se, *new;
6034 struct got_object_id *re_id, *se_id;
6035 struct got_tag_object *re_tag, *se_tag;
6036 time_t re_time, se_time;
6038 STAILQ_FOREACH(re, tags, entry) {
6039 se = STAILQ_FIRST(sorted);
6040 if (se == NULL) {
6041 err = got_reflist_entry_dup(&new, re);
6042 if (err)
6043 return err;
6044 STAILQ_INSERT_HEAD(sorted, new, entry);
6045 continue;
6046 } else {
6047 err = got_ref_resolve(&re_id, repo, re->ref);
6048 if (err)
6049 break;
6050 err = got_object_open_as_tag(&re_tag, repo, re_id);
6051 free(re_id);
6052 if (err)
6053 break;
6054 re_time = got_object_tag_get_tagger_time(re_tag);
6055 got_object_tag_close(re_tag);
6058 while (se) {
6059 err = got_ref_resolve(&se_id, repo, re->ref);
6060 if (err)
6061 break;
6062 err = got_object_open_as_tag(&se_tag, repo, se_id);
6063 free(se_id);
6064 if (err)
6065 break;
6066 se_time = got_object_tag_get_tagger_time(se_tag);
6067 got_object_tag_close(se_tag);
6069 if (se_time > re_time) {
6070 err = got_reflist_entry_dup(&new, re);
6071 if (err)
6072 return err;
6073 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6074 break;
6076 se = STAILQ_NEXT(se, entry);
6077 continue;
6080 done:
6081 return err;
6083 #endif
6085 static const struct got_error *
6086 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6088 static const struct got_error *err = NULL;
6089 struct got_reflist_head refs;
6090 struct got_reflist_entry *re;
6092 TAILQ_INIT(&refs);
6094 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6095 if (err)
6096 return err;
6098 TAILQ_FOREACH(re, &refs, entry) {
6099 const char *refname;
6100 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6101 char datebuf[26];
6102 const char *tagger;
6103 time_t tagger_time;
6104 struct got_object_id *id;
6105 struct got_tag_object *tag;
6106 struct got_commit_object *commit = NULL;
6108 refname = got_ref_get_name(re->ref);
6109 if (strncmp(refname, "refs/tags/", 10) != 0)
6110 continue;
6111 refname += 10;
6112 refstr = got_ref_to_str(re->ref);
6113 if (refstr == NULL) {
6114 err = got_error_from_errno("got_ref_to_str");
6115 break;
6117 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6118 free(refstr);
6120 err = got_ref_resolve(&id, repo, re->ref);
6121 if (err)
6122 break;
6123 err = got_object_open_as_tag(&tag, repo, id);
6124 if (err) {
6125 if (err->code != GOT_ERR_OBJ_TYPE) {
6126 free(id);
6127 break;
6129 /* "lightweight" tag */
6130 err = got_object_open_as_commit(&commit, repo, id);
6131 if (err) {
6132 free(id);
6133 break;
6135 tagger = got_object_commit_get_committer(commit);
6136 tagger_time =
6137 got_object_commit_get_committer_time(commit);
6138 err = got_object_id_str(&id_str, id);
6139 free(id);
6140 if (err)
6141 break;
6142 } else {
6143 free(id);
6144 tagger = got_object_tag_get_tagger(tag);
6145 tagger_time = got_object_tag_get_tagger_time(tag);
6146 err = got_object_id_str(&id_str,
6147 got_object_tag_get_object_id(tag));
6148 if (err)
6149 break;
6151 printf("from: %s\n", tagger);
6152 datestr = get_datestr(&tagger_time, datebuf);
6153 if (datestr)
6154 printf("date: %s UTC\n", datestr);
6155 if (commit)
6156 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6157 else {
6158 switch (got_object_tag_get_object_type(tag)) {
6159 case GOT_OBJ_TYPE_BLOB:
6160 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6161 id_str);
6162 break;
6163 case GOT_OBJ_TYPE_TREE:
6164 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6165 id_str);
6166 break;
6167 case GOT_OBJ_TYPE_COMMIT:
6168 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6169 id_str);
6170 break;
6171 case GOT_OBJ_TYPE_TAG:
6172 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6173 id_str);
6174 break;
6175 default:
6176 break;
6179 free(id_str);
6180 if (commit) {
6181 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6182 if (err)
6183 break;
6184 got_object_commit_close(commit);
6185 } else {
6186 tagmsg0 = strdup(got_object_tag_get_message(tag));
6187 got_object_tag_close(tag);
6188 if (tagmsg0 == NULL) {
6189 err = got_error_from_errno("strdup");
6190 break;
6194 tagmsg = tagmsg0;
6195 do {
6196 line = strsep(&tagmsg, "\n");
6197 if (line)
6198 printf(" %s\n", line);
6199 } while (line);
6200 free(tagmsg0);
6203 got_ref_list_free(&refs);
6204 return NULL;
6207 static const struct got_error *
6208 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6209 const char *tag_name, const char *repo_path)
6211 const struct got_error *err = NULL;
6212 char *template = NULL, *initial_content = NULL;
6213 char *editor = NULL;
6214 int initial_content_len;
6215 int fd = -1;
6217 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6218 err = got_error_from_errno("asprintf");
6219 goto done;
6222 initial_content_len = asprintf(&initial_content,
6223 "\n# tagging commit %s as %s\n",
6224 commit_id_str, tag_name);
6225 if (initial_content_len == -1) {
6226 err = got_error_from_errno("asprintf");
6227 goto done;
6230 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6231 if (err)
6232 goto done;
6234 if (write(fd, initial_content, initial_content_len) == -1) {
6235 err = got_error_from_errno2("write", *tagmsg_path);
6236 goto done;
6239 err = get_editor(&editor);
6240 if (err)
6241 goto done;
6242 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6243 initial_content_len, 1);
6244 done:
6245 free(initial_content);
6246 free(template);
6247 free(editor);
6249 if (fd != -1 && close(fd) == -1 && err == NULL)
6250 err = got_error_from_errno2("close", *tagmsg_path);
6252 /* Editor is done; we can now apply unveil(2) */
6253 if (err == NULL)
6254 err = apply_unveil(repo_path, 0, NULL);
6255 if (err) {
6256 free(*tagmsg);
6257 *tagmsg = NULL;
6259 return err;
6262 static const struct got_error *
6263 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6264 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6266 const struct got_error *err = NULL;
6267 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6268 char *label = NULL, *commit_id_str = NULL;
6269 struct got_reference *ref = NULL;
6270 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6271 char *tagmsg_path = NULL, *tag_id_str = NULL;
6272 int preserve_tagmsg = 0;
6273 struct got_reflist_head refs;
6275 TAILQ_INIT(&refs);
6278 * Don't let the user create a tag name with a leading '-'.
6279 * While technically a valid reference name, this case is usually
6280 * an unintended typo.
6282 if (tag_name[0] == '-')
6283 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6285 err = get_author(&tagger, repo, worktree);
6286 if (err)
6287 return err;
6289 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6290 if (err)
6291 goto done;
6293 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6294 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6295 if (err)
6296 goto done;
6298 err = got_object_id_str(&commit_id_str, commit_id);
6299 if (err)
6300 goto done;
6302 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6303 refname = strdup(tag_name);
6304 if (refname == NULL) {
6305 err = got_error_from_errno("strdup");
6306 goto done;
6308 tag_name += 10;
6309 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6310 err = got_error_from_errno("asprintf");
6311 goto done;
6314 err = got_ref_open(&ref, repo, refname, 0);
6315 if (err == NULL) {
6316 err = got_error(GOT_ERR_TAG_EXISTS);
6317 goto done;
6318 } else if (err->code != GOT_ERR_NOT_REF)
6319 goto done;
6321 if (tagmsg_arg == NULL) {
6322 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6323 tag_name, got_repo_get_path(repo));
6324 if (err) {
6325 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6326 tagmsg_path != NULL)
6327 preserve_tagmsg = 1;
6328 goto done;
6332 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6333 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6334 if (err) {
6335 if (tagmsg_path)
6336 preserve_tagmsg = 1;
6337 goto done;
6340 err = got_ref_alloc(&ref, refname, tag_id);
6341 if (err) {
6342 if (tagmsg_path)
6343 preserve_tagmsg = 1;
6344 goto done;
6347 err = got_ref_write(ref, repo);
6348 if (err) {
6349 if (tagmsg_path)
6350 preserve_tagmsg = 1;
6351 goto done;
6354 err = got_object_id_str(&tag_id_str, tag_id);
6355 if (err) {
6356 if (tagmsg_path)
6357 preserve_tagmsg = 1;
6358 goto done;
6360 printf("Created tag %s\n", tag_id_str);
6361 done:
6362 if (preserve_tagmsg) {
6363 fprintf(stderr, "%s: tag message preserved in %s\n",
6364 getprogname(), tagmsg_path);
6365 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6366 err = got_error_from_errno2("unlink", tagmsg_path);
6367 free(tag_id_str);
6368 if (ref)
6369 got_ref_close(ref);
6370 free(commit_id);
6371 free(commit_id_str);
6372 free(refname);
6373 free(tagmsg);
6374 free(tagmsg_path);
6375 free(tagger);
6376 got_ref_list_free(&refs);
6377 return err;
6380 static const struct got_error *
6381 cmd_tag(int argc, char *argv[])
6383 const struct got_error *error = NULL;
6384 struct got_repository *repo = NULL;
6385 struct got_worktree *worktree = NULL;
6386 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6387 char *gitconfig_path = NULL;
6388 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6389 int ch, do_list = 0;
6391 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6392 switch (ch) {
6393 case 'c':
6394 commit_id_arg = optarg;
6395 break;
6396 case 'm':
6397 tagmsg = optarg;
6398 break;
6399 case 'r':
6400 repo_path = realpath(optarg, NULL);
6401 if (repo_path == NULL)
6402 return got_error_from_errno2("realpath",
6403 optarg);
6404 got_path_strip_trailing_slashes(repo_path);
6405 break;
6406 case 'l':
6407 do_list = 1;
6408 break;
6409 default:
6410 usage_tag();
6411 /* NOTREACHED */
6415 argc -= optind;
6416 argv += optind;
6418 if (do_list) {
6419 if (commit_id_arg != NULL)
6420 errx(1,
6421 "-c option can only be used when creating a tag");
6422 if (tagmsg)
6423 option_conflict('l', 'm');
6424 if (argc > 0)
6425 usage_tag();
6426 } else if (argc != 1)
6427 usage_tag();
6429 tag_name = argv[0];
6431 #ifndef PROFILE
6432 if (do_list) {
6433 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6434 NULL) == -1)
6435 err(1, "pledge");
6436 } else {
6437 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6438 "sendfd unveil", NULL) == -1)
6439 err(1, "pledge");
6441 #endif
6442 cwd = getcwd(NULL, 0);
6443 if (cwd == NULL) {
6444 error = got_error_from_errno("getcwd");
6445 goto done;
6448 if (repo_path == NULL) {
6449 error = got_worktree_open(&worktree, cwd);
6450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6451 goto done;
6452 else
6453 error = NULL;
6454 if (worktree) {
6455 repo_path =
6456 strdup(got_worktree_get_repo_path(worktree));
6457 if (repo_path == NULL)
6458 error = got_error_from_errno("strdup");
6459 if (error)
6460 goto done;
6461 } else {
6462 repo_path = strdup(cwd);
6463 if (repo_path == NULL) {
6464 error = got_error_from_errno("strdup");
6465 goto done;
6470 if (do_list) {
6471 error = got_repo_open(&repo, repo_path, NULL);
6472 if (error != NULL)
6473 goto done;
6474 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6475 if (error)
6476 goto done;
6477 error = list_tags(repo, worktree);
6478 } else {
6479 error = get_gitconfig_path(&gitconfig_path);
6480 if (error)
6481 goto done;
6482 error = got_repo_open(&repo, repo_path, gitconfig_path);
6483 if (error != NULL)
6484 goto done;
6486 if (tagmsg) {
6487 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6488 if (error)
6489 goto done;
6492 if (commit_id_arg == NULL) {
6493 struct got_reference *head_ref;
6494 struct got_object_id *commit_id;
6495 error = got_ref_open(&head_ref, repo,
6496 worktree ? got_worktree_get_head_ref_name(worktree)
6497 : GOT_REF_HEAD, 0);
6498 if (error)
6499 goto done;
6500 error = got_ref_resolve(&commit_id, repo, head_ref);
6501 got_ref_close(head_ref);
6502 if (error)
6503 goto done;
6504 error = got_object_id_str(&commit_id_str, commit_id);
6505 free(commit_id);
6506 if (error)
6507 goto done;
6510 error = add_tag(repo, worktree, tag_name,
6511 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6513 done:
6514 if (repo) {
6515 const struct got_error *close_err = got_repo_close(repo);
6516 if (error == NULL)
6517 error = close_err;
6519 if (worktree)
6520 got_worktree_close(worktree);
6521 free(cwd);
6522 free(repo_path);
6523 free(gitconfig_path);
6524 free(commit_id_str);
6525 return error;
6528 __dead static void
6529 usage_add(void)
6531 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6532 getprogname());
6533 exit(1);
6536 static const struct got_error *
6537 add_progress(void *arg, unsigned char status, const char *path)
6539 while (path[0] == '/')
6540 path++;
6541 printf("%c %s\n", status, path);
6542 return NULL;
6545 static const struct got_error *
6546 cmd_add(int argc, char *argv[])
6548 const struct got_error *error = NULL;
6549 struct got_repository *repo = NULL;
6550 struct got_worktree *worktree = NULL;
6551 char *cwd = NULL;
6552 struct got_pathlist_head paths;
6553 struct got_pathlist_entry *pe;
6554 int ch, can_recurse = 0, no_ignores = 0;
6556 TAILQ_INIT(&paths);
6558 while ((ch = getopt(argc, argv, "IR")) != -1) {
6559 switch (ch) {
6560 case 'I':
6561 no_ignores = 1;
6562 break;
6563 case 'R':
6564 can_recurse = 1;
6565 break;
6566 default:
6567 usage_add();
6568 /* NOTREACHED */
6572 argc -= optind;
6573 argv += optind;
6575 #ifndef PROFILE
6576 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6577 NULL) == -1)
6578 err(1, "pledge");
6579 #endif
6580 if (argc < 1)
6581 usage_add();
6583 cwd = getcwd(NULL, 0);
6584 if (cwd == NULL) {
6585 error = got_error_from_errno("getcwd");
6586 goto done;
6589 error = got_worktree_open(&worktree, cwd);
6590 if (error) {
6591 if (error->code == GOT_ERR_NOT_WORKTREE)
6592 error = wrap_not_worktree_error(error, "add", cwd);
6593 goto done;
6596 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6597 NULL);
6598 if (error != NULL)
6599 goto done;
6601 error = apply_unveil(got_repo_get_path(repo), 1,
6602 got_worktree_get_root_path(worktree));
6603 if (error)
6604 goto done;
6606 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6607 if (error)
6608 goto done;
6610 if (!can_recurse) {
6611 char *ondisk_path;
6612 struct stat sb;
6613 TAILQ_FOREACH(pe, &paths, entry) {
6614 if (asprintf(&ondisk_path, "%s/%s",
6615 got_worktree_get_root_path(worktree),
6616 pe->path) == -1) {
6617 error = got_error_from_errno("asprintf");
6618 goto done;
6620 if (lstat(ondisk_path, &sb) == -1) {
6621 if (errno == ENOENT) {
6622 free(ondisk_path);
6623 continue;
6625 error = got_error_from_errno2("lstat",
6626 ondisk_path);
6627 free(ondisk_path);
6628 goto done;
6630 free(ondisk_path);
6631 if (S_ISDIR(sb.st_mode)) {
6632 error = got_error_msg(GOT_ERR_BAD_PATH,
6633 "adding directories requires -R option");
6634 goto done;
6639 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6640 NULL, repo, no_ignores);
6641 done:
6642 if (repo) {
6643 const struct got_error *close_err = got_repo_close(repo);
6644 if (error == NULL)
6645 error = close_err;
6647 if (worktree)
6648 got_worktree_close(worktree);
6649 TAILQ_FOREACH(pe, &paths, entry)
6650 free((char *)pe->path);
6651 got_pathlist_free(&paths);
6652 free(cwd);
6653 return error;
6656 __dead static void
6657 usage_remove(void)
6659 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6660 "path ...\n", getprogname());
6661 exit(1);
6664 static const struct got_error *
6665 print_remove_status(void *arg, unsigned char status,
6666 unsigned char staged_status, const char *path)
6668 while (path[0] == '/')
6669 path++;
6670 if (status == GOT_STATUS_NONEXISTENT)
6671 return NULL;
6672 if (status == staged_status && (status == GOT_STATUS_DELETE))
6673 status = GOT_STATUS_NO_CHANGE;
6674 printf("%c%c %s\n", status, staged_status, path);
6675 return NULL;
6678 static const struct got_error *
6679 cmd_remove(int argc, char *argv[])
6681 const struct got_error *error = NULL;
6682 struct got_worktree *worktree = NULL;
6683 struct got_repository *repo = NULL;
6684 const char *status_codes = NULL;
6685 char *cwd = NULL;
6686 struct got_pathlist_head paths;
6687 struct got_pathlist_entry *pe;
6688 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6690 TAILQ_INIT(&paths);
6692 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6693 switch (ch) {
6694 case 'f':
6695 delete_local_mods = 1;
6696 break;
6697 case 'k':
6698 keep_on_disk = 1;
6699 break;
6700 case 'R':
6701 can_recurse = 1;
6702 break;
6703 case 's':
6704 for (i = 0; i < strlen(optarg); i++) {
6705 switch (optarg[i]) {
6706 case GOT_STATUS_MODIFY:
6707 delete_local_mods = 1;
6708 break;
6709 case GOT_STATUS_MISSING:
6710 break;
6711 default:
6712 errx(1, "invalid status code '%c'",
6713 optarg[i]);
6716 status_codes = optarg;
6717 break;
6718 default:
6719 usage_remove();
6720 /* NOTREACHED */
6724 argc -= optind;
6725 argv += optind;
6727 #ifndef PROFILE
6728 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6729 NULL) == -1)
6730 err(1, "pledge");
6731 #endif
6732 if (argc < 1)
6733 usage_remove();
6735 cwd = getcwd(NULL, 0);
6736 if (cwd == NULL) {
6737 error = got_error_from_errno("getcwd");
6738 goto done;
6740 error = got_worktree_open(&worktree, cwd);
6741 if (error) {
6742 if (error->code == GOT_ERR_NOT_WORKTREE)
6743 error = wrap_not_worktree_error(error, "remove", cwd);
6744 goto done;
6747 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6748 NULL);
6749 if (error)
6750 goto done;
6752 error = apply_unveil(got_repo_get_path(repo), 1,
6753 got_worktree_get_root_path(worktree));
6754 if (error)
6755 goto done;
6757 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6758 if (error)
6759 goto done;
6761 if (!can_recurse) {
6762 char *ondisk_path;
6763 struct stat sb;
6764 TAILQ_FOREACH(pe, &paths, entry) {
6765 if (asprintf(&ondisk_path, "%s/%s",
6766 got_worktree_get_root_path(worktree),
6767 pe->path) == -1) {
6768 error = got_error_from_errno("asprintf");
6769 goto done;
6771 if (lstat(ondisk_path, &sb) == -1) {
6772 if (errno == ENOENT) {
6773 free(ondisk_path);
6774 continue;
6776 error = got_error_from_errno2("lstat",
6777 ondisk_path);
6778 free(ondisk_path);
6779 goto done;
6781 free(ondisk_path);
6782 if (S_ISDIR(sb.st_mode)) {
6783 error = got_error_msg(GOT_ERR_BAD_PATH,
6784 "removing directories requires -R option");
6785 goto done;
6790 error = got_worktree_schedule_delete(worktree, &paths,
6791 delete_local_mods, status_codes, print_remove_status, NULL,
6792 repo, keep_on_disk);
6793 done:
6794 if (repo) {
6795 const struct got_error *close_err = got_repo_close(repo);
6796 if (error == NULL)
6797 error = close_err;
6799 if (worktree)
6800 got_worktree_close(worktree);
6801 TAILQ_FOREACH(pe, &paths, entry)
6802 free((char *)pe->path);
6803 got_pathlist_free(&paths);
6804 free(cwd);
6805 return error;
6808 __dead static void
6809 usage_revert(void)
6811 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6812 "path ...\n", getprogname());
6813 exit(1);
6816 static const struct got_error *
6817 revert_progress(void *arg, unsigned char status, const char *path)
6819 if (status == GOT_STATUS_UNVERSIONED)
6820 return NULL;
6822 while (path[0] == '/')
6823 path++;
6824 printf("%c %s\n", status, path);
6825 return NULL;
6828 struct choose_patch_arg {
6829 FILE *patch_script_file;
6830 const char *action;
6833 static const struct got_error *
6834 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6835 int nchanges, const char *action)
6837 char *line = NULL;
6838 size_t linesize = 0;
6839 ssize_t linelen;
6841 switch (status) {
6842 case GOT_STATUS_ADD:
6843 printf("A %s\n%s this addition? [y/n] ", path, action);
6844 break;
6845 case GOT_STATUS_DELETE:
6846 printf("D %s\n%s this deletion? [y/n] ", path, action);
6847 break;
6848 case GOT_STATUS_MODIFY:
6849 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6850 return got_error_from_errno("fseek");
6851 printf(GOT_COMMIT_SEP_STR);
6852 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6853 printf("%s", line);
6854 if (ferror(patch_file))
6855 return got_error_from_errno("getline");
6856 printf(GOT_COMMIT_SEP_STR);
6857 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6858 path, n, nchanges, action);
6859 break;
6860 default:
6861 return got_error_path(path, GOT_ERR_FILE_STATUS);
6864 return NULL;
6867 static const struct got_error *
6868 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6869 FILE *patch_file, int n, int nchanges)
6871 const struct got_error *err = NULL;
6872 char *line = NULL;
6873 size_t linesize = 0;
6874 ssize_t linelen;
6875 int resp = ' ';
6876 struct choose_patch_arg *a = arg;
6878 *choice = GOT_PATCH_CHOICE_NONE;
6880 if (a->patch_script_file) {
6881 char *nl;
6882 err = show_change(status, path, patch_file, n, nchanges,
6883 a->action);
6884 if (err)
6885 return err;
6886 linelen = getline(&line, &linesize, a->patch_script_file);
6887 if (linelen == -1) {
6888 if (ferror(a->patch_script_file))
6889 return got_error_from_errno("getline");
6890 return NULL;
6892 nl = strchr(line, '\n');
6893 if (nl)
6894 *nl = '\0';
6895 if (strcmp(line, "y") == 0) {
6896 *choice = GOT_PATCH_CHOICE_YES;
6897 printf("y\n");
6898 } else if (strcmp(line, "n") == 0) {
6899 *choice = GOT_PATCH_CHOICE_NO;
6900 printf("n\n");
6901 } else if (strcmp(line, "q") == 0 &&
6902 status == GOT_STATUS_MODIFY) {
6903 *choice = GOT_PATCH_CHOICE_QUIT;
6904 printf("q\n");
6905 } else
6906 printf("invalid response '%s'\n", line);
6907 free(line);
6908 return NULL;
6911 while (resp != 'y' && resp != 'n' && resp != 'q') {
6912 err = show_change(status, path, patch_file, n, nchanges,
6913 a->action);
6914 if (err)
6915 return err;
6916 resp = getchar();
6917 if (resp == '\n')
6918 resp = getchar();
6919 if (status == GOT_STATUS_MODIFY) {
6920 if (resp != 'y' && resp != 'n' && resp != 'q') {
6921 printf("invalid response '%c'\n", resp);
6922 resp = ' ';
6924 } else if (resp != 'y' && resp != 'n') {
6925 printf("invalid response '%c'\n", resp);
6926 resp = ' ';
6930 if (resp == 'y')
6931 *choice = GOT_PATCH_CHOICE_YES;
6932 else if (resp == 'n')
6933 *choice = GOT_PATCH_CHOICE_NO;
6934 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6935 *choice = GOT_PATCH_CHOICE_QUIT;
6937 return NULL;
6941 static const struct got_error *
6942 cmd_revert(int argc, char *argv[])
6944 const struct got_error *error = NULL;
6945 struct got_worktree *worktree = NULL;
6946 struct got_repository *repo = NULL;
6947 char *cwd = NULL, *path = NULL;
6948 struct got_pathlist_head paths;
6949 struct got_pathlist_entry *pe;
6950 int ch, can_recurse = 0, pflag = 0;
6951 FILE *patch_script_file = NULL;
6952 const char *patch_script_path = NULL;
6953 struct choose_patch_arg cpa;
6955 TAILQ_INIT(&paths);
6957 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6958 switch (ch) {
6959 case 'p':
6960 pflag = 1;
6961 break;
6962 case 'F':
6963 patch_script_path = optarg;
6964 break;
6965 case 'R':
6966 can_recurse = 1;
6967 break;
6968 default:
6969 usage_revert();
6970 /* NOTREACHED */
6974 argc -= optind;
6975 argv += optind;
6977 #ifndef PROFILE
6978 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6979 "unveil", NULL) == -1)
6980 err(1, "pledge");
6981 #endif
6982 if (argc < 1)
6983 usage_revert();
6984 if (patch_script_path && !pflag)
6985 errx(1, "-F option can only be used together with -p option");
6987 cwd = getcwd(NULL, 0);
6988 if (cwd == NULL) {
6989 error = got_error_from_errno("getcwd");
6990 goto done;
6992 error = got_worktree_open(&worktree, cwd);
6993 if (error) {
6994 if (error->code == GOT_ERR_NOT_WORKTREE)
6995 error = wrap_not_worktree_error(error, "revert", cwd);
6996 goto done;
6999 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7000 NULL);
7001 if (error != NULL)
7002 goto done;
7004 if (patch_script_path) {
7005 patch_script_file = fopen(patch_script_path, "r");
7006 if (patch_script_file == NULL) {
7007 error = got_error_from_errno2("fopen",
7008 patch_script_path);
7009 goto done;
7012 error = apply_unveil(got_repo_get_path(repo), 1,
7013 got_worktree_get_root_path(worktree));
7014 if (error)
7015 goto done;
7017 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7018 if (error)
7019 goto done;
7021 if (!can_recurse) {
7022 char *ondisk_path;
7023 struct stat sb;
7024 TAILQ_FOREACH(pe, &paths, entry) {
7025 if (asprintf(&ondisk_path, "%s/%s",
7026 got_worktree_get_root_path(worktree),
7027 pe->path) == -1) {
7028 error = got_error_from_errno("asprintf");
7029 goto done;
7031 if (lstat(ondisk_path, &sb) == -1) {
7032 if (errno == ENOENT) {
7033 free(ondisk_path);
7034 continue;
7036 error = got_error_from_errno2("lstat",
7037 ondisk_path);
7038 free(ondisk_path);
7039 goto done;
7041 free(ondisk_path);
7042 if (S_ISDIR(sb.st_mode)) {
7043 error = got_error_msg(GOT_ERR_BAD_PATH,
7044 "reverting directories requires -R option");
7045 goto done;
7050 cpa.patch_script_file = patch_script_file;
7051 cpa.action = "revert";
7052 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7053 pflag ? choose_patch : NULL, &cpa, repo);
7054 done:
7055 if (patch_script_file && fclose(patch_script_file) == EOF &&
7056 error == NULL)
7057 error = got_error_from_errno2("fclose", patch_script_path);
7058 if (repo) {
7059 const struct got_error *close_err = got_repo_close(repo);
7060 if (error == NULL)
7061 error = close_err;
7063 if (worktree)
7064 got_worktree_close(worktree);
7065 free(path);
7066 free(cwd);
7067 return error;
7070 __dead static void
7071 usage_commit(void)
7073 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7074 "[path ...]\n", getprogname());
7075 exit(1);
7078 struct collect_commit_logmsg_arg {
7079 const char *cmdline_log;
7080 const char *prepared_log;
7081 int non_interactive;
7082 const char *editor;
7083 const char *worktree_path;
7084 const char *branch_name;
7085 const char *repo_path;
7086 char *logmsg_path;
7090 static const struct got_error *
7091 read_prepared_logmsg(char **logmsg, const char *path)
7093 const struct got_error *err = NULL;
7094 FILE *f = NULL;
7095 struct stat sb;
7096 size_t r;
7098 *logmsg = NULL;
7099 memset(&sb, 0, sizeof(sb));
7101 f = fopen(path, "r");
7102 if (f == NULL)
7103 return got_error_from_errno2("fopen", path);
7105 if (fstat(fileno(f), &sb) == -1) {
7106 err = got_error_from_errno2("fstat", path);
7107 goto done;
7109 if (sb.st_size == 0) {
7110 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7111 goto done;
7114 *logmsg = malloc(sb.st_size + 1);
7115 if (*logmsg == NULL) {
7116 err = got_error_from_errno("malloc");
7117 goto done;
7120 r = fread(*logmsg, 1, sb.st_size, f);
7121 if (r != sb.st_size) {
7122 if (ferror(f))
7123 err = got_error_from_errno2("fread", path);
7124 else
7125 err = got_error(GOT_ERR_IO);
7126 goto done;
7128 (*logmsg)[sb.st_size] = '\0';
7129 done:
7130 if (fclose(f) == EOF && err == NULL)
7131 err = got_error_from_errno2("fclose", path);
7132 if (err) {
7133 free(*logmsg);
7134 *logmsg = NULL;
7136 return err;
7140 static const struct got_error *
7141 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7142 void *arg)
7144 char *initial_content = NULL;
7145 struct got_pathlist_entry *pe;
7146 const struct got_error *err = NULL;
7147 char *template = NULL;
7148 struct collect_commit_logmsg_arg *a = arg;
7149 int initial_content_len;
7150 int fd = -1;
7151 size_t len;
7153 /* if a message was specified on the command line, just use it */
7154 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7155 len = strlen(a->cmdline_log) + 1;
7156 *logmsg = malloc(len + 1);
7157 if (*logmsg == NULL)
7158 return got_error_from_errno("malloc");
7159 strlcpy(*logmsg, a->cmdline_log, len);
7160 return NULL;
7161 } else if (a->prepared_log != NULL && a->non_interactive)
7162 return read_prepared_logmsg(logmsg, a->prepared_log);
7164 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7165 return got_error_from_errno("asprintf");
7167 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7168 if (err)
7169 goto done;
7171 if (a->prepared_log) {
7172 char *msg;
7173 err = read_prepared_logmsg(&msg, a->prepared_log);
7174 if (err)
7175 goto done;
7176 if (write(fd, msg, strlen(msg)) == -1) {
7177 err = got_error_from_errno2("write", a->logmsg_path);
7178 free(msg);
7179 goto done;
7181 free(msg);
7184 initial_content_len = asprintf(&initial_content,
7185 "\n# changes to be committed on branch %s:\n",
7186 a->branch_name);
7187 if (initial_content_len == -1) {
7188 err = got_error_from_errno("asprintf");
7189 goto done;
7192 if (write(fd, initial_content, initial_content_len) == -1) {
7193 err = got_error_from_errno2("write", a->logmsg_path);
7194 goto done;
7197 TAILQ_FOREACH(pe, commitable_paths, entry) {
7198 struct got_commitable *ct = pe->data;
7199 dprintf(fd, "# %c %s\n",
7200 got_commitable_get_status(ct),
7201 got_commitable_get_path(ct));
7204 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7205 initial_content_len, a->prepared_log ? 0 : 1);
7206 done:
7207 free(initial_content);
7208 free(template);
7210 if (fd != -1 && close(fd) == -1 && err == NULL)
7211 err = got_error_from_errno2("close", a->logmsg_path);
7213 /* Editor is done; we can now apply unveil(2) */
7214 if (err == NULL)
7215 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7216 if (err) {
7217 free(*logmsg);
7218 *logmsg = NULL;
7220 return err;
7223 static const struct got_error *
7224 cmd_commit(int argc, char *argv[])
7226 const struct got_error *error = NULL;
7227 struct got_worktree *worktree = NULL;
7228 struct got_repository *repo = NULL;
7229 char *cwd = NULL, *id_str = NULL;
7230 struct got_object_id *id = NULL;
7231 const char *logmsg = NULL;
7232 char *prepared_logmsg = NULL;
7233 struct collect_commit_logmsg_arg cl_arg;
7234 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7235 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7236 int allow_bad_symlinks = 0, non_interactive = 0;
7237 struct got_pathlist_head paths;
7239 TAILQ_INIT(&paths);
7240 cl_arg.logmsg_path = NULL;
7242 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7243 switch (ch) {
7244 case 'F':
7245 if (logmsg != NULL)
7246 option_conflict('F', 'm');
7247 prepared_logmsg = realpath(optarg, NULL);
7248 if (prepared_logmsg == NULL)
7249 return got_error_from_errno2("realpath",
7250 optarg);
7251 break;
7252 case 'm':
7253 if (prepared_logmsg)
7254 option_conflict('m', 'F');
7255 logmsg = optarg;
7256 break;
7257 case 'N':
7258 non_interactive = 1;
7259 break;
7260 case 'S':
7261 allow_bad_symlinks = 1;
7262 break;
7263 default:
7264 usage_commit();
7265 /* NOTREACHED */
7269 argc -= optind;
7270 argv += optind;
7272 #ifndef PROFILE
7273 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7274 "unveil", NULL) == -1)
7275 err(1, "pledge");
7276 #endif
7277 cwd = getcwd(NULL, 0);
7278 if (cwd == NULL) {
7279 error = got_error_from_errno("getcwd");
7280 goto done;
7282 error = got_worktree_open(&worktree, cwd);
7283 if (error) {
7284 if (error->code == GOT_ERR_NOT_WORKTREE)
7285 error = wrap_not_worktree_error(error, "commit", cwd);
7286 goto done;
7289 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7290 if (error)
7291 goto done;
7292 if (rebase_in_progress) {
7293 error = got_error(GOT_ERR_REBASING);
7294 goto done;
7297 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7298 worktree);
7299 if (error)
7300 goto done;
7302 error = get_gitconfig_path(&gitconfig_path);
7303 if (error)
7304 goto done;
7305 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7306 gitconfig_path);
7307 if (error != NULL)
7308 goto done;
7310 error = get_author(&author, repo, worktree);
7311 if (error)
7312 return error;
7315 * unveil(2) traverses exec(2); if an editor is used we have
7316 * to apply unveil after the log message has been written.
7318 if (logmsg == NULL || strlen(logmsg) == 0)
7319 error = get_editor(&editor);
7320 else
7321 error = apply_unveil(got_repo_get_path(repo), 0,
7322 got_worktree_get_root_path(worktree));
7323 if (error)
7324 goto done;
7326 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7327 if (error)
7328 goto done;
7330 cl_arg.editor = editor;
7331 cl_arg.cmdline_log = logmsg;
7332 cl_arg.prepared_log = prepared_logmsg;
7333 cl_arg.non_interactive = non_interactive;
7334 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7335 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7336 if (!histedit_in_progress) {
7337 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7338 error = got_error(GOT_ERR_COMMIT_BRANCH);
7339 goto done;
7341 cl_arg.branch_name += 11;
7343 cl_arg.repo_path = got_repo_get_path(repo);
7344 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7345 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7346 print_status, NULL, repo);
7347 if (error) {
7348 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7349 cl_arg.logmsg_path != NULL)
7350 preserve_logmsg = 1;
7351 goto done;
7354 error = got_object_id_str(&id_str, id);
7355 if (error)
7356 goto done;
7357 printf("Created commit %s\n", id_str);
7358 done:
7359 if (preserve_logmsg) {
7360 fprintf(stderr, "%s: log message preserved in %s\n",
7361 getprogname(), cl_arg.logmsg_path);
7362 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7363 error == NULL)
7364 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7365 free(cl_arg.logmsg_path);
7366 if (repo) {
7367 const struct got_error *close_err = got_repo_close(repo);
7368 if (error == NULL)
7369 error = close_err;
7371 if (worktree)
7372 got_worktree_close(worktree);
7373 free(cwd);
7374 free(id_str);
7375 free(gitconfig_path);
7376 free(editor);
7377 free(author);
7378 free(prepared_logmsg);
7379 return error;
7382 __dead static void
7383 usage_send(void)
7385 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7386 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7387 "[remote-repository]\n", getprogname());
7388 exit(1);
7391 struct got_send_progress_arg {
7392 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7393 int verbosity;
7394 int last_ncommits;
7395 int last_nobj_total;
7396 int last_p_deltify;
7397 int last_p_written;
7398 int last_p_sent;
7399 int printed_something;
7400 int sent_something;
7401 struct got_pathlist_head *delete_branches;
7404 static const struct got_error *
7405 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7406 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7407 int success)
7409 struct got_send_progress_arg *a = arg;
7410 char scaled_packsize[FMT_SCALED_STRSIZE];
7411 char scaled_sent[FMT_SCALED_STRSIZE];
7412 int p_deltify = 0, p_written = 0, p_sent = 0;
7413 int print_searching = 0, print_total = 0;
7414 int print_deltify = 0, print_written = 0, print_sent = 0;
7416 if (a->verbosity < 0)
7417 return NULL;
7419 if (refname) {
7420 const char *status = success ? "accepted" : "rejected";
7422 if (success) {
7423 struct got_pathlist_entry *pe;
7424 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7425 const char *branchname = pe->path;
7426 if (got_path_cmp(branchname, refname,
7427 strlen(branchname), strlen(refname)) == 0) {
7428 status = "deleted";
7429 a->sent_something = 1;
7430 break;
7435 if (a->printed_something)
7436 putchar('\n');
7437 printf("Server has %s %s", status, refname);
7438 a->printed_something = 1;
7439 return NULL;
7442 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7443 return got_error_from_errno("fmt_scaled");
7444 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7445 return got_error_from_errno("fmt_scaled");
7447 if (a->last_ncommits != ncommits) {
7448 print_searching = 1;
7449 a->last_ncommits = ncommits;
7452 if (a->last_nobj_total != nobj_total) {
7453 print_searching = 1;
7454 print_total = 1;
7455 a->last_nobj_total = nobj_total;
7458 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7459 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7460 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7461 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7462 return got_error(GOT_ERR_NO_SPACE);
7465 if (nobj_deltify > 0 || nobj_written > 0) {
7466 if (nobj_deltify > 0) {
7467 p_deltify = (nobj_deltify * 100) / nobj_total;
7468 if (p_deltify != a->last_p_deltify) {
7469 a->last_p_deltify = p_deltify;
7470 print_searching = 1;
7471 print_total = 1;
7472 print_deltify = 1;
7475 if (nobj_written > 0) {
7476 p_written = (nobj_written * 100) / nobj_total;
7477 if (p_written != a->last_p_written) {
7478 a->last_p_written = p_written;
7479 print_searching = 1;
7480 print_total = 1;
7481 print_deltify = 1;
7482 print_written = 1;
7487 if (bytes_sent > 0) {
7488 p_sent = (bytes_sent * 100) / packfile_size;
7489 if (p_sent != a->last_p_sent) {
7490 a->last_p_sent = p_sent;
7491 print_searching = 1;
7492 print_total = 1;
7493 print_deltify = 1;
7494 print_written = 1;
7495 print_sent = 1;
7497 a->sent_something = 1;
7500 if (print_searching || print_total || print_deltify || print_written ||
7501 print_sent)
7502 printf("\r");
7503 if (print_searching)
7504 printf("packing %d reference%s", ncommits,
7505 ncommits == 1 ? "" : "s");
7506 if (print_total)
7507 printf("; %d object%s", nobj_total,
7508 nobj_total == 1 ? "" : "s");
7509 if (print_deltify)
7510 printf("; deltify: %d%%", p_deltify);
7511 if (print_sent)
7512 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7513 scaled_packsize, p_sent);
7514 else if (print_written)
7515 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7516 scaled_packsize, p_written);
7517 if (print_searching || print_total || print_deltify ||
7518 print_written || print_sent) {
7519 a->printed_something = 1;
7520 fflush(stdout);
7522 return NULL;
7525 static const struct got_error *
7526 cmd_send(int argc, char *argv[])
7528 const struct got_error *error = NULL;
7529 char *cwd = NULL, *repo_path = NULL;
7530 const char *remote_name;
7531 char *proto = NULL, *host = NULL, *port = NULL;
7532 char *repo_name = NULL, *server_path = NULL;
7533 const struct got_remote_repo *remotes, *remote = NULL;
7534 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7535 struct got_repository *repo = NULL;
7536 struct got_worktree *worktree = NULL;
7537 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7538 struct got_pathlist_head branches;
7539 struct got_pathlist_head tags;
7540 struct got_reflist_head all_branches;
7541 struct got_reflist_head all_tags;
7542 struct got_pathlist_head delete_args;
7543 struct got_pathlist_head delete_branches;
7544 struct got_reflist_entry *re;
7545 struct got_pathlist_entry *pe;
7546 int i, ch, sendfd = -1, sendstatus;
7547 pid_t sendpid = -1;
7548 struct got_send_progress_arg spa;
7549 int verbosity = 0, overwrite_refs = 0;
7550 int send_all_branches = 0, send_all_tags = 0;
7551 struct got_reference *ref = NULL;
7553 TAILQ_INIT(&branches);
7554 TAILQ_INIT(&tags);
7555 TAILQ_INIT(&all_branches);
7556 TAILQ_INIT(&all_tags);
7557 TAILQ_INIT(&delete_args);
7558 TAILQ_INIT(&delete_branches);
7560 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7561 switch (ch) {
7562 case 'a':
7563 send_all_branches = 1;
7564 break;
7565 case 'b':
7566 error = got_pathlist_append(&branches, optarg, NULL);
7567 if (error)
7568 return error;
7569 nbranches++;
7570 break;
7571 case 'd':
7572 error = got_pathlist_append(&delete_args, optarg, NULL);
7573 if (error)
7574 return error;
7575 break;
7576 case 'f':
7577 overwrite_refs = 1;
7578 break;
7579 case 'r':
7580 repo_path = realpath(optarg, NULL);
7581 if (repo_path == NULL)
7582 return got_error_from_errno2("realpath",
7583 optarg);
7584 got_path_strip_trailing_slashes(repo_path);
7585 break;
7586 case 't':
7587 error = got_pathlist_append(&tags, optarg, NULL);
7588 if (error)
7589 return error;
7590 ntags++;
7591 break;
7592 case 'T':
7593 send_all_tags = 1;
7594 break;
7595 case 'v':
7596 if (verbosity < 0)
7597 verbosity = 0;
7598 else if (verbosity < 3)
7599 verbosity++;
7600 break;
7601 case 'q':
7602 verbosity = -1;
7603 break;
7604 default:
7605 usage_send();
7606 /* NOTREACHED */
7609 argc -= optind;
7610 argv += optind;
7612 if (send_all_branches && !TAILQ_EMPTY(&branches))
7613 option_conflict('a', 'b');
7614 if (send_all_tags && !TAILQ_EMPTY(&tags))
7615 option_conflict('T', 't');
7618 if (argc == 0)
7619 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7620 else if (argc == 1)
7621 remote_name = argv[0];
7622 else
7623 usage_send();
7625 cwd = getcwd(NULL, 0);
7626 if (cwd == NULL) {
7627 error = got_error_from_errno("getcwd");
7628 goto done;
7631 if (repo_path == NULL) {
7632 error = got_worktree_open(&worktree, cwd);
7633 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7634 goto done;
7635 else
7636 error = NULL;
7637 if (worktree) {
7638 repo_path =
7639 strdup(got_worktree_get_repo_path(worktree));
7640 if (repo_path == NULL)
7641 error = got_error_from_errno("strdup");
7642 if (error)
7643 goto done;
7644 } else {
7645 repo_path = strdup(cwd);
7646 if (repo_path == NULL) {
7647 error = got_error_from_errno("strdup");
7648 goto done;
7653 error = got_repo_open(&repo, repo_path, NULL);
7654 if (error)
7655 goto done;
7657 if (worktree) {
7658 worktree_conf = got_worktree_get_gotconfig(worktree);
7659 if (worktree_conf) {
7660 got_gotconfig_get_remotes(&nremotes, &remotes,
7661 worktree_conf);
7662 for (i = 0; i < nremotes; i++) {
7663 if (strcmp(remotes[i].name, remote_name) == 0) {
7664 remote = &remotes[i];
7665 break;
7670 if (remote == NULL) {
7671 repo_conf = got_repo_get_gotconfig(repo);
7672 if (repo_conf) {
7673 got_gotconfig_get_remotes(&nremotes, &remotes,
7674 repo_conf);
7675 for (i = 0; i < nremotes; i++) {
7676 if (strcmp(remotes[i].name, remote_name) == 0) {
7677 remote = &remotes[i];
7678 break;
7683 if (remote == NULL) {
7684 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7685 for (i = 0; i < nremotes; i++) {
7686 if (strcmp(remotes[i].name, remote_name) == 0) {
7687 remote = &remotes[i];
7688 break;
7692 if (remote == NULL) {
7693 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7694 goto done;
7697 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
7698 &repo_name, remote->send_url);
7699 if (error)
7700 goto done;
7702 if (strcmp(proto, "git") == 0) {
7703 #ifndef PROFILE
7704 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7705 "sendfd dns inet unveil", NULL) == -1)
7706 err(1, "pledge");
7707 #endif
7708 } else if (strcmp(proto, "git+ssh") == 0 ||
7709 strcmp(proto, "ssh") == 0) {
7710 #ifndef PROFILE
7711 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7712 "sendfd unveil", NULL) == -1)
7713 err(1, "pledge");
7714 #endif
7715 } else if (strcmp(proto, "http") == 0 ||
7716 strcmp(proto, "git+http") == 0) {
7717 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7718 goto done;
7719 } else {
7720 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7721 goto done;
7724 error = got_dial_apply_unveil(proto);
7725 if (error)
7726 goto done;
7728 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7729 if (error)
7730 goto done;
7732 if (send_all_branches) {
7733 error = got_ref_list(&all_branches, repo, "refs/heads",
7734 got_ref_cmp_by_name, NULL);
7735 if (error)
7736 goto done;
7737 TAILQ_FOREACH(re, &all_branches, entry) {
7738 const char *branchname = got_ref_get_name(re->ref);
7739 error = got_pathlist_append(&branches,
7740 branchname, NULL);
7741 if (error)
7742 goto done;
7743 nbranches++;
7745 } else if (nbranches == 0) {
7746 for (i = 0; i < remote->nsend_branches; i++) {
7747 got_pathlist_append(&branches,
7748 remote->send_branches[i], NULL);
7752 if (send_all_tags) {
7753 error = got_ref_list(&all_tags, repo, "refs/tags",
7754 got_ref_cmp_by_name, NULL);
7755 if (error)
7756 goto done;
7757 TAILQ_FOREACH(re, &all_tags, entry) {
7758 const char *tagname = got_ref_get_name(re->ref);
7759 error = got_pathlist_append(&tags,
7760 tagname, NULL);
7761 if (error)
7762 goto done;
7763 ntags++;
7768 * To prevent accidents only branches in refs/heads/ can be deleted
7769 * with 'got send -d'.
7770 * Deleting anything else requires local repository access or Git.
7772 TAILQ_FOREACH(pe, &delete_args, entry) {
7773 const char *branchname = pe->path;
7774 char *s;
7775 struct got_pathlist_entry *new;
7776 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7777 s = strdup(branchname);
7778 if (s == NULL) {
7779 error = got_error_from_errno("strdup");
7780 goto done;
7782 } else {
7783 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7784 error = got_error_from_errno("asprintf");
7785 goto done;
7788 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7789 if (error || new == NULL /* duplicate */)
7790 free(s);
7791 if (error)
7792 goto done;
7793 ndelete_branches++;
7796 if (nbranches == 0 && ndelete_branches == 0) {
7797 struct got_reference *head_ref;
7798 if (worktree)
7799 error = got_ref_open(&head_ref, repo,
7800 got_worktree_get_head_ref_name(worktree), 0);
7801 else
7802 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7803 if (error)
7804 goto done;
7805 if (got_ref_is_symbolic(head_ref)) {
7806 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7807 got_ref_close(head_ref);
7808 if (error)
7809 goto done;
7810 } else
7811 ref = head_ref;
7812 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7813 NULL);
7814 if (error)
7815 goto done;
7816 nbranches++;
7819 if (verbosity >= 0)
7820 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7821 port ? ":" : "", port ? port : "");
7823 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7824 server_path, verbosity);
7825 if (error)
7826 goto done;
7828 memset(&spa, 0, sizeof(spa));
7829 spa.last_scaled_packsize[0] = '\0';
7830 spa.last_p_deltify = -1;
7831 spa.last_p_written = -1;
7832 spa.verbosity = verbosity;
7833 spa.delete_branches = &delete_branches;
7834 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7835 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7836 check_cancelled, NULL);
7837 if (spa.printed_something)
7838 putchar('\n');
7839 if (error)
7840 goto done;
7841 if (!spa.sent_something && verbosity >= 0)
7842 printf("Already up-to-date\n");
7843 done:
7844 if (sendpid > 0) {
7845 if (kill(sendpid, SIGTERM) == -1)
7846 error = got_error_from_errno("kill");
7847 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7848 error = got_error_from_errno("waitpid");
7850 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7851 error = got_error_from_errno("close");
7852 if (repo) {
7853 const struct got_error *close_err = got_repo_close(repo);
7854 if (error == NULL)
7855 error = close_err;
7857 if (worktree)
7858 got_worktree_close(worktree);
7859 if (ref)
7860 got_ref_close(ref);
7861 got_pathlist_free(&branches);
7862 got_pathlist_free(&tags);
7863 got_ref_list_free(&all_branches);
7864 got_ref_list_free(&all_tags);
7865 got_pathlist_free(&delete_args);
7866 TAILQ_FOREACH(pe, &delete_branches, entry)
7867 free((char *)pe->path);
7868 got_pathlist_free(&delete_branches);
7869 free(cwd);
7870 free(repo_path);
7871 free(proto);
7872 free(host);
7873 free(port);
7874 free(server_path);
7875 free(repo_name);
7876 return error;
7879 __dead static void
7880 usage_cherrypick(void)
7882 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7883 exit(1);
7886 static const struct got_error *
7887 cmd_cherrypick(int argc, char *argv[])
7889 const struct got_error *error = NULL;
7890 struct got_worktree *worktree = NULL;
7891 struct got_repository *repo = NULL;
7892 char *cwd = NULL, *commit_id_str = NULL;
7893 struct got_object_id *commit_id = NULL;
7894 struct got_commit_object *commit = NULL;
7895 struct got_object_qid *pid;
7896 int ch;
7897 struct got_update_progress_arg upa;
7899 while ((ch = getopt(argc, argv, "")) != -1) {
7900 switch (ch) {
7901 default:
7902 usage_cherrypick();
7903 /* NOTREACHED */
7907 argc -= optind;
7908 argv += optind;
7910 #ifndef PROFILE
7911 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7912 "unveil", NULL) == -1)
7913 err(1, "pledge");
7914 #endif
7915 if (argc != 1)
7916 usage_cherrypick();
7918 cwd = getcwd(NULL, 0);
7919 if (cwd == NULL) {
7920 error = got_error_from_errno("getcwd");
7921 goto done;
7923 error = got_worktree_open(&worktree, cwd);
7924 if (error) {
7925 if (error->code == GOT_ERR_NOT_WORKTREE)
7926 error = wrap_not_worktree_error(error, "cherrypick",
7927 cwd);
7928 goto done;
7931 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7932 NULL);
7933 if (error != NULL)
7934 goto done;
7936 error = apply_unveil(got_repo_get_path(repo), 0,
7937 got_worktree_get_root_path(worktree));
7938 if (error)
7939 goto done;
7941 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7942 GOT_OBJ_TYPE_COMMIT, repo);
7943 if (error != NULL) {
7944 struct got_reference *ref;
7945 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7946 goto done;
7947 error = got_ref_open(&ref, repo, argv[0], 0);
7948 if (error != NULL)
7949 goto done;
7950 error = got_ref_resolve(&commit_id, repo, ref);
7951 got_ref_close(ref);
7952 if (error != NULL)
7953 goto done;
7955 error = got_object_id_str(&commit_id_str, commit_id);
7956 if (error)
7957 goto done;
7959 error = got_object_open_as_commit(&commit, repo, commit_id);
7960 if (error)
7961 goto done;
7962 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7963 memset(&upa, 0, sizeof(upa));
7964 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7965 commit_id, repo, update_progress, &upa, check_cancelled,
7966 NULL);
7967 if (error != NULL)
7968 goto done;
7970 if (upa.did_something)
7971 printf("Merged commit %s\n", commit_id_str);
7972 print_update_progress_stats(&upa);
7973 done:
7974 if (commit)
7975 got_object_commit_close(commit);
7976 free(commit_id_str);
7977 if (worktree)
7978 got_worktree_close(worktree);
7979 if (repo) {
7980 const struct got_error *close_err = got_repo_close(repo);
7981 if (error == NULL)
7982 error = close_err;
7984 return error;
7987 __dead static void
7988 usage_backout(void)
7990 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7991 exit(1);
7994 static const struct got_error *
7995 cmd_backout(int argc, char *argv[])
7997 const struct got_error *error = NULL;
7998 struct got_worktree *worktree = NULL;
7999 struct got_repository *repo = NULL;
8000 char *cwd = NULL, *commit_id_str = NULL;
8001 struct got_object_id *commit_id = NULL;
8002 struct got_commit_object *commit = NULL;
8003 struct got_object_qid *pid;
8004 int ch;
8005 struct got_update_progress_arg upa;
8007 while ((ch = getopt(argc, argv, "")) != -1) {
8008 switch (ch) {
8009 default:
8010 usage_backout();
8011 /* NOTREACHED */
8015 argc -= optind;
8016 argv += optind;
8018 #ifndef PROFILE
8019 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8020 "unveil", NULL) == -1)
8021 err(1, "pledge");
8022 #endif
8023 if (argc != 1)
8024 usage_backout();
8026 cwd = getcwd(NULL, 0);
8027 if (cwd == NULL) {
8028 error = got_error_from_errno("getcwd");
8029 goto done;
8031 error = got_worktree_open(&worktree, cwd);
8032 if (error) {
8033 if (error->code == GOT_ERR_NOT_WORKTREE)
8034 error = wrap_not_worktree_error(error, "backout", cwd);
8035 goto done;
8038 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8039 NULL);
8040 if (error != NULL)
8041 goto done;
8043 error = apply_unveil(got_repo_get_path(repo), 0,
8044 got_worktree_get_root_path(worktree));
8045 if (error)
8046 goto done;
8048 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8049 GOT_OBJ_TYPE_COMMIT, repo);
8050 if (error != NULL) {
8051 struct got_reference *ref;
8052 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8053 goto done;
8054 error = got_ref_open(&ref, repo, argv[0], 0);
8055 if (error != NULL)
8056 goto done;
8057 error = got_ref_resolve(&commit_id, repo, ref);
8058 got_ref_close(ref);
8059 if (error != NULL)
8060 goto done;
8062 error = got_object_id_str(&commit_id_str, commit_id);
8063 if (error)
8064 goto done;
8066 error = got_object_open_as_commit(&commit, repo, commit_id);
8067 if (error)
8068 goto done;
8069 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8070 if (pid == NULL) {
8071 error = got_error(GOT_ERR_ROOT_COMMIT);
8072 goto done;
8075 memset(&upa, 0, sizeof(upa));
8076 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8077 update_progress, &upa, check_cancelled, NULL);
8078 if (error != NULL)
8079 goto done;
8081 if (upa.did_something)
8082 printf("Backed out commit %s\n", commit_id_str);
8083 print_update_progress_stats(&upa);
8084 done:
8085 if (commit)
8086 got_object_commit_close(commit);
8087 free(commit_id_str);
8088 if (worktree)
8089 got_worktree_close(worktree);
8090 if (repo) {
8091 const struct got_error *close_err = got_repo_close(repo);
8092 if (error == NULL)
8093 error = close_err;
8095 return error;
8098 __dead static void
8099 usage_rebase(void)
8101 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8102 getprogname());
8103 exit(1);
8106 void
8107 trim_logmsg(char *logmsg, int limit)
8109 char *nl;
8110 size_t len;
8112 len = strlen(logmsg);
8113 if (len > limit)
8114 len = limit;
8115 logmsg[len] = '\0';
8116 nl = strchr(logmsg, '\n');
8117 if (nl)
8118 *nl = '\0';
8121 static const struct got_error *
8122 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8124 const struct got_error *err;
8125 char *logmsg0 = NULL;
8126 const char *s;
8128 err = got_object_commit_get_logmsg(&logmsg0, commit);
8129 if (err)
8130 return err;
8132 s = logmsg0;
8133 while (isspace((unsigned char)s[0]))
8134 s++;
8136 *logmsg = strdup(s);
8137 if (*logmsg == NULL) {
8138 err = got_error_from_errno("strdup");
8139 goto done;
8142 trim_logmsg(*logmsg, limit);
8143 done:
8144 free(logmsg0);
8145 return err;
8148 static const struct got_error *
8149 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8151 const struct got_error *err;
8152 struct got_commit_object *commit = NULL;
8153 char *id_str = NULL, *logmsg = NULL;
8155 err = got_object_open_as_commit(&commit, repo, id);
8156 if (err)
8157 return err;
8159 err = got_object_id_str(&id_str, id);
8160 if (err)
8161 goto done;
8163 id_str[12] = '\0';
8165 err = get_short_logmsg(&logmsg, 42, commit);
8166 if (err)
8167 goto done;
8169 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8170 done:
8171 free(id_str);
8172 got_object_commit_close(commit);
8173 free(logmsg);
8174 return err;
8177 static const struct got_error *
8178 show_rebase_progress(struct got_commit_object *commit,
8179 struct got_object_id *old_id, struct got_object_id *new_id)
8181 const struct got_error *err;
8182 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8184 err = got_object_id_str(&old_id_str, old_id);
8185 if (err)
8186 goto done;
8188 if (new_id) {
8189 err = got_object_id_str(&new_id_str, new_id);
8190 if (err)
8191 goto done;
8194 old_id_str[12] = '\0';
8195 if (new_id_str)
8196 new_id_str[12] = '\0';
8198 err = get_short_logmsg(&logmsg, 42, commit);
8199 if (err)
8200 goto done;
8202 printf("%s -> %s: %s\n", old_id_str,
8203 new_id_str ? new_id_str : "no-op change", logmsg);
8204 done:
8205 free(old_id_str);
8206 free(new_id_str);
8207 free(logmsg);
8208 return err;
8211 static const struct got_error *
8212 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8213 struct got_reference *branch, struct got_reference *new_base_branch,
8214 struct got_reference *tmp_branch, struct got_repository *repo,
8215 int create_backup)
8217 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8218 return got_worktree_rebase_complete(worktree, fileindex,
8219 new_base_branch, tmp_branch, branch, repo, create_backup);
8222 static const struct got_error *
8223 rebase_commit(struct got_pathlist_head *merged_paths,
8224 struct got_worktree *worktree, struct got_fileindex *fileindex,
8225 struct got_reference *tmp_branch,
8226 struct got_object_id *commit_id, struct got_repository *repo)
8228 const struct got_error *error;
8229 struct got_commit_object *commit;
8230 struct got_object_id *new_commit_id;
8232 error = got_object_open_as_commit(&commit, repo, commit_id);
8233 if (error)
8234 return error;
8236 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8237 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8238 if (error) {
8239 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8240 goto done;
8241 error = show_rebase_progress(commit, commit_id, NULL);
8242 } else {
8243 error = show_rebase_progress(commit, commit_id, new_commit_id);
8244 free(new_commit_id);
8246 done:
8247 got_object_commit_close(commit);
8248 return error;
8251 struct check_path_prefix_arg {
8252 const char *path_prefix;
8253 size_t len;
8254 int errcode;
8257 static const struct got_error *
8258 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8259 struct got_blob_object *blob2, struct got_object_id *id1,
8260 struct got_object_id *id2, const char *path1, const char *path2,
8261 mode_t mode1, mode_t mode2, struct got_repository *repo)
8263 struct check_path_prefix_arg *a = arg;
8265 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8266 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8267 return got_error(a->errcode);
8269 return NULL;
8272 static const struct got_error *
8273 check_path_prefix(struct got_object_id *parent_id,
8274 struct got_object_id *commit_id, const char *path_prefix,
8275 int errcode, struct got_repository *repo)
8277 const struct got_error *err;
8278 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8279 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8280 struct check_path_prefix_arg cpp_arg;
8282 if (got_path_is_root_dir(path_prefix))
8283 return NULL;
8285 err = got_object_open_as_commit(&commit, repo, commit_id);
8286 if (err)
8287 goto done;
8289 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8290 if (err)
8291 goto done;
8293 err = got_object_open_as_tree(&tree1, repo,
8294 got_object_commit_get_tree_id(parent_commit));
8295 if (err)
8296 goto done;
8298 err = got_object_open_as_tree(&tree2, repo,
8299 got_object_commit_get_tree_id(commit));
8300 if (err)
8301 goto done;
8303 cpp_arg.path_prefix = path_prefix;
8304 while (cpp_arg.path_prefix[0] == '/')
8305 cpp_arg.path_prefix++;
8306 cpp_arg.len = strlen(cpp_arg.path_prefix);
8307 cpp_arg.errcode = errcode;
8308 err = got_diff_tree(tree1, tree2, "", "", repo,
8309 check_path_prefix_in_diff, &cpp_arg, 0);
8310 done:
8311 if (tree1)
8312 got_object_tree_close(tree1);
8313 if (tree2)
8314 got_object_tree_close(tree2);
8315 if (commit)
8316 got_object_commit_close(commit);
8317 if (parent_commit)
8318 got_object_commit_close(parent_commit);
8319 return err;
8322 static const struct got_error *
8323 collect_commits(struct got_object_id_queue *commits,
8324 struct got_object_id *initial_commit_id,
8325 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8326 const char *path_prefix, int path_prefix_errcode,
8327 struct got_repository *repo)
8329 const struct got_error *err = NULL;
8330 struct got_commit_graph *graph = NULL;
8331 struct got_object_id *parent_id = NULL;
8332 struct got_object_qid *qid;
8333 struct got_object_id *commit_id = initial_commit_id;
8335 err = got_commit_graph_open(&graph, "/", 1);
8336 if (err)
8337 return err;
8339 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8340 check_cancelled, NULL);
8341 if (err)
8342 goto done;
8343 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8344 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8345 check_cancelled, NULL);
8346 if (err) {
8347 if (err->code == GOT_ERR_ITER_COMPLETED) {
8348 err = got_error_msg(GOT_ERR_ANCESTRY,
8349 "ran out of commits to rebase before "
8350 "youngest common ancestor commit has "
8351 "been reached?!?");
8353 goto done;
8354 } else {
8355 err = check_path_prefix(parent_id, commit_id,
8356 path_prefix, path_prefix_errcode, repo);
8357 if (err)
8358 goto done;
8360 err = got_object_qid_alloc(&qid, commit_id);
8361 if (err)
8362 goto done;
8363 STAILQ_INSERT_HEAD(commits, qid, entry);
8364 commit_id = parent_id;
8367 done:
8368 got_commit_graph_close(graph);
8369 return err;
8372 static const struct got_error *
8373 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8375 const struct got_error *err = NULL;
8376 time_t committer_time;
8377 struct tm tm;
8378 char datebuf[11]; /* YYYY-MM-DD + NUL */
8379 char *author0 = NULL, *author, *smallerthan;
8380 char *logmsg0 = NULL, *logmsg, *newline;
8382 committer_time = got_object_commit_get_committer_time(commit);
8383 if (gmtime_r(&committer_time, &tm) == NULL)
8384 return got_error_from_errno("gmtime_r");
8385 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8386 return got_error(GOT_ERR_NO_SPACE);
8388 author0 = strdup(got_object_commit_get_author(commit));
8389 if (author0 == NULL)
8390 return got_error_from_errno("strdup");
8391 author = author0;
8392 smallerthan = strchr(author, '<');
8393 if (smallerthan && smallerthan[1] != '\0')
8394 author = smallerthan + 1;
8395 author[strcspn(author, "@>")] = '\0';
8397 err = got_object_commit_get_logmsg(&logmsg0, commit);
8398 if (err)
8399 goto done;
8400 logmsg = logmsg0;
8401 while (*logmsg == '\n')
8402 logmsg++;
8403 newline = strchr(logmsg, '\n');
8404 if (newline)
8405 *newline = '\0';
8407 if (asprintf(brief_str, "%s %s %s",
8408 datebuf, author, logmsg) == -1)
8409 err = got_error_from_errno("asprintf");
8410 done:
8411 free(author0);
8412 free(logmsg0);
8413 return err;
8416 static const struct got_error *
8417 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8418 struct got_repository *repo)
8420 const struct got_error *err;
8421 char *id_str;
8423 err = got_object_id_str(&id_str, id);
8424 if (err)
8425 return err;
8427 err = got_ref_delete(ref, repo);
8428 if (err)
8429 goto done;
8431 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8432 done:
8433 free(id_str);
8434 return err;
8437 static const struct got_error *
8438 print_backup_ref(const char *branch_name, const char *new_id_str,
8439 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8440 struct got_reflist_object_id_map *refs_idmap,
8441 struct got_repository *repo)
8443 const struct got_error *err = NULL;
8444 struct got_reflist_head *refs;
8445 char *refs_str = NULL;
8446 struct got_object_id *new_commit_id = NULL;
8447 struct got_commit_object *new_commit = NULL;
8448 char *new_commit_brief_str = NULL;
8449 struct got_object_id *yca_id = NULL;
8450 struct got_commit_object *yca_commit = NULL;
8451 char *yca_id_str = NULL, *yca_brief_str = NULL;
8452 char *custom_refs_str;
8454 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8455 return got_error_from_errno("asprintf");
8457 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8458 0, 0, refs_idmap, custom_refs_str);
8459 if (err)
8460 goto done;
8462 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8463 if (err)
8464 goto done;
8466 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8467 if (refs) {
8468 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8469 if (err)
8470 goto done;
8473 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8474 if (err)
8475 goto done;
8477 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8478 if (err)
8479 goto done;
8481 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8482 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8483 if (err)
8484 goto done;
8486 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8487 refs_str ? " (" : "", refs_str ? refs_str : "",
8488 refs_str ? ")" : "", new_commit_brief_str);
8489 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8490 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8491 free(refs_str);
8492 refs_str = NULL;
8494 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8495 if (err)
8496 goto done;
8498 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8499 if (err)
8500 goto done;
8502 err = got_object_id_str(&yca_id_str, yca_id);
8503 if (err)
8504 goto done;
8506 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8507 if (refs) {
8508 err = build_refs_str(&refs_str, refs, yca_id, repo);
8509 if (err)
8510 goto done;
8512 printf("history forked at %s%s%s%s\n %s\n",
8513 yca_id_str,
8514 refs_str ? " (" : "", refs_str ? refs_str : "",
8515 refs_str ? ")" : "", yca_brief_str);
8517 done:
8518 free(custom_refs_str);
8519 free(new_commit_id);
8520 free(refs_str);
8521 free(yca_id);
8522 free(yca_id_str);
8523 free(yca_brief_str);
8524 if (new_commit)
8525 got_object_commit_close(new_commit);
8526 if (yca_commit)
8527 got_object_commit_close(yca_commit);
8529 return NULL;
8532 static const struct got_error *
8533 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8534 int delete, struct got_repository *repo)
8536 const struct got_error *err;
8537 struct got_reflist_head refs, backup_refs;
8538 struct got_reflist_entry *re;
8539 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8540 struct got_object_id *old_commit_id = NULL;
8541 char *branch_name = NULL;
8542 struct got_commit_object *old_commit = NULL;
8543 struct got_reflist_object_id_map *refs_idmap = NULL;
8544 int wanted_branch_found = 0;
8546 TAILQ_INIT(&refs);
8547 TAILQ_INIT(&backup_refs);
8549 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8550 if (err)
8551 return err;
8553 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8554 if (err)
8555 goto done;
8557 if (wanted_branch_name) {
8558 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8559 wanted_branch_name += 11;
8562 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8563 got_ref_cmp_by_commit_timestamp_descending, repo);
8564 if (err)
8565 goto done;
8567 TAILQ_FOREACH(re, &backup_refs, entry) {
8568 const char *refname = got_ref_get_name(re->ref);
8569 char *slash;
8571 err = check_cancelled(NULL);
8572 if (err)
8573 break;
8575 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8576 if (err)
8577 break;
8579 err = got_object_open_as_commit(&old_commit, repo,
8580 old_commit_id);
8581 if (err)
8582 break;
8584 if (strncmp(backup_ref_prefix, refname,
8585 backup_ref_prefix_len) == 0)
8586 refname += backup_ref_prefix_len;
8588 while (refname[0] == '/')
8589 refname++;
8591 branch_name = strdup(refname);
8592 if (branch_name == NULL) {
8593 err = got_error_from_errno("strdup");
8594 break;
8596 slash = strrchr(branch_name, '/');
8597 if (slash) {
8598 *slash = '\0';
8599 refname += strlen(branch_name) + 1;
8602 if (wanted_branch_name == NULL ||
8603 strcmp(wanted_branch_name, branch_name) == 0) {
8604 wanted_branch_found = 1;
8605 if (delete) {
8606 err = delete_backup_ref(re->ref,
8607 old_commit_id, repo);
8608 } else {
8609 err = print_backup_ref(branch_name, refname,
8610 old_commit_id, old_commit, refs_idmap,
8611 repo);
8613 if (err)
8614 break;
8617 free(old_commit_id);
8618 old_commit_id = NULL;
8619 free(branch_name);
8620 branch_name = NULL;
8621 got_object_commit_close(old_commit);
8622 old_commit = NULL;
8625 if (wanted_branch_name && !wanted_branch_found) {
8626 err = got_error_fmt(GOT_ERR_NOT_REF,
8627 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8629 done:
8630 if (refs_idmap)
8631 got_reflist_object_id_map_free(refs_idmap);
8632 got_ref_list_free(&refs);
8633 got_ref_list_free(&backup_refs);
8634 free(old_commit_id);
8635 free(branch_name);
8636 if (old_commit)
8637 got_object_commit_close(old_commit);
8638 return err;
8641 static const struct got_error *
8642 cmd_rebase(int argc, char *argv[])
8644 const struct got_error *error = NULL;
8645 struct got_worktree *worktree = NULL;
8646 struct got_repository *repo = NULL;
8647 struct got_fileindex *fileindex = NULL;
8648 char *cwd = NULL;
8649 struct got_reference *branch = NULL;
8650 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8651 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8652 struct got_object_id *resume_commit_id = NULL;
8653 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8654 struct got_commit_object *commit = NULL;
8655 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8656 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8657 int delete_backups = 0;
8658 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8659 struct got_object_id_queue commits;
8660 struct got_pathlist_head merged_paths;
8661 const struct got_object_id_queue *parent_ids;
8662 struct got_object_qid *qid, *pid;
8664 STAILQ_INIT(&commits);
8665 TAILQ_INIT(&merged_paths);
8667 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8668 switch (ch) {
8669 case 'a':
8670 abort_rebase = 1;
8671 break;
8672 case 'c':
8673 continue_rebase = 1;
8674 break;
8675 case 'l':
8676 list_backups = 1;
8677 break;
8678 case 'X':
8679 delete_backups = 1;
8680 break;
8681 default:
8682 usage_rebase();
8683 /* NOTREACHED */
8687 argc -= optind;
8688 argv += optind;
8690 #ifndef PROFILE
8691 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8692 "unveil", NULL) == -1)
8693 err(1, "pledge");
8694 #endif
8695 if (list_backups) {
8696 if (abort_rebase)
8697 option_conflict('l', 'a');
8698 if (continue_rebase)
8699 option_conflict('l', 'c');
8700 if (delete_backups)
8701 option_conflict('l', 'X');
8702 if (argc != 0 && argc != 1)
8703 usage_rebase();
8704 } else if (delete_backups) {
8705 if (abort_rebase)
8706 option_conflict('X', 'a');
8707 if (continue_rebase)
8708 option_conflict('X', 'c');
8709 if (list_backups)
8710 option_conflict('l', 'X');
8711 if (argc != 0 && argc != 1)
8712 usage_rebase();
8713 } else {
8714 if (abort_rebase && continue_rebase)
8715 usage_rebase();
8716 else if (abort_rebase || continue_rebase) {
8717 if (argc != 0)
8718 usage_rebase();
8719 } else if (argc != 1)
8720 usage_rebase();
8723 cwd = getcwd(NULL, 0);
8724 if (cwd == NULL) {
8725 error = got_error_from_errno("getcwd");
8726 goto done;
8728 error = got_worktree_open(&worktree, cwd);
8729 if (error) {
8730 if (list_backups || delete_backups) {
8731 if (error->code != GOT_ERR_NOT_WORKTREE)
8732 goto done;
8733 } else {
8734 if (error->code == GOT_ERR_NOT_WORKTREE)
8735 error = wrap_not_worktree_error(error,
8736 "rebase", cwd);
8737 goto done;
8741 error = got_repo_open(&repo,
8742 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8743 if (error != NULL)
8744 goto done;
8746 error = apply_unveil(got_repo_get_path(repo), 0,
8747 worktree ? got_worktree_get_root_path(worktree) : NULL);
8748 if (error)
8749 goto done;
8751 if (list_backups || delete_backups) {
8752 error = process_backup_refs(
8753 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8754 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8755 goto done; /* nothing else to do */
8758 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8759 worktree);
8760 if (error)
8761 goto done;
8762 if (histedit_in_progress) {
8763 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8764 goto done;
8767 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8768 if (error)
8769 goto done;
8771 if (abort_rebase) {
8772 struct got_update_progress_arg upa;
8773 if (!rebase_in_progress) {
8774 error = got_error(GOT_ERR_NOT_REBASING);
8775 goto done;
8777 error = got_worktree_rebase_continue(&resume_commit_id,
8778 &new_base_branch, &tmp_branch, &branch, &fileindex,
8779 worktree, repo);
8780 if (error)
8781 goto done;
8782 printf("Switching work tree to %s\n",
8783 got_ref_get_symref_target(new_base_branch));
8784 memset(&upa, 0, sizeof(upa));
8785 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8786 new_base_branch, update_progress, &upa);
8787 if (error)
8788 goto done;
8789 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8790 print_update_progress_stats(&upa);
8791 goto done; /* nothing else to do */
8794 if (continue_rebase) {
8795 if (!rebase_in_progress) {
8796 error = got_error(GOT_ERR_NOT_REBASING);
8797 goto done;
8799 error = got_worktree_rebase_continue(&resume_commit_id,
8800 &new_base_branch, &tmp_branch, &branch, &fileindex,
8801 worktree, repo);
8802 if (error)
8803 goto done;
8805 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8806 resume_commit_id, repo);
8807 if (error)
8808 goto done;
8810 yca_id = got_object_id_dup(resume_commit_id);
8811 if (yca_id == NULL) {
8812 error = got_error_from_errno("got_object_id_dup");
8813 goto done;
8815 } else {
8816 error = got_ref_open(&branch, repo, argv[0], 0);
8817 if (error != NULL)
8818 goto done;
8821 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8822 if (error)
8823 goto done;
8825 if (!continue_rebase) {
8826 struct got_object_id *base_commit_id;
8828 base_commit_id = got_worktree_get_base_commit_id(worktree);
8829 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8830 base_commit_id, branch_head_commit_id, repo,
8831 check_cancelled, NULL);
8832 if (error)
8833 goto done;
8834 if (yca_id == NULL) {
8835 error = got_error_msg(GOT_ERR_ANCESTRY,
8836 "specified branch shares no common ancestry "
8837 "with work tree's branch");
8838 goto done;
8841 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8842 if (error) {
8843 if (error->code != GOT_ERR_ANCESTRY)
8844 goto done;
8845 error = NULL;
8846 } else {
8847 static char msg[128];
8848 snprintf(msg, sizeof(msg),
8849 "%s is already based on %s",
8850 got_ref_get_name(branch),
8851 got_worktree_get_head_ref_name(worktree));
8852 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8853 goto done;
8855 error = got_worktree_rebase_prepare(&new_base_branch,
8856 &tmp_branch, &fileindex, worktree, branch, repo);
8857 if (error)
8858 goto done;
8861 commit_id = branch_head_commit_id;
8862 error = got_object_open_as_commit(&commit, repo, commit_id);
8863 if (error)
8864 goto done;
8866 parent_ids = got_object_commit_get_parent_ids(commit);
8867 pid = STAILQ_FIRST(parent_ids);
8868 if (pid == NULL) {
8869 if (!continue_rebase) {
8870 struct got_update_progress_arg upa;
8871 memset(&upa, 0, sizeof(upa));
8872 error = got_worktree_rebase_abort(worktree, fileindex,
8873 repo, new_base_branch, update_progress, &upa);
8874 if (error)
8875 goto done;
8876 printf("Rebase of %s aborted\n",
8877 got_ref_get_name(branch));
8878 print_update_progress_stats(&upa);
8881 error = got_error(GOT_ERR_EMPTY_REBASE);
8882 goto done;
8884 error = collect_commits(&commits, commit_id, pid->id,
8885 yca_id, got_worktree_get_path_prefix(worktree),
8886 GOT_ERR_REBASE_PATH, repo);
8887 got_object_commit_close(commit);
8888 commit = NULL;
8889 if (error)
8890 goto done;
8892 if (STAILQ_EMPTY(&commits)) {
8893 if (continue_rebase) {
8894 error = rebase_complete(worktree, fileindex,
8895 branch, new_base_branch, tmp_branch, repo,
8896 create_backup);
8897 goto done;
8898 } else {
8899 /* Fast-forward the reference of the branch. */
8900 struct got_object_id *new_head_commit_id;
8901 char *id_str;
8902 error = got_ref_resolve(&new_head_commit_id, repo,
8903 new_base_branch);
8904 if (error)
8905 goto done;
8906 error = got_object_id_str(&id_str, new_head_commit_id);
8907 printf("Forwarding %s to commit %s\n",
8908 got_ref_get_name(branch), id_str);
8909 free(id_str);
8910 error = got_ref_change_ref(branch,
8911 new_head_commit_id);
8912 if (error)
8913 goto done;
8914 /* No backup needed since objects did not change. */
8915 create_backup = 0;
8919 pid = NULL;
8920 STAILQ_FOREACH(qid, &commits, entry) {
8921 struct got_update_progress_arg upa;
8923 commit_id = qid->id;
8924 parent_id = pid ? pid->id : yca_id;
8925 pid = qid;
8927 memset(&upa, 0, sizeof(upa));
8928 error = got_worktree_rebase_merge_files(&merged_paths,
8929 worktree, fileindex, parent_id, commit_id, repo,
8930 update_progress, &upa, check_cancelled, NULL);
8931 if (error)
8932 goto done;
8934 print_update_progress_stats(&upa);
8935 if (upa.conflicts > 0)
8936 rebase_status = GOT_STATUS_CONFLICT;
8938 if (rebase_status == GOT_STATUS_CONFLICT) {
8939 error = show_rebase_merge_conflict(qid->id, repo);
8940 if (error)
8941 goto done;
8942 got_worktree_rebase_pathlist_free(&merged_paths);
8943 break;
8946 error = rebase_commit(&merged_paths, worktree, fileindex,
8947 tmp_branch, commit_id, repo);
8948 got_worktree_rebase_pathlist_free(&merged_paths);
8949 if (error)
8950 goto done;
8953 if (rebase_status == GOT_STATUS_CONFLICT) {
8954 error = got_worktree_rebase_postpone(worktree, fileindex);
8955 if (error)
8956 goto done;
8957 error = got_error_msg(GOT_ERR_CONFLICTS,
8958 "conflicts must be resolved before rebasing can continue");
8959 } else
8960 error = rebase_complete(worktree, fileindex, branch,
8961 new_base_branch, tmp_branch, repo, create_backup);
8962 done:
8963 got_object_id_queue_free(&commits);
8964 free(branch_head_commit_id);
8965 free(resume_commit_id);
8966 free(yca_id);
8967 if (commit)
8968 got_object_commit_close(commit);
8969 if (branch)
8970 got_ref_close(branch);
8971 if (new_base_branch)
8972 got_ref_close(new_base_branch);
8973 if (tmp_branch)
8974 got_ref_close(tmp_branch);
8975 if (worktree)
8976 got_worktree_close(worktree);
8977 if (repo) {
8978 const struct got_error *close_err = got_repo_close(repo);
8979 if (error == NULL)
8980 error = close_err;
8982 return error;
8985 __dead static void
8986 usage_histedit(void)
8988 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8989 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
8990 getprogname());
8991 exit(1);
8994 #define GOT_HISTEDIT_PICK 'p'
8995 #define GOT_HISTEDIT_EDIT 'e'
8996 #define GOT_HISTEDIT_FOLD 'f'
8997 #define GOT_HISTEDIT_DROP 'd'
8998 #define GOT_HISTEDIT_MESG 'm'
9000 static struct got_histedit_cmd {
9001 unsigned char code;
9002 const char *name;
9003 const char *desc;
9004 } got_histedit_cmds[] = {
9005 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9006 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9007 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9008 "be used" },
9009 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9010 { GOT_HISTEDIT_MESG, "mesg",
9011 "single-line log message for commit above (open editor if empty)" },
9014 struct got_histedit_list_entry {
9015 TAILQ_ENTRY(got_histedit_list_entry) entry;
9016 struct got_object_id *commit_id;
9017 const struct got_histedit_cmd *cmd;
9018 char *logmsg;
9020 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9022 static const struct got_error *
9023 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9024 FILE *f, struct got_repository *repo)
9026 const struct got_error *err = NULL;
9027 char *logmsg = NULL, *id_str = NULL;
9028 struct got_commit_object *commit = NULL;
9029 int n;
9031 err = got_object_open_as_commit(&commit, repo, commit_id);
9032 if (err)
9033 goto done;
9035 err = get_short_logmsg(&logmsg, 34, commit);
9036 if (err)
9037 goto done;
9039 err = got_object_id_str(&id_str, commit_id);
9040 if (err)
9041 goto done;
9043 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9044 if (n < 0)
9045 err = got_ferror(f, GOT_ERR_IO);
9046 done:
9047 if (commit)
9048 got_object_commit_close(commit);
9049 free(id_str);
9050 free(logmsg);
9051 return err;
9054 static const struct got_error *
9055 histedit_write_commit_list(struct got_object_id_queue *commits,
9056 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9058 const struct got_error *err = NULL;
9059 struct got_object_qid *qid;
9060 const char *histedit_cmd = NULL;
9062 if (STAILQ_EMPTY(commits))
9063 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9065 STAILQ_FOREACH(qid, commits, entry) {
9066 histedit_cmd = got_histedit_cmds[0].name;
9067 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9068 histedit_cmd = "fold";
9069 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9070 if (err)
9071 break;
9072 if (edit_logmsg_only) {
9073 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9074 if (n < 0) {
9075 err = got_ferror(f, GOT_ERR_IO);
9076 break;
9081 return err;
9084 static const struct got_error *
9085 write_cmd_list(FILE *f, const char *branch_name,
9086 struct got_object_id_queue *commits)
9088 const struct got_error *err = NULL;
9089 size_t i;
9090 int n;
9091 char *id_str;
9092 struct got_object_qid *qid;
9094 qid = STAILQ_FIRST(commits);
9095 err = got_object_id_str(&id_str, qid->id);
9096 if (err)
9097 return err;
9099 n = fprintf(f,
9100 "# Editing the history of branch '%s' starting at\n"
9101 "# commit %s\n"
9102 "# Commits will be processed in order from top to "
9103 "bottom of this file.\n", branch_name, id_str);
9104 if (n < 0) {
9105 err = got_ferror(f, GOT_ERR_IO);
9106 goto done;
9109 n = fprintf(f, "# Available histedit commands:\n");
9110 if (n < 0) {
9111 err = got_ferror(f, GOT_ERR_IO);
9112 goto done;
9115 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9116 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9117 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9118 cmd->desc);
9119 if (n < 0) {
9120 err = got_ferror(f, GOT_ERR_IO);
9121 break;
9124 done:
9125 free(id_str);
9126 return err;
9129 static const struct got_error *
9130 histedit_syntax_error(int lineno)
9132 static char msg[42];
9133 int ret;
9135 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9136 lineno);
9137 if (ret == -1 || ret >= sizeof(msg))
9138 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9140 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9143 static const struct got_error *
9144 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9145 char *logmsg, struct got_repository *repo)
9147 const struct got_error *err;
9148 struct got_commit_object *folded_commit = NULL;
9149 char *id_str, *folded_logmsg = NULL;
9151 err = got_object_id_str(&id_str, hle->commit_id);
9152 if (err)
9153 return err;
9155 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9156 if (err)
9157 goto done;
9159 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9160 if (err)
9161 goto done;
9162 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9163 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9164 folded_logmsg) == -1) {
9165 err = got_error_from_errno("asprintf");
9167 done:
9168 if (folded_commit)
9169 got_object_commit_close(folded_commit);
9170 free(id_str);
9171 free(folded_logmsg);
9172 return err;
9175 static struct got_histedit_list_entry *
9176 get_folded_commits(struct got_histedit_list_entry *hle)
9178 struct got_histedit_list_entry *prev, *folded = NULL;
9180 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9181 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9182 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9183 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9184 folded = prev;
9185 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9188 return folded;
9191 static const struct got_error *
9192 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9193 struct got_repository *repo)
9195 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9196 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9197 const struct got_error *err = NULL;
9198 struct got_commit_object *commit = NULL;
9199 int logmsg_len;
9200 int fd;
9201 struct got_histedit_list_entry *folded = NULL;
9203 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9204 if (err)
9205 return err;
9207 folded = get_folded_commits(hle);
9208 if (folded) {
9209 while (folded != hle) {
9210 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9211 folded = TAILQ_NEXT(folded, entry);
9212 continue;
9214 err = append_folded_commit_msg(&new_msg, folded,
9215 logmsg, repo);
9216 if (err)
9217 goto done;
9218 free(logmsg);
9219 logmsg = new_msg;
9220 folded = TAILQ_NEXT(folded, entry);
9224 err = got_object_id_str(&id_str, hle->commit_id);
9225 if (err)
9226 goto done;
9227 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9228 if (err)
9229 goto done;
9230 logmsg_len = asprintf(&new_msg,
9231 "%s\n# original log message of commit %s: %s",
9232 logmsg ? logmsg : "", id_str, orig_logmsg);
9233 if (logmsg_len == -1) {
9234 err = got_error_from_errno("asprintf");
9235 goto done;
9237 free(logmsg);
9238 logmsg = new_msg;
9240 err = got_object_id_str(&id_str, hle->commit_id);
9241 if (err)
9242 goto done;
9244 err = got_opentemp_named_fd(&logmsg_path, &fd,
9245 GOT_TMPDIR_STR "/got-logmsg");
9246 if (err)
9247 goto done;
9249 write(fd, logmsg, logmsg_len);
9250 close(fd);
9252 err = get_editor(&editor);
9253 if (err)
9254 goto done;
9256 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9257 logmsg_len, 0);
9258 if (err) {
9259 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9260 goto done;
9261 err = NULL;
9262 hle->logmsg = strdup(new_msg);
9263 if (hle->logmsg == NULL)
9264 err = got_error_from_errno("strdup");
9266 done:
9267 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9268 err = got_error_from_errno2("unlink", logmsg_path);
9269 free(logmsg_path);
9270 free(logmsg);
9271 free(orig_logmsg);
9272 free(editor);
9273 if (commit)
9274 got_object_commit_close(commit);
9275 return err;
9278 static const struct got_error *
9279 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9280 FILE *f, struct got_repository *repo)
9282 const struct got_error *err = NULL;
9283 char *line = NULL, *p, *end;
9284 size_t i, size;
9285 ssize_t len;
9286 int lineno = 0;
9287 const struct got_histedit_cmd *cmd;
9288 struct got_object_id *commit_id = NULL;
9289 struct got_histedit_list_entry *hle = NULL;
9291 for (;;) {
9292 len = getline(&line, &size, f);
9293 if (len == -1) {
9294 const struct got_error *getline_err;
9295 if (feof(f))
9296 break;
9297 getline_err = got_error_from_errno("getline");
9298 err = got_ferror(f, getline_err->code);
9299 break;
9301 lineno++;
9302 p = line;
9303 while (isspace((unsigned char)p[0]))
9304 p++;
9305 if (p[0] == '#' || p[0] == '\0') {
9306 free(line);
9307 line = NULL;
9308 continue;
9310 cmd = NULL;
9311 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9312 cmd = &got_histedit_cmds[i];
9313 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9314 isspace((unsigned char)p[strlen(cmd->name)])) {
9315 p += strlen(cmd->name);
9316 break;
9318 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9319 p++;
9320 break;
9323 if (i == nitems(got_histedit_cmds)) {
9324 err = histedit_syntax_error(lineno);
9325 break;
9327 while (isspace((unsigned char)p[0]))
9328 p++;
9329 if (cmd->code == GOT_HISTEDIT_MESG) {
9330 if (hle == NULL || hle->logmsg != NULL) {
9331 err = got_error(GOT_ERR_HISTEDIT_CMD);
9332 break;
9334 if (p[0] == '\0') {
9335 err = histedit_edit_logmsg(hle, repo);
9336 if (err)
9337 break;
9338 } else {
9339 hle->logmsg = strdup(p);
9340 if (hle->logmsg == NULL) {
9341 err = got_error_from_errno("strdup");
9342 break;
9345 free(line);
9346 line = NULL;
9347 continue;
9348 } else {
9349 end = p;
9350 while (end[0] && !isspace((unsigned char)end[0]))
9351 end++;
9352 *end = '\0';
9354 err = got_object_resolve_id_str(&commit_id, repo, p);
9355 if (err) {
9356 /* override error code */
9357 err = histedit_syntax_error(lineno);
9358 break;
9361 hle = malloc(sizeof(*hle));
9362 if (hle == NULL) {
9363 err = got_error_from_errno("malloc");
9364 break;
9366 hle->cmd = cmd;
9367 hle->commit_id = commit_id;
9368 hle->logmsg = NULL;
9369 commit_id = NULL;
9370 free(line);
9371 line = NULL;
9372 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9375 free(line);
9376 free(commit_id);
9377 return err;
9380 static const struct got_error *
9381 histedit_check_script(struct got_histedit_list *histedit_cmds,
9382 struct got_object_id_queue *commits, struct got_repository *repo)
9384 const struct got_error *err = NULL;
9385 struct got_object_qid *qid;
9386 struct got_histedit_list_entry *hle;
9387 static char msg[92];
9388 char *id_str;
9390 if (TAILQ_EMPTY(histedit_cmds))
9391 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9392 "histedit script contains no commands");
9393 if (STAILQ_EMPTY(commits))
9394 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9396 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9397 struct got_histedit_list_entry *hle2;
9398 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9399 if (hle == hle2)
9400 continue;
9401 if (got_object_id_cmp(hle->commit_id,
9402 hle2->commit_id) != 0)
9403 continue;
9404 err = got_object_id_str(&id_str, hle->commit_id);
9405 if (err)
9406 return err;
9407 snprintf(msg, sizeof(msg), "commit %s is listed "
9408 "more than once in histedit script", id_str);
9409 free(id_str);
9410 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9414 STAILQ_FOREACH(qid, commits, entry) {
9415 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9416 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9417 break;
9419 if (hle == NULL) {
9420 err = got_object_id_str(&id_str, qid->id);
9421 if (err)
9422 return err;
9423 snprintf(msg, sizeof(msg),
9424 "commit %s missing from histedit script", id_str);
9425 free(id_str);
9426 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9430 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9431 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9432 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9433 "last commit in histedit script cannot be folded");
9435 return NULL;
9438 static const struct got_error *
9439 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9440 const char *path, struct got_object_id_queue *commits,
9441 struct got_repository *repo)
9443 const struct got_error *err = NULL;
9444 char *editor;
9445 FILE *f = NULL;
9447 err = get_editor(&editor);
9448 if (err)
9449 return err;
9451 if (spawn_editor(editor, path) == -1) {
9452 err = got_error_from_errno("failed spawning editor");
9453 goto done;
9456 f = fopen(path, "r");
9457 if (f == NULL) {
9458 err = got_error_from_errno("fopen");
9459 goto done;
9461 err = histedit_parse_list(histedit_cmds, f, repo);
9462 if (err)
9463 goto done;
9465 err = histedit_check_script(histedit_cmds, commits, repo);
9466 done:
9467 if (f && fclose(f) == EOF && err == NULL)
9468 err = got_error_from_errno("fclose");
9469 free(editor);
9470 return err;
9473 static const struct got_error *
9474 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9475 struct got_object_id_queue *, const char *, const char *,
9476 struct got_repository *);
9478 static const struct got_error *
9479 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9480 struct got_object_id_queue *commits, const char *branch_name,
9481 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9483 const struct got_error *err;
9484 FILE *f = NULL;
9485 char *path = NULL;
9487 err = got_opentemp_named(&path, &f, "got-histedit");
9488 if (err)
9489 return err;
9491 err = write_cmd_list(f, branch_name, commits);
9492 if (err)
9493 goto done;
9495 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9496 fold_only, repo);
9497 if (err)
9498 goto done;
9500 if (edit_logmsg_only || fold_only) {
9501 rewind(f);
9502 err = histedit_parse_list(histedit_cmds, f, repo);
9503 } else {
9504 if (fclose(f) == EOF) {
9505 err = got_error_from_errno("fclose");
9506 goto done;
9508 f = NULL;
9509 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9510 if (err) {
9511 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9512 err->code != GOT_ERR_HISTEDIT_CMD)
9513 goto done;
9514 err = histedit_edit_list_retry(histedit_cmds, err,
9515 commits, path, branch_name, repo);
9518 done:
9519 if (f && fclose(f) == EOF && err == NULL)
9520 err = got_error_from_errno("fclose");
9521 if (path && unlink(path) != 0 && err == NULL)
9522 err = got_error_from_errno2("unlink", path);
9523 free(path);
9524 return err;
9527 static const struct got_error *
9528 histedit_save_list(struct got_histedit_list *histedit_cmds,
9529 struct got_worktree *worktree, struct got_repository *repo)
9531 const struct got_error *err = NULL;
9532 char *path = NULL;
9533 FILE *f = NULL;
9534 struct got_histedit_list_entry *hle;
9535 struct got_commit_object *commit = NULL;
9537 err = got_worktree_get_histedit_script_path(&path, worktree);
9538 if (err)
9539 return err;
9541 f = fopen(path, "w");
9542 if (f == NULL) {
9543 err = got_error_from_errno2("fopen", path);
9544 goto done;
9546 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9547 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9548 repo);
9549 if (err)
9550 break;
9552 if (hle->logmsg) {
9553 int n = fprintf(f, "%c %s\n",
9554 GOT_HISTEDIT_MESG, hle->logmsg);
9555 if (n < 0) {
9556 err = got_ferror(f, GOT_ERR_IO);
9557 break;
9561 done:
9562 if (f && fclose(f) == EOF && err == NULL)
9563 err = got_error_from_errno("fclose");
9564 free(path);
9565 if (commit)
9566 got_object_commit_close(commit);
9567 return err;
9570 void
9571 histedit_free_list(struct got_histedit_list *histedit_cmds)
9573 struct got_histedit_list_entry *hle;
9575 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9576 TAILQ_REMOVE(histedit_cmds, hle, entry);
9577 free(hle);
9581 static const struct got_error *
9582 histedit_load_list(struct got_histedit_list *histedit_cmds,
9583 const char *path, struct got_repository *repo)
9585 const struct got_error *err = NULL;
9586 FILE *f = NULL;
9588 f = fopen(path, "r");
9589 if (f == NULL) {
9590 err = got_error_from_errno2("fopen", path);
9591 goto done;
9594 err = histedit_parse_list(histedit_cmds, f, repo);
9595 done:
9596 if (f && fclose(f) == EOF && err == NULL)
9597 err = got_error_from_errno("fclose");
9598 return err;
9601 static const struct got_error *
9602 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9603 const struct got_error *edit_err, struct got_object_id_queue *commits,
9604 const char *path, const char *branch_name, struct got_repository *repo)
9606 const struct got_error *err = NULL, *prev_err = edit_err;
9607 int resp = ' ';
9609 while (resp != 'c' && resp != 'r' && resp != 'a') {
9610 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9611 "or (a)bort: ", getprogname(), prev_err->msg);
9612 resp = getchar();
9613 if (resp == '\n')
9614 resp = getchar();
9615 if (resp == 'c') {
9616 histedit_free_list(histedit_cmds);
9617 err = histedit_run_editor(histedit_cmds, path, commits,
9618 repo);
9619 if (err) {
9620 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9621 err->code != GOT_ERR_HISTEDIT_CMD)
9622 break;
9623 prev_err = err;
9624 resp = ' ';
9625 continue;
9627 break;
9628 } else if (resp == 'r') {
9629 histedit_free_list(histedit_cmds);
9630 err = histedit_edit_script(histedit_cmds,
9631 commits, branch_name, 0, 0, repo);
9632 if (err) {
9633 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9634 err->code != GOT_ERR_HISTEDIT_CMD)
9635 break;
9636 prev_err = err;
9637 resp = ' ';
9638 continue;
9640 break;
9641 } else if (resp == 'a') {
9642 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9643 break;
9644 } else
9645 printf("invalid response '%c'\n", resp);
9648 return err;
9651 static const struct got_error *
9652 histedit_complete(struct got_worktree *worktree,
9653 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9654 struct got_reference *branch, struct got_repository *repo)
9656 printf("Switching work tree to %s\n",
9657 got_ref_get_symref_target(branch));
9658 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9659 branch, repo);
9662 static const struct got_error *
9663 show_histedit_progress(struct got_commit_object *commit,
9664 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9666 const struct got_error *err;
9667 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9669 err = got_object_id_str(&old_id_str, hle->commit_id);
9670 if (err)
9671 goto done;
9673 if (new_id) {
9674 err = got_object_id_str(&new_id_str, new_id);
9675 if (err)
9676 goto done;
9679 old_id_str[12] = '\0';
9680 if (new_id_str)
9681 new_id_str[12] = '\0';
9683 if (hle->logmsg) {
9684 logmsg = strdup(hle->logmsg);
9685 if (logmsg == NULL) {
9686 err = got_error_from_errno("strdup");
9687 goto done;
9689 trim_logmsg(logmsg, 42);
9690 } else {
9691 err = get_short_logmsg(&logmsg, 42, commit);
9692 if (err)
9693 goto done;
9696 switch (hle->cmd->code) {
9697 case GOT_HISTEDIT_PICK:
9698 case GOT_HISTEDIT_EDIT:
9699 printf("%s -> %s: %s\n", old_id_str,
9700 new_id_str ? new_id_str : "no-op change", logmsg);
9701 break;
9702 case GOT_HISTEDIT_DROP:
9703 case GOT_HISTEDIT_FOLD:
9704 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9705 logmsg);
9706 break;
9707 default:
9708 break;
9710 done:
9711 free(old_id_str);
9712 free(new_id_str);
9713 return err;
9716 static const struct got_error *
9717 histedit_commit(struct got_pathlist_head *merged_paths,
9718 struct got_worktree *worktree, struct got_fileindex *fileindex,
9719 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9720 struct got_repository *repo)
9722 const struct got_error *err;
9723 struct got_commit_object *commit;
9724 struct got_object_id *new_commit_id;
9726 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9727 && hle->logmsg == NULL) {
9728 err = histedit_edit_logmsg(hle, repo);
9729 if (err)
9730 return err;
9733 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9734 if (err)
9735 return err;
9737 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9738 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9739 hle->logmsg, repo);
9740 if (err) {
9741 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9742 goto done;
9743 err = show_histedit_progress(commit, hle, NULL);
9744 } else {
9745 err = show_histedit_progress(commit, hle, new_commit_id);
9746 free(new_commit_id);
9748 done:
9749 got_object_commit_close(commit);
9750 return err;
9753 static const struct got_error *
9754 histedit_skip_commit(struct got_histedit_list_entry *hle,
9755 struct got_worktree *worktree, struct got_repository *repo)
9757 const struct got_error *error;
9758 struct got_commit_object *commit;
9760 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9761 repo);
9762 if (error)
9763 return error;
9765 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9766 if (error)
9767 return error;
9769 error = show_histedit_progress(commit, hle, NULL);
9770 got_object_commit_close(commit);
9771 return error;
9774 static const struct got_error *
9775 check_local_changes(void *arg, unsigned char status,
9776 unsigned char staged_status, const char *path,
9777 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9778 struct got_object_id *commit_id, int dirfd, const char *de_name)
9780 int *have_local_changes = arg;
9782 switch (status) {
9783 case GOT_STATUS_ADD:
9784 case GOT_STATUS_DELETE:
9785 case GOT_STATUS_MODIFY:
9786 case GOT_STATUS_CONFLICT:
9787 *have_local_changes = 1;
9788 return got_error(GOT_ERR_CANCELLED);
9789 default:
9790 break;
9793 switch (staged_status) {
9794 case GOT_STATUS_ADD:
9795 case GOT_STATUS_DELETE:
9796 case GOT_STATUS_MODIFY:
9797 *have_local_changes = 1;
9798 return got_error(GOT_ERR_CANCELLED);
9799 default:
9800 break;
9803 return NULL;
9806 static const struct got_error *
9807 cmd_histedit(int argc, char *argv[])
9809 const struct got_error *error = NULL;
9810 struct got_worktree *worktree = NULL;
9811 struct got_fileindex *fileindex = NULL;
9812 struct got_repository *repo = NULL;
9813 char *cwd = NULL;
9814 struct got_reference *branch = NULL;
9815 struct got_reference *tmp_branch = NULL;
9816 struct got_object_id *resume_commit_id = NULL;
9817 struct got_object_id *base_commit_id = NULL;
9818 struct got_object_id *head_commit_id = NULL;
9819 struct got_commit_object *commit = NULL;
9820 int ch, rebase_in_progress = 0;
9821 struct got_update_progress_arg upa;
9822 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9823 int edit_logmsg_only = 0, fold_only = 0;
9824 int list_backups = 0, delete_backups = 0;
9825 const char *edit_script_path = NULL;
9826 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9827 struct got_object_id_queue commits;
9828 struct got_pathlist_head merged_paths;
9829 const struct got_object_id_queue *parent_ids;
9830 struct got_object_qid *pid;
9831 struct got_histedit_list histedit_cmds;
9832 struct got_histedit_list_entry *hle;
9834 STAILQ_INIT(&commits);
9835 TAILQ_INIT(&histedit_cmds);
9836 TAILQ_INIT(&merged_paths);
9837 memset(&upa, 0, sizeof(upa));
9839 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9840 switch (ch) {
9841 case 'a':
9842 abort_edit = 1;
9843 break;
9844 case 'c':
9845 continue_edit = 1;
9846 break;
9847 case 'f':
9848 fold_only = 1;
9849 break;
9850 case 'F':
9851 edit_script_path = optarg;
9852 break;
9853 case 'm':
9854 edit_logmsg_only = 1;
9855 break;
9856 case 'l':
9857 list_backups = 1;
9858 break;
9859 case 'X':
9860 delete_backups = 1;
9861 break;
9862 default:
9863 usage_histedit();
9864 /* NOTREACHED */
9868 argc -= optind;
9869 argv += optind;
9871 #ifndef PROFILE
9872 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9873 "unveil", NULL) == -1)
9874 err(1, "pledge");
9875 #endif
9876 if (abort_edit && continue_edit)
9877 option_conflict('a', 'c');
9878 if (edit_script_path && edit_logmsg_only)
9879 option_conflict('F', 'm');
9880 if (abort_edit && edit_logmsg_only)
9881 option_conflict('a', 'm');
9882 if (continue_edit && edit_logmsg_only)
9883 option_conflict('c', 'm');
9884 if (abort_edit && fold_only)
9885 option_conflict('a', 'f');
9886 if (continue_edit && fold_only)
9887 option_conflict('c', 'f');
9888 if (fold_only && edit_logmsg_only)
9889 option_conflict('f', 'm');
9890 if (edit_script_path && fold_only)
9891 option_conflict('F', 'f');
9892 if (list_backups) {
9893 if (abort_edit)
9894 option_conflict('l', 'a');
9895 if (continue_edit)
9896 option_conflict('l', 'c');
9897 if (edit_script_path)
9898 option_conflict('l', 'F');
9899 if (edit_logmsg_only)
9900 option_conflict('l', 'm');
9901 if (fold_only)
9902 option_conflict('l', 'f');
9903 if (delete_backups)
9904 option_conflict('l', 'X');
9905 if (argc != 0 && argc != 1)
9906 usage_histedit();
9907 } else if (delete_backups) {
9908 if (abort_edit)
9909 option_conflict('X', 'a');
9910 if (continue_edit)
9911 option_conflict('X', 'c');
9912 if (edit_script_path)
9913 option_conflict('X', 'F');
9914 if (edit_logmsg_only)
9915 option_conflict('X', 'm');
9916 if (fold_only)
9917 option_conflict('X', 'f');
9918 if (list_backups)
9919 option_conflict('X', 'l');
9920 if (argc != 0 && argc != 1)
9921 usage_histedit();
9922 } else if (argc != 0)
9923 usage_histedit();
9926 * This command cannot apply unveil(2) in all cases because the
9927 * user may choose to run an editor to edit the histedit script
9928 * and to edit individual commit log messages.
9929 * unveil(2) traverses exec(2); if an editor is used we have to
9930 * apply unveil after edit script and log messages have been written.
9931 * XXX TODO: Make use of unveil(2) where possible.
9934 cwd = getcwd(NULL, 0);
9935 if (cwd == NULL) {
9936 error = got_error_from_errno("getcwd");
9937 goto done;
9939 error = got_worktree_open(&worktree, cwd);
9940 if (error) {
9941 if (list_backups || delete_backups) {
9942 if (error->code != GOT_ERR_NOT_WORKTREE)
9943 goto done;
9944 } else {
9945 if (error->code == GOT_ERR_NOT_WORKTREE)
9946 error = wrap_not_worktree_error(error,
9947 "histedit", cwd);
9948 goto done;
9952 if (list_backups || delete_backups) {
9953 error = got_repo_open(&repo,
9954 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9955 NULL);
9956 if (error != NULL)
9957 goto done;
9958 error = apply_unveil(got_repo_get_path(repo), 0,
9959 worktree ? got_worktree_get_root_path(worktree) : NULL);
9960 if (error)
9961 goto done;
9962 error = process_backup_refs(
9963 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9964 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9965 goto done; /* nothing else to do */
9968 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9969 NULL);
9970 if (error != NULL)
9971 goto done;
9973 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9974 if (error)
9975 goto done;
9976 if (rebase_in_progress) {
9977 error = got_error(GOT_ERR_REBASING);
9978 goto done;
9981 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9982 if (error)
9983 goto done;
9985 if (edit_in_progress && edit_logmsg_only) {
9986 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9987 "histedit operation is in progress in this "
9988 "work tree and must be continued or aborted "
9989 "before the -m option can be used");
9990 goto done;
9992 if (edit_in_progress && fold_only) {
9993 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9994 "histedit operation is in progress in this "
9995 "work tree and must be continued or aborted "
9996 "before the -f option can be used");
9997 goto done;
10000 if (edit_in_progress && abort_edit) {
10001 error = got_worktree_histedit_continue(&resume_commit_id,
10002 &tmp_branch, &branch, &base_commit_id, &fileindex,
10003 worktree, repo);
10004 if (error)
10005 goto done;
10006 printf("Switching work tree to %s\n",
10007 got_ref_get_symref_target(branch));
10008 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10009 branch, base_commit_id, update_progress, &upa);
10010 if (error)
10011 goto done;
10012 printf("Histedit of %s aborted\n",
10013 got_ref_get_symref_target(branch));
10014 print_update_progress_stats(&upa);
10015 goto done; /* nothing else to do */
10016 } else if (abort_edit) {
10017 error = got_error(GOT_ERR_NOT_HISTEDIT);
10018 goto done;
10021 if (continue_edit) {
10022 char *path;
10024 if (!edit_in_progress) {
10025 error = got_error(GOT_ERR_NOT_HISTEDIT);
10026 goto done;
10029 error = got_worktree_get_histedit_script_path(&path, worktree);
10030 if (error)
10031 goto done;
10033 error = histedit_load_list(&histedit_cmds, path, repo);
10034 free(path);
10035 if (error)
10036 goto done;
10038 error = got_worktree_histedit_continue(&resume_commit_id,
10039 &tmp_branch, &branch, &base_commit_id, &fileindex,
10040 worktree, repo);
10041 if (error)
10042 goto done;
10044 error = got_ref_resolve(&head_commit_id, repo, branch);
10045 if (error)
10046 goto done;
10048 error = got_object_open_as_commit(&commit, repo,
10049 head_commit_id);
10050 if (error)
10051 goto done;
10052 parent_ids = got_object_commit_get_parent_ids(commit);
10053 pid = STAILQ_FIRST(parent_ids);
10054 if (pid == NULL) {
10055 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10056 goto done;
10058 error = collect_commits(&commits, head_commit_id, pid->id,
10059 base_commit_id, got_worktree_get_path_prefix(worktree),
10060 GOT_ERR_HISTEDIT_PATH, repo);
10061 got_object_commit_close(commit);
10062 commit = NULL;
10063 if (error)
10064 goto done;
10065 } else {
10066 if (edit_in_progress) {
10067 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10068 goto done;
10071 error = got_ref_open(&branch, repo,
10072 got_worktree_get_head_ref_name(worktree), 0);
10073 if (error != NULL)
10074 goto done;
10076 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10077 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10078 "will not edit commit history of a branch outside "
10079 "the \"refs/heads/\" reference namespace");
10080 goto done;
10083 error = got_ref_resolve(&head_commit_id, repo, branch);
10084 got_ref_close(branch);
10085 branch = NULL;
10086 if (error)
10087 goto done;
10089 error = got_object_open_as_commit(&commit, repo,
10090 head_commit_id);
10091 if (error)
10092 goto done;
10093 parent_ids = got_object_commit_get_parent_ids(commit);
10094 pid = STAILQ_FIRST(parent_ids);
10095 if (pid == NULL) {
10096 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10097 goto done;
10099 error = collect_commits(&commits, head_commit_id, pid->id,
10100 got_worktree_get_base_commit_id(worktree),
10101 got_worktree_get_path_prefix(worktree),
10102 GOT_ERR_HISTEDIT_PATH, repo);
10103 got_object_commit_close(commit);
10104 commit = NULL;
10105 if (error)
10106 goto done;
10108 if (STAILQ_EMPTY(&commits)) {
10109 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10110 goto done;
10113 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10114 &base_commit_id, &fileindex, worktree, repo);
10115 if (error)
10116 goto done;
10118 if (edit_script_path) {
10119 error = histedit_load_list(&histedit_cmds,
10120 edit_script_path, repo);
10121 if (error) {
10122 got_worktree_histedit_abort(worktree, fileindex,
10123 repo, branch, base_commit_id,
10124 update_progress, &upa);
10125 print_update_progress_stats(&upa);
10126 goto done;
10128 } else {
10129 const char *branch_name;
10130 branch_name = got_ref_get_symref_target(branch);
10131 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10132 branch_name += 11;
10133 error = histedit_edit_script(&histedit_cmds, &commits,
10134 branch_name, edit_logmsg_only, fold_only, repo);
10135 if (error) {
10136 got_worktree_histedit_abort(worktree, fileindex,
10137 repo, branch, base_commit_id,
10138 update_progress, &upa);
10139 print_update_progress_stats(&upa);
10140 goto done;
10145 error = histedit_save_list(&histedit_cmds, worktree,
10146 repo);
10147 if (error) {
10148 got_worktree_histedit_abort(worktree, fileindex,
10149 repo, branch, base_commit_id,
10150 update_progress, &upa);
10151 print_update_progress_stats(&upa);
10152 goto done;
10157 error = histedit_check_script(&histedit_cmds, &commits, repo);
10158 if (error)
10159 goto done;
10161 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10162 if (resume_commit_id) {
10163 if (got_object_id_cmp(hle->commit_id,
10164 resume_commit_id) != 0)
10165 continue;
10167 resume_commit_id = NULL;
10168 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10169 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10170 error = histedit_skip_commit(hle, worktree,
10171 repo);
10172 if (error)
10173 goto done;
10174 } else {
10175 struct got_pathlist_head paths;
10176 int have_changes = 0;
10178 TAILQ_INIT(&paths);
10179 error = got_pathlist_append(&paths, "", NULL);
10180 if (error)
10181 goto done;
10182 error = got_worktree_status(worktree, &paths,
10183 repo, 0, check_local_changes, &have_changes,
10184 check_cancelled, NULL);
10185 got_pathlist_free(&paths);
10186 if (error) {
10187 if (error->code != GOT_ERR_CANCELLED)
10188 goto done;
10189 if (sigint_received || sigpipe_received)
10190 goto done;
10192 if (have_changes) {
10193 error = histedit_commit(NULL, worktree,
10194 fileindex, tmp_branch, hle, repo);
10195 if (error)
10196 goto done;
10197 } else {
10198 error = got_object_open_as_commit(
10199 &commit, repo, hle->commit_id);
10200 if (error)
10201 goto done;
10202 error = show_histedit_progress(commit,
10203 hle, NULL);
10204 got_object_commit_close(commit);
10205 commit = NULL;
10206 if (error)
10207 goto done;
10210 continue;
10213 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10214 error = histedit_skip_commit(hle, worktree, repo);
10215 if (error)
10216 goto done;
10217 continue;
10220 error = got_object_open_as_commit(&commit, repo,
10221 hle->commit_id);
10222 if (error)
10223 goto done;
10224 parent_ids = got_object_commit_get_parent_ids(commit);
10225 pid = STAILQ_FIRST(parent_ids);
10227 error = got_worktree_histedit_merge_files(&merged_paths,
10228 worktree, fileindex, pid->id, hle->commit_id, repo,
10229 update_progress, &upa, check_cancelled, NULL);
10230 if (error)
10231 goto done;
10232 got_object_commit_close(commit);
10233 commit = NULL;
10235 print_update_progress_stats(&upa);
10236 if (upa.conflicts > 0)
10237 rebase_status = GOT_STATUS_CONFLICT;
10239 if (rebase_status == GOT_STATUS_CONFLICT) {
10240 error = show_rebase_merge_conflict(hle->commit_id,
10241 repo);
10242 if (error)
10243 goto done;
10244 got_worktree_rebase_pathlist_free(&merged_paths);
10245 break;
10248 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10249 char *id_str;
10250 error = got_object_id_str(&id_str, hle->commit_id);
10251 if (error)
10252 goto done;
10253 printf("Stopping histedit for amending commit %s\n",
10254 id_str);
10255 free(id_str);
10256 got_worktree_rebase_pathlist_free(&merged_paths);
10257 error = got_worktree_histedit_postpone(worktree,
10258 fileindex);
10259 goto done;
10262 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10263 error = histedit_skip_commit(hle, worktree, repo);
10264 if (error)
10265 goto done;
10266 continue;
10269 error = histedit_commit(&merged_paths, worktree, fileindex,
10270 tmp_branch, hle, repo);
10271 got_worktree_rebase_pathlist_free(&merged_paths);
10272 if (error)
10273 goto done;
10276 if (rebase_status == GOT_STATUS_CONFLICT) {
10277 error = got_worktree_histedit_postpone(worktree, fileindex);
10278 if (error)
10279 goto done;
10280 error = got_error_msg(GOT_ERR_CONFLICTS,
10281 "conflicts must be resolved before histedit can continue");
10282 } else
10283 error = histedit_complete(worktree, fileindex, tmp_branch,
10284 branch, repo);
10285 done:
10286 got_object_id_queue_free(&commits);
10287 histedit_free_list(&histedit_cmds);
10288 free(head_commit_id);
10289 free(base_commit_id);
10290 free(resume_commit_id);
10291 if (commit)
10292 got_object_commit_close(commit);
10293 if (branch)
10294 got_ref_close(branch);
10295 if (tmp_branch)
10296 got_ref_close(tmp_branch);
10297 if (worktree)
10298 got_worktree_close(worktree);
10299 if (repo) {
10300 const struct got_error *close_err = got_repo_close(repo);
10301 if (error == NULL)
10302 error = close_err;
10304 return error;
10307 __dead static void
10308 usage_integrate(void)
10310 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10311 exit(1);
10314 static const struct got_error *
10315 cmd_integrate(int argc, char *argv[])
10317 const struct got_error *error = NULL;
10318 struct got_repository *repo = NULL;
10319 struct got_worktree *worktree = NULL;
10320 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10321 const char *branch_arg = NULL;
10322 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10323 struct got_fileindex *fileindex = NULL;
10324 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10325 int ch;
10326 struct got_update_progress_arg upa;
10328 while ((ch = getopt(argc, argv, "")) != -1) {
10329 switch (ch) {
10330 default:
10331 usage_integrate();
10332 /* NOTREACHED */
10336 argc -= optind;
10337 argv += optind;
10339 if (argc != 1)
10340 usage_integrate();
10341 branch_arg = argv[0];
10342 #ifndef PROFILE
10343 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10344 "unveil", NULL) == -1)
10345 err(1, "pledge");
10346 #endif
10347 cwd = getcwd(NULL, 0);
10348 if (cwd == NULL) {
10349 error = got_error_from_errno("getcwd");
10350 goto done;
10353 error = got_worktree_open(&worktree, cwd);
10354 if (error) {
10355 if (error->code == GOT_ERR_NOT_WORKTREE)
10356 error = wrap_not_worktree_error(error, "integrate",
10357 cwd);
10358 goto done;
10361 error = check_rebase_or_histedit_in_progress(worktree);
10362 if (error)
10363 goto done;
10365 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10366 NULL);
10367 if (error != NULL)
10368 goto done;
10370 error = apply_unveil(got_repo_get_path(repo), 0,
10371 got_worktree_get_root_path(worktree));
10372 if (error)
10373 goto done;
10375 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10376 error = got_error_from_errno("asprintf");
10377 goto done;
10380 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10381 &base_branch_ref, worktree, refname, repo);
10382 if (error)
10383 goto done;
10385 refname = strdup(got_ref_get_name(branch_ref));
10386 if (refname == NULL) {
10387 error = got_error_from_errno("strdup");
10388 got_worktree_integrate_abort(worktree, fileindex, repo,
10389 branch_ref, base_branch_ref);
10390 goto done;
10392 base_refname = strdup(got_ref_get_name(base_branch_ref));
10393 if (base_refname == NULL) {
10394 error = got_error_from_errno("strdup");
10395 got_worktree_integrate_abort(worktree, fileindex, repo,
10396 branch_ref, base_branch_ref);
10397 goto done;
10400 error = got_ref_resolve(&commit_id, repo, branch_ref);
10401 if (error)
10402 goto done;
10404 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10405 if (error)
10406 goto done;
10408 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10409 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10410 "specified branch has already been integrated");
10411 got_worktree_integrate_abort(worktree, fileindex, repo,
10412 branch_ref, base_branch_ref);
10413 goto done;
10416 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10417 if (error) {
10418 if (error->code == GOT_ERR_ANCESTRY)
10419 error = got_error(GOT_ERR_REBASE_REQUIRED);
10420 got_worktree_integrate_abort(worktree, fileindex, repo,
10421 branch_ref, base_branch_ref);
10422 goto done;
10425 memset(&upa, 0, sizeof(upa));
10426 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10427 branch_ref, base_branch_ref, update_progress, &upa,
10428 check_cancelled, NULL);
10429 if (error)
10430 goto done;
10432 printf("Integrated %s into %s\n", refname, base_refname);
10433 print_update_progress_stats(&upa);
10434 done:
10435 if (repo) {
10436 const struct got_error *close_err = got_repo_close(repo);
10437 if (error == NULL)
10438 error = close_err;
10440 if (worktree)
10441 got_worktree_close(worktree);
10442 free(cwd);
10443 free(base_commit_id);
10444 free(commit_id);
10445 free(refname);
10446 free(base_refname);
10447 return error;
10450 __dead static void
10451 usage_stage(void)
10453 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10454 "[-S] [file-path ...]\n",
10455 getprogname());
10456 exit(1);
10459 static const struct got_error *
10460 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10461 const char *path, struct got_object_id *blob_id,
10462 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10463 int dirfd, const char *de_name)
10465 const struct got_error *err = NULL;
10466 char *id_str = NULL;
10468 if (staged_status != GOT_STATUS_ADD &&
10469 staged_status != GOT_STATUS_MODIFY &&
10470 staged_status != GOT_STATUS_DELETE)
10471 return NULL;
10473 if (staged_status == GOT_STATUS_ADD ||
10474 staged_status == GOT_STATUS_MODIFY)
10475 err = got_object_id_str(&id_str, staged_blob_id);
10476 else
10477 err = got_object_id_str(&id_str, blob_id);
10478 if (err)
10479 return err;
10481 printf("%s %c %s\n", id_str, staged_status, path);
10482 free(id_str);
10483 return NULL;
10486 static const struct got_error *
10487 cmd_stage(int argc, char *argv[])
10489 const struct got_error *error = NULL;
10490 struct got_repository *repo = NULL;
10491 struct got_worktree *worktree = NULL;
10492 char *cwd = NULL;
10493 struct got_pathlist_head paths;
10494 struct got_pathlist_entry *pe;
10495 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10496 FILE *patch_script_file = NULL;
10497 const char *patch_script_path = NULL;
10498 struct choose_patch_arg cpa;
10500 TAILQ_INIT(&paths);
10502 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10503 switch (ch) {
10504 case 'l':
10505 list_stage = 1;
10506 break;
10507 case 'p':
10508 pflag = 1;
10509 break;
10510 case 'F':
10511 patch_script_path = optarg;
10512 break;
10513 case 'S':
10514 allow_bad_symlinks = 1;
10515 break;
10516 default:
10517 usage_stage();
10518 /* NOTREACHED */
10522 argc -= optind;
10523 argv += optind;
10525 #ifndef PROFILE
10526 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10527 "unveil", NULL) == -1)
10528 err(1, "pledge");
10529 #endif
10530 if (list_stage && (pflag || patch_script_path))
10531 errx(1, "-l option cannot be used with other options");
10532 if (patch_script_path && !pflag)
10533 errx(1, "-F option can only be used together with -p option");
10535 cwd = getcwd(NULL, 0);
10536 if (cwd == NULL) {
10537 error = got_error_from_errno("getcwd");
10538 goto done;
10541 error = got_worktree_open(&worktree, cwd);
10542 if (error) {
10543 if (error->code == GOT_ERR_NOT_WORKTREE)
10544 error = wrap_not_worktree_error(error, "stage", cwd);
10545 goto done;
10548 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10549 NULL);
10550 if (error != NULL)
10551 goto done;
10553 if (patch_script_path) {
10554 patch_script_file = fopen(patch_script_path, "r");
10555 if (patch_script_file == NULL) {
10556 error = got_error_from_errno2("fopen",
10557 patch_script_path);
10558 goto done;
10561 error = apply_unveil(got_repo_get_path(repo), 0,
10562 got_worktree_get_root_path(worktree));
10563 if (error)
10564 goto done;
10566 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10567 if (error)
10568 goto done;
10570 if (list_stage)
10571 error = got_worktree_status(worktree, &paths, repo, 0,
10572 print_stage, NULL, check_cancelled, NULL);
10573 else {
10574 cpa.patch_script_file = patch_script_file;
10575 cpa.action = "stage";
10576 error = got_worktree_stage(worktree, &paths,
10577 pflag ? NULL : print_status, NULL,
10578 pflag ? choose_patch : NULL, &cpa,
10579 allow_bad_symlinks, repo);
10581 done:
10582 if (patch_script_file && fclose(patch_script_file) == EOF &&
10583 error == NULL)
10584 error = got_error_from_errno2("fclose", patch_script_path);
10585 if (repo) {
10586 const struct got_error *close_err = got_repo_close(repo);
10587 if (error == NULL)
10588 error = close_err;
10590 if (worktree)
10591 got_worktree_close(worktree);
10592 TAILQ_FOREACH(pe, &paths, entry)
10593 free((char *)pe->path);
10594 got_pathlist_free(&paths);
10595 free(cwd);
10596 return error;
10599 __dead static void
10600 usage_unstage(void)
10602 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10603 "[file-path ...]\n",
10604 getprogname());
10605 exit(1);
10609 static const struct got_error *
10610 cmd_unstage(int argc, char *argv[])
10612 const struct got_error *error = NULL;
10613 struct got_repository *repo = NULL;
10614 struct got_worktree *worktree = NULL;
10615 char *cwd = NULL;
10616 struct got_pathlist_head paths;
10617 struct got_pathlist_entry *pe;
10618 int ch, pflag = 0;
10619 struct got_update_progress_arg upa;
10620 FILE *patch_script_file = NULL;
10621 const char *patch_script_path = NULL;
10622 struct choose_patch_arg cpa;
10624 TAILQ_INIT(&paths);
10626 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10627 switch (ch) {
10628 case 'p':
10629 pflag = 1;
10630 break;
10631 case 'F':
10632 patch_script_path = optarg;
10633 break;
10634 default:
10635 usage_unstage();
10636 /* NOTREACHED */
10640 argc -= optind;
10641 argv += optind;
10643 #ifndef PROFILE
10644 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10645 "unveil", NULL) == -1)
10646 err(1, "pledge");
10647 #endif
10648 if (patch_script_path && !pflag)
10649 errx(1, "-F option can only be used together with -p option");
10651 cwd = getcwd(NULL, 0);
10652 if (cwd == NULL) {
10653 error = got_error_from_errno("getcwd");
10654 goto done;
10657 error = got_worktree_open(&worktree, cwd);
10658 if (error) {
10659 if (error->code == GOT_ERR_NOT_WORKTREE)
10660 error = wrap_not_worktree_error(error, "unstage", cwd);
10661 goto done;
10664 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10665 NULL);
10666 if (error != NULL)
10667 goto done;
10669 if (patch_script_path) {
10670 patch_script_file = fopen(patch_script_path, "r");
10671 if (patch_script_file == NULL) {
10672 error = got_error_from_errno2("fopen",
10673 patch_script_path);
10674 goto done;
10678 error = apply_unveil(got_repo_get_path(repo), 0,
10679 got_worktree_get_root_path(worktree));
10680 if (error)
10681 goto done;
10683 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10684 if (error)
10685 goto done;
10687 cpa.patch_script_file = patch_script_file;
10688 cpa.action = "unstage";
10689 memset(&upa, 0, sizeof(upa));
10690 error = got_worktree_unstage(worktree, &paths, update_progress,
10691 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10692 if (!error)
10693 print_update_progress_stats(&upa);
10694 done:
10695 if (patch_script_file && fclose(patch_script_file) == EOF &&
10696 error == NULL)
10697 error = got_error_from_errno2("fclose", patch_script_path);
10698 if (repo) {
10699 const struct got_error *close_err = got_repo_close(repo);
10700 if (error == NULL)
10701 error = close_err;
10703 if (worktree)
10704 got_worktree_close(worktree);
10705 TAILQ_FOREACH(pe, &paths, entry)
10706 free((char *)pe->path);
10707 got_pathlist_free(&paths);
10708 free(cwd);
10709 return error;
10712 __dead static void
10713 usage_cat(void)
10715 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10716 "arg1 [arg2 ...]\n", getprogname());
10717 exit(1);
10720 static const struct got_error *
10721 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10723 const struct got_error *err;
10724 struct got_blob_object *blob;
10726 err = got_object_open_as_blob(&blob, repo, id, 8192);
10727 if (err)
10728 return err;
10730 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10731 got_object_blob_close(blob);
10732 return err;
10735 static const struct got_error *
10736 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10738 const struct got_error *err;
10739 struct got_tree_object *tree;
10740 int nentries, i;
10742 err = got_object_open_as_tree(&tree, repo, id);
10743 if (err)
10744 return err;
10746 nentries = got_object_tree_get_nentries(tree);
10747 for (i = 0; i < nentries; i++) {
10748 struct got_tree_entry *te;
10749 char *id_str;
10750 if (sigint_received || sigpipe_received)
10751 break;
10752 te = got_object_tree_get_entry(tree, i);
10753 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10754 if (err)
10755 break;
10756 fprintf(outfile, "%s %.7o %s\n", id_str,
10757 got_tree_entry_get_mode(te),
10758 got_tree_entry_get_name(te));
10759 free(id_str);
10762 got_object_tree_close(tree);
10763 return err;
10766 static const struct got_error *
10767 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10769 const struct got_error *err;
10770 struct got_commit_object *commit;
10771 const struct got_object_id_queue *parent_ids;
10772 struct got_object_qid *pid;
10773 char *id_str = NULL;
10774 const char *logmsg = NULL;
10776 err = got_object_open_as_commit(&commit, repo, id);
10777 if (err)
10778 return err;
10780 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10781 if (err)
10782 goto done;
10784 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10785 parent_ids = got_object_commit_get_parent_ids(commit);
10786 fprintf(outfile, "numparents %d\n",
10787 got_object_commit_get_nparents(commit));
10788 STAILQ_FOREACH(pid, parent_ids, entry) {
10789 char *pid_str;
10790 err = got_object_id_str(&pid_str, pid->id);
10791 if (err)
10792 goto done;
10793 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10794 free(pid_str);
10796 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10797 got_object_commit_get_author(commit),
10798 (long long)got_object_commit_get_author_time(commit));
10800 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10801 got_object_commit_get_author(commit),
10802 (long long)got_object_commit_get_committer_time(commit));
10804 logmsg = got_object_commit_get_logmsg_raw(commit);
10805 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10806 fprintf(outfile, "%s", logmsg);
10807 done:
10808 free(id_str);
10809 got_object_commit_close(commit);
10810 return err;
10813 static const struct got_error *
10814 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10816 const struct got_error *err;
10817 struct got_tag_object *tag;
10818 char *id_str = NULL;
10819 const char *tagmsg = NULL;
10821 err = got_object_open_as_tag(&tag, repo, id);
10822 if (err)
10823 return err;
10825 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10826 if (err)
10827 goto done;
10829 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10831 switch (got_object_tag_get_object_type(tag)) {
10832 case GOT_OBJ_TYPE_BLOB:
10833 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10834 GOT_OBJ_LABEL_BLOB);
10835 break;
10836 case GOT_OBJ_TYPE_TREE:
10837 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10838 GOT_OBJ_LABEL_TREE);
10839 break;
10840 case GOT_OBJ_TYPE_COMMIT:
10841 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10842 GOT_OBJ_LABEL_COMMIT);
10843 break;
10844 case GOT_OBJ_TYPE_TAG:
10845 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10846 GOT_OBJ_LABEL_TAG);
10847 break;
10848 default:
10849 break;
10852 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10853 got_object_tag_get_name(tag));
10855 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10856 got_object_tag_get_tagger(tag),
10857 (long long)got_object_tag_get_tagger_time(tag));
10859 tagmsg = got_object_tag_get_message(tag);
10860 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10861 fprintf(outfile, "%s", tagmsg);
10862 done:
10863 free(id_str);
10864 got_object_tag_close(tag);
10865 return err;
10868 static const struct got_error *
10869 cmd_cat(int argc, char *argv[])
10871 const struct got_error *error;
10872 struct got_repository *repo = NULL;
10873 struct got_worktree *worktree = NULL;
10874 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10875 const char *commit_id_str = NULL;
10876 struct got_object_id *id = NULL, *commit_id = NULL;
10877 int ch, obj_type, i, force_path = 0;
10878 struct got_reflist_head refs;
10880 TAILQ_INIT(&refs);
10882 #ifndef PROFILE
10883 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10884 NULL) == -1)
10885 err(1, "pledge");
10886 #endif
10888 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10889 switch (ch) {
10890 case 'c':
10891 commit_id_str = optarg;
10892 break;
10893 case 'r':
10894 repo_path = realpath(optarg, NULL);
10895 if (repo_path == NULL)
10896 return got_error_from_errno2("realpath",
10897 optarg);
10898 got_path_strip_trailing_slashes(repo_path);
10899 break;
10900 case 'P':
10901 force_path = 1;
10902 break;
10903 default:
10904 usage_cat();
10905 /* NOTREACHED */
10909 argc -= optind;
10910 argv += optind;
10912 cwd = getcwd(NULL, 0);
10913 if (cwd == NULL) {
10914 error = got_error_from_errno("getcwd");
10915 goto done;
10917 error = got_worktree_open(&worktree, cwd);
10918 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10919 goto done;
10920 if (worktree) {
10921 if (repo_path == NULL) {
10922 repo_path = strdup(
10923 got_worktree_get_repo_path(worktree));
10924 if (repo_path == NULL) {
10925 error = got_error_from_errno("strdup");
10926 goto done;
10931 if (repo_path == NULL) {
10932 repo_path = getcwd(NULL, 0);
10933 if (repo_path == NULL)
10934 return got_error_from_errno("getcwd");
10937 error = got_repo_open(&repo, repo_path, NULL);
10938 free(repo_path);
10939 if (error != NULL)
10940 goto done;
10942 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10943 if (error)
10944 goto done;
10946 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10947 if (error)
10948 goto done;
10950 if (commit_id_str == NULL)
10951 commit_id_str = GOT_REF_HEAD;
10952 error = got_repo_match_object_id(&commit_id, NULL,
10953 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10954 if (error)
10955 goto done;
10957 for (i = 0; i < argc; i++) {
10958 if (force_path) {
10959 error = got_object_id_by_path(&id, repo, commit_id,
10960 argv[i]);
10961 if (error)
10962 break;
10963 } else {
10964 error = got_repo_match_object_id(&id, &label, argv[i],
10965 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10966 repo);
10967 if (error) {
10968 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10969 error->code != GOT_ERR_NOT_REF)
10970 break;
10971 error = got_object_id_by_path(&id, repo,
10972 commit_id, argv[i]);
10973 if (error)
10974 break;
10978 error = got_object_get_type(&obj_type, repo, id);
10979 if (error)
10980 break;
10982 switch (obj_type) {
10983 case GOT_OBJ_TYPE_BLOB:
10984 error = cat_blob(id, repo, stdout);
10985 break;
10986 case GOT_OBJ_TYPE_TREE:
10987 error = cat_tree(id, repo, stdout);
10988 break;
10989 case GOT_OBJ_TYPE_COMMIT:
10990 error = cat_commit(id, repo, stdout);
10991 break;
10992 case GOT_OBJ_TYPE_TAG:
10993 error = cat_tag(id, repo, stdout);
10994 break;
10995 default:
10996 error = got_error(GOT_ERR_OBJ_TYPE);
10997 break;
10999 if (error)
11000 break;
11001 free(label);
11002 label = NULL;
11003 free(id);
11004 id = NULL;
11006 done:
11007 free(label);
11008 free(id);
11009 free(commit_id);
11010 if (worktree)
11011 got_worktree_close(worktree);
11012 if (repo) {
11013 const struct got_error *close_err = got_repo_close(repo);
11014 if (error == NULL)
11015 error = close_err;
11017 got_ref_list_free(&refs);
11018 return error;
11021 __dead static void
11022 usage_info(void)
11024 fprintf(stderr, "usage: %s info [path ...]\n",
11025 getprogname());
11026 exit(1);
11029 static const struct got_error *
11030 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11031 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11032 struct got_object_id *commit_id)
11034 const struct got_error *err = NULL;
11035 char *id_str = NULL;
11036 char datebuf[128];
11037 struct tm mytm, *tm;
11038 struct got_pathlist_head *paths = arg;
11039 struct got_pathlist_entry *pe;
11042 * Clear error indication from any of the path arguments which
11043 * would cause this file index entry to be displayed.
11045 TAILQ_FOREACH(pe, paths, entry) {
11046 if (got_path_cmp(path, pe->path, strlen(path),
11047 pe->path_len) == 0 ||
11048 got_path_is_child(path, pe->path, pe->path_len))
11049 pe->data = NULL; /* no error */
11052 printf(GOT_COMMIT_SEP_STR);
11053 if (S_ISLNK(mode))
11054 printf("symlink: %s\n", path);
11055 else if (S_ISREG(mode)) {
11056 printf("file: %s\n", path);
11057 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11058 } else if (S_ISDIR(mode))
11059 printf("directory: %s\n", path);
11060 else
11061 printf("something: %s\n", path);
11063 tm = localtime_r(&mtime, &mytm);
11064 if (tm == NULL)
11065 return NULL;
11066 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11067 return got_error(GOT_ERR_NO_SPACE);
11068 printf("timestamp: %s\n", datebuf);
11070 if (blob_id) {
11071 err = got_object_id_str(&id_str, blob_id);
11072 if (err)
11073 return err;
11074 printf("based on blob: %s\n", id_str);
11075 free(id_str);
11078 if (staged_blob_id) {
11079 err = got_object_id_str(&id_str, staged_blob_id);
11080 if (err)
11081 return err;
11082 printf("based on staged blob: %s\n", id_str);
11083 free(id_str);
11086 if (commit_id) {
11087 err = got_object_id_str(&id_str, commit_id);
11088 if (err)
11089 return err;
11090 printf("based on commit: %s\n", id_str);
11091 free(id_str);
11094 return NULL;
11097 static const struct got_error *
11098 cmd_info(int argc, char *argv[])
11100 const struct got_error *error = NULL;
11101 struct got_worktree *worktree = NULL;
11102 char *cwd = NULL, *id_str = NULL;
11103 struct got_pathlist_head paths;
11104 struct got_pathlist_entry *pe;
11105 char *uuidstr = NULL;
11106 int ch, show_files = 0;
11108 TAILQ_INIT(&paths);
11110 while ((ch = getopt(argc, argv, "")) != -1) {
11111 switch (ch) {
11112 default:
11113 usage_info();
11114 /* NOTREACHED */
11118 argc -= optind;
11119 argv += optind;
11121 #ifndef PROFILE
11122 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11123 NULL) == -1)
11124 err(1, "pledge");
11125 #endif
11126 cwd = getcwd(NULL, 0);
11127 if (cwd == NULL) {
11128 error = got_error_from_errno("getcwd");
11129 goto done;
11132 error = got_worktree_open(&worktree, cwd);
11133 if (error) {
11134 if (error->code == GOT_ERR_NOT_WORKTREE)
11135 error = wrap_not_worktree_error(error, "info", cwd);
11136 goto done;
11139 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11140 if (error)
11141 goto done;
11143 if (argc >= 1) {
11144 error = get_worktree_paths_from_argv(&paths, argc, argv,
11145 worktree);
11146 if (error)
11147 goto done;
11148 show_files = 1;
11151 error = got_object_id_str(&id_str,
11152 got_worktree_get_base_commit_id(worktree));
11153 if (error)
11154 goto done;
11156 error = got_worktree_get_uuid(&uuidstr, worktree);
11157 if (error)
11158 goto done;
11160 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11161 printf("work tree base commit: %s\n", id_str);
11162 printf("work tree path prefix: %s\n",
11163 got_worktree_get_path_prefix(worktree));
11164 printf("work tree branch reference: %s\n",
11165 got_worktree_get_head_ref_name(worktree));
11166 printf("work tree UUID: %s\n", uuidstr);
11167 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11169 if (show_files) {
11170 struct got_pathlist_entry *pe;
11171 TAILQ_FOREACH(pe, &paths, entry) {
11172 if (pe->path_len == 0)
11173 continue;
11175 * Assume this path will fail. This will be corrected
11176 * in print_path_info() in case the path does suceeed.
11178 pe->data = (void *)got_error_path(pe->path,
11179 GOT_ERR_BAD_PATH);
11181 error = got_worktree_path_info(worktree, &paths,
11182 print_path_info, &paths, check_cancelled, NULL);
11183 if (error)
11184 goto done;
11185 TAILQ_FOREACH(pe, &paths, entry) {
11186 if (pe->data != NULL) {
11187 error = pe->data; /* bad path */
11188 break;
11192 done:
11193 TAILQ_FOREACH(pe, &paths, entry)
11194 free((char *)pe->path);
11195 got_pathlist_free(&paths);
11196 free(cwd);
11197 free(id_str);
11198 free(uuidstr);
11199 return error;