Blob


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