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/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
61 #include "got_sigs.h"
62 #include "got_date.h"
64 #ifndef nitems
65 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
66 #endif
68 static volatile sig_atomic_t sigint_received;
69 static volatile sig_atomic_t sigpipe_received;
71 static void
72 catch_sigint(int signo)
73 {
74 sigint_received = 1;
75 }
77 static void
78 catch_sigpipe(int signo)
79 {
80 sigpipe_received = 1;
81 }
84 struct got_cmd {
85 const char *cmd_name;
86 const struct got_error *(*cmd_main)(int, char *[]);
87 void (*cmd_usage)(void);
88 const char *cmd_alias;
89 };
91 __dead static void usage(int, int);
92 __dead static void usage_init(void);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_init(int, char *[]);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "init", cmd_init, usage_init, "" },
156 { "import", cmd_import, usage_import, "im" },
157 { "clone", cmd_clone, usage_clone, "cl" },
158 { "fetch", cmd_fetch, usage_fetch, "fe" },
159 { "checkout", cmd_checkout, usage_checkout, "co" },
160 { "update", cmd_update, usage_update, "up" },
161 { "log", cmd_log, usage_log, "" },
162 { "diff", cmd_diff, usage_diff, "di" },
163 { "blame", cmd_blame, usage_blame, "bl" },
164 { "tree", cmd_tree, usage_tree, "tr" },
165 { "status", cmd_status, usage_status, "st" },
166 { "ref", cmd_ref, usage_ref, "" },
167 { "branch", cmd_branch, usage_branch, "br" },
168 { "tag", cmd_tag, usage_tag, "" },
169 { "add", cmd_add, usage_add, "" },
170 { "remove", cmd_remove, usage_remove, "rm" },
171 { "patch", cmd_patch, usage_patch, "pa" },
172 { "revert", cmd_revert, usage_revert, "rv" },
173 { "commit", cmd_commit, usage_commit, "ci" },
174 { "send", cmd_send, usage_send, "se" },
175 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
176 { "backout", cmd_backout, usage_backout, "bo" },
177 { "rebase", cmd_rebase, usage_rebase, "rb" },
178 { "histedit", cmd_histedit, usage_histedit, "he" },
179 { "integrate", cmd_integrate, usage_integrate,"ig" },
180 { "merge", cmd_merge, usage_merge, "mg" },
181 { "stage", cmd_stage, usage_stage, "sg" },
182 { "unstage", cmd_unstage, usage_unstage, "ug" },
183 { "cat", cmd_cat, usage_cat, "" },
184 { "info", cmd_info, usage_info, "" },
185 };
187 static void
188 list_commands(FILE *fp)
190 size_t i;
192 fprintf(fp, "commands:");
193 for (i = 0; i < nitems(got_commands); i++) {
194 const struct got_cmd *cmd = &got_commands[i];
195 fprintf(fp, " %s", cmd->cmd_name);
197 fputc('\n', fp);
200 __dead static void
201 option_conflict(char a, char b)
203 errx(1, "-%c and -%c options are mutually exclusive", a, b);
206 int
207 main(int argc, char *argv[])
209 const struct got_cmd *cmd;
210 size_t i;
211 int ch;
212 int hflag = 0, Vflag = 0;
213 static const struct option longopts[] = {
214 { "version", no_argument, NULL, 'V' },
215 { NULL, 0, NULL, 0 }
216 };
218 setlocale(LC_CTYPE, "");
220 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
221 switch (ch) {
222 case 'h':
223 hflag = 1;
224 break;
225 case 'V':
226 Vflag = 1;
227 break;
228 default:
229 usage(hflag, 1);
230 /* NOTREACHED */
234 argc -= optind;
235 argv += optind;
236 optind = 1;
237 optreset = 1;
239 if (Vflag) {
240 got_version_print_str();
241 return 0;
244 if (argc <= 0)
245 usage(hflag, hflag ? 0 : 1);
247 signal(SIGINT, catch_sigint);
248 signal(SIGPIPE, catch_sigpipe);
250 for (i = 0; i < nitems(got_commands); i++) {
251 const struct got_error *error;
253 cmd = &got_commands[i];
255 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
256 strcmp(cmd->cmd_alias, argv[0]) != 0)
257 continue;
259 if (hflag)
260 cmd->cmd_usage();
262 error = cmd->cmd_main(argc, argv);
263 if (error && error->code != GOT_ERR_CANCELLED &&
264 error->code != GOT_ERR_PRIVSEP_EXIT &&
265 !(sigpipe_received &&
266 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
267 !(sigint_received &&
268 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/bin/ed");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_init(void)
352 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
353 exit(1);
356 static const struct got_error *
357 cmd_init(int argc, char *argv[])
359 const struct got_error *error = NULL;
360 char *repo_path = NULL;
361 int ch;
363 while ((ch = getopt(argc, argv, "")) != -1) {
364 switch (ch) {
365 default:
366 usage_init();
367 /* NOTREACHED */
371 argc -= optind;
372 argv += optind;
374 #ifndef PROFILE
375 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
376 err(1, "pledge");
377 #endif
378 if (argc != 1)
379 usage_init();
381 repo_path = strdup(argv[0]);
382 if (repo_path == NULL)
383 return got_error_from_errno("strdup");
385 got_path_strip_trailing_slashes(repo_path);
387 error = got_path_mkdir(repo_path);
388 if (error &&
389 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
390 goto done;
392 error = apply_unveil(repo_path, 0, NULL);
393 if (error)
394 goto done;
396 error = got_repo_init(repo_path);
397 done:
398 free(repo_path);
399 return error;
402 __dead static void
403 usage_import(void)
405 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
406 "[-r repository-path] [-I pattern] path\n", getprogname());
407 exit(1);
410 static int
411 spawn_editor(const char *editor, const char *file)
413 pid_t pid;
414 sig_t sighup, sigint, sigquit;
415 int st = -1;
417 sighup = signal(SIGHUP, SIG_IGN);
418 sigint = signal(SIGINT, SIG_IGN);
419 sigquit = signal(SIGQUIT, SIG_IGN);
421 switch (pid = fork()) {
422 case -1:
423 goto doneediting;
424 case 0:
425 execl(editor, editor, file, (char *)NULL);
426 _exit(127);
429 while (waitpid(pid, &st, 0) == -1)
430 if (errno != EINTR)
431 break;
433 doneediting:
434 (void)signal(SIGHUP, sighup);
435 (void)signal(SIGINT, sigint);
436 (void)signal(SIGQUIT, sigquit);
438 if (!WIFEXITED(st)) {
439 errno = EINTR;
440 return -1;
443 return WEXITSTATUS(st);
446 static const struct got_error *
447 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
448 const char *initial_content, size_t initial_content_len,
449 int require_modification)
451 const struct got_error *err = NULL;
452 char *line = NULL;
453 size_t linesize = 0;
454 ssize_t linelen;
455 struct stat st, st2;
456 FILE *fp = NULL;
457 size_t len, logmsg_len;
458 char *initial_content_stripped = NULL, *buf = NULL, *s;
460 *logmsg = NULL;
462 if (stat(logmsg_path, &st) == -1)
463 return got_error_from_errno2("stat", logmsg_path);
465 if (spawn_editor(editor, logmsg_path) == -1)
466 return got_error_from_errno("failed spawning editor");
468 if (stat(logmsg_path, &st2) == -1)
469 return got_error_from_errno("stat");
471 if (require_modification &&
472 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
473 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
474 "no changes made to commit message, aborting");
476 /*
477 * Set up a stripped version of the initial content without comments
478 * and blank lines. We need this in order to check if the message
479 * has in fact been edited.
480 */
481 initial_content_stripped = malloc(initial_content_len + 1);
482 if (initial_content_stripped == NULL)
483 return got_error_from_errno("malloc");
484 initial_content_stripped[0] = '\0';
486 buf = strdup(initial_content);
487 if (buf == NULL) {
488 err = got_error_from_errno("strdup");
489 goto done;
491 s = buf;
492 len = 0;
493 while ((line = strsep(&s, "\n")) != NULL) {
494 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
495 continue; /* remove comments and leading empty lines */
496 len = strlcat(initial_content_stripped, line,
497 initial_content_len + 1);
498 if (len >= initial_content_len + 1) {
499 err = got_error(GOT_ERR_NO_SPACE);
500 goto done;
503 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
504 initial_content_stripped[len - 1] = '\0';
505 len--;
508 logmsg_len = st2.st_size;
509 *logmsg = malloc(logmsg_len + 1);
510 if (*logmsg == NULL)
511 return got_error_from_errno("malloc");
512 (*logmsg)[0] = '\0';
514 fp = fopen(logmsg_path, "re");
515 if (fp == NULL) {
516 err = got_error_from_errno("fopen");
517 goto done;
520 len = 0;
521 while ((linelen = getline(&line, &linesize, fp)) != -1) {
522 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
523 continue; /* remove comments and leading empty lines */
524 len = strlcat(*logmsg, line, logmsg_len + 1);
525 if (len >= logmsg_len + 1) {
526 err = got_error(GOT_ERR_NO_SPACE);
527 goto done;
530 free(line);
531 if (ferror(fp)) {
532 err = got_ferror(fp, GOT_ERR_IO);
533 goto done;
535 while (len > 0 && (*logmsg)[len - 1] == '\n') {
536 (*logmsg)[len - 1] = '\0';
537 len--;
540 if (len == 0) {
541 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
542 "commit message cannot be empty, aborting");
543 goto done;
545 if (require_modification &&
546 strcmp(*logmsg, initial_content_stripped) == 0)
547 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
548 "no changes made to commit message, aborting");
549 done:
550 free(initial_content_stripped);
551 free(buf);
552 if (fp && fclose(fp) == EOF && err == NULL)
553 err = got_error_from_errno("fclose");
554 if (err) {
555 free(*logmsg);
556 *logmsg = NULL;
558 return err;
561 static const struct got_error *
562 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
563 const char *path_dir, const char *branch_name)
565 char *initial_content = NULL;
566 const struct got_error *err = NULL;
567 int initial_content_len;
568 int fd = -1;
570 initial_content_len = asprintf(&initial_content,
571 "\n# %s to be imported to branch %s\n", path_dir,
572 branch_name);
573 if (initial_content_len == -1)
574 return got_error_from_errno("asprintf");
576 err = got_opentemp_named_fd(logmsg_path, &fd,
577 GOT_TMPDIR_STR "/got-importmsg");
578 if (err)
579 goto done;
581 if (write(fd, initial_content, initial_content_len) == -1) {
582 err = got_error_from_errno2("write", *logmsg_path);
583 goto done;
586 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
587 initial_content_len, 1);
588 done:
589 if (fd != -1 && close(fd) == -1 && err == NULL)
590 err = got_error_from_errno2("close", *logmsg_path);
591 free(initial_content);
592 if (err) {
593 free(*logmsg_path);
594 *logmsg_path = NULL;
596 return err;
599 static const struct got_error *
600 import_progress(void *arg, const char *path)
602 printf("A %s\n", path);
603 return NULL;
606 static int
607 valid_author(const char *author)
609 /*
610 * Really dumb email address check; we're only doing this to
611 * avoid git's object parser breaking on commits we create.
612 */
613 while (*author && *author != '<')
614 author++;
615 if (*author != '<')
616 return 0;
617 while (*author && *author != '@')
618 author++;
619 if (*author != '@')
620 return 0;
621 while (*author && *author != '>')
622 author++;
623 return *author == '>';
626 static const struct got_error *
627 get_author(char **author, struct got_repository *repo,
628 struct got_worktree *worktree)
630 const struct got_error *err = NULL;
631 const char *got_author = NULL, *name, *email;
632 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
634 *author = NULL;
636 if (worktree)
637 worktree_conf = got_worktree_get_gotconfig(worktree);
638 repo_conf = got_repo_get_gotconfig(repo);
640 /*
641 * Priority of potential author information sources, from most
642 * significant to least significant:
643 * 1) work tree's .got/got.conf file
644 * 2) repository's got.conf file
645 * 3) repository's git config file
646 * 4) environment variables
647 * 5) global git config files (in user's home directory or /etc)
648 */
650 if (worktree_conf)
651 got_author = got_gotconfig_get_author(worktree_conf);
652 if (got_author == NULL)
653 got_author = got_gotconfig_get_author(repo_conf);
654 if (got_author == NULL) {
655 name = got_repo_get_gitconfig_author_name(repo);
656 email = got_repo_get_gitconfig_author_email(repo);
657 if (name && email) {
658 if (asprintf(author, "%s <%s>", name, email) == -1)
659 return got_error_from_errno("asprintf");
660 return NULL;
663 got_author = getenv("GOT_AUTHOR");
664 if (got_author == NULL) {
665 name = got_repo_get_global_gitconfig_author_name(repo);
666 email = got_repo_get_global_gitconfig_author_email(
667 repo);
668 if (name && email) {
669 if (asprintf(author, "%s <%s>", name, email)
670 == -1)
671 return got_error_from_errno("asprintf");
672 return NULL;
674 /* TODO: Look up user in password database? */
675 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
679 *author = strdup(got_author);
680 if (*author == NULL)
681 return got_error_from_errno("strdup");
683 if (!valid_author(*author)) {
684 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
685 free(*author);
686 *author = NULL;
688 return err;
691 static const struct got_error *
692 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
693 struct got_worktree *worktree)
695 const char *got_allowed_signers = NULL;
696 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
698 *allowed_signers = NULL;
700 if (worktree)
701 worktree_conf = got_worktree_get_gotconfig(worktree);
702 repo_conf = got_repo_get_gotconfig(repo);
704 /*
705 * Priority of potential author information sources, from most
706 * significant to least significant:
707 * 1) work tree's .got/got.conf file
708 * 2) repository's got.conf file
709 */
711 if (worktree_conf)
712 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
713 worktree_conf);
714 if (got_allowed_signers == NULL)
715 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
716 repo_conf);
718 if (got_allowed_signers) {
719 *allowed_signers = strdup(got_allowed_signers);
720 if (*allowed_signers == NULL)
721 return got_error_from_errno("strdup");
723 return NULL;
726 static const struct got_error *
727 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
728 struct got_worktree *worktree)
730 const char *got_revoked_signers = NULL;
731 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
733 *revoked_signers = NULL;
735 if (worktree)
736 worktree_conf = got_worktree_get_gotconfig(worktree);
737 repo_conf = got_repo_get_gotconfig(repo);
739 /*
740 * Priority of potential author information sources, from most
741 * significant to least significant:
742 * 1) work tree's .got/got.conf file
743 * 2) repository's got.conf file
744 */
746 if (worktree_conf)
747 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
748 worktree_conf);
749 if (got_revoked_signers == NULL)
750 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
751 repo_conf);
753 if (got_revoked_signers) {
754 *revoked_signers = strdup(got_revoked_signers);
755 if (*revoked_signers == NULL)
756 return got_error_from_errno("strdup");
758 return NULL;
761 static const struct got_error *
762 get_gitconfig_path(char **gitconfig_path)
764 const char *homedir = getenv("HOME");
766 *gitconfig_path = NULL;
767 if (homedir) {
768 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
769 return got_error_from_errno("asprintf");
772 return NULL;
775 static const struct got_error *
776 cmd_import(int argc, char *argv[])
778 const struct got_error *error = NULL;
779 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
780 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
781 const char *branch_name = "main";
782 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
783 struct got_repository *repo = NULL;
784 struct got_reference *branch_ref = NULL, *head_ref = NULL;
785 struct got_object_id *new_commit_id = NULL;
786 int ch;
787 struct got_pathlist_head ignores;
788 struct got_pathlist_entry *pe;
789 int preserve_logmsg = 0;
790 int *pack_fds = NULL;
792 TAILQ_INIT(&ignores);
794 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
795 switch (ch) {
796 case 'b':
797 branch_name = optarg;
798 break;
799 case 'm':
800 logmsg = strdup(optarg);
801 if (logmsg == NULL) {
802 error = got_error_from_errno("strdup");
803 goto done;
805 break;
806 case 'r':
807 repo_path = realpath(optarg, NULL);
808 if (repo_path == NULL) {
809 error = got_error_from_errno2("realpath",
810 optarg);
811 goto done;
813 break;
814 case 'I':
815 if (optarg[0] == '\0')
816 break;
817 error = got_pathlist_insert(&pe, &ignores, optarg,
818 NULL);
819 if (error)
820 goto done;
821 break;
822 default:
823 usage_import();
824 /* NOTREACHED */
828 argc -= optind;
829 argv += optind;
831 #ifndef PROFILE
832 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
833 "unveil",
834 NULL) == -1)
835 err(1, "pledge");
836 #endif
837 if (argc != 1)
838 usage_import();
840 if (repo_path == NULL) {
841 repo_path = getcwd(NULL, 0);
842 if (repo_path == NULL)
843 return got_error_from_errno("getcwd");
845 got_path_strip_trailing_slashes(repo_path);
846 error = get_gitconfig_path(&gitconfig_path);
847 if (error)
848 goto done;
849 error = got_repo_pack_fds_open(&pack_fds);
850 if (error != NULL)
851 goto done;
852 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
853 if (error)
854 goto done;
856 error = get_author(&author, repo, NULL);
857 if (error)
858 return error;
860 /*
861 * Don't let the user create a branch name with a leading '-'.
862 * While technically a valid reference name, this case is usually
863 * an unintended typo.
864 */
865 if (branch_name[0] == '-')
866 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
868 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
869 error = got_error_from_errno("asprintf");
870 goto done;
873 error = got_ref_open(&branch_ref, repo, refname, 0);
874 if (error) {
875 if (error->code != GOT_ERR_NOT_REF)
876 goto done;
877 } else {
878 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
879 "import target branch already exists");
880 goto done;
883 path_dir = realpath(argv[0], NULL);
884 if (path_dir == NULL) {
885 error = got_error_from_errno2("realpath", argv[0]);
886 goto done;
888 got_path_strip_trailing_slashes(path_dir);
890 /*
891 * unveil(2) traverses exec(2); if an editor is used we have
892 * to apply unveil after the log message has been written.
893 */
894 if (logmsg == NULL || strlen(logmsg) == 0) {
895 error = get_editor(&editor);
896 if (error)
897 goto done;
898 free(logmsg);
899 error = collect_import_msg(&logmsg, &logmsg_path, editor,
900 path_dir, refname);
901 if (error) {
902 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
903 logmsg_path != NULL)
904 preserve_logmsg = 1;
905 goto done;
909 if (unveil(path_dir, "r") != 0) {
910 error = got_error_from_errno2("unveil", path_dir);
911 if (logmsg_path)
912 preserve_logmsg = 1;
913 goto done;
916 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
917 if (error) {
918 if (logmsg_path)
919 preserve_logmsg = 1;
920 goto done;
923 error = got_repo_import(&new_commit_id, path_dir, logmsg,
924 author, &ignores, repo, import_progress, NULL);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
938 error = got_ref_write(branch_ref, repo);
939 if (error) {
940 if (logmsg_path)
941 preserve_logmsg = 1;
942 goto done;
945 error = got_object_id_str(&id_str, new_commit_id);
946 if (error) {
947 if (logmsg_path)
948 preserve_logmsg = 1;
949 goto done;
952 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
953 if (error) {
954 if (error->code != GOT_ERR_NOT_REF) {
955 if (logmsg_path)
956 preserve_logmsg = 1;
957 goto done;
960 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
961 branch_ref);
962 if (error) {
963 if (logmsg_path)
964 preserve_logmsg = 1;
965 goto done;
968 error = got_ref_write(head_ref, repo);
969 if (error) {
970 if (logmsg_path)
971 preserve_logmsg = 1;
972 goto done;
976 printf("Created branch %s with commit %s\n",
977 got_ref_get_name(branch_ref), id_str);
978 done:
979 if (pack_fds) {
980 const struct got_error *pack_err =
981 got_repo_pack_fds_close(pack_fds);
982 if (error == NULL)
983 error = pack_err;
985 if (preserve_logmsg) {
986 fprintf(stderr, "%s: log message preserved in %s\n",
987 getprogname(), logmsg_path);
988 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
989 error = got_error_from_errno2("unlink", logmsg_path);
990 free(logmsg);
991 free(logmsg_path);
992 free(repo_path);
993 free(editor);
994 free(refname);
995 free(new_commit_id);
996 free(id_str);
997 free(author);
998 free(gitconfig_path);
999 if (branch_ref)
1000 got_ref_close(branch_ref);
1001 if (head_ref)
1002 got_ref_close(head_ref);
1003 return error;
1006 __dead static void
1007 usage_clone(void)
1009 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
1010 "[-R reference] repository-url [directory]\n", getprogname());
1011 exit(1);
1014 struct got_fetch_progress_arg {
1015 char last_scaled_size[FMT_SCALED_STRSIZE];
1016 int last_p_indexed;
1017 int last_p_resolved;
1018 int verbosity;
1020 struct got_repository *repo;
1022 int create_configs;
1023 int configs_created;
1024 struct {
1025 struct got_pathlist_head *symrefs;
1026 struct got_pathlist_head *wanted_branches;
1027 struct got_pathlist_head *wanted_refs;
1028 const char *proto;
1029 const char *host;
1030 const char *port;
1031 const char *remote_repo_path;
1032 const char *git_url;
1033 int fetch_all_branches;
1034 int mirror_references;
1035 } config_info;
1038 /* XXX forward declaration */
1039 static const struct got_error *
1040 create_config_files(const char *proto, const char *host, const char *port,
1041 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1042 int mirror_references, struct got_pathlist_head *symrefs,
1043 struct got_pathlist_head *wanted_branches,
1044 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1046 static const struct got_error *
1047 fetch_progress(void *arg, const char *message, off_t packfile_size,
1048 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1050 const struct got_error *err = NULL;
1051 struct got_fetch_progress_arg *a = arg;
1052 char scaled_size[FMT_SCALED_STRSIZE];
1053 int p_indexed, p_resolved;
1054 int print_size = 0, print_indexed = 0, print_resolved = 0;
1057 * In order to allow a failed clone to be resumed with 'got fetch'
1058 * we try to create configuration files as soon as possible.
1059 * Once the server has sent information about its default branch
1060 * we have all required information.
1062 if (a->create_configs && !a->configs_created &&
1063 !TAILQ_EMPTY(a->config_info.symrefs)) {
1064 err = create_config_files(a->config_info.proto,
1065 a->config_info.host, a->config_info.port,
1066 a->config_info.remote_repo_path,
1067 a->config_info.git_url,
1068 a->config_info.fetch_all_branches,
1069 a->config_info.mirror_references,
1070 a->config_info.symrefs,
1071 a->config_info.wanted_branches,
1072 a->config_info.wanted_refs, a->repo);
1073 if (err)
1074 return err;
1075 a->configs_created = 1;
1078 if (a->verbosity < 0)
1079 return NULL;
1081 if (message && message[0] != '\0') {
1082 printf("\rserver: %s", message);
1083 fflush(stdout);
1084 return NULL;
1087 if (packfile_size > 0 || nobj_indexed > 0) {
1088 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1089 (a->last_scaled_size[0] == '\0' ||
1090 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1091 print_size = 1;
1092 if (strlcpy(a->last_scaled_size, scaled_size,
1093 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1094 return got_error(GOT_ERR_NO_SPACE);
1096 if (nobj_indexed > 0) {
1097 p_indexed = (nobj_indexed * 100) / nobj_total;
1098 if (p_indexed != a->last_p_indexed) {
1099 a->last_p_indexed = p_indexed;
1100 print_indexed = 1;
1101 print_size = 1;
1104 if (nobj_resolved > 0) {
1105 p_resolved = (nobj_resolved * 100) /
1106 (nobj_total - nobj_loose);
1107 if (p_resolved != a->last_p_resolved) {
1108 a->last_p_resolved = p_resolved;
1109 print_resolved = 1;
1110 print_indexed = 1;
1111 print_size = 1;
1116 if (print_size || print_indexed || print_resolved)
1117 printf("\r");
1118 if (print_size)
1119 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1120 if (print_indexed)
1121 printf("; indexing %d%%", p_indexed);
1122 if (print_resolved)
1123 printf("; resolving deltas %d%%", p_resolved);
1124 if (print_size || print_indexed || print_resolved)
1125 fflush(stdout);
1127 return NULL;
1130 static const struct got_error *
1131 create_symref(const char *refname, struct got_reference *target_ref,
1132 int verbosity, struct got_repository *repo)
1134 const struct got_error *err;
1135 struct got_reference *head_symref;
1137 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1138 if (err)
1139 return err;
1141 err = got_ref_write(head_symref, repo);
1142 if (err == NULL && verbosity > 0) {
1143 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1144 got_ref_get_name(target_ref));
1146 got_ref_close(head_symref);
1147 return err;
1150 static const struct got_error *
1151 list_remote_refs(struct got_pathlist_head *symrefs,
1152 struct got_pathlist_head *refs)
1154 const struct got_error *err;
1155 struct got_pathlist_entry *pe;
1157 TAILQ_FOREACH(pe, symrefs, entry) {
1158 const char *refname = pe->path;
1159 const char *targetref = pe->data;
1161 printf("%s: %s\n", refname, targetref);
1164 TAILQ_FOREACH(pe, refs, entry) {
1165 const char *refname = pe->path;
1166 struct got_object_id *id = pe->data;
1167 char *id_str;
1169 err = got_object_id_str(&id_str, id);
1170 if (err)
1171 return err;
1172 printf("%s: %s\n", refname, id_str);
1173 free(id_str);
1176 return NULL;
1179 static const struct got_error *
1180 create_ref(const char *refname, struct got_object_id *id,
1181 int verbosity, struct got_repository *repo)
1183 const struct got_error *err = NULL;
1184 struct got_reference *ref;
1185 char *id_str;
1187 err = got_object_id_str(&id_str, id);
1188 if (err)
1189 return err;
1191 err = got_ref_alloc(&ref, refname, id);
1192 if (err)
1193 goto done;
1195 err = got_ref_write(ref, repo);
1196 got_ref_close(ref);
1198 if (err == NULL && verbosity >= 0)
1199 printf("Created reference %s: %s\n", refname, id_str);
1200 done:
1201 free(id_str);
1202 return err;
1205 static int
1206 match_wanted_ref(const char *refname, const char *wanted_ref)
1208 if (strncmp(refname, "refs/", 5) != 0)
1209 return 0;
1210 refname += 5;
1213 * Prevent fetching of references that won't make any
1214 * sense outside of the remote repository's context.
1216 if (strncmp(refname, "got/", 4) == 0)
1217 return 0;
1218 if (strncmp(refname, "remotes/", 8) == 0)
1219 return 0;
1221 if (strncmp(wanted_ref, "refs/", 5) == 0)
1222 wanted_ref += 5;
1224 /* Allow prefix match. */
1225 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1226 return 1;
1228 /* Allow exact match. */
1229 return (strcmp(refname, wanted_ref) == 0);
1232 static int
1233 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1235 struct got_pathlist_entry *pe;
1237 TAILQ_FOREACH(pe, wanted_refs, entry) {
1238 if (match_wanted_ref(refname, pe->path))
1239 return 1;
1242 return 0;
1245 static const struct got_error *
1246 create_wanted_ref(const char *refname, struct got_object_id *id,
1247 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1249 const struct got_error *err;
1250 char *remote_refname;
1252 if (strncmp("refs/", refname, 5) == 0)
1253 refname += 5;
1255 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1256 remote_repo_name, refname) == -1)
1257 return got_error_from_errno("asprintf");
1259 err = create_ref(remote_refname, id, verbosity, repo);
1260 free(remote_refname);
1261 return err;
1264 static const struct got_error *
1265 create_gotconfig(const char *proto, const char *host, const char *port,
1266 const char *remote_repo_path, const char *default_branch,
1267 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1268 struct got_pathlist_head *wanted_refs, int mirror_references,
1269 struct got_repository *repo)
1271 const struct got_error *err = NULL;
1272 char *gotconfig_path = NULL;
1273 char *gotconfig = NULL;
1274 FILE *gotconfig_file = NULL;
1275 const char *branchname = NULL;
1276 char *branches = NULL, *refs = NULL;
1277 ssize_t n;
1279 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1280 struct got_pathlist_entry *pe;
1281 TAILQ_FOREACH(pe, wanted_branches, entry) {
1282 char *s;
1283 branchname = pe->path;
1284 if (strncmp(branchname, "refs/heads/", 11) == 0)
1285 branchname += 11;
1286 if (asprintf(&s, "%s\"%s\" ",
1287 branches ? branches : "", branchname) == -1) {
1288 err = got_error_from_errno("asprintf");
1289 goto done;
1291 free(branches);
1292 branches = s;
1294 } else if (!fetch_all_branches && default_branch) {
1295 branchname = default_branch;
1296 if (strncmp(branchname, "refs/heads/", 11) == 0)
1297 branchname += 11;
1298 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1299 err = got_error_from_errno("asprintf");
1300 goto done;
1303 if (!TAILQ_EMPTY(wanted_refs)) {
1304 struct got_pathlist_entry *pe;
1305 TAILQ_FOREACH(pe, wanted_refs, entry) {
1306 char *s;
1307 const char *refname = pe->path;
1308 if (strncmp(refname, "refs/", 5) == 0)
1309 branchname += 5;
1310 if (asprintf(&s, "%s\"%s\" ",
1311 refs ? refs : "", refname) == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 free(refs);
1316 refs = s;
1320 /* Create got.conf(5). */
1321 gotconfig_path = got_repo_get_path_gotconfig(repo);
1322 if (gotconfig_path == NULL) {
1323 err = got_error_from_errno("got_repo_get_path_gotconfig");
1324 goto done;
1326 gotconfig_file = fopen(gotconfig_path, "ae");
1327 if (gotconfig_file == NULL) {
1328 err = got_error_from_errno2("fopen", gotconfig_path);
1329 goto done;
1331 if (asprintf(&gotconfig,
1332 "remote \"%s\" {\n"
1333 "\tserver %s\n"
1334 "\tprotocol %s\n"
1335 "%s%s%s"
1336 "\trepository \"%s\"\n"
1337 "%s%s%s"
1338 "%s%s%s"
1339 "%s"
1340 "%s"
1341 "}\n",
1342 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1343 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1344 remote_repo_path, branches ? "\tbranch { " : "",
1345 branches ? branches : "", branches ? "}\n" : "",
1346 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1347 mirror_references ? "\tmirror_references yes\n" : "",
1348 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1349 err = got_error_from_errno("asprintf");
1350 goto done;
1352 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1353 if (n != strlen(gotconfig)) {
1354 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1355 goto done;
1358 done:
1359 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1360 err = got_error_from_errno2("fclose", gotconfig_path);
1361 free(gotconfig_path);
1362 free(branches);
1363 return err;
1366 static const struct got_error *
1367 create_gitconfig(const char *git_url, const char *default_branch,
1368 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1369 struct got_pathlist_head *wanted_refs, int mirror_references,
1370 struct got_repository *repo)
1372 const struct got_error *err = NULL;
1373 char *gitconfig_path = NULL;
1374 char *gitconfig = NULL;
1375 FILE *gitconfig_file = NULL;
1376 char *branches = NULL, *refs = NULL;
1377 const char *branchname;
1378 ssize_t n;
1380 /* Create a config file Git can understand. */
1381 gitconfig_path = got_repo_get_path_gitconfig(repo);
1382 if (gitconfig_path == NULL) {
1383 err = got_error_from_errno("got_repo_get_path_gitconfig");
1384 goto done;
1386 gitconfig_file = fopen(gitconfig_path, "ae");
1387 if (gitconfig_file == NULL) {
1388 err = got_error_from_errno2("fopen", gitconfig_path);
1389 goto done;
1391 if (fetch_all_branches) {
1392 if (mirror_references) {
1393 if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1395 err = got_error_from_errno("asprintf");
1396 goto done;
1398 } else if (asprintf(&branches,
1399 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1400 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 } else if (!TAILQ_EMPTY(wanted_branches)) {
1405 struct got_pathlist_entry *pe;
1406 TAILQ_FOREACH(pe, wanted_branches, entry) {
1407 char *s;
1408 branchname = pe->path;
1409 if (strncmp(branchname, "refs/heads/", 11) == 0)
1410 branchname += 11;
1411 if (mirror_references) {
1412 if (asprintf(&s,
1413 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1414 branches ? branches : "",
1415 branchname, branchname) == -1) {
1416 err = got_error_from_errno("asprintf");
1417 goto done;
1419 } else if (asprintf(&s,
1420 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1421 branches ? branches : "",
1422 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1423 branchname) == -1) {
1424 err = got_error_from_errno("asprintf");
1425 goto done;
1427 free(branches);
1428 branches = s;
1430 } else {
1432 * If the server specified a default branch, use just that one.
1433 * Otherwise fall back to fetching all branches on next fetch.
1435 if (default_branch) {
1436 branchname = default_branch;
1437 if (strncmp(branchname, "refs/heads/", 11) == 0)
1438 branchname += 11;
1439 } else
1440 branchname = "*"; /* fall back to all branches */
1441 if (mirror_references) {
1442 if (asprintf(&branches,
1443 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1444 branchname, branchname) == -1) {
1445 err = got_error_from_errno("asprintf");
1446 goto done;
1448 } else if (asprintf(&branches,
1449 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1450 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1451 branchname) == -1) {
1452 err = got_error_from_errno("asprintf");
1453 goto done;
1456 if (!TAILQ_EMPTY(wanted_refs)) {
1457 struct got_pathlist_entry *pe;
1458 TAILQ_FOREACH(pe, wanted_refs, entry) {
1459 char *s;
1460 const char *refname = pe->path;
1461 if (strncmp(refname, "refs/", 5) == 0)
1462 refname += 5;
1463 if (mirror_references) {
1464 if (asprintf(&s,
1465 "%s\tfetch = refs/%s:refs/%s\n",
1466 refs ? refs : "", refname, refname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 } else if (asprintf(&s,
1471 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1472 refs ? refs : "",
1473 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1474 refname) == -1) {
1475 err = got_error_from_errno("asprintf");
1476 goto done;
1478 free(refs);
1479 refs = s;
1483 if (asprintf(&gitconfig,
1484 "[remote \"%s\"]\n"
1485 "\turl = %s\n"
1486 "%s"
1487 "%s"
1488 "\tfetch = refs/tags/*:refs/tags/*\n",
1489 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1490 refs ? refs : "") == -1) {
1491 err = got_error_from_errno("asprintf");
1492 goto done;
1494 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1495 if (n != strlen(gitconfig)) {
1496 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1497 goto done;
1499 done:
1500 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1501 err = got_error_from_errno2("fclose", gitconfig_path);
1502 free(gitconfig_path);
1503 free(branches);
1504 return err;
1507 static const struct got_error *
1508 create_config_files(const char *proto, const char *host, const char *port,
1509 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1510 int mirror_references, struct got_pathlist_head *symrefs,
1511 struct got_pathlist_head *wanted_branches,
1512 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1514 const struct got_error *err = NULL;
1515 const char *default_branch = NULL;
1516 struct got_pathlist_entry *pe;
1519 * If we asked for a set of wanted branches then use the first
1520 * one of those.
1522 if (!TAILQ_EMPTY(wanted_branches)) {
1523 pe = TAILQ_FIRST(wanted_branches);
1524 default_branch = pe->path;
1525 } else {
1526 /* First HEAD ref listed by server is the default branch. */
1527 TAILQ_FOREACH(pe, symrefs, entry) {
1528 const char *refname = pe->path;
1529 const char *target = pe->data;
1531 if (strcmp(refname, GOT_REF_HEAD) != 0)
1532 continue;
1534 default_branch = target;
1535 break;
1539 /* Create got.conf(5). */
1540 err = create_gotconfig(proto, host, port, remote_repo_path,
1541 default_branch, fetch_all_branches, wanted_branches,
1542 wanted_refs, mirror_references, repo);
1543 if (err)
1544 return err;
1546 /* Create a config file Git can understand. */
1547 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1548 wanted_branches, wanted_refs, mirror_references, repo);
1551 static const struct got_error *
1552 cmd_clone(int argc, char *argv[])
1554 const struct got_error *error = NULL;
1555 const char *uri, *dirname;
1556 char *proto, *host, *port, *repo_name, *server_path;
1557 char *default_destdir = NULL, *id_str = NULL;
1558 const char *repo_path;
1559 struct got_repository *repo = NULL;
1560 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1561 struct got_pathlist_entry *pe;
1562 struct got_object_id *pack_hash = NULL;
1563 int ch, fetchfd = -1, fetchstatus;
1564 pid_t fetchpid = -1;
1565 struct got_fetch_progress_arg fpa;
1566 char *git_url = NULL;
1567 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1568 int list_refs_only = 0;
1569 int *pack_fds = NULL;
1571 TAILQ_INIT(&refs);
1572 TAILQ_INIT(&symrefs);
1573 TAILQ_INIT(&wanted_branches);
1574 TAILQ_INIT(&wanted_refs);
1576 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1577 switch (ch) {
1578 case 'a':
1579 fetch_all_branches = 1;
1580 break;
1581 case 'b':
1582 error = got_pathlist_append(&wanted_branches,
1583 optarg, NULL);
1584 if (error)
1585 return error;
1586 break;
1587 case 'l':
1588 list_refs_only = 1;
1589 break;
1590 case 'm':
1591 mirror_references = 1;
1592 break;
1593 case 'v':
1594 if (verbosity < 0)
1595 verbosity = 0;
1596 else if (verbosity < 3)
1597 verbosity++;
1598 break;
1599 case 'q':
1600 verbosity = -1;
1601 break;
1602 case 'R':
1603 error = got_pathlist_append(&wanted_refs,
1604 optarg, NULL);
1605 if (error)
1606 return error;
1607 break;
1608 default:
1609 usage_clone();
1610 break;
1613 argc -= optind;
1614 argv += optind;
1616 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1617 option_conflict('a', 'b');
1618 if (list_refs_only) {
1619 if (!TAILQ_EMPTY(&wanted_branches))
1620 option_conflict('l', 'b');
1621 if (fetch_all_branches)
1622 option_conflict('l', 'a');
1623 if (mirror_references)
1624 option_conflict('l', 'm');
1625 if (!TAILQ_EMPTY(&wanted_refs))
1626 option_conflict('l', 'R');
1629 uri = argv[0];
1631 if (argc == 1)
1632 dirname = NULL;
1633 else if (argc == 2)
1634 dirname = argv[1];
1635 else
1636 usage_clone();
1638 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1639 &repo_name, uri);
1640 if (error)
1641 goto done;
1643 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1644 host, port ? ":" : "", port ? port : "",
1645 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1646 error = got_error_from_errno("asprintf");
1647 goto done;
1650 if (strcmp(proto, "git") == 0) {
1651 #ifndef PROFILE
1652 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1653 "sendfd dns inet unveil", NULL) == -1)
1654 err(1, "pledge");
1655 #endif
1656 } else if (strcmp(proto, "git+ssh") == 0 ||
1657 strcmp(proto, "ssh") == 0) {
1658 #ifndef PROFILE
1659 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1660 "sendfd unveil", NULL) == -1)
1661 err(1, "pledge");
1662 #endif
1663 } else if (strcmp(proto, "http") == 0 ||
1664 strcmp(proto, "git+http") == 0) {
1665 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1666 goto done;
1667 } else {
1668 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1669 goto done;
1671 if (dirname == NULL) {
1672 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1673 error = got_error_from_errno("asprintf");
1674 goto done;
1676 repo_path = default_destdir;
1677 } else
1678 repo_path = dirname;
1680 if (!list_refs_only) {
1681 error = got_path_mkdir(repo_path);
1682 if (error &&
1683 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1684 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1685 goto done;
1686 if (!got_path_dir_is_empty(repo_path)) {
1687 error = got_error_path(repo_path,
1688 GOT_ERR_DIR_NOT_EMPTY);
1689 goto done;
1693 error = got_dial_apply_unveil(proto);
1694 if (error)
1695 goto done;
1697 error = apply_unveil(repo_path, 0, NULL);
1698 if (error)
1699 goto done;
1701 if (verbosity >= 0)
1702 printf("Connecting to %s%s%s\n", host,
1703 port ? ":" : "", port ? port : "");
1705 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1706 server_path, verbosity);
1707 if (error)
1708 goto done;
1710 if (!list_refs_only) {
1711 error = got_repo_init(repo_path);
1712 if (error)
1713 goto done;
1714 error = got_repo_pack_fds_open(&pack_fds);
1715 if (error != NULL)
1716 goto done;
1717 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1718 if (error)
1719 goto done;
1722 fpa.last_scaled_size[0] = '\0';
1723 fpa.last_p_indexed = -1;
1724 fpa.last_p_resolved = -1;
1725 fpa.verbosity = verbosity;
1726 fpa.create_configs = 1;
1727 fpa.configs_created = 0;
1728 fpa.repo = repo;
1729 fpa.config_info.symrefs = &symrefs;
1730 fpa.config_info.wanted_branches = &wanted_branches;
1731 fpa.config_info.wanted_refs = &wanted_refs;
1732 fpa.config_info.proto = proto;
1733 fpa.config_info.host = host;
1734 fpa.config_info.port = port;
1735 fpa.config_info.remote_repo_path = server_path;
1736 fpa.config_info.git_url = git_url;
1737 fpa.config_info.fetch_all_branches = fetch_all_branches;
1738 fpa.config_info.mirror_references = mirror_references;
1739 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1740 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1741 fetch_all_branches, &wanted_branches, &wanted_refs,
1742 list_refs_only, verbosity, fetchfd, repo,
1743 fetch_progress, &fpa);
1744 if (error)
1745 goto done;
1747 if (list_refs_only) {
1748 error = list_remote_refs(&symrefs, &refs);
1749 goto done;
1752 if (pack_hash == NULL) {
1753 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1754 "server sent an empty pack file");
1755 goto done;
1757 error = got_object_id_str(&id_str, pack_hash);
1758 if (error)
1759 goto done;
1760 if (verbosity >= 0)
1761 printf("\nFetched %s.pack\n", id_str);
1762 free(id_str);
1764 /* Set up references provided with the pack file. */
1765 TAILQ_FOREACH(pe, &refs, entry) {
1766 const char *refname = pe->path;
1767 struct got_object_id *id = pe->data;
1768 char *remote_refname;
1770 if (is_wanted_ref(&wanted_refs, refname) &&
1771 !mirror_references) {
1772 error = create_wanted_ref(refname, id,
1773 GOT_FETCH_DEFAULT_REMOTE_NAME,
1774 verbosity - 1, repo);
1775 if (error)
1776 goto done;
1777 continue;
1780 error = create_ref(refname, id, verbosity - 1, repo);
1781 if (error)
1782 goto done;
1784 if (mirror_references)
1785 continue;
1787 if (strncmp("refs/heads/", refname, 11) != 0)
1788 continue;
1790 if (asprintf(&remote_refname,
1791 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1792 refname + 11) == -1) {
1793 error = got_error_from_errno("asprintf");
1794 goto done;
1796 error = create_ref(remote_refname, id, verbosity - 1, repo);
1797 free(remote_refname);
1798 if (error)
1799 goto done;
1802 /* Set the HEAD reference if the server provided one. */
1803 TAILQ_FOREACH(pe, &symrefs, entry) {
1804 struct got_reference *target_ref;
1805 const char *refname = pe->path;
1806 const char *target = pe->data;
1807 char *remote_refname = NULL, *remote_target = NULL;
1809 if (strcmp(refname, GOT_REF_HEAD) != 0)
1810 continue;
1812 error = got_ref_open(&target_ref, repo, target, 0);
1813 if (error) {
1814 if (error->code == GOT_ERR_NOT_REF) {
1815 error = NULL;
1816 continue;
1818 goto done;
1821 error = create_symref(refname, target_ref, verbosity, repo);
1822 got_ref_close(target_ref);
1823 if (error)
1824 goto done;
1826 if (mirror_references)
1827 continue;
1829 if (strncmp("refs/heads/", target, 11) != 0)
1830 continue;
1832 if (asprintf(&remote_refname,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 refname) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 goto done;
1838 if (asprintf(&remote_target,
1839 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1840 target + 11) == -1) {
1841 error = got_error_from_errno("asprintf");
1842 free(remote_refname);
1843 goto done;
1845 error = got_ref_open(&target_ref, repo, remote_target, 0);
1846 if (error) {
1847 free(remote_refname);
1848 free(remote_target);
1849 if (error->code == GOT_ERR_NOT_REF) {
1850 error = NULL;
1851 continue;
1853 goto done;
1855 error = create_symref(remote_refname, target_ref,
1856 verbosity - 1, repo);
1857 free(remote_refname);
1858 free(remote_target);
1859 got_ref_close(target_ref);
1860 if (error)
1861 goto done;
1863 if (pe == NULL) {
1865 * We failed to set the HEAD reference. If we asked for
1866 * a set of wanted branches use the first of one of those
1867 * which could be fetched instead.
1869 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1870 const char *target = pe->path;
1871 struct got_reference *target_ref;
1873 error = got_ref_open(&target_ref, repo, target, 0);
1874 if (error) {
1875 if (error->code == GOT_ERR_NOT_REF) {
1876 error = NULL;
1877 continue;
1879 goto done;
1882 error = create_symref(GOT_REF_HEAD, target_ref,
1883 verbosity, repo);
1884 got_ref_close(target_ref);
1885 if (error)
1886 goto done;
1887 break;
1891 if (verbosity >= 0)
1892 printf("Created %s repository '%s'\n",
1893 mirror_references ? "mirrored" : "cloned", repo_path);
1894 done:
1895 if (pack_fds) {
1896 const struct got_error *pack_err =
1897 got_repo_pack_fds_close(pack_fds);
1898 if (error == NULL)
1899 error = pack_err;
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo) {
1910 const struct got_error *close_err = got_repo_close(repo);
1911 if (error == NULL)
1912 error = close_err;
1914 TAILQ_FOREACH(pe, &refs, entry) {
1915 free((void *)pe->path);
1916 free(pe->data);
1918 got_pathlist_free(&refs);
1919 TAILQ_FOREACH(pe, &symrefs, entry) {
1920 free((void *)pe->path);
1921 free(pe->data);
1923 got_pathlist_free(&symrefs);
1924 got_pathlist_free(&wanted_branches);
1925 got_pathlist_free(&wanted_refs);
1926 free(pack_hash);
1927 free(proto);
1928 free(host);
1929 free(port);
1930 free(server_path);
1931 free(repo_name);
1932 free(default_destdir);
1933 free(git_url);
1934 return error;
1937 static const struct got_error *
1938 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1939 int replace_tags, int verbosity, struct got_repository *repo)
1941 const struct got_error *err = NULL;
1942 char *new_id_str = NULL;
1943 struct got_object_id *old_id = NULL;
1945 err = got_object_id_str(&new_id_str, new_id);
1946 if (err)
1947 goto done;
1949 if (!replace_tags &&
1950 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1951 err = got_ref_resolve(&old_id, repo, ref);
1952 if (err)
1953 goto done;
1954 if (got_object_id_cmp(old_id, new_id) == 0)
1955 goto done;
1956 if (verbosity >= 0) {
1957 printf("Rejecting update of existing tag %s: %s\n",
1958 got_ref_get_name(ref), new_id_str);
1960 goto done;
1963 if (got_ref_is_symbolic(ref)) {
1964 if (verbosity >= 0) {
1965 printf("Replacing reference %s: %s\n",
1966 got_ref_get_name(ref),
1967 got_ref_get_symref_target(ref));
1969 err = got_ref_change_symref_to_ref(ref, new_id);
1970 if (err)
1971 goto done;
1972 err = got_ref_write(ref, repo);
1973 if (err)
1974 goto done;
1975 } else {
1976 err = got_ref_resolve(&old_id, repo, ref);
1977 if (err)
1978 goto done;
1979 if (got_object_id_cmp(old_id, new_id) == 0)
1980 goto done;
1982 err = got_ref_change_ref(ref, new_id);
1983 if (err)
1984 goto done;
1985 err = got_ref_write(ref, repo);
1986 if (err)
1987 goto done;
1990 if (verbosity >= 0)
1991 printf("Updated %s: %s\n", got_ref_get_name(ref),
1992 new_id_str);
1993 done:
1994 free(old_id);
1995 free(new_id_str);
1996 return err;
1999 static const struct got_error *
2000 update_symref(const char *refname, struct got_reference *target_ref,
2001 int verbosity, struct got_repository *repo)
2003 const struct got_error *err = NULL, *unlock_err;
2004 struct got_reference *symref;
2005 int symref_is_locked = 0;
2007 err = got_ref_open(&symref, repo, refname, 1);
2008 if (err) {
2009 if (err->code != GOT_ERR_NOT_REF)
2010 return err;
2011 err = got_ref_alloc_symref(&symref, refname, target_ref);
2012 if (err)
2013 goto done;
2015 err = got_ref_write(symref, repo);
2016 if (err)
2017 goto done;
2019 if (verbosity >= 0)
2020 printf("Created reference %s: %s\n",
2021 got_ref_get_name(symref),
2022 got_ref_get_symref_target(symref));
2023 } else {
2024 symref_is_locked = 1;
2026 if (strcmp(got_ref_get_symref_target(symref),
2027 got_ref_get_name(target_ref)) == 0)
2028 goto done;
2030 err = got_ref_change_symref(symref,
2031 got_ref_get_name(target_ref));
2032 if (err)
2033 goto done;
2035 err = got_ref_write(symref, repo);
2036 if (err)
2037 goto done;
2039 if (verbosity >= 0)
2040 printf("Updated %s: %s\n", got_ref_get_name(symref),
2041 got_ref_get_symref_target(symref));
2044 done:
2045 if (symref_is_locked) {
2046 unlock_err = got_ref_unlock(symref);
2047 if (unlock_err && err == NULL)
2048 err = unlock_err;
2050 got_ref_close(symref);
2051 return err;
2054 __dead static void
2055 usage_fetch(void)
2057 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2058 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2059 "[remote-repository-name]\n",
2060 getprogname());
2061 exit(1);
2064 static const struct got_error *
2065 delete_missing_ref(struct got_reference *ref,
2066 int verbosity, struct got_repository *repo)
2068 const struct got_error *err = NULL;
2069 struct got_object_id *id = NULL;
2070 char *id_str = NULL;
2072 if (got_ref_is_symbolic(ref)) {
2073 err = got_ref_delete(ref, repo);
2074 if (err)
2075 return err;
2076 if (verbosity >= 0) {
2077 printf("Deleted %s: %s\n",
2078 got_ref_get_name(ref),
2079 got_ref_get_symref_target(ref));
2081 } else {
2082 err = got_ref_resolve(&id, repo, ref);
2083 if (err)
2084 return err;
2085 err = got_object_id_str(&id_str, id);
2086 if (err)
2087 goto done;
2089 err = got_ref_delete(ref, repo);
2090 if (err)
2091 goto done;
2092 if (verbosity >= 0) {
2093 printf("Deleted %s: %s\n",
2094 got_ref_get_name(ref), id_str);
2097 done:
2098 free(id);
2099 free(id_str);
2100 return NULL;
2103 static const struct got_error *
2104 delete_missing_refs(struct got_pathlist_head *their_refs,
2105 struct got_pathlist_head *their_symrefs,
2106 const struct got_remote_repo *remote,
2107 int verbosity, struct got_repository *repo)
2109 const struct got_error *err = NULL, *unlock_err;
2110 struct got_reflist_head my_refs;
2111 struct got_reflist_entry *re;
2112 struct got_pathlist_entry *pe;
2113 char *remote_namespace = NULL;
2114 char *local_refname = NULL;
2116 TAILQ_INIT(&my_refs);
2118 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2119 == -1)
2120 return got_error_from_errno("asprintf");
2122 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2123 if (err)
2124 goto done;
2126 TAILQ_FOREACH(re, &my_refs, entry) {
2127 const char *refname = got_ref_get_name(re->ref);
2128 const char *their_refname;
2130 if (remote->mirror_references) {
2131 their_refname = refname;
2132 } else {
2133 if (strncmp(refname, remote_namespace,
2134 strlen(remote_namespace)) == 0) {
2135 if (strcmp(refname + strlen(remote_namespace),
2136 GOT_REF_HEAD) == 0)
2137 continue;
2138 if (asprintf(&local_refname, "refs/heads/%s",
2139 refname + strlen(remote_namespace)) == -1) {
2140 err = got_error_from_errno("asprintf");
2141 goto done;
2143 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2144 continue;
2146 their_refname = local_refname;
2149 TAILQ_FOREACH(pe, their_refs, entry) {
2150 if (strcmp(their_refname, pe->path) == 0)
2151 break;
2153 if (pe != NULL)
2154 continue;
2156 TAILQ_FOREACH(pe, their_symrefs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 err = delete_missing_ref(re->ref, verbosity, repo);
2164 if (err)
2165 break;
2167 if (local_refname) {
2168 struct got_reference *ref;
2169 err = got_ref_open(&ref, repo, local_refname, 1);
2170 if (err) {
2171 if (err->code != GOT_ERR_NOT_REF)
2172 break;
2173 free(local_refname);
2174 local_refname = NULL;
2175 continue;
2177 err = delete_missing_ref(ref, verbosity, repo);
2178 if (err)
2179 break;
2180 unlock_err = got_ref_unlock(ref);
2181 got_ref_close(ref);
2182 if (unlock_err && err == NULL) {
2183 err = unlock_err;
2184 break;
2187 free(local_refname);
2188 local_refname = NULL;
2191 done:
2192 free(remote_namespace);
2193 free(local_refname);
2194 return err;
2197 static const struct got_error *
2198 update_wanted_ref(const char *refname, struct got_object_id *id,
2199 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2201 const struct got_error *err, *unlock_err;
2202 char *remote_refname;
2203 struct got_reference *ref;
2205 if (strncmp("refs/", refname, 5) == 0)
2206 refname += 5;
2208 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2209 remote_repo_name, refname) == -1)
2210 return got_error_from_errno("asprintf");
2212 err = got_ref_open(&ref, repo, remote_refname, 1);
2213 if (err) {
2214 if (err->code != GOT_ERR_NOT_REF)
2215 goto done;
2216 err = create_ref(remote_refname, id, verbosity, repo);
2217 } else {
2218 err = update_ref(ref, id, 0, verbosity, repo);
2219 unlock_err = got_ref_unlock(ref);
2220 if (unlock_err && err == NULL)
2221 err = unlock_err;
2222 got_ref_close(ref);
2224 done:
2225 free(remote_refname);
2226 return err;
2229 static const struct got_error *
2230 delete_ref(struct got_repository *repo, struct got_reference *ref)
2232 const struct got_error *err = NULL;
2233 struct got_object_id *id = NULL;
2234 char *id_str = NULL;
2235 const char *target;
2237 if (got_ref_is_symbolic(ref)) {
2238 target = got_ref_get_symref_target(ref);
2239 } else {
2240 err = got_ref_resolve(&id, repo, ref);
2241 if (err)
2242 goto done;
2243 err = got_object_id_str(&id_str, id);
2244 if (err)
2245 goto done;
2246 target = id_str;
2249 err = got_ref_delete(ref, repo);
2250 if (err)
2251 goto done;
2253 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2254 done:
2255 free(id);
2256 free(id_str);
2257 return err;
2260 static const struct got_error *
2261 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2263 const struct got_error *err = NULL;
2264 struct got_reflist_head refs;
2265 struct got_reflist_entry *re;
2266 char *prefix;
2268 TAILQ_INIT(&refs);
2270 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2271 err = got_error_from_errno("asprintf");
2272 goto done;
2274 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2275 if (err)
2276 goto done;
2278 TAILQ_FOREACH(re, &refs, entry)
2279 delete_ref(repo, re->ref);
2280 done:
2281 got_ref_list_free(&refs);
2282 return err;
2285 static const struct got_error *
2286 cmd_fetch(int argc, char *argv[])
2288 const struct got_error *error = NULL, *unlock_err;
2289 char *cwd = NULL, *repo_path = NULL;
2290 const char *remote_name;
2291 char *proto = NULL, *host = NULL, *port = NULL;
2292 char *repo_name = NULL, *server_path = NULL;
2293 const struct got_remote_repo *remotes, *remote = NULL;
2294 int nremotes;
2295 char *id_str = NULL;
2296 struct got_repository *repo = NULL;
2297 struct got_worktree *worktree = NULL;
2298 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2299 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2300 struct got_pathlist_entry *pe;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&wanted_branches);
2312 TAILQ_INIT(&wanted_refs);
2314 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2315 switch (ch) {
2316 case 'a':
2317 fetch_all_branches = 1;
2318 break;
2319 case 'b':
2320 error = got_pathlist_append(&wanted_branches,
2321 optarg, NULL);
2322 if (error)
2323 return error;
2324 break;
2325 case 'd':
2326 delete_refs = 1;
2327 break;
2328 case 'l':
2329 list_refs_only = 1;
2330 break;
2331 case 'r':
2332 repo_path = realpath(optarg, NULL);
2333 if (repo_path == NULL)
2334 return got_error_from_errno2("realpath",
2335 optarg);
2336 got_path_strip_trailing_slashes(repo_path);
2337 break;
2338 case 't':
2339 replace_tags = 1;
2340 break;
2341 case 'v':
2342 if (verbosity < 0)
2343 verbosity = 0;
2344 else if (verbosity < 3)
2345 verbosity++;
2346 break;
2347 case 'q':
2348 verbosity = -1;
2349 break;
2350 case 'R':
2351 error = got_pathlist_append(&wanted_refs,
2352 optarg, NULL);
2353 if (error)
2354 return error;
2355 break;
2356 case 'X':
2357 delete_remote = 1;
2358 break;
2359 default:
2360 usage_fetch();
2361 break;
2364 argc -= optind;
2365 argv += optind;
2367 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2368 option_conflict('a', 'b');
2369 if (list_refs_only) {
2370 if (!TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('l', 'b');
2372 if (fetch_all_branches)
2373 option_conflict('l', 'a');
2374 if (delete_refs)
2375 option_conflict('l', 'd');
2376 if (delete_remote)
2377 option_conflict('l', 'X');
2379 if (delete_remote) {
2380 if (fetch_all_branches)
2381 option_conflict('X', 'a');
2382 if (!TAILQ_EMPTY(&wanted_branches))
2383 option_conflict('X', 'b');
2384 if (delete_refs)
2385 option_conflict('X', 'd');
2386 if (replace_tags)
2387 option_conflict('X', 't');
2388 if (!TAILQ_EMPTY(&wanted_refs))
2389 option_conflict('X', 'R');
2392 if (argc == 0) {
2393 if (delete_remote)
2394 errx(1, "-X option requires a remote name");
2395 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2396 } else if (argc == 1)
2397 remote_name = argv[0];
2398 else
2399 usage_fetch();
2401 cwd = getcwd(NULL, 0);
2402 if (cwd == NULL) {
2403 error = got_error_from_errno("getcwd");
2404 goto done;
2407 error = got_repo_pack_fds_open(&pack_fds);
2408 if (error != NULL)
2409 goto done;
2411 if (repo_path == NULL) {
2412 error = got_worktree_open(&worktree, cwd);
2413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2414 goto done;
2415 else
2416 error = NULL;
2417 if (worktree) {
2418 repo_path =
2419 strdup(got_worktree_get_repo_path(worktree));
2420 if (repo_path == NULL)
2421 error = got_error_from_errno("strdup");
2422 if (error)
2423 goto done;
2424 } else {
2425 repo_path = strdup(cwd);
2426 if (repo_path == NULL) {
2427 error = got_error_from_errno("strdup");
2428 goto done;
2433 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2434 if (error)
2435 goto done;
2437 if (delete_remote) {
2438 error = delete_refs_for_remote(repo, remote_name);
2439 goto done; /* nothing else to do */
2442 if (worktree) {
2443 worktree_conf = got_worktree_get_gotconfig(worktree);
2444 if (worktree_conf) {
2445 got_gotconfig_get_remotes(&nremotes, &remotes,
2446 worktree_conf);
2447 for (i = 0; i < nremotes; i++) {
2448 if (strcmp(remotes[i].name, remote_name) == 0) {
2449 remote = &remotes[i];
2450 break;
2455 if (remote == NULL) {
2456 repo_conf = got_repo_get_gotconfig(repo);
2457 if (repo_conf) {
2458 got_gotconfig_get_remotes(&nremotes, &remotes,
2459 repo_conf);
2460 for (i = 0; i < nremotes; i++) {
2461 if (strcmp(remotes[i].name, remote_name) == 0) {
2462 remote = &remotes[i];
2463 break;
2468 if (remote == NULL) {
2469 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2470 for (i = 0; i < nremotes; i++) {
2471 if (strcmp(remotes[i].name, remote_name) == 0) {
2472 remote = &remotes[i];
2473 break;
2477 if (remote == NULL) {
2478 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2479 goto done;
2482 if (TAILQ_EMPTY(&wanted_branches)) {
2483 if (!fetch_all_branches)
2484 fetch_all_branches = remote->fetch_all_branches;
2485 for (i = 0; i < remote->nfetch_branches; i++) {
2486 got_pathlist_append(&wanted_branches,
2487 remote->fetch_branches[i], NULL);
2490 if (TAILQ_EMPTY(&wanted_refs)) {
2491 for (i = 0; i < remote->nfetch_refs; i++) {
2492 got_pathlist_append(&wanted_refs,
2493 remote->fetch_refs[i], NULL);
2497 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2498 &repo_name, remote->fetch_url);
2499 if (error)
2500 goto done;
2502 if (strcmp(proto, "git") == 0) {
2503 #ifndef PROFILE
2504 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2505 "sendfd dns inet unveil", NULL) == -1)
2506 err(1, "pledge");
2507 #endif
2508 } else if (strcmp(proto, "git+ssh") == 0 ||
2509 strcmp(proto, "ssh") == 0) {
2510 #ifndef PROFILE
2511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2512 "sendfd unveil", NULL) == -1)
2513 err(1, "pledge");
2514 #endif
2515 } else if (strcmp(proto, "http") == 0 ||
2516 strcmp(proto, "git+http") == 0) {
2517 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2518 goto done;
2519 } else {
2520 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2521 goto done;
2524 error = got_dial_apply_unveil(proto);
2525 if (error)
2526 goto done;
2528 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2529 if (error)
2530 goto done;
2532 if (verbosity >= 0)
2533 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2534 port ? ":" : "", port ? port : "");
2536 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2537 server_path, verbosity);
2538 if (error)
2539 goto done;
2541 fpa.last_scaled_size[0] = '\0';
2542 fpa.last_p_indexed = -1;
2543 fpa.last_p_resolved = -1;
2544 fpa.verbosity = verbosity;
2545 fpa.repo = repo;
2546 fpa.create_configs = 0;
2547 fpa.configs_created = 0;
2548 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2549 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2550 remote->mirror_references, fetch_all_branches, &wanted_branches,
2551 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2552 fetch_progress, &fpa);
2553 if (error)
2554 goto done;
2556 if (list_refs_only) {
2557 error = list_remote_refs(&symrefs, &refs);
2558 goto done;
2561 if (pack_hash == NULL) {
2562 if (verbosity >= 0)
2563 printf("Already up-to-date\n");
2564 } else if (verbosity >= 0) {
2565 error = got_object_id_str(&id_str, pack_hash);
2566 if (error)
2567 goto done;
2568 printf("\nFetched %s.pack\n", id_str);
2569 free(id_str);
2570 id_str = NULL;
2573 /* Update references provided with the pack file. */
2574 TAILQ_FOREACH(pe, &refs, entry) {
2575 const char *refname = pe->path;
2576 struct got_object_id *id = pe->data;
2577 struct got_reference *ref;
2578 char *remote_refname;
2580 if (is_wanted_ref(&wanted_refs, refname) &&
2581 !remote->mirror_references) {
2582 error = update_wanted_ref(refname, id,
2583 remote->name, verbosity, repo);
2584 if (error)
2585 goto done;
2586 continue;
2589 if (remote->mirror_references ||
2590 strncmp("refs/tags/", refname, 10) == 0) {
2591 error = got_ref_open(&ref, repo, refname, 1);
2592 if (error) {
2593 if (error->code != GOT_ERR_NOT_REF)
2594 goto done;
2595 error = create_ref(refname, id, verbosity,
2596 repo);
2597 if (error)
2598 goto done;
2599 } else {
2600 error = update_ref(ref, id, replace_tags,
2601 verbosity, repo);
2602 unlock_err = got_ref_unlock(ref);
2603 if (unlock_err && error == NULL)
2604 error = unlock_err;
2605 got_ref_close(ref);
2606 if (error)
2607 goto done;
2609 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2610 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2611 remote_name, refname + 11) == -1) {
2612 error = got_error_from_errno("asprintf");
2613 goto done;
2616 error = got_ref_open(&ref, repo, remote_refname, 1);
2617 if (error) {
2618 if (error->code != GOT_ERR_NOT_REF)
2619 goto done;
2620 error = create_ref(remote_refname, id,
2621 verbosity, repo);
2622 if (error)
2623 goto done;
2624 } else {
2625 error = update_ref(ref, id, replace_tags,
2626 verbosity, repo);
2627 unlock_err = got_ref_unlock(ref);
2628 if (unlock_err && error == NULL)
2629 error = unlock_err;
2630 got_ref_close(ref);
2631 if (error)
2632 goto done;
2635 /* Also create a local branch if none exists yet. */
2636 error = got_ref_open(&ref, repo, refname, 1);
2637 if (error) {
2638 if (error->code != GOT_ERR_NOT_REF)
2639 goto done;
2640 error = create_ref(refname, id, verbosity,
2641 repo);
2642 if (error)
2643 goto done;
2644 } else {
2645 unlock_err = got_ref_unlock(ref);
2646 if (unlock_err && error == NULL)
2647 error = unlock_err;
2648 got_ref_close(ref);
2652 if (delete_refs) {
2653 error = delete_missing_refs(&refs, &symrefs, remote,
2654 verbosity, repo);
2655 if (error)
2656 goto done;
2659 if (!remote->mirror_references) {
2660 /* Update remote HEAD reference if the server provided one. */
2661 TAILQ_FOREACH(pe, &symrefs, entry) {
2662 struct got_reference *target_ref;
2663 const char *refname = pe->path;
2664 const char *target = pe->data;
2665 char *remote_refname = NULL, *remote_target = NULL;
2667 if (strcmp(refname, GOT_REF_HEAD) != 0)
2668 continue;
2670 if (strncmp("refs/heads/", target, 11) != 0)
2671 continue;
2673 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2674 remote->name, refname) == -1) {
2675 error = got_error_from_errno("asprintf");
2676 goto done;
2678 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2679 remote->name, target + 11) == -1) {
2680 error = got_error_from_errno("asprintf");
2681 free(remote_refname);
2682 goto done;
2685 error = got_ref_open(&target_ref, repo, remote_target,
2686 0);
2687 if (error) {
2688 free(remote_refname);
2689 free(remote_target);
2690 if (error->code == GOT_ERR_NOT_REF) {
2691 error = NULL;
2692 continue;
2694 goto done;
2696 error = update_symref(remote_refname, target_ref,
2697 verbosity, repo);
2698 free(remote_refname);
2699 free(remote_target);
2700 got_ref_close(target_ref);
2701 if (error)
2702 goto done;
2705 done:
2706 if (fetchpid > 0) {
2707 if (kill(fetchpid, SIGTERM) == -1)
2708 error = got_error_from_errno("kill");
2709 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2710 error = got_error_from_errno("waitpid");
2712 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2713 error = got_error_from_errno("close");
2714 if (repo) {
2715 const struct got_error *close_err = got_repo_close(repo);
2716 if (error == NULL)
2717 error = close_err;
2719 if (worktree)
2720 got_worktree_close(worktree);
2721 if (pack_fds) {
2722 const struct got_error *pack_err =
2723 got_repo_pack_fds_close(pack_fds);
2724 if (error == NULL)
2725 error = pack_err;
2727 TAILQ_FOREACH(pe, &refs, entry) {
2728 free((void *)pe->path);
2729 free(pe->data);
2731 got_pathlist_free(&refs);
2732 TAILQ_FOREACH(pe, &symrefs, entry) {
2733 free((void *)pe->path);
2734 free(pe->data);
2736 got_pathlist_free(&symrefs);
2737 got_pathlist_free(&wanted_branches);
2738 got_pathlist_free(&wanted_refs);
2739 free(id_str);
2740 free(cwd);
2741 free(repo_path);
2742 free(pack_hash);
2743 free(proto);
2744 free(host);
2745 free(port);
2746 free(server_path);
2747 free(repo_name);
2748 return error;
2752 __dead static void
2753 usage_checkout(void)
2755 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2756 "[-p prefix] [-q] repository-path [worktree-path]\n",
2757 getprogname());
2758 exit(1);
2761 static void
2762 show_worktree_base_ref_warning(void)
2764 fprintf(stderr, "%s: warning: could not create a reference "
2765 "to the work tree's base commit; the commit could be "
2766 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2767 "repository writable and running 'got update' will prevent this\n",
2768 getprogname());
2771 struct got_checkout_progress_arg {
2772 const char *worktree_path;
2773 int had_base_commit_ref_error;
2774 int verbosity;
2777 static const struct got_error *
2778 checkout_progress(void *arg, unsigned char status, const char *path)
2780 struct got_checkout_progress_arg *a = arg;
2782 /* Base commit bump happens silently. */
2783 if (status == GOT_STATUS_BUMP_BASE)
2784 return NULL;
2786 if (status == GOT_STATUS_BASE_REF_ERR) {
2787 a->had_base_commit_ref_error = 1;
2788 return NULL;
2791 while (path[0] == '/')
2792 path++;
2794 if (a->verbosity >= 0)
2795 printf("%c %s/%s\n", status, a->worktree_path, path);
2797 return NULL;
2800 static const struct got_error *
2801 check_cancelled(void *arg)
2803 if (sigint_received || sigpipe_received)
2804 return got_error(GOT_ERR_CANCELLED);
2805 return NULL;
2808 static const struct got_error *
2809 check_linear_ancestry(struct got_object_id *commit_id,
2810 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2811 struct got_repository *repo)
2813 const struct got_error *err = NULL;
2814 struct got_object_id *yca_id;
2816 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2817 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2818 if (err)
2819 return err;
2821 if (yca_id == NULL)
2822 return got_error(GOT_ERR_ANCESTRY);
2825 * Require a straight line of history between the target commit
2826 * and the work tree's base commit.
2828 * Non-linear situations such as this require a rebase:
2830 * (commit) D F (base_commit)
2831 * \ /
2832 * C E
2833 * \ /
2834 * B (yca)
2835 * |
2836 * A
2838 * 'got update' only handles linear cases:
2839 * Update forwards in time: A (base/yca) - B - C - D (commit)
2840 * Update backwards in time: D (base) - C - B - A (commit/yca)
2842 if (allow_forwards_in_time_only) {
2843 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2844 return got_error(GOT_ERR_ANCESTRY);
2845 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2846 got_object_id_cmp(base_commit_id, yca_id) != 0)
2847 return got_error(GOT_ERR_ANCESTRY);
2849 free(yca_id);
2850 return NULL;
2853 static const struct got_error *
2854 check_same_branch(struct got_object_id *commit_id,
2855 struct got_reference *head_ref, struct got_object_id *yca_id,
2856 struct got_repository *repo)
2858 const struct got_error *err = NULL;
2859 struct got_commit_graph *graph = NULL;
2860 struct got_object_id *head_commit_id = NULL;
2861 int is_same_branch = 0;
2863 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2864 if (err)
2865 goto done;
2867 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2868 is_same_branch = 1;
2869 goto done;
2871 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2872 is_same_branch = 1;
2873 goto done;
2876 err = got_commit_graph_open(&graph, "/", 1);
2877 if (err)
2878 goto done;
2880 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2881 check_cancelled, NULL);
2882 if (err)
2883 goto done;
2885 for (;;) {
2886 struct got_object_id *id;
2887 err = got_commit_graph_iter_next(&id, graph, repo,
2888 check_cancelled, NULL);
2889 if (err) {
2890 if (err->code == GOT_ERR_ITER_COMPLETED)
2891 err = NULL;
2892 break;
2895 if (id) {
2896 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2897 break;
2898 if (got_object_id_cmp(id, commit_id) == 0) {
2899 is_same_branch = 1;
2900 break;
2904 done:
2905 if (graph)
2906 got_commit_graph_close(graph);
2907 free(head_commit_id);
2908 if (!err && !is_same_branch)
2909 err = got_error(GOT_ERR_ANCESTRY);
2910 return err;
2913 static const struct got_error *
2914 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2916 static char msg[512];
2917 const char *branch_name;
2919 if (got_ref_is_symbolic(ref))
2920 branch_name = got_ref_get_symref_target(ref);
2921 else
2922 branch_name = got_ref_get_name(ref);
2924 if (strncmp("refs/heads/", branch_name, 11) == 0)
2925 branch_name += 11;
2927 snprintf(msg, sizeof(msg),
2928 "target commit is not contained in branch '%s'; "
2929 "the branch to use must be specified with -b; "
2930 "if necessary a new branch can be created for "
2931 "this commit with 'got branch -c %s BRANCH_NAME'",
2932 branch_name, commit_id_str);
2934 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2937 static const struct got_error *
2938 cmd_checkout(int argc, char *argv[])
2940 const struct got_error *error = NULL;
2941 struct got_repository *repo = NULL;
2942 struct got_reference *head_ref = NULL, *ref = NULL;
2943 struct got_worktree *worktree = NULL;
2944 char *repo_path = NULL;
2945 char *worktree_path = NULL;
2946 const char *path_prefix = "";
2947 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2948 char *commit_id_str = NULL;
2949 struct got_object_id *commit_id = NULL;
2950 char *cwd = NULL;
2951 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2952 struct got_pathlist_head paths;
2953 struct got_checkout_progress_arg cpa;
2954 int *pack_fds = NULL;
2956 TAILQ_INIT(&paths);
2958 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2959 switch (ch) {
2960 case 'b':
2961 branch_name = optarg;
2962 break;
2963 case 'c':
2964 commit_id_str = strdup(optarg);
2965 if (commit_id_str == NULL)
2966 return got_error_from_errno("strdup");
2967 break;
2968 case 'E':
2969 allow_nonempty = 1;
2970 break;
2971 case 'p':
2972 path_prefix = optarg;
2973 break;
2974 case 'q':
2975 verbosity = -1;
2976 break;
2977 default:
2978 usage_checkout();
2979 /* NOTREACHED */
2983 argc -= optind;
2984 argv += optind;
2986 #ifndef PROFILE
2987 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2988 "unveil", NULL) == -1)
2989 err(1, "pledge");
2990 #endif
2991 if (argc == 1) {
2992 char *base, *dotgit;
2993 const char *path;
2994 repo_path = realpath(argv[0], NULL);
2995 if (repo_path == NULL)
2996 return got_error_from_errno2("realpath", argv[0]);
2997 cwd = getcwd(NULL, 0);
2998 if (cwd == NULL) {
2999 error = got_error_from_errno("getcwd");
3000 goto done;
3002 if (path_prefix[0])
3003 path = path_prefix;
3004 else
3005 path = repo_path;
3006 error = got_path_basename(&base, path);
3007 if (error)
3008 goto done;
3009 dotgit = strstr(base, ".git");
3010 if (dotgit)
3011 *dotgit = '\0';
3012 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3013 error = got_error_from_errno("asprintf");
3014 free(base);
3015 goto done;
3017 free(base);
3018 } else if (argc == 2) {
3019 repo_path = realpath(argv[0], NULL);
3020 if (repo_path == NULL) {
3021 error = got_error_from_errno2("realpath", argv[0]);
3022 goto done;
3024 worktree_path = realpath(argv[1], NULL);
3025 if (worktree_path == NULL) {
3026 if (errno != ENOENT) {
3027 error = got_error_from_errno2("realpath",
3028 argv[1]);
3029 goto done;
3031 worktree_path = strdup(argv[1]);
3032 if (worktree_path == NULL) {
3033 error = got_error_from_errno("strdup");
3034 goto done;
3037 } else
3038 usage_checkout();
3040 got_path_strip_trailing_slashes(repo_path);
3041 got_path_strip_trailing_slashes(worktree_path);
3043 error = got_repo_pack_fds_open(&pack_fds);
3044 if (error != NULL)
3045 goto done;
3047 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3048 if (error != NULL)
3049 goto done;
3051 /* Pre-create work tree path for unveil(2) */
3052 error = got_path_mkdir(worktree_path);
3053 if (error) {
3054 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3055 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3056 goto done;
3057 if (!allow_nonempty &&
3058 !got_path_dir_is_empty(worktree_path)) {
3059 error = got_error_path(worktree_path,
3060 GOT_ERR_DIR_NOT_EMPTY);
3061 goto done;
3065 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3066 if (error)
3067 goto done;
3069 error = got_ref_open(&head_ref, repo, branch_name, 0);
3070 if (error != NULL)
3071 goto done;
3073 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3074 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3075 goto done;
3077 error = got_worktree_open(&worktree, worktree_path);
3078 if (error != NULL)
3079 goto done;
3081 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3082 path_prefix);
3083 if (error != NULL)
3084 goto done;
3085 if (!same_path_prefix) {
3086 error = got_error(GOT_ERR_PATH_PREFIX);
3087 goto done;
3090 if (commit_id_str) {
3091 struct got_reflist_head refs;
3092 TAILQ_INIT(&refs);
3093 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3094 NULL);
3095 if (error)
3096 goto done;
3097 error = got_repo_match_object_id(&commit_id, NULL,
3098 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3099 got_ref_list_free(&refs);
3100 if (error)
3101 goto done;
3102 error = check_linear_ancestry(commit_id,
3103 got_worktree_get_base_commit_id(worktree), 0, repo);
3104 if (error != NULL) {
3105 if (error->code == GOT_ERR_ANCESTRY) {
3106 error = checkout_ancestry_error(
3107 head_ref, commit_id_str);
3109 goto done;
3111 error = check_same_branch(commit_id, head_ref, NULL, repo);
3112 if (error) {
3113 if (error->code == GOT_ERR_ANCESTRY) {
3114 error = checkout_ancestry_error(
3115 head_ref, commit_id_str);
3117 goto done;
3119 error = got_worktree_set_base_commit_id(worktree, repo,
3120 commit_id);
3121 if (error)
3122 goto done;
3123 /* Expand potentially abbreviated commit ID string. */
3124 free(commit_id_str);
3125 error = got_object_id_str(&commit_id_str, commit_id);
3126 if (error)
3127 goto done;
3128 } else {
3129 commit_id = got_object_id_dup(
3130 got_worktree_get_base_commit_id(worktree));
3131 if (commit_id == NULL) {
3132 error = got_error_from_errno("got_object_id_dup");
3133 goto done;
3135 error = got_object_id_str(&commit_id_str, commit_id);
3136 if (error)
3137 goto done;
3140 error = got_pathlist_append(&paths, "", NULL);
3141 if (error)
3142 goto done;
3143 cpa.worktree_path = worktree_path;
3144 cpa.had_base_commit_ref_error = 0;
3145 cpa.verbosity = verbosity;
3146 error = got_worktree_checkout_files(worktree, &paths, repo,
3147 checkout_progress, &cpa, check_cancelled, NULL);
3148 if (error != NULL)
3149 goto done;
3151 if (got_ref_is_symbolic(head_ref)) {
3152 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3153 if (error)
3154 goto done;
3155 refname = got_ref_get_name(ref);
3156 } else
3157 refname = got_ref_get_name(head_ref);
3158 printf("Checked out %s: %s\n", refname, commit_id_str);
3159 printf("Now shut up and hack\n");
3160 if (cpa.had_base_commit_ref_error)
3161 show_worktree_base_ref_warning();
3162 done:
3163 if (pack_fds) {
3164 const struct got_error *pack_err =
3165 got_repo_pack_fds_close(pack_fds);
3166 if (error == NULL)
3167 error = pack_err;
3169 if (head_ref)
3170 got_ref_close(head_ref);
3171 if (ref)
3172 got_ref_close(ref);
3173 got_pathlist_free(&paths);
3174 free(commit_id_str);
3175 free(commit_id);
3176 free(repo_path);
3177 free(worktree_path);
3178 free(cwd);
3179 return error;
3182 struct got_update_progress_arg {
3183 int did_something;
3184 int conflicts;
3185 int obstructed;
3186 int not_updated;
3187 int missing;
3188 int not_deleted;
3189 int unversioned;
3190 int verbosity;
3193 static void
3194 print_update_progress_stats(struct got_update_progress_arg *upa)
3196 if (!upa->did_something)
3197 return;
3199 if (upa->conflicts > 0)
3200 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3201 if (upa->obstructed > 0)
3202 printf("File paths obstructed by a non-regular file: %d\n",
3203 upa->obstructed);
3204 if (upa->not_updated > 0)
3205 printf("Files not updated because of existing merge "
3206 "conflicts: %d\n", upa->not_updated);
3210 * The meaning of some status codes differs between merge-style operations and
3211 * update operations. For example, the ! status code means "file was missing"
3212 * if changes were merged into the work tree, and "missing file was restored"
3213 * if the work tree was updated. This function should be used by any operation
3214 * which merges changes into the work tree without updating the work tree.
3216 static void
3217 print_merge_progress_stats(struct got_update_progress_arg *upa)
3219 if (!upa->did_something)
3220 return;
3222 if (upa->conflicts > 0)
3223 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3224 if (upa->obstructed > 0)
3225 printf("File paths obstructed by a non-regular file: %d\n",
3226 upa->obstructed);
3227 if (upa->missing > 0)
3228 printf("Files which had incoming changes but could not be "
3229 "found in the work tree: %d\n", upa->missing);
3230 if (upa->not_deleted > 0)
3231 printf("Files not deleted due to differences in deleted "
3232 "content: %d\n", upa->not_deleted);
3233 if (upa->unversioned > 0)
3234 printf("Files not merged because an unversioned file was "
3235 "found in the work tree: %d\n", upa->unversioned);
3238 __dead static void
3239 usage_update(void)
3241 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3242 "[path ...]\n",
3243 getprogname());
3244 exit(1);
3247 static const struct got_error *
3248 update_progress(void *arg, unsigned char status, const char *path)
3250 struct got_update_progress_arg *upa = arg;
3252 if (status == GOT_STATUS_EXISTS ||
3253 status == GOT_STATUS_BASE_REF_ERR)
3254 return NULL;
3256 upa->did_something = 1;
3258 /* Base commit bump happens silently. */
3259 if (status == GOT_STATUS_BUMP_BASE)
3260 return NULL;
3262 if (status == GOT_STATUS_CONFLICT)
3263 upa->conflicts++;
3264 if (status == GOT_STATUS_OBSTRUCTED)
3265 upa->obstructed++;
3266 if (status == GOT_STATUS_CANNOT_UPDATE)
3267 upa->not_updated++;
3268 if (status == GOT_STATUS_MISSING)
3269 upa->missing++;
3270 if (status == GOT_STATUS_CANNOT_DELETE)
3271 upa->not_deleted++;
3272 if (status == GOT_STATUS_UNVERSIONED)
3273 upa->unversioned++;
3275 while (path[0] == '/')
3276 path++;
3277 if (upa->verbosity >= 0)
3278 printf("%c %s\n", status, path);
3280 return NULL;
3283 static const struct got_error *
3284 switch_head_ref(struct got_reference *head_ref,
3285 struct got_object_id *commit_id, struct got_worktree *worktree,
3286 struct got_repository *repo)
3288 const struct got_error *err = NULL;
3289 char *base_id_str;
3290 int ref_has_moved = 0;
3292 /* Trivial case: switching between two different references. */
3293 if (strcmp(got_ref_get_name(head_ref),
3294 got_worktree_get_head_ref_name(worktree)) != 0) {
3295 printf("Switching work tree from %s to %s\n",
3296 got_worktree_get_head_ref_name(worktree),
3297 got_ref_get_name(head_ref));
3298 return got_worktree_set_head_ref(worktree, head_ref);
3301 err = check_linear_ancestry(commit_id,
3302 got_worktree_get_base_commit_id(worktree), 0, repo);
3303 if (err) {
3304 if (err->code != GOT_ERR_ANCESTRY)
3305 return err;
3306 ref_has_moved = 1;
3308 if (!ref_has_moved)
3309 return NULL;
3311 /* Switching to a rebased branch with the same reference name. */
3312 err = got_object_id_str(&base_id_str,
3313 got_worktree_get_base_commit_id(worktree));
3314 if (err)
3315 return err;
3316 printf("Reference %s now points at a different branch\n",
3317 got_worktree_get_head_ref_name(worktree));
3318 printf("Switching work tree from %s to %s\n", base_id_str,
3319 got_worktree_get_head_ref_name(worktree));
3320 return NULL;
3323 static const struct got_error *
3324 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3326 const struct got_error *err;
3327 int in_progress;
3329 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3330 if (err)
3331 return err;
3332 if (in_progress)
3333 return got_error(GOT_ERR_REBASING);
3335 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3336 if (err)
3337 return err;
3338 if (in_progress)
3339 return got_error(GOT_ERR_HISTEDIT_BUSY);
3341 return NULL;
3344 static const struct got_error *
3345 check_merge_in_progress(struct got_worktree *worktree,
3346 struct got_repository *repo)
3348 const struct got_error *err;
3349 int in_progress;
3351 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3352 if (err)
3353 return err;
3354 if (in_progress)
3355 return got_error(GOT_ERR_MERGE_BUSY);
3357 return NULL;
3360 static const struct got_error *
3361 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3362 char *argv[], struct got_worktree *worktree)
3364 const struct got_error *err = NULL;
3365 char *path;
3366 struct got_pathlist_entry *new;
3367 int i;
3369 if (argc == 0) {
3370 path = strdup("");
3371 if (path == NULL)
3372 return got_error_from_errno("strdup");
3373 return got_pathlist_append(paths, path, NULL);
3376 for (i = 0; i < argc; i++) {
3377 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3378 if (err)
3379 break;
3380 err = got_pathlist_insert(&new, paths, path, NULL);
3381 if (err || new == NULL /* duplicate */) {
3382 free(path);
3383 if (err)
3384 break;
3388 return err;
3391 static const struct got_error *
3392 wrap_not_worktree_error(const struct got_error *orig_err,
3393 const char *cmdname, const char *path)
3395 const struct got_error *err;
3396 struct got_repository *repo;
3397 static char msg[512];
3398 int *pack_fds = NULL;
3400 err = got_repo_pack_fds_open(&pack_fds);
3401 if (err)
3402 return err;
3404 err = got_repo_open(&repo, path, NULL, pack_fds);
3405 if (err)
3406 return orig_err;
3408 snprintf(msg, sizeof(msg),
3409 "'got %s' needs a work tree in addition to a git repository\n"
3410 "Work trees can be checked out from this Git repository with "
3411 "'got checkout'.\n"
3412 "The got(1) manual page contains more information.", cmdname);
3413 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3414 got_repo_close(repo);
3415 if (pack_fds) {
3416 const struct got_error *pack_err =
3417 got_repo_pack_fds_close(pack_fds);
3418 if (err == NULL)
3419 err = pack_err;
3421 return err;
3424 static const struct got_error *
3425 cmd_update(int argc, char *argv[])
3427 const struct got_error *error = NULL;
3428 struct got_repository *repo = NULL;
3429 struct got_worktree *worktree = NULL;
3430 char *worktree_path = NULL;
3431 struct got_object_id *commit_id = NULL;
3432 char *commit_id_str = NULL;
3433 const char *branch_name = NULL;
3434 struct got_reference *head_ref = NULL;
3435 struct got_pathlist_head paths;
3436 struct got_pathlist_entry *pe;
3437 int ch, verbosity = 0;
3438 struct got_update_progress_arg upa;
3439 int *pack_fds = NULL;
3441 TAILQ_INIT(&paths);
3443 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3444 switch (ch) {
3445 case 'b':
3446 branch_name = optarg;
3447 break;
3448 case 'c':
3449 commit_id_str = strdup(optarg);
3450 if (commit_id_str == NULL)
3451 return got_error_from_errno("strdup");
3452 break;
3453 case 'q':
3454 verbosity = -1;
3455 break;
3456 default:
3457 usage_update();
3458 /* NOTREACHED */
3462 argc -= optind;
3463 argv += optind;
3465 #ifndef PROFILE
3466 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3467 "unveil", NULL) == -1)
3468 err(1, "pledge");
3469 #endif
3470 worktree_path = getcwd(NULL, 0);
3471 if (worktree_path == NULL) {
3472 error = got_error_from_errno("getcwd");
3473 goto done;
3476 error = got_repo_pack_fds_open(&pack_fds);
3477 if (error != NULL)
3478 goto done;
3480 error = got_worktree_open(&worktree, worktree_path);
3481 if (error) {
3482 if (error->code == GOT_ERR_NOT_WORKTREE)
3483 error = wrap_not_worktree_error(error, "update",
3484 worktree_path);
3485 goto done;
3488 error = check_rebase_or_histedit_in_progress(worktree);
3489 if (error)
3490 goto done;
3492 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3493 NULL, pack_fds);
3494 if (error != NULL)
3495 goto done;
3497 error = apply_unveil(got_repo_get_path(repo), 0,
3498 got_worktree_get_root_path(worktree));
3499 if (error)
3500 goto done;
3502 error = check_merge_in_progress(worktree, repo);
3503 if (error)
3504 goto done;
3506 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3507 if (error)
3508 goto done;
3510 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3511 got_worktree_get_head_ref_name(worktree), 0);
3512 if (error != NULL)
3513 goto done;
3514 if (commit_id_str == NULL) {
3515 error = got_ref_resolve(&commit_id, repo, head_ref);
3516 if (error != NULL)
3517 goto done;
3518 error = got_object_id_str(&commit_id_str, commit_id);
3519 if (error != NULL)
3520 goto done;
3521 } else {
3522 struct got_reflist_head refs;
3523 TAILQ_INIT(&refs);
3524 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3525 NULL);
3526 if (error)
3527 goto done;
3528 error = got_repo_match_object_id(&commit_id, NULL,
3529 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3530 got_ref_list_free(&refs);
3531 free(commit_id_str);
3532 commit_id_str = NULL;
3533 if (error)
3534 goto done;
3535 error = got_object_id_str(&commit_id_str, commit_id);
3536 if (error)
3537 goto done;
3540 if (branch_name) {
3541 struct got_object_id *head_commit_id;
3542 TAILQ_FOREACH(pe, &paths, entry) {
3543 if (pe->path_len == 0)
3544 continue;
3545 error = got_error_msg(GOT_ERR_BAD_PATH,
3546 "switching between branches requires that "
3547 "the entire work tree gets updated");
3548 goto done;
3550 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3551 if (error)
3552 goto done;
3553 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3554 repo);
3555 free(head_commit_id);
3556 if (error != NULL)
3557 goto done;
3558 error = check_same_branch(commit_id, head_ref, NULL, repo);
3559 if (error)
3560 goto done;
3561 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3562 if (error)
3563 goto done;
3564 } else {
3565 error = check_linear_ancestry(commit_id,
3566 got_worktree_get_base_commit_id(worktree), 0, repo);
3567 if (error != NULL) {
3568 if (error->code == GOT_ERR_ANCESTRY)
3569 error = got_error(GOT_ERR_BRANCH_MOVED);
3570 goto done;
3572 error = check_same_branch(commit_id, head_ref, NULL, repo);
3573 if (error)
3574 goto done;
3577 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3578 commit_id) != 0) {
3579 error = got_worktree_set_base_commit_id(worktree, repo,
3580 commit_id);
3581 if (error)
3582 goto done;
3585 memset(&upa, 0, sizeof(upa));
3586 upa.verbosity = verbosity;
3587 error = got_worktree_checkout_files(worktree, &paths, repo,
3588 update_progress, &upa, check_cancelled, NULL);
3589 if (error != NULL)
3590 goto done;
3592 if (upa.did_something) {
3593 printf("Updated to %s: %s\n",
3594 got_worktree_get_head_ref_name(worktree), commit_id_str);
3595 } else
3596 printf("Already up-to-date\n");
3598 print_update_progress_stats(&upa);
3599 done:
3600 if (pack_fds) {
3601 const struct got_error *pack_err =
3602 got_repo_pack_fds_close(pack_fds);
3603 if (error == NULL)
3604 error = pack_err;
3606 free(worktree_path);
3607 TAILQ_FOREACH(pe, &paths, entry)
3608 free((char *)pe->path);
3609 got_pathlist_free(&paths);
3610 free(commit_id);
3611 free(commit_id_str);
3612 return error;
3615 static const struct got_error *
3616 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3617 const char *path, int diff_context, int ignore_whitespace,
3618 int force_text_diff, struct got_repository *repo, FILE *outfile)
3620 const struct got_error *err = NULL;
3621 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3622 FILE *f1 = NULL, *f2 = NULL;
3623 int fd1 = -1, fd2 = -1;
3625 fd1 = got_opentempfd();
3626 if (fd1 == -1)
3627 return got_error_from_errno("got_opentempfd");
3628 fd2 = got_opentempfd();
3629 if (fd2 == -1) {
3630 err = got_error_from_errno("got_opentempfd");
3631 goto done;
3634 if (blob_id1) {
3635 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3636 fd1);
3637 if (err)
3638 goto done;
3641 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3642 if (err)
3643 goto done;
3645 f1 = got_opentemp();
3646 if (f1 == NULL) {
3647 err = got_error_from_errno("got_opentemp");
3648 goto done;
3650 f2 = got_opentemp();
3651 if (f2 == NULL) {
3652 err = got_error_from_errno("got_opentemp");
3653 goto done;
3656 while (path[0] == '/')
3657 path++;
3658 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3659 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3660 force_text_diff, outfile);
3661 done:
3662 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3663 err = got_error_from_errno("close");
3664 if (blob1)
3665 got_object_blob_close(blob1);
3666 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3667 err = got_error_from_errno("close");
3668 got_object_blob_close(blob2);
3669 if (f1 && fclose(f1) == EOF && err == NULL)
3670 err = got_error_from_errno("fclose");
3671 if (f2 && fclose(f2) == EOF && err == NULL)
3672 err = got_error_from_errno("fclose");
3673 return err;
3676 static const struct got_error *
3677 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3678 const char *path, int diff_context, int ignore_whitespace,
3679 int force_text_diff, struct got_repository *repo, FILE *outfile)
3681 const struct got_error *err = NULL;
3682 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3683 struct got_diff_blob_output_unidiff_arg arg;
3684 FILE *f1 = NULL, *f2 = NULL;
3685 int fd1 = -1, fd2 = -1;
3687 if (tree_id1) {
3688 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3689 if (err)
3690 goto done;
3691 fd1 = got_opentempfd();
3692 if (fd1 == -1) {
3693 err = got_error_from_errno("got_opentempfd");
3694 goto done;
3698 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3699 if (err)
3700 goto done;
3702 f1 = got_opentemp();
3703 if (f1 == NULL) {
3704 err = got_error_from_errno("got_opentemp");
3705 goto done;
3708 f2 = got_opentemp();
3709 if (f2 == NULL) {
3710 err = got_error_from_errno("got_opentemp");
3711 goto done;
3713 fd2 = got_opentempfd();
3714 if (fd2 == -1) {
3715 err = got_error_from_errno("got_opentempfd");
3716 goto done;
3718 arg.diff_context = diff_context;
3719 arg.ignore_whitespace = ignore_whitespace;
3720 arg.force_text_diff = force_text_diff;
3721 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3722 arg.outfile = outfile;
3723 arg.line_offsets = NULL;
3724 arg.nlines = 0;
3725 while (path[0] == '/')
3726 path++;
3727 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3728 got_diff_blob_output_unidiff, &arg, 1);
3729 done:
3730 if (tree1)
3731 got_object_tree_close(tree1);
3732 if (tree2)
3733 got_object_tree_close(tree2);
3734 if (f1 && fclose(f1) == EOF && err == NULL)
3735 err = got_error_from_errno("fclose");
3736 if (f2 && fclose(f2) == EOF && err == NULL)
3737 err = got_error_from_errno("fclose");
3738 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3739 err = got_error_from_errno("close");
3740 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3741 err = got_error_from_errno("close");
3742 return err;
3745 static const struct got_error *
3746 get_changed_paths(struct got_pathlist_head *paths,
3747 struct got_commit_object *commit, struct got_repository *repo)
3749 const struct got_error *err = NULL;
3750 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3751 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3752 struct got_object_qid *qid;
3754 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3755 if (qid != NULL) {
3756 struct got_commit_object *pcommit;
3757 err = got_object_open_as_commit(&pcommit, repo,
3758 &qid->id);
3759 if (err)
3760 return err;
3762 tree_id1 = got_object_id_dup(
3763 got_object_commit_get_tree_id(pcommit));
3764 if (tree_id1 == NULL) {
3765 got_object_commit_close(pcommit);
3766 return got_error_from_errno("got_object_id_dup");
3768 got_object_commit_close(pcommit);
3772 if (tree_id1) {
3773 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3774 if (err)
3775 goto done;
3778 tree_id2 = got_object_commit_get_tree_id(commit);
3779 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3780 if (err)
3781 goto done;
3783 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3784 got_diff_tree_collect_changed_paths, paths, 0);
3785 done:
3786 if (tree1)
3787 got_object_tree_close(tree1);
3788 if (tree2)
3789 got_object_tree_close(tree2);
3790 free(tree_id1);
3791 return err;
3794 static const struct got_error *
3795 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3796 const char *path, int diff_context, struct got_repository *repo,
3797 FILE *outfile)
3799 const struct got_error *err = NULL;
3800 struct got_commit_object *pcommit = NULL;
3801 char *id_str1 = NULL, *id_str2 = NULL;
3802 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3803 struct got_object_qid *qid;
3805 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3806 if (qid != NULL) {
3807 err = got_object_open_as_commit(&pcommit, repo,
3808 &qid->id);
3809 if (err)
3810 return err;
3811 err = got_object_id_str(&id_str1, &qid->id);
3812 if (err)
3813 goto done;
3816 err = got_object_id_str(&id_str2, id);
3817 if (err)
3818 goto done;
3820 if (path && path[0] != '\0') {
3821 int obj_type;
3822 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3823 if (err)
3824 goto done;
3825 if (pcommit) {
3826 err = got_object_id_by_path(&obj_id1, repo,
3827 pcommit, path);
3828 if (err) {
3829 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3830 free(obj_id2);
3831 goto done;
3835 err = got_object_get_type(&obj_type, repo, obj_id2);
3836 if (err) {
3837 free(obj_id2);
3838 goto done;
3840 fprintf(outfile,
3841 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3842 fprintf(outfile, "commit - %s\n",
3843 id_str1 ? id_str1 : "/dev/null");
3844 fprintf(outfile, "commit + %s\n", id_str2);
3845 switch (obj_type) {
3846 case GOT_OBJ_TYPE_BLOB:
3847 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3848 0, 0, repo, outfile);
3849 break;
3850 case GOT_OBJ_TYPE_TREE:
3851 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3852 0, 0, repo, outfile);
3853 break;
3854 default:
3855 err = got_error(GOT_ERR_OBJ_TYPE);
3856 break;
3858 free(obj_id1);
3859 free(obj_id2);
3860 } else {
3861 obj_id2 = got_object_commit_get_tree_id(commit);
3862 if (pcommit)
3863 obj_id1 = got_object_commit_get_tree_id(pcommit);
3864 fprintf(outfile,
3865 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3866 fprintf(outfile, "commit - %s\n",
3867 id_str1 ? id_str1 : "/dev/null");
3868 fprintf(outfile, "commit + %s\n", id_str2);
3869 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3870 repo, outfile);
3872 done:
3873 free(id_str1);
3874 free(id_str2);
3875 if (pcommit)
3876 got_object_commit_close(pcommit);
3877 return err;
3880 static char *
3881 get_datestr(time_t *time, char *datebuf)
3883 struct tm mytm, *tm;
3884 char *p, *s;
3886 tm = gmtime_r(time, &mytm);
3887 if (tm == NULL)
3888 return NULL;
3889 s = asctime_r(tm, datebuf);
3890 if (s == NULL)
3891 return NULL;
3892 p = strchr(s, '\n');
3893 if (p)
3894 *p = '\0';
3895 return s;
3898 static const struct got_error *
3899 match_commit(int *have_match, struct got_object_id *id,
3900 struct got_commit_object *commit, regex_t *regex)
3902 const struct got_error *err = NULL;
3903 regmatch_t regmatch;
3904 char *id_str = NULL, *logmsg = NULL;
3906 *have_match = 0;
3908 err = got_object_id_str(&id_str, id);
3909 if (err)
3910 return err;
3912 err = got_object_commit_get_logmsg(&logmsg, commit);
3913 if (err)
3914 goto done;
3916 if (regexec(regex, got_object_commit_get_author(commit), 1,
3917 &regmatch, 0) == 0 ||
3918 regexec(regex, got_object_commit_get_committer(commit), 1,
3919 &regmatch, 0) == 0 ||
3920 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3921 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3922 *have_match = 1;
3923 done:
3924 free(id_str);
3925 free(logmsg);
3926 return err;
3929 static void
3930 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3931 regex_t *regex)
3933 regmatch_t regmatch;
3934 struct got_pathlist_entry *pe;
3936 *have_match = 0;
3938 TAILQ_FOREACH(pe, changed_paths, entry) {
3939 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3940 *have_match = 1;
3941 break;
3946 static const struct got_error *
3947 match_patch(int *have_match, struct got_commit_object *commit,
3948 struct got_object_id *id, const char *path, int diff_context,
3949 struct got_repository *repo, regex_t *regex, FILE *f)
3951 const struct got_error *err = NULL;
3952 char *line = NULL;
3953 size_t linesize = 0;
3954 ssize_t linelen;
3955 regmatch_t regmatch;
3957 *have_match = 0;
3959 err = got_opentemp_truncate(f);
3960 if (err)
3961 return err;
3963 err = print_patch(commit, id, path, diff_context, repo, f);
3964 if (err)
3965 goto done;
3967 if (fseeko(f, 0L, SEEK_SET) == -1) {
3968 err = got_error_from_errno("fseeko");
3969 goto done;
3972 while ((linelen = getline(&line, &linesize, f)) != -1) {
3973 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3974 *have_match = 1;
3975 break;
3978 done:
3979 free(line);
3980 return err;
3983 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3985 static const struct got_error*
3986 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3987 struct got_object_id *id, struct got_repository *repo,
3988 int local_only)
3990 static const struct got_error *err = NULL;
3991 struct got_reflist_entry *re;
3992 char *s;
3993 const char *name;
3995 *refs_str = NULL;
3997 TAILQ_FOREACH(re, refs, entry) {
3998 struct got_tag_object *tag = NULL;
3999 struct got_object_id *ref_id;
4000 int cmp;
4002 name = got_ref_get_name(re->ref);
4003 if (strcmp(name, GOT_REF_HEAD) == 0)
4004 continue;
4005 if (strncmp(name, "refs/", 5) == 0)
4006 name += 5;
4007 if (strncmp(name, "got/", 4) == 0)
4008 continue;
4009 if (strncmp(name, "heads/", 6) == 0)
4010 name += 6;
4011 if (strncmp(name, "remotes/", 8) == 0) {
4012 if (local_only)
4013 continue;
4014 name += 8;
4015 s = strstr(name, "/" GOT_REF_HEAD);
4016 if (s != NULL && s[strlen(s)] == '\0')
4017 continue;
4019 err = got_ref_resolve(&ref_id, repo, re->ref);
4020 if (err)
4021 break;
4022 if (strncmp(name, "tags/", 5) == 0) {
4023 err = got_object_open_as_tag(&tag, repo, ref_id);
4024 if (err) {
4025 if (err->code != GOT_ERR_OBJ_TYPE) {
4026 free(ref_id);
4027 break;
4029 /* Ref points at something other than a tag. */
4030 err = NULL;
4031 tag = NULL;
4034 cmp = got_object_id_cmp(tag ?
4035 got_object_tag_get_object_id(tag) : ref_id, id);
4036 free(ref_id);
4037 if (tag)
4038 got_object_tag_close(tag);
4039 if (cmp != 0)
4040 continue;
4041 s = *refs_str;
4042 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4043 s ? ", " : "", name) == -1) {
4044 err = got_error_from_errno("asprintf");
4045 free(s);
4046 *refs_str = NULL;
4047 break;
4049 free(s);
4052 return err;
4055 static const struct got_error *
4056 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4057 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4059 const struct got_error *err = NULL;
4060 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4061 char *comma, *s, *nl;
4062 struct got_reflist_head *refs;
4063 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4064 struct tm tm;
4065 time_t committer_time;
4067 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4068 if (refs) {
4069 err = build_refs_str(&ref_str, refs, id, repo, 1);
4070 if (err)
4071 return err;
4073 /* Display the first matching ref only. */
4074 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4075 *comma = '\0';
4078 if (ref_str == NULL) {
4079 err = got_object_id_str(&id_str, id);
4080 if (err)
4081 return err;
4084 committer_time = got_object_commit_get_committer_time(commit);
4085 if (gmtime_r(&committer_time, &tm) == NULL) {
4086 err = got_error_from_errno("gmtime_r");
4087 goto done;
4089 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4090 err = got_error(GOT_ERR_NO_SPACE);
4091 goto done;
4094 err = got_object_commit_get_logmsg(&logmsg0, commit);
4095 if (err)
4096 goto done;
4098 s = logmsg0;
4099 while (isspace((unsigned char)s[0]))
4100 s++;
4102 nl = strchr(s, '\n');
4103 if (nl) {
4104 *nl = '\0';
4107 if (ref_str)
4108 printf("%s%-7s %s\n", datebuf, ref_str, s);
4109 else
4110 printf("%s%.7s %s\n", datebuf, id_str, s);
4112 if (fflush(stdout) != 0 && err == NULL)
4113 err = got_error_from_errno("fflush");
4114 done:
4115 free(id_str);
4116 free(ref_str);
4117 free(logmsg0);
4118 return err;
4121 static const struct got_error *
4122 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4123 struct got_repository *repo, const char *path,
4124 struct got_pathlist_head *changed_paths, int show_patch,
4125 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4126 const char *custom_refs_str)
4128 const struct got_error *err = NULL;
4129 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4130 char datebuf[26];
4131 time_t committer_time;
4132 const char *author, *committer;
4133 char *refs_str = NULL;
4135 err = got_object_id_str(&id_str, id);
4136 if (err)
4137 return err;
4139 if (custom_refs_str == NULL) {
4140 struct got_reflist_head *refs;
4141 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4142 if (refs) {
4143 err = build_refs_str(&refs_str, refs, id, repo, 0);
4144 if (err)
4145 goto done;
4149 printf(GOT_COMMIT_SEP_STR);
4150 if (custom_refs_str)
4151 printf("commit %s (%s)\n", id_str, custom_refs_str);
4152 else
4153 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4154 refs_str ? refs_str : "", refs_str ? ")" : "");
4155 free(id_str);
4156 id_str = NULL;
4157 free(refs_str);
4158 refs_str = NULL;
4159 printf("from: %s\n", got_object_commit_get_author(commit));
4160 committer_time = got_object_commit_get_committer_time(commit);
4161 datestr = get_datestr(&committer_time, datebuf);
4162 if (datestr)
4163 printf("date: %s UTC\n", datestr);
4164 author = got_object_commit_get_author(commit);
4165 committer = got_object_commit_get_committer(commit);
4166 if (strcmp(author, committer) != 0)
4167 printf("via: %s\n", committer);
4168 if (got_object_commit_get_nparents(commit) > 1) {
4169 const struct got_object_id_queue *parent_ids;
4170 struct got_object_qid *qid;
4171 int n = 1;
4172 parent_ids = got_object_commit_get_parent_ids(commit);
4173 STAILQ_FOREACH(qid, parent_ids, entry) {
4174 err = got_object_id_str(&id_str, &qid->id);
4175 if (err)
4176 goto done;
4177 printf("parent %d: %s\n", n++, id_str);
4178 free(id_str);
4179 id_str = NULL;
4183 err = got_object_commit_get_logmsg(&logmsg0, commit);
4184 if (err)
4185 goto done;
4187 logmsg = logmsg0;
4188 do {
4189 line = strsep(&logmsg, "\n");
4190 if (line)
4191 printf(" %s\n", line);
4192 } while (line);
4193 free(logmsg0);
4195 if (changed_paths) {
4196 struct got_pathlist_entry *pe;
4197 TAILQ_FOREACH(pe, changed_paths, entry) {
4198 struct got_diff_changed_path *cp = pe->data;
4199 printf(" %c %s\n", cp->status, pe->path);
4201 printf("\n");
4203 if (show_patch) {
4204 err = print_patch(commit, id, path, diff_context, repo, stdout);
4205 if (err == 0)
4206 printf("\n");
4209 if (fflush(stdout) != 0 && err == NULL)
4210 err = got_error_from_errno("fflush");
4211 done:
4212 free(id_str);
4213 free(refs_str);
4214 return err;
4217 static const struct got_error *
4218 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4219 struct got_repository *repo, const char *path, int show_changed_paths,
4220 int show_patch, const char *search_pattern, int diff_context, int limit,
4221 int log_branches, int reverse_display_order,
4222 struct got_reflist_object_id_map *refs_idmap, int one_line,
4223 FILE *tmpfile)
4225 const struct got_error *err;
4226 struct got_commit_graph *graph;
4227 regex_t regex;
4228 int have_match;
4229 struct got_object_id_queue reversed_commits;
4230 struct got_object_qid *qid;
4231 struct got_commit_object *commit;
4232 struct got_pathlist_head changed_paths;
4233 struct got_pathlist_entry *pe;
4235 STAILQ_INIT(&reversed_commits);
4236 TAILQ_INIT(&changed_paths);
4238 if (search_pattern && regcomp(&regex, search_pattern,
4239 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4240 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4242 err = got_commit_graph_open(&graph, path, !log_branches);
4243 if (err)
4244 return err;
4245 err = got_commit_graph_iter_start(graph, root_id, repo,
4246 check_cancelled, NULL);
4247 if (err)
4248 goto done;
4249 for (;;) {
4250 struct got_object_id *id;
4252 if (sigint_received || sigpipe_received)
4253 break;
4255 err = got_commit_graph_iter_next(&id, graph, repo,
4256 check_cancelled, NULL);
4257 if (err) {
4258 if (err->code == GOT_ERR_ITER_COMPLETED)
4259 err = NULL;
4260 break;
4262 if (id == NULL)
4263 break;
4265 err = got_object_open_as_commit(&commit, repo, id);
4266 if (err)
4267 break;
4269 if (show_changed_paths && !reverse_display_order) {
4270 err = get_changed_paths(&changed_paths, commit, repo);
4271 if (err)
4272 break;
4275 if (search_pattern) {
4276 err = match_commit(&have_match, id, commit, &regex);
4277 if (err) {
4278 got_object_commit_close(commit);
4279 break;
4281 if (have_match == 0 && show_changed_paths)
4282 match_changed_paths(&have_match,
4283 &changed_paths, &regex);
4284 if (have_match == 0 && show_patch) {
4285 err = match_patch(&have_match, commit, id,
4286 path, diff_context, repo, &regex,
4287 tmpfile);
4288 if (err)
4289 break;
4291 if (have_match == 0) {
4292 got_object_commit_close(commit);
4293 TAILQ_FOREACH(pe, &changed_paths, entry) {
4294 free((char *)pe->path);
4295 free(pe->data);
4297 got_pathlist_free(&changed_paths);
4298 continue;
4302 if (reverse_display_order) {
4303 err = got_object_qid_alloc(&qid, id);
4304 if (err)
4305 break;
4306 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4307 got_object_commit_close(commit);
4308 } else {
4309 if (one_line)
4310 err = print_commit_oneline(commit, id,
4311 repo, refs_idmap);
4312 else
4313 err = print_commit(commit, id, repo, path,
4314 show_changed_paths ? &changed_paths : NULL,
4315 show_patch, diff_context, refs_idmap, NULL);
4316 got_object_commit_close(commit);
4317 if (err)
4318 break;
4320 if ((limit && --limit == 0) ||
4321 (end_id && got_object_id_cmp(id, end_id) == 0))
4322 break;
4324 TAILQ_FOREACH(pe, &changed_paths, entry) {
4325 free((char *)pe->path);
4326 free(pe->data);
4328 got_pathlist_free(&changed_paths);
4330 if (reverse_display_order) {
4331 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4332 err = got_object_open_as_commit(&commit, repo,
4333 &qid->id);
4334 if (err)
4335 break;
4336 if (show_changed_paths) {
4337 err = get_changed_paths(&changed_paths,
4338 commit, repo);
4339 if (err)
4340 break;
4342 if (one_line)
4343 err = print_commit_oneline(commit, &qid->id,
4344 repo, refs_idmap);
4345 else
4346 err = print_commit(commit, &qid->id, repo, path,
4347 show_changed_paths ? &changed_paths : NULL,
4348 show_patch, diff_context, refs_idmap, NULL);
4349 got_object_commit_close(commit);
4350 if (err)
4351 break;
4352 TAILQ_FOREACH(pe, &changed_paths, entry) {
4353 free((char *)pe->path);
4354 free(pe->data);
4356 got_pathlist_free(&changed_paths);
4359 done:
4360 while (!STAILQ_EMPTY(&reversed_commits)) {
4361 qid = STAILQ_FIRST(&reversed_commits);
4362 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4363 got_object_qid_free(qid);
4365 TAILQ_FOREACH(pe, &changed_paths, entry) {
4366 free((char *)pe->path);
4367 free(pe->data);
4369 got_pathlist_free(&changed_paths);
4370 if (search_pattern)
4371 regfree(&regex);
4372 got_commit_graph_close(graph);
4373 return err;
4376 __dead static void
4377 usage_log(void)
4379 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4380 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4381 "[-r repository-path] [-R] [path]\n", getprogname());
4382 exit(1);
4385 static int
4386 get_default_log_limit(void)
4388 const char *got_default_log_limit;
4389 long long n;
4390 const char *errstr;
4392 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4393 if (got_default_log_limit == NULL)
4394 return 0;
4395 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4396 if (errstr != NULL)
4397 return 0;
4398 return n;
4401 static const struct got_error *
4402 cmd_log(int argc, char *argv[])
4404 const struct got_error *error;
4405 struct got_repository *repo = NULL;
4406 struct got_worktree *worktree = NULL;
4407 struct got_object_id *start_id = NULL, *end_id = NULL;
4408 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4409 const char *start_commit = NULL, *end_commit = NULL;
4410 const char *search_pattern = NULL;
4411 int diff_context = -1, ch;
4412 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4413 int reverse_display_order = 0, one_line = 0;
4414 const char *errstr;
4415 struct got_reflist_head refs;
4416 struct got_reflist_object_id_map *refs_idmap = NULL;
4417 FILE *tmpfile = NULL;
4418 int *pack_fds = NULL;
4420 TAILQ_INIT(&refs);
4422 #ifndef PROFILE
4423 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4424 NULL)
4425 == -1)
4426 err(1, "pledge");
4427 #endif
4429 limit = get_default_log_limit();
4431 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4432 switch (ch) {
4433 case 'p':
4434 show_patch = 1;
4435 break;
4436 case 'P':
4437 show_changed_paths = 1;
4438 break;
4439 case 'c':
4440 start_commit = optarg;
4441 break;
4442 case 'C':
4443 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4444 &errstr);
4445 if (errstr != NULL)
4446 errx(1, "number of context lines is %s: %s",
4447 errstr, optarg);
4448 break;
4449 case 'l':
4450 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4451 if (errstr != NULL)
4452 errx(1, "number of commits is %s: %s",
4453 errstr, optarg);
4454 break;
4455 case 'b':
4456 log_branches = 1;
4457 break;
4458 case 'r':
4459 repo_path = realpath(optarg, NULL);
4460 if (repo_path == NULL)
4461 return got_error_from_errno2("realpath",
4462 optarg);
4463 got_path_strip_trailing_slashes(repo_path);
4464 break;
4465 case 'R':
4466 reverse_display_order = 1;
4467 break;
4468 case 's':
4469 one_line = 1;
4470 break;
4471 case 'S':
4472 search_pattern = optarg;
4473 break;
4474 case 'x':
4475 end_commit = optarg;
4476 break;
4477 default:
4478 usage_log();
4479 /* NOTREACHED */
4483 argc -= optind;
4484 argv += optind;
4486 if (diff_context == -1)
4487 diff_context = 3;
4488 else if (!show_patch)
4489 errx(1, "-C requires -p");
4491 if (one_line && (show_patch || show_changed_paths))
4492 errx(1, "cannot use -s with -p or -P");
4494 cwd = getcwd(NULL, 0);
4495 if (cwd == NULL) {
4496 error = got_error_from_errno("getcwd");
4497 goto done;
4500 error = got_repo_pack_fds_open(&pack_fds);
4501 if (error != NULL)
4502 goto done;
4504 if (repo_path == NULL) {
4505 error = got_worktree_open(&worktree, cwd);
4506 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4507 goto done;
4508 error = NULL;
4511 if (argc == 1) {
4512 if (worktree) {
4513 error = got_worktree_resolve_path(&path, worktree,
4514 argv[0]);
4515 if (error)
4516 goto done;
4517 } else {
4518 path = strdup(argv[0]);
4519 if (path == NULL) {
4520 error = got_error_from_errno("strdup");
4521 goto done;
4524 } else if (argc != 0)
4525 usage_log();
4527 if (repo_path == NULL) {
4528 repo_path = worktree ?
4529 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4531 if (repo_path == NULL) {
4532 error = got_error_from_errno("strdup");
4533 goto done;
4536 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4537 if (error != NULL)
4538 goto done;
4540 error = apply_unveil(got_repo_get_path(repo), 1,
4541 worktree ? got_worktree_get_root_path(worktree) : NULL);
4542 if (error)
4543 goto done;
4545 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4546 if (error)
4547 goto done;
4549 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4550 if (error)
4551 goto done;
4553 if (start_commit == NULL) {
4554 struct got_reference *head_ref;
4555 struct got_commit_object *commit = NULL;
4556 error = got_ref_open(&head_ref, repo,
4557 worktree ? got_worktree_get_head_ref_name(worktree)
4558 : GOT_REF_HEAD, 0);
4559 if (error != NULL)
4560 goto done;
4561 error = got_ref_resolve(&start_id, repo, head_ref);
4562 got_ref_close(head_ref);
4563 if (error != NULL)
4564 goto done;
4565 error = got_object_open_as_commit(&commit, repo,
4566 start_id);
4567 if (error != NULL)
4568 goto done;
4569 got_object_commit_close(commit);
4570 } else {
4571 error = got_repo_match_object_id(&start_id, NULL,
4572 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4573 if (error != NULL)
4574 goto done;
4576 if (end_commit != NULL) {
4577 error = got_repo_match_object_id(&end_id, NULL,
4578 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4579 if (error != NULL)
4580 goto done;
4583 if (worktree) {
4585 * If a path was specified on the command line it was resolved
4586 * to a path in the work tree above. Prepend the work tree's
4587 * path prefix to obtain the corresponding in-repository path.
4589 if (path) {
4590 const char *prefix;
4591 prefix = got_worktree_get_path_prefix(worktree);
4592 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4593 (path[0] != '\0') ? "/" : "", path) == -1) {
4594 error = got_error_from_errno("asprintf");
4595 goto done;
4598 } else
4599 error = got_repo_map_path(&in_repo_path, repo,
4600 path ? path : "");
4601 if (error != NULL)
4602 goto done;
4603 if (in_repo_path) {
4604 free(path);
4605 path = in_repo_path;
4608 if (worktree) {
4609 /* Release work tree lock. */
4610 got_worktree_close(worktree);
4611 worktree = NULL;
4614 if (search_pattern && show_patch) {
4615 tmpfile = got_opentemp();
4616 if (tmpfile == NULL) {
4617 error = got_error_from_errno("got_opentemp");
4618 goto done;
4622 error = print_commits(start_id, end_id, repo, path ? path : "",
4623 show_changed_paths, show_patch, search_pattern, diff_context,
4624 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4625 tmpfile);
4626 done:
4627 free(path);
4628 free(repo_path);
4629 free(cwd);
4630 if (worktree)
4631 got_worktree_close(worktree);
4632 if (repo) {
4633 const struct got_error *close_err = got_repo_close(repo);
4634 if (error == NULL)
4635 error = close_err;
4637 if (pack_fds) {
4638 const struct got_error *pack_err =
4639 got_repo_pack_fds_close(pack_fds);
4640 if (error == NULL)
4641 error = pack_err;
4643 if (refs_idmap)
4644 got_reflist_object_id_map_free(refs_idmap);
4645 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4646 error = got_error_from_errno("fclose");
4647 got_ref_list_free(&refs);
4648 return error;
4651 __dead static void
4652 usage_diff(void)
4654 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4655 "[-r repository-path] [-s] [-w] [-P] "
4656 "[object1 object2 | path ...]\n", getprogname());
4657 exit(1);
4660 struct print_diff_arg {
4661 struct got_repository *repo;
4662 struct got_worktree *worktree;
4663 int diff_context;
4664 const char *id_str;
4665 int header_shown;
4666 int diff_staged;
4667 enum got_diff_algorithm diff_algo;
4668 int ignore_whitespace;
4669 int force_text_diff;
4670 FILE *f1;
4671 FILE *f2;
4675 * Create a file which contains the target path of a symlink so we can feed
4676 * it as content to the diff engine.
4678 static const struct got_error *
4679 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4680 const char *abspath)
4682 const struct got_error *err = NULL;
4683 char target_path[PATH_MAX];
4684 ssize_t target_len, outlen;
4686 *fd = -1;
4688 if (dirfd != -1) {
4689 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4690 if (target_len == -1)
4691 return got_error_from_errno2("readlinkat", abspath);
4692 } else {
4693 target_len = readlink(abspath, target_path, PATH_MAX);
4694 if (target_len == -1)
4695 return got_error_from_errno2("readlink", abspath);
4698 *fd = got_opentempfd();
4699 if (*fd == -1)
4700 return got_error_from_errno("got_opentempfd");
4702 outlen = write(*fd, target_path, target_len);
4703 if (outlen == -1) {
4704 err = got_error_from_errno("got_opentempfd");
4705 goto done;
4708 if (lseek(*fd, 0, SEEK_SET) == -1) {
4709 err = got_error_from_errno2("lseek", abspath);
4710 goto done;
4712 done:
4713 if (err) {
4714 close(*fd);
4715 *fd = -1;
4717 return err;
4720 static const struct got_error *
4721 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4722 const char *path, struct got_object_id *blob_id,
4723 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4724 int dirfd, const char *de_name)
4726 struct print_diff_arg *a = arg;
4727 const struct got_error *err = NULL;
4728 struct got_blob_object *blob1 = NULL;
4729 int fd = -1, fd1 = -1, fd2 = -1;
4730 FILE *f2 = NULL;
4731 char *abspath = NULL, *label1 = NULL;
4732 struct stat sb;
4733 off_t size1 = 0;
4734 int f2_exists = 1;
4736 if (a->diff_staged) {
4737 if (staged_status != GOT_STATUS_MODIFY &&
4738 staged_status != GOT_STATUS_ADD &&
4739 staged_status != GOT_STATUS_DELETE)
4740 return NULL;
4741 } else {
4742 if (staged_status == GOT_STATUS_DELETE)
4743 return NULL;
4744 if (status == GOT_STATUS_NONEXISTENT)
4745 return got_error_set_errno(ENOENT, path);
4746 if (status != GOT_STATUS_MODIFY &&
4747 status != GOT_STATUS_ADD &&
4748 status != GOT_STATUS_DELETE &&
4749 status != GOT_STATUS_CONFLICT)
4750 return NULL;
4753 err = got_opentemp_truncate(a->f1);
4754 if (err)
4755 return got_error_from_errno("got_opentemp_truncate");
4756 err = got_opentemp_truncate(a->f2);
4757 if (err)
4758 return got_error_from_errno("got_opentemp_truncate");
4760 if (!a->header_shown) {
4761 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4762 got_worktree_get_root_path(a->worktree));
4763 printf("commit - %s\n", a->id_str);
4764 printf("path + %s%s\n",
4765 got_worktree_get_root_path(a->worktree),
4766 a->diff_staged ? " (staged changes)" : "");
4767 a->header_shown = 1;
4770 if (a->diff_staged) {
4771 const char *label1 = NULL, *label2 = NULL;
4772 switch (staged_status) {
4773 case GOT_STATUS_MODIFY:
4774 label1 = path;
4775 label2 = path;
4776 break;
4777 case GOT_STATUS_ADD:
4778 label2 = path;
4779 break;
4780 case GOT_STATUS_DELETE:
4781 label1 = path;
4782 break;
4783 default:
4784 return got_error(GOT_ERR_FILE_STATUS);
4786 fd1 = got_opentempfd();
4787 if (fd1 == -1) {
4788 err = got_error_from_errno("got_opentempfd");
4789 goto done;
4791 fd2 = got_opentempfd();
4792 if (fd2 == -1) {
4793 err = got_error_from_errno("got_opentempfd");
4794 goto done;
4796 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4797 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4798 a->diff_algo, a->diff_context, a->ignore_whitespace,
4799 a->force_text_diff, a->repo, stdout);
4800 goto done;
4803 fd1 = got_opentempfd();
4804 if (fd1 == -1) {
4805 err = got_error_from_errno("got_opentempfd");
4806 goto done;
4809 if (staged_status == GOT_STATUS_ADD ||
4810 staged_status == GOT_STATUS_MODIFY) {
4811 char *id_str;
4812 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4813 8192, fd1);
4814 if (err)
4815 goto done;
4816 err = got_object_id_str(&id_str, staged_blob_id);
4817 if (err)
4818 goto done;
4819 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4820 err = got_error_from_errno("asprintf");
4821 free(id_str);
4822 goto done;
4824 free(id_str);
4825 } else if (status != GOT_STATUS_ADD) {
4826 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4827 fd1);
4828 if (err)
4829 goto done;
4832 if (status != GOT_STATUS_DELETE) {
4833 if (asprintf(&abspath, "%s/%s",
4834 got_worktree_get_root_path(a->worktree), path) == -1) {
4835 err = got_error_from_errno("asprintf");
4836 goto done;
4839 if (dirfd != -1) {
4840 fd = openat(dirfd, de_name,
4841 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4842 if (fd == -1) {
4843 if (!got_err_open_nofollow_on_symlink()) {
4844 err = got_error_from_errno2("openat",
4845 abspath);
4846 goto done;
4848 err = get_symlink_target_file(&fd, dirfd,
4849 de_name, abspath);
4850 if (err)
4851 goto done;
4853 } else {
4854 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4855 if (fd == -1) {
4856 if (!got_err_open_nofollow_on_symlink()) {
4857 err = got_error_from_errno2("open",
4858 abspath);
4859 goto done;
4861 err = get_symlink_target_file(&fd, dirfd,
4862 de_name, abspath);
4863 if (err)
4864 goto done;
4867 if (fstat(fd, &sb) == -1) {
4868 err = got_error_from_errno2("fstat", abspath);
4869 goto done;
4871 f2 = fdopen(fd, "r");
4872 if (f2 == NULL) {
4873 err = got_error_from_errno2("fdopen", abspath);
4874 goto done;
4876 fd = -1;
4877 } else {
4878 sb.st_size = 0;
4879 f2_exists = 0;
4882 if (blob1) {
4883 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4884 a->f1, blob1);
4885 if (err)
4886 goto done;
4889 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4890 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4891 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4892 done:
4893 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4894 err = got_error_from_errno("close");
4895 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4896 err = got_error_from_errno("close");
4897 if (blob1)
4898 got_object_blob_close(blob1);
4899 if (fd != -1 && close(fd) == -1 && err == NULL)
4900 err = got_error_from_errno("close");
4901 if (f2 && fclose(f2) == EOF && err == NULL)
4902 err = got_error_from_errno("fclose");
4903 free(abspath);
4904 return err;
4907 static const struct got_error *
4908 cmd_diff(int argc, char *argv[])
4910 const struct got_error *error;
4911 struct got_repository *repo = NULL;
4912 struct got_worktree *worktree = NULL;
4913 char *cwd = NULL, *repo_path = NULL;
4914 const char *commit_args[2] = { NULL, NULL };
4915 int ncommit_args = 0;
4916 struct got_object_id *ids[2] = { NULL, NULL };
4917 char *labels[2] = { NULL, NULL };
4918 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4919 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4920 int force_text_diff = 0, force_path = 0, rflag = 0;
4921 const char *errstr;
4922 struct got_reflist_head refs;
4923 struct got_pathlist_head paths;
4924 struct got_pathlist_entry *pe;
4925 FILE *f1 = NULL, *f2 = NULL;
4926 int fd1 = -1, fd2 = -1;
4927 int *pack_fds = NULL;
4929 TAILQ_INIT(&refs);
4930 TAILQ_INIT(&paths);
4932 #ifndef PROFILE
4933 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4934 NULL) == -1)
4935 err(1, "pledge");
4936 #endif
4938 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4939 switch (ch) {
4940 case 'a':
4941 force_text_diff = 1;
4942 break;
4943 case 'c':
4944 if (ncommit_args >= 2)
4945 errx(1, "too many -c options used");
4946 commit_args[ncommit_args++] = optarg;
4947 break;
4948 case 'C':
4949 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4950 &errstr);
4951 if (errstr != NULL)
4952 errx(1, "number of context lines is %s: %s",
4953 errstr, optarg);
4954 break;
4955 case 'r':
4956 repo_path = realpath(optarg, NULL);
4957 if (repo_path == NULL)
4958 return got_error_from_errno2("realpath",
4959 optarg);
4960 got_path_strip_trailing_slashes(repo_path);
4961 rflag = 1;
4962 break;
4963 case 's':
4964 diff_staged = 1;
4965 break;
4966 case 'w':
4967 ignore_whitespace = 1;
4968 break;
4969 case 'P':
4970 force_path = 1;
4971 break;
4972 default:
4973 usage_diff();
4974 /* NOTREACHED */
4978 argc -= optind;
4979 argv += optind;
4981 cwd = getcwd(NULL, 0);
4982 if (cwd == NULL) {
4983 error = got_error_from_errno("getcwd");
4984 goto done;
4987 error = got_repo_pack_fds_open(&pack_fds);
4988 if (error != NULL)
4989 goto done;
4991 if (repo_path == NULL) {
4992 error = got_worktree_open(&worktree, cwd);
4993 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4994 goto done;
4995 else
4996 error = NULL;
4997 if (worktree) {
4998 repo_path =
4999 strdup(got_worktree_get_repo_path(worktree));
5000 if (repo_path == NULL) {
5001 error = got_error_from_errno("strdup");
5002 goto done;
5004 } else {
5005 repo_path = strdup(cwd);
5006 if (repo_path == NULL) {
5007 error = got_error_from_errno("strdup");
5008 goto done;
5013 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5014 free(repo_path);
5015 if (error != NULL)
5016 goto done;
5018 if (rflag || worktree == NULL || ncommit_args > 0) {
5019 if (force_path) {
5020 error = got_error_msg(GOT_ERR_NOT_IMPL,
5021 "-P option can only be used when diffing "
5022 "a work tree");
5023 goto done;
5025 if (diff_staged) {
5026 error = got_error_msg(GOT_ERR_NOT_IMPL,
5027 "-s option can only be used when diffing "
5028 "a work tree");
5029 goto done;
5033 error = apply_unveil(got_repo_get_path(repo), 1,
5034 worktree ? got_worktree_get_root_path(worktree) : NULL);
5035 if (error)
5036 goto done;
5038 if ((!force_path && argc == 2) || ncommit_args > 0) {
5039 int obj_type = (ncommit_args > 0 ?
5040 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5041 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5042 NULL);
5043 if (error)
5044 goto done;
5045 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5046 const char *arg;
5047 if (ncommit_args > 0)
5048 arg = commit_args[i];
5049 else
5050 arg = argv[i];
5051 error = got_repo_match_object_id(&ids[i], &labels[i],
5052 arg, obj_type, &refs, repo);
5053 if (error) {
5054 if (error->code != GOT_ERR_NOT_REF &&
5055 error->code != GOT_ERR_NO_OBJ)
5056 goto done;
5057 if (ncommit_args > 0)
5058 goto done;
5059 error = NULL;
5060 break;
5065 f1 = got_opentemp();
5066 if (f1 == NULL) {
5067 error = got_error_from_errno("got_opentemp");
5068 goto done;
5071 f2 = got_opentemp();
5072 if (f2 == NULL) {
5073 error = got_error_from_errno("got_opentemp");
5074 goto done;
5077 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5078 struct print_diff_arg arg;
5079 char *id_str;
5081 if (worktree == NULL) {
5082 if (argc == 2 && ids[0] == NULL) {
5083 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5084 goto done;
5085 } else if (argc == 2 && ids[1] == NULL) {
5086 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5087 goto done;
5088 } else if (argc > 0) {
5089 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5090 "%s", "specified paths cannot be resolved");
5091 goto done;
5092 } else {
5093 error = got_error(GOT_ERR_NOT_WORKTREE);
5094 goto done;
5098 error = get_worktree_paths_from_argv(&paths, argc, argv,
5099 worktree);
5100 if (error)
5101 goto done;
5103 error = got_object_id_str(&id_str,
5104 got_worktree_get_base_commit_id(worktree));
5105 if (error)
5106 goto done;
5107 arg.repo = repo;
5108 arg.worktree = worktree;
5109 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5110 arg.diff_context = diff_context;
5111 arg.id_str = id_str;
5112 arg.header_shown = 0;
5113 arg.diff_staged = diff_staged;
5114 arg.ignore_whitespace = ignore_whitespace;
5115 arg.force_text_diff = force_text_diff;
5116 arg.f1 = f1;
5117 arg.f2 = f2;
5119 error = got_worktree_status(worktree, &paths, repo, 0,
5120 print_diff, &arg, check_cancelled, NULL);
5121 free(id_str);
5122 goto done;
5125 if (ncommit_args == 1) {
5126 struct got_commit_object *commit;
5127 error = got_object_open_as_commit(&commit, repo, ids[0]);
5128 if (error)
5129 goto done;
5131 labels[1] = labels[0];
5132 ids[1] = ids[0];
5133 if (got_object_commit_get_nparents(commit) > 0) {
5134 const struct got_object_id_queue *pids;
5135 struct got_object_qid *pid;
5136 pids = got_object_commit_get_parent_ids(commit);
5137 pid = STAILQ_FIRST(pids);
5138 ids[0] = got_object_id_dup(&pid->id);
5139 if (ids[0] == NULL) {
5140 error = got_error_from_errno(
5141 "got_object_id_dup");
5142 got_object_commit_close(commit);
5143 goto done;
5145 error = got_object_id_str(&labels[0], ids[0]);
5146 if (error) {
5147 got_object_commit_close(commit);
5148 goto done;
5150 } else {
5151 ids[0] = NULL;
5152 labels[0] = strdup("/dev/null");
5153 if (labels[0] == NULL) {
5154 error = got_error_from_errno("strdup");
5155 got_object_commit_close(commit);
5156 goto done;
5160 got_object_commit_close(commit);
5163 if (ncommit_args == 0 && argc > 2) {
5164 error = got_error_msg(GOT_ERR_BAD_PATH,
5165 "path arguments cannot be used when diffing two objects");
5166 goto done;
5169 if (ids[0]) {
5170 error = got_object_get_type(&type1, repo, ids[0]);
5171 if (error)
5172 goto done;
5175 error = got_object_get_type(&type2, repo, ids[1]);
5176 if (error)
5177 goto done;
5178 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5179 error = got_error(GOT_ERR_OBJ_TYPE);
5180 goto done;
5182 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5183 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5184 "path arguments cannot be used when diffing blobs");
5185 goto done;
5188 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5189 char *in_repo_path;
5190 struct got_pathlist_entry *new;
5191 if (worktree) {
5192 const char *prefix;
5193 char *p;
5194 error = got_worktree_resolve_path(&p, worktree,
5195 argv[i]);
5196 if (error)
5197 goto done;
5198 prefix = got_worktree_get_path_prefix(worktree);
5199 while (prefix[0] == '/')
5200 prefix++;
5201 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5202 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5203 p) == -1) {
5204 error = got_error_from_errno("asprintf");
5205 free(p);
5206 goto done;
5208 free(p);
5209 } else {
5210 char *mapped_path, *s;
5211 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5212 if (error)
5213 goto done;
5214 s = mapped_path;
5215 while (s[0] == '/')
5216 s++;
5217 in_repo_path = strdup(s);
5218 if (in_repo_path == NULL) {
5219 error = got_error_from_errno("asprintf");
5220 free(mapped_path);
5221 goto done;
5223 free(mapped_path);
5226 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5227 if (error || new == NULL /* duplicate */)
5228 free(in_repo_path);
5229 if (error)
5230 goto done;
5233 if (worktree) {
5234 /* Release work tree lock. */
5235 got_worktree_close(worktree);
5236 worktree = NULL;
5239 fd1 = got_opentempfd();
5240 if (fd1 == -1) {
5241 error = got_error_from_errno("got_opentempfd");
5242 goto done;
5245 fd2 = got_opentempfd();
5246 if (fd2 == -1) {
5247 error = got_error_from_errno("got_opentempfd");
5248 goto done;
5251 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5252 case GOT_OBJ_TYPE_BLOB:
5253 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5254 fd1, fd2, ids[0], ids[1], NULL, NULL,
5255 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5256 ignore_whitespace, force_text_diff, repo, stdout);
5257 break;
5258 case GOT_OBJ_TYPE_TREE:
5259 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5260 ids[0], ids[1], &paths, "", "",
5261 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5262 ignore_whitespace, force_text_diff, repo, stdout);
5263 break;
5264 case GOT_OBJ_TYPE_COMMIT:
5265 printf("diff %s %s\n", labels[0], labels[1]);
5266 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5267 fd1, fd2, ids[0], ids[1], &paths,
5268 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5269 ignore_whitespace, force_text_diff, repo, stdout);
5270 break;
5271 default:
5272 error = got_error(GOT_ERR_OBJ_TYPE);
5274 done:
5275 free(labels[0]);
5276 free(labels[1]);
5277 free(ids[0]);
5278 free(ids[1]);
5279 if (worktree)
5280 got_worktree_close(worktree);
5281 if (repo) {
5282 const struct got_error *close_err = got_repo_close(repo);
5283 if (error == NULL)
5284 error = close_err;
5286 if (pack_fds) {
5287 const struct got_error *pack_err =
5288 got_repo_pack_fds_close(pack_fds);
5289 if (error == NULL)
5290 error = pack_err;
5292 TAILQ_FOREACH(pe, &paths, entry)
5293 free((char *)pe->path);
5294 got_pathlist_free(&paths);
5295 got_ref_list_free(&refs);
5296 if (f1 && fclose(f1) == EOF && error == NULL)
5297 error = got_error_from_errno("fclose");
5298 if (f2 && fclose(f2) == EOF && error == NULL)
5299 error = got_error_from_errno("fclose");
5300 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5301 error = got_error_from_errno("close");
5302 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5303 error = got_error_from_errno("close");
5304 return error;
5307 __dead static void
5308 usage_blame(void)
5310 fprintf(stderr,
5311 "usage: %s blame [-c commit] [-r repository-path] path\n",
5312 getprogname());
5313 exit(1);
5316 struct blame_line {
5317 int annotated;
5318 char *id_str;
5319 char *committer;
5320 char datebuf[11]; /* YYYY-MM-DD + NUL */
5323 struct blame_cb_args {
5324 struct blame_line *lines;
5325 int nlines;
5326 int nlines_prec;
5327 int lineno_cur;
5328 off_t *line_offsets;
5329 FILE *f;
5330 struct got_repository *repo;
5333 static const struct got_error *
5334 blame_cb(void *arg, int nlines, int lineno,
5335 struct got_commit_object *commit, struct got_object_id *id)
5337 const struct got_error *err = NULL;
5338 struct blame_cb_args *a = arg;
5339 struct blame_line *bline;
5340 char *line = NULL;
5341 size_t linesize = 0;
5342 off_t offset;
5343 struct tm tm;
5344 time_t committer_time;
5346 if (nlines != a->nlines ||
5347 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5348 return got_error(GOT_ERR_RANGE);
5350 if (sigint_received)
5351 return got_error(GOT_ERR_ITER_COMPLETED);
5353 if (lineno == -1)
5354 return NULL; /* no change in this commit */
5356 /* Annotate this line. */
5357 bline = &a->lines[lineno - 1];
5358 if (bline->annotated)
5359 return NULL;
5360 err = got_object_id_str(&bline->id_str, id);
5361 if (err)
5362 return err;
5364 bline->committer = strdup(got_object_commit_get_committer(commit));
5365 if (bline->committer == NULL) {
5366 err = got_error_from_errno("strdup");
5367 goto done;
5370 committer_time = got_object_commit_get_committer_time(commit);
5371 if (gmtime_r(&committer_time, &tm) == NULL)
5372 return got_error_from_errno("gmtime_r");
5373 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5374 &tm) == 0) {
5375 err = got_error(GOT_ERR_NO_SPACE);
5376 goto done;
5378 bline->annotated = 1;
5380 /* Print lines annotated so far. */
5381 bline = &a->lines[a->lineno_cur - 1];
5382 if (!bline->annotated)
5383 goto done;
5385 offset = a->line_offsets[a->lineno_cur - 1];
5386 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5387 err = got_error_from_errno("fseeko");
5388 goto done;
5391 while (bline->annotated) {
5392 char *smallerthan, *at, *nl, *committer;
5393 size_t len;
5395 if (getline(&line, &linesize, a->f) == -1) {
5396 if (ferror(a->f))
5397 err = got_error_from_errno("getline");
5398 break;
5401 committer = bline->committer;
5402 smallerthan = strchr(committer, '<');
5403 if (smallerthan && smallerthan[1] != '\0')
5404 committer = smallerthan + 1;
5405 at = strchr(committer, '@');
5406 if (at)
5407 *at = '\0';
5408 len = strlen(committer);
5409 if (len >= 9)
5410 committer[8] = '\0';
5412 nl = strchr(line, '\n');
5413 if (nl)
5414 *nl = '\0';
5415 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5416 bline->id_str, bline->datebuf, committer, line);
5418 a->lineno_cur++;
5419 bline = &a->lines[a->lineno_cur - 1];
5421 done:
5422 free(line);
5423 return err;
5426 static const struct got_error *
5427 cmd_blame(int argc, char *argv[])
5429 const struct got_error *error;
5430 struct got_repository *repo = NULL;
5431 struct got_worktree *worktree = NULL;
5432 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5433 char *link_target = NULL;
5434 struct got_object_id *obj_id = NULL;
5435 struct got_object_id *commit_id = NULL;
5436 struct got_commit_object *commit = NULL;
5437 struct got_blob_object *blob = NULL;
5438 char *commit_id_str = NULL;
5439 struct blame_cb_args bca;
5440 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5441 off_t filesize;
5442 int *pack_fds = NULL;
5443 FILE *f1 = NULL, *f2 = NULL;
5445 fd1 = got_opentempfd();
5446 if (fd1 == -1)
5447 return got_error_from_errno("got_opentempfd");
5449 memset(&bca, 0, sizeof(bca));
5451 #ifndef PROFILE
5452 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5453 NULL) == -1)
5454 err(1, "pledge");
5455 #endif
5457 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5458 switch (ch) {
5459 case 'c':
5460 commit_id_str = optarg;
5461 break;
5462 case 'r':
5463 repo_path = realpath(optarg, NULL);
5464 if (repo_path == NULL)
5465 return got_error_from_errno2("realpath",
5466 optarg);
5467 got_path_strip_trailing_slashes(repo_path);
5468 break;
5469 default:
5470 usage_blame();
5471 /* NOTREACHED */
5475 argc -= optind;
5476 argv += optind;
5478 if (argc == 1)
5479 path = argv[0];
5480 else
5481 usage_blame();
5483 cwd = getcwd(NULL, 0);
5484 if (cwd == NULL) {
5485 error = got_error_from_errno("getcwd");
5486 goto done;
5489 error = got_repo_pack_fds_open(&pack_fds);
5490 if (error != NULL)
5491 goto done;
5493 if (repo_path == NULL) {
5494 error = got_worktree_open(&worktree, cwd);
5495 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5496 goto done;
5497 else
5498 error = NULL;
5499 if (worktree) {
5500 repo_path =
5501 strdup(got_worktree_get_repo_path(worktree));
5502 if (repo_path == NULL) {
5503 error = got_error_from_errno("strdup");
5504 if (error)
5505 goto done;
5507 } else {
5508 repo_path = strdup(cwd);
5509 if (repo_path == NULL) {
5510 error = got_error_from_errno("strdup");
5511 goto done;
5516 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5517 if (error != NULL)
5518 goto done;
5520 if (worktree) {
5521 const char *prefix = got_worktree_get_path_prefix(worktree);
5522 char *p;
5524 error = got_worktree_resolve_path(&p, worktree, path);
5525 if (error)
5526 goto done;
5527 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5528 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5529 p) == -1) {
5530 error = got_error_from_errno("asprintf");
5531 free(p);
5532 goto done;
5534 free(p);
5535 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5536 } else {
5537 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5538 if (error)
5539 goto done;
5540 error = got_repo_map_path(&in_repo_path, repo, path);
5542 if (error)
5543 goto done;
5545 if (commit_id_str == NULL) {
5546 struct got_reference *head_ref;
5547 error = got_ref_open(&head_ref, repo, worktree ?
5548 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5549 if (error != NULL)
5550 goto done;
5551 error = got_ref_resolve(&commit_id, repo, head_ref);
5552 got_ref_close(head_ref);
5553 if (error != NULL)
5554 goto done;
5555 } else {
5556 struct got_reflist_head refs;
5557 TAILQ_INIT(&refs);
5558 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5559 NULL);
5560 if (error)
5561 goto done;
5562 error = got_repo_match_object_id(&commit_id, NULL,
5563 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5564 got_ref_list_free(&refs);
5565 if (error)
5566 goto done;
5569 if (worktree) {
5570 /* Release work tree lock. */
5571 got_worktree_close(worktree);
5572 worktree = NULL;
5575 error = got_object_open_as_commit(&commit, repo, commit_id);
5576 if (error)
5577 goto done;
5579 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5580 commit, repo);
5581 if (error)
5582 goto done;
5584 error = got_object_id_by_path(&obj_id, repo, commit,
5585 link_target ? link_target : in_repo_path);
5586 if (error)
5587 goto done;
5589 error = got_object_get_type(&obj_type, repo, obj_id);
5590 if (error)
5591 goto done;
5593 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5594 error = got_error_path(link_target ? link_target : in_repo_path,
5595 GOT_ERR_OBJ_TYPE);
5596 goto done;
5599 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5600 if (error)
5601 goto done;
5602 bca.f = got_opentemp();
5603 if (bca.f == NULL) {
5604 error = got_error_from_errno("got_opentemp");
5605 goto done;
5607 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5608 &bca.line_offsets, bca.f, blob);
5609 if (error || bca.nlines == 0)
5610 goto done;
5612 /* Don't include \n at EOF in the blame line count. */
5613 if (bca.line_offsets[bca.nlines - 1] == filesize)
5614 bca.nlines--;
5616 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5617 if (bca.lines == NULL) {
5618 error = got_error_from_errno("calloc");
5619 goto done;
5621 bca.lineno_cur = 1;
5622 bca.nlines_prec = 0;
5623 i = bca.nlines;
5624 while (i > 0) {
5625 i /= 10;
5626 bca.nlines_prec++;
5628 bca.repo = repo;
5630 fd2 = got_opentempfd();
5631 if (fd2 == -1) {
5632 error = got_error_from_errno("got_opentempfd");
5633 goto done;
5635 fd3 = got_opentempfd();
5636 if (fd3 == -1) {
5637 error = got_error_from_errno("got_opentempfd");
5638 goto done;
5640 f1 = got_opentemp();
5641 if (f1 == NULL) {
5642 error = got_error_from_errno("got_opentemp");
5643 goto done;
5645 f2 = got_opentemp();
5646 if (f2 == NULL) {
5647 error = got_error_from_errno("got_opentemp");
5648 goto done;
5650 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5651 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5652 check_cancelled, NULL, fd2, fd3, f1, f2);
5653 done:
5654 free(in_repo_path);
5655 free(link_target);
5656 free(repo_path);
5657 free(cwd);
5658 free(commit_id);
5659 free(obj_id);
5660 if (commit)
5661 got_object_commit_close(commit);
5663 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5664 error = got_error_from_errno("close");
5665 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5666 error = got_error_from_errno("close");
5667 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5668 error = got_error_from_errno("close");
5669 if (f1 && fclose(f1) == EOF && error == NULL)
5670 error = got_error_from_errno("fclose");
5671 if (f2 && fclose(f2) == EOF && error == NULL)
5672 error = got_error_from_errno("fclose");
5674 if (blob)
5675 got_object_blob_close(blob);
5676 if (worktree)
5677 got_worktree_close(worktree);
5678 if (repo) {
5679 const struct got_error *close_err = got_repo_close(repo);
5680 if (error == NULL)
5681 error = close_err;
5683 if (pack_fds) {
5684 const struct got_error *pack_err =
5685 got_repo_pack_fds_close(pack_fds);
5686 if (error == NULL)
5687 error = pack_err;
5689 if (bca.lines) {
5690 for (i = 0; i < bca.nlines; i++) {
5691 struct blame_line *bline = &bca.lines[i];
5692 free(bline->id_str);
5693 free(bline->committer);
5695 free(bca.lines);
5697 free(bca.line_offsets);
5698 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5699 error = got_error_from_errno("fclose");
5700 return error;
5703 __dead static void
5704 usage_tree(void)
5706 fprintf(stderr,
5707 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5708 getprogname());
5709 exit(1);
5712 static const struct got_error *
5713 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5714 const char *root_path, struct got_repository *repo)
5716 const struct got_error *err = NULL;
5717 int is_root_path = (strcmp(path, root_path) == 0);
5718 const char *modestr = "";
5719 mode_t mode = got_tree_entry_get_mode(te);
5720 char *link_target = NULL;
5722 path += strlen(root_path);
5723 while (path[0] == '/')
5724 path++;
5726 if (got_object_tree_entry_is_submodule(te))
5727 modestr = "$";
5728 else if (S_ISLNK(mode)) {
5729 int i;
5731 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5732 if (err)
5733 return err;
5734 for (i = 0; i < strlen(link_target); i++) {
5735 if (!isprint((unsigned char)link_target[i]))
5736 link_target[i] = '?';
5739 modestr = "@";
5741 else if (S_ISDIR(mode))
5742 modestr = "/";
5743 else if (mode & S_IXUSR)
5744 modestr = "*";
5746 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5747 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5748 link_target ? " -> ": "", link_target ? link_target : "");
5750 free(link_target);
5751 return NULL;
5754 static const struct got_error *
5755 print_tree(const char *path, struct got_commit_object *commit,
5756 int show_ids, int recurse, const char *root_path,
5757 struct got_repository *repo)
5759 const struct got_error *err = NULL;
5760 struct got_object_id *tree_id = NULL;
5761 struct got_tree_object *tree = NULL;
5762 int nentries, i;
5764 err = got_object_id_by_path(&tree_id, repo, commit, path);
5765 if (err)
5766 goto done;
5768 err = got_object_open_as_tree(&tree, repo, tree_id);
5769 if (err)
5770 goto done;
5771 nentries = got_object_tree_get_nentries(tree);
5772 for (i = 0; i < nentries; i++) {
5773 struct got_tree_entry *te;
5774 char *id = NULL;
5776 if (sigint_received || sigpipe_received)
5777 break;
5779 te = got_object_tree_get_entry(tree, i);
5780 if (show_ids) {
5781 char *id_str;
5782 err = got_object_id_str(&id_str,
5783 got_tree_entry_get_id(te));
5784 if (err)
5785 goto done;
5786 if (asprintf(&id, "%s ", id_str) == -1) {
5787 err = got_error_from_errno("asprintf");
5788 free(id_str);
5789 goto done;
5791 free(id_str);
5793 err = print_entry(te, id, path, root_path, repo);
5794 free(id);
5795 if (err)
5796 goto done;
5798 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5799 char *child_path;
5800 if (asprintf(&child_path, "%s%s%s", path,
5801 path[0] == '/' && path[1] == '\0' ? "" : "/",
5802 got_tree_entry_get_name(te)) == -1) {
5803 err = got_error_from_errno("asprintf");
5804 goto done;
5806 err = print_tree(child_path, commit, show_ids, 1,
5807 root_path, repo);
5808 free(child_path);
5809 if (err)
5810 goto done;
5813 done:
5814 if (tree)
5815 got_object_tree_close(tree);
5816 free(tree_id);
5817 return err;
5820 static const struct got_error *
5821 cmd_tree(int argc, char *argv[])
5823 const struct got_error *error;
5824 struct got_repository *repo = NULL;
5825 struct got_worktree *worktree = NULL;
5826 const char *path, *refname = NULL;
5827 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5828 struct got_object_id *commit_id = NULL;
5829 struct got_commit_object *commit = NULL;
5830 char *commit_id_str = NULL;
5831 int show_ids = 0, recurse = 0;
5832 int ch;
5833 int *pack_fds = NULL;
5835 #ifndef PROFILE
5836 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5837 NULL) == -1)
5838 err(1, "pledge");
5839 #endif
5841 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5842 switch (ch) {
5843 case 'c':
5844 commit_id_str = optarg;
5845 break;
5846 case 'r':
5847 repo_path = realpath(optarg, NULL);
5848 if (repo_path == NULL)
5849 return got_error_from_errno2("realpath",
5850 optarg);
5851 got_path_strip_trailing_slashes(repo_path);
5852 break;
5853 case 'i':
5854 show_ids = 1;
5855 break;
5856 case 'R':
5857 recurse = 1;
5858 break;
5859 default:
5860 usage_tree();
5861 /* NOTREACHED */
5865 argc -= optind;
5866 argv += optind;
5868 if (argc == 1)
5869 path = argv[0];
5870 else if (argc > 1)
5871 usage_tree();
5872 else
5873 path = NULL;
5875 cwd = getcwd(NULL, 0);
5876 if (cwd == NULL) {
5877 error = got_error_from_errno("getcwd");
5878 goto done;
5881 error = got_repo_pack_fds_open(&pack_fds);
5882 if (error != NULL)
5883 goto done;
5885 if (repo_path == NULL) {
5886 error = got_worktree_open(&worktree, cwd);
5887 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5888 goto done;
5889 else
5890 error = NULL;
5891 if (worktree) {
5892 repo_path =
5893 strdup(got_worktree_get_repo_path(worktree));
5894 if (repo_path == NULL)
5895 error = got_error_from_errno("strdup");
5896 if (error)
5897 goto done;
5898 } else {
5899 repo_path = strdup(cwd);
5900 if (repo_path == NULL) {
5901 error = got_error_from_errno("strdup");
5902 goto done;
5907 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5908 if (error != NULL)
5909 goto done;
5911 if (worktree) {
5912 const char *prefix = got_worktree_get_path_prefix(worktree);
5913 char *p;
5915 if (path == NULL)
5916 path = "";
5917 error = got_worktree_resolve_path(&p, worktree, path);
5918 if (error)
5919 goto done;
5920 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5921 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5922 p) == -1) {
5923 error = got_error_from_errno("asprintf");
5924 free(p);
5925 goto done;
5927 free(p);
5928 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5929 if (error)
5930 goto done;
5931 } else {
5932 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5933 if (error)
5934 goto done;
5935 if (path == NULL)
5936 path = "/";
5937 error = got_repo_map_path(&in_repo_path, repo, path);
5938 if (error != NULL)
5939 goto done;
5942 if (commit_id_str == NULL) {
5943 struct got_reference *head_ref;
5944 if (worktree)
5945 refname = got_worktree_get_head_ref_name(worktree);
5946 else
5947 refname = GOT_REF_HEAD;
5948 error = got_ref_open(&head_ref, repo, refname, 0);
5949 if (error != NULL)
5950 goto done;
5951 error = got_ref_resolve(&commit_id, repo, head_ref);
5952 got_ref_close(head_ref);
5953 if (error != NULL)
5954 goto done;
5955 } else {
5956 struct got_reflist_head refs;
5957 TAILQ_INIT(&refs);
5958 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5959 NULL);
5960 if (error)
5961 goto done;
5962 error = got_repo_match_object_id(&commit_id, NULL,
5963 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5964 got_ref_list_free(&refs);
5965 if (error)
5966 goto done;
5969 if (worktree) {
5970 /* Release work tree lock. */
5971 got_worktree_close(worktree);
5972 worktree = NULL;
5975 error = got_object_open_as_commit(&commit, repo, commit_id);
5976 if (error)
5977 goto done;
5979 error = print_tree(in_repo_path, commit, show_ids, recurse,
5980 in_repo_path, repo);
5981 done:
5982 free(in_repo_path);
5983 free(repo_path);
5984 free(cwd);
5985 free(commit_id);
5986 if (commit)
5987 got_object_commit_close(commit);
5988 if (worktree)
5989 got_worktree_close(worktree);
5990 if (repo) {
5991 const struct got_error *close_err = got_repo_close(repo);
5992 if (error == NULL)
5993 error = close_err;
5995 if (pack_fds) {
5996 const struct got_error *pack_err =
5997 got_repo_pack_fds_close(pack_fds);
5998 if (error == NULL)
5999 error = pack_err;
6001 return error;
6004 __dead static void
6005 usage_status(void)
6007 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
6008 "[-S status-codes] [path ...]\n", getprogname());
6009 exit(1);
6012 struct got_status_arg {
6013 char *status_codes;
6014 int suppress;
6017 static const struct got_error *
6018 print_status(void *arg, unsigned char status, unsigned char staged_status,
6019 const char *path, struct got_object_id *blob_id,
6020 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6021 int dirfd, const char *de_name)
6023 struct got_status_arg *st = arg;
6025 if (status == staged_status && (status == GOT_STATUS_DELETE))
6026 status = GOT_STATUS_NO_CHANGE;
6027 if (st != NULL && st->status_codes) {
6028 size_t ncodes = strlen(st->status_codes);
6029 int i, j = 0;
6031 for (i = 0; i < ncodes ; i++) {
6032 if (st->suppress) {
6033 if (status == st->status_codes[i] ||
6034 staged_status == st->status_codes[i]) {
6035 j++;
6036 continue;
6038 } else {
6039 if (status == st->status_codes[i] ||
6040 staged_status == st->status_codes[i])
6041 break;
6045 if (st->suppress && j == 0)
6046 goto print;
6048 if (i == ncodes)
6049 return NULL;
6051 print:
6052 printf("%c%c %s\n", status, staged_status, path);
6053 return NULL;
6056 static const struct got_error *
6057 cmd_status(int argc, char *argv[])
6059 const struct got_error *error = NULL;
6060 struct got_repository *repo = NULL;
6061 struct got_worktree *worktree = NULL;
6062 struct got_status_arg st;
6063 char *cwd = NULL;
6064 struct got_pathlist_head paths;
6065 struct got_pathlist_entry *pe;
6066 int ch, i, no_ignores = 0;
6067 int *pack_fds = NULL;
6069 TAILQ_INIT(&paths);
6071 memset(&st, 0, sizeof(st));
6072 st.status_codes = NULL;
6073 st.suppress = 0;
6075 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6076 switch (ch) {
6077 case 'I':
6078 no_ignores = 1;
6079 break;
6080 case 'S':
6081 if (st.status_codes != NULL && st.suppress == 0)
6082 option_conflict('S', 's');
6083 st.suppress = 1;
6084 /* fallthrough */
6085 case 's':
6086 for (i = 0; i < strlen(optarg); i++) {
6087 switch (optarg[i]) {
6088 case GOT_STATUS_MODIFY:
6089 case GOT_STATUS_ADD:
6090 case GOT_STATUS_DELETE:
6091 case GOT_STATUS_CONFLICT:
6092 case GOT_STATUS_MISSING:
6093 case GOT_STATUS_OBSTRUCTED:
6094 case GOT_STATUS_UNVERSIONED:
6095 case GOT_STATUS_MODE_CHANGE:
6096 case GOT_STATUS_NONEXISTENT:
6097 break;
6098 default:
6099 errx(1, "invalid status code '%c'",
6100 optarg[i]);
6103 if (ch == 's' && st.suppress)
6104 option_conflict('s', 'S');
6105 st.status_codes = optarg;
6106 break;
6107 default:
6108 usage_status();
6109 /* NOTREACHED */
6113 argc -= optind;
6114 argv += optind;
6116 #ifndef PROFILE
6117 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6118 NULL) == -1)
6119 err(1, "pledge");
6120 #endif
6121 cwd = getcwd(NULL, 0);
6122 if (cwd == NULL) {
6123 error = got_error_from_errno("getcwd");
6124 goto done;
6127 error = got_repo_pack_fds_open(&pack_fds);
6128 if (error != NULL)
6129 goto done;
6131 error = got_worktree_open(&worktree, cwd);
6132 if (error) {
6133 if (error->code == GOT_ERR_NOT_WORKTREE)
6134 error = wrap_not_worktree_error(error, "status", cwd);
6135 goto done;
6138 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6139 NULL, pack_fds);
6140 if (error != NULL)
6141 goto done;
6143 error = apply_unveil(got_repo_get_path(repo), 1,
6144 got_worktree_get_root_path(worktree));
6145 if (error)
6146 goto done;
6148 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6149 if (error)
6150 goto done;
6152 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6153 print_status, &st, check_cancelled, NULL);
6154 done:
6155 if (pack_fds) {
6156 const struct got_error *pack_err =
6157 got_repo_pack_fds_close(pack_fds);
6158 if (error == NULL)
6159 error = pack_err;
6162 TAILQ_FOREACH(pe, &paths, entry)
6163 free((char *)pe->path);
6164 got_pathlist_free(&paths);
6165 free(cwd);
6166 return error;
6169 __dead static void
6170 usage_ref(void)
6172 fprintf(stderr,
6173 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6174 "[-s reference] [-d] [name]\n",
6175 getprogname());
6176 exit(1);
6179 static const struct got_error *
6180 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6182 static const struct got_error *err = NULL;
6183 struct got_reflist_head refs;
6184 struct got_reflist_entry *re;
6186 TAILQ_INIT(&refs);
6187 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6188 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6189 repo);
6190 if (err)
6191 return err;
6193 TAILQ_FOREACH(re, &refs, entry) {
6194 char *refstr;
6195 refstr = got_ref_to_str(re->ref);
6196 if (refstr == NULL) {
6197 err = got_error_from_errno("got_ref_to_str");
6198 break;
6200 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6201 free(refstr);
6204 got_ref_list_free(&refs);
6205 return err;
6208 static const struct got_error *
6209 delete_ref_by_name(struct got_repository *repo, const char *refname)
6211 const struct got_error *err;
6212 struct got_reference *ref;
6214 err = got_ref_open(&ref, repo, refname, 0);
6215 if (err)
6216 return err;
6218 err = delete_ref(repo, ref);
6219 got_ref_close(ref);
6220 return err;
6223 static const struct got_error *
6224 add_ref(struct got_repository *repo, const char *refname, const char *target)
6226 const struct got_error *err = NULL;
6227 struct got_object_id *id = NULL;
6228 struct got_reference *ref = NULL;
6229 struct got_reflist_head refs;
6232 * Don't let the user create a reference name with a leading '-'.
6233 * While technically a valid reference name, this case is usually
6234 * an unintended typo.
6236 if (refname[0] == '-')
6237 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6239 TAILQ_INIT(&refs);
6240 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6241 if (err)
6242 goto done;
6243 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6244 &refs, repo);
6245 got_ref_list_free(&refs);
6246 if (err)
6247 goto done;
6249 err = got_ref_alloc(&ref, refname, id);
6250 if (err)
6251 goto done;
6253 err = got_ref_write(ref, repo);
6254 done:
6255 if (ref)
6256 got_ref_close(ref);
6257 free(id);
6258 return err;
6261 static const struct got_error *
6262 add_symref(struct got_repository *repo, const char *refname, const char *target)
6264 const struct got_error *err = NULL;
6265 struct got_reference *ref = NULL;
6266 struct got_reference *target_ref = NULL;
6269 * Don't let the user create a reference name with a leading '-'.
6270 * While technically a valid reference name, this case is usually
6271 * an unintended typo.
6273 if (refname[0] == '-')
6274 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6276 err = got_ref_open(&target_ref, repo, target, 0);
6277 if (err)
6278 return err;
6280 err = got_ref_alloc_symref(&ref, refname, target_ref);
6281 if (err)
6282 goto done;
6284 err = got_ref_write(ref, repo);
6285 done:
6286 if (target_ref)
6287 got_ref_close(target_ref);
6288 if (ref)
6289 got_ref_close(ref);
6290 return err;
6293 static const struct got_error *
6294 cmd_ref(int argc, char *argv[])
6296 const struct got_error *error = NULL;
6297 struct got_repository *repo = NULL;
6298 struct got_worktree *worktree = NULL;
6299 char *cwd = NULL, *repo_path = NULL;
6300 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6301 const char *obj_arg = NULL, *symref_target= NULL;
6302 char *refname = NULL;
6303 int *pack_fds = NULL;
6305 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6306 switch (ch) {
6307 case 'c':
6308 obj_arg = optarg;
6309 break;
6310 case 'd':
6311 do_delete = 1;
6312 break;
6313 case 'r':
6314 repo_path = realpath(optarg, NULL);
6315 if (repo_path == NULL)
6316 return got_error_from_errno2("realpath",
6317 optarg);
6318 got_path_strip_trailing_slashes(repo_path);
6319 break;
6320 case 'l':
6321 do_list = 1;
6322 break;
6323 case 's':
6324 symref_target = optarg;
6325 break;
6326 case 't':
6327 sort_by_time = 1;
6328 break;
6329 default:
6330 usage_ref();
6331 /* NOTREACHED */
6335 if (obj_arg && do_list)
6336 option_conflict('c', 'l');
6337 if (obj_arg && do_delete)
6338 option_conflict('c', 'd');
6339 if (obj_arg && symref_target)
6340 option_conflict('c', 's');
6341 if (symref_target && do_delete)
6342 option_conflict('s', 'd');
6343 if (symref_target && do_list)
6344 option_conflict('s', 'l');
6345 if (do_delete && do_list)
6346 option_conflict('d', 'l');
6347 if (sort_by_time && !do_list)
6348 errx(1, "-t option requires -l option");
6350 argc -= optind;
6351 argv += optind;
6353 if (do_list) {
6354 if (argc != 0 && argc != 1)
6355 usage_ref();
6356 if (argc == 1) {
6357 refname = strdup(argv[0]);
6358 if (refname == NULL) {
6359 error = got_error_from_errno("strdup");
6360 goto done;
6363 } else {
6364 if (argc != 1)
6365 usage_ref();
6366 refname = strdup(argv[0]);
6367 if (refname == NULL) {
6368 error = got_error_from_errno("strdup");
6369 goto done;
6373 if (refname)
6374 got_path_strip_trailing_slashes(refname);
6376 #ifndef PROFILE
6377 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6378 "sendfd unveil", NULL) == -1)
6379 err(1, "pledge");
6380 #endif
6381 cwd = getcwd(NULL, 0);
6382 if (cwd == NULL) {
6383 error = got_error_from_errno("getcwd");
6384 goto done;
6387 error = got_repo_pack_fds_open(&pack_fds);
6388 if (error != NULL)
6389 goto done;
6391 if (repo_path == NULL) {
6392 error = got_worktree_open(&worktree, cwd);
6393 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6394 goto done;
6395 else
6396 error = NULL;
6397 if (worktree) {
6398 repo_path =
6399 strdup(got_worktree_get_repo_path(worktree));
6400 if (repo_path == NULL)
6401 error = got_error_from_errno("strdup");
6402 if (error)
6403 goto done;
6404 } else {
6405 repo_path = strdup(cwd);
6406 if (repo_path == NULL) {
6407 error = got_error_from_errno("strdup");
6408 goto done;
6413 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6414 if (error != NULL)
6415 goto done;
6417 #ifndef PROFILE
6418 if (do_list) {
6419 /* Remove "cpath" promise. */
6420 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6421 NULL) == -1)
6422 err(1, "pledge");
6424 #endif
6426 error = apply_unveil(got_repo_get_path(repo), do_list,
6427 worktree ? got_worktree_get_root_path(worktree) : NULL);
6428 if (error)
6429 goto done;
6431 if (do_list)
6432 error = list_refs(repo, refname, sort_by_time);
6433 else if (do_delete)
6434 error = delete_ref_by_name(repo, refname);
6435 else if (symref_target)
6436 error = add_symref(repo, refname, symref_target);
6437 else {
6438 if (obj_arg == NULL)
6439 usage_ref();
6440 error = add_ref(repo, refname, obj_arg);
6442 done:
6443 free(refname);
6444 if (repo) {
6445 const struct got_error *close_err = got_repo_close(repo);
6446 if (error == NULL)
6447 error = close_err;
6449 if (worktree)
6450 got_worktree_close(worktree);
6451 if (pack_fds) {
6452 const struct got_error *pack_err =
6453 got_repo_pack_fds_close(pack_fds);
6454 if (error == NULL)
6455 error = pack_err;
6457 free(cwd);
6458 free(repo_path);
6459 return error;
6462 __dead static void
6463 usage_branch(void)
6465 fprintf(stderr,
6466 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6467 "[-n] [name]\n", getprogname());
6468 exit(1);
6471 static const struct got_error *
6472 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6473 struct got_reference *ref)
6475 const struct got_error *err = NULL;
6476 const char *refname, *marker = " ";
6477 char *refstr;
6479 refname = got_ref_get_name(ref);
6480 if (worktree && strcmp(refname,
6481 got_worktree_get_head_ref_name(worktree)) == 0) {
6482 struct got_object_id *id = NULL;
6484 err = got_ref_resolve(&id, repo, ref);
6485 if (err)
6486 return err;
6487 if (got_object_id_cmp(id,
6488 got_worktree_get_base_commit_id(worktree)) == 0)
6489 marker = "* ";
6490 else
6491 marker = "~ ";
6492 free(id);
6495 if (strncmp(refname, "refs/heads/", 11) == 0)
6496 refname += 11;
6497 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6498 refname += 18;
6499 if (strncmp(refname, "refs/remotes/", 13) == 0)
6500 refname += 13;
6502 refstr = got_ref_to_str(ref);
6503 if (refstr == NULL)
6504 return got_error_from_errno("got_ref_to_str");
6506 printf("%s%s: %s\n", marker, refname, refstr);
6507 free(refstr);
6508 return NULL;
6511 static const struct got_error *
6512 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6514 const char *refname;
6516 if (worktree == NULL)
6517 return got_error(GOT_ERR_NOT_WORKTREE);
6519 refname = got_worktree_get_head_ref_name(worktree);
6521 if (strncmp(refname, "refs/heads/", 11) == 0)
6522 refname += 11;
6523 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6524 refname += 18;
6526 printf("%s\n", refname);
6528 return NULL;
6531 static const struct got_error *
6532 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6533 int sort_by_time)
6535 static const struct got_error *err = NULL;
6536 struct got_reflist_head refs;
6537 struct got_reflist_entry *re;
6538 struct got_reference *temp_ref = NULL;
6539 int rebase_in_progress, histedit_in_progress;
6541 TAILQ_INIT(&refs);
6543 if (worktree) {
6544 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6545 worktree);
6546 if (err)
6547 return err;
6549 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6550 worktree);
6551 if (err)
6552 return err;
6554 if (rebase_in_progress || histedit_in_progress) {
6555 err = got_ref_open(&temp_ref, repo,
6556 got_worktree_get_head_ref_name(worktree), 0);
6557 if (err)
6558 return err;
6559 list_branch(repo, worktree, temp_ref);
6560 got_ref_close(temp_ref);
6564 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6565 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6566 repo);
6567 if (err)
6568 return err;
6570 TAILQ_FOREACH(re, &refs, entry)
6571 list_branch(repo, worktree, re->ref);
6573 got_ref_list_free(&refs);
6575 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6576 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6577 repo);
6578 if (err)
6579 return err;
6581 TAILQ_FOREACH(re, &refs, entry)
6582 list_branch(repo, worktree, re->ref);
6584 got_ref_list_free(&refs);
6586 return NULL;
6589 static const struct got_error *
6590 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6591 const char *branch_name)
6593 const struct got_error *err = NULL;
6594 struct got_reference *ref = NULL;
6595 char *refname, *remote_refname = NULL;
6597 if (strncmp(branch_name, "refs/", 5) == 0)
6598 branch_name += 5;
6599 if (strncmp(branch_name, "heads/", 6) == 0)
6600 branch_name += 6;
6601 else if (strncmp(branch_name, "remotes/", 8) == 0)
6602 branch_name += 8;
6604 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6605 return got_error_from_errno("asprintf");
6607 if (asprintf(&remote_refname, "refs/remotes/%s",
6608 branch_name) == -1) {
6609 err = got_error_from_errno("asprintf");
6610 goto done;
6613 err = got_ref_open(&ref, repo, refname, 0);
6614 if (err) {
6615 const struct got_error *err2;
6616 if (err->code != GOT_ERR_NOT_REF)
6617 goto done;
6619 * Keep 'err' intact such that if neither branch exists
6620 * we report "refs/heads" rather than "refs/remotes" in
6621 * our error message.
6623 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6624 if (err2)
6625 goto done;
6626 err = NULL;
6629 if (worktree &&
6630 strcmp(got_worktree_get_head_ref_name(worktree),
6631 got_ref_get_name(ref)) == 0) {
6632 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6633 "will not delete this work tree's current branch");
6634 goto done;
6637 err = delete_ref(repo, ref);
6638 done:
6639 if (ref)
6640 got_ref_close(ref);
6641 free(refname);
6642 free(remote_refname);
6643 return err;
6646 static const struct got_error *
6647 add_branch(struct got_repository *repo, const char *branch_name,
6648 struct got_object_id *base_commit_id)
6650 const struct got_error *err = NULL;
6651 struct got_reference *ref = NULL;
6652 char *base_refname = NULL, *refname = NULL;
6655 * Don't let the user create a branch name with a leading '-'.
6656 * While technically a valid reference name, this case is usually
6657 * an unintended typo.
6659 if (branch_name[0] == '-')
6660 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6662 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6663 branch_name += 11;
6665 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6666 err = got_error_from_errno("asprintf");
6667 goto done;
6670 err = got_ref_open(&ref, repo, refname, 0);
6671 if (err == NULL) {
6672 err = got_error(GOT_ERR_BRANCH_EXISTS);
6673 goto done;
6674 } else if (err->code != GOT_ERR_NOT_REF)
6675 goto done;
6677 err = got_ref_alloc(&ref, refname, base_commit_id);
6678 if (err)
6679 goto done;
6681 err = got_ref_write(ref, repo);
6682 done:
6683 if (ref)
6684 got_ref_close(ref);
6685 free(base_refname);
6686 free(refname);
6687 return err;
6690 static const struct got_error *
6691 cmd_branch(int argc, char *argv[])
6693 const struct got_error *error = NULL;
6694 struct got_repository *repo = NULL;
6695 struct got_worktree *worktree = NULL;
6696 char *cwd = NULL, *repo_path = NULL;
6697 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6698 const char *delref = NULL, *commit_id_arg = NULL;
6699 struct got_reference *ref = NULL;
6700 struct got_pathlist_head paths;
6701 struct got_pathlist_entry *pe;
6702 struct got_object_id *commit_id = NULL;
6703 char *commit_id_str = NULL;
6704 int *pack_fds = NULL;
6706 TAILQ_INIT(&paths);
6708 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6709 switch (ch) {
6710 case 'c':
6711 commit_id_arg = optarg;
6712 break;
6713 case 'd':
6714 delref = optarg;
6715 break;
6716 case 'r':
6717 repo_path = realpath(optarg, NULL);
6718 if (repo_path == NULL)
6719 return got_error_from_errno2("realpath",
6720 optarg);
6721 got_path_strip_trailing_slashes(repo_path);
6722 break;
6723 case 'l':
6724 do_list = 1;
6725 break;
6726 case 'n':
6727 do_update = 0;
6728 break;
6729 case 't':
6730 sort_by_time = 1;
6731 break;
6732 default:
6733 usage_branch();
6734 /* NOTREACHED */
6738 if (do_list && delref)
6739 option_conflict('l', 'd');
6740 if (sort_by_time && !do_list)
6741 errx(1, "-t option requires -l option");
6743 argc -= optind;
6744 argv += optind;
6746 if (!do_list && !delref && argc == 0)
6747 do_show = 1;
6749 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6750 errx(1, "-c option can only be used when creating a branch");
6752 if (do_list || delref) {
6753 if (argc > 0)
6754 usage_branch();
6755 } else if (!do_show && argc != 1)
6756 usage_branch();
6758 #ifndef PROFILE
6759 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6760 "sendfd unveil", NULL) == -1)
6761 err(1, "pledge");
6762 #endif
6763 cwd = getcwd(NULL, 0);
6764 if (cwd == NULL) {
6765 error = got_error_from_errno("getcwd");
6766 goto done;
6769 error = got_repo_pack_fds_open(&pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 if (repo_path == NULL) {
6774 error = got_worktree_open(&worktree, cwd);
6775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6776 goto done;
6777 else
6778 error = NULL;
6779 if (worktree) {
6780 repo_path =
6781 strdup(got_worktree_get_repo_path(worktree));
6782 if (repo_path == NULL)
6783 error = got_error_from_errno("strdup");
6784 if (error)
6785 goto done;
6786 } else {
6787 repo_path = strdup(cwd);
6788 if (repo_path == NULL) {
6789 error = got_error_from_errno("strdup");
6790 goto done;
6795 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6796 if (error != NULL)
6797 goto done;
6799 #ifndef PROFILE
6800 if (do_list || do_show) {
6801 /* Remove "cpath" promise. */
6802 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6803 NULL) == -1)
6804 err(1, "pledge");
6806 #endif
6808 error = apply_unveil(got_repo_get_path(repo), do_list,
6809 worktree ? got_worktree_get_root_path(worktree) : NULL);
6810 if (error)
6811 goto done;
6813 if (do_show)
6814 error = show_current_branch(repo, worktree);
6815 else if (do_list)
6816 error = list_branches(repo, worktree, sort_by_time);
6817 else if (delref)
6818 error = delete_branch(repo, worktree, delref);
6819 else {
6820 struct got_reflist_head refs;
6821 TAILQ_INIT(&refs);
6822 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6823 NULL);
6824 if (error)
6825 goto done;
6826 if (commit_id_arg == NULL)
6827 commit_id_arg = worktree ?
6828 got_worktree_get_head_ref_name(worktree) :
6829 GOT_REF_HEAD;
6830 error = got_repo_match_object_id(&commit_id, NULL,
6831 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6832 got_ref_list_free(&refs);
6833 if (error)
6834 goto done;
6835 error = add_branch(repo, argv[0], commit_id);
6836 if (error)
6837 goto done;
6838 if (worktree && do_update) {
6839 struct got_update_progress_arg upa;
6840 char *branch_refname = NULL;
6842 error = got_object_id_str(&commit_id_str, commit_id);
6843 if (error)
6844 goto done;
6845 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6846 worktree);
6847 if (error)
6848 goto done;
6849 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6850 == -1) {
6851 error = got_error_from_errno("asprintf");
6852 goto done;
6854 error = got_ref_open(&ref, repo, branch_refname, 0);
6855 free(branch_refname);
6856 if (error)
6857 goto done;
6858 error = switch_head_ref(ref, commit_id, worktree,
6859 repo);
6860 if (error)
6861 goto done;
6862 error = got_worktree_set_base_commit_id(worktree, repo,
6863 commit_id);
6864 if (error)
6865 goto done;
6866 memset(&upa, 0, sizeof(upa));
6867 error = got_worktree_checkout_files(worktree, &paths,
6868 repo, update_progress, &upa, check_cancelled,
6869 NULL);
6870 if (error)
6871 goto done;
6872 if (upa.did_something) {
6873 printf("Updated to %s: %s\n",
6874 got_worktree_get_head_ref_name(worktree),
6875 commit_id_str);
6877 print_update_progress_stats(&upa);
6880 done:
6881 if (ref)
6882 got_ref_close(ref);
6883 if (repo) {
6884 const struct got_error *close_err = got_repo_close(repo);
6885 if (error == NULL)
6886 error = close_err;
6888 if (worktree)
6889 got_worktree_close(worktree);
6890 if (pack_fds) {
6891 const struct got_error *pack_err =
6892 got_repo_pack_fds_close(pack_fds);
6893 if (error == NULL)
6894 error = pack_err;
6896 free(cwd);
6897 free(repo_path);
6898 free(commit_id);
6899 free(commit_id_str);
6900 TAILQ_FOREACH(pe, &paths, entry)
6901 free((char *)pe->path);
6902 got_pathlist_free(&paths);
6903 return error;
6907 __dead static void
6908 usage_tag(void)
6910 fprintf(stderr,
6911 "usage: %s tag [-c commit] [-r repository] [-l] "
6912 "[-m message] [-s signer_id] name\n",
6913 getprogname());
6914 exit(1);
6917 #if 0
6918 static const struct got_error *
6919 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6921 const struct got_error *err = NULL;
6922 struct got_reflist_entry *re, *se, *new;
6923 struct got_object_id *re_id, *se_id;
6924 struct got_tag_object *re_tag, *se_tag;
6925 time_t re_time, se_time;
6927 STAILQ_FOREACH(re, tags, entry) {
6928 se = STAILQ_FIRST(sorted);
6929 if (se == NULL) {
6930 err = got_reflist_entry_dup(&new, re);
6931 if (err)
6932 return err;
6933 STAILQ_INSERT_HEAD(sorted, new, entry);
6934 continue;
6935 } else {
6936 err = got_ref_resolve(&re_id, repo, re->ref);
6937 if (err)
6938 break;
6939 err = got_object_open_as_tag(&re_tag, repo, re_id);
6940 free(re_id);
6941 if (err)
6942 break;
6943 re_time = got_object_tag_get_tagger_time(re_tag);
6944 got_object_tag_close(re_tag);
6947 while (se) {
6948 err = got_ref_resolve(&se_id, repo, re->ref);
6949 if (err)
6950 break;
6951 err = got_object_open_as_tag(&se_tag, repo, se_id);
6952 free(se_id);
6953 if (err)
6954 break;
6955 se_time = got_object_tag_get_tagger_time(se_tag);
6956 got_object_tag_close(se_tag);
6958 if (se_time > re_time) {
6959 err = got_reflist_entry_dup(&new, re);
6960 if (err)
6961 return err;
6962 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6963 break;
6965 se = STAILQ_NEXT(se, entry);
6966 continue;
6969 done:
6970 return err;
6972 #endif
6974 static const struct got_error *
6975 get_tag_refname(char **refname, const char *tag_name)
6977 const struct got_error *err;
6979 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6980 *refname = strdup(tag_name);
6981 if (*refname == NULL)
6982 return got_error_from_errno("strdup");
6983 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6984 err = got_error_from_errno("asprintf");
6985 *refname = NULL;
6986 return err;
6989 return NULL;
6992 static const struct got_error *
6993 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6994 const char *allowed_signers, const char *revoked_signers, int verbosity)
6996 static const struct got_error *err = NULL;
6997 struct got_reflist_head refs;
6998 struct got_reflist_entry *re;
6999 char *wanted_refname = NULL;
7000 int bad_sigs = 0;
7002 TAILQ_INIT(&refs);
7004 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7005 if (err)
7006 return err;
7008 if (tag_name) {
7009 struct got_reference *ref;
7010 err = get_tag_refname(&wanted_refname, tag_name);
7011 if (err)
7012 goto done;
7013 /* Wanted tag reference should exist. */
7014 err = got_ref_open(&ref, repo, wanted_refname, 0);
7015 if (err)
7016 goto done;
7017 got_ref_close(ref);
7020 TAILQ_FOREACH(re, &refs, entry) {
7021 const char *refname;
7022 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7023 char datebuf[26];
7024 const char *tagger, *ssh_sig = NULL;
7025 char *sig_msg = NULL;
7026 time_t tagger_time;
7027 struct got_object_id *id;
7028 struct got_tag_object *tag;
7029 struct got_commit_object *commit = NULL;
7031 refname = got_ref_get_name(re->ref);
7032 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7033 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7034 continue;
7035 refname += 10;
7036 refstr = got_ref_to_str(re->ref);
7037 if (refstr == NULL) {
7038 err = got_error_from_errno("got_ref_to_str");
7039 break;
7042 err = got_ref_resolve(&id, repo, re->ref);
7043 if (err)
7044 break;
7045 err = got_object_open_as_tag(&tag, repo, id);
7046 if (err) {
7047 if (err->code != GOT_ERR_OBJ_TYPE) {
7048 free(id);
7049 break;
7051 /* "lightweight" tag */
7052 err = got_object_open_as_commit(&commit, repo, id);
7053 if (err) {
7054 free(id);
7055 break;
7057 tagger = got_object_commit_get_committer(commit);
7058 tagger_time =
7059 got_object_commit_get_committer_time(commit);
7060 err = got_object_id_str(&id_str, id);
7061 free(id);
7062 if (err)
7063 break;
7064 } else {
7065 free(id);
7066 tagger = got_object_tag_get_tagger(tag);
7067 tagger_time = got_object_tag_get_tagger_time(tag);
7068 err = got_object_id_str(&id_str,
7069 got_object_tag_get_object_id(tag));
7070 if (err)
7071 break;
7074 if (verify_tags) {
7075 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7076 got_object_tag_get_message(tag));
7077 if (ssh_sig && allowed_signers == NULL) {
7078 err = got_error_msg(
7079 GOT_ERR_VERIFY_TAG_SIGNATURE,
7080 "SSH signature verification requires "
7081 "setting allowed_signers in "
7082 "got.conf(5)");
7083 break;
7087 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7088 free(refstr);
7089 printf("from: %s\n", tagger);
7090 datestr = get_datestr(&tagger_time, datebuf);
7091 if (datestr)
7092 printf("date: %s UTC\n", datestr);
7093 if (commit)
7094 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7095 else {
7096 switch (got_object_tag_get_object_type(tag)) {
7097 case GOT_OBJ_TYPE_BLOB:
7098 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7099 id_str);
7100 break;
7101 case GOT_OBJ_TYPE_TREE:
7102 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7103 id_str);
7104 break;
7105 case GOT_OBJ_TYPE_COMMIT:
7106 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7107 id_str);
7108 break;
7109 case GOT_OBJ_TYPE_TAG:
7110 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7111 id_str);
7112 break;
7113 default:
7114 break;
7117 free(id_str);
7119 if (ssh_sig) {
7120 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7121 allowed_signers, revoked_signers, verbosity);
7122 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7123 bad_sigs = 1;
7124 else if (err)
7125 break;
7126 printf("signature: %s", sig_msg);
7127 free(sig_msg);
7128 sig_msg = NULL;
7131 if (commit) {
7132 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7133 if (err)
7134 break;
7135 got_object_commit_close(commit);
7136 } else {
7137 tagmsg0 = strdup(got_object_tag_get_message(tag));
7138 got_object_tag_close(tag);
7139 if (tagmsg0 == NULL) {
7140 err = got_error_from_errno("strdup");
7141 break;
7145 tagmsg = tagmsg0;
7146 do {
7147 line = strsep(&tagmsg, "\n");
7148 if (line)
7149 printf(" %s\n", line);
7150 } while (line);
7151 free(tagmsg0);
7153 done:
7154 got_ref_list_free(&refs);
7155 free(wanted_refname);
7157 if (err == NULL && bad_sigs)
7158 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7159 return err;
7162 static const struct got_error *
7163 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7164 const char *tag_name, const char *repo_path)
7166 const struct got_error *err = NULL;
7167 char *template = NULL, *initial_content = NULL;
7168 char *editor = NULL;
7169 int initial_content_len;
7170 int fd = -1;
7172 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7173 err = got_error_from_errno("asprintf");
7174 goto done;
7177 initial_content_len = asprintf(&initial_content,
7178 "\n# tagging commit %s as %s\n",
7179 commit_id_str, tag_name);
7180 if (initial_content_len == -1) {
7181 err = got_error_from_errno("asprintf");
7182 goto done;
7185 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7186 if (err)
7187 goto done;
7189 if (write(fd, initial_content, initial_content_len) == -1) {
7190 err = got_error_from_errno2("write", *tagmsg_path);
7191 goto done;
7194 err = get_editor(&editor);
7195 if (err)
7196 goto done;
7197 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7198 initial_content_len, 1);
7199 done:
7200 free(initial_content);
7201 free(template);
7202 free(editor);
7204 if (fd != -1 && close(fd) == -1 && err == NULL)
7205 err = got_error_from_errno2("close", *tagmsg_path);
7207 if (err) {
7208 free(*tagmsg);
7209 *tagmsg = NULL;
7211 return err;
7214 static const struct got_error *
7215 add_tag(struct got_repository *repo, const char *tagger,
7216 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7217 const char *signer_id, int verbosity)
7219 const struct got_error *err = NULL;
7220 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7221 char *label = NULL, *commit_id_str = NULL;
7222 struct got_reference *ref = NULL;
7223 char *refname = NULL, *tagmsg = NULL;
7224 char *tagmsg_path = NULL, *tag_id_str = NULL;
7225 int preserve_tagmsg = 0;
7226 struct got_reflist_head refs;
7228 TAILQ_INIT(&refs);
7231 * Don't let the user create a tag name with a leading '-'.
7232 * While technically a valid reference name, this case is usually
7233 * an unintended typo.
7235 if (tag_name[0] == '-')
7236 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7238 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7239 if (err)
7240 goto done;
7242 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7243 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7244 if (err)
7245 goto done;
7247 err = got_object_id_str(&commit_id_str, commit_id);
7248 if (err)
7249 goto done;
7251 err = get_tag_refname(&refname, tag_name);
7252 if (err)
7253 goto done;
7254 if (strncmp("refs/tags/", tag_name, 10) == 0)
7255 tag_name += 10;
7257 err = got_ref_open(&ref, repo, refname, 0);
7258 if (err == NULL) {
7259 err = got_error(GOT_ERR_TAG_EXISTS);
7260 goto done;
7261 } else if (err->code != GOT_ERR_NOT_REF)
7262 goto done;
7264 if (tagmsg_arg == NULL) {
7265 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7266 tag_name, got_repo_get_path(repo));
7267 if (err) {
7268 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7269 tagmsg_path != NULL)
7270 preserve_tagmsg = 1;
7271 goto done;
7273 /* Editor is done; we can now apply unveil(2) */
7274 err = got_sigs_apply_unveil();
7275 if (err)
7276 goto done;
7277 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7278 if (err)
7279 goto done;
7282 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7283 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7284 verbosity);
7285 if (err) {
7286 if (tagmsg_path)
7287 preserve_tagmsg = 1;
7288 goto done;
7291 err = got_ref_alloc(&ref, refname, tag_id);
7292 if (err) {
7293 if (tagmsg_path)
7294 preserve_tagmsg = 1;
7295 goto done;
7298 err = got_ref_write(ref, repo);
7299 if (err) {
7300 if (tagmsg_path)
7301 preserve_tagmsg = 1;
7302 goto done;
7305 err = got_object_id_str(&tag_id_str, tag_id);
7306 if (err) {
7307 if (tagmsg_path)
7308 preserve_tagmsg = 1;
7309 goto done;
7311 printf("Created tag %s\n", tag_id_str);
7312 done:
7313 if (preserve_tagmsg) {
7314 fprintf(stderr, "%s: tag message preserved in %s\n",
7315 getprogname(), tagmsg_path);
7316 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7317 err = got_error_from_errno2("unlink", tagmsg_path);
7318 free(tag_id_str);
7319 if (ref)
7320 got_ref_close(ref);
7321 free(commit_id);
7322 free(commit_id_str);
7323 free(refname);
7324 free(tagmsg);
7325 free(tagmsg_path);
7326 got_ref_list_free(&refs);
7327 return err;
7330 static const struct got_error *
7331 cmd_tag(int argc, char *argv[])
7333 const struct got_error *error = NULL;
7334 struct got_repository *repo = NULL;
7335 struct got_worktree *worktree = NULL;
7336 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7337 char *gitconfig_path = NULL, *tagger = NULL;
7338 char *allowed_signers = NULL, *revoked_signers = NULL;
7339 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7340 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7341 const char *signer_id = NULL;
7342 int *pack_fds = NULL;
7344 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7345 switch (ch) {
7346 case 'c':
7347 commit_id_arg = optarg;
7348 break;
7349 case 'm':
7350 tagmsg = optarg;
7351 break;
7352 case 'r':
7353 repo_path = realpath(optarg, NULL);
7354 if (repo_path == NULL)
7355 return got_error_from_errno2("realpath",
7356 optarg);
7357 got_path_strip_trailing_slashes(repo_path);
7358 break;
7359 case 'l':
7360 do_list = 1;
7361 break;
7362 case 's':
7363 signer_id = optarg;
7364 break;
7365 case 'V':
7366 verify_tags = 1;
7367 break;
7368 case 'v':
7369 if (verbosity < 0)
7370 verbosity = 0;
7371 else if (verbosity < 3)
7372 verbosity++;
7373 break;
7374 default:
7375 usage_tag();
7376 /* NOTREACHED */
7380 argc -= optind;
7381 argv += optind;
7383 if (do_list) {
7384 if (commit_id_arg != NULL)
7385 errx(1,
7386 "-c option can only be used when creating a tag");
7387 if (tagmsg)
7388 option_conflict('l', 'm');
7389 if (argc > 1)
7390 usage_tag();
7391 } else if (argc != 1)
7392 usage_tag();
7394 if (argc == 1)
7395 tag_name = argv[0];
7397 #ifndef PROFILE
7398 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7399 "sendfd unveil", NULL) == -1)
7400 err(1, "pledge");
7401 #endif
7402 cwd = getcwd(NULL, 0);
7403 if (cwd == NULL) {
7404 error = got_error_from_errno("getcwd");
7405 goto done;
7408 error = got_repo_pack_fds_open(&pack_fds);
7409 if (error != NULL)
7410 goto done;
7412 if (repo_path == NULL) {
7413 error = got_worktree_open(&worktree, cwd);
7414 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7415 goto done;
7416 else
7417 error = NULL;
7418 if (worktree) {
7419 repo_path =
7420 strdup(got_worktree_get_repo_path(worktree));
7421 if (repo_path == NULL)
7422 error = got_error_from_errno("strdup");
7423 if (error)
7424 goto done;
7425 } else {
7426 repo_path = strdup(cwd);
7427 if (repo_path == NULL) {
7428 error = got_error_from_errno("strdup");
7429 goto done;
7434 if (do_list || verify_tags) {
7435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7436 if (error != NULL)
7437 goto done;
7438 error = get_allowed_signers(&allowed_signers, repo, worktree);
7439 if (error)
7440 goto done;
7441 error = get_revoked_signers(&revoked_signers, repo, worktree);
7442 if (error)
7443 goto done;
7444 if (worktree) {
7445 /* Release work tree lock. */
7446 got_worktree_close(worktree);
7447 worktree = NULL;
7451 * Remove "cpath" promise unless needed for signature tmpfile
7452 * creation.
7454 if (verify_tags)
7455 got_sigs_apply_unveil();
7456 else {
7457 #ifndef PROFILE
7458 if (pledge("stdio rpath wpath flock proc exec sendfd "
7459 "unveil", NULL) == -1)
7460 err(1, "pledge");
7461 #endif
7463 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7464 if (error)
7465 goto done;
7466 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7467 revoked_signers, verbosity);
7468 } else {
7469 error = get_gitconfig_path(&gitconfig_path);
7470 if (error)
7471 goto done;
7472 error = got_repo_open(&repo, repo_path, gitconfig_path,
7473 pack_fds);
7474 if (error != NULL)
7475 goto done;
7477 error = get_author(&tagger, repo, worktree);
7478 if (error)
7479 goto done;
7480 if (worktree) {
7481 /* Release work tree lock. */
7482 got_worktree_close(worktree);
7483 worktree = NULL;
7486 if (tagmsg) {
7487 if (signer_id) {
7488 error = got_sigs_apply_unveil();
7489 if (error)
7490 goto done;
7492 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7493 if (error)
7494 goto done;
7497 if (commit_id_arg == NULL) {
7498 struct got_reference *head_ref;
7499 struct got_object_id *commit_id;
7500 error = got_ref_open(&head_ref, repo,
7501 worktree ? got_worktree_get_head_ref_name(worktree)
7502 : GOT_REF_HEAD, 0);
7503 if (error)
7504 goto done;
7505 error = got_ref_resolve(&commit_id, repo, head_ref);
7506 got_ref_close(head_ref);
7507 if (error)
7508 goto done;
7509 error = got_object_id_str(&commit_id_str, commit_id);
7510 free(commit_id);
7511 if (error)
7512 goto done;
7515 error = add_tag(repo, tagger, tag_name,
7516 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7517 signer_id, verbosity);
7519 done:
7520 if (repo) {
7521 const struct got_error *close_err = got_repo_close(repo);
7522 if (error == NULL)
7523 error = close_err;
7525 if (worktree)
7526 got_worktree_close(worktree);
7527 if (pack_fds) {
7528 const struct got_error *pack_err =
7529 got_repo_pack_fds_close(pack_fds);
7530 if (error == NULL)
7531 error = pack_err;
7533 free(cwd);
7534 free(repo_path);
7535 free(gitconfig_path);
7536 free(commit_id_str);
7537 free(tagger);
7538 free(allowed_signers);
7539 free(revoked_signers);
7540 return error;
7543 __dead static void
7544 usage_add(void)
7546 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7547 getprogname());
7548 exit(1);
7551 static const struct got_error *
7552 add_progress(void *arg, unsigned char status, const char *path)
7554 while (path[0] == '/')
7555 path++;
7556 printf("%c %s\n", status, path);
7557 return NULL;
7560 static const struct got_error *
7561 cmd_add(int argc, char *argv[])
7563 const struct got_error *error = NULL;
7564 struct got_repository *repo = NULL;
7565 struct got_worktree *worktree = NULL;
7566 char *cwd = NULL;
7567 struct got_pathlist_head paths;
7568 struct got_pathlist_entry *pe;
7569 int ch, can_recurse = 0, no_ignores = 0;
7570 int *pack_fds = NULL;
7572 TAILQ_INIT(&paths);
7574 while ((ch = getopt(argc, argv, "IR")) != -1) {
7575 switch (ch) {
7576 case 'I':
7577 no_ignores = 1;
7578 break;
7579 case 'R':
7580 can_recurse = 1;
7581 break;
7582 default:
7583 usage_add();
7584 /* NOTREACHED */
7588 argc -= optind;
7589 argv += optind;
7591 #ifndef PROFILE
7592 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7593 NULL) == -1)
7594 err(1, "pledge");
7595 #endif
7596 if (argc < 1)
7597 usage_add();
7599 cwd = getcwd(NULL, 0);
7600 if (cwd == NULL) {
7601 error = got_error_from_errno("getcwd");
7602 goto done;
7605 error = got_repo_pack_fds_open(&pack_fds);
7606 if (error != NULL)
7607 goto done;
7609 error = got_worktree_open(&worktree, cwd);
7610 if (error) {
7611 if (error->code == GOT_ERR_NOT_WORKTREE)
7612 error = wrap_not_worktree_error(error, "add", cwd);
7613 goto done;
7616 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7617 NULL, pack_fds);
7618 if (error != NULL)
7619 goto done;
7621 error = apply_unveil(got_repo_get_path(repo), 1,
7622 got_worktree_get_root_path(worktree));
7623 if (error)
7624 goto done;
7626 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7627 if (error)
7628 goto done;
7630 if (!can_recurse) {
7631 char *ondisk_path;
7632 struct stat sb;
7633 TAILQ_FOREACH(pe, &paths, entry) {
7634 if (asprintf(&ondisk_path, "%s/%s",
7635 got_worktree_get_root_path(worktree),
7636 pe->path) == -1) {
7637 error = got_error_from_errno("asprintf");
7638 goto done;
7640 if (lstat(ondisk_path, &sb) == -1) {
7641 if (errno == ENOENT) {
7642 free(ondisk_path);
7643 continue;
7645 error = got_error_from_errno2("lstat",
7646 ondisk_path);
7647 free(ondisk_path);
7648 goto done;
7650 free(ondisk_path);
7651 if (S_ISDIR(sb.st_mode)) {
7652 error = got_error_msg(GOT_ERR_BAD_PATH,
7653 "adding directories requires -R option");
7654 goto done;
7659 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7660 NULL, repo, no_ignores);
7661 done:
7662 if (repo) {
7663 const struct got_error *close_err = got_repo_close(repo);
7664 if (error == NULL)
7665 error = close_err;
7667 if (worktree)
7668 got_worktree_close(worktree);
7669 if (pack_fds) {
7670 const struct got_error *pack_err =
7671 got_repo_pack_fds_close(pack_fds);
7672 if (error == NULL)
7673 error = pack_err;
7675 TAILQ_FOREACH(pe, &paths, entry)
7676 free((char *)pe->path);
7677 got_pathlist_free(&paths);
7678 free(cwd);
7679 return error;
7682 __dead static void
7683 usage_remove(void)
7685 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7686 "path ...\n", getprogname());
7687 exit(1);
7690 static const struct got_error *
7691 print_remove_status(void *arg, unsigned char status,
7692 unsigned char staged_status, const char *path)
7694 while (path[0] == '/')
7695 path++;
7696 if (status == GOT_STATUS_NONEXISTENT)
7697 return NULL;
7698 if (status == staged_status && (status == GOT_STATUS_DELETE))
7699 status = GOT_STATUS_NO_CHANGE;
7700 printf("%c%c %s\n", status, staged_status, path);
7701 return NULL;
7704 static const struct got_error *
7705 cmd_remove(int argc, char *argv[])
7707 const struct got_error *error = NULL;
7708 struct got_worktree *worktree = NULL;
7709 struct got_repository *repo = NULL;
7710 const char *status_codes = NULL;
7711 char *cwd = NULL;
7712 struct got_pathlist_head paths;
7713 struct got_pathlist_entry *pe;
7714 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7715 int ignore_missing_paths = 0;
7716 int *pack_fds = NULL;
7718 TAILQ_INIT(&paths);
7720 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7721 switch (ch) {
7722 case 'f':
7723 delete_local_mods = 1;
7724 ignore_missing_paths = 1;
7725 break;
7726 case 'k':
7727 keep_on_disk = 1;
7728 break;
7729 case 'R':
7730 can_recurse = 1;
7731 break;
7732 case 's':
7733 for (i = 0; i < strlen(optarg); i++) {
7734 switch (optarg[i]) {
7735 case GOT_STATUS_MODIFY:
7736 delete_local_mods = 1;
7737 break;
7738 case GOT_STATUS_MISSING:
7739 ignore_missing_paths = 1;
7740 break;
7741 default:
7742 errx(1, "invalid status code '%c'",
7743 optarg[i]);
7746 status_codes = optarg;
7747 break;
7748 default:
7749 usage_remove();
7750 /* NOTREACHED */
7754 argc -= optind;
7755 argv += optind;
7757 #ifndef PROFILE
7758 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7759 NULL) == -1)
7760 err(1, "pledge");
7761 #endif
7762 if (argc < 1)
7763 usage_remove();
7765 cwd = getcwd(NULL, 0);
7766 if (cwd == NULL) {
7767 error = got_error_from_errno("getcwd");
7768 goto done;
7771 error = got_repo_pack_fds_open(&pack_fds);
7772 if (error != NULL)
7773 goto done;
7775 error = got_worktree_open(&worktree, cwd);
7776 if (error) {
7777 if (error->code == GOT_ERR_NOT_WORKTREE)
7778 error = wrap_not_worktree_error(error, "remove", cwd);
7779 goto done;
7782 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7783 NULL, pack_fds);
7784 if (error)
7785 goto done;
7787 error = apply_unveil(got_repo_get_path(repo), 1,
7788 got_worktree_get_root_path(worktree));
7789 if (error)
7790 goto done;
7792 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7793 if (error)
7794 goto done;
7796 if (!can_recurse) {
7797 char *ondisk_path;
7798 struct stat sb;
7799 TAILQ_FOREACH(pe, &paths, entry) {
7800 if (asprintf(&ondisk_path, "%s/%s",
7801 got_worktree_get_root_path(worktree),
7802 pe->path) == -1) {
7803 error = got_error_from_errno("asprintf");
7804 goto done;
7806 if (lstat(ondisk_path, &sb) == -1) {
7807 if (errno == ENOENT) {
7808 free(ondisk_path);
7809 continue;
7811 error = got_error_from_errno2("lstat",
7812 ondisk_path);
7813 free(ondisk_path);
7814 goto done;
7816 free(ondisk_path);
7817 if (S_ISDIR(sb.st_mode)) {
7818 error = got_error_msg(GOT_ERR_BAD_PATH,
7819 "removing directories requires -R option");
7820 goto done;
7825 error = got_worktree_schedule_delete(worktree, &paths,
7826 delete_local_mods, status_codes, print_remove_status, NULL,
7827 repo, keep_on_disk, ignore_missing_paths);
7828 done:
7829 if (repo) {
7830 const struct got_error *close_err = got_repo_close(repo);
7831 if (error == NULL)
7832 error = close_err;
7834 if (worktree)
7835 got_worktree_close(worktree);
7836 if (pack_fds) {
7837 const struct got_error *pack_err =
7838 got_repo_pack_fds_close(pack_fds);
7839 if (error == NULL)
7840 error = pack_err;
7842 TAILQ_FOREACH(pe, &paths, entry)
7843 free((char *)pe->path);
7844 got_pathlist_free(&paths);
7845 free(cwd);
7846 return error;
7849 __dead static void
7850 usage_patch(void)
7852 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7853 "[-R] [patchfile]\n", getprogname());
7854 exit(1);
7857 static const struct got_error *
7858 patch_from_stdin(int *patchfd)
7860 const struct got_error *err = NULL;
7861 ssize_t r;
7862 char *path, buf[BUFSIZ];
7863 sig_t sighup, sigint, sigquit;
7865 err = got_opentemp_named_fd(&path, patchfd,
7866 GOT_TMPDIR_STR "/got-patch");
7867 if (err)
7868 return err;
7869 unlink(path);
7870 free(path);
7872 sighup = signal(SIGHUP, SIG_DFL);
7873 sigint = signal(SIGINT, SIG_DFL);
7874 sigquit = signal(SIGQUIT, SIG_DFL);
7876 for (;;) {
7877 r = read(0, buf, sizeof(buf));
7878 if (r == -1) {
7879 err = got_error_from_errno("read");
7880 break;
7882 if (r == 0)
7883 break;
7884 if (write(*patchfd, buf, r) == -1) {
7885 err = got_error_from_errno("write");
7886 break;
7890 signal(SIGHUP, sighup);
7891 signal(SIGINT, sigint);
7892 signal(SIGQUIT, sigquit);
7894 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7895 err = got_error_from_errno("lseek");
7897 if (err != NULL) {
7898 close(*patchfd);
7899 *patchfd = -1;
7902 return err;
7905 static const struct got_error *
7906 patch_progress(void *arg, const char *old, const char *new,
7907 unsigned char status, const struct got_error *error, int old_from,
7908 int old_lines, int new_from, int new_lines, int offset,
7909 int ws_mangled, const struct got_error *hunk_err)
7911 const char *path = new == NULL ? old : new;
7913 while (*path == '/')
7914 path++;
7916 if (status != 0)
7917 printf("%c %s\n", status, path);
7919 if (error != NULL)
7920 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7922 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7923 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7924 old_lines, new_from, new_lines);
7925 if (hunk_err != NULL)
7926 printf("%s\n", hunk_err->msg);
7927 else if (offset != 0)
7928 printf("applied with offset %d\n", offset);
7929 else
7930 printf("hunk contains mangled whitespace\n");
7933 return NULL;
7936 static const struct got_error *
7937 cmd_patch(int argc, char *argv[])
7939 const struct got_error *error = NULL, *close_error = NULL;
7940 struct got_worktree *worktree = NULL;
7941 struct got_repository *repo = NULL;
7942 const char *errstr;
7943 char *cwd = NULL;
7944 int ch, nop = 0, strip = -1, reverse = 0;
7945 int patchfd;
7946 int *pack_fds = NULL;
7948 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7949 switch (ch) {
7950 case 'n':
7951 nop = 1;
7952 break;
7953 case 'p':
7954 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7955 if (errstr != NULL)
7956 errx(1, "pathname strip count is %s: %s",
7957 errstr, optarg);
7958 break;
7959 case 'R':
7960 reverse = 1;
7961 break;
7962 default:
7963 usage_patch();
7964 /* NOTREACHED */
7968 argc -= optind;
7969 argv += optind;
7971 if (argc == 0) {
7972 error = patch_from_stdin(&patchfd);
7973 if (error)
7974 return error;
7975 } else if (argc == 1) {
7976 patchfd = open(argv[0], O_RDONLY);
7977 if (patchfd == -1) {
7978 error = got_error_from_errno2("open", argv[0]);
7979 return error;
7981 } else
7982 usage_patch();
7984 if ((cwd = getcwd(NULL, 0)) == NULL) {
7985 error = got_error_from_errno("getcwd");
7986 goto done;
7989 error = got_repo_pack_fds_open(&pack_fds);
7990 if (error != NULL)
7991 goto done;
7993 error = got_worktree_open(&worktree, cwd);
7994 if (error != NULL)
7995 goto done;
7997 const char *repo_path = got_worktree_get_repo_path(worktree);
7998 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7999 if (error != NULL)
8000 goto done;
8002 error = apply_unveil(got_repo_get_path(repo), 0,
8003 got_worktree_get_root_path(worktree));
8004 if (error != NULL)
8005 goto done;
8007 #ifndef PROFILE
8008 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
8009 NULL) == -1)
8010 err(1, "pledge");
8011 #endif
8013 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8014 &patch_progress, NULL, check_cancelled, NULL);
8016 done:
8017 if (repo) {
8018 close_error = got_repo_close(repo);
8019 if (error == NULL)
8020 error = close_error;
8022 if (worktree != NULL) {
8023 close_error = got_worktree_close(worktree);
8024 if (error == NULL)
8025 error = close_error;
8027 if (pack_fds) {
8028 const struct got_error *pack_err =
8029 got_repo_pack_fds_close(pack_fds);
8030 if (error == NULL)
8031 error = pack_err;
8033 free(cwd);
8034 return error;
8037 __dead static void
8038 usage_revert(void)
8040 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8041 "path ...\n", getprogname());
8042 exit(1);
8045 static const struct got_error *
8046 revert_progress(void *arg, unsigned char status, const char *path)
8048 if (status == GOT_STATUS_UNVERSIONED)
8049 return NULL;
8051 while (path[0] == '/')
8052 path++;
8053 printf("%c %s\n", status, path);
8054 return NULL;
8057 struct choose_patch_arg {
8058 FILE *patch_script_file;
8059 const char *action;
8062 static const struct got_error *
8063 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8064 int nchanges, const char *action)
8066 const struct got_error *err;
8067 char *line = NULL;
8068 size_t linesize = 0;
8069 ssize_t linelen;
8071 switch (status) {
8072 case GOT_STATUS_ADD:
8073 printf("A %s\n%s this addition? [y/n] ", path, action);
8074 break;
8075 case GOT_STATUS_DELETE:
8076 printf("D %s\n%s this deletion? [y/n] ", path, action);
8077 break;
8078 case GOT_STATUS_MODIFY:
8079 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8080 return got_error_from_errno("fseek");
8081 printf(GOT_COMMIT_SEP_STR);
8082 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8083 printf("%s", line);
8084 if (linelen == -1 && ferror(patch_file)) {
8085 err = got_error_from_errno("getline");
8086 free(line);
8087 return err;
8089 free(line);
8090 printf(GOT_COMMIT_SEP_STR);
8091 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8092 path, n, nchanges, action);
8093 break;
8094 default:
8095 return got_error_path(path, GOT_ERR_FILE_STATUS);
8098 return NULL;
8101 static const struct got_error *
8102 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8103 FILE *patch_file, int n, int nchanges)
8105 const struct got_error *err = NULL;
8106 char *line = NULL;
8107 size_t linesize = 0;
8108 ssize_t linelen;
8109 int resp = ' ';
8110 struct choose_patch_arg *a = arg;
8112 *choice = GOT_PATCH_CHOICE_NONE;
8114 if (a->patch_script_file) {
8115 char *nl;
8116 err = show_change(status, path, patch_file, n, nchanges,
8117 a->action);
8118 if (err)
8119 return err;
8120 linelen = getline(&line, &linesize, a->patch_script_file);
8121 if (linelen == -1) {
8122 if (ferror(a->patch_script_file))
8123 return got_error_from_errno("getline");
8124 return NULL;
8126 nl = strchr(line, '\n');
8127 if (nl)
8128 *nl = '\0';
8129 if (strcmp(line, "y") == 0) {
8130 *choice = GOT_PATCH_CHOICE_YES;
8131 printf("y\n");
8132 } else if (strcmp(line, "n") == 0) {
8133 *choice = GOT_PATCH_CHOICE_NO;
8134 printf("n\n");
8135 } else if (strcmp(line, "q") == 0 &&
8136 status == GOT_STATUS_MODIFY) {
8137 *choice = GOT_PATCH_CHOICE_QUIT;
8138 printf("q\n");
8139 } else
8140 printf("invalid response '%s'\n", line);
8141 free(line);
8142 return NULL;
8145 while (resp != 'y' && resp != 'n' && resp != 'q') {
8146 err = show_change(status, path, patch_file, n, nchanges,
8147 a->action);
8148 if (err)
8149 return err;
8150 resp = getchar();
8151 if (resp == '\n')
8152 resp = getchar();
8153 if (status == GOT_STATUS_MODIFY) {
8154 if (resp != 'y' && resp != 'n' && resp != 'q') {
8155 printf("invalid response '%c'\n", resp);
8156 resp = ' ';
8158 } else if (resp != 'y' && resp != 'n') {
8159 printf("invalid response '%c'\n", resp);
8160 resp = ' ';
8164 if (resp == 'y')
8165 *choice = GOT_PATCH_CHOICE_YES;
8166 else if (resp == 'n')
8167 *choice = GOT_PATCH_CHOICE_NO;
8168 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8169 *choice = GOT_PATCH_CHOICE_QUIT;
8171 return NULL;
8174 static const struct got_error *
8175 cmd_revert(int argc, char *argv[])
8177 const struct got_error *error = NULL;
8178 struct got_worktree *worktree = NULL;
8179 struct got_repository *repo = NULL;
8180 char *cwd = NULL, *path = NULL;
8181 struct got_pathlist_head paths;
8182 struct got_pathlist_entry *pe;
8183 int ch, can_recurse = 0, pflag = 0;
8184 FILE *patch_script_file = NULL;
8185 const char *patch_script_path = NULL;
8186 struct choose_patch_arg cpa;
8187 int *pack_fds = NULL;
8189 TAILQ_INIT(&paths);
8191 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8192 switch (ch) {
8193 case 'p':
8194 pflag = 1;
8195 break;
8196 case 'F':
8197 patch_script_path = optarg;
8198 break;
8199 case 'R':
8200 can_recurse = 1;
8201 break;
8202 default:
8203 usage_revert();
8204 /* NOTREACHED */
8208 argc -= optind;
8209 argv += optind;
8211 #ifndef PROFILE
8212 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8213 "unveil", NULL) == -1)
8214 err(1, "pledge");
8215 #endif
8216 if (argc < 1)
8217 usage_revert();
8218 if (patch_script_path && !pflag)
8219 errx(1, "-F option can only be used together with -p option");
8221 cwd = getcwd(NULL, 0);
8222 if (cwd == NULL) {
8223 error = got_error_from_errno("getcwd");
8224 goto done;
8227 error = got_repo_pack_fds_open(&pack_fds);
8228 if (error != NULL)
8229 goto done;
8231 error = got_worktree_open(&worktree, cwd);
8232 if (error) {
8233 if (error->code == GOT_ERR_NOT_WORKTREE)
8234 error = wrap_not_worktree_error(error, "revert", cwd);
8235 goto done;
8238 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8239 NULL, pack_fds);
8240 if (error != NULL)
8241 goto done;
8243 if (patch_script_path) {
8244 patch_script_file = fopen(patch_script_path, "re");
8245 if (patch_script_file == NULL) {
8246 error = got_error_from_errno2("fopen",
8247 patch_script_path);
8248 goto done;
8251 error = apply_unveil(got_repo_get_path(repo), 1,
8252 got_worktree_get_root_path(worktree));
8253 if (error)
8254 goto done;
8256 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8257 if (error)
8258 goto done;
8260 if (!can_recurse) {
8261 char *ondisk_path;
8262 struct stat sb;
8263 TAILQ_FOREACH(pe, &paths, entry) {
8264 if (asprintf(&ondisk_path, "%s/%s",
8265 got_worktree_get_root_path(worktree),
8266 pe->path) == -1) {
8267 error = got_error_from_errno("asprintf");
8268 goto done;
8270 if (lstat(ondisk_path, &sb) == -1) {
8271 if (errno == ENOENT) {
8272 free(ondisk_path);
8273 continue;
8275 error = got_error_from_errno2("lstat",
8276 ondisk_path);
8277 free(ondisk_path);
8278 goto done;
8280 free(ondisk_path);
8281 if (S_ISDIR(sb.st_mode)) {
8282 error = got_error_msg(GOT_ERR_BAD_PATH,
8283 "reverting directories requires -R option");
8284 goto done;
8289 cpa.patch_script_file = patch_script_file;
8290 cpa.action = "revert";
8291 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8292 pflag ? choose_patch : NULL, &cpa, repo);
8293 done:
8294 if (patch_script_file && fclose(patch_script_file) == EOF &&
8295 error == NULL)
8296 error = got_error_from_errno2("fclose", patch_script_path);
8297 if (repo) {
8298 const struct got_error *close_err = got_repo_close(repo);
8299 if (error == NULL)
8300 error = close_err;
8302 if (worktree)
8303 got_worktree_close(worktree);
8304 if (pack_fds) {
8305 const struct got_error *pack_err =
8306 got_repo_pack_fds_close(pack_fds);
8307 if (error == NULL)
8308 error = pack_err;
8310 free(path);
8311 free(cwd);
8312 return error;
8315 __dead static void
8316 usage_commit(void)
8318 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8319 "[path ...]\n", getprogname());
8320 exit(1);
8323 struct collect_commit_logmsg_arg {
8324 const char *cmdline_log;
8325 const char *prepared_log;
8326 int non_interactive;
8327 const char *editor;
8328 const char *worktree_path;
8329 const char *branch_name;
8330 const char *repo_path;
8331 char *logmsg_path;
8335 static const struct got_error *
8336 read_prepared_logmsg(char **logmsg, const char *path)
8338 const struct got_error *err = NULL;
8339 FILE *f = NULL;
8340 struct stat sb;
8341 size_t r;
8343 *logmsg = NULL;
8344 memset(&sb, 0, sizeof(sb));
8346 f = fopen(path, "re");
8347 if (f == NULL)
8348 return got_error_from_errno2("fopen", path);
8350 if (fstat(fileno(f), &sb) == -1) {
8351 err = got_error_from_errno2("fstat", path);
8352 goto done;
8354 if (sb.st_size == 0) {
8355 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8356 goto done;
8359 *logmsg = malloc(sb.st_size + 1);
8360 if (*logmsg == NULL) {
8361 err = got_error_from_errno("malloc");
8362 goto done;
8365 r = fread(*logmsg, 1, sb.st_size, f);
8366 if (r != sb.st_size) {
8367 if (ferror(f))
8368 err = got_error_from_errno2("fread", path);
8369 else
8370 err = got_error(GOT_ERR_IO);
8371 goto done;
8373 (*logmsg)[sb.st_size] = '\0';
8374 done:
8375 if (fclose(f) == EOF && err == NULL)
8376 err = got_error_from_errno2("fclose", path);
8377 if (err) {
8378 free(*logmsg);
8379 *logmsg = NULL;
8381 return err;
8385 static const struct got_error *
8386 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8387 void *arg)
8389 char *initial_content = NULL;
8390 struct got_pathlist_entry *pe;
8391 const struct got_error *err = NULL;
8392 char *template = NULL;
8393 struct collect_commit_logmsg_arg *a = arg;
8394 int initial_content_len;
8395 int fd = -1;
8396 size_t len;
8398 /* if a message was specified on the command line, just use it */
8399 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8400 len = strlen(a->cmdline_log) + 1;
8401 *logmsg = malloc(len + 1);
8402 if (*logmsg == NULL)
8403 return got_error_from_errno("malloc");
8404 strlcpy(*logmsg, a->cmdline_log, len);
8405 return NULL;
8406 } else if (a->prepared_log != NULL && a->non_interactive)
8407 return read_prepared_logmsg(logmsg, a->prepared_log);
8409 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8410 return got_error_from_errno("asprintf");
8412 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8413 if (err)
8414 goto done;
8416 if (a->prepared_log) {
8417 char *msg;
8418 err = read_prepared_logmsg(&msg, a->prepared_log);
8419 if (err)
8420 goto done;
8421 if (write(fd, msg, strlen(msg)) == -1) {
8422 err = got_error_from_errno2("write", a->logmsg_path);
8423 free(msg);
8424 goto done;
8426 free(msg);
8429 initial_content_len = asprintf(&initial_content,
8430 "\n# changes to be committed on branch %s:\n",
8431 a->branch_name);
8432 if (initial_content_len == -1) {
8433 err = got_error_from_errno("asprintf");
8434 goto done;
8437 if (write(fd, initial_content, initial_content_len) == -1) {
8438 err = got_error_from_errno2("write", a->logmsg_path);
8439 goto done;
8442 TAILQ_FOREACH(pe, commitable_paths, entry) {
8443 struct got_commitable *ct = pe->data;
8444 dprintf(fd, "# %c %s\n",
8445 got_commitable_get_status(ct),
8446 got_commitable_get_path(ct));
8449 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8450 initial_content_len, a->prepared_log ? 0 : 1);
8451 done:
8452 free(initial_content);
8453 free(template);
8455 if (fd != -1 && close(fd) == -1 && err == NULL)
8456 err = got_error_from_errno2("close", a->logmsg_path);
8458 /* Editor is done; we can now apply unveil(2) */
8459 if (err == NULL)
8460 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8461 if (err) {
8462 free(*logmsg);
8463 *logmsg = NULL;
8465 return err;
8468 static const struct got_error *
8469 cmd_commit(int argc, char *argv[])
8471 const struct got_error *error = NULL;
8472 struct got_worktree *worktree = NULL;
8473 struct got_repository *repo = NULL;
8474 char *cwd = NULL, *id_str = NULL;
8475 struct got_object_id *id = NULL;
8476 const char *logmsg = NULL;
8477 char *prepared_logmsg = NULL;
8478 struct collect_commit_logmsg_arg cl_arg;
8479 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8480 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8481 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8482 struct got_pathlist_head paths;
8483 int *pack_fds = NULL;
8485 TAILQ_INIT(&paths);
8486 cl_arg.logmsg_path = NULL;
8488 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8489 switch (ch) {
8490 case 'F':
8491 if (logmsg != NULL)
8492 option_conflict('F', 'm');
8493 prepared_logmsg = realpath(optarg, NULL);
8494 if (prepared_logmsg == NULL)
8495 return got_error_from_errno2("realpath",
8496 optarg);
8497 break;
8498 case 'm':
8499 if (prepared_logmsg)
8500 option_conflict('m', 'F');
8501 logmsg = optarg;
8502 break;
8503 case 'N':
8504 non_interactive = 1;
8505 break;
8506 case 'S':
8507 allow_bad_symlinks = 1;
8508 break;
8509 default:
8510 usage_commit();
8511 /* NOTREACHED */
8515 argc -= optind;
8516 argv += optind;
8518 #ifndef PROFILE
8519 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8520 "unveil", NULL) == -1)
8521 err(1, "pledge");
8522 #endif
8523 cwd = getcwd(NULL, 0);
8524 if (cwd == NULL) {
8525 error = got_error_from_errno("getcwd");
8526 goto done;
8529 error = got_repo_pack_fds_open(&pack_fds);
8530 if (error != NULL)
8531 goto done;
8533 error = got_worktree_open(&worktree, cwd);
8534 if (error) {
8535 if (error->code == GOT_ERR_NOT_WORKTREE)
8536 error = wrap_not_worktree_error(error, "commit", cwd);
8537 goto done;
8540 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8541 if (error)
8542 goto done;
8543 if (rebase_in_progress) {
8544 error = got_error(GOT_ERR_REBASING);
8545 goto done;
8548 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8549 worktree);
8550 if (error)
8551 goto done;
8553 error = get_gitconfig_path(&gitconfig_path);
8554 if (error)
8555 goto done;
8556 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8557 gitconfig_path, pack_fds);
8558 if (error != NULL)
8559 goto done;
8561 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8562 if (error)
8563 goto done;
8564 if (merge_in_progress) {
8565 error = got_error(GOT_ERR_MERGE_BUSY);
8566 goto done;
8569 error = get_author(&author, repo, worktree);
8570 if (error)
8571 return error;
8574 * unveil(2) traverses exec(2); if an editor is used we have
8575 * to apply unveil after the log message has been written.
8577 if (logmsg == NULL || strlen(logmsg) == 0)
8578 error = get_editor(&editor);
8579 else
8580 error = apply_unveil(got_repo_get_path(repo), 0,
8581 got_worktree_get_root_path(worktree));
8582 if (error)
8583 goto done;
8585 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8586 if (error)
8587 goto done;
8589 cl_arg.editor = editor;
8590 cl_arg.cmdline_log = logmsg;
8591 cl_arg.prepared_log = prepared_logmsg;
8592 cl_arg.non_interactive = non_interactive;
8593 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8594 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8595 if (!histedit_in_progress) {
8596 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8597 error = got_error(GOT_ERR_COMMIT_BRANCH);
8598 goto done;
8600 cl_arg.branch_name += 11;
8602 cl_arg.repo_path = got_repo_get_path(repo);
8603 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8604 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8605 print_status, NULL, repo);
8606 if (error) {
8607 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8608 cl_arg.logmsg_path != NULL)
8609 preserve_logmsg = 1;
8610 goto done;
8613 error = got_object_id_str(&id_str, id);
8614 if (error)
8615 goto done;
8616 printf("Created commit %s\n", id_str);
8617 done:
8618 if (preserve_logmsg) {
8619 fprintf(stderr, "%s: log message preserved in %s\n",
8620 getprogname(), cl_arg.logmsg_path);
8621 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8622 error == NULL)
8623 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8624 free(cl_arg.logmsg_path);
8625 if (repo) {
8626 const struct got_error *close_err = got_repo_close(repo);
8627 if (error == NULL)
8628 error = close_err;
8630 if (worktree)
8631 got_worktree_close(worktree);
8632 if (pack_fds) {
8633 const struct got_error *pack_err =
8634 got_repo_pack_fds_close(pack_fds);
8635 if (error == NULL)
8636 error = pack_err;
8638 free(cwd);
8639 free(id_str);
8640 free(gitconfig_path);
8641 free(editor);
8642 free(author);
8643 free(prepared_logmsg);
8644 return error;
8647 __dead static void
8648 usage_send(void)
8650 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8651 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8652 "[remote-repository]\n", getprogname());
8653 exit(1);
8656 static void
8657 print_load_info(int print_colored, int print_found, int print_trees,
8658 int ncolored, int nfound, int ntrees)
8660 if (print_colored) {
8661 printf("%d commit%s colored", ncolored,
8662 ncolored == 1 ? "" : "s");
8664 if (print_found) {
8665 printf("%s%d object%s found",
8666 ncolored > 0 ? "; " : "",
8667 nfound, nfound == 1 ? "" : "s");
8669 if (print_trees) {
8670 printf("; %d tree%s scanned", ntrees,
8671 ntrees == 1 ? "" : "s");
8675 struct got_send_progress_arg {
8676 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8677 int verbosity;
8678 int last_ncolored;
8679 int last_nfound;
8680 int last_ntrees;
8681 int loading_done;
8682 int last_ncommits;
8683 int last_nobj_total;
8684 int last_p_deltify;
8685 int last_p_written;
8686 int last_p_sent;
8687 int printed_something;
8688 int sent_something;
8689 struct got_pathlist_head *delete_branches;
8692 static const struct got_error *
8693 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8694 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8695 int nobj_written, off_t bytes_sent, const char *refname, int success)
8697 struct got_send_progress_arg *a = arg;
8698 char scaled_packsize[FMT_SCALED_STRSIZE];
8699 char scaled_sent[FMT_SCALED_STRSIZE];
8700 int p_deltify = 0, p_written = 0, p_sent = 0;
8701 int print_colored = 0, print_found = 0, print_trees = 0;
8702 int print_searching = 0, print_total = 0;
8703 int print_deltify = 0, print_written = 0, print_sent = 0;
8705 if (a->verbosity < 0)
8706 return NULL;
8708 if (refname) {
8709 const char *status = success ? "accepted" : "rejected";
8711 if (success) {
8712 struct got_pathlist_entry *pe;
8713 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8714 const char *branchname = pe->path;
8715 if (got_path_cmp(branchname, refname,
8716 strlen(branchname), strlen(refname)) == 0) {
8717 status = "deleted";
8718 a->sent_something = 1;
8719 break;
8724 if (a->printed_something)
8725 putchar('\n');
8726 printf("Server has %s %s", status, refname);
8727 a->printed_something = 1;
8728 return NULL;
8731 if (a->last_ncolored != ncolored) {
8732 print_colored = 1;
8733 a->last_ncolored = ncolored;
8736 if (a->last_nfound != nfound) {
8737 print_colored = 1;
8738 print_found = 1;
8739 a->last_nfound = nfound;
8742 if (a->last_ntrees != ntrees) {
8743 print_colored = 1;
8744 print_found = 1;
8745 print_trees = 1;
8746 a->last_ntrees = ntrees;
8749 if ((print_colored || print_found || print_trees) &&
8750 !a->loading_done) {
8751 printf("\r");
8752 print_load_info(print_colored, print_found, print_trees,
8753 ncolored, nfound, ntrees);
8754 a->printed_something = 1;
8755 fflush(stdout);
8756 return NULL;
8757 } else if (!a->loading_done) {
8758 printf("\r");
8759 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8760 printf("\n");
8761 a->loading_done = 1;
8764 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8765 return got_error_from_errno("fmt_scaled");
8766 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8767 return got_error_from_errno("fmt_scaled");
8769 if (a->last_ncommits != ncommits) {
8770 print_searching = 1;
8771 a->last_ncommits = ncommits;
8774 if (a->last_nobj_total != nobj_total) {
8775 print_searching = 1;
8776 print_total = 1;
8777 a->last_nobj_total = nobj_total;
8780 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8781 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8782 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8783 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8784 return got_error(GOT_ERR_NO_SPACE);
8787 if (nobj_deltify > 0 || nobj_written > 0) {
8788 if (nobj_deltify > 0) {
8789 p_deltify = (nobj_deltify * 100) / nobj_total;
8790 if (p_deltify != a->last_p_deltify) {
8791 a->last_p_deltify = p_deltify;
8792 print_searching = 1;
8793 print_total = 1;
8794 print_deltify = 1;
8797 if (nobj_written > 0) {
8798 p_written = (nobj_written * 100) / nobj_total;
8799 if (p_written != a->last_p_written) {
8800 a->last_p_written = p_written;
8801 print_searching = 1;
8802 print_total = 1;
8803 print_deltify = 1;
8804 print_written = 1;
8809 if (bytes_sent > 0) {
8810 p_sent = (bytes_sent * 100) / packfile_size;
8811 if (p_sent != a->last_p_sent) {
8812 a->last_p_sent = p_sent;
8813 print_searching = 1;
8814 print_total = 1;
8815 print_deltify = 1;
8816 print_written = 1;
8817 print_sent = 1;
8819 a->sent_something = 1;
8822 if (print_searching || print_total || print_deltify || print_written ||
8823 print_sent)
8824 printf("\r");
8825 if (print_searching)
8826 printf("packing %d reference%s", ncommits,
8827 ncommits == 1 ? "" : "s");
8828 if (print_total)
8829 printf("; %d object%s", nobj_total,
8830 nobj_total == 1 ? "" : "s");
8831 if (print_deltify)
8832 printf("; deltify: %d%%", p_deltify);
8833 if (print_sent)
8834 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8835 scaled_packsize, p_sent);
8836 else if (print_written)
8837 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8838 scaled_packsize, p_written);
8839 if (print_searching || print_total || print_deltify ||
8840 print_written || print_sent) {
8841 a->printed_something = 1;
8842 fflush(stdout);
8844 return NULL;
8847 static const struct got_error *
8848 cmd_send(int argc, char *argv[])
8850 const struct got_error *error = NULL;
8851 char *cwd = NULL, *repo_path = NULL;
8852 const char *remote_name;
8853 char *proto = NULL, *host = NULL, *port = NULL;
8854 char *repo_name = NULL, *server_path = NULL;
8855 const struct got_remote_repo *remotes, *remote = NULL;
8856 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8857 struct got_repository *repo = NULL;
8858 struct got_worktree *worktree = NULL;
8859 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8860 struct got_pathlist_head branches;
8861 struct got_pathlist_head tags;
8862 struct got_reflist_head all_branches;
8863 struct got_reflist_head all_tags;
8864 struct got_pathlist_head delete_args;
8865 struct got_pathlist_head delete_branches;
8866 struct got_reflist_entry *re;
8867 struct got_pathlist_entry *pe;
8868 int i, ch, sendfd = -1, sendstatus;
8869 pid_t sendpid = -1;
8870 struct got_send_progress_arg spa;
8871 int verbosity = 0, overwrite_refs = 0;
8872 int send_all_branches = 0, send_all_tags = 0;
8873 struct got_reference *ref = NULL;
8874 int *pack_fds = NULL;
8876 TAILQ_INIT(&branches);
8877 TAILQ_INIT(&tags);
8878 TAILQ_INIT(&all_branches);
8879 TAILQ_INIT(&all_tags);
8880 TAILQ_INIT(&delete_args);
8881 TAILQ_INIT(&delete_branches);
8883 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8884 switch (ch) {
8885 case 'a':
8886 send_all_branches = 1;
8887 break;
8888 case 'b':
8889 error = got_pathlist_append(&branches, optarg, NULL);
8890 if (error)
8891 return error;
8892 nbranches++;
8893 break;
8894 case 'd':
8895 error = got_pathlist_append(&delete_args, optarg, NULL);
8896 if (error)
8897 return error;
8898 break;
8899 case 'f':
8900 overwrite_refs = 1;
8901 break;
8902 case 'r':
8903 repo_path = realpath(optarg, NULL);
8904 if (repo_path == NULL)
8905 return got_error_from_errno2("realpath",
8906 optarg);
8907 got_path_strip_trailing_slashes(repo_path);
8908 break;
8909 case 't':
8910 error = got_pathlist_append(&tags, optarg, NULL);
8911 if (error)
8912 return error;
8913 ntags++;
8914 break;
8915 case 'T':
8916 send_all_tags = 1;
8917 break;
8918 case 'v':
8919 if (verbosity < 0)
8920 verbosity = 0;
8921 else if (verbosity < 3)
8922 verbosity++;
8923 break;
8924 case 'q':
8925 verbosity = -1;
8926 break;
8927 default:
8928 usage_send();
8929 /* NOTREACHED */
8932 argc -= optind;
8933 argv += optind;
8935 if (send_all_branches && !TAILQ_EMPTY(&branches))
8936 option_conflict('a', 'b');
8937 if (send_all_tags && !TAILQ_EMPTY(&tags))
8938 option_conflict('T', 't');
8941 if (argc == 0)
8942 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8943 else if (argc == 1)
8944 remote_name = argv[0];
8945 else
8946 usage_send();
8948 cwd = getcwd(NULL, 0);
8949 if (cwd == NULL) {
8950 error = got_error_from_errno("getcwd");
8951 goto done;
8954 error = got_repo_pack_fds_open(&pack_fds);
8955 if (error != NULL)
8956 goto done;
8958 if (repo_path == NULL) {
8959 error = got_worktree_open(&worktree, cwd);
8960 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8961 goto done;
8962 else
8963 error = NULL;
8964 if (worktree) {
8965 repo_path =
8966 strdup(got_worktree_get_repo_path(worktree));
8967 if (repo_path == NULL)
8968 error = got_error_from_errno("strdup");
8969 if (error)
8970 goto done;
8971 } else {
8972 repo_path = strdup(cwd);
8973 if (repo_path == NULL) {
8974 error = got_error_from_errno("strdup");
8975 goto done;
8980 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8981 if (error)
8982 goto done;
8984 if (worktree) {
8985 worktree_conf = got_worktree_get_gotconfig(worktree);
8986 if (worktree_conf) {
8987 got_gotconfig_get_remotes(&nremotes, &remotes,
8988 worktree_conf);
8989 for (i = 0; i < nremotes; i++) {
8990 if (strcmp(remotes[i].name, remote_name) == 0) {
8991 remote = &remotes[i];
8992 break;
8997 if (remote == NULL) {
8998 repo_conf = got_repo_get_gotconfig(repo);
8999 if (repo_conf) {
9000 got_gotconfig_get_remotes(&nremotes, &remotes,
9001 repo_conf);
9002 for (i = 0; i < nremotes; i++) {
9003 if (strcmp(remotes[i].name, remote_name) == 0) {
9004 remote = &remotes[i];
9005 break;
9010 if (remote == NULL) {
9011 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9012 for (i = 0; i < nremotes; i++) {
9013 if (strcmp(remotes[i].name, remote_name) == 0) {
9014 remote = &remotes[i];
9015 break;
9019 if (remote == NULL) {
9020 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9021 goto done;
9024 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9025 &repo_name, remote->send_url);
9026 if (error)
9027 goto done;
9029 if (strcmp(proto, "git") == 0) {
9030 #ifndef PROFILE
9031 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9032 "sendfd dns inet unveil", NULL) == -1)
9033 err(1, "pledge");
9034 #endif
9035 } else if (strcmp(proto, "git+ssh") == 0 ||
9036 strcmp(proto, "ssh") == 0) {
9037 #ifndef PROFILE
9038 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9039 "sendfd unveil", NULL) == -1)
9040 err(1, "pledge");
9041 #endif
9042 } else if (strcmp(proto, "http") == 0 ||
9043 strcmp(proto, "git+http") == 0) {
9044 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9045 goto done;
9046 } else {
9047 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9048 goto done;
9051 error = got_dial_apply_unveil(proto);
9052 if (error)
9053 goto done;
9055 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9056 if (error)
9057 goto done;
9059 if (send_all_branches) {
9060 error = got_ref_list(&all_branches, repo, "refs/heads",
9061 got_ref_cmp_by_name, NULL);
9062 if (error)
9063 goto done;
9064 TAILQ_FOREACH(re, &all_branches, entry) {
9065 const char *branchname = got_ref_get_name(re->ref);
9066 error = got_pathlist_append(&branches,
9067 branchname, NULL);
9068 if (error)
9069 goto done;
9070 nbranches++;
9072 } else if (nbranches == 0) {
9073 for (i = 0; i < remote->nsend_branches; i++) {
9074 got_pathlist_append(&branches,
9075 remote->send_branches[i], NULL);
9079 if (send_all_tags) {
9080 error = got_ref_list(&all_tags, repo, "refs/tags",
9081 got_ref_cmp_by_name, NULL);
9082 if (error)
9083 goto done;
9084 TAILQ_FOREACH(re, &all_tags, entry) {
9085 const char *tagname = got_ref_get_name(re->ref);
9086 error = got_pathlist_append(&tags,
9087 tagname, NULL);
9088 if (error)
9089 goto done;
9090 ntags++;
9095 * To prevent accidents only branches in refs/heads/ can be deleted
9096 * with 'got send -d'.
9097 * Deleting anything else requires local repository access or Git.
9099 TAILQ_FOREACH(pe, &delete_args, entry) {
9100 const char *branchname = pe->path;
9101 char *s;
9102 struct got_pathlist_entry *new;
9103 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9104 s = strdup(branchname);
9105 if (s == NULL) {
9106 error = got_error_from_errno("strdup");
9107 goto done;
9109 } else {
9110 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9111 error = got_error_from_errno("asprintf");
9112 goto done;
9115 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9116 if (error || new == NULL /* duplicate */)
9117 free(s);
9118 if (error)
9119 goto done;
9120 ndelete_branches++;
9123 if (nbranches == 0 && ndelete_branches == 0) {
9124 struct got_reference *head_ref;
9125 if (worktree)
9126 error = got_ref_open(&head_ref, repo,
9127 got_worktree_get_head_ref_name(worktree), 0);
9128 else
9129 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9130 if (error)
9131 goto done;
9132 if (got_ref_is_symbolic(head_ref)) {
9133 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9134 got_ref_close(head_ref);
9135 if (error)
9136 goto done;
9137 } else
9138 ref = head_ref;
9139 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9140 NULL);
9141 if (error)
9142 goto done;
9143 nbranches++;
9146 if (verbosity >= 0)
9147 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9148 port ? ":" : "", port ? port : "");
9150 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9151 server_path, verbosity);
9152 if (error)
9153 goto done;
9155 memset(&spa, 0, sizeof(spa));
9156 spa.last_scaled_packsize[0] = '\0';
9157 spa.last_p_deltify = -1;
9158 spa.last_p_written = -1;
9159 spa.verbosity = verbosity;
9160 spa.delete_branches = &delete_branches;
9161 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9162 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9163 check_cancelled, NULL);
9164 if (spa.printed_something)
9165 putchar('\n');
9166 if (error)
9167 goto done;
9168 if (!spa.sent_something && verbosity >= 0)
9169 printf("Already up-to-date\n");
9170 done:
9171 if (sendpid > 0) {
9172 if (kill(sendpid, SIGTERM) == -1)
9173 error = got_error_from_errno("kill");
9174 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9175 error = got_error_from_errno("waitpid");
9177 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9178 error = got_error_from_errno("close");
9179 if (repo) {
9180 const struct got_error *close_err = got_repo_close(repo);
9181 if (error == NULL)
9182 error = close_err;
9184 if (worktree)
9185 got_worktree_close(worktree);
9186 if (pack_fds) {
9187 const struct got_error *pack_err =
9188 got_repo_pack_fds_close(pack_fds);
9189 if (error == NULL)
9190 error = pack_err;
9192 if (ref)
9193 got_ref_close(ref);
9194 got_pathlist_free(&branches);
9195 got_pathlist_free(&tags);
9196 got_ref_list_free(&all_branches);
9197 got_ref_list_free(&all_tags);
9198 got_pathlist_free(&delete_args);
9199 TAILQ_FOREACH(pe, &delete_branches, entry)
9200 free((char *)pe->path);
9201 got_pathlist_free(&delete_branches);
9202 free(cwd);
9203 free(repo_path);
9204 free(proto);
9205 free(host);
9206 free(port);
9207 free(server_path);
9208 free(repo_name);
9209 return error;
9212 __dead static void
9213 usage_cherrypick(void)
9215 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9216 exit(1);
9219 static const struct got_error *
9220 cmd_cherrypick(int argc, char *argv[])
9222 const struct got_error *error = NULL;
9223 struct got_worktree *worktree = NULL;
9224 struct got_repository *repo = NULL;
9225 char *cwd = NULL, *commit_id_str = NULL;
9226 struct got_object_id *commit_id = NULL;
9227 struct got_commit_object *commit = NULL;
9228 struct got_object_qid *pid;
9229 int ch;
9230 struct got_update_progress_arg upa;
9231 int *pack_fds = NULL;
9233 while ((ch = getopt(argc, argv, "")) != -1) {
9234 switch (ch) {
9235 default:
9236 usage_cherrypick();
9237 /* NOTREACHED */
9241 argc -= optind;
9242 argv += optind;
9244 #ifndef PROFILE
9245 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9246 "unveil", NULL) == -1)
9247 err(1, "pledge");
9248 #endif
9249 if (argc != 1)
9250 usage_cherrypick();
9252 cwd = getcwd(NULL, 0);
9253 if (cwd == NULL) {
9254 error = got_error_from_errno("getcwd");
9255 goto done;
9258 error = got_repo_pack_fds_open(&pack_fds);
9259 if (error != NULL)
9260 goto done;
9262 error = got_worktree_open(&worktree, cwd);
9263 if (error) {
9264 if (error->code == GOT_ERR_NOT_WORKTREE)
9265 error = wrap_not_worktree_error(error, "cherrypick",
9266 cwd);
9267 goto done;
9270 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9271 NULL, pack_fds);
9272 if (error != NULL)
9273 goto done;
9275 error = apply_unveil(got_repo_get_path(repo), 0,
9276 got_worktree_get_root_path(worktree));
9277 if (error)
9278 goto done;
9280 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9281 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9282 if (error)
9283 goto done;
9284 error = got_object_id_str(&commit_id_str, commit_id);
9285 if (error)
9286 goto done;
9288 error = got_object_open_as_commit(&commit, repo, commit_id);
9289 if (error)
9290 goto done;
9291 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9292 memset(&upa, 0, sizeof(upa));
9293 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9294 commit_id, repo, update_progress, &upa, check_cancelled,
9295 NULL);
9296 if (error != NULL)
9297 goto done;
9299 if (upa.did_something)
9300 printf("Merged commit %s\n", commit_id_str);
9301 print_merge_progress_stats(&upa);
9302 done:
9303 if (commit)
9304 got_object_commit_close(commit);
9305 free(commit_id_str);
9306 if (worktree)
9307 got_worktree_close(worktree);
9308 if (repo) {
9309 const struct got_error *close_err = got_repo_close(repo);
9310 if (error == NULL)
9311 error = close_err;
9313 if (pack_fds) {
9314 const struct got_error *pack_err =
9315 got_repo_pack_fds_close(pack_fds);
9316 if (error == NULL)
9317 error = pack_err;
9320 return error;
9323 __dead static void
9324 usage_backout(void)
9326 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9327 exit(1);
9330 static const struct got_error *
9331 cmd_backout(int argc, char *argv[])
9333 const struct got_error *error = NULL;
9334 struct got_worktree *worktree = NULL;
9335 struct got_repository *repo = NULL;
9336 char *cwd = NULL, *commit_id_str = NULL;
9337 struct got_object_id *commit_id = NULL;
9338 struct got_commit_object *commit = NULL;
9339 struct got_object_qid *pid;
9340 int ch;
9341 struct got_update_progress_arg upa;
9342 int *pack_fds = NULL;
9344 while ((ch = getopt(argc, argv, "")) != -1) {
9345 switch (ch) {
9346 default:
9347 usage_backout();
9348 /* NOTREACHED */
9352 argc -= optind;
9353 argv += optind;
9355 #ifndef PROFILE
9356 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9357 "unveil", NULL) == -1)
9358 err(1, "pledge");
9359 #endif
9360 if (argc != 1)
9361 usage_backout();
9363 cwd = getcwd(NULL, 0);
9364 if (cwd == NULL) {
9365 error = got_error_from_errno("getcwd");
9366 goto done;
9369 error = got_repo_pack_fds_open(&pack_fds);
9370 if (error != NULL)
9371 goto done;
9373 error = got_worktree_open(&worktree, cwd);
9374 if (error) {
9375 if (error->code == GOT_ERR_NOT_WORKTREE)
9376 error = wrap_not_worktree_error(error, "backout", cwd);
9377 goto done;
9380 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9381 NULL, pack_fds);
9382 if (error != NULL)
9383 goto done;
9385 error = apply_unveil(got_repo_get_path(repo), 0,
9386 got_worktree_get_root_path(worktree));
9387 if (error)
9388 goto done;
9390 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9391 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9392 if (error)
9393 goto done;
9394 error = got_object_id_str(&commit_id_str, commit_id);
9395 if (error)
9396 goto done;
9398 error = got_object_open_as_commit(&commit, repo, commit_id);
9399 if (error)
9400 goto done;
9401 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9402 if (pid == NULL) {
9403 error = got_error(GOT_ERR_ROOT_COMMIT);
9404 goto done;
9407 memset(&upa, 0, sizeof(upa));
9408 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9409 repo, update_progress, &upa, check_cancelled, NULL);
9410 if (error != NULL)
9411 goto done;
9413 if (upa.did_something)
9414 printf("Backed out commit %s\n", commit_id_str);
9415 print_merge_progress_stats(&upa);
9416 done:
9417 if (commit)
9418 got_object_commit_close(commit);
9419 free(commit_id_str);
9420 if (worktree)
9421 got_worktree_close(worktree);
9422 if (repo) {
9423 const struct got_error *close_err = got_repo_close(repo);
9424 if (error == NULL)
9425 error = close_err;
9427 if (pack_fds) {
9428 const struct got_error *pack_err =
9429 got_repo_pack_fds_close(pack_fds);
9430 if (error == NULL)
9431 error = pack_err;
9433 return error;
9436 __dead static void
9437 usage_rebase(void)
9439 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9440 getprogname());
9441 exit(1);
9444 static void
9445 trim_logmsg(char *logmsg, int limit)
9447 char *nl;
9448 size_t len;
9450 len = strlen(logmsg);
9451 if (len > limit)
9452 len = limit;
9453 logmsg[len] = '\0';
9454 nl = strchr(logmsg, '\n');
9455 if (nl)
9456 *nl = '\0';
9459 static const struct got_error *
9460 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9462 const struct got_error *err;
9463 char *logmsg0 = NULL;
9464 const char *s;
9466 err = got_object_commit_get_logmsg(&logmsg0, commit);
9467 if (err)
9468 return err;
9470 s = logmsg0;
9471 while (isspace((unsigned char)s[0]))
9472 s++;
9474 *logmsg = strdup(s);
9475 if (*logmsg == NULL) {
9476 err = got_error_from_errno("strdup");
9477 goto done;
9480 trim_logmsg(*logmsg, limit);
9481 done:
9482 free(logmsg0);
9483 return err;
9486 static const struct got_error *
9487 show_rebase_merge_conflict(struct got_object_id *id,
9488 struct got_repository *repo)
9490 const struct got_error *err;
9491 struct got_commit_object *commit = NULL;
9492 char *id_str = NULL, *logmsg = NULL;
9494 err = got_object_open_as_commit(&commit, repo, id);
9495 if (err)
9496 return err;
9498 err = got_object_id_str(&id_str, id);
9499 if (err)
9500 goto done;
9502 id_str[12] = '\0';
9504 err = get_short_logmsg(&logmsg, 42, commit);
9505 if (err)
9506 goto done;
9508 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9509 done:
9510 free(id_str);
9511 got_object_commit_close(commit);
9512 free(logmsg);
9513 return err;
9516 static const struct got_error *
9517 show_rebase_progress(struct got_commit_object *commit,
9518 struct got_object_id *old_id, struct got_object_id *new_id)
9520 const struct got_error *err;
9521 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9523 err = got_object_id_str(&old_id_str, old_id);
9524 if (err)
9525 goto done;
9527 if (new_id) {
9528 err = got_object_id_str(&new_id_str, new_id);
9529 if (err)
9530 goto done;
9533 old_id_str[12] = '\0';
9534 if (new_id_str)
9535 new_id_str[12] = '\0';
9537 err = get_short_logmsg(&logmsg, 42, commit);
9538 if (err)
9539 goto done;
9541 printf("%s -> %s: %s\n", old_id_str,
9542 new_id_str ? new_id_str : "no-op change", logmsg);
9543 done:
9544 free(old_id_str);
9545 free(new_id_str);
9546 free(logmsg);
9547 return err;
9550 static const struct got_error *
9551 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9552 struct got_reference *branch, struct got_reference *new_base_branch,
9553 struct got_reference *tmp_branch, struct got_repository *repo,
9554 int create_backup)
9556 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9557 return got_worktree_rebase_complete(worktree, fileindex,
9558 new_base_branch, tmp_branch, branch, repo, create_backup);
9561 static const struct got_error *
9562 rebase_commit(struct got_pathlist_head *merged_paths,
9563 struct got_worktree *worktree, struct got_fileindex *fileindex,
9564 struct got_reference *tmp_branch,
9565 struct got_object_id *commit_id, struct got_repository *repo)
9567 const struct got_error *error;
9568 struct got_commit_object *commit;
9569 struct got_object_id *new_commit_id;
9571 error = got_object_open_as_commit(&commit, repo, commit_id);
9572 if (error)
9573 return error;
9575 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9576 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9577 if (error) {
9578 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9579 goto done;
9580 error = show_rebase_progress(commit, commit_id, NULL);
9581 } else {
9582 error = show_rebase_progress(commit, commit_id, new_commit_id);
9583 free(new_commit_id);
9585 done:
9586 got_object_commit_close(commit);
9587 return error;
9590 struct check_path_prefix_arg {
9591 const char *path_prefix;
9592 size_t len;
9593 int errcode;
9596 static const struct got_error *
9597 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9598 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9599 struct got_object_id *id1, struct got_object_id *id2,
9600 const char *path1, const char *path2,
9601 mode_t mode1, mode_t mode2, struct got_repository *repo)
9603 struct check_path_prefix_arg *a = arg;
9605 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9606 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9607 return got_error(a->errcode);
9609 return NULL;
9612 static const struct got_error *
9613 check_path_prefix(struct got_object_id *parent_id,
9614 struct got_object_id *commit_id, const char *path_prefix,
9615 int errcode, struct got_repository *repo)
9617 const struct got_error *err;
9618 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9619 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9620 struct check_path_prefix_arg cpp_arg;
9622 if (got_path_is_root_dir(path_prefix))
9623 return NULL;
9625 err = got_object_open_as_commit(&commit, repo, commit_id);
9626 if (err)
9627 goto done;
9629 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9630 if (err)
9631 goto done;
9633 err = got_object_open_as_tree(&tree1, repo,
9634 got_object_commit_get_tree_id(parent_commit));
9635 if (err)
9636 goto done;
9638 err = got_object_open_as_tree(&tree2, repo,
9639 got_object_commit_get_tree_id(commit));
9640 if (err)
9641 goto done;
9643 cpp_arg.path_prefix = path_prefix;
9644 while (cpp_arg.path_prefix[0] == '/')
9645 cpp_arg.path_prefix++;
9646 cpp_arg.len = strlen(cpp_arg.path_prefix);
9647 cpp_arg.errcode = errcode;
9648 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9649 check_path_prefix_in_diff, &cpp_arg, 0);
9650 done:
9651 if (tree1)
9652 got_object_tree_close(tree1);
9653 if (tree2)
9654 got_object_tree_close(tree2);
9655 if (commit)
9656 got_object_commit_close(commit);
9657 if (parent_commit)
9658 got_object_commit_close(parent_commit);
9659 return err;
9662 static const struct got_error *
9663 collect_commits(struct got_object_id_queue *commits,
9664 struct got_object_id *initial_commit_id,
9665 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9666 const char *path_prefix, int path_prefix_errcode,
9667 struct got_repository *repo)
9669 const struct got_error *err = NULL;
9670 struct got_commit_graph *graph = NULL;
9671 struct got_object_id *parent_id = NULL;
9672 struct got_object_qid *qid;
9673 struct got_object_id *commit_id = initial_commit_id;
9675 err = got_commit_graph_open(&graph, "/", 1);
9676 if (err)
9677 return err;
9679 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9680 check_cancelled, NULL);
9681 if (err)
9682 goto done;
9683 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9684 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9685 check_cancelled, NULL);
9686 if (err) {
9687 if (err->code == GOT_ERR_ITER_COMPLETED) {
9688 err = got_error_msg(GOT_ERR_ANCESTRY,
9689 "ran out of commits to rebase before "
9690 "youngest common ancestor commit has "
9691 "been reached?!?");
9693 goto done;
9694 } else {
9695 err = check_path_prefix(parent_id, commit_id,
9696 path_prefix, path_prefix_errcode, repo);
9697 if (err)
9698 goto done;
9700 err = got_object_qid_alloc(&qid, commit_id);
9701 if (err)
9702 goto done;
9703 STAILQ_INSERT_HEAD(commits, qid, entry);
9704 commit_id = parent_id;
9707 done:
9708 got_commit_graph_close(graph);
9709 return err;
9712 static const struct got_error *
9713 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9715 const struct got_error *err = NULL;
9716 time_t committer_time;
9717 struct tm tm;
9718 char datebuf[11]; /* YYYY-MM-DD + NUL */
9719 char *author0 = NULL, *author, *smallerthan;
9720 char *logmsg0 = NULL, *logmsg, *newline;
9722 committer_time = got_object_commit_get_committer_time(commit);
9723 if (gmtime_r(&committer_time, &tm) == NULL)
9724 return got_error_from_errno("gmtime_r");
9725 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9726 return got_error(GOT_ERR_NO_SPACE);
9728 author0 = strdup(got_object_commit_get_author(commit));
9729 if (author0 == NULL)
9730 return got_error_from_errno("strdup");
9731 author = author0;
9732 smallerthan = strchr(author, '<');
9733 if (smallerthan && smallerthan[1] != '\0')
9734 author = smallerthan + 1;
9735 author[strcspn(author, "@>")] = '\0';
9737 err = got_object_commit_get_logmsg(&logmsg0, commit);
9738 if (err)
9739 goto done;
9740 logmsg = logmsg0;
9741 while (*logmsg == '\n')
9742 logmsg++;
9743 newline = strchr(logmsg, '\n');
9744 if (newline)
9745 *newline = '\0';
9747 if (asprintf(brief_str, "%s %s %s",
9748 datebuf, author, logmsg) == -1)
9749 err = got_error_from_errno("asprintf");
9750 done:
9751 free(author0);
9752 free(logmsg0);
9753 return err;
9756 static const struct got_error *
9757 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9758 struct got_repository *repo)
9760 const struct got_error *err;
9761 char *id_str;
9763 err = got_object_id_str(&id_str, id);
9764 if (err)
9765 return err;
9767 err = got_ref_delete(ref, repo);
9768 if (err)
9769 goto done;
9771 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9772 done:
9773 free(id_str);
9774 return err;
9777 static const struct got_error *
9778 print_backup_ref(const char *branch_name, const char *new_id_str,
9779 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9780 struct got_reflist_object_id_map *refs_idmap,
9781 struct got_repository *repo)
9783 const struct got_error *err = NULL;
9784 struct got_reflist_head *refs;
9785 char *refs_str = NULL;
9786 struct got_object_id *new_commit_id = NULL;
9787 struct got_commit_object *new_commit = NULL;
9788 char *new_commit_brief_str = NULL;
9789 struct got_object_id *yca_id = NULL;
9790 struct got_commit_object *yca_commit = NULL;
9791 char *yca_id_str = NULL, *yca_brief_str = NULL;
9792 char *custom_refs_str;
9794 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9795 return got_error_from_errno("asprintf");
9797 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9798 0, 0, refs_idmap, custom_refs_str);
9799 if (err)
9800 goto done;
9802 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9803 if (err)
9804 goto done;
9806 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9807 if (refs) {
9808 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9809 if (err)
9810 goto done;
9813 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9814 if (err)
9815 goto done;
9817 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9818 if (err)
9819 goto done;
9821 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9822 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9823 if (err)
9824 goto done;
9826 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9827 refs_str ? " (" : "", refs_str ? refs_str : "",
9828 refs_str ? ")" : "", new_commit_brief_str);
9829 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9830 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9831 free(refs_str);
9832 refs_str = NULL;
9834 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9835 if (err)
9836 goto done;
9838 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9839 if (err)
9840 goto done;
9842 err = got_object_id_str(&yca_id_str, yca_id);
9843 if (err)
9844 goto done;
9846 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9847 if (refs) {
9848 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9849 if (err)
9850 goto done;
9852 printf("history forked at %s%s%s%s\n %s\n",
9853 yca_id_str,
9854 refs_str ? " (" : "", refs_str ? refs_str : "",
9855 refs_str ? ")" : "", yca_brief_str);
9857 done:
9858 free(custom_refs_str);
9859 free(new_commit_id);
9860 free(refs_str);
9861 free(yca_id);
9862 free(yca_id_str);
9863 free(yca_brief_str);
9864 if (new_commit)
9865 got_object_commit_close(new_commit);
9866 if (yca_commit)
9867 got_object_commit_close(yca_commit);
9869 return NULL;
9872 static const struct got_error *
9873 process_backup_refs(const char *backup_ref_prefix,
9874 const char *wanted_branch_name,
9875 int delete, struct got_repository *repo)
9877 const struct got_error *err;
9878 struct got_reflist_head refs, backup_refs;
9879 struct got_reflist_entry *re;
9880 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9881 struct got_object_id *old_commit_id = NULL;
9882 char *branch_name = NULL;
9883 struct got_commit_object *old_commit = NULL;
9884 struct got_reflist_object_id_map *refs_idmap = NULL;
9885 int wanted_branch_found = 0;
9887 TAILQ_INIT(&refs);
9888 TAILQ_INIT(&backup_refs);
9890 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9891 if (err)
9892 return err;
9894 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9895 if (err)
9896 goto done;
9898 if (wanted_branch_name) {
9899 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9900 wanted_branch_name += 11;
9903 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9904 got_ref_cmp_by_commit_timestamp_descending, repo);
9905 if (err)
9906 goto done;
9908 TAILQ_FOREACH(re, &backup_refs, entry) {
9909 const char *refname = got_ref_get_name(re->ref);
9910 char *slash;
9912 err = check_cancelled(NULL);
9913 if (err)
9914 break;
9916 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9917 if (err)
9918 break;
9920 err = got_object_open_as_commit(&old_commit, repo,
9921 old_commit_id);
9922 if (err)
9923 break;
9925 if (strncmp(backup_ref_prefix, refname,
9926 backup_ref_prefix_len) == 0)
9927 refname += backup_ref_prefix_len;
9929 while (refname[0] == '/')
9930 refname++;
9932 branch_name = strdup(refname);
9933 if (branch_name == NULL) {
9934 err = got_error_from_errno("strdup");
9935 break;
9937 slash = strrchr(branch_name, '/');
9938 if (slash) {
9939 *slash = '\0';
9940 refname += strlen(branch_name) + 1;
9943 if (wanted_branch_name == NULL ||
9944 strcmp(wanted_branch_name, branch_name) == 0) {
9945 wanted_branch_found = 1;
9946 if (delete) {
9947 err = delete_backup_ref(re->ref,
9948 old_commit_id, repo);
9949 } else {
9950 err = print_backup_ref(branch_name, refname,
9951 old_commit_id, old_commit, refs_idmap,
9952 repo);
9954 if (err)
9955 break;
9958 free(old_commit_id);
9959 old_commit_id = NULL;
9960 free(branch_name);
9961 branch_name = NULL;
9962 got_object_commit_close(old_commit);
9963 old_commit = NULL;
9966 if (wanted_branch_name && !wanted_branch_found) {
9967 err = got_error_fmt(GOT_ERR_NOT_REF,
9968 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9970 done:
9971 if (refs_idmap)
9972 got_reflist_object_id_map_free(refs_idmap);
9973 got_ref_list_free(&refs);
9974 got_ref_list_free(&backup_refs);
9975 free(old_commit_id);
9976 free(branch_name);
9977 if (old_commit)
9978 got_object_commit_close(old_commit);
9979 return err;
9982 static const struct got_error *
9983 abort_progress(void *arg, unsigned char status, const char *path)
9986 * Unversioned files should not clutter progress output when
9987 * an operation is aborted.
9989 if (status == GOT_STATUS_UNVERSIONED)
9990 return NULL;
9992 return update_progress(arg, status, path);
9995 static const struct got_error *
9996 cmd_rebase(int argc, char *argv[])
9998 const struct got_error *error = NULL;
9999 struct got_worktree *worktree = NULL;
10000 struct got_repository *repo = NULL;
10001 struct got_fileindex *fileindex = NULL;
10002 char *cwd = NULL;
10003 struct got_reference *branch = NULL;
10004 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10005 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10006 struct got_object_id *resume_commit_id = NULL;
10007 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10008 struct got_commit_object *commit = NULL;
10009 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10010 int histedit_in_progress = 0, merge_in_progress = 0;
10011 int create_backup = 1, list_backups = 0, delete_backups = 0;
10012 struct got_object_id_queue commits;
10013 struct got_pathlist_head merged_paths;
10014 const struct got_object_id_queue *parent_ids;
10015 struct got_object_qid *qid, *pid;
10016 struct got_update_progress_arg upa;
10017 int *pack_fds = NULL;
10019 STAILQ_INIT(&commits);
10020 TAILQ_INIT(&merged_paths);
10021 memset(&upa, 0, sizeof(upa));
10023 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10024 switch (ch) {
10025 case 'a':
10026 abort_rebase = 1;
10027 break;
10028 case 'c':
10029 continue_rebase = 1;
10030 break;
10031 case 'l':
10032 list_backups = 1;
10033 break;
10034 case 'X':
10035 delete_backups = 1;
10036 break;
10037 default:
10038 usage_rebase();
10039 /* NOTREACHED */
10043 argc -= optind;
10044 argv += optind;
10046 #ifndef PROFILE
10047 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10048 "unveil", NULL) == -1)
10049 err(1, "pledge");
10050 #endif
10051 if (list_backups) {
10052 if (abort_rebase)
10053 option_conflict('l', 'a');
10054 if (continue_rebase)
10055 option_conflict('l', 'c');
10056 if (delete_backups)
10057 option_conflict('l', 'X');
10058 if (argc != 0 && argc != 1)
10059 usage_rebase();
10060 } else if (delete_backups) {
10061 if (abort_rebase)
10062 option_conflict('X', 'a');
10063 if (continue_rebase)
10064 option_conflict('X', 'c');
10065 if (list_backups)
10066 option_conflict('l', 'X');
10067 if (argc != 0 && argc != 1)
10068 usage_rebase();
10069 } else {
10070 if (abort_rebase && continue_rebase)
10071 usage_rebase();
10072 else if (abort_rebase || continue_rebase) {
10073 if (argc != 0)
10074 usage_rebase();
10075 } else if (argc != 1)
10076 usage_rebase();
10079 cwd = getcwd(NULL, 0);
10080 if (cwd == NULL) {
10081 error = got_error_from_errno("getcwd");
10082 goto done;
10085 error = got_repo_pack_fds_open(&pack_fds);
10086 if (error != NULL)
10087 goto done;
10089 error = got_worktree_open(&worktree, cwd);
10090 if (error) {
10091 if (list_backups || delete_backups) {
10092 if (error->code != GOT_ERR_NOT_WORKTREE)
10093 goto done;
10094 } else {
10095 if (error->code == GOT_ERR_NOT_WORKTREE)
10096 error = wrap_not_worktree_error(error,
10097 "rebase", cwd);
10098 goto done;
10102 error = got_repo_open(&repo,
10103 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10104 pack_fds);
10105 if (error != NULL)
10106 goto done;
10108 error = apply_unveil(got_repo_get_path(repo), 0,
10109 worktree ? got_worktree_get_root_path(worktree) : NULL);
10110 if (error)
10111 goto done;
10113 if (list_backups || delete_backups) {
10114 error = process_backup_refs(
10115 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10116 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10117 goto done; /* nothing else to do */
10120 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10121 worktree);
10122 if (error)
10123 goto done;
10124 if (histedit_in_progress) {
10125 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10126 goto done;
10129 error = got_worktree_merge_in_progress(&merge_in_progress,
10130 worktree, repo);
10131 if (error)
10132 goto done;
10133 if (merge_in_progress) {
10134 error = got_error(GOT_ERR_MERGE_BUSY);
10135 goto done;
10138 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10139 if (error)
10140 goto done;
10142 if (abort_rebase) {
10143 if (!rebase_in_progress) {
10144 error = got_error(GOT_ERR_NOT_REBASING);
10145 goto done;
10147 error = got_worktree_rebase_continue(&resume_commit_id,
10148 &new_base_branch, &tmp_branch, &branch, &fileindex,
10149 worktree, repo);
10150 if (error)
10151 goto done;
10152 printf("Switching work tree to %s\n",
10153 got_ref_get_symref_target(new_base_branch));
10154 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10155 new_base_branch, abort_progress, &upa);
10156 if (error)
10157 goto done;
10158 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10159 print_merge_progress_stats(&upa);
10160 goto done; /* nothing else to do */
10163 if (continue_rebase) {
10164 if (!rebase_in_progress) {
10165 error = got_error(GOT_ERR_NOT_REBASING);
10166 goto done;
10168 error = got_worktree_rebase_continue(&resume_commit_id,
10169 &new_base_branch, &tmp_branch, &branch, &fileindex,
10170 worktree, repo);
10171 if (error)
10172 goto done;
10174 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10175 resume_commit_id, repo);
10176 if (error)
10177 goto done;
10179 yca_id = got_object_id_dup(resume_commit_id);
10180 if (yca_id == NULL) {
10181 error = got_error_from_errno("got_object_id_dup");
10182 goto done;
10184 } else {
10185 error = got_ref_open(&branch, repo, argv[0], 0);
10186 if (error != NULL)
10187 goto done;
10190 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10191 if (error)
10192 goto done;
10194 if (!continue_rebase) {
10195 struct got_object_id *base_commit_id;
10197 base_commit_id = got_worktree_get_base_commit_id(worktree);
10198 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10199 base_commit_id, branch_head_commit_id, 1, repo,
10200 check_cancelled, NULL);
10201 if (error)
10202 goto done;
10203 if (yca_id == NULL) {
10204 error = got_error_msg(GOT_ERR_ANCESTRY,
10205 "specified branch shares no common ancestry "
10206 "with work tree's branch");
10207 goto done;
10210 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10211 if (error) {
10212 if (error->code != GOT_ERR_ANCESTRY)
10213 goto done;
10214 error = NULL;
10215 } else {
10216 struct got_pathlist_head paths;
10217 printf("%s is already based on %s\n",
10218 got_ref_get_name(branch),
10219 got_worktree_get_head_ref_name(worktree));
10220 error = switch_head_ref(branch, branch_head_commit_id,
10221 worktree, repo);
10222 if (error)
10223 goto done;
10224 error = got_worktree_set_base_commit_id(worktree, repo,
10225 branch_head_commit_id);
10226 if (error)
10227 goto done;
10228 TAILQ_INIT(&paths);
10229 error = got_pathlist_append(&paths, "", NULL);
10230 if (error)
10231 goto done;
10232 error = got_worktree_checkout_files(worktree,
10233 &paths, repo, update_progress, &upa,
10234 check_cancelled, NULL);
10235 got_pathlist_free(&paths);
10236 if (error)
10237 goto done;
10238 if (upa.did_something) {
10239 char *id_str;
10240 error = got_object_id_str(&id_str,
10241 branch_head_commit_id);
10242 if (error)
10243 goto done;
10244 printf("Updated to %s: %s\n",
10245 got_worktree_get_head_ref_name(worktree),
10246 id_str);
10247 free(id_str);
10248 } else
10249 printf("Already up-to-date\n");
10250 print_update_progress_stats(&upa);
10251 goto done;
10255 commit_id = branch_head_commit_id;
10256 error = got_object_open_as_commit(&commit, repo, commit_id);
10257 if (error)
10258 goto done;
10260 parent_ids = got_object_commit_get_parent_ids(commit);
10261 pid = STAILQ_FIRST(parent_ids);
10262 if (pid == NULL) {
10263 error = got_error(GOT_ERR_EMPTY_REBASE);
10264 goto done;
10266 error = collect_commits(&commits, commit_id, &pid->id,
10267 yca_id, got_worktree_get_path_prefix(worktree),
10268 GOT_ERR_REBASE_PATH, repo);
10269 got_object_commit_close(commit);
10270 commit = NULL;
10271 if (error)
10272 goto done;
10274 if (!continue_rebase) {
10275 error = got_worktree_rebase_prepare(&new_base_branch,
10276 &tmp_branch, &fileindex, worktree, branch, repo);
10277 if (error)
10278 goto done;
10281 if (STAILQ_EMPTY(&commits)) {
10282 if (continue_rebase) {
10283 error = rebase_complete(worktree, fileindex,
10284 branch, new_base_branch, tmp_branch, repo,
10285 create_backup);
10286 goto done;
10287 } else {
10288 /* Fast-forward the reference of the branch. */
10289 struct got_object_id *new_head_commit_id;
10290 char *id_str;
10291 error = got_ref_resolve(&new_head_commit_id, repo,
10292 new_base_branch);
10293 if (error)
10294 goto done;
10295 error = got_object_id_str(&id_str, new_head_commit_id);
10296 printf("Forwarding %s to commit %s\n",
10297 got_ref_get_name(branch), id_str);
10298 free(id_str);
10299 error = got_ref_change_ref(branch,
10300 new_head_commit_id);
10301 if (error)
10302 goto done;
10303 /* No backup needed since objects did not change. */
10304 create_backup = 0;
10308 pid = NULL;
10309 STAILQ_FOREACH(qid, &commits, entry) {
10311 commit_id = &qid->id;
10312 parent_id = pid ? &pid->id : yca_id;
10313 pid = qid;
10315 memset(&upa, 0, sizeof(upa));
10316 error = got_worktree_rebase_merge_files(&merged_paths,
10317 worktree, fileindex, parent_id, commit_id, repo,
10318 update_progress, &upa, check_cancelled, NULL);
10319 if (error)
10320 goto done;
10322 print_merge_progress_stats(&upa);
10323 if (upa.conflicts > 0 || upa.missing > 0 ||
10324 upa.not_deleted > 0 || upa.unversioned > 0) {
10325 if (upa.conflicts > 0) {
10326 error = show_rebase_merge_conflict(&qid->id,
10327 repo);
10328 if (error)
10329 goto done;
10331 got_worktree_rebase_pathlist_free(&merged_paths);
10332 break;
10335 error = rebase_commit(&merged_paths, worktree, fileindex,
10336 tmp_branch, commit_id, repo);
10337 got_worktree_rebase_pathlist_free(&merged_paths);
10338 if (error)
10339 goto done;
10342 if (upa.conflicts > 0 || upa.missing > 0 ||
10343 upa.not_deleted > 0 || upa.unversioned > 0) {
10344 error = got_worktree_rebase_postpone(worktree, fileindex);
10345 if (error)
10346 goto done;
10347 if (upa.conflicts > 0 && upa.missing == 0 &&
10348 upa.not_deleted == 0 && upa.unversioned == 0) {
10349 error = got_error_msg(GOT_ERR_CONFLICTS,
10350 "conflicts must be resolved before rebasing "
10351 "can continue");
10352 } else if (upa.conflicts > 0) {
10353 error = got_error_msg(GOT_ERR_CONFLICTS,
10354 "conflicts must be resolved before rebasing "
10355 "can continue; changes destined for some "
10356 "files were not yet merged and should be "
10357 "merged manually if required before the "
10358 "rebase operation is continued");
10359 } else {
10360 error = got_error_msg(GOT_ERR_CONFLICTS,
10361 "changes destined for some files were not "
10362 "yet merged and should be merged manually "
10363 "if required before the rebase operation "
10364 "is continued");
10366 } else
10367 error = rebase_complete(worktree, fileindex, branch,
10368 new_base_branch, tmp_branch, repo, create_backup);
10369 done:
10370 got_object_id_queue_free(&commits);
10371 free(branch_head_commit_id);
10372 free(resume_commit_id);
10373 free(yca_id);
10374 if (commit)
10375 got_object_commit_close(commit);
10376 if (branch)
10377 got_ref_close(branch);
10378 if (new_base_branch)
10379 got_ref_close(new_base_branch);
10380 if (tmp_branch)
10381 got_ref_close(tmp_branch);
10382 if (worktree)
10383 got_worktree_close(worktree);
10384 if (repo) {
10385 const struct got_error *close_err = got_repo_close(repo);
10386 if (error == NULL)
10387 error = close_err;
10389 if (pack_fds) {
10390 const struct got_error *pack_err =
10391 got_repo_pack_fds_close(pack_fds);
10392 if (error == NULL)
10393 error = pack_err;
10395 return error;
10398 __dead static void
10399 usage_histedit(void)
10401 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10402 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10403 getprogname());
10404 exit(1);
10407 #define GOT_HISTEDIT_PICK 'p'
10408 #define GOT_HISTEDIT_EDIT 'e'
10409 #define GOT_HISTEDIT_FOLD 'f'
10410 #define GOT_HISTEDIT_DROP 'd'
10411 #define GOT_HISTEDIT_MESG 'm'
10413 static const struct got_histedit_cmd {
10414 unsigned char code;
10415 const char *name;
10416 const char *desc;
10417 } got_histedit_cmds[] = {
10418 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10419 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10420 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10421 "be used" },
10422 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10423 { GOT_HISTEDIT_MESG, "mesg",
10424 "single-line log message for commit above (open editor if empty)" },
10427 struct got_histedit_list_entry {
10428 TAILQ_ENTRY(got_histedit_list_entry) entry;
10429 struct got_object_id *commit_id;
10430 const struct got_histedit_cmd *cmd;
10431 char *logmsg;
10433 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10435 static const struct got_error *
10436 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10437 FILE *f, struct got_repository *repo)
10439 const struct got_error *err = NULL;
10440 char *logmsg = NULL, *id_str = NULL;
10441 struct got_commit_object *commit = NULL;
10442 int n;
10444 err = got_object_open_as_commit(&commit, repo, commit_id);
10445 if (err)
10446 goto done;
10448 err = get_short_logmsg(&logmsg, 34, commit);
10449 if (err)
10450 goto done;
10452 err = got_object_id_str(&id_str, commit_id);
10453 if (err)
10454 goto done;
10456 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10457 if (n < 0)
10458 err = got_ferror(f, GOT_ERR_IO);
10459 done:
10460 if (commit)
10461 got_object_commit_close(commit);
10462 free(id_str);
10463 free(logmsg);
10464 return err;
10467 static const struct got_error *
10468 histedit_write_commit_list(struct got_object_id_queue *commits,
10469 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10470 struct got_repository *repo)
10472 const struct got_error *err = NULL;
10473 struct got_object_qid *qid;
10474 const char *histedit_cmd = NULL;
10476 if (STAILQ_EMPTY(commits))
10477 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10479 STAILQ_FOREACH(qid, commits, entry) {
10480 histedit_cmd = got_histedit_cmds[0].name;
10481 if (edit_only)
10482 histedit_cmd = "edit";
10483 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10484 histedit_cmd = "fold";
10485 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10486 if (err)
10487 break;
10488 if (edit_logmsg_only) {
10489 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10490 if (n < 0) {
10491 err = got_ferror(f, GOT_ERR_IO);
10492 break;
10497 return err;
10500 static const struct got_error *
10501 write_cmd_list(FILE *f, const char *branch_name,
10502 struct got_object_id_queue *commits)
10504 const struct got_error *err = NULL;
10505 size_t i;
10506 int n;
10507 char *id_str;
10508 struct got_object_qid *qid;
10510 qid = STAILQ_FIRST(commits);
10511 err = got_object_id_str(&id_str, &qid->id);
10512 if (err)
10513 return err;
10515 n = fprintf(f,
10516 "# Editing the history of branch '%s' starting at\n"
10517 "# commit %s\n"
10518 "# Commits will be processed in order from top to "
10519 "bottom of this file.\n", branch_name, id_str);
10520 if (n < 0) {
10521 err = got_ferror(f, GOT_ERR_IO);
10522 goto done;
10525 n = fprintf(f, "# Available histedit commands:\n");
10526 if (n < 0) {
10527 err = got_ferror(f, GOT_ERR_IO);
10528 goto done;
10531 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10532 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10533 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10534 cmd->desc);
10535 if (n < 0) {
10536 err = got_ferror(f, GOT_ERR_IO);
10537 break;
10540 done:
10541 free(id_str);
10542 return err;
10545 static const struct got_error *
10546 histedit_syntax_error(int lineno)
10548 static char msg[42];
10549 int ret;
10551 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10552 lineno);
10553 if (ret == -1 || ret >= sizeof(msg))
10554 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10556 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10559 static const struct got_error *
10560 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10561 char *logmsg, struct got_repository *repo)
10563 const struct got_error *err;
10564 struct got_commit_object *folded_commit = NULL;
10565 char *id_str, *folded_logmsg = NULL;
10567 err = got_object_id_str(&id_str, hle->commit_id);
10568 if (err)
10569 return err;
10571 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10572 if (err)
10573 goto done;
10575 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10576 if (err)
10577 goto done;
10578 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10579 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10580 folded_logmsg) == -1) {
10581 err = got_error_from_errno("asprintf");
10583 done:
10584 if (folded_commit)
10585 got_object_commit_close(folded_commit);
10586 free(id_str);
10587 free(folded_logmsg);
10588 return err;
10591 static struct got_histedit_list_entry *
10592 get_folded_commits(struct got_histedit_list_entry *hle)
10594 struct got_histedit_list_entry *prev, *folded = NULL;
10596 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10597 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10598 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10599 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10600 folded = prev;
10601 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10604 return folded;
10607 static const struct got_error *
10608 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10609 struct got_repository *repo)
10611 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10612 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10613 const struct got_error *err = NULL;
10614 struct got_commit_object *commit = NULL;
10615 int logmsg_len;
10616 int fd;
10617 struct got_histedit_list_entry *folded = NULL;
10619 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10620 if (err)
10621 return err;
10623 folded = get_folded_commits(hle);
10624 if (folded) {
10625 while (folded != hle) {
10626 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10627 folded = TAILQ_NEXT(folded, entry);
10628 continue;
10630 err = append_folded_commit_msg(&new_msg, folded,
10631 logmsg, repo);
10632 if (err)
10633 goto done;
10634 free(logmsg);
10635 logmsg = new_msg;
10636 folded = TAILQ_NEXT(folded, entry);
10640 err = got_object_id_str(&id_str, hle->commit_id);
10641 if (err)
10642 goto done;
10643 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10644 if (err)
10645 goto done;
10646 logmsg_len = asprintf(&new_msg,
10647 "%s\n# original log message of commit %s: %s",
10648 logmsg ? logmsg : "", id_str, orig_logmsg);
10649 if (logmsg_len == -1) {
10650 err = got_error_from_errno("asprintf");
10651 goto done;
10653 free(logmsg);
10654 logmsg = new_msg;
10656 err = got_object_id_str(&id_str, hle->commit_id);
10657 if (err)
10658 goto done;
10660 err = got_opentemp_named_fd(&logmsg_path, &fd,
10661 GOT_TMPDIR_STR "/got-logmsg");
10662 if (err)
10663 goto done;
10665 write(fd, logmsg, logmsg_len);
10666 close(fd);
10668 err = get_editor(&editor);
10669 if (err)
10670 goto done;
10672 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10673 logmsg_len, 0);
10674 if (err) {
10675 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10676 goto done;
10677 err = NULL;
10678 hle->logmsg = strdup(new_msg);
10679 if (hle->logmsg == NULL)
10680 err = got_error_from_errno("strdup");
10682 done:
10683 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10684 err = got_error_from_errno2("unlink", logmsg_path);
10685 free(logmsg_path);
10686 free(logmsg);
10687 free(orig_logmsg);
10688 free(editor);
10689 if (commit)
10690 got_object_commit_close(commit);
10691 return err;
10694 static const struct got_error *
10695 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10696 FILE *f, struct got_repository *repo)
10698 const struct got_error *err = NULL;
10699 char *line = NULL, *p, *end;
10700 size_t i, size;
10701 ssize_t len;
10702 int lineno = 0;
10703 const struct got_histedit_cmd *cmd;
10704 struct got_object_id *commit_id = NULL;
10705 struct got_histedit_list_entry *hle = NULL;
10707 for (;;) {
10708 len = getline(&line, &size, f);
10709 if (len == -1) {
10710 const struct got_error *getline_err;
10711 if (feof(f))
10712 break;
10713 getline_err = got_error_from_errno("getline");
10714 err = got_ferror(f, getline_err->code);
10715 break;
10717 lineno++;
10718 p = line;
10719 while (isspace((unsigned char)p[0]))
10720 p++;
10721 if (p[0] == '#' || p[0] == '\0') {
10722 free(line);
10723 line = NULL;
10724 continue;
10726 cmd = NULL;
10727 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10728 cmd = &got_histedit_cmds[i];
10729 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10730 isspace((unsigned char)p[strlen(cmd->name)])) {
10731 p += strlen(cmd->name);
10732 break;
10734 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10735 p++;
10736 break;
10739 if (i == nitems(got_histedit_cmds)) {
10740 err = histedit_syntax_error(lineno);
10741 break;
10743 while (isspace((unsigned char)p[0]))
10744 p++;
10745 if (cmd->code == GOT_HISTEDIT_MESG) {
10746 if (hle == NULL || hle->logmsg != NULL) {
10747 err = got_error(GOT_ERR_HISTEDIT_CMD);
10748 break;
10750 if (p[0] == '\0') {
10751 err = histedit_edit_logmsg(hle, repo);
10752 if (err)
10753 break;
10754 } else {
10755 hle->logmsg = strdup(p);
10756 if (hle->logmsg == NULL) {
10757 err = got_error_from_errno("strdup");
10758 break;
10761 free(line);
10762 line = NULL;
10763 continue;
10764 } else {
10765 end = p;
10766 while (end[0] && !isspace((unsigned char)end[0]))
10767 end++;
10768 *end = '\0';
10770 err = got_object_resolve_id_str(&commit_id, repo, p);
10771 if (err) {
10772 /* override error code */
10773 err = histedit_syntax_error(lineno);
10774 break;
10777 hle = malloc(sizeof(*hle));
10778 if (hle == NULL) {
10779 err = got_error_from_errno("malloc");
10780 break;
10782 hle->cmd = cmd;
10783 hle->commit_id = commit_id;
10784 hle->logmsg = NULL;
10785 commit_id = NULL;
10786 free(line);
10787 line = NULL;
10788 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10791 free(line);
10792 free(commit_id);
10793 return err;
10796 static const struct got_error *
10797 histedit_check_script(struct got_histedit_list *histedit_cmds,
10798 struct got_object_id_queue *commits, struct got_repository *repo)
10800 const struct got_error *err = NULL;
10801 struct got_object_qid *qid;
10802 struct got_histedit_list_entry *hle;
10803 static char msg[92];
10804 char *id_str;
10806 if (TAILQ_EMPTY(histedit_cmds))
10807 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10808 "histedit script contains no commands");
10809 if (STAILQ_EMPTY(commits))
10810 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10812 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10813 struct got_histedit_list_entry *hle2;
10814 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10815 if (hle == hle2)
10816 continue;
10817 if (got_object_id_cmp(hle->commit_id,
10818 hle2->commit_id) != 0)
10819 continue;
10820 err = got_object_id_str(&id_str, hle->commit_id);
10821 if (err)
10822 return err;
10823 snprintf(msg, sizeof(msg), "commit %s is listed "
10824 "more than once in histedit script", id_str);
10825 free(id_str);
10826 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10830 STAILQ_FOREACH(qid, commits, entry) {
10831 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10832 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10833 break;
10835 if (hle == NULL) {
10836 err = got_object_id_str(&id_str, &qid->id);
10837 if (err)
10838 return err;
10839 snprintf(msg, sizeof(msg),
10840 "commit %s missing from histedit script", id_str);
10841 free(id_str);
10842 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10846 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10847 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10848 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10849 "last commit in histedit script cannot be folded");
10851 return NULL;
10854 static const struct got_error *
10855 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10856 const char *path, struct got_object_id_queue *commits,
10857 struct got_repository *repo)
10859 const struct got_error *err = NULL;
10860 char *editor;
10861 FILE *f = NULL;
10863 err = get_editor(&editor);
10864 if (err)
10865 return err;
10867 if (spawn_editor(editor, path) == -1) {
10868 err = got_error_from_errno("failed spawning editor");
10869 goto done;
10872 f = fopen(path, "re");
10873 if (f == NULL) {
10874 err = got_error_from_errno("fopen");
10875 goto done;
10877 err = histedit_parse_list(histedit_cmds, f, repo);
10878 if (err)
10879 goto done;
10881 err = histedit_check_script(histedit_cmds, commits, repo);
10882 done:
10883 if (f && fclose(f) == EOF && err == NULL)
10884 err = got_error_from_errno("fclose");
10885 free(editor);
10886 return err;
10889 static const struct got_error *
10890 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10891 struct got_object_id_queue *, const char *, const char *,
10892 struct got_repository *);
10894 static const struct got_error *
10895 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10896 struct got_object_id_queue *commits, const char *branch_name,
10897 int edit_logmsg_only, int fold_only, int edit_only,
10898 struct got_repository *repo)
10900 const struct got_error *err;
10901 FILE *f = NULL;
10902 char *path = NULL;
10904 err = got_opentemp_named(&path, &f, "got-histedit");
10905 if (err)
10906 return err;
10908 err = write_cmd_list(f, branch_name, commits);
10909 if (err)
10910 goto done;
10912 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10913 fold_only, edit_only, repo);
10914 if (err)
10915 goto done;
10917 if (edit_logmsg_only || fold_only || edit_only) {
10918 rewind(f);
10919 err = histedit_parse_list(histedit_cmds, f, repo);
10920 } else {
10921 if (fclose(f) == EOF) {
10922 err = got_error_from_errno("fclose");
10923 goto done;
10925 f = NULL;
10926 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10927 if (err) {
10928 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10929 err->code != GOT_ERR_HISTEDIT_CMD)
10930 goto done;
10931 err = histedit_edit_list_retry(histedit_cmds, err,
10932 commits, path, branch_name, repo);
10935 done:
10936 if (f && fclose(f) == EOF && err == NULL)
10937 err = got_error_from_errno("fclose");
10938 if (path && unlink(path) != 0 && err == NULL)
10939 err = got_error_from_errno2("unlink", path);
10940 free(path);
10941 return err;
10944 static const struct got_error *
10945 histedit_save_list(struct got_histedit_list *histedit_cmds,
10946 struct got_worktree *worktree, struct got_repository *repo)
10948 const struct got_error *err = NULL;
10949 char *path = NULL;
10950 FILE *f = NULL;
10951 struct got_histedit_list_entry *hle;
10952 struct got_commit_object *commit = NULL;
10954 err = got_worktree_get_histedit_script_path(&path, worktree);
10955 if (err)
10956 return err;
10958 f = fopen(path, "we");
10959 if (f == NULL) {
10960 err = got_error_from_errno2("fopen", path);
10961 goto done;
10963 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10964 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10965 repo);
10966 if (err)
10967 break;
10969 if (hle->logmsg) {
10970 int n = fprintf(f, "%c %s\n",
10971 GOT_HISTEDIT_MESG, hle->logmsg);
10972 if (n < 0) {
10973 err = got_ferror(f, GOT_ERR_IO);
10974 break;
10978 done:
10979 if (f && fclose(f) == EOF && err == NULL)
10980 err = got_error_from_errno("fclose");
10981 free(path);
10982 if (commit)
10983 got_object_commit_close(commit);
10984 return err;
10987 static void
10988 histedit_free_list(struct got_histedit_list *histedit_cmds)
10990 struct got_histedit_list_entry *hle;
10992 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10993 TAILQ_REMOVE(histedit_cmds, hle, entry);
10994 free(hle);
10998 static const struct got_error *
10999 histedit_load_list(struct got_histedit_list *histedit_cmds,
11000 const char *path, struct got_repository *repo)
11002 const struct got_error *err = NULL;
11003 FILE *f = NULL;
11005 f = fopen(path, "re");
11006 if (f == NULL) {
11007 err = got_error_from_errno2("fopen", path);
11008 goto done;
11011 err = histedit_parse_list(histedit_cmds, f, repo);
11012 done:
11013 if (f && fclose(f) == EOF && err == NULL)
11014 err = got_error_from_errno("fclose");
11015 return err;
11018 static const struct got_error *
11019 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11020 const struct got_error *edit_err, struct got_object_id_queue *commits,
11021 const char *path, const char *branch_name, struct got_repository *repo)
11023 const struct got_error *err = NULL, *prev_err = edit_err;
11024 int resp = ' ';
11026 while (resp != 'c' && resp != 'r' && resp != 'a') {
11027 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11028 "or (a)bort: ", getprogname(), prev_err->msg);
11029 resp = getchar();
11030 if (resp == '\n')
11031 resp = getchar();
11032 if (resp == 'c') {
11033 histedit_free_list(histedit_cmds);
11034 err = histedit_run_editor(histedit_cmds, path, commits,
11035 repo);
11036 if (err) {
11037 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11038 err->code != GOT_ERR_HISTEDIT_CMD)
11039 break;
11040 prev_err = err;
11041 resp = ' ';
11042 continue;
11044 break;
11045 } else if (resp == 'r') {
11046 histedit_free_list(histedit_cmds);
11047 err = histedit_edit_script(histedit_cmds,
11048 commits, branch_name, 0, 0, 0, repo);
11049 if (err) {
11050 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11051 err->code != GOT_ERR_HISTEDIT_CMD)
11052 break;
11053 prev_err = err;
11054 resp = ' ';
11055 continue;
11057 break;
11058 } else if (resp == 'a') {
11059 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11060 break;
11061 } else
11062 printf("invalid response '%c'\n", resp);
11065 return err;
11068 static const struct got_error *
11069 histedit_complete(struct got_worktree *worktree,
11070 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11071 struct got_reference *branch, struct got_repository *repo)
11073 printf("Switching work tree to %s\n",
11074 got_ref_get_symref_target(branch));
11075 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11076 branch, repo);
11079 static const struct got_error *
11080 show_histedit_progress(struct got_commit_object *commit,
11081 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11083 const struct got_error *err;
11084 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11086 err = got_object_id_str(&old_id_str, hle->commit_id);
11087 if (err)
11088 goto done;
11090 if (new_id) {
11091 err = got_object_id_str(&new_id_str, new_id);
11092 if (err)
11093 goto done;
11096 old_id_str[12] = '\0';
11097 if (new_id_str)
11098 new_id_str[12] = '\0';
11100 if (hle->logmsg) {
11101 logmsg = strdup(hle->logmsg);
11102 if (logmsg == NULL) {
11103 err = got_error_from_errno("strdup");
11104 goto done;
11106 trim_logmsg(logmsg, 42);
11107 } else {
11108 err = get_short_logmsg(&logmsg, 42, commit);
11109 if (err)
11110 goto done;
11113 switch (hle->cmd->code) {
11114 case GOT_HISTEDIT_PICK:
11115 case GOT_HISTEDIT_EDIT:
11116 printf("%s -> %s: %s\n", old_id_str,
11117 new_id_str ? new_id_str : "no-op change", logmsg);
11118 break;
11119 case GOT_HISTEDIT_DROP:
11120 case GOT_HISTEDIT_FOLD:
11121 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11122 logmsg);
11123 break;
11124 default:
11125 break;
11127 done:
11128 free(old_id_str);
11129 free(new_id_str);
11130 return err;
11133 static const struct got_error *
11134 histedit_commit(struct got_pathlist_head *merged_paths,
11135 struct got_worktree *worktree, struct got_fileindex *fileindex,
11136 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11137 struct got_repository *repo)
11139 const struct got_error *err;
11140 struct got_commit_object *commit;
11141 struct got_object_id *new_commit_id;
11143 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11144 && hle->logmsg == NULL) {
11145 err = histedit_edit_logmsg(hle, repo);
11146 if (err)
11147 return err;
11150 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11151 if (err)
11152 return err;
11154 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11155 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11156 hle->logmsg, repo);
11157 if (err) {
11158 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11159 goto done;
11160 err = show_histedit_progress(commit, hle, NULL);
11161 } else {
11162 err = show_histedit_progress(commit, hle, new_commit_id);
11163 free(new_commit_id);
11165 done:
11166 got_object_commit_close(commit);
11167 return err;
11170 static const struct got_error *
11171 histedit_skip_commit(struct got_histedit_list_entry *hle,
11172 struct got_worktree *worktree, struct got_repository *repo)
11174 const struct got_error *error;
11175 struct got_commit_object *commit;
11177 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11178 repo);
11179 if (error)
11180 return error;
11182 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11183 if (error)
11184 return error;
11186 error = show_histedit_progress(commit, hle, NULL);
11187 got_object_commit_close(commit);
11188 return error;
11191 static const struct got_error *
11192 check_local_changes(void *arg, unsigned char status,
11193 unsigned char staged_status, const char *path,
11194 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11195 struct got_object_id *commit_id, int dirfd, const char *de_name)
11197 int *have_local_changes = arg;
11199 switch (status) {
11200 case GOT_STATUS_ADD:
11201 case GOT_STATUS_DELETE:
11202 case GOT_STATUS_MODIFY:
11203 case GOT_STATUS_CONFLICT:
11204 *have_local_changes = 1;
11205 return got_error(GOT_ERR_CANCELLED);
11206 default:
11207 break;
11210 switch (staged_status) {
11211 case GOT_STATUS_ADD:
11212 case GOT_STATUS_DELETE:
11213 case GOT_STATUS_MODIFY:
11214 *have_local_changes = 1;
11215 return got_error(GOT_ERR_CANCELLED);
11216 default:
11217 break;
11220 return NULL;
11223 static const struct got_error *
11224 cmd_histedit(int argc, char *argv[])
11226 const struct got_error *error = NULL;
11227 struct got_worktree *worktree = NULL;
11228 struct got_fileindex *fileindex = NULL;
11229 struct got_repository *repo = NULL;
11230 char *cwd = NULL;
11231 struct got_reference *branch = NULL;
11232 struct got_reference *tmp_branch = NULL;
11233 struct got_object_id *resume_commit_id = NULL;
11234 struct got_object_id *base_commit_id = NULL;
11235 struct got_object_id *head_commit_id = NULL;
11236 struct got_commit_object *commit = NULL;
11237 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11238 struct got_update_progress_arg upa;
11239 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11240 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11241 int list_backups = 0, delete_backups = 0;
11242 const char *edit_script_path = NULL;
11243 struct got_object_id_queue commits;
11244 struct got_pathlist_head merged_paths;
11245 const struct got_object_id_queue *parent_ids;
11246 struct got_object_qid *pid;
11247 struct got_histedit_list histedit_cmds;
11248 struct got_histedit_list_entry *hle;
11249 int *pack_fds = NULL;
11251 STAILQ_INIT(&commits);
11252 TAILQ_INIT(&histedit_cmds);
11253 TAILQ_INIT(&merged_paths);
11254 memset(&upa, 0, sizeof(upa));
11256 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11257 switch (ch) {
11258 case 'a':
11259 abort_edit = 1;
11260 break;
11261 case 'c':
11262 continue_edit = 1;
11263 break;
11264 case 'e':
11265 edit_only = 1;
11266 break;
11267 case 'f':
11268 fold_only = 1;
11269 break;
11270 case 'F':
11271 edit_script_path = optarg;
11272 break;
11273 case 'm':
11274 edit_logmsg_only = 1;
11275 break;
11276 case 'l':
11277 list_backups = 1;
11278 break;
11279 case 'X':
11280 delete_backups = 1;
11281 break;
11282 default:
11283 usage_histedit();
11284 /* NOTREACHED */
11288 argc -= optind;
11289 argv += optind;
11291 #ifndef PROFILE
11292 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11293 "unveil", NULL) == -1)
11294 err(1, "pledge");
11295 #endif
11296 if (abort_edit && continue_edit)
11297 option_conflict('a', 'c');
11298 if (edit_script_path && edit_logmsg_only)
11299 option_conflict('F', 'm');
11300 if (abort_edit && edit_logmsg_only)
11301 option_conflict('a', 'm');
11302 if (continue_edit && edit_logmsg_only)
11303 option_conflict('c', 'm');
11304 if (abort_edit && fold_only)
11305 option_conflict('a', 'f');
11306 if (continue_edit && fold_only)
11307 option_conflict('c', 'f');
11308 if (fold_only && edit_logmsg_only)
11309 option_conflict('f', 'm');
11310 if (edit_script_path && fold_only)
11311 option_conflict('F', 'f');
11312 if (abort_edit && edit_only)
11313 option_conflict('a', 'e');
11314 if (continue_edit && edit_only)
11315 option_conflict('c', 'e');
11316 if (edit_only && edit_logmsg_only)
11317 option_conflict('e', 'm');
11318 if (edit_script_path && edit_only)
11319 option_conflict('F', 'e');
11320 if (list_backups) {
11321 if (abort_edit)
11322 option_conflict('l', 'a');
11323 if (continue_edit)
11324 option_conflict('l', 'c');
11325 if (edit_script_path)
11326 option_conflict('l', 'F');
11327 if (edit_logmsg_only)
11328 option_conflict('l', 'm');
11329 if (fold_only)
11330 option_conflict('l', 'f');
11331 if (edit_only)
11332 option_conflict('l', 'e');
11333 if (delete_backups)
11334 option_conflict('l', 'X');
11335 if (argc != 0 && argc != 1)
11336 usage_histedit();
11337 } else if (delete_backups) {
11338 if (abort_edit)
11339 option_conflict('X', 'a');
11340 if (continue_edit)
11341 option_conflict('X', 'c');
11342 if (edit_script_path)
11343 option_conflict('X', 'F');
11344 if (edit_logmsg_only)
11345 option_conflict('X', 'm');
11346 if (fold_only)
11347 option_conflict('X', 'f');
11348 if (edit_only)
11349 option_conflict('X', 'e');
11350 if (list_backups)
11351 option_conflict('X', 'l');
11352 if (argc != 0 && argc != 1)
11353 usage_histedit();
11354 } else if (argc != 0)
11355 usage_histedit();
11358 * This command cannot apply unveil(2) in all cases because the
11359 * user may choose to run an editor to edit the histedit script
11360 * and to edit individual commit log messages.
11361 * unveil(2) traverses exec(2); if an editor is used we have to
11362 * apply unveil after edit script and log messages have been written.
11363 * XXX TODO: Make use of unveil(2) where possible.
11366 cwd = getcwd(NULL, 0);
11367 if (cwd == NULL) {
11368 error = got_error_from_errno("getcwd");
11369 goto done;
11372 error = got_repo_pack_fds_open(&pack_fds);
11373 if (error != NULL)
11374 goto done;
11376 error = got_worktree_open(&worktree, cwd);
11377 if (error) {
11378 if (list_backups || delete_backups) {
11379 if (error->code != GOT_ERR_NOT_WORKTREE)
11380 goto done;
11381 } else {
11382 if (error->code == GOT_ERR_NOT_WORKTREE)
11383 error = wrap_not_worktree_error(error,
11384 "histedit", cwd);
11385 goto done;
11389 if (list_backups || delete_backups) {
11390 error = got_repo_open(&repo,
11391 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11392 NULL, pack_fds);
11393 if (error != NULL)
11394 goto done;
11395 error = apply_unveil(got_repo_get_path(repo), 0,
11396 worktree ? got_worktree_get_root_path(worktree) : NULL);
11397 if (error)
11398 goto done;
11399 error = process_backup_refs(
11400 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11401 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11402 goto done; /* nothing else to do */
11405 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11406 NULL, pack_fds);
11407 if (error != NULL)
11408 goto done;
11410 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11411 if (error)
11412 goto done;
11413 if (rebase_in_progress) {
11414 error = got_error(GOT_ERR_REBASING);
11415 goto done;
11418 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11419 repo);
11420 if (error)
11421 goto done;
11422 if (merge_in_progress) {
11423 error = got_error(GOT_ERR_MERGE_BUSY);
11424 goto done;
11427 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11428 if (error)
11429 goto done;
11431 if (edit_in_progress && edit_logmsg_only) {
11432 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11433 "histedit operation is in progress in this "
11434 "work tree and must be continued or aborted "
11435 "before the -m option can be used");
11436 goto done;
11438 if (edit_in_progress && fold_only) {
11439 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11440 "histedit operation is in progress in this "
11441 "work tree and must be continued or aborted "
11442 "before the -f option can be used");
11443 goto done;
11445 if (edit_in_progress && edit_only) {
11446 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11447 "histedit operation is in progress in this "
11448 "work tree and must be continued or aborted "
11449 "before the -e option can be used");
11450 goto done;
11453 if (edit_in_progress && abort_edit) {
11454 error = got_worktree_histedit_continue(&resume_commit_id,
11455 &tmp_branch, &branch, &base_commit_id, &fileindex,
11456 worktree, repo);
11457 if (error)
11458 goto done;
11459 printf("Switching work tree to %s\n",
11460 got_ref_get_symref_target(branch));
11461 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11462 branch, base_commit_id, abort_progress, &upa);
11463 if (error)
11464 goto done;
11465 printf("Histedit of %s aborted\n",
11466 got_ref_get_symref_target(branch));
11467 print_merge_progress_stats(&upa);
11468 goto done; /* nothing else to do */
11469 } else if (abort_edit) {
11470 error = got_error(GOT_ERR_NOT_HISTEDIT);
11471 goto done;
11474 if (continue_edit) {
11475 char *path;
11477 if (!edit_in_progress) {
11478 error = got_error(GOT_ERR_NOT_HISTEDIT);
11479 goto done;
11482 error = got_worktree_get_histedit_script_path(&path, worktree);
11483 if (error)
11484 goto done;
11486 error = histedit_load_list(&histedit_cmds, path, repo);
11487 free(path);
11488 if (error)
11489 goto done;
11491 error = got_worktree_histedit_continue(&resume_commit_id,
11492 &tmp_branch, &branch, &base_commit_id, &fileindex,
11493 worktree, repo);
11494 if (error)
11495 goto done;
11497 error = got_ref_resolve(&head_commit_id, repo, branch);
11498 if (error)
11499 goto done;
11501 error = got_object_open_as_commit(&commit, repo,
11502 head_commit_id);
11503 if (error)
11504 goto done;
11505 parent_ids = got_object_commit_get_parent_ids(commit);
11506 pid = STAILQ_FIRST(parent_ids);
11507 if (pid == NULL) {
11508 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11509 goto done;
11511 error = collect_commits(&commits, head_commit_id, &pid->id,
11512 base_commit_id, got_worktree_get_path_prefix(worktree),
11513 GOT_ERR_HISTEDIT_PATH, repo);
11514 got_object_commit_close(commit);
11515 commit = NULL;
11516 if (error)
11517 goto done;
11518 } else {
11519 if (edit_in_progress) {
11520 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11521 goto done;
11524 error = got_ref_open(&branch, repo,
11525 got_worktree_get_head_ref_name(worktree), 0);
11526 if (error != NULL)
11527 goto done;
11529 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11530 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11531 "will not edit commit history of a branch outside "
11532 "the \"refs/heads/\" reference namespace");
11533 goto done;
11536 error = got_ref_resolve(&head_commit_id, repo, branch);
11537 got_ref_close(branch);
11538 branch = NULL;
11539 if (error)
11540 goto done;
11542 error = got_object_open_as_commit(&commit, repo,
11543 head_commit_id);
11544 if (error)
11545 goto done;
11546 parent_ids = got_object_commit_get_parent_ids(commit);
11547 pid = STAILQ_FIRST(parent_ids);
11548 if (pid == NULL) {
11549 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11550 goto done;
11552 error = collect_commits(&commits, head_commit_id, &pid->id,
11553 got_worktree_get_base_commit_id(worktree),
11554 got_worktree_get_path_prefix(worktree),
11555 GOT_ERR_HISTEDIT_PATH, repo);
11556 got_object_commit_close(commit);
11557 commit = NULL;
11558 if (error)
11559 goto done;
11561 if (STAILQ_EMPTY(&commits)) {
11562 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11563 goto done;
11566 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11567 &base_commit_id, &fileindex, worktree, repo);
11568 if (error)
11569 goto done;
11571 if (edit_script_path) {
11572 error = histedit_load_list(&histedit_cmds,
11573 edit_script_path, repo);
11574 if (error) {
11575 got_worktree_histedit_abort(worktree, fileindex,
11576 repo, branch, base_commit_id,
11577 abort_progress, &upa);
11578 print_merge_progress_stats(&upa);
11579 goto done;
11581 } else {
11582 const char *branch_name;
11583 branch_name = got_ref_get_symref_target(branch);
11584 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11585 branch_name += 11;
11586 error = histedit_edit_script(&histedit_cmds, &commits,
11587 branch_name, edit_logmsg_only, fold_only,
11588 edit_only, repo);
11589 if (error) {
11590 got_worktree_histedit_abort(worktree, fileindex,
11591 repo, branch, base_commit_id,
11592 abort_progress, &upa);
11593 print_merge_progress_stats(&upa);
11594 goto done;
11599 error = histedit_save_list(&histedit_cmds, worktree,
11600 repo);
11601 if (error) {
11602 got_worktree_histedit_abort(worktree, fileindex,
11603 repo, branch, base_commit_id,
11604 abort_progress, &upa);
11605 print_merge_progress_stats(&upa);
11606 goto done;
11611 error = histedit_check_script(&histedit_cmds, &commits, repo);
11612 if (error)
11613 goto done;
11615 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11616 if (resume_commit_id) {
11617 if (got_object_id_cmp(hle->commit_id,
11618 resume_commit_id) != 0)
11619 continue;
11621 resume_commit_id = NULL;
11622 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11623 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11624 error = histedit_skip_commit(hle, worktree,
11625 repo);
11626 if (error)
11627 goto done;
11628 } else {
11629 struct got_pathlist_head paths;
11630 int have_changes = 0;
11632 TAILQ_INIT(&paths);
11633 error = got_pathlist_append(&paths, "", NULL);
11634 if (error)
11635 goto done;
11636 error = got_worktree_status(worktree, &paths,
11637 repo, 0, check_local_changes, &have_changes,
11638 check_cancelled, NULL);
11639 got_pathlist_free(&paths);
11640 if (error) {
11641 if (error->code != GOT_ERR_CANCELLED)
11642 goto done;
11643 if (sigint_received || sigpipe_received)
11644 goto done;
11646 if (have_changes) {
11647 error = histedit_commit(NULL, worktree,
11648 fileindex, tmp_branch, hle, repo);
11649 if (error)
11650 goto done;
11651 } else {
11652 error = got_object_open_as_commit(
11653 &commit, repo, hle->commit_id);
11654 if (error)
11655 goto done;
11656 error = show_histedit_progress(commit,
11657 hle, NULL);
11658 got_object_commit_close(commit);
11659 commit = NULL;
11660 if (error)
11661 goto done;
11664 continue;
11667 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11668 error = histedit_skip_commit(hle, worktree, repo);
11669 if (error)
11670 goto done;
11671 continue;
11674 error = got_object_open_as_commit(&commit, repo,
11675 hle->commit_id);
11676 if (error)
11677 goto done;
11678 parent_ids = got_object_commit_get_parent_ids(commit);
11679 pid = STAILQ_FIRST(parent_ids);
11681 error = got_worktree_histedit_merge_files(&merged_paths,
11682 worktree, fileindex, &pid->id, hle->commit_id, repo,
11683 update_progress, &upa, check_cancelled, NULL);
11684 if (error)
11685 goto done;
11686 got_object_commit_close(commit);
11687 commit = NULL;
11689 print_merge_progress_stats(&upa);
11690 if (upa.conflicts > 0 || upa.missing > 0 ||
11691 upa.not_deleted > 0 || upa.unversioned > 0) {
11692 if (upa.conflicts > 0) {
11693 error = show_rebase_merge_conflict(
11694 hle->commit_id, repo);
11695 if (error)
11696 goto done;
11698 got_worktree_rebase_pathlist_free(&merged_paths);
11699 break;
11702 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11703 char *id_str;
11704 error = got_object_id_str(&id_str, hle->commit_id);
11705 if (error)
11706 goto done;
11707 printf("Stopping histedit for amending commit %s\n",
11708 id_str);
11709 free(id_str);
11710 got_worktree_rebase_pathlist_free(&merged_paths);
11711 error = got_worktree_histedit_postpone(worktree,
11712 fileindex);
11713 goto done;
11716 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11717 error = histedit_skip_commit(hle, worktree, repo);
11718 if (error)
11719 goto done;
11720 continue;
11723 error = histedit_commit(&merged_paths, worktree, fileindex,
11724 tmp_branch, hle, repo);
11725 got_worktree_rebase_pathlist_free(&merged_paths);
11726 if (error)
11727 goto done;
11730 if (upa.conflicts > 0 || upa.missing > 0 ||
11731 upa.not_deleted > 0 || upa.unversioned > 0) {
11732 error = got_worktree_histedit_postpone(worktree, fileindex);
11733 if (error)
11734 goto done;
11735 if (upa.conflicts > 0 && upa.missing == 0 &&
11736 upa.not_deleted == 0 && upa.unversioned == 0) {
11737 error = got_error_msg(GOT_ERR_CONFLICTS,
11738 "conflicts must be resolved before histedit "
11739 "can continue");
11740 } else if (upa.conflicts > 0) {
11741 error = got_error_msg(GOT_ERR_CONFLICTS,
11742 "conflicts must be resolved before histedit "
11743 "can continue; changes destined for some "
11744 "files were not yet merged and should be "
11745 "merged manually if required before the "
11746 "histedit operation is continued");
11747 } else {
11748 error = got_error_msg(GOT_ERR_CONFLICTS,
11749 "changes destined for some files were not "
11750 "yet merged and should be merged manually "
11751 "if required before the histedit operation "
11752 "is continued");
11754 } else
11755 error = histedit_complete(worktree, fileindex, tmp_branch,
11756 branch, repo);
11757 done:
11758 got_object_id_queue_free(&commits);
11759 histedit_free_list(&histedit_cmds);
11760 free(head_commit_id);
11761 free(base_commit_id);
11762 free(resume_commit_id);
11763 if (commit)
11764 got_object_commit_close(commit);
11765 if (branch)
11766 got_ref_close(branch);
11767 if (tmp_branch)
11768 got_ref_close(tmp_branch);
11769 if (worktree)
11770 got_worktree_close(worktree);
11771 if (repo) {
11772 const struct got_error *close_err = got_repo_close(repo);
11773 if (error == NULL)
11774 error = close_err;
11776 if (pack_fds) {
11777 const struct got_error *pack_err =
11778 got_repo_pack_fds_close(pack_fds);
11779 if (error == NULL)
11780 error = pack_err;
11782 return error;
11785 __dead static void
11786 usage_integrate(void)
11788 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11789 exit(1);
11792 static const struct got_error *
11793 cmd_integrate(int argc, char *argv[])
11795 const struct got_error *error = NULL;
11796 struct got_repository *repo = NULL;
11797 struct got_worktree *worktree = NULL;
11798 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11799 const char *branch_arg = NULL;
11800 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11801 struct got_fileindex *fileindex = NULL;
11802 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11803 int ch;
11804 struct got_update_progress_arg upa;
11805 int *pack_fds = NULL;
11807 while ((ch = getopt(argc, argv, "")) != -1) {
11808 switch (ch) {
11809 default:
11810 usage_integrate();
11811 /* NOTREACHED */
11815 argc -= optind;
11816 argv += optind;
11818 if (argc != 1)
11819 usage_integrate();
11820 branch_arg = argv[0];
11821 #ifndef PROFILE
11822 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11823 "unveil", NULL) == -1)
11824 err(1, "pledge");
11825 #endif
11826 cwd = getcwd(NULL, 0);
11827 if (cwd == NULL) {
11828 error = got_error_from_errno("getcwd");
11829 goto done;
11832 error = got_repo_pack_fds_open(&pack_fds);
11833 if (error != NULL)
11834 goto done;
11836 error = got_worktree_open(&worktree, cwd);
11837 if (error) {
11838 if (error->code == GOT_ERR_NOT_WORKTREE)
11839 error = wrap_not_worktree_error(error, "integrate",
11840 cwd);
11841 goto done;
11844 error = check_rebase_or_histedit_in_progress(worktree);
11845 if (error)
11846 goto done;
11848 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11849 NULL, pack_fds);
11850 if (error != NULL)
11851 goto done;
11853 error = apply_unveil(got_repo_get_path(repo), 0,
11854 got_worktree_get_root_path(worktree));
11855 if (error)
11856 goto done;
11858 error = check_merge_in_progress(worktree, repo);
11859 if (error)
11860 goto done;
11862 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11863 error = got_error_from_errno("asprintf");
11864 goto done;
11867 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11868 &base_branch_ref, worktree, refname, repo);
11869 if (error)
11870 goto done;
11872 refname = strdup(got_ref_get_name(branch_ref));
11873 if (refname == NULL) {
11874 error = got_error_from_errno("strdup");
11875 got_worktree_integrate_abort(worktree, fileindex, repo,
11876 branch_ref, base_branch_ref);
11877 goto done;
11879 base_refname = strdup(got_ref_get_name(base_branch_ref));
11880 if (base_refname == NULL) {
11881 error = got_error_from_errno("strdup");
11882 got_worktree_integrate_abort(worktree, fileindex, repo,
11883 branch_ref, base_branch_ref);
11884 goto done;
11887 error = got_ref_resolve(&commit_id, repo, branch_ref);
11888 if (error)
11889 goto done;
11891 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11892 if (error)
11893 goto done;
11895 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11896 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11897 "specified branch has already been integrated");
11898 got_worktree_integrate_abort(worktree, fileindex, repo,
11899 branch_ref, base_branch_ref);
11900 goto done;
11903 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11904 if (error) {
11905 if (error->code == GOT_ERR_ANCESTRY)
11906 error = got_error(GOT_ERR_REBASE_REQUIRED);
11907 got_worktree_integrate_abort(worktree, fileindex, repo,
11908 branch_ref, base_branch_ref);
11909 goto done;
11912 memset(&upa, 0, sizeof(upa));
11913 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11914 branch_ref, base_branch_ref, update_progress, &upa,
11915 check_cancelled, NULL);
11916 if (error)
11917 goto done;
11919 printf("Integrated %s into %s\n", refname, base_refname);
11920 print_update_progress_stats(&upa);
11921 done:
11922 if (repo) {
11923 const struct got_error *close_err = got_repo_close(repo);
11924 if (error == NULL)
11925 error = close_err;
11927 if (worktree)
11928 got_worktree_close(worktree);
11929 if (pack_fds) {
11930 const struct got_error *pack_err =
11931 got_repo_pack_fds_close(pack_fds);
11932 if (error == NULL)
11933 error = pack_err;
11935 free(cwd);
11936 free(base_commit_id);
11937 free(commit_id);
11938 free(refname);
11939 free(base_refname);
11940 return error;
11943 __dead static void
11944 usage_merge(void)
11946 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11947 getprogname());
11948 exit(1);
11951 static const struct got_error *
11952 cmd_merge(int argc, char *argv[])
11954 const struct got_error *error = NULL;
11955 struct got_worktree *worktree = NULL;
11956 struct got_repository *repo = NULL;
11957 struct got_fileindex *fileindex = NULL;
11958 char *cwd = NULL, *id_str = NULL, *author = NULL;
11959 struct got_reference *branch = NULL, *wt_branch = NULL;
11960 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11961 struct got_object_id *wt_branch_tip = NULL;
11962 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11963 int interrupt_merge = 0;
11964 struct got_update_progress_arg upa;
11965 struct got_object_id *merge_commit_id = NULL;
11966 char *branch_name = NULL;
11967 int *pack_fds = NULL;
11969 memset(&upa, 0, sizeof(upa));
11971 while ((ch = getopt(argc, argv, "acn")) != -1) {
11972 switch (ch) {
11973 case 'a':
11974 abort_merge = 1;
11975 break;
11976 case 'c':
11977 continue_merge = 1;
11978 break;
11979 case 'n':
11980 interrupt_merge = 1;
11981 break;
11982 default:
11983 usage_rebase();
11984 /* NOTREACHED */
11988 argc -= optind;
11989 argv += optind;
11991 #ifndef PROFILE
11992 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11993 "unveil", NULL) == -1)
11994 err(1, "pledge");
11995 #endif
11997 if (abort_merge && continue_merge)
11998 option_conflict('a', 'c');
11999 if (abort_merge || continue_merge) {
12000 if (argc != 0)
12001 usage_merge();
12002 } else if (argc != 1)
12003 usage_merge();
12005 cwd = getcwd(NULL, 0);
12006 if (cwd == NULL) {
12007 error = got_error_from_errno("getcwd");
12008 goto done;
12011 error = got_repo_pack_fds_open(&pack_fds);
12012 if (error != NULL)
12013 goto done;
12015 error = got_worktree_open(&worktree, cwd);
12016 if (error) {
12017 if (error->code == GOT_ERR_NOT_WORKTREE)
12018 error = wrap_not_worktree_error(error,
12019 "merge", cwd);
12020 goto done;
12023 error = got_repo_open(&repo,
12024 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12025 pack_fds);
12026 if (error != NULL)
12027 goto done;
12029 error = apply_unveil(got_repo_get_path(repo), 0,
12030 worktree ? got_worktree_get_root_path(worktree) : NULL);
12031 if (error)
12032 goto done;
12034 error = check_rebase_or_histedit_in_progress(worktree);
12035 if (error)
12036 goto done;
12038 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12039 repo);
12040 if (error)
12041 goto done;
12043 if (abort_merge) {
12044 if (!merge_in_progress) {
12045 error = got_error(GOT_ERR_NOT_MERGING);
12046 goto done;
12048 error = got_worktree_merge_continue(&branch_name,
12049 &branch_tip, &fileindex, worktree, repo);
12050 if (error)
12051 goto done;
12052 error = got_worktree_merge_abort(worktree, fileindex, repo,
12053 abort_progress, &upa);
12054 if (error)
12055 goto done;
12056 printf("Merge of %s aborted\n", branch_name);
12057 goto done; /* nothing else to do */
12060 error = get_author(&author, repo, worktree);
12061 if (error)
12062 goto done;
12064 if (continue_merge) {
12065 if (!merge_in_progress) {
12066 error = got_error(GOT_ERR_NOT_MERGING);
12067 goto done;
12069 error = got_worktree_merge_continue(&branch_name,
12070 &branch_tip, &fileindex, worktree, repo);
12071 if (error)
12072 goto done;
12073 } else {
12074 error = got_ref_open(&branch, repo, argv[0], 0);
12075 if (error != NULL)
12076 goto done;
12077 branch_name = strdup(got_ref_get_name(branch));
12078 if (branch_name == NULL) {
12079 error = got_error_from_errno("strdup");
12080 goto done;
12082 error = got_ref_resolve(&branch_tip, repo, branch);
12083 if (error)
12084 goto done;
12087 error = got_ref_open(&wt_branch, repo,
12088 got_worktree_get_head_ref_name(worktree), 0);
12089 if (error)
12090 goto done;
12091 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12092 if (error)
12093 goto done;
12094 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12095 wt_branch_tip, branch_tip, 0, repo,
12096 check_cancelled, NULL);
12097 if (error && error->code != GOT_ERR_ANCESTRY)
12098 goto done;
12100 if (!continue_merge) {
12101 error = check_path_prefix(wt_branch_tip, branch_tip,
12102 got_worktree_get_path_prefix(worktree),
12103 GOT_ERR_MERGE_PATH, repo);
12104 if (error)
12105 goto done;
12106 if (yca_id) {
12107 error = check_same_branch(wt_branch_tip, branch,
12108 yca_id, repo);
12109 if (error) {
12110 if (error->code != GOT_ERR_ANCESTRY)
12111 goto done;
12112 error = NULL;
12113 } else {
12114 static char msg[512];
12115 snprintf(msg, sizeof(msg),
12116 "cannot create a merge commit because "
12117 "%s is based on %s; %s can be integrated "
12118 "with 'got integrate' instead", branch_name,
12119 got_worktree_get_head_ref_name(worktree),
12120 branch_name);
12121 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12122 goto done;
12125 error = got_worktree_merge_prepare(&fileindex, worktree,
12126 branch, repo);
12127 if (error)
12128 goto done;
12130 error = got_worktree_merge_branch(worktree, fileindex,
12131 yca_id, branch_tip, repo, update_progress, &upa,
12132 check_cancelled, NULL);
12133 if (error)
12134 goto done;
12135 print_merge_progress_stats(&upa);
12136 if (!upa.did_something) {
12137 error = got_worktree_merge_abort(worktree, fileindex,
12138 repo, abort_progress, &upa);
12139 if (error)
12140 goto done;
12141 printf("Already up-to-date\n");
12142 goto done;
12146 if (interrupt_merge) {
12147 error = got_worktree_merge_postpone(worktree, fileindex);
12148 if (error)
12149 goto done;
12150 printf("Merge of %s interrupted on request\n", branch_name);
12151 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12152 upa.not_deleted > 0 || upa.unversioned > 0) {
12153 error = got_worktree_merge_postpone(worktree, fileindex);
12154 if (error)
12155 goto done;
12156 if (upa.conflicts > 0 && upa.missing == 0 &&
12157 upa.not_deleted == 0 && upa.unversioned == 0) {
12158 error = got_error_msg(GOT_ERR_CONFLICTS,
12159 "conflicts must be resolved before merging "
12160 "can continue");
12161 } else if (upa.conflicts > 0) {
12162 error = got_error_msg(GOT_ERR_CONFLICTS,
12163 "conflicts must be resolved before merging "
12164 "can continue; changes destined for some "
12165 "files were not yet merged and "
12166 "should be merged manually if required before the "
12167 "merge operation is continued");
12168 } else {
12169 error = got_error_msg(GOT_ERR_CONFLICTS,
12170 "changes destined for some "
12171 "files were not yet merged and should be "
12172 "merged manually if required before the "
12173 "merge operation is continued");
12175 goto done;
12176 } else {
12177 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12178 fileindex, author, NULL, 1, branch_tip, branch_name,
12179 repo, continue_merge ? print_status : NULL, NULL);
12180 if (error)
12181 goto done;
12182 error = got_worktree_merge_complete(worktree, fileindex, repo);
12183 if (error)
12184 goto done;
12185 error = got_object_id_str(&id_str, merge_commit_id);
12186 if (error)
12187 goto done;
12188 printf("Merged %s into %s: %s\n", branch_name,
12189 got_worktree_get_head_ref_name(worktree),
12190 id_str);
12193 done:
12194 free(id_str);
12195 free(merge_commit_id);
12196 free(author);
12197 free(branch_tip);
12198 free(branch_name);
12199 free(yca_id);
12200 if (branch)
12201 got_ref_close(branch);
12202 if (wt_branch)
12203 got_ref_close(wt_branch);
12204 if (worktree)
12205 got_worktree_close(worktree);
12206 if (repo) {
12207 const struct got_error *close_err = got_repo_close(repo);
12208 if (error == NULL)
12209 error = close_err;
12211 if (pack_fds) {
12212 const struct got_error *pack_err =
12213 got_repo_pack_fds_close(pack_fds);
12214 if (error == NULL)
12215 error = pack_err;
12217 return error;
12220 __dead static void
12221 usage_stage(void)
12223 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12224 "[-S] [file-path ...]\n",
12225 getprogname());
12226 exit(1);
12229 static const struct got_error *
12230 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12231 const char *path, struct got_object_id *blob_id,
12232 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12233 int dirfd, const char *de_name)
12235 const struct got_error *err = NULL;
12236 char *id_str = NULL;
12238 if (staged_status != GOT_STATUS_ADD &&
12239 staged_status != GOT_STATUS_MODIFY &&
12240 staged_status != GOT_STATUS_DELETE)
12241 return NULL;
12243 if (staged_status == GOT_STATUS_ADD ||
12244 staged_status == GOT_STATUS_MODIFY)
12245 err = got_object_id_str(&id_str, staged_blob_id);
12246 else
12247 err = got_object_id_str(&id_str, blob_id);
12248 if (err)
12249 return err;
12251 printf("%s %c %s\n", id_str, staged_status, path);
12252 free(id_str);
12253 return NULL;
12256 static const struct got_error *
12257 cmd_stage(int argc, char *argv[])
12259 const struct got_error *error = NULL;
12260 struct got_repository *repo = NULL;
12261 struct got_worktree *worktree = NULL;
12262 char *cwd = NULL;
12263 struct got_pathlist_head paths;
12264 struct got_pathlist_entry *pe;
12265 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12266 FILE *patch_script_file = NULL;
12267 const char *patch_script_path = NULL;
12268 struct choose_patch_arg cpa;
12269 int *pack_fds = NULL;
12271 TAILQ_INIT(&paths);
12273 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12274 switch (ch) {
12275 case 'l':
12276 list_stage = 1;
12277 break;
12278 case 'p':
12279 pflag = 1;
12280 break;
12281 case 'F':
12282 patch_script_path = optarg;
12283 break;
12284 case 'S':
12285 allow_bad_symlinks = 1;
12286 break;
12287 default:
12288 usage_stage();
12289 /* NOTREACHED */
12293 argc -= optind;
12294 argv += optind;
12296 #ifndef PROFILE
12297 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12298 "unveil", NULL) == -1)
12299 err(1, "pledge");
12300 #endif
12301 if (list_stage && (pflag || patch_script_path))
12302 errx(1, "-l option cannot be used with other options");
12303 if (patch_script_path && !pflag)
12304 errx(1, "-F option can only be used together with -p option");
12306 cwd = getcwd(NULL, 0);
12307 if (cwd == NULL) {
12308 error = got_error_from_errno("getcwd");
12309 goto done;
12312 error = got_repo_pack_fds_open(&pack_fds);
12313 if (error != NULL)
12314 goto done;
12316 error = got_worktree_open(&worktree, cwd);
12317 if (error) {
12318 if (error->code == GOT_ERR_NOT_WORKTREE)
12319 error = wrap_not_worktree_error(error, "stage", cwd);
12320 goto done;
12323 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12324 NULL, pack_fds);
12325 if (error != NULL)
12326 goto done;
12328 if (patch_script_path) {
12329 patch_script_file = fopen(patch_script_path, "re");
12330 if (patch_script_file == NULL) {
12331 error = got_error_from_errno2("fopen",
12332 patch_script_path);
12333 goto done;
12336 error = apply_unveil(got_repo_get_path(repo), 0,
12337 got_worktree_get_root_path(worktree));
12338 if (error)
12339 goto done;
12341 error = check_merge_in_progress(worktree, repo);
12342 if (error)
12343 goto done;
12345 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12346 if (error)
12347 goto done;
12349 if (list_stage)
12350 error = got_worktree_status(worktree, &paths, repo, 0,
12351 print_stage, NULL, check_cancelled, NULL);
12352 else {
12353 cpa.patch_script_file = patch_script_file;
12354 cpa.action = "stage";
12355 error = got_worktree_stage(worktree, &paths,
12356 pflag ? NULL : print_status, NULL,
12357 pflag ? choose_patch : NULL, &cpa,
12358 allow_bad_symlinks, repo);
12360 done:
12361 if (patch_script_file && fclose(patch_script_file) == EOF &&
12362 error == NULL)
12363 error = got_error_from_errno2("fclose", patch_script_path);
12364 if (repo) {
12365 const struct got_error *close_err = got_repo_close(repo);
12366 if (error == NULL)
12367 error = close_err;
12369 if (worktree)
12370 got_worktree_close(worktree);
12371 if (pack_fds) {
12372 const struct got_error *pack_err =
12373 got_repo_pack_fds_close(pack_fds);
12374 if (error == NULL)
12375 error = pack_err;
12377 TAILQ_FOREACH(pe, &paths, entry)
12378 free((char *)pe->path);
12379 got_pathlist_free(&paths);
12380 free(cwd);
12381 return error;
12384 __dead static void
12385 usage_unstage(void)
12387 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12388 "[file-path ...]\n",
12389 getprogname());
12390 exit(1);
12394 static const struct got_error *
12395 cmd_unstage(int argc, char *argv[])
12397 const struct got_error *error = NULL;
12398 struct got_repository *repo = NULL;
12399 struct got_worktree *worktree = NULL;
12400 char *cwd = NULL;
12401 struct got_pathlist_head paths;
12402 struct got_pathlist_entry *pe;
12403 int ch, pflag = 0;
12404 struct got_update_progress_arg upa;
12405 FILE *patch_script_file = NULL;
12406 const char *patch_script_path = NULL;
12407 struct choose_patch_arg cpa;
12408 int *pack_fds = NULL;
12410 TAILQ_INIT(&paths);
12412 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12413 switch (ch) {
12414 case 'p':
12415 pflag = 1;
12416 break;
12417 case 'F':
12418 patch_script_path = optarg;
12419 break;
12420 default:
12421 usage_unstage();
12422 /* NOTREACHED */
12426 argc -= optind;
12427 argv += optind;
12429 #ifndef PROFILE
12430 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12431 "unveil", NULL) == -1)
12432 err(1, "pledge");
12433 #endif
12434 if (patch_script_path && !pflag)
12435 errx(1, "-F option can only be used together with -p option");
12437 cwd = getcwd(NULL, 0);
12438 if (cwd == NULL) {
12439 error = got_error_from_errno("getcwd");
12440 goto done;
12443 error = got_repo_pack_fds_open(&pack_fds);
12444 if (error != NULL)
12445 goto done;
12447 error = got_worktree_open(&worktree, cwd);
12448 if (error) {
12449 if (error->code == GOT_ERR_NOT_WORKTREE)
12450 error = wrap_not_worktree_error(error, "unstage", cwd);
12451 goto done;
12454 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12455 NULL, pack_fds);
12456 if (error != NULL)
12457 goto done;
12459 if (patch_script_path) {
12460 patch_script_file = fopen(patch_script_path, "re");
12461 if (patch_script_file == NULL) {
12462 error = got_error_from_errno2("fopen",
12463 patch_script_path);
12464 goto done;
12468 error = apply_unveil(got_repo_get_path(repo), 0,
12469 got_worktree_get_root_path(worktree));
12470 if (error)
12471 goto done;
12473 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12474 if (error)
12475 goto done;
12477 cpa.patch_script_file = patch_script_file;
12478 cpa.action = "unstage";
12479 memset(&upa, 0, sizeof(upa));
12480 error = got_worktree_unstage(worktree, &paths, update_progress,
12481 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12482 if (!error)
12483 print_merge_progress_stats(&upa);
12484 done:
12485 if (patch_script_file && fclose(patch_script_file) == EOF &&
12486 error == NULL)
12487 error = got_error_from_errno2("fclose", patch_script_path);
12488 if (repo) {
12489 const struct got_error *close_err = got_repo_close(repo);
12490 if (error == NULL)
12491 error = close_err;
12493 if (worktree)
12494 got_worktree_close(worktree);
12495 if (pack_fds) {
12496 const struct got_error *pack_err =
12497 got_repo_pack_fds_close(pack_fds);
12498 if (error == NULL)
12499 error = pack_err;
12501 TAILQ_FOREACH(pe, &paths, entry)
12502 free((char *)pe->path);
12503 got_pathlist_free(&paths);
12504 free(cwd);
12505 return error;
12508 __dead static void
12509 usage_cat(void)
12511 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12512 "arg1 [arg2 ...]\n", getprogname());
12513 exit(1);
12516 static const struct got_error *
12517 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12519 const struct got_error *err;
12520 struct got_blob_object *blob;
12521 int fd = -1;
12523 fd = got_opentempfd();
12524 if (fd == -1)
12525 return got_error_from_errno("got_opentempfd");
12527 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12528 if (err)
12529 goto done;
12531 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12532 done:
12533 if (fd != -1 && close(fd) == -1 && err == NULL)
12534 err = got_error_from_errno("close");
12535 if (blob)
12536 got_object_blob_close(blob);
12537 return err;
12540 static const struct got_error *
12541 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12543 const struct got_error *err;
12544 struct got_tree_object *tree;
12545 int nentries, i;
12547 err = got_object_open_as_tree(&tree, repo, id);
12548 if (err)
12549 return err;
12551 nentries = got_object_tree_get_nentries(tree);
12552 for (i = 0; i < nentries; i++) {
12553 struct got_tree_entry *te;
12554 char *id_str;
12555 if (sigint_received || sigpipe_received)
12556 break;
12557 te = got_object_tree_get_entry(tree, i);
12558 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12559 if (err)
12560 break;
12561 fprintf(outfile, "%s %.7o %s\n", id_str,
12562 got_tree_entry_get_mode(te),
12563 got_tree_entry_get_name(te));
12564 free(id_str);
12567 got_object_tree_close(tree);
12568 return err;
12571 static const struct got_error *
12572 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12574 const struct got_error *err;
12575 struct got_commit_object *commit;
12576 const struct got_object_id_queue *parent_ids;
12577 struct got_object_qid *pid;
12578 char *id_str = NULL;
12579 const char *logmsg = NULL;
12580 char gmtoff[6];
12582 err = got_object_open_as_commit(&commit, repo, id);
12583 if (err)
12584 return err;
12586 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12587 if (err)
12588 goto done;
12590 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12591 parent_ids = got_object_commit_get_parent_ids(commit);
12592 fprintf(outfile, "numparents %d\n",
12593 got_object_commit_get_nparents(commit));
12594 STAILQ_FOREACH(pid, parent_ids, entry) {
12595 char *pid_str;
12596 err = got_object_id_str(&pid_str, &pid->id);
12597 if (err)
12598 goto done;
12599 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12600 free(pid_str);
12602 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12603 got_object_commit_get_author_gmtoff(commit));
12604 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12605 got_object_commit_get_author(commit),
12606 (long long)got_object_commit_get_author_time(commit),
12607 gmtoff);
12609 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12610 got_object_commit_get_committer_gmtoff(commit));
12611 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12612 got_object_commit_get_author(commit),
12613 (long long)got_object_commit_get_committer_time(commit),
12614 gmtoff);
12616 logmsg = got_object_commit_get_logmsg_raw(commit);
12617 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12618 fprintf(outfile, "%s", logmsg);
12619 done:
12620 free(id_str);
12621 got_object_commit_close(commit);
12622 return err;
12625 static const struct got_error *
12626 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12628 const struct got_error *err;
12629 struct got_tag_object *tag;
12630 char *id_str = NULL;
12631 const char *tagmsg = NULL;
12632 char gmtoff[6];
12634 err = got_object_open_as_tag(&tag, repo, id);
12635 if (err)
12636 return err;
12638 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12639 if (err)
12640 goto done;
12642 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12644 switch (got_object_tag_get_object_type(tag)) {
12645 case GOT_OBJ_TYPE_BLOB:
12646 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12647 GOT_OBJ_LABEL_BLOB);
12648 break;
12649 case GOT_OBJ_TYPE_TREE:
12650 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12651 GOT_OBJ_LABEL_TREE);
12652 break;
12653 case GOT_OBJ_TYPE_COMMIT:
12654 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12655 GOT_OBJ_LABEL_COMMIT);
12656 break;
12657 case GOT_OBJ_TYPE_TAG:
12658 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12659 GOT_OBJ_LABEL_TAG);
12660 break;
12661 default:
12662 break;
12665 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12666 got_object_tag_get_name(tag));
12668 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12669 got_object_tag_get_tagger_gmtoff(tag));
12670 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12671 got_object_tag_get_tagger(tag),
12672 (long long)got_object_tag_get_tagger_time(tag),
12673 gmtoff);
12675 tagmsg = got_object_tag_get_message(tag);
12676 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12677 fprintf(outfile, "%s", tagmsg);
12678 done:
12679 free(id_str);
12680 got_object_tag_close(tag);
12681 return err;
12684 static const struct got_error *
12685 cmd_cat(int argc, char *argv[])
12687 const struct got_error *error;
12688 struct got_repository *repo = NULL;
12689 struct got_worktree *worktree = NULL;
12690 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12691 const char *commit_id_str = NULL;
12692 struct got_object_id *id = NULL, *commit_id = NULL;
12693 struct got_commit_object *commit = NULL;
12694 int ch, obj_type, i, force_path = 0;
12695 struct got_reflist_head refs;
12696 int *pack_fds = NULL;
12698 TAILQ_INIT(&refs);
12700 #ifndef PROFILE
12701 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12702 NULL) == -1)
12703 err(1, "pledge");
12704 #endif
12706 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12707 switch (ch) {
12708 case 'c':
12709 commit_id_str = optarg;
12710 break;
12711 case 'r':
12712 repo_path = realpath(optarg, NULL);
12713 if (repo_path == NULL)
12714 return got_error_from_errno2("realpath",
12715 optarg);
12716 got_path_strip_trailing_slashes(repo_path);
12717 break;
12718 case 'P':
12719 force_path = 1;
12720 break;
12721 default:
12722 usage_cat();
12723 /* NOTREACHED */
12727 argc -= optind;
12728 argv += optind;
12730 cwd = getcwd(NULL, 0);
12731 if (cwd == NULL) {
12732 error = got_error_from_errno("getcwd");
12733 goto done;
12736 error = got_repo_pack_fds_open(&pack_fds);
12737 if (error != NULL)
12738 goto done;
12740 if (repo_path == NULL) {
12741 error = got_worktree_open(&worktree, cwd);
12742 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12743 goto done;
12744 if (worktree) {
12745 repo_path = strdup(
12746 got_worktree_get_repo_path(worktree));
12747 if (repo_path == NULL) {
12748 error = got_error_from_errno("strdup");
12749 goto done;
12752 /* Release work tree lock. */
12753 got_worktree_close(worktree);
12754 worktree = NULL;
12758 if (repo_path == NULL) {
12759 repo_path = strdup(cwd);
12760 if (repo_path == NULL)
12761 return got_error_from_errno("strdup");
12764 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12765 free(repo_path);
12766 if (error != NULL)
12767 goto done;
12769 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12770 if (error)
12771 goto done;
12773 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12774 if (error)
12775 goto done;
12777 if (commit_id_str == NULL)
12778 commit_id_str = GOT_REF_HEAD;
12779 error = got_repo_match_object_id(&commit_id, NULL,
12780 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12781 if (error)
12782 goto done;
12784 error = got_object_open_as_commit(&commit, repo, commit_id);
12785 if (error)
12786 goto done;
12788 for (i = 0; i < argc; i++) {
12789 if (force_path) {
12790 error = got_object_id_by_path(&id, repo, commit,
12791 argv[i]);
12792 if (error)
12793 break;
12794 } else {
12795 error = got_repo_match_object_id(&id, &label, argv[i],
12796 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12797 repo);
12798 if (error) {
12799 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12800 error->code != GOT_ERR_NOT_REF)
12801 break;
12802 error = got_object_id_by_path(&id, repo,
12803 commit, argv[i]);
12804 if (error)
12805 break;
12809 error = got_object_get_type(&obj_type, repo, id);
12810 if (error)
12811 break;
12813 switch (obj_type) {
12814 case GOT_OBJ_TYPE_BLOB:
12815 error = cat_blob(id, repo, stdout);
12816 break;
12817 case GOT_OBJ_TYPE_TREE:
12818 error = cat_tree(id, repo, stdout);
12819 break;
12820 case GOT_OBJ_TYPE_COMMIT:
12821 error = cat_commit(id, repo, stdout);
12822 break;
12823 case GOT_OBJ_TYPE_TAG:
12824 error = cat_tag(id, repo, stdout);
12825 break;
12826 default:
12827 error = got_error(GOT_ERR_OBJ_TYPE);
12828 break;
12830 if (error)
12831 break;
12832 free(label);
12833 label = NULL;
12834 free(id);
12835 id = NULL;
12837 done:
12838 free(label);
12839 free(id);
12840 free(commit_id);
12841 if (commit)
12842 got_object_commit_close(commit);
12843 if (worktree)
12844 got_worktree_close(worktree);
12845 if (repo) {
12846 const struct got_error *close_err = got_repo_close(repo);
12847 if (error == NULL)
12848 error = close_err;
12850 if (pack_fds) {
12851 const struct got_error *pack_err =
12852 got_repo_pack_fds_close(pack_fds);
12853 if (error == NULL)
12854 error = pack_err;
12857 got_ref_list_free(&refs);
12858 return error;
12861 __dead static void
12862 usage_info(void)
12864 fprintf(stderr, "usage: %s info [path ...]\n",
12865 getprogname());
12866 exit(1);
12869 static const struct got_error *
12870 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12871 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12872 struct got_object_id *commit_id)
12874 const struct got_error *err = NULL;
12875 char *id_str = NULL;
12876 char datebuf[128];
12877 struct tm mytm, *tm;
12878 struct got_pathlist_head *paths = arg;
12879 struct got_pathlist_entry *pe;
12882 * Clear error indication from any of the path arguments which
12883 * would cause this file index entry to be displayed.
12885 TAILQ_FOREACH(pe, paths, entry) {
12886 if (got_path_cmp(path, pe->path, strlen(path),
12887 pe->path_len) == 0 ||
12888 got_path_is_child(path, pe->path, pe->path_len))
12889 pe->data = NULL; /* no error */
12892 printf(GOT_COMMIT_SEP_STR);
12893 if (S_ISLNK(mode))
12894 printf("symlink: %s\n", path);
12895 else if (S_ISREG(mode)) {
12896 printf("file: %s\n", path);
12897 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12898 } else if (S_ISDIR(mode))
12899 printf("directory: %s\n", path);
12900 else
12901 printf("something: %s\n", path);
12903 tm = localtime_r(&mtime, &mytm);
12904 if (tm == NULL)
12905 return NULL;
12906 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12907 return got_error(GOT_ERR_NO_SPACE);
12908 printf("timestamp: %s\n", datebuf);
12910 if (blob_id) {
12911 err = got_object_id_str(&id_str, blob_id);
12912 if (err)
12913 return err;
12914 printf("based on blob: %s\n", id_str);
12915 free(id_str);
12918 if (staged_blob_id) {
12919 err = got_object_id_str(&id_str, staged_blob_id);
12920 if (err)
12921 return err;
12922 printf("based on staged blob: %s\n", id_str);
12923 free(id_str);
12926 if (commit_id) {
12927 err = got_object_id_str(&id_str, commit_id);
12928 if (err)
12929 return err;
12930 printf("based on commit: %s\n", id_str);
12931 free(id_str);
12934 return NULL;
12937 static const struct got_error *
12938 cmd_info(int argc, char *argv[])
12940 const struct got_error *error = NULL;
12941 struct got_worktree *worktree = NULL;
12942 char *cwd = NULL, *id_str = NULL;
12943 struct got_pathlist_head paths;
12944 struct got_pathlist_entry *pe;
12945 char *uuidstr = NULL;
12946 int ch, show_files = 0;
12947 int *pack_fds = NULL;
12949 TAILQ_INIT(&paths);
12951 while ((ch = getopt(argc, argv, "")) != -1) {
12952 switch (ch) {
12953 default:
12954 usage_info();
12955 /* NOTREACHED */
12959 argc -= optind;
12960 argv += optind;
12962 #ifndef PROFILE
12963 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12964 NULL) == -1)
12965 err(1, "pledge");
12966 #endif
12967 cwd = getcwd(NULL, 0);
12968 if (cwd == NULL) {
12969 error = got_error_from_errno("getcwd");
12970 goto done;
12973 error = got_repo_pack_fds_open(&pack_fds);
12974 if (error != NULL)
12975 goto done;
12977 error = got_worktree_open(&worktree, cwd);
12978 if (error) {
12979 if (error->code == GOT_ERR_NOT_WORKTREE)
12980 error = wrap_not_worktree_error(error, "info", cwd);
12981 goto done;
12984 #ifndef PROFILE
12985 /* Remove "cpath" promise. */
12986 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12987 NULL) == -1)
12988 err(1, "pledge");
12989 #endif
12990 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12991 if (error)
12992 goto done;
12994 if (argc >= 1) {
12995 error = get_worktree_paths_from_argv(&paths, argc, argv,
12996 worktree);
12997 if (error)
12998 goto done;
12999 show_files = 1;
13002 error = got_object_id_str(&id_str,
13003 got_worktree_get_base_commit_id(worktree));
13004 if (error)
13005 goto done;
13007 error = got_worktree_get_uuid(&uuidstr, worktree);
13008 if (error)
13009 goto done;
13011 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13012 printf("work tree base commit: %s\n", id_str);
13013 printf("work tree path prefix: %s\n",
13014 got_worktree_get_path_prefix(worktree));
13015 printf("work tree branch reference: %s\n",
13016 got_worktree_get_head_ref_name(worktree));
13017 printf("work tree UUID: %s\n", uuidstr);
13018 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13020 if (show_files) {
13021 struct got_pathlist_entry *pe;
13022 TAILQ_FOREACH(pe, &paths, entry) {
13023 if (pe->path_len == 0)
13024 continue;
13026 * Assume this path will fail. This will be corrected
13027 * in print_path_info() in case the path does suceeed.
13029 pe->data = (void *)got_error_path(pe->path,
13030 GOT_ERR_BAD_PATH);
13032 error = got_worktree_path_info(worktree, &paths,
13033 print_path_info, &paths, check_cancelled, NULL);
13034 if (error)
13035 goto done;
13036 TAILQ_FOREACH(pe, &paths, entry) {
13037 if (pe->data != NULL) {
13038 error = pe->data; /* bad path */
13039 break;
13043 done:
13044 if (pack_fds) {
13045 const struct got_error *pack_err =
13046 got_repo_pack_fds_close(pack_fds);
13047 if (error == NULL)
13048 error = pack_err;
13050 TAILQ_FOREACH(pe, &paths, entry)
13051 free((char *)pe->path);
13052 got_pathlist_free(&paths);
13053 free(cwd);
13054 free(id_str);
13055 free(uuidstr);
13056 return error;