Blob


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