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 return err;
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 err = got_error_from_errno("gmtime_r");
3921 goto done;
3923 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3924 err = got_error(GOT_ERR_NO_SPACE);
3925 goto done;
3928 err = got_object_commit_get_logmsg(&logmsg0, commit);
3929 if (err)
3930 goto done;
3932 s = logmsg0;
3933 while (isspace((unsigned char)s[0]))
3934 s++;
3936 nl = strchr(s, '\n');
3937 if (nl) {
3938 *nl = '\0';
3941 if (ref_str)
3942 printf("%s%-7s %s\n", datebuf, ref_str, s);
3943 else
3944 printf("%s%.7s %s\n", datebuf, id_str, s);
3946 if (fflush(stdout) != 0 && err == NULL)
3947 err = got_error_from_errno("fflush");
3948 done:
3949 free(id_str);
3950 free(ref_str);
3951 free(logmsg0);
3952 return err;
3955 static const struct got_error *
3956 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3957 struct got_repository *repo, const char *path,
3958 struct got_pathlist_head *changed_paths, int show_patch,
3959 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3960 const char *custom_refs_str)
3962 const struct got_error *err = NULL;
3963 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3964 char datebuf[26];
3965 time_t committer_time;
3966 const char *author, *committer;
3967 char *refs_str = NULL;
3969 err = got_object_id_str(&id_str, id);
3970 if (err)
3971 return err;
3973 if (custom_refs_str == NULL) {
3974 struct got_reflist_head *refs;
3975 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3976 if (refs) {
3977 err = build_refs_str(&refs_str, refs, id, repo, 0);
3978 if (err)
3979 goto done;
3983 printf(GOT_COMMIT_SEP_STR);
3984 if (custom_refs_str)
3985 printf("commit %s (%s)\n", id_str, custom_refs_str);
3986 else
3987 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3988 refs_str ? refs_str : "", refs_str ? ")" : "");
3989 free(id_str);
3990 id_str = NULL;
3991 free(refs_str);
3992 refs_str = NULL;
3993 printf("from: %s\n", got_object_commit_get_author(commit));
3994 committer_time = got_object_commit_get_committer_time(commit);
3995 datestr = get_datestr(&committer_time, datebuf);
3996 if (datestr)
3997 printf("date: %s UTC\n", datestr);
3998 author = got_object_commit_get_author(commit);
3999 committer = got_object_commit_get_committer(commit);
4000 if (strcmp(author, committer) != 0)
4001 printf("via: %s\n", committer);
4002 if (got_object_commit_get_nparents(commit) > 1) {
4003 const struct got_object_id_queue *parent_ids;
4004 struct got_object_qid *qid;
4005 int n = 1;
4006 parent_ids = got_object_commit_get_parent_ids(commit);
4007 STAILQ_FOREACH(qid, parent_ids, entry) {
4008 err = got_object_id_str(&id_str, &qid->id);
4009 if (err)
4010 goto done;
4011 printf("parent %d: %s\n", n++, id_str);
4012 free(id_str);
4013 id_str = NULL;
4017 err = got_object_commit_get_logmsg(&logmsg0, commit);
4018 if (err)
4019 goto done;
4021 logmsg = logmsg0;
4022 do {
4023 line = strsep(&logmsg, "\n");
4024 if (line)
4025 printf(" %s\n", line);
4026 } while (line);
4027 free(logmsg0);
4029 if (changed_paths) {
4030 struct got_pathlist_entry *pe;
4031 TAILQ_FOREACH(pe, changed_paths, entry) {
4032 struct got_diff_changed_path *cp = pe->data;
4033 printf(" %c %s\n", cp->status, pe->path);
4035 printf("\n");
4037 if (show_patch) {
4038 err = print_patch(commit, id, path, diff_context, repo, stdout);
4039 if (err == 0)
4040 printf("\n");
4043 if (fflush(stdout) != 0 && err == NULL)
4044 err = got_error_from_errno("fflush");
4045 done:
4046 free(id_str);
4047 free(refs_str);
4048 return err;
4051 static const struct got_error *
4052 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4053 struct got_repository *repo, const char *path, int show_changed_paths,
4054 int show_patch, const char *search_pattern, int diff_context, int limit,
4055 int log_branches, int reverse_display_order,
4056 struct got_reflist_object_id_map *refs_idmap, int one_line,
4057 FILE *tmpfile)
4059 const struct got_error *err;
4060 struct got_commit_graph *graph;
4061 regex_t regex;
4062 int have_match;
4063 struct got_object_id_queue reversed_commits;
4064 struct got_object_qid *qid;
4065 struct got_commit_object *commit;
4066 struct got_pathlist_head changed_paths;
4067 struct got_pathlist_entry *pe;
4069 STAILQ_INIT(&reversed_commits);
4070 TAILQ_INIT(&changed_paths);
4072 if (search_pattern && regcomp(&regex, search_pattern,
4073 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4074 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4076 err = got_commit_graph_open(&graph, path, !log_branches);
4077 if (err)
4078 return err;
4079 err = got_commit_graph_iter_start(graph, root_id, repo,
4080 check_cancelled, NULL);
4081 if (err)
4082 goto done;
4083 for (;;) {
4084 struct got_object_id *id;
4086 if (sigint_received || sigpipe_received)
4087 break;
4089 err = got_commit_graph_iter_next(&id, graph, repo,
4090 check_cancelled, NULL);
4091 if (err) {
4092 if (err->code == GOT_ERR_ITER_COMPLETED)
4093 err = NULL;
4094 break;
4096 if (id == NULL)
4097 break;
4099 err = got_object_open_as_commit(&commit, repo, id);
4100 if (err)
4101 break;
4103 if (show_changed_paths && !reverse_display_order) {
4104 err = get_changed_paths(&changed_paths, commit, repo);
4105 if (err)
4106 break;
4109 if (search_pattern) {
4110 err = match_commit(&have_match, id, commit, &regex);
4111 if (err) {
4112 got_object_commit_close(commit);
4113 break;
4115 if (have_match == 0 && show_changed_paths)
4116 match_changed_paths(&have_match,
4117 &changed_paths, &regex);
4118 if (have_match == 0 && show_patch) {
4119 err = match_patch(&have_match, commit, id,
4120 path, diff_context, repo, &regex,
4121 tmpfile);
4122 if (err)
4123 break;
4125 if (have_match == 0) {
4126 got_object_commit_close(commit);
4127 TAILQ_FOREACH(pe, &changed_paths, entry) {
4128 free((char *)pe->path);
4129 free(pe->data);
4131 got_pathlist_free(&changed_paths);
4132 continue;
4136 if (reverse_display_order) {
4137 err = got_object_qid_alloc(&qid, id);
4138 if (err)
4139 break;
4140 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4141 got_object_commit_close(commit);
4142 } else {
4143 if (one_line)
4144 err = print_commit_oneline(commit, id,
4145 repo, refs_idmap);
4146 else
4147 err = print_commit(commit, id, repo, path,
4148 show_changed_paths ? &changed_paths : NULL,
4149 show_patch, diff_context, refs_idmap, NULL);
4150 got_object_commit_close(commit);
4151 if (err)
4152 break;
4154 if ((limit && --limit == 0) ||
4155 (end_id && got_object_id_cmp(id, end_id) == 0))
4156 break;
4158 TAILQ_FOREACH(pe, &changed_paths, entry) {
4159 free((char *)pe->path);
4160 free(pe->data);
4162 got_pathlist_free(&changed_paths);
4164 if (reverse_display_order) {
4165 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4166 err = got_object_open_as_commit(&commit, repo,
4167 &qid->id);
4168 if (err)
4169 break;
4170 if (show_changed_paths) {
4171 err = get_changed_paths(&changed_paths,
4172 commit, repo);
4173 if (err)
4174 break;
4176 if (one_line)
4177 err = print_commit_oneline(commit, &qid->id,
4178 repo, refs_idmap);
4179 else
4180 err = print_commit(commit, &qid->id, repo, path,
4181 show_changed_paths ? &changed_paths : NULL,
4182 show_patch, diff_context, refs_idmap, NULL);
4183 got_object_commit_close(commit);
4184 if (err)
4185 break;
4186 TAILQ_FOREACH(pe, &changed_paths, entry) {
4187 free((char *)pe->path);
4188 free(pe->data);
4190 got_pathlist_free(&changed_paths);
4193 done:
4194 while (!STAILQ_EMPTY(&reversed_commits)) {
4195 qid = STAILQ_FIRST(&reversed_commits);
4196 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4197 got_object_qid_free(qid);
4199 TAILQ_FOREACH(pe, &changed_paths, entry) {
4200 free((char *)pe->path);
4201 free(pe->data);
4203 got_pathlist_free(&changed_paths);
4204 if (search_pattern)
4205 regfree(&regex);
4206 got_commit_graph_close(graph);
4207 return err;
4210 __dead static void
4211 usage_log(void)
4213 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4214 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4215 "[-r repository-path] [-R] [path]\n", getprogname());
4216 exit(1);
4219 static int
4220 get_default_log_limit(void)
4222 const char *got_default_log_limit;
4223 long long n;
4224 const char *errstr;
4226 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4227 if (got_default_log_limit == NULL)
4228 return 0;
4229 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4230 if (errstr != NULL)
4231 return 0;
4232 return n;
4235 static const struct got_error *
4236 cmd_log(int argc, char *argv[])
4238 const struct got_error *error;
4239 struct got_repository *repo = NULL;
4240 struct got_worktree *worktree = NULL;
4241 struct got_object_id *start_id = NULL, *end_id = NULL;
4242 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4243 const char *start_commit = NULL, *end_commit = NULL;
4244 const char *search_pattern = NULL;
4245 int diff_context = -1, ch;
4246 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4247 int reverse_display_order = 0, one_line = 0;
4248 const char *errstr;
4249 struct got_reflist_head refs;
4250 struct got_reflist_object_id_map *refs_idmap = NULL;
4251 FILE *tmpfile = NULL;
4253 TAILQ_INIT(&refs);
4255 #ifndef PROFILE
4256 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4257 NULL)
4258 == -1)
4259 err(1, "pledge");
4260 #endif
4262 limit = get_default_log_limit();
4264 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4265 switch (ch) {
4266 case 'p':
4267 show_patch = 1;
4268 break;
4269 case 'P':
4270 show_changed_paths = 1;
4271 break;
4272 case 'c':
4273 start_commit = optarg;
4274 break;
4275 case 'C':
4276 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4277 &errstr);
4278 if (errstr != NULL)
4279 errx(1, "number of context lines is %s: %s",
4280 errstr, optarg);
4281 break;
4282 case 'l':
4283 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4284 if (errstr != NULL)
4285 errx(1, "number of commits is %s: %s",
4286 errstr, optarg);
4287 break;
4288 case 'b':
4289 log_branches = 1;
4290 break;
4291 case 'r':
4292 repo_path = realpath(optarg, NULL);
4293 if (repo_path == NULL)
4294 return got_error_from_errno2("realpath",
4295 optarg);
4296 got_path_strip_trailing_slashes(repo_path);
4297 break;
4298 case 'R':
4299 reverse_display_order = 1;
4300 break;
4301 case 's':
4302 one_line = 1;
4303 break;
4304 case 'S':
4305 search_pattern = optarg;
4306 break;
4307 case 'x':
4308 end_commit = optarg;
4309 break;
4310 default:
4311 usage_log();
4312 /* NOTREACHED */
4316 argc -= optind;
4317 argv += optind;
4319 if (diff_context == -1)
4320 diff_context = 3;
4321 else if (!show_patch)
4322 errx(1, "-C requires -p");
4324 if (one_line && (show_patch || show_changed_paths))
4325 errx(1, "cannot use -s with -p or -P");
4327 cwd = getcwd(NULL, 0);
4328 if (cwd == NULL) {
4329 error = got_error_from_errno("getcwd");
4330 goto done;
4333 if (repo_path == NULL) {
4334 error = got_worktree_open(&worktree, cwd);
4335 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4336 goto done;
4337 error = NULL;
4340 if (argc == 1) {
4341 if (worktree) {
4342 error = got_worktree_resolve_path(&path, worktree,
4343 argv[0]);
4344 if (error)
4345 goto done;
4346 } else {
4347 path = strdup(argv[0]);
4348 if (path == NULL) {
4349 error = got_error_from_errno("strdup");
4350 goto done;
4353 } else if (argc != 0)
4354 usage_log();
4356 if (repo_path == NULL) {
4357 repo_path = worktree ?
4358 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4360 if (repo_path == NULL) {
4361 error = got_error_from_errno("strdup");
4362 goto done;
4365 error = got_repo_open(&repo, repo_path, NULL);
4366 if (error != NULL)
4367 goto done;
4369 error = apply_unveil(got_repo_get_path(repo), 1,
4370 worktree ? got_worktree_get_root_path(worktree) : NULL);
4371 if (error)
4372 goto done;
4374 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4375 if (error)
4376 goto done;
4378 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4379 if (error)
4380 goto done;
4382 if (start_commit == NULL) {
4383 struct got_reference *head_ref;
4384 struct got_commit_object *commit = NULL;
4385 error = got_ref_open(&head_ref, repo,
4386 worktree ? got_worktree_get_head_ref_name(worktree)
4387 : GOT_REF_HEAD, 0);
4388 if (error != NULL)
4389 goto done;
4390 error = got_ref_resolve(&start_id, repo, head_ref);
4391 got_ref_close(head_ref);
4392 if (error != NULL)
4393 goto done;
4394 error = got_object_open_as_commit(&commit, repo,
4395 start_id);
4396 if (error != NULL)
4397 goto done;
4398 got_object_commit_close(commit);
4399 } else {
4400 error = got_repo_match_object_id(&start_id, NULL,
4401 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4402 if (error != NULL)
4403 goto done;
4405 if (end_commit != NULL) {
4406 error = got_repo_match_object_id(&end_id, NULL,
4407 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4408 if (error != NULL)
4409 goto done;
4412 if (worktree) {
4414 * If a path was specified on the command line it was resolved
4415 * to a path in the work tree above. Prepend the work tree's
4416 * path prefix to obtain the corresponding in-repository path.
4418 if (path) {
4419 const char *prefix;
4420 prefix = got_worktree_get_path_prefix(worktree);
4421 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4422 (path[0] != '\0') ? "/" : "", path) == -1) {
4423 error = got_error_from_errno("asprintf");
4424 goto done;
4427 } else
4428 error = got_repo_map_path(&in_repo_path, repo,
4429 path ? path : "");
4430 if (error != NULL)
4431 goto done;
4432 if (in_repo_path) {
4433 free(path);
4434 path = in_repo_path;
4437 if (worktree) {
4438 /* Release work tree lock. */
4439 got_worktree_close(worktree);
4440 worktree = NULL;
4443 if (search_pattern && show_patch) {
4444 tmpfile = got_opentemp();
4445 if (tmpfile == NULL) {
4446 error = got_error_from_errno("got_opentemp");
4447 goto done;
4451 error = print_commits(start_id, end_id, repo, path ? path : "",
4452 show_changed_paths, show_patch, search_pattern, diff_context,
4453 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4454 tmpfile);
4455 done:
4456 free(path);
4457 free(repo_path);
4458 free(cwd);
4459 if (worktree)
4460 got_worktree_close(worktree);
4461 if (repo) {
4462 const struct got_error *close_err = got_repo_close(repo);
4463 if (error == NULL)
4464 error = close_err;
4466 if (refs_idmap)
4467 got_reflist_object_id_map_free(refs_idmap);
4468 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4469 error = got_error_from_errno("fclose");
4470 got_ref_list_free(&refs);
4471 return error;
4474 __dead static void
4475 usage_diff(void)
4477 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4478 "[-r repository-path] [-s] [-w] [-P] "
4479 "[object1 object2 | path ...]\n", getprogname());
4480 exit(1);
4483 struct print_diff_arg {
4484 struct got_repository *repo;
4485 struct got_worktree *worktree;
4486 int diff_context;
4487 const char *id_str;
4488 int header_shown;
4489 int diff_staged;
4490 int ignore_whitespace;
4491 int force_text_diff;
4495 * Create a file which contains the target path of a symlink so we can feed
4496 * it as content to the diff engine.
4498 static const struct got_error *
4499 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4500 const char *abspath)
4502 const struct got_error *err = NULL;
4503 char target_path[PATH_MAX];
4504 ssize_t target_len, outlen;
4506 *fd = -1;
4508 if (dirfd != -1) {
4509 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4510 if (target_len == -1)
4511 return got_error_from_errno2("readlinkat", abspath);
4512 } else {
4513 target_len = readlink(abspath, target_path, PATH_MAX);
4514 if (target_len == -1)
4515 return got_error_from_errno2("readlink", abspath);
4518 *fd = got_opentempfd();
4519 if (*fd == -1)
4520 return got_error_from_errno("got_opentempfd");
4522 outlen = write(*fd, target_path, target_len);
4523 if (outlen == -1) {
4524 err = got_error_from_errno("got_opentempfd");
4525 goto done;
4528 if (lseek(*fd, 0, SEEK_SET) == -1) {
4529 err = got_error_from_errno2("lseek", abspath);
4530 goto done;
4532 done:
4533 if (err) {
4534 close(*fd);
4535 *fd = -1;
4537 return err;
4540 static const struct got_error *
4541 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4542 const char *path, struct got_object_id *blob_id,
4543 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4544 int dirfd, const char *de_name)
4546 struct print_diff_arg *a = arg;
4547 const struct got_error *err = NULL;
4548 struct got_blob_object *blob1 = NULL;
4549 int fd = -1;
4550 FILE *f1 = NULL, *f2 = NULL;
4551 char *abspath = NULL, *label1 = NULL;
4552 struct stat sb;
4553 off_t size1 = 0;
4555 if (a->diff_staged) {
4556 if (staged_status != GOT_STATUS_MODIFY &&
4557 staged_status != GOT_STATUS_ADD &&
4558 staged_status != GOT_STATUS_DELETE)
4559 return NULL;
4560 } else {
4561 if (staged_status == GOT_STATUS_DELETE)
4562 return NULL;
4563 if (status == GOT_STATUS_NONEXISTENT)
4564 return got_error_set_errno(ENOENT, path);
4565 if (status != GOT_STATUS_MODIFY &&
4566 status != GOT_STATUS_ADD &&
4567 status != GOT_STATUS_DELETE &&
4568 status != GOT_STATUS_CONFLICT)
4569 return NULL;
4572 if (!a->header_shown) {
4573 printf("diff %s %s%s\n", a->id_str,
4574 got_worktree_get_root_path(a->worktree),
4575 a->diff_staged ? " (staged changes)" : "");
4576 a->header_shown = 1;
4579 if (a->diff_staged) {
4580 const char *label1 = NULL, *label2 = NULL;
4581 switch (staged_status) {
4582 case GOT_STATUS_MODIFY:
4583 label1 = path;
4584 label2 = path;
4585 break;
4586 case GOT_STATUS_ADD:
4587 label2 = path;
4588 break;
4589 case GOT_STATUS_DELETE:
4590 label1 = path;
4591 break;
4592 default:
4593 return got_error(GOT_ERR_FILE_STATUS);
4595 f1 = got_opentemp();
4596 if (f1 == NULL) {
4597 err = got_error_from_errno("got_opentemp");
4598 goto done;
4600 f2 = got_opentemp();
4601 if (f2 == NULL) {
4602 err = got_error_from_errno("got_opentemp");
4603 goto done;
4605 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4606 blob_id, staged_blob_id, label1, label2, a->diff_context,
4607 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4608 goto done;
4611 if (staged_status == GOT_STATUS_ADD ||
4612 staged_status == GOT_STATUS_MODIFY) {
4613 char *id_str;
4614 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4615 8192);
4616 if (err)
4617 goto done;
4618 err = got_object_id_str(&id_str, staged_blob_id);
4619 if (err)
4620 goto done;
4621 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4622 err = got_error_from_errno("asprintf");
4623 free(id_str);
4624 goto done;
4626 free(id_str);
4627 } else if (status != GOT_STATUS_ADD) {
4628 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4629 if (err)
4630 goto done;
4633 if (status != GOT_STATUS_DELETE) {
4634 if (asprintf(&abspath, "%s/%s",
4635 got_worktree_get_root_path(a->worktree), path) == -1) {
4636 err = got_error_from_errno("asprintf");
4637 goto done;
4640 if (dirfd != -1) {
4641 fd = openat(dirfd, de_name,
4642 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4643 if (fd == -1) {
4644 if (!got_err_open_nofollow_on_symlink()) {
4645 err = got_error_from_errno2("openat",
4646 abspath);
4647 goto done;
4649 err = get_symlink_target_file(&fd, dirfd,
4650 de_name, abspath);
4651 if (err)
4652 goto done;
4654 } else {
4655 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4656 if (fd == -1) {
4657 if (!got_err_open_nofollow_on_symlink()) {
4658 err = got_error_from_errno2("open",
4659 abspath);
4660 goto done;
4662 err = get_symlink_target_file(&fd, dirfd,
4663 de_name, abspath);
4664 if (err)
4665 goto done;
4668 if (fstat(fd, &sb) == -1) {
4669 err = got_error_from_errno2("fstat", abspath);
4670 goto done;
4672 f2 = fdopen(fd, "r");
4673 if (f2 == NULL) {
4674 err = got_error_from_errno2("fdopen", abspath);
4675 goto done;
4677 fd = -1;
4678 } else
4679 sb.st_size = 0;
4681 if (blob1) {
4682 f1 = got_opentemp();
4683 if (f1 == NULL) {
4684 err = got_error_from_errno("got_opentemp");
4685 goto done;
4687 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4688 blob1);
4689 if (err)
4690 goto done;
4693 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4694 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4695 stdout);
4696 done:
4697 if (blob1)
4698 got_object_blob_close(blob1);
4699 if (f1 && fclose(f1) == EOF && err == NULL)
4700 err = got_error_from_errno("fclose");
4701 if (f2 && fclose(f2) == EOF && err == NULL)
4702 err = got_error_from_errno("fclose");
4703 if (fd != -1 && close(fd) == -1 && err == NULL)
4704 err = got_error_from_errno("close");
4705 free(abspath);
4706 return err;
4709 static const struct got_error *
4710 cmd_diff(int argc, char *argv[])
4712 const struct got_error *error;
4713 struct got_repository *repo = NULL;
4714 struct got_worktree *worktree = NULL;
4715 char *cwd = NULL, *repo_path = NULL;
4716 const char *commit_args[2] = { NULL, NULL };
4717 int ncommit_args = 0;
4718 struct got_object_id *ids[2] = { NULL, NULL };
4719 char *labels[2] = { NULL, NULL };
4720 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4721 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4722 int force_text_diff = 0, force_path = 0, rflag = 0;
4723 const char *errstr;
4724 struct got_reflist_head refs;
4725 struct got_pathlist_head paths;
4726 struct got_pathlist_entry *pe;
4727 FILE *f1 = NULL, *f2 = NULL;
4729 TAILQ_INIT(&refs);
4730 TAILQ_INIT(&paths);
4732 #ifndef PROFILE
4733 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4734 NULL) == -1)
4735 err(1, "pledge");
4736 #endif
4738 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4739 switch (ch) {
4740 case 'a':
4741 force_text_diff = 1;
4742 break;
4743 case 'c':
4744 if (ncommit_args >= 2)
4745 errx(1, "too many -c options used");
4746 commit_args[ncommit_args++] = optarg;
4747 break;
4748 case 'C':
4749 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4750 &errstr);
4751 if (errstr != NULL)
4752 errx(1, "number of context lines is %s: %s",
4753 errstr, optarg);
4754 break;
4755 case 'r':
4756 repo_path = realpath(optarg, NULL);
4757 if (repo_path == NULL)
4758 return got_error_from_errno2("realpath",
4759 optarg);
4760 got_path_strip_trailing_slashes(repo_path);
4761 rflag = 1;
4762 break;
4763 case 's':
4764 diff_staged = 1;
4765 break;
4766 case 'w':
4767 ignore_whitespace = 1;
4768 break;
4769 case 'P':
4770 force_path = 1;
4771 break;
4772 default:
4773 usage_diff();
4774 /* NOTREACHED */
4778 argc -= optind;
4779 argv += optind;
4781 cwd = getcwd(NULL, 0);
4782 if (cwd == NULL) {
4783 error = got_error_from_errno("getcwd");
4784 goto done;
4787 if (repo_path == NULL) {
4788 error = got_worktree_open(&worktree, cwd);
4789 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4790 goto done;
4791 else
4792 error = NULL;
4793 if (worktree) {
4794 repo_path =
4795 strdup(got_worktree_get_repo_path(worktree));
4796 if (repo_path == NULL) {
4797 error = got_error_from_errno("strdup");
4798 goto done;
4800 } else {
4801 repo_path = strdup(cwd);
4802 if (repo_path == NULL) {
4803 error = got_error_from_errno("strdup");
4804 goto done;
4809 error = got_repo_open(&repo, repo_path, NULL);
4810 free(repo_path);
4811 if (error != NULL)
4812 goto done;
4814 if (rflag || worktree == NULL || ncommit_args > 0) {
4815 if (force_path) {
4816 error = got_error_msg(GOT_ERR_NOT_IMPL,
4817 "-P option can only be used when diffing "
4818 "a work tree");
4819 goto done;
4821 if (diff_staged) {
4822 error = got_error_msg(GOT_ERR_NOT_IMPL,
4823 "-s option can only be used when diffing "
4824 "a work tree");
4825 goto done;
4829 error = apply_unveil(got_repo_get_path(repo), 1,
4830 worktree ? got_worktree_get_root_path(worktree) : NULL);
4831 if (error)
4832 goto done;
4834 if ((!force_path && argc == 2) || ncommit_args > 0) {
4835 int obj_type = (ncommit_args > 0 ?
4836 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4837 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4838 NULL);
4839 if (error)
4840 goto done;
4841 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4842 const char *arg;
4843 if (ncommit_args > 0)
4844 arg = commit_args[i];
4845 else
4846 arg = argv[i];
4847 error = got_repo_match_object_id(&ids[i], &labels[i],
4848 arg, obj_type, &refs, repo);
4849 if (error) {
4850 if (error->code != GOT_ERR_NOT_REF &&
4851 error->code != GOT_ERR_NO_OBJ)
4852 goto done;
4853 if (ncommit_args > 0)
4854 goto done;
4855 error = NULL;
4856 break;
4861 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4862 struct print_diff_arg arg;
4863 char *id_str;
4865 if (worktree == NULL) {
4866 if (argc == 2 && ids[0] == NULL) {
4867 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4868 goto done;
4869 } else if (argc == 2 && ids[1] == NULL) {
4870 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4871 goto done;
4872 } else if (argc > 0) {
4873 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4874 "%s", "specified paths cannot be resolved");
4875 goto done;
4876 } else {
4877 error = got_error(GOT_ERR_NOT_WORKTREE);
4878 goto done;
4882 error = get_worktree_paths_from_argv(&paths, argc, argv,
4883 worktree);
4884 if (error)
4885 goto done;
4887 error = got_object_id_str(&id_str,
4888 got_worktree_get_base_commit_id(worktree));
4889 if (error)
4890 goto done;
4891 arg.repo = repo;
4892 arg.worktree = worktree;
4893 arg.diff_context = diff_context;
4894 arg.id_str = id_str;
4895 arg.header_shown = 0;
4896 arg.diff_staged = diff_staged;
4897 arg.ignore_whitespace = ignore_whitespace;
4898 arg.force_text_diff = force_text_diff;
4900 error = got_worktree_status(worktree, &paths, repo, 0,
4901 print_diff, &arg, check_cancelled, NULL);
4902 free(id_str);
4903 goto done;
4906 if (ncommit_args == 1) {
4907 struct got_commit_object *commit;
4908 error = got_object_open_as_commit(&commit, repo, ids[0]);
4909 if (error)
4910 goto done;
4912 labels[1] = labels[0];
4913 ids[1] = ids[0];
4914 if (got_object_commit_get_nparents(commit) > 0) {
4915 const struct got_object_id_queue *pids;
4916 struct got_object_qid *pid;
4917 pids = got_object_commit_get_parent_ids(commit);
4918 pid = STAILQ_FIRST(pids);
4919 ids[0] = got_object_id_dup(&pid->id);
4920 if (ids[0] == NULL) {
4921 error = got_error_from_errno(
4922 "got_object_id_dup");
4923 got_object_commit_close(commit);
4924 goto done;
4926 error = got_object_id_str(&labels[0], ids[0]);
4927 if (error) {
4928 got_object_commit_close(commit);
4929 goto done;
4931 } else {
4932 ids[0] = NULL;
4933 labels[0] = strdup("/dev/null");
4934 if (labels[0] == NULL) {
4935 error = got_error_from_errno("strdup");
4936 got_object_commit_close(commit);
4937 goto done;
4941 got_object_commit_close(commit);
4944 if (ncommit_args == 0 && argc > 2) {
4945 error = got_error_msg(GOT_ERR_BAD_PATH,
4946 "path arguments cannot be used when diffing two objects");
4947 goto done;
4950 if (ids[0]) {
4951 error = got_object_get_type(&type1, repo, ids[0]);
4952 if (error)
4953 goto done;
4956 error = got_object_get_type(&type2, repo, ids[1]);
4957 if (error)
4958 goto done;
4959 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4960 error = got_error(GOT_ERR_OBJ_TYPE);
4961 goto done;
4963 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4964 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4965 "path arguments cannot be used when diffing blobs");
4966 goto done;
4969 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4970 char *in_repo_path;
4971 struct got_pathlist_entry *new;
4972 if (worktree) {
4973 const char *prefix;
4974 char *p;
4975 error = got_worktree_resolve_path(&p, worktree,
4976 argv[i]);
4977 if (error)
4978 goto done;
4979 prefix = got_worktree_get_path_prefix(worktree);
4980 while (prefix[0] == '/')
4981 prefix++;
4982 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4983 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4984 p) == -1) {
4985 error = got_error_from_errno("asprintf");
4986 free(p);
4987 goto done;
4989 free(p);
4990 } else {
4991 char *mapped_path, *s;
4992 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4993 if (error)
4994 goto done;
4995 s = mapped_path;
4996 while (s[0] == '/')
4997 s++;
4998 in_repo_path = strdup(s);
4999 if (in_repo_path == NULL) {
5000 error = got_error_from_errno("asprintf");
5001 free(mapped_path);
5002 goto done;
5004 free(mapped_path);
5007 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5008 if (error || new == NULL /* duplicate */)
5009 free(in_repo_path);
5010 if (error)
5011 goto done;
5014 if (worktree) {
5015 /* Release work tree lock. */
5016 got_worktree_close(worktree);
5017 worktree = NULL;
5020 f1 = got_opentemp();
5021 if (f1 == NULL) {
5022 error = got_error_from_errno("got_opentemp");
5023 goto done;
5026 f2 = got_opentemp();
5027 if (f2 == NULL) {
5028 error = got_error_from_errno("got_opentemp");
5029 goto done;
5032 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5033 case GOT_OBJ_TYPE_BLOB:
5034 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5035 ids[0], ids[1], NULL, NULL, diff_context,
5036 ignore_whitespace, force_text_diff, repo, stdout);
5037 break;
5038 case GOT_OBJ_TYPE_TREE:
5039 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5040 ids[0], ids[1], &paths, "", "", diff_context,
5041 ignore_whitespace, force_text_diff, repo, stdout);
5042 break;
5043 case GOT_OBJ_TYPE_COMMIT:
5044 printf("diff %s %s\n", labels[0], labels[1]);
5045 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5046 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5047 force_text_diff, repo, stdout);
5048 break;
5049 default:
5050 error = got_error(GOT_ERR_OBJ_TYPE);
5052 done:
5053 free(labels[0]);
5054 free(labels[1]);
5055 free(ids[0]);
5056 free(ids[1]);
5057 if (worktree)
5058 got_worktree_close(worktree);
5059 if (repo) {
5060 const struct got_error *close_err = got_repo_close(repo);
5061 if (error == NULL)
5062 error = close_err;
5064 TAILQ_FOREACH(pe, &paths, entry)
5065 free((char *)pe->path);
5066 got_pathlist_free(&paths);
5067 got_ref_list_free(&refs);
5068 if (f1 && fclose(f1) == EOF && error == NULL)
5069 error = got_error_from_errno("fclose");
5070 if (f2 && fclose(f2) == EOF && error == NULL)
5071 error = got_error_from_errno("fclose");
5072 return error;
5075 __dead static void
5076 usage_blame(void)
5078 fprintf(stderr,
5079 "usage: %s blame [-c commit] [-r repository-path] path\n",
5080 getprogname());
5081 exit(1);
5084 struct blame_line {
5085 int annotated;
5086 char *id_str;
5087 char *committer;
5088 char datebuf[11]; /* YYYY-MM-DD + NUL */
5091 struct blame_cb_args {
5092 struct blame_line *lines;
5093 int nlines;
5094 int nlines_prec;
5095 int lineno_cur;
5096 off_t *line_offsets;
5097 FILE *f;
5098 struct got_repository *repo;
5101 static const struct got_error *
5102 blame_cb(void *arg, int nlines, int lineno,
5103 struct got_commit_object *commit, struct got_object_id *id)
5105 const struct got_error *err = NULL;
5106 struct blame_cb_args *a = arg;
5107 struct blame_line *bline;
5108 char *line = NULL;
5109 size_t linesize = 0;
5110 off_t offset;
5111 struct tm tm;
5112 time_t committer_time;
5114 if (nlines != a->nlines ||
5115 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5116 return got_error(GOT_ERR_RANGE);
5118 if (sigint_received)
5119 return got_error(GOT_ERR_ITER_COMPLETED);
5121 if (lineno == -1)
5122 return NULL; /* no change in this commit */
5124 /* Annotate this line. */
5125 bline = &a->lines[lineno - 1];
5126 if (bline->annotated)
5127 return NULL;
5128 err = got_object_id_str(&bline->id_str, id);
5129 if (err)
5130 return err;
5132 bline->committer = strdup(got_object_commit_get_committer(commit));
5133 if (bline->committer == NULL) {
5134 err = got_error_from_errno("strdup");
5135 goto done;
5138 committer_time = got_object_commit_get_committer_time(commit);
5139 if (gmtime_r(&committer_time, &tm) == NULL)
5140 return got_error_from_errno("gmtime_r");
5141 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5142 &tm) == 0) {
5143 err = got_error(GOT_ERR_NO_SPACE);
5144 goto done;
5146 bline->annotated = 1;
5148 /* Print lines annotated so far. */
5149 bline = &a->lines[a->lineno_cur - 1];
5150 if (!bline->annotated)
5151 goto done;
5153 offset = a->line_offsets[a->lineno_cur - 1];
5154 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5155 err = got_error_from_errno("fseeko");
5156 goto done;
5159 while (bline->annotated) {
5160 char *smallerthan, *at, *nl, *committer;
5161 size_t len;
5163 if (getline(&line, &linesize, a->f) == -1) {
5164 if (ferror(a->f))
5165 err = got_error_from_errno("getline");
5166 break;
5169 committer = bline->committer;
5170 smallerthan = strchr(committer, '<');
5171 if (smallerthan && smallerthan[1] != '\0')
5172 committer = smallerthan + 1;
5173 at = strchr(committer, '@');
5174 if (at)
5175 *at = '\0';
5176 len = strlen(committer);
5177 if (len >= 9)
5178 committer[8] = '\0';
5180 nl = strchr(line, '\n');
5181 if (nl)
5182 *nl = '\0';
5183 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5184 bline->id_str, bline->datebuf, committer, line);
5186 a->lineno_cur++;
5187 bline = &a->lines[a->lineno_cur - 1];
5189 done:
5190 free(line);
5191 return err;
5194 static const struct got_error *
5195 cmd_blame(int argc, char *argv[])
5197 const struct got_error *error;
5198 struct got_repository *repo = NULL;
5199 struct got_worktree *worktree = NULL;
5200 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5201 char *link_target = NULL;
5202 struct got_object_id *obj_id = NULL;
5203 struct got_object_id *commit_id = NULL;
5204 struct got_commit_object *commit = NULL;
5205 struct got_blob_object *blob = NULL;
5206 char *commit_id_str = NULL;
5207 struct blame_cb_args bca;
5208 int ch, obj_type, i;
5209 off_t filesize;
5211 memset(&bca, 0, sizeof(bca));
5213 #ifndef PROFILE
5214 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5215 NULL) == -1)
5216 err(1, "pledge");
5217 #endif
5219 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5220 switch (ch) {
5221 case 'c':
5222 commit_id_str = optarg;
5223 break;
5224 case 'r':
5225 repo_path = realpath(optarg, NULL);
5226 if (repo_path == NULL)
5227 return got_error_from_errno2("realpath",
5228 optarg);
5229 got_path_strip_trailing_slashes(repo_path);
5230 break;
5231 default:
5232 usage_blame();
5233 /* NOTREACHED */
5237 argc -= optind;
5238 argv += optind;
5240 if (argc == 1)
5241 path = argv[0];
5242 else
5243 usage_blame();
5245 cwd = getcwd(NULL, 0);
5246 if (cwd == NULL) {
5247 error = got_error_from_errno("getcwd");
5248 goto done;
5250 if (repo_path == NULL) {
5251 error = got_worktree_open(&worktree, cwd);
5252 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5253 goto done;
5254 else
5255 error = NULL;
5256 if (worktree) {
5257 repo_path =
5258 strdup(got_worktree_get_repo_path(worktree));
5259 if (repo_path == NULL) {
5260 error = got_error_from_errno("strdup");
5261 if (error)
5262 goto done;
5264 } else {
5265 repo_path = strdup(cwd);
5266 if (repo_path == NULL) {
5267 error = got_error_from_errno("strdup");
5268 goto done;
5273 error = got_repo_open(&repo, repo_path, NULL);
5274 if (error != NULL)
5275 goto done;
5277 if (worktree) {
5278 const char *prefix = got_worktree_get_path_prefix(worktree);
5279 char *p;
5281 error = got_worktree_resolve_path(&p, worktree, path);
5282 if (error)
5283 goto done;
5284 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5285 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5286 p) == -1) {
5287 error = got_error_from_errno("asprintf");
5288 free(p);
5289 goto done;
5291 free(p);
5292 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5293 } else {
5294 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5295 if (error)
5296 goto done;
5297 error = got_repo_map_path(&in_repo_path, repo, path);
5299 if (error)
5300 goto done;
5302 if (commit_id_str == NULL) {
5303 struct got_reference *head_ref;
5304 error = got_ref_open(&head_ref, repo, worktree ?
5305 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5306 if (error != NULL)
5307 goto done;
5308 error = got_ref_resolve(&commit_id, repo, head_ref);
5309 got_ref_close(head_ref);
5310 if (error != NULL)
5311 goto done;
5312 } else {
5313 struct got_reflist_head refs;
5314 TAILQ_INIT(&refs);
5315 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5316 NULL);
5317 if (error)
5318 goto done;
5319 error = got_repo_match_object_id(&commit_id, NULL,
5320 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5321 got_ref_list_free(&refs);
5322 if (error)
5323 goto done;
5326 if (worktree) {
5327 /* Release work tree lock. */
5328 got_worktree_close(worktree);
5329 worktree = NULL;
5332 error = got_object_open_as_commit(&commit, repo, commit_id);
5333 if (error)
5334 goto done;
5336 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5337 commit, repo);
5338 if (error)
5339 goto done;
5341 error = got_object_id_by_path(&obj_id, repo, commit,
5342 link_target ? link_target : in_repo_path);
5343 if (error)
5344 goto done;
5346 error = got_object_get_type(&obj_type, repo, obj_id);
5347 if (error)
5348 goto done;
5350 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5351 error = got_error_path(link_target ? link_target : in_repo_path,
5352 GOT_ERR_OBJ_TYPE);
5353 goto done;
5356 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5357 if (error)
5358 goto done;
5359 bca.f = got_opentemp();
5360 if (bca.f == NULL) {
5361 error = got_error_from_errno("got_opentemp");
5362 goto done;
5364 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5365 &bca.line_offsets, bca.f, blob);
5366 if (error || bca.nlines == 0)
5367 goto done;
5369 /* Don't include \n at EOF in the blame line count. */
5370 if (bca.line_offsets[bca.nlines - 1] == filesize)
5371 bca.nlines--;
5373 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5374 if (bca.lines == NULL) {
5375 error = got_error_from_errno("calloc");
5376 goto done;
5378 bca.lineno_cur = 1;
5379 bca.nlines_prec = 0;
5380 i = bca.nlines;
5381 while (i > 0) {
5382 i /= 10;
5383 bca.nlines_prec++;
5385 bca.repo = repo;
5387 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5388 repo, blame_cb, &bca, check_cancelled, NULL);
5389 done:
5390 free(in_repo_path);
5391 free(link_target);
5392 free(repo_path);
5393 free(cwd);
5394 free(commit_id);
5395 free(obj_id);
5396 if (commit)
5397 got_object_commit_close(commit);
5398 if (blob)
5399 got_object_blob_close(blob);
5400 if (worktree)
5401 got_worktree_close(worktree);
5402 if (repo) {
5403 const struct got_error *close_err = got_repo_close(repo);
5404 if (error == NULL)
5405 error = close_err;
5407 if (bca.lines) {
5408 for (i = 0; i < bca.nlines; i++) {
5409 struct blame_line *bline = &bca.lines[i];
5410 free(bline->id_str);
5411 free(bline->committer);
5413 free(bca.lines);
5415 free(bca.line_offsets);
5416 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5417 error = got_error_from_errno("fclose");
5418 return error;
5421 __dead static void
5422 usage_tree(void)
5424 fprintf(stderr,
5425 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5426 getprogname());
5427 exit(1);
5430 static const struct got_error *
5431 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5432 const char *root_path, struct got_repository *repo)
5434 const struct got_error *err = NULL;
5435 int is_root_path = (strcmp(path, root_path) == 0);
5436 const char *modestr = "";
5437 mode_t mode = got_tree_entry_get_mode(te);
5438 char *link_target = NULL;
5440 path += strlen(root_path);
5441 while (path[0] == '/')
5442 path++;
5444 if (got_object_tree_entry_is_submodule(te))
5445 modestr = "$";
5446 else if (S_ISLNK(mode)) {
5447 int i;
5449 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5450 if (err)
5451 return err;
5452 for (i = 0; i < strlen(link_target); i++) {
5453 if (!isprint((unsigned char)link_target[i]))
5454 link_target[i] = '?';
5457 modestr = "@";
5459 else if (S_ISDIR(mode))
5460 modestr = "/";
5461 else if (mode & S_IXUSR)
5462 modestr = "*";
5464 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5465 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5466 link_target ? " -> ": "", link_target ? link_target : "");
5468 free(link_target);
5469 return NULL;
5472 static const struct got_error *
5473 print_tree(const char *path, struct got_commit_object *commit,
5474 int show_ids, int recurse, const char *root_path,
5475 struct got_repository *repo)
5477 const struct got_error *err = NULL;
5478 struct got_object_id *tree_id = NULL;
5479 struct got_tree_object *tree = NULL;
5480 int nentries, i;
5482 err = got_object_id_by_path(&tree_id, repo, commit, path);
5483 if (err)
5484 goto done;
5486 err = got_object_open_as_tree(&tree, repo, tree_id);
5487 if (err)
5488 goto done;
5489 nentries = got_object_tree_get_nentries(tree);
5490 for (i = 0; i < nentries; i++) {
5491 struct got_tree_entry *te;
5492 char *id = NULL;
5494 if (sigint_received || sigpipe_received)
5495 break;
5497 te = got_object_tree_get_entry(tree, i);
5498 if (show_ids) {
5499 char *id_str;
5500 err = got_object_id_str(&id_str,
5501 got_tree_entry_get_id(te));
5502 if (err)
5503 goto done;
5504 if (asprintf(&id, "%s ", id_str) == -1) {
5505 err = got_error_from_errno("asprintf");
5506 free(id_str);
5507 goto done;
5509 free(id_str);
5511 err = print_entry(te, id, path, root_path, repo);
5512 free(id);
5513 if (err)
5514 goto done;
5516 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5517 char *child_path;
5518 if (asprintf(&child_path, "%s%s%s", path,
5519 path[0] == '/' && path[1] == '\0' ? "" : "/",
5520 got_tree_entry_get_name(te)) == -1) {
5521 err = got_error_from_errno("asprintf");
5522 goto done;
5524 err = print_tree(child_path, commit, show_ids, 1,
5525 root_path, repo);
5526 free(child_path);
5527 if (err)
5528 goto done;
5531 done:
5532 if (tree)
5533 got_object_tree_close(tree);
5534 free(tree_id);
5535 return err;
5538 static const struct got_error *
5539 cmd_tree(int argc, char *argv[])
5541 const struct got_error *error;
5542 struct got_repository *repo = NULL;
5543 struct got_worktree *worktree = NULL;
5544 const char *path, *refname = NULL;
5545 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5546 struct got_object_id *commit_id = NULL;
5547 struct got_commit_object *commit = NULL;
5548 char *commit_id_str = NULL;
5549 int show_ids = 0, recurse = 0;
5550 int ch;
5552 #ifndef PROFILE
5553 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5554 NULL) == -1)
5555 err(1, "pledge");
5556 #endif
5558 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5559 switch (ch) {
5560 case 'c':
5561 commit_id_str = optarg;
5562 break;
5563 case 'r':
5564 repo_path = realpath(optarg, NULL);
5565 if (repo_path == NULL)
5566 return got_error_from_errno2("realpath",
5567 optarg);
5568 got_path_strip_trailing_slashes(repo_path);
5569 break;
5570 case 'i':
5571 show_ids = 1;
5572 break;
5573 case 'R':
5574 recurse = 1;
5575 break;
5576 default:
5577 usage_tree();
5578 /* NOTREACHED */
5582 argc -= optind;
5583 argv += optind;
5585 if (argc == 1)
5586 path = argv[0];
5587 else if (argc > 1)
5588 usage_tree();
5589 else
5590 path = NULL;
5592 cwd = getcwd(NULL, 0);
5593 if (cwd == NULL) {
5594 error = got_error_from_errno("getcwd");
5595 goto done;
5597 if (repo_path == NULL) {
5598 error = got_worktree_open(&worktree, cwd);
5599 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5600 goto done;
5601 else
5602 error = NULL;
5603 if (worktree) {
5604 repo_path =
5605 strdup(got_worktree_get_repo_path(worktree));
5606 if (repo_path == NULL)
5607 error = got_error_from_errno("strdup");
5608 if (error)
5609 goto done;
5610 } else {
5611 repo_path = strdup(cwd);
5612 if (repo_path == NULL) {
5613 error = got_error_from_errno("strdup");
5614 goto done;
5619 error = got_repo_open(&repo, repo_path, NULL);
5620 if (error != NULL)
5621 goto done;
5623 if (worktree) {
5624 const char *prefix = got_worktree_get_path_prefix(worktree);
5625 char *p;
5627 if (path == NULL)
5628 path = "";
5629 error = got_worktree_resolve_path(&p, worktree, path);
5630 if (error)
5631 goto done;
5632 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5633 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5634 p) == -1) {
5635 error = got_error_from_errno("asprintf");
5636 free(p);
5637 goto done;
5639 free(p);
5640 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5641 if (error)
5642 goto done;
5643 } else {
5644 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5645 if (error)
5646 goto done;
5647 if (path == NULL)
5648 path = "/";
5649 error = got_repo_map_path(&in_repo_path, repo, path);
5650 if (error != NULL)
5651 goto done;
5654 if (commit_id_str == NULL) {
5655 struct got_reference *head_ref;
5656 if (worktree)
5657 refname = got_worktree_get_head_ref_name(worktree);
5658 else
5659 refname = GOT_REF_HEAD;
5660 error = got_ref_open(&head_ref, repo, refname, 0);
5661 if (error != NULL)
5662 goto done;
5663 error = got_ref_resolve(&commit_id, repo, head_ref);
5664 got_ref_close(head_ref);
5665 if (error != NULL)
5666 goto done;
5667 } else {
5668 struct got_reflist_head refs;
5669 TAILQ_INIT(&refs);
5670 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5671 NULL);
5672 if (error)
5673 goto done;
5674 error = got_repo_match_object_id(&commit_id, NULL,
5675 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5676 got_ref_list_free(&refs);
5677 if (error)
5678 goto done;
5681 if (worktree) {
5682 /* Release work tree lock. */
5683 got_worktree_close(worktree);
5684 worktree = NULL;
5687 error = got_object_open_as_commit(&commit, repo, commit_id);
5688 if (error)
5689 goto done;
5691 error = print_tree(in_repo_path, commit, show_ids, recurse,
5692 in_repo_path, repo);
5693 done:
5694 free(in_repo_path);
5695 free(repo_path);
5696 free(cwd);
5697 free(commit_id);
5698 if (commit)
5699 got_object_commit_close(commit);
5700 if (worktree)
5701 got_worktree_close(worktree);
5702 if (repo) {
5703 const struct got_error *close_err = got_repo_close(repo);
5704 if (error == NULL)
5705 error = close_err;
5707 return error;
5710 __dead static void
5711 usage_status(void)
5713 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5714 "[-S status-codes] [path ...]\n", getprogname());
5715 exit(1);
5718 struct got_status_arg {
5719 char *status_codes;
5720 int suppress;
5723 static const struct got_error *
5724 print_status(void *arg, unsigned char status, unsigned char staged_status,
5725 const char *path, struct got_object_id *blob_id,
5726 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5727 int dirfd, const char *de_name)
5729 struct got_status_arg *st = arg;
5731 if (status == staged_status && (status == GOT_STATUS_DELETE))
5732 status = GOT_STATUS_NO_CHANGE;
5733 if (st != NULL && st->status_codes) {
5734 size_t ncodes = strlen(st->status_codes);
5735 int i, j = 0;
5737 for (i = 0; i < ncodes ; i++) {
5738 if (st->suppress) {
5739 if (status == st->status_codes[i] ||
5740 staged_status == st->status_codes[i]) {
5741 j++;
5742 continue;
5744 } else {
5745 if (status == st->status_codes[i] ||
5746 staged_status == st->status_codes[i])
5747 break;
5751 if (st->suppress && j == 0)
5752 goto print;
5754 if (i == ncodes)
5755 return NULL;
5757 print:
5758 printf("%c%c %s\n", status, staged_status, path);
5759 return NULL;
5762 static const struct got_error *
5763 cmd_status(int argc, char *argv[])
5765 const struct got_error *error = NULL;
5766 struct got_repository *repo = NULL;
5767 struct got_worktree *worktree = NULL;
5768 struct got_status_arg st;
5769 char *cwd = NULL;
5770 struct got_pathlist_head paths;
5771 struct got_pathlist_entry *pe;
5772 int ch, i, no_ignores = 0;
5774 TAILQ_INIT(&paths);
5776 memset(&st, 0, sizeof(st));
5777 st.status_codes = NULL;
5778 st.suppress = 0;
5780 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5781 switch (ch) {
5782 case 'I':
5783 no_ignores = 1;
5784 break;
5785 case 'S':
5786 if (st.status_codes != NULL && st.suppress == 0)
5787 option_conflict('S', 's');
5788 st.suppress = 1;
5789 /* fallthrough */
5790 case 's':
5791 for (i = 0; i < strlen(optarg); i++) {
5792 switch (optarg[i]) {
5793 case GOT_STATUS_MODIFY:
5794 case GOT_STATUS_ADD:
5795 case GOT_STATUS_DELETE:
5796 case GOT_STATUS_CONFLICT:
5797 case GOT_STATUS_MISSING:
5798 case GOT_STATUS_OBSTRUCTED:
5799 case GOT_STATUS_UNVERSIONED:
5800 case GOT_STATUS_MODE_CHANGE:
5801 case GOT_STATUS_NONEXISTENT:
5802 break;
5803 default:
5804 errx(1, "invalid status code '%c'",
5805 optarg[i]);
5808 if (ch == 's' && st.suppress)
5809 option_conflict('s', 'S');
5810 st.status_codes = optarg;
5811 break;
5812 default:
5813 usage_status();
5814 /* NOTREACHED */
5818 argc -= optind;
5819 argv += optind;
5821 #ifndef PROFILE
5822 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5823 NULL) == -1)
5824 err(1, "pledge");
5825 #endif
5826 cwd = getcwd(NULL, 0);
5827 if (cwd == NULL) {
5828 error = got_error_from_errno("getcwd");
5829 goto done;
5832 error = got_worktree_open(&worktree, cwd);
5833 if (error) {
5834 if (error->code == GOT_ERR_NOT_WORKTREE)
5835 error = wrap_not_worktree_error(error, "status", cwd);
5836 goto done;
5839 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5840 NULL);
5841 if (error != NULL)
5842 goto done;
5844 error = apply_unveil(got_repo_get_path(repo), 1,
5845 got_worktree_get_root_path(worktree));
5846 if (error)
5847 goto done;
5849 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5850 if (error)
5851 goto done;
5853 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5854 print_status, &st, check_cancelled, NULL);
5855 done:
5856 TAILQ_FOREACH(pe, &paths, entry)
5857 free((char *)pe->path);
5858 got_pathlist_free(&paths);
5859 free(cwd);
5860 return error;
5863 __dead static void
5864 usage_ref(void)
5866 fprintf(stderr,
5867 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5868 "[-s reference] [-d] [name]\n",
5869 getprogname());
5870 exit(1);
5873 static const struct got_error *
5874 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5876 static const struct got_error *err = NULL;
5877 struct got_reflist_head refs;
5878 struct got_reflist_entry *re;
5880 TAILQ_INIT(&refs);
5881 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5882 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5883 repo);
5884 if (err)
5885 return err;
5887 TAILQ_FOREACH(re, &refs, entry) {
5888 char *refstr;
5889 refstr = got_ref_to_str(re->ref);
5890 if (refstr == NULL) {
5891 err = got_error_from_errno("got_ref_to_str");
5892 break;
5894 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5895 free(refstr);
5898 got_ref_list_free(&refs);
5899 return err;
5902 static const struct got_error *
5903 delete_ref_by_name(struct got_repository *repo, const char *refname)
5905 const struct got_error *err;
5906 struct got_reference *ref;
5908 err = got_ref_open(&ref, repo, refname, 0);
5909 if (err)
5910 return err;
5912 err = delete_ref(repo, ref);
5913 got_ref_close(ref);
5914 return err;
5917 static const struct got_error *
5918 add_ref(struct got_repository *repo, const char *refname, const char *target)
5920 const struct got_error *err = NULL;
5921 struct got_object_id *id = NULL;
5922 struct got_reference *ref = NULL;
5923 struct got_reflist_head refs;
5926 * Don't let the user create a reference name with a leading '-'.
5927 * While technically a valid reference name, this case is usually
5928 * an unintended typo.
5930 if (refname[0] == '-')
5931 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5933 TAILQ_INIT(&refs);
5934 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5935 if (err)
5936 goto done;
5937 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5938 &refs, repo);
5939 got_ref_list_free(&refs);
5940 if (err)
5941 goto done;
5943 err = got_ref_alloc(&ref, refname, id);
5944 if (err)
5945 goto done;
5947 err = got_ref_write(ref, repo);
5948 done:
5949 if (ref)
5950 got_ref_close(ref);
5951 free(id);
5952 return err;
5955 static const struct got_error *
5956 add_symref(struct got_repository *repo, const char *refname, const char *target)
5958 const struct got_error *err = NULL;
5959 struct got_reference *ref = NULL;
5960 struct got_reference *target_ref = NULL;
5963 * Don't let the user create a reference name with a leading '-'.
5964 * While technically a valid reference name, this case is usually
5965 * an unintended typo.
5967 if (refname[0] == '-')
5968 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5970 err = got_ref_open(&target_ref, repo, target, 0);
5971 if (err)
5972 return err;
5974 err = got_ref_alloc_symref(&ref, refname, target_ref);
5975 if (err)
5976 goto done;
5978 err = got_ref_write(ref, repo);
5979 done:
5980 if (target_ref)
5981 got_ref_close(target_ref);
5982 if (ref)
5983 got_ref_close(ref);
5984 return err;
5987 static const struct got_error *
5988 cmd_ref(int argc, char *argv[])
5990 const struct got_error *error = NULL;
5991 struct got_repository *repo = NULL;
5992 struct got_worktree *worktree = NULL;
5993 char *cwd = NULL, *repo_path = NULL;
5994 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5995 const char *obj_arg = NULL, *symref_target= NULL;
5996 char *refname = NULL;
5998 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5999 switch (ch) {
6000 case 'c':
6001 obj_arg = optarg;
6002 break;
6003 case 'd':
6004 do_delete = 1;
6005 break;
6006 case 'r':
6007 repo_path = realpath(optarg, NULL);
6008 if (repo_path == NULL)
6009 return got_error_from_errno2("realpath",
6010 optarg);
6011 got_path_strip_trailing_slashes(repo_path);
6012 break;
6013 case 'l':
6014 do_list = 1;
6015 break;
6016 case 's':
6017 symref_target = optarg;
6018 break;
6019 case 't':
6020 sort_by_time = 1;
6021 break;
6022 default:
6023 usage_ref();
6024 /* NOTREACHED */
6028 if (obj_arg && do_list)
6029 option_conflict('c', 'l');
6030 if (obj_arg && do_delete)
6031 option_conflict('c', 'd');
6032 if (obj_arg && symref_target)
6033 option_conflict('c', 's');
6034 if (symref_target && do_delete)
6035 option_conflict('s', 'd');
6036 if (symref_target && do_list)
6037 option_conflict('s', 'l');
6038 if (do_delete && do_list)
6039 option_conflict('d', 'l');
6040 if (sort_by_time && !do_list)
6041 errx(1, "-t option requires -l option");
6043 argc -= optind;
6044 argv += optind;
6046 if (do_list) {
6047 if (argc != 0 && argc != 1)
6048 usage_ref();
6049 if (argc == 1) {
6050 refname = strdup(argv[0]);
6051 if (refname == NULL) {
6052 error = got_error_from_errno("strdup");
6053 goto done;
6056 } else {
6057 if (argc != 1)
6058 usage_ref();
6059 refname = strdup(argv[0]);
6060 if (refname == NULL) {
6061 error = got_error_from_errno("strdup");
6062 goto done;
6066 if (refname)
6067 got_path_strip_trailing_slashes(refname);
6069 #ifndef PROFILE
6070 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6071 "sendfd unveil", NULL) == -1)
6072 err(1, "pledge");
6073 #endif
6074 cwd = getcwd(NULL, 0);
6075 if (cwd == NULL) {
6076 error = got_error_from_errno("getcwd");
6077 goto done;
6080 if (repo_path == NULL) {
6081 error = got_worktree_open(&worktree, cwd);
6082 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6083 goto done;
6084 else
6085 error = NULL;
6086 if (worktree) {
6087 repo_path =
6088 strdup(got_worktree_get_repo_path(worktree));
6089 if (repo_path == NULL)
6090 error = got_error_from_errno("strdup");
6091 if (error)
6092 goto done;
6093 } else {
6094 repo_path = strdup(cwd);
6095 if (repo_path == NULL) {
6096 error = got_error_from_errno("strdup");
6097 goto done;
6102 error = got_repo_open(&repo, repo_path, NULL);
6103 if (error != NULL)
6104 goto done;
6106 #ifndef PROFILE
6107 if (do_list) {
6108 /* Remove "cpath" promise. */
6109 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6110 NULL) == -1)
6111 err(1, "pledge");
6113 #endif
6115 error = apply_unveil(got_repo_get_path(repo), do_list,
6116 worktree ? got_worktree_get_root_path(worktree) : NULL);
6117 if (error)
6118 goto done;
6120 if (do_list)
6121 error = list_refs(repo, refname, sort_by_time);
6122 else if (do_delete)
6123 error = delete_ref_by_name(repo, refname);
6124 else if (symref_target)
6125 error = add_symref(repo, refname, symref_target);
6126 else {
6127 if (obj_arg == NULL)
6128 usage_ref();
6129 error = add_ref(repo, refname, obj_arg);
6131 done:
6132 free(refname);
6133 if (repo) {
6134 const struct got_error *close_err = got_repo_close(repo);
6135 if (error == NULL)
6136 error = close_err;
6138 if (worktree)
6139 got_worktree_close(worktree);
6140 free(cwd);
6141 free(repo_path);
6142 return error;
6145 __dead static void
6146 usage_branch(void)
6148 fprintf(stderr,
6149 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6150 "[-n] [name]\n", getprogname());
6151 exit(1);
6154 static const struct got_error *
6155 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6156 struct got_reference *ref)
6158 const struct got_error *err = NULL;
6159 const char *refname, *marker = " ";
6160 char *refstr;
6162 refname = got_ref_get_name(ref);
6163 if (worktree && strcmp(refname,
6164 got_worktree_get_head_ref_name(worktree)) == 0) {
6165 struct got_object_id *id = NULL;
6167 err = got_ref_resolve(&id, repo, ref);
6168 if (err)
6169 return err;
6170 if (got_object_id_cmp(id,
6171 got_worktree_get_base_commit_id(worktree)) == 0)
6172 marker = "* ";
6173 else
6174 marker = "~ ";
6175 free(id);
6178 if (strncmp(refname, "refs/heads/", 11) == 0)
6179 refname += 11;
6180 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6181 refname += 18;
6182 if (strncmp(refname, "refs/remotes/", 13) == 0)
6183 refname += 13;
6185 refstr = got_ref_to_str(ref);
6186 if (refstr == NULL)
6187 return got_error_from_errno("got_ref_to_str");
6189 printf("%s%s: %s\n", marker, refname, refstr);
6190 free(refstr);
6191 return NULL;
6194 static const struct got_error *
6195 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6197 const char *refname;
6199 if (worktree == NULL)
6200 return got_error(GOT_ERR_NOT_WORKTREE);
6202 refname = got_worktree_get_head_ref_name(worktree);
6204 if (strncmp(refname, "refs/heads/", 11) == 0)
6205 refname += 11;
6206 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6207 refname += 18;
6209 printf("%s\n", refname);
6211 return NULL;
6214 static const struct got_error *
6215 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6216 int sort_by_time)
6218 static const struct got_error *err = NULL;
6219 struct got_reflist_head refs;
6220 struct got_reflist_entry *re;
6221 struct got_reference *temp_ref = NULL;
6222 int rebase_in_progress, histedit_in_progress;
6224 TAILQ_INIT(&refs);
6226 if (worktree) {
6227 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6228 worktree);
6229 if (err)
6230 return err;
6232 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6233 worktree);
6234 if (err)
6235 return err;
6237 if (rebase_in_progress || histedit_in_progress) {
6238 err = got_ref_open(&temp_ref, repo,
6239 got_worktree_get_head_ref_name(worktree), 0);
6240 if (err)
6241 return err;
6242 list_branch(repo, worktree, temp_ref);
6243 got_ref_close(temp_ref);
6247 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6248 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6249 repo);
6250 if (err)
6251 return err;
6253 TAILQ_FOREACH(re, &refs, entry)
6254 list_branch(repo, worktree, re->ref);
6256 got_ref_list_free(&refs);
6258 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6259 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6260 repo);
6261 if (err)
6262 return err;
6264 TAILQ_FOREACH(re, &refs, entry)
6265 list_branch(repo, worktree, re->ref);
6267 got_ref_list_free(&refs);
6269 return NULL;
6272 static const struct got_error *
6273 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6274 const char *branch_name)
6276 const struct got_error *err = NULL;
6277 struct got_reference *ref = NULL;
6278 char *refname, *remote_refname = NULL;
6280 if (strncmp(branch_name, "refs/", 5) == 0)
6281 branch_name += 5;
6282 if (strncmp(branch_name, "heads/", 6) == 0)
6283 branch_name += 6;
6284 else if (strncmp(branch_name, "remotes/", 8) == 0)
6285 branch_name += 8;
6287 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6288 return got_error_from_errno("asprintf");
6290 if (asprintf(&remote_refname, "refs/remotes/%s",
6291 branch_name) == -1) {
6292 err = got_error_from_errno("asprintf");
6293 goto done;
6296 err = got_ref_open(&ref, repo, refname, 0);
6297 if (err) {
6298 const struct got_error *err2;
6299 if (err->code != GOT_ERR_NOT_REF)
6300 goto done;
6302 * Keep 'err' intact such that if neither branch exists
6303 * we report "refs/heads" rather than "refs/remotes" in
6304 * our error message.
6306 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6307 if (err2)
6308 goto done;
6309 err = NULL;
6312 if (worktree &&
6313 strcmp(got_worktree_get_head_ref_name(worktree),
6314 got_ref_get_name(ref)) == 0) {
6315 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6316 "will not delete this work tree's current branch");
6317 goto done;
6320 err = delete_ref(repo, ref);
6321 done:
6322 if (ref)
6323 got_ref_close(ref);
6324 free(refname);
6325 free(remote_refname);
6326 return err;
6329 static const struct got_error *
6330 add_branch(struct got_repository *repo, const char *branch_name,
6331 struct got_object_id *base_commit_id)
6333 const struct got_error *err = NULL;
6334 struct got_reference *ref = NULL;
6335 char *base_refname = NULL, *refname = NULL;
6338 * Don't let the user create a branch name with a leading '-'.
6339 * While technically a valid reference name, this case is usually
6340 * an unintended typo.
6342 if (branch_name[0] == '-')
6343 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6345 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6346 branch_name += 11;
6348 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6349 err = got_error_from_errno("asprintf");
6350 goto done;
6353 err = got_ref_open(&ref, repo, refname, 0);
6354 if (err == NULL) {
6355 err = got_error(GOT_ERR_BRANCH_EXISTS);
6356 goto done;
6357 } else if (err->code != GOT_ERR_NOT_REF)
6358 goto done;
6360 err = got_ref_alloc(&ref, refname, base_commit_id);
6361 if (err)
6362 goto done;
6364 err = got_ref_write(ref, repo);
6365 done:
6366 if (ref)
6367 got_ref_close(ref);
6368 free(base_refname);
6369 free(refname);
6370 return err;
6373 static const struct got_error *
6374 cmd_branch(int argc, char *argv[])
6376 const struct got_error *error = NULL;
6377 struct got_repository *repo = NULL;
6378 struct got_worktree *worktree = NULL;
6379 char *cwd = NULL, *repo_path = NULL;
6380 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6381 const char *delref = NULL, *commit_id_arg = NULL;
6382 struct got_reference *ref = NULL;
6383 struct got_pathlist_head paths;
6384 struct got_pathlist_entry *pe;
6385 struct got_object_id *commit_id = NULL;
6386 char *commit_id_str = NULL;
6388 TAILQ_INIT(&paths);
6390 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6391 switch (ch) {
6392 case 'c':
6393 commit_id_arg = optarg;
6394 break;
6395 case 'd':
6396 delref = optarg;
6397 break;
6398 case 'r':
6399 repo_path = realpath(optarg, NULL);
6400 if (repo_path == NULL)
6401 return got_error_from_errno2("realpath",
6402 optarg);
6403 got_path_strip_trailing_slashes(repo_path);
6404 break;
6405 case 'l':
6406 do_list = 1;
6407 break;
6408 case 'n':
6409 do_update = 0;
6410 break;
6411 case 't':
6412 sort_by_time = 1;
6413 break;
6414 default:
6415 usage_branch();
6416 /* NOTREACHED */
6420 if (do_list && delref)
6421 option_conflict('l', 'd');
6422 if (sort_by_time && !do_list)
6423 errx(1, "-t option requires -l option");
6425 argc -= optind;
6426 argv += optind;
6428 if (!do_list && !delref && argc == 0)
6429 do_show = 1;
6431 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6432 errx(1, "-c option can only be used when creating a branch");
6434 if (do_list || delref) {
6435 if (argc > 0)
6436 usage_branch();
6437 } else if (!do_show && argc != 1)
6438 usage_branch();
6440 #ifndef PROFILE
6441 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6442 "sendfd unveil", NULL) == -1)
6443 err(1, "pledge");
6444 #endif
6445 cwd = getcwd(NULL, 0);
6446 if (cwd == NULL) {
6447 error = got_error_from_errno("getcwd");
6448 goto done;
6451 if (repo_path == NULL) {
6452 error = got_worktree_open(&worktree, cwd);
6453 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6454 goto done;
6455 else
6456 error = NULL;
6457 if (worktree) {
6458 repo_path =
6459 strdup(got_worktree_get_repo_path(worktree));
6460 if (repo_path == NULL)
6461 error = got_error_from_errno("strdup");
6462 if (error)
6463 goto done;
6464 } else {
6465 repo_path = strdup(cwd);
6466 if (repo_path == NULL) {
6467 error = got_error_from_errno("strdup");
6468 goto done;
6473 error = got_repo_open(&repo, repo_path, NULL);
6474 if (error != NULL)
6475 goto done;
6477 #ifndef PROFILE
6478 if (do_list || do_show) {
6479 /* Remove "cpath" promise. */
6480 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6481 NULL) == -1)
6482 err(1, "pledge");
6484 #endif
6486 error = apply_unveil(got_repo_get_path(repo), do_list,
6487 worktree ? got_worktree_get_root_path(worktree) : NULL);
6488 if (error)
6489 goto done;
6491 if (do_show)
6492 error = show_current_branch(repo, worktree);
6493 else if (do_list)
6494 error = list_branches(repo, worktree, sort_by_time);
6495 else if (delref)
6496 error = delete_branch(repo, worktree, delref);
6497 else {
6498 struct got_reflist_head refs;
6499 TAILQ_INIT(&refs);
6500 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6501 NULL);
6502 if (error)
6503 goto done;
6504 if (commit_id_arg == NULL)
6505 commit_id_arg = worktree ?
6506 got_worktree_get_head_ref_name(worktree) :
6507 GOT_REF_HEAD;
6508 error = got_repo_match_object_id(&commit_id, NULL,
6509 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6510 got_ref_list_free(&refs);
6511 if (error)
6512 goto done;
6513 error = add_branch(repo, argv[0], commit_id);
6514 if (error)
6515 goto done;
6516 if (worktree && do_update) {
6517 struct got_update_progress_arg upa;
6518 char *branch_refname = NULL;
6520 error = got_object_id_str(&commit_id_str, commit_id);
6521 if (error)
6522 goto done;
6523 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6524 worktree);
6525 if (error)
6526 goto done;
6527 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6528 == -1) {
6529 error = got_error_from_errno("asprintf");
6530 goto done;
6532 error = got_ref_open(&ref, repo, branch_refname, 0);
6533 free(branch_refname);
6534 if (error)
6535 goto done;
6536 error = switch_head_ref(ref, commit_id, worktree,
6537 repo);
6538 if (error)
6539 goto done;
6540 error = got_worktree_set_base_commit_id(worktree, repo,
6541 commit_id);
6542 if (error)
6543 goto done;
6544 memset(&upa, 0, sizeof(upa));
6545 error = got_worktree_checkout_files(worktree, &paths,
6546 repo, update_progress, &upa, check_cancelled,
6547 NULL);
6548 if (error)
6549 goto done;
6550 if (upa.did_something) {
6551 printf("Updated to %s: %s\n",
6552 got_worktree_get_head_ref_name(worktree),
6553 commit_id_str);
6555 print_update_progress_stats(&upa);
6558 done:
6559 if (ref)
6560 got_ref_close(ref);
6561 if (repo) {
6562 const struct got_error *close_err = got_repo_close(repo);
6563 if (error == NULL)
6564 error = close_err;
6566 if (worktree)
6567 got_worktree_close(worktree);
6568 free(cwd);
6569 free(repo_path);
6570 free(commit_id);
6571 free(commit_id_str);
6572 TAILQ_FOREACH(pe, &paths, entry)
6573 free((char *)pe->path);
6574 got_pathlist_free(&paths);
6575 return error;
6579 __dead static void
6580 usage_tag(void)
6582 fprintf(stderr,
6583 "usage: %s tag [-c commit] [-r repository] [-l] "
6584 "[-m message] name\n", getprogname());
6585 exit(1);
6588 #if 0
6589 static const struct got_error *
6590 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6592 const struct got_error *err = NULL;
6593 struct got_reflist_entry *re, *se, *new;
6594 struct got_object_id *re_id, *se_id;
6595 struct got_tag_object *re_tag, *se_tag;
6596 time_t re_time, se_time;
6598 STAILQ_FOREACH(re, tags, entry) {
6599 se = STAILQ_FIRST(sorted);
6600 if (se == NULL) {
6601 err = got_reflist_entry_dup(&new, re);
6602 if (err)
6603 return err;
6604 STAILQ_INSERT_HEAD(sorted, new, entry);
6605 continue;
6606 } else {
6607 err = got_ref_resolve(&re_id, repo, re->ref);
6608 if (err)
6609 break;
6610 err = got_object_open_as_tag(&re_tag, repo, re_id);
6611 free(re_id);
6612 if (err)
6613 break;
6614 re_time = got_object_tag_get_tagger_time(re_tag);
6615 got_object_tag_close(re_tag);
6618 while (se) {
6619 err = got_ref_resolve(&se_id, repo, re->ref);
6620 if (err)
6621 break;
6622 err = got_object_open_as_tag(&se_tag, repo, se_id);
6623 free(se_id);
6624 if (err)
6625 break;
6626 se_time = got_object_tag_get_tagger_time(se_tag);
6627 got_object_tag_close(se_tag);
6629 if (se_time > re_time) {
6630 err = got_reflist_entry_dup(&new, re);
6631 if (err)
6632 return err;
6633 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6634 break;
6636 se = STAILQ_NEXT(se, entry);
6637 continue;
6640 done:
6641 return err;
6643 #endif
6645 static const struct got_error *
6646 list_tags(struct got_repository *repo)
6648 static const struct got_error *err = NULL;
6649 struct got_reflist_head refs;
6650 struct got_reflist_entry *re;
6652 TAILQ_INIT(&refs);
6654 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6655 if (err)
6656 return err;
6658 TAILQ_FOREACH(re, &refs, entry) {
6659 const char *refname;
6660 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6661 char datebuf[26];
6662 const char *tagger;
6663 time_t tagger_time;
6664 struct got_object_id *id;
6665 struct got_tag_object *tag;
6666 struct got_commit_object *commit = NULL;
6668 refname = got_ref_get_name(re->ref);
6669 if (strncmp(refname, "refs/tags/", 10) != 0)
6670 continue;
6671 refname += 10;
6672 refstr = got_ref_to_str(re->ref);
6673 if (refstr == NULL) {
6674 err = got_error_from_errno("got_ref_to_str");
6675 break;
6677 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6678 free(refstr);
6680 err = got_ref_resolve(&id, repo, re->ref);
6681 if (err)
6682 break;
6683 err = got_object_open_as_tag(&tag, repo, id);
6684 if (err) {
6685 if (err->code != GOT_ERR_OBJ_TYPE) {
6686 free(id);
6687 break;
6689 /* "lightweight" tag */
6690 err = got_object_open_as_commit(&commit, repo, id);
6691 if (err) {
6692 free(id);
6693 break;
6695 tagger = got_object_commit_get_committer(commit);
6696 tagger_time =
6697 got_object_commit_get_committer_time(commit);
6698 err = got_object_id_str(&id_str, id);
6699 free(id);
6700 if (err)
6701 break;
6702 } else {
6703 free(id);
6704 tagger = got_object_tag_get_tagger(tag);
6705 tagger_time = got_object_tag_get_tagger_time(tag);
6706 err = got_object_id_str(&id_str,
6707 got_object_tag_get_object_id(tag));
6708 if (err)
6709 break;
6711 printf("from: %s\n", tagger);
6712 datestr = get_datestr(&tagger_time, datebuf);
6713 if (datestr)
6714 printf("date: %s UTC\n", datestr);
6715 if (commit)
6716 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6717 else {
6718 switch (got_object_tag_get_object_type(tag)) {
6719 case GOT_OBJ_TYPE_BLOB:
6720 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6721 id_str);
6722 break;
6723 case GOT_OBJ_TYPE_TREE:
6724 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6725 id_str);
6726 break;
6727 case GOT_OBJ_TYPE_COMMIT:
6728 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6729 id_str);
6730 break;
6731 case GOT_OBJ_TYPE_TAG:
6732 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6733 id_str);
6734 break;
6735 default:
6736 break;
6739 free(id_str);
6740 if (commit) {
6741 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6742 if (err)
6743 break;
6744 got_object_commit_close(commit);
6745 } else {
6746 tagmsg0 = strdup(got_object_tag_get_message(tag));
6747 got_object_tag_close(tag);
6748 if (tagmsg0 == NULL) {
6749 err = got_error_from_errno("strdup");
6750 break;
6754 tagmsg = tagmsg0;
6755 do {
6756 line = strsep(&tagmsg, "\n");
6757 if (line)
6758 printf(" %s\n", line);
6759 } while (line);
6760 free(tagmsg0);
6763 got_ref_list_free(&refs);
6764 return NULL;
6767 static const struct got_error *
6768 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6769 const char *tag_name, const char *repo_path)
6771 const struct got_error *err = NULL;
6772 char *template = NULL, *initial_content = NULL;
6773 char *editor = NULL;
6774 int initial_content_len;
6775 int fd = -1;
6777 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6778 err = got_error_from_errno("asprintf");
6779 goto done;
6782 initial_content_len = asprintf(&initial_content,
6783 "\n# tagging commit %s as %s\n",
6784 commit_id_str, tag_name);
6785 if (initial_content_len == -1) {
6786 err = got_error_from_errno("asprintf");
6787 goto done;
6790 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6791 if (err)
6792 goto done;
6794 if (write(fd, initial_content, initial_content_len) == -1) {
6795 err = got_error_from_errno2("write", *tagmsg_path);
6796 goto done;
6799 err = get_editor(&editor);
6800 if (err)
6801 goto done;
6802 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6803 initial_content_len, 1);
6804 done:
6805 free(initial_content);
6806 free(template);
6807 free(editor);
6809 if (fd != -1 && close(fd) == -1 && err == NULL)
6810 err = got_error_from_errno2("close", *tagmsg_path);
6812 /* Editor is done; we can now apply unveil(2) */
6813 if (err == NULL)
6814 err = apply_unveil(repo_path, 0, NULL);
6815 if (err) {
6816 free(*tagmsg);
6817 *tagmsg = NULL;
6819 return err;
6822 static const struct got_error *
6823 add_tag(struct got_repository *repo, const char *tagger,
6824 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6826 const struct got_error *err = NULL;
6827 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6828 char *label = NULL, *commit_id_str = NULL;
6829 struct got_reference *ref = NULL;
6830 char *refname = NULL, *tagmsg = NULL;
6831 char *tagmsg_path = NULL, *tag_id_str = NULL;
6832 int preserve_tagmsg = 0;
6833 struct got_reflist_head refs;
6835 TAILQ_INIT(&refs);
6838 * Don't let the user create a tag name with a leading '-'.
6839 * While technically a valid reference name, this case is usually
6840 * an unintended typo.
6842 if (tag_name[0] == '-')
6843 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6845 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6846 if (err)
6847 goto done;
6849 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6850 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6851 if (err)
6852 goto done;
6854 err = got_object_id_str(&commit_id_str, commit_id);
6855 if (err)
6856 goto done;
6858 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6859 refname = strdup(tag_name);
6860 if (refname == NULL) {
6861 err = got_error_from_errno("strdup");
6862 goto done;
6864 tag_name += 10;
6865 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6866 err = got_error_from_errno("asprintf");
6867 goto done;
6870 err = got_ref_open(&ref, repo, refname, 0);
6871 if (err == NULL) {
6872 err = got_error(GOT_ERR_TAG_EXISTS);
6873 goto done;
6874 } else if (err->code != GOT_ERR_NOT_REF)
6875 goto done;
6877 if (tagmsg_arg == NULL) {
6878 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6879 tag_name, got_repo_get_path(repo));
6880 if (err) {
6881 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6882 tagmsg_path != NULL)
6883 preserve_tagmsg = 1;
6884 goto done;
6888 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6889 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6890 if (err) {
6891 if (tagmsg_path)
6892 preserve_tagmsg = 1;
6893 goto done;
6896 err = got_ref_alloc(&ref, refname, tag_id);
6897 if (err) {
6898 if (tagmsg_path)
6899 preserve_tagmsg = 1;
6900 goto done;
6903 err = got_ref_write(ref, repo);
6904 if (err) {
6905 if (tagmsg_path)
6906 preserve_tagmsg = 1;
6907 goto done;
6910 err = got_object_id_str(&tag_id_str, tag_id);
6911 if (err) {
6912 if (tagmsg_path)
6913 preserve_tagmsg = 1;
6914 goto done;
6916 printf("Created tag %s\n", tag_id_str);
6917 done:
6918 if (preserve_tagmsg) {
6919 fprintf(stderr, "%s: tag message preserved in %s\n",
6920 getprogname(), tagmsg_path);
6921 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6922 err = got_error_from_errno2("unlink", tagmsg_path);
6923 free(tag_id_str);
6924 if (ref)
6925 got_ref_close(ref);
6926 free(commit_id);
6927 free(commit_id_str);
6928 free(refname);
6929 free(tagmsg);
6930 free(tagmsg_path);
6931 got_ref_list_free(&refs);
6932 return err;
6935 static const struct got_error *
6936 cmd_tag(int argc, char *argv[])
6938 const struct got_error *error = NULL;
6939 struct got_repository *repo = NULL;
6940 struct got_worktree *worktree = NULL;
6941 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6942 char *gitconfig_path = NULL, *tagger = NULL;
6943 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6944 int ch, do_list = 0;
6946 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6947 switch (ch) {
6948 case 'c':
6949 commit_id_arg = optarg;
6950 break;
6951 case 'm':
6952 tagmsg = optarg;
6953 break;
6954 case 'r':
6955 repo_path = realpath(optarg, NULL);
6956 if (repo_path == NULL)
6957 return got_error_from_errno2("realpath",
6958 optarg);
6959 got_path_strip_trailing_slashes(repo_path);
6960 break;
6961 case 'l':
6962 do_list = 1;
6963 break;
6964 default:
6965 usage_tag();
6966 /* NOTREACHED */
6970 argc -= optind;
6971 argv += optind;
6973 if (do_list) {
6974 if (commit_id_arg != NULL)
6975 errx(1,
6976 "-c option can only be used when creating a tag");
6977 if (tagmsg)
6978 option_conflict('l', 'm');
6979 if (argc > 0)
6980 usage_tag();
6981 } else if (argc != 1)
6982 usage_tag();
6984 tag_name = argv[0];
6986 #ifndef PROFILE
6987 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6988 "sendfd unveil", NULL) == -1)
6989 err(1, "pledge");
6990 #endif
6991 cwd = getcwd(NULL, 0);
6992 if (cwd == NULL) {
6993 error = got_error_from_errno("getcwd");
6994 goto done;
6997 if (repo_path == NULL) {
6998 error = got_worktree_open(&worktree, cwd);
6999 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7000 goto done;
7001 else
7002 error = NULL;
7003 if (worktree) {
7004 repo_path =
7005 strdup(got_worktree_get_repo_path(worktree));
7006 if (repo_path == NULL)
7007 error = got_error_from_errno("strdup");
7008 if (error)
7009 goto done;
7010 } else {
7011 repo_path = strdup(cwd);
7012 if (repo_path == NULL) {
7013 error = got_error_from_errno("strdup");
7014 goto done;
7019 if (do_list) {
7020 if (worktree) {
7021 /* Release work tree lock. */
7022 got_worktree_close(worktree);
7023 worktree = NULL;
7025 error = got_repo_open(&repo, repo_path, NULL);
7026 if (error != NULL)
7027 goto done;
7028 #ifndef PROFILE
7029 /* Remove "cpath" promise. */
7030 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7031 NULL) == -1)
7032 err(1, "pledge");
7033 #endif
7034 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7035 if (error)
7036 goto done;
7037 error = list_tags(repo);
7038 } else {
7039 error = get_gitconfig_path(&gitconfig_path);
7040 if (error)
7041 goto done;
7042 error = got_repo_open(&repo, repo_path, gitconfig_path);
7043 if (error != NULL)
7044 goto done;
7046 error = get_author(&tagger, repo, worktree);
7047 if (error)
7048 goto done;
7049 if (worktree) {
7050 /* Release work tree lock. */
7051 got_worktree_close(worktree);
7052 worktree = NULL;
7055 if (tagmsg) {
7056 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7057 if (error)
7058 goto done;
7061 if (commit_id_arg == NULL) {
7062 struct got_reference *head_ref;
7063 struct got_object_id *commit_id;
7064 error = got_ref_open(&head_ref, repo,
7065 worktree ? got_worktree_get_head_ref_name(worktree)
7066 : GOT_REF_HEAD, 0);
7067 if (error)
7068 goto done;
7069 error = got_ref_resolve(&commit_id, repo, head_ref);
7070 got_ref_close(head_ref);
7071 if (error)
7072 goto done;
7073 error = got_object_id_str(&commit_id_str, commit_id);
7074 free(commit_id);
7075 if (error)
7076 goto done;
7079 error = add_tag(repo, tagger, tag_name,
7080 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7082 done:
7083 if (repo) {
7084 const struct got_error *close_err = got_repo_close(repo);
7085 if (error == NULL)
7086 error = close_err;
7088 if (worktree)
7089 got_worktree_close(worktree);
7090 free(cwd);
7091 free(repo_path);
7092 free(gitconfig_path);
7093 free(commit_id_str);
7094 free(tagger);
7095 return error;
7098 __dead static void
7099 usage_add(void)
7101 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7102 getprogname());
7103 exit(1);
7106 static const struct got_error *
7107 add_progress(void *arg, unsigned char status, const char *path)
7109 while (path[0] == '/')
7110 path++;
7111 printf("%c %s\n", status, path);
7112 return NULL;
7115 static const struct got_error *
7116 cmd_add(int argc, char *argv[])
7118 const struct got_error *error = NULL;
7119 struct got_repository *repo = NULL;
7120 struct got_worktree *worktree = NULL;
7121 char *cwd = NULL;
7122 struct got_pathlist_head paths;
7123 struct got_pathlist_entry *pe;
7124 int ch, can_recurse = 0, no_ignores = 0;
7126 TAILQ_INIT(&paths);
7128 while ((ch = getopt(argc, argv, "IR")) != -1) {
7129 switch (ch) {
7130 case 'I':
7131 no_ignores = 1;
7132 break;
7133 case 'R':
7134 can_recurse = 1;
7135 break;
7136 default:
7137 usage_add();
7138 /* NOTREACHED */
7142 argc -= optind;
7143 argv += optind;
7145 #ifndef PROFILE
7146 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7147 NULL) == -1)
7148 err(1, "pledge");
7149 #endif
7150 if (argc < 1)
7151 usage_add();
7153 cwd = getcwd(NULL, 0);
7154 if (cwd == NULL) {
7155 error = got_error_from_errno("getcwd");
7156 goto done;
7159 error = got_worktree_open(&worktree, cwd);
7160 if (error) {
7161 if (error->code == GOT_ERR_NOT_WORKTREE)
7162 error = wrap_not_worktree_error(error, "add", cwd);
7163 goto done;
7166 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7167 NULL);
7168 if (error != NULL)
7169 goto done;
7171 error = apply_unveil(got_repo_get_path(repo), 1,
7172 got_worktree_get_root_path(worktree));
7173 if (error)
7174 goto done;
7176 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7177 if (error)
7178 goto done;
7180 if (!can_recurse) {
7181 char *ondisk_path;
7182 struct stat sb;
7183 TAILQ_FOREACH(pe, &paths, entry) {
7184 if (asprintf(&ondisk_path, "%s/%s",
7185 got_worktree_get_root_path(worktree),
7186 pe->path) == -1) {
7187 error = got_error_from_errno("asprintf");
7188 goto done;
7190 if (lstat(ondisk_path, &sb) == -1) {
7191 if (errno == ENOENT) {
7192 free(ondisk_path);
7193 continue;
7195 error = got_error_from_errno2("lstat",
7196 ondisk_path);
7197 free(ondisk_path);
7198 goto done;
7200 free(ondisk_path);
7201 if (S_ISDIR(sb.st_mode)) {
7202 error = got_error_msg(GOT_ERR_BAD_PATH,
7203 "adding directories requires -R option");
7204 goto done;
7209 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7210 NULL, repo, no_ignores);
7211 done:
7212 if (repo) {
7213 const struct got_error *close_err = got_repo_close(repo);
7214 if (error == NULL)
7215 error = close_err;
7217 if (worktree)
7218 got_worktree_close(worktree);
7219 TAILQ_FOREACH(pe, &paths, entry)
7220 free((char *)pe->path);
7221 got_pathlist_free(&paths);
7222 free(cwd);
7223 return error;
7226 __dead static void
7227 usage_remove(void)
7229 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7230 "path ...\n", getprogname());
7231 exit(1);
7234 static const struct got_error *
7235 print_remove_status(void *arg, unsigned char status,
7236 unsigned char staged_status, const char *path)
7238 while (path[0] == '/')
7239 path++;
7240 if (status == GOT_STATUS_NONEXISTENT)
7241 return NULL;
7242 if (status == staged_status && (status == GOT_STATUS_DELETE))
7243 status = GOT_STATUS_NO_CHANGE;
7244 printf("%c%c %s\n", status, staged_status, path);
7245 return NULL;
7248 static const struct got_error *
7249 cmd_remove(int argc, char *argv[])
7251 const struct got_error *error = NULL;
7252 struct got_worktree *worktree = NULL;
7253 struct got_repository *repo = NULL;
7254 const char *status_codes = NULL;
7255 char *cwd = NULL;
7256 struct got_pathlist_head paths;
7257 struct got_pathlist_entry *pe;
7258 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7259 int ignore_missing_paths = 0;
7261 TAILQ_INIT(&paths);
7263 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7264 switch (ch) {
7265 case 'f':
7266 delete_local_mods = 1;
7267 ignore_missing_paths = 1;
7268 break;
7269 case 'k':
7270 keep_on_disk = 1;
7271 break;
7272 case 'R':
7273 can_recurse = 1;
7274 break;
7275 case 's':
7276 for (i = 0; i < strlen(optarg); i++) {
7277 switch (optarg[i]) {
7278 case GOT_STATUS_MODIFY:
7279 delete_local_mods = 1;
7280 break;
7281 case GOT_STATUS_MISSING:
7282 ignore_missing_paths = 1;
7283 break;
7284 default:
7285 errx(1, "invalid status code '%c'",
7286 optarg[i]);
7289 status_codes = optarg;
7290 break;
7291 default:
7292 usage_remove();
7293 /* NOTREACHED */
7297 argc -= optind;
7298 argv += optind;
7300 #ifndef PROFILE
7301 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7302 NULL) == -1)
7303 err(1, "pledge");
7304 #endif
7305 if (argc < 1)
7306 usage_remove();
7308 cwd = getcwd(NULL, 0);
7309 if (cwd == NULL) {
7310 error = got_error_from_errno("getcwd");
7311 goto done;
7313 error = got_worktree_open(&worktree, cwd);
7314 if (error) {
7315 if (error->code == GOT_ERR_NOT_WORKTREE)
7316 error = wrap_not_worktree_error(error, "remove", cwd);
7317 goto done;
7320 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7321 NULL);
7322 if (error)
7323 goto done;
7325 error = apply_unveil(got_repo_get_path(repo), 1,
7326 got_worktree_get_root_path(worktree));
7327 if (error)
7328 goto done;
7330 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7331 if (error)
7332 goto done;
7334 if (!can_recurse) {
7335 char *ondisk_path;
7336 struct stat sb;
7337 TAILQ_FOREACH(pe, &paths, entry) {
7338 if (asprintf(&ondisk_path, "%s/%s",
7339 got_worktree_get_root_path(worktree),
7340 pe->path) == -1) {
7341 error = got_error_from_errno("asprintf");
7342 goto done;
7344 if (lstat(ondisk_path, &sb) == -1) {
7345 if (errno == ENOENT) {
7346 free(ondisk_path);
7347 continue;
7349 error = got_error_from_errno2("lstat",
7350 ondisk_path);
7351 free(ondisk_path);
7352 goto done;
7354 free(ondisk_path);
7355 if (S_ISDIR(sb.st_mode)) {
7356 error = got_error_msg(GOT_ERR_BAD_PATH,
7357 "removing directories requires -R option");
7358 goto done;
7363 error = got_worktree_schedule_delete(worktree, &paths,
7364 delete_local_mods, status_codes, print_remove_status, NULL,
7365 repo, keep_on_disk, ignore_missing_paths);
7366 done:
7367 if (repo) {
7368 const struct got_error *close_err = got_repo_close(repo);
7369 if (error == NULL)
7370 error = close_err;
7372 if (worktree)
7373 got_worktree_close(worktree);
7374 TAILQ_FOREACH(pe, &paths, entry)
7375 free((char *)pe->path);
7376 got_pathlist_free(&paths);
7377 free(cwd);
7378 return error;
7381 __dead static void
7382 usage_patch(void)
7384 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7385 "[-R] [patchfile]\n", getprogname());
7386 exit(1);
7389 static const struct got_error *
7390 patch_from_stdin(int *patchfd)
7392 const struct got_error *err = NULL;
7393 ssize_t r;
7394 char *path, buf[BUFSIZ];
7395 sig_t sighup, sigint, sigquit;
7397 err = got_opentemp_named_fd(&path, patchfd,
7398 GOT_TMPDIR_STR "/got-patch");
7399 if (err)
7400 return err;
7401 unlink(path);
7402 free(path);
7404 sighup = signal(SIGHUP, SIG_DFL);
7405 sigint = signal(SIGINT, SIG_DFL);
7406 sigquit = signal(SIGQUIT, SIG_DFL);
7408 for (;;) {
7409 r = read(0, buf, sizeof(buf));
7410 if (r == -1) {
7411 err = got_error_from_errno("read");
7412 break;
7414 if (r == 0)
7415 break;
7416 if (write(*patchfd, buf, r) == -1) {
7417 err = got_error_from_errno("write");
7418 break;
7422 signal(SIGHUP, sighup);
7423 signal(SIGINT, sigint);
7424 signal(SIGQUIT, sigquit);
7426 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7427 err = got_error_from_errno("lseek");
7429 if (err != NULL) {
7430 close(*patchfd);
7431 *patchfd = -1;
7434 return err;
7437 static const struct got_error *
7438 patch_progress(void *arg, const char *old, const char *new,
7439 unsigned char status, const struct got_error *error, long old_from,
7440 long old_lines, long new_from, long new_lines, long offset,
7441 const struct got_error *hunk_err)
7443 const char *path = new == NULL ? old : new;
7445 while (*path == '/')
7446 path++;
7448 if (status != 0)
7449 printf("%c %s\n", status, path);
7451 if (error != NULL)
7452 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7454 if (offset != 0 || hunk_err != NULL) {
7455 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7456 old_lines, new_from, new_lines);
7457 if (hunk_err != NULL)
7458 printf("%s\n", hunk_err->msg);
7459 else
7460 printf("applied with offset %ld\n", offset);
7463 return NULL;
7466 static const struct got_error *
7467 cmd_patch(int argc, char *argv[])
7469 const struct got_error *error = NULL, *close_error = NULL;
7470 struct got_worktree *worktree = NULL;
7471 struct got_repository *repo = NULL;
7472 const char *errstr;
7473 char *cwd = NULL;
7474 int ch, nop = 0, strip = -1, reverse = 0;
7475 int patchfd;
7477 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7478 switch (ch) {
7479 case 'n':
7480 nop = 1;
7481 break;
7482 case 'p':
7483 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7484 if (errstr != NULL)
7485 errx(1, "pathname strip count is %s: %s",
7486 errstr, optarg);
7487 break;
7488 case 'R':
7489 reverse = 1;
7490 break;
7491 default:
7492 usage_patch();
7493 /* NOTREACHED */
7497 argc -= optind;
7498 argv += optind;
7500 if (argc == 0) {
7501 error = patch_from_stdin(&patchfd);
7502 if (error)
7503 return error;
7504 } else if (argc == 1) {
7505 patchfd = open(argv[0], O_RDONLY);
7506 if (patchfd == -1) {
7507 error = got_error_from_errno2("open", argv[0]);
7508 return error;
7510 } else
7511 usage_patch();
7513 if ((cwd = getcwd(NULL, 0)) == NULL) {
7514 error = got_error_from_errno("getcwd");
7515 goto done;
7518 error = got_worktree_open(&worktree, cwd);
7519 if (error != NULL)
7520 goto done;
7522 const char *repo_path = got_worktree_get_repo_path(worktree);
7523 error = got_repo_open(&repo, repo_path, NULL);
7524 if (error != NULL)
7525 goto done;
7527 error = apply_unveil(got_repo_get_path(repo), 0,
7528 got_worktree_get_root_path(worktree));
7529 if (error != NULL)
7530 goto done;
7532 #ifndef PROFILE
7533 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7534 NULL) == -1)
7535 err(1, "pledge");
7536 #endif
7538 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7539 &patch_progress, NULL, check_cancelled, NULL);
7541 done:
7542 if (repo) {
7543 close_error = got_repo_close(repo);
7544 if (error == NULL)
7545 error = close_error;
7547 if (worktree != NULL) {
7548 close_error = got_worktree_close(worktree);
7549 if (error == NULL)
7550 error = close_error;
7552 free(cwd);
7553 return error;
7556 __dead static void
7557 usage_revert(void)
7559 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7560 "path ...\n", getprogname());
7561 exit(1);
7564 static const struct got_error *
7565 revert_progress(void *arg, unsigned char status, const char *path)
7567 if (status == GOT_STATUS_UNVERSIONED)
7568 return NULL;
7570 while (path[0] == '/')
7571 path++;
7572 printf("%c %s\n", status, path);
7573 return NULL;
7576 struct choose_patch_arg {
7577 FILE *patch_script_file;
7578 const char *action;
7581 static const struct got_error *
7582 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7583 int nchanges, const char *action)
7585 const struct got_error *err;
7586 char *line = NULL;
7587 size_t linesize = 0;
7588 ssize_t linelen;
7590 switch (status) {
7591 case GOT_STATUS_ADD:
7592 printf("A %s\n%s this addition? [y/n] ", path, action);
7593 break;
7594 case GOT_STATUS_DELETE:
7595 printf("D %s\n%s this deletion? [y/n] ", path, action);
7596 break;
7597 case GOT_STATUS_MODIFY:
7598 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7599 return got_error_from_errno("fseek");
7600 printf(GOT_COMMIT_SEP_STR);
7601 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7602 printf("%s", line);
7603 if (linelen == -1 && ferror(patch_file)) {
7604 err = got_error_from_errno("getline");
7605 free(line);
7606 return err;
7608 free(line);
7609 printf(GOT_COMMIT_SEP_STR);
7610 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7611 path, n, nchanges, action);
7612 break;
7613 default:
7614 return got_error_path(path, GOT_ERR_FILE_STATUS);
7617 return NULL;
7620 static const struct got_error *
7621 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7622 FILE *patch_file, int n, int nchanges)
7624 const struct got_error *err = NULL;
7625 char *line = NULL;
7626 size_t linesize = 0;
7627 ssize_t linelen;
7628 int resp = ' ';
7629 struct choose_patch_arg *a = arg;
7631 *choice = GOT_PATCH_CHOICE_NONE;
7633 if (a->patch_script_file) {
7634 char *nl;
7635 err = show_change(status, path, patch_file, n, nchanges,
7636 a->action);
7637 if (err)
7638 return err;
7639 linelen = getline(&line, &linesize, a->patch_script_file);
7640 if (linelen == -1) {
7641 if (ferror(a->patch_script_file))
7642 return got_error_from_errno("getline");
7643 return NULL;
7645 nl = strchr(line, '\n');
7646 if (nl)
7647 *nl = '\0';
7648 if (strcmp(line, "y") == 0) {
7649 *choice = GOT_PATCH_CHOICE_YES;
7650 printf("y\n");
7651 } else if (strcmp(line, "n") == 0) {
7652 *choice = GOT_PATCH_CHOICE_NO;
7653 printf("n\n");
7654 } else if (strcmp(line, "q") == 0 &&
7655 status == GOT_STATUS_MODIFY) {
7656 *choice = GOT_PATCH_CHOICE_QUIT;
7657 printf("q\n");
7658 } else
7659 printf("invalid response '%s'\n", line);
7660 free(line);
7661 return NULL;
7664 while (resp != 'y' && resp != 'n' && resp != 'q') {
7665 err = show_change(status, path, patch_file, n, nchanges,
7666 a->action);
7667 if (err)
7668 return err;
7669 resp = getchar();
7670 if (resp == '\n')
7671 resp = getchar();
7672 if (status == GOT_STATUS_MODIFY) {
7673 if (resp != 'y' && resp != 'n' && resp != 'q') {
7674 printf("invalid response '%c'\n", resp);
7675 resp = ' ';
7677 } else if (resp != 'y' && resp != 'n') {
7678 printf("invalid response '%c'\n", resp);
7679 resp = ' ';
7683 if (resp == 'y')
7684 *choice = GOT_PATCH_CHOICE_YES;
7685 else if (resp == 'n')
7686 *choice = GOT_PATCH_CHOICE_NO;
7687 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7688 *choice = GOT_PATCH_CHOICE_QUIT;
7690 return NULL;
7693 static const struct got_error *
7694 cmd_revert(int argc, char *argv[])
7696 const struct got_error *error = NULL;
7697 struct got_worktree *worktree = NULL;
7698 struct got_repository *repo = NULL;
7699 char *cwd = NULL, *path = NULL;
7700 struct got_pathlist_head paths;
7701 struct got_pathlist_entry *pe;
7702 int ch, can_recurse = 0, pflag = 0;
7703 FILE *patch_script_file = NULL;
7704 const char *patch_script_path = NULL;
7705 struct choose_patch_arg cpa;
7707 TAILQ_INIT(&paths);
7709 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7710 switch (ch) {
7711 case 'p':
7712 pflag = 1;
7713 break;
7714 case 'F':
7715 patch_script_path = optarg;
7716 break;
7717 case 'R':
7718 can_recurse = 1;
7719 break;
7720 default:
7721 usage_revert();
7722 /* NOTREACHED */
7726 argc -= optind;
7727 argv += optind;
7729 #ifndef PROFILE
7730 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7731 "unveil", NULL) == -1)
7732 err(1, "pledge");
7733 #endif
7734 if (argc < 1)
7735 usage_revert();
7736 if (patch_script_path && !pflag)
7737 errx(1, "-F option can only be used together with -p option");
7739 cwd = getcwd(NULL, 0);
7740 if (cwd == NULL) {
7741 error = got_error_from_errno("getcwd");
7742 goto done;
7744 error = got_worktree_open(&worktree, cwd);
7745 if (error) {
7746 if (error->code == GOT_ERR_NOT_WORKTREE)
7747 error = wrap_not_worktree_error(error, "revert", cwd);
7748 goto done;
7751 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7752 NULL);
7753 if (error != NULL)
7754 goto done;
7756 if (patch_script_path) {
7757 patch_script_file = fopen(patch_script_path, "re");
7758 if (patch_script_file == NULL) {
7759 error = got_error_from_errno2("fopen",
7760 patch_script_path);
7761 goto done;
7764 error = apply_unveil(got_repo_get_path(repo), 1,
7765 got_worktree_get_root_path(worktree));
7766 if (error)
7767 goto done;
7769 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7770 if (error)
7771 goto done;
7773 if (!can_recurse) {
7774 char *ondisk_path;
7775 struct stat sb;
7776 TAILQ_FOREACH(pe, &paths, entry) {
7777 if (asprintf(&ondisk_path, "%s/%s",
7778 got_worktree_get_root_path(worktree),
7779 pe->path) == -1) {
7780 error = got_error_from_errno("asprintf");
7781 goto done;
7783 if (lstat(ondisk_path, &sb) == -1) {
7784 if (errno == ENOENT) {
7785 free(ondisk_path);
7786 continue;
7788 error = got_error_from_errno2("lstat",
7789 ondisk_path);
7790 free(ondisk_path);
7791 goto done;
7793 free(ondisk_path);
7794 if (S_ISDIR(sb.st_mode)) {
7795 error = got_error_msg(GOT_ERR_BAD_PATH,
7796 "reverting directories requires -R option");
7797 goto done;
7802 cpa.patch_script_file = patch_script_file;
7803 cpa.action = "revert";
7804 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7805 pflag ? choose_patch : NULL, &cpa, repo);
7806 done:
7807 if (patch_script_file && fclose(patch_script_file) == EOF &&
7808 error == NULL)
7809 error = got_error_from_errno2("fclose", patch_script_path);
7810 if (repo) {
7811 const struct got_error *close_err = got_repo_close(repo);
7812 if (error == NULL)
7813 error = close_err;
7815 if (worktree)
7816 got_worktree_close(worktree);
7817 free(path);
7818 free(cwd);
7819 return error;
7822 __dead static void
7823 usage_commit(void)
7825 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7826 "[path ...]\n", getprogname());
7827 exit(1);
7830 struct collect_commit_logmsg_arg {
7831 const char *cmdline_log;
7832 const char *prepared_log;
7833 int non_interactive;
7834 const char *editor;
7835 const char *worktree_path;
7836 const char *branch_name;
7837 const char *repo_path;
7838 char *logmsg_path;
7842 static const struct got_error *
7843 read_prepared_logmsg(char **logmsg, const char *path)
7845 const struct got_error *err = NULL;
7846 FILE *f = NULL;
7847 struct stat sb;
7848 size_t r;
7850 *logmsg = NULL;
7851 memset(&sb, 0, sizeof(sb));
7853 f = fopen(path, "re");
7854 if (f == NULL)
7855 return got_error_from_errno2("fopen", path);
7857 if (fstat(fileno(f), &sb) == -1) {
7858 err = got_error_from_errno2("fstat", path);
7859 goto done;
7861 if (sb.st_size == 0) {
7862 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7863 goto done;
7866 *logmsg = malloc(sb.st_size + 1);
7867 if (*logmsg == NULL) {
7868 err = got_error_from_errno("malloc");
7869 goto done;
7872 r = fread(*logmsg, 1, sb.st_size, f);
7873 if (r != sb.st_size) {
7874 if (ferror(f))
7875 err = got_error_from_errno2("fread", path);
7876 else
7877 err = got_error(GOT_ERR_IO);
7878 goto done;
7880 (*logmsg)[sb.st_size] = '\0';
7881 done:
7882 if (fclose(f) == EOF && err == NULL)
7883 err = got_error_from_errno2("fclose", path);
7884 if (err) {
7885 free(*logmsg);
7886 *logmsg = NULL;
7888 return err;
7892 static const struct got_error *
7893 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7894 void *arg)
7896 char *initial_content = NULL;
7897 struct got_pathlist_entry *pe;
7898 const struct got_error *err = NULL;
7899 char *template = NULL;
7900 struct collect_commit_logmsg_arg *a = arg;
7901 int initial_content_len;
7902 int fd = -1;
7903 size_t len;
7905 /* if a message was specified on the command line, just use it */
7906 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7907 len = strlen(a->cmdline_log) + 1;
7908 *logmsg = malloc(len + 1);
7909 if (*logmsg == NULL)
7910 return got_error_from_errno("malloc");
7911 strlcpy(*logmsg, a->cmdline_log, len);
7912 return NULL;
7913 } else if (a->prepared_log != NULL && a->non_interactive)
7914 return read_prepared_logmsg(logmsg, a->prepared_log);
7916 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7917 return got_error_from_errno("asprintf");
7919 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7920 if (err)
7921 goto done;
7923 if (a->prepared_log) {
7924 char *msg;
7925 err = read_prepared_logmsg(&msg, a->prepared_log);
7926 if (err)
7927 goto done;
7928 if (write(fd, msg, strlen(msg)) == -1) {
7929 err = got_error_from_errno2("write", a->logmsg_path);
7930 free(msg);
7931 goto done;
7933 free(msg);
7936 initial_content_len = asprintf(&initial_content,
7937 "\n# changes to be committed on branch %s:\n",
7938 a->branch_name);
7939 if (initial_content_len == -1) {
7940 err = got_error_from_errno("asprintf");
7941 goto done;
7944 if (write(fd, initial_content, initial_content_len) == -1) {
7945 err = got_error_from_errno2("write", a->logmsg_path);
7946 goto done;
7949 TAILQ_FOREACH(pe, commitable_paths, entry) {
7950 struct got_commitable *ct = pe->data;
7951 dprintf(fd, "# %c %s\n",
7952 got_commitable_get_status(ct),
7953 got_commitable_get_path(ct));
7956 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7957 initial_content_len, a->prepared_log ? 0 : 1);
7958 done:
7959 free(initial_content);
7960 free(template);
7962 if (fd != -1 && close(fd) == -1 && err == NULL)
7963 err = got_error_from_errno2("close", a->logmsg_path);
7965 /* Editor is done; we can now apply unveil(2) */
7966 if (err == NULL)
7967 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7968 if (err) {
7969 free(*logmsg);
7970 *logmsg = NULL;
7972 return err;
7975 static const struct got_error *
7976 cmd_commit(int argc, char *argv[])
7978 const struct got_error *error = NULL;
7979 struct got_worktree *worktree = NULL;
7980 struct got_repository *repo = NULL;
7981 char *cwd = NULL, *id_str = NULL;
7982 struct got_object_id *id = NULL;
7983 const char *logmsg = NULL;
7984 char *prepared_logmsg = NULL;
7985 struct collect_commit_logmsg_arg cl_arg;
7986 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7987 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7988 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7989 struct got_pathlist_head paths;
7991 TAILQ_INIT(&paths);
7992 cl_arg.logmsg_path = NULL;
7994 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7995 switch (ch) {
7996 case 'F':
7997 if (logmsg != NULL)
7998 option_conflict('F', 'm');
7999 prepared_logmsg = realpath(optarg, NULL);
8000 if (prepared_logmsg == NULL)
8001 return got_error_from_errno2("realpath",
8002 optarg);
8003 break;
8004 case 'm':
8005 if (prepared_logmsg)
8006 option_conflict('m', 'F');
8007 logmsg = optarg;
8008 break;
8009 case 'N':
8010 non_interactive = 1;
8011 break;
8012 case 'S':
8013 allow_bad_symlinks = 1;
8014 break;
8015 default:
8016 usage_commit();
8017 /* NOTREACHED */
8021 argc -= optind;
8022 argv += optind;
8024 #ifndef PROFILE
8025 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8026 "unveil", NULL) == -1)
8027 err(1, "pledge");
8028 #endif
8029 cwd = getcwd(NULL, 0);
8030 if (cwd == NULL) {
8031 error = got_error_from_errno("getcwd");
8032 goto done;
8034 error = got_worktree_open(&worktree, cwd);
8035 if (error) {
8036 if (error->code == GOT_ERR_NOT_WORKTREE)
8037 error = wrap_not_worktree_error(error, "commit", cwd);
8038 goto done;
8041 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8042 if (error)
8043 goto done;
8044 if (rebase_in_progress) {
8045 error = got_error(GOT_ERR_REBASING);
8046 goto done;
8049 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8050 worktree);
8051 if (error)
8052 goto done;
8054 error = get_gitconfig_path(&gitconfig_path);
8055 if (error)
8056 goto done;
8057 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8058 gitconfig_path);
8059 if (error != NULL)
8060 goto done;
8062 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8063 if (error)
8064 goto done;
8065 if (merge_in_progress) {
8066 error = got_error(GOT_ERR_MERGE_BUSY);
8067 goto done;
8070 error = get_author(&author, repo, worktree);
8071 if (error)
8072 return error;
8075 * unveil(2) traverses exec(2); if an editor is used we have
8076 * to apply unveil after the log message has been written.
8078 if (logmsg == NULL || strlen(logmsg) == 0)
8079 error = get_editor(&editor);
8080 else
8081 error = apply_unveil(got_repo_get_path(repo), 0,
8082 got_worktree_get_root_path(worktree));
8083 if (error)
8084 goto done;
8086 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8087 if (error)
8088 goto done;
8090 cl_arg.editor = editor;
8091 cl_arg.cmdline_log = logmsg;
8092 cl_arg.prepared_log = prepared_logmsg;
8093 cl_arg.non_interactive = non_interactive;
8094 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8095 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8096 if (!histedit_in_progress) {
8097 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8098 error = got_error(GOT_ERR_COMMIT_BRANCH);
8099 goto done;
8101 cl_arg.branch_name += 11;
8103 cl_arg.repo_path = got_repo_get_path(repo);
8104 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8105 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8106 print_status, NULL, repo);
8107 if (error) {
8108 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8109 cl_arg.logmsg_path != NULL)
8110 preserve_logmsg = 1;
8111 goto done;
8114 error = got_object_id_str(&id_str, id);
8115 if (error)
8116 goto done;
8117 printf("Created commit %s\n", id_str);
8118 done:
8119 if (preserve_logmsg) {
8120 fprintf(stderr, "%s: log message preserved in %s\n",
8121 getprogname(), cl_arg.logmsg_path);
8122 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8123 error == NULL)
8124 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8125 free(cl_arg.logmsg_path);
8126 if (repo) {
8127 const struct got_error *close_err = got_repo_close(repo);
8128 if (error == NULL)
8129 error = close_err;
8131 if (worktree)
8132 got_worktree_close(worktree);
8133 free(cwd);
8134 free(id_str);
8135 free(gitconfig_path);
8136 free(editor);
8137 free(author);
8138 free(prepared_logmsg);
8139 return error;
8142 __dead static void
8143 usage_send(void)
8145 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8146 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8147 "[remote-repository]\n", getprogname());
8148 exit(1);
8151 static void
8152 print_load_info(int print_colored, int print_found, int print_trees,
8153 int ncolored, int nfound, int ntrees)
8155 if (print_colored) {
8156 printf("%d commit%s colored", ncolored,
8157 ncolored == 1 ? "" : "s");
8159 if (print_found) {
8160 printf("%s%d object%s found",
8161 ncolored > 0 ? "; " : "",
8162 nfound, nfound == 1 ? "" : "s");
8164 if (print_trees) {
8165 printf("; %d tree%s scanned", ntrees,
8166 ntrees == 1 ? "" : "s");
8170 struct got_send_progress_arg {
8171 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8172 int verbosity;
8173 int last_ncolored;
8174 int last_nfound;
8175 int last_ntrees;
8176 int loading_done;
8177 int last_ncommits;
8178 int last_nobj_total;
8179 int last_p_deltify;
8180 int last_p_written;
8181 int last_p_sent;
8182 int printed_something;
8183 int sent_something;
8184 struct got_pathlist_head *delete_branches;
8187 static const struct got_error *
8188 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8189 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8190 int nobj_written, off_t bytes_sent, const char *refname, int success)
8192 struct got_send_progress_arg *a = arg;
8193 char scaled_packsize[FMT_SCALED_STRSIZE];
8194 char scaled_sent[FMT_SCALED_STRSIZE];
8195 int p_deltify = 0, p_written = 0, p_sent = 0;
8196 int print_colored = 0, print_found = 0, print_trees = 0;
8197 int print_searching = 0, print_total = 0;
8198 int print_deltify = 0, print_written = 0, print_sent = 0;
8200 if (a->verbosity < 0)
8201 return NULL;
8203 if (refname) {
8204 const char *status = success ? "accepted" : "rejected";
8206 if (success) {
8207 struct got_pathlist_entry *pe;
8208 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8209 const char *branchname = pe->path;
8210 if (got_path_cmp(branchname, refname,
8211 strlen(branchname), strlen(refname)) == 0) {
8212 status = "deleted";
8213 a->sent_something = 1;
8214 break;
8219 if (a->printed_something)
8220 putchar('\n');
8221 printf("Server has %s %s", status, refname);
8222 a->printed_something = 1;
8223 return NULL;
8226 if (a->last_ncolored != ncolored) {
8227 print_colored = 1;
8228 a->last_ncolored = ncolored;
8231 if (a->last_nfound != nfound) {
8232 print_colored = 1;
8233 print_found = 1;
8234 a->last_nfound = nfound;
8237 if (a->last_ntrees != ntrees) {
8238 print_colored = 1;
8239 print_found = 1;
8240 print_trees = 1;
8241 a->last_ntrees = ntrees;
8244 if ((print_colored || print_found || print_trees) &&
8245 !a->loading_done) {
8246 printf("\r");
8247 print_load_info(print_colored, print_found, print_trees,
8248 ncolored, nfound, ntrees);
8249 a->printed_something = 1;
8250 fflush(stdout);
8251 return NULL;
8252 } else if (!a->loading_done) {
8253 printf("\r");
8254 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8255 printf("\n");
8256 a->loading_done = 1;
8259 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8260 return got_error_from_errno("fmt_scaled");
8261 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8262 return got_error_from_errno("fmt_scaled");
8264 if (a->last_ncommits != ncommits) {
8265 print_searching = 1;
8266 a->last_ncommits = ncommits;
8269 if (a->last_nobj_total != nobj_total) {
8270 print_searching = 1;
8271 print_total = 1;
8272 a->last_nobj_total = nobj_total;
8275 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8276 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8277 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8278 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8279 return got_error(GOT_ERR_NO_SPACE);
8282 if (nobj_deltify > 0 || nobj_written > 0) {
8283 if (nobj_deltify > 0) {
8284 p_deltify = (nobj_deltify * 100) / nobj_total;
8285 if (p_deltify != a->last_p_deltify) {
8286 a->last_p_deltify = p_deltify;
8287 print_searching = 1;
8288 print_total = 1;
8289 print_deltify = 1;
8292 if (nobj_written > 0) {
8293 p_written = (nobj_written * 100) / nobj_total;
8294 if (p_written != a->last_p_written) {
8295 a->last_p_written = p_written;
8296 print_searching = 1;
8297 print_total = 1;
8298 print_deltify = 1;
8299 print_written = 1;
8304 if (bytes_sent > 0) {
8305 p_sent = (bytes_sent * 100) / packfile_size;
8306 if (p_sent != a->last_p_sent) {
8307 a->last_p_sent = p_sent;
8308 print_searching = 1;
8309 print_total = 1;
8310 print_deltify = 1;
8311 print_written = 1;
8312 print_sent = 1;
8314 a->sent_something = 1;
8317 if (print_searching || print_total || print_deltify || print_written ||
8318 print_sent)
8319 printf("\r");
8320 if (print_searching)
8321 printf("packing %d reference%s", ncommits,
8322 ncommits == 1 ? "" : "s");
8323 if (print_total)
8324 printf("; %d object%s", nobj_total,
8325 nobj_total == 1 ? "" : "s");
8326 if (print_deltify)
8327 printf("; deltify: %d%%", p_deltify);
8328 if (print_sent)
8329 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8330 scaled_packsize, p_sent);
8331 else if (print_written)
8332 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8333 scaled_packsize, p_written);
8334 if (print_searching || print_total || print_deltify ||
8335 print_written || print_sent) {
8336 a->printed_something = 1;
8337 fflush(stdout);
8339 return NULL;
8342 static const struct got_error *
8343 cmd_send(int argc, char *argv[])
8345 const struct got_error *error = NULL;
8346 char *cwd = NULL, *repo_path = NULL;
8347 const char *remote_name;
8348 char *proto = NULL, *host = NULL, *port = NULL;
8349 char *repo_name = NULL, *server_path = NULL;
8350 const struct got_remote_repo *remotes, *remote = NULL;
8351 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8352 struct got_repository *repo = NULL;
8353 struct got_worktree *worktree = NULL;
8354 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8355 struct got_pathlist_head branches;
8356 struct got_pathlist_head tags;
8357 struct got_reflist_head all_branches;
8358 struct got_reflist_head all_tags;
8359 struct got_pathlist_head delete_args;
8360 struct got_pathlist_head delete_branches;
8361 struct got_reflist_entry *re;
8362 struct got_pathlist_entry *pe;
8363 int i, ch, sendfd = -1, sendstatus;
8364 pid_t sendpid = -1;
8365 struct got_send_progress_arg spa;
8366 int verbosity = 0, overwrite_refs = 0;
8367 int send_all_branches = 0, send_all_tags = 0;
8368 struct got_reference *ref = NULL;
8370 TAILQ_INIT(&branches);
8371 TAILQ_INIT(&tags);
8372 TAILQ_INIT(&all_branches);
8373 TAILQ_INIT(&all_tags);
8374 TAILQ_INIT(&delete_args);
8375 TAILQ_INIT(&delete_branches);
8377 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8378 switch (ch) {
8379 case 'a':
8380 send_all_branches = 1;
8381 break;
8382 case 'b':
8383 error = got_pathlist_append(&branches, optarg, NULL);
8384 if (error)
8385 return error;
8386 nbranches++;
8387 break;
8388 case 'd':
8389 error = got_pathlist_append(&delete_args, optarg, NULL);
8390 if (error)
8391 return error;
8392 break;
8393 case 'f':
8394 overwrite_refs = 1;
8395 break;
8396 case 'r':
8397 repo_path = realpath(optarg, NULL);
8398 if (repo_path == NULL)
8399 return got_error_from_errno2("realpath",
8400 optarg);
8401 got_path_strip_trailing_slashes(repo_path);
8402 break;
8403 case 't':
8404 error = got_pathlist_append(&tags, optarg, NULL);
8405 if (error)
8406 return error;
8407 ntags++;
8408 break;
8409 case 'T':
8410 send_all_tags = 1;
8411 break;
8412 case 'v':
8413 if (verbosity < 0)
8414 verbosity = 0;
8415 else if (verbosity < 3)
8416 verbosity++;
8417 break;
8418 case 'q':
8419 verbosity = -1;
8420 break;
8421 default:
8422 usage_send();
8423 /* NOTREACHED */
8426 argc -= optind;
8427 argv += optind;
8429 if (send_all_branches && !TAILQ_EMPTY(&branches))
8430 option_conflict('a', 'b');
8431 if (send_all_tags && !TAILQ_EMPTY(&tags))
8432 option_conflict('T', 't');
8435 if (argc == 0)
8436 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8437 else if (argc == 1)
8438 remote_name = argv[0];
8439 else
8440 usage_send();
8442 cwd = getcwd(NULL, 0);
8443 if (cwd == NULL) {
8444 error = got_error_from_errno("getcwd");
8445 goto done;
8448 if (repo_path == NULL) {
8449 error = got_worktree_open(&worktree, cwd);
8450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8451 goto done;
8452 else
8453 error = NULL;
8454 if (worktree) {
8455 repo_path =
8456 strdup(got_worktree_get_repo_path(worktree));
8457 if (repo_path == NULL)
8458 error = got_error_from_errno("strdup");
8459 if (error)
8460 goto done;
8461 } else {
8462 repo_path = strdup(cwd);
8463 if (repo_path == NULL) {
8464 error = got_error_from_errno("strdup");
8465 goto done;
8470 error = got_repo_open(&repo, repo_path, NULL);
8471 if (error)
8472 goto done;
8474 if (worktree) {
8475 worktree_conf = got_worktree_get_gotconfig(worktree);
8476 if (worktree_conf) {
8477 got_gotconfig_get_remotes(&nremotes, &remotes,
8478 worktree_conf);
8479 for (i = 0; i < nremotes; i++) {
8480 if (strcmp(remotes[i].name, remote_name) == 0) {
8481 remote = &remotes[i];
8482 break;
8487 if (remote == NULL) {
8488 repo_conf = got_repo_get_gotconfig(repo);
8489 if (repo_conf) {
8490 got_gotconfig_get_remotes(&nremotes, &remotes,
8491 repo_conf);
8492 for (i = 0; i < nremotes; i++) {
8493 if (strcmp(remotes[i].name, remote_name) == 0) {
8494 remote = &remotes[i];
8495 break;
8500 if (remote == NULL) {
8501 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8502 for (i = 0; i < nremotes; i++) {
8503 if (strcmp(remotes[i].name, remote_name) == 0) {
8504 remote = &remotes[i];
8505 break;
8509 if (remote == NULL) {
8510 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8511 goto done;
8514 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8515 &repo_name, remote->send_url);
8516 if (error)
8517 goto done;
8519 if (strcmp(proto, "git") == 0) {
8520 #ifndef PROFILE
8521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8522 "sendfd dns inet unveil", NULL) == -1)
8523 err(1, "pledge");
8524 #endif
8525 } else if (strcmp(proto, "git+ssh") == 0 ||
8526 strcmp(proto, "ssh") == 0) {
8527 #ifndef PROFILE
8528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8529 "sendfd unveil", NULL) == -1)
8530 err(1, "pledge");
8531 #endif
8532 } else if (strcmp(proto, "http") == 0 ||
8533 strcmp(proto, "git+http") == 0) {
8534 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8535 goto done;
8536 } else {
8537 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8538 goto done;
8541 error = got_dial_apply_unveil(proto);
8542 if (error)
8543 goto done;
8545 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8546 if (error)
8547 goto done;
8549 if (send_all_branches) {
8550 error = got_ref_list(&all_branches, repo, "refs/heads",
8551 got_ref_cmp_by_name, NULL);
8552 if (error)
8553 goto done;
8554 TAILQ_FOREACH(re, &all_branches, entry) {
8555 const char *branchname = got_ref_get_name(re->ref);
8556 error = got_pathlist_append(&branches,
8557 branchname, NULL);
8558 if (error)
8559 goto done;
8560 nbranches++;
8562 } else if (nbranches == 0) {
8563 for (i = 0; i < remote->nsend_branches; i++) {
8564 got_pathlist_append(&branches,
8565 remote->send_branches[i], NULL);
8569 if (send_all_tags) {
8570 error = got_ref_list(&all_tags, repo, "refs/tags",
8571 got_ref_cmp_by_name, NULL);
8572 if (error)
8573 goto done;
8574 TAILQ_FOREACH(re, &all_tags, entry) {
8575 const char *tagname = got_ref_get_name(re->ref);
8576 error = got_pathlist_append(&tags,
8577 tagname, NULL);
8578 if (error)
8579 goto done;
8580 ntags++;
8585 * To prevent accidents only branches in refs/heads/ can be deleted
8586 * with 'got send -d'.
8587 * Deleting anything else requires local repository access or Git.
8589 TAILQ_FOREACH(pe, &delete_args, entry) {
8590 const char *branchname = pe->path;
8591 char *s;
8592 struct got_pathlist_entry *new;
8593 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8594 s = strdup(branchname);
8595 if (s == NULL) {
8596 error = got_error_from_errno("strdup");
8597 goto done;
8599 } else {
8600 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8601 error = got_error_from_errno("asprintf");
8602 goto done;
8605 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8606 if (error || new == NULL /* duplicate */)
8607 free(s);
8608 if (error)
8609 goto done;
8610 ndelete_branches++;
8613 if (nbranches == 0 && ndelete_branches == 0) {
8614 struct got_reference *head_ref;
8615 if (worktree)
8616 error = got_ref_open(&head_ref, repo,
8617 got_worktree_get_head_ref_name(worktree), 0);
8618 else
8619 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8620 if (error)
8621 goto done;
8622 if (got_ref_is_symbolic(head_ref)) {
8623 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8624 got_ref_close(head_ref);
8625 if (error)
8626 goto done;
8627 } else
8628 ref = head_ref;
8629 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8630 NULL);
8631 if (error)
8632 goto done;
8633 nbranches++;
8636 if (verbosity >= 0)
8637 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8638 port ? ":" : "", port ? port : "");
8640 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8641 server_path, verbosity);
8642 if (error)
8643 goto done;
8645 memset(&spa, 0, sizeof(spa));
8646 spa.last_scaled_packsize[0] = '\0';
8647 spa.last_p_deltify = -1;
8648 spa.last_p_written = -1;
8649 spa.verbosity = verbosity;
8650 spa.delete_branches = &delete_branches;
8651 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8652 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8653 check_cancelled, NULL);
8654 if (spa.printed_something)
8655 putchar('\n');
8656 if (error)
8657 goto done;
8658 if (!spa.sent_something && verbosity >= 0)
8659 printf("Already up-to-date\n");
8660 done:
8661 if (sendpid > 0) {
8662 if (kill(sendpid, SIGTERM) == -1)
8663 error = got_error_from_errno("kill");
8664 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8665 error = got_error_from_errno("waitpid");
8667 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8668 error = got_error_from_errno("close");
8669 if (repo) {
8670 const struct got_error *close_err = got_repo_close(repo);
8671 if (error == NULL)
8672 error = close_err;
8674 if (worktree)
8675 got_worktree_close(worktree);
8676 if (ref)
8677 got_ref_close(ref);
8678 got_pathlist_free(&branches);
8679 got_pathlist_free(&tags);
8680 got_ref_list_free(&all_branches);
8681 got_ref_list_free(&all_tags);
8682 got_pathlist_free(&delete_args);
8683 TAILQ_FOREACH(pe, &delete_branches, entry)
8684 free((char *)pe->path);
8685 got_pathlist_free(&delete_branches);
8686 free(cwd);
8687 free(repo_path);
8688 free(proto);
8689 free(host);
8690 free(port);
8691 free(server_path);
8692 free(repo_name);
8693 return error;
8696 __dead static void
8697 usage_cherrypick(void)
8699 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8700 exit(1);
8703 static const struct got_error *
8704 cmd_cherrypick(int argc, char *argv[])
8706 const struct got_error *error = NULL;
8707 struct got_worktree *worktree = NULL;
8708 struct got_repository *repo = NULL;
8709 char *cwd = NULL, *commit_id_str = NULL;
8710 struct got_object_id *commit_id = NULL;
8711 struct got_commit_object *commit = NULL;
8712 struct got_object_qid *pid;
8713 int ch;
8714 struct got_update_progress_arg upa;
8716 while ((ch = getopt(argc, argv, "")) != -1) {
8717 switch (ch) {
8718 default:
8719 usage_cherrypick();
8720 /* NOTREACHED */
8724 argc -= optind;
8725 argv += optind;
8727 #ifndef PROFILE
8728 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8729 "unveil", NULL) == -1)
8730 err(1, "pledge");
8731 #endif
8732 if (argc != 1)
8733 usage_cherrypick();
8735 cwd = getcwd(NULL, 0);
8736 if (cwd == NULL) {
8737 error = got_error_from_errno("getcwd");
8738 goto done;
8740 error = got_worktree_open(&worktree, cwd);
8741 if (error) {
8742 if (error->code == GOT_ERR_NOT_WORKTREE)
8743 error = wrap_not_worktree_error(error, "cherrypick",
8744 cwd);
8745 goto done;
8748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8749 NULL);
8750 if (error != NULL)
8751 goto done;
8753 error = apply_unveil(got_repo_get_path(repo), 0,
8754 got_worktree_get_root_path(worktree));
8755 if (error)
8756 goto done;
8758 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8759 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8760 if (error)
8761 goto done;
8762 error = got_object_id_str(&commit_id_str, commit_id);
8763 if (error)
8764 goto done;
8766 error = got_object_open_as_commit(&commit, repo, commit_id);
8767 if (error)
8768 goto done;
8769 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8770 memset(&upa, 0, sizeof(upa));
8771 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8772 commit_id, repo, update_progress, &upa, check_cancelled,
8773 NULL);
8774 if (error != NULL)
8775 goto done;
8777 if (upa.did_something)
8778 printf("Merged commit %s\n", commit_id_str);
8779 print_merge_progress_stats(&upa);
8780 done:
8781 if (commit)
8782 got_object_commit_close(commit);
8783 free(commit_id_str);
8784 if (worktree)
8785 got_worktree_close(worktree);
8786 if (repo) {
8787 const struct got_error *close_err = got_repo_close(repo);
8788 if (error == NULL)
8789 error = close_err;
8791 return error;
8794 __dead static void
8795 usage_backout(void)
8797 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8798 exit(1);
8801 static const struct got_error *
8802 cmd_backout(int argc, char *argv[])
8804 const struct got_error *error = NULL;
8805 struct got_worktree *worktree = NULL;
8806 struct got_repository *repo = NULL;
8807 char *cwd = NULL, *commit_id_str = NULL;
8808 struct got_object_id *commit_id = NULL;
8809 struct got_commit_object *commit = NULL;
8810 struct got_object_qid *pid;
8811 int ch;
8812 struct got_update_progress_arg upa;
8814 while ((ch = getopt(argc, argv, "")) != -1) {
8815 switch (ch) {
8816 default:
8817 usage_backout();
8818 /* NOTREACHED */
8822 argc -= optind;
8823 argv += optind;
8825 #ifndef PROFILE
8826 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8827 "unveil", NULL) == -1)
8828 err(1, "pledge");
8829 #endif
8830 if (argc != 1)
8831 usage_backout();
8833 cwd = getcwd(NULL, 0);
8834 if (cwd == NULL) {
8835 error = got_error_from_errno("getcwd");
8836 goto done;
8838 error = got_worktree_open(&worktree, cwd);
8839 if (error) {
8840 if (error->code == GOT_ERR_NOT_WORKTREE)
8841 error = wrap_not_worktree_error(error, "backout", cwd);
8842 goto done;
8845 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8846 NULL);
8847 if (error != NULL)
8848 goto done;
8850 error = apply_unveil(got_repo_get_path(repo), 0,
8851 got_worktree_get_root_path(worktree));
8852 if (error)
8853 goto done;
8855 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8856 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8857 if (error)
8858 goto done;
8859 error = got_object_id_str(&commit_id_str, commit_id);
8860 if (error)
8861 goto done;
8863 error = got_object_open_as_commit(&commit, repo, commit_id);
8864 if (error)
8865 goto done;
8866 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8867 if (pid == NULL) {
8868 error = got_error(GOT_ERR_ROOT_COMMIT);
8869 goto done;
8872 memset(&upa, 0, sizeof(upa));
8873 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8874 repo, update_progress, &upa, check_cancelled, NULL);
8875 if (error != NULL)
8876 goto done;
8878 if (upa.did_something)
8879 printf("Backed out commit %s\n", commit_id_str);
8880 print_merge_progress_stats(&upa);
8881 done:
8882 if (commit)
8883 got_object_commit_close(commit);
8884 free(commit_id_str);
8885 if (worktree)
8886 got_worktree_close(worktree);
8887 if (repo) {
8888 const struct got_error *close_err = got_repo_close(repo);
8889 if (error == NULL)
8890 error = close_err;
8892 return error;
8895 __dead static void
8896 usage_rebase(void)
8898 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8899 getprogname());
8900 exit(1);
8903 void
8904 trim_logmsg(char *logmsg, int limit)
8906 char *nl;
8907 size_t len;
8909 len = strlen(logmsg);
8910 if (len > limit)
8911 len = limit;
8912 logmsg[len] = '\0';
8913 nl = strchr(logmsg, '\n');
8914 if (nl)
8915 *nl = '\0';
8918 static const struct got_error *
8919 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8921 const struct got_error *err;
8922 char *logmsg0 = NULL;
8923 const char *s;
8925 err = got_object_commit_get_logmsg(&logmsg0, commit);
8926 if (err)
8927 return err;
8929 s = logmsg0;
8930 while (isspace((unsigned char)s[0]))
8931 s++;
8933 *logmsg = strdup(s);
8934 if (*logmsg == NULL) {
8935 err = got_error_from_errno("strdup");
8936 goto done;
8939 trim_logmsg(*logmsg, limit);
8940 done:
8941 free(logmsg0);
8942 return err;
8945 static const struct got_error *
8946 show_rebase_merge_conflict(struct got_object_id *id,
8947 struct got_repository *repo)
8949 const struct got_error *err;
8950 struct got_commit_object *commit = NULL;
8951 char *id_str = NULL, *logmsg = NULL;
8953 err = got_object_open_as_commit(&commit, repo, id);
8954 if (err)
8955 return err;
8957 err = got_object_id_str(&id_str, id);
8958 if (err)
8959 goto done;
8961 id_str[12] = '\0';
8963 err = get_short_logmsg(&logmsg, 42, commit);
8964 if (err)
8965 goto done;
8967 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8968 done:
8969 free(id_str);
8970 got_object_commit_close(commit);
8971 free(logmsg);
8972 return err;
8975 static const struct got_error *
8976 show_rebase_progress(struct got_commit_object *commit,
8977 struct got_object_id *old_id, struct got_object_id *new_id)
8979 const struct got_error *err;
8980 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8982 err = got_object_id_str(&old_id_str, old_id);
8983 if (err)
8984 goto done;
8986 if (new_id) {
8987 err = got_object_id_str(&new_id_str, new_id);
8988 if (err)
8989 goto done;
8992 old_id_str[12] = '\0';
8993 if (new_id_str)
8994 new_id_str[12] = '\0';
8996 err = get_short_logmsg(&logmsg, 42, commit);
8997 if (err)
8998 goto done;
9000 printf("%s -> %s: %s\n", old_id_str,
9001 new_id_str ? new_id_str : "no-op change", logmsg);
9002 done:
9003 free(old_id_str);
9004 free(new_id_str);
9005 free(logmsg);
9006 return err;
9009 static const struct got_error *
9010 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9011 struct got_reference *branch, struct got_reference *new_base_branch,
9012 struct got_reference *tmp_branch, struct got_repository *repo,
9013 int create_backup)
9015 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9016 return got_worktree_rebase_complete(worktree, fileindex,
9017 new_base_branch, tmp_branch, branch, repo, create_backup);
9020 static const struct got_error *
9021 rebase_commit(struct got_pathlist_head *merged_paths,
9022 struct got_worktree *worktree, struct got_fileindex *fileindex,
9023 struct got_reference *tmp_branch,
9024 struct got_object_id *commit_id, struct got_repository *repo)
9026 const struct got_error *error;
9027 struct got_commit_object *commit;
9028 struct got_object_id *new_commit_id;
9030 error = got_object_open_as_commit(&commit, repo, commit_id);
9031 if (error)
9032 return error;
9034 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9035 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9036 if (error) {
9037 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9038 goto done;
9039 error = show_rebase_progress(commit, commit_id, NULL);
9040 } else {
9041 error = show_rebase_progress(commit, commit_id, new_commit_id);
9042 free(new_commit_id);
9044 done:
9045 got_object_commit_close(commit);
9046 return error;
9049 struct check_path_prefix_arg {
9050 const char *path_prefix;
9051 size_t len;
9052 int errcode;
9055 static const struct got_error *
9056 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9057 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9058 struct got_object_id *id1, struct got_object_id *id2,
9059 const char *path1, const char *path2,
9060 mode_t mode1, mode_t mode2, struct got_repository *repo)
9062 struct check_path_prefix_arg *a = arg;
9064 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9065 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9066 return got_error(a->errcode);
9068 return NULL;
9071 static const struct got_error *
9072 check_path_prefix(struct got_object_id *parent_id,
9073 struct got_object_id *commit_id, const char *path_prefix,
9074 int errcode, struct got_repository *repo)
9076 const struct got_error *err;
9077 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9078 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9079 struct check_path_prefix_arg cpp_arg;
9081 if (got_path_is_root_dir(path_prefix))
9082 return NULL;
9084 err = got_object_open_as_commit(&commit, repo, commit_id);
9085 if (err)
9086 goto done;
9088 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9089 if (err)
9090 goto done;
9092 err = got_object_open_as_tree(&tree1, repo,
9093 got_object_commit_get_tree_id(parent_commit));
9094 if (err)
9095 goto done;
9097 err = got_object_open_as_tree(&tree2, repo,
9098 got_object_commit_get_tree_id(commit));
9099 if (err)
9100 goto done;
9102 cpp_arg.path_prefix = path_prefix;
9103 while (cpp_arg.path_prefix[0] == '/')
9104 cpp_arg.path_prefix++;
9105 cpp_arg.len = strlen(cpp_arg.path_prefix);
9106 cpp_arg.errcode = errcode;
9107 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9108 check_path_prefix_in_diff, &cpp_arg, 0);
9109 done:
9110 if (tree1)
9111 got_object_tree_close(tree1);
9112 if (tree2)
9113 got_object_tree_close(tree2);
9114 if (commit)
9115 got_object_commit_close(commit);
9116 if (parent_commit)
9117 got_object_commit_close(parent_commit);
9118 return err;
9121 static const struct got_error *
9122 collect_commits(struct got_object_id_queue *commits,
9123 struct got_object_id *initial_commit_id,
9124 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9125 const char *path_prefix, int path_prefix_errcode,
9126 struct got_repository *repo)
9128 const struct got_error *err = NULL;
9129 struct got_commit_graph *graph = NULL;
9130 struct got_object_id *parent_id = NULL;
9131 struct got_object_qid *qid;
9132 struct got_object_id *commit_id = initial_commit_id;
9134 err = got_commit_graph_open(&graph, "/", 1);
9135 if (err)
9136 return err;
9138 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9139 check_cancelled, NULL);
9140 if (err)
9141 goto done;
9142 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9143 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9144 check_cancelled, NULL);
9145 if (err) {
9146 if (err->code == GOT_ERR_ITER_COMPLETED) {
9147 err = got_error_msg(GOT_ERR_ANCESTRY,
9148 "ran out of commits to rebase before "
9149 "youngest common ancestor commit has "
9150 "been reached?!?");
9152 goto done;
9153 } else {
9154 err = check_path_prefix(parent_id, commit_id,
9155 path_prefix, path_prefix_errcode, repo);
9156 if (err)
9157 goto done;
9159 err = got_object_qid_alloc(&qid, commit_id);
9160 if (err)
9161 goto done;
9162 STAILQ_INSERT_HEAD(commits, qid, entry);
9163 commit_id = parent_id;
9166 done:
9167 got_commit_graph_close(graph);
9168 return err;
9171 static const struct got_error *
9172 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9174 const struct got_error *err = NULL;
9175 time_t committer_time;
9176 struct tm tm;
9177 char datebuf[11]; /* YYYY-MM-DD + NUL */
9178 char *author0 = NULL, *author, *smallerthan;
9179 char *logmsg0 = NULL, *logmsg, *newline;
9181 committer_time = got_object_commit_get_committer_time(commit);
9182 if (gmtime_r(&committer_time, &tm) == NULL)
9183 return got_error_from_errno("gmtime_r");
9184 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9185 return got_error(GOT_ERR_NO_SPACE);
9187 author0 = strdup(got_object_commit_get_author(commit));
9188 if (author0 == NULL)
9189 return got_error_from_errno("strdup");
9190 author = author0;
9191 smallerthan = strchr(author, '<');
9192 if (smallerthan && smallerthan[1] != '\0')
9193 author = smallerthan + 1;
9194 author[strcspn(author, "@>")] = '\0';
9196 err = got_object_commit_get_logmsg(&logmsg0, commit);
9197 if (err)
9198 goto done;
9199 logmsg = logmsg0;
9200 while (*logmsg == '\n')
9201 logmsg++;
9202 newline = strchr(logmsg, '\n');
9203 if (newline)
9204 *newline = '\0';
9206 if (asprintf(brief_str, "%s %s %s",
9207 datebuf, author, logmsg) == -1)
9208 err = got_error_from_errno("asprintf");
9209 done:
9210 free(author0);
9211 free(logmsg0);
9212 return err;
9215 static const struct got_error *
9216 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9217 struct got_repository *repo)
9219 const struct got_error *err;
9220 char *id_str;
9222 err = got_object_id_str(&id_str, id);
9223 if (err)
9224 return err;
9226 err = got_ref_delete(ref, repo);
9227 if (err)
9228 goto done;
9230 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9231 done:
9232 free(id_str);
9233 return err;
9236 static const struct got_error *
9237 print_backup_ref(const char *branch_name, const char *new_id_str,
9238 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9239 struct got_reflist_object_id_map *refs_idmap,
9240 struct got_repository *repo)
9242 const struct got_error *err = NULL;
9243 struct got_reflist_head *refs;
9244 char *refs_str = NULL;
9245 struct got_object_id *new_commit_id = NULL;
9246 struct got_commit_object *new_commit = NULL;
9247 char *new_commit_brief_str = NULL;
9248 struct got_object_id *yca_id = NULL;
9249 struct got_commit_object *yca_commit = NULL;
9250 char *yca_id_str = NULL, *yca_brief_str = NULL;
9251 char *custom_refs_str;
9253 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9254 return got_error_from_errno("asprintf");
9256 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9257 0, 0, refs_idmap, custom_refs_str);
9258 if (err)
9259 goto done;
9261 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9262 if (err)
9263 goto done;
9265 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9266 if (refs) {
9267 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9268 if (err)
9269 goto done;
9272 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9273 if (err)
9274 goto done;
9276 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9277 if (err)
9278 goto done;
9280 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9281 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9282 if (err)
9283 goto done;
9285 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9286 refs_str ? " (" : "", refs_str ? refs_str : "",
9287 refs_str ? ")" : "", new_commit_brief_str);
9288 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9289 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9290 free(refs_str);
9291 refs_str = NULL;
9293 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9294 if (err)
9295 goto done;
9297 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9298 if (err)
9299 goto done;
9301 err = got_object_id_str(&yca_id_str, yca_id);
9302 if (err)
9303 goto done;
9305 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9306 if (refs) {
9307 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9308 if (err)
9309 goto done;
9311 printf("history forked at %s%s%s%s\n %s\n",
9312 yca_id_str,
9313 refs_str ? " (" : "", refs_str ? refs_str : "",
9314 refs_str ? ")" : "", yca_brief_str);
9316 done:
9317 free(custom_refs_str);
9318 free(new_commit_id);
9319 free(refs_str);
9320 free(yca_id);
9321 free(yca_id_str);
9322 free(yca_brief_str);
9323 if (new_commit)
9324 got_object_commit_close(new_commit);
9325 if (yca_commit)
9326 got_object_commit_close(yca_commit);
9328 return NULL;
9331 static const struct got_error *
9332 process_backup_refs(const char *backup_ref_prefix,
9333 const char *wanted_branch_name,
9334 int delete, struct got_repository *repo)
9336 const struct got_error *err;
9337 struct got_reflist_head refs, backup_refs;
9338 struct got_reflist_entry *re;
9339 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9340 struct got_object_id *old_commit_id = NULL;
9341 char *branch_name = NULL;
9342 struct got_commit_object *old_commit = NULL;
9343 struct got_reflist_object_id_map *refs_idmap = NULL;
9344 int wanted_branch_found = 0;
9346 TAILQ_INIT(&refs);
9347 TAILQ_INIT(&backup_refs);
9349 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9350 if (err)
9351 return err;
9353 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9354 if (err)
9355 goto done;
9357 if (wanted_branch_name) {
9358 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9359 wanted_branch_name += 11;
9362 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9363 got_ref_cmp_by_commit_timestamp_descending, repo);
9364 if (err)
9365 goto done;
9367 TAILQ_FOREACH(re, &backup_refs, entry) {
9368 const char *refname = got_ref_get_name(re->ref);
9369 char *slash;
9371 err = check_cancelled(NULL);
9372 if (err)
9373 break;
9375 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9376 if (err)
9377 break;
9379 err = got_object_open_as_commit(&old_commit, repo,
9380 old_commit_id);
9381 if (err)
9382 break;
9384 if (strncmp(backup_ref_prefix, refname,
9385 backup_ref_prefix_len) == 0)
9386 refname += backup_ref_prefix_len;
9388 while (refname[0] == '/')
9389 refname++;
9391 branch_name = strdup(refname);
9392 if (branch_name == NULL) {
9393 err = got_error_from_errno("strdup");
9394 break;
9396 slash = strrchr(branch_name, '/');
9397 if (slash) {
9398 *slash = '\0';
9399 refname += strlen(branch_name) + 1;
9402 if (wanted_branch_name == NULL ||
9403 strcmp(wanted_branch_name, branch_name) == 0) {
9404 wanted_branch_found = 1;
9405 if (delete) {
9406 err = delete_backup_ref(re->ref,
9407 old_commit_id, repo);
9408 } else {
9409 err = print_backup_ref(branch_name, refname,
9410 old_commit_id, old_commit, refs_idmap,
9411 repo);
9413 if (err)
9414 break;
9417 free(old_commit_id);
9418 old_commit_id = NULL;
9419 free(branch_name);
9420 branch_name = NULL;
9421 got_object_commit_close(old_commit);
9422 old_commit = NULL;
9425 if (wanted_branch_name && !wanted_branch_found) {
9426 err = got_error_fmt(GOT_ERR_NOT_REF,
9427 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9429 done:
9430 if (refs_idmap)
9431 got_reflist_object_id_map_free(refs_idmap);
9432 got_ref_list_free(&refs);
9433 got_ref_list_free(&backup_refs);
9434 free(old_commit_id);
9435 free(branch_name);
9436 if (old_commit)
9437 got_object_commit_close(old_commit);
9438 return err;
9441 static const struct got_error *
9442 abort_progress(void *arg, unsigned char status, const char *path)
9445 * Unversioned files should not clutter progress output when
9446 * an operation is aborted.
9448 if (status == GOT_STATUS_UNVERSIONED)
9449 return NULL;
9451 return update_progress(arg, status, path);
9454 static const struct got_error *
9455 cmd_rebase(int argc, char *argv[])
9457 const struct got_error *error = NULL;
9458 struct got_worktree *worktree = NULL;
9459 struct got_repository *repo = NULL;
9460 struct got_fileindex *fileindex = NULL;
9461 char *cwd = NULL;
9462 struct got_reference *branch = NULL;
9463 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9464 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9465 struct got_object_id *resume_commit_id = NULL;
9466 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9467 struct got_commit_object *commit = NULL;
9468 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9469 int histedit_in_progress = 0, merge_in_progress = 0;
9470 int create_backup = 1, list_backups = 0, delete_backups = 0;
9471 struct got_object_id_queue commits;
9472 struct got_pathlist_head merged_paths;
9473 const struct got_object_id_queue *parent_ids;
9474 struct got_object_qid *qid, *pid;
9475 struct got_update_progress_arg upa;
9477 STAILQ_INIT(&commits);
9478 TAILQ_INIT(&merged_paths);
9479 memset(&upa, 0, sizeof(upa));
9481 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9482 switch (ch) {
9483 case 'a':
9484 abort_rebase = 1;
9485 break;
9486 case 'c':
9487 continue_rebase = 1;
9488 break;
9489 case 'l':
9490 list_backups = 1;
9491 break;
9492 case 'X':
9493 delete_backups = 1;
9494 break;
9495 default:
9496 usage_rebase();
9497 /* NOTREACHED */
9501 argc -= optind;
9502 argv += optind;
9504 #ifndef PROFILE
9505 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9506 "unveil", NULL) == -1)
9507 err(1, "pledge");
9508 #endif
9509 if (list_backups) {
9510 if (abort_rebase)
9511 option_conflict('l', 'a');
9512 if (continue_rebase)
9513 option_conflict('l', 'c');
9514 if (delete_backups)
9515 option_conflict('l', 'X');
9516 if (argc != 0 && argc != 1)
9517 usage_rebase();
9518 } else if (delete_backups) {
9519 if (abort_rebase)
9520 option_conflict('X', 'a');
9521 if (continue_rebase)
9522 option_conflict('X', 'c');
9523 if (list_backups)
9524 option_conflict('l', 'X');
9525 if (argc != 0 && argc != 1)
9526 usage_rebase();
9527 } else {
9528 if (abort_rebase && continue_rebase)
9529 usage_rebase();
9530 else if (abort_rebase || continue_rebase) {
9531 if (argc != 0)
9532 usage_rebase();
9533 } else if (argc != 1)
9534 usage_rebase();
9537 cwd = getcwd(NULL, 0);
9538 if (cwd == NULL) {
9539 error = got_error_from_errno("getcwd");
9540 goto done;
9542 error = got_worktree_open(&worktree, cwd);
9543 if (error) {
9544 if (list_backups || delete_backups) {
9545 if (error->code != GOT_ERR_NOT_WORKTREE)
9546 goto done;
9547 } else {
9548 if (error->code == GOT_ERR_NOT_WORKTREE)
9549 error = wrap_not_worktree_error(error,
9550 "rebase", cwd);
9551 goto done;
9555 error = got_repo_open(&repo,
9556 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9557 if (error != NULL)
9558 goto done;
9560 error = apply_unveil(got_repo_get_path(repo), 0,
9561 worktree ? got_worktree_get_root_path(worktree) : NULL);
9562 if (error)
9563 goto done;
9565 if (list_backups || delete_backups) {
9566 error = process_backup_refs(
9567 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9568 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9569 goto done; /* nothing else to do */
9572 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9573 worktree);
9574 if (error)
9575 goto done;
9576 if (histedit_in_progress) {
9577 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9578 goto done;
9581 error = got_worktree_merge_in_progress(&merge_in_progress,
9582 worktree, repo);
9583 if (error)
9584 goto done;
9585 if (merge_in_progress) {
9586 error = got_error(GOT_ERR_MERGE_BUSY);
9587 goto done;
9590 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9591 if (error)
9592 goto done;
9594 if (abort_rebase) {
9595 if (!rebase_in_progress) {
9596 error = got_error(GOT_ERR_NOT_REBASING);
9597 goto done;
9599 error = got_worktree_rebase_continue(&resume_commit_id,
9600 &new_base_branch, &tmp_branch, &branch, &fileindex,
9601 worktree, repo);
9602 if (error)
9603 goto done;
9604 printf("Switching work tree to %s\n",
9605 got_ref_get_symref_target(new_base_branch));
9606 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9607 new_base_branch, abort_progress, &upa);
9608 if (error)
9609 goto done;
9610 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9611 print_merge_progress_stats(&upa);
9612 goto done; /* nothing else to do */
9615 if (continue_rebase) {
9616 if (!rebase_in_progress) {
9617 error = got_error(GOT_ERR_NOT_REBASING);
9618 goto done;
9620 error = got_worktree_rebase_continue(&resume_commit_id,
9621 &new_base_branch, &tmp_branch, &branch, &fileindex,
9622 worktree, repo);
9623 if (error)
9624 goto done;
9626 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9627 resume_commit_id, repo);
9628 if (error)
9629 goto done;
9631 yca_id = got_object_id_dup(resume_commit_id);
9632 if (yca_id == NULL) {
9633 error = got_error_from_errno("got_object_id_dup");
9634 goto done;
9636 } else {
9637 error = got_ref_open(&branch, repo, argv[0], 0);
9638 if (error != NULL)
9639 goto done;
9642 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9643 if (error)
9644 goto done;
9646 if (!continue_rebase) {
9647 struct got_object_id *base_commit_id;
9649 base_commit_id = got_worktree_get_base_commit_id(worktree);
9650 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9651 base_commit_id, branch_head_commit_id, 1, repo,
9652 check_cancelled, NULL);
9653 if (error)
9654 goto done;
9655 if (yca_id == NULL) {
9656 error = got_error_msg(GOT_ERR_ANCESTRY,
9657 "specified branch shares no common ancestry "
9658 "with work tree's branch");
9659 goto done;
9662 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9663 if (error) {
9664 if (error->code != GOT_ERR_ANCESTRY)
9665 goto done;
9666 error = NULL;
9667 } else {
9668 struct got_pathlist_head paths;
9669 printf("%s is already based on %s\n",
9670 got_ref_get_name(branch),
9671 got_worktree_get_head_ref_name(worktree));
9672 error = switch_head_ref(branch, branch_head_commit_id,
9673 worktree, repo);
9674 if (error)
9675 goto done;
9676 error = got_worktree_set_base_commit_id(worktree, repo,
9677 branch_head_commit_id);
9678 if (error)
9679 goto done;
9680 TAILQ_INIT(&paths);
9681 error = got_pathlist_append(&paths, "", NULL);
9682 if (error)
9683 goto done;
9684 error = got_worktree_checkout_files(worktree,
9685 &paths, repo, update_progress, &upa,
9686 check_cancelled, NULL);
9687 got_pathlist_free(&paths);
9688 if (error)
9689 goto done;
9690 if (upa.did_something) {
9691 char *id_str;
9692 error = got_object_id_str(&id_str,
9693 branch_head_commit_id);
9694 if (error)
9695 goto done;
9696 printf("Updated to %s: %s\n",
9697 got_worktree_get_head_ref_name(worktree),
9698 id_str);
9699 free(id_str);
9700 } else
9701 printf("Already up-to-date\n");
9702 print_update_progress_stats(&upa);
9703 goto done;
9707 commit_id = branch_head_commit_id;
9708 error = got_object_open_as_commit(&commit, repo, commit_id);
9709 if (error)
9710 goto done;
9712 parent_ids = got_object_commit_get_parent_ids(commit);
9713 pid = STAILQ_FIRST(parent_ids);
9714 if (pid == NULL) {
9715 error = got_error(GOT_ERR_EMPTY_REBASE);
9716 goto done;
9718 error = collect_commits(&commits, commit_id, &pid->id,
9719 yca_id, got_worktree_get_path_prefix(worktree),
9720 GOT_ERR_REBASE_PATH, repo);
9721 got_object_commit_close(commit);
9722 commit = NULL;
9723 if (error)
9724 goto done;
9726 if (!continue_rebase) {
9727 error = got_worktree_rebase_prepare(&new_base_branch,
9728 &tmp_branch, &fileindex, worktree, branch, repo);
9729 if (error)
9730 goto done;
9733 if (STAILQ_EMPTY(&commits)) {
9734 if (continue_rebase) {
9735 error = rebase_complete(worktree, fileindex,
9736 branch, new_base_branch, tmp_branch, repo,
9737 create_backup);
9738 goto done;
9739 } else {
9740 /* Fast-forward the reference of the branch. */
9741 struct got_object_id *new_head_commit_id;
9742 char *id_str;
9743 error = got_ref_resolve(&new_head_commit_id, repo,
9744 new_base_branch);
9745 if (error)
9746 goto done;
9747 error = got_object_id_str(&id_str, new_head_commit_id);
9748 printf("Forwarding %s to commit %s\n",
9749 got_ref_get_name(branch), id_str);
9750 free(id_str);
9751 error = got_ref_change_ref(branch,
9752 new_head_commit_id);
9753 if (error)
9754 goto done;
9755 /* No backup needed since objects did not change. */
9756 create_backup = 0;
9760 pid = NULL;
9761 STAILQ_FOREACH(qid, &commits, entry) {
9763 commit_id = &qid->id;
9764 parent_id = pid ? &pid->id : yca_id;
9765 pid = qid;
9767 memset(&upa, 0, sizeof(upa));
9768 error = got_worktree_rebase_merge_files(&merged_paths,
9769 worktree, fileindex, parent_id, commit_id, repo,
9770 update_progress, &upa, check_cancelled, NULL);
9771 if (error)
9772 goto done;
9774 print_merge_progress_stats(&upa);
9775 if (upa.conflicts > 0 || upa.missing > 0 ||
9776 upa.not_deleted > 0 || upa.unversioned > 0) {
9777 if (upa.conflicts > 0) {
9778 error = show_rebase_merge_conflict(&qid->id,
9779 repo);
9780 if (error)
9781 goto done;
9783 got_worktree_rebase_pathlist_free(&merged_paths);
9784 break;
9787 error = rebase_commit(&merged_paths, worktree, fileindex,
9788 tmp_branch, commit_id, repo);
9789 got_worktree_rebase_pathlist_free(&merged_paths);
9790 if (error)
9791 goto done;
9794 if (upa.conflicts > 0 || upa.missing > 0 ||
9795 upa.not_deleted > 0 || upa.unversioned > 0) {
9796 error = got_worktree_rebase_postpone(worktree, fileindex);
9797 if (error)
9798 goto done;
9799 if (upa.conflicts > 0 && upa.missing == 0 &&
9800 upa.not_deleted == 0 && upa.unversioned == 0) {
9801 error = got_error_msg(GOT_ERR_CONFLICTS,
9802 "conflicts must be resolved before rebasing "
9803 "can continue");
9804 } else if (upa.conflicts > 0) {
9805 error = got_error_msg(GOT_ERR_CONFLICTS,
9806 "conflicts must be resolved before rebasing "
9807 "can continue; changes destined for some "
9808 "files were not yet merged and should be "
9809 "merged manually if required before the "
9810 "rebase operation is continued");
9811 } else {
9812 error = got_error_msg(GOT_ERR_CONFLICTS,
9813 "changes destined for some files were not "
9814 "yet merged and should be merged manually "
9815 "if required before the rebase operation "
9816 "is continued");
9818 } else
9819 error = rebase_complete(worktree, fileindex, branch,
9820 new_base_branch, tmp_branch, repo, create_backup);
9821 done:
9822 got_object_id_queue_free(&commits);
9823 free(branch_head_commit_id);
9824 free(resume_commit_id);
9825 free(yca_id);
9826 if (commit)
9827 got_object_commit_close(commit);
9828 if (branch)
9829 got_ref_close(branch);
9830 if (new_base_branch)
9831 got_ref_close(new_base_branch);
9832 if (tmp_branch)
9833 got_ref_close(tmp_branch);
9834 if (worktree)
9835 got_worktree_close(worktree);
9836 if (repo) {
9837 const struct got_error *close_err = got_repo_close(repo);
9838 if (error == NULL)
9839 error = close_err;
9841 return error;
9844 __dead static void
9845 usage_histedit(void)
9847 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9848 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9849 getprogname());
9850 exit(1);
9853 #define GOT_HISTEDIT_PICK 'p'
9854 #define GOT_HISTEDIT_EDIT 'e'
9855 #define GOT_HISTEDIT_FOLD 'f'
9856 #define GOT_HISTEDIT_DROP 'd'
9857 #define GOT_HISTEDIT_MESG 'm'
9859 static const struct got_histedit_cmd {
9860 unsigned char code;
9861 const char *name;
9862 const char *desc;
9863 } got_histedit_cmds[] = {
9864 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9865 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9866 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9867 "be used" },
9868 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9869 { GOT_HISTEDIT_MESG, "mesg",
9870 "single-line log message for commit above (open editor if empty)" },
9873 struct got_histedit_list_entry {
9874 TAILQ_ENTRY(got_histedit_list_entry) entry;
9875 struct got_object_id *commit_id;
9876 const struct got_histedit_cmd *cmd;
9877 char *logmsg;
9879 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9881 static const struct got_error *
9882 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9883 FILE *f, struct got_repository *repo)
9885 const struct got_error *err = NULL;
9886 char *logmsg = NULL, *id_str = NULL;
9887 struct got_commit_object *commit = NULL;
9888 int n;
9890 err = got_object_open_as_commit(&commit, repo, commit_id);
9891 if (err)
9892 goto done;
9894 err = get_short_logmsg(&logmsg, 34, commit);
9895 if (err)
9896 goto done;
9898 err = got_object_id_str(&id_str, commit_id);
9899 if (err)
9900 goto done;
9902 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9903 if (n < 0)
9904 err = got_ferror(f, GOT_ERR_IO);
9905 done:
9906 if (commit)
9907 got_object_commit_close(commit);
9908 free(id_str);
9909 free(logmsg);
9910 return err;
9913 static const struct got_error *
9914 histedit_write_commit_list(struct got_object_id_queue *commits,
9915 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9916 struct got_repository *repo)
9918 const struct got_error *err = NULL;
9919 struct got_object_qid *qid;
9920 const char *histedit_cmd = NULL;
9922 if (STAILQ_EMPTY(commits))
9923 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9925 STAILQ_FOREACH(qid, commits, entry) {
9926 histedit_cmd = got_histedit_cmds[0].name;
9927 if (edit_only)
9928 histedit_cmd = "edit";
9929 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9930 histedit_cmd = "fold";
9931 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9932 if (err)
9933 break;
9934 if (edit_logmsg_only) {
9935 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9936 if (n < 0) {
9937 err = got_ferror(f, GOT_ERR_IO);
9938 break;
9943 return err;
9946 static const struct got_error *
9947 write_cmd_list(FILE *f, const char *branch_name,
9948 struct got_object_id_queue *commits)
9950 const struct got_error *err = NULL;
9951 size_t i;
9952 int n;
9953 char *id_str;
9954 struct got_object_qid *qid;
9956 qid = STAILQ_FIRST(commits);
9957 err = got_object_id_str(&id_str, &qid->id);
9958 if (err)
9959 return err;
9961 n = fprintf(f,
9962 "# Editing the history of branch '%s' starting at\n"
9963 "# commit %s\n"
9964 "# Commits will be processed in order from top to "
9965 "bottom of this file.\n", branch_name, id_str);
9966 if (n < 0) {
9967 err = got_ferror(f, GOT_ERR_IO);
9968 goto done;
9971 n = fprintf(f, "# Available histedit commands:\n");
9972 if (n < 0) {
9973 err = got_ferror(f, GOT_ERR_IO);
9974 goto done;
9977 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9978 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9979 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9980 cmd->desc);
9981 if (n < 0) {
9982 err = got_ferror(f, GOT_ERR_IO);
9983 break;
9986 done:
9987 free(id_str);
9988 return err;
9991 static const struct got_error *
9992 histedit_syntax_error(int lineno)
9994 static char msg[42];
9995 int ret;
9997 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9998 lineno);
9999 if (ret == -1 || ret >= sizeof(msg))
10000 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10002 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10005 static const struct got_error *
10006 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10007 char *logmsg, struct got_repository *repo)
10009 const struct got_error *err;
10010 struct got_commit_object *folded_commit = NULL;
10011 char *id_str, *folded_logmsg = NULL;
10013 err = got_object_id_str(&id_str, hle->commit_id);
10014 if (err)
10015 return err;
10017 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10018 if (err)
10019 goto done;
10021 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10022 if (err)
10023 goto done;
10024 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10025 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10026 folded_logmsg) == -1) {
10027 err = got_error_from_errno("asprintf");
10029 done:
10030 if (folded_commit)
10031 got_object_commit_close(folded_commit);
10032 free(id_str);
10033 free(folded_logmsg);
10034 return err;
10037 static struct got_histedit_list_entry *
10038 get_folded_commits(struct got_histedit_list_entry *hle)
10040 struct got_histedit_list_entry *prev, *folded = NULL;
10042 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10043 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10044 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10045 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10046 folded = prev;
10047 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10050 return folded;
10053 static const struct got_error *
10054 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10055 struct got_repository *repo)
10057 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10058 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10059 const struct got_error *err = NULL;
10060 struct got_commit_object *commit = NULL;
10061 int logmsg_len;
10062 int fd;
10063 struct got_histedit_list_entry *folded = NULL;
10065 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10066 if (err)
10067 return err;
10069 folded = get_folded_commits(hle);
10070 if (folded) {
10071 while (folded != hle) {
10072 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10073 folded = TAILQ_NEXT(folded, entry);
10074 continue;
10076 err = append_folded_commit_msg(&new_msg, folded,
10077 logmsg, repo);
10078 if (err)
10079 goto done;
10080 free(logmsg);
10081 logmsg = new_msg;
10082 folded = TAILQ_NEXT(folded, entry);
10086 err = got_object_id_str(&id_str, hle->commit_id);
10087 if (err)
10088 goto done;
10089 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10090 if (err)
10091 goto done;
10092 logmsg_len = asprintf(&new_msg,
10093 "%s\n# original log message of commit %s: %s",
10094 logmsg ? logmsg : "", id_str, orig_logmsg);
10095 if (logmsg_len == -1) {
10096 err = got_error_from_errno("asprintf");
10097 goto done;
10099 free(logmsg);
10100 logmsg = new_msg;
10102 err = got_object_id_str(&id_str, hle->commit_id);
10103 if (err)
10104 goto done;
10106 err = got_opentemp_named_fd(&logmsg_path, &fd,
10107 GOT_TMPDIR_STR "/got-logmsg");
10108 if (err)
10109 goto done;
10111 write(fd, logmsg, logmsg_len);
10112 close(fd);
10114 err = get_editor(&editor);
10115 if (err)
10116 goto done;
10118 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10119 logmsg_len, 0);
10120 if (err) {
10121 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10122 goto done;
10123 err = NULL;
10124 hle->logmsg = strdup(new_msg);
10125 if (hle->logmsg == NULL)
10126 err = got_error_from_errno("strdup");
10128 done:
10129 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10130 err = got_error_from_errno2("unlink", logmsg_path);
10131 free(logmsg_path);
10132 free(logmsg);
10133 free(orig_logmsg);
10134 free(editor);
10135 if (commit)
10136 got_object_commit_close(commit);
10137 return err;
10140 static const struct got_error *
10141 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10142 FILE *f, struct got_repository *repo)
10144 const struct got_error *err = NULL;
10145 char *line = NULL, *p, *end;
10146 size_t i, size;
10147 ssize_t len;
10148 int lineno = 0;
10149 const struct got_histedit_cmd *cmd;
10150 struct got_object_id *commit_id = NULL;
10151 struct got_histedit_list_entry *hle = NULL;
10153 for (;;) {
10154 len = getline(&line, &size, f);
10155 if (len == -1) {
10156 const struct got_error *getline_err;
10157 if (feof(f))
10158 break;
10159 getline_err = got_error_from_errno("getline");
10160 err = got_ferror(f, getline_err->code);
10161 break;
10163 lineno++;
10164 p = line;
10165 while (isspace((unsigned char)p[0]))
10166 p++;
10167 if (p[0] == '#' || p[0] == '\0') {
10168 free(line);
10169 line = NULL;
10170 continue;
10172 cmd = NULL;
10173 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10174 cmd = &got_histedit_cmds[i];
10175 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10176 isspace((unsigned char)p[strlen(cmd->name)])) {
10177 p += strlen(cmd->name);
10178 break;
10180 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10181 p++;
10182 break;
10185 if (i == nitems(got_histedit_cmds)) {
10186 err = histedit_syntax_error(lineno);
10187 break;
10189 while (isspace((unsigned char)p[0]))
10190 p++;
10191 if (cmd->code == GOT_HISTEDIT_MESG) {
10192 if (hle == NULL || hle->logmsg != NULL) {
10193 err = got_error(GOT_ERR_HISTEDIT_CMD);
10194 break;
10196 if (p[0] == '\0') {
10197 err = histedit_edit_logmsg(hle, repo);
10198 if (err)
10199 break;
10200 } else {
10201 hle->logmsg = strdup(p);
10202 if (hle->logmsg == NULL) {
10203 err = got_error_from_errno("strdup");
10204 break;
10207 free(line);
10208 line = NULL;
10209 continue;
10210 } else {
10211 end = p;
10212 while (end[0] && !isspace((unsigned char)end[0]))
10213 end++;
10214 *end = '\0';
10216 err = got_object_resolve_id_str(&commit_id, repo, p);
10217 if (err) {
10218 /* override error code */
10219 err = histedit_syntax_error(lineno);
10220 break;
10223 hle = malloc(sizeof(*hle));
10224 if (hle == NULL) {
10225 err = got_error_from_errno("malloc");
10226 break;
10228 hle->cmd = cmd;
10229 hle->commit_id = commit_id;
10230 hle->logmsg = NULL;
10231 commit_id = NULL;
10232 free(line);
10233 line = NULL;
10234 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10237 free(line);
10238 free(commit_id);
10239 return err;
10242 static const struct got_error *
10243 histedit_check_script(struct got_histedit_list *histedit_cmds,
10244 struct got_object_id_queue *commits, struct got_repository *repo)
10246 const struct got_error *err = NULL;
10247 struct got_object_qid *qid;
10248 struct got_histedit_list_entry *hle;
10249 static char msg[92];
10250 char *id_str;
10252 if (TAILQ_EMPTY(histedit_cmds))
10253 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10254 "histedit script contains no commands");
10255 if (STAILQ_EMPTY(commits))
10256 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10258 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10259 struct got_histedit_list_entry *hle2;
10260 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10261 if (hle == hle2)
10262 continue;
10263 if (got_object_id_cmp(hle->commit_id,
10264 hle2->commit_id) != 0)
10265 continue;
10266 err = got_object_id_str(&id_str, hle->commit_id);
10267 if (err)
10268 return err;
10269 snprintf(msg, sizeof(msg), "commit %s is listed "
10270 "more than once in histedit script", id_str);
10271 free(id_str);
10272 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10276 STAILQ_FOREACH(qid, commits, entry) {
10277 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10278 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10279 break;
10281 if (hle == NULL) {
10282 err = got_object_id_str(&id_str, &qid->id);
10283 if (err)
10284 return err;
10285 snprintf(msg, sizeof(msg),
10286 "commit %s missing from histedit script", id_str);
10287 free(id_str);
10288 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10292 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10293 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10294 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10295 "last commit in histedit script cannot be folded");
10297 return NULL;
10300 static const struct got_error *
10301 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10302 const char *path, struct got_object_id_queue *commits,
10303 struct got_repository *repo)
10305 const struct got_error *err = NULL;
10306 char *editor;
10307 FILE *f = NULL;
10309 err = get_editor(&editor);
10310 if (err)
10311 return err;
10313 if (spawn_editor(editor, path) == -1) {
10314 err = got_error_from_errno("failed spawning editor");
10315 goto done;
10318 f = fopen(path, "re");
10319 if (f == NULL) {
10320 err = got_error_from_errno("fopen");
10321 goto done;
10323 err = histedit_parse_list(histedit_cmds, f, repo);
10324 if (err)
10325 goto done;
10327 err = histedit_check_script(histedit_cmds, commits, repo);
10328 done:
10329 if (f && fclose(f) == EOF && err == NULL)
10330 err = got_error_from_errno("fclose");
10331 free(editor);
10332 return err;
10335 static const struct got_error *
10336 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10337 struct got_object_id_queue *, const char *, const char *,
10338 struct got_repository *);
10340 static const struct got_error *
10341 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10342 struct got_object_id_queue *commits, const char *branch_name,
10343 int edit_logmsg_only, int fold_only, int edit_only,
10344 struct got_repository *repo)
10346 const struct got_error *err;
10347 FILE *f = NULL;
10348 char *path = NULL;
10350 err = got_opentemp_named(&path, &f, "got-histedit");
10351 if (err)
10352 return err;
10354 err = write_cmd_list(f, branch_name, commits);
10355 if (err)
10356 goto done;
10358 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10359 fold_only, edit_only, repo);
10360 if (err)
10361 goto done;
10363 if (edit_logmsg_only || fold_only || edit_only) {
10364 rewind(f);
10365 err = histedit_parse_list(histedit_cmds, f, repo);
10366 } else {
10367 if (fclose(f) == EOF) {
10368 err = got_error_from_errno("fclose");
10369 goto done;
10371 f = NULL;
10372 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10373 if (err) {
10374 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10375 err->code != GOT_ERR_HISTEDIT_CMD)
10376 goto done;
10377 err = histedit_edit_list_retry(histedit_cmds, err,
10378 commits, path, branch_name, repo);
10381 done:
10382 if (f && fclose(f) == EOF && err == NULL)
10383 err = got_error_from_errno("fclose");
10384 if (path && unlink(path) != 0 && err == NULL)
10385 err = got_error_from_errno2("unlink", path);
10386 free(path);
10387 return err;
10390 static const struct got_error *
10391 histedit_save_list(struct got_histedit_list *histedit_cmds,
10392 struct got_worktree *worktree, struct got_repository *repo)
10394 const struct got_error *err = NULL;
10395 char *path = NULL;
10396 FILE *f = NULL;
10397 struct got_histedit_list_entry *hle;
10398 struct got_commit_object *commit = NULL;
10400 err = got_worktree_get_histedit_script_path(&path, worktree);
10401 if (err)
10402 return err;
10404 f = fopen(path, "we");
10405 if (f == NULL) {
10406 err = got_error_from_errno2("fopen", path);
10407 goto done;
10409 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10410 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10411 repo);
10412 if (err)
10413 break;
10415 if (hle->logmsg) {
10416 int n = fprintf(f, "%c %s\n",
10417 GOT_HISTEDIT_MESG, hle->logmsg);
10418 if (n < 0) {
10419 err = got_ferror(f, GOT_ERR_IO);
10420 break;
10424 done:
10425 if (f && fclose(f) == EOF && err == NULL)
10426 err = got_error_from_errno("fclose");
10427 free(path);
10428 if (commit)
10429 got_object_commit_close(commit);
10430 return err;
10433 void
10434 histedit_free_list(struct got_histedit_list *histedit_cmds)
10436 struct got_histedit_list_entry *hle;
10438 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10439 TAILQ_REMOVE(histedit_cmds, hle, entry);
10440 free(hle);
10444 static const struct got_error *
10445 histedit_load_list(struct got_histedit_list *histedit_cmds,
10446 const char *path, struct got_repository *repo)
10448 const struct got_error *err = NULL;
10449 FILE *f = NULL;
10451 f = fopen(path, "re");
10452 if (f == NULL) {
10453 err = got_error_from_errno2("fopen", path);
10454 goto done;
10457 err = histedit_parse_list(histedit_cmds, f, repo);
10458 done:
10459 if (f && fclose(f) == EOF && err == NULL)
10460 err = got_error_from_errno("fclose");
10461 return err;
10464 static const struct got_error *
10465 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10466 const struct got_error *edit_err, struct got_object_id_queue *commits,
10467 const char *path, const char *branch_name, struct got_repository *repo)
10469 const struct got_error *err = NULL, *prev_err = edit_err;
10470 int resp = ' ';
10472 while (resp != 'c' && resp != 'r' && resp != 'a') {
10473 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10474 "or (a)bort: ", getprogname(), prev_err->msg);
10475 resp = getchar();
10476 if (resp == '\n')
10477 resp = getchar();
10478 if (resp == 'c') {
10479 histedit_free_list(histedit_cmds);
10480 err = histedit_run_editor(histedit_cmds, path, commits,
10481 repo);
10482 if (err) {
10483 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10484 err->code != GOT_ERR_HISTEDIT_CMD)
10485 break;
10486 prev_err = err;
10487 resp = ' ';
10488 continue;
10490 break;
10491 } else if (resp == 'r') {
10492 histedit_free_list(histedit_cmds);
10493 err = histedit_edit_script(histedit_cmds,
10494 commits, branch_name, 0, 0, 0, repo);
10495 if (err) {
10496 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10497 err->code != GOT_ERR_HISTEDIT_CMD)
10498 break;
10499 prev_err = err;
10500 resp = ' ';
10501 continue;
10503 break;
10504 } else if (resp == 'a') {
10505 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10506 break;
10507 } else
10508 printf("invalid response '%c'\n", resp);
10511 return err;
10514 static const struct got_error *
10515 histedit_complete(struct got_worktree *worktree,
10516 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10517 struct got_reference *branch, struct got_repository *repo)
10519 printf("Switching work tree to %s\n",
10520 got_ref_get_symref_target(branch));
10521 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10522 branch, repo);
10525 static const struct got_error *
10526 show_histedit_progress(struct got_commit_object *commit,
10527 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10529 const struct got_error *err;
10530 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10532 err = got_object_id_str(&old_id_str, hle->commit_id);
10533 if (err)
10534 goto done;
10536 if (new_id) {
10537 err = got_object_id_str(&new_id_str, new_id);
10538 if (err)
10539 goto done;
10542 old_id_str[12] = '\0';
10543 if (new_id_str)
10544 new_id_str[12] = '\0';
10546 if (hle->logmsg) {
10547 logmsg = strdup(hle->logmsg);
10548 if (logmsg == NULL) {
10549 err = got_error_from_errno("strdup");
10550 goto done;
10552 trim_logmsg(logmsg, 42);
10553 } else {
10554 err = get_short_logmsg(&logmsg, 42, commit);
10555 if (err)
10556 goto done;
10559 switch (hle->cmd->code) {
10560 case GOT_HISTEDIT_PICK:
10561 case GOT_HISTEDIT_EDIT:
10562 printf("%s -> %s: %s\n", old_id_str,
10563 new_id_str ? new_id_str : "no-op change", logmsg);
10564 break;
10565 case GOT_HISTEDIT_DROP:
10566 case GOT_HISTEDIT_FOLD:
10567 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10568 logmsg);
10569 break;
10570 default:
10571 break;
10573 done:
10574 free(old_id_str);
10575 free(new_id_str);
10576 return err;
10579 static const struct got_error *
10580 histedit_commit(struct got_pathlist_head *merged_paths,
10581 struct got_worktree *worktree, struct got_fileindex *fileindex,
10582 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10583 struct got_repository *repo)
10585 const struct got_error *err;
10586 struct got_commit_object *commit;
10587 struct got_object_id *new_commit_id;
10589 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10590 && hle->logmsg == NULL) {
10591 err = histedit_edit_logmsg(hle, repo);
10592 if (err)
10593 return err;
10596 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10597 if (err)
10598 return err;
10600 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10601 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10602 hle->logmsg, repo);
10603 if (err) {
10604 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10605 goto done;
10606 err = show_histedit_progress(commit, hle, NULL);
10607 } else {
10608 err = show_histedit_progress(commit, hle, new_commit_id);
10609 free(new_commit_id);
10611 done:
10612 got_object_commit_close(commit);
10613 return err;
10616 static const struct got_error *
10617 histedit_skip_commit(struct got_histedit_list_entry *hle,
10618 struct got_worktree *worktree, struct got_repository *repo)
10620 const struct got_error *error;
10621 struct got_commit_object *commit;
10623 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10624 repo);
10625 if (error)
10626 return error;
10628 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10629 if (error)
10630 return error;
10632 error = show_histedit_progress(commit, hle, NULL);
10633 got_object_commit_close(commit);
10634 return error;
10637 static const struct got_error *
10638 check_local_changes(void *arg, unsigned char status,
10639 unsigned char staged_status, const char *path,
10640 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10641 struct got_object_id *commit_id, int dirfd, const char *de_name)
10643 int *have_local_changes = arg;
10645 switch (status) {
10646 case GOT_STATUS_ADD:
10647 case GOT_STATUS_DELETE:
10648 case GOT_STATUS_MODIFY:
10649 case GOT_STATUS_CONFLICT:
10650 *have_local_changes = 1;
10651 return got_error(GOT_ERR_CANCELLED);
10652 default:
10653 break;
10656 switch (staged_status) {
10657 case GOT_STATUS_ADD:
10658 case GOT_STATUS_DELETE:
10659 case GOT_STATUS_MODIFY:
10660 *have_local_changes = 1;
10661 return got_error(GOT_ERR_CANCELLED);
10662 default:
10663 break;
10666 return NULL;
10669 static const struct got_error *
10670 cmd_histedit(int argc, char *argv[])
10672 const struct got_error *error = NULL;
10673 struct got_worktree *worktree = NULL;
10674 struct got_fileindex *fileindex = NULL;
10675 struct got_repository *repo = NULL;
10676 char *cwd = NULL;
10677 struct got_reference *branch = NULL;
10678 struct got_reference *tmp_branch = NULL;
10679 struct got_object_id *resume_commit_id = NULL;
10680 struct got_object_id *base_commit_id = NULL;
10681 struct got_object_id *head_commit_id = NULL;
10682 struct got_commit_object *commit = NULL;
10683 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10684 struct got_update_progress_arg upa;
10685 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10686 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10687 int list_backups = 0, delete_backups = 0;
10688 const char *edit_script_path = NULL;
10689 struct got_object_id_queue commits;
10690 struct got_pathlist_head merged_paths;
10691 const struct got_object_id_queue *parent_ids;
10692 struct got_object_qid *pid;
10693 struct got_histedit_list histedit_cmds;
10694 struct got_histedit_list_entry *hle;
10696 STAILQ_INIT(&commits);
10697 TAILQ_INIT(&histedit_cmds);
10698 TAILQ_INIT(&merged_paths);
10699 memset(&upa, 0, sizeof(upa));
10701 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10702 switch (ch) {
10703 case 'a':
10704 abort_edit = 1;
10705 break;
10706 case 'c':
10707 continue_edit = 1;
10708 break;
10709 case 'e':
10710 edit_only = 1;
10711 break;
10712 case 'f':
10713 fold_only = 1;
10714 break;
10715 case 'F':
10716 edit_script_path = optarg;
10717 break;
10718 case 'm':
10719 edit_logmsg_only = 1;
10720 break;
10721 case 'l':
10722 list_backups = 1;
10723 break;
10724 case 'X':
10725 delete_backups = 1;
10726 break;
10727 default:
10728 usage_histedit();
10729 /* NOTREACHED */
10733 argc -= optind;
10734 argv += optind;
10736 #ifndef PROFILE
10737 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10738 "unveil", NULL) == -1)
10739 err(1, "pledge");
10740 #endif
10741 if (abort_edit && continue_edit)
10742 option_conflict('a', 'c');
10743 if (edit_script_path && edit_logmsg_only)
10744 option_conflict('F', 'm');
10745 if (abort_edit && edit_logmsg_only)
10746 option_conflict('a', 'm');
10747 if (continue_edit && edit_logmsg_only)
10748 option_conflict('c', 'm');
10749 if (abort_edit && fold_only)
10750 option_conflict('a', 'f');
10751 if (continue_edit && fold_only)
10752 option_conflict('c', 'f');
10753 if (fold_only && edit_logmsg_only)
10754 option_conflict('f', 'm');
10755 if (edit_script_path && fold_only)
10756 option_conflict('F', 'f');
10757 if (abort_edit && edit_only)
10758 option_conflict('a', 'e');
10759 if (continue_edit && edit_only)
10760 option_conflict('c', 'e');
10761 if (edit_only && edit_logmsg_only)
10762 option_conflict('e', 'm');
10763 if (edit_script_path && edit_only)
10764 option_conflict('F', 'e');
10765 if (list_backups) {
10766 if (abort_edit)
10767 option_conflict('l', 'a');
10768 if (continue_edit)
10769 option_conflict('l', 'c');
10770 if (edit_script_path)
10771 option_conflict('l', 'F');
10772 if (edit_logmsg_only)
10773 option_conflict('l', 'm');
10774 if (fold_only)
10775 option_conflict('l', 'f');
10776 if (edit_only)
10777 option_conflict('l', 'e');
10778 if (delete_backups)
10779 option_conflict('l', 'X');
10780 if (argc != 0 && argc != 1)
10781 usage_histedit();
10782 } else if (delete_backups) {
10783 if (abort_edit)
10784 option_conflict('X', 'a');
10785 if (continue_edit)
10786 option_conflict('X', 'c');
10787 if (edit_script_path)
10788 option_conflict('X', 'F');
10789 if (edit_logmsg_only)
10790 option_conflict('X', 'm');
10791 if (fold_only)
10792 option_conflict('X', 'f');
10793 if (edit_only)
10794 option_conflict('X', 'e');
10795 if (list_backups)
10796 option_conflict('X', 'l');
10797 if (argc != 0 && argc != 1)
10798 usage_histedit();
10799 } else if (argc != 0)
10800 usage_histedit();
10803 * This command cannot apply unveil(2) in all cases because the
10804 * user may choose to run an editor to edit the histedit script
10805 * and to edit individual commit log messages.
10806 * unveil(2) traverses exec(2); if an editor is used we have to
10807 * apply unveil after edit script and log messages have been written.
10808 * XXX TODO: Make use of unveil(2) where possible.
10811 cwd = getcwd(NULL, 0);
10812 if (cwd == NULL) {
10813 error = got_error_from_errno("getcwd");
10814 goto done;
10816 error = got_worktree_open(&worktree, cwd);
10817 if (error) {
10818 if (list_backups || delete_backups) {
10819 if (error->code != GOT_ERR_NOT_WORKTREE)
10820 goto done;
10821 } else {
10822 if (error->code == GOT_ERR_NOT_WORKTREE)
10823 error = wrap_not_worktree_error(error,
10824 "histedit", cwd);
10825 goto done;
10829 if (list_backups || delete_backups) {
10830 error = got_repo_open(&repo,
10831 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10832 NULL);
10833 if (error != NULL)
10834 goto done;
10835 error = apply_unveil(got_repo_get_path(repo), 0,
10836 worktree ? got_worktree_get_root_path(worktree) : NULL);
10837 if (error)
10838 goto done;
10839 error = process_backup_refs(
10840 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10841 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10842 goto done; /* nothing else to do */
10845 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10846 NULL);
10847 if (error != NULL)
10848 goto done;
10850 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10851 if (error)
10852 goto done;
10853 if (rebase_in_progress) {
10854 error = got_error(GOT_ERR_REBASING);
10855 goto done;
10858 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10859 repo);
10860 if (error)
10861 goto done;
10862 if (merge_in_progress) {
10863 error = got_error(GOT_ERR_MERGE_BUSY);
10864 goto done;
10867 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10868 if (error)
10869 goto done;
10871 if (edit_in_progress && edit_logmsg_only) {
10872 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10873 "histedit operation is in progress in this "
10874 "work tree and must be continued or aborted "
10875 "before the -m option can be used");
10876 goto done;
10878 if (edit_in_progress && fold_only) {
10879 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10880 "histedit operation is in progress in this "
10881 "work tree and must be continued or aborted "
10882 "before the -f option can be used");
10883 goto done;
10885 if (edit_in_progress && edit_only) {
10886 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10887 "histedit operation is in progress in this "
10888 "work tree and must be continued or aborted "
10889 "before the -e option can be used");
10890 goto done;
10893 if (edit_in_progress && abort_edit) {
10894 error = got_worktree_histedit_continue(&resume_commit_id,
10895 &tmp_branch, &branch, &base_commit_id, &fileindex,
10896 worktree, repo);
10897 if (error)
10898 goto done;
10899 printf("Switching work tree to %s\n",
10900 got_ref_get_symref_target(branch));
10901 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10902 branch, base_commit_id, abort_progress, &upa);
10903 if (error)
10904 goto done;
10905 printf("Histedit of %s aborted\n",
10906 got_ref_get_symref_target(branch));
10907 print_merge_progress_stats(&upa);
10908 goto done; /* nothing else to do */
10909 } else if (abort_edit) {
10910 error = got_error(GOT_ERR_NOT_HISTEDIT);
10911 goto done;
10914 if (continue_edit) {
10915 char *path;
10917 if (!edit_in_progress) {
10918 error = got_error(GOT_ERR_NOT_HISTEDIT);
10919 goto done;
10922 error = got_worktree_get_histedit_script_path(&path, worktree);
10923 if (error)
10924 goto done;
10926 error = histedit_load_list(&histedit_cmds, path, repo);
10927 free(path);
10928 if (error)
10929 goto done;
10931 error = got_worktree_histedit_continue(&resume_commit_id,
10932 &tmp_branch, &branch, &base_commit_id, &fileindex,
10933 worktree, repo);
10934 if (error)
10935 goto done;
10937 error = got_ref_resolve(&head_commit_id, repo, branch);
10938 if (error)
10939 goto done;
10941 error = got_object_open_as_commit(&commit, repo,
10942 head_commit_id);
10943 if (error)
10944 goto done;
10945 parent_ids = got_object_commit_get_parent_ids(commit);
10946 pid = STAILQ_FIRST(parent_ids);
10947 if (pid == NULL) {
10948 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10949 goto done;
10951 error = collect_commits(&commits, head_commit_id, &pid->id,
10952 base_commit_id, got_worktree_get_path_prefix(worktree),
10953 GOT_ERR_HISTEDIT_PATH, repo);
10954 got_object_commit_close(commit);
10955 commit = NULL;
10956 if (error)
10957 goto done;
10958 } else {
10959 if (edit_in_progress) {
10960 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10961 goto done;
10964 error = got_ref_open(&branch, repo,
10965 got_worktree_get_head_ref_name(worktree), 0);
10966 if (error != NULL)
10967 goto done;
10969 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10970 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10971 "will not edit commit history of a branch outside "
10972 "the \"refs/heads/\" reference namespace");
10973 goto done;
10976 error = got_ref_resolve(&head_commit_id, repo, branch);
10977 got_ref_close(branch);
10978 branch = NULL;
10979 if (error)
10980 goto done;
10982 error = got_object_open_as_commit(&commit, repo,
10983 head_commit_id);
10984 if (error)
10985 goto done;
10986 parent_ids = got_object_commit_get_parent_ids(commit);
10987 pid = STAILQ_FIRST(parent_ids);
10988 if (pid == NULL) {
10989 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10990 goto done;
10992 error = collect_commits(&commits, head_commit_id, &pid->id,
10993 got_worktree_get_base_commit_id(worktree),
10994 got_worktree_get_path_prefix(worktree),
10995 GOT_ERR_HISTEDIT_PATH, repo);
10996 got_object_commit_close(commit);
10997 commit = NULL;
10998 if (error)
10999 goto done;
11001 if (STAILQ_EMPTY(&commits)) {
11002 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11003 goto done;
11006 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11007 &base_commit_id, &fileindex, worktree, repo);
11008 if (error)
11009 goto done;
11011 if (edit_script_path) {
11012 error = histedit_load_list(&histedit_cmds,
11013 edit_script_path, repo);
11014 if (error) {
11015 got_worktree_histedit_abort(worktree, fileindex,
11016 repo, branch, base_commit_id,
11017 abort_progress, &upa);
11018 print_merge_progress_stats(&upa);
11019 goto done;
11021 } else {
11022 const char *branch_name;
11023 branch_name = got_ref_get_symref_target(branch);
11024 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11025 branch_name += 11;
11026 error = histedit_edit_script(&histedit_cmds, &commits,
11027 branch_name, edit_logmsg_only, fold_only,
11028 edit_only, repo);
11029 if (error) {
11030 got_worktree_histedit_abort(worktree, fileindex,
11031 repo, branch, base_commit_id,
11032 abort_progress, &upa);
11033 print_merge_progress_stats(&upa);
11034 goto done;
11039 error = histedit_save_list(&histedit_cmds, worktree,
11040 repo);
11041 if (error) {
11042 got_worktree_histedit_abort(worktree, fileindex,
11043 repo, branch, base_commit_id,
11044 abort_progress, &upa);
11045 print_merge_progress_stats(&upa);
11046 goto done;
11051 error = histedit_check_script(&histedit_cmds, &commits, repo);
11052 if (error)
11053 goto done;
11055 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11056 if (resume_commit_id) {
11057 if (got_object_id_cmp(hle->commit_id,
11058 resume_commit_id) != 0)
11059 continue;
11061 resume_commit_id = NULL;
11062 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11063 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11064 error = histedit_skip_commit(hle, worktree,
11065 repo);
11066 if (error)
11067 goto done;
11068 } else {
11069 struct got_pathlist_head paths;
11070 int have_changes = 0;
11072 TAILQ_INIT(&paths);
11073 error = got_pathlist_append(&paths, "", NULL);
11074 if (error)
11075 goto done;
11076 error = got_worktree_status(worktree, &paths,
11077 repo, 0, check_local_changes, &have_changes,
11078 check_cancelled, NULL);
11079 got_pathlist_free(&paths);
11080 if (error) {
11081 if (error->code != GOT_ERR_CANCELLED)
11082 goto done;
11083 if (sigint_received || sigpipe_received)
11084 goto done;
11086 if (have_changes) {
11087 error = histedit_commit(NULL, worktree,
11088 fileindex, tmp_branch, hle, repo);
11089 if (error)
11090 goto done;
11091 } else {
11092 error = got_object_open_as_commit(
11093 &commit, repo, hle->commit_id);
11094 if (error)
11095 goto done;
11096 error = show_histedit_progress(commit,
11097 hle, NULL);
11098 got_object_commit_close(commit);
11099 commit = NULL;
11100 if (error)
11101 goto done;
11104 continue;
11107 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11108 error = histedit_skip_commit(hle, worktree, repo);
11109 if (error)
11110 goto done;
11111 continue;
11114 error = got_object_open_as_commit(&commit, repo,
11115 hle->commit_id);
11116 if (error)
11117 goto done;
11118 parent_ids = got_object_commit_get_parent_ids(commit);
11119 pid = STAILQ_FIRST(parent_ids);
11121 error = got_worktree_histedit_merge_files(&merged_paths,
11122 worktree, fileindex, &pid->id, hle->commit_id, repo,
11123 update_progress, &upa, check_cancelled, NULL);
11124 if (error)
11125 goto done;
11126 got_object_commit_close(commit);
11127 commit = NULL;
11129 print_merge_progress_stats(&upa);
11130 if (upa.conflicts > 0 || upa.missing > 0 ||
11131 upa.not_deleted > 0 || upa.unversioned > 0) {
11132 if (upa.conflicts > 0) {
11133 error = show_rebase_merge_conflict(
11134 hle->commit_id, repo);
11135 if (error)
11136 goto done;
11138 got_worktree_rebase_pathlist_free(&merged_paths);
11139 break;
11142 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11143 char *id_str;
11144 error = got_object_id_str(&id_str, hle->commit_id);
11145 if (error)
11146 goto done;
11147 printf("Stopping histedit for amending commit %s\n",
11148 id_str);
11149 free(id_str);
11150 got_worktree_rebase_pathlist_free(&merged_paths);
11151 error = got_worktree_histedit_postpone(worktree,
11152 fileindex);
11153 goto done;
11156 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11157 error = histedit_skip_commit(hle, worktree, repo);
11158 if (error)
11159 goto done;
11160 continue;
11163 error = histedit_commit(&merged_paths, worktree, fileindex,
11164 tmp_branch, hle, repo);
11165 got_worktree_rebase_pathlist_free(&merged_paths);
11166 if (error)
11167 goto done;
11170 if (upa.conflicts > 0 || upa.missing > 0 ||
11171 upa.not_deleted > 0 || upa.unversioned > 0) {
11172 error = got_worktree_histedit_postpone(worktree, fileindex);
11173 if (error)
11174 goto done;
11175 if (upa.conflicts > 0 && upa.missing == 0 &&
11176 upa.not_deleted == 0 && upa.unversioned == 0) {
11177 error = got_error_msg(GOT_ERR_CONFLICTS,
11178 "conflicts must be resolved before histedit "
11179 "can continue");
11180 } else if (upa.conflicts > 0) {
11181 error = got_error_msg(GOT_ERR_CONFLICTS,
11182 "conflicts must be resolved before histedit "
11183 "can continue; changes destined for some "
11184 "files were not yet merged and should be "
11185 "merged manually if required before the "
11186 "histedit operation is continued");
11187 } else {
11188 error = got_error_msg(GOT_ERR_CONFLICTS,
11189 "changes destined for some files were not "
11190 "yet merged and should be merged manually "
11191 "if required before the histedit operation "
11192 "is continued");
11194 } else
11195 error = histedit_complete(worktree, fileindex, tmp_branch,
11196 branch, repo);
11197 done:
11198 got_object_id_queue_free(&commits);
11199 histedit_free_list(&histedit_cmds);
11200 free(head_commit_id);
11201 free(base_commit_id);
11202 free(resume_commit_id);
11203 if (commit)
11204 got_object_commit_close(commit);
11205 if (branch)
11206 got_ref_close(branch);
11207 if (tmp_branch)
11208 got_ref_close(tmp_branch);
11209 if (worktree)
11210 got_worktree_close(worktree);
11211 if (repo) {
11212 const struct got_error *close_err = got_repo_close(repo);
11213 if (error == NULL)
11214 error = close_err;
11216 return error;
11219 __dead static void
11220 usage_integrate(void)
11222 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11223 exit(1);
11226 static const struct got_error *
11227 cmd_integrate(int argc, char *argv[])
11229 const struct got_error *error = NULL;
11230 struct got_repository *repo = NULL;
11231 struct got_worktree *worktree = NULL;
11232 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11233 const char *branch_arg = NULL;
11234 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11235 struct got_fileindex *fileindex = NULL;
11236 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11237 int ch;
11238 struct got_update_progress_arg upa;
11240 while ((ch = getopt(argc, argv, "")) != -1) {
11241 switch (ch) {
11242 default:
11243 usage_integrate();
11244 /* NOTREACHED */
11248 argc -= optind;
11249 argv += optind;
11251 if (argc != 1)
11252 usage_integrate();
11253 branch_arg = argv[0];
11254 #ifndef PROFILE
11255 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11256 "unveil", NULL) == -1)
11257 err(1, "pledge");
11258 #endif
11259 cwd = getcwd(NULL, 0);
11260 if (cwd == NULL) {
11261 error = got_error_from_errno("getcwd");
11262 goto done;
11265 error = got_worktree_open(&worktree, cwd);
11266 if (error) {
11267 if (error->code == GOT_ERR_NOT_WORKTREE)
11268 error = wrap_not_worktree_error(error, "integrate",
11269 cwd);
11270 goto done;
11273 error = check_rebase_or_histedit_in_progress(worktree);
11274 if (error)
11275 goto done;
11277 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11278 NULL);
11279 if (error != NULL)
11280 goto done;
11282 error = apply_unveil(got_repo_get_path(repo), 0,
11283 got_worktree_get_root_path(worktree));
11284 if (error)
11285 goto done;
11287 error = check_merge_in_progress(worktree, repo);
11288 if (error)
11289 goto done;
11291 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11292 error = got_error_from_errno("asprintf");
11293 goto done;
11296 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11297 &base_branch_ref, worktree, refname, repo);
11298 if (error)
11299 goto done;
11301 refname = strdup(got_ref_get_name(branch_ref));
11302 if (refname == NULL) {
11303 error = got_error_from_errno("strdup");
11304 got_worktree_integrate_abort(worktree, fileindex, repo,
11305 branch_ref, base_branch_ref);
11306 goto done;
11308 base_refname = strdup(got_ref_get_name(base_branch_ref));
11309 if (base_refname == NULL) {
11310 error = got_error_from_errno("strdup");
11311 got_worktree_integrate_abort(worktree, fileindex, repo,
11312 branch_ref, base_branch_ref);
11313 goto done;
11316 error = got_ref_resolve(&commit_id, repo, branch_ref);
11317 if (error)
11318 goto done;
11320 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11321 if (error)
11322 goto done;
11324 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11325 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11326 "specified branch has already been integrated");
11327 got_worktree_integrate_abort(worktree, fileindex, repo,
11328 branch_ref, base_branch_ref);
11329 goto done;
11332 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11333 if (error) {
11334 if (error->code == GOT_ERR_ANCESTRY)
11335 error = got_error(GOT_ERR_REBASE_REQUIRED);
11336 got_worktree_integrate_abort(worktree, fileindex, repo,
11337 branch_ref, base_branch_ref);
11338 goto done;
11341 memset(&upa, 0, sizeof(upa));
11342 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11343 branch_ref, base_branch_ref, update_progress, &upa,
11344 check_cancelled, NULL);
11345 if (error)
11346 goto done;
11348 printf("Integrated %s into %s\n", refname, base_refname);
11349 print_update_progress_stats(&upa);
11350 done:
11351 if (repo) {
11352 const struct got_error *close_err = got_repo_close(repo);
11353 if (error == NULL)
11354 error = close_err;
11356 if (worktree)
11357 got_worktree_close(worktree);
11358 free(cwd);
11359 free(base_commit_id);
11360 free(commit_id);
11361 free(refname);
11362 free(base_refname);
11363 return error;
11366 __dead static void
11367 usage_merge(void)
11369 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11370 getprogname());
11371 exit(1);
11374 static const struct got_error *
11375 cmd_merge(int argc, char *argv[])
11377 const struct got_error *error = NULL;
11378 struct got_worktree *worktree = NULL;
11379 struct got_repository *repo = NULL;
11380 struct got_fileindex *fileindex = NULL;
11381 char *cwd = NULL, *id_str = NULL, *author = NULL;
11382 struct got_reference *branch = NULL, *wt_branch = NULL;
11383 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11384 struct got_object_id *wt_branch_tip = NULL;
11385 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11386 int interrupt_merge = 0;
11387 struct got_update_progress_arg upa;
11388 struct got_object_id *merge_commit_id = NULL;
11389 char *branch_name = NULL;
11391 memset(&upa, 0, sizeof(upa));
11393 while ((ch = getopt(argc, argv, "acn")) != -1) {
11394 switch (ch) {
11395 case 'a':
11396 abort_merge = 1;
11397 break;
11398 case 'c':
11399 continue_merge = 1;
11400 break;
11401 case 'n':
11402 interrupt_merge = 1;
11403 break;
11404 default:
11405 usage_rebase();
11406 /* NOTREACHED */
11410 argc -= optind;
11411 argv += optind;
11413 #ifndef PROFILE
11414 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11415 "unveil", NULL) == -1)
11416 err(1, "pledge");
11417 #endif
11419 if (abort_merge && continue_merge)
11420 option_conflict('a', 'c');
11421 if (abort_merge || continue_merge) {
11422 if (argc != 0)
11423 usage_merge();
11424 } else if (argc != 1)
11425 usage_merge();
11427 cwd = getcwd(NULL, 0);
11428 if (cwd == NULL) {
11429 error = got_error_from_errno("getcwd");
11430 goto done;
11433 error = got_worktree_open(&worktree, cwd);
11434 if (error) {
11435 if (error->code == GOT_ERR_NOT_WORKTREE)
11436 error = wrap_not_worktree_error(error,
11437 "merge", cwd);
11438 goto done;
11441 error = got_repo_open(&repo,
11442 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11443 if (error != NULL)
11444 goto done;
11446 error = apply_unveil(got_repo_get_path(repo), 0,
11447 worktree ? got_worktree_get_root_path(worktree) : NULL);
11448 if (error)
11449 goto done;
11451 error = check_rebase_or_histedit_in_progress(worktree);
11452 if (error)
11453 goto done;
11455 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11456 repo);
11457 if (error)
11458 goto done;
11460 if (abort_merge) {
11461 if (!merge_in_progress) {
11462 error = got_error(GOT_ERR_NOT_MERGING);
11463 goto done;
11465 error = got_worktree_merge_continue(&branch_name,
11466 &branch_tip, &fileindex, worktree, repo);
11467 if (error)
11468 goto done;
11469 error = got_worktree_merge_abort(worktree, fileindex, repo,
11470 abort_progress, &upa);
11471 if (error)
11472 goto done;
11473 printf("Merge of %s aborted\n", branch_name);
11474 goto done; /* nothing else to do */
11477 error = get_author(&author, repo, worktree);
11478 if (error)
11479 goto done;
11481 if (continue_merge) {
11482 if (!merge_in_progress) {
11483 error = got_error(GOT_ERR_NOT_MERGING);
11484 goto done;
11486 error = got_worktree_merge_continue(&branch_name,
11487 &branch_tip, &fileindex, worktree, repo);
11488 if (error)
11489 goto done;
11490 } else {
11491 error = got_ref_open(&branch, repo, argv[0], 0);
11492 if (error != NULL)
11493 goto done;
11494 branch_name = strdup(got_ref_get_name(branch));
11495 if (branch_name == NULL) {
11496 error = got_error_from_errno("strdup");
11497 goto done;
11499 error = got_ref_resolve(&branch_tip, repo, branch);
11500 if (error)
11501 goto done;
11504 error = got_ref_open(&wt_branch, repo,
11505 got_worktree_get_head_ref_name(worktree), 0);
11506 if (error)
11507 goto done;
11508 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11509 if (error)
11510 goto done;
11511 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11512 wt_branch_tip, branch_tip, 0, repo,
11513 check_cancelled, NULL);
11514 if (error && error->code != GOT_ERR_ANCESTRY)
11515 goto done;
11517 if (!continue_merge) {
11518 error = check_path_prefix(wt_branch_tip, branch_tip,
11519 got_worktree_get_path_prefix(worktree),
11520 GOT_ERR_MERGE_PATH, repo);
11521 if (error)
11522 goto done;
11523 if (yca_id) {
11524 error = check_same_branch(wt_branch_tip, branch,
11525 yca_id, repo);
11526 if (error) {
11527 if (error->code != GOT_ERR_ANCESTRY)
11528 goto done;
11529 error = NULL;
11530 } else {
11531 static char msg[512];
11532 snprintf(msg, sizeof(msg),
11533 "cannot create a merge commit because "
11534 "%s is based on %s; %s can be integrated "
11535 "with 'got integrate' instead", branch_name,
11536 got_worktree_get_head_ref_name(worktree),
11537 branch_name);
11538 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11539 goto done;
11542 error = got_worktree_merge_prepare(&fileindex, worktree,
11543 branch, repo);
11544 if (error)
11545 goto done;
11547 error = got_worktree_merge_branch(worktree, fileindex,
11548 yca_id, branch_tip, repo, update_progress, &upa,
11549 check_cancelled, NULL);
11550 if (error)
11551 goto done;
11552 print_merge_progress_stats(&upa);
11553 if (!upa.did_something) {
11554 error = got_worktree_merge_abort(worktree, fileindex,
11555 repo, abort_progress, &upa);
11556 if (error)
11557 goto done;
11558 printf("Already up-to-date\n");
11559 goto done;
11563 if (interrupt_merge) {
11564 error = got_worktree_merge_postpone(worktree, fileindex);
11565 if (error)
11566 goto done;
11567 printf("Merge of %s interrupted on request\n", branch_name);
11568 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11569 upa.not_deleted > 0 || upa.unversioned > 0) {
11570 error = got_worktree_merge_postpone(worktree, fileindex);
11571 if (error)
11572 goto done;
11573 if (upa.conflicts > 0 && upa.missing == 0 &&
11574 upa.not_deleted == 0 && upa.unversioned == 0) {
11575 error = got_error_msg(GOT_ERR_CONFLICTS,
11576 "conflicts must be resolved before merging "
11577 "can continue");
11578 } else if (upa.conflicts > 0) {
11579 error = got_error_msg(GOT_ERR_CONFLICTS,
11580 "conflicts must be resolved before merging "
11581 "can continue; changes destined for some "
11582 "files were not yet merged and "
11583 "should be merged manually if required before the "
11584 "merge operation is continued");
11585 } else {
11586 error = got_error_msg(GOT_ERR_CONFLICTS,
11587 "changes destined for some "
11588 "files were not yet merged and should be "
11589 "merged manually if required before the "
11590 "merge operation is continued");
11592 goto done;
11593 } else {
11594 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11595 fileindex, author, NULL, 1, branch_tip, branch_name,
11596 repo, continue_merge ? print_status : NULL, NULL);
11597 if (error)
11598 goto done;
11599 error = got_worktree_merge_complete(worktree, fileindex, repo);
11600 if (error)
11601 goto done;
11602 error = got_object_id_str(&id_str, merge_commit_id);
11603 if (error)
11604 goto done;
11605 printf("Merged %s into %s: %s\n", branch_name,
11606 got_worktree_get_head_ref_name(worktree),
11607 id_str);
11610 done:
11611 free(id_str);
11612 free(merge_commit_id);
11613 free(author);
11614 free(branch_tip);
11615 free(branch_name);
11616 free(yca_id);
11617 if (branch)
11618 got_ref_close(branch);
11619 if (wt_branch)
11620 got_ref_close(wt_branch);
11621 if (worktree)
11622 got_worktree_close(worktree);
11623 if (repo) {
11624 const struct got_error *close_err = got_repo_close(repo);
11625 if (error == NULL)
11626 error = close_err;
11628 return error;
11631 __dead static void
11632 usage_stage(void)
11634 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11635 "[-S] [file-path ...]\n",
11636 getprogname());
11637 exit(1);
11640 static const struct got_error *
11641 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11642 const char *path, struct got_object_id *blob_id,
11643 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11644 int dirfd, const char *de_name)
11646 const struct got_error *err = NULL;
11647 char *id_str = NULL;
11649 if (staged_status != GOT_STATUS_ADD &&
11650 staged_status != GOT_STATUS_MODIFY &&
11651 staged_status != GOT_STATUS_DELETE)
11652 return NULL;
11654 if (staged_status == GOT_STATUS_ADD ||
11655 staged_status == GOT_STATUS_MODIFY)
11656 err = got_object_id_str(&id_str, staged_blob_id);
11657 else
11658 err = got_object_id_str(&id_str, blob_id);
11659 if (err)
11660 return err;
11662 printf("%s %c %s\n", id_str, staged_status, path);
11663 free(id_str);
11664 return NULL;
11667 static const struct got_error *
11668 cmd_stage(int argc, char *argv[])
11670 const struct got_error *error = NULL;
11671 struct got_repository *repo = NULL;
11672 struct got_worktree *worktree = NULL;
11673 char *cwd = NULL;
11674 struct got_pathlist_head paths;
11675 struct got_pathlist_entry *pe;
11676 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11677 FILE *patch_script_file = NULL;
11678 const char *patch_script_path = NULL;
11679 struct choose_patch_arg cpa;
11681 TAILQ_INIT(&paths);
11683 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11684 switch (ch) {
11685 case 'l':
11686 list_stage = 1;
11687 break;
11688 case 'p':
11689 pflag = 1;
11690 break;
11691 case 'F':
11692 patch_script_path = optarg;
11693 break;
11694 case 'S':
11695 allow_bad_symlinks = 1;
11696 break;
11697 default:
11698 usage_stage();
11699 /* NOTREACHED */
11703 argc -= optind;
11704 argv += optind;
11706 #ifndef PROFILE
11707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11708 "unveil", NULL) == -1)
11709 err(1, "pledge");
11710 #endif
11711 if (list_stage && (pflag || patch_script_path))
11712 errx(1, "-l option cannot be used with other options");
11713 if (patch_script_path && !pflag)
11714 errx(1, "-F option can only be used together with -p option");
11716 cwd = getcwd(NULL, 0);
11717 if (cwd == NULL) {
11718 error = got_error_from_errno("getcwd");
11719 goto done;
11722 error = got_worktree_open(&worktree, cwd);
11723 if (error) {
11724 if (error->code == GOT_ERR_NOT_WORKTREE)
11725 error = wrap_not_worktree_error(error, "stage", cwd);
11726 goto done;
11729 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11730 NULL);
11731 if (error != NULL)
11732 goto done;
11734 if (patch_script_path) {
11735 patch_script_file = fopen(patch_script_path, "re");
11736 if (patch_script_file == NULL) {
11737 error = got_error_from_errno2("fopen",
11738 patch_script_path);
11739 goto done;
11742 error = apply_unveil(got_repo_get_path(repo), 0,
11743 got_worktree_get_root_path(worktree));
11744 if (error)
11745 goto done;
11747 error = check_merge_in_progress(worktree, repo);
11748 if (error)
11749 goto done;
11751 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11752 if (error)
11753 goto done;
11755 if (list_stage)
11756 error = got_worktree_status(worktree, &paths, repo, 0,
11757 print_stage, NULL, check_cancelled, NULL);
11758 else {
11759 cpa.patch_script_file = patch_script_file;
11760 cpa.action = "stage";
11761 error = got_worktree_stage(worktree, &paths,
11762 pflag ? NULL : print_status, NULL,
11763 pflag ? choose_patch : NULL, &cpa,
11764 allow_bad_symlinks, repo);
11766 done:
11767 if (patch_script_file && fclose(patch_script_file) == EOF &&
11768 error == NULL)
11769 error = got_error_from_errno2("fclose", patch_script_path);
11770 if (repo) {
11771 const struct got_error *close_err = got_repo_close(repo);
11772 if (error == NULL)
11773 error = close_err;
11775 if (worktree)
11776 got_worktree_close(worktree);
11777 TAILQ_FOREACH(pe, &paths, entry)
11778 free((char *)pe->path);
11779 got_pathlist_free(&paths);
11780 free(cwd);
11781 return error;
11784 __dead static void
11785 usage_unstage(void)
11787 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11788 "[file-path ...]\n",
11789 getprogname());
11790 exit(1);
11794 static const struct got_error *
11795 cmd_unstage(int argc, char *argv[])
11797 const struct got_error *error = NULL;
11798 struct got_repository *repo = NULL;
11799 struct got_worktree *worktree = NULL;
11800 char *cwd = NULL;
11801 struct got_pathlist_head paths;
11802 struct got_pathlist_entry *pe;
11803 int ch, pflag = 0;
11804 struct got_update_progress_arg upa;
11805 FILE *patch_script_file = NULL;
11806 const char *patch_script_path = NULL;
11807 struct choose_patch_arg cpa;
11809 TAILQ_INIT(&paths);
11811 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11812 switch (ch) {
11813 case 'p':
11814 pflag = 1;
11815 break;
11816 case 'F':
11817 patch_script_path = optarg;
11818 break;
11819 default:
11820 usage_unstage();
11821 /* NOTREACHED */
11825 argc -= optind;
11826 argv += optind;
11828 #ifndef PROFILE
11829 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11830 "unveil", NULL) == -1)
11831 err(1, "pledge");
11832 #endif
11833 if (patch_script_path && !pflag)
11834 errx(1, "-F option can only be used together with -p option");
11836 cwd = getcwd(NULL, 0);
11837 if (cwd == NULL) {
11838 error = got_error_from_errno("getcwd");
11839 goto done;
11842 error = got_worktree_open(&worktree, cwd);
11843 if (error) {
11844 if (error->code == GOT_ERR_NOT_WORKTREE)
11845 error = wrap_not_worktree_error(error, "unstage", cwd);
11846 goto done;
11849 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11850 NULL);
11851 if (error != NULL)
11852 goto done;
11854 if (patch_script_path) {
11855 patch_script_file = fopen(patch_script_path, "re");
11856 if (patch_script_file == NULL) {
11857 error = got_error_from_errno2("fopen",
11858 patch_script_path);
11859 goto done;
11863 error = apply_unveil(got_repo_get_path(repo), 0,
11864 got_worktree_get_root_path(worktree));
11865 if (error)
11866 goto done;
11868 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11869 if (error)
11870 goto done;
11872 cpa.patch_script_file = patch_script_file;
11873 cpa.action = "unstage";
11874 memset(&upa, 0, sizeof(upa));
11875 error = got_worktree_unstage(worktree, &paths, update_progress,
11876 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11877 if (!error)
11878 print_merge_progress_stats(&upa);
11879 done:
11880 if (patch_script_file && fclose(patch_script_file) == EOF &&
11881 error == NULL)
11882 error = got_error_from_errno2("fclose", patch_script_path);
11883 if (repo) {
11884 const struct got_error *close_err = got_repo_close(repo);
11885 if (error == NULL)
11886 error = close_err;
11888 if (worktree)
11889 got_worktree_close(worktree);
11890 TAILQ_FOREACH(pe, &paths, entry)
11891 free((char *)pe->path);
11892 got_pathlist_free(&paths);
11893 free(cwd);
11894 return error;
11897 __dead static void
11898 usage_cat(void)
11900 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11901 "arg1 [arg2 ...]\n", getprogname());
11902 exit(1);
11905 static const struct got_error *
11906 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11908 const struct got_error *err;
11909 struct got_blob_object *blob;
11911 err = got_object_open_as_blob(&blob, repo, id, 8192);
11912 if (err)
11913 return err;
11915 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11916 got_object_blob_close(blob);
11917 return err;
11920 static const struct got_error *
11921 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11923 const struct got_error *err;
11924 struct got_tree_object *tree;
11925 int nentries, i;
11927 err = got_object_open_as_tree(&tree, repo, id);
11928 if (err)
11929 return err;
11931 nentries = got_object_tree_get_nentries(tree);
11932 for (i = 0; i < nentries; i++) {
11933 struct got_tree_entry *te;
11934 char *id_str;
11935 if (sigint_received || sigpipe_received)
11936 break;
11937 te = got_object_tree_get_entry(tree, i);
11938 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11939 if (err)
11940 break;
11941 fprintf(outfile, "%s %.7o %s\n", id_str,
11942 got_tree_entry_get_mode(te),
11943 got_tree_entry_get_name(te));
11944 free(id_str);
11947 got_object_tree_close(tree);
11948 return err;
11951 static void
11952 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11954 long long h, m;
11955 char sign = '+';
11957 if (gmtoff < 0) {
11958 sign = '-';
11959 gmtoff = -gmtoff;
11962 h = (long long)gmtoff / 3600;
11963 m = ((long long)gmtoff - h*3600) / 60;
11964 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11967 static const struct got_error *
11968 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11970 const struct got_error *err;
11971 struct got_commit_object *commit;
11972 const struct got_object_id_queue *parent_ids;
11973 struct got_object_qid *pid;
11974 char *id_str = NULL;
11975 const char *logmsg = NULL;
11976 char gmtoff[6];
11978 err = got_object_open_as_commit(&commit, repo, id);
11979 if (err)
11980 return err;
11982 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11983 if (err)
11984 goto done;
11986 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11987 parent_ids = got_object_commit_get_parent_ids(commit);
11988 fprintf(outfile, "numparents %d\n",
11989 got_object_commit_get_nparents(commit));
11990 STAILQ_FOREACH(pid, parent_ids, entry) {
11991 char *pid_str;
11992 err = got_object_id_str(&pid_str, &pid->id);
11993 if (err)
11994 goto done;
11995 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11996 free(pid_str);
11998 format_gmtoff(gmtoff, sizeof(gmtoff),
11999 got_object_commit_get_author_gmtoff(commit));
12000 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12001 got_object_commit_get_author(commit),
12002 (long long)got_object_commit_get_author_time(commit),
12003 gmtoff);
12005 format_gmtoff(gmtoff, sizeof(gmtoff),
12006 got_object_commit_get_committer_gmtoff(commit));
12007 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12008 got_object_commit_get_author(commit),
12009 (long long)got_object_commit_get_committer_time(commit),
12010 gmtoff);
12012 logmsg = got_object_commit_get_logmsg_raw(commit);
12013 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12014 fprintf(outfile, "%s", logmsg);
12015 done:
12016 free(id_str);
12017 got_object_commit_close(commit);
12018 return err;
12021 static const struct got_error *
12022 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12024 const struct got_error *err;
12025 struct got_tag_object *tag;
12026 char *id_str = NULL;
12027 const char *tagmsg = NULL;
12028 char gmtoff[6];
12030 err = got_object_open_as_tag(&tag, repo, id);
12031 if (err)
12032 return err;
12034 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12035 if (err)
12036 goto done;
12038 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12040 switch (got_object_tag_get_object_type(tag)) {
12041 case GOT_OBJ_TYPE_BLOB:
12042 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12043 GOT_OBJ_LABEL_BLOB);
12044 break;
12045 case GOT_OBJ_TYPE_TREE:
12046 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12047 GOT_OBJ_LABEL_TREE);
12048 break;
12049 case GOT_OBJ_TYPE_COMMIT:
12050 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12051 GOT_OBJ_LABEL_COMMIT);
12052 break;
12053 case GOT_OBJ_TYPE_TAG:
12054 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12055 GOT_OBJ_LABEL_TAG);
12056 break;
12057 default:
12058 break;
12061 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12062 got_object_tag_get_name(tag));
12064 format_gmtoff(gmtoff, sizeof(gmtoff),
12065 got_object_tag_get_tagger_gmtoff(tag));
12066 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12067 got_object_tag_get_tagger(tag),
12068 (long long)got_object_tag_get_tagger_time(tag),
12069 gmtoff);
12071 tagmsg = got_object_tag_get_message(tag);
12072 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12073 fprintf(outfile, "%s", tagmsg);
12074 done:
12075 free(id_str);
12076 got_object_tag_close(tag);
12077 return err;
12080 static const struct got_error *
12081 cmd_cat(int argc, char *argv[])
12083 const struct got_error *error;
12084 struct got_repository *repo = NULL;
12085 struct got_worktree *worktree = NULL;
12086 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12087 const char *commit_id_str = NULL;
12088 struct got_object_id *id = NULL, *commit_id = NULL;
12089 struct got_commit_object *commit = NULL;
12090 int ch, obj_type, i, force_path = 0;
12091 struct got_reflist_head refs;
12093 TAILQ_INIT(&refs);
12095 #ifndef PROFILE
12096 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12097 NULL) == -1)
12098 err(1, "pledge");
12099 #endif
12101 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12102 switch (ch) {
12103 case 'c':
12104 commit_id_str = optarg;
12105 break;
12106 case 'r':
12107 repo_path = realpath(optarg, NULL);
12108 if (repo_path == NULL)
12109 return got_error_from_errno2("realpath",
12110 optarg);
12111 got_path_strip_trailing_slashes(repo_path);
12112 break;
12113 case 'P':
12114 force_path = 1;
12115 break;
12116 default:
12117 usage_cat();
12118 /* NOTREACHED */
12122 argc -= optind;
12123 argv += optind;
12125 cwd = getcwd(NULL, 0);
12126 if (cwd == NULL) {
12127 error = got_error_from_errno("getcwd");
12128 goto done;
12131 if (repo_path == NULL) {
12132 error = got_worktree_open(&worktree, cwd);
12133 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12134 goto done;
12135 if (worktree) {
12136 repo_path = strdup(
12137 got_worktree_get_repo_path(worktree));
12138 if (repo_path == NULL) {
12139 error = got_error_from_errno("strdup");
12140 goto done;
12143 /* Release work tree lock. */
12144 got_worktree_close(worktree);
12145 worktree = NULL;
12149 if (repo_path == NULL) {
12150 repo_path = strdup(cwd);
12151 if (repo_path == NULL)
12152 return got_error_from_errno("strdup");
12155 error = got_repo_open(&repo, repo_path, NULL);
12156 free(repo_path);
12157 if (error != NULL)
12158 goto done;
12160 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12161 if (error)
12162 goto done;
12164 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12165 if (error)
12166 goto done;
12168 if (commit_id_str == NULL)
12169 commit_id_str = GOT_REF_HEAD;
12170 error = got_repo_match_object_id(&commit_id, NULL,
12171 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12172 if (error)
12173 goto done;
12175 error = got_object_open_as_commit(&commit, repo, commit_id);
12176 if (error)
12177 goto done;
12179 for (i = 0; i < argc; i++) {
12180 if (force_path) {
12181 error = got_object_id_by_path(&id, repo, commit,
12182 argv[i]);
12183 if (error)
12184 break;
12185 } else {
12186 error = got_repo_match_object_id(&id, &label, argv[i],
12187 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12188 repo);
12189 if (error) {
12190 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12191 error->code != GOT_ERR_NOT_REF)
12192 break;
12193 error = got_object_id_by_path(&id, repo,
12194 commit, argv[i]);
12195 if (error)
12196 break;
12200 error = got_object_get_type(&obj_type, repo, id);
12201 if (error)
12202 break;
12204 switch (obj_type) {
12205 case GOT_OBJ_TYPE_BLOB:
12206 error = cat_blob(id, repo, stdout);
12207 break;
12208 case GOT_OBJ_TYPE_TREE:
12209 error = cat_tree(id, repo, stdout);
12210 break;
12211 case GOT_OBJ_TYPE_COMMIT:
12212 error = cat_commit(id, repo, stdout);
12213 break;
12214 case GOT_OBJ_TYPE_TAG:
12215 error = cat_tag(id, repo, stdout);
12216 break;
12217 default:
12218 error = got_error(GOT_ERR_OBJ_TYPE);
12219 break;
12221 if (error)
12222 break;
12223 free(label);
12224 label = NULL;
12225 free(id);
12226 id = NULL;
12228 done:
12229 free(label);
12230 free(id);
12231 free(commit_id);
12232 if (commit)
12233 got_object_commit_close(commit);
12234 if (worktree)
12235 got_worktree_close(worktree);
12236 if (repo) {
12237 const struct got_error *close_err = got_repo_close(repo);
12238 if (error == NULL)
12239 error = close_err;
12241 got_ref_list_free(&refs);
12242 return error;
12245 __dead static void
12246 usage_info(void)
12248 fprintf(stderr, "usage: %s info [path ...]\n",
12249 getprogname());
12250 exit(1);
12253 static const struct got_error *
12254 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12255 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12256 struct got_object_id *commit_id)
12258 const struct got_error *err = NULL;
12259 char *id_str = NULL;
12260 char datebuf[128];
12261 struct tm mytm, *tm;
12262 struct got_pathlist_head *paths = arg;
12263 struct got_pathlist_entry *pe;
12266 * Clear error indication from any of the path arguments which
12267 * would cause this file index entry to be displayed.
12269 TAILQ_FOREACH(pe, paths, entry) {
12270 if (got_path_cmp(path, pe->path, strlen(path),
12271 pe->path_len) == 0 ||
12272 got_path_is_child(path, pe->path, pe->path_len))
12273 pe->data = NULL; /* no error */
12276 printf(GOT_COMMIT_SEP_STR);
12277 if (S_ISLNK(mode))
12278 printf("symlink: %s\n", path);
12279 else if (S_ISREG(mode)) {
12280 printf("file: %s\n", path);
12281 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12282 } else if (S_ISDIR(mode))
12283 printf("directory: %s\n", path);
12284 else
12285 printf("something: %s\n", path);
12287 tm = localtime_r(&mtime, &mytm);
12288 if (tm == NULL)
12289 return NULL;
12290 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12291 return got_error(GOT_ERR_NO_SPACE);
12292 printf("timestamp: %s\n", datebuf);
12294 if (blob_id) {
12295 err = got_object_id_str(&id_str, blob_id);
12296 if (err)
12297 return err;
12298 printf("based on blob: %s\n", id_str);
12299 free(id_str);
12302 if (staged_blob_id) {
12303 err = got_object_id_str(&id_str, staged_blob_id);
12304 if (err)
12305 return err;
12306 printf("based on staged blob: %s\n", id_str);
12307 free(id_str);
12310 if (commit_id) {
12311 err = got_object_id_str(&id_str, commit_id);
12312 if (err)
12313 return err;
12314 printf("based on commit: %s\n", id_str);
12315 free(id_str);
12318 return NULL;
12321 static const struct got_error *
12322 cmd_info(int argc, char *argv[])
12324 const struct got_error *error = NULL;
12325 struct got_worktree *worktree = NULL;
12326 char *cwd = NULL, *id_str = NULL;
12327 struct got_pathlist_head paths;
12328 struct got_pathlist_entry *pe;
12329 char *uuidstr = NULL;
12330 int ch, show_files = 0;
12332 TAILQ_INIT(&paths);
12334 while ((ch = getopt(argc, argv, "")) != -1) {
12335 switch (ch) {
12336 default:
12337 usage_info();
12338 /* NOTREACHED */
12342 argc -= optind;
12343 argv += optind;
12345 #ifndef PROFILE
12346 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12347 NULL) == -1)
12348 err(1, "pledge");
12349 #endif
12350 cwd = getcwd(NULL, 0);
12351 if (cwd == NULL) {
12352 error = got_error_from_errno("getcwd");
12353 goto done;
12356 error = got_worktree_open(&worktree, cwd);
12357 if (error) {
12358 if (error->code == GOT_ERR_NOT_WORKTREE)
12359 error = wrap_not_worktree_error(error, "info", cwd);
12360 goto done;
12363 #ifndef PROFILE
12364 /* Remove "cpath" promise. */
12365 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12366 NULL) == -1)
12367 err(1, "pledge");
12368 #endif
12369 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12370 if (error)
12371 goto done;
12373 if (argc >= 1) {
12374 error = get_worktree_paths_from_argv(&paths, argc, argv,
12375 worktree);
12376 if (error)
12377 goto done;
12378 show_files = 1;
12381 error = got_object_id_str(&id_str,
12382 got_worktree_get_base_commit_id(worktree));
12383 if (error)
12384 goto done;
12386 error = got_worktree_get_uuid(&uuidstr, worktree);
12387 if (error)
12388 goto done;
12390 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12391 printf("work tree base commit: %s\n", id_str);
12392 printf("work tree path prefix: %s\n",
12393 got_worktree_get_path_prefix(worktree));
12394 printf("work tree branch reference: %s\n",
12395 got_worktree_get_head_ref_name(worktree));
12396 printf("work tree UUID: %s\n", uuidstr);
12397 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12399 if (show_files) {
12400 struct got_pathlist_entry *pe;
12401 TAILQ_FOREACH(pe, &paths, entry) {
12402 if (pe->path_len == 0)
12403 continue;
12405 * Assume this path will fail. This will be corrected
12406 * in print_path_info() in case the path does suceeed.
12408 pe->data = (void *)got_error_path(pe->path,
12409 GOT_ERR_BAD_PATH);
12411 error = got_worktree_path_info(worktree, &paths,
12412 print_path_info, &paths, check_cancelled, NULL);
12413 if (error)
12414 goto done;
12415 TAILQ_FOREACH(pe, &paths, entry) {
12416 if (pe->data != NULL) {
12417 error = pe->data; /* bad path */
12418 break;
12422 done:
12423 TAILQ_FOREACH(pe, &paths, entry)
12424 free((char *)pe->path);
12425 got_pathlist_free(&paths);
12426 free(cwd);
12427 free(id_str);
12428 free(uuidstr);
12429 return error;