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/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 int
408 spawn_editor(const char *editor, const char *file)
410 pid_t pid;
411 sig_t sighup, sigint, sigquit;
412 int st = -1;
414 sighup = signal(SIGHUP, SIG_IGN);
415 sigint = signal(SIGINT, SIG_IGN);
416 sigquit = signal(SIGQUIT, SIG_IGN);
418 switch (pid = fork()) {
419 case -1:
420 goto doneediting;
421 case 0:
422 execl(editor, editor, file, (char *)NULL);
423 _exit(127);
426 while (waitpid(pid, &st, 0) == -1)
427 if (errno != EINTR)
428 break;
430 doneediting:
431 (void)signal(SIGHUP, sighup);
432 (void)signal(SIGINT, sigint);
433 (void)signal(SIGQUIT, sigquit);
435 if (!WIFEXITED(st)) {
436 errno = EINTR;
437 return -1;
440 return WEXITSTATUS(st);
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 char *line = NULL;
450 size_t linesize = 0;
451 ssize_t linelen;
452 struct stat st, st2;
453 FILE *fp = NULL;
454 size_t len, logmsg_len;
455 char *initial_content_stripped = NULL, *buf = NULL, *s;
457 *logmsg = NULL;
459 if (stat(logmsg_path, &st) == -1)
460 return got_error_from_errno2("stat", logmsg_path);
462 if (spawn_editor(editor, logmsg_path) == -1)
463 return got_error_from_errno("failed spawning editor");
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification &&
469 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 /*
474 * Set up a stripped version of the initial content without comments
475 * and blank lines. We need this in order to check if the message
476 * has in fact been edited.
477 */
478 initial_content_stripped = malloc(initial_content_len + 1);
479 if (initial_content_stripped == NULL)
480 return got_error_from_errno("malloc");
481 initial_content_stripped[0] = '\0';
483 buf = strdup(initial_content);
484 if (buf == NULL) {
485 err = got_error_from_errno("strdup");
486 goto done;
488 s = buf;
489 len = 0;
490 while ((line = strsep(&s, "\n")) != NULL) {
491 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
492 continue; /* remove comments and leading empty lines */
493 len = strlcat(initial_content_stripped, line,
494 initial_content_len + 1);
495 if (len >= initial_content_len + 1) {
496 err = got_error(GOT_ERR_NO_SPACE);
497 goto done;
500 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
501 initial_content_stripped[len - 1] = '\0';
502 len--;
505 logmsg_len = st2.st_size;
506 *logmsg = malloc(logmsg_len + 1);
507 if (*logmsg == NULL)
508 return got_error_from_errno("malloc");
509 (*logmsg)[0] = '\0';
511 fp = fopen(logmsg_path, "re");
512 if (fp == NULL) {
513 err = got_error_from_errno("fopen");
514 goto done;
517 len = 0;
518 while ((linelen = getline(&line, &linesize, fp)) != -1) {
519 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
520 continue; /* remove comments and leading empty lines */
521 len = strlcat(*logmsg, line, logmsg_len + 1);
522 if (len >= logmsg_len + 1) {
523 err = got_error(GOT_ERR_NO_SPACE);
524 goto done;
527 free(line);
528 if (ferror(fp)) {
529 err = got_ferror(fp, GOT_ERR_IO);
530 goto done;
532 while (len > 0 && (*logmsg)[len - 1] == '\n') {
533 (*logmsg)[len - 1] = '\0';
534 len--;
537 if (len == 0) {
538 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
539 "commit message cannot be empty, aborting");
540 goto done;
542 if (require_modification &&
543 strcmp(*logmsg, initial_content_stripped) == 0)
544 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
545 "no changes made to commit message, aborting");
546 done:
547 free(initial_content_stripped);
548 free(buf);
549 if (fp && fclose(fp) == EOF && err == NULL)
550 err = got_error_from_errno("fclose");
551 if (err) {
552 free(*logmsg);
553 *logmsg = NULL;
555 return err;
558 static const struct got_error *
559 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
560 const char *path_dir, const char *branch_name)
562 char *initial_content = NULL;
563 const struct got_error *err = NULL;
564 int initial_content_len;
565 int fd = -1;
567 initial_content_len = asprintf(&initial_content,
568 "\n# %s to be imported to branch %s\n", path_dir,
569 branch_name);
570 if (initial_content_len == -1)
571 return got_error_from_errno("asprintf");
573 err = got_opentemp_named_fd(logmsg_path, &fd,
574 GOT_TMPDIR_STR "/got-importmsg");
575 if (err)
576 goto done;
578 if (write(fd, initial_content, initial_content_len) == -1) {
579 err = got_error_from_errno2("write", *logmsg_path);
580 goto done;
583 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
584 initial_content_len, 1);
585 done:
586 if (fd != -1 && close(fd) == -1 && err == NULL)
587 err = got_error_from_errno2("close", *logmsg_path);
588 free(initial_content);
589 if (err) {
590 free(*logmsg_path);
591 *logmsg_path = NULL;
593 return err;
596 static const struct got_error *
597 import_progress(void *arg, const char *path)
599 printf("A %s\n", path);
600 return NULL;
603 static int
604 valid_author(const char *author)
606 /*
607 * Really dumb email address check; we're only doing this to
608 * avoid git's object parser breaking on commits we create.
609 */
610 while (*author && *author != '<')
611 author++;
612 if (*author != '<')
613 return 0;
614 while (*author && *author != '@')
615 author++;
616 if (*author != '@')
617 return 0;
618 while (*author && *author != '>')
619 author++;
620 return *author == '>';
623 static const struct got_error *
624 get_author(char **author, struct got_repository *repo,
625 struct got_worktree *worktree)
627 const struct got_error *err = NULL;
628 const char *got_author = NULL, *name, *email;
629 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
631 *author = NULL;
633 if (worktree)
634 worktree_conf = got_worktree_get_gotconfig(worktree);
635 repo_conf = got_repo_get_gotconfig(repo);
637 /*
638 * Priority of potential author information sources, from most
639 * significant to least significant:
640 * 1) work tree's .got/got.conf file
641 * 2) repository's got.conf file
642 * 3) repository's git config file
643 * 4) environment variables
644 * 5) global git config files (in user's home directory or /etc)
645 */
647 if (worktree_conf)
648 got_author = got_gotconfig_get_author(worktree_conf);
649 if (got_author == NULL)
650 got_author = got_gotconfig_get_author(repo_conf);
651 if (got_author == NULL) {
652 name = got_repo_get_gitconfig_author_name(repo);
653 email = got_repo_get_gitconfig_author_email(repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email) == -1)
656 return got_error_from_errno("asprintf");
657 return NULL;
660 got_author = getenv("GOT_AUTHOR");
661 if (got_author == NULL) {
662 name = got_repo_get_global_gitconfig_author_name(repo);
663 email = got_repo_get_global_gitconfig_author_email(
664 repo);
665 if (name && email) {
666 if (asprintf(author, "%s <%s>", name, email)
667 == -1)
668 return got_error_from_errno("asprintf");
669 return NULL;
671 /* TODO: Look up user in password database? */
672 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
676 *author = strdup(got_author);
677 if (*author == NULL)
678 return got_error_from_errno("strdup");
680 if (!valid_author(*author)) {
681 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
682 free(*author);
683 *author = NULL;
685 return err;
688 static const struct got_error *
689 get_gitconfig_path(char **gitconfig_path)
691 const char *homedir = getenv("HOME");
693 *gitconfig_path = NULL;
694 if (homedir) {
695 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
696 return got_error_from_errno("asprintf");
699 return NULL;
702 static const struct got_error *
703 cmd_import(int argc, char *argv[])
705 const struct got_error *error = NULL;
706 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
707 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
708 const char *branch_name = "main";
709 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
710 struct got_repository *repo = NULL;
711 struct got_reference *branch_ref = NULL, *head_ref = NULL;
712 struct got_object_id *new_commit_id = NULL;
713 int ch;
714 struct got_pathlist_head ignores;
715 struct got_pathlist_entry *pe;
716 int preserve_logmsg = 0;
718 TAILQ_INIT(&ignores);
720 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
721 switch (ch) {
722 case 'b':
723 branch_name = optarg;
724 break;
725 case 'm':
726 logmsg = strdup(optarg);
727 if (logmsg == NULL) {
728 error = got_error_from_errno("strdup");
729 goto done;
731 break;
732 case 'r':
733 repo_path = realpath(optarg, NULL);
734 if (repo_path == NULL) {
735 error = got_error_from_errno2("realpath",
736 optarg);
737 goto done;
739 break;
740 case 'I':
741 if (optarg[0] == '\0')
742 break;
743 error = got_pathlist_insert(&pe, &ignores, optarg,
744 NULL);
745 if (error)
746 goto done;
747 break;
748 default:
749 usage_import();
750 /* NOTREACHED */
754 argc -= optind;
755 argv += optind;
757 #ifndef PROFILE
758 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
759 "unveil",
760 NULL) == -1)
761 err(1, "pledge");
762 #endif
763 if (argc != 1)
764 usage_import();
766 if (repo_path == NULL) {
767 repo_path = getcwd(NULL, 0);
768 if (repo_path == NULL)
769 return got_error_from_errno("getcwd");
771 got_path_strip_trailing_slashes(repo_path);
772 error = get_gitconfig_path(&gitconfig_path);
773 if (error)
774 goto done;
775 error = got_repo_open(&repo, repo_path, gitconfig_path);
776 if (error)
777 goto done;
779 error = get_author(&author, repo, NULL);
780 if (error)
781 return error;
783 /*
784 * Don't let the user create a branch name with a leading '-'.
785 * While technically a valid reference name, this case is usually
786 * an unintended typo.
787 */
788 if (branch_name[0] == '-')
789 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
791 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
792 error = got_error_from_errno("asprintf");
793 goto done;
796 error = got_ref_open(&branch_ref, repo, refname, 0);
797 if (error) {
798 if (error->code != GOT_ERR_NOT_REF)
799 goto done;
800 } else {
801 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
802 "import target branch already exists");
803 goto done;
806 path_dir = realpath(argv[0], NULL);
807 if (path_dir == NULL) {
808 error = got_error_from_errno2("realpath", argv[0]);
809 goto done;
811 got_path_strip_trailing_slashes(path_dir);
813 /*
814 * unveil(2) traverses exec(2); if an editor is used we have
815 * to apply unveil after the log message has been written.
816 */
817 if (logmsg == NULL || strlen(logmsg) == 0) {
818 error = get_editor(&editor);
819 if (error)
820 goto done;
821 free(logmsg);
822 error = collect_import_msg(&logmsg, &logmsg_path, editor,
823 path_dir, refname);
824 if (error) {
825 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
826 logmsg_path != NULL)
827 preserve_logmsg = 1;
828 goto done;
832 if (unveil(path_dir, "r") != 0) {
833 error = got_error_from_errno2("unveil", path_dir);
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_repo_import(&new_commit_id, path_dir, logmsg,
847 author, &ignores, repo, import_progress, NULL);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_write(branch_ref, repo);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_object_id_str(&id_str, new_commit_id);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
876 if (error) {
877 if (error->code != GOT_ERR_NOT_REF) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
884 branch_ref);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
891 error = got_ref_write(head_ref, repo);
892 if (error) {
893 if (logmsg_path)
894 preserve_logmsg = 1;
895 goto done;
899 printf("Created branch %s with commit %s\n",
900 got_ref_get_name(branch_ref), id_str);
901 done:
902 if (preserve_logmsg) {
903 fprintf(stderr, "%s: log message preserved in %s\n",
904 getprogname(), logmsg_path);
905 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
906 error = got_error_from_errno2("unlink", logmsg_path);
907 free(logmsg);
908 free(logmsg_path);
909 free(repo_path);
910 free(editor);
911 free(refname);
912 free(new_commit_id);
913 free(id_str);
914 free(author);
915 free(gitconfig_path);
916 if (branch_ref)
917 got_ref_close(branch_ref);
918 if (head_ref)
919 got_ref_close(head_ref);
920 return error;
923 __dead static void
924 usage_clone(void)
926 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
927 "[-R reference] repository-url [directory]\n", getprogname());
928 exit(1);
931 struct got_fetch_progress_arg {
932 char last_scaled_size[FMT_SCALED_STRSIZE];
933 int last_p_indexed;
934 int last_p_resolved;
935 int verbosity;
937 struct got_repository *repo;
939 int create_configs;
940 int configs_created;
941 struct {
942 struct got_pathlist_head *symrefs;
943 struct got_pathlist_head *wanted_branches;
944 struct got_pathlist_head *wanted_refs;
945 const char *proto;
946 const char *host;
947 const char *port;
948 const char *remote_repo_path;
949 const char *git_url;
950 int fetch_all_branches;
951 int mirror_references;
952 } config_info;
953 };
955 /* XXX forward declaration */
956 static const struct got_error *
957 create_config_files(const char *proto, const char *host, const char *port,
958 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
959 int mirror_references, struct got_pathlist_head *symrefs,
960 struct got_pathlist_head *wanted_branches,
961 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
963 static const struct got_error *
964 fetch_progress(void *arg, const char *message, off_t packfile_size,
965 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
967 const struct got_error *err = NULL;
968 struct got_fetch_progress_arg *a = arg;
969 char scaled_size[FMT_SCALED_STRSIZE];
970 int p_indexed, p_resolved;
971 int print_size = 0, print_indexed = 0, print_resolved = 0;
973 /*
974 * In order to allow a failed clone to be resumed with 'got fetch'
975 * we try to create configuration files as soon as possible.
976 * Once the server has sent information about its default branch
977 * we have all required information.
978 */
979 if (a->create_configs && !a->configs_created &&
980 !TAILQ_EMPTY(a->config_info.symrefs)) {
981 err = create_config_files(a->config_info.proto,
982 a->config_info.host, a->config_info.port,
983 a->config_info.remote_repo_path,
984 a->config_info.git_url,
985 a->config_info.fetch_all_branches,
986 a->config_info.mirror_references,
987 a->config_info.symrefs,
988 a->config_info.wanted_branches,
989 a->config_info.wanted_refs, a->repo);
990 if (err)
991 return err;
992 a->configs_created = 1;
995 if (a->verbosity < 0)
996 return NULL;
998 if (message && message[0] != '\0') {
999 printf("\rserver: %s", message);
1000 fflush(stdout);
1001 return NULL;
1004 if (packfile_size > 0 || nobj_indexed > 0) {
1005 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1006 (a->last_scaled_size[0] == '\0' ||
1007 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1008 print_size = 1;
1009 if (strlcpy(a->last_scaled_size, scaled_size,
1010 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1011 return got_error(GOT_ERR_NO_SPACE);
1013 if (nobj_indexed > 0) {
1014 p_indexed = (nobj_indexed * 100) / nobj_total;
1015 if (p_indexed != a->last_p_indexed) {
1016 a->last_p_indexed = p_indexed;
1017 print_indexed = 1;
1018 print_size = 1;
1021 if (nobj_resolved > 0) {
1022 p_resolved = (nobj_resolved * 100) /
1023 (nobj_total - nobj_loose);
1024 if (p_resolved != a->last_p_resolved) {
1025 a->last_p_resolved = p_resolved;
1026 print_resolved = 1;
1027 print_indexed = 1;
1028 print_size = 1;
1033 if (print_size || print_indexed || print_resolved)
1034 printf("\r");
1035 if (print_size)
1036 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1037 if (print_indexed)
1038 printf("; indexing %d%%", p_indexed);
1039 if (print_resolved)
1040 printf("; resolving deltas %d%%", p_resolved);
1041 if (print_size || print_indexed || print_resolved)
1042 fflush(stdout);
1044 return NULL;
1047 static const struct got_error *
1048 create_symref(const char *refname, struct got_reference *target_ref,
1049 int verbosity, struct got_repository *repo)
1051 const struct got_error *err;
1052 struct got_reference *head_symref;
1054 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1055 if (err)
1056 return err;
1058 err = got_ref_write(head_symref, repo);
1059 if (err == NULL && verbosity > 0) {
1060 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1061 got_ref_get_name(target_ref));
1063 got_ref_close(head_symref);
1064 return err;
1067 static const struct got_error *
1068 list_remote_refs(struct got_pathlist_head *symrefs,
1069 struct got_pathlist_head *refs)
1071 const struct got_error *err;
1072 struct got_pathlist_entry *pe;
1074 TAILQ_FOREACH(pe, symrefs, entry) {
1075 const char *refname = pe->path;
1076 const char *targetref = pe->data;
1078 printf("%s: %s\n", refname, targetref);
1081 TAILQ_FOREACH(pe, refs, entry) {
1082 const char *refname = pe->path;
1083 struct got_object_id *id = pe->data;
1084 char *id_str;
1086 err = got_object_id_str(&id_str, id);
1087 if (err)
1088 return err;
1089 printf("%s: %s\n", refname, id_str);
1090 free(id_str);
1093 return NULL;
1096 static const struct got_error *
1097 create_ref(const char *refname, struct got_object_id *id,
1098 int verbosity, struct got_repository *repo)
1100 const struct got_error *err = NULL;
1101 struct got_reference *ref;
1102 char *id_str;
1104 err = got_object_id_str(&id_str, id);
1105 if (err)
1106 return err;
1108 err = got_ref_alloc(&ref, refname, id);
1109 if (err)
1110 goto done;
1112 err = got_ref_write(ref, repo);
1113 got_ref_close(ref);
1115 if (err == NULL && verbosity >= 0)
1116 printf("Created reference %s: %s\n", refname, id_str);
1117 done:
1118 free(id_str);
1119 return err;
1122 static int
1123 match_wanted_ref(const char *refname, const char *wanted_ref)
1125 if (strncmp(refname, "refs/", 5) != 0)
1126 return 0;
1127 refname += 5;
1130 * Prevent fetching of references that won't make any
1131 * sense outside of the remote repository's context.
1133 if (strncmp(refname, "got/", 4) == 0)
1134 return 0;
1135 if (strncmp(refname, "remotes/", 8) == 0)
1136 return 0;
1138 if (strncmp(wanted_ref, "refs/", 5) == 0)
1139 wanted_ref += 5;
1141 /* Allow prefix match. */
1142 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1143 return 1;
1145 /* Allow exact match. */
1146 return (strcmp(refname, wanted_ref) == 0);
1149 static int
1150 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1152 struct got_pathlist_entry *pe;
1154 TAILQ_FOREACH(pe, wanted_refs, entry) {
1155 if (match_wanted_ref(refname, pe->path))
1156 return 1;
1159 return 0;
1162 static const struct got_error *
1163 create_wanted_ref(const char *refname, struct got_object_id *id,
1164 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1166 const struct got_error *err;
1167 char *remote_refname;
1169 if (strncmp("refs/", refname, 5) == 0)
1170 refname += 5;
1172 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1173 remote_repo_name, refname) == -1)
1174 return got_error_from_errno("asprintf");
1176 err = create_ref(remote_refname, id, verbosity, repo);
1177 free(remote_refname);
1178 return err;
1181 static const struct got_error *
1182 create_gotconfig(const char *proto, const char *host, const char *port,
1183 const char *remote_repo_path, const char *default_branch,
1184 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1185 struct got_pathlist_head *wanted_refs, int mirror_references,
1186 struct got_repository *repo)
1188 const struct got_error *err = NULL;
1189 char *gotconfig_path = NULL;
1190 char *gotconfig = NULL;
1191 FILE *gotconfig_file = NULL;
1192 const char *branchname = NULL;
1193 char *branches = NULL, *refs = NULL;
1194 ssize_t n;
1196 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1197 struct got_pathlist_entry *pe;
1198 TAILQ_FOREACH(pe, wanted_branches, entry) {
1199 char *s;
1200 branchname = pe->path;
1201 if (strncmp(branchname, "refs/heads/", 11) == 0)
1202 branchname += 11;
1203 if (asprintf(&s, "%s\"%s\" ",
1204 branches ? branches : "", branchname) == -1) {
1205 err = got_error_from_errno("asprintf");
1206 goto done;
1208 free(branches);
1209 branches = s;
1211 } else if (!fetch_all_branches && default_branch) {
1212 branchname = default_branch;
1213 if (strncmp(branchname, "refs/heads/", 11) == 0)
1214 branchname += 11;
1215 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1220 if (!TAILQ_EMPTY(wanted_refs)) {
1221 struct got_pathlist_entry *pe;
1222 TAILQ_FOREACH(pe, wanted_refs, entry) {
1223 char *s;
1224 const char *refname = pe->path;
1225 if (strncmp(refname, "refs/", 5) == 0)
1226 branchname += 5;
1227 if (asprintf(&s, "%s\"%s\" ",
1228 refs ? refs : "", refname) == -1) {
1229 err = got_error_from_errno("asprintf");
1230 goto done;
1232 free(refs);
1233 refs = s;
1237 /* Create got.conf(5). */
1238 gotconfig_path = got_repo_get_path_gotconfig(repo);
1239 if (gotconfig_path == NULL) {
1240 err = got_error_from_errno("got_repo_get_path_gotconfig");
1241 goto done;
1243 gotconfig_file = fopen(gotconfig_path, "ae");
1244 if (gotconfig_file == NULL) {
1245 err = got_error_from_errno2("fopen", gotconfig_path);
1246 goto done;
1248 if (asprintf(&gotconfig,
1249 "remote \"%s\" {\n"
1250 "\tserver %s\n"
1251 "\tprotocol %s\n"
1252 "%s%s%s"
1253 "\trepository \"%s\"\n"
1254 "%s%s%s"
1255 "%s%s%s"
1256 "%s"
1257 "%s"
1258 "}\n",
1259 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1260 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1261 remote_repo_path, branches ? "\tbranch { " : "",
1262 branches ? branches : "", branches ? "}\n" : "",
1263 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1264 mirror_references ? "\tmirror-references yes\n" : "",
1265 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1269 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1270 if (n != strlen(gotconfig)) {
1271 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1272 goto done;
1275 done:
1276 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1277 err = got_error_from_errno2("fclose", gotconfig_path);
1278 free(gotconfig_path);
1279 free(branches);
1280 return err;
1283 static const struct got_error *
1284 create_gitconfig(const char *git_url, const char *default_branch,
1285 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1286 struct got_pathlist_head *wanted_refs, int mirror_references,
1287 struct got_repository *repo)
1289 const struct got_error *err = NULL;
1290 char *gitconfig_path = NULL;
1291 char *gitconfig = NULL;
1292 FILE *gitconfig_file = NULL;
1293 char *branches = NULL, *refs = NULL;
1294 const char *branchname;
1295 ssize_t n;
1297 /* Create a config file Git can understand. */
1298 gitconfig_path = got_repo_get_path_gitconfig(repo);
1299 if (gitconfig_path == NULL) {
1300 err = got_error_from_errno("got_repo_get_path_gitconfig");
1301 goto done;
1303 gitconfig_file = fopen(gitconfig_path, "ae");
1304 if (gitconfig_file == NULL) {
1305 err = got_error_from_errno2("fopen", gitconfig_path);
1306 goto done;
1308 if (fetch_all_branches) {
1309 if (mirror_references) {
1310 if (asprintf(&branches,
1311 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 } else if (asprintf(&branches,
1316 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1317 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1318 err = got_error_from_errno("asprintf");
1319 goto done;
1321 } else if (!TAILQ_EMPTY(wanted_branches)) {
1322 struct got_pathlist_entry *pe;
1323 TAILQ_FOREACH(pe, wanted_branches, entry) {
1324 char *s;
1325 branchname = pe->path;
1326 if (strncmp(branchname, "refs/heads/", 11) == 0)
1327 branchname += 11;
1328 if (mirror_references) {
1329 if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1331 branches ? branches : "",
1332 branchname, branchname) == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 } else if (asprintf(&s,
1337 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1338 branches ? branches : "",
1339 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1340 branchname) == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 free(branches);
1345 branches = s;
1347 } else {
1349 * If the server specified a default branch, use just that one.
1350 * Otherwise fall back to fetching all branches on next fetch.
1352 if (default_branch) {
1353 branchname = default_branch;
1354 if (strncmp(branchname, "refs/heads/", 11) == 0)
1355 branchname += 11;
1356 } else
1357 branchname = "*"; /* fall back to all branches */
1358 if (mirror_references) {
1359 if (asprintf(&branches,
1360 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1361 branchname, branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1365 } else if (asprintf(&branches,
1366 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1367 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1368 branchname) == -1) {
1369 err = got_error_from_errno("asprintf");
1370 goto done;
1373 if (!TAILQ_EMPTY(wanted_refs)) {
1374 struct got_pathlist_entry *pe;
1375 TAILQ_FOREACH(pe, wanted_refs, entry) {
1376 char *s;
1377 const char *refname = pe->path;
1378 if (strncmp(refname, "refs/", 5) == 0)
1379 refname += 5;
1380 if (mirror_references) {
1381 if (asprintf(&s,
1382 "%s\tfetch = refs/%s:refs/%s\n",
1383 refs ? refs : "", refname, refname) == -1) {
1384 err = got_error_from_errno("asprintf");
1385 goto done;
1387 } else if (asprintf(&s,
1388 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1389 refs ? refs : "",
1390 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1391 refname) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 free(refs);
1396 refs = s;
1400 if (asprintf(&gitconfig,
1401 "[remote \"%s\"]\n"
1402 "\turl = %s\n"
1403 "%s"
1404 "%s"
1405 "\tfetch = refs/tags/*:refs/tags/*\n",
1406 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1407 refs ? refs : "") == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1412 if (n != strlen(gitconfig)) {
1413 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1414 goto done;
1416 done:
1417 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1418 err = got_error_from_errno2("fclose", gitconfig_path);
1419 free(gitconfig_path);
1420 free(branches);
1421 return err;
1424 static const struct got_error *
1425 create_config_files(const char *proto, const char *host, const char *port,
1426 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1427 int mirror_references, struct got_pathlist_head *symrefs,
1428 struct got_pathlist_head *wanted_branches,
1429 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1431 const struct got_error *err = NULL;
1432 const char *default_branch = NULL;
1433 struct got_pathlist_entry *pe;
1436 * If we asked for a set of wanted branches then use the first
1437 * one of those.
1439 if (!TAILQ_EMPTY(wanted_branches)) {
1440 pe = TAILQ_FIRST(wanted_branches);
1441 default_branch = pe->path;
1442 } else {
1443 /* First HEAD ref listed by server is the default branch. */
1444 TAILQ_FOREACH(pe, symrefs, entry) {
1445 const char *refname = pe->path;
1446 const char *target = pe->data;
1448 if (strcmp(refname, GOT_REF_HEAD) != 0)
1449 continue;
1451 default_branch = target;
1452 break;
1456 /* Create got.conf(5). */
1457 err = create_gotconfig(proto, host, port, remote_repo_path,
1458 default_branch, fetch_all_branches, wanted_branches,
1459 wanted_refs, mirror_references, repo);
1460 if (err)
1461 return err;
1463 /* Create a config file Git can understand. */
1464 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1465 wanted_branches, wanted_refs, mirror_references, repo);
1468 static const struct got_error *
1469 cmd_clone(int argc, char *argv[])
1471 const struct got_error *error = NULL;
1472 const char *uri, *dirname;
1473 char *proto, *host, *port, *repo_name, *server_path;
1474 char *default_destdir = NULL, *id_str = NULL;
1475 const char *repo_path;
1476 struct got_repository *repo = NULL;
1477 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1478 struct got_pathlist_entry *pe;
1479 struct got_object_id *pack_hash = NULL;
1480 int ch, fetchfd = -1, fetchstatus;
1481 pid_t fetchpid = -1;
1482 struct got_fetch_progress_arg fpa;
1483 char *git_url = NULL;
1484 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1485 int list_refs_only = 0;
1487 TAILQ_INIT(&refs);
1488 TAILQ_INIT(&symrefs);
1489 TAILQ_INIT(&wanted_branches);
1490 TAILQ_INIT(&wanted_refs);
1492 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1493 switch (ch) {
1494 case 'a':
1495 fetch_all_branches = 1;
1496 break;
1497 case 'b':
1498 error = got_pathlist_append(&wanted_branches,
1499 optarg, NULL);
1500 if (error)
1501 return error;
1502 break;
1503 case 'l':
1504 list_refs_only = 1;
1505 break;
1506 case 'm':
1507 mirror_references = 1;
1508 break;
1509 case 'v':
1510 if (verbosity < 0)
1511 verbosity = 0;
1512 else if (verbosity < 3)
1513 verbosity++;
1514 break;
1515 case 'q':
1516 verbosity = -1;
1517 break;
1518 case 'R':
1519 error = got_pathlist_append(&wanted_refs,
1520 optarg, NULL);
1521 if (error)
1522 return error;
1523 break;
1524 default:
1525 usage_clone();
1526 break;
1529 argc -= optind;
1530 argv += optind;
1532 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1533 option_conflict('a', 'b');
1534 if (list_refs_only) {
1535 if (!TAILQ_EMPTY(&wanted_branches))
1536 option_conflict('l', 'b');
1537 if (fetch_all_branches)
1538 option_conflict('l', 'a');
1539 if (mirror_references)
1540 option_conflict('l', 'm');
1541 if (!TAILQ_EMPTY(&wanted_refs))
1542 option_conflict('l', 'R');
1545 uri = argv[0];
1547 if (argc == 1)
1548 dirname = NULL;
1549 else if (argc == 2)
1550 dirname = argv[1];
1551 else
1552 usage_clone();
1554 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1555 &repo_name, uri);
1556 if (error)
1557 goto done;
1559 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1560 host, port ? ":" : "", port ? port : "",
1561 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1562 error = got_error_from_errno("asprintf");
1563 goto done;
1566 if (strcmp(proto, "git") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd dns inet unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "git+ssh") == 0 ||
1573 strcmp(proto, "ssh") == 0) {
1574 #ifndef PROFILE
1575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1576 "sendfd unveil", NULL) == -1)
1577 err(1, "pledge");
1578 #endif
1579 } else if (strcmp(proto, "http") == 0 ||
1580 strcmp(proto, "git+http") == 0) {
1581 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1582 goto done;
1583 } else {
1584 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1585 goto done;
1587 if (dirname == NULL) {
1588 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1589 error = got_error_from_errno("asprintf");
1590 goto done;
1592 repo_path = default_destdir;
1593 } else
1594 repo_path = dirname;
1596 if (!list_refs_only) {
1597 error = got_path_mkdir(repo_path);
1598 if (error &&
1599 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1600 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1601 goto done;
1602 if (!got_path_dir_is_empty(repo_path)) {
1603 error = got_error_path(repo_path,
1604 GOT_ERR_DIR_NOT_EMPTY);
1605 goto done;
1609 error = got_dial_apply_unveil(proto);
1610 if (error)
1611 goto done;
1613 error = apply_unveil(repo_path, 0, NULL);
1614 if (error)
1615 goto done;
1617 if (verbosity >= 0)
1618 printf("Connecting to %s%s%s\n", host,
1619 port ? ":" : "", port ? port : "");
1621 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1622 server_path, verbosity);
1623 if (error)
1624 goto done;
1626 if (!list_refs_only) {
1627 error = got_repo_init(repo_path);
1628 if (error)
1629 goto done;
1630 error = got_repo_open(&repo, repo_path, NULL);
1631 if (error)
1632 goto done;
1635 fpa.last_scaled_size[0] = '\0';
1636 fpa.last_p_indexed = -1;
1637 fpa.last_p_resolved = -1;
1638 fpa.verbosity = verbosity;
1639 fpa.create_configs = 1;
1640 fpa.configs_created = 0;
1641 fpa.repo = repo;
1642 fpa.config_info.symrefs = &symrefs;
1643 fpa.config_info.wanted_branches = &wanted_branches;
1644 fpa.config_info.wanted_refs = &wanted_refs;
1645 fpa.config_info.proto = proto;
1646 fpa.config_info.host = host;
1647 fpa.config_info.port = port;
1648 fpa.config_info.remote_repo_path = server_path;
1649 fpa.config_info.git_url = git_url;
1650 fpa.config_info.fetch_all_branches = fetch_all_branches;
1651 fpa.config_info.mirror_references = mirror_references;
1652 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1653 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1654 fetch_all_branches, &wanted_branches, &wanted_refs,
1655 list_refs_only, verbosity, fetchfd, repo,
1656 fetch_progress, &fpa);
1657 if (error)
1658 goto done;
1660 if (list_refs_only) {
1661 error = list_remote_refs(&symrefs, &refs);
1662 goto done;
1665 if (pack_hash == NULL) {
1666 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1667 "server sent an empty pack file");
1668 goto done;
1670 error = got_object_id_str(&id_str, pack_hash);
1671 if (error)
1672 goto done;
1673 if (verbosity >= 0)
1674 printf("\nFetched %s.pack\n", id_str);
1675 free(id_str);
1677 /* Set up references provided with the pack file. */
1678 TAILQ_FOREACH(pe, &refs, entry) {
1679 const char *refname = pe->path;
1680 struct got_object_id *id = pe->data;
1681 char *remote_refname;
1683 if (is_wanted_ref(&wanted_refs, refname) &&
1684 !mirror_references) {
1685 error = create_wanted_ref(refname, id,
1686 GOT_FETCH_DEFAULT_REMOTE_NAME,
1687 verbosity - 1, repo);
1688 if (error)
1689 goto done;
1690 continue;
1693 error = create_ref(refname, id, verbosity - 1, repo);
1694 if (error)
1695 goto done;
1697 if (mirror_references)
1698 continue;
1700 if (strncmp("refs/heads/", refname, 11) != 0)
1701 continue;
1703 if (asprintf(&remote_refname,
1704 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1705 refname + 11) == -1) {
1706 error = got_error_from_errno("asprintf");
1707 goto done;
1709 error = create_ref(remote_refname, id, verbosity - 1, repo);
1710 free(remote_refname);
1711 if (error)
1712 goto done;
1715 /* Set the HEAD reference if the server provided one. */
1716 TAILQ_FOREACH(pe, &symrefs, entry) {
1717 struct got_reference *target_ref;
1718 const char *refname = pe->path;
1719 const char *target = pe->data;
1720 char *remote_refname = NULL, *remote_target = NULL;
1722 if (strcmp(refname, GOT_REF_HEAD) != 0)
1723 continue;
1725 error = got_ref_open(&target_ref, repo, target, 0);
1726 if (error) {
1727 if (error->code == GOT_ERR_NOT_REF) {
1728 error = NULL;
1729 continue;
1731 goto done;
1734 error = create_symref(refname, target_ref, verbosity, repo);
1735 got_ref_close(target_ref);
1736 if (error)
1737 goto done;
1739 if (mirror_references)
1740 continue;
1742 if (strncmp("refs/heads/", target, 11) != 0)
1743 continue;
1745 if (asprintf(&remote_refname,
1746 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1747 refname) == -1) {
1748 error = got_error_from_errno("asprintf");
1749 goto done;
1751 if (asprintf(&remote_target,
1752 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1753 target + 11) == -1) {
1754 error = got_error_from_errno("asprintf");
1755 free(remote_refname);
1756 goto done;
1758 error = got_ref_open(&target_ref, repo, remote_target, 0);
1759 if (error) {
1760 free(remote_refname);
1761 free(remote_target);
1762 if (error->code == GOT_ERR_NOT_REF) {
1763 error = NULL;
1764 continue;
1766 goto done;
1768 error = create_symref(remote_refname, target_ref,
1769 verbosity - 1, repo);
1770 free(remote_refname);
1771 free(remote_target);
1772 got_ref_close(target_ref);
1773 if (error)
1774 goto done;
1776 if (pe == NULL) {
1778 * We failed to set the HEAD reference. If we asked for
1779 * a set of wanted branches use the first of one of those
1780 * which could be fetched instead.
1782 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1783 const char *target = pe->path;
1784 struct got_reference *target_ref;
1786 error = got_ref_open(&target_ref, repo, target, 0);
1787 if (error) {
1788 if (error->code == GOT_ERR_NOT_REF) {
1789 error = NULL;
1790 continue;
1792 goto done;
1795 error = create_symref(GOT_REF_HEAD, target_ref,
1796 verbosity, repo);
1797 got_ref_close(target_ref);
1798 if (error)
1799 goto done;
1800 break;
1804 if (verbosity >= 0)
1805 printf("Created %s repository '%s'\n",
1806 mirror_references ? "mirrored" : "cloned", repo_path);
1807 done:
1808 if (fetchpid > 0) {
1809 if (kill(fetchpid, SIGTERM) == -1)
1810 error = got_error_from_errno("kill");
1811 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1812 error = got_error_from_errno("waitpid");
1814 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1815 error = got_error_from_errno("close");
1816 if (repo) {
1817 const struct got_error *close_err = got_repo_close(repo);
1818 if (error == NULL)
1819 error = close_err;
1821 TAILQ_FOREACH(pe, &refs, entry) {
1822 free((void *)pe->path);
1823 free(pe->data);
1825 got_pathlist_free(&refs);
1826 TAILQ_FOREACH(pe, &symrefs, entry) {
1827 free((void *)pe->path);
1828 free(pe->data);
1830 got_pathlist_free(&symrefs);
1831 got_pathlist_free(&wanted_branches);
1832 got_pathlist_free(&wanted_refs);
1833 free(pack_hash);
1834 free(proto);
1835 free(host);
1836 free(port);
1837 free(server_path);
1838 free(repo_name);
1839 free(default_destdir);
1840 free(git_url);
1841 return error;
1844 static const struct got_error *
1845 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1846 int replace_tags, int verbosity, struct got_repository *repo)
1848 const struct got_error *err = NULL;
1849 char *new_id_str = NULL;
1850 struct got_object_id *old_id = NULL;
1852 err = got_object_id_str(&new_id_str, new_id);
1853 if (err)
1854 goto done;
1856 if (!replace_tags &&
1857 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1858 err = got_ref_resolve(&old_id, repo, ref);
1859 if (err)
1860 goto done;
1861 if (got_object_id_cmp(old_id, new_id) == 0)
1862 goto done;
1863 if (verbosity >= 0) {
1864 printf("Rejecting update of existing tag %s: %s\n",
1865 got_ref_get_name(ref), new_id_str);
1867 goto done;
1870 if (got_ref_is_symbolic(ref)) {
1871 if (verbosity >= 0) {
1872 printf("Replacing reference %s: %s\n",
1873 got_ref_get_name(ref),
1874 got_ref_get_symref_target(ref));
1876 err = got_ref_change_symref_to_ref(ref, new_id);
1877 if (err)
1878 goto done;
1879 err = got_ref_write(ref, repo);
1880 if (err)
1881 goto done;
1882 } else {
1883 err = got_ref_resolve(&old_id, repo, ref);
1884 if (err)
1885 goto done;
1886 if (got_object_id_cmp(old_id, new_id) == 0)
1887 goto done;
1889 err = got_ref_change_ref(ref, new_id);
1890 if (err)
1891 goto done;
1892 err = got_ref_write(ref, repo);
1893 if (err)
1894 goto done;
1897 if (verbosity >= 0)
1898 printf("Updated %s: %s\n", got_ref_get_name(ref),
1899 new_id_str);
1900 done:
1901 free(old_id);
1902 free(new_id_str);
1903 return err;
1906 static const struct got_error *
1907 update_symref(const char *refname, struct got_reference *target_ref,
1908 int verbosity, struct got_repository *repo)
1910 const struct got_error *err = NULL, *unlock_err;
1911 struct got_reference *symref;
1912 int symref_is_locked = 0;
1914 err = got_ref_open(&symref, repo, refname, 1);
1915 if (err) {
1916 if (err->code != GOT_ERR_NOT_REF)
1917 return err;
1918 err = got_ref_alloc_symref(&symref, refname, target_ref);
1919 if (err)
1920 goto done;
1922 err = got_ref_write(symref, repo);
1923 if (err)
1924 goto done;
1926 if (verbosity >= 0)
1927 printf("Created reference %s: %s\n",
1928 got_ref_get_name(symref),
1929 got_ref_get_symref_target(symref));
1930 } else {
1931 symref_is_locked = 1;
1933 if (strcmp(got_ref_get_symref_target(symref),
1934 got_ref_get_name(target_ref)) == 0)
1935 goto done;
1937 err = got_ref_change_symref(symref,
1938 got_ref_get_name(target_ref));
1939 if (err)
1940 goto done;
1942 err = got_ref_write(symref, repo);
1943 if (err)
1944 goto done;
1946 if (verbosity >= 0)
1947 printf("Updated %s: %s\n", got_ref_get_name(symref),
1948 got_ref_get_symref_target(symref));
1951 done:
1952 if (symref_is_locked) {
1953 unlock_err = got_ref_unlock(symref);
1954 if (unlock_err && err == NULL)
1955 err = unlock_err;
1957 got_ref_close(symref);
1958 return err;
1961 __dead static void
1962 usage_fetch(void)
1964 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1965 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1966 "[remote-repository-name]\n",
1967 getprogname());
1968 exit(1);
1971 static const struct got_error *
1972 delete_missing_ref(struct got_reference *ref,
1973 int verbosity, struct got_repository *repo)
1975 const struct got_error *err = NULL;
1976 struct got_object_id *id = NULL;
1977 char *id_str = NULL;
1979 if (got_ref_is_symbolic(ref)) {
1980 err = got_ref_delete(ref, repo);
1981 if (err)
1982 return err;
1983 if (verbosity >= 0) {
1984 printf("Deleted %s: %s\n",
1985 got_ref_get_name(ref),
1986 got_ref_get_symref_target(ref));
1988 } else {
1989 err = got_ref_resolve(&id, repo, ref);
1990 if (err)
1991 return err;
1992 err = got_object_id_str(&id_str, id);
1993 if (err)
1994 goto done;
1996 err = got_ref_delete(ref, repo);
1997 if (err)
1998 goto done;
1999 if (verbosity >= 0) {
2000 printf("Deleted %s: %s\n",
2001 got_ref_get_name(ref), id_str);
2004 done:
2005 free(id);
2006 free(id_str);
2007 return NULL;
2010 static const struct got_error *
2011 delete_missing_refs(struct got_pathlist_head *their_refs,
2012 struct got_pathlist_head *their_symrefs,
2013 const struct got_remote_repo *remote,
2014 int verbosity, struct got_repository *repo)
2016 const struct got_error *err = NULL, *unlock_err;
2017 struct got_reflist_head my_refs;
2018 struct got_reflist_entry *re;
2019 struct got_pathlist_entry *pe;
2020 char *remote_namespace = NULL;
2021 char *local_refname = NULL;
2023 TAILQ_INIT(&my_refs);
2025 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2026 == -1)
2027 return got_error_from_errno("asprintf");
2029 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2030 if (err)
2031 goto done;
2033 TAILQ_FOREACH(re, &my_refs, entry) {
2034 const char *refname = got_ref_get_name(re->ref);
2035 const char *their_refname;
2037 if (remote->mirror_references) {
2038 their_refname = refname;
2039 } else {
2040 if (strncmp(refname, remote_namespace,
2041 strlen(remote_namespace)) == 0) {
2042 if (strcmp(refname + strlen(remote_namespace),
2043 GOT_REF_HEAD) == 0)
2044 continue;
2045 if (asprintf(&local_refname, "refs/heads/%s",
2046 refname + strlen(remote_namespace)) == -1) {
2047 err = got_error_from_errno("asprintf");
2048 goto done;
2050 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2051 continue;
2053 their_refname = local_refname;
2056 TAILQ_FOREACH(pe, their_refs, entry) {
2057 if (strcmp(their_refname, pe->path) == 0)
2058 break;
2060 if (pe != NULL)
2061 continue;
2063 TAILQ_FOREACH(pe, their_symrefs, entry) {
2064 if (strcmp(their_refname, pe->path) == 0)
2065 break;
2067 if (pe != NULL)
2068 continue;
2070 err = delete_missing_ref(re->ref, verbosity, repo);
2071 if (err)
2072 break;
2074 if (local_refname) {
2075 struct got_reference *ref;
2076 err = got_ref_open(&ref, repo, local_refname, 1);
2077 if (err) {
2078 if (err->code != GOT_ERR_NOT_REF)
2079 break;
2080 free(local_refname);
2081 local_refname = NULL;
2082 continue;
2084 err = delete_missing_ref(ref, verbosity, repo);
2085 if (err)
2086 break;
2087 unlock_err = got_ref_unlock(ref);
2088 got_ref_close(ref);
2089 if (unlock_err && err == NULL) {
2090 err = unlock_err;
2091 break;
2094 free(local_refname);
2095 local_refname = NULL;
2098 done:
2099 free(remote_namespace);
2100 free(local_refname);
2101 return err;
2104 static const struct got_error *
2105 update_wanted_ref(const char *refname, struct got_object_id *id,
2106 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2108 const struct got_error *err, *unlock_err;
2109 char *remote_refname;
2110 struct got_reference *ref;
2112 if (strncmp("refs/", refname, 5) == 0)
2113 refname += 5;
2115 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2116 remote_repo_name, refname) == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_open(&ref, repo, remote_refname, 1);
2120 if (err) {
2121 if (err->code != GOT_ERR_NOT_REF)
2122 goto done;
2123 err = create_ref(remote_refname, id, verbosity, repo);
2124 } else {
2125 err = update_ref(ref, id, 0, verbosity, repo);
2126 unlock_err = got_ref_unlock(ref);
2127 if (unlock_err && err == NULL)
2128 err = unlock_err;
2129 got_ref_close(ref);
2131 done:
2132 free(remote_refname);
2133 return err;
2136 static const struct got_error *
2137 delete_ref(struct got_repository *repo, struct got_reference *ref)
2139 const struct got_error *err = NULL;
2140 struct got_object_id *id = NULL;
2141 char *id_str = NULL;
2142 const char *target;
2144 if (got_ref_is_symbolic(ref)) {
2145 target = got_ref_get_symref_target(ref);
2146 } else {
2147 err = got_ref_resolve(&id, repo, ref);
2148 if (err)
2149 goto done;
2150 err = got_object_id_str(&id_str, id);
2151 if (err)
2152 goto done;
2153 target = id_str;
2156 err = got_ref_delete(ref, repo);
2157 if (err)
2158 goto done;
2160 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2161 done:
2162 free(id);
2163 free(id_str);
2164 return err;
2167 static const struct got_error *
2168 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2170 const struct got_error *err = NULL;
2171 struct got_reflist_head refs;
2172 struct got_reflist_entry *re;
2173 char *prefix;
2175 TAILQ_INIT(&refs);
2177 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2178 err = got_error_from_errno("asprintf");
2179 goto done;
2181 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2182 if (err)
2183 goto done;
2185 TAILQ_FOREACH(re, &refs, entry)
2186 delete_ref(repo, re->ref);
2187 done:
2188 got_ref_list_free(&refs);
2189 return err;
2192 static const struct got_error *
2193 cmd_fetch(int argc, char *argv[])
2195 const struct got_error *error = NULL, *unlock_err;
2196 char *cwd = NULL, *repo_path = NULL;
2197 const char *remote_name;
2198 char *proto = NULL, *host = NULL, *port = NULL;
2199 char *repo_name = NULL, *server_path = NULL;
2200 const struct got_remote_repo *remotes, *remote = NULL;
2201 int nremotes;
2202 char *id_str = NULL;
2203 struct got_repository *repo = NULL;
2204 struct got_worktree *worktree = NULL;
2205 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2206 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2207 struct got_pathlist_entry *pe;
2208 struct got_object_id *pack_hash = NULL;
2209 int i, ch, fetchfd = -1, fetchstatus;
2210 pid_t fetchpid = -1;
2211 struct got_fetch_progress_arg fpa;
2212 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2213 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2215 TAILQ_INIT(&refs);
2216 TAILQ_INIT(&symrefs);
2217 TAILQ_INIT(&wanted_branches);
2218 TAILQ_INIT(&wanted_refs);
2220 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2221 switch (ch) {
2222 case 'a':
2223 fetch_all_branches = 1;
2224 break;
2225 case 'b':
2226 error = got_pathlist_append(&wanted_branches,
2227 optarg, NULL);
2228 if (error)
2229 return error;
2230 break;
2231 case 'd':
2232 delete_refs = 1;
2233 break;
2234 case 'l':
2235 list_refs_only = 1;
2236 break;
2237 case 'r':
2238 repo_path = realpath(optarg, NULL);
2239 if (repo_path == NULL)
2240 return got_error_from_errno2("realpath",
2241 optarg);
2242 got_path_strip_trailing_slashes(repo_path);
2243 break;
2244 case 't':
2245 replace_tags = 1;
2246 break;
2247 case 'v':
2248 if (verbosity < 0)
2249 verbosity = 0;
2250 else if (verbosity < 3)
2251 verbosity++;
2252 break;
2253 case 'q':
2254 verbosity = -1;
2255 break;
2256 case 'R':
2257 error = got_pathlist_append(&wanted_refs,
2258 optarg, NULL);
2259 if (error)
2260 return error;
2261 break;
2262 case 'X':
2263 delete_remote = 1;
2264 break;
2265 default:
2266 usage_fetch();
2267 break;
2270 argc -= optind;
2271 argv += optind;
2273 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2274 option_conflict('a', 'b');
2275 if (list_refs_only) {
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('l', 'b');
2278 if (fetch_all_branches)
2279 option_conflict('l', 'a');
2280 if (delete_refs)
2281 option_conflict('l', 'd');
2282 if (delete_remote)
2283 option_conflict('l', 'X');
2285 if (delete_remote) {
2286 if (fetch_all_branches)
2287 option_conflict('X', 'a');
2288 if (!TAILQ_EMPTY(&wanted_branches))
2289 option_conflict('X', 'b');
2290 if (delete_refs)
2291 option_conflict('X', 'd');
2292 if (replace_tags)
2293 option_conflict('X', 't');
2294 if (!TAILQ_EMPTY(&wanted_refs))
2295 option_conflict('X', 'R');
2298 if (argc == 0) {
2299 if (delete_remote)
2300 errx(1, "-X option requires a remote name");
2301 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2302 } else if (argc == 1)
2303 remote_name = argv[0];
2304 else
2305 usage_fetch();
2307 cwd = getcwd(NULL, 0);
2308 if (cwd == NULL) {
2309 error = got_error_from_errno("getcwd");
2310 goto done;
2313 if (repo_path == NULL) {
2314 error = got_worktree_open(&worktree, cwd);
2315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2316 goto done;
2317 else
2318 error = NULL;
2319 if (worktree) {
2320 repo_path =
2321 strdup(got_worktree_get_repo_path(worktree));
2322 if (repo_path == NULL)
2323 error = got_error_from_errno("strdup");
2324 if (error)
2325 goto done;
2326 } else {
2327 repo_path = strdup(cwd);
2328 if (repo_path == NULL) {
2329 error = got_error_from_errno("strdup");
2330 goto done;
2335 error = got_repo_open(&repo, repo_path, NULL);
2336 if (error)
2337 goto done;
2339 if (delete_remote) {
2340 error = delete_refs_for_remote(repo, remote_name);
2341 goto done; /* nothing else to do */
2344 if (worktree) {
2345 worktree_conf = got_worktree_get_gotconfig(worktree);
2346 if (worktree_conf) {
2347 got_gotconfig_get_remotes(&nremotes, &remotes,
2348 worktree_conf);
2349 for (i = 0; i < nremotes; i++) {
2350 if (strcmp(remotes[i].name, remote_name) == 0) {
2351 remote = &remotes[i];
2352 break;
2357 if (remote == NULL) {
2358 repo_conf = got_repo_get_gotconfig(repo);
2359 if (repo_conf) {
2360 got_gotconfig_get_remotes(&nremotes, &remotes,
2361 repo_conf);
2362 for (i = 0; i < nremotes; i++) {
2363 if (strcmp(remotes[i].name, remote_name) == 0) {
2364 remote = &remotes[i];
2365 break;
2370 if (remote == NULL) {
2371 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2372 for (i = 0; i < nremotes; i++) {
2373 if (strcmp(remotes[i].name, remote_name) == 0) {
2374 remote = &remotes[i];
2375 break;
2379 if (remote == NULL) {
2380 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2381 goto done;
2384 if (TAILQ_EMPTY(&wanted_branches)) {
2385 if (!fetch_all_branches)
2386 fetch_all_branches = remote->fetch_all_branches;
2387 for (i = 0; i < remote->nfetch_branches; i++) {
2388 got_pathlist_append(&wanted_branches,
2389 remote->fetch_branches[i], NULL);
2392 if (TAILQ_EMPTY(&wanted_refs)) {
2393 for (i = 0; i < remote->nfetch_refs; i++) {
2394 got_pathlist_append(&wanted_refs,
2395 remote->fetch_refs[i], NULL);
2399 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2400 &repo_name, remote->fetch_url);
2401 if (error)
2402 goto done;
2404 if (strcmp(proto, "git") == 0) {
2405 #ifndef PROFILE
2406 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2407 "sendfd dns inet unveil", NULL) == -1)
2408 err(1, "pledge");
2409 #endif
2410 } else if (strcmp(proto, "git+ssh") == 0 ||
2411 strcmp(proto, "ssh") == 0) {
2412 #ifndef PROFILE
2413 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2414 "sendfd unveil", NULL) == -1)
2415 err(1, "pledge");
2416 #endif
2417 } else if (strcmp(proto, "http") == 0 ||
2418 strcmp(proto, "git+http") == 0) {
2419 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2420 goto done;
2421 } else {
2422 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2423 goto done;
2426 error = got_dial_apply_unveil(proto);
2427 if (error)
2428 goto done;
2430 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2431 if (error)
2432 goto done;
2434 if (verbosity >= 0)
2435 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2436 port ? ":" : "", port ? port : "");
2438 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2439 server_path, verbosity);
2440 if (error)
2441 goto done;
2443 fpa.last_scaled_size[0] = '\0';
2444 fpa.last_p_indexed = -1;
2445 fpa.last_p_resolved = -1;
2446 fpa.verbosity = verbosity;
2447 fpa.repo = repo;
2448 fpa.create_configs = 0;
2449 fpa.configs_created = 0;
2450 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2451 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2452 remote->mirror_references, fetch_all_branches, &wanted_branches,
2453 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2454 fetch_progress, &fpa);
2455 if (error)
2456 goto done;
2458 if (list_refs_only) {
2459 error = list_remote_refs(&symrefs, &refs);
2460 goto done;
2463 if (pack_hash == NULL) {
2464 if (verbosity >= 0)
2465 printf("Already up-to-date\n");
2466 } else if (verbosity >= 0) {
2467 error = got_object_id_str(&id_str, pack_hash);
2468 if (error)
2469 goto done;
2470 printf("\nFetched %s.pack\n", id_str);
2471 free(id_str);
2472 id_str = NULL;
2475 /* Update references provided with the pack file. */
2476 TAILQ_FOREACH(pe, &refs, entry) {
2477 const char *refname = pe->path;
2478 struct got_object_id *id = pe->data;
2479 struct got_reference *ref;
2480 char *remote_refname;
2482 if (is_wanted_ref(&wanted_refs, refname) &&
2483 !remote->mirror_references) {
2484 error = update_wanted_ref(refname, id,
2485 remote->name, verbosity, repo);
2486 if (error)
2487 goto done;
2488 continue;
2491 if (remote->mirror_references ||
2492 strncmp("refs/tags/", refname, 10) == 0) {
2493 error = got_ref_open(&ref, repo, refname, 1);
2494 if (error) {
2495 if (error->code != GOT_ERR_NOT_REF)
2496 goto done;
2497 error = create_ref(refname, id, verbosity,
2498 repo);
2499 if (error)
2500 goto done;
2501 } else {
2502 error = update_ref(ref, id, replace_tags,
2503 verbosity, repo);
2504 unlock_err = got_ref_unlock(ref);
2505 if (unlock_err && error == NULL)
2506 error = unlock_err;
2507 got_ref_close(ref);
2508 if (error)
2509 goto done;
2511 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2512 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2513 remote_name, refname + 11) == -1) {
2514 error = got_error_from_errno("asprintf");
2515 goto done;
2518 error = got_ref_open(&ref, repo, remote_refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(remote_refname, id,
2523 verbosity, repo);
2524 if (error)
2525 goto done;
2526 } else {
2527 error = update_ref(ref, id, replace_tags,
2528 verbosity, repo);
2529 unlock_err = got_ref_unlock(ref);
2530 if (unlock_err && error == NULL)
2531 error = unlock_err;
2532 got_ref_close(ref);
2533 if (error)
2534 goto done;
2537 /* Also create a local branch if none exists yet. */
2538 error = got_ref_open(&ref, repo, refname, 1);
2539 if (error) {
2540 if (error->code != GOT_ERR_NOT_REF)
2541 goto done;
2542 error = create_ref(refname, id, verbosity,
2543 repo);
2544 if (error)
2545 goto done;
2546 } else {
2547 unlock_err = got_ref_unlock(ref);
2548 if (unlock_err && error == NULL)
2549 error = unlock_err;
2550 got_ref_close(ref);
2554 if (delete_refs) {
2555 error = delete_missing_refs(&refs, &symrefs, remote,
2556 verbosity, repo);
2557 if (error)
2558 goto done;
2561 if (!remote->mirror_references) {
2562 /* Update remote HEAD reference if the server provided one. */
2563 TAILQ_FOREACH(pe, &symrefs, entry) {
2564 struct got_reference *target_ref;
2565 const char *refname = pe->path;
2566 const char *target = pe->data;
2567 char *remote_refname = NULL, *remote_target = NULL;
2569 if (strcmp(refname, GOT_REF_HEAD) != 0)
2570 continue;
2572 if (strncmp("refs/heads/", target, 11) != 0)
2573 continue;
2575 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2576 remote->name, refname) == -1) {
2577 error = got_error_from_errno("asprintf");
2578 goto done;
2580 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2581 remote->name, target + 11) == -1) {
2582 error = got_error_from_errno("asprintf");
2583 free(remote_refname);
2584 goto done;
2587 error = got_ref_open(&target_ref, repo, remote_target,
2588 0);
2589 if (error) {
2590 free(remote_refname);
2591 free(remote_target);
2592 if (error->code == GOT_ERR_NOT_REF) {
2593 error = NULL;
2594 continue;
2596 goto done;
2598 error = update_symref(remote_refname, target_ref,
2599 verbosity, repo);
2600 free(remote_refname);
2601 free(remote_target);
2602 got_ref_close(target_ref);
2603 if (error)
2604 goto done;
2607 done:
2608 if (fetchpid > 0) {
2609 if (kill(fetchpid, SIGTERM) == -1)
2610 error = got_error_from_errno("kill");
2611 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2612 error = got_error_from_errno("waitpid");
2614 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2615 error = got_error_from_errno("close");
2616 if (repo) {
2617 const struct got_error *close_err = got_repo_close(repo);
2618 if (error == NULL)
2619 error = close_err;
2621 if (worktree)
2622 got_worktree_close(worktree);
2623 TAILQ_FOREACH(pe, &refs, entry) {
2624 free((void *)pe->path);
2625 free(pe->data);
2627 got_pathlist_free(&refs);
2628 TAILQ_FOREACH(pe, &symrefs, entry) {
2629 free((void *)pe->path);
2630 free(pe->data);
2632 got_pathlist_free(&symrefs);
2633 got_pathlist_free(&wanted_branches);
2634 got_pathlist_free(&wanted_refs);
2635 free(id_str);
2636 free(cwd);
2637 free(repo_path);
2638 free(pack_hash);
2639 free(proto);
2640 free(host);
2641 free(port);
2642 free(server_path);
2643 free(repo_name);
2644 return error;
2648 __dead static void
2649 usage_checkout(void)
2651 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2652 "[-p prefix] [-q] repository-path [worktree-path]\n",
2653 getprogname());
2654 exit(1);
2657 static void
2658 show_worktree_base_ref_warning(void)
2660 fprintf(stderr, "%s: warning: could not create a reference "
2661 "to the work tree's base commit; the commit could be "
2662 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2663 "repository writable and running 'got update' will prevent this\n",
2664 getprogname());
2667 struct got_checkout_progress_arg {
2668 const char *worktree_path;
2669 int had_base_commit_ref_error;
2670 int verbosity;
2673 static const struct got_error *
2674 checkout_progress(void *arg, unsigned char status, const char *path)
2676 struct got_checkout_progress_arg *a = arg;
2678 /* Base commit bump happens silently. */
2679 if (status == GOT_STATUS_BUMP_BASE)
2680 return NULL;
2682 if (status == GOT_STATUS_BASE_REF_ERR) {
2683 a->had_base_commit_ref_error = 1;
2684 return NULL;
2687 while (path[0] == '/')
2688 path++;
2690 if (a->verbosity >= 0)
2691 printf("%c %s/%s\n", status, a->worktree_path, path);
2693 return NULL;
2696 static const struct got_error *
2697 check_cancelled(void *arg)
2699 if (sigint_received || sigpipe_received)
2700 return got_error(GOT_ERR_CANCELLED);
2701 return NULL;
2704 static const struct got_error *
2705 check_linear_ancestry(struct got_object_id *commit_id,
2706 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2707 struct got_repository *repo)
2709 const struct got_error *err = NULL;
2710 struct got_object_id *yca_id;
2712 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2713 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2714 if (err)
2715 return err;
2717 if (yca_id == NULL)
2718 return got_error(GOT_ERR_ANCESTRY);
2721 * Require a straight line of history between the target commit
2722 * and the work tree's base commit.
2724 * Non-linear situations such as this require a rebase:
2726 * (commit) D F (base_commit)
2727 * \ /
2728 * C E
2729 * \ /
2730 * B (yca)
2731 * |
2732 * A
2734 * 'got update' only handles linear cases:
2735 * Update forwards in time: A (base/yca) - B - C - D (commit)
2736 * Update backwards in time: D (base) - C - B - A (commit/yca)
2738 if (allow_forwards_in_time_only) {
2739 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2740 return got_error(GOT_ERR_ANCESTRY);
2741 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2742 got_object_id_cmp(base_commit_id, yca_id) != 0)
2743 return got_error(GOT_ERR_ANCESTRY);
2745 free(yca_id);
2746 return NULL;
2749 static const struct got_error *
2750 check_same_branch(struct got_object_id *commit_id,
2751 struct got_reference *head_ref, struct got_object_id *yca_id,
2752 struct got_repository *repo)
2754 const struct got_error *err = NULL;
2755 struct got_commit_graph *graph = NULL;
2756 struct got_object_id *head_commit_id = NULL;
2757 int is_same_branch = 0;
2759 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2760 if (err)
2761 goto done;
2763 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2764 is_same_branch = 1;
2765 goto done;
2767 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2768 is_same_branch = 1;
2769 goto done;
2772 err = got_commit_graph_open(&graph, "/", 1);
2773 if (err)
2774 goto done;
2776 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2777 check_cancelled, NULL);
2778 if (err)
2779 goto done;
2781 for (;;) {
2782 struct got_object_id *id;
2783 err = got_commit_graph_iter_next(&id, graph, repo,
2784 check_cancelled, NULL);
2785 if (err) {
2786 if (err->code == GOT_ERR_ITER_COMPLETED)
2787 err = NULL;
2788 break;
2791 if (id) {
2792 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2793 break;
2794 if (got_object_id_cmp(id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 break;
2800 done:
2801 if (graph)
2802 got_commit_graph_close(graph);
2803 free(head_commit_id);
2804 if (!err && !is_same_branch)
2805 err = got_error(GOT_ERR_ANCESTRY);
2806 return err;
2809 static const struct got_error *
2810 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2812 static char msg[512];
2813 const char *branch_name;
2815 if (got_ref_is_symbolic(ref))
2816 branch_name = got_ref_get_symref_target(ref);
2817 else
2818 branch_name = got_ref_get_name(ref);
2820 if (strncmp("refs/heads/", branch_name, 11) == 0)
2821 branch_name += 11;
2823 snprintf(msg, sizeof(msg),
2824 "target commit is not contained in branch '%s'; "
2825 "the branch to use must be specified with -b; "
2826 "if necessary a new branch can be created for "
2827 "this commit with 'got branch -c %s BRANCH_NAME'",
2828 branch_name, commit_id_str);
2830 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2833 static const struct got_error *
2834 cmd_checkout(int argc, char *argv[])
2836 const struct got_error *error = NULL;
2837 struct got_repository *repo = NULL;
2838 struct got_reference *head_ref = NULL, *ref = NULL;
2839 struct got_worktree *worktree = NULL;
2840 char *repo_path = NULL;
2841 char *worktree_path = NULL;
2842 const char *path_prefix = "";
2843 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2844 char *commit_id_str = NULL;
2845 struct got_object_id *commit_id = NULL;
2846 char *cwd = NULL;
2847 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2848 struct got_pathlist_head paths;
2849 struct got_checkout_progress_arg cpa;
2851 TAILQ_INIT(&paths);
2853 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2854 switch (ch) {
2855 case 'b':
2856 branch_name = optarg;
2857 break;
2858 case 'c':
2859 commit_id_str = strdup(optarg);
2860 if (commit_id_str == NULL)
2861 return got_error_from_errno("strdup");
2862 break;
2863 case 'E':
2864 allow_nonempty = 1;
2865 break;
2866 case 'p':
2867 path_prefix = optarg;
2868 break;
2869 case 'q':
2870 verbosity = -1;
2871 break;
2872 default:
2873 usage_checkout();
2874 /* NOTREACHED */
2878 argc -= optind;
2879 argv += optind;
2881 #ifndef PROFILE
2882 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2883 "unveil", NULL) == -1)
2884 err(1, "pledge");
2885 #endif
2886 if (argc == 1) {
2887 char *base, *dotgit;
2888 const char *path;
2889 repo_path = realpath(argv[0], NULL);
2890 if (repo_path == NULL)
2891 return got_error_from_errno2("realpath", argv[0]);
2892 cwd = getcwd(NULL, 0);
2893 if (cwd == NULL) {
2894 error = got_error_from_errno("getcwd");
2895 goto done;
2897 if (path_prefix[0])
2898 path = path_prefix;
2899 else
2900 path = repo_path;
2901 error = got_path_basename(&base, path);
2902 if (error)
2903 goto done;
2904 dotgit = strstr(base, ".git");
2905 if (dotgit)
2906 *dotgit = '\0';
2907 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2908 error = got_error_from_errno("asprintf");
2909 free(base);
2910 goto done;
2912 free(base);
2913 } else if (argc == 2) {
2914 repo_path = realpath(argv[0], NULL);
2915 if (repo_path == NULL) {
2916 error = got_error_from_errno2("realpath", argv[0]);
2917 goto done;
2919 worktree_path = realpath(argv[1], NULL);
2920 if (worktree_path == NULL) {
2921 if (errno != ENOENT) {
2922 error = got_error_from_errno2("realpath",
2923 argv[1]);
2924 goto done;
2926 worktree_path = strdup(argv[1]);
2927 if (worktree_path == NULL) {
2928 error = got_error_from_errno("strdup");
2929 goto done;
2932 } else
2933 usage_checkout();
2935 got_path_strip_trailing_slashes(repo_path);
2936 got_path_strip_trailing_slashes(worktree_path);
2938 error = got_repo_open(&repo, repo_path, NULL);
2939 if (error != NULL)
2940 goto done;
2942 /* Pre-create work tree path for unveil(2) */
2943 error = got_path_mkdir(worktree_path);
2944 if (error) {
2945 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2946 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2947 goto done;
2948 if (!allow_nonempty &&
2949 !got_path_dir_is_empty(worktree_path)) {
2950 error = got_error_path(worktree_path,
2951 GOT_ERR_DIR_NOT_EMPTY);
2952 goto done;
2956 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2957 if (error)
2958 goto done;
2960 error = got_ref_open(&head_ref, repo, branch_name, 0);
2961 if (error != NULL)
2962 goto done;
2964 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2965 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2966 goto done;
2968 error = got_worktree_open(&worktree, worktree_path);
2969 if (error != NULL)
2970 goto done;
2972 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2973 path_prefix);
2974 if (error != NULL)
2975 goto done;
2976 if (!same_path_prefix) {
2977 error = got_error(GOT_ERR_PATH_PREFIX);
2978 goto done;
2981 if (commit_id_str) {
2982 struct got_reflist_head refs;
2983 TAILQ_INIT(&refs);
2984 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2985 NULL);
2986 if (error)
2987 goto done;
2988 error = got_repo_match_object_id(&commit_id, NULL,
2989 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2990 got_ref_list_free(&refs);
2991 if (error)
2992 goto done;
2993 error = check_linear_ancestry(commit_id,
2994 got_worktree_get_base_commit_id(worktree), 0, repo);
2995 if (error != NULL) {
2996 if (error->code == GOT_ERR_ANCESTRY) {
2997 error = checkout_ancestry_error(
2998 head_ref, commit_id_str);
3000 goto done;
3002 error = check_same_branch(commit_id, head_ref, NULL, repo);
3003 if (error) {
3004 if (error->code == GOT_ERR_ANCESTRY) {
3005 error = checkout_ancestry_error(
3006 head_ref, commit_id_str);
3008 goto done;
3010 error = got_worktree_set_base_commit_id(worktree, repo,
3011 commit_id);
3012 if (error)
3013 goto done;
3014 /* Expand potentially abbreviated commit ID string. */
3015 free(commit_id_str);
3016 error = got_object_id_str(&commit_id_str, commit_id);
3017 if (error)
3018 goto done;
3019 } else {
3020 commit_id = got_object_id_dup(
3021 got_worktree_get_base_commit_id(worktree));
3022 if (commit_id == NULL) {
3023 error = got_error_from_errno("got_object_id_dup");
3024 goto done;
3026 error = got_object_id_str(&commit_id_str, commit_id);
3027 if (error)
3028 goto done;
3031 error = got_pathlist_append(&paths, "", NULL);
3032 if (error)
3033 goto done;
3034 cpa.worktree_path = worktree_path;
3035 cpa.had_base_commit_ref_error = 0;
3036 cpa.verbosity = verbosity;
3037 error = got_worktree_checkout_files(worktree, &paths, repo,
3038 checkout_progress, &cpa, check_cancelled, NULL);
3039 if (error != NULL)
3040 goto done;
3042 if (got_ref_is_symbolic(head_ref)) {
3043 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3044 if (error)
3045 goto done;
3046 refname = got_ref_get_name(ref);
3047 } else
3048 refname = got_ref_get_name(head_ref);
3049 printf("Checked out %s: %s\n", refname, commit_id_str);
3050 printf("Now shut up and hack\n");
3051 if (cpa.had_base_commit_ref_error)
3052 show_worktree_base_ref_warning();
3053 done:
3054 if (head_ref)
3055 got_ref_close(head_ref);
3056 if (ref)
3057 got_ref_close(ref);
3058 got_pathlist_free(&paths);
3059 free(commit_id_str);
3060 free(commit_id);
3061 free(repo_path);
3062 free(worktree_path);
3063 free(cwd);
3064 return error;
3067 struct got_update_progress_arg {
3068 int did_something;
3069 int conflicts;
3070 int obstructed;
3071 int not_updated;
3072 int missing;
3073 int not_deleted;
3074 int unversioned;
3075 int verbosity;
3078 void
3079 print_update_progress_stats(struct got_update_progress_arg *upa)
3081 if (!upa->did_something)
3082 return;
3084 if (upa->conflicts > 0)
3085 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3086 if (upa->obstructed > 0)
3087 printf("File paths obstructed by a non-regular file: %d\n",
3088 upa->obstructed);
3089 if (upa->not_updated > 0)
3090 printf("Files not updated because of existing merge "
3091 "conflicts: %d\n", upa->not_updated);
3095 * The meaning of some status codes differs between merge-style operations and
3096 * update operations. For example, the ! status code means "file was missing"
3097 * if changes were merged into the work tree, and "missing file was restored"
3098 * if the work tree was updated. This function should be used by any operation
3099 * which merges changes into the work tree without updating the work tree.
3101 void
3102 print_merge_progress_stats(struct got_update_progress_arg *upa)
3104 if (!upa->did_something)
3105 return;
3107 if (upa->conflicts > 0)
3108 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3109 if (upa->obstructed > 0)
3110 printf("File paths obstructed by a non-regular file: %d\n",
3111 upa->obstructed);
3112 if (upa->missing > 0)
3113 printf("Files which had incoming changes but could not be "
3114 "found in the work tree: %d\n", upa->missing);
3115 if (upa->not_deleted > 0)
3116 printf("Files not deleted due to differences in deleted "
3117 "content: %d\n", upa->not_deleted);
3118 if (upa->unversioned > 0)
3119 printf("Files not merged because an unversioned file was "
3120 "found in the work tree: %d\n", upa->unversioned);
3123 __dead static void
3124 usage_update(void)
3126 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3127 "[path ...]\n",
3128 getprogname());
3129 exit(1);
3132 static const struct got_error *
3133 update_progress(void *arg, unsigned char status, const char *path)
3135 struct got_update_progress_arg *upa = arg;
3137 if (status == GOT_STATUS_EXISTS ||
3138 status == GOT_STATUS_BASE_REF_ERR)
3139 return NULL;
3141 upa->did_something = 1;
3143 /* Base commit bump happens silently. */
3144 if (status == GOT_STATUS_BUMP_BASE)
3145 return NULL;
3147 if (status == GOT_STATUS_CONFLICT)
3148 upa->conflicts++;
3149 if (status == GOT_STATUS_OBSTRUCTED)
3150 upa->obstructed++;
3151 if (status == GOT_STATUS_CANNOT_UPDATE)
3152 upa->not_updated++;
3153 if (status == GOT_STATUS_MISSING)
3154 upa->missing++;
3155 if (status == GOT_STATUS_CANNOT_DELETE)
3156 upa->not_deleted++;
3157 if (status == GOT_STATUS_UNVERSIONED)
3158 upa->unversioned++;
3160 while (path[0] == '/')
3161 path++;
3162 if (upa->verbosity >= 0)
3163 printf("%c %s\n", status, path);
3165 return NULL;
3168 static const struct got_error *
3169 switch_head_ref(struct got_reference *head_ref,
3170 struct got_object_id *commit_id, struct got_worktree *worktree,
3171 struct got_repository *repo)
3173 const struct got_error *err = NULL;
3174 char *base_id_str;
3175 int ref_has_moved = 0;
3177 /* Trivial case: switching between two different references. */
3178 if (strcmp(got_ref_get_name(head_ref),
3179 got_worktree_get_head_ref_name(worktree)) != 0) {
3180 printf("Switching work tree from %s to %s\n",
3181 got_worktree_get_head_ref_name(worktree),
3182 got_ref_get_name(head_ref));
3183 return got_worktree_set_head_ref(worktree, head_ref);
3186 err = check_linear_ancestry(commit_id,
3187 got_worktree_get_base_commit_id(worktree), 0, repo);
3188 if (err) {
3189 if (err->code != GOT_ERR_ANCESTRY)
3190 return err;
3191 ref_has_moved = 1;
3193 if (!ref_has_moved)
3194 return NULL;
3196 /* Switching to a rebased branch with the same reference name. */
3197 err = got_object_id_str(&base_id_str,
3198 got_worktree_get_base_commit_id(worktree));
3199 if (err)
3200 return err;
3201 printf("Reference %s now points at a different branch\n",
3202 got_worktree_get_head_ref_name(worktree));
3203 printf("Switching work tree from %s to %s\n", base_id_str,
3204 got_worktree_get_head_ref_name(worktree));
3205 return NULL;
3208 static const struct got_error *
3209 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3211 const struct got_error *err;
3212 int in_progress;
3214 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3215 if (err)
3216 return err;
3217 if (in_progress)
3218 return got_error(GOT_ERR_REBASING);
3220 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3221 if (err)
3222 return err;
3223 if (in_progress)
3224 return got_error(GOT_ERR_HISTEDIT_BUSY);
3226 return NULL;
3229 static const struct got_error *
3230 check_merge_in_progress(struct got_worktree *worktree,
3231 struct got_repository *repo)
3233 const struct got_error *err;
3234 int in_progress;
3236 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3237 if (err)
3238 return err;
3239 if (in_progress)
3240 return got_error(GOT_ERR_MERGE_BUSY);
3242 return NULL;
3245 static const struct got_error *
3246 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3247 char *argv[], struct got_worktree *worktree)
3249 const struct got_error *err = NULL;
3250 char *path;
3251 struct got_pathlist_entry *new;
3252 int i;
3254 if (argc == 0) {
3255 path = strdup("");
3256 if (path == NULL)
3257 return got_error_from_errno("strdup");
3258 return got_pathlist_append(paths, path, NULL);
3261 for (i = 0; i < argc; i++) {
3262 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3263 if (err)
3264 break;
3265 err = got_pathlist_insert(&new, paths, path, NULL);
3266 if (err || new == NULL /* duplicate */) {
3267 free(path);
3268 if (err)
3269 break;
3273 return err;
3276 static const struct got_error *
3277 wrap_not_worktree_error(const struct got_error *orig_err,
3278 const char *cmdname, const char *path)
3280 const struct got_error *err;
3281 struct got_repository *repo;
3282 static char msg[512];
3284 err = got_repo_open(&repo, path, NULL);
3285 if (err)
3286 return orig_err;
3288 snprintf(msg, sizeof(msg),
3289 "'got %s' needs a work tree in addition to a git repository\n"
3290 "Work trees can be checked out from this Git repository with "
3291 "'got checkout'.\n"
3292 "The got(1) manual page contains more information.", cmdname);
3293 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3294 got_repo_close(repo);
3295 return err;
3298 static const struct got_error *
3299 cmd_update(int argc, char *argv[])
3301 const struct got_error *error = NULL;
3302 struct got_repository *repo = NULL;
3303 struct got_worktree *worktree = NULL;
3304 char *worktree_path = NULL;
3305 struct got_object_id *commit_id = NULL;
3306 char *commit_id_str = NULL;
3307 const char *branch_name = NULL;
3308 struct got_reference *head_ref = NULL;
3309 struct got_pathlist_head paths;
3310 struct got_pathlist_entry *pe;
3311 int ch, verbosity = 0;
3312 struct got_update_progress_arg upa;
3314 TAILQ_INIT(&paths);
3316 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3317 switch (ch) {
3318 case 'b':
3319 branch_name = optarg;
3320 break;
3321 case 'c':
3322 commit_id_str = strdup(optarg);
3323 if (commit_id_str == NULL)
3324 return got_error_from_errno("strdup");
3325 break;
3326 case 'q':
3327 verbosity = -1;
3328 break;
3329 default:
3330 usage_update();
3331 /* NOTREACHED */
3335 argc -= optind;
3336 argv += optind;
3338 #ifndef PROFILE
3339 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3340 "unveil", NULL) == -1)
3341 err(1, "pledge");
3342 #endif
3343 worktree_path = getcwd(NULL, 0);
3344 if (worktree_path == NULL) {
3345 error = got_error_from_errno("getcwd");
3346 goto done;
3348 error = got_worktree_open(&worktree, worktree_path);
3349 if (error) {
3350 if (error->code == GOT_ERR_NOT_WORKTREE)
3351 error = wrap_not_worktree_error(error, "update",
3352 worktree_path);
3353 goto done;
3356 error = check_rebase_or_histedit_in_progress(worktree);
3357 if (error)
3358 goto done;
3360 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3361 NULL);
3362 if (error != NULL)
3363 goto done;
3365 error = apply_unveil(got_repo_get_path(repo), 0,
3366 got_worktree_get_root_path(worktree));
3367 if (error)
3368 goto done;
3370 error = check_merge_in_progress(worktree, repo);
3371 if (error)
3372 goto done;
3374 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3375 if (error)
3376 goto done;
3378 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3379 got_worktree_get_head_ref_name(worktree), 0);
3380 if (error != NULL)
3381 goto done;
3382 if (commit_id_str == NULL) {
3383 error = got_ref_resolve(&commit_id, repo, head_ref);
3384 if (error != NULL)
3385 goto done;
3386 error = got_object_id_str(&commit_id_str, commit_id);
3387 if (error != NULL)
3388 goto done;
3389 } else {
3390 struct got_reflist_head refs;
3391 TAILQ_INIT(&refs);
3392 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3393 NULL);
3394 if (error)
3395 goto done;
3396 error = got_repo_match_object_id(&commit_id, NULL,
3397 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3398 got_ref_list_free(&refs);
3399 free(commit_id_str);
3400 commit_id_str = NULL;
3401 if (error)
3402 goto done;
3403 error = got_object_id_str(&commit_id_str, commit_id);
3404 if (error)
3405 goto done;
3408 if (branch_name) {
3409 struct got_object_id *head_commit_id;
3410 TAILQ_FOREACH(pe, &paths, entry) {
3411 if (pe->path_len == 0)
3412 continue;
3413 error = got_error_msg(GOT_ERR_BAD_PATH,
3414 "switching between branches requires that "
3415 "the entire work tree gets updated");
3416 goto done;
3418 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3419 if (error)
3420 goto done;
3421 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3422 repo);
3423 free(head_commit_id);
3424 if (error != NULL)
3425 goto done;
3426 error = check_same_branch(commit_id, head_ref, NULL, repo);
3427 if (error)
3428 goto done;
3429 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3430 if (error)
3431 goto done;
3432 } else {
3433 error = check_linear_ancestry(commit_id,
3434 got_worktree_get_base_commit_id(worktree), 0, repo);
3435 if (error != NULL) {
3436 if (error->code == GOT_ERR_ANCESTRY)
3437 error = got_error(GOT_ERR_BRANCH_MOVED);
3438 goto done;
3440 error = check_same_branch(commit_id, head_ref, NULL, repo);
3441 if (error)
3442 goto done;
3445 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3446 commit_id) != 0) {
3447 error = got_worktree_set_base_commit_id(worktree, repo,
3448 commit_id);
3449 if (error)
3450 goto done;
3453 memset(&upa, 0, sizeof(upa));
3454 upa.verbosity = verbosity;
3455 error = got_worktree_checkout_files(worktree, &paths, repo,
3456 update_progress, &upa, check_cancelled, NULL);
3457 if (error != NULL)
3458 goto done;
3460 if (upa.did_something) {
3461 printf("Updated to %s: %s\n",
3462 got_worktree_get_head_ref_name(worktree), commit_id_str);
3463 } else
3464 printf("Already up-to-date\n");
3465 print_update_progress_stats(&upa);
3466 done:
3467 free(worktree_path);
3468 TAILQ_FOREACH(pe, &paths, entry)
3469 free((char *)pe->path);
3470 got_pathlist_free(&paths);
3471 free(commit_id);
3472 free(commit_id_str);
3473 return error;
3476 static const struct got_error *
3477 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3478 const char *path, int diff_context, int ignore_whitespace,
3479 int force_text_diff, struct got_repository *repo, FILE *outfile)
3481 const struct got_error *err = NULL;
3482 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3483 FILE *f1 = NULL, *f2 = NULL;
3485 if (blob_id1) {
3486 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3487 if (err)
3488 goto done;
3489 f1 = got_opentemp();
3490 if (f1 == NULL) {
3491 err = got_error_from_errno("got_opentemp");
3492 goto done;
3496 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3497 if (err)
3498 goto done;
3500 f2 = got_opentemp();
3501 if (f2 == NULL) {
3502 err = got_error_from_errno("got_opentemp");
3503 goto done;
3506 while (path[0] == '/')
3507 path++;
3508 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3509 diff_context, ignore_whitespace, force_text_diff, outfile);
3510 done:
3511 if (blob1)
3512 got_object_blob_close(blob1);
3513 got_object_blob_close(blob2);
3514 if (f1 && fclose(f1) == EOF && err == NULL)
3515 err = got_error_from_errno("fclose");
3516 if (f2 && fclose(f2) == EOF && err == NULL)
3517 err = got_error_from_errno("fclose");
3518 return err;
3521 static const struct got_error *
3522 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3523 const char *path, int diff_context, int ignore_whitespace,
3524 int force_text_diff, struct got_repository *repo, FILE *outfile)
3526 const struct got_error *err = NULL;
3527 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3528 struct got_diff_blob_output_unidiff_arg arg;
3529 FILE *f1 = NULL, *f2 = NULL;
3531 if (tree_id1) {
3532 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3533 if (err)
3534 goto done;
3535 f1 = got_opentemp();
3536 if (f1 == NULL) {
3537 err = got_error_from_errno("got_opentemp");
3538 goto done;
3542 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3543 if (err)
3544 goto done;
3546 f2 = got_opentemp();
3547 if (f2 == NULL) {
3548 err = got_error_from_errno("got_opentemp");
3549 goto done;
3552 arg.diff_context = diff_context;
3553 arg.ignore_whitespace = ignore_whitespace;
3554 arg.force_text_diff = force_text_diff;
3555 arg.outfile = outfile;
3556 arg.line_offsets = NULL;
3557 arg.nlines = 0;
3558 while (path[0] == '/')
3559 path++;
3560 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3561 got_diff_blob_output_unidiff, &arg, 1);
3562 done:
3563 if (tree1)
3564 got_object_tree_close(tree1);
3565 if (tree2)
3566 got_object_tree_close(tree2);
3567 if (f1 && fclose(f1) == EOF && err == NULL)
3568 err = got_error_from_errno("fclose");
3569 if (f2 && fclose(f2) == EOF && err == NULL)
3570 err = got_error_from_errno("fclose");
3571 return err;
3574 static const struct got_error *
3575 get_changed_paths(struct got_pathlist_head *paths,
3576 struct got_commit_object *commit, struct got_repository *repo)
3578 const struct got_error *err = NULL;
3579 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3580 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3581 struct got_object_qid *qid;
3583 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3584 if (qid != NULL) {
3585 struct got_commit_object *pcommit;
3586 err = got_object_open_as_commit(&pcommit, repo,
3587 &qid->id);
3588 if (err)
3589 return err;
3591 tree_id1 = got_object_id_dup(
3592 got_object_commit_get_tree_id(pcommit));
3593 if (tree_id1 == NULL) {
3594 got_object_commit_close(pcommit);
3595 return got_error_from_errno("got_object_id_dup");
3597 got_object_commit_close(pcommit);
3601 if (tree_id1) {
3602 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3603 if (err)
3604 goto done;
3607 tree_id2 = got_object_commit_get_tree_id(commit);
3608 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3609 if (err)
3610 goto done;
3612 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3613 got_diff_tree_collect_changed_paths, paths, 0);
3614 done:
3615 if (tree1)
3616 got_object_tree_close(tree1);
3617 if (tree2)
3618 got_object_tree_close(tree2);
3619 free(tree_id1);
3620 return err;
3623 static const struct got_error *
3624 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3625 const char *path, int diff_context, struct got_repository *repo,
3626 FILE *outfile)
3628 const struct got_error *err = NULL;
3629 struct got_commit_object *pcommit = NULL;
3630 char *id_str1 = NULL, *id_str2 = NULL;
3631 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3632 struct got_object_qid *qid;
3634 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3635 if (qid != NULL) {
3636 err = got_object_open_as_commit(&pcommit, repo,
3637 &qid->id);
3638 if (err)
3639 return err;
3642 if (path && path[0] != '\0') {
3643 int obj_type;
3644 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3645 if (err)
3646 goto done;
3647 err = got_object_id_str(&id_str2, obj_id2);
3648 if (err) {
3649 free(obj_id2);
3650 goto done;
3652 if (pcommit) {
3653 err = got_object_id_by_path(&obj_id1, repo,
3654 pcommit, path);
3655 if (err) {
3656 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3657 free(obj_id2);
3658 goto done;
3660 } else {
3661 err = got_object_id_str(&id_str1, obj_id1);
3662 if (err) {
3663 free(obj_id2);
3664 goto done;
3668 err = got_object_get_type(&obj_type, repo, obj_id2);
3669 if (err) {
3670 free(obj_id2);
3671 goto done;
3673 fprintf(outfile,
3674 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3675 switch (obj_type) {
3676 case GOT_OBJ_TYPE_BLOB:
3677 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3678 0, 0, repo, outfile);
3679 break;
3680 case GOT_OBJ_TYPE_TREE:
3681 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3682 0, 0, repo, outfile);
3683 break;
3684 default:
3685 err = got_error(GOT_ERR_OBJ_TYPE);
3686 break;
3688 free(obj_id1);
3689 free(obj_id2);
3690 } else {
3691 obj_id2 = got_object_commit_get_tree_id(commit);
3692 err = got_object_id_str(&id_str2, obj_id2);
3693 if (err)
3694 goto done;
3695 if (pcommit) {
3696 obj_id1 = got_object_commit_get_tree_id(pcommit);
3697 err = got_object_id_str(&id_str1, obj_id1);
3698 if (err)
3699 goto done;
3701 fprintf(outfile,
3702 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3703 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3704 repo, outfile);
3706 done:
3707 free(id_str1);
3708 free(id_str2);
3709 if (pcommit)
3710 got_object_commit_close(pcommit);
3711 return err;
3714 static char *
3715 get_datestr(time_t *time, char *datebuf)
3717 struct tm mytm, *tm;
3718 char *p, *s;
3720 tm = gmtime_r(time, &mytm);
3721 if (tm == NULL)
3722 return NULL;
3723 s = asctime_r(tm, datebuf);
3724 if (s == NULL)
3725 return NULL;
3726 p = strchr(s, '\n');
3727 if (p)
3728 *p = '\0';
3729 return s;
3732 static const struct got_error *
3733 match_commit(int *have_match, struct got_object_id *id,
3734 struct got_commit_object *commit, regex_t *regex)
3736 const struct got_error *err = NULL;
3737 regmatch_t regmatch;
3738 char *id_str = NULL, *logmsg = NULL;
3740 *have_match = 0;
3742 err = got_object_id_str(&id_str, id);
3743 if (err)
3744 return err;
3746 err = got_object_commit_get_logmsg(&logmsg, commit);
3747 if (err)
3748 goto done;
3750 if (regexec(regex, got_object_commit_get_author(commit), 1,
3751 &regmatch, 0) == 0 ||
3752 regexec(regex, got_object_commit_get_committer(commit), 1,
3753 &regmatch, 0) == 0 ||
3754 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3755 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3756 *have_match = 1;
3757 done:
3758 free(id_str);
3759 free(logmsg);
3760 return err;
3763 static void
3764 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3765 regex_t *regex)
3767 regmatch_t regmatch;
3768 struct got_pathlist_entry *pe;
3770 *have_match = 0;
3772 TAILQ_FOREACH(pe, changed_paths, entry) {
3773 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3774 *have_match = 1;
3775 break;
3780 static const struct got_error *
3781 match_patch(int *have_match, struct got_commit_object *commit,
3782 struct got_object_id *id, const char *path, int diff_context,
3783 struct got_repository *repo, regex_t *regex, FILE *f)
3785 const struct got_error *err = NULL;
3786 char *line = NULL;
3787 size_t linesize = 0;
3788 ssize_t linelen;
3789 regmatch_t regmatch;
3791 *have_match = 0;
3793 err = got_opentemp_truncate(f);
3794 if (err)
3795 return err;
3797 err = print_patch(commit, id, path, diff_context, repo, f);
3798 if (err)
3799 goto done;
3801 if (fseeko(f, 0L, SEEK_SET) == -1) {
3802 err = got_error_from_errno("fseeko");
3803 goto done;
3806 while ((linelen = getline(&line, &linesize, f)) != -1) {
3807 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3808 *have_match = 1;
3809 break;
3812 done:
3813 free(line);
3814 return err;
3817 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3819 static const struct got_error*
3820 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3821 struct got_object_id *id, struct got_repository *repo,
3822 int local_only)
3824 static const struct got_error *err = NULL;
3825 struct got_reflist_entry *re;
3826 char *s;
3827 const char *name;
3829 *refs_str = NULL;
3831 TAILQ_FOREACH(re, refs, entry) {
3832 struct got_tag_object *tag = NULL;
3833 struct got_object_id *ref_id;
3834 int cmp;
3836 name = got_ref_get_name(re->ref);
3837 if (strcmp(name, GOT_REF_HEAD) == 0)
3838 continue;
3839 if (strncmp(name, "refs/", 5) == 0)
3840 name += 5;
3841 if (strncmp(name, "got/", 4) == 0)
3842 continue;
3843 if (strncmp(name, "heads/", 6) == 0)
3844 name += 6;
3845 if (strncmp(name, "remotes/", 8) == 0) {
3846 if (local_only)
3847 continue;
3848 name += 8;
3849 s = strstr(name, "/" GOT_REF_HEAD);
3850 if (s != NULL && s[strlen(s)] == '\0')
3851 continue;
3853 err = got_ref_resolve(&ref_id, repo, re->ref);
3854 if (err)
3855 break;
3856 if (strncmp(name, "tags/", 5) == 0) {
3857 err = got_object_open_as_tag(&tag, repo, ref_id);
3858 if (err) {
3859 if (err->code != GOT_ERR_OBJ_TYPE) {
3860 free(ref_id);
3861 break;
3863 /* Ref points at something other than a tag. */
3864 err = NULL;
3865 tag = NULL;
3868 cmp = got_object_id_cmp(tag ?
3869 got_object_tag_get_object_id(tag) : ref_id, id);
3870 free(ref_id);
3871 if (tag)
3872 got_object_tag_close(tag);
3873 if (cmp != 0)
3874 continue;
3875 s = *refs_str;
3876 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3877 s ? ", " : "", name) == -1) {
3878 err = got_error_from_errno("asprintf");
3879 free(s);
3880 *refs_str = NULL;
3881 break;
3883 free(s);
3886 return err;
3889 static const struct got_error *
3890 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3891 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3893 const struct got_error *err = NULL;
3894 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3895 char *comma, *s, *nl;
3896 struct got_reflist_head *refs;
3897 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3898 struct tm tm;
3899 time_t committer_time;
3901 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3902 if (refs) {
3903 err = build_refs_str(&ref_str, refs, id, repo, 1);
3904 if (err)
3905 goto done;
3907 /* Display the first matching ref only. */
3908 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3909 *comma = '\0';
3912 if (ref_str == NULL) {
3913 err = got_object_id_str(&id_str, id);
3914 if (err)
3915 return err;
3918 committer_time = got_object_commit_get_committer_time(commit);
3919 if (gmtime_r(&committer_time, &tm) == NULL)
3920 return got_error_from_errno("gmtime_r");
3921 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
3922 return got_error(GOT_ERR_NO_SPACE);
3924 err = got_object_commit_get_logmsg(&logmsg0, commit);
3925 if (err)
3926 goto done;
3928 s = logmsg0;
3929 while (isspace((unsigned char)s[0]))
3930 s++;
3932 nl = strchr(s, '\n');
3933 if (nl) {
3934 *nl = '\0';
3937 if (ref_str)
3938 printf("%s%-7s %s\n", datebuf, ref_str, s);
3939 else
3940 printf("%s%.7s %s\n", datebuf, id_str, s);
3942 if (fflush(stdout) != 0 && err == NULL)
3943 err = got_error_from_errno("fflush");
3944 done:
3945 free(id_str);
3946 free(ref_str);
3947 free(logmsg0);
3948 return err;
3951 static const struct got_error *
3952 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3953 struct got_repository *repo, const char *path,
3954 struct got_pathlist_head *changed_paths, int show_patch,
3955 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3956 const char *custom_refs_str)
3958 const struct got_error *err = NULL;
3959 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3960 char datebuf[26];
3961 time_t committer_time;
3962 const char *author, *committer;
3963 char *refs_str = NULL;
3965 err = got_object_id_str(&id_str, id);
3966 if (err)
3967 return err;
3969 if (custom_refs_str == NULL) {
3970 struct got_reflist_head *refs;
3971 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3972 if (refs) {
3973 err = build_refs_str(&refs_str, refs, id, repo, 0);
3974 if (err)
3975 goto done;
3979 printf(GOT_COMMIT_SEP_STR);
3980 if (custom_refs_str)
3981 printf("commit %s (%s)\n", id_str, custom_refs_str);
3982 else
3983 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3984 refs_str ? refs_str : "", refs_str ? ")" : "");
3985 free(id_str);
3986 id_str = NULL;
3987 free(refs_str);
3988 refs_str = NULL;
3989 printf("from: %s\n", got_object_commit_get_author(commit));
3990 committer_time = got_object_commit_get_committer_time(commit);
3991 datestr = get_datestr(&committer_time, datebuf);
3992 if (datestr)
3993 printf("date: %s UTC\n", datestr);
3994 author = got_object_commit_get_author(commit);
3995 committer = got_object_commit_get_committer(commit);
3996 if (strcmp(author, committer) != 0)
3997 printf("via: %s\n", committer);
3998 if (got_object_commit_get_nparents(commit) > 1) {
3999 const struct got_object_id_queue *parent_ids;
4000 struct got_object_qid *qid;
4001 int n = 1;
4002 parent_ids = got_object_commit_get_parent_ids(commit);
4003 STAILQ_FOREACH(qid, parent_ids, entry) {
4004 err = got_object_id_str(&id_str, &qid->id);
4005 if (err)
4006 goto done;
4007 printf("parent %d: %s\n", n++, id_str);
4008 free(id_str);
4009 id_str = NULL;
4013 err = got_object_commit_get_logmsg(&logmsg0, commit);
4014 if (err)
4015 goto done;
4017 logmsg = logmsg0;
4018 do {
4019 line = strsep(&logmsg, "\n");
4020 if (line)
4021 printf(" %s\n", line);
4022 } while (line);
4023 free(logmsg0);
4025 if (changed_paths) {
4026 struct got_pathlist_entry *pe;
4027 TAILQ_FOREACH(pe, changed_paths, entry) {
4028 struct got_diff_changed_path *cp = pe->data;
4029 printf(" %c %s\n", cp->status, pe->path);
4031 printf("\n");
4033 if (show_patch) {
4034 err = print_patch(commit, id, path, diff_context, repo, stdout);
4035 if (err == 0)
4036 printf("\n");
4039 if (fflush(stdout) != 0 && err == NULL)
4040 err = got_error_from_errno("fflush");
4041 done:
4042 free(id_str);
4043 free(refs_str);
4044 return err;
4047 static const struct got_error *
4048 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4049 struct got_repository *repo, const char *path, int show_changed_paths,
4050 int show_patch, const char *search_pattern, int diff_context, int limit,
4051 int log_branches, int reverse_display_order,
4052 struct got_reflist_object_id_map *refs_idmap, int one_line,
4053 FILE *tmpfile)
4055 const struct got_error *err;
4056 struct got_commit_graph *graph;
4057 regex_t regex;
4058 int have_match;
4059 struct got_object_id_queue reversed_commits;
4060 struct got_object_qid *qid;
4061 struct got_commit_object *commit;
4062 struct got_pathlist_head changed_paths;
4063 struct got_pathlist_entry *pe;
4065 STAILQ_INIT(&reversed_commits);
4066 TAILQ_INIT(&changed_paths);
4068 if (search_pattern && regcomp(&regex, search_pattern,
4069 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4070 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4072 err = got_commit_graph_open(&graph, path, !log_branches);
4073 if (err)
4074 return err;
4075 err = got_commit_graph_iter_start(graph, root_id, repo,
4076 check_cancelled, NULL);
4077 if (err)
4078 goto done;
4079 for (;;) {
4080 struct got_object_id *id;
4082 if (sigint_received || sigpipe_received)
4083 break;
4085 err = got_commit_graph_iter_next(&id, graph, repo,
4086 check_cancelled, NULL);
4087 if (err) {
4088 if (err->code == GOT_ERR_ITER_COMPLETED)
4089 err = NULL;
4090 break;
4092 if (id == NULL)
4093 break;
4095 err = got_object_open_as_commit(&commit, repo, id);
4096 if (err)
4097 break;
4099 if (show_changed_paths && !reverse_display_order) {
4100 err = get_changed_paths(&changed_paths, commit, repo);
4101 if (err)
4102 break;
4105 if (search_pattern) {
4106 err = match_commit(&have_match, id, commit, &regex);
4107 if (err) {
4108 got_object_commit_close(commit);
4109 break;
4111 if (have_match == 0 && show_changed_paths)
4112 match_changed_paths(&have_match,
4113 &changed_paths, &regex);
4114 if (have_match == 0 && show_patch) {
4115 err = match_patch(&have_match, commit, id,
4116 path, diff_context, repo, &regex,
4117 tmpfile);
4118 if (err)
4119 break;
4121 if (have_match == 0) {
4122 got_object_commit_close(commit);
4123 TAILQ_FOREACH(pe, &changed_paths, entry) {
4124 free((char *)pe->path);
4125 free(pe->data);
4127 got_pathlist_free(&changed_paths);
4128 continue;
4132 if (reverse_display_order) {
4133 err = got_object_qid_alloc(&qid, id);
4134 if (err)
4135 break;
4136 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4137 got_object_commit_close(commit);
4138 } else {
4139 if (one_line)
4140 err = print_commit_oneline(commit, id,
4141 repo, refs_idmap);
4142 else
4143 err = print_commit(commit, id, repo, path,
4144 show_changed_paths ? &changed_paths : NULL,
4145 show_patch, diff_context, refs_idmap, NULL);
4146 got_object_commit_close(commit);
4147 if (err)
4148 break;
4150 if ((limit && --limit == 0) ||
4151 (end_id && got_object_id_cmp(id, end_id) == 0))
4152 break;
4154 TAILQ_FOREACH(pe, &changed_paths, entry) {
4155 free((char *)pe->path);
4156 free(pe->data);
4158 got_pathlist_free(&changed_paths);
4160 if (reverse_display_order) {
4161 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4162 err = got_object_open_as_commit(&commit, repo,
4163 &qid->id);
4164 if (err)
4165 break;
4166 if (show_changed_paths) {
4167 err = get_changed_paths(&changed_paths,
4168 commit, repo);
4169 if (err)
4170 break;
4172 if (one_line)
4173 err = print_commit_oneline(commit, &qid->id,
4174 repo, refs_idmap);
4175 else
4176 err = print_commit(commit, &qid->id, repo, path,
4177 show_changed_paths ? &changed_paths : NULL,
4178 show_patch, diff_context, refs_idmap, NULL);
4179 got_object_commit_close(commit);
4180 if (err)
4181 break;
4182 TAILQ_FOREACH(pe, &changed_paths, entry) {
4183 free((char *)pe->path);
4184 free(pe->data);
4186 got_pathlist_free(&changed_paths);
4189 done:
4190 while (!STAILQ_EMPTY(&reversed_commits)) {
4191 qid = STAILQ_FIRST(&reversed_commits);
4192 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4193 got_object_qid_free(qid);
4195 TAILQ_FOREACH(pe, &changed_paths, entry) {
4196 free((char *)pe->path);
4197 free(pe->data);
4199 got_pathlist_free(&changed_paths);
4200 if (search_pattern)
4201 regfree(&regex);
4202 got_commit_graph_close(graph);
4203 return err;
4206 __dead static void
4207 usage_log(void)
4209 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4210 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4211 "[-r repository-path] [-R] [path]\n", getprogname());
4212 exit(1);
4215 static int
4216 get_default_log_limit(void)
4218 const char *got_default_log_limit;
4219 long long n;
4220 const char *errstr;
4222 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4223 if (got_default_log_limit == NULL)
4224 return 0;
4225 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4226 if (errstr != NULL)
4227 return 0;
4228 return n;
4231 static const struct got_error *
4232 cmd_log(int argc, char *argv[])
4234 const struct got_error *error;
4235 struct got_repository *repo = NULL;
4236 struct got_worktree *worktree = NULL;
4237 struct got_object_id *start_id = NULL, *end_id = NULL;
4238 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4239 const char *start_commit = NULL, *end_commit = NULL;
4240 const char *search_pattern = NULL;
4241 int diff_context = -1, ch;
4242 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4243 int reverse_display_order = 0, one_line = 0;
4244 const char *errstr;
4245 struct got_reflist_head refs;
4246 struct got_reflist_object_id_map *refs_idmap = NULL;
4247 FILE *tmpfile = NULL;
4249 TAILQ_INIT(&refs);
4251 #ifndef PROFILE
4252 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4253 NULL)
4254 == -1)
4255 err(1, "pledge");
4256 #endif
4258 limit = get_default_log_limit();
4260 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4261 switch (ch) {
4262 case 'p':
4263 show_patch = 1;
4264 break;
4265 case 'P':
4266 show_changed_paths = 1;
4267 break;
4268 case 'c':
4269 start_commit = optarg;
4270 break;
4271 case 'C':
4272 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4273 &errstr);
4274 if (errstr != NULL)
4275 errx(1, "number of context lines is %s: %s",
4276 errstr, optarg);
4277 break;
4278 case 'l':
4279 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4280 if (errstr != NULL)
4281 errx(1, "number of commits is %s: %s",
4282 errstr, optarg);
4283 break;
4284 case 'b':
4285 log_branches = 1;
4286 break;
4287 case 'r':
4288 repo_path = realpath(optarg, NULL);
4289 if (repo_path == NULL)
4290 return got_error_from_errno2("realpath",
4291 optarg);
4292 got_path_strip_trailing_slashes(repo_path);
4293 break;
4294 case 'R':
4295 reverse_display_order = 1;
4296 break;
4297 case 's':
4298 one_line = 1;
4299 break;
4300 case 'S':
4301 search_pattern = optarg;
4302 break;
4303 case 'x':
4304 end_commit = optarg;
4305 break;
4306 default:
4307 usage_log();
4308 /* NOTREACHED */
4312 argc -= optind;
4313 argv += optind;
4315 if (diff_context == -1)
4316 diff_context = 3;
4317 else if (!show_patch)
4318 errx(1, "-C requires -p");
4320 if (one_line && (show_patch || show_changed_paths))
4321 errx(1, "cannot use -s with -p or -P");
4323 cwd = getcwd(NULL, 0);
4324 if (cwd == NULL) {
4325 error = got_error_from_errno("getcwd");
4326 goto done;
4329 if (repo_path == NULL) {
4330 error = got_worktree_open(&worktree, cwd);
4331 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4332 goto done;
4333 error = NULL;
4336 if (argc == 1) {
4337 if (worktree) {
4338 error = got_worktree_resolve_path(&path, worktree,
4339 argv[0]);
4340 if (error)
4341 goto done;
4342 } else {
4343 path = strdup(argv[0]);
4344 if (path == NULL) {
4345 error = got_error_from_errno("strdup");
4346 goto done;
4349 } else if (argc != 0)
4350 usage_log();
4352 if (repo_path == NULL) {
4353 repo_path = worktree ?
4354 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4356 if (repo_path == NULL) {
4357 error = got_error_from_errno("strdup");
4358 goto done;
4361 error = got_repo_open(&repo, repo_path, NULL);
4362 if (error != NULL)
4363 goto done;
4365 error = apply_unveil(got_repo_get_path(repo), 1,
4366 worktree ? got_worktree_get_root_path(worktree) : NULL);
4367 if (error)
4368 goto done;
4370 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4371 if (error)
4372 goto done;
4374 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4375 if (error)
4376 goto done;
4378 if (start_commit == NULL) {
4379 struct got_reference *head_ref;
4380 struct got_commit_object *commit = NULL;
4381 error = got_ref_open(&head_ref, repo,
4382 worktree ? got_worktree_get_head_ref_name(worktree)
4383 : GOT_REF_HEAD, 0);
4384 if (error != NULL)
4385 goto done;
4386 error = got_ref_resolve(&start_id, repo, head_ref);
4387 got_ref_close(head_ref);
4388 if (error != NULL)
4389 goto done;
4390 error = got_object_open_as_commit(&commit, repo,
4391 start_id);
4392 if (error != NULL)
4393 goto done;
4394 got_object_commit_close(commit);
4395 } else {
4396 error = got_repo_match_object_id(&start_id, NULL,
4397 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4398 if (error != NULL)
4399 goto done;
4401 if (end_commit != NULL) {
4402 error = got_repo_match_object_id(&end_id, NULL,
4403 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4404 if (error != NULL)
4405 goto done;
4408 if (worktree) {
4410 * If a path was specified on the command line it was resolved
4411 * to a path in the work tree above. Prepend the work tree's
4412 * path prefix to obtain the corresponding in-repository path.
4414 if (path) {
4415 const char *prefix;
4416 prefix = got_worktree_get_path_prefix(worktree);
4417 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4418 (path[0] != '\0') ? "/" : "", path) == -1) {
4419 error = got_error_from_errno("asprintf");
4420 goto done;
4423 } else
4424 error = got_repo_map_path(&in_repo_path, repo,
4425 path ? path : "");
4426 if (error != NULL)
4427 goto done;
4428 if (in_repo_path) {
4429 free(path);
4430 path = in_repo_path;
4433 if (worktree) {
4434 /* Release work tree lock. */
4435 got_worktree_close(worktree);
4436 worktree = NULL;
4439 if (search_pattern && show_patch) {
4440 tmpfile = got_opentemp();
4441 if (tmpfile == NULL) {
4442 error = got_error_from_errno("got_opentemp");
4443 goto done;
4447 error = print_commits(start_id, end_id, repo, path ? path : "",
4448 show_changed_paths, show_patch, search_pattern, diff_context,
4449 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4450 tmpfile);
4451 done:
4452 free(path);
4453 free(repo_path);
4454 free(cwd);
4455 if (worktree)
4456 got_worktree_close(worktree);
4457 if (repo) {
4458 const struct got_error *close_err = got_repo_close(repo);
4459 if (error == NULL)
4460 error = close_err;
4462 if (refs_idmap)
4463 got_reflist_object_id_map_free(refs_idmap);
4464 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4465 error = got_error_from_errno("fclose");
4466 got_ref_list_free(&refs);
4467 return error;
4470 __dead static void
4471 usage_diff(void)
4473 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4474 "[-r repository-path] [-s] [-w] [-P] "
4475 "[object1 object2 | path ...]\n", getprogname());
4476 exit(1);
4479 struct print_diff_arg {
4480 struct got_repository *repo;
4481 struct got_worktree *worktree;
4482 int diff_context;
4483 const char *id_str;
4484 int header_shown;
4485 int diff_staged;
4486 int ignore_whitespace;
4487 int force_text_diff;
4491 * Create a file which contains the target path of a symlink so we can feed
4492 * it as content to the diff engine.
4494 static const struct got_error *
4495 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4496 const char *abspath)
4498 const struct got_error *err = NULL;
4499 char target_path[PATH_MAX];
4500 ssize_t target_len, outlen;
4502 *fd = -1;
4504 if (dirfd != -1) {
4505 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4506 if (target_len == -1)
4507 return got_error_from_errno2("readlinkat", abspath);
4508 } else {
4509 target_len = readlink(abspath, target_path, PATH_MAX);
4510 if (target_len == -1)
4511 return got_error_from_errno2("readlink", abspath);
4514 *fd = got_opentempfd();
4515 if (*fd == -1)
4516 return got_error_from_errno("got_opentempfd");
4518 outlen = write(*fd, target_path, target_len);
4519 if (outlen == -1) {
4520 err = got_error_from_errno("got_opentempfd");
4521 goto done;
4524 if (lseek(*fd, 0, SEEK_SET) == -1) {
4525 err = got_error_from_errno2("lseek", abspath);
4526 goto done;
4528 done:
4529 if (err) {
4530 close(*fd);
4531 *fd = -1;
4533 return err;
4536 static const struct got_error *
4537 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4538 const char *path, struct got_object_id *blob_id,
4539 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4540 int dirfd, const char *de_name)
4542 struct print_diff_arg *a = arg;
4543 const struct got_error *err = NULL;
4544 struct got_blob_object *blob1 = NULL;
4545 int fd = -1;
4546 FILE *f1 = NULL, *f2 = NULL;
4547 char *abspath = NULL, *label1 = NULL;
4548 struct stat sb;
4549 off_t size1 = 0;
4551 if (a->diff_staged) {
4552 if (staged_status != GOT_STATUS_MODIFY &&
4553 staged_status != GOT_STATUS_ADD &&
4554 staged_status != GOT_STATUS_DELETE)
4555 return NULL;
4556 } else {
4557 if (staged_status == GOT_STATUS_DELETE)
4558 return NULL;
4559 if (status == GOT_STATUS_NONEXISTENT)
4560 return got_error_set_errno(ENOENT, path);
4561 if (status != GOT_STATUS_MODIFY &&
4562 status != GOT_STATUS_ADD &&
4563 status != GOT_STATUS_DELETE &&
4564 status != GOT_STATUS_CONFLICT)
4565 return NULL;
4568 if (!a->header_shown) {
4569 printf("diff %s %s%s\n", a->id_str,
4570 got_worktree_get_root_path(a->worktree),
4571 a->diff_staged ? " (staged changes)" : "");
4572 a->header_shown = 1;
4575 if (a->diff_staged) {
4576 const char *label1 = NULL, *label2 = NULL;
4577 switch (staged_status) {
4578 case GOT_STATUS_MODIFY:
4579 label1 = path;
4580 label2 = path;
4581 break;
4582 case GOT_STATUS_ADD:
4583 label2 = path;
4584 break;
4585 case GOT_STATUS_DELETE:
4586 label1 = path;
4587 break;
4588 default:
4589 return got_error(GOT_ERR_FILE_STATUS);
4591 f1 = got_opentemp();
4592 if (f1 == NULL) {
4593 err = got_error_from_errno("got_opentemp");
4594 goto done;
4596 f2 = got_opentemp();
4597 if (f2 == NULL) {
4598 err = got_error_from_errno("got_opentemp");
4599 goto done;
4601 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4602 blob_id, staged_blob_id, label1, label2, a->diff_context,
4603 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4604 goto done;
4607 if (staged_status == GOT_STATUS_ADD ||
4608 staged_status == GOT_STATUS_MODIFY) {
4609 char *id_str;
4610 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4611 8192);
4612 if (err)
4613 goto done;
4614 err = got_object_id_str(&id_str, staged_blob_id);
4615 if (err)
4616 goto done;
4617 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4618 err = got_error_from_errno("asprintf");
4619 free(id_str);
4620 goto done;
4622 free(id_str);
4623 } else if (status != GOT_STATUS_ADD) {
4624 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4625 if (err)
4626 goto done;
4629 if (status != GOT_STATUS_DELETE) {
4630 if (asprintf(&abspath, "%s/%s",
4631 got_worktree_get_root_path(a->worktree), path) == -1) {
4632 err = got_error_from_errno("asprintf");
4633 goto done;
4636 if (dirfd != -1) {
4637 fd = openat(dirfd, de_name,
4638 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4639 if (fd == -1) {
4640 if (!got_err_open_nofollow_on_symlink()) {
4641 err = got_error_from_errno2("openat",
4642 abspath);
4643 goto done;
4645 err = get_symlink_target_file(&fd, dirfd,
4646 de_name, abspath);
4647 if (err)
4648 goto done;
4650 } else {
4651 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4652 if (fd == -1) {
4653 if (!got_err_open_nofollow_on_symlink()) {
4654 err = got_error_from_errno2("open",
4655 abspath);
4656 goto done;
4658 err = get_symlink_target_file(&fd, dirfd,
4659 de_name, abspath);
4660 if (err)
4661 goto done;
4664 if (fstat(fd, &sb) == -1) {
4665 err = got_error_from_errno2("fstat", abspath);
4666 goto done;
4668 f2 = fdopen(fd, "r");
4669 if (f2 == NULL) {
4670 err = got_error_from_errno2("fdopen", abspath);
4671 goto done;
4673 fd = -1;
4674 } else
4675 sb.st_size = 0;
4677 if (blob1) {
4678 f1 = got_opentemp();
4679 if (f1 == NULL) {
4680 err = got_error_from_errno("got_opentemp");
4681 goto done;
4683 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4684 blob1);
4685 if (err)
4686 goto done;
4689 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4690 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4691 stdout);
4692 done:
4693 if (blob1)
4694 got_object_blob_close(blob1);
4695 if (f1 && fclose(f1) == EOF && err == NULL)
4696 err = got_error_from_errno("fclose");
4697 if (f2 && fclose(f2) == EOF && err == NULL)
4698 err = got_error_from_errno("fclose");
4699 if (fd != -1 && close(fd) == -1 && err == NULL)
4700 err = got_error_from_errno("close");
4701 free(abspath);
4702 return err;
4705 static const struct got_error *
4706 cmd_diff(int argc, char *argv[])
4708 const struct got_error *error;
4709 struct got_repository *repo = NULL;
4710 struct got_worktree *worktree = NULL;
4711 char *cwd = NULL, *repo_path = NULL;
4712 const char *commit_args[2] = { NULL, NULL };
4713 int ncommit_args = 0;
4714 struct got_object_id *ids[2] = { NULL, NULL };
4715 char *labels[2] = { NULL, NULL };
4716 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4717 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4718 int force_text_diff = 0, force_path = 0, rflag = 0;
4719 const char *errstr;
4720 struct got_reflist_head refs;
4721 struct got_pathlist_head paths;
4722 struct got_pathlist_entry *pe;
4723 FILE *f1 = NULL, *f2 = NULL;
4725 TAILQ_INIT(&refs);
4726 TAILQ_INIT(&paths);
4728 #ifndef PROFILE
4729 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4730 NULL) == -1)
4731 err(1, "pledge");
4732 #endif
4734 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4735 switch (ch) {
4736 case 'a':
4737 force_text_diff = 1;
4738 break;
4739 case 'c':
4740 if (ncommit_args >= 2)
4741 errx(1, "too many -c options used");
4742 commit_args[ncommit_args++] = optarg;
4743 break;
4744 case 'C':
4745 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4746 &errstr);
4747 if (errstr != NULL)
4748 errx(1, "number of context lines is %s: %s",
4749 errstr, optarg);
4750 break;
4751 case 'r':
4752 repo_path = realpath(optarg, NULL);
4753 if (repo_path == NULL)
4754 return got_error_from_errno2("realpath",
4755 optarg);
4756 got_path_strip_trailing_slashes(repo_path);
4757 rflag = 1;
4758 break;
4759 case 's':
4760 diff_staged = 1;
4761 break;
4762 case 'w':
4763 ignore_whitespace = 1;
4764 break;
4765 case 'P':
4766 force_path = 1;
4767 break;
4768 default:
4769 usage_diff();
4770 /* NOTREACHED */
4774 argc -= optind;
4775 argv += optind;
4777 cwd = getcwd(NULL, 0);
4778 if (cwd == NULL) {
4779 error = got_error_from_errno("getcwd");
4780 goto done;
4783 if (repo_path == NULL) {
4784 error = got_worktree_open(&worktree, cwd);
4785 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4786 goto done;
4787 else
4788 error = NULL;
4789 if (worktree) {
4790 repo_path =
4791 strdup(got_worktree_get_repo_path(worktree));
4792 if (repo_path == NULL) {
4793 error = got_error_from_errno("strdup");
4794 goto done;
4796 } else {
4797 repo_path = strdup(cwd);
4798 if (repo_path == NULL) {
4799 error = got_error_from_errno("strdup");
4800 goto done;
4805 error = got_repo_open(&repo, repo_path, NULL);
4806 free(repo_path);
4807 if (error != NULL)
4808 goto done;
4810 if (rflag || worktree == NULL || ncommit_args > 0) {
4811 if (force_path) {
4812 error = got_error_msg(GOT_ERR_NOT_IMPL,
4813 "-P option can only be used when diffing "
4814 "a work tree");
4815 goto done;
4817 if (diff_staged) {
4818 error = got_error_msg(GOT_ERR_NOT_IMPL,
4819 "-s option can only be used when diffing "
4820 "a work tree");
4821 goto done;
4825 error = apply_unveil(got_repo_get_path(repo), 1,
4826 worktree ? got_worktree_get_root_path(worktree) : NULL);
4827 if (error)
4828 goto done;
4830 if ((!force_path && argc == 2) || ncommit_args > 0) {
4831 int obj_type = (ncommit_args > 0 ?
4832 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4833 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4834 NULL);
4835 if (error)
4836 goto done;
4837 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4838 const char *arg;
4839 if (ncommit_args > 0)
4840 arg = commit_args[i];
4841 else
4842 arg = argv[i];
4843 error = got_repo_match_object_id(&ids[i], &labels[i],
4844 arg, obj_type, &refs, repo);
4845 if (error) {
4846 if (error->code != GOT_ERR_NOT_REF &&
4847 error->code != GOT_ERR_NO_OBJ)
4848 goto done;
4849 if (ncommit_args > 0)
4850 goto done;
4851 error = NULL;
4852 break;
4857 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4858 struct print_diff_arg arg;
4859 char *id_str;
4861 if (worktree == NULL) {
4862 if (argc == 2 && ids[0] == NULL) {
4863 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4864 goto done;
4865 } else if (argc == 2 && ids[1] == NULL) {
4866 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4867 goto done;
4868 } else if (argc > 0) {
4869 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4870 "%s", "specified paths cannot be resolved");
4871 goto done;
4872 } else {
4873 error = got_error(GOT_ERR_NOT_WORKTREE);
4874 goto done;
4878 error = get_worktree_paths_from_argv(&paths, argc, argv,
4879 worktree);
4880 if (error)
4881 goto done;
4883 error = got_object_id_str(&id_str,
4884 got_worktree_get_base_commit_id(worktree));
4885 if (error)
4886 goto done;
4887 arg.repo = repo;
4888 arg.worktree = worktree;
4889 arg.diff_context = diff_context;
4890 arg.id_str = id_str;
4891 arg.header_shown = 0;
4892 arg.diff_staged = diff_staged;
4893 arg.ignore_whitespace = ignore_whitespace;
4894 arg.force_text_diff = force_text_diff;
4896 error = got_worktree_status(worktree, &paths, repo, 0,
4897 print_diff, &arg, check_cancelled, NULL);
4898 free(id_str);
4899 goto done;
4902 if (ncommit_args == 1) {
4903 struct got_commit_object *commit;
4904 error = got_object_open_as_commit(&commit, repo, ids[0]);
4905 if (error)
4906 goto done;
4908 labels[1] = labels[0];
4909 ids[1] = ids[0];
4910 if (got_object_commit_get_nparents(commit) > 0) {
4911 const struct got_object_id_queue *pids;
4912 struct got_object_qid *pid;
4913 pids = got_object_commit_get_parent_ids(commit);
4914 pid = STAILQ_FIRST(pids);
4915 ids[0] = got_object_id_dup(&pid->id);
4916 if (ids[0] == NULL) {
4917 error = got_error_from_errno(
4918 "got_object_id_dup");
4919 got_object_commit_close(commit);
4920 goto done;
4922 error = got_object_id_str(&labels[0], ids[0]);
4923 if (error) {
4924 got_object_commit_close(commit);
4925 goto done;
4927 } else {
4928 ids[0] = NULL;
4929 labels[0] = strdup("/dev/null");
4930 if (labels[0] == NULL) {
4931 error = got_error_from_errno("strdup");
4932 got_object_commit_close(commit);
4933 goto done;
4937 got_object_commit_close(commit);
4940 if (ncommit_args == 0 && argc > 2) {
4941 error = got_error_msg(GOT_ERR_BAD_PATH,
4942 "path arguments cannot be used when diffing two objects");
4943 goto done;
4946 if (ids[0]) {
4947 error = got_object_get_type(&type1, repo, ids[0]);
4948 if (error)
4949 goto done;
4952 error = got_object_get_type(&type2, repo, ids[1]);
4953 if (error)
4954 goto done;
4955 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4956 error = got_error(GOT_ERR_OBJ_TYPE);
4957 goto done;
4959 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4960 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4961 "path arguments cannot be used when diffing blobs");
4962 goto done;
4965 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4966 char *in_repo_path;
4967 struct got_pathlist_entry *new;
4968 if (worktree) {
4969 const char *prefix;
4970 char *p;
4971 error = got_worktree_resolve_path(&p, worktree,
4972 argv[i]);
4973 if (error)
4974 goto done;
4975 prefix = got_worktree_get_path_prefix(worktree);
4976 while (prefix[0] == '/')
4977 prefix++;
4978 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4979 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4980 p) == -1) {
4981 error = got_error_from_errno("asprintf");
4982 free(p);
4983 goto done;
4985 free(p);
4986 } else {
4987 char *mapped_path, *s;
4988 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4989 if (error)
4990 goto done;
4991 s = mapped_path;
4992 while (s[0] == '/')
4993 s++;
4994 in_repo_path = strdup(s);
4995 if (in_repo_path == NULL) {
4996 error = got_error_from_errno("asprintf");
4997 free(mapped_path);
4998 goto done;
5000 free(mapped_path);
5003 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5004 if (error || new == NULL /* duplicate */)
5005 free(in_repo_path);
5006 if (error)
5007 goto done;
5010 if (worktree) {
5011 /* Release work tree lock. */
5012 got_worktree_close(worktree);
5013 worktree = NULL;
5016 f1 = got_opentemp();
5017 if (f1 == NULL) {
5018 error = got_error_from_errno("got_opentemp");
5019 goto done;
5022 f2 = got_opentemp();
5023 if (f2 == NULL) {
5024 error = got_error_from_errno("got_opentemp");
5025 goto done;
5028 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5029 case GOT_OBJ_TYPE_BLOB:
5030 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5031 ids[0], ids[1], NULL, NULL, diff_context,
5032 ignore_whitespace, force_text_diff, repo, stdout);
5033 break;
5034 case GOT_OBJ_TYPE_TREE:
5035 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5036 ids[0], ids[1], &paths, "", "", diff_context,
5037 ignore_whitespace, force_text_diff, repo, stdout);
5038 break;
5039 case GOT_OBJ_TYPE_COMMIT:
5040 printf("diff %s %s\n", labels[0], labels[1]);
5041 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5042 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5043 force_text_diff, repo, stdout);
5044 break;
5045 default:
5046 error = got_error(GOT_ERR_OBJ_TYPE);
5048 done:
5049 free(labels[0]);
5050 free(labels[1]);
5051 free(ids[0]);
5052 free(ids[1]);
5053 if (worktree)
5054 got_worktree_close(worktree);
5055 if (repo) {
5056 const struct got_error *close_err = got_repo_close(repo);
5057 if (error == NULL)
5058 error = close_err;
5060 TAILQ_FOREACH(pe, &paths, entry)
5061 free((char *)pe->path);
5062 got_pathlist_free(&paths);
5063 got_ref_list_free(&refs);
5064 if (f1 && fclose(f1) == EOF && error == NULL)
5065 error = got_error_from_errno("fclose");
5066 if (f2 && fclose(f2) == EOF && error == NULL)
5067 error = got_error_from_errno("fclose");
5068 return error;
5071 __dead static void
5072 usage_blame(void)
5074 fprintf(stderr,
5075 "usage: %s blame [-c commit] [-r repository-path] path\n",
5076 getprogname());
5077 exit(1);
5080 struct blame_line {
5081 int annotated;
5082 char *id_str;
5083 char *committer;
5084 char datebuf[11]; /* YYYY-MM-DD + NUL */
5087 struct blame_cb_args {
5088 struct blame_line *lines;
5089 int nlines;
5090 int nlines_prec;
5091 int lineno_cur;
5092 off_t *line_offsets;
5093 FILE *f;
5094 struct got_repository *repo;
5097 static const struct got_error *
5098 blame_cb(void *arg, int nlines, int lineno,
5099 struct got_commit_object *commit, struct got_object_id *id)
5101 const struct got_error *err = NULL;
5102 struct blame_cb_args *a = arg;
5103 struct blame_line *bline;
5104 char *line = NULL;
5105 size_t linesize = 0;
5106 off_t offset;
5107 struct tm tm;
5108 time_t committer_time;
5110 if (nlines != a->nlines ||
5111 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5112 return got_error(GOT_ERR_RANGE);
5114 if (sigint_received)
5115 return got_error(GOT_ERR_ITER_COMPLETED);
5117 if (lineno == -1)
5118 return NULL; /* no change in this commit */
5120 /* Annotate this line. */
5121 bline = &a->lines[lineno - 1];
5122 if (bline->annotated)
5123 return NULL;
5124 err = got_object_id_str(&bline->id_str, id);
5125 if (err)
5126 return err;
5128 bline->committer = strdup(got_object_commit_get_committer(commit));
5129 if (bline->committer == NULL) {
5130 err = got_error_from_errno("strdup");
5131 goto done;
5134 committer_time = got_object_commit_get_committer_time(commit);
5135 if (gmtime_r(&committer_time, &tm) == NULL)
5136 return got_error_from_errno("gmtime_r");
5137 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5138 &tm) == 0) {
5139 err = got_error(GOT_ERR_NO_SPACE);
5140 goto done;
5142 bline->annotated = 1;
5144 /* Print lines annotated so far. */
5145 bline = &a->lines[a->lineno_cur - 1];
5146 if (!bline->annotated)
5147 goto done;
5149 offset = a->line_offsets[a->lineno_cur - 1];
5150 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5151 err = got_error_from_errno("fseeko");
5152 goto done;
5155 while (bline->annotated) {
5156 char *smallerthan, *at, *nl, *committer;
5157 size_t len;
5159 if (getline(&line, &linesize, a->f) == -1) {
5160 if (ferror(a->f))
5161 err = got_error_from_errno("getline");
5162 break;
5165 committer = bline->committer;
5166 smallerthan = strchr(committer, '<');
5167 if (smallerthan && smallerthan[1] != '\0')
5168 committer = smallerthan + 1;
5169 at = strchr(committer, '@');
5170 if (at)
5171 *at = '\0';
5172 len = strlen(committer);
5173 if (len >= 9)
5174 committer[8] = '\0';
5176 nl = strchr(line, '\n');
5177 if (nl)
5178 *nl = '\0';
5179 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5180 bline->id_str, bline->datebuf, committer, line);
5182 a->lineno_cur++;
5183 bline = &a->lines[a->lineno_cur - 1];
5185 done:
5186 free(line);
5187 return err;
5190 static const struct got_error *
5191 cmd_blame(int argc, char *argv[])
5193 const struct got_error *error;
5194 struct got_repository *repo = NULL;
5195 struct got_worktree *worktree = NULL;
5196 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5197 char *link_target = NULL;
5198 struct got_object_id *obj_id = NULL;
5199 struct got_object_id *commit_id = NULL;
5200 struct got_commit_object *commit = NULL;
5201 struct got_blob_object *blob = NULL;
5202 char *commit_id_str = NULL;
5203 struct blame_cb_args bca;
5204 int ch, obj_type, i;
5205 off_t filesize;
5207 memset(&bca, 0, sizeof(bca));
5209 #ifndef PROFILE
5210 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5211 NULL) == -1)
5212 err(1, "pledge");
5213 #endif
5215 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5216 switch (ch) {
5217 case 'c':
5218 commit_id_str = optarg;
5219 break;
5220 case 'r':
5221 repo_path = realpath(optarg, NULL);
5222 if (repo_path == NULL)
5223 return got_error_from_errno2("realpath",
5224 optarg);
5225 got_path_strip_trailing_slashes(repo_path);
5226 break;
5227 default:
5228 usage_blame();
5229 /* NOTREACHED */
5233 argc -= optind;
5234 argv += optind;
5236 if (argc == 1)
5237 path = argv[0];
5238 else
5239 usage_blame();
5241 cwd = getcwd(NULL, 0);
5242 if (cwd == NULL) {
5243 error = got_error_from_errno("getcwd");
5244 goto done;
5246 if (repo_path == NULL) {
5247 error = got_worktree_open(&worktree, cwd);
5248 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5249 goto done;
5250 else
5251 error = NULL;
5252 if (worktree) {
5253 repo_path =
5254 strdup(got_worktree_get_repo_path(worktree));
5255 if (repo_path == NULL) {
5256 error = got_error_from_errno("strdup");
5257 if (error)
5258 goto done;
5260 } else {
5261 repo_path = strdup(cwd);
5262 if (repo_path == NULL) {
5263 error = got_error_from_errno("strdup");
5264 goto done;
5269 error = got_repo_open(&repo, repo_path, NULL);
5270 if (error != NULL)
5271 goto done;
5273 if (worktree) {
5274 const char *prefix = got_worktree_get_path_prefix(worktree);
5275 char *p;
5277 error = got_worktree_resolve_path(&p, worktree, path);
5278 if (error)
5279 goto done;
5280 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5281 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5282 p) == -1) {
5283 error = got_error_from_errno("asprintf");
5284 free(p);
5285 goto done;
5287 free(p);
5288 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5289 } else {
5290 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5291 if (error)
5292 goto done;
5293 error = got_repo_map_path(&in_repo_path, repo, path);
5295 if (error)
5296 goto done;
5298 if (commit_id_str == NULL) {
5299 struct got_reference *head_ref;
5300 error = got_ref_open(&head_ref, repo, worktree ?
5301 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5302 if (error != NULL)
5303 goto done;
5304 error = got_ref_resolve(&commit_id, repo, head_ref);
5305 got_ref_close(head_ref);
5306 if (error != NULL)
5307 goto done;
5308 } else {
5309 struct got_reflist_head refs;
5310 TAILQ_INIT(&refs);
5311 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5312 NULL);
5313 if (error)
5314 goto done;
5315 error = got_repo_match_object_id(&commit_id, NULL,
5316 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5317 got_ref_list_free(&refs);
5318 if (error)
5319 goto done;
5322 if (worktree) {
5323 /* Release work tree lock. */
5324 got_worktree_close(worktree);
5325 worktree = NULL;
5328 error = got_object_open_as_commit(&commit, repo, commit_id);
5329 if (error)
5330 goto done;
5332 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5333 commit, repo);
5334 if (error)
5335 goto done;
5337 error = got_object_id_by_path(&obj_id, repo, commit,
5338 link_target ? link_target : in_repo_path);
5339 if (error)
5340 goto done;
5342 error = got_object_get_type(&obj_type, repo, obj_id);
5343 if (error)
5344 goto done;
5346 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5347 error = got_error_path(link_target ? link_target : in_repo_path,
5348 GOT_ERR_OBJ_TYPE);
5349 goto done;
5352 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5353 if (error)
5354 goto done;
5355 bca.f = got_opentemp();
5356 if (bca.f == NULL) {
5357 error = got_error_from_errno("got_opentemp");
5358 goto done;
5360 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5361 &bca.line_offsets, bca.f, blob);
5362 if (error || bca.nlines == 0)
5363 goto done;
5365 /* Don't include \n at EOF in the blame line count. */
5366 if (bca.line_offsets[bca.nlines - 1] == filesize)
5367 bca.nlines--;
5369 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5370 if (bca.lines == NULL) {
5371 error = got_error_from_errno("calloc");
5372 goto done;
5374 bca.lineno_cur = 1;
5375 bca.nlines_prec = 0;
5376 i = bca.nlines;
5377 while (i > 0) {
5378 i /= 10;
5379 bca.nlines_prec++;
5381 bca.repo = repo;
5383 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5384 repo, blame_cb, &bca, check_cancelled, NULL);
5385 done:
5386 free(in_repo_path);
5387 free(link_target);
5388 free(repo_path);
5389 free(cwd);
5390 free(commit_id);
5391 free(obj_id);
5392 if (commit)
5393 got_object_commit_close(commit);
5394 if (blob)
5395 got_object_blob_close(blob);
5396 if (worktree)
5397 got_worktree_close(worktree);
5398 if (repo) {
5399 const struct got_error *close_err = got_repo_close(repo);
5400 if (error == NULL)
5401 error = close_err;
5403 if (bca.lines) {
5404 for (i = 0; i < bca.nlines; i++) {
5405 struct blame_line *bline = &bca.lines[i];
5406 free(bline->id_str);
5407 free(bline->committer);
5409 free(bca.lines);
5411 free(bca.line_offsets);
5412 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5413 error = got_error_from_errno("fclose");
5414 return error;
5417 __dead static void
5418 usage_tree(void)
5420 fprintf(stderr,
5421 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5422 getprogname());
5423 exit(1);
5426 static const struct got_error *
5427 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5428 const char *root_path, struct got_repository *repo)
5430 const struct got_error *err = NULL;
5431 int is_root_path = (strcmp(path, root_path) == 0);
5432 const char *modestr = "";
5433 mode_t mode = got_tree_entry_get_mode(te);
5434 char *link_target = NULL;
5436 path += strlen(root_path);
5437 while (path[0] == '/')
5438 path++;
5440 if (got_object_tree_entry_is_submodule(te))
5441 modestr = "$";
5442 else if (S_ISLNK(mode)) {
5443 int i;
5445 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5446 if (err)
5447 return err;
5448 for (i = 0; i < strlen(link_target); i++) {
5449 if (!isprint((unsigned char)link_target[i]))
5450 link_target[i] = '?';
5453 modestr = "@";
5455 else if (S_ISDIR(mode))
5456 modestr = "/";
5457 else if (mode & S_IXUSR)
5458 modestr = "*";
5460 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5461 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5462 link_target ? " -> ": "", link_target ? link_target : "");
5464 free(link_target);
5465 return NULL;
5468 static const struct got_error *
5469 print_tree(const char *path, struct got_commit_object *commit,
5470 int show_ids, int recurse, const char *root_path,
5471 struct got_repository *repo)
5473 const struct got_error *err = NULL;
5474 struct got_object_id *tree_id = NULL;
5475 struct got_tree_object *tree = NULL;
5476 int nentries, i;
5478 err = got_object_id_by_path(&tree_id, repo, commit, path);
5479 if (err)
5480 goto done;
5482 err = got_object_open_as_tree(&tree, repo, tree_id);
5483 if (err)
5484 goto done;
5485 nentries = got_object_tree_get_nentries(tree);
5486 for (i = 0; i < nentries; i++) {
5487 struct got_tree_entry *te;
5488 char *id = NULL;
5490 if (sigint_received || sigpipe_received)
5491 break;
5493 te = got_object_tree_get_entry(tree, i);
5494 if (show_ids) {
5495 char *id_str;
5496 err = got_object_id_str(&id_str,
5497 got_tree_entry_get_id(te));
5498 if (err)
5499 goto done;
5500 if (asprintf(&id, "%s ", id_str) == -1) {
5501 err = got_error_from_errno("asprintf");
5502 free(id_str);
5503 goto done;
5505 free(id_str);
5507 err = print_entry(te, id, path, root_path, repo);
5508 free(id);
5509 if (err)
5510 goto done;
5512 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5513 char *child_path;
5514 if (asprintf(&child_path, "%s%s%s", path,
5515 path[0] == '/' && path[1] == '\0' ? "" : "/",
5516 got_tree_entry_get_name(te)) == -1) {
5517 err = got_error_from_errno("asprintf");
5518 goto done;
5520 err = print_tree(child_path, commit, show_ids, 1,
5521 root_path, repo);
5522 free(child_path);
5523 if (err)
5524 goto done;
5527 done:
5528 if (tree)
5529 got_object_tree_close(tree);
5530 free(tree_id);
5531 return err;
5534 static const struct got_error *
5535 cmd_tree(int argc, char *argv[])
5537 const struct got_error *error;
5538 struct got_repository *repo = NULL;
5539 struct got_worktree *worktree = NULL;
5540 const char *path, *refname = NULL;
5541 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5542 struct got_object_id *commit_id = NULL;
5543 struct got_commit_object *commit = NULL;
5544 char *commit_id_str = NULL;
5545 int show_ids = 0, recurse = 0;
5546 int ch;
5548 #ifndef PROFILE
5549 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5550 NULL) == -1)
5551 err(1, "pledge");
5552 #endif
5554 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5555 switch (ch) {
5556 case 'c':
5557 commit_id_str = optarg;
5558 break;
5559 case 'r':
5560 repo_path = realpath(optarg, NULL);
5561 if (repo_path == NULL)
5562 return got_error_from_errno2("realpath",
5563 optarg);
5564 got_path_strip_trailing_slashes(repo_path);
5565 break;
5566 case 'i':
5567 show_ids = 1;
5568 break;
5569 case 'R':
5570 recurse = 1;
5571 break;
5572 default:
5573 usage_tree();
5574 /* NOTREACHED */
5578 argc -= optind;
5579 argv += optind;
5581 if (argc == 1)
5582 path = argv[0];
5583 else if (argc > 1)
5584 usage_tree();
5585 else
5586 path = NULL;
5588 cwd = getcwd(NULL, 0);
5589 if (cwd == NULL) {
5590 error = got_error_from_errno("getcwd");
5591 goto done;
5593 if (repo_path == NULL) {
5594 error = got_worktree_open(&worktree, cwd);
5595 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5596 goto done;
5597 else
5598 error = NULL;
5599 if (worktree) {
5600 repo_path =
5601 strdup(got_worktree_get_repo_path(worktree));
5602 if (repo_path == NULL)
5603 error = got_error_from_errno("strdup");
5604 if (error)
5605 goto done;
5606 } else {
5607 repo_path = strdup(cwd);
5608 if (repo_path == NULL) {
5609 error = got_error_from_errno("strdup");
5610 goto done;
5615 error = got_repo_open(&repo, repo_path, NULL);
5616 if (error != NULL)
5617 goto done;
5619 if (worktree) {
5620 const char *prefix = got_worktree_get_path_prefix(worktree);
5621 char *p;
5623 if (path == NULL)
5624 path = "";
5625 error = got_worktree_resolve_path(&p, worktree, path);
5626 if (error)
5627 goto done;
5628 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5629 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5630 p) == -1) {
5631 error = got_error_from_errno("asprintf");
5632 free(p);
5633 goto done;
5635 free(p);
5636 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5637 if (error)
5638 goto done;
5639 } else {
5640 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5641 if (error)
5642 goto done;
5643 if (path == NULL)
5644 path = "/";
5645 error = got_repo_map_path(&in_repo_path, repo, path);
5646 if (error != NULL)
5647 goto done;
5650 if (commit_id_str == NULL) {
5651 struct got_reference *head_ref;
5652 if (worktree)
5653 refname = got_worktree_get_head_ref_name(worktree);
5654 else
5655 refname = GOT_REF_HEAD;
5656 error = got_ref_open(&head_ref, repo, refname, 0);
5657 if (error != NULL)
5658 goto done;
5659 error = got_ref_resolve(&commit_id, repo, head_ref);
5660 got_ref_close(head_ref);
5661 if (error != NULL)
5662 goto done;
5663 } else {
5664 struct got_reflist_head refs;
5665 TAILQ_INIT(&refs);
5666 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5667 NULL);
5668 if (error)
5669 goto done;
5670 error = got_repo_match_object_id(&commit_id, NULL,
5671 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5672 got_ref_list_free(&refs);
5673 if (error)
5674 goto done;
5677 if (worktree) {
5678 /* Release work tree lock. */
5679 got_worktree_close(worktree);
5680 worktree = NULL;
5683 error = got_object_open_as_commit(&commit, repo, commit_id);
5684 if (error)
5685 goto done;
5687 error = print_tree(in_repo_path, commit, show_ids, recurse,
5688 in_repo_path, repo);
5689 done:
5690 free(in_repo_path);
5691 free(repo_path);
5692 free(cwd);
5693 free(commit_id);
5694 if (commit)
5695 got_object_commit_close(commit);
5696 if (worktree)
5697 got_worktree_close(worktree);
5698 if (repo) {
5699 const struct got_error *close_err = got_repo_close(repo);
5700 if (error == NULL)
5701 error = close_err;
5703 return error;
5706 __dead static void
5707 usage_status(void)
5709 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5710 "[-S status-codes] [path ...]\n", getprogname());
5711 exit(1);
5714 struct got_status_arg {
5715 char *status_codes;
5716 int suppress;
5719 static const struct got_error *
5720 print_status(void *arg, unsigned char status, unsigned char staged_status,
5721 const char *path, struct got_object_id *blob_id,
5722 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5723 int dirfd, const char *de_name)
5725 struct got_status_arg *st = arg;
5727 if (status == staged_status && (status == GOT_STATUS_DELETE))
5728 status = GOT_STATUS_NO_CHANGE;
5729 if (st != NULL && st->status_codes) {
5730 size_t ncodes = strlen(st->status_codes);
5731 int i, j = 0;
5733 for (i = 0; i < ncodes ; i++) {
5734 if (st->suppress) {
5735 if (status == st->status_codes[i] ||
5736 staged_status == st->status_codes[i]) {
5737 j++;
5738 continue;
5740 } else {
5741 if (status == st->status_codes[i] ||
5742 staged_status == st->status_codes[i])
5743 break;
5747 if (st->suppress && j == 0)
5748 goto print;
5750 if (i == ncodes)
5751 return NULL;
5753 print:
5754 printf("%c%c %s\n", status, staged_status, path);
5755 return NULL;
5758 static const struct got_error *
5759 cmd_status(int argc, char *argv[])
5761 const struct got_error *error = NULL;
5762 struct got_repository *repo = NULL;
5763 struct got_worktree *worktree = NULL;
5764 struct got_status_arg st;
5765 char *cwd = NULL;
5766 struct got_pathlist_head paths;
5767 struct got_pathlist_entry *pe;
5768 int ch, i, no_ignores = 0;
5770 TAILQ_INIT(&paths);
5772 memset(&st, 0, sizeof(st));
5773 st.status_codes = NULL;
5774 st.suppress = 0;
5776 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5777 switch (ch) {
5778 case 'I':
5779 no_ignores = 1;
5780 break;
5781 case 'S':
5782 if (st.status_codes != NULL && st.suppress == 0)
5783 option_conflict('S', 's');
5784 st.suppress = 1;
5785 /* fallthrough */
5786 case 's':
5787 for (i = 0; i < strlen(optarg); i++) {
5788 switch (optarg[i]) {
5789 case GOT_STATUS_MODIFY:
5790 case GOT_STATUS_ADD:
5791 case GOT_STATUS_DELETE:
5792 case GOT_STATUS_CONFLICT:
5793 case GOT_STATUS_MISSING:
5794 case GOT_STATUS_OBSTRUCTED:
5795 case GOT_STATUS_UNVERSIONED:
5796 case GOT_STATUS_MODE_CHANGE:
5797 case GOT_STATUS_NONEXISTENT:
5798 break;
5799 default:
5800 errx(1, "invalid status code '%c'",
5801 optarg[i]);
5804 if (ch == 's' && st.suppress)
5805 option_conflict('s', 'S');
5806 st.status_codes = optarg;
5807 break;
5808 default:
5809 usage_status();
5810 /* NOTREACHED */
5814 argc -= optind;
5815 argv += optind;
5817 #ifndef PROFILE
5818 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5819 NULL) == -1)
5820 err(1, "pledge");
5821 #endif
5822 cwd = getcwd(NULL, 0);
5823 if (cwd == NULL) {
5824 error = got_error_from_errno("getcwd");
5825 goto done;
5828 error = got_worktree_open(&worktree, cwd);
5829 if (error) {
5830 if (error->code == GOT_ERR_NOT_WORKTREE)
5831 error = wrap_not_worktree_error(error, "status", cwd);
5832 goto done;
5835 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5836 NULL);
5837 if (error != NULL)
5838 goto done;
5840 error = apply_unveil(got_repo_get_path(repo), 1,
5841 got_worktree_get_root_path(worktree));
5842 if (error)
5843 goto done;
5845 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5846 if (error)
5847 goto done;
5849 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5850 print_status, &st, check_cancelled, NULL);
5851 done:
5852 TAILQ_FOREACH(pe, &paths, entry)
5853 free((char *)pe->path);
5854 got_pathlist_free(&paths);
5855 free(cwd);
5856 return error;
5859 __dead static void
5860 usage_ref(void)
5862 fprintf(stderr,
5863 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5864 "[-s reference] [-d] [name]\n",
5865 getprogname());
5866 exit(1);
5869 static const struct got_error *
5870 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5872 static const struct got_error *err = NULL;
5873 struct got_reflist_head refs;
5874 struct got_reflist_entry *re;
5876 TAILQ_INIT(&refs);
5877 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5878 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5879 repo);
5880 if (err)
5881 return err;
5883 TAILQ_FOREACH(re, &refs, entry) {
5884 char *refstr;
5885 refstr = got_ref_to_str(re->ref);
5886 if (refstr == NULL) {
5887 err = got_error_from_errno("got_ref_to_str");
5888 break;
5890 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5891 free(refstr);
5894 got_ref_list_free(&refs);
5895 return err;
5898 static const struct got_error *
5899 delete_ref_by_name(struct got_repository *repo, const char *refname)
5901 const struct got_error *err;
5902 struct got_reference *ref;
5904 err = got_ref_open(&ref, repo, refname, 0);
5905 if (err)
5906 return err;
5908 err = delete_ref(repo, ref);
5909 got_ref_close(ref);
5910 return err;
5913 static const struct got_error *
5914 add_ref(struct got_repository *repo, const char *refname, const char *target)
5916 const struct got_error *err = NULL;
5917 struct got_object_id *id = NULL;
5918 struct got_reference *ref = NULL;
5919 struct got_reflist_head refs;
5922 * Don't let the user create a reference name with a leading '-'.
5923 * While technically a valid reference name, this case is usually
5924 * an unintended typo.
5926 if (refname[0] == '-')
5927 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5929 TAILQ_INIT(&refs);
5930 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5931 if (err)
5932 goto done;
5933 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5934 &refs, repo);
5935 got_ref_list_free(&refs);
5936 if (err)
5937 goto done;
5939 err = got_ref_alloc(&ref, refname, id);
5940 if (err)
5941 goto done;
5943 err = got_ref_write(ref, repo);
5944 done:
5945 if (ref)
5946 got_ref_close(ref);
5947 free(id);
5948 return err;
5951 static const struct got_error *
5952 add_symref(struct got_repository *repo, const char *refname, const char *target)
5954 const struct got_error *err = NULL;
5955 struct got_reference *ref = NULL;
5956 struct got_reference *target_ref = NULL;
5959 * Don't let the user create a reference name with a leading '-'.
5960 * While technically a valid reference name, this case is usually
5961 * an unintended typo.
5963 if (refname[0] == '-')
5964 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5966 err = got_ref_open(&target_ref, repo, target, 0);
5967 if (err)
5968 return err;
5970 err = got_ref_alloc_symref(&ref, refname, target_ref);
5971 if (err)
5972 goto done;
5974 err = got_ref_write(ref, repo);
5975 done:
5976 if (target_ref)
5977 got_ref_close(target_ref);
5978 if (ref)
5979 got_ref_close(ref);
5980 return err;
5983 static const struct got_error *
5984 cmd_ref(int argc, char *argv[])
5986 const struct got_error *error = NULL;
5987 struct got_repository *repo = NULL;
5988 struct got_worktree *worktree = NULL;
5989 char *cwd = NULL, *repo_path = NULL;
5990 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5991 const char *obj_arg = NULL, *symref_target= NULL;
5992 char *refname = NULL;
5994 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5995 switch (ch) {
5996 case 'c':
5997 obj_arg = optarg;
5998 break;
5999 case 'd':
6000 do_delete = 1;
6001 break;
6002 case 'r':
6003 repo_path = realpath(optarg, NULL);
6004 if (repo_path == NULL)
6005 return got_error_from_errno2("realpath",
6006 optarg);
6007 got_path_strip_trailing_slashes(repo_path);
6008 break;
6009 case 'l':
6010 do_list = 1;
6011 break;
6012 case 's':
6013 symref_target = optarg;
6014 break;
6015 case 't':
6016 sort_by_time = 1;
6017 break;
6018 default:
6019 usage_ref();
6020 /* NOTREACHED */
6024 if (obj_arg && do_list)
6025 option_conflict('c', 'l');
6026 if (obj_arg && do_delete)
6027 option_conflict('c', 'd');
6028 if (obj_arg && symref_target)
6029 option_conflict('c', 's');
6030 if (symref_target && do_delete)
6031 option_conflict('s', 'd');
6032 if (symref_target && do_list)
6033 option_conflict('s', 'l');
6034 if (do_delete && do_list)
6035 option_conflict('d', 'l');
6036 if (sort_by_time && !do_list)
6037 errx(1, "-t option requires -l option");
6039 argc -= optind;
6040 argv += optind;
6042 if (do_list) {
6043 if (argc != 0 && argc != 1)
6044 usage_ref();
6045 if (argc == 1) {
6046 refname = strdup(argv[0]);
6047 if (refname == NULL) {
6048 error = got_error_from_errno("strdup");
6049 goto done;
6052 } else {
6053 if (argc != 1)
6054 usage_ref();
6055 refname = strdup(argv[0]);
6056 if (refname == NULL) {
6057 error = got_error_from_errno("strdup");
6058 goto done;
6062 if (refname)
6063 got_path_strip_trailing_slashes(refname);
6065 #ifndef PROFILE
6066 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6067 "sendfd unveil", NULL) == -1)
6068 err(1, "pledge");
6069 #endif
6070 cwd = getcwd(NULL, 0);
6071 if (cwd == NULL) {
6072 error = got_error_from_errno("getcwd");
6073 goto done;
6076 if (repo_path == NULL) {
6077 error = got_worktree_open(&worktree, cwd);
6078 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6079 goto done;
6080 else
6081 error = NULL;
6082 if (worktree) {
6083 repo_path =
6084 strdup(got_worktree_get_repo_path(worktree));
6085 if (repo_path == NULL)
6086 error = got_error_from_errno("strdup");
6087 if (error)
6088 goto done;
6089 } else {
6090 repo_path = strdup(cwd);
6091 if (repo_path == NULL) {
6092 error = got_error_from_errno("strdup");
6093 goto done;
6098 error = got_repo_open(&repo, repo_path, NULL);
6099 if (error != NULL)
6100 goto done;
6102 #ifndef PROFILE
6103 if (do_list) {
6104 /* Remove "cpath" promise. */
6105 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6106 NULL) == -1)
6107 err(1, "pledge");
6109 #endif
6111 error = apply_unveil(got_repo_get_path(repo), do_list,
6112 worktree ? got_worktree_get_root_path(worktree) : NULL);
6113 if (error)
6114 goto done;
6116 if (do_list)
6117 error = list_refs(repo, refname, sort_by_time);
6118 else if (do_delete)
6119 error = delete_ref_by_name(repo, refname);
6120 else if (symref_target)
6121 error = add_symref(repo, refname, symref_target);
6122 else {
6123 if (obj_arg == NULL)
6124 usage_ref();
6125 error = add_ref(repo, refname, obj_arg);
6127 done:
6128 free(refname);
6129 if (repo) {
6130 const struct got_error *close_err = got_repo_close(repo);
6131 if (error == NULL)
6132 error = close_err;
6134 if (worktree)
6135 got_worktree_close(worktree);
6136 free(cwd);
6137 free(repo_path);
6138 return error;
6141 __dead static void
6142 usage_branch(void)
6144 fprintf(stderr,
6145 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6146 "[-n] [name]\n", getprogname());
6147 exit(1);
6150 static const struct got_error *
6151 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6152 struct got_reference *ref)
6154 const struct got_error *err = NULL;
6155 const char *refname, *marker = " ";
6156 char *refstr;
6158 refname = got_ref_get_name(ref);
6159 if (worktree && strcmp(refname,
6160 got_worktree_get_head_ref_name(worktree)) == 0) {
6161 struct got_object_id *id = NULL;
6163 err = got_ref_resolve(&id, repo, ref);
6164 if (err)
6165 return err;
6166 if (got_object_id_cmp(id,
6167 got_worktree_get_base_commit_id(worktree)) == 0)
6168 marker = "* ";
6169 else
6170 marker = "~ ";
6171 free(id);
6174 if (strncmp(refname, "refs/heads/", 11) == 0)
6175 refname += 11;
6176 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6177 refname += 18;
6178 if (strncmp(refname, "refs/remotes/", 13) == 0)
6179 refname += 13;
6181 refstr = got_ref_to_str(ref);
6182 if (refstr == NULL)
6183 return got_error_from_errno("got_ref_to_str");
6185 printf("%s%s: %s\n", marker, refname, refstr);
6186 free(refstr);
6187 return NULL;
6190 static const struct got_error *
6191 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6193 const char *refname;
6195 if (worktree == NULL)
6196 return got_error(GOT_ERR_NOT_WORKTREE);
6198 refname = got_worktree_get_head_ref_name(worktree);
6200 if (strncmp(refname, "refs/heads/", 11) == 0)
6201 refname += 11;
6202 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6203 refname += 18;
6205 printf("%s\n", refname);
6207 return NULL;
6210 static const struct got_error *
6211 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6212 int sort_by_time)
6214 static const struct got_error *err = NULL;
6215 struct got_reflist_head refs;
6216 struct got_reflist_entry *re;
6217 struct got_reference *temp_ref = NULL;
6218 int rebase_in_progress, histedit_in_progress;
6220 TAILQ_INIT(&refs);
6222 if (worktree) {
6223 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6224 worktree);
6225 if (err)
6226 return err;
6228 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6229 worktree);
6230 if (err)
6231 return err;
6233 if (rebase_in_progress || histedit_in_progress) {
6234 err = got_ref_open(&temp_ref, repo,
6235 got_worktree_get_head_ref_name(worktree), 0);
6236 if (err)
6237 return err;
6238 list_branch(repo, worktree, temp_ref);
6239 got_ref_close(temp_ref);
6243 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6244 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6245 repo);
6246 if (err)
6247 return err;
6249 TAILQ_FOREACH(re, &refs, entry)
6250 list_branch(repo, worktree, re->ref);
6252 got_ref_list_free(&refs);
6254 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6255 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6256 repo);
6257 if (err)
6258 return err;
6260 TAILQ_FOREACH(re, &refs, entry)
6261 list_branch(repo, worktree, re->ref);
6263 got_ref_list_free(&refs);
6265 return NULL;
6268 static const struct got_error *
6269 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6270 const char *branch_name)
6272 const struct got_error *err = NULL;
6273 struct got_reference *ref = NULL;
6274 char *refname, *remote_refname = NULL;
6276 if (strncmp(branch_name, "refs/", 5) == 0)
6277 branch_name += 5;
6278 if (strncmp(branch_name, "heads/", 6) == 0)
6279 branch_name += 6;
6280 else if (strncmp(branch_name, "remotes/", 8) == 0)
6281 branch_name += 8;
6283 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6284 return got_error_from_errno("asprintf");
6286 if (asprintf(&remote_refname, "refs/remotes/%s",
6287 branch_name) == -1) {
6288 err = got_error_from_errno("asprintf");
6289 goto done;
6292 err = got_ref_open(&ref, repo, refname, 0);
6293 if (err) {
6294 const struct got_error *err2;
6295 if (err->code != GOT_ERR_NOT_REF)
6296 goto done;
6298 * Keep 'err' intact such that if neither branch exists
6299 * we report "refs/heads" rather than "refs/remotes" in
6300 * our error message.
6302 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6303 if (err2)
6304 goto done;
6305 err = NULL;
6308 if (worktree &&
6309 strcmp(got_worktree_get_head_ref_name(worktree),
6310 got_ref_get_name(ref)) == 0) {
6311 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6312 "will not delete this work tree's current branch");
6313 goto done;
6316 err = delete_ref(repo, ref);
6317 done:
6318 if (ref)
6319 got_ref_close(ref);
6320 free(refname);
6321 free(remote_refname);
6322 return err;
6325 static const struct got_error *
6326 add_branch(struct got_repository *repo, const char *branch_name,
6327 struct got_object_id *base_commit_id)
6329 const struct got_error *err = NULL;
6330 struct got_reference *ref = NULL;
6331 char *base_refname = NULL, *refname = NULL;
6334 * Don't let the user create a branch name with a leading '-'.
6335 * While technically a valid reference name, this case is usually
6336 * an unintended typo.
6338 if (branch_name[0] == '-')
6339 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6341 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6342 branch_name += 11;
6344 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6345 err = got_error_from_errno("asprintf");
6346 goto done;
6349 err = got_ref_open(&ref, repo, refname, 0);
6350 if (err == NULL) {
6351 err = got_error(GOT_ERR_BRANCH_EXISTS);
6352 goto done;
6353 } else if (err->code != GOT_ERR_NOT_REF)
6354 goto done;
6356 err = got_ref_alloc(&ref, refname, base_commit_id);
6357 if (err)
6358 goto done;
6360 err = got_ref_write(ref, repo);
6361 done:
6362 if (ref)
6363 got_ref_close(ref);
6364 free(base_refname);
6365 free(refname);
6366 return err;
6369 static const struct got_error *
6370 cmd_branch(int argc, char *argv[])
6372 const struct got_error *error = NULL;
6373 struct got_repository *repo = NULL;
6374 struct got_worktree *worktree = NULL;
6375 char *cwd = NULL, *repo_path = NULL;
6376 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6377 const char *delref = NULL, *commit_id_arg = NULL;
6378 struct got_reference *ref = NULL;
6379 struct got_pathlist_head paths;
6380 struct got_pathlist_entry *pe;
6381 struct got_object_id *commit_id = NULL;
6382 char *commit_id_str = NULL;
6384 TAILQ_INIT(&paths);
6386 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6387 switch (ch) {
6388 case 'c':
6389 commit_id_arg = optarg;
6390 break;
6391 case 'd':
6392 delref = optarg;
6393 break;
6394 case 'r':
6395 repo_path = realpath(optarg, NULL);
6396 if (repo_path == NULL)
6397 return got_error_from_errno2("realpath",
6398 optarg);
6399 got_path_strip_trailing_slashes(repo_path);
6400 break;
6401 case 'l':
6402 do_list = 1;
6403 break;
6404 case 'n':
6405 do_update = 0;
6406 break;
6407 case 't':
6408 sort_by_time = 1;
6409 break;
6410 default:
6411 usage_branch();
6412 /* NOTREACHED */
6416 if (do_list && delref)
6417 option_conflict('l', 'd');
6418 if (sort_by_time && !do_list)
6419 errx(1, "-t option requires -l option");
6421 argc -= optind;
6422 argv += optind;
6424 if (!do_list && !delref && argc == 0)
6425 do_show = 1;
6427 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6428 errx(1, "-c option can only be used when creating a branch");
6430 if (do_list || delref) {
6431 if (argc > 0)
6432 usage_branch();
6433 } else if (!do_show && argc != 1)
6434 usage_branch();
6436 #ifndef PROFILE
6437 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6438 "sendfd unveil", NULL) == -1)
6439 err(1, "pledge");
6440 #endif
6441 cwd = getcwd(NULL, 0);
6442 if (cwd == NULL) {
6443 error = got_error_from_errno("getcwd");
6444 goto done;
6447 if (repo_path == NULL) {
6448 error = got_worktree_open(&worktree, cwd);
6449 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6450 goto done;
6451 else
6452 error = NULL;
6453 if (worktree) {
6454 repo_path =
6455 strdup(got_worktree_get_repo_path(worktree));
6456 if (repo_path == NULL)
6457 error = got_error_from_errno("strdup");
6458 if (error)
6459 goto done;
6460 } else {
6461 repo_path = strdup(cwd);
6462 if (repo_path == NULL) {
6463 error = got_error_from_errno("strdup");
6464 goto done;
6469 error = got_repo_open(&repo, repo_path, NULL);
6470 if (error != NULL)
6471 goto done;
6473 #ifndef PROFILE
6474 if (do_list || do_show) {
6475 /* Remove "cpath" promise. */
6476 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6477 NULL) == -1)
6478 err(1, "pledge");
6480 #endif
6482 error = apply_unveil(got_repo_get_path(repo), do_list,
6483 worktree ? got_worktree_get_root_path(worktree) : NULL);
6484 if (error)
6485 goto done;
6487 if (do_show)
6488 error = show_current_branch(repo, worktree);
6489 else if (do_list)
6490 error = list_branches(repo, worktree, sort_by_time);
6491 else if (delref)
6492 error = delete_branch(repo, worktree, delref);
6493 else {
6494 struct got_reflist_head refs;
6495 TAILQ_INIT(&refs);
6496 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6497 NULL);
6498 if (error)
6499 goto done;
6500 if (commit_id_arg == NULL)
6501 commit_id_arg = worktree ?
6502 got_worktree_get_head_ref_name(worktree) :
6503 GOT_REF_HEAD;
6504 error = got_repo_match_object_id(&commit_id, NULL,
6505 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6506 got_ref_list_free(&refs);
6507 if (error)
6508 goto done;
6509 error = add_branch(repo, argv[0], commit_id);
6510 if (error)
6511 goto done;
6512 if (worktree && do_update) {
6513 struct got_update_progress_arg upa;
6514 char *branch_refname = NULL;
6516 error = got_object_id_str(&commit_id_str, commit_id);
6517 if (error)
6518 goto done;
6519 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6520 worktree);
6521 if (error)
6522 goto done;
6523 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6524 == -1) {
6525 error = got_error_from_errno("asprintf");
6526 goto done;
6528 error = got_ref_open(&ref, repo, branch_refname, 0);
6529 free(branch_refname);
6530 if (error)
6531 goto done;
6532 error = switch_head_ref(ref, commit_id, worktree,
6533 repo);
6534 if (error)
6535 goto done;
6536 error = got_worktree_set_base_commit_id(worktree, repo,
6537 commit_id);
6538 if (error)
6539 goto done;
6540 memset(&upa, 0, sizeof(upa));
6541 error = got_worktree_checkout_files(worktree, &paths,
6542 repo, update_progress, &upa, check_cancelled,
6543 NULL);
6544 if (error)
6545 goto done;
6546 if (upa.did_something) {
6547 printf("Updated to %s: %s\n",
6548 got_worktree_get_head_ref_name(worktree),
6549 commit_id_str);
6551 print_update_progress_stats(&upa);
6554 done:
6555 if (ref)
6556 got_ref_close(ref);
6557 if (repo) {
6558 const struct got_error *close_err = got_repo_close(repo);
6559 if (error == NULL)
6560 error = close_err;
6562 if (worktree)
6563 got_worktree_close(worktree);
6564 free(cwd);
6565 free(repo_path);
6566 free(commit_id);
6567 free(commit_id_str);
6568 TAILQ_FOREACH(pe, &paths, entry)
6569 free((char *)pe->path);
6570 got_pathlist_free(&paths);
6571 return error;
6575 __dead static void
6576 usage_tag(void)
6578 fprintf(stderr,
6579 "usage: %s tag [-c commit] [-r repository] [-l] "
6580 "[-m message] name\n", getprogname());
6581 exit(1);
6584 #if 0
6585 static const struct got_error *
6586 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6588 const struct got_error *err = NULL;
6589 struct got_reflist_entry *re, *se, *new;
6590 struct got_object_id *re_id, *se_id;
6591 struct got_tag_object *re_tag, *se_tag;
6592 time_t re_time, se_time;
6594 STAILQ_FOREACH(re, tags, entry) {
6595 se = STAILQ_FIRST(sorted);
6596 if (se == NULL) {
6597 err = got_reflist_entry_dup(&new, re);
6598 if (err)
6599 return err;
6600 STAILQ_INSERT_HEAD(sorted, new, entry);
6601 continue;
6602 } else {
6603 err = got_ref_resolve(&re_id, repo, re->ref);
6604 if (err)
6605 break;
6606 err = got_object_open_as_tag(&re_tag, repo, re_id);
6607 free(re_id);
6608 if (err)
6609 break;
6610 re_time = got_object_tag_get_tagger_time(re_tag);
6611 got_object_tag_close(re_tag);
6614 while (se) {
6615 err = got_ref_resolve(&se_id, repo, re->ref);
6616 if (err)
6617 break;
6618 err = got_object_open_as_tag(&se_tag, repo, se_id);
6619 free(se_id);
6620 if (err)
6621 break;
6622 se_time = got_object_tag_get_tagger_time(se_tag);
6623 got_object_tag_close(se_tag);
6625 if (se_time > re_time) {
6626 err = got_reflist_entry_dup(&new, re);
6627 if (err)
6628 return err;
6629 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6630 break;
6632 se = STAILQ_NEXT(se, entry);
6633 continue;
6636 done:
6637 return err;
6639 #endif
6641 static const struct got_error *
6642 list_tags(struct got_repository *repo)
6644 static const struct got_error *err = NULL;
6645 struct got_reflist_head refs;
6646 struct got_reflist_entry *re;
6648 TAILQ_INIT(&refs);
6650 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6651 if (err)
6652 return err;
6654 TAILQ_FOREACH(re, &refs, entry) {
6655 const char *refname;
6656 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6657 char datebuf[26];
6658 const char *tagger;
6659 time_t tagger_time;
6660 struct got_object_id *id;
6661 struct got_tag_object *tag;
6662 struct got_commit_object *commit = NULL;
6664 refname = got_ref_get_name(re->ref);
6665 if (strncmp(refname, "refs/tags/", 10) != 0)
6666 continue;
6667 refname += 10;
6668 refstr = got_ref_to_str(re->ref);
6669 if (refstr == NULL) {
6670 err = got_error_from_errno("got_ref_to_str");
6671 break;
6673 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6674 free(refstr);
6676 err = got_ref_resolve(&id, repo, re->ref);
6677 if (err)
6678 break;
6679 err = got_object_open_as_tag(&tag, repo, id);
6680 if (err) {
6681 if (err->code != GOT_ERR_OBJ_TYPE) {
6682 free(id);
6683 break;
6685 /* "lightweight" tag */
6686 err = got_object_open_as_commit(&commit, repo, id);
6687 if (err) {
6688 free(id);
6689 break;
6691 tagger = got_object_commit_get_committer(commit);
6692 tagger_time =
6693 got_object_commit_get_committer_time(commit);
6694 err = got_object_id_str(&id_str, id);
6695 free(id);
6696 if (err)
6697 break;
6698 } else {
6699 free(id);
6700 tagger = got_object_tag_get_tagger(tag);
6701 tagger_time = got_object_tag_get_tagger_time(tag);
6702 err = got_object_id_str(&id_str,
6703 got_object_tag_get_object_id(tag));
6704 if (err)
6705 break;
6707 printf("from: %s\n", tagger);
6708 datestr = get_datestr(&tagger_time, datebuf);
6709 if (datestr)
6710 printf("date: %s UTC\n", datestr);
6711 if (commit)
6712 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6713 else {
6714 switch (got_object_tag_get_object_type(tag)) {
6715 case GOT_OBJ_TYPE_BLOB:
6716 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6717 id_str);
6718 break;
6719 case GOT_OBJ_TYPE_TREE:
6720 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6721 id_str);
6722 break;
6723 case GOT_OBJ_TYPE_COMMIT:
6724 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6725 id_str);
6726 break;
6727 case GOT_OBJ_TYPE_TAG:
6728 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6729 id_str);
6730 break;
6731 default:
6732 break;
6735 free(id_str);
6736 if (commit) {
6737 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6738 if (err)
6739 break;
6740 got_object_commit_close(commit);
6741 } else {
6742 tagmsg0 = strdup(got_object_tag_get_message(tag));
6743 got_object_tag_close(tag);
6744 if (tagmsg0 == NULL) {
6745 err = got_error_from_errno("strdup");
6746 break;
6750 tagmsg = tagmsg0;
6751 do {
6752 line = strsep(&tagmsg, "\n");
6753 if (line)
6754 printf(" %s\n", line);
6755 } while (line);
6756 free(tagmsg0);
6759 got_ref_list_free(&refs);
6760 return NULL;
6763 static const struct got_error *
6764 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6765 const char *tag_name, const char *repo_path)
6767 const struct got_error *err = NULL;
6768 char *template = NULL, *initial_content = NULL;
6769 char *editor = NULL;
6770 int initial_content_len;
6771 int fd = -1;
6773 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6774 err = got_error_from_errno("asprintf");
6775 goto done;
6778 initial_content_len = asprintf(&initial_content,
6779 "\n# tagging commit %s as %s\n",
6780 commit_id_str, tag_name);
6781 if (initial_content_len == -1) {
6782 err = got_error_from_errno("asprintf");
6783 goto done;
6786 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6787 if (err)
6788 goto done;
6790 if (write(fd, initial_content, initial_content_len) == -1) {
6791 err = got_error_from_errno2("write", *tagmsg_path);
6792 goto done;
6795 err = get_editor(&editor);
6796 if (err)
6797 goto done;
6798 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6799 initial_content_len, 1);
6800 done:
6801 free(initial_content);
6802 free(template);
6803 free(editor);
6805 if (fd != -1 && close(fd) == -1 && err == NULL)
6806 err = got_error_from_errno2("close", *tagmsg_path);
6808 /* Editor is done; we can now apply unveil(2) */
6809 if (err == NULL)
6810 err = apply_unveil(repo_path, 0, NULL);
6811 if (err) {
6812 free(*tagmsg);
6813 *tagmsg = NULL;
6815 return err;
6818 static const struct got_error *
6819 add_tag(struct got_repository *repo, const char *tagger,
6820 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6822 const struct got_error *err = NULL;
6823 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6824 char *label = NULL, *commit_id_str = NULL;
6825 struct got_reference *ref = NULL;
6826 char *refname = NULL, *tagmsg = NULL;
6827 char *tagmsg_path = NULL, *tag_id_str = NULL;
6828 int preserve_tagmsg = 0;
6829 struct got_reflist_head refs;
6831 TAILQ_INIT(&refs);
6834 * Don't let the user create a tag name with a leading '-'.
6835 * While technically a valid reference name, this case is usually
6836 * an unintended typo.
6838 if (tag_name[0] == '-')
6839 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6841 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6842 if (err)
6843 goto done;
6845 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6846 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6847 if (err)
6848 goto done;
6850 err = got_object_id_str(&commit_id_str, commit_id);
6851 if (err)
6852 goto done;
6854 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6855 refname = strdup(tag_name);
6856 if (refname == NULL) {
6857 err = got_error_from_errno("strdup");
6858 goto done;
6860 tag_name += 10;
6861 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6862 err = got_error_from_errno("asprintf");
6863 goto done;
6866 err = got_ref_open(&ref, repo, refname, 0);
6867 if (err == NULL) {
6868 err = got_error(GOT_ERR_TAG_EXISTS);
6869 goto done;
6870 } else if (err->code != GOT_ERR_NOT_REF)
6871 goto done;
6873 if (tagmsg_arg == NULL) {
6874 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6875 tag_name, got_repo_get_path(repo));
6876 if (err) {
6877 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6878 tagmsg_path != NULL)
6879 preserve_tagmsg = 1;
6880 goto done;
6884 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6885 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6886 if (err) {
6887 if (tagmsg_path)
6888 preserve_tagmsg = 1;
6889 goto done;
6892 err = got_ref_alloc(&ref, refname, tag_id);
6893 if (err) {
6894 if (tagmsg_path)
6895 preserve_tagmsg = 1;
6896 goto done;
6899 err = got_ref_write(ref, repo);
6900 if (err) {
6901 if (tagmsg_path)
6902 preserve_tagmsg = 1;
6903 goto done;
6906 err = got_object_id_str(&tag_id_str, tag_id);
6907 if (err) {
6908 if (tagmsg_path)
6909 preserve_tagmsg = 1;
6910 goto done;
6912 printf("Created tag %s\n", tag_id_str);
6913 done:
6914 if (preserve_tagmsg) {
6915 fprintf(stderr, "%s: tag message preserved in %s\n",
6916 getprogname(), tagmsg_path);
6917 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6918 err = got_error_from_errno2("unlink", tagmsg_path);
6919 free(tag_id_str);
6920 if (ref)
6921 got_ref_close(ref);
6922 free(commit_id);
6923 free(commit_id_str);
6924 free(refname);
6925 free(tagmsg);
6926 free(tagmsg_path);
6927 got_ref_list_free(&refs);
6928 return err;
6931 static const struct got_error *
6932 cmd_tag(int argc, char *argv[])
6934 const struct got_error *error = NULL;
6935 struct got_repository *repo = NULL;
6936 struct got_worktree *worktree = NULL;
6937 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6938 char *gitconfig_path = NULL, *tagger = NULL;
6939 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6940 int ch, do_list = 0;
6942 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6943 switch (ch) {
6944 case 'c':
6945 commit_id_arg = optarg;
6946 break;
6947 case 'm':
6948 tagmsg = optarg;
6949 break;
6950 case 'r':
6951 repo_path = realpath(optarg, NULL);
6952 if (repo_path == NULL)
6953 return got_error_from_errno2("realpath",
6954 optarg);
6955 got_path_strip_trailing_slashes(repo_path);
6956 break;
6957 case 'l':
6958 do_list = 1;
6959 break;
6960 default:
6961 usage_tag();
6962 /* NOTREACHED */
6966 argc -= optind;
6967 argv += optind;
6969 if (do_list) {
6970 if (commit_id_arg != NULL)
6971 errx(1,
6972 "-c option can only be used when creating a tag");
6973 if (tagmsg)
6974 option_conflict('l', 'm');
6975 if (argc > 0)
6976 usage_tag();
6977 } else if (argc != 1)
6978 usage_tag();
6980 tag_name = argv[0];
6982 #ifndef PROFILE
6983 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6984 "sendfd unveil", NULL) == -1)
6985 err(1, "pledge");
6986 #endif
6987 cwd = getcwd(NULL, 0);
6988 if (cwd == NULL) {
6989 error = got_error_from_errno("getcwd");
6990 goto done;
6993 if (repo_path == NULL) {
6994 error = got_worktree_open(&worktree, cwd);
6995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6996 goto done;
6997 else
6998 error = NULL;
6999 if (worktree) {
7000 repo_path =
7001 strdup(got_worktree_get_repo_path(worktree));
7002 if (repo_path == NULL)
7003 error = got_error_from_errno("strdup");
7004 if (error)
7005 goto done;
7006 } else {
7007 repo_path = strdup(cwd);
7008 if (repo_path == NULL) {
7009 error = got_error_from_errno("strdup");
7010 goto done;
7015 if (do_list) {
7016 if (worktree) {
7017 /* Release work tree lock. */
7018 got_worktree_close(worktree);
7019 worktree = NULL;
7021 error = got_repo_open(&repo, repo_path, NULL);
7022 if (error != NULL)
7023 goto done;
7024 #ifndef PROFILE
7025 /* Remove "cpath" promise. */
7026 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7027 NULL) == -1)
7028 err(1, "pledge");
7029 #endif
7030 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7031 if (error)
7032 goto done;
7033 error = list_tags(repo);
7034 } else {
7035 error = get_gitconfig_path(&gitconfig_path);
7036 if (error)
7037 goto done;
7038 error = got_repo_open(&repo, repo_path, gitconfig_path);
7039 if (error != NULL)
7040 goto done;
7042 error = get_author(&tagger, repo, worktree);
7043 if (error)
7044 goto done;
7045 if (worktree) {
7046 /* Release work tree lock. */
7047 got_worktree_close(worktree);
7048 worktree = NULL;
7051 if (tagmsg) {
7052 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7053 if (error)
7054 goto done;
7057 if (commit_id_arg == NULL) {
7058 struct got_reference *head_ref;
7059 struct got_object_id *commit_id;
7060 error = got_ref_open(&head_ref, repo,
7061 worktree ? got_worktree_get_head_ref_name(worktree)
7062 : GOT_REF_HEAD, 0);
7063 if (error)
7064 goto done;
7065 error = got_ref_resolve(&commit_id, repo, head_ref);
7066 got_ref_close(head_ref);
7067 if (error)
7068 goto done;
7069 error = got_object_id_str(&commit_id_str, commit_id);
7070 free(commit_id);
7071 if (error)
7072 goto done;
7075 error = add_tag(repo, tagger, tag_name,
7076 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7078 done:
7079 if (repo) {
7080 const struct got_error *close_err = got_repo_close(repo);
7081 if (error == NULL)
7082 error = close_err;
7084 if (worktree)
7085 got_worktree_close(worktree);
7086 free(cwd);
7087 free(repo_path);
7088 free(gitconfig_path);
7089 free(commit_id_str);
7090 free(tagger);
7091 return error;
7094 __dead static void
7095 usage_add(void)
7097 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7098 getprogname());
7099 exit(1);
7102 static const struct got_error *
7103 add_progress(void *arg, unsigned char status, const char *path)
7105 while (path[0] == '/')
7106 path++;
7107 printf("%c %s\n", status, path);
7108 return NULL;
7111 static const struct got_error *
7112 cmd_add(int argc, char *argv[])
7114 const struct got_error *error = NULL;
7115 struct got_repository *repo = NULL;
7116 struct got_worktree *worktree = NULL;
7117 char *cwd = NULL;
7118 struct got_pathlist_head paths;
7119 struct got_pathlist_entry *pe;
7120 int ch, can_recurse = 0, no_ignores = 0;
7122 TAILQ_INIT(&paths);
7124 while ((ch = getopt(argc, argv, "IR")) != -1) {
7125 switch (ch) {
7126 case 'I':
7127 no_ignores = 1;
7128 break;
7129 case 'R':
7130 can_recurse = 1;
7131 break;
7132 default:
7133 usage_add();
7134 /* NOTREACHED */
7138 argc -= optind;
7139 argv += optind;
7141 #ifndef PROFILE
7142 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7143 NULL) == -1)
7144 err(1, "pledge");
7145 #endif
7146 if (argc < 1)
7147 usage_add();
7149 cwd = getcwd(NULL, 0);
7150 if (cwd == NULL) {
7151 error = got_error_from_errno("getcwd");
7152 goto done;
7155 error = got_worktree_open(&worktree, cwd);
7156 if (error) {
7157 if (error->code == GOT_ERR_NOT_WORKTREE)
7158 error = wrap_not_worktree_error(error, "add", cwd);
7159 goto done;
7162 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7163 NULL);
7164 if (error != NULL)
7165 goto done;
7167 error = apply_unveil(got_repo_get_path(repo), 1,
7168 got_worktree_get_root_path(worktree));
7169 if (error)
7170 goto done;
7172 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7173 if (error)
7174 goto done;
7176 if (!can_recurse) {
7177 char *ondisk_path;
7178 struct stat sb;
7179 TAILQ_FOREACH(pe, &paths, entry) {
7180 if (asprintf(&ondisk_path, "%s/%s",
7181 got_worktree_get_root_path(worktree),
7182 pe->path) == -1) {
7183 error = got_error_from_errno("asprintf");
7184 goto done;
7186 if (lstat(ondisk_path, &sb) == -1) {
7187 if (errno == ENOENT) {
7188 free(ondisk_path);
7189 continue;
7191 error = got_error_from_errno2("lstat",
7192 ondisk_path);
7193 free(ondisk_path);
7194 goto done;
7196 free(ondisk_path);
7197 if (S_ISDIR(sb.st_mode)) {
7198 error = got_error_msg(GOT_ERR_BAD_PATH,
7199 "adding directories requires -R option");
7200 goto done;
7205 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7206 NULL, repo, no_ignores);
7207 done:
7208 if (repo) {
7209 const struct got_error *close_err = got_repo_close(repo);
7210 if (error == NULL)
7211 error = close_err;
7213 if (worktree)
7214 got_worktree_close(worktree);
7215 TAILQ_FOREACH(pe, &paths, entry)
7216 free((char *)pe->path);
7217 got_pathlist_free(&paths);
7218 free(cwd);
7219 return error;
7222 __dead static void
7223 usage_remove(void)
7225 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7226 "path ...\n", getprogname());
7227 exit(1);
7230 static const struct got_error *
7231 print_remove_status(void *arg, unsigned char status,
7232 unsigned char staged_status, const char *path)
7234 while (path[0] == '/')
7235 path++;
7236 if (status == GOT_STATUS_NONEXISTENT)
7237 return NULL;
7238 if (status == staged_status && (status == GOT_STATUS_DELETE))
7239 status = GOT_STATUS_NO_CHANGE;
7240 printf("%c%c %s\n", status, staged_status, path);
7241 return NULL;
7244 static const struct got_error *
7245 cmd_remove(int argc, char *argv[])
7247 const struct got_error *error = NULL;
7248 struct got_worktree *worktree = NULL;
7249 struct got_repository *repo = NULL;
7250 const char *status_codes = NULL;
7251 char *cwd = NULL;
7252 struct got_pathlist_head paths;
7253 struct got_pathlist_entry *pe;
7254 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7255 int ignore_missing_paths = 0;
7257 TAILQ_INIT(&paths);
7259 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7260 switch (ch) {
7261 case 'f':
7262 delete_local_mods = 1;
7263 ignore_missing_paths = 1;
7264 break;
7265 case 'k':
7266 keep_on_disk = 1;
7267 break;
7268 case 'R':
7269 can_recurse = 1;
7270 break;
7271 case 's':
7272 for (i = 0; i < strlen(optarg); i++) {
7273 switch (optarg[i]) {
7274 case GOT_STATUS_MODIFY:
7275 delete_local_mods = 1;
7276 break;
7277 case GOT_STATUS_MISSING:
7278 ignore_missing_paths = 1;
7279 break;
7280 default:
7281 errx(1, "invalid status code '%c'",
7282 optarg[i]);
7285 status_codes = optarg;
7286 break;
7287 default:
7288 usage_remove();
7289 /* NOTREACHED */
7293 argc -= optind;
7294 argv += optind;
7296 #ifndef PROFILE
7297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7298 NULL) == -1)
7299 err(1, "pledge");
7300 #endif
7301 if (argc < 1)
7302 usage_remove();
7304 cwd = getcwd(NULL, 0);
7305 if (cwd == NULL) {
7306 error = got_error_from_errno("getcwd");
7307 goto done;
7309 error = got_worktree_open(&worktree, cwd);
7310 if (error) {
7311 if (error->code == GOT_ERR_NOT_WORKTREE)
7312 error = wrap_not_worktree_error(error, "remove", cwd);
7313 goto done;
7316 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7317 NULL);
7318 if (error)
7319 goto done;
7321 error = apply_unveil(got_repo_get_path(repo), 1,
7322 got_worktree_get_root_path(worktree));
7323 if (error)
7324 goto done;
7326 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7327 if (error)
7328 goto done;
7330 if (!can_recurse) {
7331 char *ondisk_path;
7332 struct stat sb;
7333 TAILQ_FOREACH(pe, &paths, entry) {
7334 if (asprintf(&ondisk_path, "%s/%s",
7335 got_worktree_get_root_path(worktree),
7336 pe->path) == -1) {
7337 error = got_error_from_errno("asprintf");
7338 goto done;
7340 if (lstat(ondisk_path, &sb) == -1) {
7341 if (errno == ENOENT) {
7342 free(ondisk_path);
7343 continue;
7345 error = got_error_from_errno2("lstat",
7346 ondisk_path);
7347 free(ondisk_path);
7348 goto done;
7350 free(ondisk_path);
7351 if (S_ISDIR(sb.st_mode)) {
7352 error = got_error_msg(GOT_ERR_BAD_PATH,
7353 "removing directories requires -R option");
7354 goto done;
7359 error = got_worktree_schedule_delete(worktree, &paths,
7360 delete_local_mods, status_codes, print_remove_status, NULL,
7361 repo, keep_on_disk, ignore_missing_paths);
7362 done:
7363 if (repo) {
7364 const struct got_error *close_err = got_repo_close(repo);
7365 if (error == NULL)
7366 error = close_err;
7368 if (worktree)
7369 got_worktree_close(worktree);
7370 TAILQ_FOREACH(pe, &paths, entry)
7371 free((char *)pe->path);
7372 got_pathlist_free(&paths);
7373 free(cwd);
7374 return error;
7377 __dead static void
7378 usage_patch(void)
7380 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7381 "[-R] [patchfile]\n", getprogname());
7382 exit(1);
7385 static const struct got_error *
7386 patch_from_stdin(int *patchfd)
7388 const struct got_error *err = NULL;
7389 ssize_t r;
7390 char *path, buf[BUFSIZ];
7391 sig_t sighup, sigint, sigquit;
7393 err = got_opentemp_named_fd(&path, patchfd,
7394 GOT_TMPDIR_STR "/got-patch");
7395 if (err)
7396 return err;
7397 unlink(path);
7398 free(path);
7400 sighup = signal(SIGHUP, SIG_DFL);
7401 sigint = signal(SIGINT, SIG_DFL);
7402 sigquit = signal(SIGQUIT, SIG_DFL);
7404 for (;;) {
7405 r = read(0, buf, sizeof(buf));
7406 if (r == -1) {
7407 err = got_error_from_errno("read");
7408 break;
7410 if (r == 0)
7411 break;
7412 if (write(*patchfd, buf, r) == -1) {
7413 err = got_error_from_errno("write");
7414 break;
7418 signal(SIGHUP, sighup);
7419 signal(SIGINT, sigint);
7420 signal(SIGQUIT, sigquit);
7422 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7423 err = got_error_from_errno("lseek");
7425 if (err != NULL) {
7426 close(*patchfd);
7427 *patchfd = -1;
7430 return err;
7433 static const struct got_error *
7434 patch_progress(void *arg, const char *old, const char *new,
7435 unsigned char status, const struct got_error *error, long old_from,
7436 long old_lines, long new_from, long new_lines, long offset,
7437 const struct got_error *hunk_err)
7439 const char *path = new == NULL ? old : new;
7441 while (*path == '/')
7442 path++;
7444 if (status != 0)
7445 printf("%c %s\n", status, path);
7447 if (error != NULL)
7448 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7450 if (offset != 0 || hunk_err != NULL) {
7451 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7452 old_lines, new_from, new_lines);
7453 if (hunk_err != NULL)
7454 printf("%s\n", hunk_err->msg);
7455 else
7456 printf("applied with offset %ld\n", offset);
7459 return NULL;
7462 static const struct got_error *
7463 cmd_patch(int argc, char *argv[])
7465 const struct got_error *error = NULL, *close_error = NULL;
7466 struct got_worktree *worktree = NULL;
7467 struct got_repository *repo = NULL;
7468 const char *errstr;
7469 char *cwd = NULL;
7470 int ch, nop = 0, strip = -1, reverse = 0;
7471 int patchfd;
7473 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7474 switch (ch) {
7475 case 'n':
7476 nop = 1;
7477 break;
7478 case 'p':
7479 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7480 if (errstr != NULL)
7481 errx(1, "pathname strip count is %s: %s",
7482 errstr, optarg);
7483 break;
7484 case 'R':
7485 reverse = 1;
7486 break;
7487 default:
7488 usage_patch();
7489 /* NOTREACHED */
7493 argc -= optind;
7494 argv += optind;
7496 if (argc == 0) {
7497 error = patch_from_stdin(&patchfd);
7498 if (error)
7499 return error;
7500 } else if (argc == 1) {
7501 patchfd = open(argv[0], O_RDONLY);
7502 if (patchfd == -1) {
7503 error = got_error_from_errno2("open", argv[0]);
7504 return error;
7506 } else
7507 usage_patch();
7509 if ((cwd = getcwd(NULL, 0)) == NULL) {
7510 error = got_error_from_errno("getcwd");
7511 goto done;
7514 error = got_worktree_open(&worktree, cwd);
7515 if (error != NULL)
7516 goto done;
7518 const char *repo_path = got_worktree_get_repo_path(worktree);
7519 error = got_repo_open(&repo, repo_path, NULL);
7520 if (error != NULL)
7521 goto done;
7523 error = apply_unveil(got_repo_get_path(repo), 0,
7524 got_worktree_get_root_path(worktree));
7525 if (error != NULL)
7526 goto done;
7528 #ifndef PROFILE
7529 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7530 NULL) == -1)
7531 err(1, "pledge");
7532 #endif
7534 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7535 &patch_progress, NULL, check_cancelled, NULL);
7537 done:
7538 if (repo) {
7539 close_error = got_repo_close(repo);
7540 if (error == NULL)
7541 error = close_error;
7543 if (worktree != NULL) {
7544 close_error = got_worktree_close(worktree);
7545 if (error == NULL)
7546 error = close_error;
7548 free(cwd);
7549 return error;
7552 __dead static void
7553 usage_revert(void)
7555 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7556 "path ...\n", getprogname());
7557 exit(1);
7560 static const struct got_error *
7561 revert_progress(void *arg, unsigned char status, const char *path)
7563 if (status == GOT_STATUS_UNVERSIONED)
7564 return NULL;
7566 while (path[0] == '/')
7567 path++;
7568 printf("%c %s\n", status, path);
7569 return NULL;
7572 struct choose_patch_arg {
7573 FILE *patch_script_file;
7574 const char *action;
7577 static const struct got_error *
7578 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7579 int nchanges, const char *action)
7581 const struct got_error *err;
7582 char *line = NULL;
7583 size_t linesize = 0;
7584 ssize_t linelen;
7586 switch (status) {
7587 case GOT_STATUS_ADD:
7588 printf("A %s\n%s this addition? [y/n] ", path, action);
7589 break;
7590 case GOT_STATUS_DELETE:
7591 printf("D %s\n%s this deletion? [y/n] ", path, action);
7592 break;
7593 case GOT_STATUS_MODIFY:
7594 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7595 return got_error_from_errno("fseek");
7596 printf(GOT_COMMIT_SEP_STR);
7597 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7598 printf("%s", line);
7599 if (linelen == -1 && ferror(patch_file)) {
7600 err = got_error_from_errno("getline");
7601 free(line);
7602 return err;
7604 free(line);
7605 printf(GOT_COMMIT_SEP_STR);
7606 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7607 path, n, nchanges, action);
7608 break;
7609 default:
7610 return got_error_path(path, GOT_ERR_FILE_STATUS);
7613 return NULL;
7616 static const struct got_error *
7617 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7618 FILE *patch_file, int n, int nchanges)
7620 const struct got_error *err = NULL;
7621 char *line = NULL;
7622 size_t linesize = 0;
7623 ssize_t linelen;
7624 int resp = ' ';
7625 struct choose_patch_arg *a = arg;
7627 *choice = GOT_PATCH_CHOICE_NONE;
7629 if (a->patch_script_file) {
7630 char *nl;
7631 err = show_change(status, path, patch_file, n, nchanges,
7632 a->action);
7633 if (err)
7634 return err;
7635 linelen = getline(&line, &linesize, a->patch_script_file);
7636 if (linelen == -1) {
7637 if (ferror(a->patch_script_file))
7638 return got_error_from_errno("getline");
7639 return NULL;
7641 nl = strchr(line, '\n');
7642 if (nl)
7643 *nl = '\0';
7644 if (strcmp(line, "y") == 0) {
7645 *choice = GOT_PATCH_CHOICE_YES;
7646 printf("y\n");
7647 } else if (strcmp(line, "n") == 0) {
7648 *choice = GOT_PATCH_CHOICE_NO;
7649 printf("n\n");
7650 } else if (strcmp(line, "q") == 0 &&
7651 status == GOT_STATUS_MODIFY) {
7652 *choice = GOT_PATCH_CHOICE_QUIT;
7653 printf("q\n");
7654 } else
7655 printf("invalid response '%s'\n", line);
7656 free(line);
7657 return NULL;
7660 while (resp != 'y' && resp != 'n' && resp != 'q') {
7661 err = show_change(status, path, patch_file, n, nchanges,
7662 a->action);
7663 if (err)
7664 return err;
7665 resp = getchar();
7666 if (resp == '\n')
7667 resp = getchar();
7668 if (status == GOT_STATUS_MODIFY) {
7669 if (resp != 'y' && resp != 'n' && resp != 'q') {
7670 printf("invalid response '%c'\n", resp);
7671 resp = ' ';
7673 } else if (resp != 'y' && resp != 'n') {
7674 printf("invalid response '%c'\n", resp);
7675 resp = ' ';
7679 if (resp == 'y')
7680 *choice = GOT_PATCH_CHOICE_YES;
7681 else if (resp == 'n')
7682 *choice = GOT_PATCH_CHOICE_NO;
7683 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7684 *choice = GOT_PATCH_CHOICE_QUIT;
7686 return NULL;
7689 static const struct got_error *
7690 cmd_revert(int argc, char *argv[])
7692 const struct got_error *error = NULL;
7693 struct got_worktree *worktree = NULL;
7694 struct got_repository *repo = NULL;
7695 char *cwd = NULL, *path = NULL;
7696 struct got_pathlist_head paths;
7697 struct got_pathlist_entry *pe;
7698 int ch, can_recurse = 0, pflag = 0;
7699 FILE *patch_script_file = NULL;
7700 const char *patch_script_path = NULL;
7701 struct choose_patch_arg cpa;
7703 TAILQ_INIT(&paths);
7705 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7706 switch (ch) {
7707 case 'p':
7708 pflag = 1;
7709 break;
7710 case 'F':
7711 patch_script_path = optarg;
7712 break;
7713 case 'R':
7714 can_recurse = 1;
7715 break;
7716 default:
7717 usage_revert();
7718 /* NOTREACHED */
7722 argc -= optind;
7723 argv += optind;
7725 #ifndef PROFILE
7726 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7727 "unveil", NULL) == -1)
7728 err(1, "pledge");
7729 #endif
7730 if (argc < 1)
7731 usage_revert();
7732 if (patch_script_path && !pflag)
7733 errx(1, "-F option can only be used together with -p option");
7735 cwd = getcwd(NULL, 0);
7736 if (cwd == NULL) {
7737 error = got_error_from_errno("getcwd");
7738 goto done;
7740 error = got_worktree_open(&worktree, cwd);
7741 if (error) {
7742 if (error->code == GOT_ERR_NOT_WORKTREE)
7743 error = wrap_not_worktree_error(error, "revert", cwd);
7744 goto done;
7747 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7748 NULL);
7749 if (error != NULL)
7750 goto done;
7752 if (patch_script_path) {
7753 patch_script_file = fopen(patch_script_path, "re");
7754 if (patch_script_file == NULL) {
7755 error = got_error_from_errno2("fopen",
7756 patch_script_path);
7757 goto done;
7760 error = apply_unveil(got_repo_get_path(repo), 1,
7761 got_worktree_get_root_path(worktree));
7762 if (error)
7763 goto done;
7765 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7766 if (error)
7767 goto done;
7769 if (!can_recurse) {
7770 char *ondisk_path;
7771 struct stat sb;
7772 TAILQ_FOREACH(pe, &paths, entry) {
7773 if (asprintf(&ondisk_path, "%s/%s",
7774 got_worktree_get_root_path(worktree),
7775 pe->path) == -1) {
7776 error = got_error_from_errno("asprintf");
7777 goto done;
7779 if (lstat(ondisk_path, &sb) == -1) {
7780 if (errno == ENOENT) {
7781 free(ondisk_path);
7782 continue;
7784 error = got_error_from_errno2("lstat",
7785 ondisk_path);
7786 free(ondisk_path);
7787 goto done;
7789 free(ondisk_path);
7790 if (S_ISDIR(sb.st_mode)) {
7791 error = got_error_msg(GOT_ERR_BAD_PATH,
7792 "reverting directories requires -R option");
7793 goto done;
7798 cpa.patch_script_file = patch_script_file;
7799 cpa.action = "revert";
7800 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7801 pflag ? choose_patch : NULL, &cpa, repo);
7802 done:
7803 if (patch_script_file && fclose(patch_script_file) == EOF &&
7804 error == NULL)
7805 error = got_error_from_errno2("fclose", patch_script_path);
7806 if (repo) {
7807 const struct got_error *close_err = got_repo_close(repo);
7808 if (error == NULL)
7809 error = close_err;
7811 if (worktree)
7812 got_worktree_close(worktree);
7813 free(path);
7814 free(cwd);
7815 return error;
7818 __dead static void
7819 usage_commit(void)
7821 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7822 "[path ...]\n", getprogname());
7823 exit(1);
7826 struct collect_commit_logmsg_arg {
7827 const char *cmdline_log;
7828 const char *prepared_log;
7829 int non_interactive;
7830 const char *editor;
7831 const char *worktree_path;
7832 const char *branch_name;
7833 const char *repo_path;
7834 char *logmsg_path;
7838 static const struct got_error *
7839 read_prepared_logmsg(char **logmsg, const char *path)
7841 const struct got_error *err = NULL;
7842 FILE *f = NULL;
7843 struct stat sb;
7844 size_t r;
7846 *logmsg = NULL;
7847 memset(&sb, 0, sizeof(sb));
7849 f = fopen(path, "re");
7850 if (f == NULL)
7851 return got_error_from_errno2("fopen", path);
7853 if (fstat(fileno(f), &sb) == -1) {
7854 err = got_error_from_errno2("fstat", path);
7855 goto done;
7857 if (sb.st_size == 0) {
7858 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7859 goto done;
7862 *logmsg = malloc(sb.st_size + 1);
7863 if (*logmsg == NULL) {
7864 err = got_error_from_errno("malloc");
7865 goto done;
7868 r = fread(*logmsg, 1, sb.st_size, f);
7869 if (r != sb.st_size) {
7870 if (ferror(f))
7871 err = got_error_from_errno2("fread", path);
7872 else
7873 err = got_error(GOT_ERR_IO);
7874 goto done;
7876 (*logmsg)[sb.st_size] = '\0';
7877 done:
7878 if (fclose(f) == EOF && err == NULL)
7879 err = got_error_from_errno2("fclose", path);
7880 if (err) {
7881 free(*logmsg);
7882 *logmsg = NULL;
7884 return err;
7888 static const struct got_error *
7889 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7890 void *arg)
7892 char *initial_content = NULL;
7893 struct got_pathlist_entry *pe;
7894 const struct got_error *err = NULL;
7895 char *template = NULL;
7896 struct collect_commit_logmsg_arg *a = arg;
7897 int initial_content_len;
7898 int fd = -1;
7899 size_t len;
7901 /* if a message was specified on the command line, just use it */
7902 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7903 len = strlen(a->cmdline_log) + 1;
7904 *logmsg = malloc(len + 1);
7905 if (*logmsg == NULL)
7906 return got_error_from_errno("malloc");
7907 strlcpy(*logmsg, a->cmdline_log, len);
7908 return NULL;
7909 } else if (a->prepared_log != NULL && a->non_interactive)
7910 return read_prepared_logmsg(logmsg, a->prepared_log);
7912 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7913 return got_error_from_errno("asprintf");
7915 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7916 if (err)
7917 goto done;
7919 if (a->prepared_log) {
7920 char *msg;
7921 err = read_prepared_logmsg(&msg, a->prepared_log);
7922 if (err)
7923 goto done;
7924 if (write(fd, msg, strlen(msg)) == -1) {
7925 err = got_error_from_errno2("write", a->logmsg_path);
7926 free(msg);
7927 goto done;
7929 free(msg);
7932 initial_content_len = asprintf(&initial_content,
7933 "\n# changes to be committed on branch %s:\n",
7934 a->branch_name);
7935 if (initial_content_len == -1) {
7936 err = got_error_from_errno("asprintf");
7937 goto done;
7940 if (write(fd, initial_content, initial_content_len) == -1) {
7941 err = got_error_from_errno2("write", a->logmsg_path);
7942 goto done;
7945 TAILQ_FOREACH(pe, commitable_paths, entry) {
7946 struct got_commitable *ct = pe->data;
7947 dprintf(fd, "# %c %s\n",
7948 got_commitable_get_status(ct),
7949 got_commitable_get_path(ct));
7952 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7953 initial_content_len, a->prepared_log ? 0 : 1);
7954 done:
7955 free(initial_content);
7956 free(template);
7958 if (fd != -1 && close(fd) == -1 && err == NULL)
7959 err = got_error_from_errno2("close", a->logmsg_path);
7961 /* Editor is done; we can now apply unveil(2) */
7962 if (err == NULL)
7963 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7964 if (err) {
7965 free(*logmsg);
7966 *logmsg = NULL;
7968 return err;
7971 static const struct got_error *
7972 cmd_commit(int argc, char *argv[])
7974 const struct got_error *error = NULL;
7975 struct got_worktree *worktree = NULL;
7976 struct got_repository *repo = NULL;
7977 char *cwd = NULL, *id_str = NULL;
7978 struct got_object_id *id = NULL;
7979 const char *logmsg = NULL;
7980 char *prepared_logmsg = NULL;
7981 struct collect_commit_logmsg_arg cl_arg;
7982 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7983 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7984 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7985 struct got_pathlist_head paths;
7987 TAILQ_INIT(&paths);
7988 cl_arg.logmsg_path = NULL;
7990 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7991 switch (ch) {
7992 case 'F':
7993 if (logmsg != NULL)
7994 option_conflict('F', 'm');
7995 prepared_logmsg = realpath(optarg, NULL);
7996 if (prepared_logmsg == NULL)
7997 return got_error_from_errno2("realpath",
7998 optarg);
7999 break;
8000 case 'm':
8001 if (prepared_logmsg)
8002 option_conflict('m', 'F');
8003 logmsg = optarg;
8004 break;
8005 case 'N':
8006 non_interactive = 1;
8007 break;
8008 case 'S':
8009 allow_bad_symlinks = 1;
8010 break;
8011 default:
8012 usage_commit();
8013 /* NOTREACHED */
8017 argc -= optind;
8018 argv += optind;
8020 #ifndef PROFILE
8021 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8022 "unveil", NULL) == -1)
8023 err(1, "pledge");
8024 #endif
8025 cwd = getcwd(NULL, 0);
8026 if (cwd == NULL) {
8027 error = got_error_from_errno("getcwd");
8028 goto done;
8030 error = got_worktree_open(&worktree, cwd);
8031 if (error) {
8032 if (error->code == GOT_ERR_NOT_WORKTREE)
8033 error = wrap_not_worktree_error(error, "commit", cwd);
8034 goto done;
8037 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8038 if (error)
8039 goto done;
8040 if (rebase_in_progress) {
8041 error = got_error(GOT_ERR_REBASING);
8042 goto done;
8045 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8046 worktree);
8047 if (error)
8048 goto done;
8050 error = get_gitconfig_path(&gitconfig_path);
8051 if (error)
8052 goto done;
8053 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8054 gitconfig_path);
8055 if (error != NULL)
8056 goto done;
8058 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8059 if (error)
8060 goto done;
8061 if (merge_in_progress) {
8062 error = got_error(GOT_ERR_MERGE_BUSY);
8063 goto done;
8066 error = get_author(&author, repo, worktree);
8067 if (error)
8068 return error;
8071 * unveil(2) traverses exec(2); if an editor is used we have
8072 * to apply unveil after the log message has been written.
8074 if (logmsg == NULL || strlen(logmsg) == 0)
8075 error = get_editor(&editor);
8076 else
8077 error = apply_unveil(got_repo_get_path(repo), 0,
8078 got_worktree_get_root_path(worktree));
8079 if (error)
8080 goto done;
8082 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8083 if (error)
8084 goto done;
8086 cl_arg.editor = editor;
8087 cl_arg.cmdline_log = logmsg;
8088 cl_arg.prepared_log = prepared_logmsg;
8089 cl_arg.non_interactive = non_interactive;
8090 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8091 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8092 if (!histedit_in_progress) {
8093 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8094 error = got_error(GOT_ERR_COMMIT_BRANCH);
8095 goto done;
8097 cl_arg.branch_name += 11;
8099 cl_arg.repo_path = got_repo_get_path(repo);
8100 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8101 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8102 print_status, NULL, repo);
8103 if (error) {
8104 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8105 cl_arg.logmsg_path != NULL)
8106 preserve_logmsg = 1;
8107 goto done;
8110 error = got_object_id_str(&id_str, id);
8111 if (error)
8112 goto done;
8113 printf("Created commit %s\n", id_str);
8114 done:
8115 if (preserve_logmsg) {
8116 fprintf(stderr, "%s: log message preserved in %s\n",
8117 getprogname(), cl_arg.logmsg_path);
8118 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8119 error == NULL)
8120 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8121 free(cl_arg.logmsg_path);
8122 if (repo) {
8123 const struct got_error *close_err = got_repo_close(repo);
8124 if (error == NULL)
8125 error = close_err;
8127 if (worktree)
8128 got_worktree_close(worktree);
8129 free(cwd);
8130 free(id_str);
8131 free(gitconfig_path);
8132 free(editor);
8133 free(author);
8134 free(prepared_logmsg);
8135 return error;
8138 __dead static void
8139 usage_send(void)
8141 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8142 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8143 "[remote-repository]\n", getprogname());
8144 exit(1);
8147 static void
8148 print_load_info(int print_colored, int print_found, int print_trees,
8149 int ncolored, int nfound, int ntrees)
8151 if (print_colored) {
8152 printf("%d commit%s colored", ncolored,
8153 ncolored == 1 ? "" : "s");
8155 if (print_found) {
8156 printf("%s%d object%s found",
8157 ncolored > 0 ? "; " : "",
8158 nfound, nfound == 1 ? "" : "s");
8160 if (print_trees) {
8161 printf("; %d tree%s scanned", ntrees,
8162 ntrees == 1 ? "" : "s");
8166 struct got_send_progress_arg {
8167 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8168 int verbosity;
8169 int last_ncolored;
8170 int last_nfound;
8171 int last_ntrees;
8172 int loading_done;
8173 int last_ncommits;
8174 int last_nobj_total;
8175 int last_p_deltify;
8176 int last_p_written;
8177 int last_p_sent;
8178 int printed_something;
8179 int sent_something;
8180 struct got_pathlist_head *delete_branches;
8183 static const struct got_error *
8184 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8185 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8186 int nobj_written, off_t bytes_sent, const char *refname, int success)
8188 struct got_send_progress_arg *a = arg;
8189 char scaled_packsize[FMT_SCALED_STRSIZE];
8190 char scaled_sent[FMT_SCALED_STRSIZE];
8191 int p_deltify = 0, p_written = 0, p_sent = 0;
8192 int print_colored = 0, print_found = 0, print_trees = 0;
8193 int print_searching = 0, print_total = 0;
8194 int print_deltify = 0, print_written = 0, print_sent = 0;
8196 if (a->verbosity < 0)
8197 return NULL;
8199 if (refname) {
8200 const char *status = success ? "accepted" : "rejected";
8202 if (success) {
8203 struct got_pathlist_entry *pe;
8204 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8205 const char *branchname = pe->path;
8206 if (got_path_cmp(branchname, refname,
8207 strlen(branchname), strlen(refname)) == 0) {
8208 status = "deleted";
8209 a->sent_something = 1;
8210 break;
8215 if (a->printed_something)
8216 putchar('\n');
8217 printf("Server has %s %s", status, refname);
8218 a->printed_something = 1;
8219 return NULL;
8222 if (a->last_ncolored != ncolored) {
8223 print_colored = 1;
8224 a->last_ncolored = ncolored;
8227 if (a->last_nfound != nfound) {
8228 print_colored = 1;
8229 print_found = 1;
8230 a->last_nfound = nfound;
8233 if (a->last_ntrees != ntrees) {
8234 print_colored = 1;
8235 print_found = 1;
8236 print_trees = 1;
8237 a->last_ntrees = ntrees;
8240 if ((print_colored || print_found || print_trees) &&
8241 !a->loading_done) {
8242 printf("\r");
8243 print_load_info(print_colored, print_found, print_trees,
8244 ncolored, nfound, ntrees);
8245 a->printed_something = 1;
8246 fflush(stdout);
8247 return NULL;
8248 } else if (!a->loading_done) {
8249 printf("\r");
8250 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8251 printf("\n");
8252 a->loading_done = 1;
8255 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8256 return got_error_from_errno("fmt_scaled");
8257 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8258 return got_error_from_errno("fmt_scaled");
8260 if (a->last_ncommits != ncommits) {
8261 print_searching = 1;
8262 a->last_ncommits = ncommits;
8265 if (a->last_nobj_total != nobj_total) {
8266 print_searching = 1;
8267 print_total = 1;
8268 a->last_nobj_total = nobj_total;
8271 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8272 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8273 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8274 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8275 return got_error(GOT_ERR_NO_SPACE);
8278 if (nobj_deltify > 0 || nobj_written > 0) {
8279 if (nobj_deltify > 0) {
8280 p_deltify = (nobj_deltify * 100) / nobj_total;
8281 if (p_deltify != a->last_p_deltify) {
8282 a->last_p_deltify = p_deltify;
8283 print_searching = 1;
8284 print_total = 1;
8285 print_deltify = 1;
8288 if (nobj_written > 0) {
8289 p_written = (nobj_written * 100) / nobj_total;
8290 if (p_written != a->last_p_written) {
8291 a->last_p_written = p_written;
8292 print_searching = 1;
8293 print_total = 1;
8294 print_deltify = 1;
8295 print_written = 1;
8300 if (bytes_sent > 0) {
8301 p_sent = (bytes_sent * 100) / packfile_size;
8302 if (p_sent != a->last_p_sent) {
8303 a->last_p_sent = p_sent;
8304 print_searching = 1;
8305 print_total = 1;
8306 print_deltify = 1;
8307 print_written = 1;
8308 print_sent = 1;
8310 a->sent_something = 1;
8313 if (print_searching || print_total || print_deltify || print_written ||
8314 print_sent)
8315 printf("\r");
8316 if (print_searching)
8317 printf("packing %d reference%s", ncommits,
8318 ncommits == 1 ? "" : "s");
8319 if (print_total)
8320 printf("; %d object%s", nobj_total,
8321 nobj_total == 1 ? "" : "s");
8322 if (print_deltify)
8323 printf("; deltify: %d%%", p_deltify);
8324 if (print_sent)
8325 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8326 scaled_packsize, p_sent);
8327 else if (print_written)
8328 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8329 scaled_packsize, p_written);
8330 if (print_searching || print_total || print_deltify ||
8331 print_written || print_sent) {
8332 a->printed_something = 1;
8333 fflush(stdout);
8335 return NULL;
8338 static const struct got_error *
8339 cmd_send(int argc, char *argv[])
8341 const struct got_error *error = NULL;
8342 char *cwd = NULL, *repo_path = NULL;
8343 const char *remote_name;
8344 char *proto = NULL, *host = NULL, *port = NULL;
8345 char *repo_name = NULL, *server_path = NULL;
8346 const struct got_remote_repo *remotes, *remote = NULL;
8347 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8348 struct got_repository *repo = NULL;
8349 struct got_worktree *worktree = NULL;
8350 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8351 struct got_pathlist_head branches;
8352 struct got_pathlist_head tags;
8353 struct got_reflist_head all_branches;
8354 struct got_reflist_head all_tags;
8355 struct got_pathlist_head delete_args;
8356 struct got_pathlist_head delete_branches;
8357 struct got_reflist_entry *re;
8358 struct got_pathlist_entry *pe;
8359 int i, ch, sendfd = -1, sendstatus;
8360 pid_t sendpid = -1;
8361 struct got_send_progress_arg spa;
8362 int verbosity = 0, overwrite_refs = 0;
8363 int send_all_branches = 0, send_all_tags = 0;
8364 struct got_reference *ref = NULL;
8366 TAILQ_INIT(&branches);
8367 TAILQ_INIT(&tags);
8368 TAILQ_INIT(&all_branches);
8369 TAILQ_INIT(&all_tags);
8370 TAILQ_INIT(&delete_args);
8371 TAILQ_INIT(&delete_branches);
8373 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8374 switch (ch) {
8375 case 'a':
8376 send_all_branches = 1;
8377 break;
8378 case 'b':
8379 error = got_pathlist_append(&branches, optarg, NULL);
8380 if (error)
8381 return error;
8382 nbranches++;
8383 break;
8384 case 'd':
8385 error = got_pathlist_append(&delete_args, optarg, NULL);
8386 if (error)
8387 return error;
8388 break;
8389 case 'f':
8390 overwrite_refs = 1;
8391 break;
8392 case 'r':
8393 repo_path = realpath(optarg, NULL);
8394 if (repo_path == NULL)
8395 return got_error_from_errno2("realpath",
8396 optarg);
8397 got_path_strip_trailing_slashes(repo_path);
8398 break;
8399 case 't':
8400 error = got_pathlist_append(&tags, optarg, NULL);
8401 if (error)
8402 return error;
8403 ntags++;
8404 break;
8405 case 'T':
8406 send_all_tags = 1;
8407 break;
8408 case 'v':
8409 if (verbosity < 0)
8410 verbosity = 0;
8411 else if (verbosity < 3)
8412 verbosity++;
8413 break;
8414 case 'q':
8415 verbosity = -1;
8416 break;
8417 default:
8418 usage_send();
8419 /* NOTREACHED */
8422 argc -= optind;
8423 argv += optind;
8425 if (send_all_branches && !TAILQ_EMPTY(&branches))
8426 option_conflict('a', 'b');
8427 if (send_all_tags && !TAILQ_EMPTY(&tags))
8428 option_conflict('T', 't');
8431 if (argc == 0)
8432 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8433 else if (argc == 1)
8434 remote_name = argv[0];
8435 else
8436 usage_send();
8438 cwd = getcwd(NULL, 0);
8439 if (cwd == NULL) {
8440 error = got_error_from_errno("getcwd");
8441 goto done;
8444 if (repo_path == NULL) {
8445 error = got_worktree_open(&worktree, cwd);
8446 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8447 goto done;
8448 else
8449 error = NULL;
8450 if (worktree) {
8451 repo_path =
8452 strdup(got_worktree_get_repo_path(worktree));
8453 if (repo_path == NULL)
8454 error = got_error_from_errno("strdup");
8455 if (error)
8456 goto done;
8457 } else {
8458 repo_path = strdup(cwd);
8459 if (repo_path == NULL) {
8460 error = got_error_from_errno("strdup");
8461 goto done;
8466 error = got_repo_open(&repo, repo_path, NULL);
8467 if (error)
8468 goto done;
8470 if (worktree) {
8471 worktree_conf = got_worktree_get_gotconfig(worktree);
8472 if (worktree_conf) {
8473 got_gotconfig_get_remotes(&nremotes, &remotes,
8474 worktree_conf);
8475 for (i = 0; i < nremotes; i++) {
8476 if (strcmp(remotes[i].name, remote_name) == 0) {
8477 remote = &remotes[i];
8478 break;
8483 if (remote == NULL) {
8484 repo_conf = got_repo_get_gotconfig(repo);
8485 if (repo_conf) {
8486 got_gotconfig_get_remotes(&nremotes, &remotes,
8487 repo_conf);
8488 for (i = 0; i < nremotes; i++) {
8489 if (strcmp(remotes[i].name, remote_name) == 0) {
8490 remote = &remotes[i];
8491 break;
8496 if (remote == NULL) {
8497 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8498 for (i = 0; i < nremotes; i++) {
8499 if (strcmp(remotes[i].name, remote_name) == 0) {
8500 remote = &remotes[i];
8501 break;
8505 if (remote == NULL) {
8506 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8507 goto done;
8510 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8511 &repo_name, remote->send_url);
8512 if (error)
8513 goto done;
8515 if (strcmp(proto, "git") == 0) {
8516 #ifndef PROFILE
8517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8518 "sendfd dns inet unveil", NULL) == -1)
8519 err(1, "pledge");
8520 #endif
8521 } else if (strcmp(proto, "git+ssh") == 0 ||
8522 strcmp(proto, "ssh") == 0) {
8523 #ifndef PROFILE
8524 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8525 "sendfd unveil", NULL) == -1)
8526 err(1, "pledge");
8527 #endif
8528 } else if (strcmp(proto, "http") == 0 ||
8529 strcmp(proto, "git+http") == 0) {
8530 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8531 goto done;
8532 } else {
8533 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8534 goto done;
8537 error = got_dial_apply_unveil(proto);
8538 if (error)
8539 goto done;
8541 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8542 if (error)
8543 goto done;
8545 if (send_all_branches) {
8546 error = got_ref_list(&all_branches, repo, "refs/heads",
8547 got_ref_cmp_by_name, NULL);
8548 if (error)
8549 goto done;
8550 TAILQ_FOREACH(re, &all_branches, entry) {
8551 const char *branchname = got_ref_get_name(re->ref);
8552 error = got_pathlist_append(&branches,
8553 branchname, NULL);
8554 if (error)
8555 goto done;
8556 nbranches++;
8558 } else if (nbranches == 0) {
8559 for (i = 0; i < remote->nsend_branches; i++) {
8560 got_pathlist_append(&branches,
8561 remote->send_branches[i], NULL);
8565 if (send_all_tags) {
8566 error = got_ref_list(&all_tags, repo, "refs/tags",
8567 got_ref_cmp_by_name, NULL);
8568 if (error)
8569 goto done;
8570 TAILQ_FOREACH(re, &all_tags, entry) {
8571 const char *tagname = got_ref_get_name(re->ref);
8572 error = got_pathlist_append(&tags,
8573 tagname, NULL);
8574 if (error)
8575 goto done;
8576 ntags++;
8581 * To prevent accidents only branches in refs/heads/ can be deleted
8582 * with 'got send -d'.
8583 * Deleting anything else requires local repository access or Git.
8585 TAILQ_FOREACH(pe, &delete_args, entry) {
8586 const char *branchname = pe->path;
8587 char *s;
8588 struct got_pathlist_entry *new;
8589 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8590 s = strdup(branchname);
8591 if (s == NULL) {
8592 error = got_error_from_errno("strdup");
8593 goto done;
8595 } else {
8596 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8597 error = got_error_from_errno("asprintf");
8598 goto done;
8601 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8602 if (error || new == NULL /* duplicate */)
8603 free(s);
8604 if (error)
8605 goto done;
8606 ndelete_branches++;
8609 if (nbranches == 0 && ndelete_branches == 0) {
8610 struct got_reference *head_ref;
8611 if (worktree)
8612 error = got_ref_open(&head_ref, repo,
8613 got_worktree_get_head_ref_name(worktree), 0);
8614 else
8615 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8616 if (error)
8617 goto done;
8618 if (got_ref_is_symbolic(head_ref)) {
8619 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8620 got_ref_close(head_ref);
8621 if (error)
8622 goto done;
8623 } else
8624 ref = head_ref;
8625 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8626 NULL);
8627 if (error)
8628 goto done;
8629 nbranches++;
8632 if (verbosity >= 0)
8633 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8634 port ? ":" : "", port ? port : "");
8636 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8637 server_path, verbosity);
8638 if (error)
8639 goto done;
8641 memset(&spa, 0, sizeof(spa));
8642 spa.last_scaled_packsize[0] = '\0';
8643 spa.last_p_deltify = -1;
8644 spa.last_p_written = -1;
8645 spa.verbosity = verbosity;
8646 spa.delete_branches = &delete_branches;
8647 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8648 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8649 check_cancelled, NULL);
8650 if (spa.printed_something)
8651 putchar('\n');
8652 if (error)
8653 goto done;
8654 if (!spa.sent_something && verbosity >= 0)
8655 printf("Already up-to-date\n");
8656 done:
8657 if (sendpid > 0) {
8658 if (kill(sendpid, SIGTERM) == -1)
8659 error = got_error_from_errno("kill");
8660 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8661 error = got_error_from_errno("waitpid");
8663 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8664 error = got_error_from_errno("close");
8665 if (repo) {
8666 const struct got_error *close_err = got_repo_close(repo);
8667 if (error == NULL)
8668 error = close_err;
8670 if (worktree)
8671 got_worktree_close(worktree);
8672 if (ref)
8673 got_ref_close(ref);
8674 got_pathlist_free(&branches);
8675 got_pathlist_free(&tags);
8676 got_ref_list_free(&all_branches);
8677 got_ref_list_free(&all_tags);
8678 got_pathlist_free(&delete_args);
8679 TAILQ_FOREACH(pe, &delete_branches, entry)
8680 free((char *)pe->path);
8681 got_pathlist_free(&delete_branches);
8682 free(cwd);
8683 free(repo_path);
8684 free(proto);
8685 free(host);
8686 free(port);
8687 free(server_path);
8688 free(repo_name);
8689 return error;
8692 __dead static void
8693 usage_cherrypick(void)
8695 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8696 exit(1);
8699 static const struct got_error *
8700 cmd_cherrypick(int argc, char *argv[])
8702 const struct got_error *error = NULL;
8703 struct got_worktree *worktree = NULL;
8704 struct got_repository *repo = NULL;
8705 char *cwd = NULL, *commit_id_str = NULL;
8706 struct got_object_id *commit_id = NULL;
8707 struct got_commit_object *commit = NULL;
8708 struct got_object_qid *pid;
8709 int ch;
8710 struct got_update_progress_arg upa;
8712 while ((ch = getopt(argc, argv, "")) != -1) {
8713 switch (ch) {
8714 default:
8715 usage_cherrypick();
8716 /* NOTREACHED */
8720 argc -= optind;
8721 argv += optind;
8723 #ifndef PROFILE
8724 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8725 "unveil", NULL) == -1)
8726 err(1, "pledge");
8727 #endif
8728 if (argc != 1)
8729 usage_cherrypick();
8731 cwd = getcwd(NULL, 0);
8732 if (cwd == NULL) {
8733 error = got_error_from_errno("getcwd");
8734 goto done;
8736 error = got_worktree_open(&worktree, cwd);
8737 if (error) {
8738 if (error->code == GOT_ERR_NOT_WORKTREE)
8739 error = wrap_not_worktree_error(error, "cherrypick",
8740 cwd);
8741 goto done;
8744 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8745 NULL);
8746 if (error != NULL)
8747 goto done;
8749 error = apply_unveil(got_repo_get_path(repo), 0,
8750 got_worktree_get_root_path(worktree));
8751 if (error)
8752 goto done;
8754 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8755 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8756 if (error)
8757 goto done;
8758 error = got_object_id_str(&commit_id_str, commit_id);
8759 if (error)
8760 goto done;
8762 error = got_object_open_as_commit(&commit, repo, commit_id);
8763 if (error)
8764 goto done;
8765 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8766 memset(&upa, 0, sizeof(upa));
8767 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8768 commit_id, repo, update_progress, &upa, check_cancelled,
8769 NULL);
8770 if (error != NULL)
8771 goto done;
8773 if (upa.did_something)
8774 printf("Merged commit %s\n", commit_id_str);
8775 print_merge_progress_stats(&upa);
8776 done:
8777 if (commit)
8778 got_object_commit_close(commit);
8779 free(commit_id_str);
8780 if (worktree)
8781 got_worktree_close(worktree);
8782 if (repo) {
8783 const struct got_error *close_err = got_repo_close(repo);
8784 if (error == NULL)
8785 error = close_err;
8787 return error;
8790 __dead static void
8791 usage_backout(void)
8793 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8794 exit(1);
8797 static const struct got_error *
8798 cmd_backout(int argc, char *argv[])
8800 const struct got_error *error = NULL;
8801 struct got_worktree *worktree = NULL;
8802 struct got_repository *repo = NULL;
8803 char *cwd = NULL, *commit_id_str = NULL;
8804 struct got_object_id *commit_id = NULL;
8805 struct got_commit_object *commit = NULL;
8806 struct got_object_qid *pid;
8807 int ch;
8808 struct got_update_progress_arg upa;
8810 while ((ch = getopt(argc, argv, "")) != -1) {
8811 switch (ch) {
8812 default:
8813 usage_backout();
8814 /* NOTREACHED */
8818 argc -= optind;
8819 argv += optind;
8821 #ifndef PROFILE
8822 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8823 "unveil", NULL) == -1)
8824 err(1, "pledge");
8825 #endif
8826 if (argc != 1)
8827 usage_backout();
8829 cwd = getcwd(NULL, 0);
8830 if (cwd == NULL) {
8831 error = got_error_from_errno("getcwd");
8832 goto done;
8834 error = got_worktree_open(&worktree, cwd);
8835 if (error) {
8836 if (error->code == GOT_ERR_NOT_WORKTREE)
8837 error = wrap_not_worktree_error(error, "backout", cwd);
8838 goto done;
8841 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8842 NULL);
8843 if (error != NULL)
8844 goto done;
8846 error = apply_unveil(got_repo_get_path(repo), 0,
8847 got_worktree_get_root_path(worktree));
8848 if (error)
8849 goto done;
8851 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8852 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8853 if (error)
8854 goto done;
8855 error = got_object_id_str(&commit_id_str, commit_id);
8856 if (error)
8857 goto done;
8859 error = got_object_open_as_commit(&commit, repo, commit_id);
8860 if (error)
8861 goto done;
8862 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8863 if (pid == NULL) {
8864 error = got_error(GOT_ERR_ROOT_COMMIT);
8865 goto done;
8868 memset(&upa, 0, sizeof(upa));
8869 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8870 repo, update_progress, &upa, check_cancelled, NULL);
8871 if (error != NULL)
8872 goto done;
8874 if (upa.did_something)
8875 printf("Backed out commit %s\n", commit_id_str);
8876 print_merge_progress_stats(&upa);
8877 done:
8878 if (commit)
8879 got_object_commit_close(commit);
8880 free(commit_id_str);
8881 if (worktree)
8882 got_worktree_close(worktree);
8883 if (repo) {
8884 const struct got_error *close_err = got_repo_close(repo);
8885 if (error == NULL)
8886 error = close_err;
8888 return error;
8891 __dead static void
8892 usage_rebase(void)
8894 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8895 getprogname());
8896 exit(1);
8899 void
8900 trim_logmsg(char *logmsg, int limit)
8902 char *nl;
8903 size_t len;
8905 len = strlen(logmsg);
8906 if (len > limit)
8907 len = limit;
8908 logmsg[len] = '\0';
8909 nl = strchr(logmsg, '\n');
8910 if (nl)
8911 *nl = '\0';
8914 static const struct got_error *
8915 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8917 const struct got_error *err;
8918 char *logmsg0 = NULL;
8919 const char *s;
8921 err = got_object_commit_get_logmsg(&logmsg0, commit);
8922 if (err)
8923 return err;
8925 s = logmsg0;
8926 while (isspace((unsigned char)s[0]))
8927 s++;
8929 *logmsg = strdup(s);
8930 if (*logmsg == NULL) {
8931 err = got_error_from_errno("strdup");
8932 goto done;
8935 trim_logmsg(*logmsg, limit);
8936 done:
8937 free(logmsg0);
8938 return err;
8941 static const struct got_error *
8942 show_rebase_merge_conflict(struct got_object_id *id,
8943 struct got_repository *repo)
8945 const struct got_error *err;
8946 struct got_commit_object *commit = NULL;
8947 char *id_str = NULL, *logmsg = NULL;
8949 err = got_object_open_as_commit(&commit, repo, id);
8950 if (err)
8951 return err;
8953 err = got_object_id_str(&id_str, id);
8954 if (err)
8955 goto done;
8957 id_str[12] = '\0';
8959 err = get_short_logmsg(&logmsg, 42, commit);
8960 if (err)
8961 goto done;
8963 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8964 done:
8965 free(id_str);
8966 got_object_commit_close(commit);
8967 free(logmsg);
8968 return err;
8971 static const struct got_error *
8972 show_rebase_progress(struct got_commit_object *commit,
8973 struct got_object_id *old_id, struct got_object_id *new_id)
8975 const struct got_error *err;
8976 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8978 err = got_object_id_str(&old_id_str, old_id);
8979 if (err)
8980 goto done;
8982 if (new_id) {
8983 err = got_object_id_str(&new_id_str, new_id);
8984 if (err)
8985 goto done;
8988 old_id_str[12] = '\0';
8989 if (new_id_str)
8990 new_id_str[12] = '\0';
8992 err = get_short_logmsg(&logmsg, 42, commit);
8993 if (err)
8994 goto done;
8996 printf("%s -> %s: %s\n", old_id_str,
8997 new_id_str ? new_id_str : "no-op change", logmsg);
8998 done:
8999 free(old_id_str);
9000 free(new_id_str);
9001 free(logmsg);
9002 return err;
9005 static const struct got_error *
9006 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9007 struct got_reference *branch, struct got_reference *new_base_branch,
9008 struct got_reference *tmp_branch, struct got_repository *repo,
9009 int create_backup)
9011 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9012 return got_worktree_rebase_complete(worktree, fileindex,
9013 new_base_branch, tmp_branch, branch, repo, create_backup);
9016 static const struct got_error *
9017 rebase_commit(struct got_pathlist_head *merged_paths,
9018 struct got_worktree *worktree, struct got_fileindex *fileindex,
9019 struct got_reference *tmp_branch,
9020 struct got_object_id *commit_id, struct got_repository *repo)
9022 const struct got_error *error;
9023 struct got_commit_object *commit;
9024 struct got_object_id *new_commit_id;
9026 error = got_object_open_as_commit(&commit, repo, commit_id);
9027 if (error)
9028 return error;
9030 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9031 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9032 if (error) {
9033 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9034 goto done;
9035 error = show_rebase_progress(commit, commit_id, NULL);
9036 } else {
9037 error = show_rebase_progress(commit, commit_id, new_commit_id);
9038 free(new_commit_id);
9040 done:
9041 got_object_commit_close(commit);
9042 return error;
9045 struct check_path_prefix_arg {
9046 const char *path_prefix;
9047 size_t len;
9048 int errcode;
9051 static const struct got_error *
9052 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9053 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9054 struct got_object_id *id1, struct got_object_id *id2,
9055 const char *path1, const char *path2,
9056 mode_t mode1, mode_t mode2, struct got_repository *repo)
9058 struct check_path_prefix_arg *a = arg;
9060 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9061 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9062 return got_error(a->errcode);
9064 return NULL;
9067 static const struct got_error *
9068 check_path_prefix(struct got_object_id *parent_id,
9069 struct got_object_id *commit_id, const char *path_prefix,
9070 int errcode, struct got_repository *repo)
9072 const struct got_error *err;
9073 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9074 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9075 struct check_path_prefix_arg cpp_arg;
9077 if (got_path_is_root_dir(path_prefix))
9078 return NULL;
9080 err = got_object_open_as_commit(&commit, repo, commit_id);
9081 if (err)
9082 goto done;
9084 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9085 if (err)
9086 goto done;
9088 err = got_object_open_as_tree(&tree1, repo,
9089 got_object_commit_get_tree_id(parent_commit));
9090 if (err)
9091 goto done;
9093 err = got_object_open_as_tree(&tree2, repo,
9094 got_object_commit_get_tree_id(commit));
9095 if (err)
9096 goto done;
9098 cpp_arg.path_prefix = path_prefix;
9099 while (cpp_arg.path_prefix[0] == '/')
9100 cpp_arg.path_prefix++;
9101 cpp_arg.len = strlen(cpp_arg.path_prefix);
9102 cpp_arg.errcode = errcode;
9103 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9104 check_path_prefix_in_diff, &cpp_arg, 0);
9105 done:
9106 if (tree1)
9107 got_object_tree_close(tree1);
9108 if (tree2)
9109 got_object_tree_close(tree2);
9110 if (commit)
9111 got_object_commit_close(commit);
9112 if (parent_commit)
9113 got_object_commit_close(parent_commit);
9114 return err;
9117 static const struct got_error *
9118 collect_commits(struct got_object_id_queue *commits,
9119 struct got_object_id *initial_commit_id,
9120 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9121 const char *path_prefix, int path_prefix_errcode,
9122 struct got_repository *repo)
9124 const struct got_error *err = NULL;
9125 struct got_commit_graph *graph = NULL;
9126 struct got_object_id *parent_id = NULL;
9127 struct got_object_qid *qid;
9128 struct got_object_id *commit_id = initial_commit_id;
9130 err = got_commit_graph_open(&graph, "/", 1);
9131 if (err)
9132 return err;
9134 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9135 check_cancelled, NULL);
9136 if (err)
9137 goto done;
9138 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9139 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9140 check_cancelled, NULL);
9141 if (err) {
9142 if (err->code == GOT_ERR_ITER_COMPLETED) {
9143 err = got_error_msg(GOT_ERR_ANCESTRY,
9144 "ran out of commits to rebase before "
9145 "youngest common ancestor commit has "
9146 "been reached?!?");
9148 goto done;
9149 } else {
9150 err = check_path_prefix(parent_id, commit_id,
9151 path_prefix, path_prefix_errcode, repo);
9152 if (err)
9153 goto done;
9155 err = got_object_qid_alloc(&qid, commit_id);
9156 if (err)
9157 goto done;
9158 STAILQ_INSERT_HEAD(commits, qid, entry);
9159 commit_id = parent_id;
9162 done:
9163 got_commit_graph_close(graph);
9164 return err;
9167 static const struct got_error *
9168 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9170 const struct got_error *err = NULL;
9171 time_t committer_time;
9172 struct tm tm;
9173 char datebuf[11]; /* YYYY-MM-DD + NUL */
9174 char *author0 = NULL, *author, *smallerthan;
9175 char *logmsg0 = NULL, *logmsg, *newline;
9177 committer_time = got_object_commit_get_committer_time(commit);
9178 if (gmtime_r(&committer_time, &tm) == NULL)
9179 return got_error_from_errno("gmtime_r");
9180 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9181 return got_error(GOT_ERR_NO_SPACE);
9183 author0 = strdup(got_object_commit_get_author(commit));
9184 if (author0 == NULL)
9185 return got_error_from_errno("strdup");
9186 author = author0;
9187 smallerthan = strchr(author, '<');
9188 if (smallerthan && smallerthan[1] != '\0')
9189 author = smallerthan + 1;
9190 author[strcspn(author, "@>")] = '\0';
9192 err = got_object_commit_get_logmsg(&logmsg0, commit);
9193 if (err)
9194 goto done;
9195 logmsg = logmsg0;
9196 while (*logmsg == '\n')
9197 logmsg++;
9198 newline = strchr(logmsg, '\n');
9199 if (newline)
9200 *newline = '\0';
9202 if (asprintf(brief_str, "%s %s %s",
9203 datebuf, author, logmsg) == -1)
9204 err = got_error_from_errno("asprintf");
9205 done:
9206 free(author0);
9207 free(logmsg0);
9208 return err;
9211 static const struct got_error *
9212 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9213 struct got_repository *repo)
9215 const struct got_error *err;
9216 char *id_str;
9218 err = got_object_id_str(&id_str, id);
9219 if (err)
9220 return err;
9222 err = got_ref_delete(ref, repo);
9223 if (err)
9224 goto done;
9226 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9227 done:
9228 free(id_str);
9229 return err;
9232 static const struct got_error *
9233 print_backup_ref(const char *branch_name, const char *new_id_str,
9234 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9235 struct got_reflist_object_id_map *refs_idmap,
9236 struct got_repository *repo)
9238 const struct got_error *err = NULL;
9239 struct got_reflist_head *refs;
9240 char *refs_str = NULL;
9241 struct got_object_id *new_commit_id = NULL;
9242 struct got_commit_object *new_commit = NULL;
9243 char *new_commit_brief_str = NULL;
9244 struct got_object_id *yca_id = NULL;
9245 struct got_commit_object *yca_commit = NULL;
9246 char *yca_id_str = NULL, *yca_brief_str = NULL;
9247 char *custom_refs_str;
9249 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9250 return got_error_from_errno("asprintf");
9252 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9253 0, 0, refs_idmap, custom_refs_str);
9254 if (err)
9255 goto done;
9257 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9258 if (err)
9259 goto done;
9261 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9262 if (refs) {
9263 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9264 if (err)
9265 goto done;
9268 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9269 if (err)
9270 goto done;
9272 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9273 if (err)
9274 goto done;
9276 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9277 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9278 if (err)
9279 goto done;
9281 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9282 refs_str ? " (" : "", refs_str ? refs_str : "",
9283 refs_str ? ")" : "", new_commit_brief_str);
9284 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9285 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9286 free(refs_str);
9287 refs_str = NULL;
9289 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9290 if (err)
9291 goto done;
9293 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9294 if (err)
9295 goto done;
9297 err = got_object_id_str(&yca_id_str, yca_id);
9298 if (err)
9299 goto done;
9301 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9302 if (refs) {
9303 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9304 if (err)
9305 goto done;
9307 printf("history forked at %s%s%s%s\n %s\n",
9308 yca_id_str,
9309 refs_str ? " (" : "", refs_str ? refs_str : "",
9310 refs_str ? ")" : "", yca_brief_str);
9312 done:
9313 free(custom_refs_str);
9314 free(new_commit_id);
9315 free(refs_str);
9316 free(yca_id);
9317 free(yca_id_str);
9318 free(yca_brief_str);
9319 if (new_commit)
9320 got_object_commit_close(new_commit);
9321 if (yca_commit)
9322 got_object_commit_close(yca_commit);
9324 return NULL;
9327 static const struct got_error *
9328 process_backup_refs(const char *backup_ref_prefix,
9329 const char *wanted_branch_name,
9330 int delete, struct got_repository *repo)
9332 const struct got_error *err;
9333 struct got_reflist_head refs, backup_refs;
9334 struct got_reflist_entry *re;
9335 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9336 struct got_object_id *old_commit_id = NULL;
9337 char *branch_name = NULL;
9338 struct got_commit_object *old_commit = NULL;
9339 struct got_reflist_object_id_map *refs_idmap = NULL;
9340 int wanted_branch_found = 0;
9342 TAILQ_INIT(&refs);
9343 TAILQ_INIT(&backup_refs);
9345 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9346 if (err)
9347 return err;
9349 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9350 if (err)
9351 goto done;
9353 if (wanted_branch_name) {
9354 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9355 wanted_branch_name += 11;
9358 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9359 got_ref_cmp_by_commit_timestamp_descending, repo);
9360 if (err)
9361 goto done;
9363 TAILQ_FOREACH(re, &backup_refs, entry) {
9364 const char *refname = got_ref_get_name(re->ref);
9365 char *slash;
9367 err = check_cancelled(NULL);
9368 if (err)
9369 break;
9371 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9372 if (err)
9373 break;
9375 err = got_object_open_as_commit(&old_commit, repo,
9376 old_commit_id);
9377 if (err)
9378 break;
9380 if (strncmp(backup_ref_prefix, refname,
9381 backup_ref_prefix_len) == 0)
9382 refname += backup_ref_prefix_len;
9384 while (refname[0] == '/')
9385 refname++;
9387 branch_name = strdup(refname);
9388 if (branch_name == NULL) {
9389 err = got_error_from_errno("strdup");
9390 break;
9392 slash = strrchr(branch_name, '/');
9393 if (slash) {
9394 *slash = '\0';
9395 refname += strlen(branch_name) + 1;
9398 if (wanted_branch_name == NULL ||
9399 strcmp(wanted_branch_name, branch_name) == 0) {
9400 wanted_branch_found = 1;
9401 if (delete) {
9402 err = delete_backup_ref(re->ref,
9403 old_commit_id, repo);
9404 } else {
9405 err = print_backup_ref(branch_name, refname,
9406 old_commit_id, old_commit, refs_idmap,
9407 repo);
9409 if (err)
9410 break;
9413 free(old_commit_id);
9414 old_commit_id = NULL;
9415 free(branch_name);
9416 branch_name = NULL;
9417 got_object_commit_close(old_commit);
9418 old_commit = NULL;
9421 if (wanted_branch_name && !wanted_branch_found) {
9422 err = got_error_fmt(GOT_ERR_NOT_REF,
9423 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9425 done:
9426 if (refs_idmap)
9427 got_reflist_object_id_map_free(refs_idmap);
9428 got_ref_list_free(&refs);
9429 got_ref_list_free(&backup_refs);
9430 free(old_commit_id);
9431 free(branch_name);
9432 if (old_commit)
9433 got_object_commit_close(old_commit);
9434 return err;
9437 static const struct got_error *
9438 abort_progress(void *arg, unsigned char status, const char *path)
9441 * Unversioned files should not clutter progress output when
9442 * an operation is aborted.
9444 if (status == GOT_STATUS_UNVERSIONED)
9445 return NULL;
9447 return update_progress(arg, status, path);
9450 static const struct got_error *
9451 cmd_rebase(int argc, char *argv[])
9453 const struct got_error *error = NULL;
9454 struct got_worktree *worktree = NULL;
9455 struct got_repository *repo = NULL;
9456 struct got_fileindex *fileindex = NULL;
9457 char *cwd = NULL;
9458 struct got_reference *branch = NULL;
9459 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9460 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9461 struct got_object_id *resume_commit_id = NULL;
9462 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9463 struct got_commit_object *commit = NULL;
9464 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9465 int histedit_in_progress = 0, merge_in_progress = 0;
9466 int create_backup = 1, list_backups = 0, delete_backups = 0;
9467 struct got_object_id_queue commits;
9468 struct got_pathlist_head merged_paths;
9469 const struct got_object_id_queue *parent_ids;
9470 struct got_object_qid *qid, *pid;
9471 struct got_update_progress_arg upa;
9473 STAILQ_INIT(&commits);
9474 TAILQ_INIT(&merged_paths);
9475 memset(&upa, 0, sizeof(upa));
9477 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9478 switch (ch) {
9479 case 'a':
9480 abort_rebase = 1;
9481 break;
9482 case 'c':
9483 continue_rebase = 1;
9484 break;
9485 case 'l':
9486 list_backups = 1;
9487 break;
9488 case 'X':
9489 delete_backups = 1;
9490 break;
9491 default:
9492 usage_rebase();
9493 /* NOTREACHED */
9497 argc -= optind;
9498 argv += optind;
9500 #ifndef PROFILE
9501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9502 "unveil", NULL) == -1)
9503 err(1, "pledge");
9504 #endif
9505 if (list_backups) {
9506 if (abort_rebase)
9507 option_conflict('l', 'a');
9508 if (continue_rebase)
9509 option_conflict('l', 'c');
9510 if (delete_backups)
9511 option_conflict('l', 'X');
9512 if (argc != 0 && argc != 1)
9513 usage_rebase();
9514 } else if (delete_backups) {
9515 if (abort_rebase)
9516 option_conflict('X', 'a');
9517 if (continue_rebase)
9518 option_conflict('X', 'c');
9519 if (list_backups)
9520 option_conflict('l', 'X');
9521 if (argc != 0 && argc != 1)
9522 usage_rebase();
9523 } else {
9524 if (abort_rebase && continue_rebase)
9525 usage_rebase();
9526 else if (abort_rebase || continue_rebase) {
9527 if (argc != 0)
9528 usage_rebase();
9529 } else if (argc != 1)
9530 usage_rebase();
9533 cwd = getcwd(NULL, 0);
9534 if (cwd == NULL) {
9535 error = got_error_from_errno("getcwd");
9536 goto done;
9538 error = got_worktree_open(&worktree, cwd);
9539 if (error) {
9540 if (list_backups || delete_backups) {
9541 if (error->code != GOT_ERR_NOT_WORKTREE)
9542 goto done;
9543 } else {
9544 if (error->code == GOT_ERR_NOT_WORKTREE)
9545 error = wrap_not_worktree_error(error,
9546 "rebase", cwd);
9547 goto done;
9551 error = got_repo_open(&repo,
9552 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9553 if (error != NULL)
9554 goto done;
9556 error = apply_unveil(got_repo_get_path(repo), 0,
9557 worktree ? got_worktree_get_root_path(worktree) : NULL);
9558 if (error)
9559 goto done;
9561 if (list_backups || delete_backups) {
9562 error = process_backup_refs(
9563 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9564 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9565 goto done; /* nothing else to do */
9568 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9569 worktree);
9570 if (error)
9571 goto done;
9572 if (histedit_in_progress) {
9573 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9574 goto done;
9577 error = got_worktree_merge_in_progress(&merge_in_progress,
9578 worktree, repo);
9579 if (error)
9580 goto done;
9581 if (merge_in_progress) {
9582 error = got_error(GOT_ERR_MERGE_BUSY);
9583 goto done;
9586 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9587 if (error)
9588 goto done;
9590 if (abort_rebase) {
9591 if (!rebase_in_progress) {
9592 error = got_error(GOT_ERR_NOT_REBASING);
9593 goto done;
9595 error = got_worktree_rebase_continue(&resume_commit_id,
9596 &new_base_branch, &tmp_branch, &branch, &fileindex,
9597 worktree, repo);
9598 if (error)
9599 goto done;
9600 printf("Switching work tree to %s\n",
9601 got_ref_get_symref_target(new_base_branch));
9602 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9603 new_base_branch, abort_progress, &upa);
9604 if (error)
9605 goto done;
9606 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9607 print_merge_progress_stats(&upa);
9608 goto done; /* nothing else to do */
9611 if (continue_rebase) {
9612 if (!rebase_in_progress) {
9613 error = got_error(GOT_ERR_NOT_REBASING);
9614 goto done;
9616 error = got_worktree_rebase_continue(&resume_commit_id,
9617 &new_base_branch, &tmp_branch, &branch, &fileindex,
9618 worktree, repo);
9619 if (error)
9620 goto done;
9622 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9623 resume_commit_id, repo);
9624 if (error)
9625 goto done;
9627 yca_id = got_object_id_dup(resume_commit_id);
9628 if (yca_id == NULL) {
9629 error = got_error_from_errno("got_object_id_dup");
9630 goto done;
9632 } else {
9633 error = got_ref_open(&branch, repo, argv[0], 0);
9634 if (error != NULL)
9635 goto done;
9638 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9639 if (error)
9640 goto done;
9642 if (!continue_rebase) {
9643 struct got_object_id *base_commit_id;
9645 base_commit_id = got_worktree_get_base_commit_id(worktree);
9646 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9647 base_commit_id, branch_head_commit_id, 1, repo,
9648 check_cancelled, NULL);
9649 if (error)
9650 goto done;
9651 if (yca_id == NULL) {
9652 error = got_error_msg(GOT_ERR_ANCESTRY,
9653 "specified branch shares no common ancestry "
9654 "with work tree's branch");
9655 goto done;
9658 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9659 if (error) {
9660 if (error->code != GOT_ERR_ANCESTRY)
9661 goto done;
9662 error = NULL;
9663 } else {
9664 struct got_pathlist_head paths;
9665 printf("%s is already based on %s\n",
9666 got_ref_get_name(branch),
9667 got_worktree_get_head_ref_name(worktree));
9668 error = switch_head_ref(branch, branch_head_commit_id,
9669 worktree, repo);
9670 if (error)
9671 goto done;
9672 error = got_worktree_set_base_commit_id(worktree, repo,
9673 branch_head_commit_id);
9674 if (error)
9675 goto done;
9676 TAILQ_INIT(&paths);
9677 error = got_pathlist_append(&paths, "", NULL);
9678 if (error)
9679 goto done;
9680 error = got_worktree_checkout_files(worktree,
9681 &paths, repo, update_progress, &upa,
9682 check_cancelled, NULL);
9683 got_pathlist_free(&paths);
9684 if (error)
9685 goto done;
9686 if (upa.did_something) {
9687 char *id_str;
9688 error = got_object_id_str(&id_str,
9689 branch_head_commit_id);
9690 if (error)
9691 goto done;
9692 printf("Updated to %s: %s\n",
9693 got_worktree_get_head_ref_name(worktree),
9694 id_str);
9695 free(id_str);
9696 } else
9697 printf("Already up-to-date\n");
9698 print_update_progress_stats(&upa);
9699 goto done;
9703 commit_id = branch_head_commit_id;
9704 error = got_object_open_as_commit(&commit, repo, commit_id);
9705 if (error)
9706 goto done;
9708 parent_ids = got_object_commit_get_parent_ids(commit);
9709 pid = STAILQ_FIRST(parent_ids);
9710 if (pid == NULL) {
9711 error = got_error(GOT_ERR_EMPTY_REBASE);
9712 goto done;
9714 error = collect_commits(&commits, commit_id, &pid->id,
9715 yca_id, got_worktree_get_path_prefix(worktree),
9716 GOT_ERR_REBASE_PATH, repo);
9717 got_object_commit_close(commit);
9718 commit = NULL;
9719 if (error)
9720 goto done;
9722 if (!continue_rebase) {
9723 error = got_worktree_rebase_prepare(&new_base_branch,
9724 &tmp_branch, &fileindex, worktree, branch, repo);
9725 if (error)
9726 goto done;
9729 if (STAILQ_EMPTY(&commits)) {
9730 if (continue_rebase) {
9731 error = rebase_complete(worktree, fileindex,
9732 branch, new_base_branch, tmp_branch, repo,
9733 create_backup);
9734 goto done;
9735 } else {
9736 /* Fast-forward the reference of the branch. */
9737 struct got_object_id *new_head_commit_id;
9738 char *id_str;
9739 error = got_ref_resolve(&new_head_commit_id, repo,
9740 new_base_branch);
9741 if (error)
9742 goto done;
9743 error = got_object_id_str(&id_str, new_head_commit_id);
9744 printf("Forwarding %s to commit %s\n",
9745 got_ref_get_name(branch), id_str);
9746 free(id_str);
9747 error = got_ref_change_ref(branch,
9748 new_head_commit_id);
9749 if (error)
9750 goto done;
9751 /* No backup needed since objects did not change. */
9752 create_backup = 0;
9756 pid = NULL;
9757 STAILQ_FOREACH(qid, &commits, entry) {
9759 commit_id = &qid->id;
9760 parent_id = pid ? &pid->id : yca_id;
9761 pid = qid;
9763 memset(&upa, 0, sizeof(upa));
9764 error = got_worktree_rebase_merge_files(&merged_paths,
9765 worktree, fileindex, parent_id, commit_id, repo,
9766 update_progress, &upa, check_cancelled, NULL);
9767 if (error)
9768 goto done;
9770 print_merge_progress_stats(&upa);
9771 if (upa.conflicts > 0 || upa.missing > 0 ||
9772 upa.not_deleted > 0 || upa.unversioned > 0) {
9773 if (upa.conflicts > 0) {
9774 error = show_rebase_merge_conflict(&qid->id,
9775 repo);
9776 if (error)
9777 goto done;
9779 got_worktree_rebase_pathlist_free(&merged_paths);
9780 break;
9783 error = rebase_commit(&merged_paths, worktree, fileindex,
9784 tmp_branch, commit_id, repo);
9785 got_worktree_rebase_pathlist_free(&merged_paths);
9786 if (error)
9787 goto done;
9790 if (upa.conflicts > 0 || upa.missing > 0 ||
9791 upa.not_deleted > 0 || upa.unversioned > 0) {
9792 error = got_worktree_rebase_postpone(worktree, fileindex);
9793 if (error)
9794 goto done;
9795 if (upa.conflicts > 0 && upa.missing == 0 &&
9796 upa.not_deleted == 0 && upa.unversioned == 0) {
9797 error = got_error_msg(GOT_ERR_CONFLICTS,
9798 "conflicts must be resolved before rebasing "
9799 "can continue");
9800 } else if (upa.conflicts > 0) {
9801 error = got_error_msg(GOT_ERR_CONFLICTS,
9802 "conflicts must be resolved before rebasing "
9803 "can continue; changes destined for some "
9804 "files were not yet merged and should be "
9805 "merged manually if required before the "
9806 "rebase operation is continued");
9807 } else {
9808 error = got_error_msg(GOT_ERR_CONFLICTS,
9809 "changes destined for some files were not "
9810 "yet merged and should be merged manually "
9811 "if required before the rebase operation "
9812 "is continued");
9814 } else
9815 error = rebase_complete(worktree, fileindex, branch,
9816 new_base_branch, tmp_branch, repo, create_backup);
9817 done:
9818 got_object_id_queue_free(&commits);
9819 free(branch_head_commit_id);
9820 free(resume_commit_id);
9821 free(yca_id);
9822 if (commit)
9823 got_object_commit_close(commit);
9824 if (branch)
9825 got_ref_close(branch);
9826 if (new_base_branch)
9827 got_ref_close(new_base_branch);
9828 if (tmp_branch)
9829 got_ref_close(tmp_branch);
9830 if (worktree)
9831 got_worktree_close(worktree);
9832 if (repo) {
9833 const struct got_error *close_err = got_repo_close(repo);
9834 if (error == NULL)
9835 error = close_err;
9837 return error;
9840 __dead static void
9841 usage_histedit(void)
9843 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9844 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9845 getprogname());
9846 exit(1);
9849 #define GOT_HISTEDIT_PICK 'p'
9850 #define GOT_HISTEDIT_EDIT 'e'
9851 #define GOT_HISTEDIT_FOLD 'f'
9852 #define GOT_HISTEDIT_DROP 'd'
9853 #define GOT_HISTEDIT_MESG 'm'
9855 static const struct got_histedit_cmd {
9856 unsigned char code;
9857 const char *name;
9858 const char *desc;
9859 } got_histedit_cmds[] = {
9860 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9861 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9862 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9863 "be used" },
9864 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9865 { GOT_HISTEDIT_MESG, "mesg",
9866 "single-line log message for commit above (open editor if empty)" },
9869 struct got_histedit_list_entry {
9870 TAILQ_ENTRY(got_histedit_list_entry) entry;
9871 struct got_object_id *commit_id;
9872 const struct got_histedit_cmd *cmd;
9873 char *logmsg;
9875 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9877 static const struct got_error *
9878 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9879 FILE *f, struct got_repository *repo)
9881 const struct got_error *err = NULL;
9882 char *logmsg = NULL, *id_str = NULL;
9883 struct got_commit_object *commit = NULL;
9884 int n;
9886 err = got_object_open_as_commit(&commit, repo, commit_id);
9887 if (err)
9888 goto done;
9890 err = get_short_logmsg(&logmsg, 34, commit);
9891 if (err)
9892 goto done;
9894 err = got_object_id_str(&id_str, commit_id);
9895 if (err)
9896 goto done;
9898 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9899 if (n < 0)
9900 err = got_ferror(f, GOT_ERR_IO);
9901 done:
9902 if (commit)
9903 got_object_commit_close(commit);
9904 free(id_str);
9905 free(logmsg);
9906 return err;
9909 static const struct got_error *
9910 histedit_write_commit_list(struct got_object_id_queue *commits,
9911 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9912 struct got_repository *repo)
9914 const struct got_error *err = NULL;
9915 struct got_object_qid *qid;
9916 const char *histedit_cmd = NULL;
9918 if (STAILQ_EMPTY(commits))
9919 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9921 STAILQ_FOREACH(qid, commits, entry) {
9922 histedit_cmd = got_histedit_cmds[0].name;
9923 if (edit_only)
9924 histedit_cmd = "edit";
9925 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9926 histedit_cmd = "fold";
9927 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9928 if (err)
9929 break;
9930 if (edit_logmsg_only) {
9931 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9932 if (n < 0) {
9933 err = got_ferror(f, GOT_ERR_IO);
9934 break;
9939 return err;
9942 static const struct got_error *
9943 write_cmd_list(FILE *f, const char *branch_name,
9944 struct got_object_id_queue *commits)
9946 const struct got_error *err = NULL;
9947 size_t i;
9948 int n;
9949 char *id_str;
9950 struct got_object_qid *qid;
9952 qid = STAILQ_FIRST(commits);
9953 err = got_object_id_str(&id_str, &qid->id);
9954 if (err)
9955 return err;
9957 n = fprintf(f,
9958 "# Editing the history of branch '%s' starting at\n"
9959 "# commit %s\n"
9960 "# Commits will be processed in order from top to "
9961 "bottom of this file.\n", branch_name, id_str);
9962 if (n < 0) {
9963 err = got_ferror(f, GOT_ERR_IO);
9964 goto done;
9967 n = fprintf(f, "# Available histedit commands:\n");
9968 if (n < 0) {
9969 err = got_ferror(f, GOT_ERR_IO);
9970 goto done;
9973 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9974 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9975 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9976 cmd->desc);
9977 if (n < 0) {
9978 err = got_ferror(f, GOT_ERR_IO);
9979 break;
9982 done:
9983 free(id_str);
9984 return err;
9987 static const struct got_error *
9988 histedit_syntax_error(int lineno)
9990 static char msg[42];
9991 int ret;
9993 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9994 lineno);
9995 if (ret == -1 || ret >= sizeof(msg))
9996 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9998 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10001 static const struct got_error *
10002 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10003 char *logmsg, struct got_repository *repo)
10005 const struct got_error *err;
10006 struct got_commit_object *folded_commit = NULL;
10007 char *id_str, *folded_logmsg = NULL;
10009 err = got_object_id_str(&id_str, hle->commit_id);
10010 if (err)
10011 return err;
10013 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10014 if (err)
10015 goto done;
10017 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10018 if (err)
10019 goto done;
10020 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10021 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10022 folded_logmsg) == -1) {
10023 err = got_error_from_errno("asprintf");
10025 done:
10026 if (folded_commit)
10027 got_object_commit_close(folded_commit);
10028 free(id_str);
10029 free(folded_logmsg);
10030 return err;
10033 static struct got_histedit_list_entry *
10034 get_folded_commits(struct got_histedit_list_entry *hle)
10036 struct got_histedit_list_entry *prev, *folded = NULL;
10038 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10039 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10040 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10041 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10042 folded = prev;
10043 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10046 return folded;
10049 static const struct got_error *
10050 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10051 struct got_repository *repo)
10053 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10054 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10055 const struct got_error *err = NULL;
10056 struct got_commit_object *commit = NULL;
10057 int logmsg_len;
10058 int fd;
10059 struct got_histedit_list_entry *folded = NULL;
10061 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10062 if (err)
10063 return err;
10065 folded = get_folded_commits(hle);
10066 if (folded) {
10067 while (folded != hle) {
10068 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10069 folded = TAILQ_NEXT(folded, entry);
10070 continue;
10072 err = append_folded_commit_msg(&new_msg, folded,
10073 logmsg, repo);
10074 if (err)
10075 goto done;
10076 free(logmsg);
10077 logmsg = new_msg;
10078 folded = TAILQ_NEXT(folded, entry);
10082 err = got_object_id_str(&id_str, hle->commit_id);
10083 if (err)
10084 goto done;
10085 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10086 if (err)
10087 goto done;
10088 logmsg_len = asprintf(&new_msg,
10089 "%s\n# original log message of commit %s: %s",
10090 logmsg ? logmsg : "", id_str, orig_logmsg);
10091 if (logmsg_len == -1) {
10092 err = got_error_from_errno("asprintf");
10093 goto done;
10095 free(logmsg);
10096 logmsg = new_msg;
10098 err = got_object_id_str(&id_str, hle->commit_id);
10099 if (err)
10100 goto done;
10102 err = got_opentemp_named_fd(&logmsg_path, &fd,
10103 GOT_TMPDIR_STR "/got-logmsg");
10104 if (err)
10105 goto done;
10107 write(fd, logmsg, logmsg_len);
10108 close(fd);
10110 err = get_editor(&editor);
10111 if (err)
10112 goto done;
10114 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10115 logmsg_len, 0);
10116 if (err) {
10117 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10118 goto done;
10119 err = NULL;
10120 hle->logmsg = strdup(new_msg);
10121 if (hle->logmsg == NULL)
10122 err = got_error_from_errno("strdup");
10124 done:
10125 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10126 err = got_error_from_errno2("unlink", logmsg_path);
10127 free(logmsg_path);
10128 free(logmsg);
10129 free(orig_logmsg);
10130 free(editor);
10131 if (commit)
10132 got_object_commit_close(commit);
10133 return err;
10136 static const struct got_error *
10137 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10138 FILE *f, struct got_repository *repo)
10140 const struct got_error *err = NULL;
10141 char *line = NULL, *p, *end;
10142 size_t i, size;
10143 ssize_t len;
10144 int lineno = 0;
10145 const struct got_histedit_cmd *cmd;
10146 struct got_object_id *commit_id = NULL;
10147 struct got_histedit_list_entry *hle = NULL;
10149 for (;;) {
10150 len = getline(&line, &size, f);
10151 if (len == -1) {
10152 const struct got_error *getline_err;
10153 if (feof(f))
10154 break;
10155 getline_err = got_error_from_errno("getline");
10156 err = got_ferror(f, getline_err->code);
10157 break;
10159 lineno++;
10160 p = line;
10161 while (isspace((unsigned char)p[0]))
10162 p++;
10163 if (p[0] == '#' || p[0] == '\0') {
10164 free(line);
10165 line = NULL;
10166 continue;
10168 cmd = NULL;
10169 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10170 cmd = &got_histedit_cmds[i];
10171 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10172 isspace((unsigned char)p[strlen(cmd->name)])) {
10173 p += strlen(cmd->name);
10174 break;
10176 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10177 p++;
10178 break;
10181 if (i == nitems(got_histedit_cmds)) {
10182 err = histedit_syntax_error(lineno);
10183 break;
10185 while (isspace((unsigned char)p[0]))
10186 p++;
10187 if (cmd->code == GOT_HISTEDIT_MESG) {
10188 if (hle == NULL || hle->logmsg != NULL) {
10189 err = got_error(GOT_ERR_HISTEDIT_CMD);
10190 break;
10192 if (p[0] == '\0') {
10193 err = histedit_edit_logmsg(hle, repo);
10194 if (err)
10195 break;
10196 } else {
10197 hle->logmsg = strdup(p);
10198 if (hle->logmsg == NULL) {
10199 err = got_error_from_errno("strdup");
10200 break;
10203 free(line);
10204 line = NULL;
10205 continue;
10206 } else {
10207 end = p;
10208 while (end[0] && !isspace((unsigned char)end[0]))
10209 end++;
10210 *end = '\0';
10212 err = got_object_resolve_id_str(&commit_id, repo, p);
10213 if (err) {
10214 /* override error code */
10215 err = histedit_syntax_error(lineno);
10216 break;
10219 hle = malloc(sizeof(*hle));
10220 if (hle == NULL) {
10221 err = got_error_from_errno("malloc");
10222 break;
10224 hle->cmd = cmd;
10225 hle->commit_id = commit_id;
10226 hle->logmsg = NULL;
10227 commit_id = NULL;
10228 free(line);
10229 line = NULL;
10230 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10233 free(line);
10234 free(commit_id);
10235 return err;
10238 static const struct got_error *
10239 histedit_check_script(struct got_histedit_list *histedit_cmds,
10240 struct got_object_id_queue *commits, struct got_repository *repo)
10242 const struct got_error *err = NULL;
10243 struct got_object_qid *qid;
10244 struct got_histedit_list_entry *hle;
10245 static char msg[92];
10246 char *id_str;
10248 if (TAILQ_EMPTY(histedit_cmds))
10249 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10250 "histedit script contains no commands");
10251 if (STAILQ_EMPTY(commits))
10252 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10254 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10255 struct got_histedit_list_entry *hle2;
10256 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10257 if (hle == hle2)
10258 continue;
10259 if (got_object_id_cmp(hle->commit_id,
10260 hle2->commit_id) != 0)
10261 continue;
10262 err = got_object_id_str(&id_str, hle->commit_id);
10263 if (err)
10264 return err;
10265 snprintf(msg, sizeof(msg), "commit %s is listed "
10266 "more than once in histedit script", id_str);
10267 free(id_str);
10268 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10272 STAILQ_FOREACH(qid, commits, entry) {
10273 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10274 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10275 break;
10277 if (hle == NULL) {
10278 err = got_object_id_str(&id_str, &qid->id);
10279 if (err)
10280 return err;
10281 snprintf(msg, sizeof(msg),
10282 "commit %s missing from histedit script", id_str);
10283 free(id_str);
10284 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10288 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10289 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10290 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10291 "last commit in histedit script cannot be folded");
10293 return NULL;
10296 static const struct got_error *
10297 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10298 const char *path, struct got_object_id_queue *commits,
10299 struct got_repository *repo)
10301 const struct got_error *err = NULL;
10302 char *editor;
10303 FILE *f = NULL;
10305 err = get_editor(&editor);
10306 if (err)
10307 return err;
10309 if (spawn_editor(editor, path) == -1) {
10310 err = got_error_from_errno("failed spawning editor");
10311 goto done;
10314 f = fopen(path, "re");
10315 if (f == NULL) {
10316 err = got_error_from_errno("fopen");
10317 goto done;
10319 err = histedit_parse_list(histedit_cmds, f, repo);
10320 if (err)
10321 goto done;
10323 err = histedit_check_script(histedit_cmds, commits, repo);
10324 done:
10325 if (f && fclose(f) == EOF && err == NULL)
10326 err = got_error_from_errno("fclose");
10327 free(editor);
10328 return err;
10331 static const struct got_error *
10332 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10333 struct got_object_id_queue *, const char *, const char *,
10334 struct got_repository *);
10336 static const struct got_error *
10337 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10338 struct got_object_id_queue *commits, const char *branch_name,
10339 int edit_logmsg_only, int fold_only, int edit_only,
10340 struct got_repository *repo)
10342 const struct got_error *err;
10343 FILE *f = NULL;
10344 char *path = NULL;
10346 err = got_opentemp_named(&path, &f, "got-histedit");
10347 if (err)
10348 return err;
10350 err = write_cmd_list(f, branch_name, commits);
10351 if (err)
10352 goto done;
10354 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10355 fold_only, edit_only, repo);
10356 if (err)
10357 goto done;
10359 if (edit_logmsg_only || fold_only || edit_only) {
10360 rewind(f);
10361 err = histedit_parse_list(histedit_cmds, f, repo);
10362 } else {
10363 if (fclose(f) == EOF) {
10364 err = got_error_from_errno("fclose");
10365 goto done;
10367 f = NULL;
10368 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10369 if (err) {
10370 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10371 err->code != GOT_ERR_HISTEDIT_CMD)
10372 goto done;
10373 err = histedit_edit_list_retry(histedit_cmds, err,
10374 commits, path, branch_name, repo);
10377 done:
10378 if (f && fclose(f) == EOF && err == NULL)
10379 err = got_error_from_errno("fclose");
10380 if (path && unlink(path) != 0 && err == NULL)
10381 err = got_error_from_errno2("unlink", path);
10382 free(path);
10383 return err;
10386 static const struct got_error *
10387 histedit_save_list(struct got_histedit_list *histedit_cmds,
10388 struct got_worktree *worktree, struct got_repository *repo)
10390 const struct got_error *err = NULL;
10391 char *path = NULL;
10392 FILE *f = NULL;
10393 struct got_histedit_list_entry *hle;
10394 struct got_commit_object *commit = NULL;
10396 err = got_worktree_get_histedit_script_path(&path, worktree);
10397 if (err)
10398 return err;
10400 f = fopen(path, "we");
10401 if (f == NULL) {
10402 err = got_error_from_errno2("fopen", path);
10403 goto done;
10405 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10406 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10407 repo);
10408 if (err)
10409 break;
10411 if (hle->logmsg) {
10412 int n = fprintf(f, "%c %s\n",
10413 GOT_HISTEDIT_MESG, hle->logmsg);
10414 if (n < 0) {
10415 err = got_ferror(f, GOT_ERR_IO);
10416 break;
10420 done:
10421 if (f && fclose(f) == EOF && err == NULL)
10422 err = got_error_from_errno("fclose");
10423 free(path);
10424 if (commit)
10425 got_object_commit_close(commit);
10426 return err;
10429 void
10430 histedit_free_list(struct got_histedit_list *histedit_cmds)
10432 struct got_histedit_list_entry *hle;
10434 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10435 TAILQ_REMOVE(histedit_cmds, hle, entry);
10436 free(hle);
10440 static const struct got_error *
10441 histedit_load_list(struct got_histedit_list *histedit_cmds,
10442 const char *path, struct got_repository *repo)
10444 const struct got_error *err = NULL;
10445 FILE *f = NULL;
10447 f = fopen(path, "re");
10448 if (f == NULL) {
10449 err = got_error_from_errno2("fopen", path);
10450 goto done;
10453 err = histedit_parse_list(histedit_cmds, f, repo);
10454 done:
10455 if (f && fclose(f) == EOF && err == NULL)
10456 err = got_error_from_errno("fclose");
10457 return err;
10460 static const struct got_error *
10461 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10462 const struct got_error *edit_err, struct got_object_id_queue *commits,
10463 const char *path, const char *branch_name, struct got_repository *repo)
10465 const struct got_error *err = NULL, *prev_err = edit_err;
10466 int resp = ' ';
10468 while (resp != 'c' && resp != 'r' && resp != 'a') {
10469 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10470 "or (a)bort: ", getprogname(), prev_err->msg);
10471 resp = getchar();
10472 if (resp == '\n')
10473 resp = getchar();
10474 if (resp == 'c') {
10475 histedit_free_list(histedit_cmds);
10476 err = histedit_run_editor(histedit_cmds, path, commits,
10477 repo);
10478 if (err) {
10479 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10480 err->code != GOT_ERR_HISTEDIT_CMD)
10481 break;
10482 prev_err = err;
10483 resp = ' ';
10484 continue;
10486 break;
10487 } else if (resp == 'r') {
10488 histedit_free_list(histedit_cmds);
10489 err = histedit_edit_script(histedit_cmds,
10490 commits, branch_name, 0, 0, 0, repo);
10491 if (err) {
10492 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10493 err->code != GOT_ERR_HISTEDIT_CMD)
10494 break;
10495 prev_err = err;
10496 resp = ' ';
10497 continue;
10499 break;
10500 } else if (resp == 'a') {
10501 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10502 break;
10503 } else
10504 printf("invalid response '%c'\n", resp);
10507 return err;
10510 static const struct got_error *
10511 histedit_complete(struct got_worktree *worktree,
10512 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10513 struct got_reference *branch, struct got_repository *repo)
10515 printf("Switching work tree to %s\n",
10516 got_ref_get_symref_target(branch));
10517 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10518 branch, repo);
10521 static const struct got_error *
10522 show_histedit_progress(struct got_commit_object *commit,
10523 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10525 const struct got_error *err;
10526 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10528 err = got_object_id_str(&old_id_str, hle->commit_id);
10529 if (err)
10530 goto done;
10532 if (new_id) {
10533 err = got_object_id_str(&new_id_str, new_id);
10534 if (err)
10535 goto done;
10538 old_id_str[12] = '\0';
10539 if (new_id_str)
10540 new_id_str[12] = '\0';
10542 if (hle->logmsg) {
10543 logmsg = strdup(hle->logmsg);
10544 if (logmsg == NULL) {
10545 err = got_error_from_errno("strdup");
10546 goto done;
10548 trim_logmsg(logmsg, 42);
10549 } else {
10550 err = get_short_logmsg(&logmsg, 42, commit);
10551 if (err)
10552 goto done;
10555 switch (hle->cmd->code) {
10556 case GOT_HISTEDIT_PICK:
10557 case GOT_HISTEDIT_EDIT:
10558 printf("%s -> %s: %s\n", old_id_str,
10559 new_id_str ? new_id_str : "no-op change", logmsg);
10560 break;
10561 case GOT_HISTEDIT_DROP:
10562 case GOT_HISTEDIT_FOLD:
10563 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10564 logmsg);
10565 break;
10566 default:
10567 break;
10569 done:
10570 free(old_id_str);
10571 free(new_id_str);
10572 return err;
10575 static const struct got_error *
10576 histedit_commit(struct got_pathlist_head *merged_paths,
10577 struct got_worktree *worktree, struct got_fileindex *fileindex,
10578 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10579 struct got_repository *repo)
10581 const struct got_error *err;
10582 struct got_commit_object *commit;
10583 struct got_object_id *new_commit_id;
10585 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10586 && hle->logmsg == NULL) {
10587 err = histedit_edit_logmsg(hle, repo);
10588 if (err)
10589 return err;
10592 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10593 if (err)
10594 return err;
10596 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10597 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10598 hle->logmsg, repo);
10599 if (err) {
10600 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10601 goto done;
10602 err = show_histedit_progress(commit, hle, NULL);
10603 } else {
10604 err = show_histedit_progress(commit, hle, new_commit_id);
10605 free(new_commit_id);
10607 done:
10608 got_object_commit_close(commit);
10609 return err;
10612 static const struct got_error *
10613 histedit_skip_commit(struct got_histedit_list_entry *hle,
10614 struct got_worktree *worktree, struct got_repository *repo)
10616 const struct got_error *error;
10617 struct got_commit_object *commit;
10619 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10620 repo);
10621 if (error)
10622 return error;
10624 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10625 if (error)
10626 return error;
10628 error = show_histedit_progress(commit, hle, NULL);
10629 got_object_commit_close(commit);
10630 return error;
10633 static const struct got_error *
10634 check_local_changes(void *arg, unsigned char status,
10635 unsigned char staged_status, const char *path,
10636 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10637 struct got_object_id *commit_id, int dirfd, const char *de_name)
10639 int *have_local_changes = arg;
10641 switch (status) {
10642 case GOT_STATUS_ADD:
10643 case GOT_STATUS_DELETE:
10644 case GOT_STATUS_MODIFY:
10645 case GOT_STATUS_CONFLICT:
10646 *have_local_changes = 1;
10647 return got_error(GOT_ERR_CANCELLED);
10648 default:
10649 break;
10652 switch (staged_status) {
10653 case GOT_STATUS_ADD:
10654 case GOT_STATUS_DELETE:
10655 case GOT_STATUS_MODIFY:
10656 *have_local_changes = 1;
10657 return got_error(GOT_ERR_CANCELLED);
10658 default:
10659 break;
10662 return NULL;
10665 static const struct got_error *
10666 cmd_histedit(int argc, char *argv[])
10668 const struct got_error *error = NULL;
10669 struct got_worktree *worktree = NULL;
10670 struct got_fileindex *fileindex = NULL;
10671 struct got_repository *repo = NULL;
10672 char *cwd = NULL;
10673 struct got_reference *branch = NULL;
10674 struct got_reference *tmp_branch = NULL;
10675 struct got_object_id *resume_commit_id = NULL;
10676 struct got_object_id *base_commit_id = NULL;
10677 struct got_object_id *head_commit_id = NULL;
10678 struct got_commit_object *commit = NULL;
10679 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10680 struct got_update_progress_arg upa;
10681 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10682 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10683 int list_backups = 0, delete_backups = 0;
10684 const char *edit_script_path = NULL;
10685 struct got_object_id_queue commits;
10686 struct got_pathlist_head merged_paths;
10687 const struct got_object_id_queue *parent_ids;
10688 struct got_object_qid *pid;
10689 struct got_histedit_list histedit_cmds;
10690 struct got_histedit_list_entry *hle;
10692 STAILQ_INIT(&commits);
10693 TAILQ_INIT(&histedit_cmds);
10694 TAILQ_INIT(&merged_paths);
10695 memset(&upa, 0, sizeof(upa));
10697 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10698 switch (ch) {
10699 case 'a':
10700 abort_edit = 1;
10701 break;
10702 case 'c':
10703 continue_edit = 1;
10704 break;
10705 case 'e':
10706 edit_only = 1;
10707 break;
10708 case 'f':
10709 fold_only = 1;
10710 break;
10711 case 'F':
10712 edit_script_path = optarg;
10713 break;
10714 case 'm':
10715 edit_logmsg_only = 1;
10716 break;
10717 case 'l':
10718 list_backups = 1;
10719 break;
10720 case 'X':
10721 delete_backups = 1;
10722 break;
10723 default:
10724 usage_histedit();
10725 /* NOTREACHED */
10729 argc -= optind;
10730 argv += optind;
10732 #ifndef PROFILE
10733 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10734 "unveil", NULL) == -1)
10735 err(1, "pledge");
10736 #endif
10737 if (abort_edit && continue_edit)
10738 option_conflict('a', 'c');
10739 if (edit_script_path && edit_logmsg_only)
10740 option_conflict('F', 'm');
10741 if (abort_edit && edit_logmsg_only)
10742 option_conflict('a', 'm');
10743 if (continue_edit && edit_logmsg_only)
10744 option_conflict('c', 'm');
10745 if (abort_edit && fold_only)
10746 option_conflict('a', 'f');
10747 if (continue_edit && fold_only)
10748 option_conflict('c', 'f');
10749 if (fold_only && edit_logmsg_only)
10750 option_conflict('f', 'm');
10751 if (edit_script_path && fold_only)
10752 option_conflict('F', 'f');
10753 if (abort_edit && edit_only)
10754 option_conflict('a', 'e');
10755 if (continue_edit && edit_only)
10756 option_conflict('c', 'e');
10757 if (edit_only && edit_logmsg_only)
10758 option_conflict('e', 'm');
10759 if (edit_script_path && edit_only)
10760 option_conflict('F', 'e');
10761 if (list_backups) {
10762 if (abort_edit)
10763 option_conflict('l', 'a');
10764 if (continue_edit)
10765 option_conflict('l', 'c');
10766 if (edit_script_path)
10767 option_conflict('l', 'F');
10768 if (edit_logmsg_only)
10769 option_conflict('l', 'm');
10770 if (fold_only)
10771 option_conflict('l', 'f');
10772 if (edit_only)
10773 option_conflict('l', 'e');
10774 if (delete_backups)
10775 option_conflict('l', 'X');
10776 if (argc != 0 && argc != 1)
10777 usage_histedit();
10778 } else if (delete_backups) {
10779 if (abort_edit)
10780 option_conflict('X', 'a');
10781 if (continue_edit)
10782 option_conflict('X', 'c');
10783 if (edit_script_path)
10784 option_conflict('X', 'F');
10785 if (edit_logmsg_only)
10786 option_conflict('X', 'm');
10787 if (fold_only)
10788 option_conflict('X', 'f');
10789 if (edit_only)
10790 option_conflict('X', 'e');
10791 if (list_backups)
10792 option_conflict('X', 'l');
10793 if (argc != 0 && argc != 1)
10794 usage_histedit();
10795 } else if (argc != 0)
10796 usage_histedit();
10799 * This command cannot apply unveil(2) in all cases because the
10800 * user may choose to run an editor to edit the histedit script
10801 * and to edit individual commit log messages.
10802 * unveil(2) traverses exec(2); if an editor is used we have to
10803 * apply unveil after edit script and log messages have been written.
10804 * XXX TODO: Make use of unveil(2) where possible.
10807 cwd = getcwd(NULL, 0);
10808 if (cwd == NULL) {
10809 error = got_error_from_errno("getcwd");
10810 goto done;
10812 error = got_worktree_open(&worktree, cwd);
10813 if (error) {
10814 if (list_backups || delete_backups) {
10815 if (error->code != GOT_ERR_NOT_WORKTREE)
10816 goto done;
10817 } else {
10818 if (error->code == GOT_ERR_NOT_WORKTREE)
10819 error = wrap_not_worktree_error(error,
10820 "histedit", cwd);
10821 goto done;
10825 if (list_backups || delete_backups) {
10826 error = got_repo_open(&repo,
10827 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10828 NULL);
10829 if (error != NULL)
10830 goto done;
10831 error = apply_unveil(got_repo_get_path(repo), 0,
10832 worktree ? got_worktree_get_root_path(worktree) : NULL);
10833 if (error)
10834 goto done;
10835 error = process_backup_refs(
10836 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10837 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10838 goto done; /* nothing else to do */
10841 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10842 NULL);
10843 if (error != NULL)
10844 goto done;
10846 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10847 if (error)
10848 goto done;
10849 if (rebase_in_progress) {
10850 error = got_error(GOT_ERR_REBASING);
10851 goto done;
10854 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10855 repo);
10856 if (error)
10857 goto done;
10858 if (merge_in_progress) {
10859 error = got_error(GOT_ERR_MERGE_BUSY);
10860 goto done;
10863 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10864 if (error)
10865 goto done;
10867 if (edit_in_progress && edit_logmsg_only) {
10868 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10869 "histedit operation is in progress in this "
10870 "work tree and must be continued or aborted "
10871 "before the -m option can be used");
10872 goto done;
10874 if (edit_in_progress && fold_only) {
10875 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10876 "histedit operation is in progress in this "
10877 "work tree and must be continued or aborted "
10878 "before the -f option can be used");
10879 goto done;
10881 if (edit_in_progress && edit_only) {
10882 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10883 "histedit operation is in progress in this "
10884 "work tree and must be continued or aborted "
10885 "before the -e option can be used");
10886 goto done;
10889 if (edit_in_progress && abort_edit) {
10890 error = got_worktree_histedit_continue(&resume_commit_id,
10891 &tmp_branch, &branch, &base_commit_id, &fileindex,
10892 worktree, repo);
10893 if (error)
10894 goto done;
10895 printf("Switching work tree to %s\n",
10896 got_ref_get_symref_target(branch));
10897 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10898 branch, base_commit_id, abort_progress, &upa);
10899 if (error)
10900 goto done;
10901 printf("Histedit of %s aborted\n",
10902 got_ref_get_symref_target(branch));
10903 print_merge_progress_stats(&upa);
10904 goto done; /* nothing else to do */
10905 } else if (abort_edit) {
10906 error = got_error(GOT_ERR_NOT_HISTEDIT);
10907 goto done;
10910 if (continue_edit) {
10911 char *path;
10913 if (!edit_in_progress) {
10914 error = got_error(GOT_ERR_NOT_HISTEDIT);
10915 goto done;
10918 error = got_worktree_get_histedit_script_path(&path, worktree);
10919 if (error)
10920 goto done;
10922 error = histedit_load_list(&histedit_cmds, path, repo);
10923 free(path);
10924 if (error)
10925 goto done;
10927 error = got_worktree_histedit_continue(&resume_commit_id,
10928 &tmp_branch, &branch, &base_commit_id, &fileindex,
10929 worktree, repo);
10930 if (error)
10931 goto done;
10933 error = got_ref_resolve(&head_commit_id, repo, branch);
10934 if (error)
10935 goto done;
10937 error = got_object_open_as_commit(&commit, repo,
10938 head_commit_id);
10939 if (error)
10940 goto done;
10941 parent_ids = got_object_commit_get_parent_ids(commit);
10942 pid = STAILQ_FIRST(parent_ids);
10943 if (pid == NULL) {
10944 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10945 goto done;
10947 error = collect_commits(&commits, head_commit_id, &pid->id,
10948 base_commit_id, got_worktree_get_path_prefix(worktree),
10949 GOT_ERR_HISTEDIT_PATH, repo);
10950 got_object_commit_close(commit);
10951 commit = NULL;
10952 if (error)
10953 goto done;
10954 } else {
10955 if (edit_in_progress) {
10956 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10957 goto done;
10960 error = got_ref_open(&branch, repo,
10961 got_worktree_get_head_ref_name(worktree), 0);
10962 if (error != NULL)
10963 goto done;
10965 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10966 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10967 "will not edit commit history of a branch outside "
10968 "the \"refs/heads/\" reference namespace");
10969 goto done;
10972 error = got_ref_resolve(&head_commit_id, repo, branch);
10973 got_ref_close(branch);
10974 branch = NULL;
10975 if (error)
10976 goto done;
10978 error = got_object_open_as_commit(&commit, repo,
10979 head_commit_id);
10980 if (error)
10981 goto done;
10982 parent_ids = got_object_commit_get_parent_ids(commit);
10983 pid = STAILQ_FIRST(parent_ids);
10984 if (pid == NULL) {
10985 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10986 goto done;
10988 error = collect_commits(&commits, head_commit_id, &pid->id,
10989 got_worktree_get_base_commit_id(worktree),
10990 got_worktree_get_path_prefix(worktree),
10991 GOT_ERR_HISTEDIT_PATH, repo);
10992 got_object_commit_close(commit);
10993 commit = NULL;
10994 if (error)
10995 goto done;
10997 if (STAILQ_EMPTY(&commits)) {
10998 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10999 goto done;
11002 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11003 &base_commit_id, &fileindex, worktree, repo);
11004 if (error)
11005 goto done;
11007 if (edit_script_path) {
11008 error = histedit_load_list(&histedit_cmds,
11009 edit_script_path, repo);
11010 if (error) {
11011 got_worktree_histedit_abort(worktree, fileindex,
11012 repo, branch, base_commit_id,
11013 abort_progress, &upa);
11014 print_merge_progress_stats(&upa);
11015 goto done;
11017 } else {
11018 const char *branch_name;
11019 branch_name = got_ref_get_symref_target(branch);
11020 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11021 branch_name += 11;
11022 error = histedit_edit_script(&histedit_cmds, &commits,
11023 branch_name, edit_logmsg_only, fold_only,
11024 edit_only, repo);
11025 if (error) {
11026 got_worktree_histedit_abort(worktree, fileindex,
11027 repo, branch, base_commit_id,
11028 abort_progress, &upa);
11029 print_merge_progress_stats(&upa);
11030 goto done;
11035 error = histedit_save_list(&histedit_cmds, worktree,
11036 repo);
11037 if (error) {
11038 got_worktree_histedit_abort(worktree, fileindex,
11039 repo, branch, base_commit_id,
11040 abort_progress, &upa);
11041 print_merge_progress_stats(&upa);
11042 goto done;
11047 error = histedit_check_script(&histedit_cmds, &commits, repo);
11048 if (error)
11049 goto done;
11051 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11052 if (resume_commit_id) {
11053 if (got_object_id_cmp(hle->commit_id,
11054 resume_commit_id) != 0)
11055 continue;
11057 resume_commit_id = NULL;
11058 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11059 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11060 error = histedit_skip_commit(hle, worktree,
11061 repo);
11062 if (error)
11063 goto done;
11064 } else {
11065 struct got_pathlist_head paths;
11066 int have_changes = 0;
11068 TAILQ_INIT(&paths);
11069 error = got_pathlist_append(&paths, "", NULL);
11070 if (error)
11071 goto done;
11072 error = got_worktree_status(worktree, &paths,
11073 repo, 0, check_local_changes, &have_changes,
11074 check_cancelled, NULL);
11075 got_pathlist_free(&paths);
11076 if (error) {
11077 if (error->code != GOT_ERR_CANCELLED)
11078 goto done;
11079 if (sigint_received || sigpipe_received)
11080 goto done;
11082 if (have_changes) {
11083 error = histedit_commit(NULL, worktree,
11084 fileindex, tmp_branch, hle, repo);
11085 if (error)
11086 goto done;
11087 } else {
11088 error = got_object_open_as_commit(
11089 &commit, repo, hle->commit_id);
11090 if (error)
11091 goto done;
11092 error = show_histedit_progress(commit,
11093 hle, NULL);
11094 got_object_commit_close(commit);
11095 commit = NULL;
11096 if (error)
11097 goto done;
11100 continue;
11103 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11104 error = histedit_skip_commit(hle, worktree, repo);
11105 if (error)
11106 goto done;
11107 continue;
11110 error = got_object_open_as_commit(&commit, repo,
11111 hle->commit_id);
11112 if (error)
11113 goto done;
11114 parent_ids = got_object_commit_get_parent_ids(commit);
11115 pid = STAILQ_FIRST(parent_ids);
11117 error = got_worktree_histedit_merge_files(&merged_paths,
11118 worktree, fileindex, &pid->id, hle->commit_id, repo,
11119 update_progress, &upa, check_cancelled, NULL);
11120 if (error)
11121 goto done;
11122 got_object_commit_close(commit);
11123 commit = NULL;
11125 print_merge_progress_stats(&upa);
11126 if (upa.conflicts > 0 || upa.missing > 0 ||
11127 upa.not_deleted > 0 || upa.unversioned > 0) {
11128 if (upa.conflicts > 0) {
11129 error = show_rebase_merge_conflict(
11130 hle->commit_id, repo);
11131 if (error)
11132 goto done;
11134 got_worktree_rebase_pathlist_free(&merged_paths);
11135 break;
11138 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11139 char *id_str;
11140 error = got_object_id_str(&id_str, hle->commit_id);
11141 if (error)
11142 goto done;
11143 printf("Stopping histedit for amending commit %s\n",
11144 id_str);
11145 free(id_str);
11146 got_worktree_rebase_pathlist_free(&merged_paths);
11147 error = got_worktree_histedit_postpone(worktree,
11148 fileindex);
11149 goto done;
11152 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11153 error = histedit_skip_commit(hle, worktree, repo);
11154 if (error)
11155 goto done;
11156 continue;
11159 error = histedit_commit(&merged_paths, worktree, fileindex,
11160 tmp_branch, hle, repo);
11161 got_worktree_rebase_pathlist_free(&merged_paths);
11162 if (error)
11163 goto done;
11166 if (upa.conflicts > 0 || upa.missing > 0 ||
11167 upa.not_deleted > 0 || upa.unversioned > 0) {
11168 error = got_worktree_histedit_postpone(worktree, fileindex);
11169 if (error)
11170 goto done;
11171 if (upa.conflicts > 0 && upa.missing == 0 &&
11172 upa.not_deleted == 0 && upa.unversioned == 0) {
11173 error = got_error_msg(GOT_ERR_CONFLICTS,
11174 "conflicts must be resolved before histedit "
11175 "can continue");
11176 } else if (upa.conflicts > 0) {
11177 error = got_error_msg(GOT_ERR_CONFLICTS,
11178 "conflicts must be resolved before histedit "
11179 "can continue; changes destined for some "
11180 "files were not yet merged and should be "
11181 "merged manually if required before the "
11182 "histedit operation is continued");
11183 } else {
11184 error = got_error_msg(GOT_ERR_CONFLICTS,
11185 "changes destined for some files were not "
11186 "yet merged and should be merged manually "
11187 "if required before the histedit operation "
11188 "is continued");
11190 } else
11191 error = histedit_complete(worktree, fileindex, tmp_branch,
11192 branch, repo);
11193 done:
11194 got_object_id_queue_free(&commits);
11195 histedit_free_list(&histedit_cmds);
11196 free(head_commit_id);
11197 free(base_commit_id);
11198 free(resume_commit_id);
11199 if (commit)
11200 got_object_commit_close(commit);
11201 if (branch)
11202 got_ref_close(branch);
11203 if (tmp_branch)
11204 got_ref_close(tmp_branch);
11205 if (worktree)
11206 got_worktree_close(worktree);
11207 if (repo) {
11208 const struct got_error *close_err = got_repo_close(repo);
11209 if (error == NULL)
11210 error = close_err;
11212 return error;
11215 __dead static void
11216 usage_integrate(void)
11218 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11219 exit(1);
11222 static const struct got_error *
11223 cmd_integrate(int argc, char *argv[])
11225 const struct got_error *error = NULL;
11226 struct got_repository *repo = NULL;
11227 struct got_worktree *worktree = NULL;
11228 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11229 const char *branch_arg = NULL;
11230 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11231 struct got_fileindex *fileindex = NULL;
11232 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11233 int ch;
11234 struct got_update_progress_arg upa;
11236 while ((ch = getopt(argc, argv, "")) != -1) {
11237 switch (ch) {
11238 default:
11239 usage_integrate();
11240 /* NOTREACHED */
11244 argc -= optind;
11245 argv += optind;
11247 if (argc != 1)
11248 usage_integrate();
11249 branch_arg = argv[0];
11250 #ifndef PROFILE
11251 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11252 "unveil", NULL) == -1)
11253 err(1, "pledge");
11254 #endif
11255 cwd = getcwd(NULL, 0);
11256 if (cwd == NULL) {
11257 error = got_error_from_errno("getcwd");
11258 goto done;
11261 error = got_worktree_open(&worktree, cwd);
11262 if (error) {
11263 if (error->code == GOT_ERR_NOT_WORKTREE)
11264 error = wrap_not_worktree_error(error, "integrate",
11265 cwd);
11266 goto done;
11269 error = check_rebase_or_histedit_in_progress(worktree);
11270 if (error)
11271 goto done;
11273 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11274 NULL);
11275 if (error != NULL)
11276 goto done;
11278 error = apply_unveil(got_repo_get_path(repo), 0,
11279 got_worktree_get_root_path(worktree));
11280 if (error)
11281 goto done;
11283 error = check_merge_in_progress(worktree, repo);
11284 if (error)
11285 goto done;
11287 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11288 error = got_error_from_errno("asprintf");
11289 goto done;
11292 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11293 &base_branch_ref, worktree, refname, repo);
11294 if (error)
11295 goto done;
11297 refname = strdup(got_ref_get_name(branch_ref));
11298 if (refname == NULL) {
11299 error = got_error_from_errno("strdup");
11300 got_worktree_integrate_abort(worktree, fileindex, repo,
11301 branch_ref, base_branch_ref);
11302 goto done;
11304 base_refname = strdup(got_ref_get_name(base_branch_ref));
11305 if (base_refname == NULL) {
11306 error = got_error_from_errno("strdup");
11307 got_worktree_integrate_abort(worktree, fileindex, repo,
11308 branch_ref, base_branch_ref);
11309 goto done;
11312 error = got_ref_resolve(&commit_id, repo, branch_ref);
11313 if (error)
11314 goto done;
11316 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11317 if (error)
11318 goto done;
11320 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11321 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11322 "specified branch has already been integrated");
11323 got_worktree_integrate_abort(worktree, fileindex, repo,
11324 branch_ref, base_branch_ref);
11325 goto done;
11328 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11329 if (error) {
11330 if (error->code == GOT_ERR_ANCESTRY)
11331 error = got_error(GOT_ERR_REBASE_REQUIRED);
11332 got_worktree_integrate_abort(worktree, fileindex, repo,
11333 branch_ref, base_branch_ref);
11334 goto done;
11337 memset(&upa, 0, sizeof(upa));
11338 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11339 branch_ref, base_branch_ref, update_progress, &upa,
11340 check_cancelled, NULL);
11341 if (error)
11342 goto done;
11344 printf("Integrated %s into %s\n", refname, base_refname);
11345 print_update_progress_stats(&upa);
11346 done:
11347 if (repo) {
11348 const struct got_error *close_err = got_repo_close(repo);
11349 if (error == NULL)
11350 error = close_err;
11352 if (worktree)
11353 got_worktree_close(worktree);
11354 free(cwd);
11355 free(base_commit_id);
11356 free(commit_id);
11357 free(refname);
11358 free(base_refname);
11359 return error;
11362 __dead static void
11363 usage_merge(void)
11365 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11366 getprogname());
11367 exit(1);
11370 static const struct got_error *
11371 cmd_merge(int argc, char *argv[])
11373 const struct got_error *error = NULL;
11374 struct got_worktree *worktree = NULL;
11375 struct got_repository *repo = NULL;
11376 struct got_fileindex *fileindex = NULL;
11377 char *cwd = NULL, *id_str = NULL, *author = NULL;
11378 struct got_reference *branch = NULL, *wt_branch = NULL;
11379 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11380 struct got_object_id *wt_branch_tip = NULL;
11381 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11382 int interrupt_merge = 0;
11383 struct got_update_progress_arg upa;
11384 struct got_object_id *merge_commit_id = NULL;
11385 char *branch_name = NULL;
11387 memset(&upa, 0, sizeof(upa));
11389 while ((ch = getopt(argc, argv, "acn")) != -1) {
11390 switch (ch) {
11391 case 'a':
11392 abort_merge = 1;
11393 break;
11394 case 'c':
11395 continue_merge = 1;
11396 break;
11397 case 'n':
11398 interrupt_merge = 1;
11399 break;
11400 default:
11401 usage_rebase();
11402 /* NOTREACHED */
11406 argc -= optind;
11407 argv += optind;
11409 #ifndef PROFILE
11410 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11411 "unveil", NULL) == -1)
11412 err(1, "pledge");
11413 #endif
11415 if (abort_merge && continue_merge)
11416 option_conflict('a', 'c');
11417 if (abort_merge || continue_merge) {
11418 if (argc != 0)
11419 usage_merge();
11420 } else if (argc != 1)
11421 usage_merge();
11423 cwd = getcwd(NULL, 0);
11424 if (cwd == NULL) {
11425 error = got_error_from_errno("getcwd");
11426 goto done;
11429 error = got_worktree_open(&worktree, cwd);
11430 if (error) {
11431 if (error->code == GOT_ERR_NOT_WORKTREE)
11432 error = wrap_not_worktree_error(error,
11433 "merge", cwd);
11434 goto done;
11437 error = got_repo_open(&repo,
11438 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11439 if (error != NULL)
11440 goto done;
11442 error = apply_unveil(got_repo_get_path(repo), 0,
11443 worktree ? got_worktree_get_root_path(worktree) : NULL);
11444 if (error)
11445 goto done;
11447 error = check_rebase_or_histedit_in_progress(worktree);
11448 if (error)
11449 goto done;
11451 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11452 repo);
11453 if (error)
11454 goto done;
11456 if (abort_merge) {
11457 if (!merge_in_progress) {
11458 error = got_error(GOT_ERR_NOT_MERGING);
11459 goto done;
11461 error = got_worktree_merge_continue(&branch_name,
11462 &branch_tip, &fileindex, worktree, repo);
11463 if (error)
11464 goto done;
11465 error = got_worktree_merge_abort(worktree, fileindex, repo,
11466 abort_progress, &upa);
11467 if (error)
11468 goto done;
11469 printf("Merge of %s aborted\n", branch_name);
11470 goto done; /* nothing else to do */
11473 error = get_author(&author, repo, worktree);
11474 if (error)
11475 goto done;
11477 if (continue_merge) {
11478 if (!merge_in_progress) {
11479 error = got_error(GOT_ERR_NOT_MERGING);
11480 goto done;
11482 error = got_worktree_merge_continue(&branch_name,
11483 &branch_tip, &fileindex, worktree, repo);
11484 if (error)
11485 goto done;
11486 } else {
11487 error = got_ref_open(&branch, repo, argv[0], 0);
11488 if (error != NULL)
11489 goto done;
11490 branch_name = strdup(got_ref_get_name(branch));
11491 if (branch_name == NULL) {
11492 error = got_error_from_errno("strdup");
11493 goto done;
11495 error = got_ref_resolve(&branch_tip, repo, branch);
11496 if (error)
11497 goto done;
11500 error = got_ref_open(&wt_branch, repo,
11501 got_worktree_get_head_ref_name(worktree), 0);
11502 if (error)
11503 goto done;
11504 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11505 if (error)
11506 goto done;
11507 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11508 wt_branch_tip, branch_tip, 0, repo,
11509 check_cancelled, NULL);
11510 if (error && error->code != GOT_ERR_ANCESTRY)
11511 goto done;
11513 if (!continue_merge) {
11514 error = check_path_prefix(wt_branch_tip, branch_tip,
11515 got_worktree_get_path_prefix(worktree),
11516 GOT_ERR_MERGE_PATH, repo);
11517 if (error)
11518 goto done;
11519 if (yca_id) {
11520 error = check_same_branch(wt_branch_tip, branch,
11521 yca_id, repo);
11522 if (error) {
11523 if (error->code != GOT_ERR_ANCESTRY)
11524 goto done;
11525 error = NULL;
11526 } else {
11527 static char msg[512];
11528 snprintf(msg, sizeof(msg),
11529 "cannot create a merge commit because "
11530 "%s is based on %s; %s can be integrated "
11531 "with 'got integrate' instead", branch_name,
11532 got_worktree_get_head_ref_name(worktree),
11533 branch_name);
11534 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11535 goto done;
11538 error = got_worktree_merge_prepare(&fileindex, worktree,
11539 branch, repo);
11540 if (error)
11541 goto done;
11543 error = got_worktree_merge_branch(worktree, fileindex,
11544 yca_id, branch_tip, repo, update_progress, &upa,
11545 check_cancelled, NULL);
11546 if (error)
11547 goto done;
11548 print_merge_progress_stats(&upa);
11549 if (!upa.did_something) {
11550 error = got_worktree_merge_abort(worktree, fileindex,
11551 repo, abort_progress, &upa);
11552 if (error)
11553 goto done;
11554 printf("Already up-to-date\n");
11555 goto done;
11559 if (interrupt_merge) {
11560 error = got_worktree_merge_postpone(worktree, fileindex);
11561 if (error)
11562 goto done;
11563 printf("Merge of %s interrupted on request\n", branch_name);
11564 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11565 upa.not_deleted > 0 || upa.unversioned > 0) {
11566 error = got_worktree_merge_postpone(worktree, fileindex);
11567 if (error)
11568 goto done;
11569 if (upa.conflicts > 0 && upa.missing == 0 &&
11570 upa.not_deleted == 0 && upa.unversioned == 0) {
11571 error = got_error_msg(GOT_ERR_CONFLICTS,
11572 "conflicts must be resolved before merging "
11573 "can continue");
11574 } else if (upa.conflicts > 0) {
11575 error = got_error_msg(GOT_ERR_CONFLICTS,
11576 "conflicts must be resolved before merging "
11577 "can continue; changes destined for some "
11578 "files were not yet merged and "
11579 "should be merged manually if required before the "
11580 "merge operation is continued");
11581 } else {
11582 error = got_error_msg(GOT_ERR_CONFLICTS,
11583 "changes destined for some "
11584 "files were not yet merged and should be "
11585 "merged manually if required before the "
11586 "merge operation is continued");
11588 goto done;
11589 } else {
11590 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11591 fileindex, author, NULL, 1, branch_tip, branch_name,
11592 repo, continue_merge ? print_status : NULL, NULL);
11593 if (error)
11594 goto done;
11595 error = got_worktree_merge_complete(worktree, fileindex, repo);
11596 if (error)
11597 goto done;
11598 error = got_object_id_str(&id_str, merge_commit_id);
11599 if (error)
11600 goto done;
11601 printf("Merged %s into %s: %s\n", branch_name,
11602 got_worktree_get_head_ref_name(worktree),
11603 id_str);
11606 done:
11607 free(id_str);
11608 free(merge_commit_id);
11609 free(author);
11610 free(branch_tip);
11611 free(branch_name);
11612 free(yca_id);
11613 if (branch)
11614 got_ref_close(branch);
11615 if (wt_branch)
11616 got_ref_close(wt_branch);
11617 if (worktree)
11618 got_worktree_close(worktree);
11619 if (repo) {
11620 const struct got_error *close_err = got_repo_close(repo);
11621 if (error == NULL)
11622 error = close_err;
11624 return error;
11627 __dead static void
11628 usage_stage(void)
11630 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11631 "[-S] [file-path ...]\n",
11632 getprogname());
11633 exit(1);
11636 static const struct got_error *
11637 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11638 const char *path, struct got_object_id *blob_id,
11639 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11640 int dirfd, const char *de_name)
11642 const struct got_error *err = NULL;
11643 char *id_str = NULL;
11645 if (staged_status != GOT_STATUS_ADD &&
11646 staged_status != GOT_STATUS_MODIFY &&
11647 staged_status != GOT_STATUS_DELETE)
11648 return NULL;
11650 if (staged_status == GOT_STATUS_ADD ||
11651 staged_status == GOT_STATUS_MODIFY)
11652 err = got_object_id_str(&id_str, staged_blob_id);
11653 else
11654 err = got_object_id_str(&id_str, blob_id);
11655 if (err)
11656 return err;
11658 printf("%s %c %s\n", id_str, staged_status, path);
11659 free(id_str);
11660 return NULL;
11663 static const struct got_error *
11664 cmd_stage(int argc, char *argv[])
11666 const struct got_error *error = NULL;
11667 struct got_repository *repo = NULL;
11668 struct got_worktree *worktree = NULL;
11669 char *cwd = NULL;
11670 struct got_pathlist_head paths;
11671 struct got_pathlist_entry *pe;
11672 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11673 FILE *patch_script_file = NULL;
11674 const char *patch_script_path = NULL;
11675 struct choose_patch_arg cpa;
11677 TAILQ_INIT(&paths);
11679 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11680 switch (ch) {
11681 case 'l':
11682 list_stage = 1;
11683 break;
11684 case 'p':
11685 pflag = 1;
11686 break;
11687 case 'F':
11688 patch_script_path = optarg;
11689 break;
11690 case 'S':
11691 allow_bad_symlinks = 1;
11692 break;
11693 default:
11694 usage_stage();
11695 /* NOTREACHED */
11699 argc -= optind;
11700 argv += optind;
11702 #ifndef PROFILE
11703 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11704 "unveil", NULL) == -1)
11705 err(1, "pledge");
11706 #endif
11707 if (list_stage && (pflag || patch_script_path))
11708 errx(1, "-l option cannot be used with other options");
11709 if (patch_script_path && !pflag)
11710 errx(1, "-F option can only be used together with -p option");
11712 cwd = getcwd(NULL, 0);
11713 if (cwd == NULL) {
11714 error = got_error_from_errno("getcwd");
11715 goto done;
11718 error = got_worktree_open(&worktree, cwd);
11719 if (error) {
11720 if (error->code == GOT_ERR_NOT_WORKTREE)
11721 error = wrap_not_worktree_error(error, "stage", cwd);
11722 goto done;
11725 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11726 NULL);
11727 if (error != NULL)
11728 goto done;
11730 if (patch_script_path) {
11731 patch_script_file = fopen(patch_script_path, "re");
11732 if (patch_script_file == NULL) {
11733 error = got_error_from_errno2("fopen",
11734 patch_script_path);
11735 goto done;
11738 error = apply_unveil(got_repo_get_path(repo), 0,
11739 got_worktree_get_root_path(worktree));
11740 if (error)
11741 goto done;
11743 error = check_merge_in_progress(worktree, repo);
11744 if (error)
11745 goto done;
11747 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11748 if (error)
11749 goto done;
11751 if (list_stage)
11752 error = got_worktree_status(worktree, &paths, repo, 0,
11753 print_stage, NULL, check_cancelled, NULL);
11754 else {
11755 cpa.patch_script_file = patch_script_file;
11756 cpa.action = "stage";
11757 error = got_worktree_stage(worktree, &paths,
11758 pflag ? NULL : print_status, NULL,
11759 pflag ? choose_patch : NULL, &cpa,
11760 allow_bad_symlinks, repo);
11762 done:
11763 if (patch_script_file && fclose(patch_script_file) == EOF &&
11764 error == NULL)
11765 error = got_error_from_errno2("fclose", patch_script_path);
11766 if (repo) {
11767 const struct got_error *close_err = got_repo_close(repo);
11768 if (error == NULL)
11769 error = close_err;
11771 if (worktree)
11772 got_worktree_close(worktree);
11773 TAILQ_FOREACH(pe, &paths, entry)
11774 free((char *)pe->path);
11775 got_pathlist_free(&paths);
11776 free(cwd);
11777 return error;
11780 __dead static void
11781 usage_unstage(void)
11783 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11784 "[file-path ...]\n",
11785 getprogname());
11786 exit(1);
11790 static const struct got_error *
11791 cmd_unstage(int argc, char *argv[])
11793 const struct got_error *error = NULL;
11794 struct got_repository *repo = NULL;
11795 struct got_worktree *worktree = NULL;
11796 char *cwd = NULL;
11797 struct got_pathlist_head paths;
11798 struct got_pathlist_entry *pe;
11799 int ch, pflag = 0;
11800 struct got_update_progress_arg upa;
11801 FILE *patch_script_file = NULL;
11802 const char *patch_script_path = NULL;
11803 struct choose_patch_arg cpa;
11805 TAILQ_INIT(&paths);
11807 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11808 switch (ch) {
11809 case 'p':
11810 pflag = 1;
11811 break;
11812 case 'F':
11813 patch_script_path = optarg;
11814 break;
11815 default:
11816 usage_unstage();
11817 /* NOTREACHED */
11821 argc -= optind;
11822 argv += optind;
11824 #ifndef PROFILE
11825 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11826 "unveil", NULL) == -1)
11827 err(1, "pledge");
11828 #endif
11829 if (patch_script_path && !pflag)
11830 errx(1, "-F option can only be used together with -p option");
11832 cwd = getcwd(NULL, 0);
11833 if (cwd == NULL) {
11834 error = got_error_from_errno("getcwd");
11835 goto done;
11838 error = got_worktree_open(&worktree, cwd);
11839 if (error) {
11840 if (error->code == GOT_ERR_NOT_WORKTREE)
11841 error = wrap_not_worktree_error(error, "unstage", cwd);
11842 goto done;
11845 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11846 NULL);
11847 if (error != NULL)
11848 goto done;
11850 if (patch_script_path) {
11851 patch_script_file = fopen(patch_script_path, "re");
11852 if (patch_script_file == NULL) {
11853 error = got_error_from_errno2("fopen",
11854 patch_script_path);
11855 goto done;
11859 error = apply_unveil(got_repo_get_path(repo), 0,
11860 got_worktree_get_root_path(worktree));
11861 if (error)
11862 goto done;
11864 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11865 if (error)
11866 goto done;
11868 cpa.patch_script_file = patch_script_file;
11869 cpa.action = "unstage";
11870 memset(&upa, 0, sizeof(upa));
11871 error = got_worktree_unstage(worktree, &paths, update_progress,
11872 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11873 if (!error)
11874 print_merge_progress_stats(&upa);
11875 done:
11876 if (patch_script_file && fclose(patch_script_file) == EOF &&
11877 error == NULL)
11878 error = got_error_from_errno2("fclose", patch_script_path);
11879 if (repo) {
11880 const struct got_error *close_err = got_repo_close(repo);
11881 if (error == NULL)
11882 error = close_err;
11884 if (worktree)
11885 got_worktree_close(worktree);
11886 TAILQ_FOREACH(pe, &paths, entry)
11887 free((char *)pe->path);
11888 got_pathlist_free(&paths);
11889 free(cwd);
11890 return error;
11893 __dead static void
11894 usage_cat(void)
11896 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11897 "arg1 [arg2 ...]\n", getprogname());
11898 exit(1);
11901 static const struct got_error *
11902 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11904 const struct got_error *err;
11905 struct got_blob_object *blob;
11907 err = got_object_open_as_blob(&blob, repo, id, 8192);
11908 if (err)
11909 return err;
11911 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11912 got_object_blob_close(blob);
11913 return err;
11916 static const struct got_error *
11917 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11919 const struct got_error *err;
11920 struct got_tree_object *tree;
11921 int nentries, i;
11923 err = got_object_open_as_tree(&tree, repo, id);
11924 if (err)
11925 return err;
11927 nentries = got_object_tree_get_nentries(tree);
11928 for (i = 0; i < nentries; i++) {
11929 struct got_tree_entry *te;
11930 char *id_str;
11931 if (sigint_received || sigpipe_received)
11932 break;
11933 te = got_object_tree_get_entry(tree, i);
11934 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11935 if (err)
11936 break;
11937 fprintf(outfile, "%s %.7o %s\n", id_str,
11938 got_tree_entry_get_mode(te),
11939 got_tree_entry_get_name(te));
11940 free(id_str);
11943 got_object_tree_close(tree);
11944 return err;
11947 static void
11948 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11950 long long h, m;
11951 char sign = '+';
11953 if (gmtoff < 0) {
11954 sign = '-';
11955 gmtoff = -gmtoff;
11958 h = (long long)gmtoff / 3600;
11959 m = ((long long)gmtoff - h*3600) / 60;
11960 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11963 static const struct got_error *
11964 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11966 const struct got_error *err;
11967 struct got_commit_object *commit;
11968 const struct got_object_id_queue *parent_ids;
11969 struct got_object_qid *pid;
11970 char *id_str = NULL;
11971 const char *logmsg = NULL;
11972 char gmtoff[6];
11974 err = got_object_open_as_commit(&commit, repo, id);
11975 if (err)
11976 return err;
11978 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11979 if (err)
11980 goto done;
11982 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11983 parent_ids = got_object_commit_get_parent_ids(commit);
11984 fprintf(outfile, "numparents %d\n",
11985 got_object_commit_get_nparents(commit));
11986 STAILQ_FOREACH(pid, parent_ids, entry) {
11987 char *pid_str;
11988 err = got_object_id_str(&pid_str, &pid->id);
11989 if (err)
11990 goto done;
11991 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11992 free(pid_str);
11994 format_gmtoff(gmtoff, sizeof(gmtoff),
11995 got_object_commit_get_author_gmtoff(commit));
11996 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11997 got_object_commit_get_author(commit),
11998 (long long)got_object_commit_get_author_time(commit),
11999 gmtoff);
12001 format_gmtoff(gmtoff, sizeof(gmtoff),
12002 got_object_commit_get_committer_gmtoff(commit));
12003 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12004 got_object_commit_get_author(commit),
12005 (long long)got_object_commit_get_committer_time(commit),
12006 gmtoff);
12008 logmsg = got_object_commit_get_logmsg_raw(commit);
12009 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12010 fprintf(outfile, "%s", logmsg);
12011 done:
12012 free(id_str);
12013 got_object_commit_close(commit);
12014 return err;
12017 static const struct got_error *
12018 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12020 const struct got_error *err;
12021 struct got_tag_object *tag;
12022 char *id_str = NULL;
12023 const char *tagmsg = NULL;
12024 char gmtoff[6];
12026 err = got_object_open_as_tag(&tag, repo, id);
12027 if (err)
12028 return err;
12030 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12031 if (err)
12032 goto done;
12034 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12036 switch (got_object_tag_get_object_type(tag)) {
12037 case GOT_OBJ_TYPE_BLOB:
12038 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12039 GOT_OBJ_LABEL_BLOB);
12040 break;
12041 case GOT_OBJ_TYPE_TREE:
12042 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12043 GOT_OBJ_LABEL_TREE);
12044 break;
12045 case GOT_OBJ_TYPE_COMMIT:
12046 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12047 GOT_OBJ_LABEL_COMMIT);
12048 break;
12049 case GOT_OBJ_TYPE_TAG:
12050 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12051 GOT_OBJ_LABEL_TAG);
12052 break;
12053 default:
12054 break;
12057 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12058 got_object_tag_get_name(tag));
12060 format_gmtoff(gmtoff, sizeof(gmtoff),
12061 got_object_tag_get_tagger_gmtoff(tag));
12062 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12063 got_object_tag_get_tagger(tag),
12064 (long long)got_object_tag_get_tagger_time(tag),
12065 gmtoff);
12067 tagmsg = got_object_tag_get_message(tag);
12068 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12069 fprintf(outfile, "%s", tagmsg);
12070 done:
12071 free(id_str);
12072 got_object_tag_close(tag);
12073 return err;
12076 static const struct got_error *
12077 cmd_cat(int argc, char *argv[])
12079 const struct got_error *error;
12080 struct got_repository *repo = NULL;
12081 struct got_worktree *worktree = NULL;
12082 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12083 const char *commit_id_str = NULL;
12084 struct got_object_id *id = NULL, *commit_id = NULL;
12085 struct got_commit_object *commit = NULL;
12086 int ch, obj_type, i, force_path = 0;
12087 struct got_reflist_head refs;
12089 TAILQ_INIT(&refs);
12091 #ifndef PROFILE
12092 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12093 NULL) == -1)
12094 err(1, "pledge");
12095 #endif
12097 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12098 switch (ch) {
12099 case 'c':
12100 commit_id_str = optarg;
12101 break;
12102 case 'r':
12103 repo_path = realpath(optarg, NULL);
12104 if (repo_path == NULL)
12105 return got_error_from_errno2("realpath",
12106 optarg);
12107 got_path_strip_trailing_slashes(repo_path);
12108 break;
12109 case 'P':
12110 force_path = 1;
12111 break;
12112 default:
12113 usage_cat();
12114 /* NOTREACHED */
12118 argc -= optind;
12119 argv += optind;
12121 cwd = getcwd(NULL, 0);
12122 if (cwd == NULL) {
12123 error = got_error_from_errno("getcwd");
12124 goto done;
12127 if (repo_path == NULL) {
12128 error = got_worktree_open(&worktree, cwd);
12129 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12130 goto done;
12131 if (worktree) {
12132 repo_path = strdup(
12133 got_worktree_get_repo_path(worktree));
12134 if (repo_path == NULL) {
12135 error = got_error_from_errno("strdup");
12136 goto done;
12139 /* Release work tree lock. */
12140 got_worktree_close(worktree);
12141 worktree = NULL;
12145 if (repo_path == NULL) {
12146 repo_path = strdup(cwd);
12147 if (repo_path == NULL)
12148 return got_error_from_errno("strdup");
12151 error = got_repo_open(&repo, repo_path, NULL);
12152 free(repo_path);
12153 if (error != NULL)
12154 goto done;
12156 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12157 if (error)
12158 goto done;
12160 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12161 if (error)
12162 goto done;
12164 if (commit_id_str == NULL)
12165 commit_id_str = GOT_REF_HEAD;
12166 error = got_repo_match_object_id(&commit_id, NULL,
12167 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12168 if (error)
12169 goto done;
12171 error = got_object_open_as_commit(&commit, repo, commit_id);
12172 if (error)
12173 goto done;
12175 for (i = 0; i < argc; i++) {
12176 if (force_path) {
12177 error = got_object_id_by_path(&id, repo, commit,
12178 argv[i]);
12179 if (error)
12180 break;
12181 } else {
12182 error = got_repo_match_object_id(&id, &label, argv[i],
12183 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12184 repo);
12185 if (error) {
12186 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12187 error->code != GOT_ERR_NOT_REF)
12188 break;
12189 error = got_object_id_by_path(&id, repo,
12190 commit, argv[i]);
12191 if (error)
12192 break;
12196 error = got_object_get_type(&obj_type, repo, id);
12197 if (error)
12198 break;
12200 switch (obj_type) {
12201 case GOT_OBJ_TYPE_BLOB:
12202 error = cat_blob(id, repo, stdout);
12203 break;
12204 case GOT_OBJ_TYPE_TREE:
12205 error = cat_tree(id, repo, stdout);
12206 break;
12207 case GOT_OBJ_TYPE_COMMIT:
12208 error = cat_commit(id, repo, stdout);
12209 break;
12210 case GOT_OBJ_TYPE_TAG:
12211 error = cat_tag(id, repo, stdout);
12212 break;
12213 default:
12214 error = got_error(GOT_ERR_OBJ_TYPE);
12215 break;
12217 if (error)
12218 break;
12219 free(label);
12220 label = NULL;
12221 free(id);
12222 id = NULL;
12224 done:
12225 free(label);
12226 free(id);
12227 free(commit_id);
12228 if (commit)
12229 got_object_commit_close(commit);
12230 if (worktree)
12231 got_worktree_close(worktree);
12232 if (repo) {
12233 const struct got_error *close_err = got_repo_close(repo);
12234 if (error == NULL)
12235 error = close_err;
12237 got_ref_list_free(&refs);
12238 return error;
12241 __dead static void
12242 usage_info(void)
12244 fprintf(stderr, "usage: %s info [path ...]\n",
12245 getprogname());
12246 exit(1);
12249 static const struct got_error *
12250 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12251 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12252 struct got_object_id *commit_id)
12254 const struct got_error *err = NULL;
12255 char *id_str = NULL;
12256 char datebuf[128];
12257 struct tm mytm, *tm;
12258 struct got_pathlist_head *paths = arg;
12259 struct got_pathlist_entry *pe;
12262 * Clear error indication from any of the path arguments which
12263 * would cause this file index entry to be displayed.
12265 TAILQ_FOREACH(pe, paths, entry) {
12266 if (got_path_cmp(path, pe->path, strlen(path),
12267 pe->path_len) == 0 ||
12268 got_path_is_child(path, pe->path, pe->path_len))
12269 pe->data = NULL; /* no error */
12272 printf(GOT_COMMIT_SEP_STR);
12273 if (S_ISLNK(mode))
12274 printf("symlink: %s\n", path);
12275 else if (S_ISREG(mode)) {
12276 printf("file: %s\n", path);
12277 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12278 } else if (S_ISDIR(mode))
12279 printf("directory: %s\n", path);
12280 else
12281 printf("something: %s\n", path);
12283 tm = localtime_r(&mtime, &mytm);
12284 if (tm == NULL)
12285 return NULL;
12286 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12287 return got_error(GOT_ERR_NO_SPACE);
12288 printf("timestamp: %s\n", datebuf);
12290 if (blob_id) {
12291 err = got_object_id_str(&id_str, blob_id);
12292 if (err)
12293 return err;
12294 printf("based on blob: %s\n", id_str);
12295 free(id_str);
12298 if (staged_blob_id) {
12299 err = got_object_id_str(&id_str, staged_blob_id);
12300 if (err)
12301 return err;
12302 printf("based on staged blob: %s\n", id_str);
12303 free(id_str);
12306 if (commit_id) {
12307 err = got_object_id_str(&id_str, commit_id);
12308 if (err)
12309 return err;
12310 printf("based on commit: %s\n", id_str);
12311 free(id_str);
12314 return NULL;
12317 static const struct got_error *
12318 cmd_info(int argc, char *argv[])
12320 const struct got_error *error = NULL;
12321 struct got_worktree *worktree = NULL;
12322 char *cwd = NULL, *id_str = NULL;
12323 struct got_pathlist_head paths;
12324 struct got_pathlist_entry *pe;
12325 char *uuidstr = NULL;
12326 int ch, show_files = 0;
12328 TAILQ_INIT(&paths);
12330 while ((ch = getopt(argc, argv, "")) != -1) {
12331 switch (ch) {
12332 default:
12333 usage_info();
12334 /* NOTREACHED */
12338 argc -= optind;
12339 argv += optind;
12341 #ifndef PROFILE
12342 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12343 NULL) == -1)
12344 err(1, "pledge");
12345 #endif
12346 cwd = getcwd(NULL, 0);
12347 if (cwd == NULL) {
12348 error = got_error_from_errno("getcwd");
12349 goto done;
12352 error = got_worktree_open(&worktree, cwd);
12353 if (error) {
12354 if (error->code == GOT_ERR_NOT_WORKTREE)
12355 error = wrap_not_worktree_error(error, "info", cwd);
12356 goto done;
12359 #ifndef PROFILE
12360 /* Remove "cpath" promise. */
12361 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12362 NULL) == -1)
12363 err(1, "pledge");
12364 #endif
12365 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12366 if (error)
12367 goto done;
12369 if (argc >= 1) {
12370 error = get_worktree_paths_from_argv(&paths, argc, argv,
12371 worktree);
12372 if (error)
12373 goto done;
12374 show_files = 1;
12377 error = got_object_id_str(&id_str,
12378 got_worktree_get_base_commit_id(worktree));
12379 if (error)
12380 goto done;
12382 error = got_worktree_get_uuid(&uuidstr, worktree);
12383 if (error)
12384 goto done;
12386 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12387 printf("work tree base commit: %s\n", id_str);
12388 printf("work tree path prefix: %s\n",
12389 got_worktree_get_path_prefix(worktree));
12390 printf("work tree branch reference: %s\n",
12391 got_worktree_get_head_ref_name(worktree));
12392 printf("work tree UUID: %s\n", uuidstr);
12393 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12395 if (show_files) {
12396 struct got_pathlist_entry *pe;
12397 TAILQ_FOREACH(pe, &paths, entry) {
12398 if (pe->path_len == 0)
12399 continue;
12401 * Assume this path will fail. This will be corrected
12402 * in print_path_info() in case the path does suceeed.
12404 pe->data = (void *)got_error_path(pe->path,
12405 GOT_ERR_BAD_PATH);
12407 error = got_worktree_path_info(worktree, &paths,
12408 print_path_info, &paths, check_cancelled, NULL);
12409 if (error)
12410 goto done;
12411 TAILQ_FOREACH(pe, &paths, entry) {
12412 if (pe->data != NULL) {
12413 error = pe->data; /* bad path */
12414 break;
12418 done:
12419 TAILQ_FOREACH(pe, &paths, entry)
12420 free((char *)pe->path);
12421 got_pathlist_free(&paths);
12422 free(cwd);
12423 free(id_str);
12424 free(uuidstr);
12425 return error;