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 static 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;
717 int *pack_fds = NULL;
719 TAILQ_INIT(&ignores);
721 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
722 switch (ch) {
723 case 'b':
724 branch_name = optarg;
725 break;
726 case 'm':
727 logmsg = strdup(optarg);
728 if (logmsg == NULL) {
729 error = got_error_from_errno("strdup");
730 goto done;
732 break;
733 case 'r':
734 repo_path = realpath(optarg, NULL);
735 if (repo_path == NULL) {
736 error = got_error_from_errno2("realpath",
737 optarg);
738 goto done;
740 break;
741 case 'I':
742 if (optarg[0] == '\0')
743 break;
744 error = got_pathlist_insert(&pe, &ignores, optarg,
745 NULL);
746 if (error)
747 goto done;
748 break;
749 default:
750 usage_import();
751 /* NOTREACHED */
755 argc -= optind;
756 argv += optind;
758 #ifndef PROFILE
759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
760 "unveil",
761 NULL) == -1)
762 err(1, "pledge");
763 #endif
764 if (argc != 1)
765 usage_import();
767 if (repo_path == NULL) {
768 repo_path = getcwd(NULL, 0);
769 if (repo_path == NULL)
770 return got_error_from_errno("getcwd");
772 got_path_strip_trailing_slashes(repo_path);
773 error = get_gitconfig_path(&gitconfig_path);
774 if (error)
775 goto done;
776 error = got_repo_pack_fds_open(&pack_fds);
777 if (error != NULL)
778 goto done;
779 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
780 if (error)
781 goto done;
783 error = get_author(&author, repo, NULL);
784 if (error)
785 return error;
787 /*
788 * Don't let the user create a branch name with a leading '-'.
789 * While technically a valid reference name, this case is usually
790 * an unintended typo.
791 */
792 if (branch_name[0] == '-')
793 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
795 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
796 error = got_error_from_errno("asprintf");
797 goto done;
800 error = got_ref_open(&branch_ref, repo, refname, 0);
801 if (error) {
802 if (error->code != GOT_ERR_NOT_REF)
803 goto done;
804 } else {
805 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
806 "import target branch already exists");
807 goto done;
810 path_dir = realpath(argv[0], NULL);
811 if (path_dir == NULL) {
812 error = got_error_from_errno2("realpath", argv[0]);
813 goto done;
815 got_path_strip_trailing_slashes(path_dir);
817 /*
818 * unveil(2) traverses exec(2); if an editor is used we have
819 * to apply unveil after the log message has been written.
820 */
821 if (logmsg == NULL || strlen(logmsg) == 0) {
822 error = get_editor(&editor);
823 if (error)
824 goto done;
825 free(logmsg);
826 error = collect_import_msg(&logmsg, &logmsg_path, editor,
827 path_dir, refname);
828 if (error) {
829 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
830 logmsg_path != NULL)
831 preserve_logmsg = 1;
832 goto done;
836 if (unveil(path_dir, "r") != 0) {
837 error = got_error_from_errno2("unveil", path_dir);
838 if (logmsg_path)
839 preserve_logmsg = 1;
840 goto done;
843 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
844 if (error) {
845 if (logmsg_path)
846 preserve_logmsg = 1;
847 goto done;
850 error = got_repo_import(&new_commit_id, path_dir, logmsg,
851 author, &ignores, repo, import_progress, NULL);
852 if (error) {
853 if (logmsg_path)
854 preserve_logmsg = 1;
855 goto done;
858 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
859 if (error) {
860 if (logmsg_path)
861 preserve_logmsg = 1;
862 goto done;
865 error = got_ref_write(branch_ref, repo);
866 if (error) {
867 if (logmsg_path)
868 preserve_logmsg = 1;
869 goto done;
872 error = got_object_id_str(&id_str, new_commit_id);
873 if (error) {
874 if (logmsg_path)
875 preserve_logmsg = 1;
876 goto done;
879 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
880 if (error) {
881 if (error->code != GOT_ERR_NOT_REF) {
882 if (logmsg_path)
883 preserve_logmsg = 1;
884 goto done;
887 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
888 branch_ref);
889 if (error) {
890 if (logmsg_path)
891 preserve_logmsg = 1;
892 goto done;
895 error = got_ref_write(head_ref, repo);
896 if (error) {
897 if (logmsg_path)
898 preserve_logmsg = 1;
899 goto done;
903 printf("Created branch %s with commit %s\n",
904 got_ref_get_name(branch_ref), id_str);
905 done:
906 if (pack_fds) {
907 const struct got_error *pack_err =
908 got_repo_pack_fds_close(pack_fds);
909 if (error == NULL)
910 error = pack_err;
912 if (preserve_logmsg) {
913 fprintf(stderr, "%s: log message preserved in %s\n",
914 getprogname(), logmsg_path);
915 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
916 error = got_error_from_errno2("unlink", logmsg_path);
917 free(logmsg);
918 free(logmsg_path);
919 free(repo_path);
920 free(editor);
921 free(refname);
922 free(new_commit_id);
923 free(id_str);
924 free(author);
925 free(gitconfig_path);
926 if (branch_ref)
927 got_ref_close(branch_ref);
928 if (head_ref)
929 got_ref_close(head_ref);
930 return error;
933 __dead static void
934 usage_clone(void)
936 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
937 "[-R reference] repository-url [directory]\n", getprogname());
938 exit(1);
941 struct got_fetch_progress_arg {
942 char last_scaled_size[FMT_SCALED_STRSIZE];
943 int last_p_indexed;
944 int last_p_resolved;
945 int verbosity;
947 struct got_repository *repo;
949 int create_configs;
950 int configs_created;
951 struct {
952 struct got_pathlist_head *symrefs;
953 struct got_pathlist_head *wanted_branches;
954 struct got_pathlist_head *wanted_refs;
955 const char *proto;
956 const char *host;
957 const char *port;
958 const char *remote_repo_path;
959 const char *git_url;
960 int fetch_all_branches;
961 int mirror_references;
962 } config_info;
963 };
965 /* XXX forward declaration */
966 static const struct got_error *
967 create_config_files(const char *proto, const char *host, const char *port,
968 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
969 int mirror_references, struct got_pathlist_head *symrefs,
970 struct got_pathlist_head *wanted_branches,
971 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
973 static const struct got_error *
974 fetch_progress(void *arg, const char *message, off_t packfile_size,
975 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
977 const struct got_error *err = NULL;
978 struct got_fetch_progress_arg *a = arg;
979 char scaled_size[FMT_SCALED_STRSIZE];
980 int p_indexed, p_resolved;
981 int print_size = 0, print_indexed = 0, print_resolved = 0;
983 /*
984 * In order to allow a failed clone to be resumed with 'got fetch'
985 * we try to create configuration files as soon as possible.
986 * Once the server has sent information about its default branch
987 * we have all required information.
988 */
989 if (a->create_configs && !a->configs_created &&
990 !TAILQ_EMPTY(a->config_info.symrefs)) {
991 err = create_config_files(a->config_info.proto,
992 a->config_info.host, a->config_info.port,
993 a->config_info.remote_repo_path,
994 a->config_info.git_url,
995 a->config_info.fetch_all_branches,
996 a->config_info.mirror_references,
997 a->config_info.symrefs,
998 a->config_info.wanted_branches,
999 a->config_info.wanted_refs, a->repo);
1000 if (err)
1001 return err;
1002 a->configs_created = 1;
1005 if (a->verbosity < 0)
1006 return NULL;
1008 if (message && message[0] != '\0') {
1009 printf("\rserver: %s", message);
1010 fflush(stdout);
1011 return NULL;
1014 if (packfile_size > 0 || nobj_indexed > 0) {
1015 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1016 (a->last_scaled_size[0] == '\0' ||
1017 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1018 print_size = 1;
1019 if (strlcpy(a->last_scaled_size, scaled_size,
1020 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1021 return got_error(GOT_ERR_NO_SPACE);
1023 if (nobj_indexed > 0) {
1024 p_indexed = (nobj_indexed * 100) / nobj_total;
1025 if (p_indexed != a->last_p_indexed) {
1026 a->last_p_indexed = p_indexed;
1027 print_indexed = 1;
1028 print_size = 1;
1031 if (nobj_resolved > 0) {
1032 p_resolved = (nobj_resolved * 100) /
1033 (nobj_total - nobj_loose);
1034 if (p_resolved != a->last_p_resolved) {
1035 a->last_p_resolved = p_resolved;
1036 print_resolved = 1;
1037 print_indexed = 1;
1038 print_size = 1;
1043 if (print_size || print_indexed || print_resolved)
1044 printf("\r");
1045 if (print_size)
1046 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1047 if (print_indexed)
1048 printf("; indexing %d%%", p_indexed);
1049 if (print_resolved)
1050 printf("; resolving deltas %d%%", p_resolved);
1051 if (print_size || print_indexed || print_resolved)
1052 fflush(stdout);
1054 return NULL;
1057 static const struct got_error *
1058 create_symref(const char *refname, struct got_reference *target_ref,
1059 int verbosity, struct got_repository *repo)
1061 const struct got_error *err;
1062 struct got_reference *head_symref;
1064 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1065 if (err)
1066 return err;
1068 err = got_ref_write(head_symref, repo);
1069 if (err == NULL && verbosity > 0) {
1070 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1071 got_ref_get_name(target_ref));
1073 got_ref_close(head_symref);
1074 return err;
1077 static const struct got_error *
1078 list_remote_refs(struct got_pathlist_head *symrefs,
1079 struct got_pathlist_head *refs)
1081 const struct got_error *err;
1082 struct got_pathlist_entry *pe;
1084 TAILQ_FOREACH(pe, symrefs, entry) {
1085 const char *refname = pe->path;
1086 const char *targetref = pe->data;
1088 printf("%s: %s\n", refname, targetref);
1091 TAILQ_FOREACH(pe, refs, entry) {
1092 const char *refname = pe->path;
1093 struct got_object_id *id = pe->data;
1094 char *id_str;
1096 err = got_object_id_str(&id_str, id);
1097 if (err)
1098 return err;
1099 printf("%s: %s\n", refname, id_str);
1100 free(id_str);
1103 return NULL;
1106 static const struct got_error *
1107 create_ref(const char *refname, struct got_object_id *id,
1108 int verbosity, struct got_repository *repo)
1110 const struct got_error *err = NULL;
1111 struct got_reference *ref;
1112 char *id_str;
1114 err = got_object_id_str(&id_str, id);
1115 if (err)
1116 return err;
1118 err = got_ref_alloc(&ref, refname, id);
1119 if (err)
1120 goto done;
1122 err = got_ref_write(ref, repo);
1123 got_ref_close(ref);
1125 if (err == NULL && verbosity >= 0)
1126 printf("Created reference %s: %s\n", refname, id_str);
1127 done:
1128 free(id_str);
1129 return err;
1132 static int
1133 match_wanted_ref(const char *refname, const char *wanted_ref)
1135 if (strncmp(refname, "refs/", 5) != 0)
1136 return 0;
1137 refname += 5;
1140 * Prevent fetching of references that won't make any
1141 * sense outside of the remote repository's context.
1143 if (strncmp(refname, "got/", 4) == 0)
1144 return 0;
1145 if (strncmp(refname, "remotes/", 8) == 0)
1146 return 0;
1148 if (strncmp(wanted_ref, "refs/", 5) == 0)
1149 wanted_ref += 5;
1151 /* Allow prefix match. */
1152 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1153 return 1;
1155 /* Allow exact match. */
1156 return (strcmp(refname, wanted_ref) == 0);
1159 static int
1160 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1162 struct got_pathlist_entry *pe;
1164 TAILQ_FOREACH(pe, wanted_refs, entry) {
1165 if (match_wanted_ref(refname, pe->path))
1166 return 1;
1169 return 0;
1172 static const struct got_error *
1173 create_wanted_ref(const char *refname, struct got_object_id *id,
1174 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1176 const struct got_error *err;
1177 char *remote_refname;
1179 if (strncmp("refs/", refname, 5) == 0)
1180 refname += 5;
1182 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1183 remote_repo_name, refname) == -1)
1184 return got_error_from_errno("asprintf");
1186 err = create_ref(remote_refname, id, verbosity, repo);
1187 free(remote_refname);
1188 return err;
1191 static const struct got_error *
1192 create_gotconfig(const char *proto, const char *host, const char *port,
1193 const char *remote_repo_path, const char *default_branch,
1194 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1195 struct got_pathlist_head *wanted_refs, int mirror_references,
1196 struct got_repository *repo)
1198 const struct got_error *err = NULL;
1199 char *gotconfig_path = NULL;
1200 char *gotconfig = NULL;
1201 FILE *gotconfig_file = NULL;
1202 const char *branchname = NULL;
1203 char *branches = NULL, *refs = NULL;
1204 ssize_t n;
1206 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1207 struct got_pathlist_entry *pe;
1208 TAILQ_FOREACH(pe, wanted_branches, entry) {
1209 char *s;
1210 branchname = pe->path;
1211 if (strncmp(branchname, "refs/heads/", 11) == 0)
1212 branchname += 11;
1213 if (asprintf(&s, "%s\"%s\" ",
1214 branches ? branches : "", branchname) == -1) {
1215 err = got_error_from_errno("asprintf");
1216 goto done;
1218 free(branches);
1219 branches = s;
1221 } else if (!fetch_all_branches && default_branch) {
1222 branchname = default_branch;
1223 if (strncmp(branchname, "refs/heads/", 11) == 0)
1224 branchname += 11;
1225 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1226 err = got_error_from_errno("asprintf");
1227 goto done;
1230 if (!TAILQ_EMPTY(wanted_refs)) {
1231 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 char *s;
1234 const char *refname = pe->path;
1235 if (strncmp(refname, "refs/", 5) == 0)
1236 branchname += 5;
1237 if (asprintf(&s, "%s\"%s\" ",
1238 refs ? refs : "", refname) == -1) {
1239 err = got_error_from_errno("asprintf");
1240 goto done;
1242 free(refs);
1243 refs = s;
1247 /* Create got.conf(5). */
1248 gotconfig_path = got_repo_get_path_gotconfig(repo);
1249 if (gotconfig_path == NULL) {
1250 err = got_error_from_errno("got_repo_get_path_gotconfig");
1251 goto done;
1253 gotconfig_file = fopen(gotconfig_path, "ae");
1254 if (gotconfig_file == NULL) {
1255 err = got_error_from_errno2("fopen", gotconfig_path);
1256 goto done;
1258 if (asprintf(&gotconfig,
1259 "remote \"%s\" {\n"
1260 "\tserver %s\n"
1261 "\tprotocol %s\n"
1262 "%s%s%s"
1263 "\trepository \"%s\"\n"
1264 "%s%s%s"
1265 "%s%s%s"
1266 "%s"
1267 "%s"
1268 "}\n",
1269 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1270 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1271 remote_repo_path, branches ? "\tbranch { " : "",
1272 branches ? branches : "", branches ? "}\n" : "",
1273 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1274 mirror_references ? "\tmirror-references yes\n" : "",
1275 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1276 err = got_error_from_errno("asprintf");
1277 goto done;
1279 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1280 if (n != strlen(gotconfig)) {
1281 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1282 goto done;
1285 done:
1286 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1287 err = got_error_from_errno2("fclose", gotconfig_path);
1288 free(gotconfig_path);
1289 free(branches);
1290 return err;
1293 static const struct got_error *
1294 create_gitconfig(const char *git_url, const char *default_branch,
1295 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1296 struct got_pathlist_head *wanted_refs, int mirror_references,
1297 struct got_repository *repo)
1299 const struct got_error *err = NULL;
1300 char *gitconfig_path = NULL;
1301 char *gitconfig = NULL;
1302 FILE *gitconfig_file = NULL;
1303 char *branches = NULL, *refs = NULL;
1304 const char *branchname;
1305 ssize_t n;
1307 /* Create a config file Git can understand. */
1308 gitconfig_path = got_repo_get_path_gitconfig(repo);
1309 if (gitconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gitconfig");
1311 goto done;
1313 gitconfig_file = fopen(gitconfig_path, "ae");
1314 if (gitconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gitconfig_path);
1316 goto done;
1318 if (fetch_all_branches) {
1319 if (mirror_references) {
1320 if (asprintf(&branches,
1321 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1322 err = got_error_from_errno("asprintf");
1323 goto done;
1325 } else if (asprintf(&branches,
1326 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1327 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1328 err = got_error_from_errno("asprintf");
1329 goto done;
1331 } else if (!TAILQ_EMPTY(wanted_branches)) {
1332 struct got_pathlist_entry *pe;
1333 TAILQ_FOREACH(pe, wanted_branches, entry) {
1334 char *s;
1335 branchname = pe->path;
1336 if (strncmp(branchname, "refs/heads/", 11) == 0)
1337 branchname += 11;
1338 if (mirror_references) {
1339 if (asprintf(&s,
1340 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1341 branches ? branches : "",
1342 branchname, branchname) == -1) {
1343 err = got_error_from_errno("asprintf");
1344 goto done;
1346 } else if (asprintf(&s,
1347 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1348 branches ? branches : "",
1349 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1350 branchname) == -1) {
1351 err = got_error_from_errno("asprintf");
1352 goto done;
1354 free(branches);
1355 branches = s;
1357 } else {
1359 * If the server specified a default branch, use just that one.
1360 * Otherwise fall back to fetching all branches on next fetch.
1362 if (default_branch) {
1363 branchname = default_branch;
1364 if (strncmp(branchname, "refs/heads/", 11) == 0)
1365 branchname += 11;
1366 } else
1367 branchname = "*"; /* fall back to all branches */
1368 if (mirror_references) {
1369 if (asprintf(&branches,
1370 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1371 branchname, branchname) == -1) {
1372 err = got_error_from_errno("asprintf");
1373 goto done;
1375 } else if (asprintf(&branches,
1376 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1377 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1378 branchname) == -1) {
1379 err = got_error_from_errno("asprintf");
1380 goto done;
1383 if (!TAILQ_EMPTY(wanted_refs)) {
1384 struct got_pathlist_entry *pe;
1385 TAILQ_FOREACH(pe, wanted_refs, entry) {
1386 char *s;
1387 const char *refname = pe->path;
1388 if (strncmp(refname, "refs/", 5) == 0)
1389 refname += 5;
1390 if (mirror_references) {
1391 if (asprintf(&s,
1392 "%s\tfetch = refs/%s:refs/%s\n",
1393 refs ? refs : "", refname, refname) == -1) {
1394 err = got_error_from_errno("asprintf");
1395 goto done;
1397 } else if (asprintf(&s,
1398 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1399 refs ? refs : "",
1400 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1401 refname) == -1) {
1402 err = got_error_from_errno("asprintf");
1403 goto done;
1405 free(refs);
1406 refs = s;
1410 if (asprintf(&gitconfig,
1411 "[remote \"%s\"]\n"
1412 "\turl = %s\n"
1413 "%s"
1414 "%s"
1415 "\tfetch = refs/tags/*:refs/tags/*\n",
1416 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1417 refs ? refs : "") == -1) {
1418 err = got_error_from_errno("asprintf");
1419 goto done;
1421 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1422 if (n != strlen(gitconfig)) {
1423 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1424 goto done;
1426 done:
1427 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1428 err = got_error_from_errno2("fclose", gitconfig_path);
1429 free(gitconfig_path);
1430 free(branches);
1431 return err;
1434 static const struct got_error *
1435 create_config_files(const char *proto, const char *host, const char *port,
1436 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1437 int mirror_references, struct got_pathlist_head *symrefs,
1438 struct got_pathlist_head *wanted_branches,
1439 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1441 const struct got_error *err = NULL;
1442 const char *default_branch = NULL;
1443 struct got_pathlist_entry *pe;
1446 * If we asked for a set of wanted branches then use the first
1447 * one of those.
1449 if (!TAILQ_EMPTY(wanted_branches)) {
1450 pe = TAILQ_FIRST(wanted_branches);
1451 default_branch = pe->path;
1452 } else {
1453 /* First HEAD ref listed by server is the default branch. */
1454 TAILQ_FOREACH(pe, symrefs, entry) {
1455 const char *refname = pe->path;
1456 const char *target = pe->data;
1458 if (strcmp(refname, GOT_REF_HEAD) != 0)
1459 continue;
1461 default_branch = target;
1462 break;
1466 /* Create got.conf(5). */
1467 err = create_gotconfig(proto, host, port, remote_repo_path,
1468 default_branch, fetch_all_branches, wanted_branches,
1469 wanted_refs, mirror_references, repo);
1470 if (err)
1471 return err;
1473 /* Create a config file Git can understand. */
1474 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1475 wanted_branches, wanted_refs, mirror_references, repo);
1478 static const struct got_error *
1479 cmd_clone(int argc, char *argv[])
1481 const struct got_error *error = NULL;
1482 const char *uri, *dirname;
1483 char *proto, *host, *port, *repo_name, *server_path;
1484 char *default_destdir = NULL, *id_str = NULL;
1485 const char *repo_path;
1486 struct got_repository *repo = NULL;
1487 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1488 struct got_pathlist_entry *pe;
1489 struct got_object_id *pack_hash = NULL;
1490 int ch, fetchfd = -1, fetchstatus;
1491 pid_t fetchpid = -1;
1492 struct got_fetch_progress_arg fpa;
1493 char *git_url = NULL;
1494 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1495 int list_refs_only = 0;
1496 int *pack_fds = NULL;
1498 TAILQ_INIT(&refs);
1499 TAILQ_INIT(&symrefs);
1500 TAILQ_INIT(&wanted_branches);
1501 TAILQ_INIT(&wanted_refs);
1503 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1504 switch (ch) {
1505 case 'a':
1506 fetch_all_branches = 1;
1507 break;
1508 case 'b':
1509 error = got_pathlist_append(&wanted_branches,
1510 optarg, NULL);
1511 if (error)
1512 return error;
1513 break;
1514 case 'l':
1515 list_refs_only = 1;
1516 break;
1517 case 'm':
1518 mirror_references = 1;
1519 break;
1520 case 'v':
1521 if (verbosity < 0)
1522 verbosity = 0;
1523 else if (verbosity < 3)
1524 verbosity++;
1525 break;
1526 case 'q':
1527 verbosity = -1;
1528 break;
1529 case 'R':
1530 error = got_pathlist_append(&wanted_refs,
1531 optarg, NULL);
1532 if (error)
1533 return error;
1534 break;
1535 default:
1536 usage_clone();
1537 break;
1540 argc -= optind;
1541 argv += optind;
1543 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1544 option_conflict('a', 'b');
1545 if (list_refs_only) {
1546 if (!TAILQ_EMPTY(&wanted_branches))
1547 option_conflict('l', 'b');
1548 if (fetch_all_branches)
1549 option_conflict('l', 'a');
1550 if (mirror_references)
1551 option_conflict('l', 'm');
1552 if (!TAILQ_EMPTY(&wanted_refs))
1553 option_conflict('l', 'R');
1556 uri = argv[0];
1558 if (argc == 1)
1559 dirname = NULL;
1560 else if (argc == 2)
1561 dirname = argv[1];
1562 else
1563 usage_clone();
1565 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1566 &repo_name, uri);
1567 if (error)
1568 goto done;
1570 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1571 host, port ? ":" : "", port ? port : "",
1572 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1573 error = got_error_from_errno("asprintf");
1574 goto done;
1577 if (strcmp(proto, "git") == 0) {
1578 #ifndef PROFILE
1579 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1580 "sendfd dns inet unveil", NULL) == -1)
1581 err(1, "pledge");
1582 #endif
1583 } else if (strcmp(proto, "git+ssh") == 0 ||
1584 strcmp(proto, "ssh") == 0) {
1585 #ifndef PROFILE
1586 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1587 "sendfd unveil", NULL) == -1)
1588 err(1, "pledge");
1589 #endif
1590 } else if (strcmp(proto, "http") == 0 ||
1591 strcmp(proto, "git+http") == 0) {
1592 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1593 goto done;
1594 } else {
1595 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1596 goto done;
1598 if (dirname == NULL) {
1599 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1600 error = got_error_from_errno("asprintf");
1601 goto done;
1603 repo_path = default_destdir;
1604 } else
1605 repo_path = dirname;
1607 if (!list_refs_only) {
1608 error = got_path_mkdir(repo_path);
1609 if (error &&
1610 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1611 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1612 goto done;
1613 if (!got_path_dir_is_empty(repo_path)) {
1614 error = got_error_path(repo_path,
1615 GOT_ERR_DIR_NOT_EMPTY);
1616 goto done;
1620 error = got_dial_apply_unveil(proto);
1621 if (error)
1622 goto done;
1624 error = apply_unveil(repo_path, 0, NULL);
1625 if (error)
1626 goto done;
1628 if (verbosity >= 0)
1629 printf("Connecting to %s%s%s\n", host,
1630 port ? ":" : "", port ? port : "");
1632 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1633 server_path, verbosity);
1634 if (error)
1635 goto done;
1637 if (!list_refs_only) {
1638 error = got_repo_init(repo_path);
1639 if (error)
1640 goto done;
1641 error = got_repo_pack_fds_open(&pack_fds);
1642 if (error != NULL)
1643 goto done;
1644 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1645 if (error)
1646 goto done;
1649 fpa.last_scaled_size[0] = '\0';
1650 fpa.last_p_indexed = -1;
1651 fpa.last_p_resolved = -1;
1652 fpa.verbosity = verbosity;
1653 fpa.create_configs = 1;
1654 fpa.configs_created = 0;
1655 fpa.repo = repo;
1656 fpa.config_info.symrefs = &symrefs;
1657 fpa.config_info.wanted_branches = &wanted_branches;
1658 fpa.config_info.wanted_refs = &wanted_refs;
1659 fpa.config_info.proto = proto;
1660 fpa.config_info.host = host;
1661 fpa.config_info.port = port;
1662 fpa.config_info.remote_repo_path = server_path;
1663 fpa.config_info.git_url = git_url;
1664 fpa.config_info.fetch_all_branches = fetch_all_branches;
1665 fpa.config_info.mirror_references = mirror_references;
1666 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1667 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1668 fetch_all_branches, &wanted_branches, &wanted_refs,
1669 list_refs_only, verbosity, fetchfd, repo,
1670 fetch_progress, &fpa);
1671 if (error)
1672 goto done;
1674 if (list_refs_only) {
1675 error = list_remote_refs(&symrefs, &refs);
1676 goto done;
1679 if (pack_hash == NULL) {
1680 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1681 "server sent an empty pack file");
1682 goto done;
1684 error = got_object_id_str(&id_str, pack_hash);
1685 if (error)
1686 goto done;
1687 if (verbosity >= 0)
1688 printf("\nFetched %s.pack\n", id_str);
1689 free(id_str);
1691 /* Set up references provided with the pack file. */
1692 TAILQ_FOREACH(pe, &refs, entry) {
1693 const char *refname = pe->path;
1694 struct got_object_id *id = pe->data;
1695 char *remote_refname;
1697 if (is_wanted_ref(&wanted_refs, refname) &&
1698 !mirror_references) {
1699 error = create_wanted_ref(refname, id,
1700 GOT_FETCH_DEFAULT_REMOTE_NAME,
1701 verbosity - 1, repo);
1702 if (error)
1703 goto done;
1704 continue;
1707 error = create_ref(refname, id, verbosity - 1, repo);
1708 if (error)
1709 goto done;
1711 if (mirror_references)
1712 continue;
1714 if (strncmp("refs/heads/", refname, 11) != 0)
1715 continue;
1717 if (asprintf(&remote_refname,
1718 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1719 refname + 11) == -1) {
1720 error = got_error_from_errno("asprintf");
1721 goto done;
1723 error = create_ref(remote_refname, id, verbosity - 1, repo);
1724 free(remote_refname);
1725 if (error)
1726 goto done;
1729 /* Set the HEAD reference if the server provided one. */
1730 TAILQ_FOREACH(pe, &symrefs, entry) {
1731 struct got_reference *target_ref;
1732 const char *refname = pe->path;
1733 const char *target = pe->data;
1734 char *remote_refname = NULL, *remote_target = NULL;
1736 if (strcmp(refname, GOT_REF_HEAD) != 0)
1737 continue;
1739 error = got_ref_open(&target_ref, repo, target, 0);
1740 if (error) {
1741 if (error->code == GOT_ERR_NOT_REF) {
1742 error = NULL;
1743 continue;
1745 goto done;
1748 error = create_symref(refname, target_ref, verbosity, repo);
1749 got_ref_close(target_ref);
1750 if (error)
1751 goto done;
1753 if (mirror_references)
1754 continue;
1756 if (strncmp("refs/heads/", target, 11) != 0)
1757 continue;
1759 if (asprintf(&remote_refname,
1760 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1761 refname) == -1) {
1762 error = got_error_from_errno("asprintf");
1763 goto done;
1765 if (asprintf(&remote_target,
1766 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1767 target + 11) == -1) {
1768 error = got_error_from_errno("asprintf");
1769 free(remote_refname);
1770 goto done;
1772 error = got_ref_open(&target_ref, repo, remote_target, 0);
1773 if (error) {
1774 free(remote_refname);
1775 free(remote_target);
1776 if (error->code == GOT_ERR_NOT_REF) {
1777 error = NULL;
1778 continue;
1780 goto done;
1782 error = create_symref(remote_refname, target_ref,
1783 verbosity - 1, repo);
1784 free(remote_refname);
1785 free(remote_target);
1786 got_ref_close(target_ref);
1787 if (error)
1788 goto done;
1790 if (pe == NULL) {
1792 * We failed to set the HEAD reference. If we asked for
1793 * a set of wanted branches use the first of one of those
1794 * which could be fetched instead.
1796 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1797 const char *target = pe->path;
1798 struct got_reference *target_ref;
1800 error = got_ref_open(&target_ref, repo, target, 0);
1801 if (error) {
1802 if (error->code == GOT_ERR_NOT_REF) {
1803 error = NULL;
1804 continue;
1806 goto done;
1809 error = create_symref(GOT_REF_HEAD, target_ref,
1810 verbosity, repo);
1811 got_ref_close(target_ref);
1812 if (error)
1813 goto done;
1814 break;
1818 if (verbosity >= 0)
1819 printf("Created %s repository '%s'\n",
1820 mirror_references ? "mirrored" : "cloned", repo_path);
1821 done:
1822 if (pack_fds) {
1823 const struct got_error *pack_err =
1824 got_repo_pack_fds_close(pack_fds);
1825 if (error == NULL)
1826 error = pack_err;
1828 if (fetchpid > 0) {
1829 if (kill(fetchpid, SIGTERM) == -1)
1830 error = got_error_from_errno("kill");
1831 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1832 error = got_error_from_errno("waitpid");
1834 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1835 error = got_error_from_errno("close");
1836 if (repo) {
1837 const struct got_error *close_err = got_repo_close(repo);
1838 if (error == NULL)
1839 error = close_err;
1841 TAILQ_FOREACH(pe, &refs, entry) {
1842 free((void *)pe->path);
1843 free(pe->data);
1845 got_pathlist_free(&refs);
1846 TAILQ_FOREACH(pe, &symrefs, entry) {
1847 free((void *)pe->path);
1848 free(pe->data);
1850 got_pathlist_free(&symrefs);
1851 got_pathlist_free(&wanted_branches);
1852 got_pathlist_free(&wanted_refs);
1853 free(pack_hash);
1854 free(proto);
1855 free(host);
1856 free(port);
1857 free(server_path);
1858 free(repo_name);
1859 free(default_destdir);
1860 free(git_url);
1861 return error;
1864 static const struct got_error *
1865 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1866 int replace_tags, int verbosity, struct got_repository *repo)
1868 const struct got_error *err = NULL;
1869 char *new_id_str = NULL;
1870 struct got_object_id *old_id = NULL;
1872 err = got_object_id_str(&new_id_str, new_id);
1873 if (err)
1874 goto done;
1876 if (!replace_tags &&
1877 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1878 err = got_ref_resolve(&old_id, repo, ref);
1879 if (err)
1880 goto done;
1881 if (got_object_id_cmp(old_id, new_id) == 0)
1882 goto done;
1883 if (verbosity >= 0) {
1884 printf("Rejecting update of existing tag %s: %s\n",
1885 got_ref_get_name(ref), new_id_str);
1887 goto done;
1890 if (got_ref_is_symbolic(ref)) {
1891 if (verbosity >= 0) {
1892 printf("Replacing reference %s: %s\n",
1893 got_ref_get_name(ref),
1894 got_ref_get_symref_target(ref));
1896 err = got_ref_change_symref_to_ref(ref, new_id);
1897 if (err)
1898 goto done;
1899 err = got_ref_write(ref, repo);
1900 if (err)
1901 goto done;
1902 } else {
1903 err = got_ref_resolve(&old_id, repo, ref);
1904 if (err)
1905 goto done;
1906 if (got_object_id_cmp(old_id, new_id) == 0)
1907 goto done;
1909 err = got_ref_change_ref(ref, new_id);
1910 if (err)
1911 goto done;
1912 err = got_ref_write(ref, repo);
1913 if (err)
1914 goto done;
1917 if (verbosity >= 0)
1918 printf("Updated %s: %s\n", got_ref_get_name(ref),
1919 new_id_str);
1920 done:
1921 free(old_id);
1922 free(new_id_str);
1923 return err;
1926 static const struct got_error *
1927 update_symref(const char *refname, struct got_reference *target_ref,
1928 int verbosity, struct got_repository *repo)
1930 const struct got_error *err = NULL, *unlock_err;
1931 struct got_reference *symref;
1932 int symref_is_locked = 0;
1934 err = got_ref_open(&symref, repo, refname, 1);
1935 if (err) {
1936 if (err->code != GOT_ERR_NOT_REF)
1937 return err;
1938 err = got_ref_alloc_symref(&symref, refname, 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("Created reference %s: %s\n",
1948 got_ref_get_name(symref),
1949 got_ref_get_symref_target(symref));
1950 } else {
1951 symref_is_locked = 1;
1953 if (strcmp(got_ref_get_symref_target(symref),
1954 got_ref_get_name(target_ref)) == 0)
1955 goto done;
1957 err = got_ref_change_symref(symref,
1958 got_ref_get_name(target_ref));
1959 if (err)
1960 goto done;
1962 err = got_ref_write(symref, repo);
1963 if (err)
1964 goto done;
1966 if (verbosity >= 0)
1967 printf("Updated %s: %s\n", got_ref_get_name(symref),
1968 got_ref_get_symref_target(symref));
1971 done:
1972 if (symref_is_locked) {
1973 unlock_err = got_ref_unlock(symref);
1974 if (unlock_err && err == NULL)
1975 err = unlock_err;
1977 got_ref_close(symref);
1978 return err;
1981 __dead static void
1982 usage_fetch(void)
1984 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1985 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1986 "[remote-repository-name]\n",
1987 getprogname());
1988 exit(1);
1991 static const struct got_error *
1992 delete_missing_ref(struct got_reference *ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL;
1996 struct got_object_id *id = NULL;
1997 char *id_str = NULL;
1999 if (got_ref_is_symbolic(ref)) {
2000 err = got_ref_delete(ref, repo);
2001 if (err)
2002 return err;
2003 if (verbosity >= 0) {
2004 printf("Deleted %s: %s\n",
2005 got_ref_get_name(ref),
2006 got_ref_get_symref_target(ref));
2008 } else {
2009 err = got_ref_resolve(&id, repo, ref);
2010 if (err)
2011 return err;
2012 err = got_object_id_str(&id_str, id);
2013 if (err)
2014 goto done;
2016 err = got_ref_delete(ref, repo);
2017 if (err)
2018 goto done;
2019 if (verbosity >= 0) {
2020 printf("Deleted %s: %s\n",
2021 got_ref_get_name(ref), id_str);
2024 done:
2025 free(id);
2026 free(id_str);
2027 return NULL;
2030 static const struct got_error *
2031 delete_missing_refs(struct got_pathlist_head *their_refs,
2032 struct got_pathlist_head *their_symrefs,
2033 const struct got_remote_repo *remote,
2034 int verbosity, struct got_repository *repo)
2036 const struct got_error *err = NULL, *unlock_err;
2037 struct got_reflist_head my_refs;
2038 struct got_reflist_entry *re;
2039 struct got_pathlist_entry *pe;
2040 char *remote_namespace = NULL;
2041 char *local_refname = NULL;
2043 TAILQ_INIT(&my_refs);
2045 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2046 == -1)
2047 return got_error_from_errno("asprintf");
2049 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2050 if (err)
2051 goto done;
2053 TAILQ_FOREACH(re, &my_refs, entry) {
2054 const char *refname = got_ref_get_name(re->ref);
2055 const char *their_refname;
2057 if (remote->mirror_references) {
2058 their_refname = refname;
2059 } else {
2060 if (strncmp(refname, remote_namespace,
2061 strlen(remote_namespace)) == 0) {
2062 if (strcmp(refname + strlen(remote_namespace),
2063 GOT_REF_HEAD) == 0)
2064 continue;
2065 if (asprintf(&local_refname, "refs/heads/%s",
2066 refname + strlen(remote_namespace)) == -1) {
2067 err = got_error_from_errno("asprintf");
2068 goto done;
2070 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2071 continue;
2073 their_refname = local_refname;
2076 TAILQ_FOREACH(pe, their_refs, entry) {
2077 if (strcmp(their_refname, pe->path) == 0)
2078 break;
2080 if (pe != NULL)
2081 continue;
2083 TAILQ_FOREACH(pe, their_symrefs, entry) {
2084 if (strcmp(their_refname, pe->path) == 0)
2085 break;
2087 if (pe != NULL)
2088 continue;
2090 err = delete_missing_ref(re->ref, verbosity, repo);
2091 if (err)
2092 break;
2094 if (local_refname) {
2095 struct got_reference *ref;
2096 err = got_ref_open(&ref, repo, local_refname, 1);
2097 if (err) {
2098 if (err->code != GOT_ERR_NOT_REF)
2099 break;
2100 free(local_refname);
2101 local_refname = NULL;
2102 continue;
2104 err = delete_missing_ref(ref, verbosity, repo);
2105 if (err)
2106 break;
2107 unlock_err = got_ref_unlock(ref);
2108 got_ref_close(ref);
2109 if (unlock_err && err == NULL) {
2110 err = unlock_err;
2111 break;
2114 free(local_refname);
2115 local_refname = NULL;
2118 done:
2119 free(remote_namespace);
2120 free(local_refname);
2121 return err;
2124 static const struct got_error *
2125 update_wanted_ref(const char *refname, struct got_object_id *id,
2126 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2128 const struct got_error *err, *unlock_err;
2129 char *remote_refname;
2130 struct got_reference *ref;
2132 if (strncmp("refs/", refname, 5) == 0)
2133 refname += 5;
2135 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2136 remote_repo_name, refname) == -1)
2137 return got_error_from_errno("asprintf");
2139 err = got_ref_open(&ref, repo, remote_refname, 1);
2140 if (err) {
2141 if (err->code != GOT_ERR_NOT_REF)
2142 goto done;
2143 err = create_ref(remote_refname, id, verbosity, repo);
2144 } else {
2145 err = update_ref(ref, id, 0, verbosity, repo);
2146 unlock_err = got_ref_unlock(ref);
2147 if (unlock_err && err == NULL)
2148 err = unlock_err;
2149 got_ref_close(ref);
2151 done:
2152 free(remote_refname);
2153 return err;
2156 static const struct got_error *
2157 delete_ref(struct got_repository *repo, struct got_reference *ref)
2159 const struct got_error *err = NULL;
2160 struct got_object_id *id = NULL;
2161 char *id_str = NULL;
2162 const char *target;
2164 if (got_ref_is_symbolic(ref)) {
2165 target = got_ref_get_symref_target(ref);
2166 } else {
2167 err = got_ref_resolve(&id, repo, ref);
2168 if (err)
2169 goto done;
2170 err = got_object_id_str(&id_str, id);
2171 if (err)
2172 goto done;
2173 target = id_str;
2176 err = got_ref_delete(ref, repo);
2177 if (err)
2178 goto done;
2180 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2181 done:
2182 free(id);
2183 free(id_str);
2184 return err;
2187 static const struct got_error *
2188 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2190 const struct got_error *err = NULL;
2191 struct got_reflist_head refs;
2192 struct got_reflist_entry *re;
2193 char *prefix;
2195 TAILQ_INIT(&refs);
2197 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2198 err = got_error_from_errno("asprintf");
2199 goto done;
2201 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2202 if (err)
2203 goto done;
2205 TAILQ_FOREACH(re, &refs, entry)
2206 delete_ref(repo, re->ref);
2207 done:
2208 got_ref_list_free(&refs);
2209 return err;
2212 static const struct got_error *
2213 cmd_fetch(int argc, char *argv[])
2215 const struct got_error *error = NULL, *unlock_err;
2216 char *cwd = NULL, *repo_path = NULL;
2217 const char *remote_name;
2218 char *proto = NULL, *host = NULL, *port = NULL;
2219 char *repo_name = NULL, *server_path = NULL;
2220 const struct got_remote_repo *remotes, *remote = NULL;
2221 int nremotes;
2222 char *id_str = NULL;
2223 struct got_repository *repo = NULL;
2224 struct got_worktree *worktree = NULL;
2225 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2226 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2227 struct got_pathlist_entry *pe;
2228 struct got_object_id *pack_hash = NULL;
2229 int i, ch, fetchfd = -1, fetchstatus;
2230 pid_t fetchpid = -1;
2231 struct got_fetch_progress_arg fpa;
2232 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2233 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2234 int *pack_fds = NULL;
2236 TAILQ_INIT(&refs);
2237 TAILQ_INIT(&symrefs);
2238 TAILQ_INIT(&wanted_branches);
2239 TAILQ_INIT(&wanted_refs);
2241 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2242 switch (ch) {
2243 case 'a':
2244 fetch_all_branches = 1;
2245 break;
2246 case 'b':
2247 error = got_pathlist_append(&wanted_branches,
2248 optarg, NULL);
2249 if (error)
2250 return error;
2251 break;
2252 case 'd':
2253 delete_refs = 1;
2254 break;
2255 case 'l':
2256 list_refs_only = 1;
2257 break;
2258 case 'r':
2259 repo_path = realpath(optarg, NULL);
2260 if (repo_path == NULL)
2261 return got_error_from_errno2("realpath",
2262 optarg);
2263 got_path_strip_trailing_slashes(repo_path);
2264 break;
2265 case 't':
2266 replace_tags = 1;
2267 break;
2268 case 'v':
2269 if (verbosity < 0)
2270 verbosity = 0;
2271 else if (verbosity < 3)
2272 verbosity++;
2273 break;
2274 case 'q':
2275 verbosity = -1;
2276 break;
2277 case 'R':
2278 error = got_pathlist_append(&wanted_refs,
2279 optarg, NULL);
2280 if (error)
2281 return error;
2282 break;
2283 case 'X':
2284 delete_remote = 1;
2285 break;
2286 default:
2287 usage_fetch();
2288 break;
2291 argc -= optind;
2292 argv += optind;
2294 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2295 option_conflict('a', 'b');
2296 if (list_refs_only) {
2297 if (!TAILQ_EMPTY(&wanted_branches))
2298 option_conflict('l', 'b');
2299 if (fetch_all_branches)
2300 option_conflict('l', 'a');
2301 if (delete_refs)
2302 option_conflict('l', 'd');
2303 if (delete_remote)
2304 option_conflict('l', 'X');
2306 if (delete_remote) {
2307 if (fetch_all_branches)
2308 option_conflict('X', 'a');
2309 if (!TAILQ_EMPTY(&wanted_branches))
2310 option_conflict('X', 'b');
2311 if (delete_refs)
2312 option_conflict('X', 'd');
2313 if (replace_tags)
2314 option_conflict('X', 't');
2315 if (!TAILQ_EMPTY(&wanted_refs))
2316 option_conflict('X', 'R');
2319 if (argc == 0) {
2320 if (delete_remote)
2321 errx(1, "-X option requires a remote name");
2322 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2323 } else if (argc == 1)
2324 remote_name = argv[0];
2325 else
2326 usage_fetch();
2328 cwd = getcwd(NULL, 0);
2329 if (cwd == NULL) {
2330 error = got_error_from_errno("getcwd");
2331 goto done;
2334 error = got_repo_pack_fds_open(&pack_fds);
2335 if (error != NULL)
2336 goto done;
2338 if (repo_path == NULL) {
2339 error = got_worktree_open(&worktree, cwd);
2340 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2341 goto done;
2342 else
2343 error = NULL;
2344 if (worktree) {
2345 repo_path =
2346 strdup(got_worktree_get_repo_path(worktree));
2347 if (repo_path == NULL)
2348 error = got_error_from_errno("strdup");
2349 if (error)
2350 goto done;
2351 } else {
2352 repo_path = strdup(cwd);
2353 if (repo_path == NULL) {
2354 error = got_error_from_errno("strdup");
2355 goto done;
2360 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2361 if (error)
2362 goto done;
2364 if (delete_remote) {
2365 error = delete_refs_for_remote(repo, remote_name);
2366 goto done; /* nothing else to do */
2369 if (worktree) {
2370 worktree_conf = got_worktree_get_gotconfig(worktree);
2371 if (worktree_conf) {
2372 got_gotconfig_get_remotes(&nremotes, &remotes,
2373 worktree_conf);
2374 for (i = 0; i < nremotes; i++) {
2375 if (strcmp(remotes[i].name, remote_name) == 0) {
2376 remote = &remotes[i];
2377 break;
2382 if (remote == NULL) {
2383 repo_conf = got_repo_get_gotconfig(repo);
2384 if (repo_conf) {
2385 got_gotconfig_get_remotes(&nremotes, &remotes,
2386 repo_conf);
2387 for (i = 0; i < nremotes; i++) {
2388 if (strcmp(remotes[i].name, remote_name) == 0) {
2389 remote = &remotes[i];
2390 break;
2395 if (remote == NULL) {
2396 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2397 for (i = 0; i < nremotes; i++) {
2398 if (strcmp(remotes[i].name, remote_name) == 0) {
2399 remote = &remotes[i];
2400 break;
2404 if (remote == NULL) {
2405 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2406 goto done;
2409 if (TAILQ_EMPTY(&wanted_branches)) {
2410 if (!fetch_all_branches)
2411 fetch_all_branches = remote->fetch_all_branches;
2412 for (i = 0; i < remote->nfetch_branches; i++) {
2413 got_pathlist_append(&wanted_branches,
2414 remote->fetch_branches[i], NULL);
2417 if (TAILQ_EMPTY(&wanted_refs)) {
2418 for (i = 0; i < remote->nfetch_refs; i++) {
2419 got_pathlist_append(&wanted_refs,
2420 remote->fetch_refs[i], NULL);
2424 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2425 &repo_name, remote->fetch_url);
2426 if (error)
2427 goto done;
2429 if (strcmp(proto, "git") == 0) {
2430 #ifndef PROFILE
2431 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2432 "sendfd dns inet unveil", NULL) == -1)
2433 err(1, "pledge");
2434 #endif
2435 } else if (strcmp(proto, "git+ssh") == 0 ||
2436 strcmp(proto, "ssh") == 0) {
2437 #ifndef PROFILE
2438 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2439 "sendfd unveil", NULL) == -1)
2440 err(1, "pledge");
2441 #endif
2442 } else if (strcmp(proto, "http") == 0 ||
2443 strcmp(proto, "git+http") == 0) {
2444 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2445 goto done;
2446 } else {
2447 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2448 goto done;
2451 error = got_dial_apply_unveil(proto);
2452 if (error)
2453 goto done;
2455 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2456 if (error)
2457 goto done;
2459 if (verbosity >= 0)
2460 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2461 port ? ":" : "", port ? port : "");
2463 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2464 server_path, verbosity);
2465 if (error)
2466 goto done;
2468 fpa.last_scaled_size[0] = '\0';
2469 fpa.last_p_indexed = -1;
2470 fpa.last_p_resolved = -1;
2471 fpa.verbosity = verbosity;
2472 fpa.repo = repo;
2473 fpa.create_configs = 0;
2474 fpa.configs_created = 0;
2475 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2476 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2477 remote->mirror_references, fetch_all_branches, &wanted_branches,
2478 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2479 fetch_progress, &fpa);
2480 if (error)
2481 goto done;
2483 if (list_refs_only) {
2484 error = list_remote_refs(&symrefs, &refs);
2485 goto done;
2488 if (pack_hash == NULL) {
2489 if (verbosity >= 0)
2490 printf("Already up-to-date\n");
2491 } else if (verbosity >= 0) {
2492 error = got_object_id_str(&id_str, pack_hash);
2493 if (error)
2494 goto done;
2495 printf("\nFetched %s.pack\n", id_str);
2496 free(id_str);
2497 id_str = NULL;
2500 /* Update references provided with the pack file. */
2501 TAILQ_FOREACH(pe, &refs, entry) {
2502 const char *refname = pe->path;
2503 struct got_object_id *id = pe->data;
2504 struct got_reference *ref;
2505 char *remote_refname;
2507 if (is_wanted_ref(&wanted_refs, refname) &&
2508 !remote->mirror_references) {
2509 error = update_wanted_ref(refname, id,
2510 remote->name, verbosity, repo);
2511 if (error)
2512 goto done;
2513 continue;
2516 if (remote->mirror_references ||
2517 strncmp("refs/tags/", refname, 10) == 0) {
2518 error = got_ref_open(&ref, repo, refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(refname, id, verbosity,
2523 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;
2536 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2537 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2538 remote_name, refname + 11) == -1) {
2539 error = got_error_from_errno("asprintf");
2540 goto done;
2543 error = got_ref_open(&ref, repo, remote_refname, 1);
2544 if (error) {
2545 if (error->code != GOT_ERR_NOT_REF)
2546 goto done;
2547 error = create_ref(remote_refname, id,
2548 verbosity, repo);
2549 if (error)
2550 goto done;
2551 } else {
2552 error = update_ref(ref, id, replace_tags,
2553 verbosity, repo);
2554 unlock_err = got_ref_unlock(ref);
2555 if (unlock_err && error == NULL)
2556 error = unlock_err;
2557 got_ref_close(ref);
2558 if (error)
2559 goto done;
2562 /* Also create a local branch if none exists yet. */
2563 error = got_ref_open(&ref, repo, refname, 1);
2564 if (error) {
2565 if (error->code != GOT_ERR_NOT_REF)
2566 goto done;
2567 error = create_ref(refname, id, verbosity,
2568 repo);
2569 if (error)
2570 goto done;
2571 } else {
2572 unlock_err = got_ref_unlock(ref);
2573 if (unlock_err && error == NULL)
2574 error = unlock_err;
2575 got_ref_close(ref);
2579 if (delete_refs) {
2580 error = delete_missing_refs(&refs, &symrefs, remote,
2581 verbosity, repo);
2582 if (error)
2583 goto done;
2586 if (!remote->mirror_references) {
2587 /* Update remote HEAD reference if the server provided one. */
2588 TAILQ_FOREACH(pe, &symrefs, entry) {
2589 struct got_reference *target_ref;
2590 const char *refname = pe->path;
2591 const char *target = pe->data;
2592 char *remote_refname = NULL, *remote_target = NULL;
2594 if (strcmp(refname, GOT_REF_HEAD) != 0)
2595 continue;
2597 if (strncmp("refs/heads/", target, 11) != 0)
2598 continue;
2600 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2601 remote->name, refname) == -1) {
2602 error = got_error_from_errno("asprintf");
2603 goto done;
2605 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2606 remote->name, target + 11) == -1) {
2607 error = got_error_from_errno("asprintf");
2608 free(remote_refname);
2609 goto done;
2612 error = got_ref_open(&target_ref, repo, remote_target,
2613 0);
2614 if (error) {
2615 free(remote_refname);
2616 free(remote_target);
2617 if (error->code == GOT_ERR_NOT_REF) {
2618 error = NULL;
2619 continue;
2621 goto done;
2623 error = update_symref(remote_refname, target_ref,
2624 verbosity, repo);
2625 free(remote_refname);
2626 free(remote_target);
2627 got_ref_close(target_ref);
2628 if (error)
2629 goto done;
2632 done:
2633 if (fetchpid > 0) {
2634 if (kill(fetchpid, SIGTERM) == -1)
2635 error = got_error_from_errno("kill");
2636 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2637 error = got_error_from_errno("waitpid");
2639 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2640 error = got_error_from_errno("close");
2641 if (repo) {
2642 const struct got_error *close_err = got_repo_close(repo);
2643 if (error == NULL)
2644 error = close_err;
2646 if (worktree)
2647 got_worktree_close(worktree);
2648 if (pack_fds) {
2649 const struct got_error *pack_err =
2650 got_repo_pack_fds_close(pack_fds);
2651 if (error == NULL)
2652 error = pack_err;
2654 TAILQ_FOREACH(pe, &refs, entry) {
2655 free((void *)pe->path);
2656 free(pe->data);
2658 got_pathlist_free(&refs);
2659 TAILQ_FOREACH(pe, &symrefs, entry) {
2660 free((void *)pe->path);
2661 free(pe->data);
2663 got_pathlist_free(&symrefs);
2664 got_pathlist_free(&wanted_branches);
2665 got_pathlist_free(&wanted_refs);
2666 free(id_str);
2667 free(cwd);
2668 free(repo_path);
2669 free(pack_hash);
2670 free(proto);
2671 free(host);
2672 free(port);
2673 free(server_path);
2674 free(repo_name);
2675 return error;
2679 __dead static void
2680 usage_checkout(void)
2682 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2683 "[-p prefix] [-q] repository-path [worktree-path]\n",
2684 getprogname());
2685 exit(1);
2688 static void
2689 show_worktree_base_ref_warning(void)
2691 fprintf(stderr, "%s: warning: could not create a reference "
2692 "to the work tree's base commit; the commit could be "
2693 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2694 "repository writable and running 'got update' will prevent this\n",
2695 getprogname());
2698 struct got_checkout_progress_arg {
2699 const char *worktree_path;
2700 int had_base_commit_ref_error;
2701 int verbosity;
2704 static const struct got_error *
2705 checkout_progress(void *arg, unsigned char status, const char *path)
2707 struct got_checkout_progress_arg *a = arg;
2709 /* Base commit bump happens silently. */
2710 if (status == GOT_STATUS_BUMP_BASE)
2711 return NULL;
2713 if (status == GOT_STATUS_BASE_REF_ERR) {
2714 a->had_base_commit_ref_error = 1;
2715 return NULL;
2718 while (path[0] == '/')
2719 path++;
2721 if (a->verbosity >= 0)
2722 printf("%c %s/%s\n", status, a->worktree_path, path);
2724 return NULL;
2727 static const struct got_error *
2728 check_cancelled(void *arg)
2730 if (sigint_received || sigpipe_received)
2731 return got_error(GOT_ERR_CANCELLED);
2732 return NULL;
2735 static const struct got_error *
2736 check_linear_ancestry(struct got_object_id *commit_id,
2737 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2738 struct got_repository *repo)
2740 const struct got_error *err = NULL;
2741 struct got_object_id *yca_id;
2743 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2744 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2745 if (err)
2746 return err;
2748 if (yca_id == NULL)
2749 return got_error(GOT_ERR_ANCESTRY);
2752 * Require a straight line of history between the target commit
2753 * and the work tree's base commit.
2755 * Non-linear situations such as this require a rebase:
2757 * (commit) D F (base_commit)
2758 * \ /
2759 * C E
2760 * \ /
2761 * B (yca)
2762 * |
2763 * A
2765 * 'got update' only handles linear cases:
2766 * Update forwards in time: A (base/yca) - B - C - D (commit)
2767 * Update backwards in time: D (base) - C - B - A (commit/yca)
2769 if (allow_forwards_in_time_only) {
2770 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2771 return got_error(GOT_ERR_ANCESTRY);
2772 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2773 got_object_id_cmp(base_commit_id, yca_id) != 0)
2774 return got_error(GOT_ERR_ANCESTRY);
2776 free(yca_id);
2777 return NULL;
2780 static const struct got_error *
2781 check_same_branch(struct got_object_id *commit_id,
2782 struct got_reference *head_ref, struct got_object_id *yca_id,
2783 struct got_repository *repo)
2785 const struct got_error *err = NULL;
2786 struct got_commit_graph *graph = NULL;
2787 struct got_object_id *head_commit_id = NULL;
2788 int is_same_branch = 0;
2790 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2791 if (err)
2792 goto done;
2794 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 goto done;
2798 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2799 is_same_branch = 1;
2800 goto done;
2803 err = got_commit_graph_open(&graph, "/", 1);
2804 if (err)
2805 goto done;
2807 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2808 check_cancelled, NULL);
2809 if (err)
2810 goto done;
2812 for (;;) {
2813 struct got_object_id *id;
2814 err = got_commit_graph_iter_next(&id, graph, repo,
2815 check_cancelled, NULL);
2816 if (err) {
2817 if (err->code == GOT_ERR_ITER_COMPLETED)
2818 err = NULL;
2819 break;
2822 if (id) {
2823 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2824 break;
2825 if (got_object_id_cmp(id, commit_id) == 0) {
2826 is_same_branch = 1;
2827 break;
2831 done:
2832 if (graph)
2833 got_commit_graph_close(graph);
2834 free(head_commit_id);
2835 if (!err && !is_same_branch)
2836 err = got_error(GOT_ERR_ANCESTRY);
2837 return err;
2840 static const struct got_error *
2841 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2843 static char msg[512];
2844 const char *branch_name;
2846 if (got_ref_is_symbolic(ref))
2847 branch_name = got_ref_get_symref_target(ref);
2848 else
2849 branch_name = got_ref_get_name(ref);
2851 if (strncmp("refs/heads/", branch_name, 11) == 0)
2852 branch_name += 11;
2854 snprintf(msg, sizeof(msg),
2855 "target commit is not contained in branch '%s'; "
2856 "the branch to use must be specified with -b; "
2857 "if necessary a new branch can be created for "
2858 "this commit with 'got branch -c %s BRANCH_NAME'",
2859 branch_name, commit_id_str);
2861 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2864 static const struct got_error *
2865 cmd_checkout(int argc, char *argv[])
2867 const struct got_error *error = NULL;
2868 struct got_repository *repo = NULL;
2869 struct got_reference *head_ref = NULL, *ref = NULL;
2870 struct got_worktree *worktree = NULL;
2871 char *repo_path = NULL;
2872 char *worktree_path = NULL;
2873 const char *path_prefix = "";
2874 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2875 char *commit_id_str = NULL;
2876 struct got_object_id *commit_id = NULL;
2877 char *cwd = NULL;
2878 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2879 struct got_pathlist_head paths;
2880 struct got_checkout_progress_arg cpa;
2881 int *pack_fds = NULL;
2883 TAILQ_INIT(&paths);
2885 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2886 switch (ch) {
2887 case 'b':
2888 branch_name = optarg;
2889 break;
2890 case 'c':
2891 commit_id_str = strdup(optarg);
2892 if (commit_id_str == NULL)
2893 return got_error_from_errno("strdup");
2894 break;
2895 case 'E':
2896 allow_nonempty = 1;
2897 break;
2898 case 'p':
2899 path_prefix = optarg;
2900 break;
2901 case 'q':
2902 verbosity = -1;
2903 break;
2904 default:
2905 usage_checkout();
2906 /* NOTREACHED */
2910 argc -= optind;
2911 argv += optind;
2913 #ifndef PROFILE
2914 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2915 "unveil", NULL) == -1)
2916 err(1, "pledge");
2917 #endif
2918 if (argc == 1) {
2919 char *base, *dotgit;
2920 const char *path;
2921 repo_path = realpath(argv[0], NULL);
2922 if (repo_path == NULL)
2923 return got_error_from_errno2("realpath", argv[0]);
2924 cwd = getcwd(NULL, 0);
2925 if (cwd == NULL) {
2926 error = got_error_from_errno("getcwd");
2927 goto done;
2929 if (path_prefix[0])
2930 path = path_prefix;
2931 else
2932 path = repo_path;
2933 error = got_path_basename(&base, path);
2934 if (error)
2935 goto done;
2936 dotgit = strstr(base, ".git");
2937 if (dotgit)
2938 *dotgit = '\0';
2939 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2940 error = got_error_from_errno("asprintf");
2941 free(base);
2942 goto done;
2944 free(base);
2945 } else if (argc == 2) {
2946 repo_path = realpath(argv[0], NULL);
2947 if (repo_path == NULL) {
2948 error = got_error_from_errno2("realpath", argv[0]);
2949 goto done;
2951 worktree_path = realpath(argv[1], NULL);
2952 if (worktree_path == NULL) {
2953 if (errno != ENOENT) {
2954 error = got_error_from_errno2("realpath",
2955 argv[1]);
2956 goto done;
2958 worktree_path = strdup(argv[1]);
2959 if (worktree_path == NULL) {
2960 error = got_error_from_errno("strdup");
2961 goto done;
2964 } else
2965 usage_checkout();
2967 got_path_strip_trailing_slashes(repo_path);
2968 got_path_strip_trailing_slashes(worktree_path);
2970 error = got_repo_pack_fds_open(&pack_fds);
2971 if (error != NULL)
2972 goto done;
2974 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2975 if (error != NULL)
2976 goto done;
2978 /* Pre-create work tree path for unveil(2) */
2979 error = got_path_mkdir(worktree_path);
2980 if (error) {
2981 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2982 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2983 goto done;
2984 if (!allow_nonempty &&
2985 !got_path_dir_is_empty(worktree_path)) {
2986 error = got_error_path(worktree_path,
2987 GOT_ERR_DIR_NOT_EMPTY);
2988 goto done;
2992 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2993 if (error)
2994 goto done;
2996 error = got_ref_open(&head_ref, repo, branch_name, 0);
2997 if (error != NULL)
2998 goto done;
3000 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3001 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3002 goto done;
3004 error = got_worktree_open(&worktree, worktree_path);
3005 if (error != NULL)
3006 goto done;
3008 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3009 path_prefix);
3010 if (error != NULL)
3011 goto done;
3012 if (!same_path_prefix) {
3013 error = got_error(GOT_ERR_PATH_PREFIX);
3014 goto done;
3017 if (commit_id_str) {
3018 struct got_reflist_head refs;
3019 TAILQ_INIT(&refs);
3020 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3021 NULL);
3022 if (error)
3023 goto done;
3024 error = got_repo_match_object_id(&commit_id, NULL,
3025 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3026 got_ref_list_free(&refs);
3027 if (error)
3028 goto done;
3029 error = check_linear_ancestry(commit_id,
3030 got_worktree_get_base_commit_id(worktree), 0, repo);
3031 if (error != NULL) {
3032 if (error->code == GOT_ERR_ANCESTRY) {
3033 error = checkout_ancestry_error(
3034 head_ref, commit_id_str);
3036 goto done;
3038 error = check_same_branch(commit_id, head_ref, NULL, repo);
3039 if (error) {
3040 if (error->code == GOT_ERR_ANCESTRY) {
3041 error = checkout_ancestry_error(
3042 head_ref, commit_id_str);
3044 goto done;
3046 error = got_worktree_set_base_commit_id(worktree, repo,
3047 commit_id);
3048 if (error)
3049 goto done;
3050 /* Expand potentially abbreviated commit ID string. */
3051 free(commit_id_str);
3052 error = got_object_id_str(&commit_id_str, commit_id);
3053 if (error)
3054 goto done;
3055 } else {
3056 commit_id = got_object_id_dup(
3057 got_worktree_get_base_commit_id(worktree));
3058 if (commit_id == NULL) {
3059 error = got_error_from_errno("got_object_id_dup");
3060 goto done;
3062 error = got_object_id_str(&commit_id_str, commit_id);
3063 if (error)
3064 goto done;
3067 error = got_pathlist_append(&paths, "", NULL);
3068 if (error)
3069 goto done;
3070 cpa.worktree_path = worktree_path;
3071 cpa.had_base_commit_ref_error = 0;
3072 cpa.verbosity = verbosity;
3073 error = got_worktree_checkout_files(worktree, &paths, repo,
3074 checkout_progress, &cpa, check_cancelled, NULL);
3075 if (error != NULL)
3076 goto done;
3078 if (got_ref_is_symbolic(head_ref)) {
3079 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3080 if (error)
3081 goto done;
3082 refname = got_ref_get_name(ref);
3083 } else
3084 refname = got_ref_get_name(head_ref);
3085 printf("Checked out %s: %s\n", refname, commit_id_str);
3086 printf("Now shut up and hack\n");
3087 if (cpa.had_base_commit_ref_error)
3088 show_worktree_base_ref_warning();
3089 done:
3090 if (pack_fds) {
3091 const struct got_error *pack_err =
3092 got_repo_pack_fds_close(pack_fds);
3093 if (error == NULL)
3094 error = pack_err;
3096 if (head_ref)
3097 got_ref_close(head_ref);
3098 if (ref)
3099 got_ref_close(ref);
3100 got_pathlist_free(&paths);
3101 free(commit_id_str);
3102 free(commit_id);
3103 free(repo_path);
3104 free(worktree_path);
3105 free(cwd);
3106 return error;
3109 struct got_update_progress_arg {
3110 int did_something;
3111 int conflicts;
3112 int obstructed;
3113 int not_updated;
3114 int missing;
3115 int not_deleted;
3116 int unversioned;
3117 int verbosity;
3120 static void
3121 print_update_progress_stats(struct got_update_progress_arg *upa)
3123 if (!upa->did_something)
3124 return;
3126 if (upa->conflicts > 0)
3127 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3128 if (upa->obstructed > 0)
3129 printf("File paths obstructed by a non-regular file: %d\n",
3130 upa->obstructed);
3131 if (upa->not_updated > 0)
3132 printf("Files not updated because of existing merge "
3133 "conflicts: %d\n", upa->not_updated);
3137 * The meaning of some status codes differs between merge-style operations and
3138 * update operations. For example, the ! status code means "file was missing"
3139 * if changes were merged into the work tree, and "missing file was restored"
3140 * if the work tree was updated. This function should be used by any operation
3141 * which merges changes into the work tree without updating the work tree.
3143 static void
3144 print_merge_progress_stats(struct got_update_progress_arg *upa)
3146 if (!upa->did_something)
3147 return;
3149 if (upa->conflicts > 0)
3150 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3151 if (upa->obstructed > 0)
3152 printf("File paths obstructed by a non-regular file: %d\n",
3153 upa->obstructed);
3154 if (upa->missing > 0)
3155 printf("Files which had incoming changes but could not be "
3156 "found in the work tree: %d\n", upa->missing);
3157 if (upa->not_deleted > 0)
3158 printf("Files not deleted due to differences in deleted "
3159 "content: %d\n", upa->not_deleted);
3160 if (upa->unversioned > 0)
3161 printf("Files not merged because an unversioned file was "
3162 "found in the work tree: %d\n", upa->unversioned);
3165 __dead static void
3166 usage_update(void)
3168 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3169 "[path ...]\n",
3170 getprogname());
3171 exit(1);
3174 static const struct got_error *
3175 update_progress(void *arg, unsigned char status, const char *path)
3177 struct got_update_progress_arg *upa = arg;
3179 if (status == GOT_STATUS_EXISTS ||
3180 status == GOT_STATUS_BASE_REF_ERR)
3181 return NULL;
3183 upa->did_something = 1;
3185 /* Base commit bump happens silently. */
3186 if (status == GOT_STATUS_BUMP_BASE)
3187 return NULL;
3189 if (status == GOT_STATUS_CONFLICT)
3190 upa->conflicts++;
3191 if (status == GOT_STATUS_OBSTRUCTED)
3192 upa->obstructed++;
3193 if (status == GOT_STATUS_CANNOT_UPDATE)
3194 upa->not_updated++;
3195 if (status == GOT_STATUS_MISSING)
3196 upa->missing++;
3197 if (status == GOT_STATUS_CANNOT_DELETE)
3198 upa->not_deleted++;
3199 if (status == GOT_STATUS_UNVERSIONED)
3200 upa->unversioned++;
3202 while (path[0] == '/')
3203 path++;
3204 if (upa->verbosity >= 0)
3205 printf("%c %s\n", status, path);
3207 return NULL;
3210 static const struct got_error *
3211 switch_head_ref(struct got_reference *head_ref,
3212 struct got_object_id *commit_id, struct got_worktree *worktree,
3213 struct got_repository *repo)
3215 const struct got_error *err = NULL;
3216 char *base_id_str;
3217 int ref_has_moved = 0;
3219 /* Trivial case: switching between two different references. */
3220 if (strcmp(got_ref_get_name(head_ref),
3221 got_worktree_get_head_ref_name(worktree)) != 0) {
3222 printf("Switching work tree from %s to %s\n",
3223 got_worktree_get_head_ref_name(worktree),
3224 got_ref_get_name(head_ref));
3225 return got_worktree_set_head_ref(worktree, head_ref);
3228 err = check_linear_ancestry(commit_id,
3229 got_worktree_get_base_commit_id(worktree), 0, repo);
3230 if (err) {
3231 if (err->code != GOT_ERR_ANCESTRY)
3232 return err;
3233 ref_has_moved = 1;
3235 if (!ref_has_moved)
3236 return NULL;
3238 /* Switching to a rebased branch with the same reference name. */
3239 err = got_object_id_str(&base_id_str,
3240 got_worktree_get_base_commit_id(worktree));
3241 if (err)
3242 return err;
3243 printf("Reference %s now points at a different branch\n",
3244 got_worktree_get_head_ref_name(worktree));
3245 printf("Switching work tree from %s to %s\n", base_id_str,
3246 got_worktree_get_head_ref_name(worktree));
3247 return NULL;
3250 static const struct got_error *
3251 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3253 const struct got_error *err;
3254 int in_progress;
3256 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3257 if (err)
3258 return err;
3259 if (in_progress)
3260 return got_error(GOT_ERR_REBASING);
3262 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3263 if (err)
3264 return err;
3265 if (in_progress)
3266 return got_error(GOT_ERR_HISTEDIT_BUSY);
3268 return NULL;
3271 static const struct got_error *
3272 check_merge_in_progress(struct got_worktree *worktree,
3273 struct got_repository *repo)
3275 const struct got_error *err;
3276 int in_progress;
3278 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3279 if (err)
3280 return err;
3281 if (in_progress)
3282 return got_error(GOT_ERR_MERGE_BUSY);
3284 return NULL;
3287 static const struct got_error *
3288 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3289 char *argv[], struct got_worktree *worktree)
3291 const struct got_error *err = NULL;
3292 char *path;
3293 struct got_pathlist_entry *new;
3294 int i;
3296 if (argc == 0) {
3297 path = strdup("");
3298 if (path == NULL)
3299 return got_error_from_errno("strdup");
3300 return got_pathlist_append(paths, path, NULL);
3303 for (i = 0; i < argc; i++) {
3304 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3305 if (err)
3306 break;
3307 err = got_pathlist_insert(&new, paths, path, NULL);
3308 if (err || new == NULL /* duplicate */) {
3309 free(path);
3310 if (err)
3311 break;
3315 return err;
3318 static const struct got_error *
3319 wrap_not_worktree_error(const struct got_error *orig_err,
3320 const char *cmdname, const char *path)
3322 const struct got_error *err;
3323 struct got_repository *repo;
3324 static char msg[512];
3325 int *pack_fds = NULL;
3327 err = got_repo_pack_fds_open(&pack_fds);
3328 if (err)
3329 return err;
3331 err = got_repo_open(&repo, path, NULL, pack_fds);
3332 if (err)
3333 return orig_err;
3335 snprintf(msg, sizeof(msg),
3336 "'got %s' needs a work tree in addition to a git repository\n"
3337 "Work trees can be checked out from this Git repository with "
3338 "'got checkout'.\n"
3339 "The got(1) manual page contains more information.", cmdname);
3340 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3341 got_repo_close(repo);
3342 if (pack_fds) {
3343 const struct got_error *pack_err =
3344 got_repo_pack_fds_close(pack_fds);
3345 if (err == NULL)
3346 err = pack_err;
3348 return err;
3351 static const struct got_error *
3352 cmd_update(int argc, char *argv[])
3354 const struct got_error *error = NULL;
3355 struct got_repository *repo = NULL;
3356 struct got_worktree *worktree = NULL;
3357 char *worktree_path = NULL;
3358 struct got_object_id *commit_id = NULL;
3359 char *commit_id_str = NULL;
3360 const char *branch_name = NULL;
3361 struct got_reference *head_ref = NULL;
3362 struct got_pathlist_head paths;
3363 struct got_pathlist_entry *pe;
3364 int ch, verbosity = 0;
3365 struct got_update_progress_arg upa;
3366 int *pack_fds = NULL;
3368 TAILQ_INIT(&paths);
3370 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3371 switch (ch) {
3372 case 'b':
3373 branch_name = optarg;
3374 break;
3375 case 'c':
3376 commit_id_str = strdup(optarg);
3377 if (commit_id_str == NULL)
3378 return got_error_from_errno("strdup");
3379 break;
3380 case 'q':
3381 verbosity = -1;
3382 break;
3383 default:
3384 usage_update();
3385 /* NOTREACHED */
3389 argc -= optind;
3390 argv += optind;
3392 #ifndef PROFILE
3393 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3394 "unveil", NULL) == -1)
3395 err(1, "pledge");
3396 #endif
3397 worktree_path = getcwd(NULL, 0);
3398 if (worktree_path == NULL) {
3399 error = got_error_from_errno("getcwd");
3400 goto done;
3403 error = got_repo_pack_fds_open(&pack_fds);
3404 if (error != NULL)
3405 goto done;
3407 error = got_worktree_open(&worktree, worktree_path);
3408 if (error) {
3409 if (error->code == GOT_ERR_NOT_WORKTREE)
3410 error = wrap_not_worktree_error(error, "update",
3411 worktree_path);
3412 goto done;
3415 error = check_rebase_or_histedit_in_progress(worktree);
3416 if (error)
3417 goto done;
3419 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3420 NULL, pack_fds);
3421 if (error != NULL)
3422 goto done;
3424 error = apply_unveil(got_repo_get_path(repo), 0,
3425 got_worktree_get_root_path(worktree));
3426 if (error)
3427 goto done;
3429 error = check_merge_in_progress(worktree, repo);
3430 if (error)
3431 goto done;
3433 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3434 if (error)
3435 goto done;
3437 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3438 got_worktree_get_head_ref_name(worktree), 0);
3439 if (error != NULL)
3440 goto done;
3441 if (commit_id_str == NULL) {
3442 error = got_ref_resolve(&commit_id, repo, head_ref);
3443 if (error != NULL)
3444 goto done;
3445 error = got_object_id_str(&commit_id_str, commit_id);
3446 if (error != NULL)
3447 goto done;
3448 } else {
3449 struct got_reflist_head refs;
3450 TAILQ_INIT(&refs);
3451 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3452 NULL);
3453 if (error)
3454 goto done;
3455 error = got_repo_match_object_id(&commit_id, NULL,
3456 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3457 got_ref_list_free(&refs);
3458 free(commit_id_str);
3459 commit_id_str = NULL;
3460 if (error)
3461 goto done;
3462 error = got_object_id_str(&commit_id_str, commit_id);
3463 if (error)
3464 goto done;
3467 if (branch_name) {
3468 struct got_object_id *head_commit_id;
3469 TAILQ_FOREACH(pe, &paths, entry) {
3470 if (pe->path_len == 0)
3471 continue;
3472 error = got_error_msg(GOT_ERR_BAD_PATH,
3473 "switching between branches requires that "
3474 "the entire work tree gets updated");
3475 goto done;
3477 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3478 if (error)
3479 goto done;
3480 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3481 repo);
3482 free(head_commit_id);
3483 if (error != NULL)
3484 goto done;
3485 error = check_same_branch(commit_id, head_ref, NULL, repo);
3486 if (error)
3487 goto done;
3488 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3489 if (error)
3490 goto done;
3491 } else {
3492 error = check_linear_ancestry(commit_id,
3493 got_worktree_get_base_commit_id(worktree), 0, repo);
3494 if (error != NULL) {
3495 if (error->code == GOT_ERR_ANCESTRY)
3496 error = got_error(GOT_ERR_BRANCH_MOVED);
3497 goto done;
3499 error = check_same_branch(commit_id, head_ref, NULL, repo);
3500 if (error)
3501 goto done;
3504 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3505 commit_id) != 0) {
3506 error = got_worktree_set_base_commit_id(worktree, repo,
3507 commit_id);
3508 if (error)
3509 goto done;
3512 memset(&upa, 0, sizeof(upa));
3513 upa.verbosity = verbosity;
3514 error = got_worktree_checkout_files(worktree, &paths, repo,
3515 update_progress, &upa, check_cancelled, NULL);
3516 if (error != NULL)
3517 goto done;
3519 if (upa.did_something) {
3520 printf("Updated to %s: %s\n",
3521 got_worktree_get_head_ref_name(worktree), commit_id_str);
3522 } else
3523 printf("Already up-to-date\n");
3525 print_update_progress_stats(&upa);
3526 done:
3527 if (pack_fds) {
3528 const struct got_error *pack_err =
3529 got_repo_pack_fds_close(pack_fds);
3530 if (error == NULL)
3531 error = pack_err;
3533 free(worktree_path);
3534 TAILQ_FOREACH(pe, &paths, entry)
3535 free((char *)pe->path);
3536 got_pathlist_free(&paths);
3537 free(commit_id);
3538 free(commit_id_str);
3539 return error;
3542 static const struct got_error *
3543 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3544 const char *path, int diff_context, int ignore_whitespace,
3545 int force_text_diff, struct got_repository *repo, FILE *outfile)
3547 const struct got_error *err = NULL;
3548 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3549 FILE *f1 = NULL, *f2 = NULL;
3551 if (blob_id1) {
3552 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3553 if (err)
3554 goto done;
3555 f1 = got_opentemp();
3556 if (f1 == NULL) {
3557 err = got_error_from_errno("got_opentemp");
3558 goto done;
3562 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3563 if (err)
3564 goto done;
3566 f2 = got_opentemp();
3567 if (f2 == NULL) {
3568 err = got_error_from_errno("got_opentemp");
3569 goto done;
3572 while (path[0] == '/')
3573 path++;
3574 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3575 diff_context, ignore_whitespace, force_text_diff, outfile);
3576 done:
3577 if (blob1)
3578 got_object_blob_close(blob1);
3579 got_object_blob_close(blob2);
3580 if (f1 && fclose(f1) == EOF && err == NULL)
3581 err = got_error_from_errno("fclose");
3582 if (f2 && fclose(f2) == EOF && err == NULL)
3583 err = got_error_from_errno("fclose");
3584 return err;
3587 static const struct got_error *
3588 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3589 const char *path, int diff_context, int ignore_whitespace,
3590 int force_text_diff, struct got_repository *repo, FILE *outfile)
3592 const struct got_error *err = NULL;
3593 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3594 struct got_diff_blob_output_unidiff_arg arg;
3595 FILE *f1 = NULL, *f2 = NULL;
3597 if (tree_id1) {
3598 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3599 if (err)
3600 goto done;
3601 f1 = got_opentemp();
3602 if (f1 == NULL) {
3603 err = got_error_from_errno("got_opentemp");
3604 goto done;
3608 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3609 if (err)
3610 goto done;
3612 f2 = got_opentemp();
3613 if (f2 == NULL) {
3614 err = got_error_from_errno("got_opentemp");
3615 goto done;
3618 arg.diff_context = diff_context;
3619 arg.ignore_whitespace = ignore_whitespace;
3620 arg.force_text_diff = force_text_diff;
3621 arg.outfile = outfile;
3622 arg.line_offsets = NULL;
3623 arg.nlines = 0;
3624 while (path[0] == '/')
3625 path++;
3626 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3627 got_diff_blob_output_unidiff, &arg, 1);
3628 done:
3629 if (tree1)
3630 got_object_tree_close(tree1);
3631 if (tree2)
3632 got_object_tree_close(tree2);
3633 if (f1 && fclose(f1) == EOF && err == NULL)
3634 err = got_error_from_errno("fclose");
3635 if (f2 && fclose(f2) == EOF && err == NULL)
3636 err = got_error_from_errno("fclose");
3637 return err;
3640 static const struct got_error *
3641 get_changed_paths(struct got_pathlist_head *paths,
3642 struct got_commit_object *commit, struct got_repository *repo)
3644 const struct got_error *err = NULL;
3645 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3646 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3647 struct got_object_qid *qid;
3649 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3650 if (qid != NULL) {
3651 struct got_commit_object *pcommit;
3652 err = got_object_open_as_commit(&pcommit, repo,
3653 &qid->id);
3654 if (err)
3655 return err;
3657 tree_id1 = got_object_id_dup(
3658 got_object_commit_get_tree_id(pcommit));
3659 if (tree_id1 == NULL) {
3660 got_object_commit_close(pcommit);
3661 return got_error_from_errno("got_object_id_dup");
3663 got_object_commit_close(pcommit);
3667 if (tree_id1) {
3668 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3669 if (err)
3670 goto done;
3673 tree_id2 = got_object_commit_get_tree_id(commit);
3674 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3675 if (err)
3676 goto done;
3678 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3679 got_diff_tree_collect_changed_paths, paths, 0);
3680 done:
3681 if (tree1)
3682 got_object_tree_close(tree1);
3683 if (tree2)
3684 got_object_tree_close(tree2);
3685 free(tree_id1);
3686 return err;
3689 static const struct got_error *
3690 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3691 const char *path, int diff_context, struct got_repository *repo,
3692 FILE *outfile)
3694 const struct got_error *err = NULL;
3695 struct got_commit_object *pcommit = NULL;
3696 char *id_str1 = NULL, *id_str2 = NULL;
3697 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3698 struct got_object_qid *qid;
3700 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3701 if (qid != NULL) {
3702 err = got_object_open_as_commit(&pcommit, repo,
3703 &qid->id);
3704 if (err)
3705 return err;
3706 err = got_object_id_str(&id_str1, &qid->id);
3707 if (err)
3708 goto done;
3711 err = got_object_id_str(&id_str2, id);
3712 if (err)
3713 goto done;
3715 if (path && path[0] != '\0') {
3716 int obj_type;
3717 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3718 if (err)
3719 goto done;
3720 if (pcommit) {
3721 err = got_object_id_by_path(&obj_id1, repo,
3722 pcommit, path);
3723 if (err) {
3724 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3725 free(obj_id2);
3726 goto done;
3730 err = got_object_get_type(&obj_type, repo, obj_id2);
3731 if (err) {
3732 free(obj_id2);
3733 goto done;
3735 fprintf(outfile,
3736 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3737 fprintf(outfile, "commit - %s\n",
3738 id_str1 ? id_str1 : "/dev/null");
3739 fprintf(outfile, "commit + %s\n", id_str2);
3740 switch (obj_type) {
3741 case GOT_OBJ_TYPE_BLOB:
3742 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3743 0, 0, repo, outfile);
3744 break;
3745 case GOT_OBJ_TYPE_TREE:
3746 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3747 0, 0, repo, outfile);
3748 break;
3749 default:
3750 err = got_error(GOT_ERR_OBJ_TYPE);
3751 break;
3753 free(obj_id1);
3754 free(obj_id2);
3755 } else {
3756 obj_id2 = got_object_commit_get_tree_id(commit);
3757 if (pcommit)
3758 obj_id1 = got_object_commit_get_tree_id(pcommit);
3759 fprintf(outfile,
3760 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3761 fprintf(outfile, "commit - %s\n",
3762 id_str1 ? id_str1 : "/dev/null");
3763 fprintf(outfile, "commit + %s\n", id_str2);
3764 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3765 repo, outfile);
3767 done:
3768 free(id_str1);
3769 free(id_str2);
3770 if (pcommit)
3771 got_object_commit_close(pcommit);
3772 return err;
3775 static char *
3776 get_datestr(time_t *time, char *datebuf)
3778 struct tm mytm, *tm;
3779 char *p, *s;
3781 tm = gmtime_r(time, &mytm);
3782 if (tm == NULL)
3783 return NULL;
3784 s = asctime_r(tm, datebuf);
3785 if (s == NULL)
3786 return NULL;
3787 p = strchr(s, '\n');
3788 if (p)
3789 *p = '\0';
3790 return s;
3793 static const struct got_error *
3794 match_commit(int *have_match, struct got_object_id *id,
3795 struct got_commit_object *commit, regex_t *regex)
3797 const struct got_error *err = NULL;
3798 regmatch_t regmatch;
3799 char *id_str = NULL, *logmsg = NULL;
3801 *have_match = 0;
3803 err = got_object_id_str(&id_str, id);
3804 if (err)
3805 return err;
3807 err = got_object_commit_get_logmsg(&logmsg, commit);
3808 if (err)
3809 goto done;
3811 if (regexec(regex, got_object_commit_get_author(commit), 1,
3812 &regmatch, 0) == 0 ||
3813 regexec(regex, got_object_commit_get_committer(commit), 1,
3814 &regmatch, 0) == 0 ||
3815 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3816 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3817 *have_match = 1;
3818 done:
3819 free(id_str);
3820 free(logmsg);
3821 return err;
3824 static void
3825 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3826 regex_t *regex)
3828 regmatch_t regmatch;
3829 struct got_pathlist_entry *pe;
3831 *have_match = 0;
3833 TAILQ_FOREACH(pe, changed_paths, entry) {
3834 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3835 *have_match = 1;
3836 break;
3841 static const struct got_error *
3842 match_patch(int *have_match, struct got_commit_object *commit,
3843 struct got_object_id *id, const char *path, int diff_context,
3844 struct got_repository *repo, regex_t *regex, FILE *f)
3846 const struct got_error *err = NULL;
3847 char *line = NULL;
3848 size_t linesize = 0;
3849 ssize_t linelen;
3850 regmatch_t regmatch;
3852 *have_match = 0;
3854 err = got_opentemp_truncate(f);
3855 if (err)
3856 return err;
3858 err = print_patch(commit, id, path, diff_context, repo, f);
3859 if (err)
3860 goto done;
3862 if (fseeko(f, 0L, SEEK_SET) == -1) {
3863 err = got_error_from_errno("fseeko");
3864 goto done;
3867 while ((linelen = getline(&line, &linesize, f)) != -1) {
3868 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3869 *have_match = 1;
3870 break;
3873 done:
3874 free(line);
3875 return err;
3878 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3880 static const struct got_error*
3881 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3882 struct got_object_id *id, struct got_repository *repo,
3883 int local_only)
3885 static const struct got_error *err = NULL;
3886 struct got_reflist_entry *re;
3887 char *s;
3888 const char *name;
3890 *refs_str = NULL;
3892 TAILQ_FOREACH(re, refs, entry) {
3893 struct got_tag_object *tag = NULL;
3894 struct got_object_id *ref_id;
3895 int cmp;
3897 name = got_ref_get_name(re->ref);
3898 if (strcmp(name, GOT_REF_HEAD) == 0)
3899 continue;
3900 if (strncmp(name, "refs/", 5) == 0)
3901 name += 5;
3902 if (strncmp(name, "got/", 4) == 0)
3903 continue;
3904 if (strncmp(name, "heads/", 6) == 0)
3905 name += 6;
3906 if (strncmp(name, "remotes/", 8) == 0) {
3907 if (local_only)
3908 continue;
3909 name += 8;
3910 s = strstr(name, "/" GOT_REF_HEAD);
3911 if (s != NULL && s[strlen(s)] == '\0')
3912 continue;
3914 err = got_ref_resolve(&ref_id, repo, re->ref);
3915 if (err)
3916 break;
3917 if (strncmp(name, "tags/", 5) == 0) {
3918 err = got_object_open_as_tag(&tag, repo, ref_id);
3919 if (err) {
3920 if (err->code != GOT_ERR_OBJ_TYPE) {
3921 free(ref_id);
3922 break;
3924 /* Ref points at something other than a tag. */
3925 err = NULL;
3926 tag = NULL;
3929 cmp = got_object_id_cmp(tag ?
3930 got_object_tag_get_object_id(tag) : ref_id, id);
3931 free(ref_id);
3932 if (tag)
3933 got_object_tag_close(tag);
3934 if (cmp != 0)
3935 continue;
3936 s = *refs_str;
3937 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3938 s ? ", " : "", name) == -1) {
3939 err = got_error_from_errno("asprintf");
3940 free(s);
3941 *refs_str = NULL;
3942 break;
3944 free(s);
3947 return err;
3950 static const struct got_error *
3951 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3952 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3954 const struct got_error *err = NULL;
3955 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3956 char *comma, *s, *nl;
3957 struct got_reflist_head *refs;
3958 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3959 struct tm tm;
3960 time_t committer_time;
3962 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3963 if (refs) {
3964 err = build_refs_str(&ref_str, refs, id, repo, 1);
3965 if (err)
3966 return err;
3968 /* Display the first matching ref only. */
3969 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3970 *comma = '\0';
3973 if (ref_str == NULL) {
3974 err = got_object_id_str(&id_str, id);
3975 if (err)
3976 return err;
3979 committer_time = got_object_commit_get_committer_time(commit);
3980 if (gmtime_r(&committer_time, &tm) == NULL) {
3981 err = got_error_from_errno("gmtime_r");
3982 goto done;
3984 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3985 err = got_error(GOT_ERR_NO_SPACE);
3986 goto done;
3989 err = got_object_commit_get_logmsg(&logmsg0, commit);
3990 if (err)
3991 goto done;
3993 s = logmsg0;
3994 while (isspace((unsigned char)s[0]))
3995 s++;
3997 nl = strchr(s, '\n');
3998 if (nl) {
3999 *nl = '\0';
4002 if (ref_str)
4003 printf("%s%-7s %s\n", datebuf, ref_str, s);
4004 else
4005 printf("%s%.7s %s\n", datebuf, id_str, s);
4007 if (fflush(stdout) != 0 && err == NULL)
4008 err = got_error_from_errno("fflush");
4009 done:
4010 free(id_str);
4011 free(ref_str);
4012 free(logmsg0);
4013 return err;
4016 static const struct got_error *
4017 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4018 struct got_repository *repo, const char *path,
4019 struct got_pathlist_head *changed_paths, int show_patch,
4020 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4021 const char *custom_refs_str)
4023 const struct got_error *err = NULL;
4024 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4025 char datebuf[26];
4026 time_t committer_time;
4027 const char *author, *committer;
4028 char *refs_str = NULL;
4030 err = got_object_id_str(&id_str, id);
4031 if (err)
4032 return err;
4034 if (custom_refs_str == NULL) {
4035 struct got_reflist_head *refs;
4036 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4037 if (refs) {
4038 err = build_refs_str(&refs_str, refs, id, repo, 0);
4039 if (err)
4040 goto done;
4044 printf(GOT_COMMIT_SEP_STR);
4045 if (custom_refs_str)
4046 printf("commit %s (%s)\n", id_str, custom_refs_str);
4047 else
4048 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4049 refs_str ? refs_str : "", refs_str ? ")" : "");
4050 free(id_str);
4051 id_str = NULL;
4052 free(refs_str);
4053 refs_str = NULL;
4054 printf("from: %s\n", got_object_commit_get_author(commit));
4055 committer_time = got_object_commit_get_committer_time(commit);
4056 datestr = get_datestr(&committer_time, datebuf);
4057 if (datestr)
4058 printf("date: %s UTC\n", datestr);
4059 author = got_object_commit_get_author(commit);
4060 committer = got_object_commit_get_committer(commit);
4061 if (strcmp(author, committer) != 0)
4062 printf("via: %s\n", committer);
4063 if (got_object_commit_get_nparents(commit) > 1) {
4064 const struct got_object_id_queue *parent_ids;
4065 struct got_object_qid *qid;
4066 int n = 1;
4067 parent_ids = got_object_commit_get_parent_ids(commit);
4068 STAILQ_FOREACH(qid, parent_ids, entry) {
4069 err = got_object_id_str(&id_str, &qid->id);
4070 if (err)
4071 goto done;
4072 printf("parent %d: %s\n", n++, id_str);
4073 free(id_str);
4074 id_str = NULL;
4078 err = got_object_commit_get_logmsg(&logmsg0, commit);
4079 if (err)
4080 goto done;
4082 logmsg = logmsg0;
4083 do {
4084 line = strsep(&logmsg, "\n");
4085 if (line)
4086 printf(" %s\n", line);
4087 } while (line);
4088 free(logmsg0);
4090 if (changed_paths) {
4091 struct got_pathlist_entry *pe;
4092 TAILQ_FOREACH(pe, changed_paths, entry) {
4093 struct got_diff_changed_path *cp = pe->data;
4094 printf(" %c %s\n", cp->status, pe->path);
4096 printf("\n");
4098 if (show_patch) {
4099 err = print_patch(commit, id, path, diff_context, repo, stdout);
4100 if (err == 0)
4101 printf("\n");
4104 if (fflush(stdout) != 0 && err == NULL)
4105 err = got_error_from_errno("fflush");
4106 done:
4107 free(id_str);
4108 free(refs_str);
4109 return err;
4112 static const struct got_error *
4113 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4114 struct got_repository *repo, const char *path, int show_changed_paths,
4115 int show_patch, const char *search_pattern, int diff_context, int limit,
4116 int log_branches, int reverse_display_order,
4117 struct got_reflist_object_id_map *refs_idmap, int one_line,
4118 FILE *tmpfile)
4120 const struct got_error *err;
4121 struct got_commit_graph *graph;
4122 regex_t regex;
4123 int have_match;
4124 struct got_object_id_queue reversed_commits;
4125 struct got_object_qid *qid;
4126 struct got_commit_object *commit;
4127 struct got_pathlist_head changed_paths;
4128 struct got_pathlist_entry *pe;
4130 STAILQ_INIT(&reversed_commits);
4131 TAILQ_INIT(&changed_paths);
4133 if (search_pattern && regcomp(&regex, search_pattern,
4134 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4135 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4137 err = got_commit_graph_open(&graph, path, !log_branches);
4138 if (err)
4139 return err;
4140 err = got_commit_graph_iter_start(graph, root_id, repo,
4141 check_cancelled, NULL);
4142 if (err)
4143 goto done;
4144 for (;;) {
4145 struct got_object_id *id;
4147 if (sigint_received || sigpipe_received)
4148 break;
4150 err = got_commit_graph_iter_next(&id, graph, repo,
4151 check_cancelled, NULL);
4152 if (err) {
4153 if (err->code == GOT_ERR_ITER_COMPLETED)
4154 err = NULL;
4155 break;
4157 if (id == NULL)
4158 break;
4160 err = got_object_open_as_commit(&commit, repo, id);
4161 if (err)
4162 break;
4164 if (show_changed_paths && !reverse_display_order) {
4165 err = get_changed_paths(&changed_paths, commit, repo);
4166 if (err)
4167 break;
4170 if (search_pattern) {
4171 err = match_commit(&have_match, id, commit, &regex);
4172 if (err) {
4173 got_object_commit_close(commit);
4174 break;
4176 if (have_match == 0 && show_changed_paths)
4177 match_changed_paths(&have_match,
4178 &changed_paths, &regex);
4179 if (have_match == 0 && show_patch) {
4180 err = match_patch(&have_match, commit, id,
4181 path, diff_context, repo, &regex,
4182 tmpfile);
4183 if (err)
4184 break;
4186 if (have_match == 0) {
4187 got_object_commit_close(commit);
4188 TAILQ_FOREACH(pe, &changed_paths, entry) {
4189 free((char *)pe->path);
4190 free(pe->data);
4192 got_pathlist_free(&changed_paths);
4193 continue;
4197 if (reverse_display_order) {
4198 err = got_object_qid_alloc(&qid, id);
4199 if (err)
4200 break;
4201 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4202 got_object_commit_close(commit);
4203 } else {
4204 if (one_line)
4205 err = print_commit_oneline(commit, id,
4206 repo, refs_idmap);
4207 else
4208 err = print_commit(commit, id, repo, path,
4209 show_changed_paths ? &changed_paths : NULL,
4210 show_patch, diff_context, refs_idmap, NULL);
4211 got_object_commit_close(commit);
4212 if (err)
4213 break;
4215 if ((limit && --limit == 0) ||
4216 (end_id && got_object_id_cmp(id, end_id) == 0))
4217 break;
4219 TAILQ_FOREACH(pe, &changed_paths, entry) {
4220 free((char *)pe->path);
4221 free(pe->data);
4223 got_pathlist_free(&changed_paths);
4225 if (reverse_display_order) {
4226 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4227 err = got_object_open_as_commit(&commit, repo,
4228 &qid->id);
4229 if (err)
4230 break;
4231 if (show_changed_paths) {
4232 err = get_changed_paths(&changed_paths,
4233 commit, repo);
4234 if (err)
4235 break;
4237 if (one_line)
4238 err = print_commit_oneline(commit, &qid->id,
4239 repo, refs_idmap);
4240 else
4241 err = print_commit(commit, &qid->id, repo, path,
4242 show_changed_paths ? &changed_paths : NULL,
4243 show_patch, diff_context, refs_idmap, NULL);
4244 got_object_commit_close(commit);
4245 if (err)
4246 break;
4247 TAILQ_FOREACH(pe, &changed_paths, entry) {
4248 free((char *)pe->path);
4249 free(pe->data);
4251 got_pathlist_free(&changed_paths);
4254 done:
4255 while (!STAILQ_EMPTY(&reversed_commits)) {
4256 qid = STAILQ_FIRST(&reversed_commits);
4257 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4258 got_object_qid_free(qid);
4260 TAILQ_FOREACH(pe, &changed_paths, entry) {
4261 free((char *)pe->path);
4262 free(pe->data);
4264 got_pathlist_free(&changed_paths);
4265 if (search_pattern)
4266 regfree(&regex);
4267 got_commit_graph_close(graph);
4268 return err;
4271 __dead static void
4272 usage_log(void)
4274 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4275 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4276 "[-r repository-path] [-R] [path]\n", getprogname());
4277 exit(1);
4280 static int
4281 get_default_log_limit(void)
4283 const char *got_default_log_limit;
4284 long long n;
4285 const char *errstr;
4287 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4288 if (got_default_log_limit == NULL)
4289 return 0;
4290 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4291 if (errstr != NULL)
4292 return 0;
4293 return n;
4296 static const struct got_error *
4297 cmd_log(int argc, char *argv[])
4299 const struct got_error *error;
4300 struct got_repository *repo = NULL;
4301 struct got_worktree *worktree = NULL;
4302 struct got_object_id *start_id = NULL, *end_id = NULL;
4303 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4304 const char *start_commit = NULL, *end_commit = NULL;
4305 const char *search_pattern = NULL;
4306 int diff_context = -1, ch;
4307 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4308 int reverse_display_order = 0, one_line = 0;
4309 const char *errstr;
4310 struct got_reflist_head refs;
4311 struct got_reflist_object_id_map *refs_idmap = NULL;
4312 FILE *tmpfile = NULL;
4313 int *pack_fds = NULL;
4315 TAILQ_INIT(&refs);
4317 #ifndef PROFILE
4318 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4319 NULL)
4320 == -1)
4321 err(1, "pledge");
4322 #endif
4324 limit = get_default_log_limit();
4326 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4327 switch (ch) {
4328 case 'p':
4329 show_patch = 1;
4330 break;
4331 case 'P':
4332 show_changed_paths = 1;
4333 break;
4334 case 'c':
4335 start_commit = optarg;
4336 break;
4337 case 'C':
4338 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4339 &errstr);
4340 if (errstr != NULL)
4341 errx(1, "number of context lines is %s: %s",
4342 errstr, optarg);
4343 break;
4344 case 'l':
4345 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4346 if (errstr != NULL)
4347 errx(1, "number of commits is %s: %s",
4348 errstr, optarg);
4349 break;
4350 case 'b':
4351 log_branches = 1;
4352 break;
4353 case 'r':
4354 repo_path = realpath(optarg, NULL);
4355 if (repo_path == NULL)
4356 return got_error_from_errno2("realpath",
4357 optarg);
4358 got_path_strip_trailing_slashes(repo_path);
4359 break;
4360 case 'R':
4361 reverse_display_order = 1;
4362 break;
4363 case 's':
4364 one_line = 1;
4365 break;
4366 case 'S':
4367 search_pattern = optarg;
4368 break;
4369 case 'x':
4370 end_commit = optarg;
4371 break;
4372 default:
4373 usage_log();
4374 /* NOTREACHED */
4378 argc -= optind;
4379 argv += optind;
4381 if (diff_context == -1)
4382 diff_context = 3;
4383 else if (!show_patch)
4384 errx(1, "-C requires -p");
4386 if (one_line && (show_patch || show_changed_paths))
4387 errx(1, "cannot use -s with -p or -P");
4389 cwd = getcwd(NULL, 0);
4390 if (cwd == NULL) {
4391 error = got_error_from_errno("getcwd");
4392 goto done;
4395 error = got_repo_pack_fds_open(&pack_fds);
4396 if (error != NULL)
4397 goto done;
4399 if (repo_path == NULL) {
4400 error = got_worktree_open(&worktree, cwd);
4401 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4402 goto done;
4403 error = NULL;
4406 if (argc == 1) {
4407 if (worktree) {
4408 error = got_worktree_resolve_path(&path, worktree,
4409 argv[0]);
4410 if (error)
4411 goto done;
4412 } else {
4413 path = strdup(argv[0]);
4414 if (path == NULL) {
4415 error = got_error_from_errno("strdup");
4416 goto done;
4419 } else if (argc != 0)
4420 usage_log();
4422 if (repo_path == NULL) {
4423 repo_path = worktree ?
4424 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4426 if (repo_path == NULL) {
4427 error = got_error_from_errno("strdup");
4428 goto done;
4431 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4432 if (error != NULL)
4433 goto done;
4435 error = apply_unveil(got_repo_get_path(repo), 1,
4436 worktree ? got_worktree_get_root_path(worktree) : NULL);
4437 if (error)
4438 goto done;
4440 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4441 if (error)
4442 goto done;
4444 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4445 if (error)
4446 goto done;
4448 if (start_commit == NULL) {
4449 struct got_reference *head_ref;
4450 struct got_commit_object *commit = NULL;
4451 error = got_ref_open(&head_ref, repo,
4452 worktree ? got_worktree_get_head_ref_name(worktree)
4453 : GOT_REF_HEAD, 0);
4454 if (error != NULL)
4455 goto done;
4456 error = got_ref_resolve(&start_id, repo, head_ref);
4457 got_ref_close(head_ref);
4458 if (error != NULL)
4459 goto done;
4460 error = got_object_open_as_commit(&commit, repo,
4461 start_id);
4462 if (error != NULL)
4463 goto done;
4464 got_object_commit_close(commit);
4465 } else {
4466 error = got_repo_match_object_id(&start_id, NULL,
4467 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4468 if (error != NULL)
4469 goto done;
4471 if (end_commit != NULL) {
4472 error = got_repo_match_object_id(&end_id, NULL,
4473 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4474 if (error != NULL)
4475 goto done;
4478 if (worktree) {
4480 * If a path was specified on the command line it was resolved
4481 * to a path in the work tree above. Prepend the work tree's
4482 * path prefix to obtain the corresponding in-repository path.
4484 if (path) {
4485 const char *prefix;
4486 prefix = got_worktree_get_path_prefix(worktree);
4487 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4488 (path[0] != '\0') ? "/" : "", path) == -1) {
4489 error = got_error_from_errno("asprintf");
4490 goto done;
4493 } else
4494 error = got_repo_map_path(&in_repo_path, repo,
4495 path ? path : "");
4496 if (error != NULL)
4497 goto done;
4498 if (in_repo_path) {
4499 free(path);
4500 path = in_repo_path;
4503 if (worktree) {
4504 /* Release work tree lock. */
4505 got_worktree_close(worktree);
4506 worktree = NULL;
4509 if (search_pattern && show_patch) {
4510 tmpfile = got_opentemp();
4511 if (tmpfile == NULL) {
4512 error = got_error_from_errno("got_opentemp");
4513 goto done;
4517 error = print_commits(start_id, end_id, repo, path ? path : "",
4518 show_changed_paths, show_patch, search_pattern, diff_context,
4519 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4520 tmpfile);
4521 done:
4522 free(path);
4523 free(repo_path);
4524 free(cwd);
4525 if (worktree)
4526 got_worktree_close(worktree);
4527 if (repo) {
4528 const struct got_error *close_err = got_repo_close(repo);
4529 if (error == NULL)
4530 error = close_err;
4532 if (pack_fds) {
4533 const struct got_error *pack_err =
4534 got_repo_pack_fds_close(pack_fds);
4535 if (error == NULL)
4536 error = pack_err;
4538 if (refs_idmap)
4539 got_reflist_object_id_map_free(refs_idmap);
4540 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4541 error = got_error_from_errno("fclose");
4542 got_ref_list_free(&refs);
4543 return error;
4546 __dead static void
4547 usage_diff(void)
4549 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4550 "[-r repository-path] [-s] [-w] [-P] "
4551 "[object1 object2 | path ...]\n", getprogname());
4552 exit(1);
4555 struct print_diff_arg {
4556 struct got_repository *repo;
4557 struct got_worktree *worktree;
4558 int diff_context;
4559 const char *id_str;
4560 int header_shown;
4561 int diff_staged;
4562 int ignore_whitespace;
4563 int force_text_diff;
4567 * Create a file which contains the target path of a symlink so we can feed
4568 * it as content to the diff engine.
4570 static const struct got_error *
4571 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4572 const char *abspath)
4574 const struct got_error *err = NULL;
4575 char target_path[PATH_MAX];
4576 ssize_t target_len, outlen;
4578 *fd = -1;
4580 if (dirfd != -1) {
4581 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4582 if (target_len == -1)
4583 return got_error_from_errno2("readlinkat", abspath);
4584 } else {
4585 target_len = readlink(abspath, target_path, PATH_MAX);
4586 if (target_len == -1)
4587 return got_error_from_errno2("readlink", abspath);
4590 *fd = got_opentempfd();
4591 if (*fd == -1)
4592 return got_error_from_errno("got_opentempfd");
4594 outlen = write(*fd, target_path, target_len);
4595 if (outlen == -1) {
4596 err = got_error_from_errno("got_opentempfd");
4597 goto done;
4600 if (lseek(*fd, 0, SEEK_SET) == -1) {
4601 err = got_error_from_errno2("lseek", abspath);
4602 goto done;
4604 done:
4605 if (err) {
4606 close(*fd);
4607 *fd = -1;
4609 return err;
4612 static const struct got_error *
4613 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4614 const char *path, struct got_object_id *blob_id,
4615 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4616 int dirfd, const char *de_name)
4618 struct print_diff_arg *a = arg;
4619 const struct got_error *err = NULL;
4620 struct got_blob_object *blob1 = NULL;
4621 int fd = -1;
4622 FILE *f1 = NULL, *f2 = NULL;
4623 char *abspath = NULL, *label1 = NULL;
4624 struct stat sb;
4625 off_t size1 = 0;
4627 if (a->diff_staged) {
4628 if (staged_status != GOT_STATUS_MODIFY &&
4629 staged_status != GOT_STATUS_ADD &&
4630 staged_status != GOT_STATUS_DELETE)
4631 return NULL;
4632 } else {
4633 if (staged_status == GOT_STATUS_DELETE)
4634 return NULL;
4635 if (status == GOT_STATUS_NONEXISTENT)
4636 return got_error_set_errno(ENOENT, path);
4637 if (status != GOT_STATUS_MODIFY &&
4638 status != GOT_STATUS_ADD &&
4639 status != GOT_STATUS_DELETE &&
4640 status != GOT_STATUS_CONFLICT)
4641 return NULL;
4644 if (!a->header_shown) {
4645 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4646 got_worktree_get_root_path(a->worktree));
4647 printf("commit - %s\n", a->id_str);
4648 printf("path + %s%s\n",
4649 got_worktree_get_root_path(a->worktree),
4650 a->diff_staged ? " (staged changes)" : "");
4651 a->header_shown = 1;
4654 if (a->diff_staged) {
4655 const char *label1 = NULL, *label2 = NULL;
4656 switch (staged_status) {
4657 case GOT_STATUS_MODIFY:
4658 label1 = path;
4659 label2 = path;
4660 break;
4661 case GOT_STATUS_ADD:
4662 label2 = path;
4663 break;
4664 case GOT_STATUS_DELETE:
4665 label1 = path;
4666 break;
4667 default:
4668 return got_error(GOT_ERR_FILE_STATUS);
4670 f1 = got_opentemp();
4671 if (f1 == NULL) {
4672 err = got_error_from_errno("got_opentemp");
4673 goto done;
4675 f2 = got_opentemp();
4676 if (f2 == NULL) {
4677 err = got_error_from_errno("got_opentemp");
4678 goto done;
4680 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4681 blob_id, staged_blob_id, label1, label2, a->diff_context,
4682 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4683 goto done;
4686 if (staged_status == GOT_STATUS_ADD ||
4687 staged_status == GOT_STATUS_MODIFY) {
4688 char *id_str;
4689 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4690 8192);
4691 if (err)
4692 goto done;
4693 err = got_object_id_str(&id_str, staged_blob_id);
4694 if (err)
4695 goto done;
4696 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4697 err = got_error_from_errno("asprintf");
4698 free(id_str);
4699 goto done;
4701 free(id_str);
4702 } else if (status != GOT_STATUS_ADD) {
4703 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4704 if (err)
4705 goto done;
4708 if (status != GOT_STATUS_DELETE) {
4709 if (asprintf(&abspath, "%s/%s",
4710 got_worktree_get_root_path(a->worktree), path) == -1) {
4711 err = got_error_from_errno("asprintf");
4712 goto done;
4715 if (dirfd != -1) {
4716 fd = openat(dirfd, de_name,
4717 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4718 if (fd == -1) {
4719 if (!got_err_open_nofollow_on_symlink()) {
4720 err = got_error_from_errno2("openat",
4721 abspath);
4722 goto done;
4724 err = get_symlink_target_file(&fd, dirfd,
4725 de_name, abspath);
4726 if (err)
4727 goto done;
4729 } else {
4730 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4731 if (fd == -1) {
4732 if (!got_err_open_nofollow_on_symlink()) {
4733 err = got_error_from_errno2("open",
4734 abspath);
4735 goto done;
4737 err = get_symlink_target_file(&fd, dirfd,
4738 de_name, abspath);
4739 if (err)
4740 goto done;
4743 if (fstat(fd, &sb) == -1) {
4744 err = got_error_from_errno2("fstat", abspath);
4745 goto done;
4747 f2 = fdopen(fd, "r");
4748 if (f2 == NULL) {
4749 err = got_error_from_errno2("fdopen", abspath);
4750 goto done;
4752 fd = -1;
4753 } else
4754 sb.st_size = 0;
4756 if (blob1) {
4757 f1 = got_opentemp();
4758 if (f1 == NULL) {
4759 err = got_error_from_errno("got_opentemp");
4760 goto done;
4762 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4763 blob1);
4764 if (err)
4765 goto done;
4768 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4769 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4770 stdout);
4771 done:
4772 if (blob1)
4773 got_object_blob_close(blob1);
4774 if (f1 && fclose(f1) == EOF && err == NULL)
4775 err = got_error_from_errno("fclose");
4776 if (f2 && fclose(f2) == EOF && err == NULL)
4777 err = got_error_from_errno("fclose");
4778 if (fd != -1 && close(fd) == -1 && err == NULL)
4779 err = got_error_from_errno("close");
4780 free(abspath);
4781 return err;
4784 static const struct got_error *
4785 cmd_diff(int argc, char *argv[])
4787 const struct got_error *error;
4788 struct got_repository *repo = NULL;
4789 struct got_worktree *worktree = NULL;
4790 char *cwd = NULL, *repo_path = NULL;
4791 const char *commit_args[2] = { NULL, NULL };
4792 int ncommit_args = 0;
4793 struct got_object_id *ids[2] = { NULL, NULL };
4794 char *labels[2] = { NULL, NULL };
4795 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4796 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4797 int force_text_diff = 0, force_path = 0, rflag = 0;
4798 const char *errstr;
4799 struct got_reflist_head refs;
4800 struct got_pathlist_head paths;
4801 struct got_pathlist_entry *pe;
4802 FILE *f1 = NULL, *f2 = NULL;
4803 int *pack_fds = NULL;
4805 TAILQ_INIT(&refs);
4806 TAILQ_INIT(&paths);
4808 #ifndef PROFILE
4809 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4810 NULL) == -1)
4811 err(1, "pledge");
4812 #endif
4814 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4815 switch (ch) {
4816 case 'a':
4817 force_text_diff = 1;
4818 break;
4819 case 'c':
4820 if (ncommit_args >= 2)
4821 errx(1, "too many -c options used");
4822 commit_args[ncommit_args++] = optarg;
4823 break;
4824 case 'C':
4825 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4826 &errstr);
4827 if (errstr != NULL)
4828 errx(1, "number of context lines is %s: %s",
4829 errstr, optarg);
4830 break;
4831 case 'r':
4832 repo_path = realpath(optarg, NULL);
4833 if (repo_path == NULL)
4834 return got_error_from_errno2("realpath",
4835 optarg);
4836 got_path_strip_trailing_slashes(repo_path);
4837 rflag = 1;
4838 break;
4839 case 's':
4840 diff_staged = 1;
4841 break;
4842 case 'w':
4843 ignore_whitespace = 1;
4844 break;
4845 case 'P':
4846 force_path = 1;
4847 break;
4848 default:
4849 usage_diff();
4850 /* NOTREACHED */
4854 argc -= optind;
4855 argv += optind;
4857 cwd = getcwd(NULL, 0);
4858 if (cwd == NULL) {
4859 error = got_error_from_errno("getcwd");
4860 goto done;
4863 error = got_repo_pack_fds_open(&pack_fds);
4864 if (error != NULL)
4865 goto done;
4867 if (repo_path == NULL) {
4868 error = got_worktree_open(&worktree, cwd);
4869 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4870 goto done;
4871 else
4872 error = NULL;
4873 if (worktree) {
4874 repo_path =
4875 strdup(got_worktree_get_repo_path(worktree));
4876 if (repo_path == NULL) {
4877 error = got_error_from_errno("strdup");
4878 goto done;
4880 } else {
4881 repo_path = strdup(cwd);
4882 if (repo_path == NULL) {
4883 error = got_error_from_errno("strdup");
4884 goto done;
4889 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4890 free(repo_path);
4891 if (error != NULL)
4892 goto done;
4894 if (rflag || worktree == NULL || ncommit_args > 0) {
4895 if (force_path) {
4896 error = got_error_msg(GOT_ERR_NOT_IMPL,
4897 "-P option can only be used when diffing "
4898 "a work tree");
4899 goto done;
4901 if (diff_staged) {
4902 error = got_error_msg(GOT_ERR_NOT_IMPL,
4903 "-s option can only be used when diffing "
4904 "a work tree");
4905 goto done;
4909 error = apply_unveil(got_repo_get_path(repo), 1,
4910 worktree ? got_worktree_get_root_path(worktree) : NULL);
4911 if (error)
4912 goto done;
4914 if ((!force_path && argc == 2) || ncommit_args > 0) {
4915 int obj_type = (ncommit_args > 0 ?
4916 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4917 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4918 NULL);
4919 if (error)
4920 goto done;
4921 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4922 const char *arg;
4923 if (ncommit_args > 0)
4924 arg = commit_args[i];
4925 else
4926 arg = argv[i];
4927 error = got_repo_match_object_id(&ids[i], &labels[i],
4928 arg, obj_type, &refs, repo);
4929 if (error) {
4930 if (error->code != GOT_ERR_NOT_REF &&
4931 error->code != GOT_ERR_NO_OBJ)
4932 goto done;
4933 if (ncommit_args > 0)
4934 goto done;
4935 error = NULL;
4936 break;
4941 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4942 struct print_diff_arg arg;
4943 char *id_str;
4945 if (worktree == NULL) {
4946 if (argc == 2 && ids[0] == NULL) {
4947 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4948 goto done;
4949 } else if (argc == 2 && ids[1] == NULL) {
4950 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4951 goto done;
4952 } else if (argc > 0) {
4953 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4954 "%s", "specified paths cannot be resolved");
4955 goto done;
4956 } else {
4957 error = got_error(GOT_ERR_NOT_WORKTREE);
4958 goto done;
4962 error = get_worktree_paths_from_argv(&paths, argc, argv,
4963 worktree);
4964 if (error)
4965 goto done;
4967 error = got_object_id_str(&id_str,
4968 got_worktree_get_base_commit_id(worktree));
4969 if (error)
4970 goto done;
4971 arg.repo = repo;
4972 arg.worktree = worktree;
4973 arg.diff_context = diff_context;
4974 arg.id_str = id_str;
4975 arg.header_shown = 0;
4976 arg.diff_staged = diff_staged;
4977 arg.ignore_whitespace = ignore_whitespace;
4978 arg.force_text_diff = force_text_diff;
4980 error = got_worktree_status(worktree, &paths, repo, 0,
4981 print_diff, &arg, check_cancelled, NULL);
4982 free(id_str);
4983 goto done;
4986 if (ncommit_args == 1) {
4987 struct got_commit_object *commit;
4988 error = got_object_open_as_commit(&commit, repo, ids[0]);
4989 if (error)
4990 goto done;
4992 labels[1] = labels[0];
4993 ids[1] = ids[0];
4994 if (got_object_commit_get_nparents(commit) > 0) {
4995 const struct got_object_id_queue *pids;
4996 struct got_object_qid *pid;
4997 pids = got_object_commit_get_parent_ids(commit);
4998 pid = STAILQ_FIRST(pids);
4999 ids[0] = got_object_id_dup(&pid->id);
5000 if (ids[0] == NULL) {
5001 error = got_error_from_errno(
5002 "got_object_id_dup");
5003 got_object_commit_close(commit);
5004 goto done;
5006 error = got_object_id_str(&labels[0], ids[0]);
5007 if (error) {
5008 got_object_commit_close(commit);
5009 goto done;
5011 } else {
5012 ids[0] = NULL;
5013 labels[0] = strdup("/dev/null");
5014 if (labels[0] == NULL) {
5015 error = got_error_from_errno("strdup");
5016 got_object_commit_close(commit);
5017 goto done;
5021 got_object_commit_close(commit);
5024 if (ncommit_args == 0 && argc > 2) {
5025 error = got_error_msg(GOT_ERR_BAD_PATH,
5026 "path arguments cannot be used when diffing two objects");
5027 goto done;
5030 if (ids[0]) {
5031 error = got_object_get_type(&type1, repo, ids[0]);
5032 if (error)
5033 goto done;
5036 error = got_object_get_type(&type2, repo, ids[1]);
5037 if (error)
5038 goto done;
5039 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5040 error = got_error(GOT_ERR_OBJ_TYPE);
5041 goto done;
5043 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5044 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5045 "path arguments cannot be used when diffing blobs");
5046 goto done;
5049 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5050 char *in_repo_path;
5051 struct got_pathlist_entry *new;
5052 if (worktree) {
5053 const char *prefix;
5054 char *p;
5055 error = got_worktree_resolve_path(&p, worktree,
5056 argv[i]);
5057 if (error)
5058 goto done;
5059 prefix = got_worktree_get_path_prefix(worktree);
5060 while (prefix[0] == '/')
5061 prefix++;
5062 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5063 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5064 p) == -1) {
5065 error = got_error_from_errno("asprintf");
5066 free(p);
5067 goto done;
5069 free(p);
5070 } else {
5071 char *mapped_path, *s;
5072 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5073 if (error)
5074 goto done;
5075 s = mapped_path;
5076 while (s[0] == '/')
5077 s++;
5078 in_repo_path = strdup(s);
5079 if (in_repo_path == NULL) {
5080 error = got_error_from_errno("asprintf");
5081 free(mapped_path);
5082 goto done;
5084 free(mapped_path);
5087 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5088 if (error || new == NULL /* duplicate */)
5089 free(in_repo_path);
5090 if (error)
5091 goto done;
5094 if (worktree) {
5095 /* Release work tree lock. */
5096 got_worktree_close(worktree);
5097 worktree = NULL;
5100 f1 = got_opentemp();
5101 if (f1 == NULL) {
5102 error = got_error_from_errno("got_opentemp");
5103 goto done;
5106 f2 = got_opentemp();
5107 if (f2 == NULL) {
5108 error = got_error_from_errno("got_opentemp");
5109 goto done;
5112 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5113 case GOT_OBJ_TYPE_BLOB:
5114 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5115 ids[0], ids[1], NULL, NULL, diff_context,
5116 ignore_whitespace, force_text_diff, repo, stdout);
5117 break;
5118 case GOT_OBJ_TYPE_TREE:
5119 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5120 ids[0], ids[1], &paths, "", "", diff_context,
5121 ignore_whitespace, force_text_diff, repo, stdout);
5122 break;
5123 case GOT_OBJ_TYPE_COMMIT:
5124 printf("diff %s %s\n", labels[0], labels[1]);
5125 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5126 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5127 force_text_diff, repo, stdout);
5128 break;
5129 default:
5130 error = got_error(GOT_ERR_OBJ_TYPE);
5132 done:
5133 free(labels[0]);
5134 free(labels[1]);
5135 free(ids[0]);
5136 free(ids[1]);
5137 if (worktree)
5138 got_worktree_close(worktree);
5139 if (repo) {
5140 const struct got_error *close_err = got_repo_close(repo);
5141 if (error == NULL)
5142 error = close_err;
5144 if (pack_fds) {
5145 const struct got_error *pack_err =
5146 got_repo_pack_fds_close(pack_fds);
5147 if (error == NULL)
5148 error = pack_err;
5150 TAILQ_FOREACH(pe, &paths, entry)
5151 free((char *)pe->path);
5152 got_pathlist_free(&paths);
5153 got_ref_list_free(&refs);
5154 if (f1 && fclose(f1) == EOF && error == NULL)
5155 error = got_error_from_errno("fclose");
5156 if (f2 && fclose(f2) == EOF && error == NULL)
5157 error = got_error_from_errno("fclose");
5158 return error;
5161 __dead static void
5162 usage_blame(void)
5164 fprintf(stderr,
5165 "usage: %s blame [-c commit] [-r repository-path] path\n",
5166 getprogname());
5167 exit(1);
5170 struct blame_line {
5171 int annotated;
5172 char *id_str;
5173 char *committer;
5174 char datebuf[11]; /* YYYY-MM-DD + NUL */
5177 struct blame_cb_args {
5178 struct blame_line *lines;
5179 int nlines;
5180 int nlines_prec;
5181 int lineno_cur;
5182 off_t *line_offsets;
5183 FILE *f;
5184 struct got_repository *repo;
5187 static const struct got_error *
5188 blame_cb(void *arg, int nlines, int lineno,
5189 struct got_commit_object *commit, struct got_object_id *id)
5191 const struct got_error *err = NULL;
5192 struct blame_cb_args *a = arg;
5193 struct blame_line *bline;
5194 char *line = NULL;
5195 size_t linesize = 0;
5196 off_t offset;
5197 struct tm tm;
5198 time_t committer_time;
5200 if (nlines != a->nlines ||
5201 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5202 return got_error(GOT_ERR_RANGE);
5204 if (sigint_received)
5205 return got_error(GOT_ERR_ITER_COMPLETED);
5207 if (lineno == -1)
5208 return NULL; /* no change in this commit */
5210 /* Annotate this line. */
5211 bline = &a->lines[lineno - 1];
5212 if (bline->annotated)
5213 return NULL;
5214 err = got_object_id_str(&bline->id_str, id);
5215 if (err)
5216 return err;
5218 bline->committer = strdup(got_object_commit_get_committer(commit));
5219 if (bline->committer == NULL) {
5220 err = got_error_from_errno("strdup");
5221 goto done;
5224 committer_time = got_object_commit_get_committer_time(commit);
5225 if (gmtime_r(&committer_time, &tm) == NULL)
5226 return got_error_from_errno("gmtime_r");
5227 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5228 &tm) == 0) {
5229 err = got_error(GOT_ERR_NO_SPACE);
5230 goto done;
5232 bline->annotated = 1;
5234 /* Print lines annotated so far. */
5235 bline = &a->lines[a->lineno_cur - 1];
5236 if (!bline->annotated)
5237 goto done;
5239 offset = a->line_offsets[a->lineno_cur - 1];
5240 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5241 err = got_error_from_errno("fseeko");
5242 goto done;
5245 while (bline->annotated) {
5246 char *smallerthan, *at, *nl, *committer;
5247 size_t len;
5249 if (getline(&line, &linesize, a->f) == -1) {
5250 if (ferror(a->f))
5251 err = got_error_from_errno("getline");
5252 break;
5255 committer = bline->committer;
5256 smallerthan = strchr(committer, '<');
5257 if (smallerthan && smallerthan[1] != '\0')
5258 committer = smallerthan + 1;
5259 at = strchr(committer, '@');
5260 if (at)
5261 *at = '\0';
5262 len = strlen(committer);
5263 if (len >= 9)
5264 committer[8] = '\0';
5266 nl = strchr(line, '\n');
5267 if (nl)
5268 *nl = '\0';
5269 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5270 bline->id_str, bline->datebuf, committer, line);
5272 a->lineno_cur++;
5273 bline = &a->lines[a->lineno_cur - 1];
5275 done:
5276 free(line);
5277 return err;
5280 static const struct got_error *
5281 cmd_blame(int argc, char *argv[])
5283 const struct got_error *error;
5284 struct got_repository *repo = NULL;
5285 struct got_worktree *worktree = NULL;
5286 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5287 char *link_target = NULL;
5288 struct got_object_id *obj_id = NULL;
5289 struct got_object_id *commit_id = NULL;
5290 struct got_commit_object *commit = NULL;
5291 struct got_blob_object *blob = NULL;
5292 char *commit_id_str = NULL;
5293 struct blame_cb_args bca;
5294 int ch, obj_type, i;
5295 off_t filesize;
5296 int *pack_fds = NULL;
5298 memset(&bca, 0, sizeof(bca));
5300 #ifndef PROFILE
5301 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5302 NULL) == -1)
5303 err(1, "pledge");
5304 #endif
5306 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5307 switch (ch) {
5308 case 'c':
5309 commit_id_str = optarg;
5310 break;
5311 case 'r':
5312 repo_path = realpath(optarg, NULL);
5313 if (repo_path == NULL)
5314 return got_error_from_errno2("realpath",
5315 optarg);
5316 got_path_strip_trailing_slashes(repo_path);
5317 break;
5318 default:
5319 usage_blame();
5320 /* NOTREACHED */
5324 argc -= optind;
5325 argv += optind;
5327 if (argc == 1)
5328 path = argv[0];
5329 else
5330 usage_blame();
5332 cwd = getcwd(NULL, 0);
5333 if (cwd == NULL) {
5334 error = got_error_from_errno("getcwd");
5335 goto done;
5338 error = got_repo_pack_fds_open(&pack_fds);
5339 if (error != NULL)
5340 goto done;
5342 if (repo_path == NULL) {
5343 error = got_worktree_open(&worktree, cwd);
5344 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5345 goto done;
5346 else
5347 error = NULL;
5348 if (worktree) {
5349 repo_path =
5350 strdup(got_worktree_get_repo_path(worktree));
5351 if (repo_path == NULL) {
5352 error = got_error_from_errno("strdup");
5353 if (error)
5354 goto done;
5356 } else {
5357 repo_path = strdup(cwd);
5358 if (repo_path == NULL) {
5359 error = got_error_from_errno("strdup");
5360 goto done;
5365 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5366 if (error != NULL)
5367 goto done;
5369 if (worktree) {
5370 const char *prefix = got_worktree_get_path_prefix(worktree);
5371 char *p;
5373 error = got_worktree_resolve_path(&p, worktree, path);
5374 if (error)
5375 goto done;
5376 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5377 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5378 p) == -1) {
5379 error = got_error_from_errno("asprintf");
5380 free(p);
5381 goto done;
5383 free(p);
5384 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5385 } else {
5386 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5387 if (error)
5388 goto done;
5389 error = got_repo_map_path(&in_repo_path, repo, path);
5391 if (error)
5392 goto done;
5394 if (commit_id_str == NULL) {
5395 struct got_reference *head_ref;
5396 error = got_ref_open(&head_ref, repo, worktree ?
5397 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5398 if (error != NULL)
5399 goto done;
5400 error = got_ref_resolve(&commit_id, repo, head_ref);
5401 got_ref_close(head_ref);
5402 if (error != NULL)
5403 goto done;
5404 } else {
5405 struct got_reflist_head refs;
5406 TAILQ_INIT(&refs);
5407 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5408 NULL);
5409 if (error)
5410 goto done;
5411 error = got_repo_match_object_id(&commit_id, NULL,
5412 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5413 got_ref_list_free(&refs);
5414 if (error)
5415 goto done;
5418 if (worktree) {
5419 /* Release work tree lock. */
5420 got_worktree_close(worktree);
5421 worktree = NULL;
5424 error = got_object_open_as_commit(&commit, repo, commit_id);
5425 if (error)
5426 goto done;
5428 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5429 commit, repo);
5430 if (error)
5431 goto done;
5433 error = got_object_id_by_path(&obj_id, repo, commit,
5434 link_target ? link_target : in_repo_path);
5435 if (error)
5436 goto done;
5438 error = got_object_get_type(&obj_type, repo, obj_id);
5439 if (error)
5440 goto done;
5442 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5443 error = got_error_path(link_target ? link_target : in_repo_path,
5444 GOT_ERR_OBJ_TYPE);
5445 goto done;
5448 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5449 if (error)
5450 goto done;
5451 bca.f = got_opentemp();
5452 if (bca.f == NULL) {
5453 error = got_error_from_errno("got_opentemp");
5454 goto done;
5456 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5457 &bca.line_offsets, bca.f, blob);
5458 if (error || bca.nlines == 0)
5459 goto done;
5461 /* Don't include \n at EOF in the blame line count. */
5462 if (bca.line_offsets[bca.nlines - 1] == filesize)
5463 bca.nlines--;
5465 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5466 if (bca.lines == NULL) {
5467 error = got_error_from_errno("calloc");
5468 goto done;
5470 bca.lineno_cur = 1;
5471 bca.nlines_prec = 0;
5472 i = bca.nlines;
5473 while (i > 0) {
5474 i /= 10;
5475 bca.nlines_prec++;
5477 bca.repo = repo;
5479 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5480 repo, blame_cb, &bca, check_cancelled, NULL);
5481 done:
5482 free(in_repo_path);
5483 free(link_target);
5484 free(repo_path);
5485 free(cwd);
5486 free(commit_id);
5487 free(obj_id);
5488 if (commit)
5489 got_object_commit_close(commit);
5490 if (blob)
5491 got_object_blob_close(blob);
5492 if (worktree)
5493 got_worktree_close(worktree);
5494 if (repo) {
5495 const struct got_error *close_err = got_repo_close(repo);
5496 if (error == NULL)
5497 error = close_err;
5499 if (pack_fds) {
5500 const struct got_error *pack_err =
5501 got_repo_pack_fds_close(pack_fds);
5502 if (error == NULL)
5503 error = pack_err;
5505 if (bca.lines) {
5506 for (i = 0; i < bca.nlines; i++) {
5507 struct blame_line *bline = &bca.lines[i];
5508 free(bline->id_str);
5509 free(bline->committer);
5511 free(bca.lines);
5513 free(bca.line_offsets);
5514 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5515 error = got_error_from_errno("fclose");
5516 return error;
5519 __dead static void
5520 usage_tree(void)
5522 fprintf(stderr,
5523 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5524 getprogname());
5525 exit(1);
5528 static const struct got_error *
5529 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5530 const char *root_path, struct got_repository *repo)
5532 const struct got_error *err = NULL;
5533 int is_root_path = (strcmp(path, root_path) == 0);
5534 const char *modestr = "";
5535 mode_t mode = got_tree_entry_get_mode(te);
5536 char *link_target = NULL;
5538 path += strlen(root_path);
5539 while (path[0] == '/')
5540 path++;
5542 if (got_object_tree_entry_is_submodule(te))
5543 modestr = "$";
5544 else if (S_ISLNK(mode)) {
5545 int i;
5547 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5548 if (err)
5549 return err;
5550 for (i = 0; i < strlen(link_target); i++) {
5551 if (!isprint((unsigned char)link_target[i]))
5552 link_target[i] = '?';
5555 modestr = "@";
5557 else if (S_ISDIR(mode))
5558 modestr = "/";
5559 else if (mode & S_IXUSR)
5560 modestr = "*";
5562 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5563 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5564 link_target ? " -> ": "", link_target ? link_target : "");
5566 free(link_target);
5567 return NULL;
5570 static const struct got_error *
5571 print_tree(const char *path, struct got_commit_object *commit,
5572 int show_ids, int recurse, const char *root_path,
5573 struct got_repository *repo)
5575 const struct got_error *err = NULL;
5576 struct got_object_id *tree_id = NULL;
5577 struct got_tree_object *tree = NULL;
5578 int nentries, i;
5580 err = got_object_id_by_path(&tree_id, repo, commit, path);
5581 if (err)
5582 goto done;
5584 err = got_object_open_as_tree(&tree, repo, tree_id);
5585 if (err)
5586 goto done;
5587 nentries = got_object_tree_get_nentries(tree);
5588 for (i = 0; i < nentries; i++) {
5589 struct got_tree_entry *te;
5590 char *id = NULL;
5592 if (sigint_received || sigpipe_received)
5593 break;
5595 te = got_object_tree_get_entry(tree, i);
5596 if (show_ids) {
5597 char *id_str;
5598 err = got_object_id_str(&id_str,
5599 got_tree_entry_get_id(te));
5600 if (err)
5601 goto done;
5602 if (asprintf(&id, "%s ", id_str) == -1) {
5603 err = got_error_from_errno("asprintf");
5604 free(id_str);
5605 goto done;
5607 free(id_str);
5609 err = print_entry(te, id, path, root_path, repo);
5610 free(id);
5611 if (err)
5612 goto done;
5614 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5615 char *child_path;
5616 if (asprintf(&child_path, "%s%s%s", path,
5617 path[0] == '/' && path[1] == '\0' ? "" : "/",
5618 got_tree_entry_get_name(te)) == -1) {
5619 err = got_error_from_errno("asprintf");
5620 goto done;
5622 err = print_tree(child_path, commit, show_ids, 1,
5623 root_path, repo);
5624 free(child_path);
5625 if (err)
5626 goto done;
5629 done:
5630 if (tree)
5631 got_object_tree_close(tree);
5632 free(tree_id);
5633 return err;
5636 static const struct got_error *
5637 cmd_tree(int argc, char *argv[])
5639 const struct got_error *error;
5640 struct got_repository *repo = NULL;
5641 struct got_worktree *worktree = NULL;
5642 const char *path, *refname = NULL;
5643 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5644 struct got_object_id *commit_id = NULL;
5645 struct got_commit_object *commit = NULL;
5646 char *commit_id_str = NULL;
5647 int show_ids = 0, recurse = 0;
5648 int ch;
5649 int *pack_fds = NULL;
5651 #ifndef PROFILE
5652 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5653 NULL) == -1)
5654 err(1, "pledge");
5655 #endif
5657 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5658 switch (ch) {
5659 case 'c':
5660 commit_id_str = optarg;
5661 break;
5662 case 'r':
5663 repo_path = realpath(optarg, NULL);
5664 if (repo_path == NULL)
5665 return got_error_from_errno2("realpath",
5666 optarg);
5667 got_path_strip_trailing_slashes(repo_path);
5668 break;
5669 case 'i':
5670 show_ids = 1;
5671 break;
5672 case 'R':
5673 recurse = 1;
5674 break;
5675 default:
5676 usage_tree();
5677 /* NOTREACHED */
5681 argc -= optind;
5682 argv += optind;
5684 if (argc == 1)
5685 path = argv[0];
5686 else if (argc > 1)
5687 usage_tree();
5688 else
5689 path = NULL;
5691 cwd = getcwd(NULL, 0);
5692 if (cwd == NULL) {
5693 error = got_error_from_errno("getcwd");
5694 goto done;
5697 error = got_repo_pack_fds_open(&pack_fds);
5698 if (error != NULL)
5699 goto done;
5701 if (repo_path == NULL) {
5702 error = got_worktree_open(&worktree, cwd);
5703 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5704 goto done;
5705 else
5706 error = NULL;
5707 if (worktree) {
5708 repo_path =
5709 strdup(got_worktree_get_repo_path(worktree));
5710 if (repo_path == NULL)
5711 error = got_error_from_errno("strdup");
5712 if (error)
5713 goto done;
5714 } else {
5715 repo_path = strdup(cwd);
5716 if (repo_path == NULL) {
5717 error = got_error_from_errno("strdup");
5718 goto done;
5723 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5724 if (error != NULL)
5725 goto done;
5727 if (worktree) {
5728 const char *prefix = got_worktree_get_path_prefix(worktree);
5729 char *p;
5731 if (path == NULL)
5732 path = "";
5733 error = got_worktree_resolve_path(&p, worktree, path);
5734 if (error)
5735 goto done;
5736 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5737 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5738 p) == -1) {
5739 error = got_error_from_errno("asprintf");
5740 free(p);
5741 goto done;
5743 free(p);
5744 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5745 if (error)
5746 goto done;
5747 } else {
5748 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5749 if (error)
5750 goto done;
5751 if (path == NULL)
5752 path = "/";
5753 error = got_repo_map_path(&in_repo_path, repo, path);
5754 if (error != NULL)
5755 goto done;
5758 if (commit_id_str == NULL) {
5759 struct got_reference *head_ref;
5760 if (worktree)
5761 refname = got_worktree_get_head_ref_name(worktree);
5762 else
5763 refname = GOT_REF_HEAD;
5764 error = got_ref_open(&head_ref, repo, refname, 0);
5765 if (error != NULL)
5766 goto done;
5767 error = got_ref_resolve(&commit_id, repo, head_ref);
5768 got_ref_close(head_ref);
5769 if (error != NULL)
5770 goto done;
5771 } else {
5772 struct got_reflist_head refs;
5773 TAILQ_INIT(&refs);
5774 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5775 NULL);
5776 if (error)
5777 goto done;
5778 error = got_repo_match_object_id(&commit_id, NULL,
5779 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5780 got_ref_list_free(&refs);
5781 if (error)
5782 goto done;
5785 if (worktree) {
5786 /* Release work tree lock. */
5787 got_worktree_close(worktree);
5788 worktree = NULL;
5791 error = got_object_open_as_commit(&commit, repo, commit_id);
5792 if (error)
5793 goto done;
5795 error = print_tree(in_repo_path, commit, show_ids, recurse,
5796 in_repo_path, repo);
5797 done:
5798 free(in_repo_path);
5799 free(repo_path);
5800 free(cwd);
5801 free(commit_id);
5802 if (commit)
5803 got_object_commit_close(commit);
5804 if (worktree)
5805 got_worktree_close(worktree);
5806 if (repo) {
5807 const struct got_error *close_err = got_repo_close(repo);
5808 if (error == NULL)
5809 error = close_err;
5811 if (pack_fds) {
5812 const struct got_error *pack_err =
5813 got_repo_pack_fds_close(pack_fds);
5814 if (error == NULL)
5815 error = pack_err;
5817 return error;
5820 __dead static void
5821 usage_status(void)
5823 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5824 "[-S status-codes] [path ...]\n", getprogname());
5825 exit(1);
5828 struct got_status_arg {
5829 char *status_codes;
5830 int suppress;
5833 static const struct got_error *
5834 print_status(void *arg, unsigned char status, unsigned char staged_status,
5835 const char *path, struct got_object_id *blob_id,
5836 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5837 int dirfd, const char *de_name)
5839 struct got_status_arg *st = arg;
5841 if (status == staged_status && (status == GOT_STATUS_DELETE))
5842 status = GOT_STATUS_NO_CHANGE;
5843 if (st != NULL && st->status_codes) {
5844 size_t ncodes = strlen(st->status_codes);
5845 int i, j = 0;
5847 for (i = 0; i < ncodes ; i++) {
5848 if (st->suppress) {
5849 if (status == st->status_codes[i] ||
5850 staged_status == st->status_codes[i]) {
5851 j++;
5852 continue;
5854 } else {
5855 if (status == st->status_codes[i] ||
5856 staged_status == st->status_codes[i])
5857 break;
5861 if (st->suppress && j == 0)
5862 goto print;
5864 if (i == ncodes)
5865 return NULL;
5867 print:
5868 printf("%c%c %s\n", status, staged_status, path);
5869 return NULL;
5872 static const struct got_error *
5873 cmd_status(int argc, char *argv[])
5875 const struct got_error *error = NULL;
5876 struct got_repository *repo = NULL;
5877 struct got_worktree *worktree = NULL;
5878 struct got_status_arg st;
5879 char *cwd = NULL;
5880 struct got_pathlist_head paths;
5881 struct got_pathlist_entry *pe;
5882 int ch, i, no_ignores = 0;
5883 int *pack_fds = NULL;
5885 TAILQ_INIT(&paths);
5887 memset(&st, 0, sizeof(st));
5888 st.status_codes = NULL;
5889 st.suppress = 0;
5891 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5892 switch (ch) {
5893 case 'I':
5894 no_ignores = 1;
5895 break;
5896 case 'S':
5897 if (st.status_codes != NULL && st.suppress == 0)
5898 option_conflict('S', 's');
5899 st.suppress = 1;
5900 /* fallthrough */
5901 case 's':
5902 for (i = 0; i < strlen(optarg); i++) {
5903 switch (optarg[i]) {
5904 case GOT_STATUS_MODIFY:
5905 case GOT_STATUS_ADD:
5906 case GOT_STATUS_DELETE:
5907 case GOT_STATUS_CONFLICT:
5908 case GOT_STATUS_MISSING:
5909 case GOT_STATUS_OBSTRUCTED:
5910 case GOT_STATUS_UNVERSIONED:
5911 case GOT_STATUS_MODE_CHANGE:
5912 case GOT_STATUS_NONEXISTENT:
5913 break;
5914 default:
5915 errx(1, "invalid status code '%c'",
5916 optarg[i]);
5919 if (ch == 's' && st.suppress)
5920 option_conflict('s', 'S');
5921 st.status_codes = optarg;
5922 break;
5923 default:
5924 usage_status();
5925 /* NOTREACHED */
5929 argc -= optind;
5930 argv += optind;
5932 #ifndef PROFILE
5933 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5934 NULL) == -1)
5935 err(1, "pledge");
5936 #endif
5937 cwd = getcwd(NULL, 0);
5938 if (cwd == NULL) {
5939 error = got_error_from_errno("getcwd");
5940 goto done;
5943 error = got_repo_pack_fds_open(&pack_fds);
5944 if (error != NULL)
5945 goto done;
5947 error = got_worktree_open(&worktree, cwd);
5948 if (error) {
5949 if (error->code == GOT_ERR_NOT_WORKTREE)
5950 error = wrap_not_worktree_error(error, "status", cwd);
5951 goto done;
5954 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5955 NULL, pack_fds);
5956 if (error != NULL)
5957 goto done;
5959 error = apply_unveil(got_repo_get_path(repo), 1,
5960 got_worktree_get_root_path(worktree));
5961 if (error)
5962 goto done;
5964 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5965 if (error)
5966 goto done;
5968 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5969 print_status, &st, check_cancelled, NULL);
5970 done:
5971 if (pack_fds) {
5972 const struct got_error *pack_err =
5973 got_repo_pack_fds_close(pack_fds);
5974 if (error == NULL)
5975 error = pack_err;
5978 TAILQ_FOREACH(pe, &paths, entry)
5979 free((char *)pe->path);
5980 got_pathlist_free(&paths);
5981 free(cwd);
5982 return error;
5985 __dead static void
5986 usage_ref(void)
5988 fprintf(stderr,
5989 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5990 "[-s reference] [-d] [name]\n",
5991 getprogname());
5992 exit(1);
5995 static const struct got_error *
5996 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5998 static const struct got_error *err = NULL;
5999 struct got_reflist_head refs;
6000 struct got_reflist_entry *re;
6002 TAILQ_INIT(&refs);
6003 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6004 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6005 repo);
6006 if (err)
6007 return err;
6009 TAILQ_FOREACH(re, &refs, entry) {
6010 char *refstr;
6011 refstr = got_ref_to_str(re->ref);
6012 if (refstr == NULL) {
6013 err = got_error_from_errno("got_ref_to_str");
6014 break;
6016 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6017 free(refstr);
6020 got_ref_list_free(&refs);
6021 return err;
6024 static const struct got_error *
6025 delete_ref_by_name(struct got_repository *repo, const char *refname)
6027 const struct got_error *err;
6028 struct got_reference *ref;
6030 err = got_ref_open(&ref, repo, refname, 0);
6031 if (err)
6032 return err;
6034 err = delete_ref(repo, ref);
6035 got_ref_close(ref);
6036 return err;
6039 static const struct got_error *
6040 add_ref(struct got_repository *repo, const char *refname, const char *target)
6042 const struct got_error *err = NULL;
6043 struct got_object_id *id = NULL;
6044 struct got_reference *ref = NULL;
6045 struct got_reflist_head refs;
6048 * Don't let the user create a reference name with a leading '-'.
6049 * While technically a valid reference name, this case is usually
6050 * an unintended typo.
6052 if (refname[0] == '-')
6053 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6055 TAILQ_INIT(&refs);
6056 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6057 if (err)
6058 goto done;
6059 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6060 &refs, repo);
6061 got_ref_list_free(&refs);
6062 if (err)
6063 goto done;
6065 err = got_ref_alloc(&ref, refname, id);
6066 if (err)
6067 goto done;
6069 err = got_ref_write(ref, repo);
6070 done:
6071 if (ref)
6072 got_ref_close(ref);
6073 free(id);
6074 return err;
6077 static const struct got_error *
6078 add_symref(struct got_repository *repo, const char *refname, const char *target)
6080 const struct got_error *err = NULL;
6081 struct got_reference *ref = NULL;
6082 struct got_reference *target_ref = NULL;
6085 * Don't let the user create a reference name with a leading '-'.
6086 * While technically a valid reference name, this case is usually
6087 * an unintended typo.
6089 if (refname[0] == '-')
6090 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6092 err = got_ref_open(&target_ref, repo, target, 0);
6093 if (err)
6094 return err;
6096 err = got_ref_alloc_symref(&ref, refname, target_ref);
6097 if (err)
6098 goto done;
6100 err = got_ref_write(ref, repo);
6101 done:
6102 if (target_ref)
6103 got_ref_close(target_ref);
6104 if (ref)
6105 got_ref_close(ref);
6106 return err;
6109 static const struct got_error *
6110 cmd_ref(int argc, char *argv[])
6112 const struct got_error *error = NULL;
6113 struct got_repository *repo = NULL;
6114 struct got_worktree *worktree = NULL;
6115 char *cwd = NULL, *repo_path = NULL;
6116 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6117 const char *obj_arg = NULL, *symref_target= NULL;
6118 char *refname = NULL;
6119 int *pack_fds = NULL;
6121 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6122 switch (ch) {
6123 case 'c':
6124 obj_arg = optarg;
6125 break;
6126 case 'd':
6127 do_delete = 1;
6128 break;
6129 case 'r':
6130 repo_path = realpath(optarg, NULL);
6131 if (repo_path == NULL)
6132 return got_error_from_errno2("realpath",
6133 optarg);
6134 got_path_strip_trailing_slashes(repo_path);
6135 break;
6136 case 'l':
6137 do_list = 1;
6138 break;
6139 case 's':
6140 symref_target = optarg;
6141 break;
6142 case 't':
6143 sort_by_time = 1;
6144 break;
6145 default:
6146 usage_ref();
6147 /* NOTREACHED */
6151 if (obj_arg && do_list)
6152 option_conflict('c', 'l');
6153 if (obj_arg && do_delete)
6154 option_conflict('c', 'd');
6155 if (obj_arg && symref_target)
6156 option_conflict('c', 's');
6157 if (symref_target && do_delete)
6158 option_conflict('s', 'd');
6159 if (symref_target && do_list)
6160 option_conflict('s', 'l');
6161 if (do_delete && do_list)
6162 option_conflict('d', 'l');
6163 if (sort_by_time && !do_list)
6164 errx(1, "-t option requires -l option");
6166 argc -= optind;
6167 argv += optind;
6169 if (do_list) {
6170 if (argc != 0 && argc != 1)
6171 usage_ref();
6172 if (argc == 1) {
6173 refname = strdup(argv[0]);
6174 if (refname == NULL) {
6175 error = got_error_from_errno("strdup");
6176 goto done;
6179 } else {
6180 if (argc != 1)
6181 usage_ref();
6182 refname = strdup(argv[0]);
6183 if (refname == NULL) {
6184 error = got_error_from_errno("strdup");
6185 goto done;
6189 if (refname)
6190 got_path_strip_trailing_slashes(refname);
6192 #ifndef PROFILE
6193 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6194 "sendfd unveil", NULL) == -1)
6195 err(1, "pledge");
6196 #endif
6197 cwd = getcwd(NULL, 0);
6198 if (cwd == NULL) {
6199 error = got_error_from_errno("getcwd");
6200 goto done;
6203 error = got_repo_pack_fds_open(&pack_fds);
6204 if (error != NULL)
6205 goto done;
6207 if (repo_path == NULL) {
6208 error = got_worktree_open(&worktree, cwd);
6209 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6210 goto done;
6211 else
6212 error = NULL;
6213 if (worktree) {
6214 repo_path =
6215 strdup(got_worktree_get_repo_path(worktree));
6216 if (repo_path == NULL)
6217 error = got_error_from_errno("strdup");
6218 if (error)
6219 goto done;
6220 } else {
6221 repo_path = strdup(cwd);
6222 if (repo_path == NULL) {
6223 error = got_error_from_errno("strdup");
6224 goto done;
6229 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6230 if (error != NULL)
6231 goto done;
6233 #ifndef PROFILE
6234 if (do_list) {
6235 /* Remove "cpath" promise. */
6236 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6237 NULL) == -1)
6238 err(1, "pledge");
6240 #endif
6242 error = apply_unveil(got_repo_get_path(repo), do_list,
6243 worktree ? got_worktree_get_root_path(worktree) : NULL);
6244 if (error)
6245 goto done;
6247 if (do_list)
6248 error = list_refs(repo, refname, sort_by_time);
6249 else if (do_delete)
6250 error = delete_ref_by_name(repo, refname);
6251 else if (symref_target)
6252 error = add_symref(repo, refname, symref_target);
6253 else {
6254 if (obj_arg == NULL)
6255 usage_ref();
6256 error = add_ref(repo, refname, obj_arg);
6258 done:
6259 free(refname);
6260 if (repo) {
6261 const struct got_error *close_err = got_repo_close(repo);
6262 if (error == NULL)
6263 error = close_err;
6265 if (worktree)
6266 got_worktree_close(worktree);
6267 if (pack_fds) {
6268 const struct got_error *pack_err =
6269 got_repo_pack_fds_close(pack_fds);
6270 if (error == NULL)
6271 error = pack_err;
6273 free(cwd);
6274 free(repo_path);
6275 return error;
6278 __dead static void
6279 usage_branch(void)
6281 fprintf(stderr,
6282 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6283 "[-n] [name]\n", getprogname());
6284 exit(1);
6287 static const struct got_error *
6288 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6289 struct got_reference *ref)
6291 const struct got_error *err = NULL;
6292 const char *refname, *marker = " ";
6293 char *refstr;
6295 refname = got_ref_get_name(ref);
6296 if (worktree && strcmp(refname,
6297 got_worktree_get_head_ref_name(worktree)) == 0) {
6298 struct got_object_id *id = NULL;
6300 err = got_ref_resolve(&id, repo, ref);
6301 if (err)
6302 return err;
6303 if (got_object_id_cmp(id,
6304 got_worktree_get_base_commit_id(worktree)) == 0)
6305 marker = "* ";
6306 else
6307 marker = "~ ";
6308 free(id);
6311 if (strncmp(refname, "refs/heads/", 11) == 0)
6312 refname += 11;
6313 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6314 refname += 18;
6315 if (strncmp(refname, "refs/remotes/", 13) == 0)
6316 refname += 13;
6318 refstr = got_ref_to_str(ref);
6319 if (refstr == NULL)
6320 return got_error_from_errno("got_ref_to_str");
6322 printf("%s%s: %s\n", marker, refname, refstr);
6323 free(refstr);
6324 return NULL;
6327 static const struct got_error *
6328 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6330 const char *refname;
6332 if (worktree == NULL)
6333 return got_error(GOT_ERR_NOT_WORKTREE);
6335 refname = got_worktree_get_head_ref_name(worktree);
6337 if (strncmp(refname, "refs/heads/", 11) == 0)
6338 refname += 11;
6339 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6340 refname += 18;
6342 printf("%s\n", refname);
6344 return NULL;
6347 static const struct got_error *
6348 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6349 int sort_by_time)
6351 static const struct got_error *err = NULL;
6352 struct got_reflist_head refs;
6353 struct got_reflist_entry *re;
6354 struct got_reference *temp_ref = NULL;
6355 int rebase_in_progress, histedit_in_progress;
6357 TAILQ_INIT(&refs);
6359 if (worktree) {
6360 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6361 worktree);
6362 if (err)
6363 return err;
6365 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6366 worktree);
6367 if (err)
6368 return err;
6370 if (rebase_in_progress || histedit_in_progress) {
6371 err = got_ref_open(&temp_ref, repo,
6372 got_worktree_get_head_ref_name(worktree), 0);
6373 if (err)
6374 return err;
6375 list_branch(repo, worktree, temp_ref);
6376 got_ref_close(temp_ref);
6380 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6381 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6382 repo);
6383 if (err)
6384 return err;
6386 TAILQ_FOREACH(re, &refs, entry)
6387 list_branch(repo, worktree, re->ref);
6389 got_ref_list_free(&refs);
6391 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6392 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6393 repo);
6394 if (err)
6395 return err;
6397 TAILQ_FOREACH(re, &refs, entry)
6398 list_branch(repo, worktree, re->ref);
6400 got_ref_list_free(&refs);
6402 return NULL;
6405 static const struct got_error *
6406 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6407 const char *branch_name)
6409 const struct got_error *err = NULL;
6410 struct got_reference *ref = NULL;
6411 char *refname, *remote_refname = NULL;
6413 if (strncmp(branch_name, "refs/", 5) == 0)
6414 branch_name += 5;
6415 if (strncmp(branch_name, "heads/", 6) == 0)
6416 branch_name += 6;
6417 else if (strncmp(branch_name, "remotes/", 8) == 0)
6418 branch_name += 8;
6420 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6421 return got_error_from_errno("asprintf");
6423 if (asprintf(&remote_refname, "refs/remotes/%s",
6424 branch_name) == -1) {
6425 err = got_error_from_errno("asprintf");
6426 goto done;
6429 err = got_ref_open(&ref, repo, refname, 0);
6430 if (err) {
6431 const struct got_error *err2;
6432 if (err->code != GOT_ERR_NOT_REF)
6433 goto done;
6435 * Keep 'err' intact such that if neither branch exists
6436 * we report "refs/heads" rather than "refs/remotes" in
6437 * our error message.
6439 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6440 if (err2)
6441 goto done;
6442 err = NULL;
6445 if (worktree &&
6446 strcmp(got_worktree_get_head_ref_name(worktree),
6447 got_ref_get_name(ref)) == 0) {
6448 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6449 "will not delete this work tree's current branch");
6450 goto done;
6453 err = delete_ref(repo, ref);
6454 done:
6455 if (ref)
6456 got_ref_close(ref);
6457 free(refname);
6458 free(remote_refname);
6459 return err;
6462 static const struct got_error *
6463 add_branch(struct got_repository *repo, const char *branch_name,
6464 struct got_object_id *base_commit_id)
6466 const struct got_error *err = NULL;
6467 struct got_reference *ref = NULL;
6468 char *base_refname = NULL, *refname = NULL;
6471 * Don't let the user create a branch name with a leading '-'.
6472 * While technically a valid reference name, this case is usually
6473 * an unintended typo.
6475 if (branch_name[0] == '-')
6476 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6478 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6479 branch_name += 11;
6481 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6482 err = got_error_from_errno("asprintf");
6483 goto done;
6486 err = got_ref_open(&ref, repo, refname, 0);
6487 if (err == NULL) {
6488 err = got_error(GOT_ERR_BRANCH_EXISTS);
6489 goto done;
6490 } else if (err->code != GOT_ERR_NOT_REF)
6491 goto done;
6493 err = got_ref_alloc(&ref, refname, base_commit_id);
6494 if (err)
6495 goto done;
6497 err = got_ref_write(ref, repo);
6498 done:
6499 if (ref)
6500 got_ref_close(ref);
6501 free(base_refname);
6502 free(refname);
6503 return err;
6506 static const struct got_error *
6507 cmd_branch(int argc, char *argv[])
6509 const struct got_error *error = NULL;
6510 struct got_repository *repo = NULL;
6511 struct got_worktree *worktree = NULL;
6512 char *cwd = NULL, *repo_path = NULL;
6513 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6514 const char *delref = NULL, *commit_id_arg = NULL;
6515 struct got_reference *ref = NULL;
6516 struct got_pathlist_head paths;
6517 struct got_pathlist_entry *pe;
6518 struct got_object_id *commit_id = NULL;
6519 char *commit_id_str = NULL;
6520 int *pack_fds = NULL;
6522 TAILQ_INIT(&paths);
6524 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6525 switch (ch) {
6526 case 'c':
6527 commit_id_arg = optarg;
6528 break;
6529 case 'd':
6530 delref = optarg;
6531 break;
6532 case 'r':
6533 repo_path = realpath(optarg, NULL);
6534 if (repo_path == NULL)
6535 return got_error_from_errno2("realpath",
6536 optarg);
6537 got_path_strip_trailing_slashes(repo_path);
6538 break;
6539 case 'l':
6540 do_list = 1;
6541 break;
6542 case 'n':
6543 do_update = 0;
6544 break;
6545 case 't':
6546 sort_by_time = 1;
6547 break;
6548 default:
6549 usage_branch();
6550 /* NOTREACHED */
6554 if (do_list && delref)
6555 option_conflict('l', 'd');
6556 if (sort_by_time && !do_list)
6557 errx(1, "-t option requires -l option");
6559 argc -= optind;
6560 argv += optind;
6562 if (!do_list && !delref && argc == 0)
6563 do_show = 1;
6565 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6566 errx(1, "-c option can only be used when creating a branch");
6568 if (do_list || delref) {
6569 if (argc > 0)
6570 usage_branch();
6571 } else if (!do_show && argc != 1)
6572 usage_branch();
6574 #ifndef PROFILE
6575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6576 "sendfd unveil", NULL) == -1)
6577 err(1, "pledge");
6578 #endif
6579 cwd = getcwd(NULL, 0);
6580 if (cwd == NULL) {
6581 error = got_error_from_errno("getcwd");
6582 goto done;
6585 error = got_repo_pack_fds_open(&pack_fds);
6586 if (error != NULL)
6587 goto done;
6589 if (repo_path == NULL) {
6590 error = got_worktree_open(&worktree, cwd);
6591 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6592 goto done;
6593 else
6594 error = NULL;
6595 if (worktree) {
6596 repo_path =
6597 strdup(got_worktree_get_repo_path(worktree));
6598 if (repo_path == NULL)
6599 error = got_error_from_errno("strdup");
6600 if (error)
6601 goto done;
6602 } else {
6603 repo_path = strdup(cwd);
6604 if (repo_path == NULL) {
6605 error = got_error_from_errno("strdup");
6606 goto done;
6611 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6612 if (error != NULL)
6613 goto done;
6615 #ifndef PROFILE
6616 if (do_list || do_show) {
6617 /* Remove "cpath" promise. */
6618 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6619 NULL) == -1)
6620 err(1, "pledge");
6622 #endif
6624 error = apply_unveil(got_repo_get_path(repo), do_list,
6625 worktree ? got_worktree_get_root_path(worktree) : NULL);
6626 if (error)
6627 goto done;
6629 if (do_show)
6630 error = show_current_branch(repo, worktree);
6631 else if (do_list)
6632 error = list_branches(repo, worktree, sort_by_time);
6633 else if (delref)
6634 error = delete_branch(repo, worktree, delref);
6635 else {
6636 struct got_reflist_head refs;
6637 TAILQ_INIT(&refs);
6638 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6639 NULL);
6640 if (error)
6641 goto done;
6642 if (commit_id_arg == NULL)
6643 commit_id_arg = worktree ?
6644 got_worktree_get_head_ref_name(worktree) :
6645 GOT_REF_HEAD;
6646 error = got_repo_match_object_id(&commit_id, NULL,
6647 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6648 got_ref_list_free(&refs);
6649 if (error)
6650 goto done;
6651 error = add_branch(repo, argv[0], commit_id);
6652 if (error)
6653 goto done;
6654 if (worktree && do_update) {
6655 struct got_update_progress_arg upa;
6656 char *branch_refname = NULL;
6658 error = got_object_id_str(&commit_id_str, commit_id);
6659 if (error)
6660 goto done;
6661 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6662 worktree);
6663 if (error)
6664 goto done;
6665 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6666 == -1) {
6667 error = got_error_from_errno("asprintf");
6668 goto done;
6670 error = got_ref_open(&ref, repo, branch_refname, 0);
6671 free(branch_refname);
6672 if (error)
6673 goto done;
6674 error = switch_head_ref(ref, commit_id, worktree,
6675 repo);
6676 if (error)
6677 goto done;
6678 error = got_worktree_set_base_commit_id(worktree, repo,
6679 commit_id);
6680 if (error)
6681 goto done;
6682 memset(&upa, 0, sizeof(upa));
6683 error = got_worktree_checkout_files(worktree, &paths,
6684 repo, update_progress, &upa, check_cancelled,
6685 NULL);
6686 if (error)
6687 goto done;
6688 if (upa.did_something) {
6689 printf("Updated to %s: %s\n",
6690 got_worktree_get_head_ref_name(worktree),
6691 commit_id_str);
6693 print_update_progress_stats(&upa);
6696 done:
6697 if (ref)
6698 got_ref_close(ref);
6699 if (repo) {
6700 const struct got_error *close_err = got_repo_close(repo);
6701 if (error == NULL)
6702 error = close_err;
6704 if (worktree)
6705 got_worktree_close(worktree);
6706 if (pack_fds) {
6707 const struct got_error *pack_err =
6708 got_repo_pack_fds_close(pack_fds);
6709 if (error == NULL)
6710 error = pack_err;
6712 free(cwd);
6713 free(repo_path);
6714 free(commit_id);
6715 free(commit_id_str);
6716 TAILQ_FOREACH(pe, &paths, entry)
6717 free((char *)pe->path);
6718 got_pathlist_free(&paths);
6719 return error;
6723 __dead static void
6724 usage_tag(void)
6726 fprintf(stderr,
6727 "usage: %s tag [-c commit] [-r repository] [-l] "
6728 "[-m message] name\n", getprogname());
6729 exit(1);
6732 #if 0
6733 static const struct got_error *
6734 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6736 const struct got_error *err = NULL;
6737 struct got_reflist_entry *re, *se, *new;
6738 struct got_object_id *re_id, *se_id;
6739 struct got_tag_object *re_tag, *se_tag;
6740 time_t re_time, se_time;
6742 STAILQ_FOREACH(re, tags, entry) {
6743 se = STAILQ_FIRST(sorted);
6744 if (se == NULL) {
6745 err = got_reflist_entry_dup(&new, re);
6746 if (err)
6747 return err;
6748 STAILQ_INSERT_HEAD(sorted, new, entry);
6749 continue;
6750 } else {
6751 err = got_ref_resolve(&re_id, repo, re->ref);
6752 if (err)
6753 break;
6754 err = got_object_open_as_tag(&re_tag, repo, re_id);
6755 free(re_id);
6756 if (err)
6757 break;
6758 re_time = got_object_tag_get_tagger_time(re_tag);
6759 got_object_tag_close(re_tag);
6762 while (se) {
6763 err = got_ref_resolve(&se_id, repo, re->ref);
6764 if (err)
6765 break;
6766 err = got_object_open_as_tag(&se_tag, repo, se_id);
6767 free(se_id);
6768 if (err)
6769 break;
6770 se_time = got_object_tag_get_tagger_time(se_tag);
6771 got_object_tag_close(se_tag);
6773 if (se_time > re_time) {
6774 err = got_reflist_entry_dup(&new, re);
6775 if (err)
6776 return err;
6777 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6778 break;
6780 se = STAILQ_NEXT(se, entry);
6781 continue;
6784 done:
6785 return err;
6787 #endif
6789 static const struct got_error *
6790 list_tags(struct got_repository *repo)
6792 static const struct got_error *err = NULL;
6793 struct got_reflist_head refs;
6794 struct got_reflist_entry *re;
6796 TAILQ_INIT(&refs);
6798 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6799 if (err)
6800 return err;
6802 TAILQ_FOREACH(re, &refs, entry) {
6803 const char *refname;
6804 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6805 char datebuf[26];
6806 const char *tagger;
6807 time_t tagger_time;
6808 struct got_object_id *id;
6809 struct got_tag_object *tag;
6810 struct got_commit_object *commit = NULL;
6812 refname = got_ref_get_name(re->ref);
6813 if (strncmp(refname, "refs/tags/", 10) != 0)
6814 continue;
6815 refname += 10;
6816 refstr = got_ref_to_str(re->ref);
6817 if (refstr == NULL) {
6818 err = got_error_from_errno("got_ref_to_str");
6819 break;
6821 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6822 free(refstr);
6824 err = got_ref_resolve(&id, repo, re->ref);
6825 if (err)
6826 break;
6827 err = got_object_open_as_tag(&tag, repo, id);
6828 if (err) {
6829 if (err->code != GOT_ERR_OBJ_TYPE) {
6830 free(id);
6831 break;
6833 /* "lightweight" tag */
6834 err = got_object_open_as_commit(&commit, repo, id);
6835 if (err) {
6836 free(id);
6837 break;
6839 tagger = got_object_commit_get_committer(commit);
6840 tagger_time =
6841 got_object_commit_get_committer_time(commit);
6842 err = got_object_id_str(&id_str, id);
6843 free(id);
6844 if (err)
6845 break;
6846 } else {
6847 free(id);
6848 tagger = got_object_tag_get_tagger(tag);
6849 tagger_time = got_object_tag_get_tagger_time(tag);
6850 err = got_object_id_str(&id_str,
6851 got_object_tag_get_object_id(tag));
6852 if (err)
6853 break;
6855 printf("from: %s\n", tagger);
6856 datestr = get_datestr(&tagger_time, datebuf);
6857 if (datestr)
6858 printf("date: %s UTC\n", datestr);
6859 if (commit)
6860 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6861 else {
6862 switch (got_object_tag_get_object_type(tag)) {
6863 case GOT_OBJ_TYPE_BLOB:
6864 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6865 id_str);
6866 break;
6867 case GOT_OBJ_TYPE_TREE:
6868 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6869 id_str);
6870 break;
6871 case GOT_OBJ_TYPE_COMMIT:
6872 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6873 id_str);
6874 break;
6875 case GOT_OBJ_TYPE_TAG:
6876 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6877 id_str);
6878 break;
6879 default:
6880 break;
6883 free(id_str);
6884 if (commit) {
6885 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6886 if (err)
6887 break;
6888 got_object_commit_close(commit);
6889 } else {
6890 tagmsg0 = strdup(got_object_tag_get_message(tag));
6891 got_object_tag_close(tag);
6892 if (tagmsg0 == NULL) {
6893 err = got_error_from_errno("strdup");
6894 break;
6898 tagmsg = tagmsg0;
6899 do {
6900 line = strsep(&tagmsg, "\n");
6901 if (line)
6902 printf(" %s\n", line);
6903 } while (line);
6904 free(tagmsg0);
6907 got_ref_list_free(&refs);
6908 return NULL;
6911 static const struct got_error *
6912 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6913 const char *tag_name, const char *repo_path)
6915 const struct got_error *err = NULL;
6916 char *template = NULL, *initial_content = NULL;
6917 char *editor = NULL;
6918 int initial_content_len;
6919 int fd = -1;
6921 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6922 err = got_error_from_errno("asprintf");
6923 goto done;
6926 initial_content_len = asprintf(&initial_content,
6927 "\n# tagging commit %s as %s\n",
6928 commit_id_str, tag_name);
6929 if (initial_content_len == -1) {
6930 err = got_error_from_errno("asprintf");
6931 goto done;
6934 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6935 if (err)
6936 goto done;
6938 if (write(fd, initial_content, initial_content_len) == -1) {
6939 err = got_error_from_errno2("write", *tagmsg_path);
6940 goto done;
6943 err = get_editor(&editor);
6944 if (err)
6945 goto done;
6946 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6947 initial_content_len, 1);
6948 done:
6949 free(initial_content);
6950 free(template);
6951 free(editor);
6953 if (fd != -1 && close(fd) == -1 && err == NULL)
6954 err = got_error_from_errno2("close", *tagmsg_path);
6956 /* Editor is done; we can now apply unveil(2) */
6957 if (err == NULL)
6958 err = apply_unveil(repo_path, 0, NULL);
6959 if (err) {
6960 free(*tagmsg);
6961 *tagmsg = NULL;
6963 return err;
6966 static const struct got_error *
6967 add_tag(struct got_repository *repo, const char *tagger,
6968 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6970 const struct got_error *err = NULL;
6971 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6972 char *label = NULL, *commit_id_str = NULL;
6973 struct got_reference *ref = NULL;
6974 char *refname = NULL, *tagmsg = NULL;
6975 char *tagmsg_path = NULL, *tag_id_str = NULL;
6976 int preserve_tagmsg = 0;
6977 struct got_reflist_head refs;
6979 TAILQ_INIT(&refs);
6982 * Don't let the user create a tag name with a leading '-'.
6983 * While technically a valid reference name, this case is usually
6984 * an unintended typo.
6986 if (tag_name[0] == '-')
6987 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6989 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6990 if (err)
6991 goto done;
6993 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6994 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6995 if (err)
6996 goto done;
6998 err = got_object_id_str(&commit_id_str, commit_id);
6999 if (err)
7000 goto done;
7002 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7003 refname = strdup(tag_name);
7004 if (refname == NULL) {
7005 err = got_error_from_errno("strdup");
7006 goto done;
7008 tag_name += 10;
7009 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
7010 err = got_error_from_errno("asprintf");
7011 goto done;
7014 err = got_ref_open(&ref, repo, refname, 0);
7015 if (err == NULL) {
7016 err = got_error(GOT_ERR_TAG_EXISTS);
7017 goto done;
7018 } else if (err->code != GOT_ERR_NOT_REF)
7019 goto done;
7021 if (tagmsg_arg == NULL) {
7022 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7023 tag_name, got_repo_get_path(repo));
7024 if (err) {
7025 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7026 tagmsg_path != NULL)
7027 preserve_tagmsg = 1;
7028 goto done;
7032 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7033 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7034 if (err) {
7035 if (tagmsg_path)
7036 preserve_tagmsg = 1;
7037 goto done;
7040 err = got_ref_alloc(&ref, refname, tag_id);
7041 if (err) {
7042 if (tagmsg_path)
7043 preserve_tagmsg = 1;
7044 goto done;
7047 err = got_ref_write(ref, repo);
7048 if (err) {
7049 if (tagmsg_path)
7050 preserve_tagmsg = 1;
7051 goto done;
7054 err = got_object_id_str(&tag_id_str, tag_id);
7055 if (err) {
7056 if (tagmsg_path)
7057 preserve_tagmsg = 1;
7058 goto done;
7060 printf("Created tag %s\n", tag_id_str);
7061 done:
7062 if (preserve_tagmsg) {
7063 fprintf(stderr, "%s: tag message preserved in %s\n",
7064 getprogname(), tagmsg_path);
7065 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7066 err = got_error_from_errno2("unlink", tagmsg_path);
7067 free(tag_id_str);
7068 if (ref)
7069 got_ref_close(ref);
7070 free(commit_id);
7071 free(commit_id_str);
7072 free(refname);
7073 free(tagmsg);
7074 free(tagmsg_path);
7075 got_ref_list_free(&refs);
7076 return err;
7079 static const struct got_error *
7080 cmd_tag(int argc, char *argv[])
7082 const struct got_error *error = NULL;
7083 struct got_repository *repo = NULL;
7084 struct got_worktree *worktree = NULL;
7085 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7086 char *gitconfig_path = NULL, *tagger = NULL;
7087 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
7088 int ch, do_list = 0;
7089 int *pack_fds = NULL;
7091 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7092 switch (ch) {
7093 case 'c':
7094 commit_id_arg = optarg;
7095 break;
7096 case 'm':
7097 tagmsg = optarg;
7098 break;
7099 case 'r':
7100 repo_path = realpath(optarg, NULL);
7101 if (repo_path == NULL)
7102 return got_error_from_errno2("realpath",
7103 optarg);
7104 got_path_strip_trailing_slashes(repo_path);
7105 break;
7106 case 'l':
7107 do_list = 1;
7108 break;
7109 default:
7110 usage_tag();
7111 /* NOTREACHED */
7115 argc -= optind;
7116 argv += optind;
7118 if (do_list) {
7119 if (commit_id_arg != NULL)
7120 errx(1,
7121 "-c option can only be used when creating a tag");
7122 if (tagmsg)
7123 option_conflict('l', 'm');
7124 if (argc > 0)
7125 usage_tag();
7126 } else if (argc != 1)
7127 usage_tag();
7129 tag_name = argv[0];
7131 #ifndef PROFILE
7132 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7133 "sendfd unveil", NULL) == -1)
7134 err(1, "pledge");
7135 #endif
7136 cwd = getcwd(NULL, 0);
7137 if (cwd == NULL) {
7138 error = got_error_from_errno("getcwd");
7139 goto done;
7142 error = got_repo_pack_fds_open(&pack_fds);
7143 if (error != NULL)
7144 goto done;
7146 if (repo_path == NULL) {
7147 error = got_worktree_open(&worktree, cwd);
7148 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7149 goto done;
7150 else
7151 error = NULL;
7152 if (worktree) {
7153 repo_path =
7154 strdup(got_worktree_get_repo_path(worktree));
7155 if (repo_path == NULL)
7156 error = got_error_from_errno("strdup");
7157 if (error)
7158 goto done;
7159 } else {
7160 repo_path = strdup(cwd);
7161 if (repo_path == NULL) {
7162 error = got_error_from_errno("strdup");
7163 goto done;
7168 if (do_list) {
7169 if (worktree) {
7170 /* Release work tree lock. */
7171 got_worktree_close(worktree);
7172 worktree = NULL;
7174 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7175 if (error != NULL)
7176 goto done;
7178 #ifndef PROFILE
7179 /* Remove "cpath" promise. */
7180 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7181 NULL) == -1)
7182 err(1, "pledge");
7183 #endif
7184 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7185 if (error)
7186 goto done;
7187 error = list_tags(repo);
7188 } else {
7189 error = get_gitconfig_path(&gitconfig_path);
7190 if (error)
7191 goto done;
7192 error = got_repo_open(&repo, repo_path, gitconfig_path,
7193 pack_fds);
7194 if (error != NULL)
7195 goto done;
7197 error = get_author(&tagger, repo, worktree);
7198 if (error)
7199 goto done;
7200 if (worktree) {
7201 /* Release work tree lock. */
7202 got_worktree_close(worktree);
7203 worktree = NULL;
7206 if (tagmsg) {
7207 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7208 if (error)
7209 goto done;
7212 if (commit_id_arg == NULL) {
7213 struct got_reference *head_ref;
7214 struct got_object_id *commit_id;
7215 error = got_ref_open(&head_ref, repo,
7216 worktree ? got_worktree_get_head_ref_name(worktree)
7217 : GOT_REF_HEAD, 0);
7218 if (error)
7219 goto done;
7220 error = got_ref_resolve(&commit_id, repo, head_ref);
7221 got_ref_close(head_ref);
7222 if (error)
7223 goto done;
7224 error = got_object_id_str(&commit_id_str, commit_id);
7225 free(commit_id);
7226 if (error)
7227 goto done;
7230 error = add_tag(repo, tagger, tag_name,
7231 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7233 done:
7234 if (repo) {
7235 const struct got_error *close_err = got_repo_close(repo);
7236 if (error == NULL)
7237 error = close_err;
7239 if (worktree)
7240 got_worktree_close(worktree);
7241 if (pack_fds) {
7242 const struct got_error *pack_err =
7243 got_repo_pack_fds_close(pack_fds);
7244 if (error == NULL)
7245 error = pack_err;
7247 free(cwd);
7248 free(repo_path);
7249 free(gitconfig_path);
7250 free(commit_id_str);
7251 free(tagger);
7252 return error;
7255 __dead static void
7256 usage_add(void)
7258 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7259 getprogname());
7260 exit(1);
7263 static const struct got_error *
7264 add_progress(void *arg, unsigned char status, const char *path)
7266 while (path[0] == '/')
7267 path++;
7268 printf("%c %s\n", status, path);
7269 return NULL;
7272 static const struct got_error *
7273 cmd_add(int argc, char *argv[])
7275 const struct got_error *error = NULL;
7276 struct got_repository *repo = NULL;
7277 struct got_worktree *worktree = NULL;
7278 char *cwd = NULL;
7279 struct got_pathlist_head paths;
7280 struct got_pathlist_entry *pe;
7281 int ch, can_recurse = 0, no_ignores = 0;
7282 int *pack_fds = NULL;
7284 TAILQ_INIT(&paths);
7286 while ((ch = getopt(argc, argv, "IR")) != -1) {
7287 switch (ch) {
7288 case 'I':
7289 no_ignores = 1;
7290 break;
7291 case 'R':
7292 can_recurse = 1;
7293 break;
7294 default:
7295 usage_add();
7296 /* NOTREACHED */
7300 argc -= optind;
7301 argv += optind;
7303 #ifndef PROFILE
7304 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7305 NULL) == -1)
7306 err(1, "pledge");
7307 #endif
7308 if (argc < 1)
7309 usage_add();
7311 cwd = getcwd(NULL, 0);
7312 if (cwd == NULL) {
7313 error = got_error_from_errno("getcwd");
7314 goto done;
7317 error = got_repo_pack_fds_open(&pack_fds);
7318 if (error != NULL)
7319 goto done;
7321 error = got_worktree_open(&worktree, cwd);
7322 if (error) {
7323 if (error->code == GOT_ERR_NOT_WORKTREE)
7324 error = wrap_not_worktree_error(error, "add", cwd);
7325 goto done;
7328 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7329 NULL, pack_fds);
7330 if (error != NULL)
7331 goto done;
7333 error = apply_unveil(got_repo_get_path(repo), 1,
7334 got_worktree_get_root_path(worktree));
7335 if (error)
7336 goto done;
7338 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7339 if (error)
7340 goto done;
7342 if (!can_recurse) {
7343 char *ondisk_path;
7344 struct stat sb;
7345 TAILQ_FOREACH(pe, &paths, entry) {
7346 if (asprintf(&ondisk_path, "%s/%s",
7347 got_worktree_get_root_path(worktree),
7348 pe->path) == -1) {
7349 error = got_error_from_errno("asprintf");
7350 goto done;
7352 if (lstat(ondisk_path, &sb) == -1) {
7353 if (errno == ENOENT) {
7354 free(ondisk_path);
7355 continue;
7357 error = got_error_from_errno2("lstat",
7358 ondisk_path);
7359 free(ondisk_path);
7360 goto done;
7362 free(ondisk_path);
7363 if (S_ISDIR(sb.st_mode)) {
7364 error = got_error_msg(GOT_ERR_BAD_PATH,
7365 "adding directories requires -R option");
7366 goto done;
7371 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7372 NULL, repo, no_ignores);
7373 done:
7374 if (repo) {
7375 const struct got_error *close_err = got_repo_close(repo);
7376 if (error == NULL)
7377 error = close_err;
7379 if (worktree)
7380 got_worktree_close(worktree);
7381 if (pack_fds) {
7382 const struct got_error *pack_err =
7383 got_repo_pack_fds_close(pack_fds);
7384 if (error == NULL)
7385 error = pack_err;
7387 TAILQ_FOREACH(pe, &paths, entry)
7388 free((char *)pe->path);
7389 got_pathlist_free(&paths);
7390 free(cwd);
7391 return error;
7394 __dead static void
7395 usage_remove(void)
7397 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7398 "path ...\n", getprogname());
7399 exit(1);
7402 static const struct got_error *
7403 print_remove_status(void *arg, unsigned char status,
7404 unsigned char staged_status, const char *path)
7406 while (path[0] == '/')
7407 path++;
7408 if (status == GOT_STATUS_NONEXISTENT)
7409 return NULL;
7410 if (status == staged_status && (status == GOT_STATUS_DELETE))
7411 status = GOT_STATUS_NO_CHANGE;
7412 printf("%c%c %s\n", status, staged_status, path);
7413 return NULL;
7416 static const struct got_error *
7417 cmd_remove(int argc, char *argv[])
7419 const struct got_error *error = NULL;
7420 struct got_worktree *worktree = NULL;
7421 struct got_repository *repo = NULL;
7422 const char *status_codes = NULL;
7423 char *cwd = NULL;
7424 struct got_pathlist_head paths;
7425 struct got_pathlist_entry *pe;
7426 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7427 int ignore_missing_paths = 0;
7428 int *pack_fds = NULL;
7430 TAILQ_INIT(&paths);
7432 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7433 switch (ch) {
7434 case 'f':
7435 delete_local_mods = 1;
7436 ignore_missing_paths = 1;
7437 break;
7438 case 'k':
7439 keep_on_disk = 1;
7440 break;
7441 case 'R':
7442 can_recurse = 1;
7443 break;
7444 case 's':
7445 for (i = 0; i < strlen(optarg); i++) {
7446 switch (optarg[i]) {
7447 case GOT_STATUS_MODIFY:
7448 delete_local_mods = 1;
7449 break;
7450 case GOT_STATUS_MISSING:
7451 ignore_missing_paths = 1;
7452 break;
7453 default:
7454 errx(1, "invalid status code '%c'",
7455 optarg[i]);
7458 status_codes = optarg;
7459 break;
7460 default:
7461 usage_remove();
7462 /* NOTREACHED */
7466 argc -= optind;
7467 argv += optind;
7469 #ifndef PROFILE
7470 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7471 NULL) == -1)
7472 err(1, "pledge");
7473 #endif
7474 if (argc < 1)
7475 usage_remove();
7477 cwd = getcwd(NULL, 0);
7478 if (cwd == NULL) {
7479 error = got_error_from_errno("getcwd");
7480 goto done;
7483 error = got_repo_pack_fds_open(&pack_fds);
7484 if (error != NULL)
7485 goto done;
7487 error = got_worktree_open(&worktree, cwd);
7488 if (error) {
7489 if (error->code == GOT_ERR_NOT_WORKTREE)
7490 error = wrap_not_worktree_error(error, "remove", cwd);
7491 goto done;
7494 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7495 NULL, pack_fds);
7496 if (error)
7497 goto done;
7499 error = apply_unveil(got_repo_get_path(repo), 1,
7500 got_worktree_get_root_path(worktree));
7501 if (error)
7502 goto done;
7504 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7505 if (error)
7506 goto done;
7508 if (!can_recurse) {
7509 char *ondisk_path;
7510 struct stat sb;
7511 TAILQ_FOREACH(pe, &paths, entry) {
7512 if (asprintf(&ondisk_path, "%s/%s",
7513 got_worktree_get_root_path(worktree),
7514 pe->path) == -1) {
7515 error = got_error_from_errno("asprintf");
7516 goto done;
7518 if (lstat(ondisk_path, &sb) == -1) {
7519 if (errno == ENOENT) {
7520 free(ondisk_path);
7521 continue;
7523 error = got_error_from_errno2("lstat",
7524 ondisk_path);
7525 free(ondisk_path);
7526 goto done;
7528 free(ondisk_path);
7529 if (S_ISDIR(sb.st_mode)) {
7530 error = got_error_msg(GOT_ERR_BAD_PATH,
7531 "removing directories requires -R option");
7532 goto done;
7537 error = got_worktree_schedule_delete(worktree, &paths,
7538 delete_local_mods, status_codes, print_remove_status, NULL,
7539 repo, keep_on_disk, ignore_missing_paths);
7540 done:
7541 if (repo) {
7542 const struct got_error *close_err = got_repo_close(repo);
7543 if (error == NULL)
7544 error = close_err;
7546 if (worktree)
7547 got_worktree_close(worktree);
7548 if (pack_fds) {
7549 const struct got_error *pack_err =
7550 got_repo_pack_fds_close(pack_fds);
7551 if (error == NULL)
7552 error = pack_err;
7554 TAILQ_FOREACH(pe, &paths, entry)
7555 free((char *)pe->path);
7556 got_pathlist_free(&paths);
7557 free(cwd);
7558 return error;
7561 __dead static void
7562 usage_patch(void)
7564 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7565 "[-R] [patchfile]\n", getprogname());
7566 exit(1);
7569 static const struct got_error *
7570 patch_from_stdin(int *patchfd)
7572 const struct got_error *err = NULL;
7573 ssize_t r;
7574 char *path, buf[BUFSIZ];
7575 sig_t sighup, sigint, sigquit;
7577 err = got_opentemp_named_fd(&path, patchfd,
7578 GOT_TMPDIR_STR "/got-patch");
7579 if (err)
7580 return err;
7581 unlink(path);
7582 free(path);
7584 sighup = signal(SIGHUP, SIG_DFL);
7585 sigint = signal(SIGINT, SIG_DFL);
7586 sigquit = signal(SIGQUIT, SIG_DFL);
7588 for (;;) {
7589 r = read(0, buf, sizeof(buf));
7590 if (r == -1) {
7591 err = got_error_from_errno("read");
7592 break;
7594 if (r == 0)
7595 break;
7596 if (write(*patchfd, buf, r) == -1) {
7597 err = got_error_from_errno("write");
7598 break;
7602 signal(SIGHUP, sighup);
7603 signal(SIGINT, sigint);
7604 signal(SIGQUIT, sigquit);
7606 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7607 err = got_error_from_errno("lseek");
7609 if (err != NULL) {
7610 close(*patchfd);
7611 *patchfd = -1;
7614 return err;
7617 static const struct got_error *
7618 patch_progress(void *arg, const char *old, const char *new,
7619 unsigned char status, const struct got_error *error, long old_from,
7620 long old_lines, long new_from, long new_lines, long offset,
7621 const struct got_error *hunk_err)
7623 const char *path = new == NULL ? old : new;
7625 while (*path == '/')
7626 path++;
7628 if (status != 0)
7629 printf("%c %s\n", status, path);
7631 if (error != NULL)
7632 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7634 if (offset != 0 || hunk_err != NULL) {
7635 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7636 old_lines, new_from, new_lines);
7637 if (hunk_err != NULL)
7638 printf("%s\n", hunk_err->msg);
7639 else
7640 printf("applied with offset %ld\n", offset);
7643 return NULL;
7646 static const struct got_error *
7647 cmd_patch(int argc, char *argv[])
7649 const struct got_error *error = NULL, *close_error = NULL;
7650 struct got_worktree *worktree = NULL;
7651 struct got_repository *repo = NULL;
7652 const char *errstr;
7653 char *cwd = NULL;
7654 int ch, nop = 0, strip = -1, reverse = 0;
7655 int patchfd;
7656 int *pack_fds = NULL;
7658 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7659 switch (ch) {
7660 case 'n':
7661 nop = 1;
7662 break;
7663 case 'p':
7664 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7665 if (errstr != NULL)
7666 errx(1, "pathname strip count is %s: %s",
7667 errstr, optarg);
7668 break;
7669 case 'R':
7670 reverse = 1;
7671 break;
7672 default:
7673 usage_patch();
7674 /* NOTREACHED */
7678 argc -= optind;
7679 argv += optind;
7681 if (argc == 0) {
7682 error = patch_from_stdin(&patchfd);
7683 if (error)
7684 return error;
7685 } else if (argc == 1) {
7686 patchfd = open(argv[0], O_RDONLY);
7687 if (patchfd == -1) {
7688 error = got_error_from_errno2("open", argv[0]);
7689 return error;
7691 } else
7692 usage_patch();
7694 if ((cwd = getcwd(NULL, 0)) == NULL) {
7695 error = got_error_from_errno("getcwd");
7696 goto done;
7699 error = got_repo_pack_fds_open(&pack_fds);
7700 if (error != NULL)
7701 goto done;
7703 error = got_worktree_open(&worktree, cwd);
7704 if (error != NULL)
7705 goto done;
7707 const char *repo_path = got_worktree_get_repo_path(worktree);
7708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7709 if (error != NULL)
7710 goto done;
7712 error = apply_unveil(got_repo_get_path(repo), 0,
7713 got_worktree_get_root_path(worktree));
7714 if (error != NULL)
7715 goto done;
7717 #ifndef PROFILE
7718 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7719 NULL) == -1)
7720 err(1, "pledge");
7721 #endif
7723 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7724 &patch_progress, NULL, check_cancelled, NULL);
7726 done:
7727 if (repo) {
7728 close_error = got_repo_close(repo);
7729 if (error == NULL)
7730 error = close_error;
7732 if (worktree != NULL) {
7733 close_error = got_worktree_close(worktree);
7734 if (error == NULL)
7735 error = close_error;
7737 if (pack_fds) {
7738 const struct got_error *pack_err =
7739 got_repo_pack_fds_close(pack_fds);
7740 if (error == NULL)
7741 error = pack_err;
7743 free(cwd);
7744 return error;
7747 __dead static void
7748 usage_revert(void)
7750 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7751 "path ...\n", getprogname());
7752 exit(1);
7755 static const struct got_error *
7756 revert_progress(void *arg, unsigned char status, const char *path)
7758 if (status == GOT_STATUS_UNVERSIONED)
7759 return NULL;
7761 while (path[0] == '/')
7762 path++;
7763 printf("%c %s\n", status, path);
7764 return NULL;
7767 struct choose_patch_arg {
7768 FILE *patch_script_file;
7769 const char *action;
7772 static const struct got_error *
7773 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7774 int nchanges, const char *action)
7776 const struct got_error *err;
7777 char *line = NULL;
7778 size_t linesize = 0;
7779 ssize_t linelen;
7781 switch (status) {
7782 case GOT_STATUS_ADD:
7783 printf("A %s\n%s this addition? [y/n] ", path, action);
7784 break;
7785 case GOT_STATUS_DELETE:
7786 printf("D %s\n%s this deletion? [y/n] ", path, action);
7787 break;
7788 case GOT_STATUS_MODIFY:
7789 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7790 return got_error_from_errno("fseek");
7791 printf(GOT_COMMIT_SEP_STR);
7792 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7793 printf("%s", line);
7794 if (linelen == -1 && ferror(patch_file)) {
7795 err = got_error_from_errno("getline");
7796 free(line);
7797 return err;
7799 free(line);
7800 printf(GOT_COMMIT_SEP_STR);
7801 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7802 path, n, nchanges, action);
7803 break;
7804 default:
7805 return got_error_path(path, GOT_ERR_FILE_STATUS);
7808 return NULL;
7811 static const struct got_error *
7812 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7813 FILE *patch_file, int n, int nchanges)
7815 const struct got_error *err = NULL;
7816 char *line = NULL;
7817 size_t linesize = 0;
7818 ssize_t linelen;
7819 int resp = ' ';
7820 struct choose_patch_arg *a = arg;
7822 *choice = GOT_PATCH_CHOICE_NONE;
7824 if (a->patch_script_file) {
7825 char *nl;
7826 err = show_change(status, path, patch_file, n, nchanges,
7827 a->action);
7828 if (err)
7829 return err;
7830 linelen = getline(&line, &linesize, a->patch_script_file);
7831 if (linelen == -1) {
7832 if (ferror(a->patch_script_file))
7833 return got_error_from_errno("getline");
7834 return NULL;
7836 nl = strchr(line, '\n');
7837 if (nl)
7838 *nl = '\0';
7839 if (strcmp(line, "y") == 0) {
7840 *choice = GOT_PATCH_CHOICE_YES;
7841 printf("y\n");
7842 } else if (strcmp(line, "n") == 0) {
7843 *choice = GOT_PATCH_CHOICE_NO;
7844 printf("n\n");
7845 } else if (strcmp(line, "q") == 0 &&
7846 status == GOT_STATUS_MODIFY) {
7847 *choice = GOT_PATCH_CHOICE_QUIT;
7848 printf("q\n");
7849 } else
7850 printf("invalid response '%s'\n", line);
7851 free(line);
7852 return NULL;
7855 while (resp != 'y' && resp != 'n' && resp != 'q') {
7856 err = show_change(status, path, patch_file, n, nchanges,
7857 a->action);
7858 if (err)
7859 return err;
7860 resp = getchar();
7861 if (resp == '\n')
7862 resp = getchar();
7863 if (status == GOT_STATUS_MODIFY) {
7864 if (resp != 'y' && resp != 'n' && resp != 'q') {
7865 printf("invalid response '%c'\n", resp);
7866 resp = ' ';
7868 } else if (resp != 'y' && resp != 'n') {
7869 printf("invalid response '%c'\n", resp);
7870 resp = ' ';
7874 if (resp == 'y')
7875 *choice = GOT_PATCH_CHOICE_YES;
7876 else if (resp == 'n')
7877 *choice = GOT_PATCH_CHOICE_NO;
7878 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7879 *choice = GOT_PATCH_CHOICE_QUIT;
7881 return NULL;
7884 static const struct got_error *
7885 cmd_revert(int argc, char *argv[])
7887 const struct got_error *error = NULL;
7888 struct got_worktree *worktree = NULL;
7889 struct got_repository *repo = NULL;
7890 char *cwd = NULL, *path = NULL;
7891 struct got_pathlist_head paths;
7892 struct got_pathlist_entry *pe;
7893 int ch, can_recurse = 0, pflag = 0;
7894 FILE *patch_script_file = NULL;
7895 const char *patch_script_path = NULL;
7896 struct choose_patch_arg cpa;
7897 int *pack_fds = NULL;
7899 TAILQ_INIT(&paths);
7901 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7902 switch (ch) {
7903 case 'p':
7904 pflag = 1;
7905 break;
7906 case 'F':
7907 patch_script_path = optarg;
7908 break;
7909 case 'R':
7910 can_recurse = 1;
7911 break;
7912 default:
7913 usage_revert();
7914 /* NOTREACHED */
7918 argc -= optind;
7919 argv += optind;
7921 #ifndef PROFILE
7922 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7923 "unveil", NULL) == -1)
7924 err(1, "pledge");
7925 #endif
7926 if (argc < 1)
7927 usage_revert();
7928 if (patch_script_path && !pflag)
7929 errx(1, "-F option can only be used together with -p option");
7931 cwd = getcwd(NULL, 0);
7932 if (cwd == NULL) {
7933 error = got_error_from_errno("getcwd");
7934 goto done;
7937 error = got_repo_pack_fds_open(&pack_fds);
7938 if (error != NULL)
7939 goto done;
7941 error = got_worktree_open(&worktree, cwd);
7942 if (error) {
7943 if (error->code == GOT_ERR_NOT_WORKTREE)
7944 error = wrap_not_worktree_error(error, "revert", cwd);
7945 goto done;
7948 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7949 NULL, pack_fds);
7950 if (error != NULL)
7951 goto done;
7953 if (patch_script_path) {
7954 patch_script_file = fopen(patch_script_path, "re");
7955 if (patch_script_file == NULL) {
7956 error = got_error_from_errno2("fopen",
7957 patch_script_path);
7958 goto done;
7961 error = apply_unveil(got_repo_get_path(repo), 1,
7962 got_worktree_get_root_path(worktree));
7963 if (error)
7964 goto done;
7966 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7967 if (error)
7968 goto done;
7970 if (!can_recurse) {
7971 char *ondisk_path;
7972 struct stat sb;
7973 TAILQ_FOREACH(pe, &paths, entry) {
7974 if (asprintf(&ondisk_path, "%s/%s",
7975 got_worktree_get_root_path(worktree),
7976 pe->path) == -1) {
7977 error = got_error_from_errno("asprintf");
7978 goto done;
7980 if (lstat(ondisk_path, &sb) == -1) {
7981 if (errno == ENOENT) {
7982 free(ondisk_path);
7983 continue;
7985 error = got_error_from_errno2("lstat",
7986 ondisk_path);
7987 free(ondisk_path);
7988 goto done;
7990 free(ondisk_path);
7991 if (S_ISDIR(sb.st_mode)) {
7992 error = got_error_msg(GOT_ERR_BAD_PATH,
7993 "reverting directories requires -R option");
7994 goto done;
7999 cpa.patch_script_file = patch_script_file;
8000 cpa.action = "revert";
8001 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8002 pflag ? choose_patch : NULL, &cpa, repo);
8003 done:
8004 if (patch_script_file && fclose(patch_script_file) == EOF &&
8005 error == NULL)
8006 error = got_error_from_errno2("fclose", patch_script_path);
8007 if (repo) {
8008 const struct got_error *close_err = got_repo_close(repo);
8009 if (error == NULL)
8010 error = close_err;
8012 if (worktree)
8013 got_worktree_close(worktree);
8014 if (pack_fds) {
8015 const struct got_error *pack_err =
8016 got_repo_pack_fds_close(pack_fds);
8017 if (error == NULL)
8018 error = pack_err;
8020 free(path);
8021 free(cwd);
8022 return error;
8025 __dead static void
8026 usage_commit(void)
8028 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8029 "[path ...]\n", getprogname());
8030 exit(1);
8033 struct collect_commit_logmsg_arg {
8034 const char *cmdline_log;
8035 const char *prepared_log;
8036 int non_interactive;
8037 const char *editor;
8038 const char *worktree_path;
8039 const char *branch_name;
8040 const char *repo_path;
8041 char *logmsg_path;
8045 static const struct got_error *
8046 read_prepared_logmsg(char **logmsg, const char *path)
8048 const struct got_error *err = NULL;
8049 FILE *f = NULL;
8050 struct stat sb;
8051 size_t r;
8053 *logmsg = NULL;
8054 memset(&sb, 0, sizeof(sb));
8056 f = fopen(path, "re");
8057 if (f == NULL)
8058 return got_error_from_errno2("fopen", path);
8060 if (fstat(fileno(f), &sb) == -1) {
8061 err = got_error_from_errno2("fstat", path);
8062 goto done;
8064 if (sb.st_size == 0) {
8065 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8066 goto done;
8069 *logmsg = malloc(sb.st_size + 1);
8070 if (*logmsg == NULL) {
8071 err = got_error_from_errno("malloc");
8072 goto done;
8075 r = fread(*logmsg, 1, sb.st_size, f);
8076 if (r != sb.st_size) {
8077 if (ferror(f))
8078 err = got_error_from_errno2("fread", path);
8079 else
8080 err = got_error(GOT_ERR_IO);
8081 goto done;
8083 (*logmsg)[sb.st_size] = '\0';
8084 done:
8085 if (fclose(f) == EOF && err == NULL)
8086 err = got_error_from_errno2("fclose", path);
8087 if (err) {
8088 free(*logmsg);
8089 *logmsg = NULL;
8091 return err;
8095 static const struct got_error *
8096 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8097 void *arg)
8099 char *initial_content = NULL;
8100 struct got_pathlist_entry *pe;
8101 const struct got_error *err = NULL;
8102 char *template = NULL;
8103 struct collect_commit_logmsg_arg *a = arg;
8104 int initial_content_len;
8105 int fd = -1;
8106 size_t len;
8108 /* if a message was specified on the command line, just use it */
8109 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8110 len = strlen(a->cmdline_log) + 1;
8111 *logmsg = malloc(len + 1);
8112 if (*logmsg == NULL)
8113 return got_error_from_errno("malloc");
8114 strlcpy(*logmsg, a->cmdline_log, len);
8115 return NULL;
8116 } else if (a->prepared_log != NULL && a->non_interactive)
8117 return read_prepared_logmsg(logmsg, a->prepared_log);
8119 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8120 return got_error_from_errno("asprintf");
8122 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8123 if (err)
8124 goto done;
8126 if (a->prepared_log) {
8127 char *msg;
8128 err = read_prepared_logmsg(&msg, a->prepared_log);
8129 if (err)
8130 goto done;
8131 if (write(fd, msg, strlen(msg)) == -1) {
8132 err = got_error_from_errno2("write", a->logmsg_path);
8133 free(msg);
8134 goto done;
8136 free(msg);
8139 initial_content_len = asprintf(&initial_content,
8140 "\n# changes to be committed on branch %s:\n",
8141 a->branch_name);
8142 if (initial_content_len == -1) {
8143 err = got_error_from_errno("asprintf");
8144 goto done;
8147 if (write(fd, initial_content, initial_content_len) == -1) {
8148 err = got_error_from_errno2("write", a->logmsg_path);
8149 goto done;
8152 TAILQ_FOREACH(pe, commitable_paths, entry) {
8153 struct got_commitable *ct = pe->data;
8154 dprintf(fd, "# %c %s\n",
8155 got_commitable_get_status(ct),
8156 got_commitable_get_path(ct));
8159 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8160 initial_content_len, a->prepared_log ? 0 : 1);
8161 done:
8162 free(initial_content);
8163 free(template);
8165 if (fd != -1 && close(fd) == -1 && err == NULL)
8166 err = got_error_from_errno2("close", a->logmsg_path);
8168 /* Editor is done; we can now apply unveil(2) */
8169 if (err == NULL)
8170 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8171 if (err) {
8172 free(*logmsg);
8173 *logmsg = NULL;
8175 return err;
8178 static const struct got_error *
8179 cmd_commit(int argc, char *argv[])
8181 const struct got_error *error = NULL;
8182 struct got_worktree *worktree = NULL;
8183 struct got_repository *repo = NULL;
8184 char *cwd = NULL, *id_str = NULL;
8185 struct got_object_id *id = NULL;
8186 const char *logmsg = NULL;
8187 char *prepared_logmsg = NULL;
8188 struct collect_commit_logmsg_arg cl_arg;
8189 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8190 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8191 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8192 struct got_pathlist_head paths;
8193 int *pack_fds = NULL;
8195 TAILQ_INIT(&paths);
8196 cl_arg.logmsg_path = NULL;
8198 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8199 switch (ch) {
8200 case 'F':
8201 if (logmsg != NULL)
8202 option_conflict('F', 'm');
8203 prepared_logmsg = realpath(optarg, NULL);
8204 if (prepared_logmsg == NULL)
8205 return got_error_from_errno2("realpath",
8206 optarg);
8207 break;
8208 case 'm':
8209 if (prepared_logmsg)
8210 option_conflict('m', 'F');
8211 logmsg = optarg;
8212 break;
8213 case 'N':
8214 non_interactive = 1;
8215 break;
8216 case 'S':
8217 allow_bad_symlinks = 1;
8218 break;
8219 default:
8220 usage_commit();
8221 /* NOTREACHED */
8225 argc -= optind;
8226 argv += optind;
8228 #ifndef PROFILE
8229 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8230 "unveil", NULL) == -1)
8231 err(1, "pledge");
8232 #endif
8233 cwd = getcwd(NULL, 0);
8234 if (cwd == NULL) {
8235 error = got_error_from_errno("getcwd");
8236 goto done;
8239 error = got_repo_pack_fds_open(&pack_fds);
8240 if (error != NULL)
8241 goto done;
8243 error = got_worktree_open(&worktree, cwd);
8244 if (error) {
8245 if (error->code == GOT_ERR_NOT_WORKTREE)
8246 error = wrap_not_worktree_error(error, "commit", cwd);
8247 goto done;
8250 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8251 if (error)
8252 goto done;
8253 if (rebase_in_progress) {
8254 error = got_error(GOT_ERR_REBASING);
8255 goto done;
8258 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8259 worktree);
8260 if (error)
8261 goto done;
8263 error = get_gitconfig_path(&gitconfig_path);
8264 if (error)
8265 goto done;
8266 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8267 gitconfig_path, pack_fds);
8268 if (error != NULL)
8269 goto done;
8271 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8272 if (error)
8273 goto done;
8274 if (merge_in_progress) {
8275 error = got_error(GOT_ERR_MERGE_BUSY);
8276 goto done;
8279 error = get_author(&author, repo, worktree);
8280 if (error)
8281 return error;
8284 * unveil(2) traverses exec(2); if an editor is used we have
8285 * to apply unveil after the log message has been written.
8287 if (logmsg == NULL || strlen(logmsg) == 0)
8288 error = get_editor(&editor);
8289 else
8290 error = apply_unveil(got_repo_get_path(repo), 0,
8291 got_worktree_get_root_path(worktree));
8292 if (error)
8293 goto done;
8295 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8296 if (error)
8297 goto done;
8299 cl_arg.editor = editor;
8300 cl_arg.cmdline_log = logmsg;
8301 cl_arg.prepared_log = prepared_logmsg;
8302 cl_arg.non_interactive = non_interactive;
8303 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8304 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8305 if (!histedit_in_progress) {
8306 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8307 error = got_error(GOT_ERR_COMMIT_BRANCH);
8308 goto done;
8310 cl_arg.branch_name += 11;
8312 cl_arg.repo_path = got_repo_get_path(repo);
8313 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8314 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8315 print_status, NULL, repo);
8316 if (error) {
8317 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8318 cl_arg.logmsg_path != NULL)
8319 preserve_logmsg = 1;
8320 goto done;
8323 error = got_object_id_str(&id_str, id);
8324 if (error)
8325 goto done;
8326 printf("Created commit %s\n", id_str);
8327 done:
8328 if (preserve_logmsg) {
8329 fprintf(stderr, "%s: log message preserved in %s\n",
8330 getprogname(), cl_arg.logmsg_path);
8331 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8332 error == NULL)
8333 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8334 free(cl_arg.logmsg_path);
8335 if (repo) {
8336 const struct got_error *close_err = got_repo_close(repo);
8337 if (error == NULL)
8338 error = close_err;
8340 if (worktree)
8341 got_worktree_close(worktree);
8342 if (pack_fds) {
8343 const struct got_error *pack_err =
8344 got_repo_pack_fds_close(pack_fds);
8345 if (error == NULL)
8346 error = pack_err;
8348 free(cwd);
8349 free(id_str);
8350 free(gitconfig_path);
8351 free(editor);
8352 free(author);
8353 free(prepared_logmsg);
8354 return error;
8357 __dead static void
8358 usage_send(void)
8360 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8361 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8362 "[remote-repository]\n", getprogname());
8363 exit(1);
8366 static void
8367 print_load_info(int print_colored, int print_found, int print_trees,
8368 int ncolored, int nfound, int ntrees)
8370 if (print_colored) {
8371 printf("%d commit%s colored", ncolored,
8372 ncolored == 1 ? "" : "s");
8374 if (print_found) {
8375 printf("%s%d object%s found",
8376 ncolored > 0 ? "; " : "",
8377 nfound, nfound == 1 ? "" : "s");
8379 if (print_trees) {
8380 printf("; %d tree%s scanned", ntrees,
8381 ntrees == 1 ? "" : "s");
8385 struct got_send_progress_arg {
8386 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8387 int verbosity;
8388 int last_ncolored;
8389 int last_nfound;
8390 int last_ntrees;
8391 int loading_done;
8392 int last_ncommits;
8393 int last_nobj_total;
8394 int last_p_deltify;
8395 int last_p_written;
8396 int last_p_sent;
8397 int printed_something;
8398 int sent_something;
8399 struct got_pathlist_head *delete_branches;
8402 static const struct got_error *
8403 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8404 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8405 int nobj_written, off_t bytes_sent, const char *refname, int success)
8407 struct got_send_progress_arg *a = arg;
8408 char scaled_packsize[FMT_SCALED_STRSIZE];
8409 char scaled_sent[FMT_SCALED_STRSIZE];
8410 int p_deltify = 0, p_written = 0, p_sent = 0;
8411 int print_colored = 0, print_found = 0, print_trees = 0;
8412 int print_searching = 0, print_total = 0;
8413 int print_deltify = 0, print_written = 0, print_sent = 0;
8415 if (a->verbosity < 0)
8416 return NULL;
8418 if (refname) {
8419 const char *status = success ? "accepted" : "rejected";
8421 if (success) {
8422 struct got_pathlist_entry *pe;
8423 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8424 const char *branchname = pe->path;
8425 if (got_path_cmp(branchname, refname,
8426 strlen(branchname), strlen(refname)) == 0) {
8427 status = "deleted";
8428 a->sent_something = 1;
8429 break;
8434 if (a->printed_something)
8435 putchar('\n');
8436 printf("Server has %s %s", status, refname);
8437 a->printed_something = 1;
8438 return NULL;
8441 if (a->last_ncolored != ncolored) {
8442 print_colored = 1;
8443 a->last_ncolored = ncolored;
8446 if (a->last_nfound != nfound) {
8447 print_colored = 1;
8448 print_found = 1;
8449 a->last_nfound = nfound;
8452 if (a->last_ntrees != ntrees) {
8453 print_colored = 1;
8454 print_found = 1;
8455 print_trees = 1;
8456 a->last_ntrees = ntrees;
8459 if ((print_colored || print_found || print_trees) &&
8460 !a->loading_done) {
8461 printf("\r");
8462 print_load_info(print_colored, print_found, print_trees,
8463 ncolored, nfound, ntrees);
8464 a->printed_something = 1;
8465 fflush(stdout);
8466 return NULL;
8467 } else if (!a->loading_done) {
8468 printf("\r");
8469 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8470 printf("\n");
8471 a->loading_done = 1;
8474 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8475 return got_error_from_errno("fmt_scaled");
8476 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8477 return got_error_from_errno("fmt_scaled");
8479 if (a->last_ncommits != ncommits) {
8480 print_searching = 1;
8481 a->last_ncommits = ncommits;
8484 if (a->last_nobj_total != nobj_total) {
8485 print_searching = 1;
8486 print_total = 1;
8487 a->last_nobj_total = nobj_total;
8490 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8491 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8492 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8493 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8494 return got_error(GOT_ERR_NO_SPACE);
8497 if (nobj_deltify > 0 || nobj_written > 0) {
8498 if (nobj_deltify > 0) {
8499 p_deltify = (nobj_deltify * 100) / nobj_total;
8500 if (p_deltify != a->last_p_deltify) {
8501 a->last_p_deltify = p_deltify;
8502 print_searching = 1;
8503 print_total = 1;
8504 print_deltify = 1;
8507 if (nobj_written > 0) {
8508 p_written = (nobj_written * 100) / nobj_total;
8509 if (p_written != a->last_p_written) {
8510 a->last_p_written = p_written;
8511 print_searching = 1;
8512 print_total = 1;
8513 print_deltify = 1;
8514 print_written = 1;
8519 if (bytes_sent > 0) {
8520 p_sent = (bytes_sent * 100) / packfile_size;
8521 if (p_sent != a->last_p_sent) {
8522 a->last_p_sent = p_sent;
8523 print_searching = 1;
8524 print_total = 1;
8525 print_deltify = 1;
8526 print_written = 1;
8527 print_sent = 1;
8529 a->sent_something = 1;
8532 if (print_searching || print_total || print_deltify || print_written ||
8533 print_sent)
8534 printf("\r");
8535 if (print_searching)
8536 printf("packing %d reference%s", ncommits,
8537 ncommits == 1 ? "" : "s");
8538 if (print_total)
8539 printf("; %d object%s", nobj_total,
8540 nobj_total == 1 ? "" : "s");
8541 if (print_deltify)
8542 printf("; deltify: %d%%", p_deltify);
8543 if (print_sent)
8544 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8545 scaled_packsize, p_sent);
8546 else if (print_written)
8547 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8548 scaled_packsize, p_written);
8549 if (print_searching || print_total || print_deltify ||
8550 print_written || print_sent) {
8551 a->printed_something = 1;
8552 fflush(stdout);
8554 return NULL;
8557 static const struct got_error *
8558 cmd_send(int argc, char *argv[])
8560 const struct got_error *error = NULL;
8561 char *cwd = NULL, *repo_path = NULL;
8562 const char *remote_name;
8563 char *proto = NULL, *host = NULL, *port = NULL;
8564 char *repo_name = NULL, *server_path = NULL;
8565 const struct got_remote_repo *remotes, *remote = NULL;
8566 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8567 struct got_repository *repo = NULL;
8568 struct got_worktree *worktree = NULL;
8569 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8570 struct got_pathlist_head branches;
8571 struct got_pathlist_head tags;
8572 struct got_reflist_head all_branches;
8573 struct got_reflist_head all_tags;
8574 struct got_pathlist_head delete_args;
8575 struct got_pathlist_head delete_branches;
8576 struct got_reflist_entry *re;
8577 struct got_pathlist_entry *pe;
8578 int i, ch, sendfd = -1, sendstatus;
8579 pid_t sendpid = -1;
8580 struct got_send_progress_arg spa;
8581 int verbosity = 0, overwrite_refs = 0;
8582 int send_all_branches = 0, send_all_tags = 0;
8583 struct got_reference *ref = NULL;
8584 int *pack_fds = NULL;
8586 TAILQ_INIT(&branches);
8587 TAILQ_INIT(&tags);
8588 TAILQ_INIT(&all_branches);
8589 TAILQ_INIT(&all_tags);
8590 TAILQ_INIT(&delete_args);
8591 TAILQ_INIT(&delete_branches);
8593 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8594 switch (ch) {
8595 case 'a':
8596 send_all_branches = 1;
8597 break;
8598 case 'b':
8599 error = got_pathlist_append(&branches, optarg, NULL);
8600 if (error)
8601 return error;
8602 nbranches++;
8603 break;
8604 case 'd':
8605 error = got_pathlist_append(&delete_args, optarg, NULL);
8606 if (error)
8607 return error;
8608 break;
8609 case 'f':
8610 overwrite_refs = 1;
8611 break;
8612 case 'r':
8613 repo_path = realpath(optarg, NULL);
8614 if (repo_path == NULL)
8615 return got_error_from_errno2("realpath",
8616 optarg);
8617 got_path_strip_trailing_slashes(repo_path);
8618 break;
8619 case 't':
8620 error = got_pathlist_append(&tags, optarg, NULL);
8621 if (error)
8622 return error;
8623 ntags++;
8624 break;
8625 case 'T':
8626 send_all_tags = 1;
8627 break;
8628 case 'v':
8629 if (verbosity < 0)
8630 verbosity = 0;
8631 else if (verbosity < 3)
8632 verbosity++;
8633 break;
8634 case 'q':
8635 verbosity = -1;
8636 break;
8637 default:
8638 usage_send();
8639 /* NOTREACHED */
8642 argc -= optind;
8643 argv += optind;
8645 if (send_all_branches && !TAILQ_EMPTY(&branches))
8646 option_conflict('a', 'b');
8647 if (send_all_tags && !TAILQ_EMPTY(&tags))
8648 option_conflict('T', 't');
8651 if (argc == 0)
8652 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8653 else if (argc == 1)
8654 remote_name = argv[0];
8655 else
8656 usage_send();
8658 cwd = getcwd(NULL, 0);
8659 if (cwd == NULL) {
8660 error = got_error_from_errno("getcwd");
8661 goto done;
8664 error = got_repo_pack_fds_open(&pack_fds);
8665 if (error != NULL)
8666 goto done;
8668 if (repo_path == NULL) {
8669 error = got_worktree_open(&worktree, cwd);
8670 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8671 goto done;
8672 else
8673 error = NULL;
8674 if (worktree) {
8675 repo_path =
8676 strdup(got_worktree_get_repo_path(worktree));
8677 if (repo_path == NULL)
8678 error = got_error_from_errno("strdup");
8679 if (error)
8680 goto done;
8681 } else {
8682 repo_path = strdup(cwd);
8683 if (repo_path == NULL) {
8684 error = got_error_from_errno("strdup");
8685 goto done;
8690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8691 if (error)
8692 goto done;
8694 if (worktree) {
8695 worktree_conf = got_worktree_get_gotconfig(worktree);
8696 if (worktree_conf) {
8697 got_gotconfig_get_remotes(&nremotes, &remotes,
8698 worktree_conf);
8699 for (i = 0; i < nremotes; i++) {
8700 if (strcmp(remotes[i].name, remote_name) == 0) {
8701 remote = &remotes[i];
8702 break;
8707 if (remote == NULL) {
8708 repo_conf = got_repo_get_gotconfig(repo);
8709 if (repo_conf) {
8710 got_gotconfig_get_remotes(&nremotes, &remotes,
8711 repo_conf);
8712 for (i = 0; i < nremotes; i++) {
8713 if (strcmp(remotes[i].name, remote_name) == 0) {
8714 remote = &remotes[i];
8715 break;
8720 if (remote == NULL) {
8721 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8722 for (i = 0; i < nremotes; i++) {
8723 if (strcmp(remotes[i].name, remote_name) == 0) {
8724 remote = &remotes[i];
8725 break;
8729 if (remote == NULL) {
8730 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8731 goto done;
8734 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8735 &repo_name, remote->send_url);
8736 if (error)
8737 goto done;
8739 if (strcmp(proto, "git") == 0) {
8740 #ifndef PROFILE
8741 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8742 "sendfd dns inet unveil", NULL) == -1)
8743 err(1, "pledge");
8744 #endif
8745 } else if (strcmp(proto, "git+ssh") == 0 ||
8746 strcmp(proto, "ssh") == 0) {
8747 #ifndef PROFILE
8748 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8749 "sendfd unveil", NULL) == -1)
8750 err(1, "pledge");
8751 #endif
8752 } else if (strcmp(proto, "http") == 0 ||
8753 strcmp(proto, "git+http") == 0) {
8754 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8755 goto done;
8756 } else {
8757 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8758 goto done;
8761 error = got_dial_apply_unveil(proto);
8762 if (error)
8763 goto done;
8765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8766 if (error)
8767 goto done;
8769 if (send_all_branches) {
8770 error = got_ref_list(&all_branches, repo, "refs/heads",
8771 got_ref_cmp_by_name, NULL);
8772 if (error)
8773 goto done;
8774 TAILQ_FOREACH(re, &all_branches, entry) {
8775 const char *branchname = got_ref_get_name(re->ref);
8776 error = got_pathlist_append(&branches,
8777 branchname, NULL);
8778 if (error)
8779 goto done;
8780 nbranches++;
8782 } else if (nbranches == 0) {
8783 for (i = 0; i < remote->nsend_branches; i++) {
8784 got_pathlist_append(&branches,
8785 remote->send_branches[i], NULL);
8789 if (send_all_tags) {
8790 error = got_ref_list(&all_tags, repo, "refs/tags",
8791 got_ref_cmp_by_name, NULL);
8792 if (error)
8793 goto done;
8794 TAILQ_FOREACH(re, &all_tags, entry) {
8795 const char *tagname = got_ref_get_name(re->ref);
8796 error = got_pathlist_append(&tags,
8797 tagname, NULL);
8798 if (error)
8799 goto done;
8800 ntags++;
8805 * To prevent accidents only branches in refs/heads/ can be deleted
8806 * with 'got send -d'.
8807 * Deleting anything else requires local repository access or Git.
8809 TAILQ_FOREACH(pe, &delete_args, entry) {
8810 const char *branchname = pe->path;
8811 char *s;
8812 struct got_pathlist_entry *new;
8813 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8814 s = strdup(branchname);
8815 if (s == NULL) {
8816 error = got_error_from_errno("strdup");
8817 goto done;
8819 } else {
8820 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8821 error = got_error_from_errno("asprintf");
8822 goto done;
8825 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8826 if (error || new == NULL /* duplicate */)
8827 free(s);
8828 if (error)
8829 goto done;
8830 ndelete_branches++;
8833 if (nbranches == 0 && ndelete_branches == 0) {
8834 struct got_reference *head_ref;
8835 if (worktree)
8836 error = got_ref_open(&head_ref, repo,
8837 got_worktree_get_head_ref_name(worktree), 0);
8838 else
8839 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8840 if (error)
8841 goto done;
8842 if (got_ref_is_symbolic(head_ref)) {
8843 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8844 got_ref_close(head_ref);
8845 if (error)
8846 goto done;
8847 } else
8848 ref = head_ref;
8849 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8850 NULL);
8851 if (error)
8852 goto done;
8853 nbranches++;
8856 if (verbosity >= 0)
8857 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8858 port ? ":" : "", port ? port : "");
8860 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8861 server_path, verbosity);
8862 if (error)
8863 goto done;
8865 memset(&spa, 0, sizeof(spa));
8866 spa.last_scaled_packsize[0] = '\0';
8867 spa.last_p_deltify = -1;
8868 spa.last_p_written = -1;
8869 spa.verbosity = verbosity;
8870 spa.delete_branches = &delete_branches;
8871 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8872 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8873 check_cancelled, NULL);
8874 if (spa.printed_something)
8875 putchar('\n');
8876 if (error)
8877 goto done;
8878 if (!spa.sent_something && verbosity >= 0)
8879 printf("Already up-to-date\n");
8880 done:
8881 if (sendpid > 0) {
8882 if (kill(sendpid, SIGTERM) == -1)
8883 error = got_error_from_errno("kill");
8884 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8885 error = got_error_from_errno("waitpid");
8887 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8888 error = got_error_from_errno("close");
8889 if (repo) {
8890 const struct got_error *close_err = got_repo_close(repo);
8891 if (error == NULL)
8892 error = close_err;
8894 if (worktree)
8895 got_worktree_close(worktree);
8896 if (pack_fds) {
8897 const struct got_error *pack_err =
8898 got_repo_pack_fds_close(pack_fds);
8899 if (error == NULL)
8900 error = pack_err;
8902 if (ref)
8903 got_ref_close(ref);
8904 got_pathlist_free(&branches);
8905 got_pathlist_free(&tags);
8906 got_ref_list_free(&all_branches);
8907 got_ref_list_free(&all_tags);
8908 got_pathlist_free(&delete_args);
8909 TAILQ_FOREACH(pe, &delete_branches, entry)
8910 free((char *)pe->path);
8911 got_pathlist_free(&delete_branches);
8912 free(cwd);
8913 free(repo_path);
8914 free(proto);
8915 free(host);
8916 free(port);
8917 free(server_path);
8918 free(repo_name);
8919 return error;
8922 __dead static void
8923 usage_cherrypick(void)
8925 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8926 exit(1);
8929 static const struct got_error *
8930 cmd_cherrypick(int argc, char *argv[])
8932 const struct got_error *error = NULL;
8933 struct got_worktree *worktree = NULL;
8934 struct got_repository *repo = NULL;
8935 char *cwd = NULL, *commit_id_str = NULL;
8936 struct got_object_id *commit_id = NULL;
8937 struct got_commit_object *commit = NULL;
8938 struct got_object_qid *pid;
8939 int ch;
8940 struct got_update_progress_arg upa;
8941 int *pack_fds = NULL;
8943 while ((ch = getopt(argc, argv, "")) != -1) {
8944 switch (ch) {
8945 default:
8946 usage_cherrypick();
8947 /* NOTREACHED */
8951 argc -= optind;
8952 argv += optind;
8954 #ifndef PROFILE
8955 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8956 "unveil", NULL) == -1)
8957 err(1, "pledge");
8958 #endif
8959 if (argc != 1)
8960 usage_cherrypick();
8962 cwd = getcwd(NULL, 0);
8963 if (cwd == NULL) {
8964 error = got_error_from_errno("getcwd");
8965 goto done;
8968 error = got_repo_pack_fds_open(&pack_fds);
8969 if (error != NULL)
8970 goto done;
8972 error = got_worktree_open(&worktree, cwd);
8973 if (error) {
8974 if (error->code == GOT_ERR_NOT_WORKTREE)
8975 error = wrap_not_worktree_error(error, "cherrypick",
8976 cwd);
8977 goto done;
8980 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8981 NULL, pack_fds);
8982 if (error != NULL)
8983 goto done;
8985 error = apply_unveil(got_repo_get_path(repo), 0,
8986 got_worktree_get_root_path(worktree));
8987 if (error)
8988 goto done;
8990 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8991 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8992 if (error)
8993 goto done;
8994 error = got_object_id_str(&commit_id_str, commit_id);
8995 if (error)
8996 goto done;
8998 error = got_object_open_as_commit(&commit, repo, commit_id);
8999 if (error)
9000 goto done;
9001 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9002 memset(&upa, 0, sizeof(upa));
9003 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9004 commit_id, repo, update_progress, &upa, check_cancelled,
9005 NULL);
9006 if (error != NULL)
9007 goto done;
9009 if (upa.did_something)
9010 printf("Merged commit %s\n", commit_id_str);
9011 print_merge_progress_stats(&upa);
9012 done:
9013 if (commit)
9014 got_object_commit_close(commit);
9015 free(commit_id_str);
9016 if (worktree)
9017 got_worktree_close(worktree);
9018 if (repo) {
9019 const struct got_error *close_err = got_repo_close(repo);
9020 if (error == NULL)
9021 error = close_err;
9023 if (pack_fds) {
9024 const struct got_error *pack_err =
9025 got_repo_pack_fds_close(pack_fds);
9026 if (error == NULL)
9027 error = pack_err;
9030 return error;
9033 __dead static void
9034 usage_backout(void)
9036 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9037 exit(1);
9040 static const struct got_error *
9041 cmd_backout(int argc, char *argv[])
9043 const struct got_error *error = NULL;
9044 struct got_worktree *worktree = NULL;
9045 struct got_repository *repo = NULL;
9046 char *cwd = NULL, *commit_id_str = NULL;
9047 struct got_object_id *commit_id = NULL;
9048 struct got_commit_object *commit = NULL;
9049 struct got_object_qid *pid;
9050 int ch;
9051 struct got_update_progress_arg upa;
9052 int *pack_fds = NULL;
9054 while ((ch = getopt(argc, argv, "")) != -1) {
9055 switch (ch) {
9056 default:
9057 usage_backout();
9058 /* NOTREACHED */
9062 argc -= optind;
9063 argv += optind;
9065 #ifndef PROFILE
9066 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9067 "unveil", NULL) == -1)
9068 err(1, "pledge");
9069 #endif
9070 if (argc != 1)
9071 usage_backout();
9073 cwd = getcwd(NULL, 0);
9074 if (cwd == NULL) {
9075 error = got_error_from_errno("getcwd");
9076 goto done;
9079 error = got_repo_pack_fds_open(&pack_fds);
9080 if (error != NULL)
9081 goto done;
9083 error = got_worktree_open(&worktree, cwd);
9084 if (error) {
9085 if (error->code == GOT_ERR_NOT_WORKTREE)
9086 error = wrap_not_worktree_error(error, "backout", cwd);
9087 goto done;
9090 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9091 NULL, pack_fds);
9092 if (error != NULL)
9093 goto done;
9095 error = apply_unveil(got_repo_get_path(repo), 0,
9096 got_worktree_get_root_path(worktree));
9097 if (error)
9098 goto done;
9100 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9101 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9102 if (error)
9103 goto done;
9104 error = got_object_id_str(&commit_id_str, commit_id);
9105 if (error)
9106 goto done;
9108 error = got_object_open_as_commit(&commit, repo, commit_id);
9109 if (error)
9110 goto done;
9111 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9112 if (pid == NULL) {
9113 error = got_error(GOT_ERR_ROOT_COMMIT);
9114 goto done;
9117 memset(&upa, 0, sizeof(upa));
9118 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9119 repo, update_progress, &upa, check_cancelled, NULL);
9120 if (error != NULL)
9121 goto done;
9123 if (upa.did_something)
9124 printf("Backed out commit %s\n", commit_id_str);
9125 print_merge_progress_stats(&upa);
9126 done:
9127 if (commit)
9128 got_object_commit_close(commit);
9129 free(commit_id_str);
9130 if (worktree)
9131 got_worktree_close(worktree);
9132 if (repo) {
9133 const struct got_error *close_err = got_repo_close(repo);
9134 if (error == NULL)
9135 error = close_err;
9137 if (pack_fds) {
9138 const struct got_error *pack_err =
9139 got_repo_pack_fds_close(pack_fds);
9140 if (error == NULL)
9141 error = pack_err;
9143 return error;
9146 __dead static void
9147 usage_rebase(void)
9149 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9150 getprogname());
9151 exit(1);
9154 static void
9155 trim_logmsg(char *logmsg, int limit)
9157 char *nl;
9158 size_t len;
9160 len = strlen(logmsg);
9161 if (len > limit)
9162 len = limit;
9163 logmsg[len] = '\0';
9164 nl = strchr(logmsg, '\n');
9165 if (nl)
9166 *nl = '\0';
9169 static const struct got_error *
9170 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9172 const struct got_error *err;
9173 char *logmsg0 = NULL;
9174 const char *s;
9176 err = got_object_commit_get_logmsg(&logmsg0, commit);
9177 if (err)
9178 return err;
9180 s = logmsg0;
9181 while (isspace((unsigned char)s[0]))
9182 s++;
9184 *logmsg = strdup(s);
9185 if (*logmsg == NULL) {
9186 err = got_error_from_errno("strdup");
9187 goto done;
9190 trim_logmsg(*logmsg, limit);
9191 done:
9192 free(logmsg0);
9193 return err;
9196 static const struct got_error *
9197 show_rebase_merge_conflict(struct got_object_id *id,
9198 struct got_repository *repo)
9200 const struct got_error *err;
9201 struct got_commit_object *commit = NULL;
9202 char *id_str = NULL, *logmsg = NULL;
9204 err = got_object_open_as_commit(&commit, repo, id);
9205 if (err)
9206 return err;
9208 err = got_object_id_str(&id_str, id);
9209 if (err)
9210 goto done;
9212 id_str[12] = '\0';
9214 err = get_short_logmsg(&logmsg, 42, commit);
9215 if (err)
9216 goto done;
9218 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9219 done:
9220 free(id_str);
9221 got_object_commit_close(commit);
9222 free(logmsg);
9223 return err;
9226 static const struct got_error *
9227 show_rebase_progress(struct got_commit_object *commit,
9228 struct got_object_id *old_id, struct got_object_id *new_id)
9230 const struct got_error *err;
9231 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9233 err = got_object_id_str(&old_id_str, old_id);
9234 if (err)
9235 goto done;
9237 if (new_id) {
9238 err = got_object_id_str(&new_id_str, new_id);
9239 if (err)
9240 goto done;
9243 old_id_str[12] = '\0';
9244 if (new_id_str)
9245 new_id_str[12] = '\0';
9247 err = get_short_logmsg(&logmsg, 42, commit);
9248 if (err)
9249 goto done;
9251 printf("%s -> %s: %s\n", old_id_str,
9252 new_id_str ? new_id_str : "no-op change", logmsg);
9253 done:
9254 free(old_id_str);
9255 free(new_id_str);
9256 free(logmsg);
9257 return err;
9260 static const struct got_error *
9261 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9262 struct got_reference *branch, struct got_reference *new_base_branch,
9263 struct got_reference *tmp_branch, struct got_repository *repo,
9264 int create_backup)
9266 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9267 return got_worktree_rebase_complete(worktree, fileindex,
9268 new_base_branch, tmp_branch, branch, repo, create_backup);
9271 static const struct got_error *
9272 rebase_commit(struct got_pathlist_head *merged_paths,
9273 struct got_worktree *worktree, struct got_fileindex *fileindex,
9274 struct got_reference *tmp_branch,
9275 struct got_object_id *commit_id, struct got_repository *repo)
9277 const struct got_error *error;
9278 struct got_commit_object *commit;
9279 struct got_object_id *new_commit_id;
9281 error = got_object_open_as_commit(&commit, repo, commit_id);
9282 if (error)
9283 return error;
9285 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9286 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9287 if (error) {
9288 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9289 goto done;
9290 error = show_rebase_progress(commit, commit_id, NULL);
9291 } else {
9292 error = show_rebase_progress(commit, commit_id, new_commit_id);
9293 free(new_commit_id);
9295 done:
9296 got_object_commit_close(commit);
9297 return error;
9300 struct check_path_prefix_arg {
9301 const char *path_prefix;
9302 size_t len;
9303 int errcode;
9306 static const struct got_error *
9307 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9308 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9309 struct got_object_id *id1, struct got_object_id *id2,
9310 const char *path1, const char *path2,
9311 mode_t mode1, mode_t mode2, struct got_repository *repo)
9313 struct check_path_prefix_arg *a = arg;
9315 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9316 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9317 return got_error(a->errcode);
9319 return NULL;
9322 static const struct got_error *
9323 check_path_prefix(struct got_object_id *parent_id,
9324 struct got_object_id *commit_id, const char *path_prefix,
9325 int errcode, struct got_repository *repo)
9327 const struct got_error *err;
9328 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9329 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9330 struct check_path_prefix_arg cpp_arg;
9332 if (got_path_is_root_dir(path_prefix))
9333 return NULL;
9335 err = got_object_open_as_commit(&commit, repo, commit_id);
9336 if (err)
9337 goto done;
9339 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9340 if (err)
9341 goto done;
9343 err = got_object_open_as_tree(&tree1, repo,
9344 got_object_commit_get_tree_id(parent_commit));
9345 if (err)
9346 goto done;
9348 err = got_object_open_as_tree(&tree2, repo,
9349 got_object_commit_get_tree_id(commit));
9350 if (err)
9351 goto done;
9353 cpp_arg.path_prefix = path_prefix;
9354 while (cpp_arg.path_prefix[0] == '/')
9355 cpp_arg.path_prefix++;
9356 cpp_arg.len = strlen(cpp_arg.path_prefix);
9357 cpp_arg.errcode = errcode;
9358 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9359 check_path_prefix_in_diff, &cpp_arg, 0);
9360 done:
9361 if (tree1)
9362 got_object_tree_close(tree1);
9363 if (tree2)
9364 got_object_tree_close(tree2);
9365 if (commit)
9366 got_object_commit_close(commit);
9367 if (parent_commit)
9368 got_object_commit_close(parent_commit);
9369 return err;
9372 static const struct got_error *
9373 collect_commits(struct got_object_id_queue *commits,
9374 struct got_object_id *initial_commit_id,
9375 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9376 const char *path_prefix, int path_prefix_errcode,
9377 struct got_repository *repo)
9379 const struct got_error *err = NULL;
9380 struct got_commit_graph *graph = NULL;
9381 struct got_object_id *parent_id = NULL;
9382 struct got_object_qid *qid;
9383 struct got_object_id *commit_id = initial_commit_id;
9385 err = got_commit_graph_open(&graph, "/", 1);
9386 if (err)
9387 return err;
9389 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9390 check_cancelled, NULL);
9391 if (err)
9392 goto done;
9393 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9394 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9395 check_cancelled, NULL);
9396 if (err) {
9397 if (err->code == GOT_ERR_ITER_COMPLETED) {
9398 err = got_error_msg(GOT_ERR_ANCESTRY,
9399 "ran out of commits to rebase before "
9400 "youngest common ancestor commit has "
9401 "been reached?!?");
9403 goto done;
9404 } else {
9405 err = check_path_prefix(parent_id, commit_id,
9406 path_prefix, path_prefix_errcode, repo);
9407 if (err)
9408 goto done;
9410 err = got_object_qid_alloc(&qid, commit_id);
9411 if (err)
9412 goto done;
9413 STAILQ_INSERT_HEAD(commits, qid, entry);
9414 commit_id = parent_id;
9417 done:
9418 got_commit_graph_close(graph);
9419 return err;
9422 static const struct got_error *
9423 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9425 const struct got_error *err = NULL;
9426 time_t committer_time;
9427 struct tm tm;
9428 char datebuf[11]; /* YYYY-MM-DD + NUL */
9429 char *author0 = NULL, *author, *smallerthan;
9430 char *logmsg0 = NULL, *logmsg, *newline;
9432 committer_time = got_object_commit_get_committer_time(commit);
9433 if (gmtime_r(&committer_time, &tm) == NULL)
9434 return got_error_from_errno("gmtime_r");
9435 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9436 return got_error(GOT_ERR_NO_SPACE);
9438 author0 = strdup(got_object_commit_get_author(commit));
9439 if (author0 == NULL)
9440 return got_error_from_errno("strdup");
9441 author = author0;
9442 smallerthan = strchr(author, '<');
9443 if (smallerthan && smallerthan[1] != '\0')
9444 author = smallerthan + 1;
9445 author[strcspn(author, "@>")] = '\0';
9447 err = got_object_commit_get_logmsg(&logmsg0, commit);
9448 if (err)
9449 goto done;
9450 logmsg = logmsg0;
9451 while (*logmsg == '\n')
9452 logmsg++;
9453 newline = strchr(logmsg, '\n');
9454 if (newline)
9455 *newline = '\0';
9457 if (asprintf(brief_str, "%s %s %s",
9458 datebuf, author, logmsg) == -1)
9459 err = got_error_from_errno("asprintf");
9460 done:
9461 free(author0);
9462 free(logmsg0);
9463 return err;
9466 static const struct got_error *
9467 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9468 struct got_repository *repo)
9470 const struct got_error *err;
9471 char *id_str;
9473 err = got_object_id_str(&id_str, id);
9474 if (err)
9475 return err;
9477 err = got_ref_delete(ref, repo);
9478 if (err)
9479 goto done;
9481 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9482 done:
9483 free(id_str);
9484 return err;
9487 static const struct got_error *
9488 print_backup_ref(const char *branch_name, const char *new_id_str,
9489 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9490 struct got_reflist_object_id_map *refs_idmap,
9491 struct got_repository *repo)
9493 const struct got_error *err = NULL;
9494 struct got_reflist_head *refs;
9495 char *refs_str = NULL;
9496 struct got_object_id *new_commit_id = NULL;
9497 struct got_commit_object *new_commit = NULL;
9498 char *new_commit_brief_str = NULL;
9499 struct got_object_id *yca_id = NULL;
9500 struct got_commit_object *yca_commit = NULL;
9501 char *yca_id_str = NULL, *yca_brief_str = NULL;
9502 char *custom_refs_str;
9504 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9505 return got_error_from_errno("asprintf");
9507 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9508 0, 0, refs_idmap, custom_refs_str);
9509 if (err)
9510 goto done;
9512 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9513 if (err)
9514 goto done;
9516 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9517 if (refs) {
9518 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9519 if (err)
9520 goto done;
9523 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9524 if (err)
9525 goto done;
9527 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9528 if (err)
9529 goto done;
9531 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9532 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9533 if (err)
9534 goto done;
9536 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9537 refs_str ? " (" : "", refs_str ? refs_str : "",
9538 refs_str ? ")" : "", new_commit_brief_str);
9539 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9540 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9541 free(refs_str);
9542 refs_str = NULL;
9544 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9545 if (err)
9546 goto done;
9548 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9549 if (err)
9550 goto done;
9552 err = got_object_id_str(&yca_id_str, yca_id);
9553 if (err)
9554 goto done;
9556 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9557 if (refs) {
9558 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9559 if (err)
9560 goto done;
9562 printf("history forked at %s%s%s%s\n %s\n",
9563 yca_id_str,
9564 refs_str ? " (" : "", refs_str ? refs_str : "",
9565 refs_str ? ")" : "", yca_brief_str);
9567 done:
9568 free(custom_refs_str);
9569 free(new_commit_id);
9570 free(refs_str);
9571 free(yca_id);
9572 free(yca_id_str);
9573 free(yca_brief_str);
9574 if (new_commit)
9575 got_object_commit_close(new_commit);
9576 if (yca_commit)
9577 got_object_commit_close(yca_commit);
9579 return NULL;
9582 static const struct got_error *
9583 process_backup_refs(const char *backup_ref_prefix,
9584 const char *wanted_branch_name,
9585 int delete, struct got_repository *repo)
9587 const struct got_error *err;
9588 struct got_reflist_head refs, backup_refs;
9589 struct got_reflist_entry *re;
9590 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9591 struct got_object_id *old_commit_id = NULL;
9592 char *branch_name = NULL;
9593 struct got_commit_object *old_commit = NULL;
9594 struct got_reflist_object_id_map *refs_idmap = NULL;
9595 int wanted_branch_found = 0;
9597 TAILQ_INIT(&refs);
9598 TAILQ_INIT(&backup_refs);
9600 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9601 if (err)
9602 return err;
9604 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9605 if (err)
9606 goto done;
9608 if (wanted_branch_name) {
9609 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9610 wanted_branch_name += 11;
9613 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9614 got_ref_cmp_by_commit_timestamp_descending, repo);
9615 if (err)
9616 goto done;
9618 TAILQ_FOREACH(re, &backup_refs, entry) {
9619 const char *refname = got_ref_get_name(re->ref);
9620 char *slash;
9622 err = check_cancelled(NULL);
9623 if (err)
9624 break;
9626 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9627 if (err)
9628 break;
9630 err = got_object_open_as_commit(&old_commit, repo,
9631 old_commit_id);
9632 if (err)
9633 break;
9635 if (strncmp(backup_ref_prefix, refname,
9636 backup_ref_prefix_len) == 0)
9637 refname += backup_ref_prefix_len;
9639 while (refname[0] == '/')
9640 refname++;
9642 branch_name = strdup(refname);
9643 if (branch_name == NULL) {
9644 err = got_error_from_errno("strdup");
9645 break;
9647 slash = strrchr(branch_name, '/');
9648 if (slash) {
9649 *slash = '\0';
9650 refname += strlen(branch_name) + 1;
9653 if (wanted_branch_name == NULL ||
9654 strcmp(wanted_branch_name, branch_name) == 0) {
9655 wanted_branch_found = 1;
9656 if (delete) {
9657 err = delete_backup_ref(re->ref,
9658 old_commit_id, repo);
9659 } else {
9660 err = print_backup_ref(branch_name, refname,
9661 old_commit_id, old_commit, refs_idmap,
9662 repo);
9664 if (err)
9665 break;
9668 free(old_commit_id);
9669 old_commit_id = NULL;
9670 free(branch_name);
9671 branch_name = NULL;
9672 got_object_commit_close(old_commit);
9673 old_commit = NULL;
9676 if (wanted_branch_name && !wanted_branch_found) {
9677 err = got_error_fmt(GOT_ERR_NOT_REF,
9678 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9680 done:
9681 if (refs_idmap)
9682 got_reflist_object_id_map_free(refs_idmap);
9683 got_ref_list_free(&refs);
9684 got_ref_list_free(&backup_refs);
9685 free(old_commit_id);
9686 free(branch_name);
9687 if (old_commit)
9688 got_object_commit_close(old_commit);
9689 return err;
9692 static const struct got_error *
9693 abort_progress(void *arg, unsigned char status, const char *path)
9696 * Unversioned files should not clutter progress output when
9697 * an operation is aborted.
9699 if (status == GOT_STATUS_UNVERSIONED)
9700 return NULL;
9702 return update_progress(arg, status, path);
9705 static const struct got_error *
9706 cmd_rebase(int argc, char *argv[])
9708 const struct got_error *error = NULL;
9709 struct got_worktree *worktree = NULL;
9710 struct got_repository *repo = NULL;
9711 struct got_fileindex *fileindex = NULL;
9712 char *cwd = NULL;
9713 struct got_reference *branch = NULL;
9714 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9715 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9716 struct got_object_id *resume_commit_id = NULL;
9717 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9718 struct got_commit_object *commit = NULL;
9719 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9720 int histedit_in_progress = 0, merge_in_progress = 0;
9721 int create_backup = 1, list_backups = 0, delete_backups = 0;
9722 struct got_object_id_queue commits;
9723 struct got_pathlist_head merged_paths;
9724 const struct got_object_id_queue *parent_ids;
9725 struct got_object_qid *qid, *pid;
9726 struct got_update_progress_arg upa;
9727 int *pack_fds = NULL;
9729 STAILQ_INIT(&commits);
9730 TAILQ_INIT(&merged_paths);
9731 memset(&upa, 0, sizeof(upa));
9733 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9734 switch (ch) {
9735 case 'a':
9736 abort_rebase = 1;
9737 break;
9738 case 'c':
9739 continue_rebase = 1;
9740 break;
9741 case 'l':
9742 list_backups = 1;
9743 break;
9744 case 'X':
9745 delete_backups = 1;
9746 break;
9747 default:
9748 usage_rebase();
9749 /* NOTREACHED */
9753 argc -= optind;
9754 argv += optind;
9756 #ifndef PROFILE
9757 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9758 "unveil", NULL) == -1)
9759 err(1, "pledge");
9760 #endif
9761 if (list_backups) {
9762 if (abort_rebase)
9763 option_conflict('l', 'a');
9764 if (continue_rebase)
9765 option_conflict('l', 'c');
9766 if (delete_backups)
9767 option_conflict('l', 'X');
9768 if (argc != 0 && argc != 1)
9769 usage_rebase();
9770 } else if (delete_backups) {
9771 if (abort_rebase)
9772 option_conflict('X', 'a');
9773 if (continue_rebase)
9774 option_conflict('X', 'c');
9775 if (list_backups)
9776 option_conflict('l', 'X');
9777 if (argc != 0 && argc != 1)
9778 usage_rebase();
9779 } else {
9780 if (abort_rebase && continue_rebase)
9781 usage_rebase();
9782 else if (abort_rebase || continue_rebase) {
9783 if (argc != 0)
9784 usage_rebase();
9785 } else if (argc != 1)
9786 usage_rebase();
9789 cwd = getcwd(NULL, 0);
9790 if (cwd == NULL) {
9791 error = got_error_from_errno("getcwd");
9792 goto done;
9795 error = got_repo_pack_fds_open(&pack_fds);
9796 if (error != NULL)
9797 goto done;
9799 error = got_worktree_open(&worktree, cwd);
9800 if (error) {
9801 if (list_backups || delete_backups) {
9802 if (error->code != GOT_ERR_NOT_WORKTREE)
9803 goto done;
9804 } else {
9805 if (error->code == GOT_ERR_NOT_WORKTREE)
9806 error = wrap_not_worktree_error(error,
9807 "rebase", cwd);
9808 goto done;
9812 error = got_repo_open(&repo,
9813 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9814 pack_fds);
9815 if (error != NULL)
9816 goto done;
9818 error = apply_unveil(got_repo_get_path(repo), 0,
9819 worktree ? got_worktree_get_root_path(worktree) : NULL);
9820 if (error)
9821 goto done;
9823 if (list_backups || delete_backups) {
9824 error = process_backup_refs(
9825 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9826 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9827 goto done; /* nothing else to do */
9830 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9831 worktree);
9832 if (error)
9833 goto done;
9834 if (histedit_in_progress) {
9835 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9836 goto done;
9839 error = got_worktree_merge_in_progress(&merge_in_progress,
9840 worktree, repo);
9841 if (error)
9842 goto done;
9843 if (merge_in_progress) {
9844 error = got_error(GOT_ERR_MERGE_BUSY);
9845 goto done;
9848 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9849 if (error)
9850 goto done;
9852 if (abort_rebase) {
9853 if (!rebase_in_progress) {
9854 error = got_error(GOT_ERR_NOT_REBASING);
9855 goto done;
9857 error = got_worktree_rebase_continue(&resume_commit_id,
9858 &new_base_branch, &tmp_branch, &branch, &fileindex,
9859 worktree, repo);
9860 if (error)
9861 goto done;
9862 printf("Switching work tree to %s\n",
9863 got_ref_get_symref_target(new_base_branch));
9864 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9865 new_base_branch, abort_progress, &upa);
9866 if (error)
9867 goto done;
9868 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9869 print_merge_progress_stats(&upa);
9870 goto done; /* nothing else to do */
9873 if (continue_rebase) {
9874 if (!rebase_in_progress) {
9875 error = got_error(GOT_ERR_NOT_REBASING);
9876 goto done;
9878 error = got_worktree_rebase_continue(&resume_commit_id,
9879 &new_base_branch, &tmp_branch, &branch, &fileindex,
9880 worktree, repo);
9881 if (error)
9882 goto done;
9884 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9885 resume_commit_id, repo);
9886 if (error)
9887 goto done;
9889 yca_id = got_object_id_dup(resume_commit_id);
9890 if (yca_id == NULL) {
9891 error = got_error_from_errno("got_object_id_dup");
9892 goto done;
9894 } else {
9895 error = got_ref_open(&branch, repo, argv[0], 0);
9896 if (error != NULL)
9897 goto done;
9900 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9901 if (error)
9902 goto done;
9904 if (!continue_rebase) {
9905 struct got_object_id *base_commit_id;
9907 base_commit_id = got_worktree_get_base_commit_id(worktree);
9908 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9909 base_commit_id, branch_head_commit_id, 1, repo,
9910 check_cancelled, NULL);
9911 if (error)
9912 goto done;
9913 if (yca_id == NULL) {
9914 error = got_error_msg(GOT_ERR_ANCESTRY,
9915 "specified branch shares no common ancestry "
9916 "with work tree's branch");
9917 goto done;
9920 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9921 if (error) {
9922 if (error->code != GOT_ERR_ANCESTRY)
9923 goto done;
9924 error = NULL;
9925 } else {
9926 struct got_pathlist_head paths;
9927 printf("%s is already based on %s\n",
9928 got_ref_get_name(branch),
9929 got_worktree_get_head_ref_name(worktree));
9930 error = switch_head_ref(branch, branch_head_commit_id,
9931 worktree, repo);
9932 if (error)
9933 goto done;
9934 error = got_worktree_set_base_commit_id(worktree, repo,
9935 branch_head_commit_id);
9936 if (error)
9937 goto done;
9938 TAILQ_INIT(&paths);
9939 error = got_pathlist_append(&paths, "", NULL);
9940 if (error)
9941 goto done;
9942 error = got_worktree_checkout_files(worktree,
9943 &paths, repo, update_progress, &upa,
9944 check_cancelled, NULL);
9945 got_pathlist_free(&paths);
9946 if (error)
9947 goto done;
9948 if (upa.did_something) {
9949 char *id_str;
9950 error = got_object_id_str(&id_str,
9951 branch_head_commit_id);
9952 if (error)
9953 goto done;
9954 printf("Updated to %s: %s\n",
9955 got_worktree_get_head_ref_name(worktree),
9956 id_str);
9957 free(id_str);
9958 } else
9959 printf("Already up-to-date\n");
9960 print_update_progress_stats(&upa);
9961 goto done;
9965 commit_id = branch_head_commit_id;
9966 error = got_object_open_as_commit(&commit, repo, commit_id);
9967 if (error)
9968 goto done;
9970 parent_ids = got_object_commit_get_parent_ids(commit);
9971 pid = STAILQ_FIRST(parent_ids);
9972 if (pid == NULL) {
9973 error = got_error(GOT_ERR_EMPTY_REBASE);
9974 goto done;
9976 error = collect_commits(&commits, commit_id, &pid->id,
9977 yca_id, got_worktree_get_path_prefix(worktree),
9978 GOT_ERR_REBASE_PATH, repo);
9979 got_object_commit_close(commit);
9980 commit = NULL;
9981 if (error)
9982 goto done;
9984 if (!continue_rebase) {
9985 error = got_worktree_rebase_prepare(&new_base_branch,
9986 &tmp_branch, &fileindex, worktree, branch, repo);
9987 if (error)
9988 goto done;
9991 if (STAILQ_EMPTY(&commits)) {
9992 if (continue_rebase) {
9993 error = rebase_complete(worktree, fileindex,
9994 branch, new_base_branch, tmp_branch, repo,
9995 create_backup);
9996 goto done;
9997 } else {
9998 /* Fast-forward the reference of the branch. */
9999 struct got_object_id *new_head_commit_id;
10000 char *id_str;
10001 error = got_ref_resolve(&new_head_commit_id, repo,
10002 new_base_branch);
10003 if (error)
10004 goto done;
10005 error = got_object_id_str(&id_str, new_head_commit_id);
10006 printf("Forwarding %s to commit %s\n",
10007 got_ref_get_name(branch), id_str);
10008 free(id_str);
10009 error = got_ref_change_ref(branch,
10010 new_head_commit_id);
10011 if (error)
10012 goto done;
10013 /* No backup needed since objects did not change. */
10014 create_backup = 0;
10018 pid = NULL;
10019 STAILQ_FOREACH(qid, &commits, entry) {
10021 commit_id = &qid->id;
10022 parent_id = pid ? &pid->id : yca_id;
10023 pid = qid;
10025 memset(&upa, 0, sizeof(upa));
10026 error = got_worktree_rebase_merge_files(&merged_paths,
10027 worktree, fileindex, parent_id, commit_id, repo,
10028 update_progress, &upa, check_cancelled, NULL);
10029 if (error)
10030 goto done;
10032 print_merge_progress_stats(&upa);
10033 if (upa.conflicts > 0 || upa.missing > 0 ||
10034 upa.not_deleted > 0 || upa.unversioned > 0) {
10035 if (upa.conflicts > 0) {
10036 error = show_rebase_merge_conflict(&qid->id,
10037 repo);
10038 if (error)
10039 goto done;
10041 got_worktree_rebase_pathlist_free(&merged_paths);
10042 break;
10045 error = rebase_commit(&merged_paths, worktree, fileindex,
10046 tmp_branch, commit_id, repo);
10047 got_worktree_rebase_pathlist_free(&merged_paths);
10048 if (error)
10049 goto done;
10052 if (upa.conflicts > 0 || upa.missing > 0 ||
10053 upa.not_deleted > 0 || upa.unversioned > 0) {
10054 error = got_worktree_rebase_postpone(worktree, fileindex);
10055 if (error)
10056 goto done;
10057 if (upa.conflicts > 0 && upa.missing == 0 &&
10058 upa.not_deleted == 0 && upa.unversioned == 0) {
10059 error = got_error_msg(GOT_ERR_CONFLICTS,
10060 "conflicts must be resolved before rebasing "
10061 "can continue");
10062 } else if (upa.conflicts > 0) {
10063 error = got_error_msg(GOT_ERR_CONFLICTS,
10064 "conflicts must be resolved before rebasing "
10065 "can continue; changes destined for some "
10066 "files were not yet merged and should be "
10067 "merged manually if required before the "
10068 "rebase operation is continued");
10069 } else {
10070 error = got_error_msg(GOT_ERR_CONFLICTS,
10071 "changes destined for some files were not "
10072 "yet merged and should be merged manually "
10073 "if required before the rebase operation "
10074 "is continued");
10076 } else
10077 error = rebase_complete(worktree, fileindex, branch,
10078 new_base_branch, tmp_branch, repo, create_backup);
10079 done:
10080 got_object_id_queue_free(&commits);
10081 free(branch_head_commit_id);
10082 free(resume_commit_id);
10083 free(yca_id);
10084 if (commit)
10085 got_object_commit_close(commit);
10086 if (branch)
10087 got_ref_close(branch);
10088 if (new_base_branch)
10089 got_ref_close(new_base_branch);
10090 if (tmp_branch)
10091 got_ref_close(tmp_branch);
10092 if (worktree)
10093 got_worktree_close(worktree);
10094 if (repo) {
10095 const struct got_error *close_err = got_repo_close(repo);
10096 if (error == NULL)
10097 error = close_err;
10099 if (pack_fds) {
10100 const struct got_error *pack_err =
10101 got_repo_pack_fds_close(pack_fds);
10102 if (error == NULL)
10103 error = pack_err;
10105 return error;
10108 __dead static void
10109 usage_histedit(void)
10111 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10112 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10113 getprogname());
10114 exit(1);
10117 #define GOT_HISTEDIT_PICK 'p'
10118 #define GOT_HISTEDIT_EDIT 'e'
10119 #define GOT_HISTEDIT_FOLD 'f'
10120 #define GOT_HISTEDIT_DROP 'd'
10121 #define GOT_HISTEDIT_MESG 'm'
10123 static const struct got_histedit_cmd {
10124 unsigned char code;
10125 const char *name;
10126 const char *desc;
10127 } got_histedit_cmds[] = {
10128 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10129 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10130 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10131 "be used" },
10132 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10133 { GOT_HISTEDIT_MESG, "mesg",
10134 "single-line log message for commit above (open editor if empty)" },
10137 struct got_histedit_list_entry {
10138 TAILQ_ENTRY(got_histedit_list_entry) entry;
10139 struct got_object_id *commit_id;
10140 const struct got_histedit_cmd *cmd;
10141 char *logmsg;
10143 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10145 static const struct got_error *
10146 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10147 FILE *f, struct got_repository *repo)
10149 const struct got_error *err = NULL;
10150 char *logmsg = NULL, *id_str = NULL;
10151 struct got_commit_object *commit = NULL;
10152 int n;
10154 err = got_object_open_as_commit(&commit, repo, commit_id);
10155 if (err)
10156 goto done;
10158 err = get_short_logmsg(&logmsg, 34, commit);
10159 if (err)
10160 goto done;
10162 err = got_object_id_str(&id_str, commit_id);
10163 if (err)
10164 goto done;
10166 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10167 if (n < 0)
10168 err = got_ferror(f, GOT_ERR_IO);
10169 done:
10170 if (commit)
10171 got_object_commit_close(commit);
10172 free(id_str);
10173 free(logmsg);
10174 return err;
10177 static const struct got_error *
10178 histedit_write_commit_list(struct got_object_id_queue *commits,
10179 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10180 struct got_repository *repo)
10182 const struct got_error *err = NULL;
10183 struct got_object_qid *qid;
10184 const char *histedit_cmd = NULL;
10186 if (STAILQ_EMPTY(commits))
10187 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10189 STAILQ_FOREACH(qid, commits, entry) {
10190 histedit_cmd = got_histedit_cmds[0].name;
10191 if (edit_only)
10192 histedit_cmd = "edit";
10193 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10194 histedit_cmd = "fold";
10195 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10196 if (err)
10197 break;
10198 if (edit_logmsg_only) {
10199 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10200 if (n < 0) {
10201 err = got_ferror(f, GOT_ERR_IO);
10202 break;
10207 return err;
10210 static const struct got_error *
10211 write_cmd_list(FILE *f, const char *branch_name,
10212 struct got_object_id_queue *commits)
10214 const struct got_error *err = NULL;
10215 size_t i;
10216 int n;
10217 char *id_str;
10218 struct got_object_qid *qid;
10220 qid = STAILQ_FIRST(commits);
10221 err = got_object_id_str(&id_str, &qid->id);
10222 if (err)
10223 return err;
10225 n = fprintf(f,
10226 "# Editing the history of branch '%s' starting at\n"
10227 "# commit %s\n"
10228 "# Commits will be processed in order from top to "
10229 "bottom of this file.\n", branch_name, id_str);
10230 if (n < 0) {
10231 err = got_ferror(f, GOT_ERR_IO);
10232 goto done;
10235 n = fprintf(f, "# Available histedit commands:\n");
10236 if (n < 0) {
10237 err = got_ferror(f, GOT_ERR_IO);
10238 goto done;
10241 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10242 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10243 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10244 cmd->desc);
10245 if (n < 0) {
10246 err = got_ferror(f, GOT_ERR_IO);
10247 break;
10250 done:
10251 free(id_str);
10252 return err;
10255 static const struct got_error *
10256 histedit_syntax_error(int lineno)
10258 static char msg[42];
10259 int ret;
10261 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10262 lineno);
10263 if (ret == -1 || ret >= sizeof(msg))
10264 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10266 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10269 static const struct got_error *
10270 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10271 char *logmsg, struct got_repository *repo)
10273 const struct got_error *err;
10274 struct got_commit_object *folded_commit = NULL;
10275 char *id_str, *folded_logmsg = NULL;
10277 err = got_object_id_str(&id_str, hle->commit_id);
10278 if (err)
10279 return err;
10281 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10282 if (err)
10283 goto done;
10285 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10286 if (err)
10287 goto done;
10288 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10289 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10290 folded_logmsg) == -1) {
10291 err = got_error_from_errno("asprintf");
10293 done:
10294 if (folded_commit)
10295 got_object_commit_close(folded_commit);
10296 free(id_str);
10297 free(folded_logmsg);
10298 return err;
10301 static struct got_histedit_list_entry *
10302 get_folded_commits(struct got_histedit_list_entry *hle)
10304 struct got_histedit_list_entry *prev, *folded = NULL;
10306 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10307 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10308 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10309 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10310 folded = prev;
10311 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10314 return folded;
10317 static const struct got_error *
10318 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10319 struct got_repository *repo)
10321 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10322 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10323 const struct got_error *err = NULL;
10324 struct got_commit_object *commit = NULL;
10325 int logmsg_len;
10326 int fd;
10327 struct got_histedit_list_entry *folded = NULL;
10329 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10330 if (err)
10331 return err;
10333 folded = get_folded_commits(hle);
10334 if (folded) {
10335 while (folded != hle) {
10336 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10337 folded = TAILQ_NEXT(folded, entry);
10338 continue;
10340 err = append_folded_commit_msg(&new_msg, folded,
10341 logmsg, repo);
10342 if (err)
10343 goto done;
10344 free(logmsg);
10345 logmsg = new_msg;
10346 folded = TAILQ_NEXT(folded, entry);
10350 err = got_object_id_str(&id_str, hle->commit_id);
10351 if (err)
10352 goto done;
10353 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10354 if (err)
10355 goto done;
10356 logmsg_len = asprintf(&new_msg,
10357 "%s\n# original log message of commit %s: %s",
10358 logmsg ? logmsg : "", id_str, orig_logmsg);
10359 if (logmsg_len == -1) {
10360 err = got_error_from_errno("asprintf");
10361 goto done;
10363 free(logmsg);
10364 logmsg = new_msg;
10366 err = got_object_id_str(&id_str, hle->commit_id);
10367 if (err)
10368 goto done;
10370 err = got_opentemp_named_fd(&logmsg_path, &fd,
10371 GOT_TMPDIR_STR "/got-logmsg");
10372 if (err)
10373 goto done;
10375 write(fd, logmsg, logmsg_len);
10376 close(fd);
10378 err = get_editor(&editor);
10379 if (err)
10380 goto done;
10382 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10383 logmsg_len, 0);
10384 if (err) {
10385 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10386 goto done;
10387 err = NULL;
10388 hle->logmsg = strdup(new_msg);
10389 if (hle->logmsg == NULL)
10390 err = got_error_from_errno("strdup");
10392 done:
10393 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10394 err = got_error_from_errno2("unlink", logmsg_path);
10395 free(logmsg_path);
10396 free(logmsg);
10397 free(orig_logmsg);
10398 free(editor);
10399 if (commit)
10400 got_object_commit_close(commit);
10401 return err;
10404 static const struct got_error *
10405 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10406 FILE *f, struct got_repository *repo)
10408 const struct got_error *err = NULL;
10409 char *line = NULL, *p, *end;
10410 size_t i, size;
10411 ssize_t len;
10412 int lineno = 0;
10413 const struct got_histedit_cmd *cmd;
10414 struct got_object_id *commit_id = NULL;
10415 struct got_histedit_list_entry *hle = NULL;
10417 for (;;) {
10418 len = getline(&line, &size, f);
10419 if (len == -1) {
10420 const struct got_error *getline_err;
10421 if (feof(f))
10422 break;
10423 getline_err = got_error_from_errno("getline");
10424 err = got_ferror(f, getline_err->code);
10425 break;
10427 lineno++;
10428 p = line;
10429 while (isspace((unsigned char)p[0]))
10430 p++;
10431 if (p[0] == '#' || p[0] == '\0') {
10432 free(line);
10433 line = NULL;
10434 continue;
10436 cmd = NULL;
10437 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10438 cmd = &got_histedit_cmds[i];
10439 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10440 isspace((unsigned char)p[strlen(cmd->name)])) {
10441 p += strlen(cmd->name);
10442 break;
10444 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10445 p++;
10446 break;
10449 if (i == nitems(got_histedit_cmds)) {
10450 err = histedit_syntax_error(lineno);
10451 break;
10453 while (isspace((unsigned char)p[0]))
10454 p++;
10455 if (cmd->code == GOT_HISTEDIT_MESG) {
10456 if (hle == NULL || hle->logmsg != NULL) {
10457 err = got_error(GOT_ERR_HISTEDIT_CMD);
10458 break;
10460 if (p[0] == '\0') {
10461 err = histedit_edit_logmsg(hle, repo);
10462 if (err)
10463 break;
10464 } else {
10465 hle->logmsg = strdup(p);
10466 if (hle->logmsg == NULL) {
10467 err = got_error_from_errno("strdup");
10468 break;
10471 free(line);
10472 line = NULL;
10473 continue;
10474 } else {
10475 end = p;
10476 while (end[0] && !isspace((unsigned char)end[0]))
10477 end++;
10478 *end = '\0';
10480 err = got_object_resolve_id_str(&commit_id, repo, p);
10481 if (err) {
10482 /* override error code */
10483 err = histedit_syntax_error(lineno);
10484 break;
10487 hle = malloc(sizeof(*hle));
10488 if (hle == NULL) {
10489 err = got_error_from_errno("malloc");
10490 break;
10492 hle->cmd = cmd;
10493 hle->commit_id = commit_id;
10494 hle->logmsg = NULL;
10495 commit_id = NULL;
10496 free(line);
10497 line = NULL;
10498 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10501 free(line);
10502 free(commit_id);
10503 return err;
10506 static const struct got_error *
10507 histedit_check_script(struct got_histedit_list *histedit_cmds,
10508 struct got_object_id_queue *commits, struct got_repository *repo)
10510 const struct got_error *err = NULL;
10511 struct got_object_qid *qid;
10512 struct got_histedit_list_entry *hle;
10513 static char msg[92];
10514 char *id_str;
10516 if (TAILQ_EMPTY(histedit_cmds))
10517 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10518 "histedit script contains no commands");
10519 if (STAILQ_EMPTY(commits))
10520 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10522 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10523 struct got_histedit_list_entry *hle2;
10524 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10525 if (hle == hle2)
10526 continue;
10527 if (got_object_id_cmp(hle->commit_id,
10528 hle2->commit_id) != 0)
10529 continue;
10530 err = got_object_id_str(&id_str, hle->commit_id);
10531 if (err)
10532 return err;
10533 snprintf(msg, sizeof(msg), "commit %s is listed "
10534 "more than once in histedit script", id_str);
10535 free(id_str);
10536 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10540 STAILQ_FOREACH(qid, commits, entry) {
10541 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10542 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10543 break;
10545 if (hle == NULL) {
10546 err = got_object_id_str(&id_str, &qid->id);
10547 if (err)
10548 return err;
10549 snprintf(msg, sizeof(msg),
10550 "commit %s missing from histedit script", id_str);
10551 free(id_str);
10552 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10556 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10557 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10558 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10559 "last commit in histedit script cannot be folded");
10561 return NULL;
10564 static const struct got_error *
10565 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10566 const char *path, struct got_object_id_queue *commits,
10567 struct got_repository *repo)
10569 const struct got_error *err = NULL;
10570 char *editor;
10571 FILE *f = NULL;
10573 err = get_editor(&editor);
10574 if (err)
10575 return err;
10577 if (spawn_editor(editor, path) == -1) {
10578 err = got_error_from_errno("failed spawning editor");
10579 goto done;
10582 f = fopen(path, "re");
10583 if (f == NULL) {
10584 err = got_error_from_errno("fopen");
10585 goto done;
10587 err = histedit_parse_list(histedit_cmds, f, repo);
10588 if (err)
10589 goto done;
10591 err = histedit_check_script(histedit_cmds, commits, repo);
10592 done:
10593 if (f && fclose(f) == EOF && err == NULL)
10594 err = got_error_from_errno("fclose");
10595 free(editor);
10596 return err;
10599 static const struct got_error *
10600 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10601 struct got_object_id_queue *, const char *, const char *,
10602 struct got_repository *);
10604 static const struct got_error *
10605 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10606 struct got_object_id_queue *commits, const char *branch_name,
10607 int edit_logmsg_only, int fold_only, int edit_only,
10608 struct got_repository *repo)
10610 const struct got_error *err;
10611 FILE *f = NULL;
10612 char *path = NULL;
10614 err = got_opentemp_named(&path, &f, "got-histedit");
10615 if (err)
10616 return err;
10618 err = write_cmd_list(f, branch_name, commits);
10619 if (err)
10620 goto done;
10622 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10623 fold_only, edit_only, repo);
10624 if (err)
10625 goto done;
10627 if (edit_logmsg_only || fold_only || edit_only) {
10628 rewind(f);
10629 err = histedit_parse_list(histedit_cmds, f, repo);
10630 } else {
10631 if (fclose(f) == EOF) {
10632 err = got_error_from_errno("fclose");
10633 goto done;
10635 f = NULL;
10636 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10637 if (err) {
10638 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10639 err->code != GOT_ERR_HISTEDIT_CMD)
10640 goto done;
10641 err = histedit_edit_list_retry(histedit_cmds, err,
10642 commits, path, branch_name, repo);
10645 done:
10646 if (f && fclose(f) == EOF && err == NULL)
10647 err = got_error_from_errno("fclose");
10648 if (path && unlink(path) != 0 && err == NULL)
10649 err = got_error_from_errno2("unlink", path);
10650 free(path);
10651 return err;
10654 static const struct got_error *
10655 histedit_save_list(struct got_histedit_list *histedit_cmds,
10656 struct got_worktree *worktree, struct got_repository *repo)
10658 const struct got_error *err = NULL;
10659 char *path = NULL;
10660 FILE *f = NULL;
10661 struct got_histedit_list_entry *hle;
10662 struct got_commit_object *commit = NULL;
10664 err = got_worktree_get_histedit_script_path(&path, worktree);
10665 if (err)
10666 return err;
10668 f = fopen(path, "we");
10669 if (f == NULL) {
10670 err = got_error_from_errno2("fopen", path);
10671 goto done;
10673 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10674 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10675 repo);
10676 if (err)
10677 break;
10679 if (hle->logmsg) {
10680 int n = fprintf(f, "%c %s\n",
10681 GOT_HISTEDIT_MESG, hle->logmsg);
10682 if (n < 0) {
10683 err = got_ferror(f, GOT_ERR_IO);
10684 break;
10688 done:
10689 if (f && fclose(f) == EOF && err == NULL)
10690 err = got_error_from_errno("fclose");
10691 free(path);
10692 if (commit)
10693 got_object_commit_close(commit);
10694 return err;
10697 static void
10698 histedit_free_list(struct got_histedit_list *histedit_cmds)
10700 struct got_histedit_list_entry *hle;
10702 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10703 TAILQ_REMOVE(histedit_cmds, hle, entry);
10704 free(hle);
10708 static const struct got_error *
10709 histedit_load_list(struct got_histedit_list *histedit_cmds,
10710 const char *path, struct got_repository *repo)
10712 const struct got_error *err = NULL;
10713 FILE *f = NULL;
10715 f = fopen(path, "re");
10716 if (f == NULL) {
10717 err = got_error_from_errno2("fopen", path);
10718 goto done;
10721 err = histedit_parse_list(histedit_cmds, f, repo);
10722 done:
10723 if (f && fclose(f) == EOF && err == NULL)
10724 err = got_error_from_errno("fclose");
10725 return err;
10728 static const struct got_error *
10729 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10730 const struct got_error *edit_err, struct got_object_id_queue *commits,
10731 const char *path, const char *branch_name, struct got_repository *repo)
10733 const struct got_error *err = NULL, *prev_err = edit_err;
10734 int resp = ' ';
10736 while (resp != 'c' && resp != 'r' && resp != 'a') {
10737 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10738 "or (a)bort: ", getprogname(), prev_err->msg);
10739 resp = getchar();
10740 if (resp == '\n')
10741 resp = getchar();
10742 if (resp == 'c') {
10743 histedit_free_list(histedit_cmds);
10744 err = histedit_run_editor(histedit_cmds, path, commits,
10745 repo);
10746 if (err) {
10747 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10748 err->code != GOT_ERR_HISTEDIT_CMD)
10749 break;
10750 prev_err = err;
10751 resp = ' ';
10752 continue;
10754 break;
10755 } else if (resp == 'r') {
10756 histedit_free_list(histedit_cmds);
10757 err = histedit_edit_script(histedit_cmds,
10758 commits, branch_name, 0, 0, 0, repo);
10759 if (err) {
10760 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10761 err->code != GOT_ERR_HISTEDIT_CMD)
10762 break;
10763 prev_err = err;
10764 resp = ' ';
10765 continue;
10767 break;
10768 } else if (resp == 'a') {
10769 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10770 break;
10771 } else
10772 printf("invalid response '%c'\n", resp);
10775 return err;
10778 static const struct got_error *
10779 histedit_complete(struct got_worktree *worktree,
10780 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10781 struct got_reference *branch, struct got_repository *repo)
10783 printf("Switching work tree to %s\n",
10784 got_ref_get_symref_target(branch));
10785 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10786 branch, repo);
10789 static const struct got_error *
10790 show_histedit_progress(struct got_commit_object *commit,
10791 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10793 const struct got_error *err;
10794 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10796 err = got_object_id_str(&old_id_str, hle->commit_id);
10797 if (err)
10798 goto done;
10800 if (new_id) {
10801 err = got_object_id_str(&new_id_str, new_id);
10802 if (err)
10803 goto done;
10806 old_id_str[12] = '\0';
10807 if (new_id_str)
10808 new_id_str[12] = '\0';
10810 if (hle->logmsg) {
10811 logmsg = strdup(hle->logmsg);
10812 if (logmsg == NULL) {
10813 err = got_error_from_errno("strdup");
10814 goto done;
10816 trim_logmsg(logmsg, 42);
10817 } else {
10818 err = get_short_logmsg(&logmsg, 42, commit);
10819 if (err)
10820 goto done;
10823 switch (hle->cmd->code) {
10824 case GOT_HISTEDIT_PICK:
10825 case GOT_HISTEDIT_EDIT:
10826 printf("%s -> %s: %s\n", old_id_str,
10827 new_id_str ? new_id_str : "no-op change", logmsg);
10828 break;
10829 case GOT_HISTEDIT_DROP:
10830 case GOT_HISTEDIT_FOLD:
10831 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10832 logmsg);
10833 break;
10834 default:
10835 break;
10837 done:
10838 free(old_id_str);
10839 free(new_id_str);
10840 return err;
10843 static const struct got_error *
10844 histedit_commit(struct got_pathlist_head *merged_paths,
10845 struct got_worktree *worktree, struct got_fileindex *fileindex,
10846 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10847 struct got_repository *repo)
10849 const struct got_error *err;
10850 struct got_commit_object *commit;
10851 struct got_object_id *new_commit_id;
10853 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10854 && hle->logmsg == NULL) {
10855 err = histedit_edit_logmsg(hle, repo);
10856 if (err)
10857 return err;
10860 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10861 if (err)
10862 return err;
10864 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10865 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10866 hle->logmsg, repo);
10867 if (err) {
10868 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10869 goto done;
10870 err = show_histedit_progress(commit, hle, NULL);
10871 } else {
10872 err = show_histedit_progress(commit, hle, new_commit_id);
10873 free(new_commit_id);
10875 done:
10876 got_object_commit_close(commit);
10877 return err;
10880 static const struct got_error *
10881 histedit_skip_commit(struct got_histedit_list_entry *hle,
10882 struct got_worktree *worktree, struct got_repository *repo)
10884 const struct got_error *error;
10885 struct got_commit_object *commit;
10887 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10888 repo);
10889 if (error)
10890 return error;
10892 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10893 if (error)
10894 return error;
10896 error = show_histedit_progress(commit, hle, NULL);
10897 got_object_commit_close(commit);
10898 return error;
10901 static const struct got_error *
10902 check_local_changes(void *arg, unsigned char status,
10903 unsigned char staged_status, const char *path,
10904 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10905 struct got_object_id *commit_id, int dirfd, const char *de_name)
10907 int *have_local_changes = arg;
10909 switch (status) {
10910 case GOT_STATUS_ADD:
10911 case GOT_STATUS_DELETE:
10912 case GOT_STATUS_MODIFY:
10913 case GOT_STATUS_CONFLICT:
10914 *have_local_changes = 1;
10915 return got_error(GOT_ERR_CANCELLED);
10916 default:
10917 break;
10920 switch (staged_status) {
10921 case GOT_STATUS_ADD:
10922 case GOT_STATUS_DELETE:
10923 case GOT_STATUS_MODIFY:
10924 *have_local_changes = 1;
10925 return got_error(GOT_ERR_CANCELLED);
10926 default:
10927 break;
10930 return NULL;
10933 static const struct got_error *
10934 cmd_histedit(int argc, char *argv[])
10936 const struct got_error *error = NULL;
10937 struct got_worktree *worktree = NULL;
10938 struct got_fileindex *fileindex = NULL;
10939 struct got_repository *repo = NULL;
10940 char *cwd = NULL;
10941 struct got_reference *branch = NULL;
10942 struct got_reference *tmp_branch = NULL;
10943 struct got_object_id *resume_commit_id = NULL;
10944 struct got_object_id *base_commit_id = NULL;
10945 struct got_object_id *head_commit_id = NULL;
10946 struct got_commit_object *commit = NULL;
10947 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10948 struct got_update_progress_arg upa;
10949 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10950 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10951 int list_backups = 0, delete_backups = 0;
10952 const char *edit_script_path = NULL;
10953 struct got_object_id_queue commits;
10954 struct got_pathlist_head merged_paths;
10955 const struct got_object_id_queue *parent_ids;
10956 struct got_object_qid *pid;
10957 struct got_histedit_list histedit_cmds;
10958 struct got_histedit_list_entry *hle;
10959 int *pack_fds = NULL;
10961 STAILQ_INIT(&commits);
10962 TAILQ_INIT(&histedit_cmds);
10963 TAILQ_INIT(&merged_paths);
10964 memset(&upa, 0, sizeof(upa));
10966 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10967 switch (ch) {
10968 case 'a':
10969 abort_edit = 1;
10970 break;
10971 case 'c':
10972 continue_edit = 1;
10973 break;
10974 case 'e':
10975 edit_only = 1;
10976 break;
10977 case 'f':
10978 fold_only = 1;
10979 break;
10980 case 'F':
10981 edit_script_path = optarg;
10982 break;
10983 case 'm':
10984 edit_logmsg_only = 1;
10985 break;
10986 case 'l':
10987 list_backups = 1;
10988 break;
10989 case 'X':
10990 delete_backups = 1;
10991 break;
10992 default:
10993 usage_histedit();
10994 /* NOTREACHED */
10998 argc -= optind;
10999 argv += optind;
11001 #ifndef PROFILE
11002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11003 "unveil", NULL) == -1)
11004 err(1, "pledge");
11005 #endif
11006 if (abort_edit && continue_edit)
11007 option_conflict('a', 'c');
11008 if (edit_script_path && edit_logmsg_only)
11009 option_conflict('F', 'm');
11010 if (abort_edit && edit_logmsg_only)
11011 option_conflict('a', 'm');
11012 if (continue_edit && edit_logmsg_only)
11013 option_conflict('c', 'm');
11014 if (abort_edit && fold_only)
11015 option_conflict('a', 'f');
11016 if (continue_edit && fold_only)
11017 option_conflict('c', 'f');
11018 if (fold_only && edit_logmsg_only)
11019 option_conflict('f', 'm');
11020 if (edit_script_path && fold_only)
11021 option_conflict('F', 'f');
11022 if (abort_edit && edit_only)
11023 option_conflict('a', 'e');
11024 if (continue_edit && edit_only)
11025 option_conflict('c', 'e');
11026 if (edit_only && edit_logmsg_only)
11027 option_conflict('e', 'm');
11028 if (edit_script_path && edit_only)
11029 option_conflict('F', 'e');
11030 if (list_backups) {
11031 if (abort_edit)
11032 option_conflict('l', 'a');
11033 if (continue_edit)
11034 option_conflict('l', 'c');
11035 if (edit_script_path)
11036 option_conflict('l', 'F');
11037 if (edit_logmsg_only)
11038 option_conflict('l', 'm');
11039 if (fold_only)
11040 option_conflict('l', 'f');
11041 if (edit_only)
11042 option_conflict('l', 'e');
11043 if (delete_backups)
11044 option_conflict('l', 'X');
11045 if (argc != 0 && argc != 1)
11046 usage_histedit();
11047 } else if (delete_backups) {
11048 if (abort_edit)
11049 option_conflict('X', 'a');
11050 if (continue_edit)
11051 option_conflict('X', 'c');
11052 if (edit_script_path)
11053 option_conflict('X', 'F');
11054 if (edit_logmsg_only)
11055 option_conflict('X', 'm');
11056 if (fold_only)
11057 option_conflict('X', 'f');
11058 if (edit_only)
11059 option_conflict('X', 'e');
11060 if (list_backups)
11061 option_conflict('X', 'l');
11062 if (argc != 0 && argc != 1)
11063 usage_histedit();
11064 } else if (argc != 0)
11065 usage_histedit();
11068 * This command cannot apply unveil(2) in all cases because the
11069 * user may choose to run an editor to edit the histedit script
11070 * and to edit individual commit log messages.
11071 * unveil(2) traverses exec(2); if an editor is used we have to
11072 * apply unveil after edit script and log messages have been written.
11073 * XXX TODO: Make use of unveil(2) where possible.
11076 cwd = getcwd(NULL, 0);
11077 if (cwd == NULL) {
11078 error = got_error_from_errno("getcwd");
11079 goto done;
11082 error = got_repo_pack_fds_open(&pack_fds);
11083 if (error != NULL)
11084 goto done;
11086 error = got_worktree_open(&worktree, cwd);
11087 if (error) {
11088 if (list_backups || delete_backups) {
11089 if (error->code != GOT_ERR_NOT_WORKTREE)
11090 goto done;
11091 } else {
11092 if (error->code == GOT_ERR_NOT_WORKTREE)
11093 error = wrap_not_worktree_error(error,
11094 "histedit", cwd);
11095 goto done;
11099 if (list_backups || delete_backups) {
11100 error = got_repo_open(&repo,
11101 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11102 NULL, pack_fds);
11103 if (error != NULL)
11104 goto done;
11105 error = apply_unveil(got_repo_get_path(repo), 0,
11106 worktree ? got_worktree_get_root_path(worktree) : NULL);
11107 if (error)
11108 goto done;
11109 error = process_backup_refs(
11110 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11111 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11112 goto done; /* nothing else to do */
11115 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11116 NULL, pack_fds);
11117 if (error != NULL)
11118 goto done;
11120 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11121 if (error)
11122 goto done;
11123 if (rebase_in_progress) {
11124 error = got_error(GOT_ERR_REBASING);
11125 goto done;
11128 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11129 repo);
11130 if (error)
11131 goto done;
11132 if (merge_in_progress) {
11133 error = got_error(GOT_ERR_MERGE_BUSY);
11134 goto done;
11137 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11138 if (error)
11139 goto done;
11141 if (edit_in_progress && edit_logmsg_only) {
11142 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11143 "histedit operation is in progress in this "
11144 "work tree and must be continued or aborted "
11145 "before the -m option can be used");
11146 goto done;
11148 if (edit_in_progress && fold_only) {
11149 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11150 "histedit operation is in progress in this "
11151 "work tree and must be continued or aborted "
11152 "before the -f option can be used");
11153 goto done;
11155 if (edit_in_progress && edit_only) {
11156 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11157 "histedit operation is in progress in this "
11158 "work tree and must be continued or aborted "
11159 "before the -e option can be used");
11160 goto done;
11163 if (edit_in_progress && abort_edit) {
11164 error = got_worktree_histedit_continue(&resume_commit_id,
11165 &tmp_branch, &branch, &base_commit_id, &fileindex,
11166 worktree, repo);
11167 if (error)
11168 goto done;
11169 printf("Switching work tree to %s\n",
11170 got_ref_get_symref_target(branch));
11171 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11172 branch, base_commit_id, abort_progress, &upa);
11173 if (error)
11174 goto done;
11175 printf("Histedit of %s aborted\n",
11176 got_ref_get_symref_target(branch));
11177 print_merge_progress_stats(&upa);
11178 goto done; /* nothing else to do */
11179 } else if (abort_edit) {
11180 error = got_error(GOT_ERR_NOT_HISTEDIT);
11181 goto done;
11184 if (continue_edit) {
11185 char *path;
11187 if (!edit_in_progress) {
11188 error = got_error(GOT_ERR_NOT_HISTEDIT);
11189 goto done;
11192 error = got_worktree_get_histedit_script_path(&path, worktree);
11193 if (error)
11194 goto done;
11196 error = histedit_load_list(&histedit_cmds, path, repo);
11197 free(path);
11198 if (error)
11199 goto done;
11201 error = got_worktree_histedit_continue(&resume_commit_id,
11202 &tmp_branch, &branch, &base_commit_id, &fileindex,
11203 worktree, repo);
11204 if (error)
11205 goto done;
11207 error = got_ref_resolve(&head_commit_id, repo, branch);
11208 if (error)
11209 goto done;
11211 error = got_object_open_as_commit(&commit, repo,
11212 head_commit_id);
11213 if (error)
11214 goto done;
11215 parent_ids = got_object_commit_get_parent_ids(commit);
11216 pid = STAILQ_FIRST(parent_ids);
11217 if (pid == NULL) {
11218 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11219 goto done;
11221 error = collect_commits(&commits, head_commit_id, &pid->id,
11222 base_commit_id, got_worktree_get_path_prefix(worktree),
11223 GOT_ERR_HISTEDIT_PATH, repo);
11224 got_object_commit_close(commit);
11225 commit = NULL;
11226 if (error)
11227 goto done;
11228 } else {
11229 if (edit_in_progress) {
11230 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11231 goto done;
11234 error = got_ref_open(&branch, repo,
11235 got_worktree_get_head_ref_name(worktree), 0);
11236 if (error != NULL)
11237 goto done;
11239 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11240 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11241 "will not edit commit history of a branch outside "
11242 "the \"refs/heads/\" reference namespace");
11243 goto done;
11246 error = got_ref_resolve(&head_commit_id, repo, branch);
11247 got_ref_close(branch);
11248 branch = NULL;
11249 if (error)
11250 goto done;
11252 error = got_object_open_as_commit(&commit, repo,
11253 head_commit_id);
11254 if (error)
11255 goto done;
11256 parent_ids = got_object_commit_get_parent_ids(commit);
11257 pid = STAILQ_FIRST(parent_ids);
11258 if (pid == NULL) {
11259 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11260 goto done;
11262 error = collect_commits(&commits, head_commit_id, &pid->id,
11263 got_worktree_get_base_commit_id(worktree),
11264 got_worktree_get_path_prefix(worktree),
11265 GOT_ERR_HISTEDIT_PATH, repo);
11266 got_object_commit_close(commit);
11267 commit = NULL;
11268 if (error)
11269 goto done;
11271 if (STAILQ_EMPTY(&commits)) {
11272 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11273 goto done;
11276 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11277 &base_commit_id, &fileindex, worktree, repo);
11278 if (error)
11279 goto done;
11281 if (edit_script_path) {
11282 error = histedit_load_list(&histedit_cmds,
11283 edit_script_path, repo);
11284 if (error) {
11285 got_worktree_histedit_abort(worktree, fileindex,
11286 repo, branch, base_commit_id,
11287 abort_progress, &upa);
11288 print_merge_progress_stats(&upa);
11289 goto done;
11291 } else {
11292 const char *branch_name;
11293 branch_name = got_ref_get_symref_target(branch);
11294 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11295 branch_name += 11;
11296 error = histedit_edit_script(&histedit_cmds, &commits,
11297 branch_name, edit_logmsg_only, fold_only,
11298 edit_only, repo);
11299 if (error) {
11300 got_worktree_histedit_abort(worktree, fileindex,
11301 repo, branch, base_commit_id,
11302 abort_progress, &upa);
11303 print_merge_progress_stats(&upa);
11304 goto done;
11309 error = histedit_save_list(&histedit_cmds, worktree,
11310 repo);
11311 if (error) {
11312 got_worktree_histedit_abort(worktree, fileindex,
11313 repo, branch, base_commit_id,
11314 abort_progress, &upa);
11315 print_merge_progress_stats(&upa);
11316 goto done;
11321 error = histedit_check_script(&histedit_cmds, &commits, repo);
11322 if (error)
11323 goto done;
11325 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11326 if (resume_commit_id) {
11327 if (got_object_id_cmp(hle->commit_id,
11328 resume_commit_id) != 0)
11329 continue;
11331 resume_commit_id = NULL;
11332 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11333 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11334 error = histedit_skip_commit(hle, worktree,
11335 repo);
11336 if (error)
11337 goto done;
11338 } else {
11339 struct got_pathlist_head paths;
11340 int have_changes = 0;
11342 TAILQ_INIT(&paths);
11343 error = got_pathlist_append(&paths, "", NULL);
11344 if (error)
11345 goto done;
11346 error = got_worktree_status(worktree, &paths,
11347 repo, 0, check_local_changes, &have_changes,
11348 check_cancelled, NULL);
11349 got_pathlist_free(&paths);
11350 if (error) {
11351 if (error->code != GOT_ERR_CANCELLED)
11352 goto done;
11353 if (sigint_received || sigpipe_received)
11354 goto done;
11356 if (have_changes) {
11357 error = histedit_commit(NULL, worktree,
11358 fileindex, tmp_branch, hle, repo);
11359 if (error)
11360 goto done;
11361 } else {
11362 error = got_object_open_as_commit(
11363 &commit, repo, hle->commit_id);
11364 if (error)
11365 goto done;
11366 error = show_histedit_progress(commit,
11367 hle, NULL);
11368 got_object_commit_close(commit);
11369 commit = NULL;
11370 if (error)
11371 goto done;
11374 continue;
11377 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11378 error = histedit_skip_commit(hle, worktree, repo);
11379 if (error)
11380 goto done;
11381 continue;
11384 error = got_object_open_as_commit(&commit, repo,
11385 hle->commit_id);
11386 if (error)
11387 goto done;
11388 parent_ids = got_object_commit_get_parent_ids(commit);
11389 pid = STAILQ_FIRST(parent_ids);
11391 error = got_worktree_histedit_merge_files(&merged_paths,
11392 worktree, fileindex, &pid->id, hle->commit_id, repo,
11393 update_progress, &upa, check_cancelled, NULL);
11394 if (error)
11395 goto done;
11396 got_object_commit_close(commit);
11397 commit = NULL;
11399 print_merge_progress_stats(&upa);
11400 if (upa.conflicts > 0 || upa.missing > 0 ||
11401 upa.not_deleted > 0 || upa.unversioned > 0) {
11402 if (upa.conflicts > 0) {
11403 error = show_rebase_merge_conflict(
11404 hle->commit_id, repo);
11405 if (error)
11406 goto done;
11408 got_worktree_rebase_pathlist_free(&merged_paths);
11409 break;
11412 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11413 char *id_str;
11414 error = got_object_id_str(&id_str, hle->commit_id);
11415 if (error)
11416 goto done;
11417 printf("Stopping histedit for amending commit %s\n",
11418 id_str);
11419 free(id_str);
11420 got_worktree_rebase_pathlist_free(&merged_paths);
11421 error = got_worktree_histedit_postpone(worktree,
11422 fileindex);
11423 goto done;
11426 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11427 error = histedit_skip_commit(hle, worktree, repo);
11428 if (error)
11429 goto done;
11430 continue;
11433 error = histedit_commit(&merged_paths, worktree, fileindex,
11434 tmp_branch, hle, repo);
11435 got_worktree_rebase_pathlist_free(&merged_paths);
11436 if (error)
11437 goto done;
11440 if (upa.conflicts > 0 || upa.missing > 0 ||
11441 upa.not_deleted > 0 || upa.unversioned > 0) {
11442 error = got_worktree_histedit_postpone(worktree, fileindex);
11443 if (error)
11444 goto done;
11445 if (upa.conflicts > 0 && upa.missing == 0 &&
11446 upa.not_deleted == 0 && upa.unversioned == 0) {
11447 error = got_error_msg(GOT_ERR_CONFLICTS,
11448 "conflicts must be resolved before histedit "
11449 "can continue");
11450 } else if (upa.conflicts > 0) {
11451 error = got_error_msg(GOT_ERR_CONFLICTS,
11452 "conflicts must be resolved before histedit "
11453 "can continue; changes destined for some "
11454 "files were not yet merged and should be "
11455 "merged manually if required before the "
11456 "histedit operation is continued");
11457 } else {
11458 error = got_error_msg(GOT_ERR_CONFLICTS,
11459 "changes destined for some files were not "
11460 "yet merged and should be merged manually "
11461 "if required before the histedit operation "
11462 "is continued");
11464 } else
11465 error = histedit_complete(worktree, fileindex, tmp_branch,
11466 branch, repo);
11467 done:
11468 got_object_id_queue_free(&commits);
11469 histedit_free_list(&histedit_cmds);
11470 free(head_commit_id);
11471 free(base_commit_id);
11472 free(resume_commit_id);
11473 if (commit)
11474 got_object_commit_close(commit);
11475 if (branch)
11476 got_ref_close(branch);
11477 if (tmp_branch)
11478 got_ref_close(tmp_branch);
11479 if (worktree)
11480 got_worktree_close(worktree);
11481 if (repo) {
11482 const struct got_error *close_err = got_repo_close(repo);
11483 if (error == NULL)
11484 error = close_err;
11486 if (pack_fds) {
11487 const struct got_error *pack_err =
11488 got_repo_pack_fds_close(pack_fds);
11489 if (error == NULL)
11490 error = pack_err;
11492 return error;
11495 __dead static void
11496 usage_integrate(void)
11498 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11499 exit(1);
11502 static const struct got_error *
11503 cmd_integrate(int argc, char *argv[])
11505 const struct got_error *error = NULL;
11506 struct got_repository *repo = NULL;
11507 struct got_worktree *worktree = NULL;
11508 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11509 const char *branch_arg = NULL;
11510 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11511 struct got_fileindex *fileindex = NULL;
11512 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11513 int ch;
11514 struct got_update_progress_arg upa;
11515 int *pack_fds = NULL;
11517 while ((ch = getopt(argc, argv, "")) != -1) {
11518 switch (ch) {
11519 default:
11520 usage_integrate();
11521 /* NOTREACHED */
11525 argc -= optind;
11526 argv += optind;
11528 if (argc != 1)
11529 usage_integrate();
11530 branch_arg = argv[0];
11531 #ifndef PROFILE
11532 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11533 "unveil", NULL) == -1)
11534 err(1, "pledge");
11535 #endif
11536 cwd = getcwd(NULL, 0);
11537 if (cwd == NULL) {
11538 error = got_error_from_errno("getcwd");
11539 goto done;
11542 error = got_repo_pack_fds_open(&pack_fds);
11543 if (error != NULL)
11544 goto done;
11546 error = got_worktree_open(&worktree, cwd);
11547 if (error) {
11548 if (error->code == GOT_ERR_NOT_WORKTREE)
11549 error = wrap_not_worktree_error(error, "integrate",
11550 cwd);
11551 goto done;
11554 error = check_rebase_or_histedit_in_progress(worktree);
11555 if (error)
11556 goto done;
11558 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11559 NULL, pack_fds);
11560 if (error != NULL)
11561 goto done;
11563 error = apply_unveil(got_repo_get_path(repo), 0,
11564 got_worktree_get_root_path(worktree));
11565 if (error)
11566 goto done;
11568 error = check_merge_in_progress(worktree, repo);
11569 if (error)
11570 goto done;
11572 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11573 error = got_error_from_errno("asprintf");
11574 goto done;
11577 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11578 &base_branch_ref, worktree, refname, repo);
11579 if (error)
11580 goto done;
11582 refname = strdup(got_ref_get_name(branch_ref));
11583 if (refname == NULL) {
11584 error = got_error_from_errno("strdup");
11585 got_worktree_integrate_abort(worktree, fileindex, repo,
11586 branch_ref, base_branch_ref);
11587 goto done;
11589 base_refname = strdup(got_ref_get_name(base_branch_ref));
11590 if (base_refname == NULL) {
11591 error = got_error_from_errno("strdup");
11592 got_worktree_integrate_abort(worktree, fileindex, repo,
11593 branch_ref, base_branch_ref);
11594 goto done;
11597 error = got_ref_resolve(&commit_id, repo, branch_ref);
11598 if (error)
11599 goto done;
11601 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11602 if (error)
11603 goto done;
11605 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11606 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11607 "specified branch has already been integrated");
11608 got_worktree_integrate_abort(worktree, fileindex, repo,
11609 branch_ref, base_branch_ref);
11610 goto done;
11613 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11614 if (error) {
11615 if (error->code == GOT_ERR_ANCESTRY)
11616 error = got_error(GOT_ERR_REBASE_REQUIRED);
11617 got_worktree_integrate_abort(worktree, fileindex, repo,
11618 branch_ref, base_branch_ref);
11619 goto done;
11622 memset(&upa, 0, sizeof(upa));
11623 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11624 branch_ref, base_branch_ref, update_progress, &upa,
11625 check_cancelled, NULL);
11626 if (error)
11627 goto done;
11629 printf("Integrated %s into %s\n", refname, base_refname);
11630 print_update_progress_stats(&upa);
11631 done:
11632 if (repo) {
11633 const struct got_error *close_err = got_repo_close(repo);
11634 if (error == NULL)
11635 error = close_err;
11637 if (worktree)
11638 got_worktree_close(worktree);
11639 if (pack_fds) {
11640 const struct got_error *pack_err =
11641 got_repo_pack_fds_close(pack_fds);
11642 if (error == NULL)
11643 error = pack_err;
11645 free(cwd);
11646 free(base_commit_id);
11647 free(commit_id);
11648 free(refname);
11649 free(base_refname);
11650 return error;
11653 __dead static void
11654 usage_merge(void)
11656 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11657 getprogname());
11658 exit(1);
11661 static const struct got_error *
11662 cmd_merge(int argc, char *argv[])
11664 const struct got_error *error = NULL;
11665 struct got_worktree *worktree = NULL;
11666 struct got_repository *repo = NULL;
11667 struct got_fileindex *fileindex = NULL;
11668 char *cwd = NULL, *id_str = NULL, *author = NULL;
11669 struct got_reference *branch = NULL, *wt_branch = NULL;
11670 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11671 struct got_object_id *wt_branch_tip = NULL;
11672 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11673 int interrupt_merge = 0;
11674 struct got_update_progress_arg upa;
11675 struct got_object_id *merge_commit_id = NULL;
11676 char *branch_name = NULL;
11677 int *pack_fds = NULL;
11679 memset(&upa, 0, sizeof(upa));
11681 while ((ch = getopt(argc, argv, "acn")) != -1) {
11682 switch (ch) {
11683 case 'a':
11684 abort_merge = 1;
11685 break;
11686 case 'c':
11687 continue_merge = 1;
11688 break;
11689 case 'n':
11690 interrupt_merge = 1;
11691 break;
11692 default:
11693 usage_rebase();
11694 /* NOTREACHED */
11698 argc -= optind;
11699 argv += optind;
11701 #ifndef PROFILE
11702 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11703 "unveil", NULL) == -1)
11704 err(1, "pledge");
11705 #endif
11707 if (abort_merge && continue_merge)
11708 option_conflict('a', 'c');
11709 if (abort_merge || continue_merge) {
11710 if (argc != 0)
11711 usage_merge();
11712 } else if (argc != 1)
11713 usage_merge();
11715 cwd = getcwd(NULL, 0);
11716 if (cwd == NULL) {
11717 error = got_error_from_errno("getcwd");
11718 goto done;
11721 error = got_repo_pack_fds_open(&pack_fds);
11722 if (error != NULL)
11723 goto done;
11725 error = got_worktree_open(&worktree, cwd);
11726 if (error) {
11727 if (error->code == GOT_ERR_NOT_WORKTREE)
11728 error = wrap_not_worktree_error(error,
11729 "merge", cwd);
11730 goto done;
11733 error = got_repo_open(&repo,
11734 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11735 pack_fds);
11736 if (error != NULL)
11737 goto done;
11739 error = apply_unveil(got_repo_get_path(repo), 0,
11740 worktree ? got_worktree_get_root_path(worktree) : NULL);
11741 if (error)
11742 goto done;
11744 error = check_rebase_or_histedit_in_progress(worktree);
11745 if (error)
11746 goto done;
11748 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11749 repo);
11750 if (error)
11751 goto done;
11753 if (abort_merge) {
11754 if (!merge_in_progress) {
11755 error = got_error(GOT_ERR_NOT_MERGING);
11756 goto done;
11758 error = got_worktree_merge_continue(&branch_name,
11759 &branch_tip, &fileindex, worktree, repo);
11760 if (error)
11761 goto done;
11762 error = got_worktree_merge_abort(worktree, fileindex, repo,
11763 abort_progress, &upa);
11764 if (error)
11765 goto done;
11766 printf("Merge of %s aborted\n", branch_name);
11767 goto done; /* nothing else to do */
11770 error = get_author(&author, repo, worktree);
11771 if (error)
11772 goto done;
11774 if (continue_merge) {
11775 if (!merge_in_progress) {
11776 error = got_error(GOT_ERR_NOT_MERGING);
11777 goto done;
11779 error = got_worktree_merge_continue(&branch_name,
11780 &branch_tip, &fileindex, worktree, repo);
11781 if (error)
11782 goto done;
11783 } else {
11784 error = got_ref_open(&branch, repo, argv[0], 0);
11785 if (error != NULL)
11786 goto done;
11787 branch_name = strdup(got_ref_get_name(branch));
11788 if (branch_name == NULL) {
11789 error = got_error_from_errno("strdup");
11790 goto done;
11792 error = got_ref_resolve(&branch_tip, repo, branch);
11793 if (error)
11794 goto done;
11797 error = got_ref_open(&wt_branch, repo,
11798 got_worktree_get_head_ref_name(worktree), 0);
11799 if (error)
11800 goto done;
11801 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11802 if (error)
11803 goto done;
11804 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11805 wt_branch_tip, branch_tip, 0, repo,
11806 check_cancelled, NULL);
11807 if (error && error->code != GOT_ERR_ANCESTRY)
11808 goto done;
11810 if (!continue_merge) {
11811 error = check_path_prefix(wt_branch_tip, branch_tip,
11812 got_worktree_get_path_prefix(worktree),
11813 GOT_ERR_MERGE_PATH, repo);
11814 if (error)
11815 goto done;
11816 if (yca_id) {
11817 error = check_same_branch(wt_branch_tip, branch,
11818 yca_id, repo);
11819 if (error) {
11820 if (error->code != GOT_ERR_ANCESTRY)
11821 goto done;
11822 error = NULL;
11823 } else {
11824 static char msg[512];
11825 snprintf(msg, sizeof(msg),
11826 "cannot create a merge commit because "
11827 "%s is based on %s; %s can be integrated "
11828 "with 'got integrate' instead", branch_name,
11829 got_worktree_get_head_ref_name(worktree),
11830 branch_name);
11831 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11832 goto done;
11835 error = got_worktree_merge_prepare(&fileindex, worktree,
11836 branch, repo);
11837 if (error)
11838 goto done;
11840 error = got_worktree_merge_branch(worktree, fileindex,
11841 yca_id, branch_tip, repo, update_progress, &upa,
11842 check_cancelled, NULL);
11843 if (error)
11844 goto done;
11845 print_merge_progress_stats(&upa);
11846 if (!upa.did_something) {
11847 error = got_worktree_merge_abort(worktree, fileindex,
11848 repo, abort_progress, &upa);
11849 if (error)
11850 goto done;
11851 printf("Already up-to-date\n");
11852 goto done;
11856 if (interrupt_merge) {
11857 error = got_worktree_merge_postpone(worktree, fileindex);
11858 if (error)
11859 goto done;
11860 printf("Merge of %s interrupted on request\n", branch_name);
11861 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11862 upa.not_deleted > 0 || upa.unversioned > 0) {
11863 error = got_worktree_merge_postpone(worktree, fileindex);
11864 if (error)
11865 goto done;
11866 if (upa.conflicts > 0 && upa.missing == 0 &&
11867 upa.not_deleted == 0 && upa.unversioned == 0) {
11868 error = got_error_msg(GOT_ERR_CONFLICTS,
11869 "conflicts must be resolved before merging "
11870 "can continue");
11871 } else if (upa.conflicts > 0) {
11872 error = got_error_msg(GOT_ERR_CONFLICTS,
11873 "conflicts must be resolved before merging "
11874 "can continue; changes destined for some "
11875 "files were not yet merged and "
11876 "should be merged manually if required before the "
11877 "merge operation is continued");
11878 } else {
11879 error = got_error_msg(GOT_ERR_CONFLICTS,
11880 "changes destined for some "
11881 "files were not yet merged and should be "
11882 "merged manually if required before the "
11883 "merge operation is continued");
11885 goto done;
11886 } else {
11887 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11888 fileindex, author, NULL, 1, branch_tip, branch_name,
11889 repo, continue_merge ? print_status : NULL, NULL);
11890 if (error)
11891 goto done;
11892 error = got_worktree_merge_complete(worktree, fileindex, repo);
11893 if (error)
11894 goto done;
11895 error = got_object_id_str(&id_str, merge_commit_id);
11896 if (error)
11897 goto done;
11898 printf("Merged %s into %s: %s\n", branch_name,
11899 got_worktree_get_head_ref_name(worktree),
11900 id_str);
11903 done:
11904 free(id_str);
11905 free(merge_commit_id);
11906 free(author);
11907 free(branch_tip);
11908 free(branch_name);
11909 free(yca_id);
11910 if (branch)
11911 got_ref_close(branch);
11912 if (wt_branch)
11913 got_ref_close(wt_branch);
11914 if (worktree)
11915 got_worktree_close(worktree);
11916 if (repo) {
11917 const struct got_error *close_err = got_repo_close(repo);
11918 if (error == NULL)
11919 error = close_err;
11921 if (pack_fds) {
11922 const struct got_error *pack_err =
11923 got_repo_pack_fds_close(pack_fds);
11924 if (error == NULL)
11925 error = pack_err;
11927 return error;
11930 __dead static void
11931 usage_stage(void)
11933 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11934 "[-S] [file-path ...]\n",
11935 getprogname());
11936 exit(1);
11939 static const struct got_error *
11940 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11941 const char *path, struct got_object_id *blob_id,
11942 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11943 int dirfd, const char *de_name)
11945 const struct got_error *err = NULL;
11946 char *id_str = NULL;
11948 if (staged_status != GOT_STATUS_ADD &&
11949 staged_status != GOT_STATUS_MODIFY &&
11950 staged_status != GOT_STATUS_DELETE)
11951 return NULL;
11953 if (staged_status == GOT_STATUS_ADD ||
11954 staged_status == GOT_STATUS_MODIFY)
11955 err = got_object_id_str(&id_str, staged_blob_id);
11956 else
11957 err = got_object_id_str(&id_str, blob_id);
11958 if (err)
11959 return err;
11961 printf("%s %c %s\n", id_str, staged_status, path);
11962 free(id_str);
11963 return NULL;
11966 static const struct got_error *
11967 cmd_stage(int argc, char *argv[])
11969 const struct got_error *error = NULL;
11970 struct got_repository *repo = NULL;
11971 struct got_worktree *worktree = NULL;
11972 char *cwd = NULL;
11973 struct got_pathlist_head paths;
11974 struct got_pathlist_entry *pe;
11975 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11976 FILE *patch_script_file = NULL;
11977 const char *patch_script_path = NULL;
11978 struct choose_patch_arg cpa;
11979 int *pack_fds = NULL;
11981 TAILQ_INIT(&paths);
11983 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11984 switch (ch) {
11985 case 'l':
11986 list_stage = 1;
11987 break;
11988 case 'p':
11989 pflag = 1;
11990 break;
11991 case 'F':
11992 patch_script_path = optarg;
11993 break;
11994 case 'S':
11995 allow_bad_symlinks = 1;
11996 break;
11997 default:
11998 usage_stage();
11999 /* NOTREACHED */
12003 argc -= optind;
12004 argv += optind;
12006 #ifndef PROFILE
12007 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12008 "unveil", NULL) == -1)
12009 err(1, "pledge");
12010 #endif
12011 if (list_stage && (pflag || patch_script_path))
12012 errx(1, "-l option cannot be used with other options");
12013 if (patch_script_path && !pflag)
12014 errx(1, "-F option can only be used together with -p option");
12016 cwd = getcwd(NULL, 0);
12017 if (cwd == NULL) {
12018 error = got_error_from_errno("getcwd");
12019 goto done;
12022 error = got_repo_pack_fds_open(&pack_fds);
12023 if (error != NULL)
12024 goto done;
12026 error = got_worktree_open(&worktree, cwd);
12027 if (error) {
12028 if (error->code == GOT_ERR_NOT_WORKTREE)
12029 error = wrap_not_worktree_error(error, "stage", cwd);
12030 goto done;
12033 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12034 NULL, pack_fds);
12035 if (error != NULL)
12036 goto done;
12038 if (patch_script_path) {
12039 patch_script_file = fopen(patch_script_path, "re");
12040 if (patch_script_file == NULL) {
12041 error = got_error_from_errno2("fopen",
12042 patch_script_path);
12043 goto done;
12046 error = apply_unveil(got_repo_get_path(repo), 0,
12047 got_worktree_get_root_path(worktree));
12048 if (error)
12049 goto done;
12051 error = check_merge_in_progress(worktree, repo);
12052 if (error)
12053 goto done;
12055 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12056 if (error)
12057 goto done;
12059 if (list_stage)
12060 error = got_worktree_status(worktree, &paths, repo, 0,
12061 print_stage, NULL, check_cancelled, NULL);
12062 else {
12063 cpa.patch_script_file = patch_script_file;
12064 cpa.action = "stage";
12065 error = got_worktree_stage(worktree, &paths,
12066 pflag ? NULL : print_status, NULL,
12067 pflag ? choose_patch : NULL, &cpa,
12068 allow_bad_symlinks, repo);
12070 done:
12071 if (patch_script_file && fclose(patch_script_file) == EOF &&
12072 error == NULL)
12073 error = got_error_from_errno2("fclose", patch_script_path);
12074 if (repo) {
12075 const struct got_error *close_err = got_repo_close(repo);
12076 if (error == NULL)
12077 error = close_err;
12079 if (worktree)
12080 got_worktree_close(worktree);
12081 if (pack_fds) {
12082 const struct got_error *pack_err =
12083 got_repo_pack_fds_close(pack_fds);
12084 if (error == NULL)
12085 error = pack_err;
12087 TAILQ_FOREACH(pe, &paths, entry)
12088 free((char *)pe->path);
12089 got_pathlist_free(&paths);
12090 free(cwd);
12091 return error;
12094 __dead static void
12095 usage_unstage(void)
12097 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12098 "[file-path ...]\n",
12099 getprogname());
12100 exit(1);
12104 static const struct got_error *
12105 cmd_unstage(int argc, char *argv[])
12107 const struct got_error *error = NULL;
12108 struct got_repository *repo = NULL;
12109 struct got_worktree *worktree = NULL;
12110 char *cwd = NULL;
12111 struct got_pathlist_head paths;
12112 struct got_pathlist_entry *pe;
12113 int ch, pflag = 0;
12114 struct got_update_progress_arg upa;
12115 FILE *patch_script_file = NULL;
12116 const char *patch_script_path = NULL;
12117 struct choose_patch_arg cpa;
12118 int *pack_fds = NULL;
12120 TAILQ_INIT(&paths);
12122 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12123 switch (ch) {
12124 case 'p':
12125 pflag = 1;
12126 break;
12127 case 'F':
12128 patch_script_path = optarg;
12129 break;
12130 default:
12131 usage_unstage();
12132 /* NOTREACHED */
12136 argc -= optind;
12137 argv += optind;
12139 #ifndef PROFILE
12140 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12141 "unveil", NULL) == -1)
12142 err(1, "pledge");
12143 #endif
12144 if (patch_script_path && !pflag)
12145 errx(1, "-F option can only be used together with -p option");
12147 cwd = getcwd(NULL, 0);
12148 if (cwd == NULL) {
12149 error = got_error_from_errno("getcwd");
12150 goto done;
12153 error = got_repo_pack_fds_open(&pack_fds);
12154 if (error != NULL)
12155 goto done;
12157 error = got_worktree_open(&worktree, cwd);
12158 if (error) {
12159 if (error->code == GOT_ERR_NOT_WORKTREE)
12160 error = wrap_not_worktree_error(error, "unstage", cwd);
12161 goto done;
12164 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12165 NULL, pack_fds);
12166 if (error != NULL)
12167 goto done;
12169 if (patch_script_path) {
12170 patch_script_file = fopen(patch_script_path, "re");
12171 if (patch_script_file == NULL) {
12172 error = got_error_from_errno2("fopen",
12173 patch_script_path);
12174 goto done;
12178 error = apply_unveil(got_repo_get_path(repo), 0,
12179 got_worktree_get_root_path(worktree));
12180 if (error)
12181 goto done;
12183 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12184 if (error)
12185 goto done;
12187 cpa.patch_script_file = patch_script_file;
12188 cpa.action = "unstage";
12189 memset(&upa, 0, sizeof(upa));
12190 error = got_worktree_unstage(worktree, &paths, update_progress,
12191 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12192 if (!error)
12193 print_merge_progress_stats(&upa);
12194 done:
12195 if (patch_script_file && fclose(patch_script_file) == EOF &&
12196 error == NULL)
12197 error = got_error_from_errno2("fclose", patch_script_path);
12198 if (repo) {
12199 const struct got_error *close_err = got_repo_close(repo);
12200 if (error == NULL)
12201 error = close_err;
12203 if (worktree)
12204 got_worktree_close(worktree);
12205 if (pack_fds) {
12206 const struct got_error *pack_err =
12207 got_repo_pack_fds_close(pack_fds);
12208 if (error == NULL)
12209 error = pack_err;
12211 TAILQ_FOREACH(pe, &paths, entry)
12212 free((char *)pe->path);
12213 got_pathlist_free(&paths);
12214 free(cwd);
12215 return error;
12218 __dead static void
12219 usage_cat(void)
12221 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12222 "arg1 [arg2 ...]\n", getprogname());
12223 exit(1);
12226 static const struct got_error *
12227 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12229 const struct got_error *err;
12230 struct got_blob_object *blob;
12232 err = got_object_open_as_blob(&blob, repo, id, 8192);
12233 if (err)
12234 return err;
12236 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12237 got_object_blob_close(blob);
12238 return err;
12241 static const struct got_error *
12242 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12244 const struct got_error *err;
12245 struct got_tree_object *tree;
12246 int nentries, i;
12248 err = got_object_open_as_tree(&tree, repo, id);
12249 if (err)
12250 return err;
12252 nentries = got_object_tree_get_nentries(tree);
12253 for (i = 0; i < nentries; i++) {
12254 struct got_tree_entry *te;
12255 char *id_str;
12256 if (sigint_received || sigpipe_received)
12257 break;
12258 te = got_object_tree_get_entry(tree, i);
12259 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12260 if (err)
12261 break;
12262 fprintf(outfile, "%s %.7o %s\n", id_str,
12263 got_tree_entry_get_mode(te),
12264 got_tree_entry_get_name(te));
12265 free(id_str);
12268 got_object_tree_close(tree);
12269 return err;
12272 static void
12273 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12275 long long h, m;
12276 char sign = '+';
12278 if (gmtoff < 0) {
12279 sign = '-';
12280 gmtoff = -gmtoff;
12283 h = (long long)gmtoff / 3600;
12284 m = ((long long)gmtoff - h*3600) / 60;
12285 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12288 static const struct got_error *
12289 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12291 const struct got_error *err;
12292 struct got_commit_object *commit;
12293 const struct got_object_id_queue *parent_ids;
12294 struct got_object_qid *pid;
12295 char *id_str = NULL;
12296 const char *logmsg = NULL;
12297 char gmtoff[6];
12299 err = got_object_open_as_commit(&commit, repo, id);
12300 if (err)
12301 return err;
12303 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12304 if (err)
12305 goto done;
12307 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12308 parent_ids = got_object_commit_get_parent_ids(commit);
12309 fprintf(outfile, "numparents %d\n",
12310 got_object_commit_get_nparents(commit));
12311 STAILQ_FOREACH(pid, parent_ids, entry) {
12312 char *pid_str;
12313 err = got_object_id_str(&pid_str, &pid->id);
12314 if (err)
12315 goto done;
12316 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12317 free(pid_str);
12319 format_gmtoff(gmtoff, sizeof(gmtoff),
12320 got_object_commit_get_author_gmtoff(commit));
12321 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12322 got_object_commit_get_author(commit),
12323 (long long)got_object_commit_get_author_time(commit),
12324 gmtoff);
12326 format_gmtoff(gmtoff, sizeof(gmtoff),
12327 got_object_commit_get_committer_gmtoff(commit));
12328 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12329 got_object_commit_get_author(commit),
12330 (long long)got_object_commit_get_committer_time(commit),
12331 gmtoff);
12333 logmsg = got_object_commit_get_logmsg_raw(commit);
12334 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12335 fprintf(outfile, "%s", logmsg);
12336 done:
12337 free(id_str);
12338 got_object_commit_close(commit);
12339 return err;
12342 static const struct got_error *
12343 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12345 const struct got_error *err;
12346 struct got_tag_object *tag;
12347 char *id_str = NULL;
12348 const char *tagmsg = NULL;
12349 char gmtoff[6];
12351 err = got_object_open_as_tag(&tag, repo, id);
12352 if (err)
12353 return err;
12355 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12356 if (err)
12357 goto done;
12359 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12361 switch (got_object_tag_get_object_type(tag)) {
12362 case GOT_OBJ_TYPE_BLOB:
12363 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12364 GOT_OBJ_LABEL_BLOB);
12365 break;
12366 case GOT_OBJ_TYPE_TREE:
12367 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12368 GOT_OBJ_LABEL_TREE);
12369 break;
12370 case GOT_OBJ_TYPE_COMMIT:
12371 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12372 GOT_OBJ_LABEL_COMMIT);
12373 break;
12374 case GOT_OBJ_TYPE_TAG:
12375 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12376 GOT_OBJ_LABEL_TAG);
12377 break;
12378 default:
12379 break;
12382 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12383 got_object_tag_get_name(tag));
12385 format_gmtoff(gmtoff, sizeof(gmtoff),
12386 got_object_tag_get_tagger_gmtoff(tag));
12387 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12388 got_object_tag_get_tagger(tag),
12389 (long long)got_object_tag_get_tagger_time(tag),
12390 gmtoff);
12392 tagmsg = got_object_tag_get_message(tag);
12393 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12394 fprintf(outfile, "%s", tagmsg);
12395 done:
12396 free(id_str);
12397 got_object_tag_close(tag);
12398 return err;
12401 static const struct got_error *
12402 cmd_cat(int argc, char *argv[])
12404 const struct got_error *error;
12405 struct got_repository *repo = NULL;
12406 struct got_worktree *worktree = NULL;
12407 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12408 const char *commit_id_str = NULL;
12409 struct got_object_id *id = NULL, *commit_id = NULL;
12410 struct got_commit_object *commit = NULL;
12411 int ch, obj_type, i, force_path = 0;
12412 struct got_reflist_head refs;
12413 int *pack_fds = NULL;
12415 TAILQ_INIT(&refs);
12417 #ifndef PROFILE
12418 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12419 NULL) == -1)
12420 err(1, "pledge");
12421 #endif
12423 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12424 switch (ch) {
12425 case 'c':
12426 commit_id_str = optarg;
12427 break;
12428 case 'r':
12429 repo_path = realpath(optarg, NULL);
12430 if (repo_path == NULL)
12431 return got_error_from_errno2("realpath",
12432 optarg);
12433 got_path_strip_trailing_slashes(repo_path);
12434 break;
12435 case 'P':
12436 force_path = 1;
12437 break;
12438 default:
12439 usage_cat();
12440 /* NOTREACHED */
12444 argc -= optind;
12445 argv += optind;
12447 cwd = getcwd(NULL, 0);
12448 if (cwd == NULL) {
12449 error = got_error_from_errno("getcwd");
12450 goto done;
12453 error = got_repo_pack_fds_open(&pack_fds);
12454 if (error != NULL)
12455 goto done;
12457 if (repo_path == NULL) {
12458 error = got_worktree_open(&worktree, cwd);
12459 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12460 goto done;
12461 if (worktree) {
12462 repo_path = strdup(
12463 got_worktree_get_repo_path(worktree));
12464 if (repo_path == NULL) {
12465 error = got_error_from_errno("strdup");
12466 goto done;
12469 /* Release work tree lock. */
12470 got_worktree_close(worktree);
12471 worktree = NULL;
12475 if (repo_path == NULL) {
12476 repo_path = strdup(cwd);
12477 if (repo_path == NULL)
12478 return got_error_from_errno("strdup");
12481 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12482 free(repo_path);
12483 if (error != NULL)
12484 goto done;
12486 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12487 if (error)
12488 goto done;
12490 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12491 if (error)
12492 goto done;
12494 if (commit_id_str == NULL)
12495 commit_id_str = GOT_REF_HEAD;
12496 error = got_repo_match_object_id(&commit_id, NULL,
12497 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12498 if (error)
12499 goto done;
12501 error = got_object_open_as_commit(&commit, repo, commit_id);
12502 if (error)
12503 goto done;
12505 for (i = 0; i < argc; i++) {
12506 if (force_path) {
12507 error = got_object_id_by_path(&id, repo, commit,
12508 argv[i]);
12509 if (error)
12510 break;
12511 } else {
12512 error = got_repo_match_object_id(&id, &label, argv[i],
12513 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12514 repo);
12515 if (error) {
12516 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12517 error->code != GOT_ERR_NOT_REF)
12518 break;
12519 error = got_object_id_by_path(&id, repo,
12520 commit, argv[i]);
12521 if (error)
12522 break;
12526 error = got_object_get_type(&obj_type, repo, id);
12527 if (error)
12528 break;
12530 switch (obj_type) {
12531 case GOT_OBJ_TYPE_BLOB:
12532 error = cat_blob(id, repo, stdout);
12533 break;
12534 case GOT_OBJ_TYPE_TREE:
12535 error = cat_tree(id, repo, stdout);
12536 break;
12537 case GOT_OBJ_TYPE_COMMIT:
12538 error = cat_commit(id, repo, stdout);
12539 break;
12540 case GOT_OBJ_TYPE_TAG:
12541 error = cat_tag(id, repo, stdout);
12542 break;
12543 default:
12544 error = got_error(GOT_ERR_OBJ_TYPE);
12545 break;
12547 if (error)
12548 break;
12549 free(label);
12550 label = NULL;
12551 free(id);
12552 id = NULL;
12554 done:
12555 free(label);
12556 free(id);
12557 free(commit_id);
12558 if (commit)
12559 got_object_commit_close(commit);
12560 if (worktree)
12561 got_worktree_close(worktree);
12562 if (repo) {
12563 const struct got_error *close_err = got_repo_close(repo);
12564 if (error == NULL)
12565 error = close_err;
12567 if (pack_fds) {
12568 const struct got_error *pack_err =
12569 got_repo_pack_fds_close(pack_fds);
12570 if (error == NULL)
12571 error = pack_err;
12574 got_ref_list_free(&refs);
12575 return error;
12578 __dead static void
12579 usage_info(void)
12581 fprintf(stderr, "usage: %s info [path ...]\n",
12582 getprogname());
12583 exit(1);
12586 static const struct got_error *
12587 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12588 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12589 struct got_object_id *commit_id)
12591 const struct got_error *err = NULL;
12592 char *id_str = NULL;
12593 char datebuf[128];
12594 struct tm mytm, *tm;
12595 struct got_pathlist_head *paths = arg;
12596 struct got_pathlist_entry *pe;
12599 * Clear error indication from any of the path arguments which
12600 * would cause this file index entry to be displayed.
12602 TAILQ_FOREACH(pe, paths, entry) {
12603 if (got_path_cmp(path, pe->path, strlen(path),
12604 pe->path_len) == 0 ||
12605 got_path_is_child(path, pe->path, pe->path_len))
12606 pe->data = NULL; /* no error */
12609 printf(GOT_COMMIT_SEP_STR);
12610 if (S_ISLNK(mode))
12611 printf("symlink: %s\n", path);
12612 else if (S_ISREG(mode)) {
12613 printf("file: %s\n", path);
12614 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12615 } else if (S_ISDIR(mode))
12616 printf("directory: %s\n", path);
12617 else
12618 printf("something: %s\n", path);
12620 tm = localtime_r(&mtime, &mytm);
12621 if (tm == NULL)
12622 return NULL;
12623 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12624 return got_error(GOT_ERR_NO_SPACE);
12625 printf("timestamp: %s\n", datebuf);
12627 if (blob_id) {
12628 err = got_object_id_str(&id_str, blob_id);
12629 if (err)
12630 return err;
12631 printf("based on blob: %s\n", id_str);
12632 free(id_str);
12635 if (staged_blob_id) {
12636 err = got_object_id_str(&id_str, staged_blob_id);
12637 if (err)
12638 return err;
12639 printf("based on staged blob: %s\n", id_str);
12640 free(id_str);
12643 if (commit_id) {
12644 err = got_object_id_str(&id_str, commit_id);
12645 if (err)
12646 return err;
12647 printf("based on commit: %s\n", id_str);
12648 free(id_str);
12651 return NULL;
12654 static const struct got_error *
12655 cmd_info(int argc, char *argv[])
12657 const struct got_error *error = NULL;
12658 struct got_worktree *worktree = NULL;
12659 char *cwd = NULL, *id_str = NULL;
12660 struct got_pathlist_head paths;
12661 struct got_pathlist_entry *pe;
12662 char *uuidstr = NULL;
12663 int ch, show_files = 0;
12664 int *pack_fds = NULL;
12666 TAILQ_INIT(&paths);
12668 while ((ch = getopt(argc, argv, "")) != -1) {
12669 switch (ch) {
12670 default:
12671 usage_info();
12672 /* NOTREACHED */
12676 argc -= optind;
12677 argv += optind;
12679 #ifndef PROFILE
12680 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12681 NULL) == -1)
12682 err(1, "pledge");
12683 #endif
12684 cwd = getcwd(NULL, 0);
12685 if (cwd == NULL) {
12686 error = got_error_from_errno("getcwd");
12687 goto done;
12690 error = got_repo_pack_fds_open(&pack_fds);
12691 if (error != NULL)
12692 goto done;
12694 error = got_worktree_open(&worktree, cwd);
12695 if (error) {
12696 if (error->code == GOT_ERR_NOT_WORKTREE)
12697 error = wrap_not_worktree_error(error, "info", cwd);
12698 goto done;
12701 #ifndef PROFILE
12702 /* Remove "cpath" promise. */
12703 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12704 NULL) == -1)
12705 err(1, "pledge");
12706 #endif
12707 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12708 if (error)
12709 goto done;
12711 if (argc >= 1) {
12712 error = get_worktree_paths_from_argv(&paths, argc, argv,
12713 worktree);
12714 if (error)
12715 goto done;
12716 show_files = 1;
12719 error = got_object_id_str(&id_str,
12720 got_worktree_get_base_commit_id(worktree));
12721 if (error)
12722 goto done;
12724 error = got_worktree_get_uuid(&uuidstr, worktree);
12725 if (error)
12726 goto done;
12728 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12729 printf("work tree base commit: %s\n", id_str);
12730 printf("work tree path prefix: %s\n",
12731 got_worktree_get_path_prefix(worktree));
12732 printf("work tree branch reference: %s\n",
12733 got_worktree_get_head_ref_name(worktree));
12734 printf("work tree UUID: %s\n", uuidstr);
12735 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12737 if (show_files) {
12738 struct got_pathlist_entry *pe;
12739 TAILQ_FOREACH(pe, &paths, entry) {
12740 if (pe->path_len == 0)
12741 continue;
12743 * Assume this path will fail. This will be corrected
12744 * in print_path_info() in case the path does suceeed.
12746 pe->data = (void *)got_error_path(pe->path,
12747 GOT_ERR_BAD_PATH);
12749 error = got_worktree_path_info(worktree, &paths,
12750 print_path_info, &paths, check_cancelled, NULL);
12751 if (error)
12752 goto done;
12753 TAILQ_FOREACH(pe, &paths, entry) {
12754 if (pe->data != NULL) {
12755 error = pe->data; /* bad path */
12756 break;
12760 done:
12761 if (pack_fds) {
12762 const struct got_error *pack_err =
12763 got_repo_pack_fds_close(pack_fds);
12764 if (error == NULL)
12765 error = pack_err;
12767 TAILQ_FOREACH(pe, &paths, entry)
12768 free((char *)pe->path);
12769 got_pathlist_free(&paths);
12770 free(cwd);
12771 free(id_str);
12772 free(uuidstr);
12773 return error;