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->nbranches; i++) {
2374 got_pathlist_append(&wanted_branches,
2375 remote->branches[i], NULL);
2378 if (TAILQ_EMPTY(&wanted_refs)) {
2379 for (i = 0; i < remote->nrefs; i++) {
2380 got_pathlist_append(&wanted_refs,
2381 remote->refs[i], NULL);
2385 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2386 &repo_name, remote->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 (localtime_r(&committer_time, &tm) == NULL)
4663 return got_error_from_errno("localtime_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;
5737 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5738 return got_error_from_errno("asprintf");
5740 err = got_ref_open(&ref, repo, refname, 0);
5741 if (err)
5742 goto done;
5744 if (worktree &&
5745 strcmp(got_worktree_get_head_ref_name(worktree),
5746 got_ref_get_name(ref)) == 0) {
5747 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5748 "will not delete this work tree's current branch");
5749 goto done;
5752 err = got_ref_delete(ref, repo);
5753 done:
5754 if (ref)
5755 got_ref_close(ref);
5756 free(refname);
5757 return err;
5760 static const struct got_error *
5761 add_branch(struct got_repository *repo, const char *branch_name,
5762 struct got_object_id *base_commit_id)
5764 const struct got_error *err = NULL;
5765 struct got_reference *ref = NULL;
5766 char *base_refname = NULL, *refname = NULL;
5769 * Don't let the user create a branch name with a leading '-'.
5770 * While technically a valid reference name, this case is usually
5771 * an unintended typo.
5773 if (branch_name[0] == '-')
5774 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5776 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5777 err = got_error_from_errno("asprintf");
5778 goto done;
5781 err = got_ref_open(&ref, repo, refname, 0);
5782 if (err == NULL) {
5783 err = got_error(GOT_ERR_BRANCH_EXISTS);
5784 goto done;
5785 } else if (err->code != GOT_ERR_NOT_REF)
5786 goto done;
5788 err = got_ref_alloc(&ref, refname, base_commit_id);
5789 if (err)
5790 goto done;
5792 err = got_ref_write(ref, repo);
5793 done:
5794 if (ref)
5795 got_ref_close(ref);
5796 free(base_refname);
5797 free(refname);
5798 return err;
5801 static const struct got_error *
5802 cmd_branch(int argc, char *argv[])
5804 const struct got_error *error = NULL;
5805 struct got_repository *repo = NULL;
5806 struct got_worktree *worktree = NULL;
5807 char *cwd = NULL, *repo_path = NULL;
5808 int ch, do_list = 0, do_show = 0, do_update = 1;
5809 const char *delref = NULL, *commit_id_arg = NULL;
5810 struct got_reference *ref = NULL;
5811 struct got_pathlist_head paths;
5812 struct got_pathlist_entry *pe;
5813 struct got_object_id *commit_id = NULL;
5814 char *commit_id_str = NULL;
5816 TAILQ_INIT(&paths);
5818 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5819 switch (ch) {
5820 case 'c':
5821 commit_id_arg = optarg;
5822 break;
5823 case 'd':
5824 delref = optarg;
5825 break;
5826 case 'r':
5827 repo_path = realpath(optarg, NULL);
5828 if (repo_path == NULL)
5829 return got_error_from_errno2("realpath",
5830 optarg);
5831 got_path_strip_trailing_slashes(repo_path);
5832 break;
5833 case 'l':
5834 do_list = 1;
5835 break;
5836 case 'n':
5837 do_update = 0;
5838 break;
5839 default:
5840 usage_branch();
5841 /* NOTREACHED */
5845 if (do_list && delref)
5846 option_conflict('l', 'd');
5848 argc -= optind;
5849 argv += optind;
5851 if (!do_list && !delref && argc == 0)
5852 do_show = 1;
5854 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5855 errx(1, "-c option can only be used when creating a branch");
5857 if (do_list || delref) {
5858 if (argc > 0)
5859 usage_branch();
5860 } else if (!do_show && argc != 1)
5861 usage_branch();
5863 #ifndef PROFILE
5864 if (do_list || do_show) {
5865 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5866 NULL) == -1)
5867 err(1, "pledge");
5868 } else {
5869 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5870 "sendfd unveil", NULL) == -1)
5871 err(1, "pledge");
5873 #endif
5874 cwd = getcwd(NULL, 0);
5875 if (cwd == NULL) {
5876 error = got_error_from_errno("getcwd");
5877 goto done;
5880 if (repo_path == NULL) {
5881 error = got_worktree_open(&worktree, cwd);
5882 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5883 goto done;
5884 else
5885 error = NULL;
5886 if (worktree) {
5887 repo_path =
5888 strdup(got_worktree_get_repo_path(worktree));
5889 if (repo_path == NULL)
5890 error = got_error_from_errno("strdup");
5891 if (error)
5892 goto done;
5893 } else {
5894 repo_path = strdup(cwd);
5895 if (repo_path == NULL) {
5896 error = got_error_from_errno("strdup");
5897 goto done;
5902 error = got_repo_open(&repo, repo_path, NULL);
5903 if (error != NULL)
5904 goto done;
5906 error = apply_unveil(got_repo_get_path(repo), do_list,
5907 worktree ? got_worktree_get_root_path(worktree) : NULL);
5908 if (error)
5909 goto done;
5911 if (do_show)
5912 error = show_current_branch(repo, worktree);
5913 else if (do_list)
5914 error = list_branches(repo, worktree);
5915 else if (delref)
5916 error = delete_branch(repo, worktree, delref);
5917 else {
5918 struct got_reflist_head refs;
5919 TAILQ_INIT(&refs);
5920 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5921 NULL);
5922 if (error)
5923 goto done;
5924 if (commit_id_arg == NULL)
5925 commit_id_arg = worktree ?
5926 got_worktree_get_head_ref_name(worktree) :
5927 GOT_REF_HEAD;
5928 error = got_repo_match_object_id(&commit_id, NULL,
5929 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5930 got_ref_list_free(&refs);
5931 if (error)
5932 goto done;
5933 error = add_branch(repo, argv[0], commit_id);
5934 if (error)
5935 goto done;
5936 if (worktree && do_update) {
5937 struct got_update_progress_arg upa;
5938 char *branch_refname = NULL;
5940 error = got_object_id_str(&commit_id_str, commit_id);
5941 if (error)
5942 goto done;
5943 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5944 worktree);
5945 if (error)
5946 goto done;
5947 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5948 == -1) {
5949 error = got_error_from_errno("asprintf");
5950 goto done;
5952 error = got_ref_open(&ref, repo, branch_refname, 0);
5953 free(branch_refname);
5954 if (error)
5955 goto done;
5956 error = switch_head_ref(ref, commit_id, worktree,
5957 repo);
5958 if (error)
5959 goto done;
5960 error = got_worktree_set_base_commit_id(worktree, repo,
5961 commit_id);
5962 if (error)
5963 goto done;
5964 memset(&upa, 0, sizeof(upa));
5965 error = got_worktree_checkout_files(worktree, &paths,
5966 repo, update_progress, &upa, check_cancelled,
5967 NULL);
5968 if (error)
5969 goto done;
5970 if (upa.did_something)
5971 printf("Updated to commit %s\n", commit_id_str);
5972 print_update_progress_stats(&upa);
5975 done:
5976 if (ref)
5977 got_ref_close(ref);
5978 if (repo) {
5979 const struct got_error *close_err = got_repo_close(repo);
5980 if (error == NULL)
5981 error = close_err;
5983 if (worktree)
5984 got_worktree_close(worktree);
5985 free(cwd);
5986 free(repo_path);
5987 free(commit_id);
5988 free(commit_id_str);
5989 TAILQ_FOREACH(pe, &paths, entry)
5990 free((char *)pe->path);
5991 got_pathlist_free(&paths);
5992 return error;
5996 __dead static void
5997 usage_tag(void)
5999 fprintf(stderr,
6000 "usage: %s tag [-c commit] [-r repository] [-l] "
6001 "[-m message] name\n", getprogname());
6002 exit(1);
6005 #if 0
6006 static const struct got_error *
6007 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6009 const struct got_error *err = NULL;
6010 struct got_reflist_entry *re, *se, *new;
6011 struct got_object_id *re_id, *se_id;
6012 struct got_tag_object *re_tag, *se_tag;
6013 time_t re_time, se_time;
6015 STAILQ_FOREACH(re, tags, entry) {
6016 se = STAILQ_FIRST(sorted);
6017 if (se == NULL) {
6018 err = got_reflist_entry_dup(&new, re);
6019 if (err)
6020 return err;
6021 STAILQ_INSERT_HEAD(sorted, new, entry);
6022 continue;
6023 } else {
6024 err = got_ref_resolve(&re_id, repo, re->ref);
6025 if (err)
6026 break;
6027 err = got_object_open_as_tag(&re_tag, repo, re_id);
6028 free(re_id);
6029 if (err)
6030 break;
6031 re_time = got_object_tag_get_tagger_time(re_tag);
6032 got_object_tag_close(re_tag);
6035 while (se) {
6036 err = got_ref_resolve(&se_id, repo, re->ref);
6037 if (err)
6038 break;
6039 err = got_object_open_as_tag(&se_tag, repo, se_id);
6040 free(se_id);
6041 if (err)
6042 break;
6043 se_time = got_object_tag_get_tagger_time(se_tag);
6044 got_object_tag_close(se_tag);
6046 if (se_time > re_time) {
6047 err = got_reflist_entry_dup(&new, re);
6048 if (err)
6049 return err;
6050 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6051 break;
6053 se = STAILQ_NEXT(se, entry);
6054 continue;
6057 done:
6058 return err;
6060 #endif
6062 static const struct got_error *
6063 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6065 static const struct got_error *err = NULL;
6066 struct got_reflist_head refs;
6067 struct got_reflist_entry *re;
6069 TAILQ_INIT(&refs);
6071 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6072 if (err)
6073 return err;
6075 TAILQ_FOREACH(re, &refs, entry) {
6076 const char *refname;
6077 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6078 char datebuf[26];
6079 const char *tagger;
6080 time_t tagger_time;
6081 struct got_object_id *id;
6082 struct got_tag_object *tag;
6083 struct got_commit_object *commit = NULL;
6085 refname = got_ref_get_name(re->ref);
6086 if (strncmp(refname, "refs/tags/", 10) != 0)
6087 continue;
6088 refname += 10;
6089 refstr = got_ref_to_str(re->ref);
6090 if (refstr == NULL) {
6091 err = got_error_from_errno("got_ref_to_str");
6092 break;
6094 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6095 free(refstr);
6097 err = got_ref_resolve(&id, repo, re->ref);
6098 if (err)
6099 break;
6100 err = got_object_open_as_tag(&tag, repo, id);
6101 if (err) {
6102 if (err->code != GOT_ERR_OBJ_TYPE) {
6103 free(id);
6104 break;
6106 /* "lightweight" tag */
6107 err = got_object_open_as_commit(&commit, repo, id);
6108 if (err) {
6109 free(id);
6110 break;
6112 tagger = got_object_commit_get_committer(commit);
6113 tagger_time =
6114 got_object_commit_get_committer_time(commit);
6115 err = got_object_id_str(&id_str, id);
6116 free(id);
6117 if (err)
6118 break;
6119 } else {
6120 free(id);
6121 tagger = got_object_tag_get_tagger(tag);
6122 tagger_time = got_object_tag_get_tagger_time(tag);
6123 err = got_object_id_str(&id_str,
6124 got_object_tag_get_object_id(tag));
6125 if (err)
6126 break;
6128 printf("from: %s\n", tagger);
6129 datestr = get_datestr(&tagger_time, datebuf);
6130 if (datestr)
6131 printf("date: %s UTC\n", datestr);
6132 if (commit)
6133 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6134 else {
6135 switch (got_object_tag_get_object_type(tag)) {
6136 case GOT_OBJ_TYPE_BLOB:
6137 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6138 id_str);
6139 break;
6140 case GOT_OBJ_TYPE_TREE:
6141 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6142 id_str);
6143 break;
6144 case GOT_OBJ_TYPE_COMMIT:
6145 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6146 id_str);
6147 break;
6148 case GOT_OBJ_TYPE_TAG:
6149 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6150 id_str);
6151 break;
6152 default:
6153 break;
6156 free(id_str);
6157 if (commit) {
6158 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6159 if (err)
6160 break;
6161 got_object_commit_close(commit);
6162 } else {
6163 tagmsg0 = strdup(got_object_tag_get_message(tag));
6164 got_object_tag_close(tag);
6165 if (tagmsg0 == NULL) {
6166 err = got_error_from_errno("strdup");
6167 break;
6171 tagmsg = tagmsg0;
6172 do {
6173 line = strsep(&tagmsg, "\n");
6174 if (line)
6175 printf(" %s\n", line);
6176 } while (line);
6177 free(tagmsg0);
6180 got_ref_list_free(&refs);
6181 return NULL;
6184 static const struct got_error *
6185 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6186 const char *tag_name, const char *repo_path)
6188 const struct got_error *err = NULL;
6189 char *template = NULL, *initial_content = NULL;
6190 char *editor = NULL;
6191 int initial_content_len;
6192 int fd = -1;
6194 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6195 err = got_error_from_errno("asprintf");
6196 goto done;
6199 initial_content_len = asprintf(&initial_content,
6200 "\n# tagging commit %s as %s\n",
6201 commit_id_str, tag_name);
6202 if (initial_content_len == -1) {
6203 err = got_error_from_errno("asprintf");
6204 goto done;
6207 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6208 if (err)
6209 goto done;
6211 if (write(fd, initial_content, initial_content_len) == -1) {
6212 err = got_error_from_errno2("write", *tagmsg_path);
6213 goto done;
6216 err = get_editor(&editor);
6217 if (err)
6218 goto done;
6219 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6220 initial_content_len, 1);
6221 done:
6222 free(initial_content);
6223 free(template);
6224 free(editor);
6226 if (fd != -1 && close(fd) == -1 && err == NULL)
6227 err = got_error_from_errno2("close", *tagmsg_path);
6229 /* Editor is done; we can now apply unveil(2) */
6230 if (err == NULL)
6231 err = apply_unveil(repo_path, 0, NULL);
6232 if (err) {
6233 free(*tagmsg);
6234 *tagmsg = NULL;
6236 return err;
6239 static const struct got_error *
6240 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6241 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6243 const struct got_error *err = NULL;
6244 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6245 char *label = NULL, *commit_id_str = NULL;
6246 struct got_reference *ref = NULL;
6247 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6248 char *tagmsg_path = NULL, *tag_id_str = NULL;
6249 int preserve_tagmsg = 0;
6250 struct got_reflist_head refs;
6252 TAILQ_INIT(&refs);
6255 * Don't let the user create a tag name with a leading '-'.
6256 * While technically a valid reference name, this case is usually
6257 * an unintended typo.
6259 if (tag_name[0] == '-')
6260 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6262 err = get_author(&tagger, repo, worktree);
6263 if (err)
6264 return err;
6266 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6267 if (err)
6268 goto done;
6270 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6271 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6272 if (err)
6273 goto done;
6275 err = got_object_id_str(&commit_id_str, commit_id);
6276 if (err)
6277 goto done;
6279 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6280 refname = strdup(tag_name);
6281 if (refname == NULL) {
6282 err = got_error_from_errno("strdup");
6283 goto done;
6285 tag_name += 10;
6286 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6287 err = got_error_from_errno("asprintf");
6288 goto done;
6291 err = got_ref_open(&ref, repo, refname, 0);
6292 if (err == NULL) {
6293 err = got_error(GOT_ERR_TAG_EXISTS);
6294 goto done;
6295 } else if (err->code != GOT_ERR_NOT_REF)
6296 goto done;
6298 if (tagmsg_arg == NULL) {
6299 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6300 tag_name, got_repo_get_path(repo));
6301 if (err) {
6302 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6303 tagmsg_path != NULL)
6304 preserve_tagmsg = 1;
6305 goto done;
6309 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6310 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6311 if (err) {
6312 if (tagmsg_path)
6313 preserve_tagmsg = 1;
6314 goto done;
6317 err = got_ref_alloc(&ref, refname, tag_id);
6318 if (err) {
6319 if (tagmsg_path)
6320 preserve_tagmsg = 1;
6321 goto done;
6324 err = got_ref_write(ref, repo);
6325 if (err) {
6326 if (tagmsg_path)
6327 preserve_tagmsg = 1;
6328 goto done;
6331 err = got_object_id_str(&tag_id_str, tag_id);
6332 if (err) {
6333 if (tagmsg_path)
6334 preserve_tagmsg = 1;
6335 goto done;
6337 printf("Created tag %s\n", tag_id_str);
6338 done:
6339 if (preserve_tagmsg) {
6340 fprintf(stderr, "%s: tag message preserved in %s\n",
6341 getprogname(), tagmsg_path);
6342 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6343 err = got_error_from_errno2("unlink", tagmsg_path);
6344 free(tag_id_str);
6345 if (ref)
6346 got_ref_close(ref);
6347 free(commit_id);
6348 free(commit_id_str);
6349 free(refname);
6350 free(tagmsg);
6351 free(tagmsg_path);
6352 free(tagger);
6353 got_ref_list_free(&refs);
6354 return err;
6357 static const struct got_error *
6358 cmd_tag(int argc, char *argv[])
6360 const struct got_error *error = NULL;
6361 struct got_repository *repo = NULL;
6362 struct got_worktree *worktree = NULL;
6363 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6364 char *gitconfig_path = NULL;
6365 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6366 int ch, do_list = 0;
6368 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6369 switch (ch) {
6370 case 'c':
6371 commit_id_arg = optarg;
6372 break;
6373 case 'm':
6374 tagmsg = optarg;
6375 break;
6376 case 'r':
6377 repo_path = realpath(optarg, NULL);
6378 if (repo_path == NULL)
6379 return got_error_from_errno2("realpath",
6380 optarg);
6381 got_path_strip_trailing_slashes(repo_path);
6382 break;
6383 case 'l':
6384 do_list = 1;
6385 break;
6386 default:
6387 usage_tag();
6388 /* NOTREACHED */
6392 argc -= optind;
6393 argv += optind;
6395 if (do_list) {
6396 if (commit_id_arg != NULL)
6397 errx(1,
6398 "-c option can only be used when creating a tag");
6399 if (tagmsg)
6400 option_conflict('l', 'm');
6401 if (argc > 0)
6402 usage_tag();
6403 } else if (argc != 1)
6404 usage_tag();
6406 tag_name = argv[0];
6408 #ifndef PROFILE
6409 if (do_list) {
6410 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6411 NULL) == -1)
6412 err(1, "pledge");
6413 } else {
6414 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6415 "sendfd unveil", NULL) == -1)
6416 err(1, "pledge");
6418 #endif
6419 cwd = getcwd(NULL, 0);
6420 if (cwd == NULL) {
6421 error = got_error_from_errno("getcwd");
6422 goto done;
6425 if (repo_path == NULL) {
6426 error = got_worktree_open(&worktree, cwd);
6427 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6428 goto done;
6429 else
6430 error = NULL;
6431 if (worktree) {
6432 repo_path =
6433 strdup(got_worktree_get_repo_path(worktree));
6434 if (repo_path == NULL)
6435 error = got_error_from_errno("strdup");
6436 if (error)
6437 goto done;
6438 } else {
6439 repo_path = strdup(cwd);
6440 if (repo_path == NULL) {
6441 error = got_error_from_errno("strdup");
6442 goto done;
6447 if (do_list) {
6448 error = got_repo_open(&repo, repo_path, NULL);
6449 if (error != NULL)
6450 goto done;
6451 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6452 if (error)
6453 goto done;
6454 error = list_tags(repo, worktree);
6455 } else {
6456 error = get_gitconfig_path(&gitconfig_path);
6457 if (error)
6458 goto done;
6459 error = got_repo_open(&repo, repo_path, gitconfig_path);
6460 if (error != NULL)
6461 goto done;
6463 if (tagmsg) {
6464 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6465 if (error)
6466 goto done;
6469 if (commit_id_arg == NULL) {
6470 struct got_reference *head_ref;
6471 struct got_object_id *commit_id;
6472 error = got_ref_open(&head_ref, repo,
6473 worktree ? got_worktree_get_head_ref_name(worktree)
6474 : GOT_REF_HEAD, 0);
6475 if (error)
6476 goto done;
6477 error = got_ref_resolve(&commit_id, repo, head_ref);
6478 got_ref_close(head_ref);
6479 if (error)
6480 goto done;
6481 error = got_object_id_str(&commit_id_str, commit_id);
6482 free(commit_id);
6483 if (error)
6484 goto done;
6487 error = add_tag(repo, worktree, tag_name,
6488 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6490 done:
6491 if (repo) {
6492 const struct got_error *close_err = got_repo_close(repo);
6493 if (error == NULL)
6494 error = close_err;
6496 if (worktree)
6497 got_worktree_close(worktree);
6498 free(cwd);
6499 free(repo_path);
6500 free(gitconfig_path);
6501 free(commit_id_str);
6502 return error;
6505 __dead static void
6506 usage_add(void)
6508 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6509 getprogname());
6510 exit(1);
6513 static const struct got_error *
6514 add_progress(void *arg, unsigned char status, const char *path)
6516 while (path[0] == '/')
6517 path++;
6518 printf("%c %s\n", status, path);
6519 return NULL;
6522 static const struct got_error *
6523 cmd_add(int argc, char *argv[])
6525 const struct got_error *error = NULL;
6526 struct got_repository *repo = NULL;
6527 struct got_worktree *worktree = NULL;
6528 char *cwd = NULL;
6529 struct got_pathlist_head paths;
6530 struct got_pathlist_entry *pe;
6531 int ch, can_recurse = 0, no_ignores = 0;
6533 TAILQ_INIT(&paths);
6535 while ((ch = getopt(argc, argv, "IR")) != -1) {
6536 switch (ch) {
6537 case 'I':
6538 no_ignores = 1;
6539 break;
6540 case 'R':
6541 can_recurse = 1;
6542 break;
6543 default:
6544 usage_add();
6545 /* NOTREACHED */
6549 argc -= optind;
6550 argv += optind;
6552 #ifndef PROFILE
6553 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6554 NULL) == -1)
6555 err(1, "pledge");
6556 #endif
6557 if (argc < 1)
6558 usage_add();
6560 cwd = getcwd(NULL, 0);
6561 if (cwd == NULL) {
6562 error = got_error_from_errno("getcwd");
6563 goto done;
6566 error = got_worktree_open(&worktree, cwd);
6567 if (error) {
6568 if (error->code == GOT_ERR_NOT_WORKTREE)
6569 error = wrap_not_worktree_error(error, "add", cwd);
6570 goto done;
6573 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6574 NULL);
6575 if (error != NULL)
6576 goto done;
6578 error = apply_unveil(got_repo_get_path(repo), 1,
6579 got_worktree_get_root_path(worktree));
6580 if (error)
6581 goto done;
6583 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6584 if (error)
6585 goto done;
6587 if (!can_recurse) {
6588 char *ondisk_path;
6589 struct stat sb;
6590 TAILQ_FOREACH(pe, &paths, entry) {
6591 if (asprintf(&ondisk_path, "%s/%s",
6592 got_worktree_get_root_path(worktree),
6593 pe->path) == -1) {
6594 error = got_error_from_errno("asprintf");
6595 goto done;
6597 if (lstat(ondisk_path, &sb) == -1) {
6598 if (errno == ENOENT) {
6599 free(ondisk_path);
6600 continue;
6602 error = got_error_from_errno2("lstat",
6603 ondisk_path);
6604 free(ondisk_path);
6605 goto done;
6607 free(ondisk_path);
6608 if (S_ISDIR(sb.st_mode)) {
6609 error = got_error_msg(GOT_ERR_BAD_PATH,
6610 "adding directories requires -R option");
6611 goto done;
6616 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6617 NULL, repo, no_ignores);
6618 done:
6619 if (repo) {
6620 const struct got_error *close_err = got_repo_close(repo);
6621 if (error == NULL)
6622 error = close_err;
6624 if (worktree)
6625 got_worktree_close(worktree);
6626 TAILQ_FOREACH(pe, &paths, entry)
6627 free((char *)pe->path);
6628 got_pathlist_free(&paths);
6629 free(cwd);
6630 return error;
6633 __dead static void
6634 usage_remove(void)
6636 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6637 "path ...\n", getprogname());
6638 exit(1);
6641 static const struct got_error *
6642 print_remove_status(void *arg, unsigned char status,
6643 unsigned char staged_status, const char *path)
6645 while (path[0] == '/')
6646 path++;
6647 if (status == GOT_STATUS_NONEXISTENT)
6648 return NULL;
6649 if (status == staged_status && (status == GOT_STATUS_DELETE))
6650 status = GOT_STATUS_NO_CHANGE;
6651 printf("%c%c %s\n", status, staged_status, path);
6652 return NULL;
6655 static const struct got_error *
6656 cmd_remove(int argc, char *argv[])
6658 const struct got_error *error = NULL;
6659 struct got_worktree *worktree = NULL;
6660 struct got_repository *repo = NULL;
6661 const char *status_codes = NULL;
6662 char *cwd = NULL;
6663 struct got_pathlist_head paths;
6664 struct got_pathlist_entry *pe;
6665 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6667 TAILQ_INIT(&paths);
6669 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6670 switch (ch) {
6671 case 'f':
6672 delete_local_mods = 1;
6673 break;
6674 case 'k':
6675 keep_on_disk = 1;
6676 break;
6677 case 'R':
6678 can_recurse = 1;
6679 break;
6680 case 's':
6681 for (i = 0; i < strlen(optarg); i++) {
6682 switch (optarg[i]) {
6683 case GOT_STATUS_MODIFY:
6684 delete_local_mods = 1;
6685 break;
6686 case GOT_STATUS_MISSING:
6687 break;
6688 default:
6689 errx(1, "invalid status code '%c'",
6690 optarg[i]);
6693 status_codes = optarg;
6694 break;
6695 default:
6696 usage_remove();
6697 /* NOTREACHED */
6701 argc -= optind;
6702 argv += optind;
6704 #ifndef PROFILE
6705 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6706 NULL) == -1)
6707 err(1, "pledge");
6708 #endif
6709 if (argc < 1)
6710 usage_remove();
6712 cwd = getcwd(NULL, 0);
6713 if (cwd == NULL) {
6714 error = got_error_from_errno("getcwd");
6715 goto done;
6717 error = got_worktree_open(&worktree, cwd);
6718 if (error) {
6719 if (error->code == GOT_ERR_NOT_WORKTREE)
6720 error = wrap_not_worktree_error(error, "remove", cwd);
6721 goto done;
6724 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6725 NULL);
6726 if (error)
6727 goto done;
6729 error = apply_unveil(got_repo_get_path(repo), 1,
6730 got_worktree_get_root_path(worktree));
6731 if (error)
6732 goto done;
6734 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6735 if (error)
6736 goto done;
6738 if (!can_recurse) {
6739 char *ondisk_path;
6740 struct stat sb;
6741 TAILQ_FOREACH(pe, &paths, entry) {
6742 if (asprintf(&ondisk_path, "%s/%s",
6743 got_worktree_get_root_path(worktree),
6744 pe->path) == -1) {
6745 error = got_error_from_errno("asprintf");
6746 goto done;
6748 if (lstat(ondisk_path, &sb) == -1) {
6749 if (errno == ENOENT) {
6750 free(ondisk_path);
6751 continue;
6753 error = got_error_from_errno2("lstat",
6754 ondisk_path);
6755 free(ondisk_path);
6756 goto done;
6758 free(ondisk_path);
6759 if (S_ISDIR(sb.st_mode)) {
6760 error = got_error_msg(GOT_ERR_BAD_PATH,
6761 "removing directories requires -R option");
6762 goto done;
6767 error = got_worktree_schedule_delete(worktree, &paths,
6768 delete_local_mods, status_codes, print_remove_status, NULL,
6769 repo, keep_on_disk);
6770 done:
6771 if (repo) {
6772 const struct got_error *close_err = got_repo_close(repo);
6773 if (error == NULL)
6774 error = close_err;
6776 if (worktree)
6777 got_worktree_close(worktree);
6778 TAILQ_FOREACH(pe, &paths, entry)
6779 free((char *)pe->path);
6780 got_pathlist_free(&paths);
6781 free(cwd);
6782 return error;
6785 __dead static void
6786 usage_revert(void)
6788 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6789 "path ...\n", getprogname());
6790 exit(1);
6793 static const struct got_error *
6794 revert_progress(void *arg, unsigned char status, const char *path)
6796 if (status == GOT_STATUS_UNVERSIONED)
6797 return NULL;
6799 while (path[0] == '/')
6800 path++;
6801 printf("%c %s\n", status, path);
6802 return NULL;
6805 struct choose_patch_arg {
6806 FILE *patch_script_file;
6807 const char *action;
6810 static const struct got_error *
6811 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6812 int nchanges, const char *action)
6814 char *line = NULL;
6815 size_t linesize = 0;
6816 ssize_t linelen;
6818 switch (status) {
6819 case GOT_STATUS_ADD:
6820 printf("A %s\n%s this addition? [y/n] ", path, action);
6821 break;
6822 case GOT_STATUS_DELETE:
6823 printf("D %s\n%s this deletion? [y/n] ", path, action);
6824 break;
6825 case GOT_STATUS_MODIFY:
6826 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6827 return got_error_from_errno("fseek");
6828 printf(GOT_COMMIT_SEP_STR);
6829 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6830 printf("%s", line);
6831 if (ferror(patch_file))
6832 return got_error_from_errno("getline");
6833 printf(GOT_COMMIT_SEP_STR);
6834 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6835 path, n, nchanges, action);
6836 break;
6837 default:
6838 return got_error_path(path, GOT_ERR_FILE_STATUS);
6841 return NULL;
6844 static const struct got_error *
6845 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6846 FILE *patch_file, int n, int nchanges)
6848 const struct got_error *err = NULL;
6849 char *line = NULL;
6850 size_t linesize = 0;
6851 ssize_t linelen;
6852 int resp = ' ';
6853 struct choose_patch_arg *a = arg;
6855 *choice = GOT_PATCH_CHOICE_NONE;
6857 if (a->patch_script_file) {
6858 char *nl;
6859 err = show_change(status, path, patch_file, n, nchanges,
6860 a->action);
6861 if (err)
6862 return err;
6863 linelen = getline(&line, &linesize, a->patch_script_file);
6864 if (linelen == -1) {
6865 if (ferror(a->patch_script_file))
6866 return got_error_from_errno("getline");
6867 return NULL;
6869 nl = strchr(line, '\n');
6870 if (nl)
6871 *nl = '\0';
6872 if (strcmp(line, "y") == 0) {
6873 *choice = GOT_PATCH_CHOICE_YES;
6874 printf("y\n");
6875 } else if (strcmp(line, "n") == 0) {
6876 *choice = GOT_PATCH_CHOICE_NO;
6877 printf("n\n");
6878 } else if (strcmp(line, "q") == 0 &&
6879 status == GOT_STATUS_MODIFY) {
6880 *choice = GOT_PATCH_CHOICE_QUIT;
6881 printf("q\n");
6882 } else
6883 printf("invalid response '%s'\n", line);
6884 free(line);
6885 return NULL;
6888 while (resp != 'y' && resp != 'n' && resp != 'q') {
6889 err = show_change(status, path, patch_file, n, nchanges,
6890 a->action);
6891 if (err)
6892 return err;
6893 resp = getchar();
6894 if (resp == '\n')
6895 resp = getchar();
6896 if (status == GOT_STATUS_MODIFY) {
6897 if (resp != 'y' && resp != 'n' && resp != 'q') {
6898 printf("invalid response '%c'\n", resp);
6899 resp = ' ';
6901 } else if (resp != 'y' && resp != 'n') {
6902 printf("invalid response '%c'\n", resp);
6903 resp = ' ';
6907 if (resp == 'y')
6908 *choice = GOT_PATCH_CHOICE_YES;
6909 else if (resp == 'n')
6910 *choice = GOT_PATCH_CHOICE_NO;
6911 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6912 *choice = GOT_PATCH_CHOICE_QUIT;
6914 return NULL;
6918 static const struct got_error *
6919 cmd_revert(int argc, char *argv[])
6921 const struct got_error *error = NULL;
6922 struct got_worktree *worktree = NULL;
6923 struct got_repository *repo = NULL;
6924 char *cwd = NULL, *path = NULL;
6925 struct got_pathlist_head paths;
6926 struct got_pathlist_entry *pe;
6927 int ch, can_recurse = 0, pflag = 0;
6928 FILE *patch_script_file = NULL;
6929 const char *patch_script_path = NULL;
6930 struct choose_patch_arg cpa;
6932 TAILQ_INIT(&paths);
6934 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6935 switch (ch) {
6936 case 'p':
6937 pflag = 1;
6938 break;
6939 case 'F':
6940 patch_script_path = optarg;
6941 break;
6942 case 'R':
6943 can_recurse = 1;
6944 break;
6945 default:
6946 usage_revert();
6947 /* NOTREACHED */
6951 argc -= optind;
6952 argv += optind;
6954 #ifndef PROFILE
6955 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6956 "unveil", NULL) == -1)
6957 err(1, "pledge");
6958 #endif
6959 if (argc < 1)
6960 usage_revert();
6961 if (patch_script_path && !pflag)
6962 errx(1, "-F option can only be used together with -p option");
6964 cwd = getcwd(NULL, 0);
6965 if (cwd == NULL) {
6966 error = got_error_from_errno("getcwd");
6967 goto done;
6969 error = got_worktree_open(&worktree, cwd);
6970 if (error) {
6971 if (error->code == GOT_ERR_NOT_WORKTREE)
6972 error = wrap_not_worktree_error(error, "revert", cwd);
6973 goto done;
6976 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6977 NULL);
6978 if (error != NULL)
6979 goto done;
6981 if (patch_script_path) {
6982 patch_script_file = fopen(patch_script_path, "r");
6983 if (patch_script_file == NULL) {
6984 error = got_error_from_errno2("fopen",
6985 patch_script_path);
6986 goto done;
6989 error = apply_unveil(got_repo_get_path(repo), 1,
6990 got_worktree_get_root_path(worktree));
6991 if (error)
6992 goto done;
6994 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6995 if (error)
6996 goto done;
6998 if (!can_recurse) {
6999 char *ondisk_path;
7000 struct stat sb;
7001 TAILQ_FOREACH(pe, &paths, entry) {
7002 if (asprintf(&ondisk_path, "%s/%s",
7003 got_worktree_get_root_path(worktree),
7004 pe->path) == -1) {
7005 error = got_error_from_errno("asprintf");
7006 goto done;
7008 if (lstat(ondisk_path, &sb) == -1) {
7009 if (errno == ENOENT) {
7010 free(ondisk_path);
7011 continue;
7013 error = got_error_from_errno2("lstat",
7014 ondisk_path);
7015 free(ondisk_path);
7016 goto done;
7018 free(ondisk_path);
7019 if (S_ISDIR(sb.st_mode)) {
7020 error = got_error_msg(GOT_ERR_BAD_PATH,
7021 "reverting directories requires -R option");
7022 goto done;
7027 cpa.patch_script_file = patch_script_file;
7028 cpa.action = "revert";
7029 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7030 pflag ? choose_patch : NULL, &cpa, repo);
7031 done:
7032 if (patch_script_file && fclose(patch_script_file) == EOF &&
7033 error == NULL)
7034 error = got_error_from_errno2("fclose", patch_script_path);
7035 if (repo) {
7036 const struct got_error *close_err = got_repo_close(repo);
7037 if (error == NULL)
7038 error = close_err;
7040 if (worktree)
7041 got_worktree_close(worktree);
7042 free(path);
7043 free(cwd);
7044 return error;
7047 __dead static void
7048 usage_commit(void)
7050 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7051 "[path ...]\n", getprogname());
7052 exit(1);
7055 struct collect_commit_logmsg_arg {
7056 const char *cmdline_log;
7057 const char *prepared_log;
7058 int non_interactive;
7059 const char *editor;
7060 const char *worktree_path;
7061 const char *branch_name;
7062 const char *repo_path;
7063 char *logmsg_path;
7067 static const struct got_error *
7068 read_prepared_logmsg(char **logmsg, const char *path)
7070 const struct got_error *err = NULL;
7071 FILE *f = NULL;
7072 struct stat sb;
7073 size_t r;
7075 *logmsg = NULL;
7076 memset(&sb, 0, sizeof(sb));
7078 f = fopen(path, "r");
7079 if (f == NULL)
7080 return got_error_from_errno2("fopen", path);
7082 if (fstat(fileno(f), &sb) == -1) {
7083 err = got_error_from_errno2("fstat", path);
7084 goto done;
7086 if (sb.st_size == 0) {
7087 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7088 goto done;
7091 *logmsg = malloc(sb.st_size + 1);
7092 if (*logmsg == NULL) {
7093 err = got_error_from_errno("malloc");
7094 goto done;
7097 r = fread(*logmsg, 1, sb.st_size, f);
7098 if (r != sb.st_size) {
7099 if (ferror(f))
7100 err = got_error_from_errno2("fread", path);
7101 else
7102 err = got_error(GOT_ERR_IO);
7103 goto done;
7105 (*logmsg)[sb.st_size] = '\0';
7106 done:
7107 if (fclose(f) == EOF && err == NULL)
7108 err = got_error_from_errno2("fclose", path);
7109 if (err) {
7110 free(*logmsg);
7111 *logmsg = NULL;
7113 return err;
7117 static const struct got_error *
7118 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7119 void *arg)
7121 char *initial_content = NULL;
7122 struct got_pathlist_entry *pe;
7123 const struct got_error *err = NULL;
7124 char *template = NULL;
7125 struct collect_commit_logmsg_arg *a = arg;
7126 int initial_content_len;
7127 int fd = -1;
7128 size_t len;
7130 /* if a message was specified on the command line, just use it */
7131 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7132 len = strlen(a->cmdline_log) + 1;
7133 *logmsg = malloc(len + 1);
7134 if (*logmsg == NULL)
7135 return got_error_from_errno("malloc");
7136 strlcpy(*logmsg, a->cmdline_log, len);
7137 return NULL;
7138 } else if (a->prepared_log != NULL && a->non_interactive)
7139 return read_prepared_logmsg(logmsg, a->prepared_log);
7141 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7142 return got_error_from_errno("asprintf");
7144 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7145 if (err)
7146 goto done;
7148 if (a->prepared_log) {
7149 char *msg;
7150 err = read_prepared_logmsg(&msg, a->prepared_log);
7151 if (err)
7152 goto done;
7153 if (write(fd, msg, strlen(msg)) == -1) {
7154 err = got_error_from_errno2("write", a->logmsg_path);
7155 free(msg);
7156 goto done;
7158 free(msg);
7161 initial_content_len = asprintf(&initial_content,
7162 "\n# changes to be committed on branch %s:\n",
7163 a->branch_name);
7164 if (initial_content_len == -1) {
7165 err = got_error_from_errno("asprintf");
7166 goto done;
7169 if (write(fd, initial_content, initial_content_len) == -1) {
7170 err = got_error_from_errno2("write", a->logmsg_path);
7171 goto done;
7174 TAILQ_FOREACH(pe, commitable_paths, entry) {
7175 struct got_commitable *ct = pe->data;
7176 dprintf(fd, "# %c %s\n",
7177 got_commitable_get_status(ct),
7178 got_commitable_get_path(ct));
7181 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7182 initial_content_len, a->prepared_log ? 0 : 1);
7183 done:
7184 free(initial_content);
7185 free(template);
7187 if (fd != -1 && close(fd) == -1 && err == NULL)
7188 err = got_error_from_errno2("close", a->logmsg_path);
7190 /* Editor is done; we can now apply unveil(2) */
7191 if (err == NULL)
7192 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7193 if (err) {
7194 free(*logmsg);
7195 *logmsg = NULL;
7197 return err;
7200 static const struct got_error *
7201 cmd_commit(int argc, char *argv[])
7203 const struct got_error *error = NULL;
7204 struct got_worktree *worktree = NULL;
7205 struct got_repository *repo = NULL;
7206 char *cwd = NULL, *id_str = NULL;
7207 struct got_object_id *id = NULL;
7208 const char *logmsg = NULL;
7209 char *prepared_logmsg = NULL;
7210 struct collect_commit_logmsg_arg cl_arg;
7211 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7212 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7213 int allow_bad_symlinks = 0, non_interactive = 0;
7214 struct got_pathlist_head paths;
7216 TAILQ_INIT(&paths);
7217 cl_arg.logmsg_path = NULL;
7219 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7220 switch (ch) {
7221 case 'F':
7222 if (logmsg != NULL)
7223 option_conflict('F', 'm');
7224 prepared_logmsg = realpath(optarg, NULL);
7225 if (prepared_logmsg == NULL)
7226 return got_error_from_errno2("realpath",
7227 optarg);
7228 break;
7229 case 'm':
7230 if (prepared_logmsg)
7231 option_conflict('m', 'F');
7232 logmsg = optarg;
7233 break;
7234 case 'N':
7235 non_interactive = 1;
7236 break;
7237 case 'S':
7238 allow_bad_symlinks = 1;
7239 break;
7240 default:
7241 usage_commit();
7242 /* NOTREACHED */
7246 argc -= optind;
7247 argv += optind;
7249 #ifndef PROFILE
7250 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7251 "unveil", NULL) == -1)
7252 err(1, "pledge");
7253 #endif
7254 cwd = getcwd(NULL, 0);
7255 if (cwd == NULL) {
7256 error = got_error_from_errno("getcwd");
7257 goto done;
7259 error = got_worktree_open(&worktree, cwd);
7260 if (error) {
7261 if (error->code == GOT_ERR_NOT_WORKTREE)
7262 error = wrap_not_worktree_error(error, "commit", cwd);
7263 goto done;
7266 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7267 if (error)
7268 goto done;
7269 if (rebase_in_progress) {
7270 error = got_error(GOT_ERR_REBASING);
7271 goto done;
7274 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7275 worktree);
7276 if (error)
7277 goto done;
7279 error = get_gitconfig_path(&gitconfig_path);
7280 if (error)
7281 goto done;
7282 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7283 gitconfig_path);
7284 if (error != NULL)
7285 goto done;
7287 error = get_author(&author, repo, worktree);
7288 if (error)
7289 return error;
7292 * unveil(2) traverses exec(2); if an editor is used we have
7293 * to apply unveil after the log message has been written.
7295 if (logmsg == NULL || strlen(logmsg) == 0)
7296 error = get_editor(&editor);
7297 else
7298 error = apply_unveil(got_repo_get_path(repo), 0,
7299 got_worktree_get_root_path(worktree));
7300 if (error)
7301 goto done;
7303 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7304 if (error)
7305 goto done;
7307 cl_arg.editor = editor;
7308 cl_arg.cmdline_log = logmsg;
7309 cl_arg.prepared_log = prepared_logmsg;
7310 cl_arg.non_interactive = non_interactive;
7311 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7312 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7313 if (!histedit_in_progress) {
7314 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7315 error = got_error(GOT_ERR_COMMIT_BRANCH);
7316 goto done;
7318 cl_arg.branch_name += 11;
7320 cl_arg.repo_path = got_repo_get_path(repo);
7321 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7322 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7323 print_status, NULL, repo);
7324 if (error) {
7325 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7326 cl_arg.logmsg_path != NULL)
7327 preserve_logmsg = 1;
7328 goto done;
7331 error = got_object_id_str(&id_str, id);
7332 if (error)
7333 goto done;
7334 printf("Created commit %s\n", id_str);
7335 done:
7336 if (preserve_logmsg) {
7337 fprintf(stderr, "%s: log message preserved in %s\n",
7338 getprogname(), cl_arg.logmsg_path);
7339 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7340 error == NULL)
7341 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7342 free(cl_arg.logmsg_path);
7343 if (repo) {
7344 const struct got_error *close_err = got_repo_close(repo);
7345 if (error == NULL)
7346 error = close_err;
7348 if (worktree)
7349 got_worktree_close(worktree);
7350 free(cwd);
7351 free(id_str);
7352 free(gitconfig_path);
7353 free(editor);
7354 free(author);
7355 free(prepared_logmsg);
7356 return error;
7359 __dead static void
7360 usage_send(void)
7362 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7363 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7364 "[remote-repository]\n", getprogname());
7365 exit(1);
7368 struct got_send_progress_arg {
7369 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7370 int verbosity;
7371 int last_ncommits;
7372 int last_nobj_total;
7373 int last_p_deltify;
7374 int last_p_written;
7375 int last_p_sent;
7376 int printed_something;
7377 int sent_something;
7378 struct got_pathlist_head *delete_branches;
7381 static const struct got_error *
7382 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7383 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7384 int success)
7386 struct got_send_progress_arg *a = arg;
7387 char scaled_packsize[FMT_SCALED_STRSIZE];
7388 char scaled_sent[FMT_SCALED_STRSIZE];
7389 int p_deltify = 0, p_written = 0, p_sent = 0;
7390 int print_searching = 0, print_total = 0;
7391 int print_deltify = 0, print_written = 0, print_sent = 0;
7393 if (a->verbosity < 0)
7394 return NULL;
7396 if (refname) {
7397 const char *status = success ? "accepted" : "rejected";
7399 if (success) {
7400 struct got_pathlist_entry *pe;
7401 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7402 const char *branchname = pe->path;
7403 if (got_path_cmp(branchname, refname,
7404 strlen(branchname), strlen(refname)) == 0) {
7405 status = "deleted";
7406 break;
7411 printf("\nServer has %s %s", status, refname);
7412 a->printed_something = 1;
7413 return NULL;
7416 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7417 return got_error_from_errno("fmt_scaled");
7418 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7419 return got_error_from_errno("fmt_scaled");
7421 if (a->last_ncommits != ncommits) {
7422 print_searching = 1;
7423 a->last_ncommits = ncommits;
7426 if (a->last_nobj_total != nobj_total) {
7427 print_searching = 1;
7428 print_total = 1;
7429 a->last_nobj_total = nobj_total;
7432 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7433 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7434 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7435 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7436 return got_error(GOT_ERR_NO_SPACE);
7439 if (nobj_deltify > 0 || nobj_written > 0) {
7440 if (nobj_deltify > 0) {
7441 p_deltify = (nobj_deltify * 100) / nobj_total;
7442 if (p_deltify != a->last_p_deltify) {
7443 a->last_p_deltify = p_deltify;
7444 print_searching = 1;
7445 print_total = 1;
7446 print_deltify = 1;
7449 if (nobj_written > 0) {
7450 p_written = (nobj_written * 100) / nobj_total;
7451 if (p_written != a->last_p_written) {
7452 a->last_p_written = p_written;
7453 print_searching = 1;
7454 print_total = 1;
7455 print_deltify = 1;
7456 print_written = 1;
7461 if (bytes_sent > 0) {
7462 p_sent = (bytes_sent * 100) / packfile_size;
7463 if (p_sent != a->last_p_sent) {
7464 a->last_p_sent = p_sent;
7465 print_searching = 1;
7466 print_total = 1;
7467 print_deltify = 1;
7468 print_written = 1;
7469 print_sent = 1;
7471 a->sent_something = 1;
7474 if (print_searching || print_total || print_deltify || print_written ||
7475 print_sent)
7476 printf("\r");
7477 if (print_searching)
7478 printf("packing %d reference%s", ncommits,
7479 ncommits == 1 ? "" : "s");
7480 if (print_total)
7481 printf("; %d object%s", nobj_total,
7482 nobj_total == 1 ? "" : "s");
7483 if (print_deltify)
7484 printf("; deltify: %d%%", p_deltify);
7485 if (print_sent)
7486 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7487 scaled_packsize, p_sent);
7488 else if (print_written)
7489 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7490 scaled_packsize, p_written);
7491 if (print_searching || print_total || print_deltify ||
7492 print_written || print_sent) {
7493 a->printed_something = 1;
7494 fflush(stdout);
7496 return NULL;
7499 static const struct got_error *
7500 cmd_send(int argc, char *argv[])
7502 const struct got_error *error = NULL;
7503 char *cwd = NULL, *repo_path = NULL;
7504 const char *remote_name;
7505 char *proto = NULL, *host = NULL, *port = NULL;
7506 char *repo_name = NULL, *server_path = NULL;
7507 const struct got_remote_repo *remotes, *remote = NULL;
7508 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7509 struct got_repository *repo = NULL;
7510 struct got_worktree *worktree = NULL;
7511 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7512 struct got_pathlist_head branches;
7513 struct got_pathlist_head tags;
7514 struct got_reflist_head all_branches;
7515 struct got_reflist_head all_tags;
7516 struct got_pathlist_head delete_args;
7517 struct got_pathlist_head delete_branches;
7518 struct got_reflist_entry *re;
7519 struct got_pathlist_entry *pe;
7520 int i, ch, sendfd = -1, sendstatus;
7521 pid_t sendpid = -1;
7522 struct got_send_progress_arg spa;
7523 int verbosity = 0, overwrite_refs = 0;
7524 int send_all_branches = 0, send_all_tags = 0;
7525 struct got_reference *ref = NULL;
7527 TAILQ_INIT(&branches);
7528 TAILQ_INIT(&tags);
7529 TAILQ_INIT(&all_branches);
7530 TAILQ_INIT(&all_tags);
7531 TAILQ_INIT(&delete_args);
7532 TAILQ_INIT(&delete_branches);
7534 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7535 switch (ch) {
7536 case 'a':
7537 send_all_branches = 1;
7538 break;
7539 case 'b':
7540 error = got_pathlist_append(&branches, optarg, NULL);
7541 if (error)
7542 return error;
7543 nbranches++;
7544 break;
7545 case 'd':
7546 error = got_pathlist_append(&delete_args, optarg, NULL);
7547 if (error)
7548 return error;
7549 break;
7550 case 'f':
7551 overwrite_refs = 1;
7552 break;
7553 case 'r':
7554 repo_path = realpath(optarg, NULL);
7555 if (repo_path == NULL)
7556 return got_error_from_errno2("realpath",
7557 optarg);
7558 got_path_strip_trailing_slashes(repo_path);
7559 break;
7560 case 't':
7561 error = got_pathlist_append(&tags, optarg, NULL);
7562 if (error)
7563 return error;
7564 ntags++;
7565 break;
7566 case 'T':
7567 send_all_tags = 1;
7568 break;
7569 case 'v':
7570 if (verbosity < 0)
7571 verbosity = 0;
7572 else if (verbosity < 3)
7573 verbosity++;
7574 break;
7575 case 'q':
7576 verbosity = -1;
7577 break;
7578 default:
7579 usage_send();
7580 /* NOTREACHED */
7583 argc -= optind;
7584 argv += optind;
7586 if (send_all_branches && !TAILQ_EMPTY(&branches))
7587 option_conflict('a', 'b');
7588 if (send_all_tags && !TAILQ_EMPTY(&tags))
7589 option_conflict('T', 't');
7592 if (argc == 0)
7593 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7594 else if (argc == 1)
7595 remote_name = argv[0];
7596 else
7597 usage_send();
7599 cwd = getcwd(NULL, 0);
7600 if (cwd == NULL) {
7601 error = got_error_from_errno("getcwd");
7602 goto done;
7605 if (repo_path == NULL) {
7606 error = got_worktree_open(&worktree, cwd);
7607 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7608 goto done;
7609 else
7610 error = NULL;
7611 if (worktree) {
7612 repo_path =
7613 strdup(got_worktree_get_repo_path(worktree));
7614 if (repo_path == NULL)
7615 error = got_error_from_errno("strdup");
7616 if (error)
7617 goto done;
7618 } else {
7619 repo_path = strdup(cwd);
7620 if (repo_path == NULL) {
7621 error = got_error_from_errno("strdup");
7622 goto done;
7627 error = got_repo_open(&repo, repo_path, NULL);
7628 if (error)
7629 goto done;
7631 if (worktree) {
7632 worktree_conf = got_worktree_get_gotconfig(worktree);
7633 if (worktree_conf) {
7634 got_gotconfig_get_remotes(&nremotes, &remotes,
7635 worktree_conf);
7636 for (i = 0; i < nremotes; i++) {
7637 if (strcmp(remotes[i].name, remote_name) == 0) {
7638 remote = &remotes[i];
7639 break;
7644 if (remote == NULL) {
7645 repo_conf = got_repo_get_gotconfig(repo);
7646 if (repo_conf) {
7647 got_gotconfig_get_remotes(&nremotes, &remotes,
7648 repo_conf);
7649 for (i = 0; i < nremotes; i++) {
7650 if (strcmp(remotes[i].name, remote_name) == 0) {
7651 remote = &remotes[i];
7652 break;
7657 if (remote == NULL) {
7658 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7659 for (i = 0; i < nremotes; i++) {
7660 if (strcmp(remotes[i].name, remote_name) == 0) {
7661 remote = &remotes[i];
7662 break;
7666 if (remote == NULL) {
7667 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7668 goto done;
7671 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
7672 &repo_name, remote->url);
7673 if (error)
7674 goto done;
7676 if (strcmp(proto, "git") == 0) {
7677 #ifndef PROFILE
7678 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7679 "sendfd dns inet unveil", NULL) == -1)
7680 err(1, "pledge");
7681 #endif
7682 } else if (strcmp(proto, "git+ssh") == 0 ||
7683 strcmp(proto, "ssh") == 0) {
7684 #ifndef PROFILE
7685 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7686 "sendfd unveil", NULL) == -1)
7687 err(1, "pledge");
7688 #endif
7689 } else if (strcmp(proto, "http") == 0 ||
7690 strcmp(proto, "git+http") == 0) {
7691 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7692 goto done;
7693 } else {
7694 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7695 goto done;
7698 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
7699 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
7700 error = got_error_from_errno2("unveil",
7701 GOT_FETCH_PATH_SSH);
7702 goto done;
7705 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7706 if (error)
7707 goto done;
7709 if (send_all_branches) {
7710 error = got_ref_list(&all_branches, repo, "refs/heads",
7711 got_ref_cmp_by_name, NULL);
7712 if (error)
7713 goto done;
7714 TAILQ_FOREACH(re, &all_branches, entry) {
7715 const char *branchname = got_ref_get_name(re->ref);
7716 error = got_pathlist_append(&branches,
7717 branchname, NULL);
7718 if (error)
7719 goto done;
7720 nbranches++;
7724 if (send_all_tags) {
7725 error = got_ref_list(&all_tags, repo, "refs/tags",
7726 got_ref_cmp_by_name, NULL);
7727 if (error)
7728 goto done;
7729 TAILQ_FOREACH(re, &all_tags, entry) {
7730 const char *tagname = got_ref_get_name(re->ref);
7731 error = got_pathlist_append(&tags,
7732 tagname, NULL);
7733 if (error)
7734 goto done;
7735 ntags++;
7740 * To prevent accidents only branches in refs/heads/ can be deleted
7741 * with 'got send -d'.
7742 * Deleting anything else requires local repository access or Git.
7744 TAILQ_FOREACH(pe, &delete_args, entry) {
7745 const char *branchname = pe->path;
7746 char *s;
7747 struct got_pathlist_entry *new;
7748 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7749 s = strdup(branchname);
7750 if (s == NULL) {
7751 error = got_error_from_errno("strdup");
7752 goto done;
7754 } else {
7755 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7756 error = got_error_from_errno("asprintf");
7757 goto done;
7760 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7761 if (error || new == NULL /* duplicate */)
7762 free(s);
7763 if (error)
7764 goto done;
7765 ndelete_branches++;
7768 if (nbranches == 0 && ndelete_branches == 0) {
7769 struct got_reference *head_ref;
7770 if (worktree)
7771 error = got_ref_open(&head_ref, repo,
7772 got_worktree_get_head_ref_name(worktree), 0);
7773 else
7774 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7775 if (error)
7776 goto done;
7777 if (got_ref_is_symbolic(head_ref)) {
7778 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7779 got_ref_close(head_ref);
7780 if (error)
7781 goto done;
7782 } else
7783 ref = head_ref;
7784 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7785 NULL);
7786 if (error)
7787 goto done;
7788 nbranches++;
7791 if (verbosity >= 0)
7792 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7793 port ? ":" : "", port ? port : "");
7795 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7796 server_path, verbosity);
7797 if (error)
7798 goto done;
7800 memset(&spa, 0, sizeof(spa));
7801 spa.last_scaled_packsize[0] = '\0';
7802 spa.last_p_deltify = -1;
7803 spa.last_p_written = -1;
7804 spa.verbosity = verbosity;
7805 spa.delete_branches = &delete_branches;
7806 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7807 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7808 check_cancelled, NULL);
7809 if (spa.printed_something)
7810 putchar('\n');
7811 if (error)
7812 goto done;
7813 if (!spa.sent_something && verbosity >= 0)
7814 printf("Already up-to-date\n");
7815 done:
7816 if (sendpid > 0) {
7817 if (kill(sendpid, SIGTERM) == -1)
7818 error = got_error_from_errno("kill");
7819 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7820 error = got_error_from_errno("waitpid");
7822 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7823 error = got_error_from_errno("close");
7824 if (repo) {
7825 const struct got_error *close_err = got_repo_close(repo);
7826 if (error == NULL)
7827 error = close_err;
7829 if (worktree)
7830 got_worktree_close(worktree);
7831 if (ref)
7832 got_ref_close(ref);
7833 got_pathlist_free(&branches);
7834 got_pathlist_free(&tags);
7835 got_ref_list_free(&all_branches);
7836 got_ref_list_free(&all_tags);
7837 got_pathlist_free(&delete_args);
7838 TAILQ_FOREACH(pe, &delete_branches, entry)
7839 free((char *)pe->path);
7840 got_pathlist_free(&delete_branches);
7841 free(cwd);
7842 free(repo_path);
7843 free(proto);
7844 free(host);
7845 free(port);
7846 free(server_path);
7847 free(repo_name);
7848 return error;
7851 __dead static void
7852 usage_cherrypick(void)
7854 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7855 exit(1);
7858 static const struct got_error *
7859 cmd_cherrypick(int argc, char *argv[])
7861 const struct got_error *error = NULL;
7862 struct got_worktree *worktree = NULL;
7863 struct got_repository *repo = NULL;
7864 char *cwd = NULL, *commit_id_str = NULL;
7865 struct got_object_id *commit_id = NULL;
7866 struct got_commit_object *commit = NULL;
7867 struct got_object_qid *pid;
7868 struct got_reference *head_ref = NULL;
7869 int ch;
7870 struct got_update_progress_arg upa;
7872 while ((ch = getopt(argc, argv, "")) != -1) {
7873 switch (ch) {
7874 default:
7875 usage_cherrypick();
7876 /* NOTREACHED */
7880 argc -= optind;
7881 argv += optind;
7883 #ifndef PROFILE
7884 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7885 "unveil", NULL) == -1)
7886 err(1, "pledge");
7887 #endif
7888 if (argc != 1)
7889 usage_cherrypick();
7891 cwd = getcwd(NULL, 0);
7892 if (cwd == NULL) {
7893 error = got_error_from_errno("getcwd");
7894 goto done;
7896 error = got_worktree_open(&worktree, cwd);
7897 if (error) {
7898 if (error->code == GOT_ERR_NOT_WORKTREE)
7899 error = wrap_not_worktree_error(error, "cherrypick",
7900 cwd);
7901 goto done;
7904 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7905 NULL);
7906 if (error != NULL)
7907 goto done;
7909 error = apply_unveil(got_repo_get_path(repo), 0,
7910 got_worktree_get_root_path(worktree));
7911 if (error)
7912 goto done;
7914 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7915 GOT_OBJ_TYPE_COMMIT, repo);
7916 if (error != NULL) {
7917 struct got_reference *ref;
7918 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7919 goto done;
7920 error = got_ref_open(&ref, repo, argv[0], 0);
7921 if (error != NULL)
7922 goto done;
7923 error = got_ref_resolve(&commit_id, repo, ref);
7924 got_ref_close(ref);
7925 if (error != NULL)
7926 goto done;
7928 error = got_object_id_str(&commit_id_str, commit_id);
7929 if (error)
7930 goto done;
7932 error = got_ref_open(&head_ref, repo,
7933 got_worktree_get_head_ref_name(worktree), 0);
7934 if (error != NULL)
7935 goto done;
7937 error = check_same_branch(commit_id, head_ref, NULL, repo);
7938 if (error) {
7939 if (error->code != GOT_ERR_ANCESTRY)
7940 goto done;
7941 error = NULL;
7942 } else {
7943 error = got_error(GOT_ERR_SAME_BRANCH);
7944 goto done;
7947 error = got_object_open_as_commit(&commit, repo, commit_id);
7948 if (error)
7949 goto done;
7950 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7951 memset(&upa, 0, sizeof(upa));
7952 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7953 commit_id, repo, update_progress, &upa, check_cancelled,
7954 NULL);
7955 if (error != NULL)
7956 goto done;
7958 if (upa.did_something)
7959 printf("Merged commit %s\n", commit_id_str);
7960 print_update_progress_stats(&upa);
7961 done:
7962 if (commit)
7963 got_object_commit_close(commit);
7964 free(commit_id_str);
7965 if (head_ref)
7966 got_ref_close(head_ref);
7967 if (worktree)
7968 got_worktree_close(worktree);
7969 if (repo) {
7970 const struct got_error *close_err = got_repo_close(repo);
7971 if (error == NULL)
7972 error = close_err;
7974 return error;
7977 __dead static void
7978 usage_backout(void)
7980 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7981 exit(1);
7984 static const struct got_error *
7985 cmd_backout(int argc, char *argv[])
7987 const struct got_error *error = NULL;
7988 struct got_worktree *worktree = NULL;
7989 struct got_repository *repo = NULL;
7990 char *cwd = NULL, *commit_id_str = NULL;
7991 struct got_object_id *commit_id = NULL;
7992 struct got_commit_object *commit = NULL;
7993 struct got_object_qid *pid;
7994 struct got_reference *head_ref = NULL;
7995 int ch;
7996 struct got_update_progress_arg upa;
7998 while ((ch = getopt(argc, argv, "")) != -1) {
7999 switch (ch) {
8000 default:
8001 usage_backout();
8002 /* NOTREACHED */
8006 argc -= optind;
8007 argv += optind;
8009 #ifndef PROFILE
8010 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8011 "unveil", NULL) == -1)
8012 err(1, "pledge");
8013 #endif
8014 if (argc != 1)
8015 usage_backout();
8017 cwd = getcwd(NULL, 0);
8018 if (cwd == NULL) {
8019 error = got_error_from_errno("getcwd");
8020 goto done;
8022 error = got_worktree_open(&worktree, cwd);
8023 if (error) {
8024 if (error->code == GOT_ERR_NOT_WORKTREE)
8025 error = wrap_not_worktree_error(error, "backout", cwd);
8026 goto done;
8029 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8030 NULL);
8031 if (error != NULL)
8032 goto done;
8034 error = apply_unveil(got_repo_get_path(repo), 0,
8035 got_worktree_get_root_path(worktree));
8036 if (error)
8037 goto done;
8039 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8040 GOT_OBJ_TYPE_COMMIT, repo);
8041 if (error != NULL) {
8042 struct got_reference *ref;
8043 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8044 goto done;
8045 error = got_ref_open(&ref, repo, argv[0], 0);
8046 if (error != NULL)
8047 goto done;
8048 error = got_ref_resolve(&commit_id, repo, ref);
8049 got_ref_close(ref);
8050 if (error != NULL)
8051 goto done;
8053 error = got_object_id_str(&commit_id_str, commit_id);
8054 if (error)
8055 goto done;
8057 error = got_ref_open(&head_ref, repo,
8058 got_worktree_get_head_ref_name(worktree), 0);
8059 if (error != NULL)
8060 goto done;
8062 error = check_same_branch(commit_id, head_ref, NULL, repo);
8063 if (error)
8064 goto done;
8066 error = got_object_open_as_commit(&commit, repo, commit_id);
8067 if (error)
8068 goto done;
8069 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8070 if (pid == NULL) {
8071 error = got_error(GOT_ERR_ROOT_COMMIT);
8072 goto done;
8075 memset(&upa, 0, sizeof(upa));
8076 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8077 update_progress, &upa, check_cancelled, NULL);
8078 if (error != NULL)
8079 goto done;
8081 if (upa.did_something)
8082 printf("Backed out commit %s\n", commit_id_str);
8083 print_update_progress_stats(&upa);
8084 done:
8085 if (commit)
8086 got_object_commit_close(commit);
8087 free(commit_id_str);
8088 if (head_ref)
8089 got_ref_close(head_ref);
8090 if (worktree)
8091 got_worktree_close(worktree);
8092 if (repo) {
8093 const struct got_error *close_err = got_repo_close(repo);
8094 if (error == NULL)
8095 error = close_err;
8097 return error;
8100 __dead static void
8101 usage_rebase(void)
8103 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8104 getprogname());
8105 exit(1);
8108 void
8109 trim_logmsg(char *logmsg, int limit)
8111 char *nl;
8112 size_t len;
8114 len = strlen(logmsg);
8115 if (len > limit)
8116 len = limit;
8117 logmsg[len] = '\0';
8118 nl = strchr(logmsg, '\n');
8119 if (nl)
8120 *nl = '\0';
8123 static const struct got_error *
8124 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8126 const struct got_error *err;
8127 char *logmsg0 = NULL;
8128 const char *s;
8130 err = got_object_commit_get_logmsg(&logmsg0, commit);
8131 if (err)
8132 return err;
8134 s = logmsg0;
8135 while (isspace((unsigned char)s[0]))
8136 s++;
8138 *logmsg = strdup(s);
8139 if (*logmsg == NULL) {
8140 err = got_error_from_errno("strdup");
8141 goto done;
8144 trim_logmsg(*logmsg, limit);
8145 done:
8146 free(logmsg0);
8147 return err;
8150 static const struct got_error *
8151 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8153 const struct got_error *err;
8154 struct got_commit_object *commit = NULL;
8155 char *id_str = NULL, *logmsg = NULL;
8157 err = got_object_open_as_commit(&commit, repo, id);
8158 if (err)
8159 return err;
8161 err = got_object_id_str(&id_str, id);
8162 if (err)
8163 goto done;
8165 id_str[12] = '\0';
8167 err = get_short_logmsg(&logmsg, 42, commit);
8168 if (err)
8169 goto done;
8171 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8172 done:
8173 free(id_str);
8174 got_object_commit_close(commit);
8175 free(logmsg);
8176 return err;
8179 static const struct got_error *
8180 show_rebase_progress(struct got_commit_object *commit,
8181 struct got_object_id *old_id, struct got_object_id *new_id)
8183 const struct got_error *err;
8184 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8186 err = got_object_id_str(&old_id_str, old_id);
8187 if (err)
8188 goto done;
8190 if (new_id) {
8191 err = got_object_id_str(&new_id_str, new_id);
8192 if (err)
8193 goto done;
8196 old_id_str[12] = '\0';
8197 if (new_id_str)
8198 new_id_str[12] = '\0';
8200 err = get_short_logmsg(&logmsg, 42, commit);
8201 if (err)
8202 goto done;
8204 printf("%s -> %s: %s\n", old_id_str,
8205 new_id_str ? new_id_str : "no-op change", logmsg);
8206 done:
8207 free(old_id_str);
8208 free(new_id_str);
8209 free(logmsg);
8210 return err;
8213 static const struct got_error *
8214 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8215 struct got_reference *branch, struct got_reference *new_base_branch,
8216 struct got_reference *tmp_branch, struct got_repository *repo,
8217 int create_backup)
8219 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8220 return got_worktree_rebase_complete(worktree, fileindex,
8221 new_base_branch, tmp_branch, branch, repo, create_backup);
8224 static const struct got_error *
8225 rebase_commit(struct got_pathlist_head *merged_paths,
8226 struct got_worktree *worktree, struct got_fileindex *fileindex,
8227 struct got_reference *tmp_branch,
8228 struct got_object_id *commit_id, struct got_repository *repo)
8230 const struct got_error *error;
8231 struct got_commit_object *commit;
8232 struct got_object_id *new_commit_id;
8234 error = got_object_open_as_commit(&commit, repo, commit_id);
8235 if (error)
8236 return error;
8238 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8239 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8240 if (error) {
8241 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8242 goto done;
8243 error = show_rebase_progress(commit, commit_id, NULL);
8244 } else {
8245 error = show_rebase_progress(commit, commit_id, new_commit_id);
8246 free(new_commit_id);
8248 done:
8249 got_object_commit_close(commit);
8250 return error;
8253 struct check_path_prefix_arg {
8254 const char *path_prefix;
8255 size_t len;
8256 int errcode;
8259 static const struct got_error *
8260 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8261 struct got_blob_object *blob2, struct got_object_id *id1,
8262 struct got_object_id *id2, const char *path1, const char *path2,
8263 mode_t mode1, mode_t mode2, struct got_repository *repo)
8265 struct check_path_prefix_arg *a = arg;
8267 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8268 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8269 return got_error(a->errcode);
8271 return NULL;
8274 static const struct got_error *
8275 check_path_prefix(struct got_object_id *parent_id,
8276 struct got_object_id *commit_id, const char *path_prefix,
8277 int errcode, struct got_repository *repo)
8279 const struct got_error *err;
8280 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8281 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8282 struct check_path_prefix_arg cpp_arg;
8284 if (got_path_is_root_dir(path_prefix))
8285 return NULL;
8287 err = got_object_open_as_commit(&commit, repo, commit_id);
8288 if (err)
8289 goto done;
8291 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8292 if (err)
8293 goto done;
8295 err = got_object_open_as_tree(&tree1, repo,
8296 got_object_commit_get_tree_id(parent_commit));
8297 if (err)
8298 goto done;
8300 err = got_object_open_as_tree(&tree2, repo,
8301 got_object_commit_get_tree_id(commit));
8302 if (err)
8303 goto done;
8305 cpp_arg.path_prefix = path_prefix;
8306 while (cpp_arg.path_prefix[0] == '/')
8307 cpp_arg.path_prefix++;
8308 cpp_arg.len = strlen(cpp_arg.path_prefix);
8309 cpp_arg.errcode = errcode;
8310 err = got_diff_tree(tree1, tree2, "", "", repo,
8311 check_path_prefix_in_diff, &cpp_arg, 0);
8312 done:
8313 if (tree1)
8314 got_object_tree_close(tree1);
8315 if (tree2)
8316 got_object_tree_close(tree2);
8317 if (commit)
8318 got_object_commit_close(commit);
8319 if (parent_commit)
8320 got_object_commit_close(parent_commit);
8321 return err;
8324 static const struct got_error *
8325 collect_commits(struct got_object_id_queue *commits,
8326 struct got_object_id *initial_commit_id,
8327 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8328 const char *path_prefix, int path_prefix_errcode,
8329 struct got_repository *repo)
8331 const struct got_error *err = NULL;
8332 struct got_commit_graph *graph = NULL;
8333 struct got_object_id *parent_id = NULL;
8334 struct got_object_qid *qid;
8335 struct got_object_id *commit_id = initial_commit_id;
8337 err = got_commit_graph_open(&graph, "/", 1);
8338 if (err)
8339 return err;
8341 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8342 check_cancelled, NULL);
8343 if (err)
8344 goto done;
8345 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8346 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8347 check_cancelled, NULL);
8348 if (err) {
8349 if (err->code == GOT_ERR_ITER_COMPLETED) {
8350 err = got_error_msg(GOT_ERR_ANCESTRY,
8351 "ran out of commits to rebase before "
8352 "youngest common ancestor commit has "
8353 "been reached?!?");
8355 goto done;
8356 } else {
8357 err = check_path_prefix(parent_id, commit_id,
8358 path_prefix, path_prefix_errcode, repo);
8359 if (err)
8360 goto done;
8362 err = got_object_qid_alloc(&qid, commit_id);
8363 if (err)
8364 goto done;
8365 STAILQ_INSERT_HEAD(commits, qid, entry);
8366 commit_id = parent_id;
8369 done:
8370 got_commit_graph_close(graph);
8371 return err;
8374 static const struct got_error *
8375 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8377 const struct got_error *err = NULL;
8378 time_t committer_time;
8379 struct tm tm;
8380 char datebuf[11]; /* YYYY-MM-DD + NUL */
8381 char *author0 = NULL, *author, *smallerthan;
8382 char *logmsg0 = NULL, *logmsg, *newline;
8384 committer_time = got_object_commit_get_committer_time(commit);
8385 if (localtime_r(&committer_time, &tm) == NULL)
8386 return got_error_from_errno("localtime_r");
8387 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8388 return got_error(GOT_ERR_NO_SPACE);
8390 author0 = strdup(got_object_commit_get_author(commit));
8391 if (author0 == NULL)
8392 return got_error_from_errno("strdup");
8393 author = author0;
8394 smallerthan = strchr(author, '<');
8395 if (smallerthan && smallerthan[1] != '\0')
8396 author = smallerthan + 1;
8397 author[strcspn(author, "@>")] = '\0';
8399 err = got_object_commit_get_logmsg(&logmsg0, commit);
8400 if (err)
8401 goto done;
8402 logmsg = logmsg0;
8403 while (*logmsg == '\n')
8404 logmsg++;
8405 newline = strchr(logmsg, '\n');
8406 if (newline)
8407 *newline = '\0';
8409 if (asprintf(brief_str, "%s %s %s",
8410 datebuf, author, logmsg) == -1)
8411 err = got_error_from_errno("asprintf");
8412 done:
8413 free(author0);
8414 free(logmsg0);
8415 return err;
8418 static const struct got_error *
8419 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8420 struct got_repository *repo)
8422 const struct got_error *err;
8423 char *id_str;
8425 err = got_object_id_str(&id_str, id);
8426 if (err)
8427 return err;
8429 err = got_ref_delete(ref, repo);
8430 if (err)
8431 goto done;
8433 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8434 done:
8435 free(id_str);
8436 return err;
8439 static const struct got_error *
8440 print_backup_ref(const char *branch_name, const char *new_id_str,
8441 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8442 struct got_reflist_object_id_map *refs_idmap,
8443 struct got_repository *repo)
8445 const struct got_error *err = NULL;
8446 struct got_reflist_head *refs;
8447 char *refs_str = NULL;
8448 struct got_object_id *new_commit_id = NULL;
8449 struct got_commit_object *new_commit = NULL;
8450 char *new_commit_brief_str = NULL;
8451 struct got_object_id *yca_id = NULL;
8452 struct got_commit_object *yca_commit = NULL;
8453 char *yca_id_str = NULL, *yca_brief_str = NULL;
8454 char *custom_refs_str;
8456 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8457 return got_error_from_errno("asprintf");
8459 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8460 0, 0, refs_idmap, custom_refs_str);
8461 if (err)
8462 goto done;
8464 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8465 if (err)
8466 goto done;
8468 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8469 if (refs) {
8470 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8471 if (err)
8472 goto done;
8475 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8476 if (err)
8477 goto done;
8479 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8480 if (err)
8481 goto done;
8483 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8484 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8485 if (err)
8486 goto done;
8488 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8489 refs_str ? " (" : "", refs_str ? refs_str : "",
8490 refs_str ? ")" : "", new_commit_brief_str);
8491 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8492 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8493 free(refs_str);
8494 refs_str = NULL;
8496 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8497 if (err)
8498 goto done;
8500 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8501 if (err)
8502 goto done;
8504 err = got_object_id_str(&yca_id_str, yca_id);
8505 if (err)
8506 goto done;
8508 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8509 if (refs) {
8510 err = build_refs_str(&refs_str, refs, yca_id, repo);
8511 if (err)
8512 goto done;
8514 printf("history forked at %s%s%s%s\n %s\n",
8515 yca_id_str,
8516 refs_str ? " (" : "", refs_str ? refs_str : "",
8517 refs_str ? ")" : "", yca_brief_str);
8519 done:
8520 free(custom_refs_str);
8521 free(new_commit_id);
8522 free(refs_str);
8523 free(yca_id);
8524 free(yca_id_str);
8525 free(yca_brief_str);
8526 if (new_commit)
8527 got_object_commit_close(new_commit);
8528 if (yca_commit)
8529 got_object_commit_close(yca_commit);
8531 return NULL;
8534 static const struct got_error *
8535 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8536 int delete, struct got_repository *repo)
8538 const struct got_error *err;
8539 struct got_reflist_head refs, backup_refs;
8540 struct got_reflist_entry *re;
8541 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8542 struct got_object_id *old_commit_id = NULL;
8543 char *branch_name = NULL;
8544 struct got_commit_object *old_commit = NULL;
8545 struct got_reflist_object_id_map *refs_idmap = NULL;
8546 int wanted_branch_found = 0;
8548 TAILQ_INIT(&refs);
8549 TAILQ_INIT(&backup_refs);
8551 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8552 if (err)
8553 return err;
8555 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8556 if (err)
8557 goto done;
8559 if (wanted_branch_name) {
8560 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8561 wanted_branch_name += 11;
8564 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8565 got_ref_cmp_by_commit_timestamp_descending, repo);
8566 if (err)
8567 goto done;
8569 TAILQ_FOREACH(re, &backup_refs, entry) {
8570 const char *refname = got_ref_get_name(re->ref);
8571 char *slash;
8573 err = check_cancelled(NULL);
8574 if (err)
8575 break;
8577 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8578 if (err)
8579 break;
8581 err = got_object_open_as_commit(&old_commit, repo,
8582 old_commit_id);
8583 if (err)
8584 break;
8586 if (strncmp(backup_ref_prefix, refname,
8587 backup_ref_prefix_len) == 0)
8588 refname += backup_ref_prefix_len;
8590 while (refname[0] == '/')
8591 refname++;
8593 branch_name = strdup(refname);
8594 if (branch_name == NULL) {
8595 err = got_error_from_errno("strdup");
8596 break;
8598 slash = strrchr(branch_name, '/');
8599 if (slash) {
8600 *slash = '\0';
8601 refname += strlen(branch_name) + 1;
8604 if (wanted_branch_name == NULL ||
8605 strcmp(wanted_branch_name, branch_name) == 0) {
8606 wanted_branch_found = 1;
8607 if (delete) {
8608 err = delete_backup_ref(re->ref,
8609 old_commit_id, repo);
8610 } else {
8611 err = print_backup_ref(branch_name, refname,
8612 old_commit_id, old_commit, refs_idmap,
8613 repo);
8615 if (err)
8616 break;
8619 free(old_commit_id);
8620 old_commit_id = NULL;
8621 free(branch_name);
8622 branch_name = NULL;
8623 got_object_commit_close(old_commit);
8624 old_commit = NULL;
8627 if (wanted_branch_name && !wanted_branch_found) {
8628 err = got_error_fmt(GOT_ERR_NOT_REF,
8629 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8631 done:
8632 if (refs_idmap)
8633 got_reflist_object_id_map_free(refs_idmap);
8634 got_ref_list_free(&refs);
8635 got_ref_list_free(&backup_refs);
8636 free(old_commit_id);
8637 free(branch_name);
8638 if (old_commit)
8639 got_object_commit_close(old_commit);
8640 return err;
8643 static const struct got_error *
8644 cmd_rebase(int argc, char *argv[])
8646 const struct got_error *error = NULL;
8647 struct got_worktree *worktree = NULL;
8648 struct got_repository *repo = NULL;
8649 struct got_fileindex *fileindex = NULL;
8650 char *cwd = NULL;
8651 struct got_reference *branch = NULL;
8652 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8653 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8654 struct got_object_id *resume_commit_id = NULL;
8655 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8656 struct got_commit_object *commit = NULL;
8657 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8658 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8659 int delete_backups = 0;
8660 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8661 struct got_object_id_queue commits;
8662 struct got_pathlist_head merged_paths;
8663 const struct got_object_id_queue *parent_ids;
8664 struct got_object_qid *qid, *pid;
8666 STAILQ_INIT(&commits);
8667 TAILQ_INIT(&merged_paths);
8669 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8670 switch (ch) {
8671 case 'a':
8672 abort_rebase = 1;
8673 break;
8674 case 'c':
8675 continue_rebase = 1;
8676 break;
8677 case 'l':
8678 list_backups = 1;
8679 break;
8680 case 'X':
8681 delete_backups = 1;
8682 break;
8683 default:
8684 usage_rebase();
8685 /* NOTREACHED */
8689 argc -= optind;
8690 argv += optind;
8692 #ifndef PROFILE
8693 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8694 "unveil", NULL) == -1)
8695 err(1, "pledge");
8696 #endif
8697 if (list_backups) {
8698 if (abort_rebase)
8699 option_conflict('l', 'a');
8700 if (continue_rebase)
8701 option_conflict('l', 'c');
8702 if (delete_backups)
8703 option_conflict('l', 'X');
8704 if (argc != 0 && argc != 1)
8705 usage_rebase();
8706 } else if (delete_backups) {
8707 if (abort_rebase)
8708 option_conflict('X', 'a');
8709 if (continue_rebase)
8710 option_conflict('X', 'c');
8711 if (list_backups)
8712 option_conflict('l', 'X');
8713 if (argc != 0 && argc != 1)
8714 usage_rebase();
8715 } else {
8716 if (abort_rebase && continue_rebase)
8717 usage_rebase();
8718 else if (abort_rebase || continue_rebase) {
8719 if (argc != 0)
8720 usage_rebase();
8721 } else if (argc != 1)
8722 usage_rebase();
8725 cwd = getcwd(NULL, 0);
8726 if (cwd == NULL) {
8727 error = got_error_from_errno("getcwd");
8728 goto done;
8730 error = got_worktree_open(&worktree, cwd);
8731 if (error) {
8732 if (list_backups || delete_backups) {
8733 if (error->code != GOT_ERR_NOT_WORKTREE)
8734 goto done;
8735 } else {
8736 if (error->code == GOT_ERR_NOT_WORKTREE)
8737 error = wrap_not_worktree_error(error,
8738 "rebase", cwd);
8739 goto done;
8743 error = got_repo_open(&repo,
8744 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8745 if (error != NULL)
8746 goto done;
8748 error = apply_unveil(got_repo_get_path(repo), 0,
8749 worktree ? got_worktree_get_root_path(worktree) : NULL);
8750 if (error)
8751 goto done;
8753 if (list_backups || delete_backups) {
8754 error = process_backup_refs(
8755 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8756 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8757 goto done; /* nothing else to do */
8760 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8761 worktree);
8762 if (error)
8763 goto done;
8764 if (histedit_in_progress) {
8765 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8766 goto done;
8769 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8770 if (error)
8771 goto done;
8773 if (abort_rebase) {
8774 struct got_update_progress_arg upa;
8775 if (!rebase_in_progress) {
8776 error = got_error(GOT_ERR_NOT_REBASING);
8777 goto done;
8779 error = got_worktree_rebase_continue(&resume_commit_id,
8780 &new_base_branch, &tmp_branch, &branch, &fileindex,
8781 worktree, repo);
8782 if (error)
8783 goto done;
8784 printf("Switching work tree to %s\n",
8785 got_ref_get_symref_target(new_base_branch));
8786 memset(&upa, 0, sizeof(upa));
8787 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8788 new_base_branch, update_progress, &upa);
8789 if (error)
8790 goto done;
8791 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8792 print_update_progress_stats(&upa);
8793 goto done; /* nothing else to do */
8796 if (continue_rebase) {
8797 if (!rebase_in_progress) {
8798 error = got_error(GOT_ERR_NOT_REBASING);
8799 goto done;
8801 error = got_worktree_rebase_continue(&resume_commit_id,
8802 &new_base_branch, &tmp_branch, &branch, &fileindex,
8803 worktree, repo);
8804 if (error)
8805 goto done;
8807 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8808 resume_commit_id, repo);
8809 if (error)
8810 goto done;
8812 yca_id = got_object_id_dup(resume_commit_id);
8813 if (yca_id == NULL) {
8814 error = got_error_from_errno("got_object_id_dup");
8815 goto done;
8817 } else {
8818 error = got_ref_open(&branch, repo, argv[0], 0);
8819 if (error != NULL)
8820 goto done;
8823 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8824 if (error)
8825 goto done;
8827 if (!continue_rebase) {
8828 struct got_object_id *base_commit_id;
8830 base_commit_id = got_worktree_get_base_commit_id(worktree);
8831 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8832 base_commit_id, branch_head_commit_id, repo,
8833 check_cancelled, NULL);
8834 if (error)
8835 goto done;
8836 if (yca_id == NULL) {
8837 error = got_error_msg(GOT_ERR_ANCESTRY,
8838 "specified branch shares no common ancestry "
8839 "with work tree's branch");
8840 goto done;
8843 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8844 if (error) {
8845 if (error->code != GOT_ERR_ANCESTRY)
8846 goto done;
8847 error = NULL;
8848 } else {
8849 static char msg[128];
8850 snprintf(msg, sizeof(msg),
8851 "%s is already based on %s",
8852 got_ref_get_name(branch),
8853 got_worktree_get_head_ref_name(worktree));
8854 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8855 goto done;
8857 error = got_worktree_rebase_prepare(&new_base_branch,
8858 &tmp_branch, &fileindex, worktree, branch, repo);
8859 if (error)
8860 goto done;
8863 commit_id = branch_head_commit_id;
8864 error = got_object_open_as_commit(&commit, repo, commit_id);
8865 if (error)
8866 goto done;
8868 parent_ids = got_object_commit_get_parent_ids(commit);
8869 pid = STAILQ_FIRST(parent_ids);
8870 if (pid == NULL) {
8871 if (!continue_rebase) {
8872 struct got_update_progress_arg upa;
8873 memset(&upa, 0, sizeof(upa));
8874 error = got_worktree_rebase_abort(worktree, fileindex,
8875 repo, new_base_branch, update_progress, &upa);
8876 if (error)
8877 goto done;
8878 printf("Rebase of %s aborted\n",
8879 got_ref_get_name(branch));
8880 print_update_progress_stats(&upa);
8883 error = got_error(GOT_ERR_EMPTY_REBASE);
8884 goto done;
8886 error = collect_commits(&commits, commit_id, pid->id,
8887 yca_id, got_worktree_get_path_prefix(worktree),
8888 GOT_ERR_REBASE_PATH, repo);
8889 got_object_commit_close(commit);
8890 commit = NULL;
8891 if (error)
8892 goto done;
8894 if (STAILQ_EMPTY(&commits)) {
8895 if (continue_rebase) {
8896 error = rebase_complete(worktree, fileindex,
8897 branch, new_base_branch, tmp_branch, repo,
8898 create_backup);
8899 goto done;
8900 } else {
8901 /* Fast-forward the reference of the branch. */
8902 struct got_object_id *new_head_commit_id;
8903 char *id_str;
8904 error = got_ref_resolve(&new_head_commit_id, repo,
8905 new_base_branch);
8906 if (error)
8907 goto done;
8908 error = got_object_id_str(&id_str, new_head_commit_id);
8909 printf("Forwarding %s to commit %s\n",
8910 got_ref_get_name(branch), id_str);
8911 free(id_str);
8912 error = got_ref_change_ref(branch,
8913 new_head_commit_id);
8914 if (error)
8915 goto done;
8916 /* No backup needed since objects did not change. */
8917 create_backup = 0;
8921 pid = NULL;
8922 STAILQ_FOREACH(qid, &commits, entry) {
8923 struct got_update_progress_arg upa;
8925 commit_id = qid->id;
8926 parent_id = pid ? pid->id : yca_id;
8927 pid = qid;
8929 memset(&upa, 0, sizeof(upa));
8930 error = got_worktree_rebase_merge_files(&merged_paths,
8931 worktree, fileindex, parent_id, commit_id, repo,
8932 update_progress, &upa, check_cancelled, NULL);
8933 if (error)
8934 goto done;
8936 print_update_progress_stats(&upa);
8937 if (upa.conflicts > 0)
8938 rebase_status = GOT_STATUS_CONFLICT;
8940 if (rebase_status == GOT_STATUS_CONFLICT) {
8941 error = show_rebase_merge_conflict(qid->id, repo);
8942 if (error)
8943 goto done;
8944 got_worktree_rebase_pathlist_free(&merged_paths);
8945 break;
8948 error = rebase_commit(&merged_paths, worktree, fileindex,
8949 tmp_branch, commit_id, repo);
8950 got_worktree_rebase_pathlist_free(&merged_paths);
8951 if (error)
8952 goto done;
8955 if (rebase_status == GOT_STATUS_CONFLICT) {
8956 error = got_worktree_rebase_postpone(worktree, fileindex);
8957 if (error)
8958 goto done;
8959 error = got_error_msg(GOT_ERR_CONFLICTS,
8960 "conflicts must be resolved before rebasing can continue");
8961 } else
8962 error = rebase_complete(worktree, fileindex, branch,
8963 new_base_branch, tmp_branch, repo, create_backup);
8964 done:
8965 got_object_id_queue_free(&commits);
8966 free(branch_head_commit_id);
8967 free(resume_commit_id);
8968 free(yca_id);
8969 if (commit)
8970 got_object_commit_close(commit);
8971 if (branch)
8972 got_ref_close(branch);
8973 if (new_base_branch)
8974 got_ref_close(new_base_branch);
8975 if (tmp_branch)
8976 got_ref_close(tmp_branch);
8977 if (worktree)
8978 got_worktree_close(worktree);
8979 if (repo) {
8980 const struct got_error *close_err = got_repo_close(repo);
8981 if (error == NULL)
8982 error = close_err;
8984 return error;
8987 __dead static void
8988 usage_histedit(void)
8990 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8991 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
8992 getprogname());
8993 exit(1);
8996 #define GOT_HISTEDIT_PICK 'p'
8997 #define GOT_HISTEDIT_EDIT 'e'
8998 #define GOT_HISTEDIT_FOLD 'f'
8999 #define GOT_HISTEDIT_DROP 'd'
9000 #define GOT_HISTEDIT_MESG 'm'
9002 static struct got_histedit_cmd {
9003 unsigned char code;
9004 const char *name;
9005 const char *desc;
9006 } got_histedit_cmds[] = {
9007 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9008 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9009 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9010 "be used" },
9011 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9012 { GOT_HISTEDIT_MESG, "mesg",
9013 "single-line log message for commit above (open editor if empty)" },
9016 struct got_histedit_list_entry {
9017 TAILQ_ENTRY(got_histedit_list_entry) entry;
9018 struct got_object_id *commit_id;
9019 const struct got_histedit_cmd *cmd;
9020 char *logmsg;
9022 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9024 static const struct got_error *
9025 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9026 FILE *f, struct got_repository *repo)
9028 const struct got_error *err = NULL;
9029 char *logmsg = NULL, *id_str = NULL;
9030 struct got_commit_object *commit = NULL;
9031 int n;
9033 err = got_object_open_as_commit(&commit, repo, commit_id);
9034 if (err)
9035 goto done;
9037 err = get_short_logmsg(&logmsg, 34, commit);
9038 if (err)
9039 goto done;
9041 err = got_object_id_str(&id_str, commit_id);
9042 if (err)
9043 goto done;
9045 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9046 if (n < 0)
9047 err = got_ferror(f, GOT_ERR_IO);
9048 done:
9049 if (commit)
9050 got_object_commit_close(commit);
9051 free(id_str);
9052 free(logmsg);
9053 return err;
9056 static const struct got_error *
9057 histedit_write_commit_list(struct got_object_id_queue *commits,
9058 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9060 const struct got_error *err = NULL;
9061 struct got_object_qid *qid;
9062 const char *histedit_cmd = NULL;
9064 if (STAILQ_EMPTY(commits))
9065 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9067 STAILQ_FOREACH(qid, commits, entry) {
9068 histedit_cmd = got_histedit_cmds[0].name;
9069 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9070 histedit_cmd = "fold";
9071 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9072 if (err)
9073 break;
9074 if (edit_logmsg_only) {
9075 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9076 if (n < 0) {
9077 err = got_ferror(f, GOT_ERR_IO);
9078 break;
9083 return err;
9086 static const struct got_error *
9087 write_cmd_list(FILE *f, const char *branch_name,
9088 struct got_object_id_queue *commits)
9090 const struct got_error *err = NULL;
9091 size_t i;
9092 int n;
9093 char *id_str;
9094 struct got_object_qid *qid;
9096 qid = STAILQ_FIRST(commits);
9097 err = got_object_id_str(&id_str, qid->id);
9098 if (err)
9099 return err;
9101 n = fprintf(f,
9102 "# Editing the history of branch '%s' starting at\n"
9103 "# commit %s\n"
9104 "# Commits will be processed in order from top to "
9105 "bottom of this file.\n", branch_name, id_str);
9106 if (n < 0) {
9107 err = got_ferror(f, GOT_ERR_IO);
9108 goto done;
9111 n = fprintf(f, "# Available histedit commands:\n");
9112 if (n < 0) {
9113 err = got_ferror(f, GOT_ERR_IO);
9114 goto done;
9117 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9118 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9119 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9120 cmd->desc);
9121 if (n < 0) {
9122 err = got_ferror(f, GOT_ERR_IO);
9123 break;
9126 done:
9127 free(id_str);
9128 return err;
9131 static const struct got_error *
9132 histedit_syntax_error(int lineno)
9134 static char msg[42];
9135 int ret;
9137 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9138 lineno);
9139 if (ret == -1 || ret >= sizeof(msg))
9140 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9142 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9145 static const struct got_error *
9146 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9147 char *logmsg, struct got_repository *repo)
9149 const struct got_error *err;
9150 struct got_commit_object *folded_commit = NULL;
9151 char *id_str, *folded_logmsg = NULL;
9153 err = got_object_id_str(&id_str, hle->commit_id);
9154 if (err)
9155 return err;
9157 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9158 if (err)
9159 goto done;
9161 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9162 if (err)
9163 goto done;
9164 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9165 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9166 folded_logmsg) == -1) {
9167 err = got_error_from_errno("asprintf");
9169 done:
9170 if (folded_commit)
9171 got_object_commit_close(folded_commit);
9172 free(id_str);
9173 free(folded_logmsg);
9174 return err;
9177 static struct got_histedit_list_entry *
9178 get_folded_commits(struct got_histedit_list_entry *hle)
9180 struct got_histedit_list_entry *prev, *folded = NULL;
9182 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9183 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9184 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9185 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9186 folded = prev;
9187 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9190 return folded;
9193 static const struct got_error *
9194 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9195 struct got_repository *repo)
9197 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9198 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9199 const struct got_error *err = NULL;
9200 struct got_commit_object *commit = NULL;
9201 int logmsg_len;
9202 int fd;
9203 struct got_histedit_list_entry *folded = NULL;
9205 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9206 if (err)
9207 return err;
9209 folded = get_folded_commits(hle);
9210 if (folded) {
9211 while (folded != hle) {
9212 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9213 folded = TAILQ_NEXT(folded, entry);
9214 continue;
9216 err = append_folded_commit_msg(&new_msg, folded,
9217 logmsg, repo);
9218 if (err)
9219 goto done;
9220 free(logmsg);
9221 logmsg = new_msg;
9222 folded = TAILQ_NEXT(folded, entry);
9226 err = got_object_id_str(&id_str, hle->commit_id);
9227 if (err)
9228 goto done;
9229 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9230 if (err)
9231 goto done;
9232 logmsg_len = asprintf(&new_msg,
9233 "%s\n# original log message of commit %s: %s",
9234 logmsg ? logmsg : "", id_str, orig_logmsg);
9235 if (logmsg_len == -1) {
9236 err = got_error_from_errno("asprintf");
9237 goto done;
9239 free(logmsg);
9240 logmsg = new_msg;
9242 err = got_object_id_str(&id_str, hle->commit_id);
9243 if (err)
9244 goto done;
9246 err = got_opentemp_named_fd(&logmsg_path, &fd,
9247 GOT_TMPDIR_STR "/got-logmsg");
9248 if (err)
9249 goto done;
9251 write(fd, logmsg, logmsg_len);
9252 close(fd);
9254 err = get_editor(&editor);
9255 if (err)
9256 goto done;
9258 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9259 logmsg_len, 0);
9260 if (err) {
9261 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9262 goto done;
9263 err = NULL;
9264 hle->logmsg = strdup(new_msg);
9265 if (hle->logmsg == NULL)
9266 err = got_error_from_errno("strdup");
9268 done:
9269 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9270 err = got_error_from_errno2("unlink", logmsg_path);
9271 free(logmsg_path);
9272 free(logmsg);
9273 free(orig_logmsg);
9274 free(editor);
9275 if (commit)
9276 got_object_commit_close(commit);
9277 return err;
9280 static const struct got_error *
9281 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9282 FILE *f, struct got_repository *repo)
9284 const struct got_error *err = NULL;
9285 char *line = NULL, *p, *end;
9286 size_t i, size;
9287 ssize_t len;
9288 int lineno = 0;
9289 const struct got_histedit_cmd *cmd;
9290 struct got_object_id *commit_id = NULL;
9291 struct got_histedit_list_entry *hle = NULL;
9293 for (;;) {
9294 len = getline(&line, &size, f);
9295 if (len == -1) {
9296 const struct got_error *getline_err;
9297 if (feof(f))
9298 break;
9299 getline_err = got_error_from_errno("getline");
9300 err = got_ferror(f, getline_err->code);
9301 break;
9303 lineno++;
9304 p = line;
9305 while (isspace((unsigned char)p[0]))
9306 p++;
9307 if (p[0] == '#' || p[0] == '\0') {
9308 free(line);
9309 line = NULL;
9310 continue;
9312 cmd = NULL;
9313 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9314 cmd = &got_histedit_cmds[i];
9315 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9316 isspace((unsigned char)p[strlen(cmd->name)])) {
9317 p += strlen(cmd->name);
9318 break;
9320 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9321 p++;
9322 break;
9325 if (i == nitems(got_histedit_cmds)) {
9326 err = histedit_syntax_error(lineno);
9327 break;
9329 while (isspace((unsigned char)p[0]))
9330 p++;
9331 if (cmd->code == GOT_HISTEDIT_MESG) {
9332 if (hle == NULL || hle->logmsg != NULL) {
9333 err = got_error(GOT_ERR_HISTEDIT_CMD);
9334 break;
9336 if (p[0] == '\0') {
9337 err = histedit_edit_logmsg(hle, repo);
9338 if (err)
9339 break;
9340 } else {
9341 hle->logmsg = strdup(p);
9342 if (hle->logmsg == NULL) {
9343 err = got_error_from_errno("strdup");
9344 break;
9347 free(line);
9348 line = NULL;
9349 continue;
9350 } else {
9351 end = p;
9352 while (end[0] && !isspace((unsigned char)end[0]))
9353 end++;
9354 *end = '\0';
9356 err = got_object_resolve_id_str(&commit_id, repo, p);
9357 if (err) {
9358 /* override error code */
9359 err = histedit_syntax_error(lineno);
9360 break;
9363 hle = malloc(sizeof(*hle));
9364 if (hle == NULL) {
9365 err = got_error_from_errno("malloc");
9366 break;
9368 hle->cmd = cmd;
9369 hle->commit_id = commit_id;
9370 hle->logmsg = NULL;
9371 commit_id = NULL;
9372 free(line);
9373 line = NULL;
9374 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9377 free(line);
9378 free(commit_id);
9379 return err;
9382 static const struct got_error *
9383 histedit_check_script(struct got_histedit_list *histedit_cmds,
9384 struct got_object_id_queue *commits, struct got_repository *repo)
9386 const struct got_error *err = NULL;
9387 struct got_object_qid *qid;
9388 struct got_histedit_list_entry *hle;
9389 static char msg[92];
9390 char *id_str;
9392 if (TAILQ_EMPTY(histedit_cmds))
9393 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9394 "histedit script contains no commands");
9395 if (STAILQ_EMPTY(commits))
9396 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9398 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9399 struct got_histedit_list_entry *hle2;
9400 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9401 if (hle == hle2)
9402 continue;
9403 if (got_object_id_cmp(hle->commit_id,
9404 hle2->commit_id) != 0)
9405 continue;
9406 err = got_object_id_str(&id_str, hle->commit_id);
9407 if (err)
9408 return err;
9409 snprintf(msg, sizeof(msg), "commit %s is listed "
9410 "more than once in histedit script", id_str);
9411 free(id_str);
9412 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9416 STAILQ_FOREACH(qid, commits, entry) {
9417 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9418 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9419 break;
9421 if (hle == NULL) {
9422 err = got_object_id_str(&id_str, qid->id);
9423 if (err)
9424 return err;
9425 snprintf(msg, sizeof(msg),
9426 "commit %s missing from histedit script", id_str);
9427 free(id_str);
9428 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9432 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9433 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9434 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9435 "last commit in histedit script cannot be folded");
9437 return NULL;
9440 static const struct got_error *
9441 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9442 const char *path, struct got_object_id_queue *commits,
9443 struct got_repository *repo)
9445 const struct got_error *err = NULL;
9446 char *editor;
9447 FILE *f = NULL;
9449 err = get_editor(&editor);
9450 if (err)
9451 return err;
9453 if (spawn_editor(editor, path) == -1) {
9454 err = got_error_from_errno("failed spawning editor");
9455 goto done;
9458 f = fopen(path, "r");
9459 if (f == NULL) {
9460 err = got_error_from_errno("fopen");
9461 goto done;
9463 err = histedit_parse_list(histedit_cmds, f, repo);
9464 if (err)
9465 goto done;
9467 err = histedit_check_script(histedit_cmds, commits, repo);
9468 done:
9469 if (f && fclose(f) == EOF && err == NULL)
9470 err = got_error_from_errno("fclose");
9471 free(editor);
9472 return err;
9475 static const struct got_error *
9476 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9477 struct got_object_id_queue *, const char *, const char *,
9478 struct got_repository *);
9480 static const struct got_error *
9481 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9482 struct got_object_id_queue *commits, const char *branch_name,
9483 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9485 const struct got_error *err;
9486 FILE *f = NULL;
9487 char *path = NULL;
9489 err = got_opentemp_named(&path, &f, "got-histedit");
9490 if (err)
9491 return err;
9493 err = write_cmd_list(f, branch_name, commits);
9494 if (err)
9495 goto done;
9497 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9498 fold_only, repo);
9499 if (err)
9500 goto done;
9502 if (edit_logmsg_only || fold_only) {
9503 rewind(f);
9504 err = histedit_parse_list(histedit_cmds, f, repo);
9505 } else {
9506 if (fclose(f) == EOF) {
9507 err = got_error_from_errno("fclose");
9508 goto done;
9510 f = NULL;
9511 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9512 if (err) {
9513 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9514 err->code != GOT_ERR_HISTEDIT_CMD)
9515 goto done;
9516 err = histedit_edit_list_retry(histedit_cmds, err,
9517 commits, path, branch_name, repo);
9520 done:
9521 if (f && fclose(f) == EOF && err == NULL)
9522 err = got_error_from_errno("fclose");
9523 if (path && unlink(path) != 0 && err == NULL)
9524 err = got_error_from_errno2("unlink", path);
9525 free(path);
9526 return err;
9529 static const struct got_error *
9530 histedit_save_list(struct got_histedit_list *histedit_cmds,
9531 struct got_worktree *worktree, struct got_repository *repo)
9533 const struct got_error *err = NULL;
9534 char *path = NULL;
9535 FILE *f = NULL;
9536 struct got_histedit_list_entry *hle;
9537 struct got_commit_object *commit = NULL;
9539 err = got_worktree_get_histedit_script_path(&path, worktree);
9540 if (err)
9541 return err;
9543 f = fopen(path, "w");
9544 if (f == NULL) {
9545 err = got_error_from_errno2("fopen", path);
9546 goto done;
9548 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9549 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9550 repo);
9551 if (err)
9552 break;
9554 if (hle->logmsg) {
9555 int n = fprintf(f, "%c %s\n",
9556 GOT_HISTEDIT_MESG, hle->logmsg);
9557 if (n < 0) {
9558 err = got_ferror(f, GOT_ERR_IO);
9559 break;
9563 done:
9564 if (f && fclose(f) == EOF && err == NULL)
9565 err = got_error_from_errno("fclose");
9566 free(path);
9567 if (commit)
9568 got_object_commit_close(commit);
9569 return err;
9572 void
9573 histedit_free_list(struct got_histedit_list *histedit_cmds)
9575 struct got_histedit_list_entry *hle;
9577 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9578 TAILQ_REMOVE(histedit_cmds, hle, entry);
9579 free(hle);
9583 static const struct got_error *
9584 histedit_load_list(struct got_histedit_list *histedit_cmds,
9585 const char *path, struct got_repository *repo)
9587 const struct got_error *err = NULL;
9588 FILE *f = NULL;
9590 f = fopen(path, "r");
9591 if (f == NULL) {
9592 err = got_error_from_errno2("fopen", path);
9593 goto done;
9596 err = histedit_parse_list(histedit_cmds, f, repo);
9597 done:
9598 if (f && fclose(f) == EOF && err == NULL)
9599 err = got_error_from_errno("fclose");
9600 return err;
9603 static const struct got_error *
9604 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9605 const struct got_error *edit_err, struct got_object_id_queue *commits,
9606 const char *path, const char *branch_name, struct got_repository *repo)
9608 const struct got_error *err = NULL, *prev_err = edit_err;
9609 int resp = ' ';
9611 while (resp != 'c' && resp != 'r' && resp != 'a') {
9612 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9613 "or (a)bort: ", getprogname(), prev_err->msg);
9614 resp = getchar();
9615 if (resp == '\n')
9616 resp = getchar();
9617 if (resp == 'c') {
9618 histedit_free_list(histedit_cmds);
9619 err = histedit_run_editor(histedit_cmds, path, commits,
9620 repo);
9621 if (err) {
9622 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9623 err->code != GOT_ERR_HISTEDIT_CMD)
9624 break;
9625 prev_err = err;
9626 resp = ' ';
9627 continue;
9629 break;
9630 } else if (resp == 'r') {
9631 histedit_free_list(histedit_cmds);
9632 err = histedit_edit_script(histedit_cmds,
9633 commits, branch_name, 0, 0, repo);
9634 if (err) {
9635 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9636 err->code != GOT_ERR_HISTEDIT_CMD)
9637 break;
9638 prev_err = err;
9639 resp = ' ';
9640 continue;
9642 break;
9643 } else if (resp == 'a') {
9644 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9645 break;
9646 } else
9647 printf("invalid response '%c'\n", resp);
9650 return err;
9653 static const struct got_error *
9654 histedit_complete(struct got_worktree *worktree,
9655 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9656 struct got_reference *branch, struct got_repository *repo)
9658 printf("Switching work tree to %s\n",
9659 got_ref_get_symref_target(branch));
9660 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9661 branch, repo);
9664 static const struct got_error *
9665 show_histedit_progress(struct got_commit_object *commit,
9666 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9668 const struct got_error *err;
9669 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9671 err = got_object_id_str(&old_id_str, hle->commit_id);
9672 if (err)
9673 goto done;
9675 if (new_id) {
9676 err = got_object_id_str(&new_id_str, new_id);
9677 if (err)
9678 goto done;
9681 old_id_str[12] = '\0';
9682 if (new_id_str)
9683 new_id_str[12] = '\0';
9685 if (hle->logmsg) {
9686 logmsg = strdup(hle->logmsg);
9687 if (logmsg == NULL) {
9688 err = got_error_from_errno("strdup");
9689 goto done;
9691 trim_logmsg(logmsg, 42);
9692 } else {
9693 err = get_short_logmsg(&logmsg, 42, commit);
9694 if (err)
9695 goto done;
9698 switch (hle->cmd->code) {
9699 case GOT_HISTEDIT_PICK:
9700 case GOT_HISTEDIT_EDIT:
9701 printf("%s -> %s: %s\n", old_id_str,
9702 new_id_str ? new_id_str : "no-op change", logmsg);
9703 break;
9704 case GOT_HISTEDIT_DROP:
9705 case GOT_HISTEDIT_FOLD:
9706 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9707 logmsg);
9708 break;
9709 default:
9710 break;
9712 done:
9713 free(old_id_str);
9714 free(new_id_str);
9715 return err;
9718 static const struct got_error *
9719 histedit_commit(struct got_pathlist_head *merged_paths,
9720 struct got_worktree *worktree, struct got_fileindex *fileindex,
9721 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9722 struct got_repository *repo)
9724 const struct got_error *err;
9725 struct got_commit_object *commit;
9726 struct got_object_id *new_commit_id;
9728 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9729 && hle->logmsg == NULL) {
9730 err = histedit_edit_logmsg(hle, repo);
9731 if (err)
9732 return err;
9735 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9736 if (err)
9737 return err;
9739 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9740 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9741 hle->logmsg, repo);
9742 if (err) {
9743 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9744 goto done;
9745 err = show_histedit_progress(commit, hle, NULL);
9746 } else {
9747 err = show_histedit_progress(commit, hle, new_commit_id);
9748 free(new_commit_id);
9750 done:
9751 got_object_commit_close(commit);
9752 return err;
9755 static const struct got_error *
9756 histedit_skip_commit(struct got_histedit_list_entry *hle,
9757 struct got_worktree *worktree, struct got_repository *repo)
9759 const struct got_error *error;
9760 struct got_commit_object *commit;
9762 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9763 repo);
9764 if (error)
9765 return error;
9767 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9768 if (error)
9769 return error;
9771 error = show_histedit_progress(commit, hle, NULL);
9772 got_object_commit_close(commit);
9773 return error;
9776 static const struct got_error *
9777 check_local_changes(void *arg, unsigned char status,
9778 unsigned char staged_status, const char *path,
9779 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9780 struct got_object_id *commit_id, int dirfd, const char *de_name)
9782 int *have_local_changes = arg;
9784 switch (status) {
9785 case GOT_STATUS_ADD:
9786 case GOT_STATUS_DELETE:
9787 case GOT_STATUS_MODIFY:
9788 case GOT_STATUS_CONFLICT:
9789 *have_local_changes = 1;
9790 return got_error(GOT_ERR_CANCELLED);
9791 default:
9792 break;
9795 switch (staged_status) {
9796 case GOT_STATUS_ADD:
9797 case GOT_STATUS_DELETE:
9798 case GOT_STATUS_MODIFY:
9799 *have_local_changes = 1;
9800 return got_error(GOT_ERR_CANCELLED);
9801 default:
9802 break;
9805 return NULL;
9808 static const struct got_error *
9809 cmd_histedit(int argc, char *argv[])
9811 const struct got_error *error = NULL;
9812 struct got_worktree *worktree = NULL;
9813 struct got_fileindex *fileindex = NULL;
9814 struct got_repository *repo = NULL;
9815 char *cwd = NULL;
9816 struct got_reference *branch = NULL;
9817 struct got_reference *tmp_branch = NULL;
9818 struct got_object_id *resume_commit_id = NULL;
9819 struct got_object_id *base_commit_id = NULL;
9820 struct got_object_id *head_commit_id = NULL;
9821 struct got_commit_object *commit = NULL;
9822 int ch, rebase_in_progress = 0;
9823 struct got_update_progress_arg upa;
9824 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9825 int edit_logmsg_only = 0, fold_only = 0;
9826 int list_backups = 0, delete_backups = 0;
9827 const char *edit_script_path = NULL;
9828 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9829 struct got_object_id_queue commits;
9830 struct got_pathlist_head merged_paths;
9831 const struct got_object_id_queue *parent_ids;
9832 struct got_object_qid *pid;
9833 struct got_histedit_list histedit_cmds;
9834 struct got_histedit_list_entry *hle;
9836 STAILQ_INIT(&commits);
9837 TAILQ_INIT(&histedit_cmds);
9838 TAILQ_INIT(&merged_paths);
9839 memset(&upa, 0, sizeof(upa));
9841 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9842 switch (ch) {
9843 case 'a':
9844 abort_edit = 1;
9845 break;
9846 case 'c':
9847 continue_edit = 1;
9848 break;
9849 case 'f':
9850 fold_only = 1;
9851 break;
9852 case 'F':
9853 edit_script_path = optarg;
9854 break;
9855 case 'm':
9856 edit_logmsg_only = 1;
9857 break;
9858 case 'l':
9859 list_backups = 1;
9860 break;
9861 case 'X':
9862 delete_backups = 1;
9863 break;
9864 default:
9865 usage_histedit();
9866 /* NOTREACHED */
9870 argc -= optind;
9871 argv += optind;
9873 #ifndef PROFILE
9874 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9875 "unveil", NULL) == -1)
9876 err(1, "pledge");
9877 #endif
9878 if (abort_edit && continue_edit)
9879 option_conflict('a', 'c');
9880 if (edit_script_path && edit_logmsg_only)
9881 option_conflict('F', 'm');
9882 if (abort_edit && edit_logmsg_only)
9883 option_conflict('a', 'm');
9884 if (continue_edit && edit_logmsg_only)
9885 option_conflict('c', 'm');
9886 if (abort_edit && fold_only)
9887 option_conflict('a', 'f');
9888 if (continue_edit && fold_only)
9889 option_conflict('c', 'f');
9890 if (fold_only && edit_logmsg_only)
9891 option_conflict('f', 'm');
9892 if (edit_script_path && fold_only)
9893 option_conflict('F', 'f');
9894 if (list_backups) {
9895 if (abort_edit)
9896 option_conflict('l', 'a');
9897 if (continue_edit)
9898 option_conflict('l', 'c');
9899 if (edit_script_path)
9900 option_conflict('l', 'F');
9901 if (edit_logmsg_only)
9902 option_conflict('l', 'm');
9903 if (fold_only)
9904 option_conflict('l', 'f');
9905 if (delete_backups)
9906 option_conflict('l', 'X');
9907 if (argc != 0 && argc != 1)
9908 usage_histedit();
9909 } else if (delete_backups) {
9910 if (abort_edit)
9911 option_conflict('X', 'a');
9912 if (continue_edit)
9913 option_conflict('X', 'c');
9914 if (edit_script_path)
9915 option_conflict('X', 'F');
9916 if (edit_logmsg_only)
9917 option_conflict('X', 'm');
9918 if (fold_only)
9919 option_conflict('X', 'f');
9920 if (list_backups)
9921 option_conflict('X', 'l');
9922 if (argc != 0 && argc != 1)
9923 usage_histedit();
9924 } else if (argc != 0)
9925 usage_histedit();
9928 * This command cannot apply unveil(2) in all cases because the
9929 * user may choose to run an editor to edit the histedit script
9930 * and to edit individual commit log messages.
9931 * unveil(2) traverses exec(2); if an editor is used we have to
9932 * apply unveil after edit script and log messages have been written.
9933 * XXX TODO: Make use of unveil(2) where possible.
9936 cwd = getcwd(NULL, 0);
9937 if (cwd == NULL) {
9938 error = got_error_from_errno("getcwd");
9939 goto done;
9941 error = got_worktree_open(&worktree, cwd);
9942 if (error) {
9943 if (list_backups || delete_backups) {
9944 if (error->code != GOT_ERR_NOT_WORKTREE)
9945 goto done;
9946 } else {
9947 if (error->code == GOT_ERR_NOT_WORKTREE)
9948 error = wrap_not_worktree_error(error,
9949 "histedit", cwd);
9950 goto done;
9954 if (list_backups || delete_backups) {
9955 error = got_repo_open(&repo,
9956 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9957 NULL);
9958 if (error != NULL)
9959 goto done;
9960 error = apply_unveil(got_repo_get_path(repo), 0,
9961 worktree ? got_worktree_get_root_path(worktree) : NULL);
9962 if (error)
9963 goto done;
9964 error = process_backup_refs(
9965 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9966 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9967 goto done; /* nothing else to do */
9970 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9971 NULL);
9972 if (error != NULL)
9973 goto done;
9975 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9976 if (error)
9977 goto done;
9978 if (rebase_in_progress) {
9979 error = got_error(GOT_ERR_REBASING);
9980 goto done;
9983 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9984 if (error)
9985 goto done;
9987 if (edit_in_progress && edit_logmsg_only) {
9988 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9989 "histedit operation is in progress in this "
9990 "work tree and must be continued or aborted "
9991 "before the -m option can be used");
9992 goto done;
9994 if (edit_in_progress && fold_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 -f option can be used");
9999 goto done;
10002 if (edit_in_progress && abort_edit) {
10003 error = got_worktree_histedit_continue(&resume_commit_id,
10004 &tmp_branch, &branch, &base_commit_id, &fileindex,
10005 worktree, repo);
10006 if (error)
10007 goto done;
10008 printf("Switching work tree to %s\n",
10009 got_ref_get_symref_target(branch));
10010 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10011 branch, base_commit_id, update_progress, &upa);
10012 if (error)
10013 goto done;
10014 printf("Histedit of %s aborted\n",
10015 got_ref_get_symref_target(branch));
10016 print_update_progress_stats(&upa);
10017 goto done; /* nothing else to do */
10018 } else if (abort_edit) {
10019 error = got_error(GOT_ERR_NOT_HISTEDIT);
10020 goto done;
10023 if (continue_edit) {
10024 char *path;
10026 if (!edit_in_progress) {
10027 error = got_error(GOT_ERR_NOT_HISTEDIT);
10028 goto done;
10031 error = got_worktree_get_histedit_script_path(&path, worktree);
10032 if (error)
10033 goto done;
10035 error = histedit_load_list(&histedit_cmds, path, repo);
10036 free(path);
10037 if (error)
10038 goto done;
10040 error = got_worktree_histedit_continue(&resume_commit_id,
10041 &tmp_branch, &branch, &base_commit_id, &fileindex,
10042 worktree, repo);
10043 if (error)
10044 goto done;
10046 error = got_ref_resolve(&head_commit_id, repo, branch);
10047 if (error)
10048 goto done;
10050 error = got_object_open_as_commit(&commit, repo,
10051 head_commit_id);
10052 if (error)
10053 goto done;
10054 parent_ids = got_object_commit_get_parent_ids(commit);
10055 pid = STAILQ_FIRST(parent_ids);
10056 if (pid == NULL) {
10057 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10058 goto done;
10060 error = collect_commits(&commits, head_commit_id, pid->id,
10061 base_commit_id, got_worktree_get_path_prefix(worktree),
10062 GOT_ERR_HISTEDIT_PATH, repo);
10063 got_object_commit_close(commit);
10064 commit = NULL;
10065 if (error)
10066 goto done;
10067 } else {
10068 if (edit_in_progress) {
10069 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10070 goto done;
10073 error = got_ref_open(&branch, repo,
10074 got_worktree_get_head_ref_name(worktree), 0);
10075 if (error != NULL)
10076 goto done;
10078 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10079 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10080 "will not edit commit history of a branch outside "
10081 "the \"refs/heads/\" reference namespace");
10082 goto done;
10085 error = got_ref_resolve(&head_commit_id, repo, branch);
10086 got_ref_close(branch);
10087 branch = NULL;
10088 if (error)
10089 goto done;
10091 error = got_object_open_as_commit(&commit, repo,
10092 head_commit_id);
10093 if (error)
10094 goto done;
10095 parent_ids = got_object_commit_get_parent_ids(commit);
10096 pid = STAILQ_FIRST(parent_ids);
10097 if (pid == NULL) {
10098 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10099 goto done;
10101 error = collect_commits(&commits, head_commit_id, pid->id,
10102 got_worktree_get_base_commit_id(worktree),
10103 got_worktree_get_path_prefix(worktree),
10104 GOT_ERR_HISTEDIT_PATH, repo);
10105 got_object_commit_close(commit);
10106 commit = NULL;
10107 if (error)
10108 goto done;
10110 if (STAILQ_EMPTY(&commits)) {
10111 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10112 goto done;
10115 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10116 &base_commit_id, &fileindex, worktree, repo);
10117 if (error)
10118 goto done;
10120 if (edit_script_path) {
10121 error = histedit_load_list(&histedit_cmds,
10122 edit_script_path, repo);
10123 if (error) {
10124 got_worktree_histedit_abort(worktree, fileindex,
10125 repo, branch, base_commit_id,
10126 update_progress, &upa);
10127 print_update_progress_stats(&upa);
10128 goto done;
10130 } else {
10131 const char *branch_name;
10132 branch_name = got_ref_get_symref_target(branch);
10133 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10134 branch_name += 11;
10135 error = histedit_edit_script(&histedit_cmds, &commits,
10136 branch_name, edit_logmsg_only, fold_only, repo);
10137 if (error) {
10138 got_worktree_histedit_abort(worktree, fileindex,
10139 repo, branch, base_commit_id,
10140 update_progress, &upa);
10141 print_update_progress_stats(&upa);
10142 goto done;
10147 error = histedit_save_list(&histedit_cmds, worktree,
10148 repo);
10149 if (error) {
10150 got_worktree_histedit_abort(worktree, fileindex,
10151 repo, branch, base_commit_id,
10152 update_progress, &upa);
10153 print_update_progress_stats(&upa);
10154 goto done;
10159 error = histedit_check_script(&histedit_cmds, &commits, repo);
10160 if (error)
10161 goto done;
10163 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10164 if (resume_commit_id) {
10165 if (got_object_id_cmp(hle->commit_id,
10166 resume_commit_id) != 0)
10167 continue;
10169 resume_commit_id = NULL;
10170 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10171 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10172 error = histedit_skip_commit(hle, worktree,
10173 repo);
10174 if (error)
10175 goto done;
10176 } else {
10177 struct got_pathlist_head paths;
10178 int have_changes = 0;
10180 TAILQ_INIT(&paths);
10181 error = got_pathlist_append(&paths, "", NULL);
10182 if (error)
10183 goto done;
10184 error = got_worktree_status(worktree, &paths,
10185 repo, 0, check_local_changes, &have_changes,
10186 check_cancelled, NULL);
10187 got_pathlist_free(&paths);
10188 if (error) {
10189 if (error->code != GOT_ERR_CANCELLED)
10190 goto done;
10191 if (sigint_received || sigpipe_received)
10192 goto done;
10194 if (have_changes) {
10195 error = histedit_commit(NULL, worktree,
10196 fileindex, tmp_branch, hle, repo);
10197 if (error)
10198 goto done;
10199 } else {
10200 error = got_object_open_as_commit(
10201 &commit, repo, hle->commit_id);
10202 if (error)
10203 goto done;
10204 error = show_histedit_progress(commit,
10205 hle, NULL);
10206 got_object_commit_close(commit);
10207 commit = NULL;
10208 if (error)
10209 goto done;
10212 continue;
10215 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10216 error = histedit_skip_commit(hle, worktree, repo);
10217 if (error)
10218 goto done;
10219 continue;
10222 error = got_object_open_as_commit(&commit, repo,
10223 hle->commit_id);
10224 if (error)
10225 goto done;
10226 parent_ids = got_object_commit_get_parent_ids(commit);
10227 pid = STAILQ_FIRST(parent_ids);
10229 error = got_worktree_histedit_merge_files(&merged_paths,
10230 worktree, fileindex, pid->id, hle->commit_id, repo,
10231 update_progress, &upa, check_cancelled, NULL);
10232 if (error)
10233 goto done;
10234 got_object_commit_close(commit);
10235 commit = NULL;
10237 print_update_progress_stats(&upa);
10238 if (upa.conflicts > 0)
10239 rebase_status = GOT_STATUS_CONFLICT;
10241 if (rebase_status == GOT_STATUS_CONFLICT) {
10242 error = show_rebase_merge_conflict(hle->commit_id,
10243 repo);
10244 if (error)
10245 goto done;
10246 got_worktree_rebase_pathlist_free(&merged_paths);
10247 break;
10250 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10251 char *id_str;
10252 error = got_object_id_str(&id_str, hle->commit_id);
10253 if (error)
10254 goto done;
10255 printf("Stopping histedit for amending commit %s\n",
10256 id_str);
10257 free(id_str);
10258 got_worktree_rebase_pathlist_free(&merged_paths);
10259 error = got_worktree_histedit_postpone(worktree,
10260 fileindex);
10261 goto done;
10264 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10265 error = histedit_skip_commit(hle, worktree, repo);
10266 if (error)
10267 goto done;
10268 continue;
10271 error = histedit_commit(&merged_paths, worktree, fileindex,
10272 tmp_branch, hle, repo);
10273 got_worktree_rebase_pathlist_free(&merged_paths);
10274 if (error)
10275 goto done;
10278 if (rebase_status == GOT_STATUS_CONFLICT) {
10279 error = got_worktree_histedit_postpone(worktree, fileindex);
10280 if (error)
10281 goto done;
10282 error = got_error_msg(GOT_ERR_CONFLICTS,
10283 "conflicts must be resolved before histedit can continue");
10284 } else
10285 error = histedit_complete(worktree, fileindex, tmp_branch,
10286 branch, repo);
10287 done:
10288 got_object_id_queue_free(&commits);
10289 histedit_free_list(&histedit_cmds);
10290 free(head_commit_id);
10291 free(base_commit_id);
10292 free(resume_commit_id);
10293 if (commit)
10294 got_object_commit_close(commit);
10295 if (branch)
10296 got_ref_close(branch);
10297 if (tmp_branch)
10298 got_ref_close(tmp_branch);
10299 if (worktree)
10300 got_worktree_close(worktree);
10301 if (repo) {
10302 const struct got_error *close_err = got_repo_close(repo);
10303 if (error == NULL)
10304 error = close_err;
10306 return error;
10309 __dead static void
10310 usage_integrate(void)
10312 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10313 exit(1);
10316 static const struct got_error *
10317 cmd_integrate(int argc, char *argv[])
10319 const struct got_error *error = NULL;
10320 struct got_repository *repo = NULL;
10321 struct got_worktree *worktree = NULL;
10322 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10323 const char *branch_arg = NULL;
10324 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10325 struct got_fileindex *fileindex = NULL;
10326 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10327 int ch;
10328 struct got_update_progress_arg upa;
10330 while ((ch = getopt(argc, argv, "")) != -1) {
10331 switch (ch) {
10332 default:
10333 usage_integrate();
10334 /* NOTREACHED */
10338 argc -= optind;
10339 argv += optind;
10341 if (argc != 1)
10342 usage_integrate();
10343 branch_arg = argv[0];
10344 #ifndef PROFILE
10345 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10346 "unveil", NULL) == -1)
10347 err(1, "pledge");
10348 #endif
10349 cwd = getcwd(NULL, 0);
10350 if (cwd == NULL) {
10351 error = got_error_from_errno("getcwd");
10352 goto done;
10355 error = got_worktree_open(&worktree, cwd);
10356 if (error) {
10357 if (error->code == GOT_ERR_NOT_WORKTREE)
10358 error = wrap_not_worktree_error(error, "integrate",
10359 cwd);
10360 goto done;
10363 error = check_rebase_or_histedit_in_progress(worktree);
10364 if (error)
10365 goto done;
10367 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10368 NULL);
10369 if (error != NULL)
10370 goto done;
10372 error = apply_unveil(got_repo_get_path(repo), 0,
10373 got_worktree_get_root_path(worktree));
10374 if (error)
10375 goto done;
10377 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10378 error = got_error_from_errno("asprintf");
10379 goto done;
10382 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10383 &base_branch_ref, worktree, refname, repo);
10384 if (error)
10385 goto done;
10387 refname = strdup(got_ref_get_name(branch_ref));
10388 if (refname == NULL) {
10389 error = got_error_from_errno("strdup");
10390 got_worktree_integrate_abort(worktree, fileindex, repo,
10391 branch_ref, base_branch_ref);
10392 goto done;
10394 base_refname = strdup(got_ref_get_name(base_branch_ref));
10395 if (base_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;
10402 error = got_ref_resolve(&commit_id, repo, branch_ref);
10403 if (error)
10404 goto done;
10406 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10407 if (error)
10408 goto done;
10410 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10411 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10412 "specified branch has already been integrated");
10413 got_worktree_integrate_abort(worktree, fileindex, repo,
10414 branch_ref, base_branch_ref);
10415 goto done;
10418 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10419 if (error) {
10420 if (error->code == GOT_ERR_ANCESTRY)
10421 error = got_error(GOT_ERR_REBASE_REQUIRED);
10422 got_worktree_integrate_abort(worktree, fileindex, repo,
10423 branch_ref, base_branch_ref);
10424 goto done;
10427 memset(&upa, 0, sizeof(upa));
10428 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10429 branch_ref, base_branch_ref, update_progress, &upa,
10430 check_cancelled, NULL);
10431 if (error)
10432 goto done;
10434 printf("Integrated %s into %s\n", refname, base_refname);
10435 print_update_progress_stats(&upa);
10436 done:
10437 if (repo) {
10438 const struct got_error *close_err = got_repo_close(repo);
10439 if (error == NULL)
10440 error = close_err;
10442 if (worktree)
10443 got_worktree_close(worktree);
10444 free(cwd);
10445 free(base_commit_id);
10446 free(commit_id);
10447 free(refname);
10448 free(base_refname);
10449 return error;
10452 __dead static void
10453 usage_stage(void)
10455 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10456 "[-S] [file-path ...]\n",
10457 getprogname());
10458 exit(1);
10461 static const struct got_error *
10462 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10463 const char *path, struct got_object_id *blob_id,
10464 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10465 int dirfd, const char *de_name)
10467 const struct got_error *err = NULL;
10468 char *id_str = NULL;
10470 if (staged_status != GOT_STATUS_ADD &&
10471 staged_status != GOT_STATUS_MODIFY &&
10472 staged_status != GOT_STATUS_DELETE)
10473 return NULL;
10475 if (staged_status == GOT_STATUS_ADD ||
10476 staged_status == GOT_STATUS_MODIFY)
10477 err = got_object_id_str(&id_str, staged_blob_id);
10478 else
10479 err = got_object_id_str(&id_str, blob_id);
10480 if (err)
10481 return err;
10483 printf("%s %c %s\n", id_str, staged_status, path);
10484 free(id_str);
10485 return NULL;
10488 static const struct got_error *
10489 cmd_stage(int argc, char *argv[])
10491 const struct got_error *error = NULL;
10492 struct got_repository *repo = NULL;
10493 struct got_worktree *worktree = NULL;
10494 char *cwd = NULL;
10495 struct got_pathlist_head paths;
10496 struct got_pathlist_entry *pe;
10497 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10498 FILE *patch_script_file = NULL;
10499 const char *patch_script_path = NULL;
10500 struct choose_patch_arg cpa;
10502 TAILQ_INIT(&paths);
10504 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10505 switch (ch) {
10506 case 'l':
10507 list_stage = 1;
10508 break;
10509 case 'p':
10510 pflag = 1;
10511 break;
10512 case 'F':
10513 patch_script_path = optarg;
10514 break;
10515 case 'S':
10516 allow_bad_symlinks = 1;
10517 break;
10518 default:
10519 usage_stage();
10520 /* NOTREACHED */
10524 argc -= optind;
10525 argv += optind;
10527 #ifndef PROFILE
10528 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10529 "unveil", NULL) == -1)
10530 err(1, "pledge");
10531 #endif
10532 if (list_stage && (pflag || patch_script_path))
10533 errx(1, "-l option cannot be used with other options");
10534 if (patch_script_path && !pflag)
10535 errx(1, "-F option can only be used together with -p option");
10537 cwd = getcwd(NULL, 0);
10538 if (cwd == NULL) {
10539 error = got_error_from_errno("getcwd");
10540 goto done;
10543 error = got_worktree_open(&worktree, cwd);
10544 if (error) {
10545 if (error->code == GOT_ERR_NOT_WORKTREE)
10546 error = wrap_not_worktree_error(error, "stage", cwd);
10547 goto done;
10550 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10551 NULL);
10552 if (error != NULL)
10553 goto done;
10555 if (patch_script_path) {
10556 patch_script_file = fopen(patch_script_path, "r");
10557 if (patch_script_file == NULL) {
10558 error = got_error_from_errno2("fopen",
10559 patch_script_path);
10560 goto done;
10563 error = apply_unveil(got_repo_get_path(repo), 0,
10564 got_worktree_get_root_path(worktree));
10565 if (error)
10566 goto done;
10568 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10569 if (error)
10570 goto done;
10572 if (list_stage)
10573 error = got_worktree_status(worktree, &paths, repo, 0,
10574 print_stage, NULL, check_cancelled, NULL);
10575 else {
10576 cpa.patch_script_file = patch_script_file;
10577 cpa.action = "stage";
10578 error = got_worktree_stage(worktree, &paths,
10579 pflag ? NULL : print_status, NULL,
10580 pflag ? choose_patch : NULL, &cpa,
10581 allow_bad_symlinks, repo);
10583 done:
10584 if (patch_script_file && fclose(patch_script_file) == EOF &&
10585 error == NULL)
10586 error = got_error_from_errno2("fclose", patch_script_path);
10587 if (repo) {
10588 const struct got_error *close_err = got_repo_close(repo);
10589 if (error == NULL)
10590 error = close_err;
10592 if (worktree)
10593 got_worktree_close(worktree);
10594 TAILQ_FOREACH(pe, &paths, entry)
10595 free((char *)pe->path);
10596 got_pathlist_free(&paths);
10597 free(cwd);
10598 return error;
10601 __dead static void
10602 usage_unstage(void)
10604 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10605 "[file-path ...]\n",
10606 getprogname());
10607 exit(1);
10611 static const struct got_error *
10612 cmd_unstage(int argc, char *argv[])
10614 const struct got_error *error = NULL;
10615 struct got_repository *repo = NULL;
10616 struct got_worktree *worktree = NULL;
10617 char *cwd = NULL;
10618 struct got_pathlist_head paths;
10619 struct got_pathlist_entry *pe;
10620 int ch, pflag = 0;
10621 struct got_update_progress_arg upa;
10622 FILE *patch_script_file = NULL;
10623 const char *patch_script_path = NULL;
10624 struct choose_patch_arg cpa;
10626 TAILQ_INIT(&paths);
10628 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10629 switch (ch) {
10630 case 'p':
10631 pflag = 1;
10632 break;
10633 case 'F':
10634 patch_script_path = optarg;
10635 break;
10636 default:
10637 usage_unstage();
10638 /* NOTREACHED */
10642 argc -= optind;
10643 argv += optind;
10645 #ifndef PROFILE
10646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10647 "unveil", NULL) == -1)
10648 err(1, "pledge");
10649 #endif
10650 if (patch_script_path && !pflag)
10651 errx(1, "-F option can only be used together with -p option");
10653 cwd = getcwd(NULL, 0);
10654 if (cwd == NULL) {
10655 error = got_error_from_errno("getcwd");
10656 goto done;
10659 error = got_worktree_open(&worktree, cwd);
10660 if (error) {
10661 if (error->code == GOT_ERR_NOT_WORKTREE)
10662 error = wrap_not_worktree_error(error, "unstage", cwd);
10663 goto done;
10666 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10667 NULL);
10668 if (error != NULL)
10669 goto done;
10671 if (patch_script_path) {
10672 patch_script_file = fopen(patch_script_path, "r");
10673 if (patch_script_file == NULL) {
10674 error = got_error_from_errno2("fopen",
10675 patch_script_path);
10676 goto done;
10680 error = apply_unveil(got_repo_get_path(repo), 0,
10681 got_worktree_get_root_path(worktree));
10682 if (error)
10683 goto done;
10685 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10686 if (error)
10687 goto done;
10689 cpa.patch_script_file = patch_script_file;
10690 cpa.action = "unstage";
10691 memset(&upa, 0, sizeof(upa));
10692 error = got_worktree_unstage(worktree, &paths, update_progress,
10693 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10694 if (!error)
10695 print_update_progress_stats(&upa);
10696 done:
10697 if (patch_script_file && fclose(patch_script_file) == EOF &&
10698 error == NULL)
10699 error = got_error_from_errno2("fclose", patch_script_path);
10700 if (repo) {
10701 const struct got_error *close_err = got_repo_close(repo);
10702 if (error == NULL)
10703 error = close_err;
10705 if (worktree)
10706 got_worktree_close(worktree);
10707 TAILQ_FOREACH(pe, &paths, entry)
10708 free((char *)pe->path);
10709 got_pathlist_free(&paths);
10710 free(cwd);
10711 return error;
10714 __dead static void
10715 usage_cat(void)
10717 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10718 "arg1 [arg2 ...]\n", getprogname());
10719 exit(1);
10722 static const struct got_error *
10723 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10725 const struct got_error *err;
10726 struct got_blob_object *blob;
10728 err = got_object_open_as_blob(&blob, repo, id, 8192);
10729 if (err)
10730 return err;
10732 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10733 got_object_blob_close(blob);
10734 return err;
10737 static const struct got_error *
10738 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10740 const struct got_error *err;
10741 struct got_tree_object *tree;
10742 int nentries, i;
10744 err = got_object_open_as_tree(&tree, repo, id);
10745 if (err)
10746 return err;
10748 nentries = got_object_tree_get_nentries(tree);
10749 for (i = 0; i < nentries; i++) {
10750 struct got_tree_entry *te;
10751 char *id_str;
10752 if (sigint_received || sigpipe_received)
10753 break;
10754 te = got_object_tree_get_entry(tree, i);
10755 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10756 if (err)
10757 break;
10758 fprintf(outfile, "%s %.7o %s\n", id_str,
10759 got_tree_entry_get_mode(te),
10760 got_tree_entry_get_name(te));
10761 free(id_str);
10764 got_object_tree_close(tree);
10765 return err;
10768 static const struct got_error *
10769 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10771 const struct got_error *err;
10772 struct got_commit_object *commit;
10773 const struct got_object_id_queue *parent_ids;
10774 struct got_object_qid *pid;
10775 char *id_str = NULL;
10776 const char *logmsg = NULL;
10778 err = got_object_open_as_commit(&commit, repo, id);
10779 if (err)
10780 return err;
10782 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10783 if (err)
10784 goto done;
10786 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10787 parent_ids = got_object_commit_get_parent_ids(commit);
10788 fprintf(outfile, "numparents %d\n",
10789 got_object_commit_get_nparents(commit));
10790 STAILQ_FOREACH(pid, parent_ids, entry) {
10791 char *pid_str;
10792 err = got_object_id_str(&pid_str, pid->id);
10793 if (err)
10794 goto done;
10795 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10796 free(pid_str);
10798 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10799 got_object_commit_get_author(commit),
10800 (long long)got_object_commit_get_author_time(commit));
10802 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10803 got_object_commit_get_author(commit),
10804 (long long)got_object_commit_get_committer_time(commit));
10806 logmsg = got_object_commit_get_logmsg_raw(commit);
10807 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10808 fprintf(outfile, "%s", logmsg);
10809 done:
10810 free(id_str);
10811 got_object_commit_close(commit);
10812 return err;
10815 static const struct got_error *
10816 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10818 const struct got_error *err;
10819 struct got_tag_object *tag;
10820 char *id_str = NULL;
10821 const char *tagmsg = NULL;
10823 err = got_object_open_as_tag(&tag, repo, id);
10824 if (err)
10825 return err;
10827 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10828 if (err)
10829 goto done;
10831 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10833 switch (got_object_tag_get_object_type(tag)) {
10834 case GOT_OBJ_TYPE_BLOB:
10835 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10836 GOT_OBJ_LABEL_BLOB);
10837 break;
10838 case GOT_OBJ_TYPE_TREE:
10839 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10840 GOT_OBJ_LABEL_TREE);
10841 break;
10842 case GOT_OBJ_TYPE_COMMIT:
10843 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10844 GOT_OBJ_LABEL_COMMIT);
10845 break;
10846 case GOT_OBJ_TYPE_TAG:
10847 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10848 GOT_OBJ_LABEL_TAG);
10849 break;
10850 default:
10851 break;
10854 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10855 got_object_tag_get_name(tag));
10857 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10858 got_object_tag_get_tagger(tag),
10859 (long long)got_object_tag_get_tagger_time(tag));
10861 tagmsg = got_object_tag_get_message(tag);
10862 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10863 fprintf(outfile, "%s", tagmsg);
10864 done:
10865 free(id_str);
10866 got_object_tag_close(tag);
10867 return err;
10870 static const struct got_error *
10871 cmd_cat(int argc, char *argv[])
10873 const struct got_error *error;
10874 struct got_repository *repo = NULL;
10875 struct got_worktree *worktree = NULL;
10876 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10877 const char *commit_id_str = NULL;
10878 struct got_object_id *id = NULL, *commit_id = NULL;
10879 int ch, obj_type, i, force_path = 0;
10880 struct got_reflist_head refs;
10882 TAILQ_INIT(&refs);
10884 #ifndef PROFILE
10885 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10886 NULL) == -1)
10887 err(1, "pledge");
10888 #endif
10890 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10891 switch (ch) {
10892 case 'c':
10893 commit_id_str = optarg;
10894 break;
10895 case 'r':
10896 repo_path = realpath(optarg, NULL);
10897 if (repo_path == NULL)
10898 return got_error_from_errno2("realpath",
10899 optarg);
10900 got_path_strip_trailing_slashes(repo_path);
10901 break;
10902 case 'P':
10903 force_path = 1;
10904 break;
10905 default:
10906 usage_cat();
10907 /* NOTREACHED */
10911 argc -= optind;
10912 argv += optind;
10914 cwd = getcwd(NULL, 0);
10915 if (cwd == NULL) {
10916 error = got_error_from_errno("getcwd");
10917 goto done;
10919 error = got_worktree_open(&worktree, cwd);
10920 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10921 goto done;
10922 if (worktree) {
10923 if (repo_path == NULL) {
10924 repo_path = strdup(
10925 got_worktree_get_repo_path(worktree));
10926 if (repo_path == NULL) {
10927 error = got_error_from_errno("strdup");
10928 goto done;
10933 if (repo_path == NULL) {
10934 repo_path = getcwd(NULL, 0);
10935 if (repo_path == NULL)
10936 return got_error_from_errno("getcwd");
10939 error = got_repo_open(&repo, repo_path, NULL);
10940 free(repo_path);
10941 if (error != NULL)
10942 goto done;
10944 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10945 if (error)
10946 goto done;
10948 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10949 if (error)
10950 goto done;
10952 if (commit_id_str == NULL)
10953 commit_id_str = GOT_REF_HEAD;
10954 error = got_repo_match_object_id(&commit_id, NULL,
10955 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10956 if (error)
10957 goto done;
10959 for (i = 0; i < argc; i++) {
10960 if (force_path) {
10961 error = got_object_id_by_path(&id, repo, commit_id,
10962 argv[i]);
10963 if (error)
10964 break;
10965 } else {
10966 error = got_repo_match_object_id(&id, &label, argv[i],
10967 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10968 repo);
10969 if (error) {
10970 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10971 error->code != GOT_ERR_NOT_REF)
10972 break;
10973 error = got_object_id_by_path(&id, repo,
10974 commit_id, argv[i]);
10975 if (error)
10976 break;
10980 error = got_object_get_type(&obj_type, repo, id);
10981 if (error)
10982 break;
10984 switch (obj_type) {
10985 case GOT_OBJ_TYPE_BLOB:
10986 error = cat_blob(id, repo, stdout);
10987 break;
10988 case GOT_OBJ_TYPE_TREE:
10989 error = cat_tree(id, repo, stdout);
10990 break;
10991 case GOT_OBJ_TYPE_COMMIT:
10992 error = cat_commit(id, repo, stdout);
10993 break;
10994 case GOT_OBJ_TYPE_TAG:
10995 error = cat_tag(id, repo, stdout);
10996 break;
10997 default:
10998 error = got_error(GOT_ERR_OBJ_TYPE);
10999 break;
11001 if (error)
11002 break;
11003 free(label);
11004 label = NULL;
11005 free(id);
11006 id = NULL;
11008 done:
11009 free(label);
11010 free(id);
11011 free(commit_id);
11012 if (worktree)
11013 got_worktree_close(worktree);
11014 if (repo) {
11015 const struct got_error *close_err = got_repo_close(repo);
11016 if (error == NULL)
11017 error = close_err;
11019 got_ref_list_free(&refs);
11020 return error;
11023 __dead static void
11024 usage_info(void)
11026 fprintf(stderr, "usage: %s info [path ...]\n",
11027 getprogname());
11028 exit(1);
11031 static const struct got_error *
11032 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11033 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11034 struct got_object_id *commit_id)
11036 const struct got_error *err = NULL;
11037 char *id_str = NULL;
11038 char datebuf[128];
11039 struct tm mytm, *tm;
11040 struct got_pathlist_head *paths = arg;
11041 struct got_pathlist_entry *pe;
11044 * Clear error indication from any of the path arguments which
11045 * would cause this file index entry to be displayed.
11047 TAILQ_FOREACH(pe, paths, entry) {
11048 if (got_path_cmp(path, pe->path, strlen(path),
11049 pe->path_len) == 0 ||
11050 got_path_is_child(path, pe->path, pe->path_len))
11051 pe->data = NULL; /* no error */
11054 printf(GOT_COMMIT_SEP_STR);
11055 if (S_ISLNK(mode))
11056 printf("symlink: %s\n", path);
11057 else if (S_ISREG(mode)) {
11058 printf("file: %s\n", path);
11059 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11060 } else if (S_ISDIR(mode))
11061 printf("directory: %s\n", path);
11062 else
11063 printf("something: %s\n", path);
11065 tm = localtime_r(&mtime, &mytm);
11066 if (tm == NULL)
11067 return NULL;
11068 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11069 return got_error(GOT_ERR_NO_SPACE);
11070 printf("timestamp: %s\n", datebuf);
11072 if (blob_id) {
11073 err = got_object_id_str(&id_str, blob_id);
11074 if (err)
11075 return err;
11076 printf("based on blob: %s\n", id_str);
11077 free(id_str);
11080 if (staged_blob_id) {
11081 err = got_object_id_str(&id_str, staged_blob_id);
11082 if (err)
11083 return err;
11084 printf("based on staged blob: %s\n", id_str);
11085 free(id_str);
11088 if (commit_id) {
11089 err = got_object_id_str(&id_str, commit_id);
11090 if (err)
11091 return err;
11092 printf("based on commit: %s\n", id_str);
11093 free(id_str);
11096 return NULL;
11099 static const struct got_error *
11100 cmd_info(int argc, char *argv[])
11102 const struct got_error *error = NULL;
11103 struct got_worktree *worktree = NULL;
11104 char *cwd = NULL, *id_str = NULL;
11105 struct got_pathlist_head paths;
11106 struct got_pathlist_entry *pe;
11107 char *uuidstr = NULL;
11108 int ch, show_files = 0;
11110 TAILQ_INIT(&paths);
11112 while ((ch = getopt(argc, argv, "")) != -1) {
11113 switch (ch) {
11114 default:
11115 usage_info();
11116 /* NOTREACHED */
11120 argc -= optind;
11121 argv += optind;
11123 #ifndef PROFILE
11124 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11125 NULL) == -1)
11126 err(1, "pledge");
11127 #endif
11128 cwd = getcwd(NULL, 0);
11129 if (cwd == NULL) {
11130 error = got_error_from_errno("getcwd");
11131 goto done;
11134 error = got_worktree_open(&worktree, cwd);
11135 if (error) {
11136 if (error->code == GOT_ERR_NOT_WORKTREE)
11137 error = wrap_not_worktree_error(error, "info", cwd);
11138 goto done;
11141 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11142 if (error)
11143 goto done;
11145 if (argc >= 1) {
11146 error = get_worktree_paths_from_argv(&paths, argc, argv,
11147 worktree);
11148 if (error)
11149 goto done;
11150 show_files = 1;
11153 error = got_object_id_str(&id_str,
11154 got_worktree_get_base_commit_id(worktree));
11155 if (error)
11156 goto done;
11158 error = got_worktree_get_uuid(&uuidstr, worktree);
11159 if (error)
11160 goto done;
11162 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11163 printf("work tree base commit: %s\n", id_str);
11164 printf("work tree path prefix: %s\n",
11165 got_worktree_get_path_prefix(worktree));
11166 printf("work tree branch reference: %s\n",
11167 got_worktree_get_head_ref_name(worktree));
11168 printf("work tree UUID: %s\n", uuidstr);
11169 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11171 if (show_files) {
11172 struct got_pathlist_entry *pe;
11173 TAILQ_FOREACH(pe, &paths, entry) {
11174 if (pe->path_len == 0)
11175 continue;
11177 * Assume this path will fail. This will be corrected
11178 * in print_path_info() in case the path does suceeed.
11180 pe->data = (void *)got_error_path(pe->path,
11181 GOT_ERR_BAD_PATH);
11183 error = got_worktree_path_info(worktree, &paths,
11184 print_path_info, &paths, check_cancelled, NULL);
11185 if (error)
11186 goto done;
11187 TAILQ_FOREACH(pe, &paths, entry) {
11188 if (pe->data != NULL) {
11189 error = pe->data; /* bad path */
11190 break;
11194 done:
11195 TAILQ_FOREACH(pe, &paths, entry)
11196 free((char *)pe->path);
11197 got_pathlist_free(&paths);
11198 free(cwd);
11199 free(id_str);
11200 free(uuidstr);
11201 return error;