Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 int
408 spawn_editor(const char *editor, const char *file)
410 pid_t pid;
411 sig_t sighup, sigint, sigquit;
412 int st = -1;
414 sighup = signal(SIGHUP, SIG_IGN);
415 sigint = signal(SIGINT, SIG_IGN);
416 sigquit = signal(SIGQUIT, SIG_IGN);
418 switch (pid = fork()) {
419 case -1:
420 goto doneediting;
421 case 0:
422 execl(editor, editor, file, (char *)NULL);
423 _exit(127);
426 while (waitpid(pid, &st, 0) == -1)
427 if (errno != EINTR)
428 break;
430 doneediting:
431 (void)signal(SIGHUP, sighup);
432 (void)signal(SIGINT, sigint);
433 (void)signal(SIGQUIT, sigquit);
435 if (!WIFEXITED(st)) {
436 errno = EINTR;
437 return -1;
440 return WEXITSTATUS(st);
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 char *line = NULL;
450 size_t linesize = 0;
451 ssize_t linelen;
452 struct stat st, st2;
453 FILE *fp = NULL;
454 size_t len, logmsg_len;
455 char *initial_content_stripped = NULL, *buf = NULL, *s;
457 *logmsg = NULL;
459 if (stat(logmsg_path, &st) == -1)
460 return got_error_from_errno2("stat", logmsg_path);
462 if (spawn_editor(editor, logmsg_path) == -1)
463 return got_error_from_errno("failed spawning editor");
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification &&
469 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 /*
474 * Set up a stripped version of the initial content without comments
475 * and blank lines. We need this in order to check if the message
476 * has in fact been edited.
477 */
478 initial_content_stripped = malloc(initial_content_len + 1);
479 if (initial_content_stripped == NULL)
480 return got_error_from_errno("malloc");
481 initial_content_stripped[0] = '\0';
483 buf = strdup(initial_content);
484 if (buf == NULL) {
485 err = got_error_from_errno("strdup");
486 goto done;
488 s = buf;
489 len = 0;
490 while ((line = strsep(&s, "\n")) != NULL) {
491 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
492 continue; /* remove comments and leading empty lines */
493 len = strlcat(initial_content_stripped, line,
494 initial_content_len + 1);
495 if (len >= initial_content_len + 1) {
496 err = got_error(GOT_ERR_NO_SPACE);
497 goto done;
500 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
501 initial_content_stripped[len - 1] = '\0';
502 len--;
505 logmsg_len = st2.st_size;
506 *logmsg = malloc(logmsg_len + 1);
507 if (*logmsg == NULL)
508 return got_error_from_errno("malloc");
509 (*logmsg)[0] = '\0';
511 fp = fopen(logmsg_path, "re");
512 if (fp == NULL) {
513 err = got_error_from_errno("fopen");
514 goto done;
517 len = 0;
518 while ((linelen = getline(&line, &linesize, fp)) != -1) {
519 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
520 continue; /* remove comments and leading empty lines */
521 len = strlcat(*logmsg, line, logmsg_len + 1);
522 if (len >= logmsg_len + 1) {
523 err = got_error(GOT_ERR_NO_SPACE);
524 goto done;
527 free(line);
528 if (ferror(fp)) {
529 err = got_ferror(fp, GOT_ERR_IO);
530 goto done;
532 while (len > 0 && (*logmsg)[len - 1] == '\n') {
533 (*logmsg)[len - 1] = '\0';
534 len--;
537 if (len == 0) {
538 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
539 "commit message cannot be empty, aborting");
540 goto done;
542 if (require_modification &&
543 strcmp(*logmsg, initial_content_stripped) == 0)
544 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
545 "no changes made to commit message, aborting");
546 done:
547 free(initial_content_stripped);
548 free(buf);
549 if (fp && fclose(fp) == EOF && err == NULL)
550 err = got_error_from_errno("fclose");
551 if (err) {
552 free(*logmsg);
553 *logmsg = NULL;
555 return err;
558 static const struct got_error *
559 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
560 const char *path_dir, const char *branch_name)
562 char *initial_content = NULL;
563 const struct got_error *err = NULL;
564 int initial_content_len;
565 int fd = -1;
567 initial_content_len = asprintf(&initial_content,
568 "\n# %s to be imported to branch %s\n", path_dir,
569 branch_name);
570 if (initial_content_len == -1)
571 return got_error_from_errno("asprintf");
573 err = got_opentemp_named_fd(logmsg_path, &fd,
574 GOT_TMPDIR_STR "/got-importmsg");
575 if (err)
576 goto done;
578 if (write(fd, initial_content, initial_content_len) == -1) {
579 err = got_error_from_errno2("write", *logmsg_path);
580 goto done;
583 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
584 initial_content_len, 1);
585 done:
586 if (fd != -1 && close(fd) == -1 && err == NULL)
587 err = got_error_from_errno2("close", *logmsg_path);
588 free(initial_content);
589 if (err) {
590 free(*logmsg_path);
591 *logmsg_path = NULL;
593 return err;
596 static const struct got_error *
597 import_progress(void *arg, const char *path)
599 printf("A %s\n", path);
600 return NULL;
603 static int
604 valid_author(const char *author)
606 /*
607 * Really dumb email address check; we're only doing this to
608 * avoid git's object parser breaking on commits we create.
609 */
610 while (*author && *author != '<')
611 author++;
612 if (*author != '<')
613 return 0;
614 while (*author && *author != '@')
615 author++;
616 if (*author != '@')
617 return 0;
618 while (*author && *author != '>')
619 author++;
620 return *author == '>';
623 static const struct got_error *
624 get_author(char **author, struct got_repository *repo,
625 struct got_worktree *worktree)
627 const struct got_error *err = NULL;
628 const char *got_author = NULL, *name, *email;
629 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
631 *author = NULL;
633 if (worktree)
634 worktree_conf = got_worktree_get_gotconfig(worktree);
635 repo_conf = got_repo_get_gotconfig(repo);
637 /*
638 * Priority of potential author information sources, from most
639 * significant to least significant:
640 * 1) work tree's .got/got.conf file
641 * 2) repository's got.conf file
642 * 3) repository's git config file
643 * 4) environment variables
644 * 5) global git config files (in user's home directory or /etc)
645 */
647 if (worktree_conf)
648 got_author = got_gotconfig_get_author(worktree_conf);
649 if (got_author == NULL)
650 got_author = got_gotconfig_get_author(repo_conf);
651 if (got_author == NULL) {
652 name = got_repo_get_gitconfig_author_name(repo);
653 email = got_repo_get_gitconfig_author_email(repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email) == -1)
656 return got_error_from_errno("asprintf");
657 return NULL;
660 got_author = getenv("GOT_AUTHOR");
661 if (got_author == NULL) {
662 name = got_repo_get_global_gitconfig_author_name(repo);
663 email = got_repo_get_global_gitconfig_author_email(
664 repo);
665 if (name && email) {
666 if (asprintf(author, "%s <%s>", name, email)
667 == -1)
668 return got_error_from_errno("asprintf");
669 return NULL;
671 /* TODO: Look up user in password database? */
672 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
676 *author = strdup(got_author);
677 if (*author == NULL)
678 return got_error_from_errno("strdup");
680 if (!valid_author(*author)) {
681 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
682 free(*author);
683 *author = NULL;
685 return err;
688 static const struct got_error *
689 get_gitconfig_path(char **gitconfig_path)
691 const char *homedir = getenv("HOME");
693 *gitconfig_path = NULL;
694 if (homedir) {
695 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
696 return got_error_from_errno("asprintf");
699 return NULL;
702 static const struct got_error *
703 cmd_import(int argc, char *argv[])
705 const struct got_error *error = NULL;
706 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
707 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
708 const char *branch_name = "main";
709 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
710 struct got_repository *repo = NULL;
711 struct got_reference *branch_ref = NULL, *head_ref = NULL;
712 struct got_object_id *new_commit_id = NULL;
713 int ch;
714 struct got_pathlist_head ignores;
715 struct got_pathlist_entry *pe;
716 int preserve_logmsg = 0;
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 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 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;
3708 if (path && path[0] != '\0') {
3709 int obj_type;
3710 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3711 if (err)
3712 goto done;
3713 err = got_object_id_str(&id_str2, obj_id2);
3714 if (err) {
3715 free(obj_id2);
3716 goto done;
3718 if (pcommit) {
3719 err = got_object_id_by_path(&obj_id1, repo,
3720 pcommit, path);
3721 if (err) {
3722 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3723 free(obj_id2);
3724 goto done;
3726 } else {
3727 err = got_object_id_str(&id_str1, obj_id1);
3728 if (err) {
3729 free(obj_id2);
3730 goto done;
3734 err = got_object_get_type(&obj_type, repo, obj_id2);
3735 if (err) {
3736 free(obj_id2);
3737 goto done;
3739 fprintf(outfile,
3740 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3741 switch (obj_type) {
3742 case GOT_OBJ_TYPE_BLOB:
3743 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3744 0, 0, repo, outfile);
3745 break;
3746 case GOT_OBJ_TYPE_TREE:
3747 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3748 0, 0, repo, outfile);
3749 break;
3750 default:
3751 err = got_error(GOT_ERR_OBJ_TYPE);
3752 break;
3754 free(obj_id1);
3755 free(obj_id2);
3756 } else {
3757 obj_id2 = got_object_commit_get_tree_id(commit);
3758 err = got_object_id_str(&id_str2, obj_id2);
3759 if (err)
3760 goto done;
3761 if (pcommit) {
3762 obj_id1 = got_object_commit_get_tree_id(pcommit);
3763 err = got_object_id_str(&id_str1, obj_id1);
3764 if (err)
3765 goto done;
3767 fprintf(outfile,
3768 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3769 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3770 repo, outfile);
3772 done:
3773 free(id_str1);
3774 free(id_str2);
3775 if (pcommit)
3776 got_object_commit_close(pcommit);
3777 return err;
3780 static char *
3781 get_datestr(time_t *time, char *datebuf)
3783 struct tm mytm, *tm;
3784 char *p, *s;
3786 tm = gmtime_r(time, &mytm);
3787 if (tm == NULL)
3788 return NULL;
3789 s = asctime_r(tm, datebuf);
3790 if (s == NULL)
3791 return NULL;
3792 p = strchr(s, '\n');
3793 if (p)
3794 *p = '\0';
3795 return s;
3798 static const struct got_error *
3799 match_commit(int *have_match, struct got_object_id *id,
3800 struct got_commit_object *commit, regex_t *regex)
3802 const struct got_error *err = NULL;
3803 regmatch_t regmatch;
3804 char *id_str = NULL, *logmsg = NULL;
3806 *have_match = 0;
3808 err = got_object_id_str(&id_str, id);
3809 if (err)
3810 return err;
3812 err = got_object_commit_get_logmsg(&logmsg, commit);
3813 if (err)
3814 goto done;
3816 if (regexec(regex, got_object_commit_get_author(commit), 1,
3817 &regmatch, 0) == 0 ||
3818 regexec(regex, got_object_commit_get_committer(commit), 1,
3819 &regmatch, 0) == 0 ||
3820 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3821 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3822 *have_match = 1;
3823 done:
3824 free(id_str);
3825 free(logmsg);
3826 return err;
3829 static void
3830 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3831 regex_t *regex)
3833 regmatch_t regmatch;
3834 struct got_pathlist_entry *pe;
3836 *have_match = 0;
3838 TAILQ_FOREACH(pe, changed_paths, entry) {
3839 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3840 *have_match = 1;
3841 break;
3846 static const struct got_error *
3847 match_patch(int *have_match, struct got_commit_object *commit,
3848 struct got_object_id *id, const char *path, int diff_context,
3849 struct got_repository *repo, regex_t *regex, FILE *f)
3851 const struct got_error *err = NULL;
3852 char *line = NULL;
3853 size_t linesize = 0;
3854 ssize_t linelen;
3855 regmatch_t regmatch;
3857 *have_match = 0;
3859 err = got_opentemp_truncate(f);
3860 if (err)
3861 return err;
3863 err = print_patch(commit, id, path, diff_context, repo, f);
3864 if (err)
3865 goto done;
3867 if (fseeko(f, 0L, SEEK_SET) == -1) {
3868 err = got_error_from_errno("fseeko");
3869 goto done;
3872 while ((linelen = getline(&line, &linesize, f)) != -1) {
3873 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3874 *have_match = 1;
3875 break;
3878 done:
3879 free(line);
3880 return err;
3883 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3885 static const struct got_error*
3886 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3887 struct got_object_id *id, struct got_repository *repo,
3888 int local_only)
3890 static const struct got_error *err = NULL;
3891 struct got_reflist_entry *re;
3892 char *s;
3893 const char *name;
3895 *refs_str = NULL;
3897 TAILQ_FOREACH(re, refs, entry) {
3898 struct got_tag_object *tag = NULL;
3899 struct got_object_id *ref_id;
3900 int cmp;
3902 name = got_ref_get_name(re->ref);
3903 if (strcmp(name, GOT_REF_HEAD) == 0)
3904 continue;
3905 if (strncmp(name, "refs/", 5) == 0)
3906 name += 5;
3907 if (strncmp(name, "got/", 4) == 0)
3908 continue;
3909 if (strncmp(name, "heads/", 6) == 0)
3910 name += 6;
3911 if (strncmp(name, "remotes/", 8) == 0) {
3912 if (local_only)
3913 continue;
3914 name += 8;
3915 s = strstr(name, "/" GOT_REF_HEAD);
3916 if (s != NULL && s[strlen(s)] == '\0')
3917 continue;
3919 err = got_ref_resolve(&ref_id, repo, re->ref);
3920 if (err)
3921 break;
3922 if (strncmp(name, "tags/", 5) == 0) {
3923 err = got_object_open_as_tag(&tag, repo, ref_id);
3924 if (err) {
3925 if (err->code != GOT_ERR_OBJ_TYPE) {
3926 free(ref_id);
3927 break;
3929 /* Ref points at something other than a tag. */
3930 err = NULL;
3931 tag = NULL;
3934 cmp = got_object_id_cmp(tag ?
3935 got_object_tag_get_object_id(tag) : ref_id, id);
3936 free(ref_id);
3937 if (tag)
3938 got_object_tag_close(tag);
3939 if (cmp != 0)
3940 continue;
3941 s = *refs_str;
3942 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3943 s ? ", " : "", name) == -1) {
3944 err = got_error_from_errno("asprintf");
3945 free(s);
3946 *refs_str = NULL;
3947 break;
3949 free(s);
3952 return err;
3955 static const struct got_error *
3956 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3957 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3959 const struct got_error *err = NULL;
3960 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3961 char *comma, *s, *nl;
3962 struct got_reflist_head *refs;
3963 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3964 struct tm tm;
3965 time_t committer_time;
3967 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3968 if (refs) {
3969 err = build_refs_str(&ref_str, refs, id, repo, 1);
3970 if (err)
3971 return err;
3973 /* Display the first matching ref only. */
3974 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3975 *comma = '\0';
3978 if (ref_str == NULL) {
3979 err = got_object_id_str(&id_str, id);
3980 if (err)
3981 return err;
3984 committer_time = got_object_commit_get_committer_time(commit);
3985 if (gmtime_r(&committer_time, &tm) == NULL) {
3986 err = got_error_from_errno("gmtime_r");
3987 goto done;
3989 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3990 err = got_error(GOT_ERR_NO_SPACE);
3991 goto done;
3994 err = got_object_commit_get_logmsg(&logmsg0, commit);
3995 if (err)
3996 goto done;
3998 s = logmsg0;
3999 while (isspace((unsigned char)s[0]))
4000 s++;
4002 nl = strchr(s, '\n');
4003 if (nl) {
4004 *nl = '\0';
4007 if (ref_str)
4008 printf("%s%-7s %s\n", datebuf, ref_str, s);
4009 else
4010 printf("%s%.7s %s\n", datebuf, id_str, s);
4012 if (fflush(stdout) != 0 && err == NULL)
4013 err = got_error_from_errno("fflush");
4014 done:
4015 free(id_str);
4016 free(ref_str);
4017 free(logmsg0);
4018 return err;
4021 static const struct got_error *
4022 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4023 struct got_repository *repo, const char *path,
4024 struct got_pathlist_head *changed_paths, int show_patch,
4025 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4026 const char *custom_refs_str)
4028 const struct got_error *err = NULL;
4029 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4030 char datebuf[26];
4031 time_t committer_time;
4032 const char *author, *committer;
4033 char *refs_str = NULL;
4035 err = got_object_id_str(&id_str, id);
4036 if (err)
4037 return err;
4039 if (custom_refs_str == NULL) {
4040 struct got_reflist_head *refs;
4041 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4042 if (refs) {
4043 err = build_refs_str(&refs_str, refs, id, repo, 0);
4044 if (err)
4045 goto done;
4049 printf(GOT_COMMIT_SEP_STR);
4050 if (custom_refs_str)
4051 printf("commit %s (%s)\n", id_str, custom_refs_str);
4052 else
4053 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4054 refs_str ? refs_str : "", refs_str ? ")" : "");
4055 free(id_str);
4056 id_str = NULL;
4057 free(refs_str);
4058 refs_str = NULL;
4059 printf("from: %s\n", got_object_commit_get_author(commit));
4060 committer_time = got_object_commit_get_committer_time(commit);
4061 datestr = get_datestr(&committer_time, datebuf);
4062 if (datestr)
4063 printf("date: %s UTC\n", datestr);
4064 author = got_object_commit_get_author(commit);
4065 committer = got_object_commit_get_committer(commit);
4066 if (strcmp(author, committer) != 0)
4067 printf("via: %s\n", committer);
4068 if (got_object_commit_get_nparents(commit) > 1) {
4069 const struct got_object_id_queue *parent_ids;
4070 struct got_object_qid *qid;
4071 int n = 1;
4072 parent_ids = got_object_commit_get_parent_ids(commit);
4073 STAILQ_FOREACH(qid, parent_ids, entry) {
4074 err = got_object_id_str(&id_str, &qid->id);
4075 if (err)
4076 goto done;
4077 printf("parent %d: %s\n", n++, id_str);
4078 free(id_str);
4079 id_str = NULL;
4083 err = got_object_commit_get_logmsg(&logmsg0, commit);
4084 if (err)
4085 goto done;
4087 logmsg = logmsg0;
4088 do {
4089 line = strsep(&logmsg, "\n");
4090 if (line)
4091 printf(" %s\n", line);
4092 } while (line);
4093 free(logmsg0);
4095 if (changed_paths) {
4096 struct got_pathlist_entry *pe;
4097 TAILQ_FOREACH(pe, changed_paths, entry) {
4098 struct got_diff_changed_path *cp = pe->data;
4099 printf(" %c %s\n", cp->status, pe->path);
4101 printf("\n");
4103 if (show_patch) {
4104 err = print_patch(commit, id, path, diff_context, repo, stdout);
4105 if (err == 0)
4106 printf("\n");
4109 if (fflush(stdout) != 0 && err == NULL)
4110 err = got_error_from_errno("fflush");
4111 done:
4112 free(id_str);
4113 free(refs_str);
4114 return err;
4117 static const struct got_error *
4118 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4119 struct got_repository *repo, const char *path, int show_changed_paths,
4120 int show_patch, const char *search_pattern, int diff_context, int limit,
4121 int log_branches, int reverse_display_order,
4122 struct got_reflist_object_id_map *refs_idmap, int one_line,
4123 FILE *tmpfile)
4125 const struct got_error *err;
4126 struct got_commit_graph *graph;
4127 regex_t regex;
4128 int have_match;
4129 struct got_object_id_queue reversed_commits;
4130 struct got_object_qid *qid;
4131 struct got_commit_object *commit;
4132 struct got_pathlist_head changed_paths;
4133 struct got_pathlist_entry *pe;
4135 STAILQ_INIT(&reversed_commits);
4136 TAILQ_INIT(&changed_paths);
4138 if (search_pattern && regcomp(&regex, search_pattern,
4139 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4140 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4142 err = got_commit_graph_open(&graph, path, !log_branches);
4143 if (err)
4144 return err;
4145 err = got_commit_graph_iter_start(graph, root_id, repo,
4146 check_cancelled, NULL);
4147 if (err)
4148 goto done;
4149 for (;;) {
4150 struct got_object_id *id;
4152 if (sigint_received || sigpipe_received)
4153 break;
4155 err = got_commit_graph_iter_next(&id, graph, repo,
4156 check_cancelled, NULL);
4157 if (err) {
4158 if (err->code == GOT_ERR_ITER_COMPLETED)
4159 err = NULL;
4160 break;
4162 if (id == NULL)
4163 break;
4165 err = got_object_open_as_commit(&commit, repo, id);
4166 if (err)
4167 break;
4169 if (show_changed_paths && !reverse_display_order) {
4170 err = get_changed_paths(&changed_paths, commit, repo);
4171 if (err)
4172 break;
4175 if (search_pattern) {
4176 err = match_commit(&have_match, id, commit, &regex);
4177 if (err) {
4178 got_object_commit_close(commit);
4179 break;
4181 if (have_match == 0 && show_changed_paths)
4182 match_changed_paths(&have_match,
4183 &changed_paths, &regex);
4184 if (have_match == 0 && show_patch) {
4185 err = match_patch(&have_match, commit, id,
4186 path, diff_context, repo, &regex,
4187 tmpfile);
4188 if (err)
4189 break;
4191 if (have_match == 0) {
4192 got_object_commit_close(commit);
4193 TAILQ_FOREACH(pe, &changed_paths, entry) {
4194 free((char *)pe->path);
4195 free(pe->data);
4197 got_pathlist_free(&changed_paths);
4198 continue;
4202 if (reverse_display_order) {
4203 err = got_object_qid_alloc(&qid, id);
4204 if (err)
4205 break;
4206 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4207 got_object_commit_close(commit);
4208 } else {
4209 if (one_line)
4210 err = print_commit_oneline(commit, id,
4211 repo, refs_idmap);
4212 else
4213 err = print_commit(commit, id, repo, path,
4214 show_changed_paths ? &changed_paths : NULL,
4215 show_patch, diff_context, refs_idmap, NULL);
4216 got_object_commit_close(commit);
4217 if (err)
4218 break;
4220 if ((limit && --limit == 0) ||
4221 (end_id && got_object_id_cmp(id, end_id) == 0))
4222 break;
4224 TAILQ_FOREACH(pe, &changed_paths, entry) {
4225 free((char *)pe->path);
4226 free(pe->data);
4228 got_pathlist_free(&changed_paths);
4230 if (reverse_display_order) {
4231 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4232 err = got_object_open_as_commit(&commit, repo,
4233 &qid->id);
4234 if (err)
4235 break;
4236 if (show_changed_paths) {
4237 err = get_changed_paths(&changed_paths,
4238 commit, repo);
4239 if (err)
4240 break;
4242 if (one_line)
4243 err = print_commit_oneline(commit, &qid->id,
4244 repo, refs_idmap);
4245 else
4246 err = print_commit(commit, &qid->id, repo, path,
4247 show_changed_paths ? &changed_paths : NULL,
4248 show_patch, diff_context, refs_idmap, NULL);
4249 got_object_commit_close(commit);
4250 if (err)
4251 break;
4252 TAILQ_FOREACH(pe, &changed_paths, entry) {
4253 free((char *)pe->path);
4254 free(pe->data);
4256 got_pathlist_free(&changed_paths);
4259 done:
4260 while (!STAILQ_EMPTY(&reversed_commits)) {
4261 qid = STAILQ_FIRST(&reversed_commits);
4262 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4263 got_object_qid_free(qid);
4265 TAILQ_FOREACH(pe, &changed_paths, entry) {
4266 free((char *)pe->path);
4267 free(pe->data);
4269 got_pathlist_free(&changed_paths);
4270 if (search_pattern)
4271 regfree(&regex);
4272 got_commit_graph_close(graph);
4273 return err;
4276 __dead static void
4277 usage_log(void)
4279 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4280 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4281 "[-r repository-path] [-R] [path]\n", getprogname());
4282 exit(1);
4285 static int
4286 get_default_log_limit(void)
4288 const char *got_default_log_limit;
4289 long long n;
4290 const char *errstr;
4292 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4293 if (got_default_log_limit == NULL)
4294 return 0;
4295 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4296 if (errstr != NULL)
4297 return 0;
4298 return n;
4301 static const struct got_error *
4302 cmd_log(int argc, char *argv[])
4304 const struct got_error *error;
4305 struct got_repository *repo = NULL;
4306 struct got_worktree *worktree = NULL;
4307 struct got_object_id *start_id = NULL, *end_id = NULL;
4308 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4309 const char *start_commit = NULL, *end_commit = NULL;
4310 const char *search_pattern = NULL;
4311 int diff_context = -1, ch;
4312 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4313 int reverse_display_order = 0, one_line = 0;
4314 const char *errstr;
4315 struct got_reflist_head refs;
4316 struct got_reflist_object_id_map *refs_idmap = NULL;
4317 FILE *tmpfile = NULL;
4318 int *pack_fds = NULL;
4320 TAILQ_INIT(&refs);
4322 #ifndef PROFILE
4323 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4324 NULL)
4325 == -1)
4326 err(1, "pledge");
4327 #endif
4329 limit = get_default_log_limit();
4331 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4332 switch (ch) {
4333 case 'p':
4334 show_patch = 1;
4335 break;
4336 case 'P':
4337 show_changed_paths = 1;
4338 break;
4339 case 'c':
4340 start_commit = optarg;
4341 break;
4342 case 'C':
4343 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4344 &errstr);
4345 if (errstr != NULL)
4346 errx(1, "number of context lines is %s: %s",
4347 errstr, optarg);
4348 break;
4349 case 'l':
4350 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4351 if (errstr != NULL)
4352 errx(1, "number of commits is %s: %s",
4353 errstr, optarg);
4354 break;
4355 case 'b':
4356 log_branches = 1;
4357 break;
4358 case 'r':
4359 repo_path = realpath(optarg, NULL);
4360 if (repo_path == NULL)
4361 return got_error_from_errno2("realpath",
4362 optarg);
4363 got_path_strip_trailing_slashes(repo_path);
4364 break;
4365 case 'R':
4366 reverse_display_order = 1;
4367 break;
4368 case 's':
4369 one_line = 1;
4370 break;
4371 case 'S':
4372 search_pattern = optarg;
4373 break;
4374 case 'x':
4375 end_commit = optarg;
4376 break;
4377 default:
4378 usage_log();
4379 /* NOTREACHED */
4383 argc -= optind;
4384 argv += optind;
4386 if (diff_context == -1)
4387 diff_context = 3;
4388 else if (!show_patch)
4389 errx(1, "-C requires -p");
4391 if (one_line && (show_patch || show_changed_paths))
4392 errx(1, "cannot use -s with -p or -P");
4394 cwd = getcwd(NULL, 0);
4395 if (cwd == NULL) {
4396 error = got_error_from_errno("getcwd");
4397 goto done;
4400 error = got_repo_pack_fds_open(&pack_fds);
4401 if (error != NULL)
4402 goto done;
4404 if (repo_path == NULL) {
4405 error = got_worktree_open(&worktree, cwd);
4406 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4407 goto done;
4408 error = NULL;
4411 if (argc == 1) {
4412 if (worktree) {
4413 error = got_worktree_resolve_path(&path, worktree,
4414 argv[0]);
4415 if (error)
4416 goto done;
4417 } else {
4418 path = strdup(argv[0]);
4419 if (path == NULL) {
4420 error = got_error_from_errno("strdup");
4421 goto done;
4424 } else if (argc != 0)
4425 usage_log();
4427 if (repo_path == NULL) {
4428 repo_path = worktree ?
4429 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4431 if (repo_path == NULL) {
4432 error = got_error_from_errno("strdup");
4433 goto done;
4436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4437 if (error != NULL)
4438 goto done;
4440 error = apply_unveil(got_repo_get_path(repo), 1,
4441 worktree ? got_worktree_get_root_path(worktree) : NULL);
4442 if (error)
4443 goto done;
4445 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4446 if (error)
4447 goto done;
4449 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4450 if (error)
4451 goto done;
4453 if (start_commit == NULL) {
4454 struct got_reference *head_ref;
4455 struct got_commit_object *commit = NULL;
4456 error = got_ref_open(&head_ref, repo,
4457 worktree ? got_worktree_get_head_ref_name(worktree)
4458 : GOT_REF_HEAD, 0);
4459 if (error != NULL)
4460 goto done;
4461 error = got_ref_resolve(&start_id, repo, head_ref);
4462 got_ref_close(head_ref);
4463 if (error != NULL)
4464 goto done;
4465 error = got_object_open_as_commit(&commit, repo,
4466 start_id);
4467 if (error != NULL)
4468 goto done;
4469 got_object_commit_close(commit);
4470 } else {
4471 error = got_repo_match_object_id(&start_id, NULL,
4472 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4473 if (error != NULL)
4474 goto done;
4476 if (end_commit != NULL) {
4477 error = got_repo_match_object_id(&end_id, NULL,
4478 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4479 if (error != NULL)
4480 goto done;
4483 if (worktree) {
4485 * If a path was specified on the command line it was resolved
4486 * to a path in the work tree above. Prepend the work tree's
4487 * path prefix to obtain the corresponding in-repository path.
4489 if (path) {
4490 const char *prefix;
4491 prefix = got_worktree_get_path_prefix(worktree);
4492 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4493 (path[0] != '\0') ? "/" : "", path) == -1) {
4494 error = got_error_from_errno("asprintf");
4495 goto done;
4498 } else
4499 error = got_repo_map_path(&in_repo_path, repo,
4500 path ? path : "");
4501 if (error != NULL)
4502 goto done;
4503 if (in_repo_path) {
4504 free(path);
4505 path = in_repo_path;
4508 if (worktree) {
4509 /* Release work tree lock. */
4510 got_worktree_close(worktree);
4511 worktree = NULL;
4514 if (search_pattern && show_patch) {
4515 tmpfile = got_opentemp();
4516 if (tmpfile == NULL) {
4517 error = got_error_from_errno("got_opentemp");
4518 goto done;
4522 error = print_commits(start_id, end_id, repo, path ? path : "",
4523 show_changed_paths, show_patch, search_pattern, diff_context,
4524 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4525 tmpfile);
4526 done:
4527 free(path);
4528 free(repo_path);
4529 free(cwd);
4530 if (worktree)
4531 got_worktree_close(worktree);
4532 if (repo) {
4533 const struct got_error *close_err = got_repo_close(repo);
4534 if (error == NULL)
4535 error = close_err;
4537 if (pack_fds) {
4538 const struct got_error *pack_err =
4539 got_repo_pack_fds_close(pack_fds);
4540 if (error == NULL)
4541 error = pack_err;
4543 if (refs_idmap)
4544 got_reflist_object_id_map_free(refs_idmap);
4545 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4546 error = got_error_from_errno("fclose");
4547 got_ref_list_free(&refs);
4548 return error;
4551 __dead static void
4552 usage_diff(void)
4554 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4555 "[-r repository-path] [-s] [-w] [-P] "
4556 "[object1 object2 | path ...]\n", getprogname());
4557 exit(1);
4560 struct print_diff_arg {
4561 struct got_repository *repo;
4562 struct got_worktree *worktree;
4563 int diff_context;
4564 const char *id_str;
4565 int header_shown;
4566 int diff_staged;
4567 int ignore_whitespace;
4568 int force_text_diff;
4572 * Create a file which contains the target path of a symlink so we can feed
4573 * it as content to the diff engine.
4575 static const struct got_error *
4576 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4577 const char *abspath)
4579 const struct got_error *err = NULL;
4580 char target_path[PATH_MAX];
4581 ssize_t target_len, outlen;
4583 *fd = -1;
4585 if (dirfd != -1) {
4586 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4587 if (target_len == -1)
4588 return got_error_from_errno2("readlinkat", abspath);
4589 } else {
4590 target_len = readlink(abspath, target_path, PATH_MAX);
4591 if (target_len == -1)
4592 return got_error_from_errno2("readlink", abspath);
4595 *fd = got_opentempfd();
4596 if (*fd == -1)
4597 return got_error_from_errno("got_opentempfd");
4599 outlen = write(*fd, target_path, target_len);
4600 if (outlen == -1) {
4601 err = got_error_from_errno("got_opentempfd");
4602 goto done;
4605 if (lseek(*fd, 0, SEEK_SET) == -1) {
4606 err = got_error_from_errno2("lseek", abspath);
4607 goto done;
4609 done:
4610 if (err) {
4611 close(*fd);
4612 *fd = -1;
4614 return err;
4617 static const struct got_error *
4618 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4619 const char *path, struct got_object_id *blob_id,
4620 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4621 int dirfd, const char *de_name)
4623 struct print_diff_arg *a = arg;
4624 const struct got_error *err = NULL;
4625 struct got_blob_object *blob1 = NULL;
4626 int fd = -1;
4627 FILE *f1 = NULL, *f2 = NULL;
4628 char *abspath = NULL, *label1 = NULL;
4629 struct stat sb;
4630 off_t size1 = 0;
4632 if (a->diff_staged) {
4633 if (staged_status != GOT_STATUS_MODIFY &&
4634 staged_status != GOT_STATUS_ADD &&
4635 staged_status != GOT_STATUS_DELETE)
4636 return NULL;
4637 } else {
4638 if (staged_status == GOT_STATUS_DELETE)
4639 return NULL;
4640 if (status == GOT_STATUS_NONEXISTENT)
4641 return got_error_set_errno(ENOENT, path);
4642 if (status != GOT_STATUS_MODIFY &&
4643 status != GOT_STATUS_ADD &&
4644 status != GOT_STATUS_DELETE &&
4645 status != GOT_STATUS_CONFLICT)
4646 return NULL;
4649 if (!a->header_shown) {
4650 printf("diff %s %s%s\n", a->id_str,
4651 got_worktree_get_root_path(a->worktree),
4652 a->diff_staged ? " (staged changes)" : "");
4653 a->header_shown = 1;
4656 if (a->diff_staged) {
4657 const char *label1 = NULL, *label2 = NULL;
4658 switch (staged_status) {
4659 case GOT_STATUS_MODIFY:
4660 label1 = path;
4661 label2 = path;
4662 break;
4663 case GOT_STATUS_ADD:
4664 label2 = path;
4665 break;
4666 case GOT_STATUS_DELETE:
4667 label1 = path;
4668 break;
4669 default:
4670 return got_error(GOT_ERR_FILE_STATUS);
4672 f1 = got_opentemp();
4673 if (f1 == NULL) {
4674 err = got_error_from_errno("got_opentemp");
4675 goto done;
4677 f2 = got_opentemp();
4678 if (f2 == NULL) {
4679 err = got_error_from_errno("got_opentemp");
4680 goto done;
4682 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4683 blob_id, staged_blob_id, label1, label2, a->diff_context,
4684 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4685 goto done;
4688 if (staged_status == GOT_STATUS_ADD ||
4689 staged_status == GOT_STATUS_MODIFY) {
4690 char *id_str;
4691 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4692 8192);
4693 if (err)
4694 goto done;
4695 err = got_object_id_str(&id_str, staged_blob_id);
4696 if (err)
4697 goto done;
4698 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4699 err = got_error_from_errno("asprintf");
4700 free(id_str);
4701 goto done;
4703 free(id_str);
4704 } else if (status != GOT_STATUS_ADD) {
4705 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4706 if (err)
4707 goto done;
4710 if (status != GOT_STATUS_DELETE) {
4711 if (asprintf(&abspath, "%s/%s",
4712 got_worktree_get_root_path(a->worktree), path) == -1) {
4713 err = got_error_from_errno("asprintf");
4714 goto done;
4717 if (dirfd != -1) {
4718 fd = openat(dirfd, de_name,
4719 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4720 if (fd == -1) {
4721 if (!got_err_open_nofollow_on_symlink()) {
4722 err = got_error_from_errno2("openat",
4723 abspath);
4724 goto done;
4726 err = get_symlink_target_file(&fd, dirfd,
4727 de_name, abspath);
4728 if (err)
4729 goto done;
4731 } else {
4732 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4733 if (fd == -1) {
4734 if (!got_err_open_nofollow_on_symlink()) {
4735 err = got_error_from_errno2("open",
4736 abspath);
4737 goto done;
4739 err = get_symlink_target_file(&fd, dirfd,
4740 de_name, abspath);
4741 if (err)
4742 goto done;
4745 if (fstat(fd, &sb) == -1) {
4746 err = got_error_from_errno2("fstat", abspath);
4747 goto done;
4749 f2 = fdopen(fd, "r");
4750 if (f2 == NULL) {
4751 err = got_error_from_errno2("fdopen", abspath);
4752 goto done;
4754 fd = -1;
4755 } else
4756 sb.st_size = 0;
4758 if (blob1) {
4759 f1 = got_opentemp();
4760 if (f1 == NULL) {
4761 err = got_error_from_errno("got_opentemp");
4762 goto done;
4764 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4765 blob1);
4766 if (err)
4767 goto done;
4770 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4771 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4772 stdout);
4773 done:
4774 if (blob1)
4775 got_object_blob_close(blob1);
4776 if (f1 && fclose(f1) == EOF && err == NULL)
4777 err = got_error_from_errno("fclose");
4778 if (f2 && fclose(f2) == EOF && err == NULL)
4779 err = got_error_from_errno("fclose");
4780 if (fd != -1 && close(fd) == -1 && err == NULL)
4781 err = got_error_from_errno("close");
4782 free(abspath);
4783 return err;
4786 static const struct got_error *
4787 cmd_diff(int argc, char *argv[])
4789 const struct got_error *error;
4790 struct got_repository *repo = NULL;
4791 struct got_worktree *worktree = NULL;
4792 char *cwd = NULL, *repo_path = NULL;
4793 const char *commit_args[2] = { NULL, NULL };
4794 int ncommit_args = 0;
4795 struct got_object_id *ids[2] = { NULL, NULL };
4796 char *labels[2] = { NULL, NULL };
4797 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4798 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4799 int force_text_diff = 0, force_path = 0, rflag = 0;
4800 const char *errstr;
4801 struct got_reflist_head refs;
4802 struct got_pathlist_head paths;
4803 struct got_pathlist_entry *pe;
4804 FILE *f1 = NULL, *f2 = NULL;
4805 int *pack_fds = NULL;
4807 TAILQ_INIT(&refs);
4808 TAILQ_INIT(&paths);
4810 #ifndef PROFILE
4811 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4812 NULL) == -1)
4813 err(1, "pledge");
4814 #endif
4816 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4817 switch (ch) {
4818 case 'a':
4819 force_text_diff = 1;
4820 break;
4821 case 'c':
4822 if (ncommit_args >= 2)
4823 errx(1, "too many -c options used");
4824 commit_args[ncommit_args++] = optarg;
4825 break;
4826 case 'C':
4827 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4828 &errstr);
4829 if (errstr != NULL)
4830 errx(1, "number of context lines is %s: %s",
4831 errstr, optarg);
4832 break;
4833 case 'r':
4834 repo_path = realpath(optarg, NULL);
4835 if (repo_path == NULL)
4836 return got_error_from_errno2("realpath",
4837 optarg);
4838 got_path_strip_trailing_slashes(repo_path);
4839 rflag = 1;
4840 break;
4841 case 's':
4842 diff_staged = 1;
4843 break;
4844 case 'w':
4845 ignore_whitespace = 1;
4846 break;
4847 case 'P':
4848 force_path = 1;
4849 break;
4850 default:
4851 usage_diff();
4852 /* NOTREACHED */
4856 argc -= optind;
4857 argv += optind;
4859 cwd = getcwd(NULL, 0);
4860 if (cwd == NULL) {
4861 error = got_error_from_errno("getcwd");
4862 goto done;
4865 error = got_repo_pack_fds_open(&pack_fds);
4866 if (error != NULL)
4867 goto done;
4869 if (repo_path == NULL) {
4870 error = got_worktree_open(&worktree, cwd);
4871 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4872 goto done;
4873 else
4874 error = NULL;
4875 if (worktree) {
4876 repo_path =
4877 strdup(got_worktree_get_repo_path(worktree));
4878 if (repo_path == NULL) {
4879 error = got_error_from_errno("strdup");
4880 goto done;
4882 } else {
4883 repo_path = strdup(cwd);
4884 if (repo_path == NULL) {
4885 error = got_error_from_errno("strdup");
4886 goto done;
4891 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4892 free(repo_path);
4893 if (error != NULL)
4894 goto done;
4896 if (rflag || worktree == NULL || ncommit_args > 0) {
4897 if (force_path) {
4898 error = got_error_msg(GOT_ERR_NOT_IMPL,
4899 "-P option can only be used when diffing "
4900 "a work tree");
4901 goto done;
4903 if (diff_staged) {
4904 error = got_error_msg(GOT_ERR_NOT_IMPL,
4905 "-s option can only be used when diffing "
4906 "a work tree");
4907 goto done;
4911 error = apply_unveil(got_repo_get_path(repo), 1,
4912 worktree ? got_worktree_get_root_path(worktree) : NULL);
4913 if (error)
4914 goto done;
4916 if ((!force_path && argc == 2) || ncommit_args > 0) {
4917 int obj_type = (ncommit_args > 0 ?
4918 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4919 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4920 NULL);
4921 if (error)
4922 goto done;
4923 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4924 const char *arg;
4925 if (ncommit_args > 0)
4926 arg = commit_args[i];
4927 else
4928 arg = argv[i];
4929 error = got_repo_match_object_id(&ids[i], &labels[i],
4930 arg, obj_type, &refs, repo);
4931 if (error) {
4932 if (error->code != GOT_ERR_NOT_REF &&
4933 error->code != GOT_ERR_NO_OBJ)
4934 goto done;
4935 if (ncommit_args > 0)
4936 goto done;
4937 error = NULL;
4938 break;
4943 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4944 struct print_diff_arg arg;
4945 char *id_str;
4947 if (worktree == NULL) {
4948 if (argc == 2 && ids[0] == NULL) {
4949 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4950 goto done;
4951 } else if (argc == 2 && ids[1] == NULL) {
4952 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4953 goto done;
4954 } else if (argc > 0) {
4955 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4956 "%s", "specified paths cannot be resolved");
4957 goto done;
4958 } else {
4959 error = got_error(GOT_ERR_NOT_WORKTREE);
4960 goto done;
4964 error = get_worktree_paths_from_argv(&paths, argc, argv,
4965 worktree);
4966 if (error)
4967 goto done;
4969 error = got_object_id_str(&id_str,
4970 got_worktree_get_base_commit_id(worktree));
4971 if (error)
4972 goto done;
4973 arg.repo = repo;
4974 arg.worktree = worktree;
4975 arg.diff_context = diff_context;
4976 arg.id_str = id_str;
4977 arg.header_shown = 0;
4978 arg.diff_staged = diff_staged;
4979 arg.ignore_whitespace = ignore_whitespace;
4980 arg.force_text_diff = force_text_diff;
4982 error = got_worktree_status(worktree, &paths, repo, 0,
4983 print_diff, &arg, check_cancelled, NULL);
4984 free(id_str);
4985 goto done;
4988 if (ncommit_args == 1) {
4989 struct got_commit_object *commit;
4990 error = got_object_open_as_commit(&commit, repo, ids[0]);
4991 if (error)
4992 goto done;
4994 labels[1] = labels[0];
4995 ids[1] = ids[0];
4996 if (got_object_commit_get_nparents(commit) > 0) {
4997 const struct got_object_id_queue *pids;
4998 struct got_object_qid *pid;
4999 pids = got_object_commit_get_parent_ids(commit);
5000 pid = STAILQ_FIRST(pids);
5001 ids[0] = got_object_id_dup(&pid->id);
5002 if (ids[0] == NULL) {
5003 error = got_error_from_errno(
5004 "got_object_id_dup");
5005 got_object_commit_close(commit);
5006 goto done;
5008 error = got_object_id_str(&labels[0], ids[0]);
5009 if (error) {
5010 got_object_commit_close(commit);
5011 goto done;
5013 } else {
5014 ids[0] = NULL;
5015 labels[0] = strdup("/dev/null");
5016 if (labels[0] == NULL) {
5017 error = got_error_from_errno("strdup");
5018 got_object_commit_close(commit);
5019 goto done;
5023 got_object_commit_close(commit);
5026 if (ncommit_args == 0 && argc > 2) {
5027 error = got_error_msg(GOT_ERR_BAD_PATH,
5028 "path arguments cannot be used when diffing two objects");
5029 goto done;
5032 if (ids[0]) {
5033 error = got_object_get_type(&type1, repo, ids[0]);
5034 if (error)
5035 goto done;
5038 error = got_object_get_type(&type2, repo, ids[1]);
5039 if (error)
5040 goto done;
5041 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5042 error = got_error(GOT_ERR_OBJ_TYPE);
5043 goto done;
5045 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5046 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5047 "path arguments cannot be used when diffing blobs");
5048 goto done;
5051 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5052 char *in_repo_path;
5053 struct got_pathlist_entry *new;
5054 if (worktree) {
5055 const char *prefix;
5056 char *p;
5057 error = got_worktree_resolve_path(&p, worktree,
5058 argv[i]);
5059 if (error)
5060 goto done;
5061 prefix = got_worktree_get_path_prefix(worktree);
5062 while (prefix[0] == '/')
5063 prefix++;
5064 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5065 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5066 p) == -1) {
5067 error = got_error_from_errno("asprintf");
5068 free(p);
5069 goto done;
5071 free(p);
5072 } else {
5073 char *mapped_path, *s;
5074 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5075 if (error)
5076 goto done;
5077 s = mapped_path;
5078 while (s[0] == '/')
5079 s++;
5080 in_repo_path = strdup(s);
5081 if (in_repo_path == NULL) {
5082 error = got_error_from_errno("asprintf");
5083 free(mapped_path);
5084 goto done;
5086 free(mapped_path);
5089 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5090 if (error || new == NULL /* duplicate */)
5091 free(in_repo_path);
5092 if (error)
5093 goto done;
5096 if (worktree) {
5097 /* Release work tree lock. */
5098 got_worktree_close(worktree);
5099 worktree = NULL;
5102 f1 = got_opentemp();
5103 if (f1 == NULL) {
5104 error = got_error_from_errno("got_opentemp");
5105 goto done;
5108 f2 = got_opentemp();
5109 if (f2 == NULL) {
5110 error = got_error_from_errno("got_opentemp");
5111 goto done;
5114 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5115 case GOT_OBJ_TYPE_BLOB:
5116 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5117 ids[0], ids[1], NULL, NULL, diff_context,
5118 ignore_whitespace, force_text_diff, repo, stdout);
5119 break;
5120 case GOT_OBJ_TYPE_TREE:
5121 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5122 ids[0], ids[1], &paths, "", "", diff_context,
5123 ignore_whitespace, force_text_diff, repo, stdout);
5124 break;
5125 case GOT_OBJ_TYPE_COMMIT:
5126 printf("diff %s %s\n", labels[0], labels[1]);
5127 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5128 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5129 force_text_diff, repo, stdout);
5130 break;
5131 default:
5132 error = got_error(GOT_ERR_OBJ_TYPE);
5134 done:
5135 free(labels[0]);
5136 free(labels[1]);
5137 free(ids[0]);
5138 free(ids[1]);
5139 if (worktree)
5140 got_worktree_close(worktree);
5141 if (repo) {
5142 const struct got_error *close_err = got_repo_close(repo);
5143 if (error == NULL)
5144 error = close_err;
5146 if (pack_fds) {
5147 const struct got_error *pack_err =
5148 got_repo_pack_fds_close(pack_fds);
5149 if (error == NULL)
5150 error = pack_err;
5152 TAILQ_FOREACH(pe, &paths, entry)
5153 free((char *)pe->path);
5154 got_pathlist_free(&paths);
5155 got_ref_list_free(&refs);
5156 if (f1 && fclose(f1) == EOF && error == NULL)
5157 error = got_error_from_errno("fclose");
5158 if (f2 && fclose(f2) == EOF && error == NULL)
5159 error = got_error_from_errno("fclose");
5160 return error;
5163 __dead static void
5164 usage_blame(void)
5166 fprintf(stderr,
5167 "usage: %s blame [-c commit] [-r repository-path] path\n",
5168 getprogname());
5169 exit(1);
5172 struct blame_line {
5173 int annotated;
5174 char *id_str;
5175 char *committer;
5176 char datebuf[11]; /* YYYY-MM-DD + NUL */
5179 struct blame_cb_args {
5180 struct blame_line *lines;
5181 int nlines;
5182 int nlines_prec;
5183 int lineno_cur;
5184 off_t *line_offsets;
5185 FILE *f;
5186 struct got_repository *repo;
5189 static const struct got_error *
5190 blame_cb(void *arg, int nlines, int lineno,
5191 struct got_commit_object *commit, struct got_object_id *id)
5193 const struct got_error *err = NULL;
5194 struct blame_cb_args *a = arg;
5195 struct blame_line *bline;
5196 char *line = NULL;
5197 size_t linesize = 0;
5198 off_t offset;
5199 struct tm tm;
5200 time_t committer_time;
5202 if (nlines != a->nlines ||
5203 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5204 return got_error(GOT_ERR_RANGE);
5206 if (sigint_received)
5207 return got_error(GOT_ERR_ITER_COMPLETED);
5209 if (lineno == -1)
5210 return NULL; /* no change in this commit */
5212 /* Annotate this line. */
5213 bline = &a->lines[lineno - 1];
5214 if (bline->annotated)
5215 return NULL;
5216 err = got_object_id_str(&bline->id_str, id);
5217 if (err)
5218 return err;
5220 bline->committer = strdup(got_object_commit_get_committer(commit));
5221 if (bline->committer == NULL) {
5222 err = got_error_from_errno("strdup");
5223 goto done;
5226 committer_time = got_object_commit_get_committer_time(commit);
5227 if (gmtime_r(&committer_time, &tm) == NULL)
5228 return got_error_from_errno("gmtime_r");
5229 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5230 &tm) == 0) {
5231 err = got_error(GOT_ERR_NO_SPACE);
5232 goto done;
5234 bline->annotated = 1;
5236 /* Print lines annotated so far. */
5237 bline = &a->lines[a->lineno_cur - 1];
5238 if (!bline->annotated)
5239 goto done;
5241 offset = a->line_offsets[a->lineno_cur - 1];
5242 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5243 err = got_error_from_errno("fseeko");
5244 goto done;
5247 while (bline->annotated) {
5248 char *smallerthan, *at, *nl, *committer;
5249 size_t len;
5251 if (getline(&line, &linesize, a->f) == -1) {
5252 if (ferror(a->f))
5253 err = got_error_from_errno("getline");
5254 break;
5257 committer = bline->committer;
5258 smallerthan = strchr(committer, '<');
5259 if (smallerthan && smallerthan[1] != '\0')
5260 committer = smallerthan + 1;
5261 at = strchr(committer, '@');
5262 if (at)
5263 *at = '\0';
5264 len = strlen(committer);
5265 if (len >= 9)
5266 committer[8] = '\0';
5268 nl = strchr(line, '\n');
5269 if (nl)
5270 *nl = '\0';
5271 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5272 bline->id_str, bline->datebuf, committer, line);
5274 a->lineno_cur++;
5275 bline = &a->lines[a->lineno_cur - 1];
5277 done:
5278 free(line);
5279 return err;
5282 static const struct got_error *
5283 cmd_blame(int argc, char *argv[])
5285 const struct got_error *error;
5286 struct got_repository *repo = NULL;
5287 struct got_worktree *worktree = NULL;
5288 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5289 char *link_target = NULL;
5290 struct got_object_id *obj_id = NULL;
5291 struct got_object_id *commit_id = NULL;
5292 struct got_commit_object *commit = NULL;
5293 struct got_blob_object *blob = NULL;
5294 char *commit_id_str = NULL;
5295 struct blame_cb_args bca;
5296 int ch, obj_type, i;
5297 off_t filesize;
5298 int *pack_fds = NULL;
5300 memset(&bca, 0, sizeof(bca));
5302 #ifndef PROFILE
5303 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5304 NULL) == -1)
5305 err(1, "pledge");
5306 #endif
5308 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5309 switch (ch) {
5310 case 'c':
5311 commit_id_str = optarg;
5312 break;
5313 case 'r':
5314 repo_path = realpath(optarg, NULL);
5315 if (repo_path == NULL)
5316 return got_error_from_errno2("realpath",
5317 optarg);
5318 got_path_strip_trailing_slashes(repo_path);
5319 break;
5320 default:
5321 usage_blame();
5322 /* NOTREACHED */
5326 argc -= optind;
5327 argv += optind;
5329 if (argc == 1)
5330 path = argv[0];
5331 else
5332 usage_blame();
5334 cwd = getcwd(NULL, 0);
5335 if (cwd == NULL) {
5336 error = got_error_from_errno("getcwd");
5337 goto done;
5340 error = got_repo_pack_fds_open(&pack_fds);
5341 if (error != NULL)
5342 goto done;
5344 if (repo_path == NULL) {
5345 error = got_worktree_open(&worktree, cwd);
5346 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5347 goto done;
5348 else
5349 error = NULL;
5350 if (worktree) {
5351 repo_path =
5352 strdup(got_worktree_get_repo_path(worktree));
5353 if (repo_path == NULL) {
5354 error = got_error_from_errno("strdup");
5355 if (error)
5356 goto done;
5358 } else {
5359 repo_path = strdup(cwd);
5360 if (repo_path == NULL) {
5361 error = got_error_from_errno("strdup");
5362 goto done;
5367 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5368 if (error != NULL)
5369 goto done;
5371 if (worktree) {
5372 const char *prefix = got_worktree_get_path_prefix(worktree);
5373 char *p;
5375 error = got_worktree_resolve_path(&p, worktree, path);
5376 if (error)
5377 goto done;
5378 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5379 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5380 p) == -1) {
5381 error = got_error_from_errno("asprintf");
5382 free(p);
5383 goto done;
5385 free(p);
5386 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5387 } else {
5388 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5389 if (error)
5390 goto done;
5391 error = got_repo_map_path(&in_repo_path, repo, path);
5393 if (error)
5394 goto done;
5396 if (commit_id_str == NULL) {
5397 struct got_reference *head_ref;
5398 error = got_ref_open(&head_ref, repo, worktree ?
5399 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5400 if (error != NULL)
5401 goto done;
5402 error = got_ref_resolve(&commit_id, repo, head_ref);
5403 got_ref_close(head_ref);
5404 if (error != NULL)
5405 goto done;
5406 } else {
5407 struct got_reflist_head refs;
5408 TAILQ_INIT(&refs);
5409 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5410 NULL);
5411 if (error)
5412 goto done;
5413 error = got_repo_match_object_id(&commit_id, NULL,
5414 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5415 got_ref_list_free(&refs);
5416 if (error)
5417 goto done;
5420 if (worktree) {
5421 /* Release work tree lock. */
5422 got_worktree_close(worktree);
5423 worktree = NULL;
5426 error = got_object_open_as_commit(&commit, repo, commit_id);
5427 if (error)
5428 goto done;
5430 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5431 commit, repo);
5432 if (error)
5433 goto done;
5435 error = got_object_id_by_path(&obj_id, repo, commit,
5436 link_target ? link_target : in_repo_path);
5437 if (error)
5438 goto done;
5440 error = got_object_get_type(&obj_type, repo, obj_id);
5441 if (error)
5442 goto done;
5444 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5445 error = got_error_path(link_target ? link_target : in_repo_path,
5446 GOT_ERR_OBJ_TYPE);
5447 goto done;
5450 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5451 if (error)
5452 goto done;
5453 bca.f = got_opentemp();
5454 if (bca.f == NULL) {
5455 error = got_error_from_errno("got_opentemp");
5456 goto done;
5458 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5459 &bca.line_offsets, bca.f, blob);
5460 if (error || bca.nlines == 0)
5461 goto done;
5463 /* Don't include \n at EOF in the blame line count. */
5464 if (bca.line_offsets[bca.nlines - 1] == filesize)
5465 bca.nlines--;
5467 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5468 if (bca.lines == NULL) {
5469 error = got_error_from_errno("calloc");
5470 goto done;
5472 bca.lineno_cur = 1;
5473 bca.nlines_prec = 0;
5474 i = bca.nlines;
5475 while (i > 0) {
5476 i /= 10;
5477 bca.nlines_prec++;
5479 bca.repo = repo;
5481 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5482 repo, blame_cb, &bca, check_cancelled, NULL);
5483 done:
5484 free(in_repo_path);
5485 free(link_target);
5486 free(repo_path);
5487 free(cwd);
5488 free(commit_id);
5489 free(obj_id);
5490 if (commit)
5491 got_object_commit_close(commit);
5492 if (blob)
5493 got_object_blob_close(blob);
5494 if (worktree)
5495 got_worktree_close(worktree);
5496 if (repo) {
5497 const struct got_error *close_err = got_repo_close(repo);
5498 if (error == NULL)
5499 error = close_err;
5501 if (pack_fds) {
5502 const struct got_error *pack_err =
5503 got_repo_pack_fds_close(pack_fds);
5504 if (error == NULL)
5505 error = pack_err;
5507 if (bca.lines) {
5508 for (i = 0; i < bca.nlines; i++) {
5509 struct blame_line *bline = &bca.lines[i];
5510 free(bline->id_str);
5511 free(bline->committer);
5513 free(bca.lines);
5515 free(bca.line_offsets);
5516 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5517 error = got_error_from_errno("fclose");
5518 return error;
5521 __dead static void
5522 usage_tree(void)
5524 fprintf(stderr,
5525 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5526 getprogname());
5527 exit(1);
5530 static const struct got_error *
5531 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5532 const char *root_path, struct got_repository *repo)
5534 const struct got_error *err = NULL;
5535 int is_root_path = (strcmp(path, root_path) == 0);
5536 const char *modestr = "";
5537 mode_t mode = got_tree_entry_get_mode(te);
5538 char *link_target = NULL;
5540 path += strlen(root_path);
5541 while (path[0] == '/')
5542 path++;
5544 if (got_object_tree_entry_is_submodule(te))
5545 modestr = "$";
5546 else if (S_ISLNK(mode)) {
5547 int i;
5549 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5550 if (err)
5551 return err;
5552 for (i = 0; i < strlen(link_target); i++) {
5553 if (!isprint((unsigned char)link_target[i]))
5554 link_target[i] = '?';
5557 modestr = "@";
5559 else if (S_ISDIR(mode))
5560 modestr = "/";
5561 else if (mode & S_IXUSR)
5562 modestr = "*";
5564 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5565 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5566 link_target ? " -> ": "", link_target ? link_target : "");
5568 free(link_target);
5569 return NULL;
5572 static const struct got_error *
5573 print_tree(const char *path, struct got_commit_object *commit,
5574 int show_ids, int recurse, const char *root_path,
5575 struct got_repository *repo)
5577 const struct got_error *err = NULL;
5578 struct got_object_id *tree_id = NULL;
5579 struct got_tree_object *tree = NULL;
5580 int nentries, i;
5582 err = got_object_id_by_path(&tree_id, repo, commit, path);
5583 if (err)
5584 goto done;
5586 err = got_object_open_as_tree(&tree, repo, tree_id);
5587 if (err)
5588 goto done;
5589 nentries = got_object_tree_get_nentries(tree);
5590 for (i = 0; i < nentries; i++) {
5591 struct got_tree_entry *te;
5592 char *id = NULL;
5594 if (sigint_received || sigpipe_received)
5595 break;
5597 te = got_object_tree_get_entry(tree, i);
5598 if (show_ids) {
5599 char *id_str;
5600 err = got_object_id_str(&id_str,
5601 got_tree_entry_get_id(te));
5602 if (err)
5603 goto done;
5604 if (asprintf(&id, "%s ", id_str) == -1) {
5605 err = got_error_from_errno("asprintf");
5606 free(id_str);
5607 goto done;
5609 free(id_str);
5611 err = print_entry(te, id, path, root_path, repo);
5612 free(id);
5613 if (err)
5614 goto done;
5616 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5617 char *child_path;
5618 if (asprintf(&child_path, "%s%s%s", path,
5619 path[0] == '/' && path[1] == '\0' ? "" : "/",
5620 got_tree_entry_get_name(te)) == -1) {
5621 err = got_error_from_errno("asprintf");
5622 goto done;
5624 err = print_tree(child_path, commit, show_ids, 1,
5625 root_path, repo);
5626 free(child_path);
5627 if (err)
5628 goto done;
5631 done:
5632 if (tree)
5633 got_object_tree_close(tree);
5634 free(tree_id);
5635 return err;
5638 static const struct got_error *
5639 cmd_tree(int argc, char *argv[])
5641 const struct got_error *error;
5642 struct got_repository *repo = NULL;
5643 struct got_worktree *worktree = NULL;
5644 const char *path, *refname = NULL;
5645 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5646 struct got_object_id *commit_id = NULL;
5647 struct got_commit_object *commit = NULL;
5648 char *commit_id_str = NULL;
5649 int show_ids = 0, recurse = 0;
5650 int ch;
5651 int *pack_fds = NULL;
5653 #ifndef PROFILE
5654 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5655 NULL) == -1)
5656 err(1, "pledge");
5657 #endif
5659 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5660 switch (ch) {
5661 case 'c':
5662 commit_id_str = optarg;
5663 break;
5664 case 'r':
5665 repo_path = realpath(optarg, NULL);
5666 if (repo_path == NULL)
5667 return got_error_from_errno2("realpath",
5668 optarg);
5669 got_path_strip_trailing_slashes(repo_path);
5670 break;
5671 case 'i':
5672 show_ids = 1;
5673 break;
5674 case 'R':
5675 recurse = 1;
5676 break;
5677 default:
5678 usage_tree();
5679 /* NOTREACHED */
5683 argc -= optind;
5684 argv += optind;
5686 if (argc == 1)
5687 path = argv[0];
5688 else if (argc > 1)
5689 usage_tree();
5690 else
5691 path = NULL;
5693 cwd = getcwd(NULL, 0);
5694 if (cwd == NULL) {
5695 error = got_error_from_errno("getcwd");
5696 goto done;
5699 error = got_repo_pack_fds_open(&pack_fds);
5700 if (error != NULL)
5701 goto done;
5703 if (repo_path == NULL) {
5704 error = got_worktree_open(&worktree, cwd);
5705 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5706 goto done;
5707 else
5708 error = NULL;
5709 if (worktree) {
5710 repo_path =
5711 strdup(got_worktree_get_repo_path(worktree));
5712 if (repo_path == NULL)
5713 error = got_error_from_errno("strdup");
5714 if (error)
5715 goto done;
5716 } else {
5717 repo_path = strdup(cwd);
5718 if (repo_path == NULL) {
5719 error = got_error_from_errno("strdup");
5720 goto done;
5725 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5726 if (error != NULL)
5727 goto done;
5729 if (worktree) {
5730 const char *prefix = got_worktree_get_path_prefix(worktree);
5731 char *p;
5733 if (path == NULL)
5734 path = "";
5735 error = got_worktree_resolve_path(&p, worktree, path);
5736 if (error)
5737 goto done;
5738 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5739 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5740 p) == -1) {
5741 error = got_error_from_errno("asprintf");
5742 free(p);
5743 goto done;
5745 free(p);
5746 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5747 if (error)
5748 goto done;
5749 } else {
5750 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5751 if (error)
5752 goto done;
5753 if (path == NULL)
5754 path = "/";
5755 error = got_repo_map_path(&in_repo_path, repo, path);
5756 if (error != NULL)
5757 goto done;
5760 if (commit_id_str == NULL) {
5761 struct got_reference *head_ref;
5762 if (worktree)
5763 refname = got_worktree_get_head_ref_name(worktree);
5764 else
5765 refname = GOT_REF_HEAD;
5766 error = got_ref_open(&head_ref, repo, refname, 0);
5767 if (error != NULL)
5768 goto done;
5769 error = got_ref_resolve(&commit_id, repo, head_ref);
5770 got_ref_close(head_ref);
5771 if (error != NULL)
5772 goto done;
5773 } else {
5774 struct got_reflist_head refs;
5775 TAILQ_INIT(&refs);
5776 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5777 NULL);
5778 if (error)
5779 goto done;
5780 error = got_repo_match_object_id(&commit_id, NULL,
5781 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5782 got_ref_list_free(&refs);
5783 if (error)
5784 goto done;
5787 if (worktree) {
5788 /* Release work tree lock. */
5789 got_worktree_close(worktree);
5790 worktree = NULL;
5793 error = got_object_open_as_commit(&commit, repo, commit_id);
5794 if (error)
5795 goto done;
5797 error = print_tree(in_repo_path, commit, show_ids, recurse,
5798 in_repo_path, repo);
5799 done:
5800 free(in_repo_path);
5801 free(repo_path);
5802 free(cwd);
5803 free(commit_id);
5804 if (commit)
5805 got_object_commit_close(commit);
5806 if (worktree)
5807 got_worktree_close(worktree);
5808 if (repo) {
5809 const struct got_error *close_err = got_repo_close(repo);
5810 if (error == NULL)
5811 error = close_err;
5813 if (pack_fds) {
5814 const struct got_error *pack_err =
5815 got_repo_pack_fds_close(pack_fds);
5816 if (error == NULL)
5817 error = pack_err;
5819 return error;
5822 __dead static void
5823 usage_status(void)
5825 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5826 "[-S status-codes] [path ...]\n", getprogname());
5827 exit(1);
5830 struct got_status_arg {
5831 char *status_codes;
5832 int suppress;
5835 static const struct got_error *
5836 print_status(void *arg, unsigned char status, unsigned char staged_status,
5837 const char *path, struct got_object_id *blob_id,
5838 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5839 int dirfd, const char *de_name)
5841 struct got_status_arg *st = arg;
5843 if (status == staged_status && (status == GOT_STATUS_DELETE))
5844 status = GOT_STATUS_NO_CHANGE;
5845 if (st != NULL && st->status_codes) {
5846 size_t ncodes = strlen(st->status_codes);
5847 int i, j = 0;
5849 for (i = 0; i < ncodes ; i++) {
5850 if (st->suppress) {
5851 if (status == st->status_codes[i] ||
5852 staged_status == st->status_codes[i]) {
5853 j++;
5854 continue;
5856 } else {
5857 if (status == st->status_codes[i] ||
5858 staged_status == st->status_codes[i])
5859 break;
5863 if (st->suppress && j == 0)
5864 goto print;
5866 if (i == ncodes)
5867 return NULL;
5869 print:
5870 printf("%c%c %s\n", status, staged_status, path);
5871 return NULL;
5874 static const struct got_error *
5875 cmd_status(int argc, char *argv[])
5877 const struct got_error *error = NULL;
5878 struct got_repository *repo = NULL;
5879 struct got_worktree *worktree = NULL;
5880 struct got_status_arg st;
5881 char *cwd = NULL;
5882 struct got_pathlist_head paths;
5883 struct got_pathlist_entry *pe;
5884 int ch, i, no_ignores = 0;
5885 int *pack_fds = NULL;
5887 TAILQ_INIT(&paths);
5889 memset(&st, 0, sizeof(st));
5890 st.status_codes = NULL;
5891 st.suppress = 0;
5893 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5894 switch (ch) {
5895 case 'I':
5896 no_ignores = 1;
5897 break;
5898 case 'S':
5899 if (st.status_codes != NULL && st.suppress == 0)
5900 option_conflict('S', 's');
5901 st.suppress = 1;
5902 /* fallthrough */
5903 case 's':
5904 for (i = 0; i < strlen(optarg); i++) {
5905 switch (optarg[i]) {
5906 case GOT_STATUS_MODIFY:
5907 case GOT_STATUS_ADD:
5908 case GOT_STATUS_DELETE:
5909 case GOT_STATUS_CONFLICT:
5910 case GOT_STATUS_MISSING:
5911 case GOT_STATUS_OBSTRUCTED:
5912 case GOT_STATUS_UNVERSIONED:
5913 case GOT_STATUS_MODE_CHANGE:
5914 case GOT_STATUS_NONEXISTENT:
5915 break;
5916 default:
5917 errx(1, "invalid status code '%c'",
5918 optarg[i]);
5921 if (ch == 's' && st.suppress)
5922 option_conflict('s', 'S');
5923 st.status_codes = optarg;
5924 break;
5925 default:
5926 usage_status();
5927 /* NOTREACHED */
5931 argc -= optind;
5932 argv += optind;
5934 #ifndef PROFILE
5935 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5936 NULL) == -1)
5937 err(1, "pledge");
5938 #endif
5939 cwd = getcwd(NULL, 0);
5940 if (cwd == NULL) {
5941 error = got_error_from_errno("getcwd");
5942 goto done;
5945 error = got_repo_pack_fds_open(&pack_fds);
5946 if (error != NULL)
5947 goto done;
5949 error = got_worktree_open(&worktree, cwd);
5950 if (error) {
5951 if (error->code == GOT_ERR_NOT_WORKTREE)
5952 error = wrap_not_worktree_error(error, "status", cwd);
5953 goto done;
5956 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5957 NULL, pack_fds);
5958 if (error != NULL)
5959 goto done;
5961 error = apply_unveil(got_repo_get_path(repo), 1,
5962 got_worktree_get_root_path(worktree));
5963 if (error)
5964 goto done;
5966 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5967 if (error)
5968 goto done;
5970 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5971 print_status, &st, check_cancelled, NULL);
5972 done:
5973 if (pack_fds) {
5974 const struct got_error *pack_err =
5975 got_repo_pack_fds_close(pack_fds);
5976 if (error == NULL)
5977 error = pack_err;
5980 TAILQ_FOREACH(pe, &paths, entry)
5981 free((char *)pe->path);
5982 got_pathlist_free(&paths);
5983 free(cwd);
5984 return error;
5987 __dead static void
5988 usage_ref(void)
5990 fprintf(stderr,
5991 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5992 "[-s reference] [-d] [name]\n",
5993 getprogname());
5994 exit(1);
5997 static const struct got_error *
5998 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6000 static const struct got_error *err = NULL;
6001 struct got_reflist_head refs;
6002 struct got_reflist_entry *re;
6004 TAILQ_INIT(&refs);
6005 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6006 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6007 repo);
6008 if (err)
6009 return err;
6011 TAILQ_FOREACH(re, &refs, entry) {
6012 char *refstr;
6013 refstr = got_ref_to_str(re->ref);
6014 if (refstr == NULL) {
6015 err = got_error_from_errno("got_ref_to_str");
6016 break;
6018 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6019 free(refstr);
6022 got_ref_list_free(&refs);
6023 return err;
6026 static const struct got_error *
6027 delete_ref_by_name(struct got_repository *repo, const char *refname)
6029 const struct got_error *err;
6030 struct got_reference *ref;
6032 err = got_ref_open(&ref, repo, refname, 0);
6033 if (err)
6034 return err;
6036 err = delete_ref(repo, ref);
6037 got_ref_close(ref);
6038 return err;
6041 static const struct got_error *
6042 add_ref(struct got_repository *repo, const char *refname, const char *target)
6044 const struct got_error *err = NULL;
6045 struct got_object_id *id = NULL;
6046 struct got_reference *ref = NULL;
6047 struct got_reflist_head refs;
6050 * Don't let the user create a reference name with a leading '-'.
6051 * While technically a valid reference name, this case is usually
6052 * an unintended typo.
6054 if (refname[0] == '-')
6055 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6057 TAILQ_INIT(&refs);
6058 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6059 if (err)
6060 goto done;
6061 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6062 &refs, repo);
6063 got_ref_list_free(&refs);
6064 if (err)
6065 goto done;
6067 err = got_ref_alloc(&ref, refname, id);
6068 if (err)
6069 goto done;
6071 err = got_ref_write(ref, repo);
6072 done:
6073 if (ref)
6074 got_ref_close(ref);
6075 free(id);
6076 return err;
6079 static const struct got_error *
6080 add_symref(struct got_repository *repo, const char *refname, const char *target)
6082 const struct got_error *err = NULL;
6083 struct got_reference *ref = NULL;
6084 struct got_reference *target_ref = NULL;
6087 * Don't let the user create a reference name with a leading '-'.
6088 * While technically a valid reference name, this case is usually
6089 * an unintended typo.
6091 if (refname[0] == '-')
6092 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6094 err = got_ref_open(&target_ref, repo, target, 0);
6095 if (err)
6096 return err;
6098 err = got_ref_alloc_symref(&ref, refname, target_ref);
6099 if (err)
6100 goto done;
6102 err = got_ref_write(ref, repo);
6103 done:
6104 if (target_ref)
6105 got_ref_close(target_ref);
6106 if (ref)
6107 got_ref_close(ref);
6108 return err;
6111 static const struct got_error *
6112 cmd_ref(int argc, char *argv[])
6114 const struct got_error *error = NULL;
6115 struct got_repository *repo = NULL;
6116 struct got_worktree *worktree = NULL;
6117 char *cwd = NULL, *repo_path = NULL;
6118 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6119 const char *obj_arg = NULL, *symref_target= NULL;
6120 char *refname = NULL;
6121 int *pack_fds = NULL;
6123 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6124 switch (ch) {
6125 case 'c':
6126 obj_arg = optarg;
6127 break;
6128 case 'd':
6129 do_delete = 1;
6130 break;
6131 case 'r':
6132 repo_path = realpath(optarg, NULL);
6133 if (repo_path == NULL)
6134 return got_error_from_errno2("realpath",
6135 optarg);
6136 got_path_strip_trailing_slashes(repo_path);
6137 break;
6138 case 'l':
6139 do_list = 1;
6140 break;
6141 case 's':
6142 symref_target = optarg;
6143 break;
6144 case 't':
6145 sort_by_time = 1;
6146 break;
6147 default:
6148 usage_ref();
6149 /* NOTREACHED */
6153 if (obj_arg && do_list)
6154 option_conflict('c', 'l');
6155 if (obj_arg && do_delete)
6156 option_conflict('c', 'd');
6157 if (obj_arg && symref_target)
6158 option_conflict('c', 's');
6159 if (symref_target && do_delete)
6160 option_conflict('s', 'd');
6161 if (symref_target && do_list)
6162 option_conflict('s', 'l');
6163 if (do_delete && do_list)
6164 option_conflict('d', 'l');
6165 if (sort_by_time && !do_list)
6166 errx(1, "-t option requires -l option");
6168 argc -= optind;
6169 argv += optind;
6171 if (do_list) {
6172 if (argc != 0 && argc != 1)
6173 usage_ref();
6174 if (argc == 1) {
6175 refname = strdup(argv[0]);
6176 if (refname == NULL) {
6177 error = got_error_from_errno("strdup");
6178 goto done;
6181 } else {
6182 if (argc != 1)
6183 usage_ref();
6184 refname = strdup(argv[0]);
6185 if (refname == NULL) {
6186 error = got_error_from_errno("strdup");
6187 goto done;
6191 if (refname)
6192 got_path_strip_trailing_slashes(refname);
6194 #ifndef PROFILE
6195 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6196 "sendfd unveil", NULL) == -1)
6197 err(1, "pledge");
6198 #endif
6199 cwd = getcwd(NULL, 0);
6200 if (cwd == NULL) {
6201 error = got_error_from_errno("getcwd");
6202 goto done;
6205 error = got_repo_pack_fds_open(&pack_fds);
6206 if (error != NULL)
6207 goto done;
6209 if (repo_path == NULL) {
6210 error = got_worktree_open(&worktree, cwd);
6211 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6212 goto done;
6213 else
6214 error = NULL;
6215 if (worktree) {
6216 repo_path =
6217 strdup(got_worktree_get_repo_path(worktree));
6218 if (repo_path == NULL)
6219 error = got_error_from_errno("strdup");
6220 if (error)
6221 goto done;
6222 } else {
6223 repo_path = strdup(cwd);
6224 if (repo_path == NULL) {
6225 error = got_error_from_errno("strdup");
6226 goto done;
6231 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6232 if (error != NULL)
6233 goto done;
6235 #ifndef PROFILE
6236 if (do_list) {
6237 /* Remove "cpath" promise. */
6238 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6239 NULL) == -1)
6240 err(1, "pledge");
6242 #endif
6244 error = apply_unveil(got_repo_get_path(repo), do_list,
6245 worktree ? got_worktree_get_root_path(worktree) : NULL);
6246 if (error)
6247 goto done;
6249 if (do_list)
6250 error = list_refs(repo, refname, sort_by_time);
6251 else if (do_delete)
6252 error = delete_ref_by_name(repo, refname);
6253 else if (symref_target)
6254 error = add_symref(repo, refname, symref_target);
6255 else {
6256 if (obj_arg == NULL)
6257 usage_ref();
6258 error = add_ref(repo, refname, obj_arg);
6260 done:
6261 free(refname);
6262 if (repo) {
6263 const struct got_error *close_err = got_repo_close(repo);
6264 if (error == NULL)
6265 error = close_err;
6267 if (worktree)
6268 got_worktree_close(worktree);
6269 if (pack_fds) {
6270 const struct got_error *pack_err =
6271 got_repo_pack_fds_close(pack_fds);
6272 if (error == NULL)
6273 error = pack_err;
6275 free(cwd);
6276 free(repo_path);
6277 return error;
6280 __dead static void
6281 usage_branch(void)
6283 fprintf(stderr,
6284 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6285 "[-n] [name]\n", getprogname());
6286 exit(1);
6289 static const struct got_error *
6290 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6291 struct got_reference *ref)
6293 const struct got_error *err = NULL;
6294 const char *refname, *marker = " ";
6295 char *refstr;
6297 refname = got_ref_get_name(ref);
6298 if (worktree && strcmp(refname,
6299 got_worktree_get_head_ref_name(worktree)) == 0) {
6300 struct got_object_id *id = NULL;
6302 err = got_ref_resolve(&id, repo, ref);
6303 if (err)
6304 return err;
6305 if (got_object_id_cmp(id,
6306 got_worktree_get_base_commit_id(worktree)) == 0)
6307 marker = "* ";
6308 else
6309 marker = "~ ";
6310 free(id);
6313 if (strncmp(refname, "refs/heads/", 11) == 0)
6314 refname += 11;
6315 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6316 refname += 18;
6317 if (strncmp(refname, "refs/remotes/", 13) == 0)
6318 refname += 13;
6320 refstr = got_ref_to_str(ref);
6321 if (refstr == NULL)
6322 return got_error_from_errno("got_ref_to_str");
6324 printf("%s%s: %s\n", marker, refname, refstr);
6325 free(refstr);
6326 return NULL;
6329 static const struct got_error *
6330 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6332 const char *refname;
6334 if (worktree == NULL)
6335 return got_error(GOT_ERR_NOT_WORKTREE);
6337 refname = got_worktree_get_head_ref_name(worktree);
6339 if (strncmp(refname, "refs/heads/", 11) == 0)
6340 refname += 11;
6341 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6342 refname += 18;
6344 printf("%s\n", refname);
6346 return NULL;
6349 static const struct got_error *
6350 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6351 int sort_by_time)
6353 static const struct got_error *err = NULL;
6354 struct got_reflist_head refs;
6355 struct got_reflist_entry *re;
6356 struct got_reference *temp_ref = NULL;
6357 int rebase_in_progress, histedit_in_progress;
6359 TAILQ_INIT(&refs);
6361 if (worktree) {
6362 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6363 worktree);
6364 if (err)
6365 return err;
6367 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6368 worktree);
6369 if (err)
6370 return err;
6372 if (rebase_in_progress || histedit_in_progress) {
6373 err = got_ref_open(&temp_ref, repo,
6374 got_worktree_get_head_ref_name(worktree), 0);
6375 if (err)
6376 return err;
6377 list_branch(repo, worktree, temp_ref);
6378 got_ref_close(temp_ref);
6382 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6383 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6384 repo);
6385 if (err)
6386 return err;
6388 TAILQ_FOREACH(re, &refs, entry)
6389 list_branch(repo, worktree, re->ref);
6391 got_ref_list_free(&refs);
6393 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6394 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6395 repo);
6396 if (err)
6397 return err;
6399 TAILQ_FOREACH(re, &refs, entry)
6400 list_branch(repo, worktree, re->ref);
6402 got_ref_list_free(&refs);
6404 return NULL;
6407 static const struct got_error *
6408 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6409 const char *branch_name)
6411 const struct got_error *err = NULL;
6412 struct got_reference *ref = NULL;
6413 char *refname, *remote_refname = NULL;
6415 if (strncmp(branch_name, "refs/", 5) == 0)
6416 branch_name += 5;
6417 if (strncmp(branch_name, "heads/", 6) == 0)
6418 branch_name += 6;
6419 else if (strncmp(branch_name, "remotes/", 8) == 0)
6420 branch_name += 8;
6422 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6423 return got_error_from_errno("asprintf");
6425 if (asprintf(&remote_refname, "refs/remotes/%s",
6426 branch_name) == -1) {
6427 err = got_error_from_errno("asprintf");
6428 goto done;
6431 err = got_ref_open(&ref, repo, refname, 0);
6432 if (err) {
6433 const struct got_error *err2;
6434 if (err->code != GOT_ERR_NOT_REF)
6435 goto done;
6437 * Keep 'err' intact such that if neither branch exists
6438 * we report "refs/heads" rather than "refs/remotes" in
6439 * our error message.
6441 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6442 if (err2)
6443 goto done;
6444 err = NULL;
6447 if (worktree &&
6448 strcmp(got_worktree_get_head_ref_name(worktree),
6449 got_ref_get_name(ref)) == 0) {
6450 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6451 "will not delete this work tree's current branch");
6452 goto done;
6455 err = delete_ref(repo, ref);
6456 done:
6457 if (ref)
6458 got_ref_close(ref);
6459 free(refname);
6460 free(remote_refname);
6461 return err;
6464 static const struct got_error *
6465 add_branch(struct got_repository *repo, const char *branch_name,
6466 struct got_object_id *base_commit_id)
6468 const struct got_error *err = NULL;
6469 struct got_reference *ref = NULL;
6470 char *base_refname = NULL, *refname = NULL;
6473 * Don't let the user create a branch name with a leading '-'.
6474 * While technically a valid reference name, this case is usually
6475 * an unintended typo.
6477 if (branch_name[0] == '-')
6478 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6480 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6481 branch_name += 11;
6483 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6484 err = got_error_from_errno("asprintf");
6485 goto done;
6488 err = got_ref_open(&ref, repo, refname, 0);
6489 if (err == NULL) {
6490 err = got_error(GOT_ERR_BRANCH_EXISTS);
6491 goto done;
6492 } else if (err->code != GOT_ERR_NOT_REF)
6493 goto done;
6495 err = got_ref_alloc(&ref, refname, base_commit_id);
6496 if (err)
6497 goto done;
6499 err = got_ref_write(ref, repo);
6500 done:
6501 if (ref)
6502 got_ref_close(ref);
6503 free(base_refname);
6504 free(refname);
6505 return err;
6508 static const struct got_error *
6509 cmd_branch(int argc, char *argv[])
6511 const struct got_error *error = NULL;
6512 struct got_repository *repo = NULL;
6513 struct got_worktree *worktree = NULL;
6514 char *cwd = NULL, *repo_path = NULL;
6515 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6516 const char *delref = NULL, *commit_id_arg = NULL;
6517 struct got_reference *ref = NULL;
6518 struct got_pathlist_head paths;
6519 struct got_pathlist_entry *pe;
6520 struct got_object_id *commit_id = NULL;
6521 char *commit_id_str = NULL;
6522 int *pack_fds = NULL;
6524 TAILQ_INIT(&paths);
6526 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6527 switch (ch) {
6528 case 'c':
6529 commit_id_arg = optarg;
6530 break;
6531 case 'd':
6532 delref = optarg;
6533 break;
6534 case 'r':
6535 repo_path = realpath(optarg, NULL);
6536 if (repo_path == NULL)
6537 return got_error_from_errno2("realpath",
6538 optarg);
6539 got_path_strip_trailing_slashes(repo_path);
6540 break;
6541 case 'l':
6542 do_list = 1;
6543 break;
6544 case 'n':
6545 do_update = 0;
6546 break;
6547 case 't':
6548 sort_by_time = 1;
6549 break;
6550 default:
6551 usage_branch();
6552 /* NOTREACHED */
6556 if (do_list && delref)
6557 option_conflict('l', 'd');
6558 if (sort_by_time && !do_list)
6559 errx(1, "-t option requires -l option");
6561 argc -= optind;
6562 argv += optind;
6564 if (!do_list && !delref && argc == 0)
6565 do_show = 1;
6567 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6568 errx(1, "-c option can only be used when creating a branch");
6570 if (do_list || delref) {
6571 if (argc > 0)
6572 usage_branch();
6573 } else if (!do_show && argc != 1)
6574 usage_branch();
6576 #ifndef PROFILE
6577 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6578 "sendfd unveil", NULL) == -1)
6579 err(1, "pledge");
6580 #endif
6581 cwd = getcwd(NULL, 0);
6582 if (cwd == NULL) {
6583 error = got_error_from_errno("getcwd");
6584 goto done;
6587 error = got_repo_pack_fds_open(&pack_fds);
6588 if (error != NULL)
6589 goto done;
6591 if (repo_path == NULL) {
6592 error = got_worktree_open(&worktree, cwd);
6593 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6594 goto done;
6595 else
6596 error = NULL;
6597 if (worktree) {
6598 repo_path =
6599 strdup(got_worktree_get_repo_path(worktree));
6600 if (repo_path == NULL)
6601 error = got_error_from_errno("strdup");
6602 if (error)
6603 goto done;
6604 } else {
6605 repo_path = strdup(cwd);
6606 if (repo_path == NULL) {
6607 error = got_error_from_errno("strdup");
6608 goto done;
6613 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6614 if (error != NULL)
6615 goto done;
6617 #ifndef PROFILE
6618 if (do_list || do_show) {
6619 /* Remove "cpath" promise. */
6620 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6621 NULL) == -1)
6622 err(1, "pledge");
6624 #endif
6626 error = apply_unveil(got_repo_get_path(repo), do_list,
6627 worktree ? got_worktree_get_root_path(worktree) : NULL);
6628 if (error)
6629 goto done;
6631 if (do_show)
6632 error = show_current_branch(repo, worktree);
6633 else if (do_list)
6634 error = list_branches(repo, worktree, sort_by_time);
6635 else if (delref)
6636 error = delete_branch(repo, worktree, delref);
6637 else {
6638 struct got_reflist_head refs;
6639 TAILQ_INIT(&refs);
6640 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6641 NULL);
6642 if (error)
6643 goto done;
6644 if (commit_id_arg == NULL)
6645 commit_id_arg = worktree ?
6646 got_worktree_get_head_ref_name(worktree) :
6647 GOT_REF_HEAD;
6648 error = got_repo_match_object_id(&commit_id, NULL,
6649 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6650 got_ref_list_free(&refs);
6651 if (error)
6652 goto done;
6653 error = add_branch(repo, argv[0], commit_id);
6654 if (error)
6655 goto done;
6656 if (worktree && do_update) {
6657 struct got_update_progress_arg upa;
6658 char *branch_refname = NULL;
6660 error = got_object_id_str(&commit_id_str, commit_id);
6661 if (error)
6662 goto done;
6663 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6664 worktree);
6665 if (error)
6666 goto done;
6667 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6668 == -1) {
6669 error = got_error_from_errno("asprintf");
6670 goto done;
6672 error = got_ref_open(&ref, repo, branch_refname, 0);
6673 free(branch_refname);
6674 if (error)
6675 goto done;
6676 error = switch_head_ref(ref, commit_id, worktree,
6677 repo);
6678 if (error)
6679 goto done;
6680 error = got_worktree_set_base_commit_id(worktree, repo,
6681 commit_id);
6682 if (error)
6683 goto done;
6684 memset(&upa, 0, sizeof(upa));
6685 error = got_worktree_checkout_files(worktree, &paths,
6686 repo, update_progress, &upa, check_cancelled,
6687 NULL);
6688 if (error)
6689 goto done;
6690 if (upa.did_something) {
6691 printf("Updated to %s: %s\n",
6692 got_worktree_get_head_ref_name(worktree),
6693 commit_id_str);
6695 print_update_progress_stats(&upa);
6698 done:
6699 if (ref)
6700 got_ref_close(ref);
6701 if (repo) {
6702 const struct got_error *close_err = got_repo_close(repo);
6703 if (error == NULL)
6704 error = close_err;
6706 if (worktree)
6707 got_worktree_close(worktree);
6708 if (pack_fds) {
6709 const struct got_error *pack_err =
6710 got_repo_pack_fds_close(pack_fds);
6711 if (error == NULL)
6712 error = pack_err;
6714 free(cwd);
6715 free(repo_path);
6716 free(commit_id);
6717 free(commit_id_str);
6718 TAILQ_FOREACH(pe, &paths, entry)
6719 free((char *)pe->path);
6720 got_pathlist_free(&paths);
6721 return error;
6725 __dead static void
6726 usage_tag(void)
6728 fprintf(stderr,
6729 "usage: %s tag [-c commit] [-r repository] [-l] "
6730 "[-m message] name\n", getprogname());
6731 exit(1);
6734 #if 0
6735 static const struct got_error *
6736 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6738 const struct got_error *err = NULL;
6739 struct got_reflist_entry *re, *se, *new;
6740 struct got_object_id *re_id, *se_id;
6741 struct got_tag_object *re_tag, *se_tag;
6742 time_t re_time, se_time;
6744 STAILQ_FOREACH(re, tags, entry) {
6745 se = STAILQ_FIRST(sorted);
6746 if (se == NULL) {
6747 err = got_reflist_entry_dup(&new, re);
6748 if (err)
6749 return err;
6750 STAILQ_INSERT_HEAD(sorted, new, entry);
6751 continue;
6752 } else {
6753 err = got_ref_resolve(&re_id, repo, re->ref);
6754 if (err)
6755 break;
6756 err = got_object_open_as_tag(&re_tag, repo, re_id);
6757 free(re_id);
6758 if (err)
6759 break;
6760 re_time = got_object_tag_get_tagger_time(re_tag);
6761 got_object_tag_close(re_tag);
6764 while (se) {
6765 err = got_ref_resolve(&se_id, repo, re->ref);
6766 if (err)
6767 break;
6768 err = got_object_open_as_tag(&se_tag, repo, se_id);
6769 free(se_id);
6770 if (err)
6771 break;
6772 se_time = got_object_tag_get_tagger_time(se_tag);
6773 got_object_tag_close(se_tag);
6775 if (se_time > re_time) {
6776 err = got_reflist_entry_dup(&new, re);
6777 if (err)
6778 return err;
6779 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6780 break;
6782 se = STAILQ_NEXT(se, entry);
6783 continue;
6786 done:
6787 return err;
6789 #endif
6791 static const struct got_error *
6792 list_tags(struct got_repository *repo)
6794 static const struct got_error *err = NULL;
6795 struct got_reflist_head refs;
6796 struct got_reflist_entry *re;
6798 TAILQ_INIT(&refs);
6800 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6801 if (err)
6802 return err;
6804 TAILQ_FOREACH(re, &refs, entry) {
6805 const char *refname;
6806 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6807 char datebuf[26];
6808 const char *tagger;
6809 time_t tagger_time;
6810 struct got_object_id *id;
6811 struct got_tag_object *tag;
6812 struct got_commit_object *commit = NULL;
6814 refname = got_ref_get_name(re->ref);
6815 if (strncmp(refname, "refs/tags/", 10) != 0)
6816 continue;
6817 refname += 10;
6818 refstr = got_ref_to_str(re->ref);
6819 if (refstr == NULL) {
6820 err = got_error_from_errno("got_ref_to_str");
6821 break;
6823 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6824 free(refstr);
6826 err = got_ref_resolve(&id, repo, re->ref);
6827 if (err)
6828 break;
6829 err = got_object_open_as_tag(&tag, repo, id);
6830 if (err) {
6831 if (err->code != GOT_ERR_OBJ_TYPE) {
6832 free(id);
6833 break;
6835 /* "lightweight" tag */
6836 err = got_object_open_as_commit(&commit, repo, id);
6837 if (err) {
6838 free(id);
6839 break;
6841 tagger = got_object_commit_get_committer(commit);
6842 tagger_time =
6843 got_object_commit_get_committer_time(commit);
6844 err = got_object_id_str(&id_str, id);
6845 free(id);
6846 if (err)
6847 break;
6848 } else {
6849 free(id);
6850 tagger = got_object_tag_get_tagger(tag);
6851 tagger_time = got_object_tag_get_tagger_time(tag);
6852 err = got_object_id_str(&id_str,
6853 got_object_tag_get_object_id(tag));
6854 if (err)
6855 break;
6857 printf("from: %s\n", tagger);
6858 datestr = get_datestr(&tagger_time, datebuf);
6859 if (datestr)
6860 printf("date: %s UTC\n", datestr);
6861 if (commit)
6862 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6863 else {
6864 switch (got_object_tag_get_object_type(tag)) {
6865 case GOT_OBJ_TYPE_BLOB:
6866 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6867 id_str);
6868 break;
6869 case GOT_OBJ_TYPE_TREE:
6870 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6871 id_str);
6872 break;
6873 case GOT_OBJ_TYPE_COMMIT:
6874 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6875 id_str);
6876 break;
6877 case GOT_OBJ_TYPE_TAG:
6878 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6879 id_str);
6880 break;
6881 default:
6882 break;
6885 free(id_str);
6886 if (commit) {
6887 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6888 if (err)
6889 break;
6890 got_object_commit_close(commit);
6891 } else {
6892 tagmsg0 = strdup(got_object_tag_get_message(tag));
6893 got_object_tag_close(tag);
6894 if (tagmsg0 == NULL) {
6895 err = got_error_from_errno("strdup");
6896 break;
6900 tagmsg = tagmsg0;
6901 do {
6902 line = strsep(&tagmsg, "\n");
6903 if (line)
6904 printf(" %s\n", line);
6905 } while (line);
6906 free(tagmsg0);
6909 got_ref_list_free(&refs);
6910 return NULL;
6913 static const struct got_error *
6914 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6915 const char *tag_name, const char *repo_path)
6917 const struct got_error *err = NULL;
6918 char *template = NULL, *initial_content = NULL;
6919 char *editor = NULL;
6920 int initial_content_len;
6921 int fd = -1;
6923 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6924 err = got_error_from_errno("asprintf");
6925 goto done;
6928 initial_content_len = asprintf(&initial_content,
6929 "\n# tagging commit %s as %s\n",
6930 commit_id_str, tag_name);
6931 if (initial_content_len == -1) {
6932 err = got_error_from_errno("asprintf");
6933 goto done;
6936 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6937 if (err)
6938 goto done;
6940 if (write(fd, initial_content, initial_content_len) == -1) {
6941 err = got_error_from_errno2("write", *tagmsg_path);
6942 goto done;
6945 err = get_editor(&editor);
6946 if (err)
6947 goto done;
6948 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6949 initial_content_len, 1);
6950 done:
6951 free(initial_content);
6952 free(template);
6953 free(editor);
6955 if (fd != -1 && close(fd) == -1 && err == NULL)
6956 err = got_error_from_errno2("close", *tagmsg_path);
6958 /* Editor is done; we can now apply unveil(2) */
6959 if (err == NULL)
6960 err = apply_unveil(repo_path, 0, NULL);
6961 if (err) {
6962 free(*tagmsg);
6963 *tagmsg = NULL;
6965 return err;
6968 static const struct got_error *
6969 add_tag(struct got_repository *repo, const char *tagger,
6970 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6972 const struct got_error *err = NULL;
6973 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6974 char *label = NULL, *commit_id_str = NULL;
6975 struct got_reference *ref = NULL;
6976 char *refname = NULL, *tagmsg = NULL;
6977 char *tagmsg_path = NULL, *tag_id_str = NULL;
6978 int preserve_tagmsg = 0;
6979 struct got_reflist_head refs;
6981 TAILQ_INIT(&refs);
6984 * Don't let the user create a tag name with a leading '-'.
6985 * While technically a valid reference name, this case is usually
6986 * an unintended typo.
6988 if (tag_name[0] == '-')
6989 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6991 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6992 if (err)
6993 goto done;
6995 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6996 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6997 if (err)
6998 goto done;
7000 err = got_object_id_str(&commit_id_str, commit_id);
7001 if (err)
7002 goto done;
7004 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7005 refname = strdup(tag_name);
7006 if (refname == NULL) {
7007 err = got_error_from_errno("strdup");
7008 goto done;
7010 tag_name += 10;
7011 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
7012 err = got_error_from_errno("asprintf");
7013 goto done;
7016 err = got_ref_open(&ref, repo, refname, 0);
7017 if (err == NULL) {
7018 err = got_error(GOT_ERR_TAG_EXISTS);
7019 goto done;
7020 } else if (err->code != GOT_ERR_NOT_REF)
7021 goto done;
7023 if (tagmsg_arg == NULL) {
7024 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7025 tag_name, got_repo_get_path(repo));
7026 if (err) {
7027 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7028 tagmsg_path != NULL)
7029 preserve_tagmsg = 1;
7030 goto done;
7034 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7035 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7036 if (err) {
7037 if (tagmsg_path)
7038 preserve_tagmsg = 1;
7039 goto done;
7042 err = got_ref_alloc(&ref, refname, tag_id);
7043 if (err) {
7044 if (tagmsg_path)
7045 preserve_tagmsg = 1;
7046 goto done;
7049 err = got_ref_write(ref, repo);
7050 if (err) {
7051 if (tagmsg_path)
7052 preserve_tagmsg = 1;
7053 goto done;
7056 err = got_object_id_str(&tag_id_str, tag_id);
7057 if (err) {
7058 if (tagmsg_path)
7059 preserve_tagmsg = 1;
7060 goto done;
7062 printf("Created tag %s\n", tag_id_str);
7063 done:
7064 if (preserve_tagmsg) {
7065 fprintf(stderr, "%s: tag message preserved in %s\n",
7066 getprogname(), tagmsg_path);
7067 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7068 err = got_error_from_errno2("unlink", tagmsg_path);
7069 free(tag_id_str);
7070 if (ref)
7071 got_ref_close(ref);
7072 free(commit_id);
7073 free(commit_id_str);
7074 free(refname);
7075 free(tagmsg);
7076 free(tagmsg_path);
7077 got_ref_list_free(&refs);
7078 return err;
7081 static const struct got_error *
7082 cmd_tag(int argc, char *argv[])
7084 const struct got_error *error = NULL;
7085 struct got_repository *repo = NULL;
7086 struct got_worktree *worktree = NULL;
7087 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7088 char *gitconfig_path = NULL, *tagger = NULL;
7089 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
7090 int ch, do_list = 0;
7091 int *pack_fds = NULL;
7093 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7094 switch (ch) {
7095 case 'c':
7096 commit_id_arg = optarg;
7097 break;
7098 case 'm':
7099 tagmsg = optarg;
7100 break;
7101 case 'r':
7102 repo_path = realpath(optarg, NULL);
7103 if (repo_path == NULL)
7104 return got_error_from_errno2("realpath",
7105 optarg);
7106 got_path_strip_trailing_slashes(repo_path);
7107 break;
7108 case 'l':
7109 do_list = 1;
7110 break;
7111 default:
7112 usage_tag();
7113 /* NOTREACHED */
7117 argc -= optind;
7118 argv += optind;
7120 if (do_list) {
7121 if (commit_id_arg != NULL)
7122 errx(1,
7123 "-c option can only be used when creating a tag");
7124 if (tagmsg)
7125 option_conflict('l', 'm');
7126 if (argc > 0)
7127 usage_tag();
7128 } else if (argc != 1)
7129 usage_tag();
7131 tag_name = argv[0];
7133 #ifndef PROFILE
7134 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7135 "sendfd unveil", NULL) == -1)
7136 err(1, "pledge");
7137 #endif
7138 cwd = getcwd(NULL, 0);
7139 if (cwd == NULL) {
7140 error = got_error_from_errno("getcwd");
7141 goto done;
7144 error = got_repo_pack_fds_open(&pack_fds);
7145 if (error != NULL)
7146 goto done;
7148 if (repo_path == NULL) {
7149 error = got_worktree_open(&worktree, cwd);
7150 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7151 goto done;
7152 else
7153 error = NULL;
7154 if (worktree) {
7155 repo_path =
7156 strdup(got_worktree_get_repo_path(worktree));
7157 if (repo_path == NULL)
7158 error = got_error_from_errno("strdup");
7159 if (error)
7160 goto done;
7161 } else {
7162 repo_path = strdup(cwd);
7163 if (repo_path == NULL) {
7164 error = got_error_from_errno("strdup");
7165 goto done;
7170 if (do_list) {
7171 if (worktree) {
7172 /* Release work tree lock. */
7173 got_worktree_close(worktree);
7174 worktree = NULL;
7176 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7177 if (error != NULL)
7178 goto done;
7180 #ifndef PROFILE
7181 /* Remove "cpath" promise. */
7182 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7183 NULL) == -1)
7184 err(1, "pledge");
7185 #endif
7186 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7187 if (error)
7188 goto done;
7189 error = list_tags(repo);
7190 } else {
7191 error = get_gitconfig_path(&gitconfig_path);
7192 if (error)
7193 goto done;
7194 error = got_repo_open(&repo, repo_path, gitconfig_path,
7195 pack_fds);
7196 if (error != NULL)
7197 goto done;
7199 error = get_author(&tagger, repo, worktree);
7200 if (error)
7201 goto done;
7202 if (worktree) {
7203 /* Release work tree lock. */
7204 got_worktree_close(worktree);
7205 worktree = NULL;
7208 if (tagmsg) {
7209 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7210 if (error)
7211 goto done;
7214 if (commit_id_arg == NULL) {
7215 struct got_reference *head_ref;
7216 struct got_object_id *commit_id;
7217 error = got_ref_open(&head_ref, repo,
7218 worktree ? got_worktree_get_head_ref_name(worktree)
7219 : GOT_REF_HEAD, 0);
7220 if (error)
7221 goto done;
7222 error = got_ref_resolve(&commit_id, repo, head_ref);
7223 got_ref_close(head_ref);
7224 if (error)
7225 goto done;
7226 error = got_object_id_str(&commit_id_str, commit_id);
7227 free(commit_id);
7228 if (error)
7229 goto done;
7232 error = add_tag(repo, tagger, tag_name,
7233 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7235 done:
7236 if (repo) {
7237 const struct got_error *close_err = got_repo_close(repo);
7238 if (error == NULL)
7239 error = close_err;
7241 if (worktree)
7242 got_worktree_close(worktree);
7243 if (pack_fds) {
7244 const struct got_error *pack_err =
7245 got_repo_pack_fds_close(pack_fds);
7246 if (error == NULL)
7247 error = pack_err;
7249 free(cwd);
7250 free(repo_path);
7251 free(gitconfig_path);
7252 free(commit_id_str);
7253 free(tagger);
7254 return error;
7257 __dead static void
7258 usage_add(void)
7260 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7261 getprogname());
7262 exit(1);
7265 static const struct got_error *
7266 add_progress(void *arg, unsigned char status, const char *path)
7268 while (path[0] == '/')
7269 path++;
7270 printf("%c %s\n", status, path);
7271 return NULL;
7274 static const struct got_error *
7275 cmd_add(int argc, char *argv[])
7277 const struct got_error *error = NULL;
7278 struct got_repository *repo = NULL;
7279 struct got_worktree *worktree = NULL;
7280 char *cwd = NULL;
7281 struct got_pathlist_head paths;
7282 struct got_pathlist_entry *pe;
7283 int ch, can_recurse = 0, no_ignores = 0;
7284 int *pack_fds = NULL;
7286 TAILQ_INIT(&paths);
7288 while ((ch = getopt(argc, argv, "IR")) != -1) {
7289 switch (ch) {
7290 case 'I':
7291 no_ignores = 1;
7292 break;
7293 case 'R':
7294 can_recurse = 1;
7295 break;
7296 default:
7297 usage_add();
7298 /* NOTREACHED */
7302 argc -= optind;
7303 argv += optind;
7305 #ifndef PROFILE
7306 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7307 NULL) == -1)
7308 err(1, "pledge");
7309 #endif
7310 if (argc < 1)
7311 usage_add();
7313 cwd = getcwd(NULL, 0);
7314 if (cwd == NULL) {
7315 error = got_error_from_errno("getcwd");
7316 goto done;
7319 error = got_repo_pack_fds_open(&pack_fds);
7320 if (error != NULL)
7321 goto done;
7323 error = got_worktree_open(&worktree, cwd);
7324 if (error) {
7325 if (error->code == GOT_ERR_NOT_WORKTREE)
7326 error = wrap_not_worktree_error(error, "add", cwd);
7327 goto done;
7330 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7331 NULL, pack_fds);
7332 if (error != NULL)
7333 goto done;
7335 error = apply_unveil(got_repo_get_path(repo), 1,
7336 got_worktree_get_root_path(worktree));
7337 if (error)
7338 goto done;
7340 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7341 if (error)
7342 goto done;
7344 if (!can_recurse) {
7345 char *ondisk_path;
7346 struct stat sb;
7347 TAILQ_FOREACH(pe, &paths, entry) {
7348 if (asprintf(&ondisk_path, "%s/%s",
7349 got_worktree_get_root_path(worktree),
7350 pe->path) == -1) {
7351 error = got_error_from_errno("asprintf");
7352 goto done;
7354 if (lstat(ondisk_path, &sb) == -1) {
7355 if (errno == ENOENT) {
7356 free(ondisk_path);
7357 continue;
7359 error = got_error_from_errno2("lstat",
7360 ondisk_path);
7361 free(ondisk_path);
7362 goto done;
7364 free(ondisk_path);
7365 if (S_ISDIR(sb.st_mode)) {
7366 error = got_error_msg(GOT_ERR_BAD_PATH,
7367 "adding directories requires -R option");
7368 goto done;
7373 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7374 NULL, repo, no_ignores);
7375 done:
7376 if (repo) {
7377 const struct got_error *close_err = got_repo_close(repo);
7378 if (error == NULL)
7379 error = close_err;
7381 if (worktree)
7382 got_worktree_close(worktree);
7383 if (pack_fds) {
7384 const struct got_error *pack_err =
7385 got_repo_pack_fds_close(pack_fds);
7386 if (error == NULL)
7387 error = pack_err;
7389 TAILQ_FOREACH(pe, &paths, entry)
7390 free((char *)pe->path);
7391 got_pathlist_free(&paths);
7392 free(cwd);
7393 return error;
7396 __dead static void
7397 usage_remove(void)
7399 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7400 "path ...\n", getprogname());
7401 exit(1);
7404 static const struct got_error *
7405 print_remove_status(void *arg, unsigned char status,
7406 unsigned char staged_status, const char *path)
7408 while (path[0] == '/')
7409 path++;
7410 if (status == GOT_STATUS_NONEXISTENT)
7411 return NULL;
7412 if (status == staged_status && (status == GOT_STATUS_DELETE))
7413 status = GOT_STATUS_NO_CHANGE;
7414 printf("%c%c %s\n", status, staged_status, path);
7415 return NULL;
7418 static const struct got_error *
7419 cmd_remove(int argc, char *argv[])
7421 const struct got_error *error = NULL;
7422 struct got_worktree *worktree = NULL;
7423 struct got_repository *repo = NULL;
7424 const char *status_codes = NULL;
7425 char *cwd = NULL;
7426 struct got_pathlist_head paths;
7427 struct got_pathlist_entry *pe;
7428 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7429 int ignore_missing_paths = 0;
7430 int *pack_fds = NULL;
7432 TAILQ_INIT(&paths);
7434 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7435 switch (ch) {
7436 case 'f':
7437 delete_local_mods = 1;
7438 ignore_missing_paths = 1;
7439 break;
7440 case 'k':
7441 keep_on_disk = 1;
7442 break;
7443 case 'R':
7444 can_recurse = 1;
7445 break;
7446 case 's':
7447 for (i = 0; i < strlen(optarg); i++) {
7448 switch (optarg[i]) {
7449 case GOT_STATUS_MODIFY:
7450 delete_local_mods = 1;
7451 break;
7452 case GOT_STATUS_MISSING:
7453 ignore_missing_paths = 1;
7454 break;
7455 default:
7456 errx(1, "invalid status code '%c'",
7457 optarg[i]);
7460 status_codes = optarg;
7461 break;
7462 default:
7463 usage_remove();
7464 /* NOTREACHED */
7468 argc -= optind;
7469 argv += optind;
7471 #ifndef PROFILE
7472 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7473 NULL) == -1)
7474 err(1, "pledge");
7475 #endif
7476 if (argc < 1)
7477 usage_remove();
7479 cwd = getcwd(NULL, 0);
7480 if (cwd == NULL) {
7481 error = got_error_from_errno("getcwd");
7482 goto done;
7485 error = got_repo_pack_fds_open(&pack_fds);
7486 if (error != NULL)
7487 goto done;
7489 error = got_worktree_open(&worktree, cwd);
7490 if (error) {
7491 if (error->code == GOT_ERR_NOT_WORKTREE)
7492 error = wrap_not_worktree_error(error, "remove", cwd);
7493 goto done;
7496 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7497 NULL, pack_fds);
7498 if (error)
7499 goto done;
7501 error = apply_unveil(got_repo_get_path(repo), 1,
7502 got_worktree_get_root_path(worktree));
7503 if (error)
7504 goto done;
7506 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7507 if (error)
7508 goto done;
7510 if (!can_recurse) {
7511 char *ondisk_path;
7512 struct stat sb;
7513 TAILQ_FOREACH(pe, &paths, entry) {
7514 if (asprintf(&ondisk_path, "%s/%s",
7515 got_worktree_get_root_path(worktree),
7516 pe->path) == -1) {
7517 error = got_error_from_errno("asprintf");
7518 goto done;
7520 if (lstat(ondisk_path, &sb) == -1) {
7521 if (errno == ENOENT) {
7522 free(ondisk_path);
7523 continue;
7525 error = got_error_from_errno2("lstat",
7526 ondisk_path);
7527 free(ondisk_path);
7528 goto done;
7530 free(ondisk_path);
7531 if (S_ISDIR(sb.st_mode)) {
7532 error = got_error_msg(GOT_ERR_BAD_PATH,
7533 "removing directories requires -R option");
7534 goto done;
7539 error = got_worktree_schedule_delete(worktree, &paths,
7540 delete_local_mods, status_codes, print_remove_status, NULL,
7541 repo, keep_on_disk, ignore_missing_paths);
7542 done:
7543 if (repo) {
7544 const struct got_error *close_err = got_repo_close(repo);
7545 if (error == NULL)
7546 error = close_err;
7548 if (worktree)
7549 got_worktree_close(worktree);
7550 if (pack_fds) {
7551 const struct got_error *pack_err =
7552 got_repo_pack_fds_close(pack_fds);
7553 if (error == NULL)
7554 error = pack_err;
7556 TAILQ_FOREACH(pe, &paths, entry)
7557 free((char *)pe->path);
7558 got_pathlist_free(&paths);
7559 free(cwd);
7560 return error;
7563 __dead static void
7564 usage_patch(void)
7566 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7567 "[-R] [patchfile]\n", getprogname());
7568 exit(1);
7571 static const struct got_error *
7572 patch_from_stdin(int *patchfd)
7574 const struct got_error *err = NULL;
7575 ssize_t r;
7576 char *path, buf[BUFSIZ];
7577 sig_t sighup, sigint, sigquit;
7579 err = got_opentemp_named_fd(&path, patchfd,
7580 GOT_TMPDIR_STR "/got-patch");
7581 if (err)
7582 return err;
7583 unlink(path);
7584 free(path);
7586 sighup = signal(SIGHUP, SIG_DFL);
7587 sigint = signal(SIGINT, SIG_DFL);
7588 sigquit = signal(SIGQUIT, SIG_DFL);
7590 for (;;) {
7591 r = read(0, buf, sizeof(buf));
7592 if (r == -1) {
7593 err = got_error_from_errno("read");
7594 break;
7596 if (r == 0)
7597 break;
7598 if (write(*patchfd, buf, r) == -1) {
7599 err = got_error_from_errno("write");
7600 break;
7604 signal(SIGHUP, sighup);
7605 signal(SIGINT, sigint);
7606 signal(SIGQUIT, sigquit);
7608 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7609 err = got_error_from_errno("lseek");
7611 if (err != NULL) {
7612 close(*patchfd);
7613 *patchfd = -1;
7616 return err;
7619 static const struct got_error *
7620 patch_progress(void *arg, const char *old, const char *new,
7621 unsigned char status, const struct got_error *error, long old_from,
7622 long old_lines, long new_from, long new_lines, long offset,
7623 const struct got_error *hunk_err)
7625 const char *path = new == NULL ? old : new;
7627 while (*path == '/')
7628 path++;
7630 if (status != 0)
7631 printf("%c %s\n", status, path);
7633 if (error != NULL)
7634 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7636 if (offset != 0 || hunk_err != NULL) {
7637 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7638 old_lines, new_from, new_lines);
7639 if (hunk_err != NULL)
7640 printf("%s\n", hunk_err->msg);
7641 else
7642 printf("applied with offset %ld\n", offset);
7645 return NULL;
7648 static const struct got_error *
7649 cmd_patch(int argc, char *argv[])
7651 const struct got_error *error = NULL, *close_error = NULL;
7652 struct got_worktree *worktree = NULL;
7653 struct got_repository *repo = NULL;
7654 const char *errstr;
7655 char *cwd = NULL;
7656 int ch, nop = 0, strip = -1, reverse = 0;
7657 int patchfd;
7658 int *pack_fds = NULL;
7660 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7661 switch (ch) {
7662 case 'n':
7663 nop = 1;
7664 break;
7665 case 'p':
7666 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7667 if (errstr != NULL)
7668 errx(1, "pathname strip count is %s: %s",
7669 errstr, optarg);
7670 break;
7671 case 'R':
7672 reverse = 1;
7673 break;
7674 default:
7675 usage_patch();
7676 /* NOTREACHED */
7680 argc -= optind;
7681 argv += optind;
7683 if (argc == 0) {
7684 error = patch_from_stdin(&patchfd);
7685 if (error)
7686 return error;
7687 } else if (argc == 1) {
7688 patchfd = open(argv[0], O_RDONLY);
7689 if (patchfd == -1) {
7690 error = got_error_from_errno2("open", argv[0]);
7691 return error;
7693 } else
7694 usage_patch();
7696 if ((cwd = getcwd(NULL, 0)) == NULL) {
7697 error = got_error_from_errno("getcwd");
7698 goto done;
7701 error = got_repo_pack_fds_open(&pack_fds);
7702 if (error != NULL)
7703 goto done;
7705 error = got_worktree_open(&worktree, cwd);
7706 if (error != NULL)
7707 goto done;
7709 const char *repo_path = got_worktree_get_repo_path(worktree);
7710 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7711 if (error != NULL)
7712 goto done;
7714 error = apply_unveil(got_repo_get_path(repo), 0,
7715 got_worktree_get_root_path(worktree));
7716 if (error != NULL)
7717 goto done;
7719 #ifndef PROFILE
7720 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7721 NULL) == -1)
7722 err(1, "pledge");
7723 #endif
7725 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7726 &patch_progress, NULL, check_cancelled, NULL);
7728 done:
7729 if (repo) {
7730 close_error = got_repo_close(repo);
7731 if (error == NULL)
7732 error = close_error;
7734 if (worktree != NULL) {
7735 close_error = got_worktree_close(worktree);
7736 if (error == NULL)
7737 error = close_error;
7739 if (pack_fds) {
7740 const struct got_error *pack_err =
7741 got_repo_pack_fds_close(pack_fds);
7742 if (error == NULL)
7743 error = pack_err;
7745 free(cwd);
7746 return error;
7749 __dead static void
7750 usage_revert(void)
7752 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7753 "path ...\n", getprogname());
7754 exit(1);
7757 static const struct got_error *
7758 revert_progress(void *arg, unsigned char status, const char *path)
7760 if (status == GOT_STATUS_UNVERSIONED)
7761 return NULL;
7763 while (path[0] == '/')
7764 path++;
7765 printf("%c %s\n", status, path);
7766 return NULL;
7769 struct choose_patch_arg {
7770 FILE *patch_script_file;
7771 const char *action;
7774 static const struct got_error *
7775 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7776 int nchanges, const char *action)
7778 const struct got_error *err;
7779 char *line = NULL;
7780 size_t linesize = 0;
7781 ssize_t linelen;
7783 switch (status) {
7784 case GOT_STATUS_ADD:
7785 printf("A %s\n%s this addition? [y/n] ", path, action);
7786 break;
7787 case GOT_STATUS_DELETE:
7788 printf("D %s\n%s this deletion? [y/n] ", path, action);
7789 break;
7790 case GOT_STATUS_MODIFY:
7791 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7792 return got_error_from_errno("fseek");
7793 printf(GOT_COMMIT_SEP_STR);
7794 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7795 printf("%s", line);
7796 if (linelen == -1 && ferror(patch_file)) {
7797 err = got_error_from_errno("getline");
7798 free(line);
7799 return err;
7801 free(line);
7802 printf(GOT_COMMIT_SEP_STR);
7803 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7804 path, n, nchanges, action);
7805 break;
7806 default:
7807 return got_error_path(path, GOT_ERR_FILE_STATUS);
7810 return NULL;
7813 static const struct got_error *
7814 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7815 FILE *patch_file, int n, int nchanges)
7817 const struct got_error *err = NULL;
7818 char *line = NULL;
7819 size_t linesize = 0;
7820 ssize_t linelen;
7821 int resp = ' ';
7822 struct choose_patch_arg *a = arg;
7824 *choice = GOT_PATCH_CHOICE_NONE;
7826 if (a->patch_script_file) {
7827 char *nl;
7828 err = show_change(status, path, patch_file, n, nchanges,
7829 a->action);
7830 if (err)
7831 return err;
7832 linelen = getline(&line, &linesize, a->patch_script_file);
7833 if (linelen == -1) {
7834 if (ferror(a->patch_script_file))
7835 return got_error_from_errno("getline");
7836 return NULL;
7838 nl = strchr(line, '\n');
7839 if (nl)
7840 *nl = '\0';
7841 if (strcmp(line, "y") == 0) {
7842 *choice = GOT_PATCH_CHOICE_YES;
7843 printf("y\n");
7844 } else if (strcmp(line, "n") == 0) {
7845 *choice = GOT_PATCH_CHOICE_NO;
7846 printf("n\n");
7847 } else if (strcmp(line, "q") == 0 &&
7848 status == GOT_STATUS_MODIFY) {
7849 *choice = GOT_PATCH_CHOICE_QUIT;
7850 printf("q\n");
7851 } else
7852 printf("invalid response '%s'\n", line);
7853 free(line);
7854 return NULL;
7857 while (resp != 'y' && resp != 'n' && resp != 'q') {
7858 err = show_change(status, path, patch_file, n, nchanges,
7859 a->action);
7860 if (err)
7861 return err;
7862 resp = getchar();
7863 if (resp == '\n')
7864 resp = getchar();
7865 if (status == GOT_STATUS_MODIFY) {
7866 if (resp != 'y' && resp != 'n' && resp != 'q') {
7867 printf("invalid response '%c'\n", resp);
7868 resp = ' ';
7870 } else if (resp != 'y' && resp != 'n') {
7871 printf("invalid response '%c'\n", resp);
7872 resp = ' ';
7876 if (resp == 'y')
7877 *choice = GOT_PATCH_CHOICE_YES;
7878 else if (resp == 'n')
7879 *choice = GOT_PATCH_CHOICE_NO;
7880 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7881 *choice = GOT_PATCH_CHOICE_QUIT;
7883 return NULL;
7886 static const struct got_error *
7887 cmd_revert(int argc, char *argv[])
7889 const struct got_error *error = NULL;
7890 struct got_worktree *worktree = NULL;
7891 struct got_repository *repo = NULL;
7892 char *cwd = NULL, *path = NULL;
7893 struct got_pathlist_head paths;
7894 struct got_pathlist_entry *pe;
7895 int ch, can_recurse = 0, pflag = 0;
7896 FILE *patch_script_file = NULL;
7897 const char *patch_script_path = NULL;
7898 struct choose_patch_arg cpa;
7899 int *pack_fds = NULL;
7901 TAILQ_INIT(&paths);
7903 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7904 switch (ch) {
7905 case 'p':
7906 pflag = 1;
7907 break;
7908 case 'F':
7909 patch_script_path = optarg;
7910 break;
7911 case 'R':
7912 can_recurse = 1;
7913 break;
7914 default:
7915 usage_revert();
7916 /* NOTREACHED */
7920 argc -= optind;
7921 argv += optind;
7923 #ifndef PROFILE
7924 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7925 "unveil", NULL) == -1)
7926 err(1, "pledge");
7927 #endif
7928 if (argc < 1)
7929 usage_revert();
7930 if (patch_script_path && !pflag)
7931 errx(1, "-F option can only be used together with -p option");
7933 cwd = getcwd(NULL, 0);
7934 if (cwd == NULL) {
7935 error = got_error_from_errno("getcwd");
7936 goto done;
7939 error = got_repo_pack_fds_open(&pack_fds);
7940 if (error != NULL)
7941 goto done;
7943 error = got_worktree_open(&worktree, cwd);
7944 if (error) {
7945 if (error->code == GOT_ERR_NOT_WORKTREE)
7946 error = wrap_not_worktree_error(error, "revert", cwd);
7947 goto done;
7950 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7951 NULL, pack_fds);
7952 if (error != NULL)
7953 goto done;
7955 if (patch_script_path) {
7956 patch_script_file = fopen(patch_script_path, "re");
7957 if (patch_script_file == NULL) {
7958 error = got_error_from_errno2("fopen",
7959 patch_script_path);
7960 goto done;
7963 error = apply_unveil(got_repo_get_path(repo), 1,
7964 got_worktree_get_root_path(worktree));
7965 if (error)
7966 goto done;
7968 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7969 if (error)
7970 goto done;
7972 if (!can_recurse) {
7973 char *ondisk_path;
7974 struct stat sb;
7975 TAILQ_FOREACH(pe, &paths, entry) {
7976 if (asprintf(&ondisk_path, "%s/%s",
7977 got_worktree_get_root_path(worktree),
7978 pe->path) == -1) {
7979 error = got_error_from_errno("asprintf");
7980 goto done;
7982 if (lstat(ondisk_path, &sb) == -1) {
7983 if (errno == ENOENT) {
7984 free(ondisk_path);
7985 continue;
7987 error = got_error_from_errno2("lstat",
7988 ondisk_path);
7989 free(ondisk_path);
7990 goto done;
7992 free(ondisk_path);
7993 if (S_ISDIR(sb.st_mode)) {
7994 error = got_error_msg(GOT_ERR_BAD_PATH,
7995 "reverting directories requires -R option");
7996 goto done;
8001 cpa.patch_script_file = patch_script_file;
8002 cpa.action = "revert";
8003 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8004 pflag ? choose_patch : NULL, &cpa, repo);
8005 done:
8006 if (patch_script_file && fclose(patch_script_file) == EOF &&
8007 error == NULL)
8008 error = got_error_from_errno2("fclose", patch_script_path);
8009 if (repo) {
8010 const struct got_error *close_err = got_repo_close(repo);
8011 if (error == NULL)
8012 error = close_err;
8014 if (worktree)
8015 got_worktree_close(worktree);
8016 if (pack_fds) {
8017 const struct got_error *pack_err =
8018 got_repo_pack_fds_close(pack_fds);
8019 if (error == NULL)
8020 error = pack_err;
8022 free(path);
8023 free(cwd);
8024 return error;
8027 __dead static void
8028 usage_commit(void)
8030 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8031 "[path ...]\n", getprogname());
8032 exit(1);
8035 struct collect_commit_logmsg_arg {
8036 const char *cmdline_log;
8037 const char *prepared_log;
8038 int non_interactive;
8039 const char *editor;
8040 const char *worktree_path;
8041 const char *branch_name;
8042 const char *repo_path;
8043 char *logmsg_path;
8047 static const struct got_error *
8048 read_prepared_logmsg(char **logmsg, const char *path)
8050 const struct got_error *err = NULL;
8051 FILE *f = NULL;
8052 struct stat sb;
8053 size_t r;
8055 *logmsg = NULL;
8056 memset(&sb, 0, sizeof(sb));
8058 f = fopen(path, "re");
8059 if (f == NULL)
8060 return got_error_from_errno2("fopen", path);
8062 if (fstat(fileno(f), &sb) == -1) {
8063 err = got_error_from_errno2("fstat", path);
8064 goto done;
8066 if (sb.st_size == 0) {
8067 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8068 goto done;
8071 *logmsg = malloc(sb.st_size + 1);
8072 if (*logmsg == NULL) {
8073 err = got_error_from_errno("malloc");
8074 goto done;
8077 r = fread(*logmsg, 1, sb.st_size, f);
8078 if (r != sb.st_size) {
8079 if (ferror(f))
8080 err = got_error_from_errno2("fread", path);
8081 else
8082 err = got_error(GOT_ERR_IO);
8083 goto done;
8085 (*logmsg)[sb.st_size] = '\0';
8086 done:
8087 if (fclose(f) == EOF && err == NULL)
8088 err = got_error_from_errno2("fclose", path);
8089 if (err) {
8090 free(*logmsg);
8091 *logmsg = NULL;
8093 return err;
8097 static const struct got_error *
8098 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8099 void *arg)
8101 char *initial_content = NULL;
8102 struct got_pathlist_entry *pe;
8103 const struct got_error *err = NULL;
8104 char *template = NULL;
8105 struct collect_commit_logmsg_arg *a = arg;
8106 int initial_content_len;
8107 int fd = -1;
8108 size_t len;
8110 /* if a message was specified on the command line, just use it */
8111 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8112 len = strlen(a->cmdline_log) + 1;
8113 *logmsg = malloc(len + 1);
8114 if (*logmsg == NULL)
8115 return got_error_from_errno("malloc");
8116 strlcpy(*logmsg, a->cmdline_log, len);
8117 return NULL;
8118 } else if (a->prepared_log != NULL && a->non_interactive)
8119 return read_prepared_logmsg(logmsg, a->prepared_log);
8121 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8122 return got_error_from_errno("asprintf");
8124 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8125 if (err)
8126 goto done;
8128 if (a->prepared_log) {
8129 char *msg;
8130 err = read_prepared_logmsg(&msg, a->prepared_log);
8131 if (err)
8132 goto done;
8133 if (write(fd, msg, strlen(msg)) == -1) {
8134 err = got_error_from_errno2("write", a->logmsg_path);
8135 free(msg);
8136 goto done;
8138 free(msg);
8141 initial_content_len = asprintf(&initial_content,
8142 "\n# changes to be committed on branch %s:\n",
8143 a->branch_name);
8144 if (initial_content_len == -1) {
8145 err = got_error_from_errno("asprintf");
8146 goto done;
8149 if (write(fd, initial_content, initial_content_len) == -1) {
8150 err = got_error_from_errno2("write", a->logmsg_path);
8151 goto done;
8154 TAILQ_FOREACH(pe, commitable_paths, entry) {
8155 struct got_commitable *ct = pe->data;
8156 dprintf(fd, "# %c %s\n",
8157 got_commitable_get_status(ct),
8158 got_commitable_get_path(ct));
8161 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8162 initial_content_len, a->prepared_log ? 0 : 1);
8163 done:
8164 free(initial_content);
8165 free(template);
8167 if (fd != -1 && close(fd) == -1 && err == NULL)
8168 err = got_error_from_errno2("close", a->logmsg_path);
8170 /* Editor is done; we can now apply unveil(2) */
8171 if (err == NULL)
8172 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8173 if (err) {
8174 free(*logmsg);
8175 *logmsg = NULL;
8177 return err;
8180 static const struct got_error *
8181 cmd_commit(int argc, char *argv[])
8183 const struct got_error *error = NULL;
8184 struct got_worktree *worktree = NULL;
8185 struct got_repository *repo = NULL;
8186 char *cwd = NULL, *id_str = NULL;
8187 struct got_object_id *id = NULL;
8188 const char *logmsg = NULL;
8189 char *prepared_logmsg = NULL;
8190 struct collect_commit_logmsg_arg cl_arg;
8191 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8192 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8193 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8194 struct got_pathlist_head paths;
8195 int *pack_fds = NULL;
8197 TAILQ_INIT(&paths);
8198 cl_arg.logmsg_path = NULL;
8200 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8201 switch (ch) {
8202 case 'F':
8203 if (logmsg != NULL)
8204 option_conflict('F', 'm');
8205 prepared_logmsg = realpath(optarg, NULL);
8206 if (prepared_logmsg == NULL)
8207 return got_error_from_errno2("realpath",
8208 optarg);
8209 break;
8210 case 'm':
8211 if (prepared_logmsg)
8212 option_conflict('m', 'F');
8213 logmsg = optarg;
8214 break;
8215 case 'N':
8216 non_interactive = 1;
8217 break;
8218 case 'S':
8219 allow_bad_symlinks = 1;
8220 break;
8221 default:
8222 usage_commit();
8223 /* NOTREACHED */
8227 argc -= optind;
8228 argv += optind;
8230 #ifndef PROFILE
8231 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8232 "unveil", NULL) == -1)
8233 err(1, "pledge");
8234 #endif
8235 cwd = getcwd(NULL, 0);
8236 if (cwd == NULL) {
8237 error = got_error_from_errno("getcwd");
8238 goto done;
8241 error = got_repo_pack_fds_open(&pack_fds);
8242 if (error != NULL)
8243 goto done;
8245 error = got_worktree_open(&worktree, cwd);
8246 if (error) {
8247 if (error->code == GOT_ERR_NOT_WORKTREE)
8248 error = wrap_not_worktree_error(error, "commit", cwd);
8249 goto done;
8252 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8253 if (error)
8254 goto done;
8255 if (rebase_in_progress) {
8256 error = got_error(GOT_ERR_REBASING);
8257 goto done;
8260 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8261 worktree);
8262 if (error)
8263 goto done;
8265 error = get_gitconfig_path(&gitconfig_path);
8266 if (error)
8267 goto done;
8268 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8269 gitconfig_path, pack_fds);
8270 if (error != NULL)
8271 goto done;
8273 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8274 if (error)
8275 goto done;
8276 if (merge_in_progress) {
8277 error = got_error(GOT_ERR_MERGE_BUSY);
8278 goto done;
8281 error = get_author(&author, repo, worktree);
8282 if (error)
8283 return error;
8286 * unveil(2) traverses exec(2); if an editor is used we have
8287 * to apply unveil after the log message has been written.
8289 if (logmsg == NULL || strlen(logmsg) == 0)
8290 error = get_editor(&editor);
8291 else
8292 error = apply_unveil(got_repo_get_path(repo), 0,
8293 got_worktree_get_root_path(worktree));
8294 if (error)
8295 goto done;
8297 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8298 if (error)
8299 goto done;
8301 cl_arg.editor = editor;
8302 cl_arg.cmdline_log = logmsg;
8303 cl_arg.prepared_log = prepared_logmsg;
8304 cl_arg.non_interactive = non_interactive;
8305 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8306 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8307 if (!histedit_in_progress) {
8308 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8309 error = got_error(GOT_ERR_COMMIT_BRANCH);
8310 goto done;
8312 cl_arg.branch_name += 11;
8314 cl_arg.repo_path = got_repo_get_path(repo);
8315 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8316 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8317 print_status, NULL, repo);
8318 if (error) {
8319 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8320 cl_arg.logmsg_path != NULL)
8321 preserve_logmsg = 1;
8322 goto done;
8325 error = got_object_id_str(&id_str, id);
8326 if (error)
8327 goto done;
8328 printf("Created commit %s\n", id_str);
8329 done:
8330 if (preserve_logmsg) {
8331 fprintf(stderr, "%s: log message preserved in %s\n",
8332 getprogname(), cl_arg.logmsg_path);
8333 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8334 error == NULL)
8335 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8336 free(cl_arg.logmsg_path);
8337 if (repo) {
8338 const struct got_error *close_err = got_repo_close(repo);
8339 if (error == NULL)
8340 error = close_err;
8342 if (worktree)
8343 got_worktree_close(worktree);
8344 if (pack_fds) {
8345 const struct got_error *pack_err =
8346 got_repo_pack_fds_close(pack_fds);
8347 if (error == NULL)
8348 error = pack_err;
8350 free(cwd);
8351 free(id_str);
8352 free(gitconfig_path);
8353 free(editor);
8354 free(author);
8355 free(prepared_logmsg);
8356 return error;
8359 __dead static void
8360 usage_send(void)
8362 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8363 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8364 "[remote-repository]\n", getprogname());
8365 exit(1);
8368 static void
8369 print_load_info(int print_colored, int print_found, int print_trees,
8370 int ncolored, int nfound, int ntrees)
8372 if (print_colored) {
8373 printf("%d commit%s colored", ncolored,
8374 ncolored == 1 ? "" : "s");
8376 if (print_found) {
8377 printf("%s%d object%s found",
8378 ncolored > 0 ? "; " : "",
8379 nfound, nfound == 1 ? "" : "s");
8381 if (print_trees) {
8382 printf("; %d tree%s scanned", ntrees,
8383 ntrees == 1 ? "" : "s");
8387 struct got_send_progress_arg {
8388 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8389 int verbosity;
8390 int last_ncolored;
8391 int last_nfound;
8392 int last_ntrees;
8393 int loading_done;
8394 int last_ncommits;
8395 int last_nobj_total;
8396 int last_p_deltify;
8397 int last_p_written;
8398 int last_p_sent;
8399 int printed_something;
8400 int sent_something;
8401 struct got_pathlist_head *delete_branches;
8404 static const struct got_error *
8405 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8406 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8407 int nobj_written, off_t bytes_sent, const char *refname, int success)
8409 struct got_send_progress_arg *a = arg;
8410 char scaled_packsize[FMT_SCALED_STRSIZE];
8411 char scaled_sent[FMT_SCALED_STRSIZE];
8412 int p_deltify = 0, p_written = 0, p_sent = 0;
8413 int print_colored = 0, print_found = 0, print_trees = 0;
8414 int print_searching = 0, print_total = 0;
8415 int print_deltify = 0, print_written = 0, print_sent = 0;
8417 if (a->verbosity < 0)
8418 return NULL;
8420 if (refname) {
8421 const char *status = success ? "accepted" : "rejected";
8423 if (success) {
8424 struct got_pathlist_entry *pe;
8425 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8426 const char *branchname = pe->path;
8427 if (got_path_cmp(branchname, refname,
8428 strlen(branchname), strlen(refname)) == 0) {
8429 status = "deleted";
8430 a->sent_something = 1;
8431 break;
8436 if (a->printed_something)
8437 putchar('\n');
8438 printf("Server has %s %s", status, refname);
8439 a->printed_something = 1;
8440 return NULL;
8443 if (a->last_ncolored != ncolored) {
8444 print_colored = 1;
8445 a->last_ncolored = ncolored;
8448 if (a->last_nfound != nfound) {
8449 print_colored = 1;
8450 print_found = 1;
8451 a->last_nfound = nfound;
8454 if (a->last_ntrees != ntrees) {
8455 print_colored = 1;
8456 print_found = 1;
8457 print_trees = 1;
8458 a->last_ntrees = ntrees;
8461 if ((print_colored || print_found || print_trees) &&
8462 !a->loading_done) {
8463 printf("\r");
8464 print_load_info(print_colored, print_found, print_trees,
8465 ncolored, nfound, ntrees);
8466 a->printed_something = 1;
8467 fflush(stdout);
8468 return NULL;
8469 } else if (!a->loading_done) {
8470 printf("\r");
8471 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8472 printf("\n");
8473 a->loading_done = 1;
8476 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8477 return got_error_from_errno("fmt_scaled");
8478 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8479 return got_error_from_errno("fmt_scaled");
8481 if (a->last_ncommits != ncommits) {
8482 print_searching = 1;
8483 a->last_ncommits = ncommits;
8486 if (a->last_nobj_total != nobj_total) {
8487 print_searching = 1;
8488 print_total = 1;
8489 a->last_nobj_total = nobj_total;
8492 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8493 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8494 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8495 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8496 return got_error(GOT_ERR_NO_SPACE);
8499 if (nobj_deltify > 0 || nobj_written > 0) {
8500 if (nobj_deltify > 0) {
8501 p_deltify = (nobj_deltify * 100) / nobj_total;
8502 if (p_deltify != a->last_p_deltify) {
8503 a->last_p_deltify = p_deltify;
8504 print_searching = 1;
8505 print_total = 1;
8506 print_deltify = 1;
8509 if (nobj_written > 0) {
8510 p_written = (nobj_written * 100) / nobj_total;
8511 if (p_written != a->last_p_written) {
8512 a->last_p_written = p_written;
8513 print_searching = 1;
8514 print_total = 1;
8515 print_deltify = 1;
8516 print_written = 1;
8521 if (bytes_sent > 0) {
8522 p_sent = (bytes_sent * 100) / packfile_size;
8523 if (p_sent != a->last_p_sent) {
8524 a->last_p_sent = p_sent;
8525 print_searching = 1;
8526 print_total = 1;
8527 print_deltify = 1;
8528 print_written = 1;
8529 print_sent = 1;
8531 a->sent_something = 1;
8534 if (print_searching || print_total || print_deltify || print_written ||
8535 print_sent)
8536 printf("\r");
8537 if (print_searching)
8538 printf("packing %d reference%s", ncommits,
8539 ncommits == 1 ? "" : "s");
8540 if (print_total)
8541 printf("; %d object%s", nobj_total,
8542 nobj_total == 1 ? "" : "s");
8543 if (print_deltify)
8544 printf("; deltify: %d%%", p_deltify);
8545 if (print_sent)
8546 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8547 scaled_packsize, p_sent);
8548 else if (print_written)
8549 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8550 scaled_packsize, p_written);
8551 if (print_searching || print_total || print_deltify ||
8552 print_written || print_sent) {
8553 a->printed_something = 1;
8554 fflush(stdout);
8556 return NULL;
8559 static const struct got_error *
8560 cmd_send(int argc, char *argv[])
8562 const struct got_error *error = NULL;
8563 char *cwd = NULL, *repo_path = NULL;
8564 const char *remote_name;
8565 char *proto = NULL, *host = NULL, *port = NULL;
8566 char *repo_name = NULL, *server_path = NULL;
8567 const struct got_remote_repo *remotes, *remote = NULL;
8568 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8569 struct got_repository *repo = NULL;
8570 struct got_worktree *worktree = NULL;
8571 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8572 struct got_pathlist_head branches;
8573 struct got_pathlist_head tags;
8574 struct got_reflist_head all_branches;
8575 struct got_reflist_head all_tags;
8576 struct got_pathlist_head delete_args;
8577 struct got_pathlist_head delete_branches;
8578 struct got_reflist_entry *re;
8579 struct got_pathlist_entry *pe;
8580 int i, ch, sendfd = -1, sendstatus;
8581 pid_t sendpid = -1;
8582 struct got_send_progress_arg spa;
8583 int verbosity = 0, overwrite_refs = 0;
8584 int send_all_branches = 0, send_all_tags = 0;
8585 struct got_reference *ref = NULL;
8586 int *pack_fds = NULL;
8588 TAILQ_INIT(&branches);
8589 TAILQ_INIT(&tags);
8590 TAILQ_INIT(&all_branches);
8591 TAILQ_INIT(&all_tags);
8592 TAILQ_INIT(&delete_args);
8593 TAILQ_INIT(&delete_branches);
8595 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8596 switch (ch) {
8597 case 'a':
8598 send_all_branches = 1;
8599 break;
8600 case 'b':
8601 error = got_pathlist_append(&branches, optarg, NULL);
8602 if (error)
8603 return error;
8604 nbranches++;
8605 break;
8606 case 'd':
8607 error = got_pathlist_append(&delete_args, optarg, NULL);
8608 if (error)
8609 return error;
8610 break;
8611 case 'f':
8612 overwrite_refs = 1;
8613 break;
8614 case 'r':
8615 repo_path = realpath(optarg, NULL);
8616 if (repo_path == NULL)
8617 return got_error_from_errno2("realpath",
8618 optarg);
8619 got_path_strip_trailing_slashes(repo_path);
8620 break;
8621 case 't':
8622 error = got_pathlist_append(&tags, optarg, NULL);
8623 if (error)
8624 return error;
8625 ntags++;
8626 break;
8627 case 'T':
8628 send_all_tags = 1;
8629 break;
8630 case 'v':
8631 if (verbosity < 0)
8632 verbosity = 0;
8633 else if (verbosity < 3)
8634 verbosity++;
8635 break;
8636 case 'q':
8637 verbosity = -1;
8638 break;
8639 default:
8640 usage_send();
8641 /* NOTREACHED */
8644 argc -= optind;
8645 argv += optind;
8647 if (send_all_branches && !TAILQ_EMPTY(&branches))
8648 option_conflict('a', 'b');
8649 if (send_all_tags && !TAILQ_EMPTY(&tags))
8650 option_conflict('T', 't');
8653 if (argc == 0)
8654 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8655 else if (argc == 1)
8656 remote_name = argv[0];
8657 else
8658 usage_send();
8660 cwd = getcwd(NULL, 0);
8661 if (cwd == NULL) {
8662 error = got_error_from_errno("getcwd");
8663 goto done;
8666 error = got_repo_pack_fds_open(&pack_fds);
8667 if (error != NULL)
8668 goto done;
8670 if (repo_path == NULL) {
8671 error = got_worktree_open(&worktree, cwd);
8672 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8673 goto done;
8674 else
8675 error = NULL;
8676 if (worktree) {
8677 repo_path =
8678 strdup(got_worktree_get_repo_path(worktree));
8679 if (repo_path == NULL)
8680 error = got_error_from_errno("strdup");
8681 if (error)
8682 goto done;
8683 } else {
8684 repo_path = strdup(cwd);
8685 if (repo_path == NULL) {
8686 error = got_error_from_errno("strdup");
8687 goto done;
8692 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8693 if (error)
8694 goto done;
8696 if (worktree) {
8697 worktree_conf = got_worktree_get_gotconfig(worktree);
8698 if (worktree_conf) {
8699 got_gotconfig_get_remotes(&nremotes, &remotes,
8700 worktree_conf);
8701 for (i = 0; i < nremotes; i++) {
8702 if (strcmp(remotes[i].name, remote_name) == 0) {
8703 remote = &remotes[i];
8704 break;
8709 if (remote == NULL) {
8710 repo_conf = got_repo_get_gotconfig(repo);
8711 if (repo_conf) {
8712 got_gotconfig_get_remotes(&nremotes, &remotes,
8713 repo_conf);
8714 for (i = 0; i < nremotes; i++) {
8715 if (strcmp(remotes[i].name, remote_name) == 0) {
8716 remote = &remotes[i];
8717 break;
8722 if (remote == NULL) {
8723 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8724 for (i = 0; i < nremotes; i++) {
8725 if (strcmp(remotes[i].name, remote_name) == 0) {
8726 remote = &remotes[i];
8727 break;
8731 if (remote == NULL) {
8732 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8733 goto done;
8736 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8737 &repo_name, remote->send_url);
8738 if (error)
8739 goto done;
8741 if (strcmp(proto, "git") == 0) {
8742 #ifndef PROFILE
8743 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8744 "sendfd dns inet unveil", NULL) == -1)
8745 err(1, "pledge");
8746 #endif
8747 } else if (strcmp(proto, "git+ssh") == 0 ||
8748 strcmp(proto, "ssh") == 0) {
8749 #ifndef PROFILE
8750 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8751 "sendfd unveil", NULL) == -1)
8752 err(1, "pledge");
8753 #endif
8754 } else if (strcmp(proto, "http") == 0 ||
8755 strcmp(proto, "git+http") == 0) {
8756 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8757 goto done;
8758 } else {
8759 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8760 goto done;
8763 error = got_dial_apply_unveil(proto);
8764 if (error)
8765 goto done;
8767 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8768 if (error)
8769 goto done;
8771 if (send_all_branches) {
8772 error = got_ref_list(&all_branches, repo, "refs/heads",
8773 got_ref_cmp_by_name, NULL);
8774 if (error)
8775 goto done;
8776 TAILQ_FOREACH(re, &all_branches, entry) {
8777 const char *branchname = got_ref_get_name(re->ref);
8778 error = got_pathlist_append(&branches,
8779 branchname, NULL);
8780 if (error)
8781 goto done;
8782 nbranches++;
8784 } else if (nbranches == 0) {
8785 for (i = 0; i < remote->nsend_branches; i++) {
8786 got_pathlist_append(&branches,
8787 remote->send_branches[i], NULL);
8791 if (send_all_tags) {
8792 error = got_ref_list(&all_tags, repo, "refs/tags",
8793 got_ref_cmp_by_name, NULL);
8794 if (error)
8795 goto done;
8796 TAILQ_FOREACH(re, &all_tags, entry) {
8797 const char *tagname = got_ref_get_name(re->ref);
8798 error = got_pathlist_append(&tags,
8799 tagname, NULL);
8800 if (error)
8801 goto done;
8802 ntags++;
8807 * To prevent accidents only branches in refs/heads/ can be deleted
8808 * with 'got send -d'.
8809 * Deleting anything else requires local repository access or Git.
8811 TAILQ_FOREACH(pe, &delete_args, entry) {
8812 const char *branchname = pe->path;
8813 char *s;
8814 struct got_pathlist_entry *new;
8815 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8816 s = strdup(branchname);
8817 if (s == NULL) {
8818 error = got_error_from_errno("strdup");
8819 goto done;
8821 } else {
8822 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8823 error = got_error_from_errno("asprintf");
8824 goto done;
8827 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8828 if (error || new == NULL /* duplicate */)
8829 free(s);
8830 if (error)
8831 goto done;
8832 ndelete_branches++;
8835 if (nbranches == 0 && ndelete_branches == 0) {
8836 struct got_reference *head_ref;
8837 if (worktree)
8838 error = got_ref_open(&head_ref, repo,
8839 got_worktree_get_head_ref_name(worktree), 0);
8840 else
8841 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8842 if (error)
8843 goto done;
8844 if (got_ref_is_symbolic(head_ref)) {
8845 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8846 got_ref_close(head_ref);
8847 if (error)
8848 goto done;
8849 } else
8850 ref = head_ref;
8851 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8852 NULL);
8853 if (error)
8854 goto done;
8855 nbranches++;
8858 if (verbosity >= 0)
8859 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8860 port ? ":" : "", port ? port : "");
8862 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8863 server_path, verbosity);
8864 if (error)
8865 goto done;
8867 memset(&spa, 0, sizeof(spa));
8868 spa.last_scaled_packsize[0] = '\0';
8869 spa.last_p_deltify = -1;
8870 spa.last_p_written = -1;
8871 spa.verbosity = verbosity;
8872 spa.delete_branches = &delete_branches;
8873 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8874 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8875 check_cancelled, NULL);
8876 if (spa.printed_something)
8877 putchar('\n');
8878 if (error)
8879 goto done;
8880 if (!spa.sent_something && verbosity >= 0)
8881 printf("Already up-to-date\n");
8882 done:
8883 if (sendpid > 0) {
8884 if (kill(sendpid, SIGTERM) == -1)
8885 error = got_error_from_errno("kill");
8886 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8887 error = got_error_from_errno("waitpid");
8889 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8890 error = got_error_from_errno("close");
8891 if (repo) {
8892 const struct got_error *close_err = got_repo_close(repo);
8893 if (error == NULL)
8894 error = close_err;
8896 if (worktree)
8897 got_worktree_close(worktree);
8898 if (pack_fds) {
8899 const struct got_error *pack_err =
8900 got_repo_pack_fds_close(pack_fds);
8901 if (error == NULL)
8902 error = pack_err;
8904 if (ref)
8905 got_ref_close(ref);
8906 got_pathlist_free(&branches);
8907 got_pathlist_free(&tags);
8908 got_ref_list_free(&all_branches);
8909 got_ref_list_free(&all_tags);
8910 got_pathlist_free(&delete_args);
8911 TAILQ_FOREACH(pe, &delete_branches, entry)
8912 free((char *)pe->path);
8913 got_pathlist_free(&delete_branches);
8914 free(cwd);
8915 free(repo_path);
8916 free(proto);
8917 free(host);
8918 free(port);
8919 free(server_path);
8920 free(repo_name);
8921 return error;
8924 __dead static void
8925 usage_cherrypick(void)
8927 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8928 exit(1);
8931 static const struct got_error *
8932 cmd_cherrypick(int argc, char *argv[])
8934 const struct got_error *error = NULL;
8935 struct got_worktree *worktree = NULL;
8936 struct got_repository *repo = NULL;
8937 char *cwd = NULL, *commit_id_str = NULL;
8938 struct got_object_id *commit_id = NULL;
8939 struct got_commit_object *commit = NULL;
8940 struct got_object_qid *pid;
8941 int ch;
8942 struct got_update_progress_arg upa;
8943 int *pack_fds = NULL;
8945 while ((ch = getopt(argc, argv, "")) != -1) {
8946 switch (ch) {
8947 default:
8948 usage_cherrypick();
8949 /* NOTREACHED */
8953 argc -= optind;
8954 argv += optind;
8956 #ifndef PROFILE
8957 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8958 "unveil", NULL) == -1)
8959 err(1, "pledge");
8960 #endif
8961 if (argc != 1)
8962 usage_cherrypick();
8964 cwd = getcwd(NULL, 0);
8965 if (cwd == NULL) {
8966 error = got_error_from_errno("getcwd");
8967 goto done;
8970 error = got_repo_pack_fds_open(&pack_fds);
8971 if (error != NULL)
8972 goto done;
8974 error = got_worktree_open(&worktree, cwd);
8975 if (error) {
8976 if (error->code == GOT_ERR_NOT_WORKTREE)
8977 error = wrap_not_worktree_error(error, "cherrypick",
8978 cwd);
8979 goto done;
8982 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8983 NULL, pack_fds);
8984 if (error != NULL)
8985 goto done;
8987 error = apply_unveil(got_repo_get_path(repo), 0,
8988 got_worktree_get_root_path(worktree));
8989 if (error)
8990 goto done;
8992 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8993 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8994 if (error)
8995 goto done;
8996 error = got_object_id_str(&commit_id_str, commit_id);
8997 if (error)
8998 goto done;
9000 error = got_object_open_as_commit(&commit, repo, commit_id);
9001 if (error)
9002 goto done;
9003 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9004 memset(&upa, 0, sizeof(upa));
9005 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9006 commit_id, repo, update_progress, &upa, check_cancelled,
9007 NULL);
9008 if (error != NULL)
9009 goto done;
9011 if (upa.did_something)
9012 printf("Merged commit %s\n", commit_id_str);
9013 print_merge_progress_stats(&upa);
9014 done:
9015 if (commit)
9016 got_object_commit_close(commit);
9017 free(commit_id_str);
9018 if (worktree)
9019 got_worktree_close(worktree);
9020 if (repo) {
9021 const struct got_error *close_err = got_repo_close(repo);
9022 if (error == NULL)
9023 error = close_err;
9025 if (pack_fds) {
9026 const struct got_error *pack_err =
9027 got_repo_pack_fds_close(pack_fds);
9028 if (error == NULL)
9029 error = pack_err;
9032 return error;
9035 __dead static void
9036 usage_backout(void)
9038 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9039 exit(1);
9042 static const struct got_error *
9043 cmd_backout(int argc, char *argv[])
9045 const struct got_error *error = NULL;
9046 struct got_worktree *worktree = NULL;
9047 struct got_repository *repo = NULL;
9048 char *cwd = NULL, *commit_id_str = NULL;
9049 struct got_object_id *commit_id = NULL;
9050 struct got_commit_object *commit = NULL;
9051 struct got_object_qid *pid;
9052 int ch;
9053 struct got_update_progress_arg upa;
9054 int *pack_fds = NULL;
9056 while ((ch = getopt(argc, argv, "")) != -1) {
9057 switch (ch) {
9058 default:
9059 usage_backout();
9060 /* NOTREACHED */
9064 argc -= optind;
9065 argv += optind;
9067 #ifndef PROFILE
9068 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9069 "unveil", NULL) == -1)
9070 err(1, "pledge");
9071 #endif
9072 if (argc != 1)
9073 usage_backout();
9075 cwd = getcwd(NULL, 0);
9076 if (cwd == NULL) {
9077 error = got_error_from_errno("getcwd");
9078 goto done;
9081 error = got_repo_pack_fds_open(&pack_fds);
9082 if (error != NULL)
9083 goto done;
9085 error = got_worktree_open(&worktree, cwd);
9086 if (error) {
9087 if (error->code == GOT_ERR_NOT_WORKTREE)
9088 error = wrap_not_worktree_error(error, "backout", cwd);
9089 goto done;
9092 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9093 NULL, pack_fds);
9094 if (error != NULL)
9095 goto done;
9097 error = apply_unveil(got_repo_get_path(repo), 0,
9098 got_worktree_get_root_path(worktree));
9099 if (error)
9100 goto done;
9102 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9103 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9104 if (error)
9105 goto done;
9106 error = got_object_id_str(&commit_id_str, commit_id);
9107 if (error)
9108 goto done;
9110 error = got_object_open_as_commit(&commit, repo, commit_id);
9111 if (error)
9112 goto done;
9113 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9114 if (pid == NULL) {
9115 error = got_error(GOT_ERR_ROOT_COMMIT);
9116 goto done;
9119 memset(&upa, 0, sizeof(upa));
9120 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9121 repo, update_progress, &upa, check_cancelled, NULL);
9122 if (error != NULL)
9123 goto done;
9125 if (upa.did_something)
9126 printf("Backed out commit %s\n", commit_id_str);
9127 print_merge_progress_stats(&upa);
9128 done:
9129 if (commit)
9130 got_object_commit_close(commit);
9131 free(commit_id_str);
9132 if (worktree)
9133 got_worktree_close(worktree);
9134 if (repo) {
9135 const struct got_error *close_err = got_repo_close(repo);
9136 if (error == NULL)
9137 error = close_err;
9139 if (pack_fds) {
9140 const struct got_error *pack_err =
9141 got_repo_pack_fds_close(pack_fds);
9142 if (error == NULL)
9143 error = pack_err;
9145 return error;
9148 __dead static void
9149 usage_rebase(void)
9151 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9152 getprogname());
9153 exit(1);
9156 void
9157 trim_logmsg(char *logmsg, int limit)
9159 char *nl;
9160 size_t len;
9162 len = strlen(logmsg);
9163 if (len > limit)
9164 len = limit;
9165 logmsg[len] = '\0';
9166 nl = strchr(logmsg, '\n');
9167 if (nl)
9168 *nl = '\0';
9171 static const struct got_error *
9172 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9174 const struct got_error *err;
9175 char *logmsg0 = NULL;
9176 const char *s;
9178 err = got_object_commit_get_logmsg(&logmsg0, commit);
9179 if (err)
9180 return err;
9182 s = logmsg0;
9183 while (isspace((unsigned char)s[0]))
9184 s++;
9186 *logmsg = strdup(s);
9187 if (*logmsg == NULL) {
9188 err = got_error_from_errno("strdup");
9189 goto done;
9192 trim_logmsg(*logmsg, limit);
9193 done:
9194 free(logmsg0);
9195 return err;
9198 static const struct got_error *
9199 show_rebase_merge_conflict(struct got_object_id *id,
9200 struct got_repository *repo)
9202 const struct got_error *err;
9203 struct got_commit_object *commit = NULL;
9204 char *id_str = NULL, *logmsg = NULL;
9206 err = got_object_open_as_commit(&commit, repo, id);
9207 if (err)
9208 return err;
9210 err = got_object_id_str(&id_str, id);
9211 if (err)
9212 goto done;
9214 id_str[12] = '\0';
9216 err = get_short_logmsg(&logmsg, 42, commit);
9217 if (err)
9218 goto done;
9220 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9221 done:
9222 free(id_str);
9223 got_object_commit_close(commit);
9224 free(logmsg);
9225 return err;
9228 static const struct got_error *
9229 show_rebase_progress(struct got_commit_object *commit,
9230 struct got_object_id *old_id, struct got_object_id *new_id)
9232 const struct got_error *err;
9233 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9235 err = got_object_id_str(&old_id_str, old_id);
9236 if (err)
9237 goto done;
9239 if (new_id) {
9240 err = got_object_id_str(&new_id_str, new_id);
9241 if (err)
9242 goto done;
9245 old_id_str[12] = '\0';
9246 if (new_id_str)
9247 new_id_str[12] = '\0';
9249 err = get_short_logmsg(&logmsg, 42, commit);
9250 if (err)
9251 goto done;
9253 printf("%s -> %s: %s\n", old_id_str,
9254 new_id_str ? new_id_str : "no-op change", logmsg);
9255 done:
9256 free(old_id_str);
9257 free(new_id_str);
9258 free(logmsg);
9259 return err;
9262 static const struct got_error *
9263 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9264 struct got_reference *branch, struct got_reference *new_base_branch,
9265 struct got_reference *tmp_branch, struct got_repository *repo,
9266 int create_backup)
9268 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9269 return got_worktree_rebase_complete(worktree, fileindex,
9270 new_base_branch, tmp_branch, branch, repo, create_backup);
9273 static const struct got_error *
9274 rebase_commit(struct got_pathlist_head *merged_paths,
9275 struct got_worktree *worktree, struct got_fileindex *fileindex,
9276 struct got_reference *tmp_branch,
9277 struct got_object_id *commit_id, struct got_repository *repo)
9279 const struct got_error *error;
9280 struct got_commit_object *commit;
9281 struct got_object_id *new_commit_id;
9283 error = got_object_open_as_commit(&commit, repo, commit_id);
9284 if (error)
9285 return error;
9287 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9288 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9289 if (error) {
9290 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9291 goto done;
9292 error = show_rebase_progress(commit, commit_id, NULL);
9293 } else {
9294 error = show_rebase_progress(commit, commit_id, new_commit_id);
9295 free(new_commit_id);
9297 done:
9298 got_object_commit_close(commit);
9299 return error;
9302 struct check_path_prefix_arg {
9303 const char *path_prefix;
9304 size_t len;
9305 int errcode;
9308 static const struct got_error *
9309 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9310 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9311 struct got_object_id *id1, struct got_object_id *id2,
9312 const char *path1, const char *path2,
9313 mode_t mode1, mode_t mode2, struct got_repository *repo)
9315 struct check_path_prefix_arg *a = arg;
9317 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9318 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9319 return got_error(a->errcode);
9321 return NULL;
9324 static const struct got_error *
9325 check_path_prefix(struct got_object_id *parent_id,
9326 struct got_object_id *commit_id, const char *path_prefix,
9327 int errcode, struct got_repository *repo)
9329 const struct got_error *err;
9330 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9331 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9332 struct check_path_prefix_arg cpp_arg;
9334 if (got_path_is_root_dir(path_prefix))
9335 return NULL;
9337 err = got_object_open_as_commit(&commit, repo, commit_id);
9338 if (err)
9339 goto done;
9341 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9342 if (err)
9343 goto done;
9345 err = got_object_open_as_tree(&tree1, repo,
9346 got_object_commit_get_tree_id(parent_commit));
9347 if (err)
9348 goto done;
9350 err = got_object_open_as_tree(&tree2, repo,
9351 got_object_commit_get_tree_id(commit));
9352 if (err)
9353 goto done;
9355 cpp_arg.path_prefix = path_prefix;
9356 while (cpp_arg.path_prefix[0] == '/')
9357 cpp_arg.path_prefix++;
9358 cpp_arg.len = strlen(cpp_arg.path_prefix);
9359 cpp_arg.errcode = errcode;
9360 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9361 check_path_prefix_in_diff, &cpp_arg, 0);
9362 done:
9363 if (tree1)
9364 got_object_tree_close(tree1);
9365 if (tree2)
9366 got_object_tree_close(tree2);
9367 if (commit)
9368 got_object_commit_close(commit);
9369 if (parent_commit)
9370 got_object_commit_close(parent_commit);
9371 return err;
9374 static const struct got_error *
9375 collect_commits(struct got_object_id_queue *commits,
9376 struct got_object_id *initial_commit_id,
9377 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9378 const char *path_prefix, int path_prefix_errcode,
9379 struct got_repository *repo)
9381 const struct got_error *err = NULL;
9382 struct got_commit_graph *graph = NULL;
9383 struct got_object_id *parent_id = NULL;
9384 struct got_object_qid *qid;
9385 struct got_object_id *commit_id = initial_commit_id;
9387 err = got_commit_graph_open(&graph, "/", 1);
9388 if (err)
9389 return err;
9391 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9392 check_cancelled, NULL);
9393 if (err)
9394 goto done;
9395 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9396 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9397 check_cancelled, NULL);
9398 if (err) {
9399 if (err->code == GOT_ERR_ITER_COMPLETED) {
9400 err = got_error_msg(GOT_ERR_ANCESTRY,
9401 "ran out of commits to rebase before "
9402 "youngest common ancestor commit has "
9403 "been reached?!?");
9405 goto done;
9406 } else {
9407 err = check_path_prefix(parent_id, commit_id,
9408 path_prefix, path_prefix_errcode, repo);
9409 if (err)
9410 goto done;
9412 err = got_object_qid_alloc(&qid, commit_id);
9413 if (err)
9414 goto done;
9415 STAILQ_INSERT_HEAD(commits, qid, entry);
9416 commit_id = parent_id;
9419 done:
9420 got_commit_graph_close(graph);
9421 return err;
9424 static const struct got_error *
9425 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9427 const struct got_error *err = NULL;
9428 time_t committer_time;
9429 struct tm tm;
9430 char datebuf[11]; /* YYYY-MM-DD + NUL */
9431 char *author0 = NULL, *author, *smallerthan;
9432 char *logmsg0 = NULL, *logmsg, *newline;
9434 committer_time = got_object_commit_get_committer_time(commit);
9435 if (gmtime_r(&committer_time, &tm) == NULL)
9436 return got_error_from_errno("gmtime_r");
9437 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9438 return got_error(GOT_ERR_NO_SPACE);
9440 author0 = strdup(got_object_commit_get_author(commit));
9441 if (author0 == NULL)
9442 return got_error_from_errno("strdup");
9443 author = author0;
9444 smallerthan = strchr(author, '<');
9445 if (smallerthan && smallerthan[1] != '\0')
9446 author = smallerthan + 1;
9447 author[strcspn(author, "@>")] = '\0';
9449 err = got_object_commit_get_logmsg(&logmsg0, commit);
9450 if (err)
9451 goto done;
9452 logmsg = logmsg0;
9453 while (*logmsg == '\n')
9454 logmsg++;
9455 newline = strchr(logmsg, '\n');
9456 if (newline)
9457 *newline = '\0';
9459 if (asprintf(brief_str, "%s %s %s",
9460 datebuf, author, logmsg) == -1)
9461 err = got_error_from_errno("asprintf");
9462 done:
9463 free(author0);
9464 free(logmsg0);
9465 return err;
9468 static const struct got_error *
9469 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9470 struct got_repository *repo)
9472 const struct got_error *err;
9473 char *id_str;
9475 err = got_object_id_str(&id_str, id);
9476 if (err)
9477 return err;
9479 err = got_ref_delete(ref, repo);
9480 if (err)
9481 goto done;
9483 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9484 done:
9485 free(id_str);
9486 return err;
9489 static const struct got_error *
9490 print_backup_ref(const char *branch_name, const char *new_id_str,
9491 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9492 struct got_reflist_object_id_map *refs_idmap,
9493 struct got_repository *repo)
9495 const struct got_error *err = NULL;
9496 struct got_reflist_head *refs;
9497 char *refs_str = NULL;
9498 struct got_object_id *new_commit_id = NULL;
9499 struct got_commit_object *new_commit = NULL;
9500 char *new_commit_brief_str = NULL;
9501 struct got_object_id *yca_id = NULL;
9502 struct got_commit_object *yca_commit = NULL;
9503 char *yca_id_str = NULL, *yca_brief_str = NULL;
9504 char *custom_refs_str;
9506 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9507 return got_error_from_errno("asprintf");
9509 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9510 0, 0, refs_idmap, custom_refs_str);
9511 if (err)
9512 goto done;
9514 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9515 if (err)
9516 goto done;
9518 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9519 if (refs) {
9520 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9521 if (err)
9522 goto done;
9525 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9526 if (err)
9527 goto done;
9529 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9530 if (err)
9531 goto done;
9533 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9534 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9535 if (err)
9536 goto done;
9538 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9539 refs_str ? " (" : "", refs_str ? refs_str : "",
9540 refs_str ? ")" : "", new_commit_brief_str);
9541 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9542 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9543 free(refs_str);
9544 refs_str = NULL;
9546 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9547 if (err)
9548 goto done;
9550 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9551 if (err)
9552 goto done;
9554 err = got_object_id_str(&yca_id_str, yca_id);
9555 if (err)
9556 goto done;
9558 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9559 if (refs) {
9560 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9561 if (err)
9562 goto done;
9564 printf("history forked at %s%s%s%s\n %s\n",
9565 yca_id_str,
9566 refs_str ? " (" : "", refs_str ? refs_str : "",
9567 refs_str ? ")" : "", yca_brief_str);
9569 done:
9570 free(custom_refs_str);
9571 free(new_commit_id);
9572 free(refs_str);
9573 free(yca_id);
9574 free(yca_id_str);
9575 free(yca_brief_str);
9576 if (new_commit)
9577 got_object_commit_close(new_commit);
9578 if (yca_commit)
9579 got_object_commit_close(yca_commit);
9581 return NULL;
9584 static const struct got_error *
9585 process_backup_refs(const char *backup_ref_prefix,
9586 const char *wanted_branch_name,
9587 int delete, struct got_repository *repo)
9589 const struct got_error *err;
9590 struct got_reflist_head refs, backup_refs;
9591 struct got_reflist_entry *re;
9592 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9593 struct got_object_id *old_commit_id = NULL;
9594 char *branch_name = NULL;
9595 struct got_commit_object *old_commit = NULL;
9596 struct got_reflist_object_id_map *refs_idmap = NULL;
9597 int wanted_branch_found = 0;
9599 TAILQ_INIT(&refs);
9600 TAILQ_INIT(&backup_refs);
9602 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9603 if (err)
9604 return err;
9606 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9607 if (err)
9608 goto done;
9610 if (wanted_branch_name) {
9611 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9612 wanted_branch_name += 11;
9615 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9616 got_ref_cmp_by_commit_timestamp_descending, repo);
9617 if (err)
9618 goto done;
9620 TAILQ_FOREACH(re, &backup_refs, entry) {
9621 const char *refname = got_ref_get_name(re->ref);
9622 char *slash;
9624 err = check_cancelled(NULL);
9625 if (err)
9626 break;
9628 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9629 if (err)
9630 break;
9632 err = got_object_open_as_commit(&old_commit, repo,
9633 old_commit_id);
9634 if (err)
9635 break;
9637 if (strncmp(backup_ref_prefix, refname,
9638 backup_ref_prefix_len) == 0)
9639 refname += backup_ref_prefix_len;
9641 while (refname[0] == '/')
9642 refname++;
9644 branch_name = strdup(refname);
9645 if (branch_name == NULL) {
9646 err = got_error_from_errno("strdup");
9647 break;
9649 slash = strrchr(branch_name, '/');
9650 if (slash) {
9651 *slash = '\0';
9652 refname += strlen(branch_name) + 1;
9655 if (wanted_branch_name == NULL ||
9656 strcmp(wanted_branch_name, branch_name) == 0) {
9657 wanted_branch_found = 1;
9658 if (delete) {
9659 err = delete_backup_ref(re->ref,
9660 old_commit_id, repo);
9661 } else {
9662 err = print_backup_ref(branch_name, refname,
9663 old_commit_id, old_commit, refs_idmap,
9664 repo);
9666 if (err)
9667 break;
9670 free(old_commit_id);
9671 old_commit_id = NULL;
9672 free(branch_name);
9673 branch_name = NULL;
9674 got_object_commit_close(old_commit);
9675 old_commit = NULL;
9678 if (wanted_branch_name && !wanted_branch_found) {
9679 err = got_error_fmt(GOT_ERR_NOT_REF,
9680 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9682 done:
9683 if (refs_idmap)
9684 got_reflist_object_id_map_free(refs_idmap);
9685 got_ref_list_free(&refs);
9686 got_ref_list_free(&backup_refs);
9687 free(old_commit_id);
9688 free(branch_name);
9689 if (old_commit)
9690 got_object_commit_close(old_commit);
9691 return err;
9694 static const struct got_error *
9695 abort_progress(void *arg, unsigned char status, const char *path)
9698 * Unversioned files should not clutter progress output when
9699 * an operation is aborted.
9701 if (status == GOT_STATUS_UNVERSIONED)
9702 return NULL;
9704 return update_progress(arg, status, path);
9707 static const struct got_error *
9708 cmd_rebase(int argc, char *argv[])
9710 const struct got_error *error = NULL;
9711 struct got_worktree *worktree = NULL;
9712 struct got_repository *repo = NULL;
9713 struct got_fileindex *fileindex = NULL;
9714 char *cwd = NULL;
9715 struct got_reference *branch = NULL;
9716 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9717 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9718 struct got_object_id *resume_commit_id = NULL;
9719 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9720 struct got_commit_object *commit = NULL;
9721 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9722 int histedit_in_progress = 0, merge_in_progress = 0;
9723 int create_backup = 1, list_backups = 0, delete_backups = 0;
9724 struct got_object_id_queue commits;
9725 struct got_pathlist_head merged_paths;
9726 const struct got_object_id_queue *parent_ids;
9727 struct got_object_qid *qid, *pid;
9728 struct got_update_progress_arg upa;
9729 int *pack_fds = NULL;
9731 STAILQ_INIT(&commits);
9732 TAILQ_INIT(&merged_paths);
9733 memset(&upa, 0, sizeof(upa));
9735 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9736 switch (ch) {
9737 case 'a':
9738 abort_rebase = 1;
9739 break;
9740 case 'c':
9741 continue_rebase = 1;
9742 break;
9743 case 'l':
9744 list_backups = 1;
9745 break;
9746 case 'X':
9747 delete_backups = 1;
9748 break;
9749 default:
9750 usage_rebase();
9751 /* NOTREACHED */
9755 argc -= optind;
9756 argv += optind;
9758 #ifndef PROFILE
9759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9760 "unveil", NULL) == -1)
9761 err(1, "pledge");
9762 #endif
9763 if (list_backups) {
9764 if (abort_rebase)
9765 option_conflict('l', 'a');
9766 if (continue_rebase)
9767 option_conflict('l', 'c');
9768 if (delete_backups)
9769 option_conflict('l', 'X');
9770 if (argc != 0 && argc != 1)
9771 usage_rebase();
9772 } else if (delete_backups) {
9773 if (abort_rebase)
9774 option_conflict('X', 'a');
9775 if (continue_rebase)
9776 option_conflict('X', 'c');
9777 if (list_backups)
9778 option_conflict('l', 'X');
9779 if (argc != 0 && argc != 1)
9780 usage_rebase();
9781 } else {
9782 if (abort_rebase && continue_rebase)
9783 usage_rebase();
9784 else if (abort_rebase || continue_rebase) {
9785 if (argc != 0)
9786 usage_rebase();
9787 } else if (argc != 1)
9788 usage_rebase();
9791 cwd = getcwd(NULL, 0);
9792 if (cwd == NULL) {
9793 error = got_error_from_errno("getcwd");
9794 goto done;
9797 error = got_repo_pack_fds_open(&pack_fds);
9798 if (error != NULL)
9799 goto done;
9801 error = got_worktree_open(&worktree, cwd);
9802 if (error) {
9803 if (list_backups || delete_backups) {
9804 if (error->code != GOT_ERR_NOT_WORKTREE)
9805 goto done;
9806 } else {
9807 if (error->code == GOT_ERR_NOT_WORKTREE)
9808 error = wrap_not_worktree_error(error,
9809 "rebase", cwd);
9810 goto done;
9814 error = got_repo_open(&repo,
9815 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9816 pack_fds);
9817 if (error != NULL)
9818 goto done;
9820 error = apply_unveil(got_repo_get_path(repo), 0,
9821 worktree ? got_worktree_get_root_path(worktree) : NULL);
9822 if (error)
9823 goto done;
9825 if (list_backups || delete_backups) {
9826 error = process_backup_refs(
9827 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9828 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9829 goto done; /* nothing else to do */
9832 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9833 worktree);
9834 if (error)
9835 goto done;
9836 if (histedit_in_progress) {
9837 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9838 goto done;
9841 error = got_worktree_merge_in_progress(&merge_in_progress,
9842 worktree, repo);
9843 if (error)
9844 goto done;
9845 if (merge_in_progress) {
9846 error = got_error(GOT_ERR_MERGE_BUSY);
9847 goto done;
9850 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9851 if (error)
9852 goto done;
9854 if (abort_rebase) {
9855 if (!rebase_in_progress) {
9856 error = got_error(GOT_ERR_NOT_REBASING);
9857 goto done;
9859 error = got_worktree_rebase_continue(&resume_commit_id,
9860 &new_base_branch, &tmp_branch, &branch, &fileindex,
9861 worktree, repo);
9862 if (error)
9863 goto done;
9864 printf("Switching work tree to %s\n",
9865 got_ref_get_symref_target(new_base_branch));
9866 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9867 new_base_branch, abort_progress, &upa);
9868 if (error)
9869 goto done;
9870 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9871 print_merge_progress_stats(&upa);
9872 goto done; /* nothing else to do */
9875 if (continue_rebase) {
9876 if (!rebase_in_progress) {
9877 error = got_error(GOT_ERR_NOT_REBASING);
9878 goto done;
9880 error = got_worktree_rebase_continue(&resume_commit_id,
9881 &new_base_branch, &tmp_branch, &branch, &fileindex,
9882 worktree, repo);
9883 if (error)
9884 goto done;
9886 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9887 resume_commit_id, repo);
9888 if (error)
9889 goto done;
9891 yca_id = got_object_id_dup(resume_commit_id);
9892 if (yca_id == NULL) {
9893 error = got_error_from_errno("got_object_id_dup");
9894 goto done;
9896 } else {
9897 error = got_ref_open(&branch, repo, argv[0], 0);
9898 if (error != NULL)
9899 goto done;
9902 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9903 if (error)
9904 goto done;
9906 if (!continue_rebase) {
9907 struct got_object_id *base_commit_id;
9909 base_commit_id = got_worktree_get_base_commit_id(worktree);
9910 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9911 base_commit_id, branch_head_commit_id, 1, repo,
9912 check_cancelled, NULL);
9913 if (error)
9914 goto done;
9915 if (yca_id == NULL) {
9916 error = got_error_msg(GOT_ERR_ANCESTRY,
9917 "specified branch shares no common ancestry "
9918 "with work tree's branch");
9919 goto done;
9922 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9923 if (error) {
9924 if (error->code != GOT_ERR_ANCESTRY)
9925 goto done;
9926 error = NULL;
9927 } else {
9928 struct got_pathlist_head paths;
9929 printf("%s is already based on %s\n",
9930 got_ref_get_name(branch),
9931 got_worktree_get_head_ref_name(worktree));
9932 error = switch_head_ref(branch, branch_head_commit_id,
9933 worktree, repo);
9934 if (error)
9935 goto done;
9936 error = got_worktree_set_base_commit_id(worktree, repo,
9937 branch_head_commit_id);
9938 if (error)
9939 goto done;
9940 TAILQ_INIT(&paths);
9941 error = got_pathlist_append(&paths, "", NULL);
9942 if (error)
9943 goto done;
9944 error = got_worktree_checkout_files(worktree,
9945 &paths, repo, update_progress, &upa,
9946 check_cancelled, NULL);
9947 got_pathlist_free(&paths);
9948 if (error)
9949 goto done;
9950 if (upa.did_something) {
9951 char *id_str;
9952 error = got_object_id_str(&id_str,
9953 branch_head_commit_id);
9954 if (error)
9955 goto done;
9956 printf("Updated to %s: %s\n",
9957 got_worktree_get_head_ref_name(worktree),
9958 id_str);
9959 free(id_str);
9960 } else
9961 printf("Already up-to-date\n");
9962 print_update_progress_stats(&upa);
9963 goto done;
9967 commit_id = branch_head_commit_id;
9968 error = got_object_open_as_commit(&commit, repo, commit_id);
9969 if (error)
9970 goto done;
9972 parent_ids = got_object_commit_get_parent_ids(commit);
9973 pid = STAILQ_FIRST(parent_ids);
9974 if (pid == NULL) {
9975 error = got_error(GOT_ERR_EMPTY_REBASE);
9976 goto done;
9978 error = collect_commits(&commits, commit_id, &pid->id,
9979 yca_id, got_worktree_get_path_prefix(worktree),
9980 GOT_ERR_REBASE_PATH, repo);
9981 got_object_commit_close(commit);
9982 commit = NULL;
9983 if (error)
9984 goto done;
9986 if (!continue_rebase) {
9987 error = got_worktree_rebase_prepare(&new_base_branch,
9988 &tmp_branch, &fileindex, worktree, branch, repo);
9989 if (error)
9990 goto done;
9993 if (STAILQ_EMPTY(&commits)) {
9994 if (continue_rebase) {
9995 error = rebase_complete(worktree, fileindex,
9996 branch, new_base_branch, tmp_branch, repo,
9997 create_backup);
9998 goto done;
9999 } else {
10000 /* Fast-forward the reference of the branch. */
10001 struct got_object_id *new_head_commit_id;
10002 char *id_str;
10003 error = got_ref_resolve(&new_head_commit_id, repo,
10004 new_base_branch);
10005 if (error)
10006 goto done;
10007 error = got_object_id_str(&id_str, new_head_commit_id);
10008 printf("Forwarding %s to commit %s\n",
10009 got_ref_get_name(branch), id_str);
10010 free(id_str);
10011 error = got_ref_change_ref(branch,
10012 new_head_commit_id);
10013 if (error)
10014 goto done;
10015 /* No backup needed since objects did not change. */
10016 create_backup = 0;
10020 pid = NULL;
10021 STAILQ_FOREACH(qid, &commits, entry) {
10023 commit_id = &qid->id;
10024 parent_id = pid ? &pid->id : yca_id;
10025 pid = qid;
10027 memset(&upa, 0, sizeof(upa));
10028 error = got_worktree_rebase_merge_files(&merged_paths,
10029 worktree, fileindex, parent_id, commit_id, repo,
10030 update_progress, &upa, check_cancelled, NULL);
10031 if (error)
10032 goto done;
10034 print_merge_progress_stats(&upa);
10035 if (upa.conflicts > 0 || upa.missing > 0 ||
10036 upa.not_deleted > 0 || upa.unversioned > 0) {
10037 if (upa.conflicts > 0) {
10038 error = show_rebase_merge_conflict(&qid->id,
10039 repo);
10040 if (error)
10041 goto done;
10043 got_worktree_rebase_pathlist_free(&merged_paths);
10044 break;
10047 error = rebase_commit(&merged_paths, worktree, fileindex,
10048 tmp_branch, commit_id, repo);
10049 got_worktree_rebase_pathlist_free(&merged_paths);
10050 if (error)
10051 goto done;
10054 if (upa.conflicts > 0 || upa.missing > 0 ||
10055 upa.not_deleted > 0 || upa.unversioned > 0) {
10056 error = got_worktree_rebase_postpone(worktree, fileindex);
10057 if (error)
10058 goto done;
10059 if (upa.conflicts > 0 && upa.missing == 0 &&
10060 upa.not_deleted == 0 && upa.unversioned == 0) {
10061 error = got_error_msg(GOT_ERR_CONFLICTS,
10062 "conflicts must be resolved before rebasing "
10063 "can continue");
10064 } else if (upa.conflicts > 0) {
10065 error = got_error_msg(GOT_ERR_CONFLICTS,
10066 "conflicts must be resolved before rebasing "
10067 "can continue; changes destined for some "
10068 "files were not yet merged and should be "
10069 "merged manually if required before the "
10070 "rebase operation is continued");
10071 } else {
10072 error = got_error_msg(GOT_ERR_CONFLICTS,
10073 "changes destined for some files were not "
10074 "yet merged and should be merged manually "
10075 "if required before the rebase operation "
10076 "is continued");
10078 } else
10079 error = rebase_complete(worktree, fileindex, branch,
10080 new_base_branch, tmp_branch, repo, create_backup);
10081 done:
10082 got_object_id_queue_free(&commits);
10083 free(branch_head_commit_id);
10084 free(resume_commit_id);
10085 free(yca_id);
10086 if (commit)
10087 got_object_commit_close(commit);
10088 if (branch)
10089 got_ref_close(branch);
10090 if (new_base_branch)
10091 got_ref_close(new_base_branch);
10092 if (tmp_branch)
10093 got_ref_close(tmp_branch);
10094 if (worktree)
10095 got_worktree_close(worktree);
10096 if (repo) {
10097 const struct got_error *close_err = got_repo_close(repo);
10098 if (error == NULL)
10099 error = close_err;
10101 if (pack_fds) {
10102 const struct got_error *pack_err =
10103 got_repo_pack_fds_close(pack_fds);
10104 if (error == NULL)
10105 error = pack_err;
10107 return error;
10110 __dead static void
10111 usage_histedit(void)
10113 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10114 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10115 getprogname());
10116 exit(1);
10119 #define GOT_HISTEDIT_PICK 'p'
10120 #define GOT_HISTEDIT_EDIT 'e'
10121 #define GOT_HISTEDIT_FOLD 'f'
10122 #define GOT_HISTEDIT_DROP 'd'
10123 #define GOT_HISTEDIT_MESG 'm'
10125 static const struct got_histedit_cmd {
10126 unsigned char code;
10127 const char *name;
10128 const char *desc;
10129 } got_histedit_cmds[] = {
10130 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10131 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10132 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10133 "be used" },
10134 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10135 { GOT_HISTEDIT_MESG, "mesg",
10136 "single-line log message for commit above (open editor if empty)" },
10139 struct got_histedit_list_entry {
10140 TAILQ_ENTRY(got_histedit_list_entry) entry;
10141 struct got_object_id *commit_id;
10142 const struct got_histedit_cmd *cmd;
10143 char *logmsg;
10145 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10147 static const struct got_error *
10148 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10149 FILE *f, struct got_repository *repo)
10151 const struct got_error *err = NULL;
10152 char *logmsg = NULL, *id_str = NULL;
10153 struct got_commit_object *commit = NULL;
10154 int n;
10156 err = got_object_open_as_commit(&commit, repo, commit_id);
10157 if (err)
10158 goto done;
10160 err = get_short_logmsg(&logmsg, 34, commit);
10161 if (err)
10162 goto done;
10164 err = got_object_id_str(&id_str, commit_id);
10165 if (err)
10166 goto done;
10168 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10169 if (n < 0)
10170 err = got_ferror(f, GOT_ERR_IO);
10171 done:
10172 if (commit)
10173 got_object_commit_close(commit);
10174 free(id_str);
10175 free(logmsg);
10176 return err;
10179 static const struct got_error *
10180 histedit_write_commit_list(struct got_object_id_queue *commits,
10181 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10182 struct got_repository *repo)
10184 const struct got_error *err = NULL;
10185 struct got_object_qid *qid;
10186 const char *histedit_cmd = NULL;
10188 if (STAILQ_EMPTY(commits))
10189 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10191 STAILQ_FOREACH(qid, commits, entry) {
10192 histedit_cmd = got_histedit_cmds[0].name;
10193 if (edit_only)
10194 histedit_cmd = "edit";
10195 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10196 histedit_cmd = "fold";
10197 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10198 if (err)
10199 break;
10200 if (edit_logmsg_only) {
10201 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10202 if (n < 0) {
10203 err = got_ferror(f, GOT_ERR_IO);
10204 break;
10209 return err;
10212 static const struct got_error *
10213 write_cmd_list(FILE *f, const char *branch_name,
10214 struct got_object_id_queue *commits)
10216 const struct got_error *err = NULL;
10217 size_t i;
10218 int n;
10219 char *id_str;
10220 struct got_object_qid *qid;
10222 qid = STAILQ_FIRST(commits);
10223 err = got_object_id_str(&id_str, &qid->id);
10224 if (err)
10225 return err;
10227 n = fprintf(f,
10228 "# Editing the history of branch '%s' starting at\n"
10229 "# commit %s\n"
10230 "# Commits will be processed in order from top to "
10231 "bottom of this file.\n", branch_name, id_str);
10232 if (n < 0) {
10233 err = got_ferror(f, GOT_ERR_IO);
10234 goto done;
10237 n = fprintf(f, "# Available histedit commands:\n");
10238 if (n < 0) {
10239 err = got_ferror(f, GOT_ERR_IO);
10240 goto done;
10243 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10244 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10245 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10246 cmd->desc);
10247 if (n < 0) {
10248 err = got_ferror(f, GOT_ERR_IO);
10249 break;
10252 done:
10253 free(id_str);
10254 return err;
10257 static const struct got_error *
10258 histedit_syntax_error(int lineno)
10260 static char msg[42];
10261 int ret;
10263 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10264 lineno);
10265 if (ret == -1 || ret >= sizeof(msg))
10266 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10268 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10271 static const struct got_error *
10272 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10273 char *logmsg, struct got_repository *repo)
10275 const struct got_error *err;
10276 struct got_commit_object *folded_commit = NULL;
10277 char *id_str, *folded_logmsg = NULL;
10279 err = got_object_id_str(&id_str, hle->commit_id);
10280 if (err)
10281 return err;
10283 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10284 if (err)
10285 goto done;
10287 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10288 if (err)
10289 goto done;
10290 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10291 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10292 folded_logmsg) == -1) {
10293 err = got_error_from_errno("asprintf");
10295 done:
10296 if (folded_commit)
10297 got_object_commit_close(folded_commit);
10298 free(id_str);
10299 free(folded_logmsg);
10300 return err;
10303 static struct got_histedit_list_entry *
10304 get_folded_commits(struct got_histedit_list_entry *hle)
10306 struct got_histedit_list_entry *prev, *folded = NULL;
10308 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10309 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10310 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10311 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10312 folded = prev;
10313 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10316 return folded;
10319 static const struct got_error *
10320 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10321 struct got_repository *repo)
10323 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10324 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10325 const struct got_error *err = NULL;
10326 struct got_commit_object *commit = NULL;
10327 int logmsg_len;
10328 int fd;
10329 struct got_histedit_list_entry *folded = NULL;
10331 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10332 if (err)
10333 return err;
10335 folded = get_folded_commits(hle);
10336 if (folded) {
10337 while (folded != hle) {
10338 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10339 folded = TAILQ_NEXT(folded, entry);
10340 continue;
10342 err = append_folded_commit_msg(&new_msg, folded,
10343 logmsg, repo);
10344 if (err)
10345 goto done;
10346 free(logmsg);
10347 logmsg = new_msg;
10348 folded = TAILQ_NEXT(folded, entry);
10352 err = got_object_id_str(&id_str, hle->commit_id);
10353 if (err)
10354 goto done;
10355 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10356 if (err)
10357 goto done;
10358 logmsg_len = asprintf(&new_msg,
10359 "%s\n# original log message of commit %s: %s",
10360 logmsg ? logmsg : "", id_str, orig_logmsg);
10361 if (logmsg_len == -1) {
10362 err = got_error_from_errno("asprintf");
10363 goto done;
10365 free(logmsg);
10366 logmsg = new_msg;
10368 err = got_object_id_str(&id_str, hle->commit_id);
10369 if (err)
10370 goto done;
10372 err = got_opentemp_named_fd(&logmsg_path, &fd,
10373 GOT_TMPDIR_STR "/got-logmsg");
10374 if (err)
10375 goto done;
10377 write(fd, logmsg, logmsg_len);
10378 close(fd);
10380 err = get_editor(&editor);
10381 if (err)
10382 goto done;
10384 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10385 logmsg_len, 0);
10386 if (err) {
10387 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10388 goto done;
10389 err = NULL;
10390 hle->logmsg = strdup(new_msg);
10391 if (hle->logmsg == NULL)
10392 err = got_error_from_errno("strdup");
10394 done:
10395 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10396 err = got_error_from_errno2("unlink", logmsg_path);
10397 free(logmsg_path);
10398 free(logmsg);
10399 free(orig_logmsg);
10400 free(editor);
10401 if (commit)
10402 got_object_commit_close(commit);
10403 return err;
10406 static const struct got_error *
10407 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10408 FILE *f, struct got_repository *repo)
10410 const struct got_error *err = NULL;
10411 char *line = NULL, *p, *end;
10412 size_t i, size;
10413 ssize_t len;
10414 int lineno = 0;
10415 const struct got_histedit_cmd *cmd;
10416 struct got_object_id *commit_id = NULL;
10417 struct got_histedit_list_entry *hle = NULL;
10419 for (;;) {
10420 len = getline(&line, &size, f);
10421 if (len == -1) {
10422 const struct got_error *getline_err;
10423 if (feof(f))
10424 break;
10425 getline_err = got_error_from_errno("getline");
10426 err = got_ferror(f, getline_err->code);
10427 break;
10429 lineno++;
10430 p = line;
10431 while (isspace((unsigned char)p[0]))
10432 p++;
10433 if (p[0] == '#' || p[0] == '\0') {
10434 free(line);
10435 line = NULL;
10436 continue;
10438 cmd = NULL;
10439 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10440 cmd = &got_histedit_cmds[i];
10441 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10442 isspace((unsigned char)p[strlen(cmd->name)])) {
10443 p += strlen(cmd->name);
10444 break;
10446 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10447 p++;
10448 break;
10451 if (i == nitems(got_histedit_cmds)) {
10452 err = histedit_syntax_error(lineno);
10453 break;
10455 while (isspace((unsigned char)p[0]))
10456 p++;
10457 if (cmd->code == GOT_HISTEDIT_MESG) {
10458 if (hle == NULL || hle->logmsg != NULL) {
10459 err = got_error(GOT_ERR_HISTEDIT_CMD);
10460 break;
10462 if (p[0] == '\0') {
10463 err = histedit_edit_logmsg(hle, repo);
10464 if (err)
10465 break;
10466 } else {
10467 hle->logmsg = strdup(p);
10468 if (hle->logmsg == NULL) {
10469 err = got_error_from_errno("strdup");
10470 break;
10473 free(line);
10474 line = NULL;
10475 continue;
10476 } else {
10477 end = p;
10478 while (end[0] && !isspace((unsigned char)end[0]))
10479 end++;
10480 *end = '\0';
10482 err = got_object_resolve_id_str(&commit_id, repo, p);
10483 if (err) {
10484 /* override error code */
10485 err = histedit_syntax_error(lineno);
10486 break;
10489 hle = malloc(sizeof(*hle));
10490 if (hle == NULL) {
10491 err = got_error_from_errno("malloc");
10492 break;
10494 hle->cmd = cmd;
10495 hle->commit_id = commit_id;
10496 hle->logmsg = NULL;
10497 commit_id = NULL;
10498 free(line);
10499 line = NULL;
10500 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10503 free(line);
10504 free(commit_id);
10505 return err;
10508 static const struct got_error *
10509 histedit_check_script(struct got_histedit_list *histedit_cmds,
10510 struct got_object_id_queue *commits, struct got_repository *repo)
10512 const struct got_error *err = NULL;
10513 struct got_object_qid *qid;
10514 struct got_histedit_list_entry *hle;
10515 static char msg[92];
10516 char *id_str;
10518 if (TAILQ_EMPTY(histedit_cmds))
10519 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10520 "histedit script contains no commands");
10521 if (STAILQ_EMPTY(commits))
10522 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10524 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10525 struct got_histedit_list_entry *hle2;
10526 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10527 if (hle == hle2)
10528 continue;
10529 if (got_object_id_cmp(hle->commit_id,
10530 hle2->commit_id) != 0)
10531 continue;
10532 err = got_object_id_str(&id_str, hle->commit_id);
10533 if (err)
10534 return err;
10535 snprintf(msg, sizeof(msg), "commit %s is listed "
10536 "more than once in histedit script", id_str);
10537 free(id_str);
10538 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10542 STAILQ_FOREACH(qid, commits, entry) {
10543 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10544 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10545 break;
10547 if (hle == NULL) {
10548 err = got_object_id_str(&id_str, &qid->id);
10549 if (err)
10550 return err;
10551 snprintf(msg, sizeof(msg),
10552 "commit %s missing from histedit script", id_str);
10553 free(id_str);
10554 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10558 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10559 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10560 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10561 "last commit in histedit script cannot be folded");
10563 return NULL;
10566 static const struct got_error *
10567 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10568 const char *path, struct got_object_id_queue *commits,
10569 struct got_repository *repo)
10571 const struct got_error *err = NULL;
10572 char *editor;
10573 FILE *f = NULL;
10575 err = get_editor(&editor);
10576 if (err)
10577 return err;
10579 if (spawn_editor(editor, path) == -1) {
10580 err = got_error_from_errno("failed spawning editor");
10581 goto done;
10584 f = fopen(path, "re");
10585 if (f == NULL) {
10586 err = got_error_from_errno("fopen");
10587 goto done;
10589 err = histedit_parse_list(histedit_cmds, f, repo);
10590 if (err)
10591 goto done;
10593 err = histedit_check_script(histedit_cmds, commits, repo);
10594 done:
10595 if (f && fclose(f) == EOF && err == NULL)
10596 err = got_error_from_errno("fclose");
10597 free(editor);
10598 return err;
10601 static const struct got_error *
10602 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10603 struct got_object_id_queue *, const char *, const char *,
10604 struct got_repository *);
10606 static const struct got_error *
10607 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10608 struct got_object_id_queue *commits, const char *branch_name,
10609 int edit_logmsg_only, int fold_only, int edit_only,
10610 struct got_repository *repo)
10612 const struct got_error *err;
10613 FILE *f = NULL;
10614 char *path = NULL;
10616 err = got_opentemp_named(&path, &f, "got-histedit");
10617 if (err)
10618 return err;
10620 err = write_cmd_list(f, branch_name, commits);
10621 if (err)
10622 goto done;
10624 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10625 fold_only, edit_only, repo);
10626 if (err)
10627 goto done;
10629 if (edit_logmsg_only || fold_only || edit_only) {
10630 rewind(f);
10631 err = histedit_parse_list(histedit_cmds, f, repo);
10632 } else {
10633 if (fclose(f) == EOF) {
10634 err = got_error_from_errno("fclose");
10635 goto done;
10637 f = NULL;
10638 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10639 if (err) {
10640 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10641 err->code != GOT_ERR_HISTEDIT_CMD)
10642 goto done;
10643 err = histedit_edit_list_retry(histedit_cmds, err,
10644 commits, path, branch_name, repo);
10647 done:
10648 if (f && fclose(f) == EOF && err == NULL)
10649 err = got_error_from_errno("fclose");
10650 if (path && unlink(path) != 0 && err == NULL)
10651 err = got_error_from_errno2("unlink", path);
10652 free(path);
10653 return err;
10656 static const struct got_error *
10657 histedit_save_list(struct got_histedit_list *histedit_cmds,
10658 struct got_worktree *worktree, struct got_repository *repo)
10660 const struct got_error *err = NULL;
10661 char *path = NULL;
10662 FILE *f = NULL;
10663 struct got_histedit_list_entry *hle;
10664 struct got_commit_object *commit = NULL;
10666 err = got_worktree_get_histedit_script_path(&path, worktree);
10667 if (err)
10668 return err;
10670 f = fopen(path, "we");
10671 if (f == NULL) {
10672 err = got_error_from_errno2("fopen", path);
10673 goto done;
10675 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10676 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10677 repo);
10678 if (err)
10679 break;
10681 if (hle->logmsg) {
10682 int n = fprintf(f, "%c %s\n",
10683 GOT_HISTEDIT_MESG, hle->logmsg);
10684 if (n < 0) {
10685 err = got_ferror(f, GOT_ERR_IO);
10686 break;
10690 done:
10691 if (f && fclose(f) == EOF && err == NULL)
10692 err = got_error_from_errno("fclose");
10693 free(path);
10694 if (commit)
10695 got_object_commit_close(commit);
10696 return err;
10699 void
10700 histedit_free_list(struct got_histedit_list *histedit_cmds)
10702 struct got_histedit_list_entry *hle;
10704 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10705 TAILQ_REMOVE(histedit_cmds, hle, entry);
10706 free(hle);
10710 static const struct got_error *
10711 histedit_load_list(struct got_histedit_list *histedit_cmds,
10712 const char *path, struct got_repository *repo)
10714 const struct got_error *err = NULL;
10715 FILE *f = NULL;
10717 f = fopen(path, "re");
10718 if (f == NULL) {
10719 err = got_error_from_errno2("fopen", path);
10720 goto done;
10723 err = histedit_parse_list(histedit_cmds, f, repo);
10724 done:
10725 if (f && fclose(f) == EOF && err == NULL)
10726 err = got_error_from_errno("fclose");
10727 return err;
10730 static const struct got_error *
10731 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10732 const struct got_error *edit_err, struct got_object_id_queue *commits,
10733 const char *path, const char *branch_name, struct got_repository *repo)
10735 const struct got_error *err = NULL, *prev_err = edit_err;
10736 int resp = ' ';
10738 while (resp != 'c' && resp != 'r' && resp != 'a') {
10739 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10740 "or (a)bort: ", getprogname(), prev_err->msg);
10741 resp = getchar();
10742 if (resp == '\n')
10743 resp = getchar();
10744 if (resp == 'c') {
10745 histedit_free_list(histedit_cmds);
10746 err = histedit_run_editor(histedit_cmds, path, commits,
10747 repo);
10748 if (err) {
10749 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10750 err->code != GOT_ERR_HISTEDIT_CMD)
10751 break;
10752 prev_err = err;
10753 resp = ' ';
10754 continue;
10756 break;
10757 } else if (resp == 'r') {
10758 histedit_free_list(histedit_cmds);
10759 err = histedit_edit_script(histedit_cmds,
10760 commits, branch_name, 0, 0, 0, repo);
10761 if (err) {
10762 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10763 err->code != GOT_ERR_HISTEDIT_CMD)
10764 break;
10765 prev_err = err;
10766 resp = ' ';
10767 continue;
10769 break;
10770 } else if (resp == 'a') {
10771 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10772 break;
10773 } else
10774 printf("invalid response '%c'\n", resp);
10777 return err;
10780 static const struct got_error *
10781 histedit_complete(struct got_worktree *worktree,
10782 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10783 struct got_reference *branch, struct got_repository *repo)
10785 printf("Switching work tree to %s\n",
10786 got_ref_get_symref_target(branch));
10787 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10788 branch, repo);
10791 static const struct got_error *
10792 show_histedit_progress(struct got_commit_object *commit,
10793 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10795 const struct got_error *err;
10796 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10798 err = got_object_id_str(&old_id_str, hle->commit_id);
10799 if (err)
10800 goto done;
10802 if (new_id) {
10803 err = got_object_id_str(&new_id_str, new_id);
10804 if (err)
10805 goto done;
10808 old_id_str[12] = '\0';
10809 if (new_id_str)
10810 new_id_str[12] = '\0';
10812 if (hle->logmsg) {
10813 logmsg = strdup(hle->logmsg);
10814 if (logmsg == NULL) {
10815 err = got_error_from_errno("strdup");
10816 goto done;
10818 trim_logmsg(logmsg, 42);
10819 } else {
10820 err = get_short_logmsg(&logmsg, 42, commit);
10821 if (err)
10822 goto done;
10825 switch (hle->cmd->code) {
10826 case GOT_HISTEDIT_PICK:
10827 case GOT_HISTEDIT_EDIT:
10828 printf("%s -> %s: %s\n", old_id_str,
10829 new_id_str ? new_id_str : "no-op change", logmsg);
10830 break;
10831 case GOT_HISTEDIT_DROP:
10832 case GOT_HISTEDIT_FOLD:
10833 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10834 logmsg);
10835 break;
10836 default:
10837 break;
10839 done:
10840 free(old_id_str);
10841 free(new_id_str);
10842 return err;
10845 static const struct got_error *
10846 histedit_commit(struct got_pathlist_head *merged_paths,
10847 struct got_worktree *worktree, struct got_fileindex *fileindex,
10848 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10849 struct got_repository *repo)
10851 const struct got_error *err;
10852 struct got_commit_object *commit;
10853 struct got_object_id *new_commit_id;
10855 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10856 && hle->logmsg == NULL) {
10857 err = histedit_edit_logmsg(hle, repo);
10858 if (err)
10859 return err;
10862 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10863 if (err)
10864 return err;
10866 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10867 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10868 hle->logmsg, repo);
10869 if (err) {
10870 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10871 goto done;
10872 err = show_histedit_progress(commit, hle, NULL);
10873 } else {
10874 err = show_histedit_progress(commit, hle, new_commit_id);
10875 free(new_commit_id);
10877 done:
10878 got_object_commit_close(commit);
10879 return err;
10882 static const struct got_error *
10883 histedit_skip_commit(struct got_histedit_list_entry *hle,
10884 struct got_worktree *worktree, struct got_repository *repo)
10886 const struct got_error *error;
10887 struct got_commit_object *commit;
10889 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10890 repo);
10891 if (error)
10892 return error;
10894 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10895 if (error)
10896 return error;
10898 error = show_histedit_progress(commit, hle, NULL);
10899 got_object_commit_close(commit);
10900 return error;
10903 static const struct got_error *
10904 check_local_changes(void *arg, unsigned char status,
10905 unsigned char staged_status, const char *path,
10906 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10907 struct got_object_id *commit_id, int dirfd, const char *de_name)
10909 int *have_local_changes = arg;
10911 switch (status) {
10912 case GOT_STATUS_ADD:
10913 case GOT_STATUS_DELETE:
10914 case GOT_STATUS_MODIFY:
10915 case GOT_STATUS_CONFLICT:
10916 *have_local_changes = 1;
10917 return got_error(GOT_ERR_CANCELLED);
10918 default:
10919 break;
10922 switch (staged_status) {
10923 case GOT_STATUS_ADD:
10924 case GOT_STATUS_DELETE:
10925 case GOT_STATUS_MODIFY:
10926 *have_local_changes = 1;
10927 return got_error(GOT_ERR_CANCELLED);
10928 default:
10929 break;
10932 return NULL;
10935 static const struct got_error *
10936 cmd_histedit(int argc, char *argv[])
10938 const struct got_error *error = NULL;
10939 struct got_worktree *worktree = NULL;
10940 struct got_fileindex *fileindex = NULL;
10941 struct got_repository *repo = NULL;
10942 char *cwd = NULL;
10943 struct got_reference *branch = NULL;
10944 struct got_reference *tmp_branch = NULL;
10945 struct got_object_id *resume_commit_id = NULL;
10946 struct got_object_id *base_commit_id = NULL;
10947 struct got_object_id *head_commit_id = NULL;
10948 struct got_commit_object *commit = NULL;
10949 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10950 struct got_update_progress_arg upa;
10951 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10952 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10953 int list_backups = 0, delete_backups = 0;
10954 const char *edit_script_path = NULL;
10955 struct got_object_id_queue commits;
10956 struct got_pathlist_head merged_paths;
10957 const struct got_object_id_queue *parent_ids;
10958 struct got_object_qid *pid;
10959 struct got_histedit_list histedit_cmds;
10960 struct got_histedit_list_entry *hle;
10961 int *pack_fds = NULL;
10963 STAILQ_INIT(&commits);
10964 TAILQ_INIT(&histedit_cmds);
10965 TAILQ_INIT(&merged_paths);
10966 memset(&upa, 0, sizeof(upa));
10968 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10969 switch (ch) {
10970 case 'a':
10971 abort_edit = 1;
10972 break;
10973 case 'c':
10974 continue_edit = 1;
10975 break;
10976 case 'e':
10977 edit_only = 1;
10978 break;
10979 case 'f':
10980 fold_only = 1;
10981 break;
10982 case 'F':
10983 edit_script_path = optarg;
10984 break;
10985 case 'm':
10986 edit_logmsg_only = 1;
10987 break;
10988 case 'l':
10989 list_backups = 1;
10990 break;
10991 case 'X':
10992 delete_backups = 1;
10993 break;
10994 default:
10995 usage_histedit();
10996 /* NOTREACHED */
11000 argc -= optind;
11001 argv += optind;
11003 #ifndef PROFILE
11004 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11005 "unveil", NULL) == -1)
11006 err(1, "pledge");
11007 #endif
11008 if (abort_edit && continue_edit)
11009 option_conflict('a', 'c');
11010 if (edit_script_path && edit_logmsg_only)
11011 option_conflict('F', 'm');
11012 if (abort_edit && edit_logmsg_only)
11013 option_conflict('a', 'm');
11014 if (continue_edit && edit_logmsg_only)
11015 option_conflict('c', 'm');
11016 if (abort_edit && fold_only)
11017 option_conflict('a', 'f');
11018 if (continue_edit && fold_only)
11019 option_conflict('c', 'f');
11020 if (fold_only && edit_logmsg_only)
11021 option_conflict('f', 'm');
11022 if (edit_script_path && fold_only)
11023 option_conflict('F', 'f');
11024 if (abort_edit && edit_only)
11025 option_conflict('a', 'e');
11026 if (continue_edit && edit_only)
11027 option_conflict('c', 'e');
11028 if (edit_only && edit_logmsg_only)
11029 option_conflict('e', 'm');
11030 if (edit_script_path && edit_only)
11031 option_conflict('F', 'e');
11032 if (list_backups) {
11033 if (abort_edit)
11034 option_conflict('l', 'a');
11035 if (continue_edit)
11036 option_conflict('l', 'c');
11037 if (edit_script_path)
11038 option_conflict('l', 'F');
11039 if (edit_logmsg_only)
11040 option_conflict('l', 'm');
11041 if (fold_only)
11042 option_conflict('l', 'f');
11043 if (edit_only)
11044 option_conflict('l', 'e');
11045 if (delete_backups)
11046 option_conflict('l', 'X');
11047 if (argc != 0 && argc != 1)
11048 usage_histedit();
11049 } else if (delete_backups) {
11050 if (abort_edit)
11051 option_conflict('X', 'a');
11052 if (continue_edit)
11053 option_conflict('X', 'c');
11054 if (edit_script_path)
11055 option_conflict('X', 'F');
11056 if (edit_logmsg_only)
11057 option_conflict('X', 'm');
11058 if (fold_only)
11059 option_conflict('X', 'f');
11060 if (edit_only)
11061 option_conflict('X', 'e');
11062 if (list_backups)
11063 option_conflict('X', 'l');
11064 if (argc != 0 && argc != 1)
11065 usage_histedit();
11066 } else if (argc != 0)
11067 usage_histedit();
11070 * This command cannot apply unveil(2) in all cases because the
11071 * user may choose to run an editor to edit the histedit script
11072 * and to edit individual commit log messages.
11073 * unveil(2) traverses exec(2); if an editor is used we have to
11074 * apply unveil after edit script and log messages have been written.
11075 * XXX TODO: Make use of unveil(2) where possible.
11078 cwd = getcwd(NULL, 0);
11079 if (cwd == NULL) {
11080 error = got_error_from_errno("getcwd");
11081 goto done;
11084 error = got_repo_pack_fds_open(&pack_fds);
11085 if (error != NULL)
11086 goto done;
11088 error = got_worktree_open(&worktree, cwd);
11089 if (error) {
11090 if (list_backups || delete_backups) {
11091 if (error->code != GOT_ERR_NOT_WORKTREE)
11092 goto done;
11093 } else {
11094 if (error->code == GOT_ERR_NOT_WORKTREE)
11095 error = wrap_not_worktree_error(error,
11096 "histedit", cwd);
11097 goto done;
11101 if (list_backups || delete_backups) {
11102 error = got_repo_open(&repo,
11103 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11104 NULL, pack_fds);
11105 if (error != NULL)
11106 goto done;
11107 error = apply_unveil(got_repo_get_path(repo), 0,
11108 worktree ? got_worktree_get_root_path(worktree) : NULL);
11109 if (error)
11110 goto done;
11111 error = process_backup_refs(
11112 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11113 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11114 goto done; /* nothing else to do */
11117 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11118 NULL, pack_fds);
11119 if (error != NULL)
11120 goto done;
11122 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11123 if (error)
11124 goto done;
11125 if (rebase_in_progress) {
11126 error = got_error(GOT_ERR_REBASING);
11127 goto done;
11130 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11131 repo);
11132 if (error)
11133 goto done;
11134 if (merge_in_progress) {
11135 error = got_error(GOT_ERR_MERGE_BUSY);
11136 goto done;
11139 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11140 if (error)
11141 goto done;
11143 if (edit_in_progress && edit_logmsg_only) {
11144 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11145 "histedit operation is in progress in this "
11146 "work tree and must be continued or aborted "
11147 "before the -m option can be used");
11148 goto done;
11150 if (edit_in_progress && fold_only) {
11151 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11152 "histedit operation is in progress in this "
11153 "work tree and must be continued or aborted "
11154 "before the -f option can be used");
11155 goto done;
11157 if (edit_in_progress && edit_only) {
11158 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11159 "histedit operation is in progress in this "
11160 "work tree and must be continued or aborted "
11161 "before the -e option can be used");
11162 goto done;
11165 if (edit_in_progress && abort_edit) {
11166 error = got_worktree_histedit_continue(&resume_commit_id,
11167 &tmp_branch, &branch, &base_commit_id, &fileindex,
11168 worktree, repo);
11169 if (error)
11170 goto done;
11171 printf("Switching work tree to %s\n",
11172 got_ref_get_symref_target(branch));
11173 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11174 branch, base_commit_id, abort_progress, &upa);
11175 if (error)
11176 goto done;
11177 printf("Histedit of %s aborted\n",
11178 got_ref_get_symref_target(branch));
11179 print_merge_progress_stats(&upa);
11180 goto done; /* nothing else to do */
11181 } else if (abort_edit) {
11182 error = got_error(GOT_ERR_NOT_HISTEDIT);
11183 goto done;
11186 if (continue_edit) {
11187 char *path;
11189 if (!edit_in_progress) {
11190 error = got_error(GOT_ERR_NOT_HISTEDIT);
11191 goto done;
11194 error = got_worktree_get_histedit_script_path(&path, worktree);
11195 if (error)
11196 goto done;
11198 error = histedit_load_list(&histedit_cmds, path, repo);
11199 free(path);
11200 if (error)
11201 goto done;
11203 error = got_worktree_histedit_continue(&resume_commit_id,
11204 &tmp_branch, &branch, &base_commit_id, &fileindex,
11205 worktree, repo);
11206 if (error)
11207 goto done;
11209 error = got_ref_resolve(&head_commit_id, repo, branch);
11210 if (error)
11211 goto done;
11213 error = got_object_open_as_commit(&commit, repo,
11214 head_commit_id);
11215 if (error)
11216 goto done;
11217 parent_ids = got_object_commit_get_parent_ids(commit);
11218 pid = STAILQ_FIRST(parent_ids);
11219 if (pid == NULL) {
11220 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11221 goto done;
11223 error = collect_commits(&commits, head_commit_id, &pid->id,
11224 base_commit_id, got_worktree_get_path_prefix(worktree),
11225 GOT_ERR_HISTEDIT_PATH, repo);
11226 got_object_commit_close(commit);
11227 commit = NULL;
11228 if (error)
11229 goto done;
11230 } else {
11231 if (edit_in_progress) {
11232 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11233 goto done;
11236 error = got_ref_open(&branch, repo,
11237 got_worktree_get_head_ref_name(worktree), 0);
11238 if (error != NULL)
11239 goto done;
11241 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11242 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11243 "will not edit commit history of a branch outside "
11244 "the \"refs/heads/\" reference namespace");
11245 goto done;
11248 error = got_ref_resolve(&head_commit_id, repo, branch);
11249 got_ref_close(branch);
11250 branch = NULL;
11251 if (error)
11252 goto done;
11254 error = got_object_open_as_commit(&commit, repo,
11255 head_commit_id);
11256 if (error)
11257 goto done;
11258 parent_ids = got_object_commit_get_parent_ids(commit);
11259 pid = STAILQ_FIRST(parent_ids);
11260 if (pid == NULL) {
11261 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11262 goto done;
11264 error = collect_commits(&commits, head_commit_id, &pid->id,
11265 got_worktree_get_base_commit_id(worktree),
11266 got_worktree_get_path_prefix(worktree),
11267 GOT_ERR_HISTEDIT_PATH, repo);
11268 got_object_commit_close(commit);
11269 commit = NULL;
11270 if (error)
11271 goto done;
11273 if (STAILQ_EMPTY(&commits)) {
11274 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11275 goto done;
11278 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11279 &base_commit_id, &fileindex, worktree, repo);
11280 if (error)
11281 goto done;
11283 if (edit_script_path) {
11284 error = histedit_load_list(&histedit_cmds,
11285 edit_script_path, repo);
11286 if (error) {
11287 got_worktree_histedit_abort(worktree, fileindex,
11288 repo, branch, base_commit_id,
11289 abort_progress, &upa);
11290 print_merge_progress_stats(&upa);
11291 goto done;
11293 } else {
11294 const char *branch_name;
11295 branch_name = got_ref_get_symref_target(branch);
11296 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11297 branch_name += 11;
11298 error = histedit_edit_script(&histedit_cmds, &commits,
11299 branch_name, edit_logmsg_only, fold_only,
11300 edit_only, repo);
11301 if (error) {
11302 got_worktree_histedit_abort(worktree, fileindex,
11303 repo, branch, base_commit_id,
11304 abort_progress, &upa);
11305 print_merge_progress_stats(&upa);
11306 goto done;
11311 error = histedit_save_list(&histedit_cmds, worktree,
11312 repo);
11313 if (error) {
11314 got_worktree_histedit_abort(worktree, fileindex,
11315 repo, branch, base_commit_id,
11316 abort_progress, &upa);
11317 print_merge_progress_stats(&upa);
11318 goto done;
11323 error = histedit_check_script(&histedit_cmds, &commits, repo);
11324 if (error)
11325 goto done;
11327 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11328 if (resume_commit_id) {
11329 if (got_object_id_cmp(hle->commit_id,
11330 resume_commit_id) != 0)
11331 continue;
11333 resume_commit_id = NULL;
11334 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11335 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11336 error = histedit_skip_commit(hle, worktree,
11337 repo);
11338 if (error)
11339 goto done;
11340 } else {
11341 struct got_pathlist_head paths;
11342 int have_changes = 0;
11344 TAILQ_INIT(&paths);
11345 error = got_pathlist_append(&paths, "", NULL);
11346 if (error)
11347 goto done;
11348 error = got_worktree_status(worktree, &paths,
11349 repo, 0, check_local_changes, &have_changes,
11350 check_cancelled, NULL);
11351 got_pathlist_free(&paths);
11352 if (error) {
11353 if (error->code != GOT_ERR_CANCELLED)
11354 goto done;
11355 if (sigint_received || sigpipe_received)
11356 goto done;
11358 if (have_changes) {
11359 error = histedit_commit(NULL, worktree,
11360 fileindex, tmp_branch, hle, repo);
11361 if (error)
11362 goto done;
11363 } else {
11364 error = got_object_open_as_commit(
11365 &commit, repo, hle->commit_id);
11366 if (error)
11367 goto done;
11368 error = show_histedit_progress(commit,
11369 hle, NULL);
11370 got_object_commit_close(commit);
11371 commit = NULL;
11372 if (error)
11373 goto done;
11376 continue;
11379 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11380 error = histedit_skip_commit(hle, worktree, repo);
11381 if (error)
11382 goto done;
11383 continue;
11386 error = got_object_open_as_commit(&commit, repo,
11387 hle->commit_id);
11388 if (error)
11389 goto done;
11390 parent_ids = got_object_commit_get_parent_ids(commit);
11391 pid = STAILQ_FIRST(parent_ids);
11393 error = got_worktree_histedit_merge_files(&merged_paths,
11394 worktree, fileindex, &pid->id, hle->commit_id, repo,
11395 update_progress, &upa, check_cancelled, NULL);
11396 if (error)
11397 goto done;
11398 got_object_commit_close(commit);
11399 commit = NULL;
11401 print_merge_progress_stats(&upa);
11402 if (upa.conflicts > 0 || upa.missing > 0 ||
11403 upa.not_deleted > 0 || upa.unversioned > 0) {
11404 if (upa.conflicts > 0) {
11405 error = show_rebase_merge_conflict(
11406 hle->commit_id, repo);
11407 if (error)
11408 goto done;
11410 got_worktree_rebase_pathlist_free(&merged_paths);
11411 break;
11414 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11415 char *id_str;
11416 error = got_object_id_str(&id_str, hle->commit_id);
11417 if (error)
11418 goto done;
11419 printf("Stopping histedit for amending commit %s\n",
11420 id_str);
11421 free(id_str);
11422 got_worktree_rebase_pathlist_free(&merged_paths);
11423 error = got_worktree_histedit_postpone(worktree,
11424 fileindex);
11425 goto done;
11428 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11429 error = histedit_skip_commit(hle, worktree, repo);
11430 if (error)
11431 goto done;
11432 continue;
11435 error = histedit_commit(&merged_paths, worktree, fileindex,
11436 tmp_branch, hle, repo);
11437 got_worktree_rebase_pathlist_free(&merged_paths);
11438 if (error)
11439 goto done;
11442 if (upa.conflicts > 0 || upa.missing > 0 ||
11443 upa.not_deleted > 0 || upa.unversioned > 0) {
11444 error = got_worktree_histedit_postpone(worktree, fileindex);
11445 if (error)
11446 goto done;
11447 if (upa.conflicts > 0 && upa.missing == 0 &&
11448 upa.not_deleted == 0 && upa.unversioned == 0) {
11449 error = got_error_msg(GOT_ERR_CONFLICTS,
11450 "conflicts must be resolved before histedit "
11451 "can continue");
11452 } else if (upa.conflicts > 0) {
11453 error = got_error_msg(GOT_ERR_CONFLICTS,
11454 "conflicts must be resolved before histedit "
11455 "can continue; changes destined for some "
11456 "files were not yet merged and should be "
11457 "merged manually if required before the "
11458 "histedit operation is continued");
11459 } else {
11460 error = got_error_msg(GOT_ERR_CONFLICTS,
11461 "changes destined for some files were not "
11462 "yet merged and should be merged manually "
11463 "if required before the histedit operation "
11464 "is continued");
11466 } else
11467 error = histedit_complete(worktree, fileindex, tmp_branch,
11468 branch, repo);
11469 done:
11470 got_object_id_queue_free(&commits);
11471 histedit_free_list(&histedit_cmds);
11472 free(head_commit_id);
11473 free(base_commit_id);
11474 free(resume_commit_id);
11475 if (commit)
11476 got_object_commit_close(commit);
11477 if (branch)
11478 got_ref_close(branch);
11479 if (tmp_branch)
11480 got_ref_close(tmp_branch);
11481 if (worktree)
11482 got_worktree_close(worktree);
11483 if (repo) {
11484 const struct got_error *close_err = got_repo_close(repo);
11485 if (error == NULL)
11486 error = close_err;
11488 if (pack_fds) {
11489 const struct got_error *pack_err =
11490 got_repo_pack_fds_close(pack_fds);
11491 if (error == NULL)
11492 error = pack_err;
11494 return error;
11497 __dead static void
11498 usage_integrate(void)
11500 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11501 exit(1);
11504 static const struct got_error *
11505 cmd_integrate(int argc, char *argv[])
11507 const struct got_error *error = NULL;
11508 struct got_repository *repo = NULL;
11509 struct got_worktree *worktree = NULL;
11510 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11511 const char *branch_arg = NULL;
11512 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11513 struct got_fileindex *fileindex = NULL;
11514 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11515 int ch;
11516 struct got_update_progress_arg upa;
11517 int *pack_fds = NULL;
11519 while ((ch = getopt(argc, argv, "")) != -1) {
11520 switch (ch) {
11521 default:
11522 usage_integrate();
11523 /* NOTREACHED */
11527 argc -= optind;
11528 argv += optind;
11530 if (argc != 1)
11531 usage_integrate();
11532 branch_arg = argv[0];
11533 #ifndef PROFILE
11534 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11535 "unveil", NULL) == -1)
11536 err(1, "pledge");
11537 #endif
11538 cwd = getcwd(NULL, 0);
11539 if (cwd == NULL) {
11540 error = got_error_from_errno("getcwd");
11541 goto done;
11544 error = got_repo_pack_fds_open(&pack_fds);
11545 if (error != NULL)
11546 goto done;
11548 error = got_worktree_open(&worktree, cwd);
11549 if (error) {
11550 if (error->code == GOT_ERR_NOT_WORKTREE)
11551 error = wrap_not_worktree_error(error, "integrate",
11552 cwd);
11553 goto done;
11556 error = check_rebase_or_histedit_in_progress(worktree);
11557 if (error)
11558 goto done;
11560 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11561 NULL, pack_fds);
11562 if (error != NULL)
11563 goto done;
11565 error = apply_unveil(got_repo_get_path(repo), 0,
11566 got_worktree_get_root_path(worktree));
11567 if (error)
11568 goto done;
11570 error = check_merge_in_progress(worktree, repo);
11571 if (error)
11572 goto done;
11574 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11575 error = got_error_from_errno("asprintf");
11576 goto done;
11579 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11580 &base_branch_ref, worktree, refname, repo);
11581 if (error)
11582 goto done;
11584 refname = strdup(got_ref_get_name(branch_ref));
11585 if (refname == NULL) {
11586 error = got_error_from_errno("strdup");
11587 got_worktree_integrate_abort(worktree, fileindex, repo,
11588 branch_ref, base_branch_ref);
11589 goto done;
11591 base_refname = strdup(got_ref_get_name(base_branch_ref));
11592 if (base_refname == NULL) {
11593 error = got_error_from_errno("strdup");
11594 got_worktree_integrate_abort(worktree, fileindex, repo,
11595 branch_ref, base_branch_ref);
11596 goto done;
11599 error = got_ref_resolve(&commit_id, repo, branch_ref);
11600 if (error)
11601 goto done;
11603 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11604 if (error)
11605 goto done;
11607 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11608 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11609 "specified branch has already been integrated");
11610 got_worktree_integrate_abort(worktree, fileindex, repo,
11611 branch_ref, base_branch_ref);
11612 goto done;
11615 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11616 if (error) {
11617 if (error->code == GOT_ERR_ANCESTRY)
11618 error = got_error(GOT_ERR_REBASE_REQUIRED);
11619 got_worktree_integrate_abort(worktree, fileindex, repo,
11620 branch_ref, base_branch_ref);
11621 goto done;
11624 memset(&upa, 0, sizeof(upa));
11625 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11626 branch_ref, base_branch_ref, update_progress, &upa,
11627 check_cancelled, NULL);
11628 if (error)
11629 goto done;
11631 printf("Integrated %s into %s\n", refname, base_refname);
11632 print_update_progress_stats(&upa);
11633 done:
11634 if (repo) {
11635 const struct got_error *close_err = got_repo_close(repo);
11636 if (error == NULL)
11637 error = close_err;
11639 if (worktree)
11640 got_worktree_close(worktree);
11641 if (pack_fds) {
11642 const struct got_error *pack_err =
11643 got_repo_pack_fds_close(pack_fds);
11644 if (error == NULL)
11645 error = pack_err;
11647 free(cwd);
11648 free(base_commit_id);
11649 free(commit_id);
11650 free(refname);
11651 free(base_refname);
11652 return error;
11655 __dead static void
11656 usage_merge(void)
11658 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11659 getprogname());
11660 exit(1);
11663 static const struct got_error *
11664 cmd_merge(int argc, char *argv[])
11666 const struct got_error *error = NULL;
11667 struct got_worktree *worktree = NULL;
11668 struct got_repository *repo = NULL;
11669 struct got_fileindex *fileindex = NULL;
11670 char *cwd = NULL, *id_str = NULL, *author = NULL;
11671 struct got_reference *branch = NULL, *wt_branch = NULL;
11672 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11673 struct got_object_id *wt_branch_tip = NULL;
11674 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11675 int interrupt_merge = 0;
11676 struct got_update_progress_arg upa;
11677 struct got_object_id *merge_commit_id = NULL;
11678 char *branch_name = NULL;
11679 int *pack_fds = NULL;
11681 memset(&upa, 0, sizeof(upa));
11683 while ((ch = getopt(argc, argv, "acn")) != -1) {
11684 switch (ch) {
11685 case 'a':
11686 abort_merge = 1;
11687 break;
11688 case 'c':
11689 continue_merge = 1;
11690 break;
11691 case 'n':
11692 interrupt_merge = 1;
11693 break;
11694 default:
11695 usage_rebase();
11696 /* NOTREACHED */
11700 argc -= optind;
11701 argv += optind;
11703 #ifndef PROFILE
11704 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11705 "unveil", NULL) == -1)
11706 err(1, "pledge");
11707 #endif
11709 if (abort_merge && continue_merge)
11710 option_conflict('a', 'c');
11711 if (abort_merge || continue_merge) {
11712 if (argc != 0)
11713 usage_merge();
11714 } else if (argc != 1)
11715 usage_merge();
11717 cwd = getcwd(NULL, 0);
11718 if (cwd == NULL) {
11719 error = got_error_from_errno("getcwd");
11720 goto done;
11723 error = got_repo_pack_fds_open(&pack_fds);
11724 if (error != NULL)
11725 goto done;
11727 error = got_worktree_open(&worktree, cwd);
11728 if (error) {
11729 if (error->code == GOT_ERR_NOT_WORKTREE)
11730 error = wrap_not_worktree_error(error,
11731 "merge", cwd);
11732 goto done;
11735 error = got_repo_open(&repo,
11736 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11737 pack_fds);
11738 if (error != NULL)
11739 goto done;
11741 error = apply_unveil(got_repo_get_path(repo), 0,
11742 worktree ? got_worktree_get_root_path(worktree) : NULL);
11743 if (error)
11744 goto done;
11746 error = check_rebase_or_histedit_in_progress(worktree);
11747 if (error)
11748 goto done;
11750 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11751 repo);
11752 if (error)
11753 goto done;
11755 if (abort_merge) {
11756 if (!merge_in_progress) {
11757 error = got_error(GOT_ERR_NOT_MERGING);
11758 goto done;
11760 error = got_worktree_merge_continue(&branch_name,
11761 &branch_tip, &fileindex, worktree, repo);
11762 if (error)
11763 goto done;
11764 error = got_worktree_merge_abort(worktree, fileindex, repo,
11765 abort_progress, &upa);
11766 if (error)
11767 goto done;
11768 printf("Merge of %s aborted\n", branch_name);
11769 goto done; /* nothing else to do */
11772 error = get_author(&author, repo, worktree);
11773 if (error)
11774 goto done;
11776 if (continue_merge) {
11777 if (!merge_in_progress) {
11778 error = got_error(GOT_ERR_NOT_MERGING);
11779 goto done;
11781 error = got_worktree_merge_continue(&branch_name,
11782 &branch_tip, &fileindex, worktree, repo);
11783 if (error)
11784 goto done;
11785 } else {
11786 error = got_ref_open(&branch, repo, argv[0], 0);
11787 if (error != NULL)
11788 goto done;
11789 branch_name = strdup(got_ref_get_name(branch));
11790 if (branch_name == NULL) {
11791 error = got_error_from_errno("strdup");
11792 goto done;
11794 error = got_ref_resolve(&branch_tip, repo, branch);
11795 if (error)
11796 goto done;
11799 error = got_ref_open(&wt_branch, repo,
11800 got_worktree_get_head_ref_name(worktree), 0);
11801 if (error)
11802 goto done;
11803 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11804 if (error)
11805 goto done;
11806 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11807 wt_branch_tip, branch_tip, 0, repo,
11808 check_cancelled, NULL);
11809 if (error && error->code != GOT_ERR_ANCESTRY)
11810 goto done;
11812 if (!continue_merge) {
11813 error = check_path_prefix(wt_branch_tip, branch_tip,
11814 got_worktree_get_path_prefix(worktree),
11815 GOT_ERR_MERGE_PATH, repo);
11816 if (error)
11817 goto done;
11818 if (yca_id) {
11819 error = check_same_branch(wt_branch_tip, branch,
11820 yca_id, repo);
11821 if (error) {
11822 if (error->code != GOT_ERR_ANCESTRY)
11823 goto done;
11824 error = NULL;
11825 } else {
11826 static char msg[512];
11827 snprintf(msg, sizeof(msg),
11828 "cannot create a merge commit because "
11829 "%s is based on %s; %s can be integrated "
11830 "with 'got integrate' instead", branch_name,
11831 got_worktree_get_head_ref_name(worktree),
11832 branch_name);
11833 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11834 goto done;
11837 error = got_worktree_merge_prepare(&fileindex, worktree,
11838 branch, repo);
11839 if (error)
11840 goto done;
11842 error = got_worktree_merge_branch(worktree, fileindex,
11843 yca_id, branch_tip, repo, update_progress, &upa,
11844 check_cancelled, NULL);
11845 if (error)
11846 goto done;
11847 print_merge_progress_stats(&upa);
11848 if (!upa.did_something) {
11849 error = got_worktree_merge_abort(worktree, fileindex,
11850 repo, abort_progress, &upa);
11851 if (error)
11852 goto done;
11853 printf("Already up-to-date\n");
11854 goto done;
11858 if (interrupt_merge) {
11859 error = got_worktree_merge_postpone(worktree, fileindex);
11860 if (error)
11861 goto done;
11862 printf("Merge of %s interrupted on request\n", branch_name);
11863 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11864 upa.not_deleted > 0 || upa.unversioned > 0) {
11865 error = got_worktree_merge_postpone(worktree, fileindex);
11866 if (error)
11867 goto done;
11868 if (upa.conflicts > 0 && upa.missing == 0 &&
11869 upa.not_deleted == 0 && upa.unversioned == 0) {
11870 error = got_error_msg(GOT_ERR_CONFLICTS,
11871 "conflicts must be resolved before merging "
11872 "can continue");
11873 } else if (upa.conflicts > 0) {
11874 error = got_error_msg(GOT_ERR_CONFLICTS,
11875 "conflicts must be resolved before merging "
11876 "can continue; changes destined for some "
11877 "files were not yet merged and "
11878 "should be merged manually if required before the "
11879 "merge operation is continued");
11880 } else {
11881 error = got_error_msg(GOT_ERR_CONFLICTS,
11882 "changes destined for some "
11883 "files were not yet merged and should be "
11884 "merged manually if required before the "
11885 "merge operation is continued");
11887 goto done;
11888 } else {
11889 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11890 fileindex, author, NULL, 1, branch_tip, branch_name,
11891 repo, continue_merge ? print_status : NULL, NULL);
11892 if (error)
11893 goto done;
11894 error = got_worktree_merge_complete(worktree, fileindex, repo);
11895 if (error)
11896 goto done;
11897 error = got_object_id_str(&id_str, merge_commit_id);
11898 if (error)
11899 goto done;
11900 printf("Merged %s into %s: %s\n", branch_name,
11901 got_worktree_get_head_ref_name(worktree),
11902 id_str);
11905 done:
11906 free(id_str);
11907 free(merge_commit_id);
11908 free(author);
11909 free(branch_tip);
11910 free(branch_name);
11911 free(yca_id);
11912 if (branch)
11913 got_ref_close(branch);
11914 if (wt_branch)
11915 got_ref_close(wt_branch);
11916 if (worktree)
11917 got_worktree_close(worktree);
11918 if (repo) {
11919 const struct got_error *close_err = got_repo_close(repo);
11920 if (error == NULL)
11921 error = close_err;
11923 if (pack_fds) {
11924 const struct got_error *pack_err =
11925 got_repo_pack_fds_close(pack_fds);
11926 if (error == NULL)
11927 error = pack_err;
11929 return error;
11932 __dead static void
11933 usage_stage(void)
11935 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11936 "[-S] [file-path ...]\n",
11937 getprogname());
11938 exit(1);
11941 static const struct got_error *
11942 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11943 const char *path, struct got_object_id *blob_id,
11944 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11945 int dirfd, const char *de_name)
11947 const struct got_error *err = NULL;
11948 char *id_str = NULL;
11950 if (staged_status != GOT_STATUS_ADD &&
11951 staged_status != GOT_STATUS_MODIFY &&
11952 staged_status != GOT_STATUS_DELETE)
11953 return NULL;
11955 if (staged_status == GOT_STATUS_ADD ||
11956 staged_status == GOT_STATUS_MODIFY)
11957 err = got_object_id_str(&id_str, staged_blob_id);
11958 else
11959 err = got_object_id_str(&id_str, blob_id);
11960 if (err)
11961 return err;
11963 printf("%s %c %s\n", id_str, staged_status, path);
11964 free(id_str);
11965 return NULL;
11968 static const struct got_error *
11969 cmd_stage(int argc, char *argv[])
11971 const struct got_error *error = NULL;
11972 struct got_repository *repo = NULL;
11973 struct got_worktree *worktree = NULL;
11974 char *cwd = NULL;
11975 struct got_pathlist_head paths;
11976 struct got_pathlist_entry *pe;
11977 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11978 FILE *patch_script_file = NULL;
11979 const char *patch_script_path = NULL;
11980 struct choose_patch_arg cpa;
11981 int *pack_fds = NULL;
11983 TAILQ_INIT(&paths);
11985 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11986 switch (ch) {
11987 case 'l':
11988 list_stage = 1;
11989 break;
11990 case 'p':
11991 pflag = 1;
11992 break;
11993 case 'F':
11994 patch_script_path = optarg;
11995 break;
11996 case 'S':
11997 allow_bad_symlinks = 1;
11998 break;
11999 default:
12000 usage_stage();
12001 /* NOTREACHED */
12005 argc -= optind;
12006 argv += optind;
12008 #ifndef PROFILE
12009 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12010 "unveil", NULL) == -1)
12011 err(1, "pledge");
12012 #endif
12013 if (list_stage && (pflag || patch_script_path))
12014 errx(1, "-l option cannot be used with other options");
12015 if (patch_script_path && !pflag)
12016 errx(1, "-F option can only be used together with -p option");
12018 cwd = getcwd(NULL, 0);
12019 if (cwd == NULL) {
12020 error = got_error_from_errno("getcwd");
12021 goto done;
12024 error = got_repo_pack_fds_open(&pack_fds);
12025 if (error != NULL)
12026 goto done;
12028 error = got_worktree_open(&worktree, cwd);
12029 if (error) {
12030 if (error->code == GOT_ERR_NOT_WORKTREE)
12031 error = wrap_not_worktree_error(error, "stage", cwd);
12032 goto done;
12035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12036 NULL, pack_fds);
12037 if (error != NULL)
12038 goto done;
12040 if (patch_script_path) {
12041 patch_script_file = fopen(patch_script_path, "re");
12042 if (patch_script_file == NULL) {
12043 error = got_error_from_errno2("fopen",
12044 patch_script_path);
12045 goto done;
12048 error = apply_unveil(got_repo_get_path(repo), 0,
12049 got_worktree_get_root_path(worktree));
12050 if (error)
12051 goto done;
12053 error = check_merge_in_progress(worktree, repo);
12054 if (error)
12055 goto done;
12057 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12058 if (error)
12059 goto done;
12061 if (list_stage)
12062 error = got_worktree_status(worktree, &paths, repo, 0,
12063 print_stage, NULL, check_cancelled, NULL);
12064 else {
12065 cpa.patch_script_file = patch_script_file;
12066 cpa.action = "stage";
12067 error = got_worktree_stage(worktree, &paths,
12068 pflag ? NULL : print_status, NULL,
12069 pflag ? choose_patch : NULL, &cpa,
12070 allow_bad_symlinks, repo);
12072 done:
12073 if (patch_script_file && fclose(patch_script_file) == EOF &&
12074 error == NULL)
12075 error = got_error_from_errno2("fclose", patch_script_path);
12076 if (repo) {
12077 const struct got_error *close_err = got_repo_close(repo);
12078 if (error == NULL)
12079 error = close_err;
12081 if (worktree)
12082 got_worktree_close(worktree);
12083 if (pack_fds) {
12084 const struct got_error *pack_err =
12085 got_repo_pack_fds_close(pack_fds);
12086 if (error == NULL)
12087 error = pack_err;
12089 TAILQ_FOREACH(pe, &paths, entry)
12090 free((char *)pe->path);
12091 got_pathlist_free(&paths);
12092 free(cwd);
12093 return error;
12096 __dead static void
12097 usage_unstage(void)
12099 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12100 "[file-path ...]\n",
12101 getprogname());
12102 exit(1);
12106 static const struct got_error *
12107 cmd_unstage(int argc, char *argv[])
12109 const struct got_error *error = NULL;
12110 struct got_repository *repo = NULL;
12111 struct got_worktree *worktree = NULL;
12112 char *cwd = NULL;
12113 struct got_pathlist_head paths;
12114 struct got_pathlist_entry *pe;
12115 int ch, pflag = 0;
12116 struct got_update_progress_arg upa;
12117 FILE *patch_script_file = NULL;
12118 const char *patch_script_path = NULL;
12119 struct choose_patch_arg cpa;
12120 int *pack_fds = NULL;
12122 TAILQ_INIT(&paths);
12124 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12125 switch (ch) {
12126 case 'p':
12127 pflag = 1;
12128 break;
12129 case 'F':
12130 patch_script_path = optarg;
12131 break;
12132 default:
12133 usage_unstage();
12134 /* NOTREACHED */
12138 argc -= optind;
12139 argv += optind;
12141 #ifndef PROFILE
12142 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12143 "unveil", NULL) == -1)
12144 err(1, "pledge");
12145 #endif
12146 if (patch_script_path && !pflag)
12147 errx(1, "-F option can only be used together with -p option");
12149 cwd = getcwd(NULL, 0);
12150 if (cwd == NULL) {
12151 error = got_error_from_errno("getcwd");
12152 goto done;
12155 error = got_repo_pack_fds_open(&pack_fds);
12156 if (error != NULL)
12157 goto done;
12159 error = got_worktree_open(&worktree, cwd);
12160 if (error) {
12161 if (error->code == GOT_ERR_NOT_WORKTREE)
12162 error = wrap_not_worktree_error(error, "unstage", cwd);
12163 goto done;
12166 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12167 NULL, pack_fds);
12168 if (error != NULL)
12169 goto done;
12171 if (patch_script_path) {
12172 patch_script_file = fopen(patch_script_path, "re");
12173 if (patch_script_file == NULL) {
12174 error = got_error_from_errno2("fopen",
12175 patch_script_path);
12176 goto done;
12180 error = apply_unveil(got_repo_get_path(repo), 0,
12181 got_worktree_get_root_path(worktree));
12182 if (error)
12183 goto done;
12185 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12186 if (error)
12187 goto done;
12189 cpa.patch_script_file = patch_script_file;
12190 cpa.action = "unstage";
12191 memset(&upa, 0, sizeof(upa));
12192 error = got_worktree_unstage(worktree, &paths, update_progress,
12193 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12194 if (!error)
12195 print_merge_progress_stats(&upa);
12196 done:
12197 if (patch_script_file && fclose(patch_script_file) == EOF &&
12198 error == NULL)
12199 error = got_error_from_errno2("fclose", patch_script_path);
12200 if (repo) {
12201 const struct got_error *close_err = got_repo_close(repo);
12202 if (error == NULL)
12203 error = close_err;
12205 if (worktree)
12206 got_worktree_close(worktree);
12207 if (pack_fds) {
12208 const struct got_error *pack_err =
12209 got_repo_pack_fds_close(pack_fds);
12210 if (error == NULL)
12211 error = pack_err;
12213 TAILQ_FOREACH(pe, &paths, entry)
12214 free((char *)pe->path);
12215 got_pathlist_free(&paths);
12216 free(cwd);
12217 return error;
12220 __dead static void
12221 usage_cat(void)
12223 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12224 "arg1 [arg2 ...]\n", getprogname());
12225 exit(1);
12228 static const struct got_error *
12229 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12231 const struct got_error *err;
12232 struct got_blob_object *blob;
12234 err = got_object_open_as_blob(&blob, repo, id, 8192);
12235 if (err)
12236 return err;
12238 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12239 got_object_blob_close(blob);
12240 return err;
12243 static const struct got_error *
12244 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12246 const struct got_error *err;
12247 struct got_tree_object *tree;
12248 int nentries, i;
12250 err = got_object_open_as_tree(&tree, repo, id);
12251 if (err)
12252 return err;
12254 nentries = got_object_tree_get_nentries(tree);
12255 for (i = 0; i < nentries; i++) {
12256 struct got_tree_entry *te;
12257 char *id_str;
12258 if (sigint_received || sigpipe_received)
12259 break;
12260 te = got_object_tree_get_entry(tree, i);
12261 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12262 if (err)
12263 break;
12264 fprintf(outfile, "%s %.7o %s\n", id_str,
12265 got_tree_entry_get_mode(te),
12266 got_tree_entry_get_name(te));
12267 free(id_str);
12270 got_object_tree_close(tree);
12271 return err;
12274 static void
12275 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12277 long long h, m;
12278 char sign = '+';
12280 if (gmtoff < 0) {
12281 sign = '-';
12282 gmtoff = -gmtoff;
12285 h = (long long)gmtoff / 3600;
12286 m = ((long long)gmtoff - h*3600) / 60;
12287 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12290 static const struct got_error *
12291 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12293 const struct got_error *err;
12294 struct got_commit_object *commit;
12295 const struct got_object_id_queue *parent_ids;
12296 struct got_object_qid *pid;
12297 char *id_str = NULL;
12298 const char *logmsg = NULL;
12299 char gmtoff[6];
12301 err = got_object_open_as_commit(&commit, repo, id);
12302 if (err)
12303 return err;
12305 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12306 if (err)
12307 goto done;
12309 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12310 parent_ids = got_object_commit_get_parent_ids(commit);
12311 fprintf(outfile, "numparents %d\n",
12312 got_object_commit_get_nparents(commit));
12313 STAILQ_FOREACH(pid, parent_ids, entry) {
12314 char *pid_str;
12315 err = got_object_id_str(&pid_str, &pid->id);
12316 if (err)
12317 goto done;
12318 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12319 free(pid_str);
12321 format_gmtoff(gmtoff, sizeof(gmtoff),
12322 got_object_commit_get_author_gmtoff(commit));
12323 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12324 got_object_commit_get_author(commit),
12325 (long long)got_object_commit_get_author_time(commit),
12326 gmtoff);
12328 format_gmtoff(gmtoff, sizeof(gmtoff),
12329 got_object_commit_get_committer_gmtoff(commit));
12330 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12331 got_object_commit_get_author(commit),
12332 (long long)got_object_commit_get_committer_time(commit),
12333 gmtoff);
12335 logmsg = got_object_commit_get_logmsg_raw(commit);
12336 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12337 fprintf(outfile, "%s", logmsg);
12338 done:
12339 free(id_str);
12340 got_object_commit_close(commit);
12341 return err;
12344 static const struct got_error *
12345 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12347 const struct got_error *err;
12348 struct got_tag_object *tag;
12349 char *id_str = NULL;
12350 const char *tagmsg = NULL;
12351 char gmtoff[6];
12353 err = got_object_open_as_tag(&tag, repo, id);
12354 if (err)
12355 return err;
12357 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12358 if (err)
12359 goto done;
12361 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12363 switch (got_object_tag_get_object_type(tag)) {
12364 case GOT_OBJ_TYPE_BLOB:
12365 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12366 GOT_OBJ_LABEL_BLOB);
12367 break;
12368 case GOT_OBJ_TYPE_TREE:
12369 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12370 GOT_OBJ_LABEL_TREE);
12371 break;
12372 case GOT_OBJ_TYPE_COMMIT:
12373 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12374 GOT_OBJ_LABEL_COMMIT);
12375 break;
12376 case GOT_OBJ_TYPE_TAG:
12377 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12378 GOT_OBJ_LABEL_TAG);
12379 break;
12380 default:
12381 break;
12384 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12385 got_object_tag_get_name(tag));
12387 format_gmtoff(gmtoff, sizeof(gmtoff),
12388 got_object_tag_get_tagger_gmtoff(tag));
12389 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12390 got_object_tag_get_tagger(tag),
12391 (long long)got_object_tag_get_tagger_time(tag),
12392 gmtoff);
12394 tagmsg = got_object_tag_get_message(tag);
12395 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12396 fprintf(outfile, "%s", tagmsg);
12397 done:
12398 free(id_str);
12399 got_object_tag_close(tag);
12400 return err;
12403 static const struct got_error *
12404 cmd_cat(int argc, char *argv[])
12406 const struct got_error *error;
12407 struct got_repository *repo = NULL;
12408 struct got_worktree *worktree = NULL;
12409 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12410 const char *commit_id_str = NULL;
12411 struct got_object_id *id = NULL, *commit_id = NULL;
12412 struct got_commit_object *commit = NULL;
12413 int ch, obj_type, i, force_path = 0;
12414 struct got_reflist_head refs;
12415 int *pack_fds = NULL;
12417 TAILQ_INIT(&refs);
12419 #ifndef PROFILE
12420 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12421 NULL) == -1)
12422 err(1, "pledge");
12423 #endif
12425 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12426 switch (ch) {
12427 case 'c':
12428 commit_id_str = optarg;
12429 break;
12430 case 'r':
12431 repo_path = realpath(optarg, NULL);
12432 if (repo_path == NULL)
12433 return got_error_from_errno2("realpath",
12434 optarg);
12435 got_path_strip_trailing_slashes(repo_path);
12436 break;
12437 case 'P':
12438 force_path = 1;
12439 break;
12440 default:
12441 usage_cat();
12442 /* NOTREACHED */
12446 argc -= optind;
12447 argv += optind;
12449 cwd = getcwd(NULL, 0);
12450 if (cwd == NULL) {
12451 error = got_error_from_errno("getcwd");
12452 goto done;
12455 error = got_repo_pack_fds_open(&pack_fds);
12456 if (error != NULL)
12457 goto done;
12459 if (repo_path == NULL) {
12460 error = got_worktree_open(&worktree, cwd);
12461 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12462 goto done;
12463 if (worktree) {
12464 repo_path = strdup(
12465 got_worktree_get_repo_path(worktree));
12466 if (repo_path == NULL) {
12467 error = got_error_from_errno("strdup");
12468 goto done;
12471 /* Release work tree lock. */
12472 got_worktree_close(worktree);
12473 worktree = NULL;
12477 if (repo_path == NULL) {
12478 repo_path = strdup(cwd);
12479 if (repo_path == NULL)
12480 return got_error_from_errno("strdup");
12483 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12484 free(repo_path);
12485 if (error != NULL)
12486 goto done;
12488 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12489 if (error)
12490 goto done;
12492 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12493 if (error)
12494 goto done;
12496 if (commit_id_str == NULL)
12497 commit_id_str = GOT_REF_HEAD;
12498 error = got_repo_match_object_id(&commit_id, NULL,
12499 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12500 if (error)
12501 goto done;
12503 error = got_object_open_as_commit(&commit, repo, commit_id);
12504 if (error)
12505 goto done;
12507 for (i = 0; i < argc; i++) {
12508 if (force_path) {
12509 error = got_object_id_by_path(&id, repo, commit,
12510 argv[i]);
12511 if (error)
12512 break;
12513 } else {
12514 error = got_repo_match_object_id(&id, &label, argv[i],
12515 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12516 repo);
12517 if (error) {
12518 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12519 error->code != GOT_ERR_NOT_REF)
12520 break;
12521 error = got_object_id_by_path(&id, repo,
12522 commit, argv[i]);
12523 if (error)
12524 break;
12528 error = got_object_get_type(&obj_type, repo, id);
12529 if (error)
12530 break;
12532 switch (obj_type) {
12533 case GOT_OBJ_TYPE_BLOB:
12534 error = cat_blob(id, repo, stdout);
12535 break;
12536 case GOT_OBJ_TYPE_TREE:
12537 error = cat_tree(id, repo, stdout);
12538 break;
12539 case GOT_OBJ_TYPE_COMMIT:
12540 error = cat_commit(id, repo, stdout);
12541 break;
12542 case GOT_OBJ_TYPE_TAG:
12543 error = cat_tag(id, repo, stdout);
12544 break;
12545 default:
12546 error = got_error(GOT_ERR_OBJ_TYPE);
12547 break;
12549 if (error)
12550 break;
12551 free(label);
12552 label = NULL;
12553 free(id);
12554 id = NULL;
12556 done:
12557 free(label);
12558 free(id);
12559 free(commit_id);
12560 if (commit)
12561 got_object_commit_close(commit);
12562 if (worktree)
12563 got_worktree_close(worktree);
12564 if (repo) {
12565 const struct got_error *close_err = got_repo_close(repo);
12566 if (error == NULL)
12567 error = close_err;
12569 if (pack_fds) {
12570 const struct got_error *pack_err =
12571 got_repo_pack_fds_close(pack_fds);
12572 if (error == NULL)
12573 error = pack_err;
12576 got_ref_list_free(&refs);
12577 return error;
12580 __dead static void
12581 usage_info(void)
12583 fprintf(stderr, "usage: %s info [path ...]\n",
12584 getprogname());
12585 exit(1);
12588 static const struct got_error *
12589 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12590 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12591 struct got_object_id *commit_id)
12593 const struct got_error *err = NULL;
12594 char *id_str = NULL;
12595 char datebuf[128];
12596 struct tm mytm, *tm;
12597 struct got_pathlist_head *paths = arg;
12598 struct got_pathlist_entry *pe;
12601 * Clear error indication from any of the path arguments which
12602 * would cause this file index entry to be displayed.
12604 TAILQ_FOREACH(pe, paths, entry) {
12605 if (got_path_cmp(path, pe->path, strlen(path),
12606 pe->path_len) == 0 ||
12607 got_path_is_child(path, pe->path, pe->path_len))
12608 pe->data = NULL; /* no error */
12611 printf(GOT_COMMIT_SEP_STR);
12612 if (S_ISLNK(mode))
12613 printf("symlink: %s\n", path);
12614 else if (S_ISREG(mode)) {
12615 printf("file: %s\n", path);
12616 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12617 } else if (S_ISDIR(mode))
12618 printf("directory: %s\n", path);
12619 else
12620 printf("something: %s\n", path);
12622 tm = localtime_r(&mtime, &mytm);
12623 if (tm == NULL)
12624 return NULL;
12625 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12626 return got_error(GOT_ERR_NO_SPACE);
12627 printf("timestamp: %s\n", datebuf);
12629 if (blob_id) {
12630 err = got_object_id_str(&id_str, blob_id);
12631 if (err)
12632 return err;
12633 printf("based on blob: %s\n", id_str);
12634 free(id_str);
12637 if (staged_blob_id) {
12638 err = got_object_id_str(&id_str, staged_blob_id);
12639 if (err)
12640 return err;
12641 printf("based on staged blob: %s\n", id_str);
12642 free(id_str);
12645 if (commit_id) {
12646 err = got_object_id_str(&id_str, commit_id);
12647 if (err)
12648 return err;
12649 printf("based on commit: %s\n", id_str);
12650 free(id_str);
12653 return NULL;
12656 static const struct got_error *
12657 cmd_info(int argc, char *argv[])
12659 const struct got_error *error = NULL;
12660 struct got_worktree *worktree = NULL;
12661 char *cwd = NULL, *id_str = NULL;
12662 struct got_pathlist_head paths;
12663 struct got_pathlist_entry *pe;
12664 char *uuidstr = NULL;
12665 int ch, show_files = 0;
12666 int *pack_fds = NULL;
12668 TAILQ_INIT(&paths);
12670 while ((ch = getopt(argc, argv, "")) != -1) {
12671 switch (ch) {
12672 default:
12673 usage_info();
12674 /* NOTREACHED */
12678 argc -= optind;
12679 argv += optind;
12681 #ifndef PROFILE
12682 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12683 NULL) == -1)
12684 err(1, "pledge");
12685 #endif
12686 cwd = getcwd(NULL, 0);
12687 if (cwd == NULL) {
12688 error = got_error_from_errno("getcwd");
12689 goto done;
12692 error = got_repo_pack_fds_open(&pack_fds);
12693 if (error != NULL)
12694 goto done;
12696 error = got_worktree_open(&worktree, cwd);
12697 if (error) {
12698 if (error->code == GOT_ERR_NOT_WORKTREE)
12699 error = wrap_not_worktree_error(error, "info", cwd);
12700 goto done;
12703 #ifndef PROFILE
12704 /* Remove "cpath" promise. */
12705 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12706 NULL) == -1)
12707 err(1, "pledge");
12708 #endif
12709 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12710 if (error)
12711 goto done;
12713 if (argc >= 1) {
12714 error = get_worktree_paths_from_argv(&paths, argc, argv,
12715 worktree);
12716 if (error)
12717 goto done;
12718 show_files = 1;
12721 error = got_object_id_str(&id_str,
12722 got_worktree_get_base_commit_id(worktree));
12723 if (error)
12724 goto done;
12726 error = got_worktree_get_uuid(&uuidstr, worktree);
12727 if (error)
12728 goto done;
12730 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12731 printf("work tree base commit: %s\n", id_str);
12732 printf("work tree path prefix: %s\n",
12733 got_worktree_get_path_prefix(worktree));
12734 printf("work tree branch reference: %s\n",
12735 got_worktree_get_head_ref_name(worktree));
12736 printf("work tree UUID: %s\n", uuidstr);
12737 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12739 if (show_files) {
12740 struct got_pathlist_entry *pe;
12741 TAILQ_FOREACH(pe, &paths, entry) {
12742 if (pe->path_len == 0)
12743 continue;
12745 * Assume this path will fail. This will be corrected
12746 * in print_path_info() in case the path does suceeed.
12748 pe->data = (void *)got_error_path(pe->path,
12749 GOT_ERR_BAD_PATH);
12751 error = got_worktree_path_info(worktree, &paths,
12752 print_path_info, &paths, check_cancelled, NULL);
12753 if (error)
12754 goto done;
12755 TAILQ_FOREACH(pe, &paths, entry) {
12756 if (pe->data != NULL) {
12757 error = pe->data; /* bad path */
12758 break;
12762 done:
12763 if (pack_fds) {
12764 const struct got_error *pack_err =
12765 got_repo_pack_fds_close(pack_fds);
12766 if (error == NULL)
12767 error = pack_err;
12769 TAILQ_FOREACH(pe, &paths, entry)
12770 free((char *)pe->path);
12771 got_pathlist_free(&paths);
12772 free(cwd);
12773 free(id_str);
12774 free(uuidstr);
12775 return error;