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"
60 #include "got_sigs.h"
61 #include "got_date.h"
63 #ifndef nitems
64 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
65 #endif
67 static volatile sig_atomic_t sigint_received;
68 static volatile sig_atomic_t sigpipe_received;
70 static void
71 catch_sigint(int signo)
72 {
73 sigint_received = 1;
74 }
76 static void
77 catch_sigpipe(int signo)
78 {
79 sigpipe_received = 1;
80 }
83 struct got_cmd {
84 const char *cmd_name;
85 const struct got_error *(*cmd_main)(int, char *[]);
86 void (*cmd_usage)(void);
87 const char *cmd_alias;
88 };
90 __dead static void usage(int, int);
91 __dead static void usage_init(void);
92 __dead static void usage_import(void);
93 __dead static void usage_clone(void);
94 __dead static void usage_fetch(void);
95 __dead static void usage_checkout(void);
96 __dead static void usage_update(void);
97 __dead static void usage_log(void);
98 __dead static void usage_diff(void);
99 __dead static void usage_blame(void);
100 __dead static void usage_tree(void);
101 __dead static void usage_status(void);
102 __dead static void usage_ref(void);
103 __dead static void usage_branch(void);
104 __dead static void usage_tag(void);
105 __dead static void usage_add(void);
106 __dead static void usage_remove(void);
107 __dead static void usage_patch(void);
108 __dead static void usage_revert(void);
109 __dead static void usage_commit(void);
110 __dead static void usage_send(void);
111 __dead static void usage_cherrypick(void);
112 __dead static void usage_backout(void);
113 __dead static void usage_rebase(void);
114 __dead static void usage_histedit(void);
115 __dead static void usage_integrate(void);
116 __dead static void usage_merge(void);
117 __dead static void usage_stage(void);
118 __dead static void usage_unstage(void);
119 __dead static void usage_cat(void);
120 __dead static void usage_info(void);
122 static const struct got_error* cmd_init(int, char *[]);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "init", cmd_init, usage_init, "" },
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
269 return 1;
272 return 0;
275 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
276 list_commands(stderr);
277 return 1;
280 __dead static void
281 usage(int hflag, int status)
283 FILE *fp = (status == 0) ? stdout : stderr;
285 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
286 getprogname());
287 if (hflag)
288 list_commands(fp);
289 exit(status);
292 static const struct got_error *
293 get_editor(char **abspath)
295 const struct got_error *err = NULL;
296 const char *editor;
298 *abspath = NULL;
300 editor = getenv("VISUAL");
301 if (editor == NULL)
302 editor = getenv("EDITOR");
304 if (editor) {
305 err = got_path_find_prog(abspath, editor);
306 if (err)
307 return err;
310 if (*abspath == NULL) {
311 *abspath = strdup("/bin/ed");
312 if (*abspath == NULL)
313 return got_error_from_errno("strdup");
316 return NULL;
319 static const struct got_error *
320 apply_unveil(const char *repo_path, int repo_read_only,
321 const char *worktree_path)
323 const struct got_error *err;
325 #ifdef PROFILE
326 if (unveil("gmon.out", "rwc") != 0)
327 return got_error_from_errno2("unveil", "gmon.out");
328 #endif
329 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
330 return got_error_from_errno2("unveil", repo_path);
332 if (worktree_path && unveil(worktree_path, "rwc") != 0)
333 return got_error_from_errno2("unveil", worktree_path);
335 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
336 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
338 err = got_privsep_unveil_exec_helpers();
339 if (err != NULL)
340 return err;
342 if (unveil(NULL, NULL) != 0)
343 return got_error_from_errno("unveil");
345 return NULL;
348 __dead static void
349 usage_init(void)
351 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
352 exit(1);
355 static const struct got_error *
356 cmd_init(int argc, char *argv[])
358 const struct got_error *error = NULL;
359 char *repo_path = NULL;
360 int ch;
362 while ((ch = getopt(argc, argv, "")) != -1) {
363 switch (ch) {
364 default:
365 usage_init();
366 /* NOTREACHED */
370 argc -= optind;
371 argv += optind;
373 #ifndef PROFILE
374 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
375 err(1, "pledge");
376 #endif
377 if (argc != 1)
378 usage_init();
380 repo_path = strdup(argv[0]);
381 if (repo_path == NULL)
382 return got_error_from_errno("strdup");
384 got_path_strip_trailing_slashes(repo_path);
386 error = got_path_mkdir(repo_path);
387 if (error &&
388 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
389 goto done;
391 error = apply_unveil(repo_path, 0, NULL);
392 if (error)
393 goto done;
395 error = got_repo_init(repo_path);
396 done:
397 free(repo_path);
398 return error;
401 __dead static void
402 usage_import(void)
404 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
405 "[-r repository-path] [-I pattern] path\n", getprogname());
406 exit(1);
409 static int
410 spawn_editor(const char *editor, const char *file)
412 pid_t pid;
413 sig_t sighup, sigint, sigquit;
414 int st = -1;
416 sighup = signal(SIGHUP, SIG_IGN);
417 sigint = signal(SIGINT, SIG_IGN);
418 sigquit = signal(SIGQUIT, SIG_IGN);
420 switch (pid = fork()) {
421 case -1:
422 goto doneediting;
423 case 0:
424 execl(editor, editor, file, (char *)NULL);
425 _exit(127);
428 while (waitpid(pid, &st, 0) == -1)
429 if (errno != EINTR)
430 break;
432 doneediting:
433 (void)signal(SIGHUP, sighup);
434 (void)signal(SIGINT, sigint);
435 (void)signal(SIGQUIT, sigquit);
437 if (!WIFEXITED(st)) {
438 errno = EINTR;
439 return -1;
442 return WEXITSTATUS(st);
445 static const struct got_error *
446 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
447 const char *initial_content, size_t initial_content_len,
448 int require_modification)
450 const struct got_error *err = NULL;
451 char *line = NULL;
452 size_t linesize = 0;
453 ssize_t linelen;
454 struct stat st, st2;
455 FILE *fp = NULL;
456 size_t len, logmsg_len;
457 char *initial_content_stripped = NULL, *buf = NULL, *s;
459 *logmsg = NULL;
461 if (stat(logmsg_path, &st) == -1)
462 return got_error_from_errno2("stat", logmsg_path);
464 if (spawn_editor(editor, logmsg_path) == -1)
465 return got_error_from_errno("failed spawning editor");
467 if (stat(logmsg_path, &st2) == -1)
468 return got_error_from_errno("stat");
470 if (require_modification &&
471 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
472 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
473 "no changes made to commit message, aborting");
475 /*
476 * Set up a stripped version of the initial content without comments
477 * and blank lines. We need this in order to check if the message
478 * has in fact been edited.
479 */
480 initial_content_stripped = malloc(initial_content_len + 1);
481 if (initial_content_stripped == NULL)
482 return got_error_from_errno("malloc");
483 initial_content_stripped[0] = '\0';
485 buf = strdup(initial_content);
486 if (buf == NULL) {
487 err = got_error_from_errno("strdup");
488 goto done;
490 s = buf;
491 len = 0;
492 while ((line = strsep(&s, "\n")) != NULL) {
493 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
494 continue; /* remove comments and leading empty lines */
495 len = strlcat(initial_content_stripped, line,
496 initial_content_len + 1);
497 if (len >= initial_content_len + 1) {
498 err = got_error(GOT_ERR_NO_SPACE);
499 goto done;
502 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
503 initial_content_stripped[len - 1] = '\0';
504 len--;
507 logmsg_len = st2.st_size;
508 *logmsg = malloc(logmsg_len + 1);
509 if (*logmsg == NULL)
510 return got_error_from_errno("malloc");
511 (*logmsg)[0] = '\0';
513 fp = fopen(logmsg_path, "re");
514 if (fp == NULL) {
515 err = got_error_from_errno("fopen");
516 goto done;
519 len = 0;
520 while ((linelen = getline(&line, &linesize, fp)) != -1) {
521 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
522 continue; /* remove comments and leading empty lines */
523 len = strlcat(*logmsg, line, logmsg_len + 1);
524 if (len >= logmsg_len + 1) {
525 err = got_error(GOT_ERR_NO_SPACE);
526 goto done;
529 free(line);
530 if (ferror(fp)) {
531 err = got_ferror(fp, GOT_ERR_IO);
532 goto done;
534 while (len > 0 && (*logmsg)[len - 1] == '\n') {
535 (*logmsg)[len - 1] = '\0';
536 len--;
539 if (len == 0) {
540 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
541 "commit message cannot be empty, aborting");
542 goto done;
544 if (require_modification &&
545 strcmp(*logmsg, initial_content_stripped) == 0)
546 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
547 "no changes made to commit message, aborting");
548 done:
549 free(initial_content_stripped);
550 free(buf);
551 if (fp && fclose(fp) == EOF && err == NULL)
552 err = got_error_from_errno("fclose");
553 if (err) {
554 free(*logmsg);
555 *logmsg = NULL;
557 return err;
560 static const struct got_error *
561 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
562 const char *path_dir, const char *branch_name)
564 char *initial_content = NULL;
565 const struct got_error *err = NULL;
566 int initial_content_len;
567 int fd = -1;
569 initial_content_len = asprintf(&initial_content,
570 "\n# %s to be imported to branch %s\n", path_dir,
571 branch_name);
572 if (initial_content_len == -1)
573 return got_error_from_errno("asprintf");
575 err = got_opentemp_named_fd(logmsg_path, &fd,
576 GOT_TMPDIR_STR "/got-importmsg");
577 if (err)
578 goto done;
580 if (write(fd, initial_content, initial_content_len) == -1) {
581 err = got_error_from_errno2("write", *logmsg_path);
582 goto done;
585 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
586 initial_content_len, 1);
587 done:
588 if (fd != -1 && close(fd) == -1 && err == NULL)
589 err = got_error_from_errno2("close", *logmsg_path);
590 free(initial_content);
591 if (err) {
592 free(*logmsg_path);
593 *logmsg_path = NULL;
595 return err;
598 static const struct got_error *
599 import_progress(void *arg, const char *path)
601 printf("A %s\n", path);
602 return NULL;
605 static int
606 valid_author(const char *author)
608 /*
609 * Really dumb email address check; we're only doing this to
610 * avoid git's object parser breaking on commits we create.
611 */
612 while (*author && *author != '<')
613 author++;
614 if (*author != '<')
615 return 0;
616 while (*author && *author != '@')
617 author++;
618 if (*author != '@')
619 return 0;
620 while (*author && *author != '>')
621 author++;
622 return *author == '>';
625 static const struct got_error *
626 get_author(char **author, struct got_repository *repo,
627 struct got_worktree *worktree)
629 const struct got_error *err = NULL;
630 const char *got_author = NULL, *name, *email;
631 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
633 *author = NULL;
635 if (worktree)
636 worktree_conf = got_worktree_get_gotconfig(worktree);
637 repo_conf = got_repo_get_gotconfig(repo);
639 /*
640 * Priority of potential author information sources, from most
641 * significant to least significant:
642 * 1) work tree's .got/got.conf file
643 * 2) repository's got.conf file
644 * 3) repository's git config file
645 * 4) environment variables
646 * 5) global git config files (in user's home directory or /etc)
647 */
649 if (worktree_conf)
650 got_author = got_gotconfig_get_author(worktree_conf);
651 if (got_author == NULL)
652 got_author = got_gotconfig_get_author(repo_conf);
653 if (got_author == NULL) {
654 name = got_repo_get_gitconfig_author_name(repo);
655 email = got_repo_get_gitconfig_author_email(repo);
656 if (name && email) {
657 if (asprintf(author, "%s <%s>", name, email) == -1)
658 return got_error_from_errno("asprintf");
659 return NULL;
662 got_author = getenv("GOT_AUTHOR");
663 if (got_author == NULL) {
664 name = got_repo_get_global_gitconfig_author_name(repo);
665 email = got_repo_get_global_gitconfig_author_email(
666 repo);
667 if (name && email) {
668 if (asprintf(author, "%s <%s>", name, email)
669 == -1)
670 return got_error_from_errno("asprintf");
671 return NULL;
673 /* TODO: Look up user in password database? */
674 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
678 *author = strdup(got_author);
679 if (*author == NULL)
680 return got_error_from_errno("strdup");
682 if (!valid_author(*author)) {
683 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
684 free(*author);
685 *author = NULL;
687 return err;
690 static const struct got_error *
691 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
692 struct got_worktree *worktree)
694 const char *got_allowed_signers = NULL;
695 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
697 *allowed_signers = NULL;
699 if (worktree)
700 worktree_conf = got_worktree_get_gotconfig(worktree);
701 repo_conf = got_repo_get_gotconfig(repo);
703 /*
704 * Priority of potential author information sources, from most
705 * significant to least significant:
706 * 1) work tree's .got/got.conf file
707 * 2) repository's got.conf file
708 */
710 if (worktree_conf)
711 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
712 worktree_conf);
713 if (got_allowed_signers == NULL)
714 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
715 repo_conf);
717 if (got_allowed_signers) {
718 *allowed_signers = strdup(got_allowed_signers);
719 if (*allowed_signers == NULL)
720 return got_error_from_errno("strdup");
722 return NULL;
725 static const struct got_error *
726 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
727 struct got_worktree *worktree)
729 const char *got_revoked_signers = NULL;
730 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
732 *revoked_signers = NULL;
734 if (worktree)
735 worktree_conf = got_worktree_get_gotconfig(worktree);
736 repo_conf = got_repo_get_gotconfig(repo);
738 /*
739 * Priority of potential author information sources, from most
740 * significant to least significant:
741 * 1) work tree's .got/got.conf file
742 * 2) repository's got.conf file
743 */
745 if (worktree_conf)
746 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
747 worktree_conf);
748 if (got_revoked_signers == NULL)
749 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
750 repo_conf);
752 if (got_revoked_signers) {
753 *revoked_signers = strdup(got_revoked_signers);
754 if (*revoked_signers == NULL)
755 return got_error_from_errno("strdup");
757 return NULL;
760 static const struct got_error *
761 get_gitconfig_path(char **gitconfig_path)
763 const char *homedir = getenv("HOME");
765 *gitconfig_path = NULL;
766 if (homedir) {
767 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
768 return got_error_from_errno("asprintf");
771 return NULL;
774 static const struct got_error *
775 cmd_import(int argc, char *argv[])
777 const struct got_error *error = NULL;
778 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
779 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
780 const char *branch_name = "main";
781 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
782 struct got_repository *repo = NULL;
783 struct got_reference *branch_ref = NULL, *head_ref = NULL;
784 struct got_object_id *new_commit_id = NULL;
785 int ch;
786 struct got_pathlist_head ignores;
787 struct got_pathlist_entry *pe;
788 int preserve_logmsg = 0;
789 int *pack_fds = NULL;
791 TAILQ_INIT(&ignores);
793 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
794 switch (ch) {
795 case 'b':
796 branch_name = optarg;
797 break;
798 case 'm':
799 logmsg = strdup(optarg);
800 if (logmsg == NULL) {
801 error = got_error_from_errno("strdup");
802 goto done;
804 break;
805 case 'r':
806 repo_path = realpath(optarg, NULL);
807 if (repo_path == NULL) {
808 error = got_error_from_errno2("realpath",
809 optarg);
810 goto done;
812 break;
813 case 'I':
814 if (optarg[0] == '\0')
815 break;
816 error = got_pathlist_insert(&pe, &ignores, optarg,
817 NULL);
818 if (error)
819 goto done;
820 break;
821 default:
822 usage_import();
823 /* NOTREACHED */
827 argc -= optind;
828 argv += optind;
830 #ifndef PROFILE
831 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
832 "unveil",
833 NULL) == -1)
834 err(1, "pledge");
835 #endif
836 if (argc != 1)
837 usage_import();
839 if (repo_path == NULL) {
840 repo_path = getcwd(NULL, 0);
841 if (repo_path == NULL)
842 return got_error_from_errno("getcwd");
844 got_path_strip_trailing_slashes(repo_path);
845 error = get_gitconfig_path(&gitconfig_path);
846 if (error)
847 goto done;
848 error = got_repo_pack_fds_open(&pack_fds);
849 if (error != NULL)
850 goto done;
851 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
852 if (error)
853 goto done;
855 error = get_author(&author, repo, NULL);
856 if (error)
857 return error;
859 /*
860 * Don't let the user create a branch name with a leading '-'.
861 * While technically a valid reference name, this case is usually
862 * an unintended typo.
863 */
864 if (branch_name[0] == '-')
865 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
867 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
868 error = got_error_from_errno("asprintf");
869 goto done;
872 error = got_ref_open(&branch_ref, repo, refname, 0);
873 if (error) {
874 if (error->code != GOT_ERR_NOT_REF)
875 goto done;
876 } else {
877 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
878 "import target branch already exists");
879 goto done;
882 path_dir = realpath(argv[0], NULL);
883 if (path_dir == NULL) {
884 error = got_error_from_errno2("realpath", argv[0]);
885 goto done;
887 got_path_strip_trailing_slashes(path_dir);
889 /*
890 * unveil(2) traverses exec(2); if an editor is used we have
891 * to apply unveil after the log message has been written.
892 */
893 if (logmsg == NULL || strlen(logmsg) == 0) {
894 error = get_editor(&editor);
895 if (error)
896 goto done;
897 free(logmsg);
898 error = collect_import_msg(&logmsg, &logmsg_path, editor,
899 path_dir, refname);
900 if (error) {
901 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
902 logmsg_path != NULL)
903 preserve_logmsg = 1;
904 goto done;
908 if (unveil(path_dir, "r") != 0) {
909 error = got_error_from_errno2("unveil", path_dir);
910 if (logmsg_path)
911 preserve_logmsg = 1;
912 goto done;
915 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
916 if (error) {
917 if (logmsg_path)
918 preserve_logmsg = 1;
919 goto done;
922 error = got_repo_import(&new_commit_id, path_dir, logmsg,
923 author, &ignores, repo, import_progress, NULL);
924 if (error) {
925 if (logmsg_path)
926 preserve_logmsg = 1;
927 goto done;
930 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
931 if (error) {
932 if (logmsg_path)
933 preserve_logmsg = 1;
934 goto done;
937 error = got_ref_write(branch_ref, repo);
938 if (error) {
939 if (logmsg_path)
940 preserve_logmsg = 1;
941 goto done;
944 error = got_object_id_str(&id_str, new_commit_id);
945 if (error) {
946 if (logmsg_path)
947 preserve_logmsg = 1;
948 goto done;
951 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
952 if (error) {
953 if (error->code != GOT_ERR_NOT_REF) {
954 if (logmsg_path)
955 preserve_logmsg = 1;
956 goto done;
959 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
960 branch_ref);
961 if (error) {
962 if (logmsg_path)
963 preserve_logmsg = 1;
964 goto done;
967 error = got_ref_write(head_ref, repo);
968 if (error) {
969 if (logmsg_path)
970 preserve_logmsg = 1;
971 goto done;
975 printf("Created branch %s with commit %s\n",
976 got_ref_get_name(branch_ref), id_str);
977 done:
978 if (pack_fds) {
979 const struct got_error *pack_err =
980 got_repo_pack_fds_close(pack_fds);
981 if (error == NULL)
982 error = pack_err;
984 if (preserve_logmsg) {
985 fprintf(stderr, "%s: log message preserved in %s\n",
986 getprogname(), logmsg_path);
987 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
988 error = got_error_from_errno2("unlink", logmsg_path);
989 free(logmsg);
990 free(logmsg_path);
991 free(repo_path);
992 free(editor);
993 free(refname);
994 free(new_commit_id);
995 free(id_str);
996 free(author);
997 free(gitconfig_path);
998 if (branch_ref)
999 got_ref_close(branch_ref);
1000 if (head_ref)
1001 got_ref_close(head_ref);
1002 return error;
1005 __dead static void
1006 usage_clone(void)
1008 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
1009 "[-R reference] repository-url [directory]\n", getprogname());
1010 exit(1);
1013 struct got_fetch_progress_arg {
1014 char last_scaled_size[FMT_SCALED_STRSIZE];
1015 int last_p_indexed;
1016 int last_p_resolved;
1017 int verbosity;
1019 struct got_repository *repo;
1021 int create_configs;
1022 int configs_created;
1023 struct {
1024 struct got_pathlist_head *symrefs;
1025 struct got_pathlist_head *wanted_branches;
1026 struct got_pathlist_head *wanted_refs;
1027 const char *proto;
1028 const char *host;
1029 const char *port;
1030 const char *remote_repo_path;
1031 const char *git_url;
1032 int fetch_all_branches;
1033 int mirror_references;
1034 } config_info;
1037 /* XXX forward declaration */
1038 static const struct got_error *
1039 create_config_files(const char *proto, const char *host, const char *port,
1040 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1041 int mirror_references, struct got_pathlist_head *symrefs,
1042 struct got_pathlist_head *wanted_branches,
1043 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1045 static const struct got_error *
1046 fetch_progress(void *arg, const char *message, off_t packfile_size,
1047 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1049 const struct got_error *err = NULL;
1050 struct got_fetch_progress_arg *a = arg;
1051 char scaled_size[FMT_SCALED_STRSIZE];
1052 int p_indexed, p_resolved;
1053 int print_size = 0, print_indexed = 0, print_resolved = 0;
1056 * In order to allow a failed clone to be resumed with 'got fetch'
1057 * we try to create configuration files as soon as possible.
1058 * Once the server has sent information about its default branch
1059 * we have all required information.
1061 if (a->create_configs && !a->configs_created &&
1062 !TAILQ_EMPTY(a->config_info.symrefs)) {
1063 err = create_config_files(a->config_info.proto,
1064 a->config_info.host, a->config_info.port,
1065 a->config_info.remote_repo_path,
1066 a->config_info.git_url,
1067 a->config_info.fetch_all_branches,
1068 a->config_info.mirror_references,
1069 a->config_info.symrefs,
1070 a->config_info.wanted_branches,
1071 a->config_info.wanted_refs, a->repo);
1072 if (err)
1073 return err;
1074 a->configs_created = 1;
1077 if (a->verbosity < 0)
1078 return NULL;
1080 if (message && message[0] != '\0') {
1081 printf("\rserver: %s", message);
1082 fflush(stdout);
1083 return NULL;
1086 if (packfile_size > 0 || nobj_indexed > 0) {
1087 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1088 (a->last_scaled_size[0] == '\0' ||
1089 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1090 print_size = 1;
1091 if (strlcpy(a->last_scaled_size, scaled_size,
1092 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1093 return got_error(GOT_ERR_NO_SPACE);
1095 if (nobj_indexed > 0) {
1096 p_indexed = (nobj_indexed * 100) / nobj_total;
1097 if (p_indexed != a->last_p_indexed) {
1098 a->last_p_indexed = p_indexed;
1099 print_indexed = 1;
1100 print_size = 1;
1103 if (nobj_resolved > 0) {
1104 p_resolved = (nobj_resolved * 100) /
1105 (nobj_total - nobj_loose);
1106 if (p_resolved != a->last_p_resolved) {
1107 a->last_p_resolved = p_resolved;
1108 print_resolved = 1;
1109 print_indexed = 1;
1110 print_size = 1;
1115 if (print_size || print_indexed || print_resolved)
1116 printf("\r");
1117 if (print_size)
1118 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1119 if (print_indexed)
1120 printf("; indexing %d%%", p_indexed);
1121 if (print_resolved)
1122 printf("; resolving deltas %d%%", p_resolved);
1123 if (print_size || print_indexed || print_resolved)
1124 fflush(stdout);
1126 return NULL;
1129 static const struct got_error *
1130 create_symref(const char *refname, struct got_reference *target_ref,
1131 int verbosity, struct got_repository *repo)
1133 const struct got_error *err;
1134 struct got_reference *head_symref;
1136 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1137 if (err)
1138 return err;
1140 err = got_ref_write(head_symref, repo);
1141 if (err == NULL && verbosity > 0) {
1142 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1143 got_ref_get_name(target_ref));
1145 got_ref_close(head_symref);
1146 return err;
1149 static const struct got_error *
1150 list_remote_refs(struct got_pathlist_head *symrefs,
1151 struct got_pathlist_head *refs)
1153 const struct got_error *err;
1154 struct got_pathlist_entry *pe;
1156 TAILQ_FOREACH(pe, symrefs, entry) {
1157 const char *refname = pe->path;
1158 const char *targetref = pe->data;
1160 printf("%s: %s\n", refname, targetref);
1163 TAILQ_FOREACH(pe, refs, entry) {
1164 const char *refname = pe->path;
1165 struct got_object_id *id = pe->data;
1166 char *id_str;
1168 err = got_object_id_str(&id_str, id);
1169 if (err)
1170 return err;
1171 printf("%s: %s\n", refname, id_str);
1172 free(id_str);
1175 return NULL;
1178 static const struct got_error *
1179 create_ref(const char *refname, struct got_object_id *id,
1180 int verbosity, struct got_repository *repo)
1182 const struct got_error *err = NULL;
1183 struct got_reference *ref;
1184 char *id_str;
1186 err = got_object_id_str(&id_str, id);
1187 if (err)
1188 return err;
1190 err = got_ref_alloc(&ref, refname, id);
1191 if (err)
1192 goto done;
1194 err = got_ref_write(ref, repo);
1195 got_ref_close(ref);
1197 if (err == NULL && verbosity >= 0)
1198 printf("Created reference %s: %s\n", refname, id_str);
1199 done:
1200 free(id_str);
1201 return err;
1204 static int
1205 match_wanted_ref(const char *refname, const char *wanted_ref)
1207 if (strncmp(refname, "refs/", 5) != 0)
1208 return 0;
1209 refname += 5;
1212 * Prevent fetching of references that won't make any
1213 * sense outside of the remote repository's context.
1215 if (strncmp(refname, "got/", 4) == 0)
1216 return 0;
1217 if (strncmp(refname, "remotes/", 8) == 0)
1218 return 0;
1220 if (strncmp(wanted_ref, "refs/", 5) == 0)
1221 wanted_ref += 5;
1223 /* Allow prefix match. */
1224 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1225 return 1;
1227 /* Allow exact match. */
1228 return (strcmp(refname, wanted_ref) == 0);
1231 static int
1232 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1234 struct got_pathlist_entry *pe;
1236 TAILQ_FOREACH(pe, wanted_refs, entry) {
1237 if (match_wanted_ref(refname, pe->path))
1238 return 1;
1241 return 0;
1244 static const struct got_error *
1245 create_wanted_ref(const char *refname, struct got_object_id *id,
1246 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1248 const struct got_error *err;
1249 char *remote_refname;
1251 if (strncmp("refs/", refname, 5) == 0)
1252 refname += 5;
1254 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1255 remote_repo_name, refname) == -1)
1256 return got_error_from_errno("asprintf");
1258 err = create_ref(remote_refname, id, verbosity, repo);
1259 free(remote_refname);
1260 return err;
1263 static const struct got_error *
1264 create_gotconfig(const char *proto, const char *host, const char *port,
1265 const char *remote_repo_path, const char *default_branch,
1266 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1267 struct got_pathlist_head *wanted_refs, int mirror_references,
1268 struct got_repository *repo)
1270 const struct got_error *err = NULL;
1271 char *gotconfig_path = NULL;
1272 char *gotconfig = NULL;
1273 FILE *gotconfig_file = NULL;
1274 const char *branchname = NULL;
1275 char *branches = NULL, *refs = NULL;
1276 ssize_t n;
1278 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1279 struct got_pathlist_entry *pe;
1280 TAILQ_FOREACH(pe, wanted_branches, entry) {
1281 char *s;
1282 branchname = pe->path;
1283 if (strncmp(branchname, "refs/heads/", 11) == 0)
1284 branchname += 11;
1285 if (asprintf(&s, "%s\"%s\" ",
1286 branches ? branches : "", branchname) == -1) {
1287 err = got_error_from_errno("asprintf");
1288 goto done;
1290 free(branches);
1291 branches = s;
1293 } else if (!fetch_all_branches && default_branch) {
1294 branchname = default_branch;
1295 if (strncmp(branchname, "refs/heads/", 11) == 0)
1296 branchname += 11;
1297 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1298 err = got_error_from_errno("asprintf");
1299 goto done;
1302 if (!TAILQ_EMPTY(wanted_refs)) {
1303 struct got_pathlist_entry *pe;
1304 TAILQ_FOREACH(pe, wanted_refs, entry) {
1305 char *s;
1306 const char *refname = pe->path;
1307 if (strncmp(refname, "refs/", 5) == 0)
1308 branchname += 5;
1309 if (asprintf(&s, "%s\"%s\" ",
1310 refs ? refs : "", refname) == -1) {
1311 err = got_error_from_errno("asprintf");
1312 goto done;
1314 free(refs);
1315 refs = s;
1319 /* Create got.conf(5). */
1320 gotconfig_path = got_repo_get_path_gotconfig(repo);
1321 if (gotconfig_path == NULL) {
1322 err = got_error_from_errno("got_repo_get_path_gotconfig");
1323 goto done;
1325 gotconfig_file = fopen(gotconfig_path, "ae");
1326 if (gotconfig_file == NULL) {
1327 err = got_error_from_errno2("fopen", gotconfig_path);
1328 goto done;
1330 if (asprintf(&gotconfig,
1331 "remote \"%s\" {\n"
1332 "\tserver %s\n"
1333 "\tprotocol %s\n"
1334 "%s%s%s"
1335 "\trepository \"%s\"\n"
1336 "%s%s%s"
1337 "%s%s%s"
1338 "%s"
1339 "%s"
1340 "}\n",
1341 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1342 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1343 remote_repo_path, branches ? "\tbranch { " : "",
1344 branches ? branches : "", branches ? "}\n" : "",
1345 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1346 mirror_references ? "\tmirror_references yes\n" : "",
1347 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1348 err = got_error_from_errno("asprintf");
1349 goto done;
1351 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1352 if (n != strlen(gotconfig)) {
1353 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1354 goto done;
1357 done:
1358 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1359 err = got_error_from_errno2("fclose", gotconfig_path);
1360 free(gotconfig_path);
1361 free(branches);
1362 return err;
1365 static const struct got_error *
1366 create_gitconfig(const char *git_url, const char *default_branch,
1367 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1368 struct got_pathlist_head *wanted_refs, int mirror_references,
1369 struct got_repository *repo)
1371 const struct got_error *err = NULL;
1372 char *gitconfig_path = NULL;
1373 char *gitconfig = NULL;
1374 FILE *gitconfig_file = NULL;
1375 char *branches = NULL, *refs = NULL;
1376 const char *branchname;
1377 ssize_t n;
1379 /* Create a config file Git can understand. */
1380 gitconfig_path = got_repo_get_path_gitconfig(repo);
1381 if (gitconfig_path == NULL) {
1382 err = got_error_from_errno("got_repo_get_path_gitconfig");
1383 goto done;
1385 gitconfig_file = fopen(gitconfig_path, "ae");
1386 if (gitconfig_file == NULL) {
1387 err = got_error_from_errno2("fopen", gitconfig_path);
1388 goto done;
1390 if (fetch_all_branches) {
1391 if (mirror_references) {
1392 if (asprintf(&branches,
1393 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1394 err = got_error_from_errno("asprintf");
1395 goto done;
1397 } else if (asprintf(&branches,
1398 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1399 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1400 err = got_error_from_errno("asprintf");
1401 goto done;
1403 } else if (!TAILQ_EMPTY(wanted_branches)) {
1404 struct got_pathlist_entry *pe;
1405 TAILQ_FOREACH(pe, wanted_branches, entry) {
1406 char *s;
1407 branchname = pe->path;
1408 if (strncmp(branchname, "refs/heads/", 11) == 0)
1409 branchname += 11;
1410 if (mirror_references) {
1411 if (asprintf(&s,
1412 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1413 branches ? branches : "",
1414 branchname, branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 } else if (asprintf(&s,
1419 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1420 branches ? branches : "",
1421 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1422 branchname) == -1) {
1423 err = got_error_from_errno("asprintf");
1424 goto done;
1426 free(branches);
1427 branches = s;
1429 } else {
1431 * If the server specified a default branch, use just that one.
1432 * Otherwise fall back to fetching all branches on next fetch.
1434 if (default_branch) {
1435 branchname = default_branch;
1436 if (strncmp(branchname, "refs/heads/", 11) == 0)
1437 branchname += 11;
1438 } else
1439 branchname = "*"; /* fall back to all branches */
1440 if (mirror_references) {
1441 if (asprintf(&branches,
1442 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1443 branchname, branchname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1447 } else if (asprintf(&branches,
1448 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1449 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1450 branchname) == -1) {
1451 err = got_error_from_errno("asprintf");
1452 goto done;
1455 if (!TAILQ_EMPTY(wanted_refs)) {
1456 struct got_pathlist_entry *pe;
1457 TAILQ_FOREACH(pe, wanted_refs, entry) {
1458 char *s;
1459 const char *refname = pe->path;
1460 if (strncmp(refname, "refs/", 5) == 0)
1461 refname += 5;
1462 if (mirror_references) {
1463 if (asprintf(&s,
1464 "%s\tfetch = refs/%s:refs/%s\n",
1465 refs ? refs : "", refname, refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 } else if (asprintf(&s,
1470 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1471 refs ? refs : "",
1472 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1473 refname) == -1) {
1474 err = got_error_from_errno("asprintf");
1475 goto done;
1477 free(refs);
1478 refs = s;
1482 if (asprintf(&gitconfig,
1483 "[remote \"%s\"]\n"
1484 "\turl = %s\n"
1485 "%s"
1486 "%s"
1487 "\tfetch = refs/tags/*:refs/tags/*\n",
1488 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1489 refs ? refs : "") == -1) {
1490 err = got_error_from_errno("asprintf");
1491 goto done;
1493 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1494 if (n != strlen(gitconfig)) {
1495 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1496 goto done;
1498 done:
1499 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1500 err = got_error_from_errno2("fclose", gitconfig_path);
1501 free(gitconfig_path);
1502 free(branches);
1503 return err;
1506 static const struct got_error *
1507 create_config_files(const char *proto, const char *host, const char *port,
1508 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1509 int mirror_references, struct got_pathlist_head *symrefs,
1510 struct got_pathlist_head *wanted_branches,
1511 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1513 const struct got_error *err = NULL;
1514 const char *default_branch = NULL;
1515 struct got_pathlist_entry *pe;
1518 * If we asked for a set of wanted branches then use the first
1519 * one of those.
1521 if (!TAILQ_EMPTY(wanted_branches)) {
1522 pe = TAILQ_FIRST(wanted_branches);
1523 default_branch = pe->path;
1524 } else {
1525 /* First HEAD ref listed by server is the default branch. */
1526 TAILQ_FOREACH(pe, symrefs, entry) {
1527 const char *refname = pe->path;
1528 const char *target = pe->data;
1530 if (strcmp(refname, GOT_REF_HEAD) != 0)
1531 continue;
1533 default_branch = target;
1534 break;
1538 /* Create got.conf(5). */
1539 err = create_gotconfig(proto, host, port, remote_repo_path,
1540 default_branch, fetch_all_branches, wanted_branches,
1541 wanted_refs, mirror_references, repo);
1542 if (err)
1543 return err;
1545 /* Create a config file Git can understand. */
1546 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1547 wanted_branches, wanted_refs, mirror_references, repo);
1550 static const struct got_error *
1551 cmd_clone(int argc, char *argv[])
1553 const struct got_error *error = NULL;
1554 const char *uri, *dirname;
1555 char *proto, *host, *port, *repo_name, *server_path;
1556 char *default_destdir = NULL, *id_str = NULL;
1557 const char *repo_path;
1558 struct got_repository *repo = NULL;
1559 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1560 struct got_pathlist_entry *pe;
1561 struct got_object_id *pack_hash = NULL;
1562 int ch, fetchfd = -1, fetchstatus;
1563 pid_t fetchpid = -1;
1564 struct got_fetch_progress_arg fpa;
1565 char *git_url = NULL;
1566 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1567 int list_refs_only = 0;
1568 int *pack_fds = NULL;
1570 TAILQ_INIT(&refs);
1571 TAILQ_INIT(&symrefs);
1572 TAILQ_INIT(&wanted_branches);
1573 TAILQ_INIT(&wanted_refs);
1575 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1576 switch (ch) {
1577 case 'a':
1578 fetch_all_branches = 1;
1579 break;
1580 case 'b':
1581 error = got_pathlist_append(&wanted_branches,
1582 optarg, NULL);
1583 if (error)
1584 return error;
1585 break;
1586 case 'l':
1587 list_refs_only = 1;
1588 break;
1589 case 'm':
1590 mirror_references = 1;
1591 break;
1592 case 'v':
1593 if (verbosity < 0)
1594 verbosity = 0;
1595 else if (verbosity < 3)
1596 verbosity++;
1597 break;
1598 case 'q':
1599 verbosity = -1;
1600 break;
1601 case 'R':
1602 error = got_pathlist_append(&wanted_refs,
1603 optarg, NULL);
1604 if (error)
1605 return error;
1606 break;
1607 default:
1608 usage_clone();
1609 break;
1612 argc -= optind;
1613 argv += optind;
1615 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1616 option_conflict('a', 'b');
1617 if (list_refs_only) {
1618 if (!TAILQ_EMPTY(&wanted_branches))
1619 option_conflict('l', 'b');
1620 if (fetch_all_branches)
1621 option_conflict('l', 'a');
1622 if (mirror_references)
1623 option_conflict('l', 'm');
1624 if (!TAILQ_EMPTY(&wanted_refs))
1625 option_conflict('l', 'R');
1628 uri = argv[0];
1630 if (argc == 1)
1631 dirname = NULL;
1632 else if (argc == 2)
1633 dirname = argv[1];
1634 else
1635 usage_clone();
1637 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1638 &repo_name, uri);
1639 if (error)
1640 goto done;
1642 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1643 host, port ? ":" : "", port ? port : "",
1644 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1645 error = got_error_from_errno("asprintf");
1646 goto done;
1649 if (strcmp(proto, "git") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd dns inet unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "git+ssh") == 0 ||
1656 strcmp(proto, "ssh") == 0) {
1657 #ifndef PROFILE
1658 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1659 "sendfd unveil", NULL) == -1)
1660 err(1, "pledge");
1661 #endif
1662 } else if (strcmp(proto, "http") == 0 ||
1663 strcmp(proto, "git+http") == 0) {
1664 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1665 goto done;
1666 } else {
1667 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1668 goto done;
1670 if (dirname == NULL) {
1671 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1672 error = got_error_from_errno("asprintf");
1673 goto done;
1675 repo_path = default_destdir;
1676 } else
1677 repo_path = dirname;
1679 if (!list_refs_only) {
1680 error = got_path_mkdir(repo_path);
1681 if (error &&
1682 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1683 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1684 goto done;
1685 if (!got_path_dir_is_empty(repo_path)) {
1686 error = got_error_path(repo_path,
1687 GOT_ERR_DIR_NOT_EMPTY);
1688 goto done;
1692 error = got_dial_apply_unveil(proto);
1693 if (error)
1694 goto done;
1696 error = apply_unveil(repo_path, 0, NULL);
1697 if (error)
1698 goto done;
1700 if (verbosity >= 0)
1701 printf("Connecting to %s%s%s\n", host,
1702 port ? ":" : "", port ? port : "");
1704 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1705 server_path, verbosity);
1706 if (error)
1707 goto done;
1709 if (!list_refs_only) {
1710 error = got_repo_init(repo_path);
1711 if (error)
1712 goto done;
1713 error = got_repo_pack_fds_open(&pack_fds);
1714 if (error != NULL)
1715 goto done;
1716 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1717 if (error)
1718 goto done;
1721 fpa.last_scaled_size[0] = '\0';
1722 fpa.last_p_indexed = -1;
1723 fpa.last_p_resolved = -1;
1724 fpa.verbosity = verbosity;
1725 fpa.create_configs = 1;
1726 fpa.configs_created = 0;
1727 fpa.repo = repo;
1728 fpa.config_info.symrefs = &symrefs;
1729 fpa.config_info.wanted_branches = &wanted_branches;
1730 fpa.config_info.wanted_refs = &wanted_refs;
1731 fpa.config_info.proto = proto;
1732 fpa.config_info.host = host;
1733 fpa.config_info.port = port;
1734 fpa.config_info.remote_repo_path = server_path;
1735 fpa.config_info.git_url = git_url;
1736 fpa.config_info.fetch_all_branches = fetch_all_branches;
1737 fpa.config_info.mirror_references = mirror_references;
1738 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1739 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1740 fetch_all_branches, &wanted_branches, &wanted_refs,
1741 list_refs_only, verbosity, fetchfd, repo,
1742 fetch_progress, &fpa);
1743 if (error)
1744 goto done;
1746 if (list_refs_only) {
1747 error = list_remote_refs(&symrefs, &refs);
1748 goto done;
1751 if (pack_hash == NULL) {
1752 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1753 "server sent an empty pack file");
1754 goto done;
1756 error = got_object_id_str(&id_str, pack_hash);
1757 if (error)
1758 goto done;
1759 if (verbosity >= 0)
1760 printf("\nFetched %s.pack\n", id_str);
1761 free(id_str);
1763 /* Set up references provided with the pack file. */
1764 TAILQ_FOREACH(pe, &refs, entry) {
1765 const char *refname = pe->path;
1766 struct got_object_id *id = pe->data;
1767 char *remote_refname;
1769 if (is_wanted_ref(&wanted_refs, refname) &&
1770 !mirror_references) {
1771 error = create_wanted_ref(refname, id,
1772 GOT_FETCH_DEFAULT_REMOTE_NAME,
1773 verbosity - 1, repo);
1774 if (error)
1775 goto done;
1776 continue;
1779 error = create_ref(refname, id, verbosity - 1, repo);
1780 if (error)
1781 goto done;
1783 if (mirror_references)
1784 continue;
1786 if (strncmp("refs/heads/", refname, 11) != 0)
1787 continue;
1789 if (asprintf(&remote_refname,
1790 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1791 refname + 11) == -1) {
1792 error = got_error_from_errno("asprintf");
1793 goto done;
1795 error = create_ref(remote_refname, id, verbosity - 1, repo);
1796 free(remote_refname);
1797 if (error)
1798 goto done;
1801 /* Set the HEAD reference if the server provided one. */
1802 TAILQ_FOREACH(pe, &symrefs, entry) {
1803 struct got_reference *target_ref;
1804 const char *refname = pe->path;
1805 const char *target = pe->data;
1806 char *remote_refname = NULL, *remote_target = NULL;
1808 if (strcmp(refname, GOT_REF_HEAD) != 0)
1809 continue;
1811 error = got_ref_open(&target_ref, repo, target, 0);
1812 if (error) {
1813 if (error->code == GOT_ERR_NOT_REF) {
1814 error = NULL;
1815 continue;
1817 goto done;
1820 error = create_symref(refname, target_ref, verbosity, repo);
1821 got_ref_close(target_ref);
1822 if (error)
1823 goto done;
1825 if (mirror_references)
1826 continue;
1828 if (strncmp("refs/heads/", target, 11) != 0)
1829 continue;
1831 if (asprintf(&remote_refname,
1832 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1833 refname) == -1) {
1834 error = got_error_from_errno("asprintf");
1835 goto done;
1837 if (asprintf(&remote_target,
1838 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1839 target + 11) == -1) {
1840 error = got_error_from_errno("asprintf");
1841 free(remote_refname);
1842 goto done;
1844 error = got_ref_open(&target_ref, repo, remote_target, 0);
1845 if (error) {
1846 free(remote_refname);
1847 free(remote_target);
1848 if (error->code == GOT_ERR_NOT_REF) {
1849 error = NULL;
1850 continue;
1852 goto done;
1854 error = create_symref(remote_refname, target_ref,
1855 verbosity - 1, repo);
1856 free(remote_refname);
1857 free(remote_target);
1858 got_ref_close(target_ref);
1859 if (error)
1860 goto done;
1862 if (pe == NULL) {
1864 * We failed to set the HEAD reference. If we asked for
1865 * a set of wanted branches use the first of one of those
1866 * which could be fetched instead.
1868 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1869 const char *target = pe->path;
1870 struct got_reference *target_ref;
1872 error = got_ref_open(&target_ref, repo, target, 0);
1873 if (error) {
1874 if (error->code == GOT_ERR_NOT_REF) {
1875 error = NULL;
1876 continue;
1878 goto done;
1881 error = create_symref(GOT_REF_HEAD, target_ref,
1882 verbosity, repo);
1883 got_ref_close(target_ref);
1884 if (error)
1885 goto done;
1886 break;
1890 if (verbosity >= 0)
1891 printf("Created %s repository '%s'\n",
1892 mirror_references ? "mirrored" : "cloned", repo_path);
1893 done:
1894 if (pack_fds) {
1895 const struct got_error *pack_err =
1896 got_repo_pack_fds_close(pack_fds);
1897 if (error == NULL)
1898 error = pack_err;
1900 if (fetchpid > 0) {
1901 if (kill(fetchpid, SIGTERM) == -1)
1902 error = got_error_from_errno("kill");
1903 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1904 error = got_error_from_errno("waitpid");
1906 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1907 error = got_error_from_errno("close");
1908 if (repo) {
1909 const struct got_error *close_err = got_repo_close(repo);
1910 if (error == NULL)
1911 error = close_err;
1913 TAILQ_FOREACH(pe, &refs, entry) {
1914 free((void *)pe->path);
1915 free(pe->data);
1917 got_pathlist_free(&refs);
1918 TAILQ_FOREACH(pe, &symrefs, entry) {
1919 free((void *)pe->path);
1920 free(pe->data);
1922 got_pathlist_free(&symrefs);
1923 got_pathlist_free(&wanted_branches);
1924 got_pathlist_free(&wanted_refs);
1925 free(pack_hash);
1926 free(proto);
1927 free(host);
1928 free(port);
1929 free(server_path);
1930 free(repo_name);
1931 free(default_destdir);
1932 free(git_url);
1933 return error;
1936 static const struct got_error *
1937 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1938 int replace_tags, int verbosity, struct got_repository *repo)
1940 const struct got_error *err = NULL;
1941 char *new_id_str = NULL;
1942 struct got_object_id *old_id = NULL;
1944 err = got_object_id_str(&new_id_str, new_id);
1945 if (err)
1946 goto done;
1948 if (!replace_tags &&
1949 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1950 err = got_ref_resolve(&old_id, repo, ref);
1951 if (err)
1952 goto done;
1953 if (got_object_id_cmp(old_id, new_id) == 0)
1954 goto done;
1955 if (verbosity >= 0) {
1956 printf("Rejecting update of existing tag %s: %s\n",
1957 got_ref_get_name(ref), new_id_str);
1959 goto done;
1962 if (got_ref_is_symbolic(ref)) {
1963 if (verbosity >= 0) {
1964 printf("Replacing reference %s: %s\n",
1965 got_ref_get_name(ref),
1966 got_ref_get_symref_target(ref));
1968 err = got_ref_change_symref_to_ref(ref, new_id);
1969 if (err)
1970 goto done;
1971 err = got_ref_write(ref, repo);
1972 if (err)
1973 goto done;
1974 } else {
1975 err = got_ref_resolve(&old_id, repo, ref);
1976 if (err)
1977 goto done;
1978 if (got_object_id_cmp(old_id, new_id) == 0)
1979 goto done;
1981 err = got_ref_change_ref(ref, new_id);
1982 if (err)
1983 goto done;
1984 err = got_ref_write(ref, repo);
1985 if (err)
1986 goto done;
1989 if (verbosity >= 0)
1990 printf("Updated %s: %s\n", got_ref_get_name(ref),
1991 new_id_str);
1992 done:
1993 free(old_id);
1994 free(new_id_str);
1995 return err;
1998 static const struct got_error *
1999 update_symref(const char *refname, struct got_reference *target_ref,
2000 int verbosity, struct got_repository *repo)
2002 const struct got_error *err = NULL, *unlock_err;
2003 struct got_reference *symref;
2004 int symref_is_locked = 0;
2006 err = got_ref_open(&symref, repo, refname, 1);
2007 if (err) {
2008 if (err->code != GOT_ERR_NOT_REF)
2009 return err;
2010 err = got_ref_alloc_symref(&symref, refname, target_ref);
2011 if (err)
2012 goto done;
2014 err = got_ref_write(symref, repo);
2015 if (err)
2016 goto done;
2018 if (verbosity >= 0)
2019 printf("Created reference %s: %s\n",
2020 got_ref_get_name(symref),
2021 got_ref_get_symref_target(symref));
2022 } else {
2023 symref_is_locked = 1;
2025 if (strcmp(got_ref_get_symref_target(symref),
2026 got_ref_get_name(target_ref)) == 0)
2027 goto done;
2029 err = got_ref_change_symref(symref,
2030 got_ref_get_name(target_ref));
2031 if (err)
2032 goto done;
2034 err = got_ref_write(symref, repo);
2035 if (err)
2036 goto done;
2038 if (verbosity >= 0)
2039 printf("Updated %s: %s\n", got_ref_get_name(symref),
2040 got_ref_get_symref_target(symref));
2043 done:
2044 if (symref_is_locked) {
2045 unlock_err = got_ref_unlock(symref);
2046 if (unlock_err && err == NULL)
2047 err = unlock_err;
2049 got_ref_close(symref);
2050 return err;
2053 __dead static void
2054 usage_fetch(void)
2056 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2057 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2058 "[remote-repository-name]\n",
2059 getprogname());
2060 exit(1);
2063 static const struct got_error *
2064 delete_missing_ref(struct got_reference *ref,
2065 int verbosity, struct got_repository *repo)
2067 const struct got_error *err = NULL;
2068 struct got_object_id *id = NULL;
2069 char *id_str = NULL;
2071 if (got_ref_is_symbolic(ref)) {
2072 err = got_ref_delete(ref, repo);
2073 if (err)
2074 return err;
2075 if (verbosity >= 0) {
2076 printf("Deleted %s: %s\n",
2077 got_ref_get_name(ref),
2078 got_ref_get_symref_target(ref));
2080 } else {
2081 err = got_ref_resolve(&id, repo, ref);
2082 if (err)
2083 return err;
2084 err = got_object_id_str(&id_str, id);
2085 if (err)
2086 goto done;
2088 err = got_ref_delete(ref, repo);
2089 if (err)
2090 goto done;
2091 if (verbosity >= 0) {
2092 printf("Deleted %s: %s\n",
2093 got_ref_get_name(ref), id_str);
2096 done:
2097 free(id);
2098 free(id_str);
2099 return NULL;
2102 static const struct got_error *
2103 delete_missing_refs(struct got_pathlist_head *their_refs,
2104 struct got_pathlist_head *their_symrefs,
2105 const struct got_remote_repo *remote,
2106 int verbosity, struct got_repository *repo)
2108 const struct got_error *err = NULL, *unlock_err;
2109 struct got_reflist_head my_refs;
2110 struct got_reflist_entry *re;
2111 struct got_pathlist_entry *pe;
2112 char *remote_namespace = NULL;
2113 char *local_refname = NULL;
2115 TAILQ_INIT(&my_refs);
2117 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2118 == -1)
2119 return got_error_from_errno("asprintf");
2121 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2122 if (err)
2123 goto done;
2125 TAILQ_FOREACH(re, &my_refs, entry) {
2126 const char *refname = got_ref_get_name(re->ref);
2127 const char *their_refname;
2129 if (remote->mirror_references) {
2130 their_refname = refname;
2131 } else {
2132 if (strncmp(refname, remote_namespace,
2133 strlen(remote_namespace)) == 0) {
2134 if (strcmp(refname + strlen(remote_namespace),
2135 GOT_REF_HEAD) == 0)
2136 continue;
2137 if (asprintf(&local_refname, "refs/heads/%s",
2138 refname + strlen(remote_namespace)) == -1) {
2139 err = got_error_from_errno("asprintf");
2140 goto done;
2142 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2143 continue;
2145 their_refname = local_refname;
2148 TAILQ_FOREACH(pe, their_refs, entry) {
2149 if (strcmp(their_refname, pe->path) == 0)
2150 break;
2152 if (pe != NULL)
2153 continue;
2155 TAILQ_FOREACH(pe, their_symrefs, entry) {
2156 if (strcmp(their_refname, pe->path) == 0)
2157 break;
2159 if (pe != NULL)
2160 continue;
2162 err = delete_missing_ref(re->ref, verbosity, repo);
2163 if (err)
2164 break;
2166 if (local_refname) {
2167 struct got_reference *ref;
2168 err = got_ref_open(&ref, repo, local_refname, 1);
2169 if (err) {
2170 if (err->code != GOT_ERR_NOT_REF)
2171 break;
2172 free(local_refname);
2173 local_refname = NULL;
2174 continue;
2176 err = delete_missing_ref(ref, verbosity, repo);
2177 if (err)
2178 break;
2179 unlock_err = got_ref_unlock(ref);
2180 got_ref_close(ref);
2181 if (unlock_err && err == NULL) {
2182 err = unlock_err;
2183 break;
2186 free(local_refname);
2187 local_refname = NULL;
2190 done:
2191 free(remote_namespace);
2192 free(local_refname);
2193 return err;
2196 static const struct got_error *
2197 update_wanted_ref(const char *refname, struct got_object_id *id,
2198 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2200 const struct got_error *err, *unlock_err;
2201 char *remote_refname;
2202 struct got_reference *ref;
2204 if (strncmp("refs/", refname, 5) == 0)
2205 refname += 5;
2207 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2208 remote_repo_name, refname) == -1)
2209 return got_error_from_errno("asprintf");
2211 err = got_ref_open(&ref, repo, remote_refname, 1);
2212 if (err) {
2213 if (err->code != GOT_ERR_NOT_REF)
2214 goto done;
2215 err = create_ref(remote_refname, id, verbosity, repo);
2216 } else {
2217 err = update_ref(ref, id, 0, verbosity, repo);
2218 unlock_err = got_ref_unlock(ref);
2219 if (unlock_err && err == NULL)
2220 err = unlock_err;
2221 got_ref_close(ref);
2223 done:
2224 free(remote_refname);
2225 return err;
2228 static const struct got_error *
2229 delete_ref(struct got_repository *repo, struct got_reference *ref)
2231 const struct got_error *err = NULL;
2232 struct got_object_id *id = NULL;
2233 char *id_str = NULL;
2234 const char *target;
2236 if (got_ref_is_symbolic(ref)) {
2237 target = got_ref_get_symref_target(ref);
2238 } else {
2239 err = got_ref_resolve(&id, repo, ref);
2240 if (err)
2241 goto done;
2242 err = got_object_id_str(&id_str, id);
2243 if (err)
2244 goto done;
2245 target = id_str;
2248 err = got_ref_delete(ref, repo);
2249 if (err)
2250 goto done;
2252 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2253 done:
2254 free(id);
2255 free(id_str);
2256 return err;
2259 static const struct got_error *
2260 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2262 const struct got_error *err = NULL;
2263 struct got_reflist_head refs;
2264 struct got_reflist_entry *re;
2265 char *prefix;
2267 TAILQ_INIT(&refs);
2269 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2270 err = got_error_from_errno("asprintf");
2271 goto done;
2273 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2274 if (err)
2275 goto done;
2277 TAILQ_FOREACH(re, &refs, entry)
2278 delete_ref(repo, re->ref);
2279 done:
2280 got_ref_list_free(&refs);
2281 return err;
2284 static const struct got_error *
2285 cmd_fetch(int argc, char *argv[])
2287 const struct got_error *error = NULL, *unlock_err;
2288 char *cwd = NULL, *repo_path = NULL;
2289 const char *remote_name;
2290 char *proto = NULL, *host = NULL, *port = NULL;
2291 char *repo_name = NULL, *server_path = NULL;
2292 const struct got_remote_repo *remotes, *remote = NULL;
2293 int nremotes;
2294 char *id_str = NULL;
2295 struct got_repository *repo = NULL;
2296 struct got_worktree *worktree = NULL;
2297 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2298 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2299 struct got_pathlist_entry *pe;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL;
2308 TAILQ_INIT(&refs);
2309 TAILQ_INIT(&symrefs);
2310 TAILQ_INIT(&wanted_branches);
2311 TAILQ_INIT(&wanted_refs);
2313 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2314 switch (ch) {
2315 case 'a':
2316 fetch_all_branches = 1;
2317 break;
2318 case 'b':
2319 error = got_pathlist_append(&wanted_branches,
2320 optarg, NULL);
2321 if (error)
2322 return error;
2323 break;
2324 case 'd':
2325 delete_refs = 1;
2326 break;
2327 case 'l':
2328 list_refs_only = 1;
2329 break;
2330 case 'r':
2331 repo_path = realpath(optarg, NULL);
2332 if (repo_path == NULL)
2333 return got_error_from_errno2("realpath",
2334 optarg);
2335 got_path_strip_trailing_slashes(repo_path);
2336 break;
2337 case 't':
2338 replace_tags = 1;
2339 break;
2340 case 'v':
2341 if (verbosity < 0)
2342 verbosity = 0;
2343 else if (verbosity < 3)
2344 verbosity++;
2345 break;
2346 case 'q':
2347 verbosity = -1;
2348 break;
2349 case 'R':
2350 error = got_pathlist_append(&wanted_refs,
2351 optarg, NULL);
2352 if (error)
2353 return error;
2354 break;
2355 case 'X':
2356 delete_remote = 1;
2357 break;
2358 default:
2359 usage_fetch();
2360 break;
2363 argc -= optind;
2364 argv += optind;
2366 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2367 option_conflict('a', 'b');
2368 if (list_refs_only) {
2369 if (!TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('l', 'b');
2371 if (fetch_all_branches)
2372 option_conflict('l', 'a');
2373 if (delete_refs)
2374 option_conflict('l', 'd');
2375 if (delete_remote)
2376 option_conflict('l', 'X');
2378 if (delete_remote) {
2379 if (fetch_all_branches)
2380 option_conflict('X', 'a');
2381 if (!TAILQ_EMPTY(&wanted_branches))
2382 option_conflict('X', 'b');
2383 if (delete_refs)
2384 option_conflict('X', 'd');
2385 if (replace_tags)
2386 option_conflict('X', 't');
2387 if (!TAILQ_EMPTY(&wanted_refs))
2388 option_conflict('X', 'R');
2391 if (argc == 0) {
2392 if (delete_remote)
2393 errx(1, "-X option requires a remote name");
2394 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2395 } else if (argc == 1)
2396 remote_name = argv[0];
2397 else
2398 usage_fetch();
2400 cwd = getcwd(NULL, 0);
2401 if (cwd == NULL) {
2402 error = got_error_from_errno("getcwd");
2403 goto done;
2406 error = got_repo_pack_fds_open(&pack_fds);
2407 if (error != NULL)
2408 goto done;
2410 if (repo_path == NULL) {
2411 error = got_worktree_open(&worktree, cwd);
2412 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2413 goto done;
2414 else
2415 error = NULL;
2416 if (worktree) {
2417 repo_path =
2418 strdup(got_worktree_get_repo_path(worktree));
2419 if (repo_path == NULL)
2420 error = got_error_from_errno("strdup");
2421 if (error)
2422 goto done;
2423 } else {
2424 repo_path = strdup(cwd);
2425 if (repo_path == NULL) {
2426 error = got_error_from_errno("strdup");
2427 goto done;
2432 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2433 if (error)
2434 goto done;
2436 if (delete_remote) {
2437 error = delete_refs_for_remote(repo, remote_name);
2438 goto done; /* nothing else to do */
2441 if (worktree) {
2442 worktree_conf = got_worktree_get_gotconfig(worktree);
2443 if (worktree_conf) {
2444 got_gotconfig_get_remotes(&nremotes, &remotes,
2445 worktree_conf);
2446 for (i = 0; i < nremotes; i++) {
2447 if (strcmp(remotes[i].name, remote_name) == 0) {
2448 remote = &remotes[i];
2449 break;
2454 if (remote == NULL) {
2455 repo_conf = got_repo_get_gotconfig(repo);
2456 if (repo_conf) {
2457 got_gotconfig_get_remotes(&nremotes, &remotes,
2458 repo_conf);
2459 for (i = 0; i < nremotes; i++) {
2460 if (strcmp(remotes[i].name, remote_name) == 0) {
2461 remote = &remotes[i];
2462 break;
2467 if (remote == NULL) {
2468 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2469 for (i = 0; i < nremotes; i++) {
2470 if (strcmp(remotes[i].name, remote_name) == 0) {
2471 remote = &remotes[i];
2472 break;
2476 if (remote == NULL) {
2477 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2478 goto done;
2481 if (TAILQ_EMPTY(&wanted_branches)) {
2482 if (!fetch_all_branches)
2483 fetch_all_branches = remote->fetch_all_branches;
2484 for (i = 0; i < remote->nfetch_branches; i++) {
2485 got_pathlist_append(&wanted_branches,
2486 remote->fetch_branches[i], NULL);
2489 if (TAILQ_EMPTY(&wanted_refs)) {
2490 for (i = 0; i < remote->nfetch_refs; i++) {
2491 got_pathlist_append(&wanted_refs,
2492 remote->fetch_refs[i], NULL);
2496 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2497 &repo_name, remote->fetch_url);
2498 if (error)
2499 goto done;
2501 if (strcmp(proto, "git") == 0) {
2502 #ifndef PROFILE
2503 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2504 "sendfd dns inet unveil", NULL) == -1)
2505 err(1, "pledge");
2506 #endif
2507 } else if (strcmp(proto, "git+ssh") == 0 ||
2508 strcmp(proto, "ssh") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "http") == 0 ||
2515 strcmp(proto, "git+http") == 0) {
2516 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2517 goto done;
2518 } else {
2519 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2520 goto done;
2523 error = got_dial_apply_unveil(proto);
2524 if (error)
2525 goto done;
2527 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2528 if (error)
2529 goto done;
2531 if (verbosity >= 0)
2532 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2533 port ? ":" : "", port ? port : "");
2535 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2536 server_path, verbosity);
2537 if (error)
2538 goto done;
2540 fpa.last_scaled_size[0] = '\0';
2541 fpa.last_p_indexed = -1;
2542 fpa.last_p_resolved = -1;
2543 fpa.verbosity = verbosity;
2544 fpa.repo = repo;
2545 fpa.create_configs = 0;
2546 fpa.configs_created = 0;
2547 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2548 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2549 remote->mirror_references, fetch_all_branches, &wanted_branches,
2550 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2551 fetch_progress, &fpa);
2552 if (error)
2553 goto done;
2555 if (list_refs_only) {
2556 error = list_remote_refs(&symrefs, &refs);
2557 goto done;
2560 if (pack_hash == NULL) {
2561 if (verbosity >= 0)
2562 printf("Already up-to-date\n");
2563 } else if (verbosity >= 0) {
2564 error = got_object_id_str(&id_str, pack_hash);
2565 if (error)
2566 goto done;
2567 printf("\nFetched %s.pack\n", id_str);
2568 free(id_str);
2569 id_str = NULL;
2572 /* Update references provided with the pack file. */
2573 TAILQ_FOREACH(pe, &refs, entry) {
2574 const char *refname = pe->path;
2575 struct got_object_id *id = pe->data;
2576 struct got_reference *ref;
2577 char *remote_refname;
2579 if (is_wanted_ref(&wanted_refs, refname) &&
2580 !remote->mirror_references) {
2581 error = update_wanted_ref(refname, id,
2582 remote->name, verbosity, repo);
2583 if (error)
2584 goto done;
2585 continue;
2588 if (remote->mirror_references ||
2589 strncmp("refs/tags/", refname, 10) == 0) {
2590 error = got_ref_open(&ref, repo, refname, 1);
2591 if (error) {
2592 if (error->code != GOT_ERR_NOT_REF)
2593 goto done;
2594 error = create_ref(refname, id, verbosity,
2595 repo);
2596 if (error)
2597 goto done;
2598 } else {
2599 error = update_ref(ref, id, replace_tags,
2600 verbosity, repo);
2601 unlock_err = got_ref_unlock(ref);
2602 if (unlock_err && error == NULL)
2603 error = unlock_err;
2604 got_ref_close(ref);
2605 if (error)
2606 goto done;
2608 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2609 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2610 remote_name, refname + 11) == -1) {
2611 error = got_error_from_errno("asprintf");
2612 goto done;
2615 error = got_ref_open(&ref, repo, remote_refname, 1);
2616 if (error) {
2617 if (error->code != GOT_ERR_NOT_REF)
2618 goto done;
2619 error = create_ref(remote_refname, id,
2620 verbosity, repo);
2621 if (error)
2622 goto done;
2623 } else {
2624 error = update_ref(ref, id, replace_tags,
2625 verbosity, repo);
2626 unlock_err = got_ref_unlock(ref);
2627 if (unlock_err && error == NULL)
2628 error = unlock_err;
2629 got_ref_close(ref);
2630 if (error)
2631 goto done;
2634 /* Also create a local branch if none exists yet. */
2635 error = got_ref_open(&ref, repo, refname, 1);
2636 if (error) {
2637 if (error->code != GOT_ERR_NOT_REF)
2638 goto done;
2639 error = create_ref(refname, id, verbosity,
2640 repo);
2641 if (error)
2642 goto done;
2643 } else {
2644 unlock_err = got_ref_unlock(ref);
2645 if (unlock_err && error == NULL)
2646 error = unlock_err;
2647 got_ref_close(ref);
2651 if (delete_refs) {
2652 error = delete_missing_refs(&refs, &symrefs, remote,
2653 verbosity, repo);
2654 if (error)
2655 goto done;
2658 if (!remote->mirror_references) {
2659 /* Update remote HEAD reference if the server provided one. */
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 struct got_reference *target_ref;
2662 const char *refname = pe->path;
2663 const char *target = pe->data;
2664 char *remote_refname = NULL, *remote_target = NULL;
2666 if (strcmp(refname, GOT_REF_HEAD) != 0)
2667 continue;
2669 if (strncmp("refs/heads/", target, 11) != 0)
2670 continue;
2672 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2673 remote->name, refname) == -1) {
2674 error = got_error_from_errno("asprintf");
2675 goto done;
2677 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2678 remote->name, target + 11) == -1) {
2679 error = got_error_from_errno("asprintf");
2680 free(remote_refname);
2681 goto done;
2684 error = got_ref_open(&target_ref, repo, remote_target,
2685 0);
2686 if (error) {
2687 free(remote_refname);
2688 free(remote_target);
2689 if (error->code == GOT_ERR_NOT_REF) {
2690 error = NULL;
2691 continue;
2693 goto done;
2695 error = update_symref(remote_refname, target_ref,
2696 verbosity, repo);
2697 free(remote_refname);
2698 free(remote_target);
2699 got_ref_close(target_ref);
2700 if (error)
2701 goto done;
2704 done:
2705 if (fetchpid > 0) {
2706 if (kill(fetchpid, SIGTERM) == -1)
2707 error = got_error_from_errno("kill");
2708 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2709 error = got_error_from_errno("waitpid");
2711 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2712 error = got_error_from_errno("close");
2713 if (repo) {
2714 const struct got_error *close_err = got_repo_close(repo);
2715 if (error == NULL)
2716 error = close_err;
2718 if (worktree)
2719 got_worktree_close(worktree);
2720 if (pack_fds) {
2721 const struct got_error *pack_err =
2722 got_repo_pack_fds_close(pack_fds);
2723 if (error == NULL)
2724 error = pack_err;
2726 TAILQ_FOREACH(pe, &refs, entry) {
2727 free((void *)pe->path);
2728 free(pe->data);
2730 got_pathlist_free(&refs);
2731 TAILQ_FOREACH(pe, &symrefs, entry) {
2732 free((void *)pe->path);
2733 free(pe->data);
2735 got_pathlist_free(&symrefs);
2736 got_pathlist_free(&wanted_branches);
2737 got_pathlist_free(&wanted_refs);
2738 free(id_str);
2739 free(cwd);
2740 free(repo_path);
2741 free(pack_hash);
2742 free(proto);
2743 free(host);
2744 free(port);
2745 free(server_path);
2746 free(repo_name);
2747 return error;
2751 __dead static void
2752 usage_checkout(void)
2754 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2755 "[-p prefix] [-q] repository-path [worktree-path]\n",
2756 getprogname());
2757 exit(1);
2760 static void
2761 show_worktree_base_ref_warning(void)
2763 fprintf(stderr, "%s: warning: could not create a reference "
2764 "to the work tree's base commit; the commit could be "
2765 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2766 "repository writable and running 'got update' will prevent this\n",
2767 getprogname());
2770 struct got_checkout_progress_arg {
2771 const char *worktree_path;
2772 int had_base_commit_ref_error;
2773 int verbosity;
2776 static const struct got_error *
2777 checkout_progress(void *arg, unsigned char status, const char *path)
2779 struct got_checkout_progress_arg *a = arg;
2781 /* Base commit bump happens silently. */
2782 if (status == GOT_STATUS_BUMP_BASE)
2783 return NULL;
2785 if (status == GOT_STATUS_BASE_REF_ERR) {
2786 a->had_base_commit_ref_error = 1;
2787 return NULL;
2790 while (path[0] == '/')
2791 path++;
2793 if (a->verbosity >= 0)
2794 printf("%c %s/%s\n", status, a->worktree_path, path);
2796 return NULL;
2799 static const struct got_error *
2800 check_cancelled(void *arg)
2802 if (sigint_received || sigpipe_received)
2803 return got_error(GOT_ERR_CANCELLED);
2804 return NULL;
2807 static const struct got_error *
2808 check_linear_ancestry(struct got_object_id *commit_id,
2809 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2810 struct got_repository *repo)
2812 const struct got_error *err = NULL;
2813 struct got_object_id *yca_id;
2815 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2816 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2817 if (err)
2818 return err;
2820 if (yca_id == NULL)
2821 return got_error(GOT_ERR_ANCESTRY);
2824 * Require a straight line of history between the target commit
2825 * and the work tree's base commit.
2827 * Non-linear situations such as this require a rebase:
2829 * (commit) D F (base_commit)
2830 * \ /
2831 * C E
2832 * \ /
2833 * B (yca)
2834 * |
2835 * A
2837 * 'got update' only handles linear cases:
2838 * Update forwards in time: A (base/yca) - B - C - D (commit)
2839 * Update backwards in time: D (base) - C - B - A (commit/yca)
2841 if (allow_forwards_in_time_only) {
2842 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2843 return got_error(GOT_ERR_ANCESTRY);
2844 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2845 got_object_id_cmp(base_commit_id, yca_id) != 0)
2846 return got_error(GOT_ERR_ANCESTRY);
2848 free(yca_id);
2849 return NULL;
2852 static const struct got_error *
2853 check_same_branch(struct got_object_id *commit_id,
2854 struct got_reference *head_ref, struct got_object_id *yca_id,
2855 struct got_repository *repo)
2857 const struct got_error *err = NULL;
2858 struct got_commit_graph *graph = NULL;
2859 struct got_object_id *head_commit_id = NULL;
2860 int is_same_branch = 0;
2862 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2863 if (err)
2864 goto done;
2866 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2870 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2871 is_same_branch = 1;
2872 goto done;
2875 err = got_commit_graph_open(&graph, "/", 1);
2876 if (err)
2877 goto done;
2879 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2880 check_cancelled, NULL);
2881 if (err)
2882 goto done;
2884 for (;;) {
2885 struct got_object_id *id;
2886 err = got_commit_graph_iter_next(&id, graph, repo,
2887 check_cancelled, NULL);
2888 if (err) {
2889 if (err->code == GOT_ERR_ITER_COMPLETED)
2890 err = NULL;
2891 break;
2894 if (id) {
2895 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2896 break;
2897 if (got_object_id_cmp(id, commit_id) == 0) {
2898 is_same_branch = 1;
2899 break;
2903 done:
2904 if (graph)
2905 got_commit_graph_close(graph);
2906 free(head_commit_id);
2907 if (!err && !is_same_branch)
2908 err = got_error(GOT_ERR_ANCESTRY);
2909 return err;
2912 static const struct got_error *
2913 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2915 static char msg[512];
2916 const char *branch_name;
2918 if (got_ref_is_symbolic(ref))
2919 branch_name = got_ref_get_symref_target(ref);
2920 else
2921 branch_name = got_ref_get_name(ref);
2923 if (strncmp("refs/heads/", branch_name, 11) == 0)
2924 branch_name += 11;
2926 snprintf(msg, sizeof(msg),
2927 "target commit is not contained in branch '%s'; "
2928 "the branch to use must be specified with -b; "
2929 "if necessary a new branch can be created for "
2930 "this commit with 'got branch -c %s BRANCH_NAME'",
2931 branch_name, commit_id_str);
2933 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2936 static const struct got_error *
2937 cmd_checkout(int argc, char *argv[])
2939 const struct got_error *error = NULL;
2940 struct got_repository *repo = NULL;
2941 struct got_reference *head_ref = NULL, *ref = NULL;
2942 struct got_worktree *worktree = NULL;
2943 char *repo_path = NULL;
2944 char *worktree_path = NULL;
2945 const char *path_prefix = "";
2946 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2947 char *commit_id_str = NULL;
2948 struct got_object_id *commit_id = NULL;
2949 char *cwd = NULL;
2950 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2951 struct got_pathlist_head paths;
2952 struct got_checkout_progress_arg cpa;
2953 int *pack_fds = NULL;
2955 TAILQ_INIT(&paths);
2957 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2958 switch (ch) {
2959 case 'b':
2960 branch_name = optarg;
2961 break;
2962 case 'c':
2963 commit_id_str = strdup(optarg);
2964 if (commit_id_str == NULL)
2965 return got_error_from_errno("strdup");
2966 break;
2967 case 'E':
2968 allow_nonempty = 1;
2969 break;
2970 case 'p':
2971 path_prefix = optarg;
2972 break;
2973 case 'q':
2974 verbosity = -1;
2975 break;
2976 default:
2977 usage_checkout();
2978 /* NOTREACHED */
2982 argc -= optind;
2983 argv += optind;
2985 #ifndef PROFILE
2986 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2987 "unveil", NULL) == -1)
2988 err(1, "pledge");
2989 #endif
2990 if (argc == 1) {
2991 char *base, *dotgit;
2992 const char *path;
2993 repo_path = realpath(argv[0], NULL);
2994 if (repo_path == NULL)
2995 return got_error_from_errno2("realpath", argv[0]);
2996 cwd = getcwd(NULL, 0);
2997 if (cwd == NULL) {
2998 error = got_error_from_errno("getcwd");
2999 goto done;
3001 if (path_prefix[0])
3002 path = path_prefix;
3003 else
3004 path = repo_path;
3005 error = got_path_basename(&base, path);
3006 if (error)
3007 goto done;
3008 dotgit = strstr(base, ".git");
3009 if (dotgit)
3010 *dotgit = '\0';
3011 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3012 error = got_error_from_errno("asprintf");
3013 free(base);
3014 goto done;
3016 free(base);
3017 } else if (argc == 2) {
3018 repo_path = realpath(argv[0], NULL);
3019 if (repo_path == NULL) {
3020 error = got_error_from_errno2("realpath", argv[0]);
3021 goto done;
3023 worktree_path = realpath(argv[1], NULL);
3024 if (worktree_path == NULL) {
3025 if (errno != ENOENT) {
3026 error = got_error_from_errno2("realpath",
3027 argv[1]);
3028 goto done;
3030 worktree_path = strdup(argv[1]);
3031 if (worktree_path == NULL) {
3032 error = got_error_from_errno("strdup");
3033 goto done;
3036 } else
3037 usage_checkout();
3039 got_path_strip_trailing_slashes(repo_path);
3040 got_path_strip_trailing_slashes(worktree_path);
3042 error = got_repo_pack_fds_open(&pack_fds);
3043 if (error != NULL)
3044 goto done;
3046 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3047 if (error != NULL)
3048 goto done;
3050 /* Pre-create work tree path for unveil(2) */
3051 error = got_path_mkdir(worktree_path);
3052 if (error) {
3053 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3054 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3055 goto done;
3056 if (!allow_nonempty &&
3057 !got_path_dir_is_empty(worktree_path)) {
3058 error = got_error_path(worktree_path,
3059 GOT_ERR_DIR_NOT_EMPTY);
3060 goto done;
3064 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3065 if (error)
3066 goto done;
3068 error = got_ref_open(&head_ref, repo, branch_name, 0);
3069 if (error != NULL)
3070 goto done;
3072 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3073 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3074 goto done;
3076 error = got_worktree_open(&worktree, worktree_path);
3077 if (error != NULL)
3078 goto done;
3080 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3081 path_prefix);
3082 if (error != NULL)
3083 goto done;
3084 if (!same_path_prefix) {
3085 error = got_error(GOT_ERR_PATH_PREFIX);
3086 goto done;
3089 if (commit_id_str) {
3090 struct got_reflist_head refs;
3091 TAILQ_INIT(&refs);
3092 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3093 NULL);
3094 if (error)
3095 goto done;
3096 error = got_repo_match_object_id(&commit_id, NULL,
3097 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3098 got_ref_list_free(&refs);
3099 if (error)
3100 goto done;
3101 error = check_linear_ancestry(commit_id,
3102 got_worktree_get_base_commit_id(worktree), 0, repo);
3103 if (error != NULL) {
3104 if (error->code == GOT_ERR_ANCESTRY) {
3105 error = checkout_ancestry_error(
3106 head_ref, commit_id_str);
3108 goto done;
3110 error = check_same_branch(commit_id, head_ref, NULL, repo);
3111 if (error) {
3112 if (error->code == GOT_ERR_ANCESTRY) {
3113 error = checkout_ancestry_error(
3114 head_ref, commit_id_str);
3116 goto done;
3118 error = got_worktree_set_base_commit_id(worktree, repo,
3119 commit_id);
3120 if (error)
3121 goto done;
3122 /* Expand potentially abbreviated commit ID string. */
3123 free(commit_id_str);
3124 error = got_object_id_str(&commit_id_str, commit_id);
3125 if (error)
3126 goto done;
3127 } else {
3128 commit_id = got_object_id_dup(
3129 got_worktree_get_base_commit_id(worktree));
3130 if (commit_id == NULL) {
3131 error = got_error_from_errno("got_object_id_dup");
3132 goto done;
3134 error = got_object_id_str(&commit_id_str, commit_id);
3135 if (error)
3136 goto done;
3139 error = got_pathlist_append(&paths, "", NULL);
3140 if (error)
3141 goto done;
3142 cpa.worktree_path = worktree_path;
3143 cpa.had_base_commit_ref_error = 0;
3144 cpa.verbosity = verbosity;
3145 error = got_worktree_checkout_files(worktree, &paths, repo,
3146 checkout_progress, &cpa, check_cancelled, NULL);
3147 if (error != NULL)
3148 goto done;
3150 if (got_ref_is_symbolic(head_ref)) {
3151 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3152 if (error)
3153 goto done;
3154 refname = got_ref_get_name(ref);
3155 } else
3156 refname = got_ref_get_name(head_ref);
3157 printf("Checked out %s: %s\n", refname, commit_id_str);
3158 printf("Now shut up and hack\n");
3159 if (cpa.had_base_commit_ref_error)
3160 show_worktree_base_ref_warning();
3161 done:
3162 if (pack_fds) {
3163 const struct got_error *pack_err =
3164 got_repo_pack_fds_close(pack_fds);
3165 if (error == NULL)
3166 error = pack_err;
3168 if (head_ref)
3169 got_ref_close(head_ref);
3170 if (ref)
3171 got_ref_close(ref);
3172 got_pathlist_free(&paths);
3173 free(commit_id_str);
3174 free(commit_id);
3175 free(repo_path);
3176 free(worktree_path);
3177 free(cwd);
3178 return error;
3181 struct got_update_progress_arg {
3182 int did_something;
3183 int conflicts;
3184 int obstructed;
3185 int not_updated;
3186 int missing;
3187 int not_deleted;
3188 int unversioned;
3189 int verbosity;
3192 static void
3193 print_update_progress_stats(struct got_update_progress_arg *upa)
3195 if (!upa->did_something)
3196 return;
3198 if (upa->conflicts > 0)
3199 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3200 if (upa->obstructed > 0)
3201 printf("File paths obstructed by a non-regular file: %d\n",
3202 upa->obstructed);
3203 if (upa->not_updated > 0)
3204 printf("Files not updated because of existing merge "
3205 "conflicts: %d\n", upa->not_updated);
3209 * The meaning of some status codes differs between merge-style operations and
3210 * update operations. For example, the ! status code means "file was missing"
3211 * if changes were merged into the work tree, and "missing file was restored"
3212 * if the work tree was updated. This function should be used by any operation
3213 * which merges changes into the work tree without updating the work tree.
3215 static void
3216 print_merge_progress_stats(struct got_update_progress_arg *upa)
3218 if (!upa->did_something)
3219 return;
3221 if (upa->conflicts > 0)
3222 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3223 if (upa->obstructed > 0)
3224 printf("File paths obstructed by a non-regular file: %d\n",
3225 upa->obstructed);
3226 if (upa->missing > 0)
3227 printf("Files which had incoming changes but could not be "
3228 "found in the work tree: %d\n", upa->missing);
3229 if (upa->not_deleted > 0)
3230 printf("Files not deleted due to differences in deleted "
3231 "content: %d\n", upa->not_deleted);
3232 if (upa->unversioned > 0)
3233 printf("Files not merged because an unversioned file was "
3234 "found in the work tree: %d\n", upa->unversioned);
3237 __dead static void
3238 usage_update(void)
3240 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3241 "[path ...]\n",
3242 getprogname());
3243 exit(1);
3246 static const struct got_error *
3247 update_progress(void *arg, unsigned char status, const char *path)
3249 struct got_update_progress_arg *upa = arg;
3251 if (status == GOT_STATUS_EXISTS ||
3252 status == GOT_STATUS_BASE_REF_ERR)
3253 return NULL;
3255 upa->did_something = 1;
3257 /* Base commit bump happens silently. */
3258 if (status == GOT_STATUS_BUMP_BASE)
3259 return NULL;
3261 if (status == GOT_STATUS_CONFLICT)
3262 upa->conflicts++;
3263 if (status == GOT_STATUS_OBSTRUCTED)
3264 upa->obstructed++;
3265 if (status == GOT_STATUS_CANNOT_UPDATE)
3266 upa->not_updated++;
3267 if (status == GOT_STATUS_MISSING)
3268 upa->missing++;
3269 if (status == GOT_STATUS_CANNOT_DELETE)
3270 upa->not_deleted++;
3271 if (status == GOT_STATUS_UNVERSIONED)
3272 upa->unversioned++;
3274 while (path[0] == '/')
3275 path++;
3276 if (upa->verbosity >= 0)
3277 printf("%c %s\n", status, path);
3279 return NULL;
3282 static const struct got_error *
3283 switch_head_ref(struct got_reference *head_ref,
3284 struct got_object_id *commit_id, struct got_worktree *worktree,
3285 struct got_repository *repo)
3287 const struct got_error *err = NULL;
3288 char *base_id_str;
3289 int ref_has_moved = 0;
3291 /* Trivial case: switching between two different references. */
3292 if (strcmp(got_ref_get_name(head_ref),
3293 got_worktree_get_head_ref_name(worktree)) != 0) {
3294 printf("Switching work tree from %s to %s\n",
3295 got_worktree_get_head_ref_name(worktree),
3296 got_ref_get_name(head_ref));
3297 return got_worktree_set_head_ref(worktree, head_ref);
3300 err = check_linear_ancestry(commit_id,
3301 got_worktree_get_base_commit_id(worktree), 0, repo);
3302 if (err) {
3303 if (err->code != GOT_ERR_ANCESTRY)
3304 return err;
3305 ref_has_moved = 1;
3307 if (!ref_has_moved)
3308 return NULL;
3310 /* Switching to a rebased branch with the same reference name. */
3311 err = got_object_id_str(&base_id_str,
3312 got_worktree_get_base_commit_id(worktree));
3313 if (err)
3314 return err;
3315 printf("Reference %s now points at a different branch\n",
3316 got_worktree_get_head_ref_name(worktree));
3317 printf("Switching work tree from %s to %s\n", base_id_str,
3318 got_worktree_get_head_ref_name(worktree));
3319 return NULL;
3322 static const struct got_error *
3323 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3325 const struct got_error *err;
3326 int in_progress;
3328 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_REBASING);
3334 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3335 if (err)
3336 return err;
3337 if (in_progress)
3338 return got_error(GOT_ERR_HISTEDIT_BUSY);
3340 return NULL;
3343 static const struct got_error *
3344 check_merge_in_progress(struct got_worktree *worktree,
3345 struct got_repository *repo)
3347 const struct got_error *err;
3348 int in_progress;
3350 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3351 if (err)
3352 return err;
3353 if (in_progress)
3354 return got_error(GOT_ERR_MERGE_BUSY);
3356 return NULL;
3359 static const struct got_error *
3360 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3361 char *argv[], struct got_worktree *worktree)
3363 const struct got_error *err = NULL;
3364 char *path;
3365 struct got_pathlist_entry *new;
3366 int i;
3368 if (argc == 0) {
3369 path = strdup("");
3370 if (path == NULL)
3371 return got_error_from_errno("strdup");
3372 return got_pathlist_append(paths, path, NULL);
3375 for (i = 0; i < argc; i++) {
3376 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3377 if (err)
3378 break;
3379 err = got_pathlist_insert(&new, paths, path, NULL);
3380 if (err || new == NULL /* duplicate */) {
3381 free(path);
3382 if (err)
3383 break;
3387 return err;
3390 static const struct got_error *
3391 wrap_not_worktree_error(const struct got_error *orig_err,
3392 const char *cmdname, const char *path)
3394 const struct got_error *err;
3395 struct got_repository *repo;
3396 static char msg[512];
3397 int *pack_fds = NULL;
3399 err = got_repo_pack_fds_open(&pack_fds);
3400 if (err)
3401 return err;
3403 err = got_repo_open(&repo, path, NULL, pack_fds);
3404 if (err)
3405 return orig_err;
3407 snprintf(msg, sizeof(msg),
3408 "'got %s' needs a work tree in addition to a git repository\n"
3409 "Work trees can be checked out from this Git repository with "
3410 "'got checkout'.\n"
3411 "The got(1) manual page contains more information.", cmdname);
3412 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3413 got_repo_close(repo);
3414 if (pack_fds) {
3415 const struct got_error *pack_err =
3416 got_repo_pack_fds_close(pack_fds);
3417 if (err == NULL)
3418 err = pack_err;
3420 return err;
3423 static const struct got_error *
3424 cmd_update(int argc, char *argv[])
3426 const struct got_error *error = NULL;
3427 struct got_repository *repo = NULL;
3428 struct got_worktree *worktree = NULL;
3429 char *worktree_path = NULL;
3430 struct got_object_id *commit_id = NULL;
3431 char *commit_id_str = NULL;
3432 const char *branch_name = NULL;
3433 struct got_reference *head_ref = NULL;
3434 struct got_pathlist_head paths;
3435 struct got_pathlist_entry *pe;
3436 int ch, verbosity = 0;
3437 struct got_update_progress_arg upa;
3438 int *pack_fds = NULL;
3440 TAILQ_INIT(&paths);
3442 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3443 switch (ch) {
3444 case 'b':
3445 branch_name = optarg;
3446 break;
3447 case 'c':
3448 commit_id_str = strdup(optarg);
3449 if (commit_id_str == NULL)
3450 return got_error_from_errno("strdup");
3451 break;
3452 case 'q':
3453 verbosity = -1;
3454 break;
3455 default:
3456 usage_update();
3457 /* NOTREACHED */
3461 argc -= optind;
3462 argv += optind;
3464 #ifndef PROFILE
3465 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3466 "unveil", NULL) == -1)
3467 err(1, "pledge");
3468 #endif
3469 worktree_path = getcwd(NULL, 0);
3470 if (worktree_path == NULL) {
3471 error = got_error_from_errno("getcwd");
3472 goto done;
3475 error = got_repo_pack_fds_open(&pack_fds);
3476 if (error != NULL)
3477 goto done;
3479 error = got_worktree_open(&worktree, worktree_path);
3480 if (error) {
3481 if (error->code == GOT_ERR_NOT_WORKTREE)
3482 error = wrap_not_worktree_error(error, "update",
3483 worktree_path);
3484 goto done;
3487 error = check_rebase_or_histedit_in_progress(worktree);
3488 if (error)
3489 goto done;
3491 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3492 NULL, pack_fds);
3493 if (error != NULL)
3494 goto done;
3496 error = apply_unveil(got_repo_get_path(repo), 0,
3497 got_worktree_get_root_path(worktree));
3498 if (error)
3499 goto done;
3501 error = check_merge_in_progress(worktree, repo);
3502 if (error)
3503 goto done;
3505 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3506 if (error)
3507 goto done;
3509 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3510 got_worktree_get_head_ref_name(worktree), 0);
3511 if (error != NULL)
3512 goto done;
3513 if (commit_id_str == NULL) {
3514 error = got_ref_resolve(&commit_id, repo, head_ref);
3515 if (error != NULL)
3516 goto done;
3517 error = got_object_id_str(&commit_id_str, commit_id);
3518 if (error != NULL)
3519 goto done;
3520 } else {
3521 struct got_reflist_head refs;
3522 TAILQ_INIT(&refs);
3523 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3524 NULL);
3525 if (error)
3526 goto done;
3527 error = got_repo_match_object_id(&commit_id, NULL,
3528 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3529 got_ref_list_free(&refs);
3530 free(commit_id_str);
3531 commit_id_str = NULL;
3532 if (error)
3533 goto done;
3534 error = got_object_id_str(&commit_id_str, commit_id);
3535 if (error)
3536 goto done;
3539 if (branch_name) {
3540 struct got_object_id *head_commit_id;
3541 TAILQ_FOREACH(pe, &paths, entry) {
3542 if (pe->path_len == 0)
3543 continue;
3544 error = got_error_msg(GOT_ERR_BAD_PATH,
3545 "switching between branches requires that "
3546 "the entire work tree gets updated");
3547 goto done;
3549 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3550 if (error)
3551 goto done;
3552 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3553 repo);
3554 free(head_commit_id);
3555 if (error != NULL)
3556 goto done;
3557 error = check_same_branch(commit_id, head_ref, NULL, repo);
3558 if (error)
3559 goto done;
3560 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3561 if (error)
3562 goto done;
3563 } else {
3564 error = check_linear_ancestry(commit_id,
3565 got_worktree_get_base_commit_id(worktree), 0, repo);
3566 if (error != NULL) {
3567 if (error->code == GOT_ERR_ANCESTRY)
3568 error = got_error(GOT_ERR_BRANCH_MOVED);
3569 goto done;
3571 error = check_same_branch(commit_id, head_ref, NULL, repo);
3572 if (error)
3573 goto done;
3576 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3577 commit_id) != 0) {
3578 error = got_worktree_set_base_commit_id(worktree, repo,
3579 commit_id);
3580 if (error)
3581 goto done;
3584 memset(&upa, 0, sizeof(upa));
3585 upa.verbosity = verbosity;
3586 error = got_worktree_checkout_files(worktree, &paths, repo,
3587 update_progress, &upa, check_cancelled, NULL);
3588 if (error != NULL)
3589 goto done;
3591 if (upa.did_something) {
3592 printf("Updated to %s: %s\n",
3593 got_worktree_get_head_ref_name(worktree), commit_id_str);
3594 } else
3595 printf("Already up-to-date\n");
3597 print_update_progress_stats(&upa);
3598 done:
3599 if (pack_fds) {
3600 const struct got_error *pack_err =
3601 got_repo_pack_fds_close(pack_fds);
3602 if (error == NULL)
3603 error = pack_err;
3605 free(worktree_path);
3606 TAILQ_FOREACH(pe, &paths, entry)
3607 free((char *)pe->path);
3608 got_pathlist_free(&paths);
3609 free(commit_id);
3610 free(commit_id_str);
3611 return error;
3614 static const struct got_error *
3615 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3616 const char *path, int diff_context, int ignore_whitespace,
3617 int force_text_diff, struct got_repository *repo, FILE *outfile)
3619 const struct got_error *err = NULL;
3620 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3621 FILE *f1 = NULL, *f2 = NULL;
3622 int fd1 = -1, fd2 = -1;
3624 fd1 = got_opentempfd();
3625 if (fd1 == -1)
3626 return got_error_from_errno("got_opentempfd");
3627 fd2 = got_opentempfd();
3628 if (fd2 == -1) {
3629 err = got_error_from_errno("got_opentempfd");
3630 goto done;
3633 if (blob_id1) {
3634 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3635 fd1);
3636 if (err)
3637 goto done;
3640 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3641 if (err)
3642 goto done;
3644 f1 = got_opentemp();
3645 if (f1 == NULL) {
3646 err = got_error_from_errno("got_opentemp");
3647 goto done;
3649 f2 = got_opentemp();
3650 if (f2 == NULL) {
3651 err = got_error_from_errno("got_opentemp");
3652 goto done;
3655 while (path[0] == '/')
3656 path++;
3657 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3658 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3659 force_text_diff, outfile);
3660 done:
3661 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3662 err = got_error_from_errno("close");
3663 if (blob1)
3664 got_object_blob_close(blob1);
3665 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3666 err = got_error_from_errno("close");
3667 got_object_blob_close(blob2);
3668 if (f1 && fclose(f1) == EOF && err == NULL)
3669 err = got_error_from_errno("fclose");
3670 if (f2 && fclose(f2) == EOF && err == NULL)
3671 err = got_error_from_errno("fclose");
3672 return err;
3675 static const struct got_error *
3676 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3677 const char *path, int diff_context, int ignore_whitespace,
3678 int force_text_diff, struct got_repository *repo, FILE *outfile)
3680 const struct got_error *err = NULL;
3681 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3682 struct got_diff_blob_output_unidiff_arg arg;
3683 FILE *f1 = NULL, *f2 = NULL;
3684 int fd1 = -1, fd2 = -1;
3686 if (tree_id1) {
3687 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3688 if (err)
3689 goto done;
3690 fd1 = got_opentempfd();
3691 if (fd1 == -1) {
3692 err = got_error_from_errno("got_opentempfd");
3693 goto done;
3697 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3698 if (err)
3699 goto done;
3701 f1 = got_opentemp();
3702 if (f1 == NULL) {
3703 err = got_error_from_errno("got_opentemp");
3704 goto done;
3707 f2 = got_opentemp();
3708 if (f2 == NULL) {
3709 err = got_error_from_errno("got_opentemp");
3710 goto done;
3712 fd2 = got_opentempfd();
3713 if (fd2 == -1) {
3714 err = got_error_from_errno("got_opentempfd");
3715 goto done;
3717 arg.diff_context = diff_context;
3718 arg.ignore_whitespace = ignore_whitespace;
3719 arg.force_text_diff = force_text_diff;
3720 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3721 arg.outfile = outfile;
3722 arg.line_offsets = NULL;
3723 arg.nlines = 0;
3724 while (path[0] == '/')
3725 path++;
3726 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3727 got_diff_blob_output_unidiff, &arg, 1);
3728 done:
3729 if (tree1)
3730 got_object_tree_close(tree1);
3731 if (tree2)
3732 got_object_tree_close(tree2);
3733 if (f1 && fclose(f1) == EOF && err == NULL)
3734 err = got_error_from_errno("fclose");
3735 if (f2 && fclose(f2) == EOF && err == NULL)
3736 err = got_error_from_errno("fclose");
3737 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3738 err = got_error_from_errno("close");
3739 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3740 err = got_error_from_errno("close");
3741 return err;
3744 static const struct got_error *
3745 get_changed_paths(struct got_pathlist_head *paths,
3746 struct got_commit_object *commit, struct got_repository *repo)
3748 const struct got_error *err = NULL;
3749 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3750 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3751 struct got_object_qid *qid;
3753 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3754 if (qid != NULL) {
3755 struct got_commit_object *pcommit;
3756 err = got_object_open_as_commit(&pcommit, repo,
3757 &qid->id);
3758 if (err)
3759 return err;
3761 tree_id1 = got_object_id_dup(
3762 got_object_commit_get_tree_id(pcommit));
3763 if (tree_id1 == NULL) {
3764 got_object_commit_close(pcommit);
3765 return got_error_from_errno("got_object_id_dup");
3767 got_object_commit_close(pcommit);
3771 if (tree_id1) {
3772 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3773 if (err)
3774 goto done;
3777 tree_id2 = got_object_commit_get_tree_id(commit);
3778 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3779 if (err)
3780 goto done;
3782 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3783 got_diff_tree_collect_changed_paths, paths, 0);
3784 done:
3785 if (tree1)
3786 got_object_tree_close(tree1);
3787 if (tree2)
3788 got_object_tree_close(tree2);
3789 free(tree_id1);
3790 return err;
3793 static const struct got_error *
3794 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3795 const char *path, int diff_context, struct got_repository *repo,
3796 FILE *outfile)
3798 const struct got_error *err = NULL;
3799 struct got_commit_object *pcommit = NULL;
3800 char *id_str1 = NULL, *id_str2 = NULL;
3801 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3802 struct got_object_qid *qid;
3804 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3805 if (qid != NULL) {
3806 err = got_object_open_as_commit(&pcommit, repo,
3807 &qid->id);
3808 if (err)
3809 return err;
3810 err = got_object_id_str(&id_str1, &qid->id);
3811 if (err)
3812 goto done;
3815 err = got_object_id_str(&id_str2, id);
3816 if (err)
3817 goto done;
3819 if (path && path[0] != '\0') {
3820 int obj_type;
3821 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3822 if (err)
3823 goto done;
3824 if (pcommit) {
3825 err = got_object_id_by_path(&obj_id1, repo,
3826 pcommit, path);
3827 if (err) {
3828 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3829 free(obj_id2);
3830 goto done;
3834 err = got_object_get_type(&obj_type, repo, obj_id2);
3835 if (err) {
3836 free(obj_id2);
3837 goto done;
3839 fprintf(outfile,
3840 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3841 fprintf(outfile, "commit - %s\n",
3842 id_str1 ? id_str1 : "/dev/null");
3843 fprintf(outfile, "commit + %s\n", id_str2);
3844 switch (obj_type) {
3845 case GOT_OBJ_TYPE_BLOB:
3846 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3847 0, 0, repo, outfile);
3848 break;
3849 case GOT_OBJ_TYPE_TREE:
3850 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3851 0, 0, repo, outfile);
3852 break;
3853 default:
3854 err = got_error(GOT_ERR_OBJ_TYPE);
3855 break;
3857 free(obj_id1);
3858 free(obj_id2);
3859 } else {
3860 obj_id2 = got_object_commit_get_tree_id(commit);
3861 if (pcommit)
3862 obj_id1 = got_object_commit_get_tree_id(pcommit);
3863 fprintf(outfile,
3864 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3865 fprintf(outfile, "commit - %s\n",
3866 id_str1 ? id_str1 : "/dev/null");
3867 fprintf(outfile, "commit + %s\n", id_str2);
3868 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3869 repo, outfile);
3871 done:
3872 free(id_str1);
3873 free(id_str2);
3874 if (pcommit)
3875 got_object_commit_close(pcommit);
3876 return err;
3879 static char *
3880 get_datestr(time_t *time, char *datebuf)
3882 struct tm mytm, *tm;
3883 char *p, *s;
3885 tm = gmtime_r(time, &mytm);
3886 if (tm == NULL)
3887 return NULL;
3888 s = asctime_r(tm, datebuf);
3889 if (s == NULL)
3890 return NULL;
3891 p = strchr(s, '\n');
3892 if (p)
3893 *p = '\0';
3894 return s;
3897 static const struct got_error *
3898 match_commit(int *have_match, struct got_object_id *id,
3899 struct got_commit_object *commit, regex_t *regex)
3901 const struct got_error *err = NULL;
3902 regmatch_t regmatch;
3903 char *id_str = NULL, *logmsg = NULL;
3905 *have_match = 0;
3907 err = got_object_id_str(&id_str, id);
3908 if (err)
3909 return err;
3911 err = got_object_commit_get_logmsg(&logmsg, commit);
3912 if (err)
3913 goto done;
3915 if (regexec(regex, got_object_commit_get_author(commit), 1,
3916 &regmatch, 0) == 0 ||
3917 regexec(regex, got_object_commit_get_committer(commit), 1,
3918 &regmatch, 0) == 0 ||
3919 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3920 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3921 *have_match = 1;
3922 done:
3923 free(id_str);
3924 free(logmsg);
3925 return err;
3928 static void
3929 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3930 regex_t *regex)
3932 regmatch_t regmatch;
3933 struct got_pathlist_entry *pe;
3935 *have_match = 0;
3937 TAILQ_FOREACH(pe, changed_paths, entry) {
3938 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3939 *have_match = 1;
3940 break;
3945 static const struct got_error *
3946 match_patch(int *have_match, struct got_commit_object *commit,
3947 struct got_object_id *id, const char *path, int diff_context,
3948 struct got_repository *repo, regex_t *regex, FILE *f)
3950 const struct got_error *err = NULL;
3951 char *line = NULL;
3952 size_t linesize = 0;
3953 ssize_t linelen;
3954 regmatch_t regmatch;
3956 *have_match = 0;
3958 err = got_opentemp_truncate(f);
3959 if (err)
3960 return err;
3962 err = print_patch(commit, id, path, diff_context, repo, f);
3963 if (err)
3964 goto done;
3966 if (fseeko(f, 0L, SEEK_SET) == -1) {
3967 err = got_error_from_errno("fseeko");
3968 goto done;
3971 while ((linelen = getline(&line, &linesize, f)) != -1) {
3972 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3973 *have_match = 1;
3974 break;
3977 done:
3978 free(line);
3979 return err;
3982 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3984 static const struct got_error*
3985 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3986 struct got_object_id *id, struct got_repository *repo,
3987 int local_only)
3989 static const struct got_error *err = NULL;
3990 struct got_reflist_entry *re;
3991 char *s;
3992 const char *name;
3994 *refs_str = NULL;
3996 TAILQ_FOREACH(re, refs, entry) {
3997 struct got_tag_object *tag = NULL;
3998 struct got_object_id *ref_id;
3999 int cmp;
4001 name = got_ref_get_name(re->ref);
4002 if (strcmp(name, GOT_REF_HEAD) == 0)
4003 continue;
4004 if (strncmp(name, "refs/", 5) == 0)
4005 name += 5;
4006 if (strncmp(name, "got/", 4) == 0)
4007 continue;
4008 if (strncmp(name, "heads/", 6) == 0)
4009 name += 6;
4010 if (strncmp(name, "remotes/", 8) == 0) {
4011 if (local_only)
4012 continue;
4013 name += 8;
4014 s = strstr(name, "/" GOT_REF_HEAD);
4015 if (s != NULL && s[strlen(s)] == '\0')
4016 continue;
4018 err = got_ref_resolve(&ref_id, repo, re->ref);
4019 if (err)
4020 break;
4021 if (strncmp(name, "tags/", 5) == 0) {
4022 err = got_object_open_as_tag(&tag, repo, ref_id);
4023 if (err) {
4024 if (err->code != GOT_ERR_OBJ_TYPE) {
4025 free(ref_id);
4026 break;
4028 /* Ref points at something other than a tag. */
4029 err = NULL;
4030 tag = NULL;
4033 cmp = got_object_id_cmp(tag ?
4034 got_object_tag_get_object_id(tag) : ref_id, id);
4035 free(ref_id);
4036 if (tag)
4037 got_object_tag_close(tag);
4038 if (cmp != 0)
4039 continue;
4040 s = *refs_str;
4041 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4042 s ? ", " : "", name) == -1) {
4043 err = got_error_from_errno("asprintf");
4044 free(s);
4045 *refs_str = NULL;
4046 break;
4048 free(s);
4051 return err;
4054 static const struct got_error *
4055 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4056 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4058 const struct got_error *err = NULL;
4059 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4060 char *comma, *s, *nl;
4061 struct got_reflist_head *refs;
4062 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4063 struct tm tm;
4064 time_t committer_time;
4066 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4067 if (refs) {
4068 err = build_refs_str(&ref_str, refs, id, repo, 1);
4069 if (err)
4070 return err;
4072 /* Display the first matching ref only. */
4073 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4074 *comma = '\0';
4077 if (ref_str == NULL) {
4078 err = got_object_id_str(&id_str, id);
4079 if (err)
4080 return err;
4083 committer_time = got_object_commit_get_committer_time(commit);
4084 if (gmtime_r(&committer_time, &tm) == NULL) {
4085 err = got_error_from_errno("gmtime_r");
4086 goto done;
4088 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4089 err = got_error(GOT_ERR_NO_SPACE);
4090 goto done;
4093 err = got_object_commit_get_logmsg(&logmsg0, commit);
4094 if (err)
4095 goto done;
4097 s = logmsg0;
4098 while (isspace((unsigned char)s[0]))
4099 s++;
4101 nl = strchr(s, '\n');
4102 if (nl) {
4103 *nl = '\0';
4106 if (ref_str)
4107 printf("%s%-7s %s\n", datebuf, ref_str, s);
4108 else
4109 printf("%s%.7s %s\n", datebuf, id_str, s);
4111 if (fflush(stdout) != 0 && err == NULL)
4112 err = got_error_from_errno("fflush");
4113 done:
4114 free(id_str);
4115 free(ref_str);
4116 free(logmsg0);
4117 return err;
4120 static const struct got_error *
4121 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4122 struct got_repository *repo, const char *path,
4123 struct got_pathlist_head *changed_paths, int show_patch,
4124 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4125 const char *custom_refs_str)
4127 const struct got_error *err = NULL;
4128 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4129 char datebuf[26];
4130 time_t committer_time;
4131 const char *author, *committer;
4132 char *refs_str = NULL;
4134 err = got_object_id_str(&id_str, id);
4135 if (err)
4136 return err;
4138 if (custom_refs_str == NULL) {
4139 struct got_reflist_head *refs;
4140 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4141 if (refs) {
4142 err = build_refs_str(&refs_str, refs, id, repo, 0);
4143 if (err)
4144 goto done;
4148 printf(GOT_COMMIT_SEP_STR);
4149 if (custom_refs_str)
4150 printf("commit %s (%s)\n", id_str, custom_refs_str);
4151 else
4152 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4153 refs_str ? refs_str : "", refs_str ? ")" : "");
4154 free(id_str);
4155 id_str = NULL;
4156 free(refs_str);
4157 refs_str = NULL;
4158 printf("from: %s\n", got_object_commit_get_author(commit));
4159 committer_time = got_object_commit_get_committer_time(commit);
4160 datestr = get_datestr(&committer_time, datebuf);
4161 if (datestr)
4162 printf("date: %s UTC\n", datestr);
4163 author = got_object_commit_get_author(commit);
4164 committer = got_object_commit_get_committer(commit);
4165 if (strcmp(author, committer) != 0)
4166 printf("via: %s\n", committer);
4167 if (got_object_commit_get_nparents(commit) > 1) {
4168 const struct got_object_id_queue *parent_ids;
4169 struct got_object_qid *qid;
4170 int n = 1;
4171 parent_ids = got_object_commit_get_parent_ids(commit);
4172 STAILQ_FOREACH(qid, parent_ids, entry) {
4173 err = got_object_id_str(&id_str, &qid->id);
4174 if (err)
4175 goto done;
4176 printf("parent %d: %s\n", n++, id_str);
4177 free(id_str);
4178 id_str = NULL;
4182 err = got_object_commit_get_logmsg(&logmsg0, commit);
4183 if (err)
4184 goto done;
4186 logmsg = logmsg0;
4187 do {
4188 line = strsep(&logmsg, "\n");
4189 if (line)
4190 printf(" %s\n", line);
4191 } while (line);
4192 free(logmsg0);
4194 if (changed_paths) {
4195 struct got_pathlist_entry *pe;
4196 TAILQ_FOREACH(pe, changed_paths, entry) {
4197 struct got_diff_changed_path *cp = pe->data;
4198 printf(" %c %s\n", cp->status, pe->path);
4200 printf("\n");
4202 if (show_patch) {
4203 err = print_patch(commit, id, path, diff_context, repo, stdout);
4204 if (err == 0)
4205 printf("\n");
4208 if (fflush(stdout) != 0 && err == NULL)
4209 err = got_error_from_errno("fflush");
4210 done:
4211 free(id_str);
4212 free(refs_str);
4213 return err;
4216 static const struct got_error *
4217 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4218 struct got_repository *repo, const char *path, int show_changed_paths,
4219 int show_patch, const char *search_pattern, int diff_context, int limit,
4220 int log_branches, int reverse_display_order,
4221 struct got_reflist_object_id_map *refs_idmap, int one_line,
4222 FILE *tmpfile)
4224 const struct got_error *err;
4225 struct got_commit_graph *graph;
4226 regex_t regex;
4227 int have_match;
4228 struct got_object_id_queue reversed_commits;
4229 struct got_object_qid *qid;
4230 struct got_commit_object *commit;
4231 struct got_pathlist_head changed_paths;
4232 struct got_pathlist_entry *pe;
4234 STAILQ_INIT(&reversed_commits);
4235 TAILQ_INIT(&changed_paths);
4237 if (search_pattern && regcomp(&regex, search_pattern,
4238 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4239 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4241 err = got_commit_graph_open(&graph, path, !log_branches);
4242 if (err)
4243 return err;
4244 err = got_commit_graph_iter_start(graph, root_id, repo,
4245 check_cancelled, NULL);
4246 if (err)
4247 goto done;
4248 for (;;) {
4249 struct got_object_id *id;
4251 if (sigint_received || sigpipe_received)
4252 break;
4254 err = got_commit_graph_iter_next(&id, graph, repo,
4255 check_cancelled, NULL);
4256 if (err) {
4257 if (err->code == GOT_ERR_ITER_COMPLETED)
4258 err = NULL;
4259 break;
4261 if (id == NULL)
4262 break;
4264 err = got_object_open_as_commit(&commit, repo, id);
4265 if (err)
4266 break;
4268 if (show_changed_paths && !reverse_display_order) {
4269 err = get_changed_paths(&changed_paths, commit, repo);
4270 if (err)
4271 break;
4274 if (search_pattern) {
4275 err = match_commit(&have_match, id, commit, &regex);
4276 if (err) {
4277 got_object_commit_close(commit);
4278 break;
4280 if (have_match == 0 && show_changed_paths)
4281 match_changed_paths(&have_match,
4282 &changed_paths, &regex);
4283 if (have_match == 0 && show_patch) {
4284 err = match_patch(&have_match, commit, id,
4285 path, diff_context, repo, &regex,
4286 tmpfile);
4287 if (err)
4288 break;
4290 if (have_match == 0) {
4291 got_object_commit_close(commit);
4292 TAILQ_FOREACH(pe, &changed_paths, entry) {
4293 free((char *)pe->path);
4294 free(pe->data);
4296 got_pathlist_free(&changed_paths);
4297 continue;
4301 if (reverse_display_order) {
4302 err = got_object_qid_alloc(&qid, id);
4303 if (err)
4304 break;
4305 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4306 got_object_commit_close(commit);
4307 } else {
4308 if (one_line)
4309 err = print_commit_oneline(commit, id,
4310 repo, refs_idmap);
4311 else
4312 err = print_commit(commit, id, repo, path,
4313 show_changed_paths ? &changed_paths : NULL,
4314 show_patch, diff_context, refs_idmap, NULL);
4315 got_object_commit_close(commit);
4316 if (err)
4317 break;
4319 if ((limit && --limit == 0) ||
4320 (end_id && got_object_id_cmp(id, end_id) == 0))
4321 break;
4323 TAILQ_FOREACH(pe, &changed_paths, entry) {
4324 free((char *)pe->path);
4325 free(pe->data);
4327 got_pathlist_free(&changed_paths);
4329 if (reverse_display_order) {
4330 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4331 err = got_object_open_as_commit(&commit, repo,
4332 &qid->id);
4333 if (err)
4334 break;
4335 if (show_changed_paths) {
4336 err = get_changed_paths(&changed_paths,
4337 commit, repo);
4338 if (err)
4339 break;
4341 if (one_line)
4342 err = print_commit_oneline(commit, &qid->id,
4343 repo, refs_idmap);
4344 else
4345 err = print_commit(commit, &qid->id, repo, path,
4346 show_changed_paths ? &changed_paths : NULL,
4347 show_patch, diff_context, refs_idmap, NULL);
4348 got_object_commit_close(commit);
4349 if (err)
4350 break;
4351 TAILQ_FOREACH(pe, &changed_paths, entry) {
4352 free((char *)pe->path);
4353 free(pe->data);
4355 got_pathlist_free(&changed_paths);
4358 done:
4359 while (!STAILQ_EMPTY(&reversed_commits)) {
4360 qid = STAILQ_FIRST(&reversed_commits);
4361 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4362 got_object_qid_free(qid);
4364 TAILQ_FOREACH(pe, &changed_paths, entry) {
4365 free((char *)pe->path);
4366 free(pe->data);
4368 got_pathlist_free(&changed_paths);
4369 if (search_pattern)
4370 regfree(&regex);
4371 got_commit_graph_close(graph);
4372 return err;
4375 __dead static void
4376 usage_log(void)
4378 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4379 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4380 "[-r repository-path] [-R] [path]\n", getprogname());
4381 exit(1);
4384 static int
4385 get_default_log_limit(void)
4387 const char *got_default_log_limit;
4388 long long n;
4389 const char *errstr;
4391 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4392 if (got_default_log_limit == NULL)
4393 return 0;
4394 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4395 if (errstr != NULL)
4396 return 0;
4397 return n;
4400 static const struct got_error *
4401 cmd_log(int argc, char *argv[])
4403 const struct got_error *error;
4404 struct got_repository *repo = NULL;
4405 struct got_worktree *worktree = NULL;
4406 struct got_object_id *start_id = NULL, *end_id = NULL;
4407 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4408 const char *start_commit = NULL, *end_commit = NULL;
4409 const char *search_pattern = NULL;
4410 int diff_context = -1, ch;
4411 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4412 int reverse_display_order = 0, one_line = 0;
4413 const char *errstr;
4414 struct got_reflist_head refs;
4415 struct got_reflist_object_id_map *refs_idmap = NULL;
4416 FILE *tmpfile = NULL;
4417 int *pack_fds = NULL;
4419 TAILQ_INIT(&refs);
4421 #ifndef PROFILE
4422 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4423 NULL)
4424 == -1)
4425 err(1, "pledge");
4426 #endif
4428 limit = get_default_log_limit();
4430 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4431 switch (ch) {
4432 case 'p':
4433 show_patch = 1;
4434 break;
4435 case 'P':
4436 show_changed_paths = 1;
4437 break;
4438 case 'c':
4439 start_commit = optarg;
4440 break;
4441 case 'C':
4442 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4443 &errstr);
4444 if (errstr != NULL)
4445 errx(1, "number of context lines is %s: %s",
4446 errstr, optarg);
4447 break;
4448 case 'l':
4449 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4450 if (errstr != NULL)
4451 errx(1, "number of commits is %s: %s",
4452 errstr, optarg);
4453 break;
4454 case 'b':
4455 log_branches = 1;
4456 break;
4457 case 'r':
4458 repo_path = realpath(optarg, NULL);
4459 if (repo_path == NULL)
4460 return got_error_from_errno2("realpath",
4461 optarg);
4462 got_path_strip_trailing_slashes(repo_path);
4463 break;
4464 case 'R':
4465 reverse_display_order = 1;
4466 break;
4467 case 's':
4468 one_line = 1;
4469 break;
4470 case 'S':
4471 search_pattern = optarg;
4472 break;
4473 case 'x':
4474 end_commit = optarg;
4475 break;
4476 default:
4477 usage_log();
4478 /* NOTREACHED */
4482 argc -= optind;
4483 argv += optind;
4485 if (diff_context == -1)
4486 diff_context = 3;
4487 else if (!show_patch)
4488 errx(1, "-C requires -p");
4490 if (one_line && (show_patch || show_changed_paths))
4491 errx(1, "cannot use -s with -p or -P");
4493 cwd = getcwd(NULL, 0);
4494 if (cwd == NULL) {
4495 error = got_error_from_errno("getcwd");
4496 goto done;
4499 error = got_repo_pack_fds_open(&pack_fds);
4500 if (error != NULL)
4501 goto done;
4503 if (repo_path == NULL) {
4504 error = got_worktree_open(&worktree, cwd);
4505 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4506 goto done;
4507 error = NULL;
4510 if (argc == 1) {
4511 if (worktree) {
4512 error = got_worktree_resolve_path(&path, worktree,
4513 argv[0]);
4514 if (error)
4515 goto done;
4516 } else {
4517 path = strdup(argv[0]);
4518 if (path == NULL) {
4519 error = got_error_from_errno("strdup");
4520 goto done;
4523 } else if (argc != 0)
4524 usage_log();
4526 if (repo_path == NULL) {
4527 repo_path = worktree ?
4528 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4530 if (repo_path == NULL) {
4531 error = got_error_from_errno("strdup");
4532 goto done;
4535 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4536 if (error != NULL)
4537 goto done;
4539 error = apply_unveil(got_repo_get_path(repo), 1,
4540 worktree ? got_worktree_get_root_path(worktree) : NULL);
4541 if (error)
4542 goto done;
4544 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4545 if (error)
4546 goto done;
4548 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4549 if (error)
4550 goto done;
4552 if (start_commit == NULL) {
4553 struct got_reference *head_ref;
4554 struct got_commit_object *commit = NULL;
4555 error = got_ref_open(&head_ref, repo,
4556 worktree ? got_worktree_get_head_ref_name(worktree)
4557 : GOT_REF_HEAD, 0);
4558 if (error != NULL)
4559 goto done;
4560 error = got_ref_resolve(&start_id, repo, head_ref);
4561 got_ref_close(head_ref);
4562 if (error != NULL)
4563 goto done;
4564 error = got_object_open_as_commit(&commit, repo,
4565 start_id);
4566 if (error != NULL)
4567 goto done;
4568 got_object_commit_close(commit);
4569 } else {
4570 error = got_repo_match_object_id(&start_id, NULL,
4571 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4572 if (error != NULL)
4573 goto done;
4575 if (end_commit != NULL) {
4576 error = got_repo_match_object_id(&end_id, NULL,
4577 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4578 if (error != NULL)
4579 goto done;
4582 if (worktree) {
4584 * If a path was specified on the command line it was resolved
4585 * to a path in the work tree above. Prepend the work tree's
4586 * path prefix to obtain the corresponding in-repository path.
4588 if (path) {
4589 const char *prefix;
4590 prefix = got_worktree_get_path_prefix(worktree);
4591 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4592 (path[0] != '\0') ? "/" : "", path) == -1) {
4593 error = got_error_from_errno("asprintf");
4594 goto done;
4597 } else
4598 error = got_repo_map_path(&in_repo_path, repo,
4599 path ? path : "");
4600 if (error != NULL)
4601 goto done;
4602 if (in_repo_path) {
4603 free(path);
4604 path = in_repo_path;
4607 if (worktree) {
4608 /* Release work tree lock. */
4609 got_worktree_close(worktree);
4610 worktree = NULL;
4613 if (search_pattern && show_patch) {
4614 tmpfile = got_opentemp();
4615 if (tmpfile == NULL) {
4616 error = got_error_from_errno("got_opentemp");
4617 goto done;
4621 error = print_commits(start_id, end_id, repo, path ? path : "",
4622 show_changed_paths, show_patch, search_pattern, diff_context,
4623 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4624 tmpfile);
4625 done:
4626 free(path);
4627 free(repo_path);
4628 free(cwd);
4629 if (worktree)
4630 got_worktree_close(worktree);
4631 if (repo) {
4632 const struct got_error *close_err = got_repo_close(repo);
4633 if (error == NULL)
4634 error = close_err;
4636 if (pack_fds) {
4637 const struct got_error *pack_err =
4638 got_repo_pack_fds_close(pack_fds);
4639 if (error == NULL)
4640 error = pack_err;
4642 if (refs_idmap)
4643 got_reflist_object_id_map_free(refs_idmap);
4644 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4645 error = got_error_from_errno("fclose");
4646 got_ref_list_free(&refs);
4647 return error;
4650 __dead static void
4651 usage_diff(void)
4653 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4654 "[-r repository-path] [-s] [-w] [-P] "
4655 "[object1 object2 | path ...]\n", getprogname());
4656 exit(1);
4659 struct print_diff_arg {
4660 struct got_repository *repo;
4661 struct got_worktree *worktree;
4662 int diff_context;
4663 const char *id_str;
4664 int header_shown;
4665 int diff_staged;
4666 enum got_diff_algorithm diff_algo;
4667 int ignore_whitespace;
4668 int force_text_diff;
4669 FILE *f1;
4670 FILE *f2;
4674 * Create a file which contains the target path of a symlink so we can feed
4675 * it as content to the diff engine.
4677 static const struct got_error *
4678 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4679 const char *abspath)
4681 const struct got_error *err = NULL;
4682 char target_path[PATH_MAX];
4683 ssize_t target_len, outlen;
4685 *fd = -1;
4687 if (dirfd != -1) {
4688 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4689 if (target_len == -1)
4690 return got_error_from_errno2("readlinkat", abspath);
4691 } else {
4692 target_len = readlink(abspath, target_path, PATH_MAX);
4693 if (target_len == -1)
4694 return got_error_from_errno2("readlink", abspath);
4697 *fd = got_opentempfd();
4698 if (*fd == -1)
4699 return got_error_from_errno("got_opentempfd");
4701 outlen = write(*fd, target_path, target_len);
4702 if (outlen == -1) {
4703 err = got_error_from_errno("got_opentempfd");
4704 goto done;
4707 if (lseek(*fd, 0, SEEK_SET) == -1) {
4708 err = got_error_from_errno2("lseek", abspath);
4709 goto done;
4711 done:
4712 if (err) {
4713 close(*fd);
4714 *fd = -1;
4716 return err;
4719 static const struct got_error *
4720 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4721 const char *path, struct got_object_id *blob_id,
4722 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4723 int dirfd, const char *de_name)
4725 struct print_diff_arg *a = arg;
4726 const struct got_error *err = NULL;
4727 struct got_blob_object *blob1 = NULL;
4728 int fd = -1, fd1 = -1, fd2 = -1;
4729 FILE *f2 = NULL;
4730 char *abspath = NULL, *label1 = NULL;
4731 struct stat sb;
4732 off_t size1 = 0;
4733 int f2_exists = 1;
4735 if (a->diff_staged) {
4736 if (staged_status != GOT_STATUS_MODIFY &&
4737 staged_status != GOT_STATUS_ADD &&
4738 staged_status != GOT_STATUS_DELETE)
4739 return NULL;
4740 } else {
4741 if (staged_status == GOT_STATUS_DELETE)
4742 return NULL;
4743 if (status == GOT_STATUS_NONEXISTENT)
4744 return got_error_set_errno(ENOENT, path);
4745 if (status != GOT_STATUS_MODIFY &&
4746 status != GOT_STATUS_ADD &&
4747 status != GOT_STATUS_DELETE &&
4748 status != GOT_STATUS_CONFLICT)
4749 return NULL;
4752 err = got_opentemp_truncate(a->f1);
4753 if (err)
4754 return got_error_from_errno("got_opentemp_truncate");
4755 err = got_opentemp_truncate(a->f2);
4756 if (err)
4757 return got_error_from_errno("got_opentemp_truncate");
4759 if (!a->header_shown) {
4760 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4761 got_worktree_get_root_path(a->worktree));
4762 printf("commit - %s\n", a->id_str);
4763 printf("path + %s%s\n",
4764 got_worktree_get_root_path(a->worktree),
4765 a->diff_staged ? " (staged changes)" : "");
4766 a->header_shown = 1;
4769 if (a->diff_staged) {
4770 const char *label1 = NULL, *label2 = NULL;
4771 switch (staged_status) {
4772 case GOT_STATUS_MODIFY:
4773 label1 = path;
4774 label2 = path;
4775 break;
4776 case GOT_STATUS_ADD:
4777 label2 = path;
4778 break;
4779 case GOT_STATUS_DELETE:
4780 label1 = path;
4781 break;
4782 default:
4783 return got_error(GOT_ERR_FILE_STATUS);
4785 fd1 = got_opentempfd();
4786 if (fd1 == -1) {
4787 err = got_error_from_errno("got_opentempfd");
4788 goto done;
4790 fd2 = got_opentempfd();
4791 if (fd2 == -1) {
4792 err = got_error_from_errno("got_opentempfd");
4793 goto done;
4795 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4796 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4797 a->diff_algo, a->diff_context, a->ignore_whitespace,
4798 a->force_text_diff, a->repo, stdout);
4799 goto done;
4802 fd1 = got_opentempfd();
4803 if (fd1 == -1) {
4804 err = got_error_from_errno("got_opentempfd");
4805 goto done;
4808 if (staged_status == GOT_STATUS_ADD ||
4809 staged_status == GOT_STATUS_MODIFY) {
4810 char *id_str;
4811 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4812 8192, fd1);
4813 if (err)
4814 goto done;
4815 err = got_object_id_str(&id_str, staged_blob_id);
4816 if (err)
4817 goto done;
4818 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4819 err = got_error_from_errno("asprintf");
4820 free(id_str);
4821 goto done;
4823 free(id_str);
4824 } else if (status != GOT_STATUS_ADD) {
4825 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4826 fd1);
4827 if (err)
4828 goto done;
4831 if (status != GOT_STATUS_DELETE) {
4832 if (asprintf(&abspath, "%s/%s",
4833 got_worktree_get_root_path(a->worktree), path) == -1) {
4834 err = got_error_from_errno("asprintf");
4835 goto done;
4838 if (dirfd != -1) {
4839 fd = openat(dirfd, de_name,
4840 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4841 if (fd == -1) {
4842 if (!got_err_open_nofollow_on_symlink()) {
4843 err = got_error_from_errno2("openat",
4844 abspath);
4845 goto done;
4847 err = get_symlink_target_file(&fd, dirfd,
4848 de_name, abspath);
4849 if (err)
4850 goto done;
4852 } else {
4853 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4854 if (fd == -1) {
4855 if (!got_err_open_nofollow_on_symlink()) {
4856 err = got_error_from_errno2("open",
4857 abspath);
4858 goto done;
4860 err = get_symlink_target_file(&fd, dirfd,
4861 de_name, abspath);
4862 if (err)
4863 goto done;
4866 if (fstat(fd, &sb) == -1) {
4867 err = got_error_from_errno2("fstat", abspath);
4868 goto done;
4870 f2 = fdopen(fd, "r");
4871 if (f2 == NULL) {
4872 err = got_error_from_errno2("fdopen", abspath);
4873 goto done;
4875 fd = -1;
4876 } else {
4877 sb.st_size = 0;
4878 f2_exists = 0;
4881 if (blob1) {
4882 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4883 a->f1, blob1);
4884 if (err)
4885 goto done;
4888 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4889 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4890 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4891 done:
4892 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4893 err = got_error_from_errno("close");
4894 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4895 err = got_error_from_errno("close");
4896 if (blob1)
4897 got_object_blob_close(blob1);
4898 if (fd != -1 && close(fd) == -1 && err == NULL)
4899 err = got_error_from_errno("close");
4900 if (f2 && fclose(f2) == EOF && err == NULL)
4901 err = got_error_from_errno("fclose");
4902 free(abspath);
4903 return err;
4906 static const struct got_error *
4907 cmd_diff(int argc, char *argv[])
4909 const struct got_error *error;
4910 struct got_repository *repo = NULL;
4911 struct got_worktree *worktree = NULL;
4912 char *cwd = NULL, *repo_path = NULL;
4913 const char *commit_args[2] = { NULL, NULL };
4914 int ncommit_args = 0;
4915 struct got_object_id *ids[2] = { NULL, NULL };
4916 char *labels[2] = { NULL, NULL };
4917 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4918 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4919 int force_text_diff = 0, force_path = 0, rflag = 0;
4920 const char *errstr;
4921 struct got_reflist_head refs;
4922 struct got_pathlist_head paths;
4923 struct got_pathlist_entry *pe;
4924 FILE *f1 = NULL, *f2 = NULL;
4925 int fd1 = -1, fd2 = -1;
4926 int *pack_fds = NULL;
4928 TAILQ_INIT(&refs);
4929 TAILQ_INIT(&paths);
4931 #ifndef PROFILE
4932 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4933 NULL) == -1)
4934 err(1, "pledge");
4935 #endif
4937 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4938 switch (ch) {
4939 case 'a':
4940 force_text_diff = 1;
4941 break;
4942 case 'c':
4943 if (ncommit_args >= 2)
4944 errx(1, "too many -c options used");
4945 commit_args[ncommit_args++] = optarg;
4946 break;
4947 case 'C':
4948 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4949 &errstr);
4950 if (errstr != NULL)
4951 errx(1, "number of context lines is %s: %s",
4952 errstr, optarg);
4953 break;
4954 case 'r':
4955 repo_path = realpath(optarg, NULL);
4956 if (repo_path == NULL)
4957 return got_error_from_errno2("realpath",
4958 optarg);
4959 got_path_strip_trailing_slashes(repo_path);
4960 rflag = 1;
4961 break;
4962 case 's':
4963 diff_staged = 1;
4964 break;
4965 case 'w':
4966 ignore_whitespace = 1;
4967 break;
4968 case 'P':
4969 force_path = 1;
4970 break;
4971 default:
4972 usage_diff();
4973 /* NOTREACHED */
4977 argc -= optind;
4978 argv += optind;
4980 cwd = getcwd(NULL, 0);
4981 if (cwd == NULL) {
4982 error = got_error_from_errno("getcwd");
4983 goto done;
4986 error = got_repo_pack_fds_open(&pack_fds);
4987 if (error != NULL)
4988 goto done;
4990 if (repo_path == NULL) {
4991 error = got_worktree_open(&worktree, cwd);
4992 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4993 goto done;
4994 else
4995 error = NULL;
4996 if (worktree) {
4997 repo_path =
4998 strdup(got_worktree_get_repo_path(worktree));
4999 if (repo_path == NULL) {
5000 error = got_error_from_errno("strdup");
5001 goto done;
5003 } else {
5004 repo_path = strdup(cwd);
5005 if (repo_path == NULL) {
5006 error = got_error_from_errno("strdup");
5007 goto done;
5012 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5013 free(repo_path);
5014 if (error != NULL)
5015 goto done;
5017 if (rflag || worktree == NULL || ncommit_args > 0) {
5018 if (force_path) {
5019 error = got_error_msg(GOT_ERR_NOT_IMPL,
5020 "-P option can only be used when diffing "
5021 "a work tree");
5022 goto done;
5024 if (diff_staged) {
5025 error = got_error_msg(GOT_ERR_NOT_IMPL,
5026 "-s option can only be used when diffing "
5027 "a work tree");
5028 goto done;
5032 error = apply_unveil(got_repo_get_path(repo), 1,
5033 worktree ? got_worktree_get_root_path(worktree) : NULL);
5034 if (error)
5035 goto done;
5037 if ((!force_path && argc == 2) || ncommit_args > 0) {
5038 int obj_type = (ncommit_args > 0 ?
5039 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5040 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5041 NULL);
5042 if (error)
5043 goto done;
5044 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5045 const char *arg;
5046 if (ncommit_args > 0)
5047 arg = commit_args[i];
5048 else
5049 arg = argv[i];
5050 error = got_repo_match_object_id(&ids[i], &labels[i],
5051 arg, obj_type, &refs, repo);
5052 if (error) {
5053 if (error->code != GOT_ERR_NOT_REF &&
5054 error->code != GOT_ERR_NO_OBJ)
5055 goto done;
5056 if (ncommit_args > 0)
5057 goto done;
5058 error = NULL;
5059 break;
5064 f1 = got_opentemp();
5065 if (f1 == NULL) {
5066 error = got_error_from_errno("got_opentemp");
5067 goto done;
5070 f2 = got_opentemp();
5071 if (f2 == NULL) {
5072 error = got_error_from_errno("got_opentemp");
5073 goto done;
5076 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5077 struct print_diff_arg arg;
5078 char *id_str;
5080 if (worktree == NULL) {
5081 if (argc == 2 && ids[0] == NULL) {
5082 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5083 goto done;
5084 } else if (argc == 2 && ids[1] == NULL) {
5085 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5086 goto done;
5087 } else if (argc > 0) {
5088 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5089 "%s", "specified paths cannot be resolved");
5090 goto done;
5091 } else {
5092 error = got_error(GOT_ERR_NOT_WORKTREE);
5093 goto done;
5097 error = get_worktree_paths_from_argv(&paths, argc, argv,
5098 worktree);
5099 if (error)
5100 goto done;
5102 error = got_object_id_str(&id_str,
5103 got_worktree_get_base_commit_id(worktree));
5104 if (error)
5105 goto done;
5106 arg.repo = repo;
5107 arg.worktree = worktree;
5108 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5109 arg.diff_context = diff_context;
5110 arg.id_str = id_str;
5111 arg.header_shown = 0;
5112 arg.diff_staged = diff_staged;
5113 arg.ignore_whitespace = ignore_whitespace;
5114 arg.force_text_diff = force_text_diff;
5115 arg.f1 = f1;
5116 arg.f2 = f2;
5118 error = got_worktree_status(worktree, &paths, repo, 0,
5119 print_diff, &arg, check_cancelled, NULL);
5120 free(id_str);
5121 goto done;
5124 if (ncommit_args == 1) {
5125 struct got_commit_object *commit;
5126 error = got_object_open_as_commit(&commit, repo, ids[0]);
5127 if (error)
5128 goto done;
5130 labels[1] = labels[0];
5131 ids[1] = ids[0];
5132 if (got_object_commit_get_nparents(commit) > 0) {
5133 const struct got_object_id_queue *pids;
5134 struct got_object_qid *pid;
5135 pids = got_object_commit_get_parent_ids(commit);
5136 pid = STAILQ_FIRST(pids);
5137 ids[0] = got_object_id_dup(&pid->id);
5138 if (ids[0] == NULL) {
5139 error = got_error_from_errno(
5140 "got_object_id_dup");
5141 got_object_commit_close(commit);
5142 goto done;
5144 error = got_object_id_str(&labels[0], ids[0]);
5145 if (error) {
5146 got_object_commit_close(commit);
5147 goto done;
5149 } else {
5150 ids[0] = NULL;
5151 labels[0] = strdup("/dev/null");
5152 if (labels[0] == NULL) {
5153 error = got_error_from_errno("strdup");
5154 got_object_commit_close(commit);
5155 goto done;
5159 got_object_commit_close(commit);
5162 if (ncommit_args == 0 && argc > 2) {
5163 error = got_error_msg(GOT_ERR_BAD_PATH,
5164 "path arguments cannot be used when diffing two objects");
5165 goto done;
5168 if (ids[0]) {
5169 error = got_object_get_type(&type1, repo, ids[0]);
5170 if (error)
5171 goto done;
5174 error = got_object_get_type(&type2, repo, ids[1]);
5175 if (error)
5176 goto done;
5177 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5178 error = got_error(GOT_ERR_OBJ_TYPE);
5179 goto done;
5181 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5182 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5183 "path arguments cannot be used when diffing blobs");
5184 goto done;
5187 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5188 char *in_repo_path;
5189 struct got_pathlist_entry *new;
5190 if (worktree) {
5191 const char *prefix;
5192 char *p;
5193 error = got_worktree_resolve_path(&p, worktree,
5194 argv[i]);
5195 if (error)
5196 goto done;
5197 prefix = got_worktree_get_path_prefix(worktree);
5198 while (prefix[0] == '/')
5199 prefix++;
5200 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5201 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5202 p) == -1) {
5203 error = got_error_from_errno("asprintf");
5204 free(p);
5205 goto done;
5207 free(p);
5208 } else {
5209 char *mapped_path, *s;
5210 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5211 if (error)
5212 goto done;
5213 s = mapped_path;
5214 while (s[0] == '/')
5215 s++;
5216 in_repo_path = strdup(s);
5217 if (in_repo_path == NULL) {
5218 error = got_error_from_errno("asprintf");
5219 free(mapped_path);
5220 goto done;
5222 free(mapped_path);
5225 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5226 if (error || new == NULL /* duplicate */)
5227 free(in_repo_path);
5228 if (error)
5229 goto done;
5232 if (worktree) {
5233 /* Release work tree lock. */
5234 got_worktree_close(worktree);
5235 worktree = NULL;
5238 fd1 = got_opentempfd();
5239 if (fd1 == -1) {
5240 error = got_error_from_errno("got_opentempfd");
5241 goto done;
5244 fd2 = got_opentempfd();
5245 if (fd2 == -1) {
5246 error = got_error_from_errno("got_opentempfd");
5247 goto done;
5250 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5251 case GOT_OBJ_TYPE_BLOB:
5252 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5253 fd1, fd2, ids[0], ids[1], NULL, NULL,
5254 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5255 ignore_whitespace, force_text_diff, repo, stdout);
5256 break;
5257 case GOT_OBJ_TYPE_TREE:
5258 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5259 ids[0], ids[1], &paths, "", "",
5260 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5261 ignore_whitespace, force_text_diff, repo, stdout);
5262 break;
5263 case GOT_OBJ_TYPE_COMMIT:
5264 printf("diff %s %s\n", labels[0], labels[1]);
5265 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5266 fd1, fd2, ids[0], ids[1], &paths,
5267 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5268 ignore_whitespace, force_text_diff, repo, stdout);
5269 break;
5270 default:
5271 error = got_error(GOT_ERR_OBJ_TYPE);
5273 done:
5274 free(labels[0]);
5275 free(labels[1]);
5276 free(ids[0]);
5277 free(ids[1]);
5278 if (worktree)
5279 got_worktree_close(worktree);
5280 if (repo) {
5281 const struct got_error *close_err = got_repo_close(repo);
5282 if (error == NULL)
5283 error = close_err;
5285 if (pack_fds) {
5286 const struct got_error *pack_err =
5287 got_repo_pack_fds_close(pack_fds);
5288 if (error == NULL)
5289 error = pack_err;
5291 TAILQ_FOREACH(pe, &paths, entry)
5292 free((char *)pe->path);
5293 got_pathlist_free(&paths);
5294 got_ref_list_free(&refs);
5295 if (f1 && fclose(f1) == EOF && error == NULL)
5296 error = got_error_from_errno("fclose");
5297 if (f2 && fclose(f2) == EOF && error == NULL)
5298 error = got_error_from_errno("fclose");
5299 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5300 error = got_error_from_errno("close");
5301 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5302 error = got_error_from_errno("close");
5303 return error;
5306 __dead static void
5307 usage_blame(void)
5309 fprintf(stderr,
5310 "usage: %s blame [-c commit] [-r repository-path] path\n",
5311 getprogname());
5312 exit(1);
5315 struct blame_line {
5316 int annotated;
5317 char *id_str;
5318 char *committer;
5319 char datebuf[11]; /* YYYY-MM-DD + NUL */
5322 struct blame_cb_args {
5323 struct blame_line *lines;
5324 int nlines;
5325 int nlines_prec;
5326 int lineno_cur;
5327 off_t *line_offsets;
5328 FILE *f;
5329 struct got_repository *repo;
5332 static const struct got_error *
5333 blame_cb(void *arg, int nlines, int lineno,
5334 struct got_commit_object *commit, struct got_object_id *id)
5336 const struct got_error *err = NULL;
5337 struct blame_cb_args *a = arg;
5338 struct blame_line *bline;
5339 char *line = NULL;
5340 size_t linesize = 0;
5341 off_t offset;
5342 struct tm tm;
5343 time_t committer_time;
5345 if (nlines != a->nlines ||
5346 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5347 return got_error(GOT_ERR_RANGE);
5349 if (sigint_received)
5350 return got_error(GOT_ERR_ITER_COMPLETED);
5352 if (lineno == -1)
5353 return NULL; /* no change in this commit */
5355 /* Annotate this line. */
5356 bline = &a->lines[lineno - 1];
5357 if (bline->annotated)
5358 return NULL;
5359 err = got_object_id_str(&bline->id_str, id);
5360 if (err)
5361 return err;
5363 bline->committer = strdup(got_object_commit_get_committer(commit));
5364 if (bline->committer == NULL) {
5365 err = got_error_from_errno("strdup");
5366 goto done;
5369 committer_time = got_object_commit_get_committer_time(commit);
5370 if (gmtime_r(&committer_time, &tm) == NULL)
5371 return got_error_from_errno("gmtime_r");
5372 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5373 &tm) == 0) {
5374 err = got_error(GOT_ERR_NO_SPACE);
5375 goto done;
5377 bline->annotated = 1;
5379 /* Print lines annotated so far. */
5380 bline = &a->lines[a->lineno_cur - 1];
5381 if (!bline->annotated)
5382 goto done;
5384 offset = a->line_offsets[a->lineno_cur - 1];
5385 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5386 err = got_error_from_errno("fseeko");
5387 goto done;
5390 while (bline->annotated) {
5391 char *smallerthan, *at, *nl, *committer;
5392 size_t len;
5394 if (getline(&line, &linesize, a->f) == -1) {
5395 if (ferror(a->f))
5396 err = got_error_from_errno("getline");
5397 break;
5400 committer = bline->committer;
5401 smallerthan = strchr(committer, '<');
5402 if (smallerthan && smallerthan[1] != '\0')
5403 committer = smallerthan + 1;
5404 at = strchr(committer, '@');
5405 if (at)
5406 *at = '\0';
5407 len = strlen(committer);
5408 if (len >= 9)
5409 committer[8] = '\0';
5411 nl = strchr(line, '\n');
5412 if (nl)
5413 *nl = '\0';
5414 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5415 bline->id_str, bline->datebuf, committer, line);
5417 a->lineno_cur++;
5418 bline = &a->lines[a->lineno_cur - 1];
5420 done:
5421 free(line);
5422 return err;
5425 static const struct got_error *
5426 cmd_blame(int argc, char *argv[])
5428 const struct got_error *error;
5429 struct got_repository *repo = NULL;
5430 struct got_worktree *worktree = NULL;
5431 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5432 char *link_target = NULL;
5433 struct got_object_id *obj_id = NULL;
5434 struct got_object_id *commit_id = NULL;
5435 struct got_commit_object *commit = NULL;
5436 struct got_blob_object *blob = NULL;
5437 char *commit_id_str = NULL;
5438 struct blame_cb_args bca;
5439 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5440 off_t filesize;
5441 int *pack_fds = NULL;
5442 FILE *f1 = NULL, *f2 = NULL;
5444 fd1 = got_opentempfd();
5445 if (fd1 == -1)
5446 return got_error_from_errno("got_opentempfd");
5448 memset(&bca, 0, sizeof(bca));
5450 #ifndef PROFILE
5451 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5452 NULL) == -1)
5453 err(1, "pledge");
5454 #endif
5456 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5457 switch (ch) {
5458 case 'c':
5459 commit_id_str = optarg;
5460 break;
5461 case 'r':
5462 repo_path = realpath(optarg, NULL);
5463 if (repo_path == NULL)
5464 return got_error_from_errno2("realpath",
5465 optarg);
5466 got_path_strip_trailing_slashes(repo_path);
5467 break;
5468 default:
5469 usage_blame();
5470 /* NOTREACHED */
5474 argc -= optind;
5475 argv += optind;
5477 if (argc == 1)
5478 path = argv[0];
5479 else
5480 usage_blame();
5482 cwd = getcwd(NULL, 0);
5483 if (cwd == NULL) {
5484 error = got_error_from_errno("getcwd");
5485 goto done;
5488 error = got_repo_pack_fds_open(&pack_fds);
5489 if (error != NULL)
5490 goto done;
5492 if (repo_path == NULL) {
5493 error = got_worktree_open(&worktree, cwd);
5494 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5495 goto done;
5496 else
5497 error = NULL;
5498 if (worktree) {
5499 repo_path =
5500 strdup(got_worktree_get_repo_path(worktree));
5501 if (repo_path == NULL) {
5502 error = got_error_from_errno("strdup");
5503 if (error)
5504 goto done;
5506 } else {
5507 repo_path = strdup(cwd);
5508 if (repo_path == NULL) {
5509 error = got_error_from_errno("strdup");
5510 goto done;
5515 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5516 if (error != NULL)
5517 goto done;
5519 if (worktree) {
5520 const char *prefix = got_worktree_get_path_prefix(worktree);
5521 char *p;
5523 error = got_worktree_resolve_path(&p, worktree, path);
5524 if (error)
5525 goto done;
5526 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5527 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5528 p) == -1) {
5529 error = got_error_from_errno("asprintf");
5530 free(p);
5531 goto done;
5533 free(p);
5534 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5535 } else {
5536 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5537 if (error)
5538 goto done;
5539 error = got_repo_map_path(&in_repo_path, repo, path);
5541 if (error)
5542 goto done;
5544 if (commit_id_str == NULL) {
5545 struct got_reference *head_ref;
5546 error = got_ref_open(&head_ref, repo, worktree ?
5547 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5548 if (error != NULL)
5549 goto done;
5550 error = got_ref_resolve(&commit_id, repo, head_ref);
5551 got_ref_close(head_ref);
5552 if (error != NULL)
5553 goto done;
5554 } else {
5555 struct got_reflist_head refs;
5556 TAILQ_INIT(&refs);
5557 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5558 NULL);
5559 if (error)
5560 goto done;
5561 error = got_repo_match_object_id(&commit_id, NULL,
5562 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5563 got_ref_list_free(&refs);
5564 if (error)
5565 goto done;
5568 if (worktree) {
5569 /* Release work tree lock. */
5570 got_worktree_close(worktree);
5571 worktree = NULL;
5574 error = got_object_open_as_commit(&commit, repo, commit_id);
5575 if (error)
5576 goto done;
5578 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5579 commit, repo);
5580 if (error)
5581 goto done;
5583 error = got_object_id_by_path(&obj_id, repo, commit,
5584 link_target ? link_target : in_repo_path);
5585 if (error)
5586 goto done;
5588 error = got_object_get_type(&obj_type, repo, obj_id);
5589 if (error)
5590 goto done;
5592 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5593 error = got_error_path(link_target ? link_target : in_repo_path,
5594 GOT_ERR_OBJ_TYPE);
5595 goto done;
5598 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5599 if (error)
5600 goto done;
5601 bca.f = got_opentemp();
5602 if (bca.f == NULL) {
5603 error = got_error_from_errno("got_opentemp");
5604 goto done;
5606 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5607 &bca.line_offsets, bca.f, blob);
5608 if (error || bca.nlines == 0)
5609 goto done;
5611 /* Don't include \n at EOF in the blame line count. */
5612 if (bca.line_offsets[bca.nlines - 1] == filesize)
5613 bca.nlines--;
5615 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5616 if (bca.lines == NULL) {
5617 error = got_error_from_errno("calloc");
5618 goto done;
5620 bca.lineno_cur = 1;
5621 bca.nlines_prec = 0;
5622 i = bca.nlines;
5623 while (i > 0) {
5624 i /= 10;
5625 bca.nlines_prec++;
5627 bca.repo = repo;
5629 fd2 = got_opentempfd();
5630 if (fd2 == -1) {
5631 error = got_error_from_errno("got_opentempfd");
5632 goto done;
5634 fd3 = got_opentempfd();
5635 if (fd3 == -1) {
5636 error = got_error_from_errno("got_opentempfd");
5637 goto done;
5639 f1 = got_opentemp();
5640 if (f1 == NULL) {
5641 error = got_error_from_errno("got_opentemp");
5642 goto done;
5644 f2 = got_opentemp();
5645 if (f2 == NULL) {
5646 error = got_error_from_errno("got_opentemp");
5647 goto done;
5649 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5650 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5651 check_cancelled, NULL, fd2, fd3, f1, f2);
5652 done:
5653 free(in_repo_path);
5654 free(link_target);
5655 free(repo_path);
5656 free(cwd);
5657 free(commit_id);
5658 free(obj_id);
5659 if (commit)
5660 got_object_commit_close(commit);
5662 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5663 error = got_error_from_errno("close");
5664 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5665 error = got_error_from_errno("close");
5666 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5667 error = got_error_from_errno("close");
5668 if (f1 && fclose(f1) == EOF && error == NULL)
5669 error = got_error_from_errno("fclose");
5670 if (f2 && fclose(f2) == EOF && error == NULL)
5671 error = got_error_from_errno("fclose");
5673 if (blob)
5674 got_object_blob_close(blob);
5675 if (worktree)
5676 got_worktree_close(worktree);
5677 if (repo) {
5678 const struct got_error *close_err = got_repo_close(repo);
5679 if (error == NULL)
5680 error = close_err;
5682 if (pack_fds) {
5683 const struct got_error *pack_err =
5684 got_repo_pack_fds_close(pack_fds);
5685 if (error == NULL)
5686 error = pack_err;
5688 if (bca.lines) {
5689 for (i = 0; i < bca.nlines; i++) {
5690 struct blame_line *bline = &bca.lines[i];
5691 free(bline->id_str);
5692 free(bline->committer);
5694 free(bca.lines);
5696 free(bca.line_offsets);
5697 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5698 error = got_error_from_errno("fclose");
5699 return error;
5702 __dead static void
5703 usage_tree(void)
5705 fprintf(stderr,
5706 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5707 getprogname());
5708 exit(1);
5711 static const struct got_error *
5712 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5713 const char *root_path, struct got_repository *repo)
5715 const struct got_error *err = NULL;
5716 int is_root_path = (strcmp(path, root_path) == 0);
5717 const char *modestr = "";
5718 mode_t mode = got_tree_entry_get_mode(te);
5719 char *link_target = NULL;
5721 path += strlen(root_path);
5722 while (path[0] == '/')
5723 path++;
5725 if (got_object_tree_entry_is_submodule(te))
5726 modestr = "$";
5727 else if (S_ISLNK(mode)) {
5728 int i;
5730 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5731 if (err)
5732 return err;
5733 for (i = 0; i < strlen(link_target); i++) {
5734 if (!isprint((unsigned char)link_target[i]))
5735 link_target[i] = '?';
5738 modestr = "@";
5740 else if (S_ISDIR(mode))
5741 modestr = "/";
5742 else if (mode & S_IXUSR)
5743 modestr = "*";
5745 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5746 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5747 link_target ? " -> ": "", link_target ? link_target : "");
5749 free(link_target);
5750 return NULL;
5753 static const struct got_error *
5754 print_tree(const char *path, struct got_commit_object *commit,
5755 int show_ids, int recurse, const char *root_path,
5756 struct got_repository *repo)
5758 const struct got_error *err = NULL;
5759 struct got_object_id *tree_id = NULL;
5760 struct got_tree_object *tree = NULL;
5761 int nentries, i;
5763 err = got_object_id_by_path(&tree_id, repo, commit, path);
5764 if (err)
5765 goto done;
5767 err = got_object_open_as_tree(&tree, repo, tree_id);
5768 if (err)
5769 goto done;
5770 nentries = got_object_tree_get_nentries(tree);
5771 for (i = 0; i < nentries; i++) {
5772 struct got_tree_entry *te;
5773 char *id = NULL;
5775 if (sigint_received || sigpipe_received)
5776 break;
5778 te = got_object_tree_get_entry(tree, i);
5779 if (show_ids) {
5780 char *id_str;
5781 err = got_object_id_str(&id_str,
5782 got_tree_entry_get_id(te));
5783 if (err)
5784 goto done;
5785 if (asprintf(&id, "%s ", id_str) == -1) {
5786 err = got_error_from_errno("asprintf");
5787 free(id_str);
5788 goto done;
5790 free(id_str);
5792 err = print_entry(te, id, path, root_path, repo);
5793 free(id);
5794 if (err)
5795 goto done;
5797 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5798 char *child_path;
5799 if (asprintf(&child_path, "%s%s%s", path,
5800 path[0] == '/' && path[1] == '\0' ? "" : "/",
5801 got_tree_entry_get_name(te)) == -1) {
5802 err = got_error_from_errno("asprintf");
5803 goto done;
5805 err = print_tree(child_path, commit, show_ids, 1,
5806 root_path, repo);
5807 free(child_path);
5808 if (err)
5809 goto done;
5812 done:
5813 if (tree)
5814 got_object_tree_close(tree);
5815 free(tree_id);
5816 return err;
5819 static const struct got_error *
5820 cmd_tree(int argc, char *argv[])
5822 const struct got_error *error;
5823 struct got_repository *repo = NULL;
5824 struct got_worktree *worktree = NULL;
5825 const char *path, *refname = NULL;
5826 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5827 struct got_object_id *commit_id = NULL;
5828 struct got_commit_object *commit = NULL;
5829 char *commit_id_str = NULL;
5830 int show_ids = 0, recurse = 0;
5831 int ch;
5832 int *pack_fds = NULL;
5834 #ifndef PROFILE
5835 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5836 NULL) == -1)
5837 err(1, "pledge");
5838 #endif
5840 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5841 switch (ch) {
5842 case 'c':
5843 commit_id_str = optarg;
5844 break;
5845 case 'r':
5846 repo_path = realpath(optarg, NULL);
5847 if (repo_path == NULL)
5848 return got_error_from_errno2("realpath",
5849 optarg);
5850 got_path_strip_trailing_slashes(repo_path);
5851 break;
5852 case 'i':
5853 show_ids = 1;
5854 break;
5855 case 'R':
5856 recurse = 1;
5857 break;
5858 default:
5859 usage_tree();
5860 /* NOTREACHED */
5864 argc -= optind;
5865 argv += optind;
5867 if (argc == 1)
5868 path = argv[0];
5869 else if (argc > 1)
5870 usage_tree();
5871 else
5872 path = NULL;
5874 cwd = getcwd(NULL, 0);
5875 if (cwd == NULL) {
5876 error = got_error_from_errno("getcwd");
5877 goto done;
5880 error = got_repo_pack_fds_open(&pack_fds);
5881 if (error != NULL)
5882 goto done;
5884 if (repo_path == NULL) {
5885 error = got_worktree_open(&worktree, cwd);
5886 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5887 goto done;
5888 else
5889 error = NULL;
5890 if (worktree) {
5891 repo_path =
5892 strdup(got_worktree_get_repo_path(worktree));
5893 if (repo_path == NULL)
5894 error = got_error_from_errno("strdup");
5895 if (error)
5896 goto done;
5897 } else {
5898 repo_path = strdup(cwd);
5899 if (repo_path == NULL) {
5900 error = got_error_from_errno("strdup");
5901 goto done;
5906 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5907 if (error != NULL)
5908 goto done;
5910 if (worktree) {
5911 const char *prefix = got_worktree_get_path_prefix(worktree);
5912 char *p;
5914 if (path == NULL)
5915 path = "";
5916 error = got_worktree_resolve_path(&p, worktree, path);
5917 if (error)
5918 goto done;
5919 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5920 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5921 p) == -1) {
5922 error = got_error_from_errno("asprintf");
5923 free(p);
5924 goto done;
5926 free(p);
5927 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5928 if (error)
5929 goto done;
5930 } else {
5931 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5932 if (error)
5933 goto done;
5934 if (path == NULL)
5935 path = "/";
5936 error = got_repo_map_path(&in_repo_path, repo, path);
5937 if (error != NULL)
5938 goto done;
5941 if (commit_id_str == NULL) {
5942 struct got_reference *head_ref;
5943 if (worktree)
5944 refname = got_worktree_get_head_ref_name(worktree);
5945 else
5946 refname = GOT_REF_HEAD;
5947 error = got_ref_open(&head_ref, repo, refname, 0);
5948 if (error != NULL)
5949 goto done;
5950 error = got_ref_resolve(&commit_id, repo, head_ref);
5951 got_ref_close(head_ref);
5952 if (error != NULL)
5953 goto done;
5954 } else {
5955 struct got_reflist_head refs;
5956 TAILQ_INIT(&refs);
5957 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5958 NULL);
5959 if (error)
5960 goto done;
5961 error = got_repo_match_object_id(&commit_id, NULL,
5962 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5963 got_ref_list_free(&refs);
5964 if (error)
5965 goto done;
5968 if (worktree) {
5969 /* Release work tree lock. */
5970 got_worktree_close(worktree);
5971 worktree = NULL;
5974 error = got_object_open_as_commit(&commit, repo, commit_id);
5975 if (error)
5976 goto done;
5978 error = print_tree(in_repo_path, commit, show_ids, recurse,
5979 in_repo_path, repo);
5980 done:
5981 free(in_repo_path);
5982 free(repo_path);
5983 free(cwd);
5984 free(commit_id);
5985 if (commit)
5986 got_object_commit_close(commit);
5987 if (worktree)
5988 got_worktree_close(worktree);
5989 if (repo) {
5990 const struct got_error *close_err = got_repo_close(repo);
5991 if (error == NULL)
5992 error = close_err;
5994 if (pack_fds) {
5995 const struct got_error *pack_err =
5996 got_repo_pack_fds_close(pack_fds);
5997 if (error == NULL)
5998 error = pack_err;
6000 return error;
6003 __dead static void
6004 usage_status(void)
6006 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
6007 "[-S status-codes] [path ...]\n", getprogname());
6008 exit(1);
6011 struct got_status_arg {
6012 char *status_codes;
6013 int suppress;
6016 static const struct got_error *
6017 print_status(void *arg, unsigned char status, unsigned char staged_status,
6018 const char *path, struct got_object_id *blob_id,
6019 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6020 int dirfd, const char *de_name)
6022 struct got_status_arg *st = arg;
6024 if (status == staged_status && (status == GOT_STATUS_DELETE))
6025 status = GOT_STATUS_NO_CHANGE;
6026 if (st != NULL && st->status_codes) {
6027 size_t ncodes = strlen(st->status_codes);
6028 int i, j = 0;
6030 for (i = 0; i < ncodes ; i++) {
6031 if (st->suppress) {
6032 if (status == st->status_codes[i] ||
6033 staged_status == st->status_codes[i]) {
6034 j++;
6035 continue;
6037 } else {
6038 if (status == st->status_codes[i] ||
6039 staged_status == st->status_codes[i])
6040 break;
6044 if (st->suppress && j == 0)
6045 goto print;
6047 if (i == ncodes)
6048 return NULL;
6050 print:
6051 printf("%c%c %s\n", status, staged_status, path);
6052 return NULL;
6055 static const struct got_error *
6056 cmd_status(int argc, char *argv[])
6058 const struct got_error *error = NULL;
6059 struct got_repository *repo = NULL;
6060 struct got_worktree *worktree = NULL;
6061 struct got_status_arg st;
6062 char *cwd = NULL;
6063 struct got_pathlist_head paths;
6064 struct got_pathlist_entry *pe;
6065 int ch, i, no_ignores = 0;
6066 int *pack_fds = NULL;
6068 TAILQ_INIT(&paths);
6070 memset(&st, 0, sizeof(st));
6071 st.status_codes = NULL;
6072 st.suppress = 0;
6074 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6075 switch (ch) {
6076 case 'I':
6077 no_ignores = 1;
6078 break;
6079 case 'S':
6080 if (st.status_codes != NULL && st.suppress == 0)
6081 option_conflict('S', 's');
6082 st.suppress = 1;
6083 /* fallthrough */
6084 case 's':
6085 for (i = 0; i < strlen(optarg); i++) {
6086 switch (optarg[i]) {
6087 case GOT_STATUS_MODIFY:
6088 case GOT_STATUS_ADD:
6089 case GOT_STATUS_DELETE:
6090 case GOT_STATUS_CONFLICT:
6091 case GOT_STATUS_MISSING:
6092 case GOT_STATUS_OBSTRUCTED:
6093 case GOT_STATUS_UNVERSIONED:
6094 case GOT_STATUS_MODE_CHANGE:
6095 case GOT_STATUS_NONEXISTENT:
6096 break;
6097 default:
6098 errx(1, "invalid status code '%c'",
6099 optarg[i]);
6102 if (ch == 's' && st.suppress)
6103 option_conflict('s', 'S');
6104 st.status_codes = optarg;
6105 break;
6106 default:
6107 usage_status();
6108 /* NOTREACHED */
6112 argc -= optind;
6113 argv += optind;
6115 #ifndef PROFILE
6116 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6117 NULL) == -1)
6118 err(1, "pledge");
6119 #endif
6120 cwd = getcwd(NULL, 0);
6121 if (cwd == NULL) {
6122 error = got_error_from_errno("getcwd");
6123 goto done;
6126 error = got_repo_pack_fds_open(&pack_fds);
6127 if (error != NULL)
6128 goto done;
6130 error = got_worktree_open(&worktree, cwd);
6131 if (error) {
6132 if (error->code == GOT_ERR_NOT_WORKTREE)
6133 error = wrap_not_worktree_error(error, "status", cwd);
6134 goto done;
6137 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6138 NULL, pack_fds);
6139 if (error != NULL)
6140 goto done;
6142 error = apply_unveil(got_repo_get_path(repo), 1,
6143 got_worktree_get_root_path(worktree));
6144 if (error)
6145 goto done;
6147 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6148 if (error)
6149 goto done;
6151 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6152 print_status, &st, check_cancelled, NULL);
6153 done:
6154 if (pack_fds) {
6155 const struct got_error *pack_err =
6156 got_repo_pack_fds_close(pack_fds);
6157 if (error == NULL)
6158 error = pack_err;
6161 TAILQ_FOREACH(pe, &paths, entry)
6162 free((char *)pe->path);
6163 got_pathlist_free(&paths);
6164 free(cwd);
6165 return error;
6168 __dead static void
6169 usage_ref(void)
6171 fprintf(stderr,
6172 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6173 "[-s reference] [-d] [name]\n",
6174 getprogname());
6175 exit(1);
6178 static const struct got_error *
6179 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6181 static const struct got_error *err = NULL;
6182 struct got_reflist_head refs;
6183 struct got_reflist_entry *re;
6185 TAILQ_INIT(&refs);
6186 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6187 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6188 repo);
6189 if (err)
6190 return err;
6192 TAILQ_FOREACH(re, &refs, entry) {
6193 char *refstr;
6194 refstr = got_ref_to_str(re->ref);
6195 if (refstr == NULL) {
6196 err = got_error_from_errno("got_ref_to_str");
6197 break;
6199 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6200 free(refstr);
6203 got_ref_list_free(&refs);
6204 return err;
6207 static const struct got_error *
6208 delete_ref_by_name(struct got_repository *repo, const char *refname)
6210 const struct got_error *err;
6211 struct got_reference *ref;
6213 err = got_ref_open(&ref, repo, refname, 0);
6214 if (err)
6215 return err;
6217 err = delete_ref(repo, ref);
6218 got_ref_close(ref);
6219 return err;
6222 static const struct got_error *
6223 add_ref(struct got_repository *repo, const char *refname, const char *target)
6225 const struct got_error *err = NULL;
6226 struct got_object_id *id = NULL;
6227 struct got_reference *ref = NULL;
6228 struct got_reflist_head refs;
6231 * Don't let the user create a reference name with a leading '-'.
6232 * While technically a valid reference name, this case is usually
6233 * an unintended typo.
6235 if (refname[0] == '-')
6236 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6238 TAILQ_INIT(&refs);
6239 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6240 if (err)
6241 goto done;
6242 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6243 &refs, repo);
6244 got_ref_list_free(&refs);
6245 if (err)
6246 goto done;
6248 err = got_ref_alloc(&ref, refname, id);
6249 if (err)
6250 goto done;
6252 err = got_ref_write(ref, repo);
6253 done:
6254 if (ref)
6255 got_ref_close(ref);
6256 free(id);
6257 return err;
6260 static const struct got_error *
6261 add_symref(struct got_repository *repo, const char *refname, const char *target)
6263 const struct got_error *err = NULL;
6264 struct got_reference *ref = NULL;
6265 struct got_reference *target_ref = NULL;
6268 * Don't let the user create a reference name with a leading '-'.
6269 * While technically a valid reference name, this case is usually
6270 * an unintended typo.
6272 if (refname[0] == '-')
6273 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6275 err = got_ref_open(&target_ref, repo, target, 0);
6276 if (err)
6277 return err;
6279 err = got_ref_alloc_symref(&ref, refname, target_ref);
6280 if (err)
6281 goto done;
6283 err = got_ref_write(ref, repo);
6284 done:
6285 if (target_ref)
6286 got_ref_close(target_ref);
6287 if (ref)
6288 got_ref_close(ref);
6289 return err;
6292 static const struct got_error *
6293 cmd_ref(int argc, char *argv[])
6295 const struct got_error *error = NULL;
6296 struct got_repository *repo = NULL;
6297 struct got_worktree *worktree = NULL;
6298 char *cwd = NULL, *repo_path = NULL;
6299 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6300 const char *obj_arg = NULL, *symref_target= NULL;
6301 char *refname = NULL;
6302 int *pack_fds = NULL;
6304 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6305 switch (ch) {
6306 case 'c':
6307 obj_arg = optarg;
6308 break;
6309 case 'd':
6310 do_delete = 1;
6311 break;
6312 case 'r':
6313 repo_path = realpath(optarg, NULL);
6314 if (repo_path == NULL)
6315 return got_error_from_errno2("realpath",
6316 optarg);
6317 got_path_strip_trailing_slashes(repo_path);
6318 break;
6319 case 'l':
6320 do_list = 1;
6321 break;
6322 case 's':
6323 symref_target = optarg;
6324 break;
6325 case 't':
6326 sort_by_time = 1;
6327 break;
6328 default:
6329 usage_ref();
6330 /* NOTREACHED */
6334 if (obj_arg && do_list)
6335 option_conflict('c', 'l');
6336 if (obj_arg && do_delete)
6337 option_conflict('c', 'd');
6338 if (obj_arg && symref_target)
6339 option_conflict('c', 's');
6340 if (symref_target && do_delete)
6341 option_conflict('s', 'd');
6342 if (symref_target && do_list)
6343 option_conflict('s', 'l');
6344 if (do_delete && do_list)
6345 option_conflict('d', 'l');
6346 if (sort_by_time && !do_list)
6347 errx(1, "-t option requires -l option");
6349 argc -= optind;
6350 argv += optind;
6352 if (do_list) {
6353 if (argc != 0 && argc != 1)
6354 usage_ref();
6355 if (argc == 1) {
6356 refname = strdup(argv[0]);
6357 if (refname == NULL) {
6358 error = got_error_from_errno("strdup");
6359 goto done;
6362 } else {
6363 if (argc != 1)
6364 usage_ref();
6365 refname = strdup(argv[0]);
6366 if (refname == NULL) {
6367 error = got_error_from_errno("strdup");
6368 goto done;
6372 if (refname)
6373 got_path_strip_trailing_slashes(refname);
6375 #ifndef PROFILE
6376 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6377 "sendfd unveil", NULL) == -1)
6378 err(1, "pledge");
6379 #endif
6380 cwd = getcwd(NULL, 0);
6381 if (cwd == NULL) {
6382 error = got_error_from_errno("getcwd");
6383 goto done;
6386 error = got_repo_pack_fds_open(&pack_fds);
6387 if (error != NULL)
6388 goto done;
6390 if (repo_path == NULL) {
6391 error = got_worktree_open(&worktree, cwd);
6392 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6393 goto done;
6394 else
6395 error = NULL;
6396 if (worktree) {
6397 repo_path =
6398 strdup(got_worktree_get_repo_path(worktree));
6399 if (repo_path == NULL)
6400 error = got_error_from_errno("strdup");
6401 if (error)
6402 goto done;
6403 } else {
6404 repo_path = strdup(cwd);
6405 if (repo_path == NULL) {
6406 error = got_error_from_errno("strdup");
6407 goto done;
6412 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6413 if (error != NULL)
6414 goto done;
6416 #ifndef PROFILE
6417 if (do_list) {
6418 /* Remove "cpath" promise. */
6419 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6420 NULL) == -1)
6421 err(1, "pledge");
6423 #endif
6425 error = apply_unveil(got_repo_get_path(repo), do_list,
6426 worktree ? got_worktree_get_root_path(worktree) : NULL);
6427 if (error)
6428 goto done;
6430 if (do_list)
6431 error = list_refs(repo, refname, sort_by_time);
6432 else if (do_delete)
6433 error = delete_ref_by_name(repo, refname);
6434 else if (symref_target)
6435 error = add_symref(repo, refname, symref_target);
6436 else {
6437 if (obj_arg == NULL)
6438 usage_ref();
6439 error = add_ref(repo, refname, obj_arg);
6441 done:
6442 free(refname);
6443 if (repo) {
6444 const struct got_error *close_err = got_repo_close(repo);
6445 if (error == NULL)
6446 error = close_err;
6448 if (worktree)
6449 got_worktree_close(worktree);
6450 if (pack_fds) {
6451 const struct got_error *pack_err =
6452 got_repo_pack_fds_close(pack_fds);
6453 if (error == NULL)
6454 error = pack_err;
6456 free(cwd);
6457 free(repo_path);
6458 return error;
6461 __dead static void
6462 usage_branch(void)
6464 fprintf(stderr,
6465 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6466 "[-n] [name]\n", getprogname());
6467 exit(1);
6470 static const struct got_error *
6471 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6472 struct got_reference *ref)
6474 const struct got_error *err = NULL;
6475 const char *refname, *marker = " ";
6476 char *refstr;
6478 refname = got_ref_get_name(ref);
6479 if (worktree && strcmp(refname,
6480 got_worktree_get_head_ref_name(worktree)) == 0) {
6481 struct got_object_id *id = NULL;
6483 err = got_ref_resolve(&id, repo, ref);
6484 if (err)
6485 return err;
6486 if (got_object_id_cmp(id,
6487 got_worktree_get_base_commit_id(worktree)) == 0)
6488 marker = "* ";
6489 else
6490 marker = "~ ";
6491 free(id);
6494 if (strncmp(refname, "refs/heads/", 11) == 0)
6495 refname += 11;
6496 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6497 refname += 18;
6498 if (strncmp(refname, "refs/remotes/", 13) == 0)
6499 refname += 13;
6501 refstr = got_ref_to_str(ref);
6502 if (refstr == NULL)
6503 return got_error_from_errno("got_ref_to_str");
6505 printf("%s%s: %s\n", marker, refname, refstr);
6506 free(refstr);
6507 return NULL;
6510 static const struct got_error *
6511 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6513 const char *refname;
6515 if (worktree == NULL)
6516 return got_error(GOT_ERR_NOT_WORKTREE);
6518 refname = got_worktree_get_head_ref_name(worktree);
6520 if (strncmp(refname, "refs/heads/", 11) == 0)
6521 refname += 11;
6522 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6523 refname += 18;
6525 printf("%s\n", refname);
6527 return NULL;
6530 static const struct got_error *
6531 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6532 int sort_by_time)
6534 static const struct got_error *err = NULL;
6535 struct got_reflist_head refs;
6536 struct got_reflist_entry *re;
6537 struct got_reference *temp_ref = NULL;
6538 int rebase_in_progress, histedit_in_progress;
6540 TAILQ_INIT(&refs);
6542 if (worktree) {
6543 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6544 worktree);
6545 if (err)
6546 return err;
6548 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6549 worktree);
6550 if (err)
6551 return err;
6553 if (rebase_in_progress || histedit_in_progress) {
6554 err = got_ref_open(&temp_ref, repo,
6555 got_worktree_get_head_ref_name(worktree), 0);
6556 if (err)
6557 return err;
6558 list_branch(repo, worktree, temp_ref);
6559 got_ref_close(temp_ref);
6563 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6564 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6565 repo);
6566 if (err)
6567 return err;
6569 TAILQ_FOREACH(re, &refs, entry)
6570 list_branch(repo, worktree, re->ref);
6572 got_ref_list_free(&refs);
6574 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6575 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6576 repo);
6577 if (err)
6578 return err;
6580 TAILQ_FOREACH(re, &refs, entry)
6581 list_branch(repo, worktree, re->ref);
6583 got_ref_list_free(&refs);
6585 return NULL;
6588 static const struct got_error *
6589 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6590 const char *branch_name)
6592 const struct got_error *err = NULL;
6593 struct got_reference *ref = NULL;
6594 char *refname, *remote_refname = NULL;
6596 if (strncmp(branch_name, "refs/", 5) == 0)
6597 branch_name += 5;
6598 if (strncmp(branch_name, "heads/", 6) == 0)
6599 branch_name += 6;
6600 else if (strncmp(branch_name, "remotes/", 8) == 0)
6601 branch_name += 8;
6603 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6604 return got_error_from_errno("asprintf");
6606 if (asprintf(&remote_refname, "refs/remotes/%s",
6607 branch_name) == -1) {
6608 err = got_error_from_errno("asprintf");
6609 goto done;
6612 err = got_ref_open(&ref, repo, refname, 0);
6613 if (err) {
6614 const struct got_error *err2;
6615 if (err->code != GOT_ERR_NOT_REF)
6616 goto done;
6618 * Keep 'err' intact such that if neither branch exists
6619 * we report "refs/heads" rather than "refs/remotes" in
6620 * our error message.
6622 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6623 if (err2)
6624 goto done;
6625 err = NULL;
6628 if (worktree &&
6629 strcmp(got_worktree_get_head_ref_name(worktree),
6630 got_ref_get_name(ref)) == 0) {
6631 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6632 "will not delete this work tree's current branch");
6633 goto done;
6636 err = delete_ref(repo, ref);
6637 done:
6638 if (ref)
6639 got_ref_close(ref);
6640 free(refname);
6641 free(remote_refname);
6642 return err;
6645 static const struct got_error *
6646 add_branch(struct got_repository *repo, const char *branch_name,
6647 struct got_object_id *base_commit_id)
6649 const struct got_error *err = NULL;
6650 struct got_reference *ref = NULL;
6651 char *base_refname = NULL, *refname = NULL;
6654 * Don't let the user create a branch name with a leading '-'.
6655 * While technically a valid reference name, this case is usually
6656 * an unintended typo.
6658 if (branch_name[0] == '-')
6659 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6661 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6662 branch_name += 11;
6664 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6665 err = got_error_from_errno("asprintf");
6666 goto done;
6669 err = got_ref_open(&ref, repo, refname, 0);
6670 if (err == NULL) {
6671 err = got_error(GOT_ERR_BRANCH_EXISTS);
6672 goto done;
6673 } else if (err->code != GOT_ERR_NOT_REF)
6674 goto done;
6676 err = got_ref_alloc(&ref, refname, base_commit_id);
6677 if (err)
6678 goto done;
6680 err = got_ref_write(ref, repo);
6681 done:
6682 if (ref)
6683 got_ref_close(ref);
6684 free(base_refname);
6685 free(refname);
6686 return err;
6689 static const struct got_error *
6690 cmd_branch(int argc, char *argv[])
6692 const struct got_error *error = NULL;
6693 struct got_repository *repo = NULL;
6694 struct got_worktree *worktree = NULL;
6695 char *cwd = NULL, *repo_path = NULL;
6696 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6697 const char *delref = NULL, *commit_id_arg = NULL;
6698 struct got_reference *ref = NULL;
6699 struct got_pathlist_head paths;
6700 struct got_pathlist_entry *pe;
6701 struct got_object_id *commit_id = NULL;
6702 char *commit_id_str = NULL;
6703 int *pack_fds = NULL;
6705 TAILQ_INIT(&paths);
6707 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6708 switch (ch) {
6709 case 'c':
6710 commit_id_arg = optarg;
6711 break;
6712 case 'd':
6713 delref = optarg;
6714 break;
6715 case 'r':
6716 repo_path = realpath(optarg, NULL);
6717 if (repo_path == NULL)
6718 return got_error_from_errno2("realpath",
6719 optarg);
6720 got_path_strip_trailing_slashes(repo_path);
6721 break;
6722 case 'l':
6723 do_list = 1;
6724 break;
6725 case 'n':
6726 do_update = 0;
6727 break;
6728 case 't':
6729 sort_by_time = 1;
6730 break;
6731 default:
6732 usage_branch();
6733 /* NOTREACHED */
6737 if (do_list && delref)
6738 option_conflict('l', 'd');
6739 if (sort_by_time && !do_list)
6740 errx(1, "-t option requires -l option");
6742 argc -= optind;
6743 argv += optind;
6745 if (!do_list && !delref && argc == 0)
6746 do_show = 1;
6748 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6749 errx(1, "-c option can only be used when creating a branch");
6751 if (do_list || delref) {
6752 if (argc > 0)
6753 usage_branch();
6754 } else if (!do_show && argc != 1)
6755 usage_branch();
6757 #ifndef PROFILE
6758 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6759 "sendfd unveil", NULL) == -1)
6760 err(1, "pledge");
6761 #endif
6762 cwd = getcwd(NULL, 0);
6763 if (cwd == NULL) {
6764 error = got_error_from_errno("getcwd");
6765 goto done;
6768 error = got_repo_pack_fds_open(&pack_fds);
6769 if (error != NULL)
6770 goto done;
6772 if (repo_path == NULL) {
6773 error = got_worktree_open(&worktree, cwd);
6774 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6775 goto done;
6776 else
6777 error = NULL;
6778 if (worktree) {
6779 repo_path =
6780 strdup(got_worktree_get_repo_path(worktree));
6781 if (repo_path == NULL)
6782 error = got_error_from_errno("strdup");
6783 if (error)
6784 goto done;
6785 } else {
6786 repo_path = strdup(cwd);
6787 if (repo_path == NULL) {
6788 error = got_error_from_errno("strdup");
6789 goto done;
6794 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6795 if (error != NULL)
6796 goto done;
6798 #ifndef PROFILE
6799 if (do_list || do_show) {
6800 /* Remove "cpath" promise. */
6801 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6802 NULL) == -1)
6803 err(1, "pledge");
6805 #endif
6807 error = apply_unveil(got_repo_get_path(repo), do_list,
6808 worktree ? got_worktree_get_root_path(worktree) : NULL);
6809 if (error)
6810 goto done;
6812 if (do_show)
6813 error = show_current_branch(repo, worktree);
6814 else if (do_list)
6815 error = list_branches(repo, worktree, sort_by_time);
6816 else if (delref)
6817 error = delete_branch(repo, worktree, delref);
6818 else {
6819 struct got_reflist_head refs;
6820 TAILQ_INIT(&refs);
6821 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6822 NULL);
6823 if (error)
6824 goto done;
6825 if (commit_id_arg == NULL)
6826 commit_id_arg = worktree ?
6827 got_worktree_get_head_ref_name(worktree) :
6828 GOT_REF_HEAD;
6829 error = got_repo_match_object_id(&commit_id, NULL,
6830 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6831 got_ref_list_free(&refs);
6832 if (error)
6833 goto done;
6834 error = add_branch(repo, argv[0], commit_id);
6835 if (error)
6836 goto done;
6837 if (worktree && do_update) {
6838 struct got_update_progress_arg upa;
6839 char *branch_refname = NULL;
6841 error = got_object_id_str(&commit_id_str, commit_id);
6842 if (error)
6843 goto done;
6844 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6845 worktree);
6846 if (error)
6847 goto done;
6848 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6849 == -1) {
6850 error = got_error_from_errno("asprintf");
6851 goto done;
6853 error = got_ref_open(&ref, repo, branch_refname, 0);
6854 free(branch_refname);
6855 if (error)
6856 goto done;
6857 error = switch_head_ref(ref, commit_id, worktree,
6858 repo);
6859 if (error)
6860 goto done;
6861 error = got_worktree_set_base_commit_id(worktree, repo,
6862 commit_id);
6863 if (error)
6864 goto done;
6865 memset(&upa, 0, sizeof(upa));
6866 error = got_worktree_checkout_files(worktree, &paths,
6867 repo, update_progress, &upa, check_cancelled,
6868 NULL);
6869 if (error)
6870 goto done;
6871 if (upa.did_something) {
6872 printf("Updated to %s: %s\n",
6873 got_worktree_get_head_ref_name(worktree),
6874 commit_id_str);
6876 print_update_progress_stats(&upa);
6879 done:
6880 if (ref)
6881 got_ref_close(ref);
6882 if (repo) {
6883 const struct got_error *close_err = got_repo_close(repo);
6884 if (error == NULL)
6885 error = close_err;
6887 if (worktree)
6888 got_worktree_close(worktree);
6889 if (pack_fds) {
6890 const struct got_error *pack_err =
6891 got_repo_pack_fds_close(pack_fds);
6892 if (error == NULL)
6893 error = pack_err;
6895 free(cwd);
6896 free(repo_path);
6897 free(commit_id);
6898 free(commit_id_str);
6899 TAILQ_FOREACH(pe, &paths, entry)
6900 free((char *)pe->path);
6901 got_pathlist_free(&paths);
6902 return error;
6906 __dead static void
6907 usage_tag(void)
6909 fprintf(stderr,
6910 "usage: %s tag [-c commit] [-r repository] [-l] "
6911 "[-m message] [-s signer-id] [-v] [-V] name\n",
6912 getprogname());
6913 exit(1);
6916 #if 0
6917 static const struct got_error *
6918 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6920 const struct got_error *err = NULL;
6921 struct got_reflist_entry *re, *se, *new;
6922 struct got_object_id *re_id, *se_id;
6923 struct got_tag_object *re_tag, *se_tag;
6924 time_t re_time, se_time;
6926 STAILQ_FOREACH(re, tags, entry) {
6927 se = STAILQ_FIRST(sorted);
6928 if (se == NULL) {
6929 err = got_reflist_entry_dup(&new, re);
6930 if (err)
6931 return err;
6932 STAILQ_INSERT_HEAD(sorted, new, entry);
6933 continue;
6934 } else {
6935 err = got_ref_resolve(&re_id, repo, re->ref);
6936 if (err)
6937 break;
6938 err = got_object_open_as_tag(&re_tag, repo, re_id);
6939 free(re_id);
6940 if (err)
6941 break;
6942 re_time = got_object_tag_get_tagger_time(re_tag);
6943 got_object_tag_close(re_tag);
6946 while (se) {
6947 err = got_ref_resolve(&se_id, repo, re->ref);
6948 if (err)
6949 break;
6950 err = got_object_open_as_tag(&se_tag, repo, se_id);
6951 free(se_id);
6952 if (err)
6953 break;
6954 se_time = got_object_tag_get_tagger_time(se_tag);
6955 got_object_tag_close(se_tag);
6957 if (se_time > re_time) {
6958 err = got_reflist_entry_dup(&new, re);
6959 if (err)
6960 return err;
6961 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6962 break;
6964 se = STAILQ_NEXT(se, entry);
6965 continue;
6968 done:
6969 return err;
6971 #endif
6973 static const struct got_error *
6974 get_tag_refname(char **refname, const char *tag_name)
6976 const struct got_error *err;
6978 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6979 *refname = strdup(tag_name);
6980 if (*refname == NULL)
6981 return got_error_from_errno("strdup");
6982 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6983 err = got_error_from_errno("asprintf");
6984 *refname = NULL;
6985 return err;
6988 return NULL;
6991 static const struct got_error *
6992 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6993 const char *allowed_signers, const char *revoked_signers, int verbosity)
6995 static const struct got_error *err = NULL;
6996 struct got_reflist_head refs;
6997 struct got_reflist_entry *re;
6998 char *wanted_refname = NULL;
6999 int bad_sigs = 0;
7001 TAILQ_INIT(&refs);
7003 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7004 if (err)
7005 return err;
7007 if (tag_name) {
7008 struct got_reference *ref;
7009 err = get_tag_refname(&wanted_refname, tag_name);
7010 if (err)
7011 goto done;
7012 /* Wanted tag reference should exist. */
7013 err = got_ref_open(&ref, repo, wanted_refname, 0);
7014 if (err)
7015 goto done;
7016 got_ref_close(ref);
7019 TAILQ_FOREACH(re, &refs, entry) {
7020 const char *refname;
7021 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7022 char datebuf[26];
7023 const char *tagger, *ssh_sig = NULL;
7024 char *sig_msg = NULL;
7025 time_t tagger_time;
7026 struct got_object_id *id;
7027 struct got_tag_object *tag;
7028 struct got_commit_object *commit = NULL;
7030 refname = got_ref_get_name(re->ref);
7031 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7032 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7033 continue;
7034 refname += 10;
7035 refstr = got_ref_to_str(re->ref);
7036 if (refstr == NULL) {
7037 err = got_error_from_errno("got_ref_to_str");
7038 break;
7041 err = got_ref_resolve(&id, repo, re->ref);
7042 if (err)
7043 break;
7044 err = got_object_open_as_tag(&tag, repo, id);
7045 if (err) {
7046 if (err->code != GOT_ERR_OBJ_TYPE) {
7047 free(id);
7048 break;
7050 /* "lightweight" tag */
7051 err = got_object_open_as_commit(&commit, repo, id);
7052 if (err) {
7053 free(id);
7054 break;
7056 tagger = got_object_commit_get_committer(commit);
7057 tagger_time =
7058 got_object_commit_get_committer_time(commit);
7059 err = got_object_id_str(&id_str, id);
7060 free(id);
7061 if (err)
7062 break;
7063 } else {
7064 free(id);
7065 tagger = got_object_tag_get_tagger(tag);
7066 tagger_time = got_object_tag_get_tagger_time(tag);
7067 err = got_object_id_str(&id_str,
7068 got_object_tag_get_object_id(tag));
7069 if (err)
7070 break;
7073 if (verify_tags) {
7074 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7075 got_object_tag_get_message(tag));
7076 if (ssh_sig && allowed_signers == NULL) {
7077 err = got_error_msg(
7078 GOT_ERR_VERIFY_TAG_SIGNATURE,
7079 "SSH signature verification requires "
7080 "setting allowed_signers in "
7081 "got.conf(5)");
7082 break;
7086 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7087 free(refstr);
7088 printf("from: %s\n", tagger);
7089 datestr = get_datestr(&tagger_time, datebuf);
7090 if (datestr)
7091 printf("date: %s UTC\n", datestr);
7092 if (commit)
7093 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7094 else {
7095 switch (got_object_tag_get_object_type(tag)) {
7096 case GOT_OBJ_TYPE_BLOB:
7097 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7098 id_str);
7099 break;
7100 case GOT_OBJ_TYPE_TREE:
7101 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7102 id_str);
7103 break;
7104 case GOT_OBJ_TYPE_COMMIT:
7105 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7106 id_str);
7107 break;
7108 case GOT_OBJ_TYPE_TAG:
7109 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7110 id_str);
7111 break;
7112 default:
7113 break;
7116 free(id_str);
7118 if (ssh_sig) {
7119 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7120 allowed_signers, revoked_signers, verbosity);
7121 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7122 bad_sigs = 1;
7123 else if (err)
7124 break;
7125 printf("signature: %s", sig_msg);
7126 free(sig_msg);
7127 sig_msg = NULL;
7130 if (commit) {
7131 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7132 if (err)
7133 break;
7134 got_object_commit_close(commit);
7135 } else {
7136 tagmsg0 = strdup(got_object_tag_get_message(tag));
7137 got_object_tag_close(tag);
7138 if (tagmsg0 == NULL) {
7139 err = got_error_from_errno("strdup");
7140 break;
7144 tagmsg = tagmsg0;
7145 do {
7146 line = strsep(&tagmsg, "\n");
7147 if (line)
7148 printf(" %s\n", line);
7149 } while (line);
7150 free(tagmsg0);
7152 done:
7153 got_ref_list_free(&refs);
7154 free(wanted_refname);
7156 if (err == NULL && bad_sigs)
7157 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7158 return err;
7161 static const struct got_error *
7162 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7163 const char *tag_name, const char *repo_path)
7165 const struct got_error *err = NULL;
7166 char *template = NULL, *initial_content = NULL;
7167 char *editor = NULL;
7168 int initial_content_len;
7169 int fd = -1;
7171 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7172 err = got_error_from_errno("asprintf");
7173 goto done;
7176 initial_content_len = asprintf(&initial_content,
7177 "\n# tagging commit %s as %s\n",
7178 commit_id_str, tag_name);
7179 if (initial_content_len == -1) {
7180 err = got_error_from_errno("asprintf");
7181 goto done;
7184 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7185 if (err)
7186 goto done;
7188 if (write(fd, initial_content, initial_content_len) == -1) {
7189 err = got_error_from_errno2("write", *tagmsg_path);
7190 goto done;
7193 err = get_editor(&editor);
7194 if (err)
7195 goto done;
7196 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7197 initial_content_len, 1);
7198 done:
7199 free(initial_content);
7200 free(template);
7201 free(editor);
7203 if (fd != -1 && close(fd) == -1 && err == NULL)
7204 err = got_error_from_errno2("close", *tagmsg_path);
7206 if (err) {
7207 free(*tagmsg);
7208 *tagmsg = NULL;
7210 return err;
7213 static const struct got_error *
7214 add_tag(struct got_repository *repo, const char *tagger,
7215 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7216 const char *signer_id, int verbosity)
7218 const struct got_error *err = NULL;
7219 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7220 char *label = NULL, *commit_id_str = NULL;
7221 struct got_reference *ref = NULL;
7222 char *refname = NULL, *tagmsg = NULL;
7223 char *tagmsg_path = NULL, *tag_id_str = NULL;
7224 int preserve_tagmsg = 0;
7225 struct got_reflist_head refs;
7227 TAILQ_INIT(&refs);
7230 * Don't let the user create a tag name with a leading '-'.
7231 * While technically a valid reference name, this case is usually
7232 * an unintended typo.
7234 if (tag_name[0] == '-')
7235 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7237 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7238 if (err)
7239 goto done;
7241 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7242 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7243 if (err)
7244 goto done;
7246 err = got_object_id_str(&commit_id_str, commit_id);
7247 if (err)
7248 goto done;
7250 err = get_tag_refname(&refname, tag_name);
7251 if (err)
7252 goto done;
7253 if (strncmp("refs/tags/", tag_name, 10) == 0)
7254 tag_name += 10;
7256 err = got_ref_open(&ref, repo, refname, 0);
7257 if (err == NULL) {
7258 err = got_error(GOT_ERR_TAG_EXISTS);
7259 goto done;
7260 } else if (err->code != GOT_ERR_NOT_REF)
7261 goto done;
7263 if (tagmsg_arg == NULL) {
7264 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7265 tag_name, got_repo_get_path(repo));
7266 if (err) {
7267 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7268 tagmsg_path != NULL)
7269 preserve_tagmsg = 1;
7270 goto done;
7272 /* Editor is done; we can now apply unveil(2) */
7273 err = got_sigs_apply_unveil();
7274 if (err)
7275 goto done;
7276 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7277 if (err)
7278 goto done;
7281 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7282 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7283 verbosity);
7284 if (err) {
7285 if (tagmsg_path)
7286 preserve_tagmsg = 1;
7287 goto done;
7290 err = got_ref_alloc(&ref, refname, tag_id);
7291 if (err) {
7292 if (tagmsg_path)
7293 preserve_tagmsg = 1;
7294 goto done;
7297 err = got_ref_write(ref, repo);
7298 if (err) {
7299 if (tagmsg_path)
7300 preserve_tagmsg = 1;
7301 goto done;
7304 err = got_object_id_str(&tag_id_str, tag_id);
7305 if (err) {
7306 if (tagmsg_path)
7307 preserve_tagmsg = 1;
7308 goto done;
7310 printf("Created tag %s\n", tag_id_str);
7311 done:
7312 if (preserve_tagmsg) {
7313 fprintf(stderr, "%s: tag message preserved in %s\n",
7314 getprogname(), tagmsg_path);
7315 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7316 err = got_error_from_errno2("unlink", tagmsg_path);
7317 free(tag_id_str);
7318 if (ref)
7319 got_ref_close(ref);
7320 free(commit_id);
7321 free(commit_id_str);
7322 free(refname);
7323 free(tagmsg);
7324 free(tagmsg_path);
7325 got_ref_list_free(&refs);
7326 return err;
7329 static const struct got_error *
7330 cmd_tag(int argc, char *argv[])
7332 const struct got_error *error = NULL;
7333 struct got_repository *repo = NULL;
7334 struct got_worktree *worktree = NULL;
7335 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7336 char *gitconfig_path = NULL, *tagger = NULL;
7337 char *allowed_signers = NULL, *revoked_signers = NULL;
7338 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7339 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7340 const char *signer_id = NULL;
7341 int *pack_fds = NULL;
7343 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7344 switch (ch) {
7345 case 'c':
7346 commit_id_arg = optarg;
7347 break;
7348 case 'm':
7349 tagmsg = optarg;
7350 break;
7351 case 'r':
7352 repo_path = realpath(optarg, NULL);
7353 if (repo_path == NULL)
7354 return got_error_from_errno2("realpath",
7355 optarg);
7356 got_path_strip_trailing_slashes(repo_path);
7357 break;
7358 case 'l':
7359 do_list = 1;
7360 break;
7361 case 's':
7362 signer_id = optarg;
7363 break;
7364 case 'V':
7365 verify_tags = 1;
7366 break;
7367 case 'v':
7368 if (verbosity < 0)
7369 verbosity = 0;
7370 else if (verbosity < 3)
7371 verbosity++;
7372 break;
7373 default:
7374 usage_tag();
7375 /* NOTREACHED */
7379 argc -= optind;
7380 argv += optind;
7382 if (do_list || verify_tags) {
7383 if (commit_id_arg != NULL)
7384 errx(1,
7385 "-c option can only be used when creating a tag");
7386 if (tagmsg) {
7387 if (do_list)
7388 option_conflict('l', 'm');
7389 else
7390 option_conflict('V', 'm');
7392 if (signer_id) {
7393 if (do_list)
7394 option_conflict('l', 's');
7395 else
7396 option_conflict('V', 's');
7398 if (argc > 1)
7399 usage_tag();
7400 } else if (argc != 1)
7401 usage_tag();
7403 if (argc == 1)
7404 tag_name = argv[0];
7406 #ifndef PROFILE
7407 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7408 "sendfd unveil", NULL) == -1)
7409 err(1, "pledge");
7410 #endif
7411 cwd = getcwd(NULL, 0);
7412 if (cwd == NULL) {
7413 error = got_error_from_errno("getcwd");
7414 goto done;
7417 error = got_repo_pack_fds_open(&pack_fds);
7418 if (error != NULL)
7419 goto done;
7421 if (repo_path == NULL) {
7422 error = got_worktree_open(&worktree, cwd);
7423 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7424 goto done;
7425 else
7426 error = NULL;
7427 if (worktree) {
7428 repo_path =
7429 strdup(got_worktree_get_repo_path(worktree));
7430 if (repo_path == NULL)
7431 error = got_error_from_errno("strdup");
7432 if (error)
7433 goto done;
7434 } else {
7435 repo_path = strdup(cwd);
7436 if (repo_path == NULL) {
7437 error = got_error_from_errno("strdup");
7438 goto done;
7443 if (do_list || verify_tags) {
7444 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7445 if (error != NULL)
7446 goto done;
7447 error = get_allowed_signers(&allowed_signers, repo, worktree);
7448 if (error)
7449 goto done;
7450 error = get_revoked_signers(&revoked_signers, repo, worktree);
7451 if (error)
7452 goto done;
7453 if (worktree) {
7454 /* Release work tree lock. */
7455 got_worktree_close(worktree);
7456 worktree = NULL;
7460 * Remove "cpath" promise unless needed for signature tmpfile
7461 * creation.
7463 if (verify_tags)
7464 got_sigs_apply_unveil();
7465 else {
7466 #ifndef PROFILE
7467 if (pledge("stdio rpath wpath flock proc exec sendfd "
7468 "unveil", NULL) == -1)
7469 err(1, "pledge");
7470 #endif
7472 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7473 if (error)
7474 goto done;
7475 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7476 revoked_signers, verbosity);
7477 } else {
7478 error = get_gitconfig_path(&gitconfig_path);
7479 if (error)
7480 goto done;
7481 error = got_repo_open(&repo, repo_path, gitconfig_path,
7482 pack_fds);
7483 if (error != NULL)
7484 goto done;
7486 error = get_author(&tagger, repo, worktree);
7487 if (error)
7488 goto done;
7489 if (worktree) {
7490 /* Release work tree lock. */
7491 got_worktree_close(worktree);
7492 worktree = NULL;
7495 if (tagmsg) {
7496 if (signer_id) {
7497 error = got_sigs_apply_unveil();
7498 if (error)
7499 goto done;
7501 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7502 if (error)
7503 goto done;
7506 if (commit_id_arg == NULL) {
7507 struct got_reference *head_ref;
7508 struct got_object_id *commit_id;
7509 error = got_ref_open(&head_ref, repo,
7510 worktree ? got_worktree_get_head_ref_name(worktree)
7511 : GOT_REF_HEAD, 0);
7512 if (error)
7513 goto done;
7514 error = got_ref_resolve(&commit_id, repo, head_ref);
7515 got_ref_close(head_ref);
7516 if (error)
7517 goto done;
7518 error = got_object_id_str(&commit_id_str, commit_id);
7519 free(commit_id);
7520 if (error)
7521 goto done;
7524 error = add_tag(repo, tagger, tag_name,
7525 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7526 signer_id, verbosity);
7528 done:
7529 if (repo) {
7530 const struct got_error *close_err = got_repo_close(repo);
7531 if (error == NULL)
7532 error = close_err;
7534 if (worktree)
7535 got_worktree_close(worktree);
7536 if (pack_fds) {
7537 const struct got_error *pack_err =
7538 got_repo_pack_fds_close(pack_fds);
7539 if (error == NULL)
7540 error = pack_err;
7542 free(cwd);
7543 free(repo_path);
7544 free(gitconfig_path);
7545 free(commit_id_str);
7546 free(tagger);
7547 free(allowed_signers);
7548 free(revoked_signers);
7549 return error;
7552 __dead static void
7553 usage_add(void)
7555 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7556 getprogname());
7557 exit(1);
7560 static const struct got_error *
7561 add_progress(void *arg, unsigned char status, const char *path)
7563 while (path[0] == '/')
7564 path++;
7565 printf("%c %s\n", status, path);
7566 return NULL;
7569 static const struct got_error *
7570 cmd_add(int argc, char *argv[])
7572 const struct got_error *error = NULL;
7573 struct got_repository *repo = NULL;
7574 struct got_worktree *worktree = NULL;
7575 char *cwd = NULL;
7576 struct got_pathlist_head paths;
7577 struct got_pathlist_entry *pe;
7578 int ch, can_recurse = 0, no_ignores = 0;
7579 int *pack_fds = NULL;
7581 TAILQ_INIT(&paths);
7583 while ((ch = getopt(argc, argv, "IR")) != -1) {
7584 switch (ch) {
7585 case 'I':
7586 no_ignores = 1;
7587 break;
7588 case 'R':
7589 can_recurse = 1;
7590 break;
7591 default:
7592 usage_add();
7593 /* NOTREACHED */
7597 argc -= optind;
7598 argv += optind;
7600 #ifndef PROFILE
7601 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7602 NULL) == -1)
7603 err(1, "pledge");
7604 #endif
7605 if (argc < 1)
7606 usage_add();
7608 cwd = getcwd(NULL, 0);
7609 if (cwd == NULL) {
7610 error = got_error_from_errno("getcwd");
7611 goto done;
7614 error = got_repo_pack_fds_open(&pack_fds);
7615 if (error != NULL)
7616 goto done;
7618 error = got_worktree_open(&worktree, cwd);
7619 if (error) {
7620 if (error->code == GOT_ERR_NOT_WORKTREE)
7621 error = wrap_not_worktree_error(error, "add", cwd);
7622 goto done;
7625 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7626 NULL, pack_fds);
7627 if (error != NULL)
7628 goto done;
7630 error = apply_unveil(got_repo_get_path(repo), 1,
7631 got_worktree_get_root_path(worktree));
7632 if (error)
7633 goto done;
7635 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7636 if (error)
7637 goto done;
7639 if (!can_recurse) {
7640 char *ondisk_path;
7641 struct stat sb;
7642 TAILQ_FOREACH(pe, &paths, entry) {
7643 if (asprintf(&ondisk_path, "%s/%s",
7644 got_worktree_get_root_path(worktree),
7645 pe->path) == -1) {
7646 error = got_error_from_errno("asprintf");
7647 goto done;
7649 if (lstat(ondisk_path, &sb) == -1) {
7650 if (errno == ENOENT) {
7651 free(ondisk_path);
7652 continue;
7654 error = got_error_from_errno2("lstat",
7655 ondisk_path);
7656 free(ondisk_path);
7657 goto done;
7659 free(ondisk_path);
7660 if (S_ISDIR(sb.st_mode)) {
7661 error = got_error_msg(GOT_ERR_BAD_PATH,
7662 "adding directories requires -R option");
7663 goto done;
7668 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7669 NULL, repo, no_ignores);
7670 done:
7671 if (repo) {
7672 const struct got_error *close_err = got_repo_close(repo);
7673 if (error == NULL)
7674 error = close_err;
7676 if (worktree)
7677 got_worktree_close(worktree);
7678 if (pack_fds) {
7679 const struct got_error *pack_err =
7680 got_repo_pack_fds_close(pack_fds);
7681 if (error == NULL)
7682 error = pack_err;
7684 TAILQ_FOREACH(pe, &paths, entry)
7685 free((char *)pe->path);
7686 got_pathlist_free(&paths);
7687 free(cwd);
7688 return error;
7691 __dead static void
7692 usage_remove(void)
7694 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7695 "path ...\n", getprogname());
7696 exit(1);
7699 static const struct got_error *
7700 print_remove_status(void *arg, unsigned char status,
7701 unsigned char staged_status, const char *path)
7703 while (path[0] == '/')
7704 path++;
7705 if (status == GOT_STATUS_NONEXISTENT)
7706 return NULL;
7707 if (status == staged_status && (status == GOT_STATUS_DELETE))
7708 status = GOT_STATUS_NO_CHANGE;
7709 printf("%c%c %s\n", status, staged_status, path);
7710 return NULL;
7713 static const struct got_error *
7714 cmd_remove(int argc, char *argv[])
7716 const struct got_error *error = NULL;
7717 struct got_worktree *worktree = NULL;
7718 struct got_repository *repo = NULL;
7719 const char *status_codes = NULL;
7720 char *cwd = NULL;
7721 struct got_pathlist_head paths;
7722 struct got_pathlist_entry *pe;
7723 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7724 int ignore_missing_paths = 0;
7725 int *pack_fds = NULL;
7727 TAILQ_INIT(&paths);
7729 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7730 switch (ch) {
7731 case 'f':
7732 delete_local_mods = 1;
7733 ignore_missing_paths = 1;
7734 break;
7735 case 'k':
7736 keep_on_disk = 1;
7737 break;
7738 case 'R':
7739 can_recurse = 1;
7740 break;
7741 case 's':
7742 for (i = 0; i < strlen(optarg); i++) {
7743 switch (optarg[i]) {
7744 case GOT_STATUS_MODIFY:
7745 delete_local_mods = 1;
7746 break;
7747 case GOT_STATUS_MISSING:
7748 ignore_missing_paths = 1;
7749 break;
7750 default:
7751 errx(1, "invalid status code '%c'",
7752 optarg[i]);
7755 status_codes = optarg;
7756 break;
7757 default:
7758 usage_remove();
7759 /* NOTREACHED */
7763 argc -= optind;
7764 argv += optind;
7766 #ifndef PROFILE
7767 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7768 NULL) == -1)
7769 err(1, "pledge");
7770 #endif
7771 if (argc < 1)
7772 usage_remove();
7774 cwd = getcwd(NULL, 0);
7775 if (cwd == NULL) {
7776 error = got_error_from_errno("getcwd");
7777 goto done;
7780 error = got_repo_pack_fds_open(&pack_fds);
7781 if (error != NULL)
7782 goto done;
7784 error = got_worktree_open(&worktree, cwd);
7785 if (error) {
7786 if (error->code == GOT_ERR_NOT_WORKTREE)
7787 error = wrap_not_worktree_error(error, "remove", cwd);
7788 goto done;
7791 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7792 NULL, pack_fds);
7793 if (error)
7794 goto done;
7796 error = apply_unveil(got_repo_get_path(repo), 1,
7797 got_worktree_get_root_path(worktree));
7798 if (error)
7799 goto done;
7801 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7802 if (error)
7803 goto done;
7805 if (!can_recurse) {
7806 char *ondisk_path;
7807 struct stat sb;
7808 TAILQ_FOREACH(pe, &paths, entry) {
7809 if (asprintf(&ondisk_path, "%s/%s",
7810 got_worktree_get_root_path(worktree),
7811 pe->path) == -1) {
7812 error = got_error_from_errno("asprintf");
7813 goto done;
7815 if (lstat(ondisk_path, &sb) == -1) {
7816 if (errno == ENOENT) {
7817 free(ondisk_path);
7818 continue;
7820 error = got_error_from_errno2("lstat",
7821 ondisk_path);
7822 free(ondisk_path);
7823 goto done;
7825 free(ondisk_path);
7826 if (S_ISDIR(sb.st_mode)) {
7827 error = got_error_msg(GOT_ERR_BAD_PATH,
7828 "removing directories requires -R option");
7829 goto done;
7834 error = got_worktree_schedule_delete(worktree, &paths,
7835 delete_local_mods, status_codes, print_remove_status, NULL,
7836 repo, keep_on_disk, ignore_missing_paths);
7837 done:
7838 if (repo) {
7839 const struct got_error *close_err = got_repo_close(repo);
7840 if (error == NULL)
7841 error = close_err;
7843 if (worktree)
7844 got_worktree_close(worktree);
7845 if (pack_fds) {
7846 const struct got_error *pack_err =
7847 got_repo_pack_fds_close(pack_fds);
7848 if (error == NULL)
7849 error = pack_err;
7851 TAILQ_FOREACH(pe, &paths, entry)
7852 free((char *)pe->path);
7853 got_pathlist_free(&paths);
7854 free(cwd);
7855 return error;
7858 __dead static void
7859 usage_patch(void)
7861 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7862 "[-R] [patchfile]\n", getprogname());
7863 exit(1);
7866 static const struct got_error *
7867 patch_from_stdin(int *patchfd)
7869 const struct got_error *err = NULL;
7870 ssize_t r;
7871 char *path, buf[BUFSIZ];
7872 sig_t sighup, sigint, sigquit;
7874 err = got_opentemp_named_fd(&path, patchfd,
7875 GOT_TMPDIR_STR "/got-patch");
7876 if (err)
7877 return err;
7878 unlink(path);
7879 free(path);
7881 sighup = signal(SIGHUP, SIG_DFL);
7882 sigint = signal(SIGINT, SIG_DFL);
7883 sigquit = signal(SIGQUIT, SIG_DFL);
7885 for (;;) {
7886 r = read(0, buf, sizeof(buf));
7887 if (r == -1) {
7888 err = got_error_from_errno("read");
7889 break;
7891 if (r == 0)
7892 break;
7893 if (write(*patchfd, buf, r) == -1) {
7894 err = got_error_from_errno("write");
7895 break;
7899 signal(SIGHUP, sighup);
7900 signal(SIGINT, sigint);
7901 signal(SIGQUIT, sigquit);
7903 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7904 err = got_error_from_errno("lseek");
7906 if (err != NULL) {
7907 close(*patchfd);
7908 *patchfd = -1;
7911 return err;
7914 static const struct got_error *
7915 patch_progress(void *arg, const char *old, const char *new,
7916 unsigned char status, const struct got_error *error, int old_from,
7917 int old_lines, int new_from, int new_lines, int offset,
7918 int ws_mangled, const struct got_error *hunk_err)
7920 const char *path = new == NULL ? old : new;
7922 while (*path == '/')
7923 path++;
7925 if (status != 0)
7926 printf("%c %s\n", status, path);
7928 if (error != NULL)
7929 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7931 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7932 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7933 old_lines, new_from, new_lines);
7934 if (hunk_err != NULL)
7935 printf("%s\n", hunk_err->msg);
7936 else if (offset != 0)
7937 printf("applied with offset %d\n", offset);
7938 else
7939 printf("hunk contains mangled whitespace\n");
7942 return NULL;
7945 static const struct got_error *
7946 cmd_patch(int argc, char *argv[])
7948 const struct got_error *error = NULL, *close_error = NULL;
7949 struct got_worktree *worktree = NULL;
7950 struct got_repository *repo = NULL;
7951 const char *errstr;
7952 char *cwd = NULL;
7953 int ch, nop = 0, strip = -1, reverse = 0;
7954 int patchfd;
7955 int *pack_fds = NULL;
7957 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7958 switch (ch) {
7959 case 'n':
7960 nop = 1;
7961 break;
7962 case 'p':
7963 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7964 if (errstr != NULL)
7965 errx(1, "pathname strip count is %s: %s",
7966 errstr, optarg);
7967 break;
7968 case 'R':
7969 reverse = 1;
7970 break;
7971 default:
7972 usage_patch();
7973 /* NOTREACHED */
7977 argc -= optind;
7978 argv += optind;
7980 if (argc == 0) {
7981 error = patch_from_stdin(&patchfd);
7982 if (error)
7983 return error;
7984 } else if (argc == 1) {
7985 patchfd = open(argv[0], O_RDONLY);
7986 if (patchfd == -1) {
7987 error = got_error_from_errno2("open", argv[0]);
7988 return error;
7990 } else
7991 usage_patch();
7993 if ((cwd = getcwd(NULL, 0)) == NULL) {
7994 error = got_error_from_errno("getcwd");
7995 goto done;
7998 error = got_repo_pack_fds_open(&pack_fds);
7999 if (error != NULL)
8000 goto done;
8002 error = got_worktree_open(&worktree, cwd);
8003 if (error != NULL)
8004 goto done;
8006 const char *repo_path = got_worktree_get_repo_path(worktree);
8007 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8008 if (error != NULL)
8009 goto done;
8011 error = apply_unveil(got_repo_get_path(repo), 0,
8012 got_worktree_get_root_path(worktree));
8013 if (error != NULL)
8014 goto done;
8016 #ifndef PROFILE
8017 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
8018 NULL) == -1)
8019 err(1, "pledge");
8020 #endif
8022 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8023 &patch_progress, NULL, check_cancelled, NULL);
8025 done:
8026 if (repo) {
8027 close_error = got_repo_close(repo);
8028 if (error == NULL)
8029 error = close_error;
8031 if (worktree != NULL) {
8032 close_error = got_worktree_close(worktree);
8033 if (error == NULL)
8034 error = close_error;
8036 if (pack_fds) {
8037 const struct got_error *pack_err =
8038 got_repo_pack_fds_close(pack_fds);
8039 if (error == NULL)
8040 error = pack_err;
8042 free(cwd);
8043 return error;
8046 __dead static void
8047 usage_revert(void)
8049 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8050 "path ...\n", getprogname());
8051 exit(1);
8054 static const struct got_error *
8055 revert_progress(void *arg, unsigned char status, const char *path)
8057 if (status == GOT_STATUS_UNVERSIONED)
8058 return NULL;
8060 while (path[0] == '/')
8061 path++;
8062 printf("%c %s\n", status, path);
8063 return NULL;
8066 struct choose_patch_arg {
8067 FILE *patch_script_file;
8068 const char *action;
8071 static const struct got_error *
8072 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8073 int nchanges, const char *action)
8075 const struct got_error *err;
8076 char *line = NULL;
8077 size_t linesize = 0;
8078 ssize_t linelen;
8080 switch (status) {
8081 case GOT_STATUS_ADD:
8082 printf("A %s\n%s this addition? [y/n] ", path, action);
8083 break;
8084 case GOT_STATUS_DELETE:
8085 printf("D %s\n%s this deletion? [y/n] ", path, action);
8086 break;
8087 case GOT_STATUS_MODIFY:
8088 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8089 return got_error_from_errno("fseek");
8090 printf(GOT_COMMIT_SEP_STR);
8091 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8092 printf("%s", line);
8093 if (linelen == -1 && ferror(patch_file)) {
8094 err = got_error_from_errno("getline");
8095 free(line);
8096 return err;
8098 free(line);
8099 printf(GOT_COMMIT_SEP_STR);
8100 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8101 path, n, nchanges, action);
8102 break;
8103 default:
8104 return got_error_path(path, GOT_ERR_FILE_STATUS);
8107 return NULL;
8110 static const struct got_error *
8111 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8112 FILE *patch_file, int n, int nchanges)
8114 const struct got_error *err = NULL;
8115 char *line = NULL;
8116 size_t linesize = 0;
8117 ssize_t linelen;
8118 int resp = ' ';
8119 struct choose_patch_arg *a = arg;
8121 *choice = GOT_PATCH_CHOICE_NONE;
8123 if (a->patch_script_file) {
8124 char *nl;
8125 err = show_change(status, path, patch_file, n, nchanges,
8126 a->action);
8127 if (err)
8128 return err;
8129 linelen = getline(&line, &linesize, a->patch_script_file);
8130 if (linelen == -1) {
8131 if (ferror(a->patch_script_file))
8132 return got_error_from_errno("getline");
8133 return NULL;
8135 nl = strchr(line, '\n');
8136 if (nl)
8137 *nl = '\0';
8138 if (strcmp(line, "y") == 0) {
8139 *choice = GOT_PATCH_CHOICE_YES;
8140 printf("y\n");
8141 } else if (strcmp(line, "n") == 0) {
8142 *choice = GOT_PATCH_CHOICE_NO;
8143 printf("n\n");
8144 } else if (strcmp(line, "q") == 0 &&
8145 status == GOT_STATUS_MODIFY) {
8146 *choice = GOT_PATCH_CHOICE_QUIT;
8147 printf("q\n");
8148 } else
8149 printf("invalid response '%s'\n", line);
8150 free(line);
8151 return NULL;
8154 while (resp != 'y' && resp != 'n' && resp != 'q') {
8155 err = show_change(status, path, patch_file, n, nchanges,
8156 a->action);
8157 if (err)
8158 return err;
8159 resp = getchar();
8160 if (resp == '\n')
8161 resp = getchar();
8162 if (status == GOT_STATUS_MODIFY) {
8163 if (resp != 'y' && resp != 'n' && resp != 'q') {
8164 printf("invalid response '%c'\n", resp);
8165 resp = ' ';
8167 } else if (resp != 'y' && resp != 'n') {
8168 printf("invalid response '%c'\n", resp);
8169 resp = ' ';
8173 if (resp == 'y')
8174 *choice = GOT_PATCH_CHOICE_YES;
8175 else if (resp == 'n')
8176 *choice = GOT_PATCH_CHOICE_NO;
8177 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8178 *choice = GOT_PATCH_CHOICE_QUIT;
8180 return NULL;
8183 static const struct got_error *
8184 cmd_revert(int argc, char *argv[])
8186 const struct got_error *error = NULL;
8187 struct got_worktree *worktree = NULL;
8188 struct got_repository *repo = NULL;
8189 char *cwd = NULL, *path = NULL;
8190 struct got_pathlist_head paths;
8191 struct got_pathlist_entry *pe;
8192 int ch, can_recurse = 0, pflag = 0;
8193 FILE *patch_script_file = NULL;
8194 const char *patch_script_path = NULL;
8195 struct choose_patch_arg cpa;
8196 int *pack_fds = NULL;
8198 TAILQ_INIT(&paths);
8200 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8201 switch (ch) {
8202 case 'p':
8203 pflag = 1;
8204 break;
8205 case 'F':
8206 patch_script_path = optarg;
8207 break;
8208 case 'R':
8209 can_recurse = 1;
8210 break;
8211 default:
8212 usage_revert();
8213 /* NOTREACHED */
8217 argc -= optind;
8218 argv += optind;
8220 #ifndef PROFILE
8221 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8222 "unveil", NULL) == -1)
8223 err(1, "pledge");
8224 #endif
8225 if (argc < 1)
8226 usage_revert();
8227 if (patch_script_path && !pflag)
8228 errx(1, "-F option can only be used together with -p option");
8230 cwd = getcwd(NULL, 0);
8231 if (cwd == NULL) {
8232 error = got_error_from_errno("getcwd");
8233 goto done;
8236 error = got_repo_pack_fds_open(&pack_fds);
8237 if (error != NULL)
8238 goto done;
8240 error = got_worktree_open(&worktree, cwd);
8241 if (error) {
8242 if (error->code == GOT_ERR_NOT_WORKTREE)
8243 error = wrap_not_worktree_error(error, "revert", cwd);
8244 goto done;
8247 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8248 NULL, pack_fds);
8249 if (error != NULL)
8250 goto done;
8252 if (patch_script_path) {
8253 patch_script_file = fopen(patch_script_path, "re");
8254 if (patch_script_file == NULL) {
8255 error = got_error_from_errno2("fopen",
8256 patch_script_path);
8257 goto done;
8260 error = apply_unveil(got_repo_get_path(repo), 1,
8261 got_worktree_get_root_path(worktree));
8262 if (error)
8263 goto done;
8265 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8266 if (error)
8267 goto done;
8269 if (!can_recurse) {
8270 char *ondisk_path;
8271 struct stat sb;
8272 TAILQ_FOREACH(pe, &paths, entry) {
8273 if (asprintf(&ondisk_path, "%s/%s",
8274 got_worktree_get_root_path(worktree),
8275 pe->path) == -1) {
8276 error = got_error_from_errno("asprintf");
8277 goto done;
8279 if (lstat(ondisk_path, &sb) == -1) {
8280 if (errno == ENOENT) {
8281 free(ondisk_path);
8282 continue;
8284 error = got_error_from_errno2("lstat",
8285 ondisk_path);
8286 free(ondisk_path);
8287 goto done;
8289 free(ondisk_path);
8290 if (S_ISDIR(sb.st_mode)) {
8291 error = got_error_msg(GOT_ERR_BAD_PATH,
8292 "reverting directories requires -R option");
8293 goto done;
8298 cpa.patch_script_file = patch_script_file;
8299 cpa.action = "revert";
8300 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8301 pflag ? choose_patch : NULL, &cpa, repo);
8302 done:
8303 if (patch_script_file && fclose(patch_script_file) == EOF &&
8304 error == NULL)
8305 error = got_error_from_errno2("fclose", patch_script_path);
8306 if (repo) {
8307 const struct got_error *close_err = got_repo_close(repo);
8308 if (error == NULL)
8309 error = close_err;
8311 if (worktree)
8312 got_worktree_close(worktree);
8313 if (pack_fds) {
8314 const struct got_error *pack_err =
8315 got_repo_pack_fds_close(pack_fds);
8316 if (error == NULL)
8317 error = pack_err;
8319 free(path);
8320 free(cwd);
8321 return error;
8324 __dead static void
8325 usage_commit(void)
8327 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8328 "[path ...]\n", getprogname());
8329 exit(1);
8332 struct collect_commit_logmsg_arg {
8333 const char *cmdline_log;
8334 const char *prepared_log;
8335 int non_interactive;
8336 const char *editor;
8337 const char *worktree_path;
8338 const char *branch_name;
8339 const char *repo_path;
8340 char *logmsg_path;
8344 static const struct got_error *
8345 read_prepared_logmsg(char **logmsg, const char *path)
8347 const struct got_error *err = NULL;
8348 FILE *f = NULL;
8349 struct stat sb;
8350 size_t r;
8352 *logmsg = NULL;
8353 memset(&sb, 0, sizeof(sb));
8355 f = fopen(path, "re");
8356 if (f == NULL)
8357 return got_error_from_errno2("fopen", path);
8359 if (fstat(fileno(f), &sb) == -1) {
8360 err = got_error_from_errno2("fstat", path);
8361 goto done;
8363 if (sb.st_size == 0) {
8364 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8365 goto done;
8368 *logmsg = malloc(sb.st_size + 1);
8369 if (*logmsg == NULL) {
8370 err = got_error_from_errno("malloc");
8371 goto done;
8374 r = fread(*logmsg, 1, sb.st_size, f);
8375 if (r != sb.st_size) {
8376 if (ferror(f))
8377 err = got_error_from_errno2("fread", path);
8378 else
8379 err = got_error(GOT_ERR_IO);
8380 goto done;
8382 (*logmsg)[sb.st_size] = '\0';
8383 done:
8384 if (fclose(f) == EOF && err == NULL)
8385 err = got_error_from_errno2("fclose", path);
8386 if (err) {
8387 free(*logmsg);
8388 *logmsg = NULL;
8390 return err;
8394 static const struct got_error *
8395 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8396 void *arg)
8398 char *initial_content = NULL;
8399 struct got_pathlist_entry *pe;
8400 const struct got_error *err = NULL;
8401 char *template = NULL;
8402 struct collect_commit_logmsg_arg *a = arg;
8403 int initial_content_len;
8404 int fd = -1;
8405 size_t len;
8407 /* if a message was specified on the command line, just use it */
8408 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8409 len = strlen(a->cmdline_log) + 1;
8410 *logmsg = malloc(len + 1);
8411 if (*logmsg == NULL)
8412 return got_error_from_errno("malloc");
8413 strlcpy(*logmsg, a->cmdline_log, len);
8414 return NULL;
8415 } else if (a->prepared_log != NULL && a->non_interactive)
8416 return read_prepared_logmsg(logmsg, a->prepared_log);
8418 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8419 return got_error_from_errno("asprintf");
8421 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8422 if (err)
8423 goto done;
8425 if (a->prepared_log) {
8426 char *msg;
8427 err = read_prepared_logmsg(&msg, a->prepared_log);
8428 if (err)
8429 goto done;
8430 if (write(fd, msg, strlen(msg)) == -1) {
8431 err = got_error_from_errno2("write", a->logmsg_path);
8432 free(msg);
8433 goto done;
8435 free(msg);
8438 initial_content_len = asprintf(&initial_content,
8439 "\n# changes to be committed on branch %s:\n",
8440 a->branch_name);
8441 if (initial_content_len == -1) {
8442 err = got_error_from_errno("asprintf");
8443 goto done;
8446 if (write(fd, initial_content, initial_content_len) == -1) {
8447 err = got_error_from_errno2("write", a->logmsg_path);
8448 goto done;
8451 TAILQ_FOREACH(pe, commitable_paths, entry) {
8452 struct got_commitable *ct = pe->data;
8453 dprintf(fd, "# %c %s\n",
8454 got_commitable_get_status(ct),
8455 got_commitable_get_path(ct));
8458 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8459 initial_content_len, a->prepared_log ? 0 : 1);
8460 done:
8461 free(initial_content);
8462 free(template);
8464 if (fd != -1 && close(fd) == -1 && err == NULL)
8465 err = got_error_from_errno2("close", a->logmsg_path);
8467 /* Editor is done; we can now apply unveil(2) */
8468 if (err == NULL)
8469 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8470 if (err) {
8471 free(*logmsg);
8472 *logmsg = NULL;
8474 return err;
8477 static const struct got_error *
8478 cmd_commit(int argc, char *argv[])
8480 const struct got_error *error = NULL;
8481 struct got_worktree *worktree = NULL;
8482 struct got_repository *repo = NULL;
8483 char *cwd = NULL, *id_str = NULL;
8484 struct got_object_id *id = NULL;
8485 const char *logmsg = NULL;
8486 char *prepared_logmsg = NULL;
8487 struct collect_commit_logmsg_arg cl_arg;
8488 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8489 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8490 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8491 struct got_pathlist_head paths;
8492 int *pack_fds = NULL;
8494 TAILQ_INIT(&paths);
8495 cl_arg.logmsg_path = NULL;
8497 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8498 switch (ch) {
8499 case 'F':
8500 if (logmsg != NULL)
8501 option_conflict('F', 'm');
8502 prepared_logmsg = realpath(optarg, NULL);
8503 if (prepared_logmsg == NULL)
8504 return got_error_from_errno2("realpath",
8505 optarg);
8506 break;
8507 case 'm':
8508 if (prepared_logmsg)
8509 option_conflict('m', 'F');
8510 logmsg = optarg;
8511 break;
8512 case 'N':
8513 non_interactive = 1;
8514 break;
8515 case 'S':
8516 allow_bad_symlinks = 1;
8517 break;
8518 default:
8519 usage_commit();
8520 /* NOTREACHED */
8524 argc -= optind;
8525 argv += optind;
8527 #ifndef PROFILE
8528 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8529 "unveil", NULL) == -1)
8530 err(1, "pledge");
8531 #endif
8532 cwd = getcwd(NULL, 0);
8533 if (cwd == NULL) {
8534 error = got_error_from_errno("getcwd");
8535 goto done;
8538 error = got_repo_pack_fds_open(&pack_fds);
8539 if (error != NULL)
8540 goto done;
8542 error = got_worktree_open(&worktree, cwd);
8543 if (error) {
8544 if (error->code == GOT_ERR_NOT_WORKTREE)
8545 error = wrap_not_worktree_error(error, "commit", cwd);
8546 goto done;
8549 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8550 if (error)
8551 goto done;
8552 if (rebase_in_progress) {
8553 error = got_error(GOT_ERR_REBASING);
8554 goto done;
8557 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8558 worktree);
8559 if (error)
8560 goto done;
8562 error = get_gitconfig_path(&gitconfig_path);
8563 if (error)
8564 goto done;
8565 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8566 gitconfig_path, pack_fds);
8567 if (error != NULL)
8568 goto done;
8570 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8571 if (error)
8572 goto done;
8573 if (merge_in_progress) {
8574 error = got_error(GOT_ERR_MERGE_BUSY);
8575 goto done;
8578 error = get_author(&author, repo, worktree);
8579 if (error)
8580 return error;
8583 * unveil(2) traverses exec(2); if an editor is used we have
8584 * to apply unveil after the log message has been written.
8586 if (logmsg == NULL || strlen(logmsg) == 0)
8587 error = get_editor(&editor);
8588 else
8589 error = apply_unveil(got_repo_get_path(repo), 0,
8590 got_worktree_get_root_path(worktree));
8591 if (error)
8592 goto done;
8594 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8595 if (error)
8596 goto done;
8598 cl_arg.editor = editor;
8599 cl_arg.cmdline_log = logmsg;
8600 cl_arg.prepared_log = prepared_logmsg;
8601 cl_arg.non_interactive = non_interactive;
8602 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8603 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8604 if (!histedit_in_progress) {
8605 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8606 error = got_error(GOT_ERR_COMMIT_BRANCH);
8607 goto done;
8609 cl_arg.branch_name += 11;
8611 cl_arg.repo_path = got_repo_get_path(repo);
8612 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8613 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8614 print_status, NULL, repo);
8615 if (error) {
8616 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8617 cl_arg.logmsg_path != NULL)
8618 preserve_logmsg = 1;
8619 goto done;
8622 error = got_object_id_str(&id_str, id);
8623 if (error)
8624 goto done;
8625 printf("Created commit %s\n", id_str);
8626 done:
8627 if (preserve_logmsg) {
8628 fprintf(stderr, "%s: log message preserved in %s\n",
8629 getprogname(), cl_arg.logmsg_path);
8630 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8631 error == NULL)
8632 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8633 free(cl_arg.logmsg_path);
8634 if (repo) {
8635 const struct got_error *close_err = got_repo_close(repo);
8636 if (error == NULL)
8637 error = close_err;
8639 if (worktree)
8640 got_worktree_close(worktree);
8641 if (pack_fds) {
8642 const struct got_error *pack_err =
8643 got_repo_pack_fds_close(pack_fds);
8644 if (error == NULL)
8645 error = pack_err;
8647 free(cwd);
8648 free(id_str);
8649 free(gitconfig_path);
8650 free(editor);
8651 free(author);
8652 free(prepared_logmsg);
8653 return error;
8656 __dead static void
8657 usage_send(void)
8659 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8660 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8661 "[remote-repository]\n", getprogname());
8662 exit(1);
8665 static void
8666 print_load_info(int print_colored, int print_found, int print_trees,
8667 int ncolored, int nfound, int ntrees)
8669 if (print_colored) {
8670 printf("%d commit%s colored", ncolored,
8671 ncolored == 1 ? "" : "s");
8673 if (print_found) {
8674 printf("%s%d object%s found",
8675 ncolored > 0 ? "; " : "",
8676 nfound, nfound == 1 ? "" : "s");
8678 if (print_trees) {
8679 printf("; %d tree%s scanned", ntrees,
8680 ntrees == 1 ? "" : "s");
8684 struct got_send_progress_arg {
8685 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8686 int verbosity;
8687 int last_ncolored;
8688 int last_nfound;
8689 int last_ntrees;
8690 int loading_done;
8691 int last_ncommits;
8692 int last_nobj_total;
8693 int last_p_deltify;
8694 int last_p_written;
8695 int last_p_sent;
8696 int printed_something;
8697 int sent_something;
8698 struct got_pathlist_head *delete_branches;
8701 static const struct got_error *
8702 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8703 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8704 int nobj_written, off_t bytes_sent, const char *refname, int success)
8706 struct got_send_progress_arg *a = arg;
8707 char scaled_packsize[FMT_SCALED_STRSIZE];
8708 char scaled_sent[FMT_SCALED_STRSIZE];
8709 int p_deltify = 0, p_written = 0, p_sent = 0;
8710 int print_colored = 0, print_found = 0, print_trees = 0;
8711 int print_searching = 0, print_total = 0;
8712 int print_deltify = 0, print_written = 0, print_sent = 0;
8714 if (a->verbosity < 0)
8715 return NULL;
8717 if (refname) {
8718 const char *status = success ? "accepted" : "rejected";
8720 if (success) {
8721 struct got_pathlist_entry *pe;
8722 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8723 const char *branchname = pe->path;
8724 if (got_path_cmp(branchname, refname,
8725 strlen(branchname), strlen(refname)) == 0) {
8726 status = "deleted";
8727 a->sent_something = 1;
8728 break;
8733 if (a->printed_something)
8734 putchar('\n');
8735 printf("Server has %s %s", status, refname);
8736 a->printed_something = 1;
8737 return NULL;
8740 if (a->last_ncolored != ncolored) {
8741 print_colored = 1;
8742 a->last_ncolored = ncolored;
8745 if (a->last_nfound != nfound) {
8746 print_colored = 1;
8747 print_found = 1;
8748 a->last_nfound = nfound;
8751 if (a->last_ntrees != ntrees) {
8752 print_colored = 1;
8753 print_found = 1;
8754 print_trees = 1;
8755 a->last_ntrees = ntrees;
8758 if ((print_colored || print_found || print_trees) &&
8759 !a->loading_done) {
8760 printf("\r");
8761 print_load_info(print_colored, print_found, print_trees,
8762 ncolored, nfound, ntrees);
8763 a->printed_something = 1;
8764 fflush(stdout);
8765 return NULL;
8766 } else if (!a->loading_done) {
8767 printf("\r");
8768 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8769 printf("\n");
8770 a->loading_done = 1;
8773 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8774 return got_error_from_errno("fmt_scaled");
8775 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8776 return got_error_from_errno("fmt_scaled");
8778 if (a->last_ncommits != ncommits) {
8779 print_searching = 1;
8780 a->last_ncommits = ncommits;
8783 if (a->last_nobj_total != nobj_total) {
8784 print_searching = 1;
8785 print_total = 1;
8786 a->last_nobj_total = nobj_total;
8789 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8790 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8791 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8792 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8793 return got_error(GOT_ERR_NO_SPACE);
8796 if (nobj_deltify > 0 || nobj_written > 0) {
8797 if (nobj_deltify > 0) {
8798 p_deltify = (nobj_deltify * 100) / nobj_total;
8799 if (p_deltify != a->last_p_deltify) {
8800 a->last_p_deltify = p_deltify;
8801 print_searching = 1;
8802 print_total = 1;
8803 print_deltify = 1;
8806 if (nobj_written > 0) {
8807 p_written = (nobj_written * 100) / nobj_total;
8808 if (p_written != a->last_p_written) {
8809 a->last_p_written = p_written;
8810 print_searching = 1;
8811 print_total = 1;
8812 print_deltify = 1;
8813 print_written = 1;
8818 if (bytes_sent > 0) {
8819 p_sent = (bytes_sent * 100) / packfile_size;
8820 if (p_sent != a->last_p_sent) {
8821 a->last_p_sent = p_sent;
8822 print_searching = 1;
8823 print_total = 1;
8824 print_deltify = 1;
8825 print_written = 1;
8826 print_sent = 1;
8828 a->sent_something = 1;
8831 if (print_searching || print_total || print_deltify || print_written ||
8832 print_sent)
8833 printf("\r");
8834 if (print_searching)
8835 printf("packing %d reference%s", ncommits,
8836 ncommits == 1 ? "" : "s");
8837 if (print_total)
8838 printf("; %d object%s", nobj_total,
8839 nobj_total == 1 ? "" : "s");
8840 if (print_deltify)
8841 printf("; deltify: %d%%", p_deltify);
8842 if (print_sent)
8843 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8844 scaled_packsize, p_sent);
8845 else if (print_written)
8846 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8847 scaled_packsize, p_written);
8848 if (print_searching || print_total || print_deltify ||
8849 print_written || print_sent) {
8850 a->printed_something = 1;
8851 fflush(stdout);
8853 return NULL;
8856 static const struct got_error *
8857 cmd_send(int argc, char *argv[])
8859 const struct got_error *error = NULL;
8860 char *cwd = NULL, *repo_path = NULL;
8861 const char *remote_name;
8862 char *proto = NULL, *host = NULL, *port = NULL;
8863 char *repo_name = NULL, *server_path = NULL;
8864 const struct got_remote_repo *remotes, *remote = NULL;
8865 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8866 struct got_repository *repo = NULL;
8867 struct got_worktree *worktree = NULL;
8868 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8869 struct got_pathlist_head branches;
8870 struct got_pathlist_head tags;
8871 struct got_reflist_head all_branches;
8872 struct got_reflist_head all_tags;
8873 struct got_pathlist_head delete_args;
8874 struct got_pathlist_head delete_branches;
8875 struct got_reflist_entry *re;
8876 struct got_pathlist_entry *pe;
8877 int i, ch, sendfd = -1, sendstatus;
8878 pid_t sendpid = -1;
8879 struct got_send_progress_arg spa;
8880 int verbosity = 0, overwrite_refs = 0;
8881 int send_all_branches = 0, send_all_tags = 0;
8882 struct got_reference *ref = NULL;
8883 int *pack_fds = NULL;
8885 TAILQ_INIT(&branches);
8886 TAILQ_INIT(&tags);
8887 TAILQ_INIT(&all_branches);
8888 TAILQ_INIT(&all_tags);
8889 TAILQ_INIT(&delete_args);
8890 TAILQ_INIT(&delete_branches);
8892 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8893 switch (ch) {
8894 case 'a':
8895 send_all_branches = 1;
8896 break;
8897 case 'b':
8898 error = got_pathlist_append(&branches, optarg, NULL);
8899 if (error)
8900 return error;
8901 nbranches++;
8902 break;
8903 case 'd':
8904 error = got_pathlist_append(&delete_args, optarg, NULL);
8905 if (error)
8906 return error;
8907 break;
8908 case 'f':
8909 overwrite_refs = 1;
8910 break;
8911 case 'r':
8912 repo_path = realpath(optarg, NULL);
8913 if (repo_path == NULL)
8914 return got_error_from_errno2("realpath",
8915 optarg);
8916 got_path_strip_trailing_slashes(repo_path);
8917 break;
8918 case 't':
8919 error = got_pathlist_append(&tags, optarg, NULL);
8920 if (error)
8921 return error;
8922 ntags++;
8923 break;
8924 case 'T':
8925 send_all_tags = 1;
8926 break;
8927 case 'v':
8928 if (verbosity < 0)
8929 verbosity = 0;
8930 else if (verbosity < 3)
8931 verbosity++;
8932 break;
8933 case 'q':
8934 verbosity = -1;
8935 break;
8936 default:
8937 usage_send();
8938 /* NOTREACHED */
8941 argc -= optind;
8942 argv += optind;
8944 if (send_all_branches && !TAILQ_EMPTY(&branches))
8945 option_conflict('a', 'b');
8946 if (send_all_tags && !TAILQ_EMPTY(&tags))
8947 option_conflict('T', 't');
8950 if (argc == 0)
8951 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8952 else if (argc == 1)
8953 remote_name = argv[0];
8954 else
8955 usage_send();
8957 cwd = getcwd(NULL, 0);
8958 if (cwd == NULL) {
8959 error = got_error_from_errno("getcwd");
8960 goto done;
8963 error = got_repo_pack_fds_open(&pack_fds);
8964 if (error != NULL)
8965 goto done;
8967 if (repo_path == NULL) {
8968 error = got_worktree_open(&worktree, cwd);
8969 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8970 goto done;
8971 else
8972 error = NULL;
8973 if (worktree) {
8974 repo_path =
8975 strdup(got_worktree_get_repo_path(worktree));
8976 if (repo_path == NULL)
8977 error = got_error_from_errno("strdup");
8978 if (error)
8979 goto done;
8980 } else {
8981 repo_path = strdup(cwd);
8982 if (repo_path == NULL) {
8983 error = got_error_from_errno("strdup");
8984 goto done;
8989 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8990 if (error)
8991 goto done;
8993 if (worktree) {
8994 worktree_conf = got_worktree_get_gotconfig(worktree);
8995 if (worktree_conf) {
8996 got_gotconfig_get_remotes(&nremotes, &remotes,
8997 worktree_conf);
8998 for (i = 0; i < nremotes; i++) {
8999 if (strcmp(remotes[i].name, remote_name) == 0) {
9000 remote = &remotes[i];
9001 break;
9006 if (remote == NULL) {
9007 repo_conf = got_repo_get_gotconfig(repo);
9008 if (repo_conf) {
9009 got_gotconfig_get_remotes(&nremotes, &remotes,
9010 repo_conf);
9011 for (i = 0; i < nremotes; i++) {
9012 if (strcmp(remotes[i].name, remote_name) == 0) {
9013 remote = &remotes[i];
9014 break;
9019 if (remote == NULL) {
9020 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9021 for (i = 0; i < nremotes; i++) {
9022 if (strcmp(remotes[i].name, remote_name) == 0) {
9023 remote = &remotes[i];
9024 break;
9028 if (remote == NULL) {
9029 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9030 goto done;
9033 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9034 &repo_name, remote->send_url);
9035 if (error)
9036 goto done;
9038 if (strcmp(proto, "git") == 0) {
9039 #ifndef PROFILE
9040 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9041 "sendfd dns inet unveil", NULL) == -1)
9042 err(1, "pledge");
9043 #endif
9044 } else if (strcmp(proto, "git+ssh") == 0 ||
9045 strcmp(proto, "ssh") == 0) {
9046 #ifndef PROFILE
9047 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9048 "sendfd unveil", NULL) == -1)
9049 err(1, "pledge");
9050 #endif
9051 } else if (strcmp(proto, "http") == 0 ||
9052 strcmp(proto, "git+http") == 0) {
9053 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9054 goto done;
9055 } else {
9056 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9057 goto done;
9060 error = got_dial_apply_unveil(proto);
9061 if (error)
9062 goto done;
9064 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9065 if (error)
9066 goto done;
9068 if (send_all_branches) {
9069 error = got_ref_list(&all_branches, repo, "refs/heads",
9070 got_ref_cmp_by_name, NULL);
9071 if (error)
9072 goto done;
9073 TAILQ_FOREACH(re, &all_branches, entry) {
9074 const char *branchname = got_ref_get_name(re->ref);
9075 error = got_pathlist_append(&branches,
9076 branchname, NULL);
9077 if (error)
9078 goto done;
9079 nbranches++;
9081 } else if (nbranches == 0) {
9082 for (i = 0; i < remote->nsend_branches; i++) {
9083 got_pathlist_append(&branches,
9084 remote->send_branches[i], NULL);
9088 if (send_all_tags) {
9089 error = got_ref_list(&all_tags, repo, "refs/tags",
9090 got_ref_cmp_by_name, NULL);
9091 if (error)
9092 goto done;
9093 TAILQ_FOREACH(re, &all_tags, entry) {
9094 const char *tagname = got_ref_get_name(re->ref);
9095 error = got_pathlist_append(&tags,
9096 tagname, NULL);
9097 if (error)
9098 goto done;
9099 ntags++;
9104 * To prevent accidents only branches in refs/heads/ can be deleted
9105 * with 'got send -d'.
9106 * Deleting anything else requires local repository access or Git.
9108 TAILQ_FOREACH(pe, &delete_args, entry) {
9109 const char *branchname = pe->path;
9110 char *s;
9111 struct got_pathlist_entry *new;
9112 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9113 s = strdup(branchname);
9114 if (s == NULL) {
9115 error = got_error_from_errno("strdup");
9116 goto done;
9118 } else {
9119 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9120 error = got_error_from_errno("asprintf");
9121 goto done;
9124 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9125 if (error || new == NULL /* duplicate */)
9126 free(s);
9127 if (error)
9128 goto done;
9129 ndelete_branches++;
9132 if (nbranches == 0 && ndelete_branches == 0) {
9133 struct got_reference *head_ref;
9134 if (worktree)
9135 error = got_ref_open(&head_ref, repo,
9136 got_worktree_get_head_ref_name(worktree), 0);
9137 else
9138 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9139 if (error)
9140 goto done;
9141 if (got_ref_is_symbolic(head_ref)) {
9142 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9143 got_ref_close(head_ref);
9144 if (error)
9145 goto done;
9146 } else
9147 ref = head_ref;
9148 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9149 NULL);
9150 if (error)
9151 goto done;
9152 nbranches++;
9155 if (verbosity >= 0)
9156 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9157 port ? ":" : "", port ? port : "");
9159 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9160 server_path, verbosity);
9161 if (error)
9162 goto done;
9164 memset(&spa, 0, sizeof(spa));
9165 spa.last_scaled_packsize[0] = '\0';
9166 spa.last_p_deltify = -1;
9167 spa.last_p_written = -1;
9168 spa.verbosity = verbosity;
9169 spa.delete_branches = &delete_branches;
9170 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9171 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9172 check_cancelled, NULL);
9173 if (spa.printed_something)
9174 putchar('\n');
9175 if (error)
9176 goto done;
9177 if (!spa.sent_something && verbosity >= 0)
9178 printf("Already up-to-date\n");
9179 done:
9180 if (sendpid > 0) {
9181 if (kill(sendpid, SIGTERM) == -1)
9182 error = got_error_from_errno("kill");
9183 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9184 error = got_error_from_errno("waitpid");
9186 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9187 error = got_error_from_errno("close");
9188 if (repo) {
9189 const struct got_error *close_err = got_repo_close(repo);
9190 if (error == NULL)
9191 error = close_err;
9193 if (worktree)
9194 got_worktree_close(worktree);
9195 if (pack_fds) {
9196 const struct got_error *pack_err =
9197 got_repo_pack_fds_close(pack_fds);
9198 if (error == NULL)
9199 error = pack_err;
9201 if (ref)
9202 got_ref_close(ref);
9203 got_pathlist_free(&branches);
9204 got_pathlist_free(&tags);
9205 got_ref_list_free(&all_branches);
9206 got_ref_list_free(&all_tags);
9207 got_pathlist_free(&delete_args);
9208 TAILQ_FOREACH(pe, &delete_branches, entry)
9209 free((char *)pe->path);
9210 got_pathlist_free(&delete_branches);
9211 free(cwd);
9212 free(repo_path);
9213 free(proto);
9214 free(host);
9215 free(port);
9216 free(server_path);
9217 free(repo_name);
9218 return error;
9221 __dead static void
9222 usage_cherrypick(void)
9224 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9225 exit(1);
9228 static const struct got_error *
9229 cmd_cherrypick(int argc, char *argv[])
9231 const struct got_error *error = NULL;
9232 struct got_worktree *worktree = NULL;
9233 struct got_repository *repo = NULL;
9234 char *cwd = NULL, *commit_id_str = NULL;
9235 struct got_object_id *commit_id = NULL;
9236 struct got_commit_object *commit = NULL;
9237 struct got_object_qid *pid;
9238 int ch;
9239 struct got_update_progress_arg upa;
9240 int *pack_fds = NULL;
9242 while ((ch = getopt(argc, argv, "")) != -1) {
9243 switch (ch) {
9244 default:
9245 usage_cherrypick();
9246 /* NOTREACHED */
9250 argc -= optind;
9251 argv += optind;
9253 #ifndef PROFILE
9254 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9255 "unveil", NULL) == -1)
9256 err(1, "pledge");
9257 #endif
9258 if (argc != 1)
9259 usage_cherrypick();
9261 cwd = getcwd(NULL, 0);
9262 if (cwd == NULL) {
9263 error = got_error_from_errno("getcwd");
9264 goto done;
9267 error = got_repo_pack_fds_open(&pack_fds);
9268 if (error != NULL)
9269 goto done;
9271 error = got_worktree_open(&worktree, cwd);
9272 if (error) {
9273 if (error->code == GOT_ERR_NOT_WORKTREE)
9274 error = wrap_not_worktree_error(error, "cherrypick",
9275 cwd);
9276 goto done;
9279 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9280 NULL, pack_fds);
9281 if (error != NULL)
9282 goto done;
9284 error = apply_unveil(got_repo_get_path(repo), 0,
9285 got_worktree_get_root_path(worktree));
9286 if (error)
9287 goto done;
9289 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9290 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9291 if (error)
9292 goto done;
9293 error = got_object_id_str(&commit_id_str, commit_id);
9294 if (error)
9295 goto done;
9297 error = got_object_open_as_commit(&commit, repo, commit_id);
9298 if (error)
9299 goto done;
9300 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9301 memset(&upa, 0, sizeof(upa));
9302 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9303 commit_id, repo, update_progress, &upa, check_cancelled,
9304 NULL);
9305 if (error != NULL)
9306 goto done;
9308 if (upa.did_something)
9309 printf("Merged commit %s\n", commit_id_str);
9310 print_merge_progress_stats(&upa);
9311 done:
9312 if (commit)
9313 got_object_commit_close(commit);
9314 free(commit_id_str);
9315 if (worktree)
9316 got_worktree_close(worktree);
9317 if (repo) {
9318 const struct got_error *close_err = got_repo_close(repo);
9319 if (error == NULL)
9320 error = close_err;
9322 if (pack_fds) {
9323 const struct got_error *pack_err =
9324 got_repo_pack_fds_close(pack_fds);
9325 if (error == NULL)
9326 error = pack_err;
9329 return error;
9332 __dead static void
9333 usage_backout(void)
9335 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9336 exit(1);
9339 static const struct got_error *
9340 cmd_backout(int argc, char *argv[])
9342 const struct got_error *error = NULL;
9343 struct got_worktree *worktree = NULL;
9344 struct got_repository *repo = NULL;
9345 char *cwd = NULL, *commit_id_str = NULL;
9346 struct got_object_id *commit_id = NULL;
9347 struct got_commit_object *commit = NULL;
9348 struct got_object_qid *pid;
9349 int ch;
9350 struct got_update_progress_arg upa;
9351 int *pack_fds = NULL;
9353 while ((ch = getopt(argc, argv, "")) != -1) {
9354 switch (ch) {
9355 default:
9356 usage_backout();
9357 /* NOTREACHED */
9361 argc -= optind;
9362 argv += optind;
9364 #ifndef PROFILE
9365 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9366 "unveil", NULL) == -1)
9367 err(1, "pledge");
9368 #endif
9369 if (argc != 1)
9370 usage_backout();
9372 cwd = getcwd(NULL, 0);
9373 if (cwd == NULL) {
9374 error = got_error_from_errno("getcwd");
9375 goto done;
9378 error = got_repo_pack_fds_open(&pack_fds);
9379 if (error != NULL)
9380 goto done;
9382 error = got_worktree_open(&worktree, cwd);
9383 if (error) {
9384 if (error->code == GOT_ERR_NOT_WORKTREE)
9385 error = wrap_not_worktree_error(error, "backout", cwd);
9386 goto done;
9389 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9390 NULL, pack_fds);
9391 if (error != NULL)
9392 goto done;
9394 error = apply_unveil(got_repo_get_path(repo), 0,
9395 got_worktree_get_root_path(worktree));
9396 if (error)
9397 goto done;
9399 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9400 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9401 if (error)
9402 goto done;
9403 error = got_object_id_str(&commit_id_str, commit_id);
9404 if (error)
9405 goto done;
9407 error = got_object_open_as_commit(&commit, repo, commit_id);
9408 if (error)
9409 goto done;
9410 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9411 if (pid == NULL) {
9412 error = got_error(GOT_ERR_ROOT_COMMIT);
9413 goto done;
9416 memset(&upa, 0, sizeof(upa));
9417 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9418 repo, update_progress, &upa, check_cancelled, NULL);
9419 if (error != NULL)
9420 goto done;
9422 if (upa.did_something)
9423 printf("Backed out commit %s\n", commit_id_str);
9424 print_merge_progress_stats(&upa);
9425 done:
9426 if (commit)
9427 got_object_commit_close(commit);
9428 free(commit_id_str);
9429 if (worktree)
9430 got_worktree_close(worktree);
9431 if (repo) {
9432 const struct got_error *close_err = got_repo_close(repo);
9433 if (error == NULL)
9434 error = close_err;
9436 if (pack_fds) {
9437 const struct got_error *pack_err =
9438 got_repo_pack_fds_close(pack_fds);
9439 if (error == NULL)
9440 error = pack_err;
9442 return error;
9445 __dead static void
9446 usage_rebase(void)
9448 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9449 getprogname());
9450 exit(1);
9453 static void
9454 trim_logmsg(char *logmsg, int limit)
9456 char *nl;
9457 size_t len;
9459 len = strlen(logmsg);
9460 if (len > limit)
9461 len = limit;
9462 logmsg[len] = '\0';
9463 nl = strchr(logmsg, '\n');
9464 if (nl)
9465 *nl = '\0';
9468 static const struct got_error *
9469 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9471 const struct got_error *err;
9472 char *logmsg0 = NULL;
9473 const char *s;
9475 err = got_object_commit_get_logmsg(&logmsg0, commit);
9476 if (err)
9477 return err;
9479 s = logmsg0;
9480 while (isspace((unsigned char)s[0]))
9481 s++;
9483 *logmsg = strdup(s);
9484 if (*logmsg == NULL) {
9485 err = got_error_from_errno("strdup");
9486 goto done;
9489 trim_logmsg(*logmsg, limit);
9490 done:
9491 free(logmsg0);
9492 return err;
9495 static const struct got_error *
9496 show_rebase_merge_conflict(struct got_object_id *id,
9497 struct got_repository *repo)
9499 const struct got_error *err;
9500 struct got_commit_object *commit = NULL;
9501 char *id_str = NULL, *logmsg = NULL;
9503 err = got_object_open_as_commit(&commit, repo, id);
9504 if (err)
9505 return err;
9507 err = got_object_id_str(&id_str, id);
9508 if (err)
9509 goto done;
9511 id_str[12] = '\0';
9513 err = get_short_logmsg(&logmsg, 42, commit);
9514 if (err)
9515 goto done;
9517 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9518 done:
9519 free(id_str);
9520 got_object_commit_close(commit);
9521 free(logmsg);
9522 return err;
9525 static const struct got_error *
9526 show_rebase_progress(struct got_commit_object *commit,
9527 struct got_object_id *old_id, struct got_object_id *new_id)
9529 const struct got_error *err;
9530 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9532 err = got_object_id_str(&old_id_str, old_id);
9533 if (err)
9534 goto done;
9536 if (new_id) {
9537 err = got_object_id_str(&new_id_str, new_id);
9538 if (err)
9539 goto done;
9542 old_id_str[12] = '\0';
9543 if (new_id_str)
9544 new_id_str[12] = '\0';
9546 err = get_short_logmsg(&logmsg, 42, commit);
9547 if (err)
9548 goto done;
9550 printf("%s -> %s: %s\n", old_id_str,
9551 new_id_str ? new_id_str : "no-op change", logmsg);
9552 done:
9553 free(old_id_str);
9554 free(new_id_str);
9555 free(logmsg);
9556 return err;
9559 static const struct got_error *
9560 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9561 struct got_reference *branch, struct got_reference *new_base_branch,
9562 struct got_reference *tmp_branch, struct got_repository *repo,
9563 int create_backup)
9565 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9566 return got_worktree_rebase_complete(worktree, fileindex,
9567 new_base_branch, tmp_branch, branch, repo, create_backup);
9570 static const struct got_error *
9571 rebase_commit(struct got_pathlist_head *merged_paths,
9572 struct got_worktree *worktree, struct got_fileindex *fileindex,
9573 struct got_reference *tmp_branch,
9574 struct got_object_id *commit_id, struct got_repository *repo)
9576 const struct got_error *error;
9577 struct got_commit_object *commit;
9578 struct got_object_id *new_commit_id;
9580 error = got_object_open_as_commit(&commit, repo, commit_id);
9581 if (error)
9582 return error;
9584 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9585 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9586 if (error) {
9587 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9588 goto done;
9589 error = show_rebase_progress(commit, commit_id, NULL);
9590 } else {
9591 error = show_rebase_progress(commit, commit_id, new_commit_id);
9592 free(new_commit_id);
9594 done:
9595 got_object_commit_close(commit);
9596 return error;
9599 struct check_path_prefix_arg {
9600 const char *path_prefix;
9601 size_t len;
9602 int errcode;
9605 static const struct got_error *
9606 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9607 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9608 struct got_object_id *id1, struct got_object_id *id2,
9609 const char *path1, const char *path2,
9610 mode_t mode1, mode_t mode2, struct got_repository *repo)
9612 struct check_path_prefix_arg *a = arg;
9614 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9615 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9616 return got_error(a->errcode);
9618 return NULL;
9621 static const struct got_error *
9622 check_path_prefix(struct got_object_id *parent_id,
9623 struct got_object_id *commit_id, const char *path_prefix,
9624 int errcode, struct got_repository *repo)
9626 const struct got_error *err;
9627 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9628 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9629 struct check_path_prefix_arg cpp_arg;
9631 if (got_path_is_root_dir(path_prefix))
9632 return NULL;
9634 err = got_object_open_as_commit(&commit, repo, commit_id);
9635 if (err)
9636 goto done;
9638 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9639 if (err)
9640 goto done;
9642 err = got_object_open_as_tree(&tree1, repo,
9643 got_object_commit_get_tree_id(parent_commit));
9644 if (err)
9645 goto done;
9647 err = got_object_open_as_tree(&tree2, repo,
9648 got_object_commit_get_tree_id(commit));
9649 if (err)
9650 goto done;
9652 cpp_arg.path_prefix = path_prefix;
9653 while (cpp_arg.path_prefix[0] == '/')
9654 cpp_arg.path_prefix++;
9655 cpp_arg.len = strlen(cpp_arg.path_prefix);
9656 cpp_arg.errcode = errcode;
9657 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9658 check_path_prefix_in_diff, &cpp_arg, 0);
9659 done:
9660 if (tree1)
9661 got_object_tree_close(tree1);
9662 if (tree2)
9663 got_object_tree_close(tree2);
9664 if (commit)
9665 got_object_commit_close(commit);
9666 if (parent_commit)
9667 got_object_commit_close(parent_commit);
9668 return err;
9671 static const struct got_error *
9672 collect_commits(struct got_object_id_queue *commits,
9673 struct got_object_id *initial_commit_id,
9674 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9675 const char *path_prefix, int path_prefix_errcode,
9676 struct got_repository *repo)
9678 const struct got_error *err = NULL;
9679 struct got_commit_graph *graph = NULL;
9680 struct got_object_id *parent_id = NULL;
9681 struct got_object_qid *qid;
9682 struct got_object_id *commit_id = initial_commit_id;
9684 err = got_commit_graph_open(&graph, "/", 1);
9685 if (err)
9686 return err;
9688 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9689 check_cancelled, NULL);
9690 if (err)
9691 goto done;
9692 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9693 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9694 check_cancelled, NULL);
9695 if (err) {
9696 if (err->code == GOT_ERR_ITER_COMPLETED) {
9697 err = got_error_msg(GOT_ERR_ANCESTRY,
9698 "ran out of commits to rebase before "
9699 "youngest common ancestor commit has "
9700 "been reached?!?");
9702 goto done;
9703 } else {
9704 err = check_path_prefix(parent_id, commit_id,
9705 path_prefix, path_prefix_errcode, repo);
9706 if (err)
9707 goto done;
9709 err = got_object_qid_alloc(&qid, commit_id);
9710 if (err)
9711 goto done;
9712 STAILQ_INSERT_HEAD(commits, qid, entry);
9713 commit_id = parent_id;
9716 done:
9717 got_commit_graph_close(graph);
9718 return err;
9721 static const struct got_error *
9722 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9724 const struct got_error *err = NULL;
9725 time_t committer_time;
9726 struct tm tm;
9727 char datebuf[11]; /* YYYY-MM-DD + NUL */
9728 char *author0 = NULL, *author, *smallerthan;
9729 char *logmsg0 = NULL, *logmsg, *newline;
9731 committer_time = got_object_commit_get_committer_time(commit);
9732 if (gmtime_r(&committer_time, &tm) == NULL)
9733 return got_error_from_errno("gmtime_r");
9734 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9735 return got_error(GOT_ERR_NO_SPACE);
9737 author0 = strdup(got_object_commit_get_author(commit));
9738 if (author0 == NULL)
9739 return got_error_from_errno("strdup");
9740 author = author0;
9741 smallerthan = strchr(author, '<');
9742 if (smallerthan && smallerthan[1] != '\0')
9743 author = smallerthan + 1;
9744 author[strcspn(author, "@>")] = '\0';
9746 err = got_object_commit_get_logmsg(&logmsg0, commit);
9747 if (err)
9748 goto done;
9749 logmsg = logmsg0;
9750 while (*logmsg == '\n')
9751 logmsg++;
9752 newline = strchr(logmsg, '\n');
9753 if (newline)
9754 *newline = '\0';
9756 if (asprintf(brief_str, "%s %s %s",
9757 datebuf, author, logmsg) == -1)
9758 err = got_error_from_errno("asprintf");
9759 done:
9760 free(author0);
9761 free(logmsg0);
9762 return err;
9765 static const struct got_error *
9766 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9767 struct got_repository *repo)
9769 const struct got_error *err;
9770 char *id_str;
9772 err = got_object_id_str(&id_str, id);
9773 if (err)
9774 return err;
9776 err = got_ref_delete(ref, repo);
9777 if (err)
9778 goto done;
9780 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9781 done:
9782 free(id_str);
9783 return err;
9786 static const struct got_error *
9787 print_backup_ref(const char *branch_name, const char *new_id_str,
9788 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9789 struct got_reflist_object_id_map *refs_idmap,
9790 struct got_repository *repo)
9792 const struct got_error *err = NULL;
9793 struct got_reflist_head *refs;
9794 char *refs_str = NULL;
9795 struct got_object_id *new_commit_id = NULL;
9796 struct got_commit_object *new_commit = NULL;
9797 char *new_commit_brief_str = NULL;
9798 struct got_object_id *yca_id = NULL;
9799 struct got_commit_object *yca_commit = NULL;
9800 char *yca_id_str = NULL, *yca_brief_str = NULL;
9801 char *custom_refs_str;
9803 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9804 return got_error_from_errno("asprintf");
9806 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9807 0, 0, refs_idmap, custom_refs_str);
9808 if (err)
9809 goto done;
9811 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9812 if (err)
9813 goto done;
9815 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9816 if (refs) {
9817 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9818 if (err)
9819 goto done;
9822 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9823 if (err)
9824 goto done;
9826 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9827 if (err)
9828 goto done;
9830 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9831 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9832 if (err)
9833 goto done;
9835 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9836 refs_str ? " (" : "", refs_str ? refs_str : "",
9837 refs_str ? ")" : "", new_commit_brief_str);
9838 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9839 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9840 free(refs_str);
9841 refs_str = NULL;
9843 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9844 if (err)
9845 goto done;
9847 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9848 if (err)
9849 goto done;
9851 err = got_object_id_str(&yca_id_str, yca_id);
9852 if (err)
9853 goto done;
9855 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9856 if (refs) {
9857 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9858 if (err)
9859 goto done;
9861 printf("history forked at %s%s%s%s\n %s\n",
9862 yca_id_str,
9863 refs_str ? " (" : "", refs_str ? refs_str : "",
9864 refs_str ? ")" : "", yca_brief_str);
9866 done:
9867 free(custom_refs_str);
9868 free(new_commit_id);
9869 free(refs_str);
9870 free(yca_id);
9871 free(yca_id_str);
9872 free(yca_brief_str);
9873 if (new_commit)
9874 got_object_commit_close(new_commit);
9875 if (yca_commit)
9876 got_object_commit_close(yca_commit);
9878 return NULL;
9881 static const struct got_error *
9882 process_backup_refs(const char *backup_ref_prefix,
9883 const char *wanted_branch_name,
9884 int delete, struct got_repository *repo)
9886 const struct got_error *err;
9887 struct got_reflist_head refs, backup_refs;
9888 struct got_reflist_entry *re;
9889 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9890 struct got_object_id *old_commit_id = NULL;
9891 char *branch_name = NULL;
9892 struct got_commit_object *old_commit = NULL;
9893 struct got_reflist_object_id_map *refs_idmap = NULL;
9894 int wanted_branch_found = 0;
9896 TAILQ_INIT(&refs);
9897 TAILQ_INIT(&backup_refs);
9899 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9900 if (err)
9901 return err;
9903 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9904 if (err)
9905 goto done;
9907 if (wanted_branch_name) {
9908 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9909 wanted_branch_name += 11;
9912 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9913 got_ref_cmp_by_commit_timestamp_descending, repo);
9914 if (err)
9915 goto done;
9917 TAILQ_FOREACH(re, &backup_refs, entry) {
9918 const char *refname = got_ref_get_name(re->ref);
9919 char *slash;
9921 err = check_cancelled(NULL);
9922 if (err)
9923 break;
9925 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9926 if (err)
9927 break;
9929 err = got_object_open_as_commit(&old_commit, repo,
9930 old_commit_id);
9931 if (err)
9932 break;
9934 if (strncmp(backup_ref_prefix, refname,
9935 backup_ref_prefix_len) == 0)
9936 refname += backup_ref_prefix_len;
9938 while (refname[0] == '/')
9939 refname++;
9941 branch_name = strdup(refname);
9942 if (branch_name == NULL) {
9943 err = got_error_from_errno("strdup");
9944 break;
9946 slash = strrchr(branch_name, '/');
9947 if (slash) {
9948 *slash = '\0';
9949 refname += strlen(branch_name) + 1;
9952 if (wanted_branch_name == NULL ||
9953 strcmp(wanted_branch_name, branch_name) == 0) {
9954 wanted_branch_found = 1;
9955 if (delete) {
9956 err = delete_backup_ref(re->ref,
9957 old_commit_id, repo);
9958 } else {
9959 err = print_backup_ref(branch_name, refname,
9960 old_commit_id, old_commit, refs_idmap,
9961 repo);
9963 if (err)
9964 break;
9967 free(old_commit_id);
9968 old_commit_id = NULL;
9969 free(branch_name);
9970 branch_name = NULL;
9971 got_object_commit_close(old_commit);
9972 old_commit = NULL;
9975 if (wanted_branch_name && !wanted_branch_found) {
9976 err = got_error_fmt(GOT_ERR_NOT_REF,
9977 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9979 done:
9980 if (refs_idmap)
9981 got_reflist_object_id_map_free(refs_idmap);
9982 got_ref_list_free(&refs);
9983 got_ref_list_free(&backup_refs);
9984 free(old_commit_id);
9985 free(branch_name);
9986 if (old_commit)
9987 got_object_commit_close(old_commit);
9988 return err;
9991 static const struct got_error *
9992 abort_progress(void *arg, unsigned char status, const char *path)
9995 * Unversioned files should not clutter progress output when
9996 * an operation is aborted.
9998 if (status == GOT_STATUS_UNVERSIONED)
9999 return NULL;
10001 return update_progress(arg, status, path);
10004 static const struct got_error *
10005 cmd_rebase(int argc, char *argv[])
10007 const struct got_error *error = NULL;
10008 struct got_worktree *worktree = NULL;
10009 struct got_repository *repo = NULL;
10010 struct got_fileindex *fileindex = NULL;
10011 char *cwd = NULL;
10012 struct got_reference *branch = NULL;
10013 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10014 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10015 struct got_object_id *resume_commit_id = NULL;
10016 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10017 struct got_commit_object *commit = NULL;
10018 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10019 int histedit_in_progress = 0, merge_in_progress = 0;
10020 int create_backup = 1, list_backups = 0, delete_backups = 0;
10021 struct got_object_id_queue commits;
10022 struct got_pathlist_head merged_paths;
10023 const struct got_object_id_queue *parent_ids;
10024 struct got_object_qid *qid, *pid;
10025 struct got_update_progress_arg upa;
10026 int *pack_fds = NULL;
10028 STAILQ_INIT(&commits);
10029 TAILQ_INIT(&merged_paths);
10030 memset(&upa, 0, sizeof(upa));
10032 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10033 switch (ch) {
10034 case 'a':
10035 abort_rebase = 1;
10036 break;
10037 case 'c':
10038 continue_rebase = 1;
10039 break;
10040 case 'l':
10041 list_backups = 1;
10042 break;
10043 case 'X':
10044 delete_backups = 1;
10045 break;
10046 default:
10047 usage_rebase();
10048 /* NOTREACHED */
10052 argc -= optind;
10053 argv += optind;
10055 #ifndef PROFILE
10056 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10057 "unveil", NULL) == -1)
10058 err(1, "pledge");
10059 #endif
10060 if (list_backups) {
10061 if (abort_rebase)
10062 option_conflict('l', 'a');
10063 if (continue_rebase)
10064 option_conflict('l', 'c');
10065 if (delete_backups)
10066 option_conflict('l', 'X');
10067 if (argc != 0 && argc != 1)
10068 usage_rebase();
10069 } else if (delete_backups) {
10070 if (abort_rebase)
10071 option_conflict('X', 'a');
10072 if (continue_rebase)
10073 option_conflict('X', 'c');
10074 if (list_backups)
10075 option_conflict('l', 'X');
10076 if (argc != 0 && argc != 1)
10077 usage_rebase();
10078 } else {
10079 if (abort_rebase && continue_rebase)
10080 usage_rebase();
10081 else if (abort_rebase || continue_rebase) {
10082 if (argc != 0)
10083 usage_rebase();
10084 } else if (argc != 1)
10085 usage_rebase();
10088 cwd = getcwd(NULL, 0);
10089 if (cwd == NULL) {
10090 error = got_error_from_errno("getcwd");
10091 goto done;
10094 error = got_repo_pack_fds_open(&pack_fds);
10095 if (error != NULL)
10096 goto done;
10098 error = got_worktree_open(&worktree, cwd);
10099 if (error) {
10100 if (list_backups || delete_backups) {
10101 if (error->code != GOT_ERR_NOT_WORKTREE)
10102 goto done;
10103 } else {
10104 if (error->code == GOT_ERR_NOT_WORKTREE)
10105 error = wrap_not_worktree_error(error,
10106 "rebase", cwd);
10107 goto done;
10111 error = got_repo_open(&repo,
10112 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10113 pack_fds);
10114 if (error != NULL)
10115 goto done;
10117 error = apply_unveil(got_repo_get_path(repo), 0,
10118 worktree ? got_worktree_get_root_path(worktree) : NULL);
10119 if (error)
10120 goto done;
10122 if (list_backups || delete_backups) {
10123 error = process_backup_refs(
10124 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10125 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10126 goto done; /* nothing else to do */
10129 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10130 worktree);
10131 if (error)
10132 goto done;
10133 if (histedit_in_progress) {
10134 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10135 goto done;
10138 error = got_worktree_merge_in_progress(&merge_in_progress,
10139 worktree, repo);
10140 if (error)
10141 goto done;
10142 if (merge_in_progress) {
10143 error = got_error(GOT_ERR_MERGE_BUSY);
10144 goto done;
10147 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10148 if (error)
10149 goto done;
10151 if (abort_rebase) {
10152 if (!rebase_in_progress) {
10153 error = got_error(GOT_ERR_NOT_REBASING);
10154 goto done;
10156 error = got_worktree_rebase_continue(&resume_commit_id,
10157 &new_base_branch, &tmp_branch, &branch, &fileindex,
10158 worktree, repo);
10159 if (error)
10160 goto done;
10161 printf("Switching work tree to %s\n",
10162 got_ref_get_symref_target(new_base_branch));
10163 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10164 new_base_branch, abort_progress, &upa);
10165 if (error)
10166 goto done;
10167 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10168 print_merge_progress_stats(&upa);
10169 goto done; /* nothing else to do */
10172 if (continue_rebase) {
10173 if (!rebase_in_progress) {
10174 error = got_error(GOT_ERR_NOT_REBASING);
10175 goto done;
10177 error = got_worktree_rebase_continue(&resume_commit_id,
10178 &new_base_branch, &tmp_branch, &branch, &fileindex,
10179 worktree, repo);
10180 if (error)
10181 goto done;
10183 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10184 resume_commit_id, repo);
10185 if (error)
10186 goto done;
10188 yca_id = got_object_id_dup(resume_commit_id);
10189 if (yca_id == NULL) {
10190 error = got_error_from_errno("got_object_id_dup");
10191 goto done;
10193 } else {
10194 error = got_ref_open(&branch, repo, argv[0], 0);
10195 if (error != NULL)
10196 goto done;
10199 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10200 if (error)
10201 goto done;
10203 if (!continue_rebase) {
10204 struct got_object_id *base_commit_id;
10206 base_commit_id = got_worktree_get_base_commit_id(worktree);
10207 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10208 base_commit_id, branch_head_commit_id, 1, repo,
10209 check_cancelled, NULL);
10210 if (error)
10211 goto done;
10212 if (yca_id == NULL) {
10213 error = got_error_msg(GOT_ERR_ANCESTRY,
10214 "specified branch shares no common ancestry "
10215 "with work tree's branch");
10216 goto done;
10219 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10220 if (error) {
10221 if (error->code != GOT_ERR_ANCESTRY)
10222 goto done;
10223 error = NULL;
10224 } else {
10225 struct got_pathlist_head paths;
10226 printf("%s is already based on %s\n",
10227 got_ref_get_name(branch),
10228 got_worktree_get_head_ref_name(worktree));
10229 error = switch_head_ref(branch, branch_head_commit_id,
10230 worktree, repo);
10231 if (error)
10232 goto done;
10233 error = got_worktree_set_base_commit_id(worktree, repo,
10234 branch_head_commit_id);
10235 if (error)
10236 goto done;
10237 TAILQ_INIT(&paths);
10238 error = got_pathlist_append(&paths, "", NULL);
10239 if (error)
10240 goto done;
10241 error = got_worktree_checkout_files(worktree,
10242 &paths, repo, update_progress, &upa,
10243 check_cancelled, NULL);
10244 got_pathlist_free(&paths);
10245 if (error)
10246 goto done;
10247 if (upa.did_something) {
10248 char *id_str;
10249 error = got_object_id_str(&id_str,
10250 branch_head_commit_id);
10251 if (error)
10252 goto done;
10253 printf("Updated to %s: %s\n",
10254 got_worktree_get_head_ref_name(worktree),
10255 id_str);
10256 free(id_str);
10257 } else
10258 printf("Already up-to-date\n");
10259 print_update_progress_stats(&upa);
10260 goto done;
10264 commit_id = branch_head_commit_id;
10265 error = got_object_open_as_commit(&commit, repo, commit_id);
10266 if (error)
10267 goto done;
10269 parent_ids = got_object_commit_get_parent_ids(commit);
10270 pid = STAILQ_FIRST(parent_ids);
10271 if (pid == NULL) {
10272 error = got_error(GOT_ERR_EMPTY_REBASE);
10273 goto done;
10275 error = collect_commits(&commits, commit_id, &pid->id,
10276 yca_id, got_worktree_get_path_prefix(worktree),
10277 GOT_ERR_REBASE_PATH, repo);
10278 got_object_commit_close(commit);
10279 commit = NULL;
10280 if (error)
10281 goto done;
10283 if (!continue_rebase) {
10284 error = got_worktree_rebase_prepare(&new_base_branch,
10285 &tmp_branch, &fileindex, worktree, branch, repo);
10286 if (error)
10287 goto done;
10290 if (STAILQ_EMPTY(&commits)) {
10291 if (continue_rebase) {
10292 error = rebase_complete(worktree, fileindex,
10293 branch, new_base_branch, tmp_branch, repo,
10294 create_backup);
10295 goto done;
10296 } else {
10297 /* Fast-forward the reference of the branch. */
10298 struct got_object_id *new_head_commit_id;
10299 char *id_str;
10300 error = got_ref_resolve(&new_head_commit_id, repo,
10301 new_base_branch);
10302 if (error)
10303 goto done;
10304 error = got_object_id_str(&id_str, new_head_commit_id);
10305 printf("Forwarding %s to commit %s\n",
10306 got_ref_get_name(branch), id_str);
10307 free(id_str);
10308 error = got_ref_change_ref(branch,
10309 new_head_commit_id);
10310 if (error)
10311 goto done;
10312 /* No backup needed since objects did not change. */
10313 create_backup = 0;
10317 pid = NULL;
10318 STAILQ_FOREACH(qid, &commits, entry) {
10320 commit_id = &qid->id;
10321 parent_id = pid ? &pid->id : yca_id;
10322 pid = qid;
10324 memset(&upa, 0, sizeof(upa));
10325 error = got_worktree_rebase_merge_files(&merged_paths,
10326 worktree, fileindex, parent_id, commit_id, repo,
10327 update_progress, &upa, check_cancelled, NULL);
10328 if (error)
10329 goto done;
10331 print_merge_progress_stats(&upa);
10332 if (upa.conflicts > 0 || upa.missing > 0 ||
10333 upa.not_deleted > 0 || upa.unversioned > 0) {
10334 if (upa.conflicts > 0) {
10335 error = show_rebase_merge_conflict(&qid->id,
10336 repo);
10337 if (error)
10338 goto done;
10340 got_worktree_rebase_pathlist_free(&merged_paths);
10341 break;
10344 error = rebase_commit(&merged_paths, worktree, fileindex,
10345 tmp_branch, commit_id, repo);
10346 got_worktree_rebase_pathlist_free(&merged_paths);
10347 if (error)
10348 goto done;
10351 if (upa.conflicts > 0 || upa.missing > 0 ||
10352 upa.not_deleted > 0 || upa.unversioned > 0) {
10353 error = got_worktree_rebase_postpone(worktree, fileindex);
10354 if (error)
10355 goto done;
10356 if (upa.conflicts > 0 && upa.missing == 0 &&
10357 upa.not_deleted == 0 && upa.unversioned == 0) {
10358 error = got_error_msg(GOT_ERR_CONFLICTS,
10359 "conflicts must be resolved before rebasing "
10360 "can continue");
10361 } else if (upa.conflicts > 0) {
10362 error = got_error_msg(GOT_ERR_CONFLICTS,
10363 "conflicts must be resolved before rebasing "
10364 "can continue; changes destined for some "
10365 "files were not yet merged and should be "
10366 "merged manually if required before the "
10367 "rebase operation is continued");
10368 } else {
10369 error = got_error_msg(GOT_ERR_CONFLICTS,
10370 "changes destined for some files were not "
10371 "yet merged and should be merged manually "
10372 "if required before the rebase operation "
10373 "is continued");
10375 } else
10376 error = rebase_complete(worktree, fileindex, branch,
10377 new_base_branch, tmp_branch, repo, create_backup);
10378 done:
10379 got_object_id_queue_free(&commits);
10380 free(branch_head_commit_id);
10381 free(resume_commit_id);
10382 free(yca_id);
10383 if (commit)
10384 got_object_commit_close(commit);
10385 if (branch)
10386 got_ref_close(branch);
10387 if (new_base_branch)
10388 got_ref_close(new_base_branch);
10389 if (tmp_branch)
10390 got_ref_close(tmp_branch);
10391 if (worktree)
10392 got_worktree_close(worktree);
10393 if (repo) {
10394 const struct got_error *close_err = got_repo_close(repo);
10395 if (error == NULL)
10396 error = close_err;
10398 if (pack_fds) {
10399 const struct got_error *pack_err =
10400 got_repo_pack_fds_close(pack_fds);
10401 if (error == NULL)
10402 error = pack_err;
10404 return error;
10407 __dead static void
10408 usage_histedit(void)
10410 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10411 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10412 getprogname());
10413 exit(1);
10416 #define GOT_HISTEDIT_PICK 'p'
10417 #define GOT_HISTEDIT_EDIT 'e'
10418 #define GOT_HISTEDIT_FOLD 'f'
10419 #define GOT_HISTEDIT_DROP 'd'
10420 #define GOT_HISTEDIT_MESG 'm'
10422 static const struct got_histedit_cmd {
10423 unsigned char code;
10424 const char *name;
10425 const char *desc;
10426 } got_histedit_cmds[] = {
10427 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10428 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10429 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10430 "be used" },
10431 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10432 { GOT_HISTEDIT_MESG, "mesg",
10433 "single-line log message for commit above (open editor if empty)" },
10436 struct got_histedit_list_entry {
10437 TAILQ_ENTRY(got_histedit_list_entry) entry;
10438 struct got_object_id *commit_id;
10439 const struct got_histedit_cmd *cmd;
10440 char *logmsg;
10442 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10444 static const struct got_error *
10445 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10446 FILE *f, struct got_repository *repo)
10448 const struct got_error *err = NULL;
10449 char *logmsg = NULL, *id_str = NULL;
10450 struct got_commit_object *commit = NULL;
10451 int n;
10453 err = got_object_open_as_commit(&commit, repo, commit_id);
10454 if (err)
10455 goto done;
10457 err = get_short_logmsg(&logmsg, 34, commit);
10458 if (err)
10459 goto done;
10461 err = got_object_id_str(&id_str, commit_id);
10462 if (err)
10463 goto done;
10465 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10466 if (n < 0)
10467 err = got_ferror(f, GOT_ERR_IO);
10468 done:
10469 if (commit)
10470 got_object_commit_close(commit);
10471 free(id_str);
10472 free(logmsg);
10473 return err;
10476 static const struct got_error *
10477 histedit_write_commit_list(struct got_object_id_queue *commits,
10478 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10479 struct got_repository *repo)
10481 const struct got_error *err = NULL;
10482 struct got_object_qid *qid;
10483 const char *histedit_cmd = NULL;
10485 if (STAILQ_EMPTY(commits))
10486 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10488 STAILQ_FOREACH(qid, commits, entry) {
10489 histedit_cmd = got_histedit_cmds[0].name;
10490 if (edit_only)
10491 histedit_cmd = "edit";
10492 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10493 histedit_cmd = "fold";
10494 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10495 if (err)
10496 break;
10497 if (edit_logmsg_only) {
10498 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10499 if (n < 0) {
10500 err = got_ferror(f, GOT_ERR_IO);
10501 break;
10506 return err;
10509 static const struct got_error *
10510 write_cmd_list(FILE *f, const char *branch_name,
10511 struct got_object_id_queue *commits)
10513 const struct got_error *err = NULL;
10514 size_t i;
10515 int n;
10516 char *id_str;
10517 struct got_object_qid *qid;
10519 qid = STAILQ_FIRST(commits);
10520 err = got_object_id_str(&id_str, &qid->id);
10521 if (err)
10522 return err;
10524 n = fprintf(f,
10525 "# Editing the history of branch '%s' starting at\n"
10526 "# commit %s\n"
10527 "# Commits will be processed in order from top to "
10528 "bottom of this file.\n", branch_name, id_str);
10529 if (n < 0) {
10530 err = got_ferror(f, GOT_ERR_IO);
10531 goto done;
10534 n = fprintf(f, "# Available histedit commands:\n");
10535 if (n < 0) {
10536 err = got_ferror(f, GOT_ERR_IO);
10537 goto done;
10540 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10541 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10542 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10543 cmd->desc);
10544 if (n < 0) {
10545 err = got_ferror(f, GOT_ERR_IO);
10546 break;
10549 done:
10550 free(id_str);
10551 return err;
10554 static const struct got_error *
10555 histedit_syntax_error(int lineno)
10557 static char msg[42];
10558 int ret;
10560 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10561 lineno);
10562 if (ret == -1 || ret >= sizeof(msg))
10563 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10565 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10568 static const struct got_error *
10569 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10570 char *logmsg, struct got_repository *repo)
10572 const struct got_error *err;
10573 struct got_commit_object *folded_commit = NULL;
10574 char *id_str, *folded_logmsg = NULL;
10576 err = got_object_id_str(&id_str, hle->commit_id);
10577 if (err)
10578 return err;
10580 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10581 if (err)
10582 goto done;
10584 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10585 if (err)
10586 goto done;
10587 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10588 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10589 folded_logmsg) == -1) {
10590 err = got_error_from_errno("asprintf");
10592 done:
10593 if (folded_commit)
10594 got_object_commit_close(folded_commit);
10595 free(id_str);
10596 free(folded_logmsg);
10597 return err;
10600 static struct got_histedit_list_entry *
10601 get_folded_commits(struct got_histedit_list_entry *hle)
10603 struct got_histedit_list_entry *prev, *folded = NULL;
10605 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10606 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10607 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10608 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10609 folded = prev;
10610 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10613 return folded;
10616 static const struct got_error *
10617 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10618 struct got_repository *repo)
10620 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10621 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10622 const struct got_error *err = NULL;
10623 struct got_commit_object *commit = NULL;
10624 int logmsg_len;
10625 int fd;
10626 struct got_histedit_list_entry *folded = NULL;
10628 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10629 if (err)
10630 return err;
10632 folded = get_folded_commits(hle);
10633 if (folded) {
10634 while (folded != hle) {
10635 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10636 folded = TAILQ_NEXT(folded, entry);
10637 continue;
10639 err = append_folded_commit_msg(&new_msg, folded,
10640 logmsg, repo);
10641 if (err)
10642 goto done;
10643 free(logmsg);
10644 logmsg = new_msg;
10645 folded = TAILQ_NEXT(folded, entry);
10649 err = got_object_id_str(&id_str, hle->commit_id);
10650 if (err)
10651 goto done;
10652 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10653 if (err)
10654 goto done;
10655 logmsg_len = asprintf(&new_msg,
10656 "%s\n# original log message of commit %s: %s",
10657 logmsg ? logmsg : "", id_str, orig_logmsg);
10658 if (logmsg_len == -1) {
10659 err = got_error_from_errno("asprintf");
10660 goto done;
10662 free(logmsg);
10663 logmsg = new_msg;
10665 err = got_object_id_str(&id_str, hle->commit_id);
10666 if (err)
10667 goto done;
10669 err = got_opentemp_named_fd(&logmsg_path, &fd,
10670 GOT_TMPDIR_STR "/got-logmsg");
10671 if (err)
10672 goto done;
10674 write(fd, logmsg, logmsg_len);
10675 close(fd);
10677 err = get_editor(&editor);
10678 if (err)
10679 goto done;
10681 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10682 logmsg_len, 0);
10683 if (err) {
10684 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10685 goto done;
10686 err = NULL;
10687 hle->logmsg = strdup(new_msg);
10688 if (hle->logmsg == NULL)
10689 err = got_error_from_errno("strdup");
10691 done:
10692 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10693 err = got_error_from_errno2("unlink", logmsg_path);
10694 free(logmsg_path);
10695 free(logmsg);
10696 free(orig_logmsg);
10697 free(editor);
10698 if (commit)
10699 got_object_commit_close(commit);
10700 return err;
10703 static const struct got_error *
10704 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10705 FILE *f, struct got_repository *repo)
10707 const struct got_error *err = NULL;
10708 char *line = NULL, *p, *end;
10709 size_t i, size;
10710 ssize_t len;
10711 int lineno = 0;
10712 const struct got_histedit_cmd *cmd;
10713 struct got_object_id *commit_id = NULL;
10714 struct got_histedit_list_entry *hle = NULL;
10716 for (;;) {
10717 len = getline(&line, &size, f);
10718 if (len == -1) {
10719 const struct got_error *getline_err;
10720 if (feof(f))
10721 break;
10722 getline_err = got_error_from_errno("getline");
10723 err = got_ferror(f, getline_err->code);
10724 break;
10726 lineno++;
10727 p = line;
10728 while (isspace((unsigned char)p[0]))
10729 p++;
10730 if (p[0] == '#' || p[0] == '\0') {
10731 free(line);
10732 line = NULL;
10733 continue;
10735 cmd = NULL;
10736 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10737 cmd = &got_histedit_cmds[i];
10738 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10739 isspace((unsigned char)p[strlen(cmd->name)])) {
10740 p += strlen(cmd->name);
10741 break;
10743 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10744 p++;
10745 break;
10748 if (i == nitems(got_histedit_cmds)) {
10749 err = histedit_syntax_error(lineno);
10750 break;
10752 while (isspace((unsigned char)p[0]))
10753 p++;
10754 if (cmd->code == GOT_HISTEDIT_MESG) {
10755 if (hle == NULL || hle->logmsg != NULL) {
10756 err = got_error(GOT_ERR_HISTEDIT_CMD);
10757 break;
10759 if (p[0] == '\0') {
10760 err = histedit_edit_logmsg(hle, repo);
10761 if (err)
10762 break;
10763 } else {
10764 hle->logmsg = strdup(p);
10765 if (hle->logmsg == NULL) {
10766 err = got_error_from_errno("strdup");
10767 break;
10770 free(line);
10771 line = NULL;
10772 continue;
10773 } else {
10774 end = p;
10775 while (end[0] && !isspace((unsigned char)end[0]))
10776 end++;
10777 *end = '\0';
10779 err = got_object_resolve_id_str(&commit_id, repo, p);
10780 if (err) {
10781 /* override error code */
10782 err = histedit_syntax_error(lineno);
10783 break;
10786 hle = malloc(sizeof(*hle));
10787 if (hle == NULL) {
10788 err = got_error_from_errno("malloc");
10789 break;
10791 hle->cmd = cmd;
10792 hle->commit_id = commit_id;
10793 hle->logmsg = NULL;
10794 commit_id = NULL;
10795 free(line);
10796 line = NULL;
10797 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10800 free(line);
10801 free(commit_id);
10802 return err;
10805 static const struct got_error *
10806 histedit_check_script(struct got_histedit_list *histedit_cmds,
10807 struct got_object_id_queue *commits, struct got_repository *repo)
10809 const struct got_error *err = NULL;
10810 struct got_object_qid *qid;
10811 struct got_histedit_list_entry *hle;
10812 static char msg[92];
10813 char *id_str;
10815 if (TAILQ_EMPTY(histedit_cmds))
10816 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10817 "histedit script contains no commands");
10818 if (STAILQ_EMPTY(commits))
10819 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10821 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10822 struct got_histedit_list_entry *hle2;
10823 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10824 if (hle == hle2)
10825 continue;
10826 if (got_object_id_cmp(hle->commit_id,
10827 hle2->commit_id) != 0)
10828 continue;
10829 err = got_object_id_str(&id_str, hle->commit_id);
10830 if (err)
10831 return err;
10832 snprintf(msg, sizeof(msg), "commit %s is listed "
10833 "more than once in histedit script", id_str);
10834 free(id_str);
10835 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10839 STAILQ_FOREACH(qid, commits, entry) {
10840 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10841 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10842 break;
10844 if (hle == NULL) {
10845 err = got_object_id_str(&id_str, &qid->id);
10846 if (err)
10847 return err;
10848 snprintf(msg, sizeof(msg),
10849 "commit %s missing from histedit script", id_str);
10850 free(id_str);
10851 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10855 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10856 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10857 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10858 "last commit in histedit script cannot be folded");
10860 return NULL;
10863 static const struct got_error *
10864 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10865 const char *path, struct got_object_id_queue *commits,
10866 struct got_repository *repo)
10868 const struct got_error *err = NULL;
10869 char *editor;
10870 FILE *f = NULL;
10872 err = get_editor(&editor);
10873 if (err)
10874 return err;
10876 if (spawn_editor(editor, path) == -1) {
10877 err = got_error_from_errno("failed spawning editor");
10878 goto done;
10881 f = fopen(path, "re");
10882 if (f == NULL) {
10883 err = got_error_from_errno("fopen");
10884 goto done;
10886 err = histedit_parse_list(histedit_cmds, f, repo);
10887 if (err)
10888 goto done;
10890 err = histedit_check_script(histedit_cmds, commits, repo);
10891 done:
10892 if (f && fclose(f) == EOF && err == NULL)
10893 err = got_error_from_errno("fclose");
10894 free(editor);
10895 return err;
10898 static const struct got_error *
10899 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10900 struct got_object_id_queue *, const char *, const char *,
10901 struct got_repository *);
10903 static const struct got_error *
10904 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10905 struct got_object_id_queue *commits, const char *branch_name,
10906 int edit_logmsg_only, int fold_only, int edit_only,
10907 struct got_repository *repo)
10909 const struct got_error *err;
10910 FILE *f = NULL;
10911 char *path = NULL;
10913 err = got_opentemp_named(&path, &f, "got-histedit");
10914 if (err)
10915 return err;
10917 err = write_cmd_list(f, branch_name, commits);
10918 if (err)
10919 goto done;
10921 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10922 fold_only, edit_only, repo);
10923 if (err)
10924 goto done;
10926 if (edit_logmsg_only || fold_only || edit_only) {
10927 rewind(f);
10928 err = histedit_parse_list(histedit_cmds, f, repo);
10929 } else {
10930 if (fclose(f) == EOF) {
10931 err = got_error_from_errno("fclose");
10932 goto done;
10934 f = NULL;
10935 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10936 if (err) {
10937 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10938 err->code != GOT_ERR_HISTEDIT_CMD)
10939 goto done;
10940 err = histedit_edit_list_retry(histedit_cmds, err,
10941 commits, path, branch_name, repo);
10944 done:
10945 if (f && fclose(f) == EOF && err == NULL)
10946 err = got_error_from_errno("fclose");
10947 if (path && unlink(path) != 0 && err == NULL)
10948 err = got_error_from_errno2("unlink", path);
10949 free(path);
10950 return err;
10953 static const struct got_error *
10954 histedit_save_list(struct got_histedit_list *histedit_cmds,
10955 struct got_worktree *worktree, struct got_repository *repo)
10957 const struct got_error *err = NULL;
10958 char *path = NULL;
10959 FILE *f = NULL;
10960 struct got_histedit_list_entry *hle;
10961 struct got_commit_object *commit = NULL;
10963 err = got_worktree_get_histedit_script_path(&path, worktree);
10964 if (err)
10965 return err;
10967 f = fopen(path, "we");
10968 if (f == NULL) {
10969 err = got_error_from_errno2("fopen", path);
10970 goto done;
10972 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10973 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10974 repo);
10975 if (err)
10976 break;
10978 if (hle->logmsg) {
10979 int n = fprintf(f, "%c %s\n",
10980 GOT_HISTEDIT_MESG, hle->logmsg);
10981 if (n < 0) {
10982 err = got_ferror(f, GOT_ERR_IO);
10983 break;
10987 done:
10988 if (f && fclose(f) == EOF && err == NULL)
10989 err = got_error_from_errno("fclose");
10990 free(path);
10991 if (commit)
10992 got_object_commit_close(commit);
10993 return err;
10996 static void
10997 histedit_free_list(struct got_histedit_list *histedit_cmds)
10999 struct got_histedit_list_entry *hle;
11001 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11002 TAILQ_REMOVE(histedit_cmds, hle, entry);
11003 free(hle);
11007 static const struct got_error *
11008 histedit_load_list(struct got_histedit_list *histedit_cmds,
11009 const char *path, struct got_repository *repo)
11011 const struct got_error *err = NULL;
11012 FILE *f = NULL;
11014 f = fopen(path, "re");
11015 if (f == NULL) {
11016 err = got_error_from_errno2("fopen", path);
11017 goto done;
11020 err = histedit_parse_list(histedit_cmds, f, repo);
11021 done:
11022 if (f && fclose(f) == EOF && err == NULL)
11023 err = got_error_from_errno("fclose");
11024 return err;
11027 static const struct got_error *
11028 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11029 const struct got_error *edit_err, struct got_object_id_queue *commits,
11030 const char *path, const char *branch_name, struct got_repository *repo)
11032 const struct got_error *err = NULL, *prev_err = edit_err;
11033 int resp = ' ';
11035 while (resp != 'c' && resp != 'r' && resp != 'a') {
11036 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11037 "or (a)bort: ", getprogname(), prev_err->msg);
11038 resp = getchar();
11039 if (resp == '\n')
11040 resp = getchar();
11041 if (resp == 'c') {
11042 histedit_free_list(histedit_cmds);
11043 err = histedit_run_editor(histedit_cmds, path, commits,
11044 repo);
11045 if (err) {
11046 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11047 err->code != GOT_ERR_HISTEDIT_CMD)
11048 break;
11049 prev_err = err;
11050 resp = ' ';
11051 continue;
11053 break;
11054 } else if (resp == 'r') {
11055 histedit_free_list(histedit_cmds);
11056 err = histedit_edit_script(histedit_cmds,
11057 commits, branch_name, 0, 0, 0, repo);
11058 if (err) {
11059 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11060 err->code != GOT_ERR_HISTEDIT_CMD)
11061 break;
11062 prev_err = err;
11063 resp = ' ';
11064 continue;
11066 break;
11067 } else if (resp == 'a') {
11068 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11069 break;
11070 } else
11071 printf("invalid response '%c'\n", resp);
11074 return err;
11077 static const struct got_error *
11078 histedit_complete(struct got_worktree *worktree,
11079 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11080 struct got_reference *branch, struct got_repository *repo)
11082 printf("Switching work tree to %s\n",
11083 got_ref_get_symref_target(branch));
11084 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11085 branch, repo);
11088 static const struct got_error *
11089 show_histedit_progress(struct got_commit_object *commit,
11090 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11092 const struct got_error *err;
11093 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11095 err = got_object_id_str(&old_id_str, hle->commit_id);
11096 if (err)
11097 goto done;
11099 if (new_id) {
11100 err = got_object_id_str(&new_id_str, new_id);
11101 if (err)
11102 goto done;
11105 old_id_str[12] = '\0';
11106 if (new_id_str)
11107 new_id_str[12] = '\0';
11109 if (hle->logmsg) {
11110 logmsg = strdup(hle->logmsg);
11111 if (logmsg == NULL) {
11112 err = got_error_from_errno("strdup");
11113 goto done;
11115 trim_logmsg(logmsg, 42);
11116 } else {
11117 err = get_short_logmsg(&logmsg, 42, commit);
11118 if (err)
11119 goto done;
11122 switch (hle->cmd->code) {
11123 case GOT_HISTEDIT_PICK:
11124 case GOT_HISTEDIT_EDIT:
11125 printf("%s -> %s: %s\n", old_id_str,
11126 new_id_str ? new_id_str : "no-op change", logmsg);
11127 break;
11128 case GOT_HISTEDIT_DROP:
11129 case GOT_HISTEDIT_FOLD:
11130 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11131 logmsg);
11132 break;
11133 default:
11134 break;
11136 done:
11137 free(old_id_str);
11138 free(new_id_str);
11139 return err;
11142 static const struct got_error *
11143 histedit_commit(struct got_pathlist_head *merged_paths,
11144 struct got_worktree *worktree, struct got_fileindex *fileindex,
11145 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11146 struct got_repository *repo)
11148 const struct got_error *err;
11149 struct got_commit_object *commit;
11150 struct got_object_id *new_commit_id;
11152 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11153 && hle->logmsg == NULL) {
11154 err = histedit_edit_logmsg(hle, repo);
11155 if (err)
11156 return err;
11159 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11160 if (err)
11161 return err;
11163 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11164 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11165 hle->logmsg, repo);
11166 if (err) {
11167 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11168 goto done;
11169 err = show_histedit_progress(commit, hle, NULL);
11170 } else {
11171 err = show_histedit_progress(commit, hle, new_commit_id);
11172 free(new_commit_id);
11174 done:
11175 got_object_commit_close(commit);
11176 return err;
11179 static const struct got_error *
11180 histedit_skip_commit(struct got_histedit_list_entry *hle,
11181 struct got_worktree *worktree, struct got_repository *repo)
11183 const struct got_error *error;
11184 struct got_commit_object *commit;
11186 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11187 repo);
11188 if (error)
11189 return error;
11191 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11192 if (error)
11193 return error;
11195 error = show_histedit_progress(commit, hle, NULL);
11196 got_object_commit_close(commit);
11197 return error;
11200 static const struct got_error *
11201 check_local_changes(void *arg, unsigned char status,
11202 unsigned char staged_status, const char *path,
11203 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11204 struct got_object_id *commit_id, int dirfd, const char *de_name)
11206 int *have_local_changes = arg;
11208 switch (status) {
11209 case GOT_STATUS_ADD:
11210 case GOT_STATUS_DELETE:
11211 case GOT_STATUS_MODIFY:
11212 case GOT_STATUS_CONFLICT:
11213 *have_local_changes = 1;
11214 return got_error(GOT_ERR_CANCELLED);
11215 default:
11216 break;
11219 switch (staged_status) {
11220 case GOT_STATUS_ADD:
11221 case GOT_STATUS_DELETE:
11222 case GOT_STATUS_MODIFY:
11223 *have_local_changes = 1;
11224 return got_error(GOT_ERR_CANCELLED);
11225 default:
11226 break;
11229 return NULL;
11232 static const struct got_error *
11233 cmd_histedit(int argc, char *argv[])
11235 const struct got_error *error = NULL;
11236 struct got_worktree *worktree = NULL;
11237 struct got_fileindex *fileindex = NULL;
11238 struct got_repository *repo = NULL;
11239 char *cwd = NULL;
11240 struct got_reference *branch = NULL;
11241 struct got_reference *tmp_branch = NULL;
11242 struct got_object_id *resume_commit_id = NULL;
11243 struct got_object_id *base_commit_id = NULL;
11244 struct got_object_id *head_commit_id = NULL;
11245 struct got_commit_object *commit = NULL;
11246 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11247 struct got_update_progress_arg upa;
11248 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11249 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11250 int list_backups = 0, delete_backups = 0;
11251 const char *edit_script_path = NULL;
11252 struct got_object_id_queue commits;
11253 struct got_pathlist_head merged_paths;
11254 const struct got_object_id_queue *parent_ids;
11255 struct got_object_qid *pid;
11256 struct got_histedit_list histedit_cmds;
11257 struct got_histedit_list_entry *hle;
11258 int *pack_fds = NULL;
11260 STAILQ_INIT(&commits);
11261 TAILQ_INIT(&histedit_cmds);
11262 TAILQ_INIT(&merged_paths);
11263 memset(&upa, 0, sizeof(upa));
11265 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11266 switch (ch) {
11267 case 'a':
11268 abort_edit = 1;
11269 break;
11270 case 'c':
11271 continue_edit = 1;
11272 break;
11273 case 'e':
11274 edit_only = 1;
11275 break;
11276 case 'f':
11277 fold_only = 1;
11278 break;
11279 case 'F':
11280 edit_script_path = optarg;
11281 break;
11282 case 'm':
11283 edit_logmsg_only = 1;
11284 break;
11285 case 'l':
11286 list_backups = 1;
11287 break;
11288 case 'X':
11289 delete_backups = 1;
11290 break;
11291 default:
11292 usage_histedit();
11293 /* NOTREACHED */
11297 argc -= optind;
11298 argv += optind;
11300 #ifndef PROFILE
11301 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11302 "unveil", NULL) == -1)
11303 err(1, "pledge");
11304 #endif
11305 if (abort_edit && continue_edit)
11306 option_conflict('a', 'c');
11307 if (edit_script_path && edit_logmsg_only)
11308 option_conflict('F', 'm');
11309 if (abort_edit && edit_logmsg_only)
11310 option_conflict('a', 'm');
11311 if (continue_edit && edit_logmsg_only)
11312 option_conflict('c', 'm');
11313 if (abort_edit && fold_only)
11314 option_conflict('a', 'f');
11315 if (continue_edit && fold_only)
11316 option_conflict('c', 'f');
11317 if (fold_only && edit_logmsg_only)
11318 option_conflict('f', 'm');
11319 if (edit_script_path && fold_only)
11320 option_conflict('F', 'f');
11321 if (abort_edit && edit_only)
11322 option_conflict('a', 'e');
11323 if (continue_edit && edit_only)
11324 option_conflict('c', 'e');
11325 if (edit_only && edit_logmsg_only)
11326 option_conflict('e', 'm');
11327 if (edit_script_path && edit_only)
11328 option_conflict('F', 'e');
11329 if (list_backups) {
11330 if (abort_edit)
11331 option_conflict('l', 'a');
11332 if (continue_edit)
11333 option_conflict('l', 'c');
11334 if (edit_script_path)
11335 option_conflict('l', 'F');
11336 if (edit_logmsg_only)
11337 option_conflict('l', 'm');
11338 if (fold_only)
11339 option_conflict('l', 'f');
11340 if (edit_only)
11341 option_conflict('l', 'e');
11342 if (delete_backups)
11343 option_conflict('l', 'X');
11344 if (argc != 0 && argc != 1)
11345 usage_histedit();
11346 } else if (delete_backups) {
11347 if (abort_edit)
11348 option_conflict('X', 'a');
11349 if (continue_edit)
11350 option_conflict('X', 'c');
11351 if (edit_script_path)
11352 option_conflict('X', 'F');
11353 if (edit_logmsg_only)
11354 option_conflict('X', 'm');
11355 if (fold_only)
11356 option_conflict('X', 'f');
11357 if (edit_only)
11358 option_conflict('X', 'e');
11359 if (list_backups)
11360 option_conflict('X', 'l');
11361 if (argc != 0 && argc != 1)
11362 usage_histedit();
11363 } else if (argc != 0)
11364 usage_histedit();
11367 * This command cannot apply unveil(2) in all cases because the
11368 * user may choose to run an editor to edit the histedit script
11369 * and to edit individual commit log messages.
11370 * unveil(2) traverses exec(2); if an editor is used we have to
11371 * apply unveil after edit script and log messages have been written.
11372 * XXX TODO: Make use of unveil(2) where possible.
11375 cwd = getcwd(NULL, 0);
11376 if (cwd == NULL) {
11377 error = got_error_from_errno("getcwd");
11378 goto done;
11381 error = got_repo_pack_fds_open(&pack_fds);
11382 if (error != NULL)
11383 goto done;
11385 error = got_worktree_open(&worktree, cwd);
11386 if (error) {
11387 if (list_backups || delete_backups) {
11388 if (error->code != GOT_ERR_NOT_WORKTREE)
11389 goto done;
11390 } else {
11391 if (error->code == GOT_ERR_NOT_WORKTREE)
11392 error = wrap_not_worktree_error(error,
11393 "histedit", cwd);
11394 goto done;
11398 if (list_backups || delete_backups) {
11399 error = got_repo_open(&repo,
11400 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11401 NULL, pack_fds);
11402 if (error != NULL)
11403 goto done;
11404 error = apply_unveil(got_repo_get_path(repo), 0,
11405 worktree ? got_worktree_get_root_path(worktree) : NULL);
11406 if (error)
11407 goto done;
11408 error = process_backup_refs(
11409 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11410 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11411 goto done; /* nothing else to do */
11414 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11415 NULL, pack_fds);
11416 if (error != NULL)
11417 goto done;
11419 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11420 if (error)
11421 goto done;
11422 if (rebase_in_progress) {
11423 error = got_error(GOT_ERR_REBASING);
11424 goto done;
11427 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11428 repo);
11429 if (error)
11430 goto done;
11431 if (merge_in_progress) {
11432 error = got_error(GOT_ERR_MERGE_BUSY);
11433 goto done;
11436 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11437 if (error)
11438 goto done;
11440 if (edit_in_progress && edit_logmsg_only) {
11441 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11442 "histedit operation is in progress in this "
11443 "work tree and must be continued or aborted "
11444 "before the -m option can be used");
11445 goto done;
11447 if (edit_in_progress && fold_only) {
11448 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11449 "histedit operation is in progress in this "
11450 "work tree and must be continued or aborted "
11451 "before the -f option can be used");
11452 goto done;
11454 if (edit_in_progress && edit_only) {
11455 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11456 "histedit operation is in progress in this "
11457 "work tree and must be continued or aborted "
11458 "before the -e option can be used");
11459 goto done;
11462 if (edit_in_progress && abort_edit) {
11463 error = got_worktree_histedit_continue(&resume_commit_id,
11464 &tmp_branch, &branch, &base_commit_id, &fileindex,
11465 worktree, repo);
11466 if (error)
11467 goto done;
11468 printf("Switching work tree to %s\n",
11469 got_ref_get_symref_target(branch));
11470 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11471 branch, base_commit_id, abort_progress, &upa);
11472 if (error)
11473 goto done;
11474 printf("Histedit of %s aborted\n",
11475 got_ref_get_symref_target(branch));
11476 print_merge_progress_stats(&upa);
11477 goto done; /* nothing else to do */
11478 } else if (abort_edit) {
11479 error = got_error(GOT_ERR_NOT_HISTEDIT);
11480 goto done;
11483 if (continue_edit) {
11484 char *path;
11486 if (!edit_in_progress) {
11487 error = got_error(GOT_ERR_NOT_HISTEDIT);
11488 goto done;
11491 error = got_worktree_get_histedit_script_path(&path, worktree);
11492 if (error)
11493 goto done;
11495 error = histedit_load_list(&histedit_cmds, path, repo);
11496 free(path);
11497 if (error)
11498 goto done;
11500 error = got_worktree_histedit_continue(&resume_commit_id,
11501 &tmp_branch, &branch, &base_commit_id, &fileindex,
11502 worktree, repo);
11503 if (error)
11504 goto done;
11506 error = got_ref_resolve(&head_commit_id, repo, branch);
11507 if (error)
11508 goto done;
11510 error = got_object_open_as_commit(&commit, repo,
11511 head_commit_id);
11512 if (error)
11513 goto done;
11514 parent_ids = got_object_commit_get_parent_ids(commit);
11515 pid = STAILQ_FIRST(parent_ids);
11516 if (pid == NULL) {
11517 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11518 goto done;
11520 error = collect_commits(&commits, head_commit_id, &pid->id,
11521 base_commit_id, got_worktree_get_path_prefix(worktree),
11522 GOT_ERR_HISTEDIT_PATH, repo);
11523 got_object_commit_close(commit);
11524 commit = NULL;
11525 if (error)
11526 goto done;
11527 } else {
11528 if (edit_in_progress) {
11529 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11530 goto done;
11533 error = got_ref_open(&branch, repo,
11534 got_worktree_get_head_ref_name(worktree), 0);
11535 if (error != NULL)
11536 goto done;
11538 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11539 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11540 "will not edit commit history of a branch outside "
11541 "the \"refs/heads/\" reference namespace");
11542 goto done;
11545 error = got_ref_resolve(&head_commit_id, repo, branch);
11546 got_ref_close(branch);
11547 branch = NULL;
11548 if (error)
11549 goto done;
11551 error = got_object_open_as_commit(&commit, repo,
11552 head_commit_id);
11553 if (error)
11554 goto done;
11555 parent_ids = got_object_commit_get_parent_ids(commit);
11556 pid = STAILQ_FIRST(parent_ids);
11557 if (pid == NULL) {
11558 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11559 goto done;
11561 error = collect_commits(&commits, head_commit_id, &pid->id,
11562 got_worktree_get_base_commit_id(worktree),
11563 got_worktree_get_path_prefix(worktree),
11564 GOT_ERR_HISTEDIT_PATH, repo);
11565 got_object_commit_close(commit);
11566 commit = NULL;
11567 if (error)
11568 goto done;
11570 if (STAILQ_EMPTY(&commits)) {
11571 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11572 goto done;
11575 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11576 &base_commit_id, &fileindex, worktree, repo);
11577 if (error)
11578 goto done;
11580 if (edit_script_path) {
11581 error = histedit_load_list(&histedit_cmds,
11582 edit_script_path, repo);
11583 if (error) {
11584 got_worktree_histedit_abort(worktree, fileindex,
11585 repo, branch, base_commit_id,
11586 abort_progress, &upa);
11587 print_merge_progress_stats(&upa);
11588 goto done;
11590 } else {
11591 const char *branch_name;
11592 branch_name = got_ref_get_symref_target(branch);
11593 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11594 branch_name += 11;
11595 error = histedit_edit_script(&histedit_cmds, &commits,
11596 branch_name, edit_logmsg_only, fold_only,
11597 edit_only, repo);
11598 if (error) {
11599 got_worktree_histedit_abort(worktree, fileindex,
11600 repo, branch, base_commit_id,
11601 abort_progress, &upa);
11602 print_merge_progress_stats(&upa);
11603 goto done;
11608 error = histedit_save_list(&histedit_cmds, worktree,
11609 repo);
11610 if (error) {
11611 got_worktree_histedit_abort(worktree, fileindex,
11612 repo, branch, base_commit_id,
11613 abort_progress, &upa);
11614 print_merge_progress_stats(&upa);
11615 goto done;
11620 error = histedit_check_script(&histedit_cmds, &commits, repo);
11621 if (error)
11622 goto done;
11624 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11625 if (resume_commit_id) {
11626 if (got_object_id_cmp(hle->commit_id,
11627 resume_commit_id) != 0)
11628 continue;
11630 resume_commit_id = NULL;
11631 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11632 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11633 error = histedit_skip_commit(hle, worktree,
11634 repo);
11635 if (error)
11636 goto done;
11637 } else {
11638 struct got_pathlist_head paths;
11639 int have_changes = 0;
11641 TAILQ_INIT(&paths);
11642 error = got_pathlist_append(&paths, "", NULL);
11643 if (error)
11644 goto done;
11645 error = got_worktree_status(worktree, &paths,
11646 repo, 0, check_local_changes, &have_changes,
11647 check_cancelled, NULL);
11648 got_pathlist_free(&paths);
11649 if (error) {
11650 if (error->code != GOT_ERR_CANCELLED)
11651 goto done;
11652 if (sigint_received || sigpipe_received)
11653 goto done;
11655 if (have_changes) {
11656 error = histedit_commit(NULL, worktree,
11657 fileindex, tmp_branch, hle, repo);
11658 if (error)
11659 goto done;
11660 } else {
11661 error = got_object_open_as_commit(
11662 &commit, repo, hle->commit_id);
11663 if (error)
11664 goto done;
11665 error = show_histedit_progress(commit,
11666 hle, NULL);
11667 got_object_commit_close(commit);
11668 commit = NULL;
11669 if (error)
11670 goto done;
11673 continue;
11676 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11677 error = histedit_skip_commit(hle, worktree, repo);
11678 if (error)
11679 goto done;
11680 continue;
11683 error = got_object_open_as_commit(&commit, repo,
11684 hle->commit_id);
11685 if (error)
11686 goto done;
11687 parent_ids = got_object_commit_get_parent_ids(commit);
11688 pid = STAILQ_FIRST(parent_ids);
11690 error = got_worktree_histedit_merge_files(&merged_paths,
11691 worktree, fileindex, &pid->id, hle->commit_id, repo,
11692 update_progress, &upa, check_cancelled, NULL);
11693 if (error)
11694 goto done;
11695 got_object_commit_close(commit);
11696 commit = NULL;
11698 print_merge_progress_stats(&upa);
11699 if (upa.conflicts > 0 || upa.missing > 0 ||
11700 upa.not_deleted > 0 || upa.unversioned > 0) {
11701 if (upa.conflicts > 0) {
11702 error = show_rebase_merge_conflict(
11703 hle->commit_id, repo);
11704 if (error)
11705 goto done;
11707 got_worktree_rebase_pathlist_free(&merged_paths);
11708 break;
11711 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11712 char *id_str;
11713 error = got_object_id_str(&id_str, hle->commit_id);
11714 if (error)
11715 goto done;
11716 printf("Stopping histedit for amending commit %s\n",
11717 id_str);
11718 free(id_str);
11719 got_worktree_rebase_pathlist_free(&merged_paths);
11720 error = got_worktree_histedit_postpone(worktree,
11721 fileindex);
11722 goto done;
11725 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11726 error = histedit_skip_commit(hle, worktree, repo);
11727 if (error)
11728 goto done;
11729 continue;
11732 error = histedit_commit(&merged_paths, worktree, fileindex,
11733 tmp_branch, hle, repo);
11734 got_worktree_rebase_pathlist_free(&merged_paths);
11735 if (error)
11736 goto done;
11739 if (upa.conflicts > 0 || upa.missing > 0 ||
11740 upa.not_deleted > 0 || upa.unversioned > 0) {
11741 error = got_worktree_histedit_postpone(worktree, fileindex);
11742 if (error)
11743 goto done;
11744 if (upa.conflicts > 0 && upa.missing == 0 &&
11745 upa.not_deleted == 0 && upa.unversioned == 0) {
11746 error = got_error_msg(GOT_ERR_CONFLICTS,
11747 "conflicts must be resolved before histedit "
11748 "can continue");
11749 } else if (upa.conflicts > 0) {
11750 error = got_error_msg(GOT_ERR_CONFLICTS,
11751 "conflicts must be resolved before histedit "
11752 "can continue; changes destined for some "
11753 "files were not yet merged and should be "
11754 "merged manually if required before the "
11755 "histedit operation is continued");
11756 } else {
11757 error = got_error_msg(GOT_ERR_CONFLICTS,
11758 "changes destined for some files were not "
11759 "yet merged and should be merged manually "
11760 "if required before the histedit operation "
11761 "is continued");
11763 } else
11764 error = histedit_complete(worktree, fileindex, tmp_branch,
11765 branch, repo);
11766 done:
11767 got_object_id_queue_free(&commits);
11768 histedit_free_list(&histedit_cmds);
11769 free(head_commit_id);
11770 free(base_commit_id);
11771 free(resume_commit_id);
11772 if (commit)
11773 got_object_commit_close(commit);
11774 if (branch)
11775 got_ref_close(branch);
11776 if (tmp_branch)
11777 got_ref_close(tmp_branch);
11778 if (worktree)
11779 got_worktree_close(worktree);
11780 if (repo) {
11781 const struct got_error *close_err = got_repo_close(repo);
11782 if (error == NULL)
11783 error = close_err;
11785 if (pack_fds) {
11786 const struct got_error *pack_err =
11787 got_repo_pack_fds_close(pack_fds);
11788 if (error == NULL)
11789 error = pack_err;
11791 return error;
11794 __dead static void
11795 usage_integrate(void)
11797 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11798 exit(1);
11801 static const struct got_error *
11802 cmd_integrate(int argc, char *argv[])
11804 const struct got_error *error = NULL;
11805 struct got_repository *repo = NULL;
11806 struct got_worktree *worktree = NULL;
11807 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11808 const char *branch_arg = NULL;
11809 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11810 struct got_fileindex *fileindex = NULL;
11811 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11812 int ch;
11813 struct got_update_progress_arg upa;
11814 int *pack_fds = NULL;
11816 while ((ch = getopt(argc, argv, "")) != -1) {
11817 switch (ch) {
11818 default:
11819 usage_integrate();
11820 /* NOTREACHED */
11824 argc -= optind;
11825 argv += optind;
11827 if (argc != 1)
11828 usage_integrate();
11829 branch_arg = argv[0];
11830 #ifndef PROFILE
11831 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11832 "unveil", NULL) == -1)
11833 err(1, "pledge");
11834 #endif
11835 cwd = getcwd(NULL, 0);
11836 if (cwd == NULL) {
11837 error = got_error_from_errno("getcwd");
11838 goto done;
11841 error = got_repo_pack_fds_open(&pack_fds);
11842 if (error != NULL)
11843 goto done;
11845 error = got_worktree_open(&worktree, cwd);
11846 if (error) {
11847 if (error->code == GOT_ERR_NOT_WORKTREE)
11848 error = wrap_not_worktree_error(error, "integrate",
11849 cwd);
11850 goto done;
11853 error = check_rebase_or_histedit_in_progress(worktree);
11854 if (error)
11855 goto done;
11857 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11858 NULL, pack_fds);
11859 if (error != NULL)
11860 goto done;
11862 error = apply_unveil(got_repo_get_path(repo), 0,
11863 got_worktree_get_root_path(worktree));
11864 if (error)
11865 goto done;
11867 error = check_merge_in_progress(worktree, repo);
11868 if (error)
11869 goto done;
11871 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11872 error = got_error_from_errno("asprintf");
11873 goto done;
11876 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11877 &base_branch_ref, worktree, refname, repo);
11878 if (error)
11879 goto done;
11881 refname = strdup(got_ref_get_name(branch_ref));
11882 if (refname == NULL) {
11883 error = got_error_from_errno("strdup");
11884 got_worktree_integrate_abort(worktree, fileindex, repo,
11885 branch_ref, base_branch_ref);
11886 goto done;
11888 base_refname = strdup(got_ref_get_name(base_branch_ref));
11889 if (base_refname == NULL) {
11890 error = got_error_from_errno("strdup");
11891 got_worktree_integrate_abort(worktree, fileindex, repo,
11892 branch_ref, base_branch_ref);
11893 goto done;
11896 error = got_ref_resolve(&commit_id, repo, branch_ref);
11897 if (error)
11898 goto done;
11900 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11901 if (error)
11902 goto done;
11904 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11905 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11906 "specified branch has already been integrated");
11907 got_worktree_integrate_abort(worktree, fileindex, repo,
11908 branch_ref, base_branch_ref);
11909 goto done;
11912 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11913 if (error) {
11914 if (error->code == GOT_ERR_ANCESTRY)
11915 error = got_error(GOT_ERR_REBASE_REQUIRED);
11916 got_worktree_integrate_abort(worktree, fileindex, repo,
11917 branch_ref, base_branch_ref);
11918 goto done;
11921 memset(&upa, 0, sizeof(upa));
11922 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11923 branch_ref, base_branch_ref, update_progress, &upa,
11924 check_cancelled, NULL);
11925 if (error)
11926 goto done;
11928 printf("Integrated %s into %s\n", refname, base_refname);
11929 print_update_progress_stats(&upa);
11930 done:
11931 if (repo) {
11932 const struct got_error *close_err = got_repo_close(repo);
11933 if (error == NULL)
11934 error = close_err;
11936 if (worktree)
11937 got_worktree_close(worktree);
11938 if (pack_fds) {
11939 const struct got_error *pack_err =
11940 got_repo_pack_fds_close(pack_fds);
11941 if (error == NULL)
11942 error = pack_err;
11944 free(cwd);
11945 free(base_commit_id);
11946 free(commit_id);
11947 free(refname);
11948 free(base_refname);
11949 return error;
11952 __dead static void
11953 usage_merge(void)
11955 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11956 getprogname());
11957 exit(1);
11960 static const struct got_error *
11961 cmd_merge(int argc, char *argv[])
11963 const struct got_error *error = NULL;
11964 struct got_worktree *worktree = NULL;
11965 struct got_repository *repo = NULL;
11966 struct got_fileindex *fileindex = NULL;
11967 char *cwd = NULL, *id_str = NULL, *author = NULL;
11968 struct got_reference *branch = NULL, *wt_branch = NULL;
11969 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11970 struct got_object_id *wt_branch_tip = NULL;
11971 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11972 int interrupt_merge = 0;
11973 struct got_update_progress_arg upa;
11974 struct got_object_id *merge_commit_id = NULL;
11975 char *branch_name = NULL;
11976 int *pack_fds = NULL;
11978 memset(&upa, 0, sizeof(upa));
11980 while ((ch = getopt(argc, argv, "acn")) != -1) {
11981 switch (ch) {
11982 case 'a':
11983 abort_merge = 1;
11984 break;
11985 case 'c':
11986 continue_merge = 1;
11987 break;
11988 case 'n':
11989 interrupt_merge = 1;
11990 break;
11991 default:
11992 usage_rebase();
11993 /* NOTREACHED */
11997 argc -= optind;
11998 argv += optind;
12000 #ifndef PROFILE
12001 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12002 "unveil", NULL) == -1)
12003 err(1, "pledge");
12004 #endif
12006 if (abort_merge && continue_merge)
12007 option_conflict('a', 'c');
12008 if (abort_merge || continue_merge) {
12009 if (argc != 0)
12010 usage_merge();
12011 } else if (argc != 1)
12012 usage_merge();
12014 cwd = getcwd(NULL, 0);
12015 if (cwd == NULL) {
12016 error = got_error_from_errno("getcwd");
12017 goto done;
12020 error = got_repo_pack_fds_open(&pack_fds);
12021 if (error != NULL)
12022 goto done;
12024 error = got_worktree_open(&worktree, cwd);
12025 if (error) {
12026 if (error->code == GOT_ERR_NOT_WORKTREE)
12027 error = wrap_not_worktree_error(error,
12028 "merge", cwd);
12029 goto done;
12032 error = got_repo_open(&repo,
12033 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12034 pack_fds);
12035 if (error != NULL)
12036 goto done;
12038 error = apply_unveil(got_repo_get_path(repo), 0,
12039 worktree ? got_worktree_get_root_path(worktree) : NULL);
12040 if (error)
12041 goto done;
12043 error = check_rebase_or_histedit_in_progress(worktree);
12044 if (error)
12045 goto done;
12047 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12048 repo);
12049 if (error)
12050 goto done;
12052 if (abort_merge) {
12053 if (!merge_in_progress) {
12054 error = got_error(GOT_ERR_NOT_MERGING);
12055 goto done;
12057 error = got_worktree_merge_continue(&branch_name,
12058 &branch_tip, &fileindex, worktree, repo);
12059 if (error)
12060 goto done;
12061 error = got_worktree_merge_abort(worktree, fileindex, repo,
12062 abort_progress, &upa);
12063 if (error)
12064 goto done;
12065 printf("Merge of %s aborted\n", branch_name);
12066 goto done; /* nothing else to do */
12069 error = get_author(&author, repo, worktree);
12070 if (error)
12071 goto done;
12073 if (continue_merge) {
12074 if (!merge_in_progress) {
12075 error = got_error(GOT_ERR_NOT_MERGING);
12076 goto done;
12078 error = got_worktree_merge_continue(&branch_name,
12079 &branch_tip, &fileindex, worktree, repo);
12080 if (error)
12081 goto done;
12082 } else {
12083 error = got_ref_open(&branch, repo, argv[0], 0);
12084 if (error != NULL)
12085 goto done;
12086 branch_name = strdup(got_ref_get_name(branch));
12087 if (branch_name == NULL) {
12088 error = got_error_from_errno("strdup");
12089 goto done;
12091 error = got_ref_resolve(&branch_tip, repo, branch);
12092 if (error)
12093 goto done;
12096 error = got_ref_open(&wt_branch, repo,
12097 got_worktree_get_head_ref_name(worktree), 0);
12098 if (error)
12099 goto done;
12100 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12101 if (error)
12102 goto done;
12103 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12104 wt_branch_tip, branch_tip, 0, repo,
12105 check_cancelled, NULL);
12106 if (error && error->code != GOT_ERR_ANCESTRY)
12107 goto done;
12109 if (!continue_merge) {
12110 error = check_path_prefix(wt_branch_tip, branch_tip,
12111 got_worktree_get_path_prefix(worktree),
12112 GOT_ERR_MERGE_PATH, repo);
12113 if (error)
12114 goto done;
12115 if (yca_id) {
12116 error = check_same_branch(wt_branch_tip, branch,
12117 yca_id, repo);
12118 if (error) {
12119 if (error->code != GOT_ERR_ANCESTRY)
12120 goto done;
12121 error = NULL;
12122 } else {
12123 static char msg[512];
12124 snprintf(msg, sizeof(msg),
12125 "cannot create a merge commit because "
12126 "%s is based on %s; %s can be integrated "
12127 "with 'got integrate' instead", branch_name,
12128 got_worktree_get_head_ref_name(worktree),
12129 branch_name);
12130 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12131 goto done;
12134 error = got_worktree_merge_prepare(&fileindex, worktree,
12135 branch, repo);
12136 if (error)
12137 goto done;
12139 error = got_worktree_merge_branch(worktree, fileindex,
12140 yca_id, branch_tip, repo, update_progress, &upa,
12141 check_cancelled, NULL);
12142 if (error)
12143 goto done;
12144 print_merge_progress_stats(&upa);
12145 if (!upa.did_something) {
12146 error = got_worktree_merge_abort(worktree, fileindex,
12147 repo, abort_progress, &upa);
12148 if (error)
12149 goto done;
12150 printf("Already up-to-date\n");
12151 goto done;
12155 if (interrupt_merge) {
12156 error = got_worktree_merge_postpone(worktree, fileindex);
12157 if (error)
12158 goto done;
12159 printf("Merge of %s interrupted on request\n", branch_name);
12160 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12161 upa.not_deleted > 0 || upa.unversioned > 0) {
12162 error = got_worktree_merge_postpone(worktree, fileindex);
12163 if (error)
12164 goto done;
12165 if (upa.conflicts > 0 && upa.missing == 0 &&
12166 upa.not_deleted == 0 && upa.unversioned == 0) {
12167 error = got_error_msg(GOT_ERR_CONFLICTS,
12168 "conflicts must be resolved before merging "
12169 "can continue");
12170 } else if (upa.conflicts > 0) {
12171 error = got_error_msg(GOT_ERR_CONFLICTS,
12172 "conflicts must be resolved before merging "
12173 "can continue; changes destined for some "
12174 "files were not yet merged and "
12175 "should be merged manually if required before the "
12176 "merge operation is continued");
12177 } else {
12178 error = got_error_msg(GOT_ERR_CONFLICTS,
12179 "changes destined for some "
12180 "files were not yet merged and should be "
12181 "merged manually if required before the "
12182 "merge operation is continued");
12184 goto done;
12185 } else {
12186 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12187 fileindex, author, NULL, 1, branch_tip, branch_name,
12188 repo, continue_merge ? print_status : NULL, NULL);
12189 if (error)
12190 goto done;
12191 error = got_worktree_merge_complete(worktree, fileindex, repo);
12192 if (error)
12193 goto done;
12194 error = got_object_id_str(&id_str, merge_commit_id);
12195 if (error)
12196 goto done;
12197 printf("Merged %s into %s: %s\n", branch_name,
12198 got_worktree_get_head_ref_name(worktree),
12199 id_str);
12202 done:
12203 free(id_str);
12204 free(merge_commit_id);
12205 free(author);
12206 free(branch_tip);
12207 free(branch_name);
12208 free(yca_id);
12209 if (branch)
12210 got_ref_close(branch);
12211 if (wt_branch)
12212 got_ref_close(wt_branch);
12213 if (worktree)
12214 got_worktree_close(worktree);
12215 if (repo) {
12216 const struct got_error *close_err = got_repo_close(repo);
12217 if (error == NULL)
12218 error = close_err;
12220 if (pack_fds) {
12221 const struct got_error *pack_err =
12222 got_repo_pack_fds_close(pack_fds);
12223 if (error == NULL)
12224 error = pack_err;
12226 return error;
12229 __dead static void
12230 usage_stage(void)
12232 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12233 "[-S] [file-path ...]\n",
12234 getprogname());
12235 exit(1);
12238 static const struct got_error *
12239 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12240 const char *path, struct got_object_id *blob_id,
12241 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12242 int dirfd, const char *de_name)
12244 const struct got_error *err = NULL;
12245 char *id_str = NULL;
12247 if (staged_status != GOT_STATUS_ADD &&
12248 staged_status != GOT_STATUS_MODIFY &&
12249 staged_status != GOT_STATUS_DELETE)
12250 return NULL;
12252 if (staged_status == GOT_STATUS_ADD ||
12253 staged_status == GOT_STATUS_MODIFY)
12254 err = got_object_id_str(&id_str, staged_blob_id);
12255 else
12256 err = got_object_id_str(&id_str, blob_id);
12257 if (err)
12258 return err;
12260 printf("%s %c %s\n", id_str, staged_status, path);
12261 free(id_str);
12262 return NULL;
12265 static const struct got_error *
12266 cmd_stage(int argc, char *argv[])
12268 const struct got_error *error = NULL;
12269 struct got_repository *repo = NULL;
12270 struct got_worktree *worktree = NULL;
12271 char *cwd = NULL;
12272 struct got_pathlist_head paths;
12273 struct got_pathlist_entry *pe;
12274 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12275 FILE *patch_script_file = NULL;
12276 const char *patch_script_path = NULL;
12277 struct choose_patch_arg cpa;
12278 int *pack_fds = NULL;
12280 TAILQ_INIT(&paths);
12282 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12283 switch (ch) {
12284 case 'l':
12285 list_stage = 1;
12286 break;
12287 case 'p':
12288 pflag = 1;
12289 break;
12290 case 'F':
12291 patch_script_path = optarg;
12292 break;
12293 case 'S':
12294 allow_bad_symlinks = 1;
12295 break;
12296 default:
12297 usage_stage();
12298 /* NOTREACHED */
12302 argc -= optind;
12303 argv += optind;
12305 #ifndef PROFILE
12306 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12307 "unveil", NULL) == -1)
12308 err(1, "pledge");
12309 #endif
12310 if (list_stage && (pflag || patch_script_path))
12311 errx(1, "-l option cannot be used with other options");
12312 if (patch_script_path && !pflag)
12313 errx(1, "-F option can only be used together with -p option");
12315 cwd = getcwd(NULL, 0);
12316 if (cwd == NULL) {
12317 error = got_error_from_errno("getcwd");
12318 goto done;
12321 error = got_repo_pack_fds_open(&pack_fds);
12322 if (error != NULL)
12323 goto done;
12325 error = got_worktree_open(&worktree, cwd);
12326 if (error) {
12327 if (error->code == GOT_ERR_NOT_WORKTREE)
12328 error = wrap_not_worktree_error(error, "stage", cwd);
12329 goto done;
12332 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12333 NULL, pack_fds);
12334 if (error != NULL)
12335 goto done;
12337 if (patch_script_path) {
12338 patch_script_file = fopen(patch_script_path, "re");
12339 if (patch_script_file == NULL) {
12340 error = got_error_from_errno2("fopen",
12341 patch_script_path);
12342 goto done;
12345 error = apply_unveil(got_repo_get_path(repo), 0,
12346 got_worktree_get_root_path(worktree));
12347 if (error)
12348 goto done;
12350 error = check_merge_in_progress(worktree, repo);
12351 if (error)
12352 goto done;
12354 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12355 if (error)
12356 goto done;
12358 if (list_stage)
12359 error = got_worktree_status(worktree, &paths, repo, 0,
12360 print_stage, NULL, check_cancelled, NULL);
12361 else {
12362 cpa.patch_script_file = patch_script_file;
12363 cpa.action = "stage";
12364 error = got_worktree_stage(worktree, &paths,
12365 pflag ? NULL : print_status, NULL,
12366 pflag ? choose_patch : NULL, &cpa,
12367 allow_bad_symlinks, repo);
12369 done:
12370 if (patch_script_file && fclose(patch_script_file) == EOF &&
12371 error == NULL)
12372 error = got_error_from_errno2("fclose", patch_script_path);
12373 if (repo) {
12374 const struct got_error *close_err = got_repo_close(repo);
12375 if (error == NULL)
12376 error = close_err;
12378 if (worktree)
12379 got_worktree_close(worktree);
12380 if (pack_fds) {
12381 const struct got_error *pack_err =
12382 got_repo_pack_fds_close(pack_fds);
12383 if (error == NULL)
12384 error = pack_err;
12386 TAILQ_FOREACH(pe, &paths, entry)
12387 free((char *)pe->path);
12388 got_pathlist_free(&paths);
12389 free(cwd);
12390 return error;
12393 __dead static void
12394 usage_unstage(void)
12396 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12397 "[file-path ...]\n",
12398 getprogname());
12399 exit(1);
12403 static const struct got_error *
12404 cmd_unstage(int argc, char *argv[])
12406 const struct got_error *error = NULL;
12407 struct got_repository *repo = NULL;
12408 struct got_worktree *worktree = NULL;
12409 char *cwd = NULL;
12410 struct got_pathlist_head paths;
12411 struct got_pathlist_entry *pe;
12412 int ch, pflag = 0;
12413 struct got_update_progress_arg upa;
12414 FILE *patch_script_file = NULL;
12415 const char *patch_script_path = NULL;
12416 struct choose_patch_arg cpa;
12417 int *pack_fds = NULL;
12419 TAILQ_INIT(&paths);
12421 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12422 switch (ch) {
12423 case 'p':
12424 pflag = 1;
12425 break;
12426 case 'F':
12427 patch_script_path = optarg;
12428 break;
12429 default:
12430 usage_unstage();
12431 /* NOTREACHED */
12435 argc -= optind;
12436 argv += optind;
12438 #ifndef PROFILE
12439 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12440 "unveil", NULL) == -1)
12441 err(1, "pledge");
12442 #endif
12443 if (patch_script_path && !pflag)
12444 errx(1, "-F option can only be used together with -p option");
12446 cwd = getcwd(NULL, 0);
12447 if (cwd == NULL) {
12448 error = got_error_from_errno("getcwd");
12449 goto done;
12452 error = got_repo_pack_fds_open(&pack_fds);
12453 if (error != NULL)
12454 goto done;
12456 error = got_worktree_open(&worktree, cwd);
12457 if (error) {
12458 if (error->code == GOT_ERR_NOT_WORKTREE)
12459 error = wrap_not_worktree_error(error, "unstage", cwd);
12460 goto done;
12463 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12464 NULL, pack_fds);
12465 if (error != NULL)
12466 goto done;
12468 if (patch_script_path) {
12469 patch_script_file = fopen(patch_script_path, "re");
12470 if (patch_script_file == NULL) {
12471 error = got_error_from_errno2("fopen",
12472 patch_script_path);
12473 goto done;
12477 error = apply_unveil(got_repo_get_path(repo), 0,
12478 got_worktree_get_root_path(worktree));
12479 if (error)
12480 goto done;
12482 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12483 if (error)
12484 goto done;
12486 cpa.patch_script_file = patch_script_file;
12487 cpa.action = "unstage";
12488 memset(&upa, 0, sizeof(upa));
12489 error = got_worktree_unstage(worktree, &paths, update_progress,
12490 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12491 if (!error)
12492 print_merge_progress_stats(&upa);
12493 done:
12494 if (patch_script_file && fclose(patch_script_file) == EOF &&
12495 error == NULL)
12496 error = got_error_from_errno2("fclose", patch_script_path);
12497 if (repo) {
12498 const struct got_error *close_err = got_repo_close(repo);
12499 if (error == NULL)
12500 error = close_err;
12502 if (worktree)
12503 got_worktree_close(worktree);
12504 if (pack_fds) {
12505 const struct got_error *pack_err =
12506 got_repo_pack_fds_close(pack_fds);
12507 if (error == NULL)
12508 error = pack_err;
12510 TAILQ_FOREACH(pe, &paths, entry)
12511 free((char *)pe->path);
12512 got_pathlist_free(&paths);
12513 free(cwd);
12514 return error;
12517 __dead static void
12518 usage_cat(void)
12520 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12521 "arg1 [arg2 ...]\n", getprogname());
12522 exit(1);
12525 static const struct got_error *
12526 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12528 const struct got_error *err;
12529 struct got_blob_object *blob;
12530 int fd = -1;
12532 fd = got_opentempfd();
12533 if (fd == -1)
12534 return got_error_from_errno("got_opentempfd");
12536 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12537 if (err)
12538 goto done;
12540 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12541 done:
12542 if (fd != -1 && close(fd) == -1 && err == NULL)
12543 err = got_error_from_errno("close");
12544 if (blob)
12545 got_object_blob_close(blob);
12546 return err;
12549 static const struct got_error *
12550 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12552 const struct got_error *err;
12553 struct got_tree_object *tree;
12554 int nentries, i;
12556 err = got_object_open_as_tree(&tree, repo, id);
12557 if (err)
12558 return err;
12560 nentries = got_object_tree_get_nentries(tree);
12561 for (i = 0; i < nentries; i++) {
12562 struct got_tree_entry *te;
12563 char *id_str;
12564 if (sigint_received || sigpipe_received)
12565 break;
12566 te = got_object_tree_get_entry(tree, i);
12567 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12568 if (err)
12569 break;
12570 fprintf(outfile, "%s %.7o %s\n", id_str,
12571 got_tree_entry_get_mode(te),
12572 got_tree_entry_get_name(te));
12573 free(id_str);
12576 got_object_tree_close(tree);
12577 return err;
12580 static const struct got_error *
12581 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12583 const struct got_error *err;
12584 struct got_commit_object *commit;
12585 const struct got_object_id_queue *parent_ids;
12586 struct got_object_qid *pid;
12587 char *id_str = NULL;
12588 const char *logmsg = NULL;
12589 char gmtoff[6];
12591 err = got_object_open_as_commit(&commit, repo, id);
12592 if (err)
12593 return err;
12595 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12596 if (err)
12597 goto done;
12599 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12600 parent_ids = got_object_commit_get_parent_ids(commit);
12601 fprintf(outfile, "numparents %d\n",
12602 got_object_commit_get_nparents(commit));
12603 STAILQ_FOREACH(pid, parent_ids, entry) {
12604 char *pid_str;
12605 err = got_object_id_str(&pid_str, &pid->id);
12606 if (err)
12607 goto done;
12608 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12609 free(pid_str);
12611 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12612 got_object_commit_get_author_gmtoff(commit));
12613 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12614 got_object_commit_get_author(commit),
12615 (long long)got_object_commit_get_author_time(commit),
12616 gmtoff);
12618 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12619 got_object_commit_get_committer_gmtoff(commit));
12620 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12621 got_object_commit_get_author(commit),
12622 (long long)got_object_commit_get_committer_time(commit),
12623 gmtoff);
12625 logmsg = got_object_commit_get_logmsg_raw(commit);
12626 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12627 fprintf(outfile, "%s", logmsg);
12628 done:
12629 free(id_str);
12630 got_object_commit_close(commit);
12631 return err;
12634 static const struct got_error *
12635 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12637 const struct got_error *err;
12638 struct got_tag_object *tag;
12639 char *id_str = NULL;
12640 const char *tagmsg = NULL;
12641 char gmtoff[6];
12643 err = got_object_open_as_tag(&tag, repo, id);
12644 if (err)
12645 return err;
12647 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12648 if (err)
12649 goto done;
12651 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12653 switch (got_object_tag_get_object_type(tag)) {
12654 case GOT_OBJ_TYPE_BLOB:
12655 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12656 GOT_OBJ_LABEL_BLOB);
12657 break;
12658 case GOT_OBJ_TYPE_TREE:
12659 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12660 GOT_OBJ_LABEL_TREE);
12661 break;
12662 case GOT_OBJ_TYPE_COMMIT:
12663 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12664 GOT_OBJ_LABEL_COMMIT);
12665 break;
12666 case GOT_OBJ_TYPE_TAG:
12667 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12668 GOT_OBJ_LABEL_TAG);
12669 break;
12670 default:
12671 break;
12674 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12675 got_object_tag_get_name(tag));
12677 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12678 got_object_tag_get_tagger_gmtoff(tag));
12679 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12680 got_object_tag_get_tagger(tag),
12681 (long long)got_object_tag_get_tagger_time(tag),
12682 gmtoff);
12684 tagmsg = got_object_tag_get_message(tag);
12685 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12686 fprintf(outfile, "%s", tagmsg);
12687 done:
12688 free(id_str);
12689 got_object_tag_close(tag);
12690 return err;
12693 static const struct got_error *
12694 cmd_cat(int argc, char *argv[])
12696 const struct got_error *error;
12697 struct got_repository *repo = NULL;
12698 struct got_worktree *worktree = NULL;
12699 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12700 const char *commit_id_str = NULL;
12701 struct got_object_id *id = NULL, *commit_id = NULL;
12702 struct got_commit_object *commit = NULL;
12703 int ch, obj_type, i, force_path = 0;
12704 struct got_reflist_head refs;
12705 int *pack_fds = NULL;
12707 TAILQ_INIT(&refs);
12709 #ifndef PROFILE
12710 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12711 NULL) == -1)
12712 err(1, "pledge");
12713 #endif
12715 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12716 switch (ch) {
12717 case 'c':
12718 commit_id_str = optarg;
12719 break;
12720 case 'r':
12721 repo_path = realpath(optarg, NULL);
12722 if (repo_path == NULL)
12723 return got_error_from_errno2("realpath",
12724 optarg);
12725 got_path_strip_trailing_slashes(repo_path);
12726 break;
12727 case 'P':
12728 force_path = 1;
12729 break;
12730 default:
12731 usage_cat();
12732 /* NOTREACHED */
12736 argc -= optind;
12737 argv += optind;
12739 cwd = getcwd(NULL, 0);
12740 if (cwd == NULL) {
12741 error = got_error_from_errno("getcwd");
12742 goto done;
12745 error = got_repo_pack_fds_open(&pack_fds);
12746 if (error != NULL)
12747 goto done;
12749 if (repo_path == NULL) {
12750 error = got_worktree_open(&worktree, cwd);
12751 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12752 goto done;
12753 if (worktree) {
12754 repo_path = strdup(
12755 got_worktree_get_repo_path(worktree));
12756 if (repo_path == NULL) {
12757 error = got_error_from_errno("strdup");
12758 goto done;
12761 /* Release work tree lock. */
12762 got_worktree_close(worktree);
12763 worktree = NULL;
12767 if (repo_path == NULL) {
12768 repo_path = strdup(cwd);
12769 if (repo_path == NULL)
12770 return got_error_from_errno("strdup");
12773 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12774 free(repo_path);
12775 if (error != NULL)
12776 goto done;
12778 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12779 if (error)
12780 goto done;
12782 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12783 if (error)
12784 goto done;
12786 if (commit_id_str == NULL)
12787 commit_id_str = GOT_REF_HEAD;
12788 error = got_repo_match_object_id(&commit_id, NULL,
12789 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12790 if (error)
12791 goto done;
12793 error = got_object_open_as_commit(&commit, repo, commit_id);
12794 if (error)
12795 goto done;
12797 for (i = 0; i < argc; i++) {
12798 if (force_path) {
12799 error = got_object_id_by_path(&id, repo, commit,
12800 argv[i]);
12801 if (error)
12802 break;
12803 } else {
12804 error = got_repo_match_object_id(&id, &label, argv[i],
12805 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12806 repo);
12807 if (error) {
12808 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12809 error->code != GOT_ERR_NOT_REF)
12810 break;
12811 error = got_object_id_by_path(&id, repo,
12812 commit, argv[i]);
12813 if (error)
12814 break;
12818 error = got_object_get_type(&obj_type, repo, id);
12819 if (error)
12820 break;
12822 switch (obj_type) {
12823 case GOT_OBJ_TYPE_BLOB:
12824 error = cat_blob(id, repo, stdout);
12825 break;
12826 case GOT_OBJ_TYPE_TREE:
12827 error = cat_tree(id, repo, stdout);
12828 break;
12829 case GOT_OBJ_TYPE_COMMIT:
12830 error = cat_commit(id, repo, stdout);
12831 break;
12832 case GOT_OBJ_TYPE_TAG:
12833 error = cat_tag(id, repo, stdout);
12834 break;
12835 default:
12836 error = got_error(GOT_ERR_OBJ_TYPE);
12837 break;
12839 if (error)
12840 break;
12841 free(label);
12842 label = NULL;
12843 free(id);
12844 id = NULL;
12846 done:
12847 free(label);
12848 free(id);
12849 free(commit_id);
12850 if (commit)
12851 got_object_commit_close(commit);
12852 if (worktree)
12853 got_worktree_close(worktree);
12854 if (repo) {
12855 const struct got_error *close_err = got_repo_close(repo);
12856 if (error == NULL)
12857 error = close_err;
12859 if (pack_fds) {
12860 const struct got_error *pack_err =
12861 got_repo_pack_fds_close(pack_fds);
12862 if (error == NULL)
12863 error = pack_err;
12866 got_ref_list_free(&refs);
12867 return error;
12870 __dead static void
12871 usage_info(void)
12873 fprintf(stderr, "usage: %s info [path ...]\n",
12874 getprogname());
12875 exit(1);
12878 static const struct got_error *
12879 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12880 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12881 struct got_object_id *commit_id)
12883 const struct got_error *err = NULL;
12884 char *id_str = NULL;
12885 char datebuf[128];
12886 struct tm mytm, *tm;
12887 struct got_pathlist_head *paths = arg;
12888 struct got_pathlist_entry *pe;
12891 * Clear error indication from any of the path arguments which
12892 * would cause this file index entry to be displayed.
12894 TAILQ_FOREACH(pe, paths, entry) {
12895 if (got_path_cmp(path, pe->path, strlen(path),
12896 pe->path_len) == 0 ||
12897 got_path_is_child(path, pe->path, pe->path_len))
12898 pe->data = NULL; /* no error */
12901 printf(GOT_COMMIT_SEP_STR);
12902 if (S_ISLNK(mode))
12903 printf("symlink: %s\n", path);
12904 else if (S_ISREG(mode)) {
12905 printf("file: %s\n", path);
12906 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12907 } else if (S_ISDIR(mode))
12908 printf("directory: %s\n", path);
12909 else
12910 printf("something: %s\n", path);
12912 tm = localtime_r(&mtime, &mytm);
12913 if (tm == NULL)
12914 return NULL;
12915 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12916 return got_error(GOT_ERR_NO_SPACE);
12917 printf("timestamp: %s\n", datebuf);
12919 if (blob_id) {
12920 err = got_object_id_str(&id_str, blob_id);
12921 if (err)
12922 return err;
12923 printf("based on blob: %s\n", id_str);
12924 free(id_str);
12927 if (staged_blob_id) {
12928 err = got_object_id_str(&id_str, staged_blob_id);
12929 if (err)
12930 return err;
12931 printf("based on staged blob: %s\n", id_str);
12932 free(id_str);
12935 if (commit_id) {
12936 err = got_object_id_str(&id_str, commit_id);
12937 if (err)
12938 return err;
12939 printf("based on commit: %s\n", id_str);
12940 free(id_str);
12943 return NULL;
12946 static const struct got_error *
12947 cmd_info(int argc, char *argv[])
12949 const struct got_error *error = NULL;
12950 struct got_worktree *worktree = NULL;
12951 char *cwd = NULL, *id_str = NULL;
12952 struct got_pathlist_head paths;
12953 struct got_pathlist_entry *pe;
12954 char *uuidstr = NULL;
12955 int ch, show_files = 0;
12956 int *pack_fds = NULL;
12958 TAILQ_INIT(&paths);
12960 while ((ch = getopt(argc, argv, "")) != -1) {
12961 switch (ch) {
12962 default:
12963 usage_info();
12964 /* NOTREACHED */
12968 argc -= optind;
12969 argv += optind;
12971 #ifndef PROFILE
12972 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12973 NULL) == -1)
12974 err(1, "pledge");
12975 #endif
12976 cwd = getcwd(NULL, 0);
12977 if (cwd == NULL) {
12978 error = got_error_from_errno("getcwd");
12979 goto done;
12982 error = got_repo_pack_fds_open(&pack_fds);
12983 if (error != NULL)
12984 goto done;
12986 error = got_worktree_open(&worktree, cwd);
12987 if (error) {
12988 if (error->code == GOT_ERR_NOT_WORKTREE)
12989 error = wrap_not_worktree_error(error, "info", cwd);
12990 goto done;
12993 #ifndef PROFILE
12994 /* Remove "cpath" promise. */
12995 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12996 NULL) == -1)
12997 err(1, "pledge");
12998 #endif
12999 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13000 if (error)
13001 goto done;
13003 if (argc >= 1) {
13004 error = get_worktree_paths_from_argv(&paths, argc, argv,
13005 worktree);
13006 if (error)
13007 goto done;
13008 show_files = 1;
13011 error = got_object_id_str(&id_str,
13012 got_worktree_get_base_commit_id(worktree));
13013 if (error)
13014 goto done;
13016 error = got_worktree_get_uuid(&uuidstr, worktree);
13017 if (error)
13018 goto done;
13020 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13021 printf("work tree base commit: %s\n", id_str);
13022 printf("work tree path prefix: %s\n",
13023 got_worktree_get_path_prefix(worktree));
13024 printf("work tree branch reference: %s\n",
13025 got_worktree_get_head_ref_name(worktree));
13026 printf("work tree UUID: %s\n", uuidstr);
13027 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13029 if (show_files) {
13030 struct got_pathlist_entry *pe;
13031 TAILQ_FOREACH(pe, &paths, entry) {
13032 if (pe->path_len == 0)
13033 continue;
13035 * Assume this path will fail. This will be corrected
13036 * in print_path_info() in case the path does suceeed.
13038 pe->data = (void *)got_error_path(pe->path,
13039 GOT_ERR_BAD_PATH);
13041 error = got_worktree_path_info(worktree, &paths,
13042 print_path_info, &paths, check_cancelled, NULL);
13043 if (error)
13044 goto done;
13045 TAILQ_FOREACH(pe, &paths, entry) {
13046 if (pe->data != NULL) {
13047 error = pe->data; /* bad path */
13048 break;
13052 done:
13053 if (pack_fds) {
13054 const struct got_error *pack_err =
13055 got_repo_pack_fds_close(pack_fds);
13056 if (error == NULL)
13057 error = pack_err;
13059 TAILQ_FOREACH(pe, &paths, entry)
13060 free((char *)pe->path);
13061 got_pathlist_free(&paths);
13062 free(cwd);
13063 free(id_str);
13064 free(uuidstr);
13065 return error;