Blob


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