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