Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 static volatile sig_atomic_t sigint_received;
72 static volatile sig_atomic_t sigpipe_received;
74 static void
75 catch_sigint(int signo)
76 {
77 sigint_received = 1;
78 }
80 static void
81 catch_sigpipe(int signo)
82 {
83 sigpipe_received = 1;
84 }
87 struct got_cmd {
88 const char *cmd_name;
89 const struct got_error *(*cmd_main)(int, char *[]);
90 void (*cmd_usage)(void);
91 const char *cmd_alias;
92 };
94 __dead static void usage(int, int);
95 __dead static void usage_import(void);
96 __dead static void usage_clone(void);
97 __dead static void usage_fetch(void);
98 __dead static void usage_checkout(void);
99 __dead static void usage_update(void);
100 __dead static void usage_log(void);
101 __dead static void usage_diff(void);
102 __dead static void usage_blame(void);
103 __dead static void usage_tree(void);
104 __dead static void usage_status(void);
105 __dead static void usage_ref(void);
106 __dead static void usage_branch(void);
107 __dead static void usage_tag(void);
108 __dead static void usage_add(void);
109 __dead static void usage_remove(void);
110 __dead static void usage_patch(void);
111 __dead static void usage_revert(void);
112 __dead static void usage_commit(void);
113 __dead static void usage_send(void);
114 __dead static void usage_cherrypick(void);
115 __dead static void usage_backout(void);
116 __dead static void usage_rebase(void);
117 __dead static void usage_histedit(void);
118 __dead static void usage_integrate(void);
119 __dead static void usage_merge(void);
120 __dead static void usage_stage(void);
121 __dead static void usage_unstage(void);
122 __dead static void usage_cat(void);
123 __dead static void usage_info(void);
125 static const struct got_error* cmd_import(int, char *[]);
126 static const struct got_error* cmd_clone(int, char *[]);
127 static const struct got_error* cmd_fetch(int, char *[]);
128 static const struct got_error* cmd_checkout(int, char *[]);
129 static const struct got_error* cmd_update(int, char *[]);
130 static const struct got_error* cmd_log(int, char *[]);
131 static const struct got_error* cmd_diff(int, char *[]);
132 static const struct got_error* cmd_blame(int, char *[]);
133 static const struct got_error* cmd_tree(int, char *[]);
134 static const struct got_error* cmd_status(int, char *[]);
135 static const struct got_error* cmd_ref(int, char *[]);
136 static const struct got_error* cmd_branch(int, char *[]);
137 static const struct got_error* cmd_tag(int, char *[]);
138 static const struct got_error* cmd_add(int, char *[]);
139 static const struct got_error* cmd_remove(int, char *[]);
140 static const struct got_error* cmd_patch(int, char *[]);
141 static const struct got_error* cmd_revert(int, char *[]);
142 static const struct got_error* cmd_commit(int, char *[]);
143 static const struct got_error* cmd_send(int, char *[]);
144 static const struct got_error* cmd_cherrypick(int, char *[]);
145 static const struct got_error* cmd_backout(int, char *[]);
146 static const struct got_error* cmd_rebase(int, char *[]);
147 static const struct got_error* cmd_histedit(int, char *[]);
148 static const struct got_error* cmd_integrate(int, char *[]);
149 static const struct got_error* cmd_merge(int, char *[]);
150 static const struct got_error* cmd_stage(int, char *[]);
151 static const struct got_error* cmd_unstage(int, char *[]);
152 static const struct got_error* cmd_cat(int, char *[]);
153 static const struct got_error* cmd_info(int, char *[]);
155 static const struct got_cmd got_commands[] = {
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 fflush(stdout);
270 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
271 return 1;
274 return 0;
277 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
278 list_commands(stderr);
279 return 1;
282 __dead static void
283 usage(int hflag, int status)
285 FILE *fp = (status == 0) ? stdout : stderr;
287 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
288 getprogname());
289 if (hflag)
290 list_commands(fp);
291 exit(status);
294 static const struct got_error *
295 get_editor(char **abspath)
297 const struct got_error *err = NULL;
298 const char *editor;
300 *abspath = NULL;
302 editor = getenv("VISUAL");
303 if (editor == NULL)
304 editor = getenv("EDITOR");
306 if (editor) {
307 err = got_path_find_prog(abspath, editor);
308 if (err)
309 return err;
312 if (*abspath == NULL) {
313 *abspath = strdup("/usr/bin/vi");
314 if (*abspath == NULL)
315 return got_error_from_errno("strdup");
318 return NULL;
321 static const struct got_error *
322 apply_unveil(const char *repo_path, int repo_read_only,
323 const char *worktree_path)
325 const struct got_error *err;
327 #ifdef PROFILE
328 if (unveil("gmon.out", "rwc") != 0)
329 return got_error_from_errno2("unveil", "gmon.out");
330 #endif
331 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
332 return got_error_from_errno2("unveil", repo_path);
334 if (worktree_path && unveil(worktree_path, "rwc") != 0)
335 return got_error_from_errno2("unveil", worktree_path);
337 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
338 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
340 err = got_privsep_unveil_exec_helpers();
341 if (err != NULL)
342 return err;
344 if (unveil(NULL, NULL) != 0)
345 return got_error_from_errno("unveil");
347 return NULL;
350 __dead static void
351 usage_import(void)
353 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
354 "[-r repository-path] directory\n", getprogname());
355 exit(1);
358 static int
359 spawn_editor(const char *editor, const char *file)
361 pid_t pid;
362 sig_t sighup, sigint, sigquit;
363 int st = -1;
365 sighup = signal(SIGHUP, SIG_IGN);
366 sigint = signal(SIGINT, SIG_IGN);
367 sigquit = signal(SIGQUIT, SIG_IGN);
369 switch (pid = fork()) {
370 case -1:
371 goto doneediting;
372 case 0:
373 execl(editor, editor, file, (char *)NULL);
374 _exit(127);
377 while (waitpid(pid, &st, 0) == -1)
378 if (errno != EINTR)
379 break;
381 doneediting:
382 (void)signal(SIGHUP, sighup);
383 (void)signal(SIGINT, sigint);
384 (void)signal(SIGQUIT, sigquit);
386 if (!WIFEXITED(st)) {
387 errno = EINTR;
388 return -1;
391 return WEXITSTATUS(st);
394 static const struct got_error *
395 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
397 const struct got_error *err = NULL;
398 char *line = NULL;
399 size_t linesize = 0;
401 *logmsg = NULL;
402 *len = 0;
404 if (fseeko(fp, 0L, SEEK_SET) == -1)
405 return got_error_from_errno("fseeko");
407 *logmsg = malloc(filesize + 1);
408 if (*logmsg == NULL)
409 return got_error_from_errno("malloc");
410 (*logmsg)[0] = '\0';
412 while (getline(&line, &linesize, fp) != -1) {
413 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
414 continue; /* remove comments and leading empty lines */
415 *len = strlcat(*logmsg, line, filesize + 1);
416 if (*len >= filesize + 1) {
417 err = got_error(GOT_ERR_NO_SPACE);
418 goto done;
421 if (ferror(fp)) {
422 err = got_ferror(fp, GOT_ERR_IO);
423 goto done;
426 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
427 (*logmsg)[*len - 1] = '\0';
428 (*len)--;
430 done:
431 free(line);
432 if (err) {
433 free(*logmsg);
434 *logmsg = NULL;
435 *len = 0;
437 return err;
440 static const struct got_error *
441 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
442 const char *initial_content, size_t initial_content_len,
443 int require_modification)
445 const struct got_error *err = NULL;
446 struct stat st, st2;
447 FILE *fp = NULL;
448 size_t logmsg_len;
450 *logmsg = NULL;
452 if (stat(logmsg_path, &st) == -1)
453 return got_error_from_errno2("stat", logmsg_path);
455 if (spawn_editor(editor, logmsg_path) == -1)
456 return got_error_from_errno("failed spawning editor");
458 if (require_modification) {
459 struct timespec timeout;
461 timeout.tv_sec = 0;
462 timeout.tv_nsec = 1;
463 nanosleep(&timeout, NULL);
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno2("stat", logmsg_path);
469 if (require_modification && st.st_size == st2.st_size &&
470 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 fp = fopen(logmsg_path, "re");
475 if (fp == NULL) {
476 err = got_error_from_errno("fopen");
477 goto done;
480 /* strip comments and leading/trailing newlines */
481 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
482 if (err)
483 goto done;
484 if (logmsg_len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 done:
490 if (fp && fclose(fp) == EOF && err == NULL)
491 err = got_error_from_errno("fclose");
492 if (err) {
493 free(*logmsg);
494 *logmsg = NULL;
496 return err;
499 static const struct got_error *
500 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
501 const char *path_dir, const char *branch_name)
503 char *initial_content = NULL;
504 const struct got_error *err = NULL;
505 int initial_content_len;
506 int fd = -1;
508 initial_content_len = asprintf(&initial_content,
509 "\n# %s to be imported to branch %s\n", path_dir,
510 branch_name);
511 if (initial_content_len == -1)
512 return got_error_from_errno("asprintf");
514 err = got_opentemp_named_fd(logmsg_path, &fd,
515 GOT_TMPDIR_STR "/got-importmsg", "");
516 if (err)
517 goto done;
519 if (write(fd, initial_content, initial_content_len) == -1) {
520 err = got_error_from_errno2("write", *logmsg_path);
521 goto done;
523 if (close(fd) == -1) {
524 err = got_error_from_errno2("close", *logmsg_path);
525 goto done;
527 fd = -1;
529 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
530 initial_content_len, 1);
531 done:
532 if (fd != -1 && close(fd) == -1 && err == NULL)
533 err = got_error_from_errno2("close", *logmsg_path);
534 free(initial_content);
535 if (err) {
536 free(*logmsg_path);
537 *logmsg_path = NULL;
539 return err;
542 static const struct got_error *
543 import_progress(void *arg, const char *path)
545 printf("A %s\n", path);
546 return NULL;
549 static const struct got_error *
550 valid_author(const char *author)
552 const char *email = author;
554 /*
555 * Git' expects the author (or committer) to be in the form
556 * "name <email>", which are mostly free form (see the
557 * "committer" description in git-fast-import(1)). We're only
558 * doing this to avoid git's object parser breaking on commits
559 * we create.
560 */
562 while (*author && *author != '\n' && *author != '<' && *author != '>')
563 author++;
564 if (author != email && *author == '<' && *(author - 1) != ' ')
565 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
566 "between author name and email required", email);
567 if (*author++ != '<')
568 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
569 while (*author && *author != '\n' && *author != '<' && *author != '>')
570 author++;
571 if (strcmp(author, ">") != 0)
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 return NULL;
576 static const struct got_error *
577 get_author(char **author, struct got_repository *repo,
578 struct got_worktree *worktree)
580 const struct got_error *err = NULL;
581 const char *got_author = NULL, *name, *email;
582 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
584 *author = NULL;
586 if (worktree)
587 worktree_conf = got_worktree_get_gotconfig(worktree);
588 repo_conf = got_repo_get_gotconfig(repo);
590 /*
591 * Priority of potential author information sources, from most
592 * significant to least significant:
593 * 1) work tree's .got/got.conf file
594 * 2) repository's got.conf file
595 * 3) repository's git config file
596 * 4) environment variables
597 * 5) global git config files (in user's home directory or /etc)
598 */
600 if (worktree_conf)
601 got_author = got_gotconfig_get_author(worktree_conf);
602 if (got_author == NULL)
603 got_author = got_gotconfig_get_author(repo_conf);
604 if (got_author == NULL) {
605 name = got_repo_get_gitconfig_author_name(repo);
606 email = got_repo_get_gitconfig_author_email(repo);
607 if (name && email) {
608 if (asprintf(author, "%s <%s>", name, email) == -1)
609 return got_error_from_errno("asprintf");
610 return NULL;
613 got_author = getenv("GOT_AUTHOR");
614 if (got_author == NULL) {
615 name = got_repo_get_global_gitconfig_author_name(repo);
616 email = got_repo_get_global_gitconfig_author_email(
617 repo);
618 if (name && email) {
619 if (asprintf(author, "%s <%s>", name, email)
620 == -1)
621 return got_error_from_errno("asprintf");
622 return NULL;
624 /* TODO: Look up user in password database? */
625 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
629 *author = strdup(got_author);
630 if (*author == NULL)
631 return got_error_from_errno("strdup");
633 err = valid_author(*author);
634 if (err) {
635 free(*author);
636 *author = NULL;
638 return err;
641 static const struct got_error *
642 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
643 struct got_worktree *worktree)
645 const char *got_allowed_signers = NULL;
646 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
648 *allowed_signers = NULL;
650 if (worktree)
651 worktree_conf = got_worktree_get_gotconfig(worktree);
652 repo_conf = got_repo_get_gotconfig(repo);
654 /*
655 * Priority of potential author information sources, from most
656 * significant to least significant:
657 * 1) work tree's .got/got.conf file
658 * 2) repository's got.conf file
659 */
661 if (worktree_conf)
662 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
663 worktree_conf);
664 if (got_allowed_signers == NULL)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 repo_conf);
668 if (got_allowed_signers) {
669 *allowed_signers = strdup(got_allowed_signers);
670 if (*allowed_signers == NULL)
671 return got_error_from_errno("strdup");
673 return NULL;
676 static const struct got_error *
677 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
678 struct got_worktree *worktree)
680 const char *got_revoked_signers = NULL;
681 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
683 *revoked_signers = NULL;
685 if (worktree)
686 worktree_conf = got_worktree_get_gotconfig(worktree);
687 repo_conf = got_repo_get_gotconfig(repo);
689 /*
690 * Priority of potential author information sources, from most
691 * significant to least significant:
692 * 1) work tree's .got/got.conf file
693 * 2) repository's got.conf file
694 */
696 if (worktree_conf)
697 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
698 worktree_conf);
699 if (got_revoked_signers == NULL)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 repo_conf);
703 if (got_revoked_signers) {
704 *revoked_signers = strdup(got_revoked_signers);
705 if (*revoked_signers == NULL)
706 return got_error_from_errno("strdup");
708 return NULL;
711 static const char *
712 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
714 const char *got_signer_id = NULL;
715 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
717 if (worktree)
718 worktree_conf = got_worktree_get_gotconfig(worktree);
719 repo_conf = got_repo_get_gotconfig(repo);
721 /*
722 * Priority of potential author information sources, from most
723 * significant to least significant:
724 * 1) work tree's .got/got.conf file
725 * 2) repository's got.conf file
726 */
728 if (worktree_conf)
729 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
730 if (got_signer_id == NULL)
731 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
733 return got_signer_id;
736 static const struct got_error *
737 get_gitconfig_path(char **gitconfig_path)
739 const char *homedir = getenv("HOME");
741 *gitconfig_path = NULL;
742 if (homedir) {
743 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
744 return got_error_from_errno("asprintf");
747 return NULL;
750 static const struct got_error *
751 cmd_import(int argc, char *argv[])
753 const struct got_error *error = NULL;
754 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
755 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
756 const char *branch_name = NULL;
757 char *id_str = NULL, *logmsg_path = NULL;
758 char refname[PATH_MAX] = "refs/heads/";
759 struct got_repository *repo = NULL;
760 struct got_reference *branch_ref = NULL, *head_ref = NULL;
761 struct got_object_id *new_commit_id = NULL;
762 int ch, n = 0;
763 struct got_pathlist_head ignores;
764 struct got_pathlist_entry *pe;
765 int preserve_logmsg = 0;
766 int *pack_fds = NULL;
768 TAILQ_INIT(&ignores);
770 #ifndef PROFILE
771 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
772 "unveil",
773 NULL) == -1)
774 err(1, "pledge");
775 #endif
777 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
778 switch (ch) {
779 case 'b':
780 branch_name = optarg;
781 break;
782 case 'I':
783 if (optarg[0] == '\0')
784 break;
785 error = got_pathlist_insert(&pe, &ignores, optarg,
786 NULL);
787 if (error)
788 goto done;
789 break;
790 case 'm':
791 logmsg = strdup(optarg);
792 if (logmsg == NULL) {
793 error = got_error_from_errno("strdup");
794 goto done;
796 break;
797 case 'r':
798 repo_path = realpath(optarg, NULL);
799 if (repo_path == NULL) {
800 error = got_error_from_errno2("realpath",
801 optarg);
802 goto done;
804 break;
805 default:
806 usage_import();
807 /* NOTREACHED */
811 argc -= optind;
812 argv += optind;
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || *logmsg == '\0') {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (repo) {
974 const struct got_error *close_err = got_repo_close(repo);
975 if (error == NULL)
976 error = close_err;
978 if (preserve_logmsg) {
979 fprintf(stderr, "%s: log message preserved in %s\n",
980 getprogname(), logmsg_path);
981 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
982 error = got_error_from_errno2("unlink", logmsg_path);
983 free(logmsg);
984 free(logmsg_path);
985 free(repo_path);
986 free(editor);
987 free(new_commit_id);
988 free(id_str);
989 free(author);
990 free(gitconfig_path);
991 if (branch_ref)
992 got_ref_close(branch_ref);
993 if (head_ref)
994 got_ref_close(head_ref);
995 return error;
998 __dead static void
999 usage_clone(void)
1001 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1002 "repository-URL [directory]\n", getprogname());
1003 exit(1);
1006 struct got_fetch_progress_arg {
1007 char last_scaled_size[FMT_SCALED_STRSIZE];
1008 int last_p_indexed;
1009 int last_p_resolved;
1010 int verbosity;
1012 struct got_repository *repo;
1014 int create_configs;
1015 int configs_created;
1016 struct {
1017 struct got_pathlist_head *symrefs;
1018 struct got_pathlist_head *wanted_branches;
1019 struct got_pathlist_head *wanted_refs;
1020 const char *proto;
1021 const char *host;
1022 const char *port;
1023 const char *remote_repo_path;
1024 const char *git_url;
1025 int fetch_all_branches;
1026 int mirror_references;
1027 } config_info;
1030 /* XXX forward declaration */
1031 static const struct got_error *
1032 create_config_files(const char *proto, const char *host, const char *port,
1033 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1034 int mirror_references, struct got_pathlist_head *symrefs,
1035 struct got_pathlist_head *wanted_branches,
1036 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1038 static const struct got_error *
1039 fetch_progress(void *arg, const char *message, off_t packfile_size,
1040 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1042 const struct got_error *err = NULL;
1043 struct got_fetch_progress_arg *a = arg;
1044 char scaled_size[FMT_SCALED_STRSIZE];
1045 int p_indexed, p_resolved;
1046 int print_size = 0, print_indexed = 0, print_resolved = 0;
1049 * In order to allow a failed clone to be resumed with 'got fetch'
1050 * we try to create configuration files as soon as possible.
1051 * Once the server has sent information about its default branch
1052 * we have all required information.
1054 if (a->create_configs && !a->configs_created &&
1055 !TAILQ_EMPTY(a->config_info.symrefs)) {
1056 err = create_config_files(a->config_info.proto,
1057 a->config_info.host, a->config_info.port,
1058 a->config_info.remote_repo_path,
1059 a->config_info.git_url,
1060 a->config_info.fetch_all_branches,
1061 a->config_info.mirror_references,
1062 a->config_info.symrefs,
1063 a->config_info.wanted_branches,
1064 a->config_info.wanted_refs, a->repo);
1065 if (err)
1066 return err;
1067 a->configs_created = 1;
1070 if (a->verbosity < 0)
1071 return NULL;
1073 if (message && message[0] != '\0') {
1074 printf("\rserver: %s", message);
1075 fflush(stdout);
1076 return NULL;
1079 if (packfile_size > 0 || nobj_indexed > 0) {
1080 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1081 (a->last_scaled_size[0] == '\0' ||
1082 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1083 print_size = 1;
1084 if (strlcpy(a->last_scaled_size, scaled_size,
1085 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1086 return got_error(GOT_ERR_NO_SPACE);
1088 if (nobj_indexed > 0) {
1089 p_indexed = (nobj_indexed * 100) / nobj_total;
1090 if (p_indexed != a->last_p_indexed) {
1091 a->last_p_indexed = p_indexed;
1092 print_indexed = 1;
1093 print_size = 1;
1096 if (nobj_resolved > 0) {
1097 p_resolved = (nobj_resolved * 100) /
1098 (nobj_total - nobj_loose);
1099 if (p_resolved != a->last_p_resolved) {
1100 a->last_p_resolved = p_resolved;
1101 print_resolved = 1;
1102 print_indexed = 1;
1103 print_size = 1;
1108 if (print_size || print_indexed || print_resolved)
1109 printf("\r");
1110 if (print_size)
1111 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1112 if (print_indexed)
1113 printf("; indexing %d%%", p_indexed);
1114 if (print_resolved)
1115 printf("; resolving deltas %d%%", p_resolved);
1116 if (print_size || print_indexed || print_resolved)
1117 fflush(stdout);
1119 return NULL;
1122 static const struct got_error *
1123 create_symref(const char *refname, struct got_reference *target_ref,
1124 int verbosity, struct got_repository *repo)
1126 const struct got_error *err;
1127 struct got_reference *head_symref;
1129 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1130 if (err)
1131 return err;
1133 err = got_ref_write(head_symref, repo);
1134 if (err == NULL && verbosity > 0) {
1135 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1136 got_ref_get_name(target_ref));
1138 got_ref_close(head_symref);
1139 return err;
1142 static const struct got_error *
1143 list_remote_refs(struct got_pathlist_head *symrefs,
1144 struct got_pathlist_head *refs)
1146 const struct got_error *err;
1147 struct got_pathlist_entry *pe;
1149 TAILQ_FOREACH(pe, symrefs, entry) {
1150 const char *refname = pe->path;
1151 const char *targetref = pe->data;
1153 printf("%s: %s\n", refname, targetref);
1156 TAILQ_FOREACH(pe, refs, entry) {
1157 const char *refname = pe->path;
1158 struct got_object_id *id = pe->data;
1159 char *id_str;
1161 err = got_object_id_str(&id_str, id);
1162 if (err)
1163 return err;
1164 printf("%s: %s\n", refname, id_str);
1165 free(id_str);
1168 return NULL;
1171 static const struct got_error *
1172 create_ref(const char *refname, struct got_object_id *id,
1173 int verbosity, struct got_repository *repo)
1175 const struct got_error *err = NULL;
1176 struct got_reference *ref;
1177 char *id_str;
1179 err = got_object_id_str(&id_str, id);
1180 if (err)
1181 return err;
1183 err = got_ref_alloc(&ref, refname, id);
1184 if (err)
1185 goto done;
1187 err = got_ref_write(ref, repo);
1188 got_ref_close(ref);
1190 if (err == NULL && verbosity >= 0)
1191 printf("Created reference %s: %s\n", refname, id_str);
1192 done:
1193 free(id_str);
1194 return err;
1197 static int
1198 match_wanted_ref(const char *refname, const char *wanted_ref)
1200 if (strncmp(refname, "refs/", 5) != 0)
1201 return 0;
1202 refname += 5;
1205 * Prevent fetching of references that won't make any
1206 * sense outside of the remote repository's context.
1208 if (strncmp(refname, "got/", 4) == 0)
1209 return 0;
1210 if (strncmp(refname, "remotes/", 8) == 0)
1211 return 0;
1213 if (strncmp(wanted_ref, "refs/", 5) == 0)
1214 wanted_ref += 5;
1216 /* Allow prefix match. */
1217 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1218 return 1;
1220 /* Allow exact match. */
1221 return (strcmp(refname, wanted_ref) == 0);
1224 static int
1225 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1227 struct got_pathlist_entry *pe;
1229 TAILQ_FOREACH(pe, wanted_refs, entry) {
1230 if (match_wanted_ref(refname, pe->path))
1231 return 1;
1234 return 0;
1237 static const struct got_error *
1238 create_wanted_ref(const char *refname, struct got_object_id *id,
1239 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1241 const struct got_error *err;
1242 char *remote_refname;
1244 if (strncmp("refs/", refname, 5) == 0)
1245 refname += 5;
1247 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1248 remote_repo_name, refname) == -1)
1249 return got_error_from_errno("asprintf");
1251 err = create_ref(remote_refname, id, verbosity, repo);
1252 free(remote_refname);
1253 return err;
1256 static const struct got_error *
1257 create_gotconfig(const char *proto, const char *host, const char *port,
1258 const char *remote_repo_path, const char *default_branch,
1259 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1260 struct got_pathlist_head *wanted_refs, int mirror_references,
1261 struct got_repository *repo)
1263 const struct got_error *err = NULL;
1264 char *gotconfig_path = NULL;
1265 char *gotconfig = NULL;
1266 FILE *gotconfig_file = NULL;
1267 const char *branchname = NULL;
1268 char *branches = NULL, *refs = NULL;
1269 ssize_t n;
1271 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1272 struct got_pathlist_entry *pe;
1273 TAILQ_FOREACH(pe, wanted_branches, entry) {
1274 char *s;
1275 branchname = pe->path;
1276 if (strncmp(branchname, "refs/heads/", 11) == 0)
1277 branchname += 11;
1278 if (asprintf(&s, "%s\"%s\" ",
1279 branches ? branches : "", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1283 free(branches);
1284 branches = s;
1286 } else if (!fetch_all_branches && default_branch) {
1287 branchname = default_branch;
1288 if (strncmp(branchname, "refs/heads/", 11) == 0)
1289 branchname += 11;
1290 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1295 if (!TAILQ_EMPTY(wanted_refs)) {
1296 struct got_pathlist_entry *pe;
1297 TAILQ_FOREACH(pe, wanted_refs, entry) {
1298 char *s;
1299 const char *refname = pe->path;
1300 if (strncmp(refname, "refs/", 5) == 0)
1301 branchname += 5;
1302 if (asprintf(&s, "%s\"%s\" ",
1303 refs ? refs : "", refname) == -1) {
1304 err = got_error_from_errno("asprintf");
1305 goto done;
1307 free(refs);
1308 refs = s;
1312 /* Create got.conf(5). */
1313 gotconfig_path = got_repo_get_path_gotconfig(repo);
1314 if (gotconfig_path == NULL) {
1315 err = got_error_from_errno("got_repo_get_path_gotconfig");
1316 goto done;
1318 gotconfig_file = fopen(gotconfig_path, "ae");
1319 if (gotconfig_file == NULL) {
1320 err = got_error_from_errno2("fopen", gotconfig_path);
1321 goto done;
1323 if (asprintf(&gotconfig,
1324 "remote \"%s\" {\n"
1325 "\tserver %s\n"
1326 "\tprotocol %s\n"
1327 "%s%s%s"
1328 "\trepository \"%s\"\n"
1329 "%s%s%s"
1330 "%s%s%s"
1331 "%s"
1332 "%s"
1333 "}\n",
1334 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1335 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1336 remote_repo_path, branches ? "\tbranch { " : "",
1337 branches ? branches : "", branches ? "}\n" : "",
1338 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1339 mirror_references ? "\tmirror_references yes\n" : "",
1340 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1345 if (n != strlen(gotconfig)) {
1346 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1347 goto done;
1350 done:
1351 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1352 err = got_error_from_errno2("fclose", gotconfig_path);
1353 free(gotconfig_path);
1354 free(branches);
1355 return err;
1358 static const struct got_error *
1359 create_gitconfig(const char *git_url, const char *default_branch,
1360 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1361 struct got_pathlist_head *wanted_refs, int mirror_references,
1362 struct got_repository *repo)
1364 const struct got_error *err = NULL;
1365 char *gitconfig_path = NULL;
1366 char *gitconfig = NULL;
1367 FILE *gitconfig_file = NULL;
1368 char *branches = NULL, *refs = NULL;
1369 const char *branchname;
1370 ssize_t n;
1372 /* Create a config file Git can understand. */
1373 gitconfig_path = got_repo_get_path_gitconfig(repo);
1374 if (gitconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gitconfig");
1376 goto done;
1378 gitconfig_file = fopen(gitconfig_path, "ae");
1379 if (gitconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gitconfig_path);
1381 goto done;
1383 if (fetch_all_branches) {
1384 if (mirror_references) {
1385 if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1387 err = got_error_from_errno("asprintf");
1388 goto done;
1390 } else if (asprintf(&branches,
1391 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1392 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 } else if (!TAILQ_EMPTY(wanted_branches)) {
1397 struct got_pathlist_entry *pe;
1398 TAILQ_FOREACH(pe, wanted_branches, entry) {
1399 char *s;
1400 branchname = pe->path;
1401 if (strncmp(branchname, "refs/heads/", 11) == 0)
1402 branchname += 11;
1403 if (mirror_references) {
1404 if (asprintf(&s,
1405 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1406 branches ? branches : "",
1407 branchname, branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 } else if (asprintf(&s,
1412 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1413 branches ? branches : "",
1414 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1415 branchname) == -1) {
1416 err = got_error_from_errno("asprintf");
1417 goto done;
1419 free(branches);
1420 branches = s;
1422 } else {
1424 * If the server specified a default branch, use just that one.
1425 * Otherwise fall back to fetching all branches on next fetch.
1427 if (default_branch) {
1428 branchname = default_branch;
1429 if (strncmp(branchname, "refs/heads/", 11) == 0)
1430 branchname += 11;
1431 } else
1432 branchname = "*"; /* fall back to all branches */
1433 if (mirror_references) {
1434 if (asprintf(&branches,
1435 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1436 branchname, branchname) == -1) {
1437 err = got_error_from_errno("asprintf");
1438 goto done;
1440 } else if (asprintf(&branches,
1441 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1442 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1443 branchname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1448 if (!TAILQ_EMPTY(wanted_refs)) {
1449 struct got_pathlist_entry *pe;
1450 TAILQ_FOREACH(pe, wanted_refs, entry) {
1451 char *s;
1452 const char *refname = pe->path;
1453 if (strncmp(refname, "refs/", 5) == 0)
1454 refname += 5;
1455 if (mirror_references) {
1456 if (asprintf(&s,
1457 "%s\tfetch = refs/%s:refs/%s\n",
1458 refs ? refs : "", refname, refname) == -1) {
1459 err = got_error_from_errno("asprintf");
1460 goto done;
1462 } else if (asprintf(&s,
1463 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1464 refs ? refs : "",
1465 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1466 refname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 free(refs);
1471 refs = s;
1475 if (asprintf(&gitconfig,
1476 "[remote \"%s\"]\n"
1477 "\turl = %s\n"
1478 "%s"
1479 "%s"
1480 "\tfetch = refs/tags/*:refs/tags/*\n",
1481 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1482 refs ? refs : "") == -1) {
1483 err = got_error_from_errno("asprintf");
1484 goto done;
1486 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1487 if (n != strlen(gitconfig)) {
1488 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1489 goto done;
1491 done:
1492 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1493 err = got_error_from_errno2("fclose", gitconfig_path);
1494 free(gitconfig_path);
1495 free(branches);
1496 return err;
1499 static const struct got_error *
1500 create_config_files(const char *proto, const char *host, const char *port,
1501 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1502 int mirror_references, struct got_pathlist_head *symrefs,
1503 struct got_pathlist_head *wanted_branches,
1504 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1506 const struct got_error *err = NULL;
1507 const char *default_branch = NULL;
1508 struct got_pathlist_entry *pe;
1511 * If we asked for a set of wanted branches then use the first
1512 * one of those.
1514 if (!TAILQ_EMPTY(wanted_branches)) {
1515 pe = TAILQ_FIRST(wanted_branches);
1516 default_branch = pe->path;
1517 } else {
1518 /* First HEAD ref listed by server is the default branch. */
1519 TAILQ_FOREACH(pe, symrefs, entry) {
1520 const char *refname = pe->path;
1521 const char *target = pe->data;
1523 if (strcmp(refname, GOT_REF_HEAD) != 0)
1524 continue;
1526 default_branch = target;
1527 break;
1531 /* Create got.conf(5). */
1532 err = create_gotconfig(proto, host, port, remote_repo_path,
1533 default_branch, fetch_all_branches, wanted_branches,
1534 wanted_refs, mirror_references, repo);
1535 if (err)
1536 return err;
1538 /* Create a config file Git can understand. */
1539 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1540 wanted_branches, wanted_refs, mirror_references, repo);
1543 static const struct got_error *
1544 cmd_clone(int argc, char *argv[])
1546 const struct got_error *error = NULL;
1547 const char *uri, *dirname;
1548 char *proto, *host, *port, *repo_name, *server_path;
1549 char *default_destdir = NULL, *id_str = NULL;
1550 const char *repo_path;
1551 struct got_repository *repo = NULL;
1552 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1553 struct got_pathlist_entry *pe;
1554 struct got_object_id *pack_hash = NULL;
1555 int ch, fetchfd = -1, fetchstatus;
1556 pid_t fetchpid = -1;
1557 struct got_fetch_progress_arg fpa;
1558 char *git_url = NULL;
1559 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1560 int bflag = 0, list_refs_only = 0;
1561 int *pack_fds = NULL;
1563 TAILQ_INIT(&refs);
1564 TAILQ_INIT(&symrefs);
1565 TAILQ_INIT(&wanted_branches);
1566 TAILQ_INIT(&wanted_refs);
1568 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1569 switch (ch) {
1570 case 'a':
1571 fetch_all_branches = 1;
1572 break;
1573 case 'b':
1574 error = got_pathlist_append(&wanted_branches,
1575 optarg, NULL);
1576 if (error)
1577 return error;
1578 bflag = 1;
1579 break;
1580 case 'l':
1581 list_refs_only = 1;
1582 break;
1583 case 'm':
1584 mirror_references = 1;
1585 break;
1586 case 'q':
1587 verbosity = -1;
1588 break;
1589 case 'R':
1590 error = got_pathlist_append(&wanted_refs,
1591 optarg, NULL);
1592 if (error)
1593 return error;
1594 break;
1595 case 'v':
1596 if (verbosity < 0)
1597 verbosity = 0;
1598 else if (verbosity < 3)
1599 verbosity++;
1600 break;
1601 default:
1602 usage_clone();
1603 break;
1606 argc -= optind;
1607 argv += optind;
1609 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1610 option_conflict('a', 'b');
1611 if (list_refs_only) {
1612 if (!TAILQ_EMPTY(&wanted_branches))
1613 option_conflict('l', 'b');
1614 if (fetch_all_branches)
1615 option_conflict('l', 'a');
1616 if (mirror_references)
1617 option_conflict('l', 'm');
1618 if (!TAILQ_EMPTY(&wanted_refs))
1619 option_conflict('l', 'R');
1622 uri = argv[0];
1624 if (argc == 1)
1625 dirname = NULL;
1626 else if (argc == 2)
1627 dirname = argv[1];
1628 else
1629 usage_clone();
1631 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1632 &repo_name, uri);
1633 if (error)
1634 goto done;
1636 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1637 host, port ? ":" : "", port ? port : "",
1638 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1639 error = got_error_from_errno("asprintf");
1640 goto done;
1643 if (strcmp(proto, "git") == 0) {
1644 #ifndef PROFILE
1645 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1646 "sendfd dns inet unveil", NULL) == -1)
1647 err(1, "pledge");
1648 #endif
1649 } else if (strcmp(proto, "git+ssh") == 0 ||
1650 strcmp(proto, "ssh") == 0) {
1651 #ifndef PROFILE
1652 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1653 "sendfd unveil", NULL) == -1)
1654 err(1, "pledge");
1655 #endif
1656 } else if (strcmp(proto, "http") == 0 ||
1657 strcmp(proto, "git+http") == 0) {
1658 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1659 goto done;
1660 } else {
1661 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1662 goto done;
1664 if (dirname == NULL) {
1665 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1666 error = got_error_from_errno("asprintf");
1667 goto done;
1669 repo_path = default_destdir;
1670 } else
1671 repo_path = dirname;
1673 if (!list_refs_only) {
1674 error = got_path_mkdir(repo_path);
1675 if (error &&
1676 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1677 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1678 goto done;
1679 if (!got_path_dir_is_empty(repo_path)) {
1680 error = got_error_path(repo_path,
1681 GOT_ERR_DIR_NOT_EMPTY);
1682 goto done;
1686 error = got_dial_apply_unveil(proto);
1687 if (error)
1688 goto done;
1690 error = apply_unveil(repo_path, 0, NULL);
1691 if (error)
1692 goto done;
1694 if (verbosity >= 0)
1695 printf("Connecting to %s\n", git_url);
1697 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1698 server_path, verbosity);
1699 if (error)
1700 goto done;
1702 if (!list_refs_only) {
1703 error = got_repo_init(repo_path, NULL);
1704 if (error)
1705 goto done;
1706 error = got_repo_pack_fds_open(&pack_fds);
1707 if (error != NULL)
1708 goto done;
1709 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1710 if (error)
1711 goto done;
1714 fpa.last_scaled_size[0] = '\0';
1715 fpa.last_p_indexed = -1;
1716 fpa.last_p_resolved = -1;
1717 fpa.verbosity = verbosity;
1718 fpa.create_configs = 1;
1719 fpa.configs_created = 0;
1720 fpa.repo = repo;
1721 fpa.config_info.symrefs = &symrefs;
1722 fpa.config_info.wanted_branches = &wanted_branches;
1723 fpa.config_info.wanted_refs = &wanted_refs;
1724 fpa.config_info.proto = proto;
1725 fpa.config_info.host = host;
1726 fpa.config_info.port = port;
1727 fpa.config_info.remote_repo_path = server_path;
1728 fpa.config_info.git_url = git_url;
1729 fpa.config_info.fetch_all_branches = fetch_all_branches;
1730 fpa.config_info.mirror_references = mirror_references;
1731 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1732 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1733 fetch_all_branches, &wanted_branches, &wanted_refs,
1734 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1735 fetch_progress, &fpa);
1736 if (error)
1737 goto done;
1739 if (list_refs_only) {
1740 error = list_remote_refs(&symrefs, &refs);
1741 goto done;
1744 if (pack_hash == NULL) {
1745 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1746 "server sent an empty pack file");
1747 goto done;
1749 error = got_object_id_str(&id_str, pack_hash);
1750 if (error)
1751 goto done;
1752 if (verbosity >= 0)
1753 printf("\nFetched %s.pack\n", id_str);
1754 free(id_str);
1756 /* Set up references provided with the pack file. */
1757 TAILQ_FOREACH(pe, &refs, entry) {
1758 const char *refname = pe->path;
1759 struct got_object_id *id = pe->data;
1760 char *remote_refname;
1762 if (is_wanted_ref(&wanted_refs, refname) &&
1763 !mirror_references) {
1764 error = create_wanted_ref(refname, id,
1765 GOT_FETCH_DEFAULT_REMOTE_NAME,
1766 verbosity - 1, repo);
1767 if (error)
1768 goto done;
1769 continue;
1772 error = create_ref(refname, id, verbosity - 1, repo);
1773 if (error)
1774 goto done;
1776 if (mirror_references)
1777 continue;
1779 if (strncmp("refs/heads/", refname, 11) != 0)
1780 continue;
1782 if (asprintf(&remote_refname,
1783 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1784 refname + 11) == -1) {
1785 error = got_error_from_errno("asprintf");
1786 goto done;
1788 error = create_ref(remote_refname, id, verbosity - 1, repo);
1789 free(remote_refname);
1790 if (error)
1791 goto done;
1794 /* Set the HEAD reference if the server provided one. */
1795 TAILQ_FOREACH(pe, &symrefs, entry) {
1796 struct got_reference *target_ref;
1797 const char *refname = pe->path;
1798 const char *target = pe->data;
1799 char *remote_refname = NULL, *remote_target = NULL;
1801 if (strcmp(refname, GOT_REF_HEAD) != 0)
1802 continue;
1804 error = got_ref_open(&target_ref, repo, target, 0);
1805 if (error) {
1806 if (error->code == GOT_ERR_NOT_REF) {
1807 error = NULL;
1808 continue;
1810 goto done;
1813 error = create_symref(refname, target_ref, verbosity, repo);
1814 got_ref_close(target_ref);
1815 if (error)
1816 goto done;
1818 if (mirror_references)
1819 continue;
1821 if (strncmp("refs/heads/", target, 11) != 0)
1822 continue;
1824 if (asprintf(&remote_refname,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 refname) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 goto done;
1830 if (asprintf(&remote_target,
1831 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1832 target + 11) == -1) {
1833 error = got_error_from_errno("asprintf");
1834 free(remote_refname);
1835 goto done;
1837 error = got_ref_open(&target_ref, repo, remote_target, 0);
1838 if (error) {
1839 free(remote_refname);
1840 free(remote_target);
1841 if (error->code == GOT_ERR_NOT_REF) {
1842 error = NULL;
1843 continue;
1845 goto done;
1847 error = create_symref(remote_refname, target_ref,
1848 verbosity - 1, repo);
1849 free(remote_refname);
1850 free(remote_target);
1851 got_ref_close(target_ref);
1852 if (error)
1853 goto done;
1855 if (pe == NULL) {
1857 * We failed to set the HEAD reference. If we asked for
1858 * a set of wanted branches use the first of one of those
1859 * which could be fetched instead.
1861 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1862 const char *target = pe->path;
1863 struct got_reference *target_ref;
1865 error = got_ref_open(&target_ref, repo, target, 0);
1866 if (error) {
1867 if (error->code == GOT_ERR_NOT_REF) {
1868 error = NULL;
1869 continue;
1871 goto done;
1874 error = create_symref(GOT_REF_HEAD, target_ref,
1875 verbosity, repo);
1876 got_ref_close(target_ref);
1877 if (error)
1878 goto done;
1879 break;
1882 if (!fpa.configs_created && pe != NULL) {
1883 error = create_config_files(fpa.config_info.proto,
1884 fpa.config_info.host, fpa.config_info.port,
1885 fpa.config_info.remote_repo_path,
1886 fpa.config_info.git_url,
1887 fpa.config_info.fetch_all_branches,
1888 fpa.config_info.mirror_references,
1889 fpa.config_info.symrefs,
1890 fpa.config_info.wanted_branches,
1891 fpa.config_info.wanted_refs, fpa.repo);
1892 if (error)
1893 goto done;
1897 if (verbosity >= 0)
1898 printf("Created %s repository '%s'\n",
1899 mirror_references ? "mirrored" : "cloned", repo_path);
1900 done:
1901 if (pack_fds) {
1902 const struct got_error *pack_err =
1903 got_repo_pack_fds_close(pack_fds);
1904 if (error == NULL)
1905 error = pack_err;
1907 if (fetchpid > 0) {
1908 if (kill(fetchpid, SIGTERM) == -1)
1909 error = got_error_from_errno("kill");
1910 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1911 error = got_error_from_errno("waitpid");
1913 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1914 error = got_error_from_errno("close");
1915 if (repo) {
1916 const struct got_error *close_err = got_repo_close(repo);
1917 if (error == NULL)
1918 error = close_err;
1920 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1922 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1923 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1924 free(pack_hash);
1925 free(proto);
1926 free(host);
1927 free(port);
1928 free(server_path);
1929 free(repo_name);
1930 free(default_destdir);
1931 free(git_url);
1932 return error;
1935 static const struct got_error *
1936 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1937 int replace_tags, int verbosity, struct got_repository *repo)
1939 const struct got_error *err = NULL;
1940 char *new_id_str = NULL;
1941 struct got_object_id *old_id = NULL;
1943 err = got_object_id_str(&new_id_str, new_id);
1944 if (err)
1945 goto done;
1947 if (!replace_tags &&
1948 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1949 err = got_ref_resolve(&old_id, repo, ref);
1950 if (err)
1951 goto done;
1952 if (got_object_id_cmp(old_id, new_id) == 0)
1953 goto done;
1954 if (verbosity >= 0) {
1955 printf("Rejecting update of existing tag %s: %s\n",
1956 got_ref_get_name(ref), new_id_str);
1958 goto done;
1961 if (got_ref_is_symbolic(ref)) {
1962 if (verbosity >= 0) {
1963 printf("Replacing reference %s: %s\n",
1964 got_ref_get_name(ref),
1965 got_ref_get_symref_target(ref));
1967 err = got_ref_change_symref_to_ref(ref, new_id);
1968 if (err)
1969 goto done;
1970 err = got_ref_write(ref, repo);
1971 if (err)
1972 goto done;
1973 } else {
1974 err = got_ref_resolve(&old_id, repo, ref);
1975 if (err)
1976 goto done;
1977 if (got_object_id_cmp(old_id, new_id) == 0)
1978 goto done;
1980 err = got_ref_change_ref(ref, new_id);
1981 if (err)
1982 goto done;
1983 err = got_ref_write(ref, repo);
1984 if (err)
1985 goto done;
1988 if (verbosity >= 0)
1989 printf("Updated %s: %s\n", got_ref_get_name(ref),
1990 new_id_str);
1991 done:
1992 free(old_id);
1993 free(new_id_str);
1994 return err;
1997 static const struct got_error *
1998 update_symref(const char *refname, struct got_reference *target_ref,
1999 int verbosity, struct got_repository *repo)
2001 const struct got_error *err = NULL, *unlock_err;
2002 struct got_reference *symref;
2003 int symref_is_locked = 0;
2005 err = got_ref_open(&symref, repo, refname, 1);
2006 if (err) {
2007 if (err->code != GOT_ERR_NOT_REF)
2008 return err;
2009 err = got_ref_alloc_symref(&symref, refname, target_ref);
2010 if (err)
2011 goto done;
2013 err = got_ref_write(symref, repo);
2014 if (err)
2015 goto done;
2017 if (verbosity >= 0)
2018 printf("Created reference %s: %s\n",
2019 got_ref_get_name(symref),
2020 got_ref_get_symref_target(symref));
2021 } else {
2022 symref_is_locked = 1;
2024 if (strcmp(got_ref_get_symref_target(symref),
2025 got_ref_get_name(target_ref)) == 0)
2026 goto done;
2028 err = got_ref_change_symref(symref,
2029 got_ref_get_name(target_ref));
2030 if (err)
2031 goto done;
2033 err = got_ref_write(symref, repo);
2034 if (err)
2035 goto done;
2037 if (verbosity >= 0)
2038 printf("Updated %s: %s\n", got_ref_get_name(symref),
2039 got_ref_get_symref_target(symref));
2042 done:
2043 if (symref_is_locked) {
2044 unlock_err = got_ref_unlock(symref);
2045 if (unlock_err && err == NULL)
2046 err = unlock_err;
2048 got_ref_close(symref);
2049 return err;
2052 __dead static void
2053 usage_fetch(void)
2055 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2056 "[-R reference] [-r repository-path] [remote-repository]\n",
2057 getprogname());
2058 exit(1);
2061 static const struct got_error *
2062 delete_missing_ref(struct got_reference *ref,
2063 int verbosity, struct got_repository *repo)
2065 const struct got_error *err = NULL;
2066 struct got_object_id *id = NULL;
2067 char *id_str = NULL;
2069 if (got_ref_is_symbolic(ref)) {
2070 err = got_ref_delete(ref, repo);
2071 if (err)
2072 return err;
2073 if (verbosity >= 0) {
2074 printf("Deleted %s: %s\n",
2075 got_ref_get_name(ref),
2076 got_ref_get_symref_target(ref));
2078 } else {
2079 err = got_ref_resolve(&id, repo, ref);
2080 if (err)
2081 return err;
2082 err = got_object_id_str(&id_str, id);
2083 if (err)
2084 goto done;
2086 err = got_ref_delete(ref, repo);
2087 if (err)
2088 goto done;
2089 if (verbosity >= 0) {
2090 printf("Deleted %s: %s\n",
2091 got_ref_get_name(ref), id_str);
2094 done:
2095 free(id);
2096 free(id_str);
2097 return err;
2100 static const struct got_error *
2101 delete_missing_refs(struct got_pathlist_head *their_refs,
2102 struct got_pathlist_head *their_symrefs,
2103 const struct got_remote_repo *remote,
2104 int verbosity, struct got_repository *repo)
2106 const struct got_error *err = NULL, *unlock_err;
2107 struct got_reflist_head my_refs;
2108 struct got_reflist_entry *re;
2109 struct got_pathlist_entry *pe;
2110 char *remote_namespace = NULL;
2111 char *local_refname = NULL;
2113 TAILQ_INIT(&my_refs);
2115 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2116 == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2120 if (err)
2121 goto done;
2123 TAILQ_FOREACH(re, &my_refs, entry) {
2124 const char *refname = got_ref_get_name(re->ref);
2125 const char *their_refname;
2127 if (remote->mirror_references) {
2128 their_refname = refname;
2129 } else {
2130 if (strncmp(refname, remote_namespace,
2131 strlen(remote_namespace)) == 0) {
2132 if (strcmp(refname + strlen(remote_namespace),
2133 GOT_REF_HEAD) == 0)
2134 continue;
2135 if (asprintf(&local_refname, "refs/heads/%s",
2136 refname + strlen(remote_namespace)) == -1) {
2137 err = got_error_from_errno("asprintf");
2138 goto done;
2140 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2141 continue;
2143 their_refname = local_refname;
2146 TAILQ_FOREACH(pe, their_refs, entry) {
2147 if (strcmp(their_refname, pe->path) == 0)
2148 break;
2150 if (pe != NULL)
2151 continue;
2153 TAILQ_FOREACH(pe, their_symrefs, entry) {
2154 if (strcmp(their_refname, pe->path) == 0)
2155 break;
2157 if (pe != NULL)
2158 continue;
2160 err = delete_missing_ref(re->ref, verbosity, repo);
2161 if (err)
2162 break;
2164 if (local_refname) {
2165 struct got_reference *ref;
2166 err = got_ref_open(&ref, repo, local_refname, 1);
2167 if (err) {
2168 if (err->code != GOT_ERR_NOT_REF)
2169 break;
2170 free(local_refname);
2171 local_refname = NULL;
2172 continue;
2174 err = delete_missing_ref(ref, verbosity, repo);
2175 if (err)
2176 break;
2177 unlock_err = got_ref_unlock(ref);
2178 got_ref_close(ref);
2179 if (unlock_err && err == NULL) {
2180 err = unlock_err;
2181 break;
2184 free(local_refname);
2185 local_refname = NULL;
2188 done:
2189 got_ref_list_free(&my_refs);
2190 free(remote_namespace);
2191 free(local_refname);
2192 return err;
2195 static const struct got_error *
2196 update_wanted_ref(const char *refname, struct got_object_id *id,
2197 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2199 const struct got_error *err, *unlock_err;
2200 char *remote_refname;
2201 struct got_reference *ref;
2203 if (strncmp("refs/", refname, 5) == 0)
2204 refname += 5;
2206 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2207 remote_repo_name, refname) == -1)
2208 return got_error_from_errno("asprintf");
2210 err = got_ref_open(&ref, repo, remote_refname, 1);
2211 if (err) {
2212 if (err->code != GOT_ERR_NOT_REF)
2213 goto done;
2214 err = create_ref(remote_refname, id, verbosity, repo);
2215 } else {
2216 err = update_ref(ref, id, 0, verbosity, repo);
2217 unlock_err = got_ref_unlock(ref);
2218 if (unlock_err && err == NULL)
2219 err = unlock_err;
2220 got_ref_close(ref);
2222 done:
2223 free(remote_refname);
2224 return err;
2227 static const struct got_error *
2228 delete_ref(struct got_repository *repo, struct got_reference *ref)
2230 const struct got_error *err = NULL;
2231 struct got_object_id *id = NULL;
2232 char *id_str = NULL;
2233 const char *target;
2235 if (got_ref_is_symbolic(ref)) {
2236 target = got_ref_get_symref_target(ref);
2237 } else {
2238 err = got_ref_resolve(&id, repo, ref);
2239 if (err)
2240 goto done;
2241 err = got_object_id_str(&id_str, id);
2242 if (err)
2243 goto done;
2244 target = id_str;
2247 err = got_ref_delete(ref, repo);
2248 if (err)
2249 goto done;
2251 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2252 done:
2253 free(id);
2254 free(id_str);
2255 return err;
2258 static const struct got_error *
2259 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2261 const struct got_error *err = NULL;
2262 struct got_reflist_head refs;
2263 struct got_reflist_entry *re;
2264 char *prefix;
2266 TAILQ_INIT(&refs);
2268 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2269 err = got_error_from_errno("asprintf");
2270 goto done;
2272 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2273 if (err)
2274 goto done;
2276 TAILQ_FOREACH(re, &refs, entry)
2277 delete_ref(repo, re->ref);
2278 done:
2279 got_ref_list_free(&refs);
2280 return err;
2283 static const struct got_error *
2284 cmd_fetch(int argc, char *argv[])
2286 const struct got_error *error = NULL, *unlock_err;
2287 char *cwd = NULL, *repo_path = NULL;
2288 const char *remote_name;
2289 char *proto = NULL, *host = NULL, *port = NULL;
2290 char *repo_name = NULL, *server_path = NULL;
2291 const struct got_remote_repo *remotes, *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 struct got_pathlist_entry *pe;
2299 struct got_reflist_head remote_refs;
2300 struct got_reflist_entry *re;
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, have_bflag = 0;
2308 const char *remote_head = NULL, *worktree_branch = NULL;
2310 TAILQ_INIT(&refs);
2311 TAILQ_INIT(&symrefs);
2312 TAILQ_INIT(&remote_refs);
2313 TAILQ_INIT(&wanted_branches);
2314 TAILQ_INIT(&wanted_refs);
2316 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2317 switch (ch) {
2318 case 'a':
2319 fetch_all_branches = 1;
2320 break;
2321 case 'b':
2322 error = got_pathlist_append(&wanted_branches,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 have_bflag = 1;
2327 break;
2328 case 'd':
2329 delete_refs = 1;
2330 break;
2331 case 'l':
2332 list_refs_only = 1;
2333 break;
2334 case 'q':
2335 verbosity = -1;
2336 break;
2337 case 'R':
2338 error = got_pathlist_append(&wanted_refs,
2339 optarg, NULL);
2340 if (error)
2341 return error;
2342 break;
2343 case 'r':
2344 repo_path = realpath(optarg, NULL);
2345 if (repo_path == NULL)
2346 return got_error_from_errno2("realpath",
2347 optarg);
2348 got_path_strip_trailing_slashes(repo_path);
2349 break;
2350 case 't':
2351 replace_tags = 1;
2352 break;
2353 case 'v':
2354 if (verbosity < 0)
2355 verbosity = 0;
2356 else if (verbosity < 3)
2357 verbosity++;
2358 break;
2359 case 'X':
2360 delete_remote = 1;
2361 break;
2362 default:
2363 usage_fetch();
2364 break;
2367 argc -= optind;
2368 argv += optind;
2370 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('a', 'b');
2372 if (list_refs_only) {
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('l', 'b');
2375 if (fetch_all_branches)
2376 option_conflict('l', 'a');
2377 if (delete_refs)
2378 option_conflict('l', 'd');
2379 if (delete_remote)
2380 option_conflict('l', 'X');
2382 if (delete_remote) {
2383 if (fetch_all_branches)
2384 option_conflict('X', 'a');
2385 if (!TAILQ_EMPTY(&wanted_branches))
2386 option_conflict('X', 'b');
2387 if (delete_refs)
2388 option_conflict('X', 'd');
2389 if (replace_tags)
2390 option_conflict('X', 't');
2391 if (!TAILQ_EMPTY(&wanted_refs))
2392 option_conflict('X', 'R');
2395 if (argc == 0) {
2396 if (delete_remote)
2397 errx(1, "-X option requires a remote name");
2398 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2399 } else if (argc == 1)
2400 remote_name = argv[0];
2401 else
2402 usage_fetch();
2404 cwd = getcwd(NULL, 0);
2405 if (cwd == NULL) {
2406 error = got_error_from_errno("getcwd");
2407 goto done;
2410 error = got_repo_pack_fds_open(&pack_fds);
2411 if (error != NULL)
2412 goto done;
2414 if (repo_path == NULL) {
2415 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2417 goto done;
2418 else
2419 error = NULL;
2420 if (worktree) {
2421 repo_path =
2422 strdup(got_worktree_get_repo_path(worktree));
2423 if (repo_path == NULL)
2424 error = got_error_from_errno("strdup");
2425 if (error)
2426 goto done;
2427 } else {
2428 repo_path = strdup(cwd);
2429 if (repo_path == NULL) {
2430 error = got_error_from_errno("strdup");
2431 goto done;
2436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2437 if (error)
2438 goto done;
2440 if (delete_remote) {
2441 error = delete_refs_for_remote(repo, remote_name);
2442 goto done; /* nothing else to do */
2445 if (worktree) {
2446 worktree_conf = got_worktree_get_gotconfig(worktree);
2447 if (worktree_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 worktree_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2458 if (remote == NULL) {
2459 repo_conf = got_repo_get_gotconfig(repo);
2460 if (repo_conf) {
2461 got_gotconfig_get_remotes(&nremotes, &remotes,
2462 repo_conf);
2463 for (i = 0; i < nremotes; i++) {
2464 if (strcmp(remotes[i].name, remote_name) == 0) {
2465 remote = &remotes[i];
2466 break;
2471 if (remote == NULL) {
2472 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2473 for (i = 0; i < nremotes; i++) {
2474 if (strcmp(remotes[i].name, remote_name) == 0) {
2475 remote = &remotes[i];
2476 break;
2480 if (remote == NULL) {
2481 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2482 goto done;
2485 if (TAILQ_EMPTY(&wanted_branches)) {
2486 if (!fetch_all_branches)
2487 fetch_all_branches = remote->fetch_all_branches;
2488 for (i = 0; i < remote->nfetch_branches; i++) {
2489 error = got_pathlist_append(&wanted_branches,
2490 remote->fetch_branches[i], NULL);
2491 if (error)
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_refs)) {
2496 for (i = 0; i < remote->nfetch_refs; i++) {
2497 error = got_pathlist_append(&wanted_refs,
2498 remote->fetch_refs[i], NULL);
2499 if (error)
2500 goto done;
2504 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2505 &repo_name, remote->fetch_url);
2506 if (error)
2507 goto done;
2509 if (strcmp(proto, "git") == 0) {
2510 #ifndef PROFILE
2511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2512 "sendfd dns inet unveil", NULL) == -1)
2513 err(1, "pledge");
2514 #endif
2515 } else if (strcmp(proto, "git+ssh") == 0 ||
2516 strcmp(proto, "ssh") == 0) {
2517 #ifndef PROFILE
2518 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2519 "sendfd unveil", NULL) == -1)
2520 err(1, "pledge");
2521 #endif
2522 } else if (strcmp(proto, "http") == 0 ||
2523 strcmp(proto, "git+http") == 0) {
2524 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2525 goto done;
2526 } else {
2527 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2528 goto done;
2531 error = got_dial_apply_unveil(proto);
2532 if (error)
2533 goto done;
2535 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2536 if (error)
2537 goto done;
2539 if (verbosity >= 0) {
2540 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2541 remote->name, proto, host,
2542 port ? ":" : "", port ? port : "",
2543 *server_path == '/' ? "" : "/", server_path);
2546 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2547 server_path, verbosity);
2548 if (error)
2549 goto done;
2551 if (!have_bflag) {
2553 * If set, get this remote's HEAD ref target so
2554 * if it has changed on the server we can fetch it.
2556 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2557 got_ref_cmp_by_name, repo);
2558 if (error)
2559 goto done;
2561 TAILQ_FOREACH(re, &remote_refs, entry) {
2562 const char *remote_refname, *remote_target;
2563 size_t remote_name_len;
2565 if (!got_ref_is_symbolic(re->ref))
2566 continue;
2568 remote_name_len = strlen(remote->name);
2569 remote_refname = got_ref_get_name(re->ref);
2571 /* we only want refs/remotes/$remote->name/HEAD */
2572 if (strncmp(remote_refname + 13, remote->name,
2573 remote_name_len) != 0)
2574 continue;
2576 if (strcmp(remote_refname + remote_name_len + 14,
2577 GOT_REF_HEAD) != 0)
2578 continue;
2581 * Take the name itself because we already
2582 * only match with refs/heads/ in fetch_pack().
2584 remote_target = got_ref_get_symref_target(re->ref);
2585 remote_head = remote_target + remote_name_len + 14;
2586 break;
2589 if (worktree) {
2590 const char *refname;
2592 refname = got_worktree_get_head_ref_name(worktree);
2593 if (strncmp(refname, "refs/heads/", 11) == 0)
2594 worktree_branch = refname;
2598 fpa.last_scaled_size[0] = '\0';
2599 fpa.last_p_indexed = -1;
2600 fpa.last_p_resolved = -1;
2601 fpa.verbosity = verbosity;
2602 fpa.repo = repo;
2603 fpa.create_configs = 0;
2604 fpa.configs_created = 0;
2605 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2607 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2608 remote->mirror_references, fetch_all_branches, &wanted_branches,
2609 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2610 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2611 if (error)
2612 goto done;
2614 if (list_refs_only) {
2615 error = list_remote_refs(&symrefs, &refs);
2616 goto done;
2619 if (pack_hash == NULL) {
2620 if (verbosity >= 0)
2621 printf("Already up-to-date\n");
2622 } else if (verbosity >= 0) {
2623 error = got_object_id_str(&id_str, pack_hash);
2624 if (error)
2625 goto done;
2626 printf("\nFetched %s.pack\n", id_str);
2627 free(id_str);
2628 id_str = NULL;
2631 /* Update references provided with the pack file. */
2632 TAILQ_FOREACH(pe, &refs, entry) {
2633 const char *refname = pe->path;
2634 struct got_object_id *id = pe->data;
2635 struct got_reference *ref;
2636 char *remote_refname;
2638 if (is_wanted_ref(&wanted_refs, refname) &&
2639 !remote->mirror_references) {
2640 error = update_wanted_ref(refname, id,
2641 remote->name, verbosity, repo);
2642 if (error)
2643 goto done;
2644 continue;
2647 if (remote->mirror_references ||
2648 strncmp("refs/tags/", refname, 10) == 0) {
2649 error = got_ref_open(&ref, repo, refname, 1);
2650 if (error) {
2651 if (error->code != GOT_ERR_NOT_REF)
2652 goto done;
2653 error = create_ref(refname, id, verbosity,
2654 repo);
2655 if (error)
2656 goto done;
2657 } else {
2658 error = update_ref(ref, id, replace_tags,
2659 verbosity, repo);
2660 unlock_err = got_ref_unlock(ref);
2661 if (unlock_err && error == NULL)
2662 error = unlock_err;
2663 got_ref_close(ref);
2664 if (error)
2665 goto done;
2667 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2668 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2669 remote_name, refname + 11) == -1) {
2670 error = got_error_from_errno("asprintf");
2671 goto done;
2674 error = got_ref_open(&ref, repo, remote_refname, 1);
2675 if (error) {
2676 if (error->code != GOT_ERR_NOT_REF)
2677 goto done;
2678 error = create_ref(remote_refname, id,
2679 verbosity, repo);
2680 if (error)
2681 goto done;
2682 } else {
2683 error = update_ref(ref, id, replace_tags,
2684 verbosity, repo);
2685 unlock_err = got_ref_unlock(ref);
2686 if (unlock_err && error == NULL)
2687 error = unlock_err;
2688 got_ref_close(ref);
2689 if (error)
2690 goto done;
2693 /* Also create a local branch if none exists yet. */
2694 error = got_ref_open(&ref, repo, refname, 1);
2695 if (error) {
2696 if (error->code != GOT_ERR_NOT_REF)
2697 goto done;
2698 error = create_ref(refname, id, verbosity,
2699 repo);
2700 if (error)
2701 goto done;
2702 } else {
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2710 if (delete_refs) {
2711 error = delete_missing_refs(&refs, &symrefs, remote,
2712 verbosity, repo);
2713 if (error)
2714 goto done;
2717 if (!remote->mirror_references) {
2718 /* Update remote HEAD reference if the server provided one. */
2719 TAILQ_FOREACH(pe, &symrefs, entry) {
2720 struct got_reference *target_ref;
2721 const char *refname = pe->path;
2722 const char *target = pe->data;
2723 char *remote_refname = NULL, *remote_target = NULL;
2725 if (strcmp(refname, GOT_REF_HEAD) != 0)
2726 continue;
2728 if (strncmp("refs/heads/", target, 11) != 0)
2729 continue;
2731 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2732 remote->name, refname) == -1) {
2733 error = got_error_from_errno("asprintf");
2734 goto done;
2736 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2737 remote->name, target + 11) == -1) {
2738 error = got_error_from_errno("asprintf");
2739 free(remote_refname);
2740 goto done;
2743 error = got_ref_open(&target_ref, repo, remote_target,
2744 0);
2745 if (error) {
2746 free(remote_refname);
2747 free(remote_target);
2748 if (error->code == GOT_ERR_NOT_REF) {
2749 error = NULL;
2750 continue;
2752 goto done;
2754 error = update_symref(remote_refname, target_ref,
2755 verbosity, repo);
2756 free(remote_refname);
2757 free(remote_target);
2758 got_ref_close(target_ref);
2759 if (error)
2760 goto done;
2763 done:
2764 if (fetchpid > 0) {
2765 if (kill(fetchpid, SIGTERM) == -1)
2766 error = got_error_from_errno("kill");
2767 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2768 error = got_error_from_errno("waitpid");
2770 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2771 error = got_error_from_errno("close");
2772 if (repo) {
2773 const struct got_error *close_err = got_repo_close(repo);
2774 if (error == NULL)
2775 error = close_err;
2777 if (worktree)
2778 got_worktree_close(worktree);
2779 if (pack_fds) {
2780 const struct got_error *pack_err =
2781 got_repo_pack_fds_close(pack_fds);
2782 if (error == NULL)
2783 error = pack_err;
2785 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2787 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2788 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2789 got_ref_list_free(&remote_refs);
2790 free(id_str);
2791 free(cwd);
2792 free(repo_path);
2793 free(pack_hash);
2794 free(proto);
2795 free(host);
2796 free(port);
2797 free(server_path);
2798 free(repo_name);
2799 return error;
2803 __dead static void
2804 usage_checkout(void)
2806 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2807 "[-p path-prefix] repository-path [work-tree-path]\n",
2808 getprogname());
2809 exit(1);
2812 static void
2813 show_worktree_base_ref_warning(void)
2815 fprintf(stderr, "%s: warning: could not create a reference "
2816 "to the work tree's base commit; the commit could be "
2817 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2818 "repository writable and running 'got update' will prevent this\n",
2819 getprogname());
2822 struct got_checkout_progress_arg {
2823 const char *worktree_path;
2824 int had_base_commit_ref_error;
2825 int verbosity;
2828 static const struct got_error *
2829 checkout_progress(void *arg, unsigned char status, const char *path)
2831 struct got_checkout_progress_arg *a = arg;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_BASE_REF_ERR) {
2838 a->had_base_commit_ref_error = 1;
2839 return NULL;
2842 while (path[0] == '/')
2843 path++;
2845 if (a->verbosity >= 0)
2846 printf("%c %s/%s\n", status, a->worktree_path, path);
2848 return NULL;
2851 static const struct got_error *
2852 check_cancelled(void *arg)
2854 if (sigint_received || sigpipe_received)
2855 return got_error(GOT_ERR_CANCELLED);
2856 return NULL;
2859 static const struct got_error *
2860 check_linear_ancestry(struct got_object_id *commit_id,
2861 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2862 struct got_repository *repo)
2864 const struct got_error *err = NULL;
2865 struct got_object_id *yca_id;
2867 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2868 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2869 if (err)
2870 return err;
2872 if (yca_id == NULL)
2873 return got_error(GOT_ERR_ANCESTRY);
2876 * Require a straight line of history between the target commit
2877 * and the work tree's base commit.
2879 * Non-linear situations such as this require a rebase:
2881 * (commit) D F (base_commit)
2882 * \ /
2883 * C E
2884 * \ /
2885 * B (yca)
2886 * |
2887 * A
2889 * 'got update' only handles linear cases:
2890 * Update forwards in time: A (base/yca) - B - C - D (commit)
2891 * Update backwards in time: D (base) - C - B - A (commit/yca)
2893 if (allow_forwards_in_time_only) {
2894 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2895 return got_error(GOT_ERR_ANCESTRY);
2896 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2897 got_object_id_cmp(base_commit_id, yca_id) != 0)
2898 return got_error(GOT_ERR_ANCESTRY);
2900 free(yca_id);
2901 return NULL;
2904 static const struct got_error *
2905 check_same_branch(struct got_object_id *commit_id,
2906 struct got_reference *head_ref, struct got_repository *repo)
2908 const struct got_error *err = NULL;
2909 struct got_commit_graph *graph = NULL;
2910 struct got_object_id *head_commit_id = NULL;
2912 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2913 if (err)
2914 goto done;
2916 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2917 goto done;
2919 err = got_commit_graph_open(&graph, "/", 1);
2920 if (err)
2921 goto done;
2923 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2924 check_cancelled, NULL);
2925 if (err)
2926 goto done;
2928 for (;;) {
2929 struct got_object_id id;
2931 err = got_commit_graph_iter_next(&id, graph, repo,
2932 check_cancelled, NULL);
2933 if (err) {
2934 if (err->code == GOT_ERR_ITER_COMPLETED)
2935 err = got_error(GOT_ERR_ANCESTRY);
2936 break;
2939 if (got_object_id_cmp(&id, commit_id) == 0)
2940 break;
2942 done:
2943 if (graph)
2944 got_commit_graph_close(graph);
2945 free(head_commit_id);
2946 return err;
2949 static const struct got_error *
2950 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2952 static char msg[512];
2953 const char *branch_name;
2955 if (got_ref_is_symbolic(ref))
2956 branch_name = got_ref_get_symref_target(ref);
2957 else
2958 branch_name = got_ref_get_name(ref);
2960 if (strncmp("refs/heads/", branch_name, 11) == 0)
2961 branch_name += 11;
2963 snprintf(msg, sizeof(msg),
2964 "target commit is not contained in branch '%s'; "
2965 "the branch to use must be specified with -b; "
2966 "if necessary a new branch can be created for "
2967 "this commit with 'got branch -c %s BRANCH_NAME'",
2968 branch_name, commit_id_str);
2970 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2973 static const struct got_error *
2974 cmd_checkout(int argc, char *argv[])
2976 const struct got_error *error = NULL;
2977 struct got_repository *repo = NULL;
2978 struct got_reference *head_ref = NULL, *ref = NULL;
2979 struct got_worktree *worktree = NULL;
2980 char *repo_path = NULL;
2981 char *worktree_path = NULL;
2982 const char *path_prefix = "";
2983 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2984 char *commit_id_str = NULL, *keyword_idstr = NULL;
2985 struct got_object_id *commit_id = NULL;
2986 char *cwd = NULL;
2987 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2988 struct got_pathlist_head paths;
2989 struct got_checkout_progress_arg cpa;
2990 int *pack_fds = NULL;
2992 TAILQ_INIT(&paths);
2994 #ifndef PROFILE
2995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2996 "unveil", NULL) == -1)
2997 err(1, "pledge");
2998 #endif
3000 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3001 switch (ch) {
3002 case 'b':
3003 branch_name = optarg;
3004 break;
3005 case 'c':
3006 commit_id_str = strdup(optarg);
3007 if (commit_id_str == NULL)
3008 return got_error_from_errno("strdup");
3009 break;
3010 case 'E':
3011 allow_nonempty = 1;
3012 break;
3013 case 'p':
3014 path_prefix = optarg;
3015 break;
3016 case 'q':
3017 verbosity = -1;
3018 break;
3019 default:
3020 usage_checkout();
3021 /* NOTREACHED */
3025 argc -= optind;
3026 argv += optind;
3028 if (argc == 1) {
3029 char *base, *dotgit;
3030 const char *path;
3031 repo_path = realpath(argv[0], NULL);
3032 if (repo_path == NULL)
3033 return got_error_from_errno2("realpath", argv[0]);
3034 cwd = getcwd(NULL, 0);
3035 if (cwd == NULL) {
3036 error = got_error_from_errno("getcwd");
3037 goto done;
3039 if (path_prefix[0])
3040 path = path_prefix;
3041 else
3042 path = repo_path;
3043 error = got_path_basename(&base, path);
3044 if (error)
3045 goto done;
3046 dotgit = strstr(base, ".git");
3047 if (dotgit)
3048 *dotgit = '\0';
3049 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3050 error = got_error_from_errno("asprintf");
3051 free(base);
3052 goto done;
3054 free(base);
3055 } else if (argc == 2) {
3056 repo_path = realpath(argv[0], NULL);
3057 if (repo_path == NULL) {
3058 error = got_error_from_errno2("realpath", argv[0]);
3059 goto done;
3061 worktree_path = realpath(argv[1], NULL);
3062 if (worktree_path == NULL) {
3063 if (errno != ENOENT) {
3064 error = got_error_from_errno2("realpath",
3065 argv[1]);
3066 goto done;
3068 worktree_path = strdup(argv[1]);
3069 if (worktree_path == NULL) {
3070 error = got_error_from_errno("strdup");
3071 goto done;
3074 } else
3075 usage_checkout();
3077 got_path_strip_trailing_slashes(repo_path);
3078 got_path_strip_trailing_slashes(worktree_path);
3080 error = got_repo_pack_fds_open(&pack_fds);
3081 if (error != NULL)
3082 goto done;
3084 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3085 if (error != NULL)
3086 goto done;
3088 /* Pre-create work tree path for unveil(2) */
3089 error = got_path_mkdir(worktree_path);
3090 if (error) {
3091 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3092 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3093 goto done;
3094 if (!allow_nonempty &&
3095 !got_path_dir_is_empty(worktree_path)) {
3096 error = got_error_path(worktree_path,
3097 GOT_ERR_DIR_NOT_EMPTY);
3098 goto done;
3102 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3103 if (error)
3104 goto done;
3106 error = got_ref_open(&head_ref, repo, branch_name, 0);
3107 if (error != NULL)
3108 goto done;
3110 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3111 GOT_WORKTREE_GOT_DIR, repo);
3112 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3113 goto done;
3115 error = got_worktree_open(&worktree, worktree_path,
3116 GOT_WORKTREE_GOT_DIR);
3117 if (error != NULL)
3118 goto done;
3120 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3121 path_prefix);
3122 if (error != NULL)
3123 goto done;
3124 if (!same_path_prefix) {
3125 error = got_error(GOT_ERR_PATH_PREFIX);
3126 goto done;
3129 if (commit_id_str) {
3130 struct got_reflist_head refs;
3131 TAILQ_INIT(&refs);
3132 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3133 NULL);
3134 if (error)
3135 goto done;
3137 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3138 repo, worktree);
3139 if (error != NULL)
3140 goto done;
3141 if (keyword_idstr != NULL) {
3142 free(commit_id_str);
3143 commit_id_str = keyword_idstr;
3146 error = got_repo_match_object_id(&commit_id, NULL,
3147 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3148 got_ref_list_free(&refs);
3149 if (error)
3150 goto done;
3151 error = check_linear_ancestry(commit_id,
3152 got_worktree_get_base_commit_id(worktree), 0, repo);
3153 if (error != NULL) {
3154 if (error->code == GOT_ERR_ANCESTRY) {
3155 error = checkout_ancestry_error(
3156 head_ref, commit_id_str);
3158 goto done;
3160 error = check_same_branch(commit_id, head_ref, repo);
3161 if (error) {
3162 if (error->code == GOT_ERR_ANCESTRY) {
3163 error = checkout_ancestry_error(
3164 head_ref, commit_id_str);
3166 goto done;
3168 error = got_worktree_set_base_commit_id(worktree, repo,
3169 commit_id);
3170 if (error)
3171 goto done;
3172 /* Expand potentially abbreviated commit ID string. */
3173 free(commit_id_str);
3174 error = got_object_id_str(&commit_id_str, commit_id);
3175 if (error)
3176 goto done;
3177 } else {
3178 commit_id = got_object_id_dup(
3179 got_worktree_get_base_commit_id(worktree));
3180 if (commit_id == NULL) {
3181 error = got_error_from_errno("got_object_id_dup");
3182 goto done;
3184 error = got_object_id_str(&commit_id_str, commit_id);
3185 if (error)
3186 goto done;
3189 error = got_pathlist_append(&paths, "", NULL);
3190 if (error)
3191 goto done;
3192 cpa.worktree_path = worktree_path;
3193 cpa.had_base_commit_ref_error = 0;
3194 cpa.verbosity = verbosity;
3195 error = got_worktree_checkout_files(worktree, &paths, repo,
3196 checkout_progress, &cpa, check_cancelled, NULL);
3197 if (error != NULL)
3198 goto done;
3200 if (got_ref_is_symbolic(head_ref)) {
3201 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3202 if (error)
3203 goto done;
3204 refname = got_ref_get_name(ref);
3205 } else
3206 refname = got_ref_get_name(head_ref);
3207 printf("Checked out %s: %s\n", refname, commit_id_str);
3208 printf("Now shut up and hack\n");
3209 if (cpa.had_base_commit_ref_error)
3210 show_worktree_base_ref_warning();
3211 done:
3212 if (pack_fds) {
3213 const struct got_error *pack_err =
3214 got_repo_pack_fds_close(pack_fds);
3215 if (error == NULL)
3216 error = pack_err;
3218 if (head_ref)
3219 got_ref_close(head_ref);
3220 if (ref)
3221 got_ref_close(ref);
3222 if (repo) {
3223 const struct got_error *close_err = got_repo_close(repo);
3224 if (error == NULL)
3225 error = close_err;
3227 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3228 free(commit_id_str);
3229 free(commit_id);
3230 free(repo_path);
3231 free(worktree_path);
3232 free(cwd);
3233 return error;
3236 struct got_update_progress_arg {
3237 int did_something;
3238 int conflicts;
3239 int obstructed;
3240 int not_updated;
3241 int missing;
3242 int not_deleted;
3243 int unversioned;
3244 int verbosity;
3247 static void
3248 print_update_progress_stats(struct got_update_progress_arg *upa)
3250 if (!upa->did_something)
3251 return;
3253 if (upa->conflicts > 0)
3254 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3255 if (upa->obstructed > 0)
3256 printf("File paths obstructed by a non-regular file: %d\n",
3257 upa->obstructed);
3258 if (upa->not_updated > 0)
3259 printf("Files not updated because of existing merge "
3260 "conflicts: %d\n", upa->not_updated);
3264 * The meaning of some status codes differs between merge-style operations and
3265 * update operations. For example, the ! status code means "file was missing"
3266 * if changes were merged into the work tree, and "missing file was restored"
3267 * if the work tree was updated. This function should be used by any operation
3268 * which merges changes into the work tree without updating the work tree.
3270 static void
3271 print_merge_progress_stats(struct got_update_progress_arg *upa)
3273 if (!upa->did_something)
3274 return;
3276 if (upa->conflicts > 0)
3277 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3278 if (upa->obstructed > 0)
3279 printf("File paths obstructed by a non-regular file: %d\n",
3280 upa->obstructed);
3281 if (upa->missing > 0)
3282 printf("Files which had incoming changes but could not be "
3283 "found in the work tree: %d\n", upa->missing);
3284 if (upa->not_deleted > 0)
3285 printf("Files not deleted due to differences in deleted "
3286 "content: %d\n", upa->not_deleted);
3287 if (upa->unversioned > 0)
3288 printf("Files not merged because an unversioned file was "
3289 "found in the work tree: %d\n", upa->unversioned);
3292 __dead static void
3293 usage_update(void)
3295 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3296 "[path ...]\n", getprogname());
3297 exit(1);
3300 static const struct got_error *
3301 update_progress(void *arg, unsigned char status, const char *path)
3303 struct got_update_progress_arg *upa = arg;
3305 if (status == GOT_STATUS_EXISTS ||
3306 status == GOT_STATUS_BASE_REF_ERR)
3307 return NULL;
3309 upa->did_something = 1;
3311 /* Base commit bump happens silently. */
3312 if (status == GOT_STATUS_BUMP_BASE)
3313 return NULL;
3315 if (status == GOT_STATUS_CONFLICT)
3316 upa->conflicts++;
3317 if (status == GOT_STATUS_OBSTRUCTED)
3318 upa->obstructed++;
3319 if (status == GOT_STATUS_CANNOT_UPDATE)
3320 upa->not_updated++;
3321 if (status == GOT_STATUS_MISSING)
3322 upa->missing++;
3323 if (status == GOT_STATUS_CANNOT_DELETE)
3324 upa->not_deleted++;
3325 if (status == GOT_STATUS_UNVERSIONED)
3326 upa->unversioned++;
3328 while (path[0] == '/')
3329 path++;
3330 if (upa->verbosity >= 0)
3331 printf("%c %s\n", status, path);
3333 return NULL;
3336 static const struct got_error *
3337 switch_head_ref(struct got_reference *head_ref,
3338 struct got_object_id *commit_id, struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err = NULL;
3342 char *base_id_str;
3343 int ref_has_moved = 0;
3345 /* Trivial case: switching between two different references. */
3346 if (strcmp(got_ref_get_name(head_ref),
3347 got_worktree_get_head_ref_name(worktree)) != 0) {
3348 printf("Switching work tree from %s to %s\n",
3349 got_worktree_get_head_ref_name(worktree),
3350 got_ref_get_name(head_ref));
3351 return got_worktree_set_head_ref(worktree, head_ref);
3354 err = check_linear_ancestry(commit_id,
3355 got_worktree_get_base_commit_id(worktree), 0, repo);
3356 if (err) {
3357 if (err->code != GOT_ERR_ANCESTRY)
3358 return err;
3359 ref_has_moved = 1;
3361 if (!ref_has_moved)
3362 return NULL;
3364 /* Switching to a rebased branch with the same reference name. */
3365 err = got_object_id_str(&base_id_str,
3366 got_worktree_get_base_commit_id(worktree));
3367 if (err)
3368 return err;
3369 printf("Reference %s now points at a different branch\n",
3370 got_worktree_get_head_ref_name(worktree));
3371 printf("Switching work tree from %s to %s\n", base_id_str,
3372 got_worktree_get_head_ref_name(worktree));
3373 return NULL;
3376 static const struct got_error *
3377 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3379 const struct got_error *err;
3380 int in_progress;
3382 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3383 if (err)
3384 return err;
3385 if (in_progress)
3386 return got_error(GOT_ERR_REBASING);
3388 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3389 if (err)
3390 return err;
3391 if (in_progress)
3392 return got_error(GOT_ERR_HISTEDIT_BUSY);
3394 return NULL;
3397 static const struct got_error *
3398 check_merge_in_progress(struct got_worktree *worktree,
3399 struct got_repository *repo)
3401 const struct got_error *err;
3402 int in_progress;
3404 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3405 if (err)
3406 return err;
3407 if (in_progress)
3408 return got_error(GOT_ERR_MERGE_BUSY);
3410 return NULL;
3413 static const struct got_error *
3414 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3415 char *argv[], struct got_worktree *worktree)
3417 const struct got_error *err = NULL;
3418 char *path;
3419 struct got_pathlist_entry *new;
3420 int i;
3422 if (argc == 0) {
3423 path = strdup("");
3424 if (path == NULL)
3425 return got_error_from_errno("strdup");
3426 return got_pathlist_append(paths, path, NULL);
3429 for (i = 0; i < argc; i++) {
3430 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3431 if (err)
3432 break;
3433 err = got_pathlist_insert(&new, paths, path, NULL);
3434 if (err || new == NULL /* duplicate */) {
3435 free(path);
3436 if (err)
3437 break;
3441 return err;
3444 static const struct got_error *
3445 wrap_not_worktree_error(const struct got_error *orig_err,
3446 const char *cmdname, const char *path)
3448 const struct got_error *err;
3449 struct got_repository *repo;
3450 static char msg[512];
3451 int *pack_fds = NULL;
3453 err = got_repo_pack_fds_open(&pack_fds);
3454 if (err)
3455 return err;
3457 err = got_repo_open(&repo, path, NULL, pack_fds);
3458 if (err)
3459 return orig_err;
3461 snprintf(msg, sizeof(msg),
3462 "'got %s' needs a work tree in addition to a git repository\n"
3463 "Work trees can be checked out from this Git repository with "
3464 "'got checkout'.\n"
3465 "The got(1) manual page contains more information.", cmdname);
3466 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3467 if (repo) {
3468 const struct got_error *close_err = got_repo_close(repo);
3469 if (err == NULL)
3470 err = close_err;
3472 if (pack_fds) {
3473 const struct got_error *pack_err =
3474 got_repo_pack_fds_close(pack_fds);
3475 if (err == NULL)
3476 err = pack_err;
3478 return err;
3481 static const struct got_error *
3482 cmd_update(int argc, char *argv[])
3484 const struct got_error *error = NULL;
3485 struct got_repository *repo = NULL;
3486 struct got_worktree *worktree = NULL;
3487 char *worktree_path = NULL;
3488 struct got_object_id *commit_id = NULL;
3489 char *commit_id_str = NULL;
3490 const char *branch_name = NULL;
3491 struct got_reference *head_ref = NULL;
3492 struct got_pathlist_head paths;
3493 struct got_pathlist_entry *pe;
3494 int ch, verbosity = 0;
3495 struct got_update_progress_arg upa;
3496 int *pack_fds = NULL;
3498 TAILQ_INIT(&paths);
3500 #ifndef PROFILE
3501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3502 "unveil", NULL) == -1)
3503 err(1, "pledge");
3504 #endif
3506 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3507 switch (ch) {
3508 case 'b':
3509 branch_name = optarg;
3510 break;
3511 case 'c':
3512 commit_id_str = strdup(optarg);
3513 if (commit_id_str == NULL)
3514 return got_error_from_errno("strdup");
3515 break;
3516 case 'q':
3517 verbosity = -1;
3518 break;
3519 default:
3520 usage_update();
3521 /* NOTREACHED */
3525 argc -= optind;
3526 argv += optind;
3528 worktree_path = getcwd(NULL, 0);
3529 if (worktree_path == NULL) {
3530 error = got_error_from_errno("getcwd");
3531 goto done;
3534 error = got_repo_pack_fds_open(&pack_fds);
3535 if (error != NULL)
3536 goto done;
3538 error = got_worktree_open(&worktree, worktree_path,
3539 GOT_WORKTREE_GOT_DIR);
3540 if (error) {
3541 if (error->code == GOT_ERR_NOT_WORKTREE)
3542 error = wrap_not_worktree_error(error, "update",
3543 worktree_path);
3544 goto done;
3547 error = check_rebase_or_histedit_in_progress(worktree);
3548 if (error)
3549 goto done;
3551 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3552 NULL, pack_fds);
3553 if (error != NULL)
3554 goto done;
3556 error = apply_unveil(got_repo_get_path(repo), 0,
3557 got_worktree_get_root_path(worktree));
3558 if (error)
3559 goto done;
3561 error = check_merge_in_progress(worktree, repo);
3562 if (error)
3563 goto done;
3565 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3566 if (error)
3567 goto done;
3569 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3570 got_worktree_get_head_ref_name(worktree), 0);
3571 if (error != NULL)
3572 goto done;
3573 if (commit_id_str == NULL) {
3574 error = got_ref_resolve(&commit_id, repo, head_ref);
3575 if (error != NULL)
3576 goto done;
3577 error = got_object_id_str(&commit_id_str, commit_id);
3578 if (error != NULL)
3579 goto done;
3580 } else {
3581 struct got_reflist_head refs;
3582 char *keyword_idstr = NULL;
3584 TAILQ_INIT(&refs);
3586 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3587 NULL);
3588 if (error)
3589 goto done;
3591 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3592 repo, worktree);
3593 if (error != NULL)
3594 goto done;
3595 if (keyword_idstr != NULL) {
3596 free(commit_id_str);
3597 commit_id_str = keyword_idstr;
3600 error = got_repo_match_object_id(&commit_id, NULL,
3601 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3602 got_ref_list_free(&refs);
3603 free(commit_id_str);
3604 commit_id_str = NULL;
3605 if (error)
3606 goto done;
3607 error = got_object_id_str(&commit_id_str, commit_id);
3608 if (error)
3609 goto done;
3612 if (branch_name) {
3613 struct got_object_id *head_commit_id;
3614 TAILQ_FOREACH(pe, &paths, entry) {
3615 if (pe->path_len == 0)
3616 continue;
3617 error = got_error_msg(GOT_ERR_BAD_PATH,
3618 "switching between branches requires that "
3619 "the entire work tree gets updated");
3620 goto done;
3622 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3623 if (error)
3624 goto done;
3625 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3626 repo);
3627 free(head_commit_id);
3628 if (error != NULL)
3629 goto done;
3630 error = check_same_branch(commit_id, head_ref, repo);
3631 if (error)
3632 goto done;
3633 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3634 if (error)
3635 goto done;
3636 } else {
3637 error = check_linear_ancestry(commit_id,
3638 got_worktree_get_base_commit_id(worktree), 0, repo);
3639 if (error != NULL) {
3640 if (error->code == GOT_ERR_ANCESTRY)
3641 error = got_error(GOT_ERR_BRANCH_MOVED);
3642 goto done;
3644 error = check_same_branch(commit_id, head_ref, repo);
3645 if (error)
3646 goto done;
3649 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3650 commit_id) != 0) {
3651 error = got_worktree_set_base_commit_id(worktree, repo,
3652 commit_id);
3653 if (error)
3654 goto done;
3657 memset(&upa, 0, sizeof(upa));
3658 upa.verbosity = verbosity;
3659 error = got_worktree_checkout_files(worktree, &paths, repo,
3660 update_progress, &upa, check_cancelled, NULL);
3661 if (error != NULL)
3662 goto done;
3664 if (upa.did_something) {
3665 printf("Updated to %s: %s\n",
3666 got_worktree_get_head_ref_name(worktree), commit_id_str);
3667 } else
3668 printf("Already up-to-date\n");
3670 print_update_progress_stats(&upa);
3671 done:
3672 if (pack_fds) {
3673 const struct got_error *pack_err =
3674 got_repo_pack_fds_close(pack_fds);
3675 if (error == NULL)
3676 error = pack_err;
3678 if (repo) {
3679 const struct got_error *close_err = got_repo_close(repo);
3680 if (error == NULL)
3681 error = close_err;
3683 if (head_ref != NULL)
3684 got_ref_close(head_ref);
3685 free(worktree_path);
3686 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3687 free(commit_id);
3688 free(commit_id_str);
3689 return error;
3692 static const struct got_error *
3693 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3694 const char *path, int diff_context, int ignore_whitespace,
3695 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3696 struct got_repository *repo, FILE *outfile)
3698 const struct got_error *err = NULL;
3699 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3700 FILE *f1 = NULL, *f2 = NULL;
3701 int fd1 = -1, fd2 = -1;
3703 fd1 = got_opentempfd();
3704 if (fd1 == -1)
3705 return got_error_from_errno("got_opentempfd");
3706 fd2 = got_opentempfd();
3707 if (fd2 == -1) {
3708 err = got_error_from_errno("got_opentempfd");
3709 goto done;
3712 if (blob_id1) {
3713 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3714 fd1);
3715 if (err)
3716 goto done;
3719 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3720 if (err)
3721 goto done;
3723 f1 = got_opentemp();
3724 if (f1 == NULL) {
3725 err = got_error_from_errno("got_opentemp");
3726 goto done;
3728 f2 = got_opentemp();
3729 if (f2 == NULL) {
3730 err = got_error_from_errno("got_opentemp");
3731 goto done;
3734 while (path[0] == '/')
3735 path++;
3736 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3737 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3738 force_text_diff, dsa, outfile);
3739 done:
3740 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3741 err = got_error_from_errno("close");
3742 if (blob1)
3743 got_object_blob_close(blob1);
3744 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3745 err = got_error_from_errno("close");
3746 if (blob2)
3747 got_object_blob_close(blob2);
3748 if (f1 && fclose(f1) == EOF && err == NULL)
3749 err = got_error_from_errno("fclose");
3750 if (f2 && fclose(f2) == EOF && err == NULL)
3751 err = got_error_from_errno("fclose");
3752 return err;
3755 static const struct got_error *
3756 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3757 const char *path, int diff_context, int ignore_whitespace,
3758 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3759 struct got_repository *repo, FILE *outfile)
3761 const struct got_error *err = NULL;
3762 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3763 struct got_diff_blob_output_unidiff_arg arg;
3764 FILE *f1 = NULL, *f2 = NULL;
3765 int fd1 = -1, fd2 = -1;
3767 if (tree_id1) {
3768 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3769 if (err)
3770 goto done;
3771 fd1 = got_opentempfd();
3772 if (fd1 == -1) {
3773 err = got_error_from_errno("got_opentempfd");
3774 goto done;
3778 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3779 if (err)
3780 goto done;
3782 f1 = got_opentemp();
3783 if (f1 == NULL) {
3784 err = got_error_from_errno("got_opentemp");
3785 goto done;
3788 f2 = got_opentemp();
3789 if (f2 == NULL) {
3790 err = got_error_from_errno("got_opentemp");
3791 goto done;
3793 fd2 = got_opentempfd();
3794 if (fd2 == -1) {
3795 err = got_error_from_errno("got_opentempfd");
3796 goto done;
3798 arg.diff_context = diff_context;
3799 arg.ignore_whitespace = ignore_whitespace;
3800 arg.force_text_diff = force_text_diff;
3801 arg.diffstat = dsa;
3802 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3803 arg.outfile = outfile;
3804 arg.lines = NULL;
3805 arg.nlines = 0;
3806 while (path[0] == '/')
3807 path++;
3808 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3809 got_diff_blob_output_unidiff, &arg, 1);
3810 done:
3811 if (tree1)
3812 got_object_tree_close(tree1);
3813 if (tree2)
3814 got_object_tree_close(tree2);
3815 if (f1 && fclose(f1) == EOF && err == NULL)
3816 err = got_error_from_errno("fclose");
3817 if (f2 && fclose(f2) == EOF && err == NULL)
3818 err = got_error_from_errno("fclose");
3819 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3820 err = got_error_from_errno("close");
3821 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3822 err = got_error_from_errno("close");
3823 return err;
3826 static const struct got_error *
3827 get_changed_paths(struct got_pathlist_head *paths,
3828 struct got_commit_object *commit, struct got_repository *repo,
3829 struct got_diffstat_cb_arg *dsa)
3831 const struct got_error *err = NULL;
3832 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3833 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3834 struct got_object_qid *qid;
3835 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3836 FILE *f1 = NULL, *f2 = NULL;
3837 int fd1 = -1, fd2 = -1;
3839 if (dsa) {
3840 cb = got_diff_tree_compute_diffstat;
3842 f1 = got_opentemp();
3843 if (f1 == NULL) {
3844 err = got_error_from_errno("got_opentemp");
3845 goto done;
3847 f2 = got_opentemp();
3848 if (f2 == NULL) {
3849 err = got_error_from_errno("got_opentemp");
3850 goto done;
3852 fd1 = got_opentempfd();
3853 if (fd1 == -1) {
3854 err = got_error_from_errno("got_opentempfd");
3855 goto done;
3857 fd2 = got_opentempfd();
3858 if (fd2 == -1) {
3859 err = got_error_from_errno("got_opentempfd");
3860 goto done;
3864 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3865 if (qid != NULL) {
3866 struct got_commit_object *pcommit;
3867 err = got_object_open_as_commit(&pcommit, repo,
3868 &qid->id);
3869 if (err)
3870 return err;
3872 tree_id1 = got_object_id_dup(
3873 got_object_commit_get_tree_id(pcommit));
3874 if (tree_id1 == NULL) {
3875 got_object_commit_close(pcommit);
3876 return got_error_from_errno("got_object_id_dup");
3878 got_object_commit_close(pcommit);
3882 if (tree_id1) {
3883 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3884 if (err)
3885 goto done;
3888 tree_id2 = got_object_commit_get_tree_id(commit);
3889 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3890 if (err)
3891 goto done;
3893 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3894 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3895 done:
3896 if (tree1)
3897 got_object_tree_close(tree1);
3898 if (tree2)
3899 got_object_tree_close(tree2);
3900 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3901 err = got_error_from_errno("close");
3902 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3903 err = got_error_from_errno("close");
3904 if (f1 && fclose(f1) == EOF && err == NULL)
3905 err = got_error_from_errno("fclose");
3906 if (f2 && fclose(f2) == EOF && err == NULL)
3907 err = got_error_from_errno("fclose");
3908 free(tree_id1);
3909 return err;
3912 static const struct got_error *
3913 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3914 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3915 struct got_repository *repo, FILE *outfile)
3917 const struct got_error *err = NULL;
3918 struct got_commit_object *pcommit = NULL;
3919 char *id_str1 = NULL, *id_str2 = NULL;
3920 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3921 struct got_object_qid *qid;
3923 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3924 if (qid != NULL) {
3925 err = got_object_open_as_commit(&pcommit, repo,
3926 &qid->id);
3927 if (err)
3928 return err;
3929 err = got_object_id_str(&id_str1, &qid->id);
3930 if (err)
3931 goto done;
3934 err = got_object_id_str(&id_str2, id);
3935 if (err)
3936 goto done;
3938 if (path && path[0] != '\0') {
3939 int obj_type;
3940 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3941 if (err)
3942 goto done;
3943 if (pcommit) {
3944 err = got_object_id_by_path(&obj_id1, repo,
3945 pcommit, path);
3946 if (err) {
3947 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3948 free(obj_id2);
3949 goto done;
3953 err = got_object_get_type(&obj_type, repo, obj_id2);
3954 if (err) {
3955 free(obj_id2);
3956 goto done;
3958 fprintf(outfile,
3959 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3960 fprintf(outfile, "commit - %s\n",
3961 id_str1 ? id_str1 : "/dev/null");
3962 fprintf(outfile, "commit + %s\n", id_str2);
3963 switch (obj_type) {
3964 case GOT_OBJ_TYPE_BLOB:
3965 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3966 0, 0, dsa, repo, outfile);
3967 break;
3968 case GOT_OBJ_TYPE_TREE:
3969 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3970 0, 0, dsa, repo, outfile);
3971 break;
3972 default:
3973 err = got_error(GOT_ERR_OBJ_TYPE);
3974 break;
3976 free(obj_id1);
3977 free(obj_id2);
3978 } else {
3979 obj_id2 = got_object_commit_get_tree_id(commit);
3980 if (pcommit)
3981 obj_id1 = got_object_commit_get_tree_id(pcommit);
3982 fprintf(outfile,
3983 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3984 fprintf(outfile, "commit - %s\n",
3985 id_str1 ? id_str1 : "/dev/null");
3986 fprintf(outfile, "commit + %s\n", id_str2);
3987 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3988 dsa, repo, outfile);
3990 done:
3991 free(id_str1);
3992 free(id_str2);
3993 if (pcommit)
3994 got_object_commit_close(pcommit);
3995 return err;
3998 static char *
3999 get_datestr(time_t *time, char *datebuf)
4001 struct tm mytm, *tm;
4002 char *p, *s;
4004 tm = gmtime_r(time, &mytm);
4005 if (tm == NULL)
4006 return NULL;
4007 s = asctime_r(tm, datebuf);
4008 if (s == NULL)
4009 return NULL;
4010 p = strchr(s, '\n');
4011 if (p)
4012 *p = '\0';
4013 return s;
4016 static const struct got_error *
4017 match_commit(int *have_match, struct got_object_id *id,
4018 struct got_commit_object *commit, regex_t *regex)
4020 const struct got_error *err = NULL;
4021 regmatch_t regmatch;
4022 char *id_str = NULL, *logmsg = NULL;
4024 *have_match = 0;
4026 err = got_object_id_str(&id_str, id);
4027 if (err)
4028 return err;
4030 err = got_object_commit_get_logmsg(&logmsg, commit);
4031 if (err)
4032 goto done;
4034 if (regexec(regex, got_object_commit_get_author(commit), 1,
4035 &regmatch, 0) == 0 ||
4036 regexec(regex, got_object_commit_get_committer(commit), 1,
4037 &regmatch, 0) == 0 ||
4038 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4039 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4040 *have_match = 1;
4041 done:
4042 free(id_str);
4043 free(logmsg);
4044 return err;
4047 static void
4048 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4049 regex_t *regex)
4051 regmatch_t regmatch;
4052 struct got_pathlist_entry *pe;
4054 *have_match = 0;
4056 TAILQ_FOREACH(pe, changed_paths, entry) {
4057 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4058 *have_match = 1;
4059 break;
4064 static const struct got_error *
4065 match_patch(int *have_match, struct got_commit_object *commit,
4066 struct got_object_id *id, const char *path, int diff_context,
4067 struct got_repository *repo, regex_t *regex, FILE *f)
4069 const struct got_error *err = NULL;
4070 char *line = NULL;
4071 size_t linesize = 0;
4072 regmatch_t regmatch;
4074 *have_match = 0;
4076 err = got_opentemp_truncate(f);
4077 if (err)
4078 return err;
4080 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4081 if (err)
4082 goto done;
4084 if (fseeko(f, 0L, SEEK_SET) == -1) {
4085 err = got_error_from_errno("fseeko");
4086 goto done;
4089 while (getline(&line, &linesize, f) != -1) {
4090 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4091 *have_match = 1;
4092 break;
4095 done:
4096 free(line);
4097 return err;
4100 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4102 static const struct got_error*
4103 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4104 struct got_object_id *id, struct got_repository *repo,
4105 int local_only)
4107 static const struct got_error *err = NULL;
4108 struct got_reflist_entry *re;
4109 char *s;
4110 const char *name;
4112 *refs_str = NULL;
4114 TAILQ_FOREACH(re, refs, entry) {
4115 struct got_tag_object *tag = NULL;
4116 struct got_object_id *ref_id;
4117 int cmp;
4119 name = got_ref_get_name(re->ref);
4120 if (strcmp(name, GOT_REF_HEAD) == 0)
4121 continue;
4122 if (strncmp(name, "refs/", 5) == 0)
4123 name += 5;
4124 if (strncmp(name, "got/", 4) == 0)
4125 continue;
4126 if (strncmp(name, "heads/", 6) == 0)
4127 name += 6;
4128 if (strncmp(name, "remotes/", 8) == 0) {
4129 if (local_only)
4130 continue;
4131 name += 8;
4132 s = strstr(name, "/" GOT_REF_HEAD);
4133 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4134 continue;
4136 err = got_ref_resolve(&ref_id, repo, re->ref);
4137 if (err)
4138 break;
4139 if (strncmp(name, "tags/", 5) == 0) {
4140 err = got_object_open_as_tag(&tag, repo, ref_id);
4141 if (err) {
4142 if (err->code != GOT_ERR_OBJ_TYPE) {
4143 free(ref_id);
4144 break;
4146 /* Ref points at something other than a tag. */
4147 err = NULL;
4148 tag = NULL;
4151 cmp = got_object_id_cmp(tag ?
4152 got_object_tag_get_object_id(tag) : ref_id, id);
4153 free(ref_id);
4154 if (tag)
4155 got_object_tag_close(tag);
4156 if (cmp != 0)
4157 continue;
4158 s = *refs_str;
4159 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4160 s ? ", " : "", name) == -1) {
4161 err = got_error_from_errno("asprintf");
4162 free(s);
4163 *refs_str = NULL;
4164 break;
4166 free(s);
4169 return err;
4172 static const struct got_error *
4173 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4174 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4176 const struct got_error *err = NULL;
4177 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4178 char *comma, *s, *nl;
4179 struct got_reflist_head *refs;
4180 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4181 struct tm tm;
4182 time_t committer_time;
4184 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4185 if (refs) {
4186 err = build_refs_str(&ref_str, refs, id, repo, 1);
4187 if (err)
4188 return err;
4190 /* Display the first matching ref only. */
4191 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4192 *comma = '\0';
4195 if (ref_str == NULL) {
4196 err = got_object_id_str(&id_str, id);
4197 if (err)
4198 return err;
4201 committer_time = got_object_commit_get_committer_time(commit);
4202 if (gmtime_r(&committer_time, &tm) == NULL) {
4203 err = got_error_from_errno("gmtime_r");
4204 goto done;
4206 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4207 err = got_error(GOT_ERR_NO_SPACE);
4208 goto done;
4211 err = got_object_commit_get_logmsg(&logmsg0, commit);
4212 if (err)
4213 goto done;
4215 s = logmsg0;
4216 while (isspace((unsigned char)s[0]))
4217 s++;
4219 nl = strchr(s, '\n');
4220 if (nl) {
4221 *nl = '\0';
4224 if (ref_str)
4225 printf("%s%-7s %s\n", datebuf, ref_str, s);
4226 else
4227 printf("%s%.7s %s\n", datebuf, id_str, s);
4229 if (fflush(stdout) != 0 && err == NULL)
4230 err = got_error_from_errno("fflush");
4231 done:
4232 free(id_str);
4233 free(ref_str);
4234 free(logmsg0);
4235 return err;
4238 static const struct got_error *
4239 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4241 struct got_pathlist_entry *pe;
4243 if (header != NULL)
4244 printf("%s\n", header);
4246 TAILQ_FOREACH(pe, dsa->paths, entry) {
4247 struct got_diff_changed_path *cp = pe->data;
4248 int pad = dsa->max_path_len - pe->path_len + 1;
4250 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4251 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4253 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4254 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4255 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4257 if (fflush(stdout) != 0)
4258 return got_error_from_errno("fflush");
4260 return NULL;
4263 static const struct got_error *
4264 printfile(FILE *f)
4266 char buf[8192];
4267 size_t r;
4269 if (fseeko(f, 0L, SEEK_SET) == -1)
4270 return got_error_from_errno("fseek");
4272 for (;;) {
4273 r = fread(buf, 1, sizeof(buf), f);
4274 if (r == 0) {
4275 if (ferror(f))
4276 return got_error_from_errno("fread");
4277 if (feof(f))
4278 break;
4280 if (fwrite(buf, 1, r, stdout) != r)
4281 return got_ferror(stdout, GOT_ERR_IO);
4284 return NULL;
4287 static const struct got_error *
4288 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4289 struct got_repository *repo, const char *path,
4290 struct got_pathlist_head *changed_paths,
4291 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4292 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4293 const char *prefix)
4295 const struct got_error *err = NULL;
4296 FILE *f = NULL;
4297 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4298 char datebuf[26];
4299 time_t committer_time;
4300 const char *author, *committer;
4301 char *refs_str = NULL;
4303 err = got_object_id_str(&id_str, id);
4304 if (err)
4305 return err;
4307 if (custom_refs_str == NULL) {
4308 struct got_reflist_head *refs;
4309 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4310 if (refs) {
4311 err = build_refs_str(&refs_str, refs, id, repo, 0);
4312 if (err)
4313 goto done;
4317 printf(GOT_COMMIT_SEP_STR);
4318 if (custom_refs_str)
4319 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4320 custom_refs_str);
4321 else
4322 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4323 refs_str ? " (" : "", refs_str ? refs_str : "",
4324 refs_str ? ")" : "");
4325 free(id_str);
4326 id_str = NULL;
4327 free(refs_str);
4328 refs_str = NULL;
4329 printf("from: %s\n", got_object_commit_get_author(commit));
4330 author = got_object_commit_get_author(commit);
4331 committer = got_object_commit_get_committer(commit);
4332 if (strcmp(author, committer) != 0)
4333 printf("via: %s\n", committer);
4334 committer_time = got_object_commit_get_committer_time(commit);
4335 datestr = get_datestr(&committer_time, datebuf);
4336 if (datestr)
4337 printf("date: %s UTC\n", datestr);
4338 if (got_object_commit_get_nparents(commit) > 1) {
4339 const struct got_object_id_queue *parent_ids;
4340 struct got_object_qid *qid;
4341 int n = 1;
4342 parent_ids = got_object_commit_get_parent_ids(commit);
4343 STAILQ_FOREACH(qid, parent_ids, entry) {
4344 err = got_object_id_str(&id_str, &qid->id);
4345 if (err)
4346 goto done;
4347 printf("parent %d: %s\n", n++, id_str);
4348 free(id_str);
4349 id_str = NULL;
4353 err = got_object_commit_get_logmsg(&logmsg0, commit);
4354 if (err)
4355 goto done;
4357 logmsg = logmsg0;
4358 do {
4359 line = strsep(&logmsg, "\n");
4360 if (line)
4361 printf(" %s\n", line);
4362 } while (line);
4363 free(logmsg0);
4365 if (changed_paths && diffstat == NULL) {
4366 struct got_pathlist_entry *pe;
4368 TAILQ_FOREACH(pe, changed_paths, entry) {
4369 struct got_diff_changed_path *cp = pe->data;
4371 printf(" %c %s\n", cp->status, pe->path);
4373 printf("\n");
4375 if (show_patch) {
4376 if (diffstat) {
4377 f = got_opentemp();
4378 if (f == NULL) {
4379 err = got_error_from_errno("got_opentemp");
4380 goto done;
4384 err = print_patch(commit, id, path, diff_context, diffstat,
4385 repo, diffstat == NULL ? stdout : f);
4386 if (err)
4387 goto done;
4389 if (diffstat) {
4390 err = print_diffstat(diffstat, NULL);
4391 if (err)
4392 goto done;
4393 if (show_patch) {
4394 err = printfile(f);
4395 if (err)
4396 goto done;
4399 if (show_patch)
4400 printf("\n");
4402 if (fflush(stdout) != 0 && err == NULL)
4403 err = got_error_from_errno("fflush");
4404 done:
4405 if (f && fclose(f) == EOF && err == NULL)
4406 err = got_error_from_errno("fclose");
4407 free(id_str);
4408 free(refs_str);
4409 return err;
4412 static const struct got_error *
4413 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4414 struct got_repository *repo, const char *path, int show_changed_paths,
4415 int show_diffstat, int show_patch, const char *search_pattern,
4416 int diff_context, int limit, int log_branches, int reverse_display_order,
4417 struct got_reflist_object_id_map *refs_idmap, int one_line,
4418 FILE *tmpfile)
4420 const struct got_error *err;
4421 struct got_commit_graph *graph;
4422 regex_t regex;
4423 int have_match;
4424 struct got_object_id_queue reversed_commits;
4425 struct got_object_qid *qid;
4426 struct got_commit_object *commit;
4427 struct got_pathlist_head changed_paths;
4429 STAILQ_INIT(&reversed_commits);
4430 TAILQ_INIT(&changed_paths);
4432 if (search_pattern && regcomp(&regex, search_pattern,
4433 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4434 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4436 err = got_commit_graph_open(&graph, path, !log_branches);
4437 if (err)
4438 return err;
4439 err = got_commit_graph_iter_start(graph, root_id, repo,
4440 check_cancelled, NULL);
4441 if (err)
4442 goto done;
4443 for (;;) {
4444 struct got_object_id id;
4445 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4446 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4448 if (sigint_received || sigpipe_received)
4449 break;
4451 err = got_commit_graph_iter_next(&id, graph, repo,
4452 check_cancelled, NULL);
4453 if (err) {
4454 if (err->code == GOT_ERR_ITER_COMPLETED)
4455 err = NULL;
4456 break;
4459 err = got_object_open_as_commit(&commit, repo, &id);
4460 if (err)
4461 break;
4463 if ((show_changed_paths || (show_diffstat && !show_patch))
4464 && !reverse_display_order) {
4465 err = get_changed_paths(&changed_paths, commit, repo,
4466 show_diffstat ? &dsa : NULL);
4467 if (err)
4468 break;
4471 if (search_pattern) {
4472 err = match_commit(&have_match, &id, commit, &regex);
4473 if (err) {
4474 got_object_commit_close(commit);
4475 break;
4477 if (have_match == 0 && show_changed_paths)
4478 match_changed_paths(&have_match,
4479 &changed_paths, &regex);
4480 if (have_match == 0 && show_patch) {
4481 err = match_patch(&have_match, commit, &id,
4482 path, diff_context, repo, &regex, tmpfile);
4483 if (err)
4484 break;
4486 if (have_match == 0) {
4487 got_object_commit_close(commit);
4488 got_pathlist_free(&changed_paths,
4489 GOT_PATHLIST_FREE_ALL);
4490 continue;
4494 if (reverse_display_order) {
4495 err = got_object_qid_alloc(&qid, &id);
4496 if (err)
4497 break;
4498 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4499 got_object_commit_close(commit);
4500 } else {
4501 if (one_line)
4502 err = print_commit_oneline(commit, &id,
4503 repo, refs_idmap);
4504 else
4505 err = print_commit(commit, &id, repo, path,
4506 (show_changed_paths || show_diffstat) ?
4507 &changed_paths : NULL,
4508 show_diffstat ? &dsa : NULL, show_patch,
4509 diff_context, refs_idmap, NULL, NULL);
4510 got_object_commit_close(commit);
4511 if (err)
4512 break;
4514 if ((limit && --limit == 0) ||
4515 (end_id && got_object_id_cmp(&id, end_id) == 0))
4516 break;
4518 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4520 if (reverse_display_order) {
4521 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4522 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4523 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4525 err = got_object_open_as_commit(&commit, repo,
4526 &qid->id);
4527 if (err)
4528 break;
4529 if (show_changed_paths ||
4530 (show_diffstat && !show_patch)) {
4531 err = get_changed_paths(&changed_paths, commit,
4532 repo, show_diffstat ? &dsa : NULL);
4533 if (err)
4534 break;
4536 if (one_line)
4537 err = print_commit_oneline(commit, &qid->id,
4538 repo, refs_idmap);
4539 else
4540 err = print_commit(commit, &qid->id, repo, path,
4541 (show_changed_paths || show_diffstat) ?
4542 &changed_paths : NULL,
4543 show_diffstat ? &dsa : NULL, show_patch,
4544 diff_context, refs_idmap, NULL, NULL);
4545 got_object_commit_close(commit);
4546 if (err)
4547 break;
4548 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4551 done:
4552 while (!STAILQ_EMPTY(&reversed_commits)) {
4553 qid = STAILQ_FIRST(&reversed_commits);
4554 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4555 got_object_qid_free(qid);
4557 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4558 if (search_pattern)
4559 regfree(&regex);
4560 got_commit_graph_close(graph);
4561 return err;
4564 __dead static void
4565 usage_log(void)
4567 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4568 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4569 "[path]\n", getprogname());
4570 exit(1);
4573 static int
4574 get_default_log_limit(void)
4576 const char *got_default_log_limit;
4577 long long n;
4578 const char *errstr;
4580 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4581 if (got_default_log_limit == NULL)
4582 return 0;
4583 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4584 if (errstr != NULL)
4585 return 0;
4586 return n;
4589 static const struct got_error *
4590 cmd_log(int argc, char *argv[])
4592 const struct got_error *error;
4593 struct got_repository *repo = NULL;
4594 struct got_worktree *worktree = NULL;
4595 struct got_object_id *start_id = NULL, *end_id = NULL;
4596 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4597 const char *start_commit = NULL, *end_commit = NULL;
4598 const char *search_pattern = NULL;
4599 int diff_context = -1, ch;
4600 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4601 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4602 const char *errstr;
4603 struct got_reflist_head refs;
4604 struct got_reflist_object_id_map *refs_idmap = NULL;
4605 FILE *tmpfile = NULL;
4606 int *pack_fds = NULL;
4608 TAILQ_INIT(&refs);
4610 #ifndef PROFILE
4611 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4612 NULL)
4613 == -1)
4614 err(1, "pledge");
4615 #endif
4617 limit = get_default_log_limit();
4619 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4620 switch (ch) {
4621 case 'b':
4622 log_branches = 1;
4623 break;
4624 case 'C':
4625 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4626 &errstr);
4627 if (errstr != NULL)
4628 errx(1, "number of context lines is %s: %s",
4629 errstr, optarg);
4630 break;
4631 case 'c':
4632 start_commit = optarg;
4633 break;
4634 case 'd':
4635 show_diffstat = 1;
4636 break;
4637 case 'l':
4638 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4639 if (errstr != NULL)
4640 errx(1, "number of commits is %s: %s",
4641 errstr, optarg);
4642 break;
4643 case 'P':
4644 show_changed_paths = 1;
4645 break;
4646 case 'p':
4647 show_patch = 1;
4648 break;
4649 case 'R':
4650 reverse_display_order = 1;
4651 break;
4652 case 'r':
4653 repo_path = realpath(optarg, NULL);
4654 if (repo_path == NULL)
4655 return got_error_from_errno2("realpath",
4656 optarg);
4657 got_path_strip_trailing_slashes(repo_path);
4658 break;
4659 case 'S':
4660 search_pattern = optarg;
4661 break;
4662 case 's':
4663 one_line = 1;
4664 break;
4665 case 'x':
4666 end_commit = optarg;
4667 break;
4668 default:
4669 usage_log();
4670 /* NOTREACHED */
4674 argc -= optind;
4675 argv += optind;
4677 if (diff_context == -1)
4678 diff_context = 3;
4679 else if (!show_patch)
4680 errx(1, "-C requires -p");
4682 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4683 errx(1, "cannot use -s with -d, -p or -P");
4685 cwd = getcwd(NULL, 0);
4686 if (cwd == NULL) {
4687 error = got_error_from_errno("getcwd");
4688 goto done;
4691 error = got_repo_pack_fds_open(&pack_fds);
4692 if (error != NULL)
4693 goto done;
4695 if (repo_path == NULL) {
4696 error = got_worktree_open(&worktree, cwd,
4697 GOT_WORKTREE_GOT_DIR);
4698 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4699 goto done;
4700 error = NULL;
4703 if (argc == 1) {
4704 if (worktree) {
4705 error = got_worktree_resolve_path(&path, worktree,
4706 argv[0]);
4707 if (error)
4708 goto done;
4709 } else {
4710 path = strdup(argv[0]);
4711 if (path == NULL) {
4712 error = got_error_from_errno("strdup");
4713 goto done;
4716 } else if (argc != 0)
4717 usage_log();
4719 if (repo_path == NULL) {
4720 repo_path = worktree ?
4721 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4723 if (repo_path == NULL) {
4724 error = got_error_from_errno("strdup");
4725 goto done;
4728 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4729 if (error != NULL)
4730 goto done;
4732 error = apply_unveil(got_repo_get_path(repo), 1,
4733 worktree ? got_worktree_get_root_path(worktree) : NULL);
4734 if (error)
4735 goto done;
4737 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4738 if (error)
4739 goto done;
4741 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4742 if (error)
4743 goto done;
4745 if (start_commit == NULL) {
4746 struct got_reference *head_ref;
4747 struct got_commit_object *commit = NULL;
4748 error = got_ref_open(&head_ref, repo,
4749 worktree ? got_worktree_get_head_ref_name(worktree)
4750 : GOT_REF_HEAD, 0);
4751 if (error != NULL)
4752 goto done;
4753 error = got_ref_resolve(&start_id, repo, head_ref);
4754 got_ref_close(head_ref);
4755 if (error != NULL)
4756 goto done;
4757 error = got_object_open_as_commit(&commit, repo,
4758 start_id);
4759 if (error != NULL)
4760 goto done;
4761 got_object_commit_close(commit);
4762 } else {
4763 char *keyword_idstr = NULL;
4765 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4766 repo, worktree);
4767 if (error != NULL)
4768 goto done;
4769 if (keyword_idstr != NULL)
4770 start_commit = keyword_idstr;
4772 error = got_repo_match_object_id(&start_id, NULL,
4773 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4774 free(keyword_idstr);
4775 if (error != NULL)
4776 goto done;
4778 if (end_commit != NULL) {
4779 error = got_repo_match_object_id(&end_id, NULL,
4780 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4781 if (error != NULL)
4782 goto done;
4785 if (worktree) {
4787 * If a path was specified on the command line it was resolved
4788 * to a path in the work tree above. Prepend the work tree's
4789 * path prefix to obtain the corresponding in-repository path.
4791 if (path) {
4792 const char *prefix;
4793 prefix = got_worktree_get_path_prefix(worktree);
4794 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4795 (path[0] != '\0') ? "/" : "", path) == -1) {
4796 error = got_error_from_errno("asprintf");
4797 goto done;
4800 } else
4801 error = got_repo_map_path(&in_repo_path, repo,
4802 path ? path : "");
4803 if (error != NULL)
4804 goto done;
4805 if (in_repo_path) {
4806 free(path);
4807 path = in_repo_path;
4810 if (worktree) {
4811 /* Release work tree lock. */
4812 got_worktree_close(worktree);
4813 worktree = NULL;
4816 if (search_pattern && show_patch) {
4817 tmpfile = got_opentemp();
4818 if (tmpfile == NULL) {
4819 error = got_error_from_errno("got_opentemp");
4820 goto done;
4824 error = print_commits(start_id, end_id, repo, path ? path : "",
4825 show_changed_paths, show_diffstat, show_patch, search_pattern,
4826 diff_context, limit, log_branches, reverse_display_order,
4827 refs_idmap, one_line, tmpfile);
4828 done:
4829 free(path);
4830 free(repo_path);
4831 free(cwd);
4832 free(start_id);
4833 free(end_id);
4834 if (worktree)
4835 got_worktree_close(worktree);
4836 if (repo) {
4837 const struct got_error *close_err = got_repo_close(repo);
4838 if (error == NULL)
4839 error = close_err;
4841 if (pack_fds) {
4842 const struct got_error *pack_err =
4843 got_repo_pack_fds_close(pack_fds);
4844 if (error == NULL)
4845 error = pack_err;
4847 if (refs_idmap)
4848 got_reflist_object_id_map_free(refs_idmap);
4849 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4850 error = got_error_from_errno("fclose");
4851 got_ref_list_free(&refs);
4852 return error;
4855 __dead static void
4856 usage_diff(void)
4858 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4859 "[-r repository-path] [object1 object2 | path ...]\n",
4860 getprogname());
4861 exit(1);
4864 struct print_diff_arg {
4865 struct got_repository *repo;
4866 struct got_worktree *worktree;
4867 struct got_diffstat_cb_arg *diffstat;
4868 int diff_context;
4869 const char *id_str;
4870 int header_shown;
4871 int diff_staged;
4872 enum got_diff_algorithm diff_algo;
4873 int ignore_whitespace;
4874 int force_text_diff;
4875 FILE *f1;
4876 FILE *f2;
4877 FILE *outfile;
4881 * Create a file which contains the target path of a symlink so we can feed
4882 * it as content to the diff engine.
4884 static const struct got_error *
4885 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4886 const char *abspath)
4888 const struct got_error *err = NULL;
4889 char target_path[PATH_MAX];
4890 ssize_t target_len, outlen;
4892 *fd = -1;
4894 if (dirfd != -1) {
4895 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4896 if (target_len == -1)
4897 return got_error_from_errno2("readlinkat", abspath);
4898 } else {
4899 target_len = readlink(abspath, target_path, PATH_MAX);
4900 if (target_len == -1)
4901 return got_error_from_errno2("readlink", abspath);
4904 *fd = got_opentempfd();
4905 if (*fd == -1)
4906 return got_error_from_errno("got_opentempfd");
4908 outlen = write(*fd, target_path, target_len);
4909 if (outlen == -1) {
4910 err = got_error_from_errno("got_opentempfd");
4911 goto done;
4914 if (lseek(*fd, 0, SEEK_SET) == -1) {
4915 err = got_error_from_errno2("lseek", abspath);
4916 goto done;
4918 done:
4919 if (err) {
4920 close(*fd);
4921 *fd = -1;
4923 return err;
4926 static const struct got_error *
4927 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4928 const char *path, struct got_object_id *blob_id,
4929 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4930 int dirfd, const char *de_name)
4932 struct print_diff_arg *a = arg;
4933 const struct got_error *err = NULL;
4934 struct got_blob_object *blob1 = NULL;
4935 int fd = -1, fd1 = -1, fd2 = -1;
4936 FILE *f2 = NULL;
4937 char *abspath = NULL, *label1 = NULL;
4938 struct stat sb;
4939 off_t size1 = 0;
4940 int f2_exists = 0;
4942 memset(&sb, 0, sizeof(sb));
4944 if (a->diff_staged) {
4945 if (staged_status != GOT_STATUS_MODIFY &&
4946 staged_status != GOT_STATUS_ADD &&
4947 staged_status != GOT_STATUS_DELETE)
4948 return NULL;
4949 } else {
4950 if (staged_status == GOT_STATUS_DELETE)
4951 return NULL;
4952 if (status == GOT_STATUS_NONEXISTENT)
4953 return got_error_set_errno(ENOENT, path);
4954 if (status != GOT_STATUS_MODIFY &&
4955 status != GOT_STATUS_ADD &&
4956 status != GOT_STATUS_DELETE &&
4957 status != GOT_STATUS_CONFLICT)
4958 return NULL;
4961 err = got_opentemp_truncate(a->f1);
4962 if (err)
4963 return got_error_from_errno("got_opentemp_truncate");
4964 err = got_opentemp_truncate(a->f2);
4965 if (err)
4966 return got_error_from_errno("got_opentemp_truncate");
4968 if (!a->header_shown) {
4969 if (fprintf(a->outfile, "diff %s%s\n",
4970 a->diff_staged ? "-s " : "",
4971 got_worktree_get_root_path(a->worktree)) < 0) {
4972 err = got_error_from_errno("fprintf");
4973 goto done;
4975 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4976 err = got_error_from_errno("fprintf");
4977 goto done;
4979 if (fprintf(a->outfile, "path + %s%s\n",
4980 got_worktree_get_root_path(a->worktree),
4981 a->diff_staged ? " (staged changes)" : "") < 0) {
4982 err = got_error_from_errno("fprintf");
4983 goto done;
4985 a->header_shown = 1;
4988 if (a->diff_staged) {
4989 const char *label1 = NULL, *label2 = NULL;
4990 switch (staged_status) {
4991 case GOT_STATUS_MODIFY:
4992 label1 = path;
4993 label2 = path;
4994 break;
4995 case GOT_STATUS_ADD:
4996 label2 = path;
4997 break;
4998 case GOT_STATUS_DELETE:
4999 label1 = path;
5000 break;
5001 default:
5002 return got_error(GOT_ERR_FILE_STATUS);
5004 fd1 = got_opentempfd();
5005 if (fd1 == -1) {
5006 err = got_error_from_errno("got_opentempfd");
5007 goto done;
5009 fd2 = got_opentempfd();
5010 if (fd2 == -1) {
5011 err = got_error_from_errno("got_opentempfd");
5012 goto done;
5014 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5015 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5016 a->diff_algo, a->diff_context, a->ignore_whitespace,
5017 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5018 goto done;
5021 fd1 = got_opentempfd();
5022 if (fd1 == -1) {
5023 err = got_error_from_errno("got_opentempfd");
5024 goto done;
5027 if (staged_status == GOT_STATUS_ADD ||
5028 staged_status == GOT_STATUS_MODIFY) {
5029 char *id_str;
5030 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5031 8192, fd1);
5032 if (err)
5033 goto done;
5034 err = got_object_id_str(&id_str, staged_blob_id);
5035 if (err)
5036 goto done;
5037 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5038 err = got_error_from_errno("asprintf");
5039 free(id_str);
5040 goto done;
5042 free(id_str);
5043 } else if (status != GOT_STATUS_ADD) {
5044 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5045 fd1);
5046 if (err)
5047 goto done;
5050 if (status != GOT_STATUS_DELETE) {
5051 if (asprintf(&abspath, "%s/%s",
5052 got_worktree_get_root_path(a->worktree), path) == -1) {
5053 err = got_error_from_errno("asprintf");
5054 goto done;
5057 if (dirfd != -1) {
5058 fd = openat(dirfd, de_name,
5059 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5060 if (fd == -1) {
5061 if (!got_err_open_nofollow_on_symlink()) {
5062 err = got_error_from_errno2("openat",
5063 abspath);
5064 goto done;
5066 err = get_symlink_target_file(&fd, dirfd,
5067 de_name, abspath);
5068 if (err)
5069 goto done;
5071 } else {
5072 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5073 if (fd == -1) {
5074 if (!got_err_open_nofollow_on_symlink()) {
5075 err = got_error_from_errno2("open",
5076 abspath);
5077 goto done;
5079 err = get_symlink_target_file(&fd, dirfd,
5080 de_name, abspath);
5081 if (err)
5082 goto done;
5085 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5086 err = got_error_from_errno2("fstatat", abspath);
5087 goto done;
5089 f2 = fdopen(fd, "r");
5090 if (f2 == NULL) {
5091 err = got_error_from_errno2("fdopen", abspath);
5092 goto done;
5094 fd = -1;
5095 f2_exists = 1;
5098 if (blob1) {
5099 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5100 a->f1, blob1);
5101 if (err)
5102 goto done;
5105 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5106 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5107 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5108 done:
5109 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5110 err = got_error_from_errno("close");
5111 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5112 err = got_error_from_errno("close");
5113 if (blob1)
5114 got_object_blob_close(blob1);
5115 if (fd != -1 && close(fd) == -1 && err == NULL)
5116 err = got_error_from_errno("close");
5117 if (f2 && fclose(f2) == EOF && err == NULL)
5118 err = got_error_from_errno("fclose");
5119 free(abspath);
5120 return err;
5123 static const struct got_error *
5124 cmd_diff(int argc, char *argv[])
5126 const struct got_error *error;
5127 struct got_repository *repo = NULL;
5128 struct got_worktree *worktree = NULL;
5129 char *cwd = NULL, *repo_path = NULL;
5130 const char *commit_args[2] = { NULL, NULL };
5131 int ncommit_args = 0;
5132 struct got_object_id *ids[2] = { NULL, NULL };
5133 char *labels[2] = { NULL, NULL };
5134 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5135 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5136 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5137 const char *errstr;
5138 struct got_reflist_head refs;
5139 struct got_pathlist_head diffstat_paths, paths;
5140 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5141 int fd1 = -1, fd2 = -1;
5142 int *pack_fds = NULL;
5143 struct got_diffstat_cb_arg dsa;
5145 memset(&dsa, 0, sizeof(dsa));
5147 TAILQ_INIT(&refs);
5148 TAILQ_INIT(&paths);
5149 TAILQ_INIT(&diffstat_paths);
5151 #ifndef PROFILE
5152 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5153 NULL) == -1)
5154 err(1, "pledge");
5155 #endif
5157 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5158 switch (ch) {
5159 case 'a':
5160 force_text_diff = 1;
5161 break;
5162 case 'C':
5163 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5164 &errstr);
5165 if (errstr != NULL)
5166 errx(1, "number of context lines is %s: %s",
5167 errstr, optarg);
5168 break;
5169 case 'c':
5170 if (ncommit_args >= 2)
5171 errx(1, "too many -c options used");
5172 commit_args[ncommit_args++] = optarg;
5173 break;
5174 case 'd':
5175 show_diffstat = 1;
5176 break;
5177 case 'P':
5178 force_path = 1;
5179 break;
5180 case 'r':
5181 repo_path = realpath(optarg, NULL);
5182 if (repo_path == NULL)
5183 return got_error_from_errno2("realpath",
5184 optarg);
5185 got_path_strip_trailing_slashes(repo_path);
5186 rflag = 1;
5187 break;
5188 case 's':
5189 diff_staged = 1;
5190 break;
5191 case 'w':
5192 ignore_whitespace = 1;
5193 break;
5194 default:
5195 usage_diff();
5196 /* NOTREACHED */
5200 argc -= optind;
5201 argv += optind;
5203 cwd = getcwd(NULL, 0);
5204 if (cwd == NULL) {
5205 error = got_error_from_errno("getcwd");
5206 goto done;
5209 error = got_repo_pack_fds_open(&pack_fds);
5210 if (error != NULL)
5211 goto done;
5213 if (repo_path == NULL) {
5214 error = got_worktree_open(&worktree, cwd,
5215 GOT_WORKTREE_GOT_DIR);
5216 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5217 goto done;
5218 else
5219 error = NULL;
5220 if (worktree) {
5221 repo_path =
5222 strdup(got_worktree_get_repo_path(worktree));
5223 if (repo_path == NULL) {
5224 error = got_error_from_errno("strdup");
5225 goto done;
5227 } else {
5228 repo_path = strdup(cwd);
5229 if (repo_path == NULL) {
5230 error = got_error_from_errno("strdup");
5231 goto done;
5236 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5237 free(repo_path);
5238 if (error != NULL)
5239 goto done;
5241 if (show_diffstat) {
5242 dsa.paths = &diffstat_paths;
5243 dsa.force_text = force_text_diff;
5244 dsa.ignore_ws = ignore_whitespace;
5245 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5248 if (rflag || worktree == NULL || ncommit_args > 0) {
5249 if (force_path) {
5250 error = got_error_msg(GOT_ERR_NOT_IMPL,
5251 "-P option can only be used when diffing "
5252 "a work tree");
5253 goto done;
5255 if (diff_staged) {
5256 error = got_error_msg(GOT_ERR_NOT_IMPL,
5257 "-s option can only be used when diffing "
5258 "a work tree");
5259 goto done;
5263 error = apply_unveil(got_repo_get_path(repo), 1,
5264 worktree ? got_worktree_get_root_path(worktree) : NULL);
5265 if (error)
5266 goto done;
5268 if ((!force_path && argc == 2) || ncommit_args > 0) {
5269 int obj_type = (ncommit_args > 0 ?
5270 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5271 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5272 NULL);
5273 if (error)
5274 goto done;
5275 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5276 const char *arg;
5277 char *keyword_idstr = NULL;
5279 if (ncommit_args > 0)
5280 arg = commit_args[i];
5281 else
5282 arg = argv[i];
5284 error = got_keyword_to_idstr(&keyword_idstr, arg,
5285 repo, worktree);
5286 if (error != NULL)
5287 goto done;
5288 if (keyword_idstr != NULL)
5289 arg = keyword_idstr;
5291 error = got_repo_match_object_id(&ids[i], &labels[i],
5292 arg, obj_type, &refs, repo);
5293 free(keyword_idstr);
5294 if (error) {
5295 if (error->code != GOT_ERR_NOT_REF &&
5296 error->code != GOT_ERR_NO_OBJ)
5297 goto done;
5298 if (ncommit_args > 0)
5299 goto done;
5300 error = NULL;
5301 break;
5306 f1 = got_opentemp();
5307 if (f1 == NULL) {
5308 error = got_error_from_errno("got_opentemp");
5309 goto done;
5312 f2 = got_opentemp();
5313 if (f2 == NULL) {
5314 error = got_error_from_errno("got_opentemp");
5315 goto done;
5318 outfile = got_opentemp();
5319 if (outfile == NULL) {
5320 error = got_error_from_errno("got_opentemp");
5321 goto done;
5324 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5325 struct print_diff_arg arg;
5326 char *id_str;
5328 if (worktree == NULL) {
5329 if (argc == 2 && ids[0] == NULL) {
5330 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5331 goto done;
5332 } else if (argc == 2 && ids[1] == NULL) {
5333 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5334 goto done;
5335 } else if (argc > 0) {
5336 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5337 "%s", "specified paths cannot be resolved");
5338 goto done;
5339 } else {
5340 error = got_error(GOT_ERR_NOT_WORKTREE);
5341 goto done;
5345 error = get_worktree_paths_from_argv(&paths, argc, argv,
5346 worktree);
5347 if (error)
5348 goto done;
5350 error = got_object_id_str(&id_str,
5351 got_worktree_get_base_commit_id(worktree));
5352 if (error)
5353 goto done;
5354 arg.repo = repo;
5355 arg.worktree = worktree;
5356 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5357 arg.diff_context = diff_context;
5358 arg.id_str = id_str;
5359 arg.header_shown = 0;
5360 arg.diff_staged = diff_staged;
5361 arg.ignore_whitespace = ignore_whitespace;
5362 arg.force_text_diff = force_text_diff;
5363 arg.diffstat = show_diffstat ? &dsa : NULL;
5364 arg.f1 = f1;
5365 arg.f2 = f2;
5366 arg.outfile = outfile;
5368 error = got_worktree_status(worktree, &paths, repo, 0,
5369 print_diff, &arg, check_cancelled, NULL);
5370 free(id_str);
5371 if (error)
5372 goto done;
5374 if (show_diffstat && dsa.nfiles > 0) {
5375 char *header;
5377 if (asprintf(&header, "diffstat %s%s",
5378 diff_staged ? "-s " : "",
5379 got_worktree_get_root_path(worktree)) == -1) {
5380 error = got_error_from_errno("asprintf");
5381 goto done;
5384 error = print_diffstat(&dsa, header);
5385 free(header);
5386 if (error)
5387 goto done;
5390 error = printfile(outfile);
5391 goto done;
5394 if (ncommit_args == 1) {
5395 struct got_commit_object *commit;
5396 error = got_object_open_as_commit(&commit, repo, ids[0]);
5397 if (error)
5398 goto done;
5400 labels[1] = labels[0];
5401 ids[1] = ids[0];
5402 if (got_object_commit_get_nparents(commit) > 0) {
5403 const struct got_object_id_queue *pids;
5404 struct got_object_qid *pid;
5405 pids = got_object_commit_get_parent_ids(commit);
5406 pid = STAILQ_FIRST(pids);
5407 ids[0] = got_object_id_dup(&pid->id);
5408 if (ids[0] == NULL) {
5409 error = got_error_from_errno(
5410 "got_object_id_dup");
5411 got_object_commit_close(commit);
5412 goto done;
5414 error = got_object_id_str(&labels[0], ids[0]);
5415 if (error) {
5416 got_object_commit_close(commit);
5417 goto done;
5419 } else {
5420 ids[0] = NULL;
5421 labels[0] = strdup("/dev/null");
5422 if (labels[0] == NULL) {
5423 error = got_error_from_errno("strdup");
5424 got_object_commit_close(commit);
5425 goto done;
5429 got_object_commit_close(commit);
5432 if (ncommit_args == 0 && argc > 2) {
5433 error = got_error_msg(GOT_ERR_BAD_PATH,
5434 "path arguments cannot be used when diffing two objects");
5435 goto done;
5438 if (ids[0]) {
5439 error = got_object_get_type(&type1, repo, ids[0]);
5440 if (error)
5441 goto done;
5444 error = got_object_get_type(&type2, repo, ids[1]);
5445 if (error)
5446 goto done;
5447 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5448 error = got_error(GOT_ERR_OBJ_TYPE);
5449 goto done;
5451 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5452 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5453 "path arguments cannot be used when diffing blobs");
5454 goto done;
5457 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5458 char *in_repo_path;
5459 struct got_pathlist_entry *new;
5460 if (worktree) {
5461 const char *prefix;
5462 char *p;
5463 error = got_worktree_resolve_path(&p, worktree,
5464 argv[i]);
5465 if (error)
5466 goto done;
5467 prefix = got_worktree_get_path_prefix(worktree);
5468 while (prefix[0] == '/')
5469 prefix++;
5470 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5471 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5472 p) == -1) {
5473 error = got_error_from_errno("asprintf");
5474 free(p);
5475 goto done;
5477 free(p);
5478 } else {
5479 char *mapped_path, *s;
5480 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5481 if (error)
5482 goto done;
5483 s = mapped_path;
5484 while (s[0] == '/')
5485 s++;
5486 in_repo_path = strdup(s);
5487 if (in_repo_path == NULL) {
5488 error = got_error_from_errno("asprintf");
5489 free(mapped_path);
5490 goto done;
5492 free(mapped_path);
5495 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5496 if (error || new == NULL /* duplicate */)
5497 free(in_repo_path);
5498 if (error)
5499 goto done;
5502 if (worktree) {
5503 /* Release work tree lock. */
5504 got_worktree_close(worktree);
5505 worktree = NULL;
5508 fd1 = got_opentempfd();
5509 if (fd1 == -1) {
5510 error = got_error_from_errno("got_opentempfd");
5511 goto done;
5514 fd2 = got_opentempfd();
5515 if (fd2 == -1) {
5516 error = got_error_from_errno("got_opentempfd");
5517 goto done;
5520 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5521 case GOT_OBJ_TYPE_BLOB:
5522 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5523 fd1, fd2, ids[0], ids[1], NULL, NULL,
5524 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5525 ignore_whitespace, force_text_diff,
5526 show_diffstat ? &dsa : NULL, repo, outfile);
5527 break;
5528 case GOT_OBJ_TYPE_TREE:
5529 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5530 ids[0], ids[1], &paths, "", "",
5531 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5532 ignore_whitespace, force_text_diff,
5533 show_diffstat ? &dsa : NULL, repo, outfile);
5534 break;
5535 case GOT_OBJ_TYPE_COMMIT:
5536 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5537 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5538 fd1, fd2, ids[0], ids[1], &paths,
5539 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5540 ignore_whitespace, force_text_diff,
5541 show_diffstat ? &dsa : NULL, repo, outfile);
5542 break;
5543 default:
5544 error = got_error(GOT_ERR_OBJ_TYPE);
5546 if (error)
5547 goto done;
5549 if (show_diffstat && dsa.nfiles > 0) {
5550 char *header = NULL;
5552 if (asprintf(&header, "diffstat %s %s",
5553 labels[0], labels[1]) == -1) {
5554 error = got_error_from_errno("asprintf");
5555 goto done;
5558 error = print_diffstat(&dsa, header);
5559 free(header);
5560 if (error)
5561 goto done;
5564 error = printfile(outfile);
5566 done:
5567 free(labels[0]);
5568 free(labels[1]);
5569 free(ids[0]);
5570 free(ids[1]);
5571 if (worktree)
5572 got_worktree_close(worktree);
5573 if (repo) {
5574 const struct got_error *close_err = got_repo_close(repo);
5575 if (error == NULL)
5576 error = close_err;
5578 if (pack_fds) {
5579 const struct got_error *pack_err =
5580 got_repo_pack_fds_close(pack_fds);
5581 if (error == NULL)
5582 error = pack_err;
5584 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5585 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5586 got_ref_list_free(&refs);
5587 if (outfile && fclose(outfile) == EOF && error == NULL)
5588 error = got_error_from_errno("fclose");
5589 if (f1 && fclose(f1) == EOF && error == NULL)
5590 error = got_error_from_errno("fclose");
5591 if (f2 && fclose(f2) == EOF && error == NULL)
5592 error = got_error_from_errno("fclose");
5593 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5594 error = got_error_from_errno("close");
5595 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5596 error = got_error_from_errno("close");
5597 return error;
5600 __dead static void
5601 usage_blame(void)
5603 fprintf(stderr,
5604 "usage: %s blame [-c commit] [-r repository-path] path\n",
5605 getprogname());
5606 exit(1);
5609 struct blame_line {
5610 int annotated;
5611 char *id_str;
5612 char *committer;
5613 char datebuf[11]; /* YYYY-MM-DD + NUL */
5616 struct blame_cb_args {
5617 struct blame_line *lines;
5618 int nlines;
5619 int nlines_prec;
5620 int lineno_cur;
5621 off_t *line_offsets;
5622 FILE *f;
5623 struct got_repository *repo;
5626 static const struct got_error *
5627 blame_cb(void *arg, int nlines, int lineno,
5628 struct got_commit_object *commit, struct got_object_id *id)
5630 const struct got_error *err = NULL;
5631 struct blame_cb_args *a = arg;
5632 struct blame_line *bline;
5633 char *line = NULL;
5634 size_t linesize = 0;
5635 off_t offset;
5636 struct tm tm;
5637 time_t committer_time;
5639 if (nlines != a->nlines ||
5640 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5641 return got_error(GOT_ERR_RANGE);
5643 if (sigint_received)
5644 return got_error(GOT_ERR_ITER_COMPLETED);
5646 if (lineno == -1)
5647 return NULL; /* no change in this commit */
5649 /* Annotate this line. */
5650 bline = &a->lines[lineno - 1];
5651 if (bline->annotated)
5652 return NULL;
5653 err = got_object_id_str(&bline->id_str, id);
5654 if (err)
5655 return err;
5657 bline->committer = strdup(got_object_commit_get_committer(commit));
5658 if (bline->committer == NULL) {
5659 err = got_error_from_errno("strdup");
5660 goto done;
5663 committer_time = got_object_commit_get_committer_time(commit);
5664 if (gmtime_r(&committer_time, &tm) == NULL)
5665 return got_error_from_errno("gmtime_r");
5666 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5667 &tm) == 0) {
5668 err = got_error(GOT_ERR_NO_SPACE);
5669 goto done;
5671 bline->annotated = 1;
5673 /* Print lines annotated so far. */
5674 bline = &a->lines[a->lineno_cur - 1];
5675 if (!bline->annotated)
5676 goto done;
5678 offset = a->line_offsets[a->lineno_cur - 1];
5679 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5680 err = got_error_from_errno("fseeko");
5681 goto done;
5684 while (a->lineno_cur <= a->nlines && bline->annotated) {
5685 char *smallerthan, *at, *nl, *committer;
5686 size_t len;
5688 if (getline(&line, &linesize, a->f) == -1) {
5689 if (ferror(a->f))
5690 err = got_error_from_errno("getline");
5691 break;
5694 committer = bline->committer;
5695 smallerthan = strchr(committer, '<');
5696 if (smallerthan && smallerthan[1] != '\0')
5697 committer = smallerthan + 1;
5698 at = strchr(committer, '@');
5699 if (at)
5700 *at = '\0';
5701 len = strlen(committer);
5702 if (len >= 9)
5703 committer[8] = '\0';
5705 nl = strchr(line, '\n');
5706 if (nl)
5707 *nl = '\0';
5708 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5709 bline->id_str, bline->datebuf, committer, line);
5711 a->lineno_cur++;
5712 bline = &a->lines[a->lineno_cur - 1];
5714 done:
5715 free(line);
5716 return err;
5719 static const struct got_error *
5720 cmd_blame(int argc, char *argv[])
5722 const struct got_error *error;
5723 struct got_repository *repo = NULL;
5724 struct got_worktree *worktree = NULL;
5725 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5726 char *link_target = NULL;
5727 struct got_object_id *obj_id = NULL;
5728 struct got_object_id *commit_id = NULL;
5729 struct got_commit_object *commit = NULL;
5730 struct got_blob_object *blob = NULL;
5731 char *commit_id_str = NULL, *keyword_idstr = NULL;
5732 struct blame_cb_args bca;
5733 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5734 off_t filesize;
5735 int *pack_fds = NULL;
5736 FILE *f1 = NULL, *f2 = NULL;
5738 fd1 = got_opentempfd();
5739 if (fd1 == -1)
5740 return got_error_from_errno("got_opentempfd");
5742 memset(&bca, 0, sizeof(bca));
5744 #ifndef PROFILE
5745 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5746 NULL) == -1)
5747 err(1, "pledge");
5748 #endif
5750 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5751 switch (ch) {
5752 case 'c':
5753 commit_id_str = optarg;
5754 break;
5755 case 'r':
5756 repo_path = realpath(optarg, NULL);
5757 if (repo_path == NULL)
5758 return got_error_from_errno2("realpath",
5759 optarg);
5760 got_path_strip_trailing_slashes(repo_path);
5761 break;
5762 default:
5763 usage_blame();
5764 /* NOTREACHED */
5768 argc -= optind;
5769 argv += optind;
5771 if (argc == 1)
5772 path = argv[0];
5773 else
5774 usage_blame();
5776 cwd = getcwd(NULL, 0);
5777 if (cwd == NULL) {
5778 error = got_error_from_errno("getcwd");
5779 goto done;
5782 error = got_repo_pack_fds_open(&pack_fds);
5783 if (error != NULL)
5784 goto done;
5786 if (repo_path == NULL) {
5787 error = got_worktree_open(&worktree, cwd,
5788 GOT_WORKTREE_GOT_DIR);
5789 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5790 goto done;
5791 else
5792 error = NULL;
5793 if (worktree) {
5794 repo_path =
5795 strdup(got_worktree_get_repo_path(worktree));
5796 if (repo_path == NULL) {
5797 error = got_error_from_errno("strdup");
5798 if (error)
5799 goto done;
5801 } else {
5802 repo_path = strdup(cwd);
5803 if (repo_path == NULL) {
5804 error = got_error_from_errno("strdup");
5805 goto done;
5810 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5811 if (error != NULL)
5812 goto done;
5814 if (worktree) {
5815 const char *prefix = got_worktree_get_path_prefix(worktree);
5816 char *p;
5818 error = got_worktree_resolve_path(&p, worktree, path);
5819 if (error)
5820 goto done;
5821 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5822 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5823 p) == -1) {
5824 error = got_error_from_errno("asprintf");
5825 free(p);
5826 goto done;
5828 free(p);
5829 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5830 } else {
5831 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5832 if (error)
5833 goto done;
5834 error = got_repo_map_path(&in_repo_path, repo, path);
5836 if (error)
5837 goto done;
5839 if (commit_id_str == NULL) {
5840 struct got_reference *head_ref;
5841 error = got_ref_open(&head_ref, repo, worktree ?
5842 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5843 if (error != NULL)
5844 goto done;
5845 error = got_ref_resolve(&commit_id, repo, head_ref);
5846 got_ref_close(head_ref);
5847 if (error != NULL)
5848 goto done;
5849 } else {
5850 struct got_reflist_head refs;
5852 TAILQ_INIT(&refs);
5853 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5854 NULL);
5855 if (error)
5856 goto done;
5858 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5859 repo, worktree);
5860 if (error != NULL)
5861 goto done;
5862 if (keyword_idstr != NULL)
5863 commit_id_str = keyword_idstr;
5865 error = got_repo_match_object_id(&commit_id, NULL,
5866 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5867 got_ref_list_free(&refs);
5868 if (error)
5869 goto done;
5872 if (worktree) {
5873 /* Release work tree lock. */
5874 got_worktree_close(worktree);
5875 worktree = NULL;
5878 error = got_object_open_as_commit(&commit, repo, commit_id);
5879 if (error)
5880 goto done;
5882 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5883 commit, repo);
5884 if (error)
5885 goto done;
5887 error = got_object_id_by_path(&obj_id, repo, commit,
5888 link_target ? link_target : in_repo_path);
5889 if (error)
5890 goto done;
5892 error = got_object_get_type(&obj_type, repo, obj_id);
5893 if (error)
5894 goto done;
5896 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5897 error = got_error_path(link_target ? link_target : in_repo_path,
5898 GOT_ERR_OBJ_TYPE);
5899 goto done;
5902 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5903 if (error)
5904 goto done;
5905 bca.f = got_opentemp();
5906 if (bca.f == NULL) {
5907 error = got_error_from_errno("got_opentemp");
5908 goto done;
5910 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5911 &bca.line_offsets, bca.f, blob);
5912 if (error || bca.nlines == 0)
5913 goto done;
5915 /* Don't include \n at EOF in the blame line count. */
5916 if (bca.line_offsets[bca.nlines - 1] == filesize)
5917 bca.nlines--;
5919 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5920 if (bca.lines == NULL) {
5921 error = got_error_from_errno("calloc");
5922 goto done;
5924 bca.lineno_cur = 1;
5925 bca.nlines_prec = 0;
5926 i = bca.nlines;
5927 while (i > 0) {
5928 i /= 10;
5929 bca.nlines_prec++;
5931 bca.repo = repo;
5933 fd2 = got_opentempfd();
5934 if (fd2 == -1) {
5935 error = got_error_from_errno("got_opentempfd");
5936 goto done;
5938 fd3 = got_opentempfd();
5939 if (fd3 == -1) {
5940 error = got_error_from_errno("got_opentempfd");
5941 goto done;
5943 f1 = got_opentemp();
5944 if (f1 == NULL) {
5945 error = got_error_from_errno("got_opentemp");
5946 goto done;
5948 f2 = got_opentemp();
5949 if (f2 == NULL) {
5950 error = got_error_from_errno("got_opentemp");
5951 goto done;
5953 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5954 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5955 check_cancelled, NULL, fd2, fd3, f1, f2);
5956 done:
5957 free(keyword_idstr);
5958 free(in_repo_path);
5959 free(link_target);
5960 free(repo_path);
5961 free(cwd);
5962 free(commit_id);
5963 free(obj_id);
5964 if (commit)
5965 got_object_commit_close(commit);
5967 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5968 error = got_error_from_errno("close");
5969 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5970 error = got_error_from_errno("close");
5971 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5972 error = got_error_from_errno("close");
5973 if (f1 && fclose(f1) == EOF && error == NULL)
5974 error = got_error_from_errno("fclose");
5975 if (f2 && fclose(f2) == EOF && error == NULL)
5976 error = got_error_from_errno("fclose");
5978 if (blob)
5979 got_object_blob_close(blob);
5980 if (worktree)
5981 got_worktree_close(worktree);
5982 if (repo) {
5983 const struct got_error *close_err = got_repo_close(repo);
5984 if (error == NULL)
5985 error = close_err;
5987 if (pack_fds) {
5988 const struct got_error *pack_err =
5989 got_repo_pack_fds_close(pack_fds);
5990 if (error == NULL)
5991 error = pack_err;
5993 if (bca.lines) {
5994 for (i = 0; i < bca.nlines; i++) {
5995 struct blame_line *bline = &bca.lines[i];
5996 free(bline->id_str);
5997 free(bline->committer);
5999 free(bca.lines);
6001 free(bca.line_offsets);
6002 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6003 error = got_error_from_errno("fclose");
6004 return error;
6007 __dead static void
6008 usage_tree(void)
6010 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6011 "[path]\n", getprogname());
6012 exit(1);
6015 static const struct got_error *
6016 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6017 const char *root_path, struct got_repository *repo)
6019 const struct got_error *err = NULL;
6020 int is_root_path = (strcmp(path, root_path) == 0);
6021 const char *modestr = "";
6022 mode_t mode = got_tree_entry_get_mode(te);
6023 char *link_target = NULL;
6025 path += strlen(root_path);
6026 while (path[0] == '/')
6027 path++;
6029 if (got_object_tree_entry_is_submodule(te))
6030 modestr = "$";
6031 else if (S_ISLNK(mode)) {
6032 int i;
6034 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6035 if (err)
6036 return err;
6037 for (i = 0; link_target[i] != '\0'; i++) {
6038 if (!isprint((unsigned char)link_target[i]))
6039 link_target[i] = '?';
6042 modestr = "@";
6044 else if (S_ISDIR(mode))
6045 modestr = "/";
6046 else if (mode & S_IXUSR)
6047 modestr = "*";
6049 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6050 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6051 link_target ? " -> ": "", link_target ? link_target : "");
6053 free(link_target);
6054 return NULL;
6057 static const struct got_error *
6058 print_tree(const char *path, struct got_commit_object *commit,
6059 int show_ids, int recurse, const char *root_path,
6060 struct got_repository *repo)
6062 const struct got_error *err = NULL;
6063 struct got_object_id *tree_id = NULL;
6064 struct got_tree_object *tree = NULL;
6065 int nentries, i;
6067 err = got_object_id_by_path(&tree_id, repo, commit, path);
6068 if (err)
6069 goto done;
6071 err = got_object_open_as_tree(&tree, repo, tree_id);
6072 if (err)
6073 goto done;
6074 nentries = got_object_tree_get_nentries(tree);
6075 for (i = 0; i < nentries; i++) {
6076 struct got_tree_entry *te;
6077 char *id = NULL;
6079 if (sigint_received || sigpipe_received)
6080 break;
6082 te = got_object_tree_get_entry(tree, i);
6083 if (show_ids) {
6084 char *id_str;
6085 err = got_object_id_str(&id_str,
6086 got_tree_entry_get_id(te));
6087 if (err)
6088 goto done;
6089 if (asprintf(&id, "%s ", id_str) == -1) {
6090 err = got_error_from_errno("asprintf");
6091 free(id_str);
6092 goto done;
6094 free(id_str);
6096 err = print_entry(te, id, path, root_path, repo);
6097 free(id);
6098 if (err)
6099 goto done;
6101 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6102 char *child_path;
6103 if (asprintf(&child_path, "%s%s%s", path,
6104 path[0] == '/' && path[1] == '\0' ? "" : "/",
6105 got_tree_entry_get_name(te)) == -1) {
6106 err = got_error_from_errno("asprintf");
6107 goto done;
6109 err = print_tree(child_path, commit, show_ids, 1,
6110 root_path, repo);
6111 free(child_path);
6112 if (err)
6113 goto done;
6116 done:
6117 if (tree)
6118 got_object_tree_close(tree);
6119 free(tree_id);
6120 return err;
6123 static const struct got_error *
6124 cmd_tree(int argc, char *argv[])
6126 const struct got_error *error;
6127 struct got_repository *repo = NULL;
6128 struct got_worktree *worktree = NULL;
6129 const char *path, *refname = NULL;
6130 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6131 struct got_object_id *commit_id = NULL;
6132 struct got_commit_object *commit = NULL;
6133 char *commit_id_str = NULL, *keyword_idstr = NULL;
6134 int show_ids = 0, recurse = 0;
6135 int ch;
6136 int *pack_fds = NULL;
6138 #ifndef PROFILE
6139 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6140 NULL) == -1)
6141 err(1, "pledge");
6142 #endif
6144 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6145 switch (ch) {
6146 case 'c':
6147 commit_id_str = optarg;
6148 break;
6149 case 'i':
6150 show_ids = 1;
6151 break;
6152 case 'R':
6153 recurse = 1;
6154 break;
6155 case 'r':
6156 repo_path = realpath(optarg, NULL);
6157 if (repo_path == NULL)
6158 return got_error_from_errno2("realpath",
6159 optarg);
6160 got_path_strip_trailing_slashes(repo_path);
6161 break;
6162 default:
6163 usage_tree();
6164 /* NOTREACHED */
6168 argc -= optind;
6169 argv += optind;
6171 if (argc == 1)
6172 path = argv[0];
6173 else if (argc > 1)
6174 usage_tree();
6175 else
6176 path = NULL;
6178 cwd = getcwd(NULL, 0);
6179 if (cwd == NULL) {
6180 error = got_error_from_errno("getcwd");
6181 goto done;
6184 error = got_repo_pack_fds_open(&pack_fds);
6185 if (error != NULL)
6186 goto done;
6188 if (repo_path == NULL) {
6189 error = got_worktree_open(&worktree, cwd,
6190 GOT_WORKTREE_GOT_DIR);
6191 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6192 goto done;
6193 else
6194 error = NULL;
6195 if (worktree) {
6196 repo_path =
6197 strdup(got_worktree_get_repo_path(worktree));
6198 if (repo_path == NULL)
6199 error = got_error_from_errno("strdup");
6200 if (error)
6201 goto done;
6202 } else {
6203 repo_path = strdup(cwd);
6204 if (repo_path == NULL) {
6205 error = got_error_from_errno("strdup");
6206 goto done;
6211 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6212 if (error != NULL)
6213 goto done;
6215 if (worktree) {
6216 const char *prefix = got_worktree_get_path_prefix(worktree);
6217 char *p;
6219 if (path == NULL || got_path_is_root_dir(path))
6220 path = "";
6221 error = got_worktree_resolve_path(&p, worktree, path);
6222 if (error)
6223 goto done;
6224 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6225 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6226 p) == -1) {
6227 error = got_error_from_errno("asprintf");
6228 free(p);
6229 goto done;
6231 free(p);
6232 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6233 if (error)
6234 goto done;
6235 } else {
6236 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6237 if (error)
6238 goto done;
6239 if (path == NULL)
6240 path = "/";
6241 error = got_repo_map_path(&in_repo_path, repo, path);
6242 if (error != NULL)
6243 goto done;
6246 if (commit_id_str == NULL) {
6247 struct got_reference *head_ref;
6248 if (worktree)
6249 refname = got_worktree_get_head_ref_name(worktree);
6250 else
6251 refname = GOT_REF_HEAD;
6252 error = got_ref_open(&head_ref, repo, refname, 0);
6253 if (error != NULL)
6254 goto done;
6255 error = got_ref_resolve(&commit_id, repo, head_ref);
6256 got_ref_close(head_ref);
6257 if (error != NULL)
6258 goto done;
6259 } else {
6260 struct got_reflist_head refs;
6262 TAILQ_INIT(&refs);
6263 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6264 NULL);
6265 if (error)
6266 goto done;
6268 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6269 repo, worktree);
6270 if (error != NULL)
6271 goto done;
6272 if (keyword_idstr != NULL)
6273 commit_id_str = keyword_idstr;
6275 error = got_repo_match_object_id(&commit_id, NULL,
6276 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6277 got_ref_list_free(&refs);
6278 if (error)
6279 goto done;
6282 if (worktree) {
6283 /* Release work tree lock. */
6284 got_worktree_close(worktree);
6285 worktree = NULL;
6288 error = got_object_open_as_commit(&commit, repo, commit_id);
6289 if (error)
6290 goto done;
6292 error = print_tree(in_repo_path, commit, show_ids, recurse,
6293 in_repo_path, repo);
6294 done:
6295 free(keyword_idstr);
6296 free(in_repo_path);
6297 free(repo_path);
6298 free(cwd);
6299 free(commit_id);
6300 if (commit)
6301 got_object_commit_close(commit);
6302 if (worktree)
6303 got_worktree_close(worktree);
6304 if (repo) {
6305 const struct got_error *close_err = got_repo_close(repo);
6306 if (error == NULL)
6307 error = close_err;
6309 if (pack_fds) {
6310 const struct got_error *pack_err =
6311 got_repo_pack_fds_close(pack_fds);
6312 if (error == NULL)
6313 error = pack_err;
6315 return error;
6318 __dead static void
6319 usage_status(void)
6321 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6322 "[-s status-codes] [path ...]\n", getprogname());
6323 exit(1);
6326 struct got_status_arg {
6327 char *status_codes;
6328 int suppress;
6331 static const struct got_error *
6332 print_status(void *arg, unsigned char status, unsigned char staged_status,
6333 const char *path, struct got_object_id *blob_id,
6334 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6335 int dirfd, const char *de_name)
6337 struct got_status_arg *st = arg;
6339 if (status == staged_status && (status == GOT_STATUS_DELETE))
6340 status = GOT_STATUS_NO_CHANGE;
6341 if (st != NULL && st->status_codes) {
6342 size_t ncodes = strlen(st->status_codes);
6343 int i, j = 0;
6345 for (i = 0; i < ncodes ; i++) {
6346 if (st->suppress) {
6347 if (status == st->status_codes[i] ||
6348 staged_status == st->status_codes[i]) {
6349 j++;
6350 continue;
6352 } else {
6353 if (status == st->status_codes[i] ||
6354 staged_status == st->status_codes[i])
6355 break;
6359 if (st->suppress && j == 0)
6360 goto print;
6362 if (i == ncodes)
6363 return NULL;
6365 print:
6366 printf("%c%c %s\n", status, staged_status, path);
6367 return NULL;
6370 static const struct got_error *
6371 cmd_status(int argc, char *argv[])
6373 const struct got_error *error = NULL;
6374 struct got_repository *repo = NULL;
6375 struct got_worktree *worktree = NULL;
6376 struct got_status_arg st;
6377 char *cwd = NULL;
6378 struct got_pathlist_head paths;
6379 int ch, i, no_ignores = 0;
6380 int *pack_fds = NULL;
6382 TAILQ_INIT(&paths);
6384 memset(&st, 0, sizeof(st));
6385 st.status_codes = NULL;
6386 st.suppress = 0;
6388 #ifndef PROFILE
6389 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6390 NULL) == -1)
6391 err(1, "pledge");
6392 #endif
6394 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6395 switch (ch) {
6396 case 'I':
6397 no_ignores = 1;
6398 break;
6399 case 'S':
6400 if (st.status_codes != NULL && st.suppress == 0)
6401 option_conflict('S', 's');
6402 st.suppress = 1;
6403 /* fallthrough */
6404 case 's':
6405 for (i = 0; optarg[i] != '\0'; i++) {
6406 switch (optarg[i]) {
6407 case GOT_STATUS_MODIFY:
6408 case GOT_STATUS_ADD:
6409 case GOT_STATUS_DELETE:
6410 case GOT_STATUS_CONFLICT:
6411 case GOT_STATUS_MISSING:
6412 case GOT_STATUS_OBSTRUCTED:
6413 case GOT_STATUS_UNVERSIONED:
6414 case GOT_STATUS_MODE_CHANGE:
6415 case GOT_STATUS_NONEXISTENT:
6416 break;
6417 default:
6418 errx(1, "invalid status code '%c'",
6419 optarg[i]);
6422 if (ch == 's' && st.suppress)
6423 option_conflict('s', 'S');
6424 st.status_codes = optarg;
6425 break;
6426 default:
6427 usage_status();
6428 /* NOTREACHED */
6432 argc -= optind;
6433 argv += optind;
6435 cwd = getcwd(NULL, 0);
6436 if (cwd == NULL) {
6437 error = got_error_from_errno("getcwd");
6438 goto done;
6441 error = got_repo_pack_fds_open(&pack_fds);
6442 if (error != NULL)
6443 goto done;
6445 error = got_worktree_open(&worktree, cwd,
6446 GOT_WORKTREE_GOT_DIR);
6447 if (error) {
6448 if (error->code == GOT_ERR_NOT_WORKTREE)
6449 error = wrap_not_worktree_error(error, "status", cwd);
6450 goto done;
6453 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6454 NULL, pack_fds);
6455 if (error != NULL)
6456 goto done;
6458 error = apply_unveil(got_repo_get_path(repo), 1,
6459 got_worktree_get_root_path(worktree));
6460 if (error)
6461 goto done;
6463 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6464 if (error)
6465 goto done;
6467 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6468 print_status, &st, check_cancelled, NULL);
6469 done:
6470 if (pack_fds) {
6471 const struct got_error *pack_err =
6472 got_repo_pack_fds_close(pack_fds);
6473 if (error == NULL)
6474 error = pack_err;
6476 if (repo) {
6477 const struct got_error *close_err = got_repo_close(repo);
6478 if (error == NULL)
6479 error = close_err;
6482 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6483 free(cwd);
6484 return error;
6487 __dead static void
6488 usage_ref(void)
6490 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6491 "[-s reference] [name]\n", getprogname());
6492 exit(1);
6495 static const struct got_error *
6496 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6498 static const struct got_error *err = NULL;
6499 struct got_reflist_head refs;
6500 struct got_reflist_entry *re;
6502 TAILQ_INIT(&refs);
6503 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6504 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6505 repo);
6506 if (err)
6507 return err;
6509 TAILQ_FOREACH(re, &refs, entry) {
6510 char *refstr;
6511 refstr = got_ref_to_str(re->ref);
6512 if (refstr == NULL) {
6513 err = got_error_from_errno("got_ref_to_str");
6514 break;
6516 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6517 free(refstr);
6520 got_ref_list_free(&refs);
6521 return err;
6524 static const struct got_error *
6525 delete_ref_by_name(struct got_repository *repo, const char *refname)
6527 const struct got_error *err;
6528 struct got_reference *ref;
6530 err = got_ref_open(&ref, repo, refname, 0);
6531 if (err)
6532 return err;
6534 err = delete_ref(repo, ref);
6535 got_ref_close(ref);
6536 return err;
6539 static const struct got_error *
6540 add_ref(struct got_repository *repo, const char *refname, const char *target)
6542 const struct got_error *err = NULL;
6543 struct got_object_id *id = NULL;
6544 struct got_reference *ref = NULL;
6545 struct got_reflist_head refs;
6548 * Don't let the user create a reference name with a leading '-'.
6549 * While technically a valid reference name, this case is usually
6550 * an unintended typo.
6552 if (refname[0] == '-')
6553 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6555 TAILQ_INIT(&refs);
6556 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6557 if (err)
6558 goto done;
6559 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6560 &refs, repo);
6561 got_ref_list_free(&refs);
6562 if (err)
6563 goto done;
6565 err = got_ref_alloc(&ref, refname, id);
6566 if (err)
6567 goto done;
6569 err = got_ref_write(ref, repo);
6570 done:
6571 if (ref)
6572 got_ref_close(ref);
6573 free(id);
6574 return err;
6577 static const struct got_error *
6578 add_symref(struct got_repository *repo, const char *refname, const char *target)
6580 const struct got_error *err = NULL;
6581 struct got_reference *ref = NULL;
6582 struct got_reference *target_ref = NULL;
6585 * Don't let the user create a reference name with a leading '-'.
6586 * While technically a valid reference name, this case is usually
6587 * an unintended typo.
6589 if (refname[0] == '-')
6590 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6592 err = got_ref_open(&target_ref, repo, target, 0);
6593 if (err)
6594 return err;
6596 err = got_ref_alloc_symref(&ref, refname, target_ref);
6597 if (err)
6598 goto done;
6600 err = got_ref_write(ref, repo);
6601 done:
6602 if (target_ref)
6603 got_ref_close(target_ref);
6604 if (ref)
6605 got_ref_close(ref);
6606 return err;
6609 static const struct got_error *
6610 cmd_ref(int argc, char *argv[])
6612 const struct got_error *error = NULL;
6613 struct got_repository *repo = NULL;
6614 struct got_worktree *worktree = NULL;
6615 char *cwd = NULL, *repo_path = NULL;
6616 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6617 const char *obj_arg = NULL, *symref_target= NULL;
6618 char *refname = NULL, *keyword_idstr = NULL;
6619 int *pack_fds = NULL;
6621 #ifndef PROFILE
6622 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6623 "sendfd unveil", NULL) == -1)
6624 err(1, "pledge");
6625 #endif
6627 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6628 switch (ch) {
6629 case 'c':
6630 obj_arg = optarg;
6631 break;
6632 case 'd':
6633 do_delete = 1;
6634 break;
6635 case 'l':
6636 do_list = 1;
6637 break;
6638 case 'r':
6639 repo_path = realpath(optarg, NULL);
6640 if (repo_path == NULL)
6641 return got_error_from_errno2("realpath",
6642 optarg);
6643 got_path_strip_trailing_slashes(repo_path);
6644 break;
6645 case 's':
6646 symref_target = optarg;
6647 break;
6648 case 't':
6649 sort_by_time = 1;
6650 break;
6651 default:
6652 usage_ref();
6653 /* NOTREACHED */
6657 if (obj_arg && do_list)
6658 option_conflict('c', 'l');
6659 if (obj_arg && do_delete)
6660 option_conflict('c', 'd');
6661 if (obj_arg && symref_target)
6662 option_conflict('c', 's');
6663 if (symref_target && do_delete)
6664 option_conflict('s', 'd');
6665 if (symref_target && do_list)
6666 option_conflict('s', 'l');
6667 if (do_delete && do_list)
6668 option_conflict('d', 'l');
6669 if (sort_by_time && !do_list)
6670 errx(1, "-t option requires -l option");
6672 argc -= optind;
6673 argv += optind;
6675 if (do_list) {
6676 if (argc != 0 && argc != 1)
6677 usage_ref();
6678 if (argc == 1) {
6679 refname = strdup(argv[0]);
6680 if (refname == NULL) {
6681 error = got_error_from_errno("strdup");
6682 goto done;
6685 } else {
6686 if (argc != 1)
6687 usage_ref();
6688 refname = strdup(argv[0]);
6689 if (refname == NULL) {
6690 error = got_error_from_errno("strdup");
6691 goto done;
6695 if (refname)
6696 got_path_strip_trailing_slashes(refname);
6698 cwd = getcwd(NULL, 0);
6699 if (cwd == NULL) {
6700 error = got_error_from_errno("getcwd");
6701 goto done;
6704 error = got_repo_pack_fds_open(&pack_fds);
6705 if (error != NULL)
6706 goto done;
6708 if (repo_path == NULL) {
6709 error = got_worktree_open(&worktree, cwd,
6710 GOT_WORKTREE_GOT_DIR);
6711 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6712 goto done;
6713 else
6714 error = NULL;
6715 if (worktree) {
6716 repo_path =
6717 strdup(got_worktree_get_repo_path(worktree));
6718 if (repo_path == NULL)
6719 error = got_error_from_errno("strdup");
6720 if (error)
6721 goto done;
6722 } else {
6723 repo_path = strdup(cwd);
6724 if (repo_path == NULL) {
6725 error = got_error_from_errno("strdup");
6726 goto done;
6731 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6732 if (error != NULL)
6733 goto done;
6735 #ifndef PROFILE
6736 if (do_list) {
6737 /* Remove "cpath" promise. */
6738 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6739 NULL) == -1)
6740 err(1, "pledge");
6742 #endif
6744 error = apply_unveil(got_repo_get_path(repo), do_list,
6745 worktree ? got_worktree_get_root_path(worktree) : NULL);
6746 if (error)
6747 goto done;
6749 if (do_list)
6750 error = list_refs(repo, refname, sort_by_time);
6751 else if (do_delete)
6752 error = delete_ref_by_name(repo, refname);
6753 else if (symref_target)
6754 error = add_symref(repo, refname, symref_target);
6755 else {
6756 if (obj_arg == NULL)
6757 usage_ref();
6759 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6760 repo, worktree);
6761 if (error != NULL)
6762 goto done;
6763 if (keyword_idstr != NULL)
6764 obj_arg = keyword_idstr;
6766 error = add_ref(repo, refname, obj_arg);
6768 done:
6769 free(refname);
6770 if (repo) {
6771 const struct got_error *close_err = got_repo_close(repo);
6772 if (error == NULL)
6773 error = close_err;
6775 if (worktree)
6776 got_worktree_close(worktree);
6777 if (pack_fds) {
6778 const struct got_error *pack_err =
6779 got_repo_pack_fds_close(pack_fds);
6780 if (error == NULL)
6781 error = pack_err;
6783 free(cwd);
6784 free(repo_path);
6785 free(keyword_idstr);
6786 return error;
6789 __dead static void
6790 usage_branch(void)
6792 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6793 "[-r repository-path] [name]\n", getprogname());
6794 exit(1);
6797 static const struct got_error *
6798 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6799 struct got_reference *ref)
6801 const struct got_error *err = NULL;
6802 const char *refname;
6803 char *refstr;
6804 char marker = ' ';
6806 refname = got_ref_get_name(ref);
6807 if (worktree && strcmp(refname,
6808 got_worktree_get_head_ref_name(worktree)) == 0) {
6809 err = got_worktree_get_state(&marker, repo, worktree,
6810 check_cancelled, NULL);
6811 if (err != NULL)
6812 return err;
6815 if (strncmp(refname, "refs/heads/", 11) == 0)
6816 refname += 11;
6817 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6818 refname += 18;
6819 if (strncmp(refname, "refs/remotes/", 13) == 0)
6820 refname += 13;
6822 refstr = got_ref_to_str(ref);
6823 if (refstr == NULL)
6824 return got_error_from_errno("got_ref_to_str");
6826 printf("%c %s: %s\n", marker, refname, refstr);
6827 free(refstr);
6828 return NULL;
6831 static const struct got_error *
6832 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6834 const char *refname;
6836 if (worktree == NULL)
6837 return got_error(GOT_ERR_NOT_WORKTREE);
6839 refname = got_worktree_get_head_ref_name(worktree);
6841 if (strncmp(refname, "refs/heads/", 11) == 0)
6842 refname += 11;
6843 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6844 refname += 18;
6846 printf("%s\n", refname);
6848 return NULL;
6851 static const struct got_error *
6852 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6853 int sort_by_time)
6855 static const struct got_error *err = NULL;
6856 struct got_reflist_head refs;
6857 struct got_reflist_entry *re;
6858 struct got_reference *temp_ref = NULL;
6859 int rebase_in_progress, histedit_in_progress;
6861 TAILQ_INIT(&refs);
6863 if (worktree) {
6864 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6865 worktree);
6866 if (err)
6867 return err;
6869 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6870 worktree);
6871 if (err)
6872 return err;
6874 if (rebase_in_progress || histedit_in_progress) {
6875 err = got_ref_open(&temp_ref, repo,
6876 got_worktree_get_head_ref_name(worktree), 0);
6877 if (err)
6878 return err;
6879 list_branch(repo, worktree, temp_ref);
6880 got_ref_close(temp_ref);
6884 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6885 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6886 repo);
6887 if (err)
6888 return err;
6890 TAILQ_FOREACH(re, &refs, entry)
6891 list_branch(repo, worktree, re->ref);
6893 got_ref_list_free(&refs);
6895 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6896 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6897 repo);
6898 if (err)
6899 return err;
6901 TAILQ_FOREACH(re, &refs, entry)
6902 list_branch(repo, worktree, re->ref);
6904 got_ref_list_free(&refs);
6906 return NULL;
6909 static const struct got_error *
6910 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6911 const char *branch_name)
6913 const struct got_error *err = NULL;
6914 struct got_reference *ref = NULL;
6915 char *refname, *remote_refname = NULL;
6917 if (strncmp(branch_name, "refs/", 5) == 0)
6918 branch_name += 5;
6919 if (strncmp(branch_name, "heads/", 6) == 0)
6920 branch_name += 6;
6921 else if (strncmp(branch_name, "remotes/", 8) == 0)
6922 branch_name += 8;
6924 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6925 return got_error_from_errno("asprintf");
6927 if (asprintf(&remote_refname, "refs/remotes/%s",
6928 branch_name) == -1) {
6929 err = got_error_from_errno("asprintf");
6930 goto done;
6933 err = got_ref_open(&ref, repo, refname, 0);
6934 if (err) {
6935 const struct got_error *err2;
6936 if (err->code != GOT_ERR_NOT_REF)
6937 goto done;
6939 * Keep 'err' intact such that if neither branch exists
6940 * we report "refs/heads" rather than "refs/remotes" in
6941 * our error message.
6943 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6944 if (err2)
6945 goto done;
6946 err = NULL;
6949 if (worktree &&
6950 strcmp(got_worktree_get_head_ref_name(worktree),
6951 got_ref_get_name(ref)) == 0) {
6952 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6953 "will not delete this work tree's current branch");
6954 goto done;
6957 err = delete_ref(repo, ref);
6958 done:
6959 if (ref)
6960 got_ref_close(ref);
6961 free(refname);
6962 free(remote_refname);
6963 return err;
6966 static const struct got_error *
6967 add_branch(struct got_repository *repo, const char *branch_name,
6968 struct got_object_id *base_commit_id)
6970 const struct got_error *err = NULL;
6971 struct got_reference *ref = NULL;
6972 char *refname = NULL;
6975 * Don't let the user create a branch name with a leading '-'.
6976 * While technically a valid reference name, this case is usually
6977 * an unintended typo.
6979 if (branch_name[0] == '-')
6980 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6982 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6983 branch_name += 11;
6985 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6986 err = got_error_from_errno("asprintf");
6987 goto done;
6990 err = got_ref_open(&ref, repo, refname, 0);
6991 if (err == NULL) {
6992 err = got_error(GOT_ERR_BRANCH_EXISTS);
6993 goto done;
6994 } else if (err->code != GOT_ERR_NOT_REF)
6995 goto done;
6997 err = got_ref_alloc(&ref, refname, base_commit_id);
6998 if (err)
6999 goto done;
7001 err = got_ref_write(ref, repo);
7002 done:
7003 if (ref)
7004 got_ref_close(ref);
7005 free(refname);
7006 return err;
7009 static const struct got_error *
7010 cmd_branch(int argc, char *argv[])
7012 const struct got_error *error = NULL;
7013 struct got_repository *repo = NULL;
7014 struct got_worktree *worktree = NULL;
7015 char *cwd = NULL, *repo_path = NULL;
7016 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7017 const char *delref = NULL, *commit_id_arg = NULL;
7018 struct got_reference *ref = NULL;
7019 struct got_pathlist_head paths;
7020 struct got_object_id *commit_id = NULL;
7021 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7022 int *pack_fds = NULL;
7024 TAILQ_INIT(&paths);
7026 #ifndef PROFILE
7027 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7028 "sendfd unveil", NULL) == -1)
7029 err(1, "pledge");
7030 #endif
7032 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7033 switch (ch) {
7034 case 'c':
7035 commit_id_arg = optarg;
7036 break;
7037 case 'd':
7038 delref = optarg;
7039 break;
7040 case 'l':
7041 do_list = 1;
7042 break;
7043 case 'n':
7044 do_update = 0;
7045 break;
7046 case 'r':
7047 repo_path = realpath(optarg, NULL);
7048 if (repo_path == NULL)
7049 return got_error_from_errno2("realpath",
7050 optarg);
7051 got_path_strip_trailing_slashes(repo_path);
7052 break;
7053 case 't':
7054 sort_by_time = 1;
7055 break;
7056 default:
7057 usage_branch();
7058 /* NOTREACHED */
7062 if (do_list && delref)
7063 option_conflict('l', 'd');
7064 if (sort_by_time && !do_list)
7065 errx(1, "-t option requires -l option");
7067 argc -= optind;
7068 argv += optind;
7070 if (!do_list && !delref && argc == 0)
7071 do_show = 1;
7073 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7074 errx(1, "-c option can only be used when creating a branch");
7076 if (do_list || delref) {
7077 if (argc > 0)
7078 usage_branch();
7079 } else if (!do_show && argc != 1)
7080 usage_branch();
7082 cwd = getcwd(NULL, 0);
7083 if (cwd == NULL) {
7084 error = got_error_from_errno("getcwd");
7085 goto done;
7088 error = got_repo_pack_fds_open(&pack_fds);
7089 if (error != NULL)
7090 goto done;
7092 if (repo_path == NULL) {
7093 error = got_worktree_open(&worktree, cwd,
7094 GOT_WORKTREE_GOT_DIR);
7095 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7096 goto done;
7097 else
7098 error = NULL;
7099 if (worktree) {
7100 repo_path =
7101 strdup(got_worktree_get_repo_path(worktree));
7102 if (repo_path == NULL)
7103 error = got_error_from_errno("strdup");
7104 if (error)
7105 goto done;
7106 } else {
7107 repo_path = strdup(cwd);
7108 if (repo_path == NULL) {
7109 error = got_error_from_errno("strdup");
7110 goto done;
7115 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7116 if (error != NULL)
7117 goto done;
7119 #ifndef PROFILE
7120 if (do_list || do_show) {
7121 /* Remove "cpath" promise. */
7122 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7123 NULL) == -1)
7124 err(1, "pledge");
7126 #endif
7128 error = apply_unveil(got_repo_get_path(repo), do_list,
7129 worktree ? got_worktree_get_root_path(worktree) : NULL);
7130 if (error)
7131 goto done;
7133 if (do_show)
7134 error = show_current_branch(repo, worktree);
7135 else if (do_list)
7136 error = list_branches(repo, worktree, sort_by_time);
7137 else if (delref)
7138 error = delete_branch(repo, worktree, delref);
7139 else {
7140 struct got_reflist_head refs;
7141 TAILQ_INIT(&refs);
7142 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7143 NULL);
7144 if (error)
7145 goto done;
7146 if (commit_id_arg == NULL)
7147 commit_id_arg = worktree ?
7148 got_worktree_get_head_ref_name(worktree) :
7149 GOT_REF_HEAD;
7150 else {
7151 error = got_keyword_to_idstr(&keyword_idstr,
7152 commit_id_arg, repo, worktree);
7153 if (error != NULL)
7154 goto done;
7155 if (keyword_idstr != NULL)
7156 commit_id_arg = keyword_idstr;
7158 error = got_repo_match_object_id(&commit_id, NULL,
7159 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7160 got_ref_list_free(&refs);
7161 if (error)
7162 goto done;
7163 error = add_branch(repo, argv[0], commit_id);
7164 if (error)
7165 goto done;
7166 if (worktree && do_update) {
7167 struct got_update_progress_arg upa;
7168 char *branch_refname = NULL;
7170 error = got_object_id_str(&commit_id_str, commit_id);
7171 if (error)
7172 goto done;
7173 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7174 worktree);
7175 if (error)
7176 goto done;
7177 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7178 == -1) {
7179 error = got_error_from_errno("asprintf");
7180 goto done;
7182 error = got_ref_open(&ref, repo, branch_refname, 0);
7183 free(branch_refname);
7184 if (error)
7185 goto done;
7186 error = switch_head_ref(ref, commit_id, worktree,
7187 repo);
7188 if (error)
7189 goto done;
7190 error = got_worktree_set_base_commit_id(worktree, repo,
7191 commit_id);
7192 if (error)
7193 goto done;
7194 memset(&upa, 0, sizeof(upa));
7195 error = got_worktree_checkout_files(worktree, &paths,
7196 repo, update_progress, &upa, check_cancelled,
7197 NULL);
7198 if (error)
7199 goto done;
7200 if (upa.did_something) {
7201 printf("Updated to %s: %s\n",
7202 got_worktree_get_head_ref_name(worktree),
7203 commit_id_str);
7205 print_update_progress_stats(&upa);
7208 done:
7209 free(keyword_idstr);
7210 if (ref)
7211 got_ref_close(ref);
7212 if (repo) {
7213 const struct got_error *close_err = got_repo_close(repo);
7214 if (error == NULL)
7215 error = close_err;
7217 if (worktree)
7218 got_worktree_close(worktree);
7219 if (pack_fds) {
7220 const struct got_error *pack_err =
7221 got_repo_pack_fds_close(pack_fds);
7222 if (error == NULL)
7223 error = pack_err;
7225 free(cwd);
7226 free(repo_path);
7227 free(commit_id);
7228 free(commit_id_str);
7229 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7230 return error;
7234 __dead static void
7235 usage_tag(void)
7237 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7238 "[-r repository-path] [-s signer-id] name\n", getprogname());
7239 exit(1);
7242 #if 0
7243 static const struct got_error *
7244 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7246 const struct got_error *err = NULL;
7247 struct got_reflist_entry *re, *se, *new;
7248 struct got_object_id *re_id, *se_id;
7249 struct got_tag_object *re_tag, *se_tag;
7250 time_t re_time, se_time;
7252 STAILQ_FOREACH(re, tags, entry) {
7253 se = STAILQ_FIRST(sorted);
7254 if (se == NULL) {
7255 err = got_reflist_entry_dup(&new, re);
7256 if (err)
7257 return err;
7258 STAILQ_INSERT_HEAD(sorted, new, entry);
7259 continue;
7260 } else {
7261 err = got_ref_resolve(&re_id, repo, re->ref);
7262 if (err)
7263 break;
7264 err = got_object_open_as_tag(&re_tag, repo, re_id);
7265 free(re_id);
7266 if (err)
7267 break;
7268 re_time = got_object_tag_get_tagger_time(re_tag);
7269 got_object_tag_close(re_tag);
7272 while (se) {
7273 err = got_ref_resolve(&se_id, repo, re->ref);
7274 if (err)
7275 break;
7276 err = got_object_open_as_tag(&se_tag, repo, se_id);
7277 free(se_id);
7278 if (err)
7279 break;
7280 se_time = got_object_tag_get_tagger_time(se_tag);
7281 got_object_tag_close(se_tag);
7283 if (se_time > re_time) {
7284 err = got_reflist_entry_dup(&new, re);
7285 if (err)
7286 return err;
7287 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7288 break;
7290 se = STAILQ_NEXT(se, entry);
7291 continue;
7294 done:
7295 return err;
7297 #endif
7299 static const struct got_error *
7300 get_tag_refname(char **refname, const char *tag_name)
7302 const struct got_error *err;
7304 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7305 *refname = strdup(tag_name);
7306 if (*refname == NULL)
7307 return got_error_from_errno("strdup");
7308 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7309 err = got_error_from_errno("asprintf");
7310 *refname = NULL;
7311 return err;
7314 return NULL;
7317 static const struct got_error *
7318 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7319 const char *allowed_signers, const char *revoked_signers, int verbosity)
7321 static const struct got_error *err = NULL;
7322 struct got_reflist_head refs;
7323 struct got_reflist_entry *re;
7324 char *wanted_refname = NULL;
7325 int bad_sigs = 0;
7327 TAILQ_INIT(&refs);
7329 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7330 if (err)
7331 return err;
7333 if (tag_name) {
7334 struct got_reference *ref;
7335 err = get_tag_refname(&wanted_refname, tag_name);
7336 if (err)
7337 goto done;
7338 /* Wanted tag reference should exist. */
7339 err = got_ref_open(&ref, repo, wanted_refname, 0);
7340 if (err)
7341 goto done;
7342 got_ref_close(ref);
7345 TAILQ_FOREACH(re, &refs, entry) {
7346 const char *refname;
7347 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7348 char datebuf[26];
7349 const char *tagger, *ssh_sig = NULL;
7350 char *sig_msg = NULL;
7351 time_t tagger_time;
7352 struct got_object_id *id;
7353 struct got_tag_object *tag;
7354 struct got_commit_object *commit = NULL;
7356 refname = got_ref_get_name(re->ref);
7357 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7358 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7359 continue;
7360 refname += 10;
7361 refstr = got_ref_to_str(re->ref);
7362 if (refstr == NULL) {
7363 err = got_error_from_errno("got_ref_to_str");
7364 break;
7367 err = got_ref_resolve(&id, repo, re->ref);
7368 if (err)
7369 break;
7370 err = got_object_open_as_tag(&tag, repo, id);
7371 if (err) {
7372 if (err->code != GOT_ERR_OBJ_TYPE) {
7373 free(id);
7374 break;
7376 /* "lightweight" tag */
7377 err = got_object_open_as_commit(&commit, repo, id);
7378 if (err) {
7379 free(id);
7380 break;
7382 tagger = got_object_commit_get_committer(commit);
7383 tagger_time =
7384 got_object_commit_get_committer_time(commit);
7385 err = got_object_id_str(&id_str, id);
7386 free(id);
7387 if (err)
7388 break;
7389 } else {
7390 free(id);
7391 tagger = got_object_tag_get_tagger(tag);
7392 tagger_time = got_object_tag_get_tagger_time(tag);
7393 err = got_object_id_str(&id_str,
7394 got_object_tag_get_object_id(tag));
7395 if (err)
7396 break;
7399 if (tag && verify_tags) {
7400 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7401 got_object_tag_get_message(tag));
7402 if (ssh_sig && allowed_signers == NULL) {
7403 err = got_error_msg(
7404 GOT_ERR_VERIFY_TAG_SIGNATURE,
7405 "SSH signature verification requires "
7406 "setting allowed_signers in "
7407 "got.conf(5)");
7408 break;
7412 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7413 free(refstr);
7414 printf("from: %s\n", tagger);
7415 datestr = get_datestr(&tagger_time, datebuf);
7416 if (datestr)
7417 printf("date: %s UTC\n", datestr);
7418 if (commit)
7419 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7420 else {
7421 switch (got_object_tag_get_object_type(tag)) {
7422 case GOT_OBJ_TYPE_BLOB:
7423 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7424 id_str);
7425 break;
7426 case GOT_OBJ_TYPE_TREE:
7427 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7428 id_str);
7429 break;
7430 case GOT_OBJ_TYPE_COMMIT:
7431 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7432 id_str);
7433 break;
7434 case GOT_OBJ_TYPE_TAG:
7435 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7436 id_str);
7437 break;
7438 default:
7439 break;
7442 free(id_str);
7444 if (ssh_sig) {
7445 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7446 allowed_signers, revoked_signers, verbosity);
7447 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7448 bad_sigs = 1;
7449 else if (err)
7450 break;
7451 printf("signature: %s", sig_msg);
7452 free(sig_msg);
7453 sig_msg = NULL;
7456 if (commit) {
7457 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7458 if (err)
7459 break;
7460 got_object_commit_close(commit);
7461 } else {
7462 tagmsg0 = strdup(got_object_tag_get_message(tag));
7463 got_object_tag_close(tag);
7464 if (tagmsg0 == NULL) {
7465 err = got_error_from_errno("strdup");
7466 break;
7470 tagmsg = tagmsg0;
7471 do {
7472 line = strsep(&tagmsg, "\n");
7473 if (line)
7474 printf(" %s\n", line);
7475 } while (line);
7476 free(tagmsg0);
7478 done:
7479 got_ref_list_free(&refs);
7480 free(wanted_refname);
7482 if (err == NULL && bad_sigs)
7483 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7484 return err;
7487 static const struct got_error *
7488 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7489 const char *tag_name, const char *repo_path)
7491 const struct got_error *err = NULL;
7492 char *template = NULL, *initial_content = NULL;
7493 char *editor = NULL;
7494 int initial_content_len;
7495 int fd = -1;
7497 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7498 err = got_error_from_errno("asprintf");
7499 goto done;
7502 initial_content_len = asprintf(&initial_content,
7503 "\n# tagging commit %s as %s\n",
7504 commit_id_str, tag_name);
7505 if (initial_content_len == -1) {
7506 err = got_error_from_errno("asprintf");
7507 goto done;
7510 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7511 if (err)
7512 goto done;
7514 if (write(fd, initial_content, initial_content_len) == -1) {
7515 err = got_error_from_errno2("write", *tagmsg_path);
7516 goto done;
7518 if (close(fd) == -1) {
7519 err = got_error_from_errno2("close", *tagmsg_path);
7520 goto done;
7522 fd = -1;
7524 err = get_editor(&editor);
7525 if (err)
7526 goto done;
7527 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7528 initial_content_len, 1);
7529 done:
7530 free(initial_content);
7531 free(template);
7532 free(editor);
7534 if (fd != -1 && close(fd) == -1 && err == NULL)
7535 err = got_error_from_errno2("close", *tagmsg_path);
7537 if (err) {
7538 free(*tagmsg);
7539 *tagmsg = NULL;
7541 return err;
7544 static const struct got_error *
7545 add_tag(struct got_repository *repo, const char *tagger,
7546 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7547 const char *signer_id, int verbosity)
7549 const struct got_error *err = NULL;
7550 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7551 char *label = NULL, *commit_id_str = NULL;
7552 struct got_reference *ref = NULL;
7553 char *refname = NULL, *tagmsg = NULL;
7554 char *tagmsg_path = NULL, *tag_id_str = NULL;
7555 int preserve_tagmsg = 0;
7556 struct got_reflist_head refs;
7558 TAILQ_INIT(&refs);
7561 * Don't let the user create a tag name with a leading '-'.
7562 * While technically a valid reference name, this case is usually
7563 * an unintended typo.
7565 if (tag_name[0] == '-')
7566 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7568 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7569 if (err)
7570 goto done;
7572 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7573 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7574 if (err)
7575 goto done;
7577 err = got_object_id_str(&commit_id_str, commit_id);
7578 if (err)
7579 goto done;
7581 err = get_tag_refname(&refname, tag_name);
7582 if (err)
7583 goto done;
7584 if (strncmp("refs/tags/", tag_name, 10) == 0)
7585 tag_name += 10;
7587 err = got_ref_open(&ref, repo, refname, 0);
7588 if (err == NULL) {
7589 err = got_error(GOT_ERR_TAG_EXISTS);
7590 goto done;
7591 } else if (err->code != GOT_ERR_NOT_REF)
7592 goto done;
7594 if (tagmsg_arg == NULL) {
7595 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7596 tag_name, got_repo_get_path(repo));
7597 if (err) {
7598 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7599 tagmsg_path != NULL)
7600 preserve_tagmsg = 1;
7601 goto done;
7603 /* Editor is done; we can now apply unveil(2) */
7604 err = got_sigs_apply_unveil();
7605 if (err)
7606 goto done;
7607 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7608 if (err)
7609 goto done;
7612 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7613 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7614 verbosity);
7615 if (err) {
7616 if (tagmsg_path)
7617 preserve_tagmsg = 1;
7618 goto done;
7621 err = got_ref_alloc(&ref, refname, tag_id);
7622 if (err) {
7623 if (tagmsg_path)
7624 preserve_tagmsg = 1;
7625 goto done;
7628 err = got_ref_write(ref, repo);
7629 if (err) {
7630 if (tagmsg_path)
7631 preserve_tagmsg = 1;
7632 goto done;
7635 err = got_object_id_str(&tag_id_str, tag_id);
7636 if (err) {
7637 if (tagmsg_path)
7638 preserve_tagmsg = 1;
7639 goto done;
7641 printf("Created tag %s\n", tag_id_str);
7642 done:
7643 if (preserve_tagmsg) {
7644 fprintf(stderr, "%s: tag message preserved in %s\n",
7645 getprogname(), tagmsg_path);
7646 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7647 err = got_error_from_errno2("unlink", tagmsg_path);
7648 free(tag_id_str);
7649 if (ref)
7650 got_ref_close(ref);
7651 free(commit_id);
7652 free(commit_id_str);
7653 free(refname);
7654 free(tagmsg);
7655 free(tagmsg_path);
7656 got_ref_list_free(&refs);
7657 return err;
7660 static const struct got_error *
7661 cmd_tag(int argc, char *argv[])
7663 const struct got_error *error = NULL;
7664 struct got_repository *repo = NULL;
7665 struct got_worktree *worktree = NULL;
7666 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7667 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7668 char *allowed_signers = NULL, *revoked_signers = NULL;
7669 const char *signer_id = NULL;
7670 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7671 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7672 int *pack_fds = NULL;
7674 #ifndef PROFILE
7675 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7676 "sendfd unveil", NULL) == -1)
7677 err(1, "pledge");
7678 #endif
7680 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7681 switch (ch) {
7682 case 'c':
7683 commit_id_arg = optarg;
7684 break;
7685 case 'l':
7686 do_list = 1;
7687 break;
7688 case 'm':
7689 tagmsg = optarg;
7690 break;
7691 case 'r':
7692 repo_path = realpath(optarg, NULL);
7693 if (repo_path == NULL) {
7694 error = got_error_from_errno2("realpath",
7695 optarg);
7696 goto done;
7698 got_path_strip_trailing_slashes(repo_path);
7699 break;
7700 case 's':
7701 signer_id = optarg;
7702 break;
7703 case 'V':
7704 verify_tags = 1;
7705 break;
7706 case 'v':
7707 if (verbosity < 0)
7708 verbosity = 0;
7709 else if (verbosity < 3)
7710 verbosity++;
7711 break;
7712 default:
7713 usage_tag();
7714 /* NOTREACHED */
7718 argc -= optind;
7719 argv += optind;
7721 if (do_list || verify_tags) {
7722 if (commit_id_arg != NULL)
7723 errx(1,
7724 "-c option can only be used when creating a tag");
7725 if (tagmsg) {
7726 if (do_list)
7727 option_conflict('l', 'm');
7728 else
7729 option_conflict('V', 'm');
7731 if (signer_id) {
7732 if (do_list)
7733 option_conflict('l', 's');
7734 else
7735 option_conflict('V', 's');
7737 if (argc > 1)
7738 usage_tag();
7739 } else if (argc != 1)
7740 usage_tag();
7742 if (argc == 1)
7743 tag_name = argv[0];
7745 cwd = getcwd(NULL, 0);
7746 if (cwd == NULL) {
7747 error = got_error_from_errno("getcwd");
7748 goto done;
7751 error = got_repo_pack_fds_open(&pack_fds);
7752 if (error != NULL)
7753 goto done;
7755 if (repo_path == NULL) {
7756 error = got_worktree_open(&worktree, cwd,
7757 GOT_WORKTREE_GOT_DIR);
7758 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7759 goto done;
7760 else
7761 error = NULL;
7762 if (worktree) {
7763 repo_path =
7764 strdup(got_worktree_get_repo_path(worktree));
7765 if (repo_path == NULL)
7766 error = got_error_from_errno("strdup");
7767 if (error)
7768 goto done;
7769 } else {
7770 repo_path = strdup(cwd);
7771 if (repo_path == NULL) {
7772 error = got_error_from_errno("strdup");
7773 goto done;
7778 if (do_list || verify_tags) {
7779 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7780 if (error != NULL)
7781 goto done;
7782 error = get_allowed_signers(&allowed_signers, repo, worktree);
7783 if (error)
7784 goto done;
7785 error = get_revoked_signers(&revoked_signers, repo, worktree);
7786 if (error)
7787 goto done;
7788 if (worktree) {
7789 /* Release work tree lock. */
7790 got_worktree_close(worktree);
7791 worktree = NULL;
7795 * Remove "cpath" promise unless needed for signature tmpfile
7796 * creation.
7798 if (verify_tags)
7799 got_sigs_apply_unveil();
7800 else {
7801 #ifndef PROFILE
7802 if (pledge("stdio rpath wpath flock proc exec sendfd "
7803 "unveil", NULL) == -1)
7804 err(1, "pledge");
7805 #endif
7807 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7808 if (error)
7809 goto done;
7810 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7811 revoked_signers, verbosity);
7812 } else {
7813 error = get_gitconfig_path(&gitconfig_path);
7814 if (error)
7815 goto done;
7816 error = got_repo_open(&repo, repo_path, gitconfig_path,
7817 pack_fds);
7818 if (error != NULL)
7819 goto done;
7821 error = get_author(&tagger, repo, worktree);
7822 if (error)
7823 goto done;
7824 if (signer_id == NULL)
7825 signer_id = get_signer_id(repo, worktree);
7827 if (tagmsg) {
7828 if (signer_id) {
7829 error = got_sigs_apply_unveil();
7830 if (error)
7831 goto done;
7833 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7834 if (error)
7835 goto done;
7838 if (commit_id_arg == NULL) {
7839 struct got_reference *head_ref;
7840 struct got_object_id *commit_id;
7841 error = got_ref_open(&head_ref, repo,
7842 worktree ? got_worktree_get_head_ref_name(worktree)
7843 : GOT_REF_HEAD, 0);
7844 if (error)
7845 goto done;
7846 error = got_ref_resolve(&commit_id, repo, head_ref);
7847 got_ref_close(head_ref);
7848 if (error)
7849 goto done;
7850 error = got_object_id_str(&commit_id_str, commit_id);
7851 free(commit_id);
7852 if (error)
7853 goto done;
7854 } else {
7855 error = got_keyword_to_idstr(&keyword_idstr,
7856 commit_id_arg, repo, worktree);
7857 if (error != NULL)
7858 goto done;
7859 commit_id_str = keyword_idstr;
7862 if (worktree) {
7863 /* Release work tree lock. */
7864 got_worktree_close(worktree);
7865 worktree = NULL;
7868 error = add_tag(repo, tagger, tag_name,
7869 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7870 signer_id, verbosity);
7872 done:
7873 if (repo) {
7874 const struct got_error *close_err = got_repo_close(repo);
7875 if (error == NULL)
7876 error = close_err;
7878 if (worktree)
7879 got_worktree_close(worktree);
7880 if (pack_fds) {
7881 const struct got_error *pack_err =
7882 got_repo_pack_fds_close(pack_fds);
7883 if (error == NULL)
7884 error = pack_err;
7886 free(cwd);
7887 free(repo_path);
7888 free(gitconfig_path);
7889 free(commit_id_str);
7890 free(tagger);
7891 free(allowed_signers);
7892 free(revoked_signers);
7893 return error;
7896 __dead static void
7897 usage_add(void)
7899 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7900 exit(1);
7903 static const struct got_error *
7904 add_progress(void *arg, unsigned char status, const char *path)
7906 while (path[0] == '/')
7907 path++;
7908 printf("%c %s\n", status, path);
7909 return NULL;
7912 static const struct got_error *
7913 cmd_add(int argc, char *argv[])
7915 const struct got_error *error = NULL;
7916 struct got_repository *repo = NULL;
7917 struct got_worktree *worktree = NULL;
7918 char *cwd = NULL;
7919 struct got_pathlist_head paths;
7920 struct got_pathlist_entry *pe;
7921 int ch, can_recurse = 0, no_ignores = 0;
7922 int *pack_fds = NULL;
7924 TAILQ_INIT(&paths);
7926 #ifndef PROFILE
7927 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7928 NULL) == -1)
7929 err(1, "pledge");
7930 #endif
7932 while ((ch = getopt(argc, argv, "IR")) != -1) {
7933 switch (ch) {
7934 case 'I':
7935 no_ignores = 1;
7936 break;
7937 case 'R':
7938 can_recurse = 1;
7939 break;
7940 default:
7941 usage_add();
7942 /* NOTREACHED */
7946 argc -= optind;
7947 argv += optind;
7949 if (argc < 1)
7950 usage_add();
7952 cwd = getcwd(NULL, 0);
7953 if (cwd == NULL) {
7954 error = got_error_from_errno("getcwd");
7955 goto done;
7958 error = got_repo_pack_fds_open(&pack_fds);
7959 if (error != NULL)
7960 goto done;
7962 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7963 if (error) {
7964 if (error->code == GOT_ERR_NOT_WORKTREE)
7965 error = wrap_not_worktree_error(error, "add", cwd);
7966 goto done;
7969 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7970 NULL, pack_fds);
7971 if (error != NULL)
7972 goto done;
7974 error = apply_unveil(got_repo_get_path(repo), 1,
7975 got_worktree_get_root_path(worktree));
7976 if (error)
7977 goto done;
7979 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7980 if (error)
7981 goto done;
7983 if (!can_recurse) {
7984 char *ondisk_path;
7985 struct stat sb;
7986 TAILQ_FOREACH(pe, &paths, entry) {
7987 if (asprintf(&ondisk_path, "%s/%s",
7988 got_worktree_get_root_path(worktree),
7989 pe->path) == -1) {
7990 error = got_error_from_errno("asprintf");
7991 goto done;
7993 if (lstat(ondisk_path, &sb) == -1) {
7994 if (errno == ENOENT) {
7995 free(ondisk_path);
7996 continue;
7998 error = got_error_from_errno2("lstat",
7999 ondisk_path);
8000 free(ondisk_path);
8001 goto done;
8003 free(ondisk_path);
8004 if (S_ISDIR(sb.st_mode)) {
8005 error = got_error_msg(GOT_ERR_BAD_PATH,
8006 "adding directories requires -R option");
8007 goto done;
8012 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8013 NULL, repo, no_ignores);
8014 done:
8015 if (repo) {
8016 const struct got_error *close_err = got_repo_close(repo);
8017 if (error == NULL)
8018 error = close_err;
8020 if (worktree)
8021 got_worktree_close(worktree);
8022 if (pack_fds) {
8023 const struct got_error *pack_err =
8024 got_repo_pack_fds_close(pack_fds);
8025 if (error == NULL)
8026 error = pack_err;
8028 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8029 free(cwd);
8030 return error;
8033 __dead static void
8034 usage_remove(void)
8036 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8037 getprogname());
8038 exit(1);
8041 static const struct got_error *
8042 print_remove_status(void *arg, unsigned char status,
8043 unsigned char staged_status, const char *path)
8045 while (path[0] == '/')
8046 path++;
8047 if (status == GOT_STATUS_NONEXISTENT)
8048 return NULL;
8049 if (status == staged_status && (status == GOT_STATUS_DELETE))
8050 status = GOT_STATUS_NO_CHANGE;
8051 printf("%c%c %s\n", status, staged_status, path);
8052 return NULL;
8055 static const struct got_error *
8056 cmd_remove(int argc, char *argv[])
8058 const struct got_error *error = NULL;
8059 struct got_worktree *worktree = NULL;
8060 struct got_repository *repo = NULL;
8061 const char *status_codes = NULL;
8062 char *cwd = NULL;
8063 struct got_pathlist_head paths;
8064 struct got_pathlist_entry *pe;
8065 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8066 int ignore_missing_paths = 0;
8067 int *pack_fds = NULL;
8069 TAILQ_INIT(&paths);
8071 #ifndef PROFILE
8072 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8073 NULL) == -1)
8074 err(1, "pledge");
8075 #endif
8077 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8078 switch (ch) {
8079 case 'f':
8080 delete_local_mods = 1;
8081 ignore_missing_paths = 1;
8082 break;
8083 case 'k':
8084 keep_on_disk = 1;
8085 break;
8086 case 'R':
8087 can_recurse = 1;
8088 break;
8089 case 's':
8090 for (i = 0; optarg[i] != '\0'; i++) {
8091 switch (optarg[i]) {
8092 case GOT_STATUS_MODIFY:
8093 delete_local_mods = 1;
8094 break;
8095 case GOT_STATUS_MISSING:
8096 ignore_missing_paths = 1;
8097 break;
8098 default:
8099 errx(1, "invalid status code '%c'",
8100 optarg[i]);
8103 status_codes = optarg;
8104 break;
8105 default:
8106 usage_remove();
8107 /* NOTREACHED */
8111 argc -= optind;
8112 argv += optind;
8114 if (argc < 1)
8115 usage_remove();
8117 cwd = getcwd(NULL, 0);
8118 if (cwd == NULL) {
8119 error = got_error_from_errno("getcwd");
8120 goto done;
8123 error = got_repo_pack_fds_open(&pack_fds);
8124 if (error != NULL)
8125 goto done;
8127 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8128 if (error) {
8129 if (error->code == GOT_ERR_NOT_WORKTREE)
8130 error = wrap_not_worktree_error(error, "remove", cwd);
8131 goto done;
8134 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8135 NULL, pack_fds);
8136 if (error)
8137 goto done;
8139 error = apply_unveil(got_repo_get_path(repo), 1,
8140 got_worktree_get_root_path(worktree));
8141 if (error)
8142 goto done;
8144 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8145 if (error)
8146 goto done;
8148 if (!can_recurse) {
8149 char *ondisk_path;
8150 struct stat sb;
8151 TAILQ_FOREACH(pe, &paths, entry) {
8152 if (asprintf(&ondisk_path, "%s/%s",
8153 got_worktree_get_root_path(worktree),
8154 pe->path) == -1) {
8155 error = got_error_from_errno("asprintf");
8156 goto done;
8158 if (lstat(ondisk_path, &sb) == -1) {
8159 if (errno == ENOENT) {
8160 free(ondisk_path);
8161 continue;
8163 error = got_error_from_errno2("lstat",
8164 ondisk_path);
8165 free(ondisk_path);
8166 goto done;
8168 free(ondisk_path);
8169 if (S_ISDIR(sb.st_mode)) {
8170 error = got_error_msg(GOT_ERR_BAD_PATH,
8171 "removing directories requires -R option");
8172 goto done;
8177 error = got_worktree_schedule_delete(worktree, &paths,
8178 delete_local_mods, status_codes, print_remove_status, NULL,
8179 repo, keep_on_disk, ignore_missing_paths);
8180 done:
8181 if (repo) {
8182 const struct got_error *close_err = got_repo_close(repo);
8183 if (error == NULL)
8184 error = close_err;
8186 if (worktree)
8187 got_worktree_close(worktree);
8188 if (pack_fds) {
8189 const struct got_error *pack_err =
8190 got_repo_pack_fds_close(pack_fds);
8191 if (error == NULL)
8192 error = pack_err;
8194 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8195 free(cwd);
8196 return error;
8199 __dead static void
8200 usage_patch(void)
8202 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8203 "[patchfile]\n", getprogname());
8204 exit(1);
8207 static const struct got_error *
8208 patch_from_stdin(int *patchfd)
8210 const struct got_error *err = NULL;
8211 ssize_t r;
8212 char buf[BUFSIZ];
8213 sig_t sighup, sigint, sigquit;
8215 *patchfd = got_opentempfd();
8216 if (*patchfd == -1)
8217 return got_error_from_errno("got_opentempfd");
8219 sighup = signal(SIGHUP, SIG_DFL);
8220 sigint = signal(SIGINT, SIG_DFL);
8221 sigquit = signal(SIGQUIT, SIG_DFL);
8223 for (;;) {
8224 r = read(0, buf, sizeof(buf));
8225 if (r == -1) {
8226 err = got_error_from_errno("read");
8227 break;
8229 if (r == 0)
8230 break;
8231 if (write(*patchfd, buf, r) == -1) {
8232 err = got_error_from_errno("write");
8233 break;
8237 signal(SIGHUP, sighup);
8238 signal(SIGINT, sigint);
8239 signal(SIGQUIT, sigquit);
8241 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8242 err = got_error_from_errno("lseek");
8244 if (err != NULL) {
8245 close(*patchfd);
8246 *patchfd = -1;
8249 return err;
8252 struct got_patch_progress_arg {
8253 int did_something;
8254 int conflicts;
8255 int rejects;
8258 static const struct got_error *
8259 patch_progress(void *arg, const char *old, const char *new,
8260 unsigned char status, const struct got_error *error, int old_from,
8261 int old_lines, int new_from, int new_lines, int offset,
8262 int ws_mangled, const struct got_error *hunk_err)
8264 const char *path = new == NULL ? old : new;
8265 struct got_patch_progress_arg *a = arg;
8267 while (*path == '/')
8268 path++;
8270 if (status != GOT_STATUS_NO_CHANGE &&
8271 status != 0 /* per-hunk progress */) {
8272 printf("%c %s\n", status, path);
8273 a->did_something = 1;
8276 if (hunk_err == NULL) {
8277 if (status == GOT_STATUS_CANNOT_UPDATE)
8278 a->rejects++;
8279 else if (status == GOT_STATUS_CONFLICT)
8280 a->conflicts++;
8283 if (error != NULL)
8284 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8286 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8287 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8288 old_lines, new_from, new_lines);
8289 if (hunk_err != NULL)
8290 printf("%s\n", hunk_err->msg);
8291 else if (offset != 0)
8292 printf("applied with offset %d\n", offset);
8293 else
8294 printf("hunk contains mangled whitespace\n");
8297 return NULL;
8300 static void
8301 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8303 if (!ppa->did_something)
8304 return;
8306 if (ppa->conflicts > 0)
8307 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8309 if (ppa->rejects > 0) {
8310 printf("Files where patch failed to apply: %d\n",
8311 ppa->rejects);
8315 static const struct got_error *
8316 cmd_patch(int argc, char *argv[])
8318 const struct got_error *error = NULL, *close_error = NULL;
8319 struct got_worktree *worktree = NULL;
8320 struct got_repository *repo = NULL;
8321 struct got_reflist_head refs;
8322 struct got_object_id *commit_id = NULL;
8323 const char *commit_id_str = NULL;
8324 struct stat sb;
8325 const char *errstr;
8326 char *cwd = NULL, *keyword_idstr = NULL;
8327 int ch, nop = 0, strip = -1, reverse = 0;
8328 int patchfd;
8329 int *pack_fds = NULL;
8330 struct got_patch_progress_arg ppa;
8332 TAILQ_INIT(&refs);
8334 #ifndef PROFILE
8335 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8336 "unveil", NULL) == -1)
8337 err(1, "pledge");
8338 #endif
8340 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8341 switch (ch) {
8342 case 'c':
8343 commit_id_str = optarg;
8344 break;
8345 case 'n':
8346 nop = 1;
8347 break;
8348 case 'p':
8349 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8350 if (errstr != NULL)
8351 errx(1, "pathname strip count is %s: %s",
8352 errstr, optarg);
8353 break;
8354 case 'R':
8355 reverse = 1;
8356 break;
8357 default:
8358 usage_patch();
8359 /* NOTREACHED */
8363 argc -= optind;
8364 argv += optind;
8366 if (argc == 0) {
8367 error = patch_from_stdin(&patchfd);
8368 if (error)
8369 return error;
8370 } else if (argc == 1) {
8371 patchfd = open(argv[0], O_RDONLY);
8372 if (patchfd == -1) {
8373 error = got_error_from_errno2("open", argv[0]);
8374 return error;
8376 if (fstat(patchfd, &sb) == -1) {
8377 error = got_error_from_errno2("fstat", argv[0]);
8378 goto done;
8380 if (!S_ISREG(sb.st_mode)) {
8381 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8382 goto done;
8384 } else
8385 usage_patch();
8387 if ((cwd = getcwd(NULL, 0)) == NULL) {
8388 error = got_error_from_errno("getcwd");
8389 goto done;
8392 error = got_repo_pack_fds_open(&pack_fds);
8393 if (error != NULL)
8394 goto done;
8396 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8397 if (error != NULL)
8398 goto done;
8400 const char *repo_path = got_worktree_get_repo_path(worktree);
8401 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8402 if (error != NULL)
8403 goto done;
8405 error = apply_unveil(got_repo_get_path(repo), 0,
8406 got_worktree_get_root_path(worktree));
8407 if (error != NULL)
8408 goto done;
8410 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8411 if (error)
8412 goto done;
8414 if (commit_id_str != NULL) {
8415 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8416 repo, worktree);
8417 if (error != NULL)
8418 goto done;
8420 error = got_repo_match_object_id(&commit_id, NULL,
8421 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8422 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8423 if (error)
8424 goto done;
8427 memset(&ppa, 0, sizeof(ppa));
8428 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8429 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8430 print_patch_progress_stats(&ppa);
8431 done:
8432 got_ref_list_free(&refs);
8433 free(keyword_idstr);
8434 free(commit_id);
8435 if (repo) {
8436 close_error = got_repo_close(repo);
8437 if (error == NULL)
8438 error = close_error;
8440 if (worktree != NULL) {
8441 close_error = got_worktree_close(worktree);
8442 if (error == NULL)
8443 error = close_error;
8445 if (pack_fds) {
8446 const struct got_error *pack_err =
8447 got_repo_pack_fds_close(pack_fds);
8448 if (error == NULL)
8449 error = pack_err;
8451 free(cwd);
8452 return error;
8455 __dead static void
8456 usage_revert(void)
8458 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8459 getprogname());
8460 exit(1);
8463 static const struct got_error *
8464 revert_progress(void *arg, unsigned char status, const char *path)
8466 if (status == GOT_STATUS_UNVERSIONED)
8467 return NULL;
8469 while (path[0] == '/')
8470 path++;
8471 printf("%c %s\n", status, path);
8472 return NULL;
8475 struct choose_patch_arg {
8476 FILE *patch_script_file;
8477 const char *action;
8480 static const struct got_error *
8481 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8482 int nchanges, const char *action)
8484 const struct got_error *err;
8485 char *line = NULL;
8486 size_t linesize = 0;
8487 ssize_t linelen;
8489 switch (status) {
8490 case GOT_STATUS_ADD:
8491 printf("A %s\n%s this addition? [y/n] ", path, action);
8492 break;
8493 case GOT_STATUS_DELETE:
8494 printf("D %s\n%s this deletion? [y/n] ", path, action);
8495 break;
8496 case GOT_STATUS_MODIFY:
8497 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8498 return got_error_from_errno("fseek");
8499 printf(GOT_COMMIT_SEP_STR);
8500 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8501 printf("%s", line);
8502 if (linelen == -1 && ferror(patch_file)) {
8503 err = got_error_from_errno("getline");
8504 free(line);
8505 return err;
8507 free(line);
8508 printf(GOT_COMMIT_SEP_STR);
8509 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8510 path, n, nchanges, action);
8511 break;
8512 default:
8513 return got_error_path(path, GOT_ERR_FILE_STATUS);
8516 fflush(stdout);
8517 return NULL;
8520 static const struct got_error *
8521 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8522 FILE *patch_file, int n, int nchanges)
8524 const struct got_error *err = NULL;
8525 char *line = NULL;
8526 size_t linesize = 0;
8527 ssize_t linelen;
8528 int resp = ' ';
8529 struct choose_patch_arg *a = arg;
8531 *choice = GOT_PATCH_CHOICE_NONE;
8533 if (a->patch_script_file) {
8534 char *nl;
8535 err = show_change(status, path, patch_file, n, nchanges,
8536 a->action);
8537 if (err)
8538 return err;
8539 linelen = getline(&line, &linesize, a->patch_script_file);
8540 if (linelen == -1) {
8541 if (ferror(a->patch_script_file))
8542 return got_error_from_errno("getline");
8543 return NULL;
8545 nl = strchr(line, '\n');
8546 if (nl)
8547 *nl = '\0';
8548 if (strcmp(line, "y") == 0) {
8549 *choice = GOT_PATCH_CHOICE_YES;
8550 printf("y\n");
8551 } else if (strcmp(line, "n") == 0) {
8552 *choice = GOT_PATCH_CHOICE_NO;
8553 printf("n\n");
8554 } else if (strcmp(line, "q") == 0 &&
8555 status == GOT_STATUS_MODIFY) {
8556 *choice = GOT_PATCH_CHOICE_QUIT;
8557 printf("q\n");
8558 } else
8559 printf("invalid response '%s'\n", line);
8560 free(line);
8561 return NULL;
8564 while (resp != 'y' && resp != 'n' && resp != 'q') {
8565 err = show_change(status, path, patch_file, n, nchanges,
8566 a->action);
8567 if (err)
8568 return err;
8569 resp = getchar();
8570 if (resp == '\n')
8571 resp = getchar();
8572 if (status == GOT_STATUS_MODIFY) {
8573 if (resp != 'y' && resp != 'n' && resp != 'q') {
8574 printf("invalid response '%c'\n", resp);
8575 resp = ' ';
8577 } else if (resp != 'y' && resp != 'n') {
8578 printf("invalid response '%c'\n", resp);
8579 resp = ' ';
8583 if (resp == 'y')
8584 *choice = GOT_PATCH_CHOICE_YES;
8585 else if (resp == 'n')
8586 *choice = GOT_PATCH_CHOICE_NO;
8587 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8588 *choice = GOT_PATCH_CHOICE_QUIT;
8590 return NULL;
8593 struct wt_commitable_path_arg {
8594 struct got_pathlist_head *commit_paths;
8595 int *has_changes;
8599 * Shortcut work tree status callback to determine if the set of paths scanned
8600 * has at least one versioned path that is being modified and, if not NULL, is
8601 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8602 * soon as a path is passed with a status that satisfies this criteria.
8604 static const struct got_error *
8605 worktree_has_commitable_path(void *arg, unsigned char status,
8606 unsigned char staged_status, const char *path,
8607 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8608 struct got_object_id *commit_id, int dirfd, const char *de_name)
8610 struct wt_commitable_path_arg *a = arg;
8612 if (status == staged_status && (status == GOT_STATUS_DELETE))
8613 status = GOT_STATUS_NO_CHANGE;
8615 if (!(status == GOT_STATUS_NO_CHANGE ||
8616 status == GOT_STATUS_UNVERSIONED) ||
8617 staged_status != GOT_STATUS_NO_CHANGE) {
8618 if (a->commit_paths != NULL) {
8619 struct got_pathlist_entry *pe;
8621 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8622 if (strncmp(path, pe->path,
8623 pe->path_len) == 0) {
8624 *a->has_changes = 1;
8625 break;
8628 } else
8629 *a->has_changes = 1;
8631 if (*a->has_changes)
8632 return got_error(GOT_ERR_FILE_MODIFIED);
8635 return NULL;
8639 * Check that the changeset of the commit identified by id is
8640 * comprised of at least one modified path that is being committed.
8642 static const struct got_error *
8643 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8644 struct got_object_id *id, struct got_worktree *worktree,
8645 struct got_repository *repo)
8647 const struct got_error *err;
8648 struct got_pathlist_head paths;
8649 struct got_commit_object *commit = NULL, *pcommit = NULL;
8650 struct got_tree_object *tree = NULL, *ptree = NULL;
8651 struct got_object_qid *pid;
8653 TAILQ_INIT(&paths);
8655 err = got_object_open_as_commit(&commit, repo, id);
8656 if (err)
8657 goto done;
8659 err = got_object_open_as_tree(&tree, repo,
8660 got_object_commit_get_tree_id(commit));
8661 if (err)
8662 goto done;
8664 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8665 if (pid != NULL) {
8666 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8667 if (err)
8668 goto done;
8670 err = got_object_open_as_tree(&ptree, repo,
8671 got_object_commit_get_tree_id(pcommit));
8672 if (err)
8673 goto done;
8676 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8677 got_diff_tree_collect_changed_paths, &paths, 0);
8678 if (err)
8679 goto done;
8681 err = got_worktree_status(worktree, &paths, repo, 0,
8682 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8683 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8685 * At least one changed path in the referenced commit is
8686 * modified in the work tree, that's all we need to know!
8688 err = NULL;
8691 done:
8692 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8693 if (commit)
8694 got_object_commit_close(commit);
8695 if (pcommit)
8696 got_object_commit_close(pcommit);
8697 if (tree)
8698 got_object_tree_close(tree);
8699 if (ptree)
8700 got_object_tree_close(ptree);
8701 return err;
8705 * Remove any "logmsg" reference comprised entirely of paths that have
8706 * been reverted in this work tree. If any path in the logmsg ref changeset
8707 * remains in a changed state in the worktree, do not remove the reference.
8709 static const struct got_error *
8710 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8712 const struct got_error *err;
8713 struct got_reflist_head refs;
8714 struct got_reflist_entry *re;
8715 struct got_commit_object *commit = NULL;
8716 struct got_object_id *commit_id = NULL;
8717 struct wt_commitable_path_arg wcpa;
8718 char *uuidstr = NULL;
8720 TAILQ_INIT(&refs);
8722 err = got_worktree_get_uuid(&uuidstr, worktree);
8723 if (err)
8724 goto done;
8726 err = got_ref_list(&refs, repo, "refs/got/worktree",
8727 got_ref_cmp_by_name, repo);
8728 if (err)
8729 goto done;
8731 TAILQ_FOREACH(re, &refs, entry) {
8732 const char *refname;
8733 int has_changes = 0;
8735 refname = got_ref_get_name(re->ref);
8737 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8738 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8739 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8740 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8741 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8742 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8743 else
8744 continue;
8746 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8747 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8748 else
8749 continue;
8751 err = got_repo_match_object_id(&commit_id, NULL, refname,
8752 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8753 if (err)
8754 goto done;
8756 err = got_object_open_as_commit(&commit, repo, commit_id);
8757 if (err)
8758 goto done;
8760 wcpa.commit_paths = NULL;
8761 wcpa.has_changes = &has_changes;
8763 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8764 worktree, repo);
8765 if (err)
8766 goto done;
8768 if (!has_changes) {
8769 err = got_ref_delete(re->ref, repo);
8770 if (err)
8771 goto done;
8774 got_object_commit_close(commit);
8775 commit = NULL;
8776 free(commit_id);
8777 commit_id = NULL;
8780 done:
8781 free(uuidstr);
8782 free(commit_id);
8783 got_ref_list_free(&refs);
8784 if (commit)
8785 got_object_commit_close(commit);
8786 return err;
8789 static const struct got_error *
8790 cmd_revert(int argc, char *argv[])
8792 const struct got_error *error = NULL;
8793 struct got_worktree *worktree = NULL;
8794 struct got_repository *repo = NULL;
8795 char *cwd = NULL, *path = NULL;
8796 struct got_pathlist_head paths;
8797 struct got_pathlist_entry *pe;
8798 int ch, can_recurse = 0, pflag = 0;
8799 FILE *patch_script_file = NULL;
8800 const char *patch_script_path = NULL;
8801 struct choose_patch_arg cpa;
8802 int *pack_fds = NULL;
8804 TAILQ_INIT(&paths);
8806 #ifndef PROFILE
8807 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8808 "unveil", NULL) == -1)
8809 err(1, "pledge");
8810 #endif
8812 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8813 switch (ch) {
8814 case 'F':
8815 patch_script_path = optarg;
8816 break;
8817 case 'p':
8818 pflag = 1;
8819 break;
8820 case 'R':
8821 can_recurse = 1;
8822 break;
8823 default:
8824 usage_revert();
8825 /* NOTREACHED */
8829 argc -= optind;
8830 argv += optind;
8832 if (argc < 1)
8833 usage_revert();
8834 if (patch_script_path && !pflag)
8835 errx(1, "-F option can only be used together with -p option");
8837 cwd = getcwd(NULL, 0);
8838 if (cwd == NULL) {
8839 error = got_error_from_errno("getcwd");
8840 goto done;
8843 error = got_repo_pack_fds_open(&pack_fds);
8844 if (error != NULL)
8845 goto done;
8847 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8848 if (error) {
8849 if (error->code == GOT_ERR_NOT_WORKTREE)
8850 error = wrap_not_worktree_error(error, "revert", cwd);
8851 goto done;
8854 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8855 NULL, pack_fds);
8856 if (error != NULL)
8857 goto done;
8859 if (patch_script_path) {
8860 patch_script_file = fopen(patch_script_path, "re");
8861 if (patch_script_file == NULL) {
8862 error = got_error_from_errno2("fopen",
8863 patch_script_path);
8864 goto done;
8869 * XXX "c" perm needed on repo dir to delete merge references.
8871 error = apply_unveil(got_repo_get_path(repo), 0,
8872 got_worktree_get_root_path(worktree));
8873 if (error)
8874 goto done;
8876 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8877 if (error)
8878 goto done;
8880 if (!can_recurse) {
8881 char *ondisk_path;
8882 struct stat sb;
8883 TAILQ_FOREACH(pe, &paths, entry) {
8884 if (asprintf(&ondisk_path, "%s/%s",
8885 got_worktree_get_root_path(worktree),
8886 pe->path) == -1) {
8887 error = got_error_from_errno("asprintf");
8888 goto done;
8890 if (lstat(ondisk_path, &sb) == -1) {
8891 if (errno == ENOENT) {
8892 free(ondisk_path);
8893 continue;
8895 error = got_error_from_errno2("lstat",
8896 ondisk_path);
8897 free(ondisk_path);
8898 goto done;
8900 free(ondisk_path);
8901 if (S_ISDIR(sb.st_mode)) {
8902 error = got_error_msg(GOT_ERR_BAD_PATH,
8903 "reverting directories requires -R option");
8904 goto done;
8909 cpa.patch_script_file = patch_script_file;
8910 cpa.action = "revert";
8911 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8912 pflag ? choose_patch : NULL, &cpa, repo);
8914 error = rm_logmsg_ref(worktree, repo);
8915 done:
8916 if (patch_script_file && fclose(patch_script_file) == EOF &&
8917 error == NULL)
8918 error = got_error_from_errno2("fclose", patch_script_path);
8919 if (repo) {
8920 const struct got_error *close_err = got_repo_close(repo);
8921 if (error == NULL)
8922 error = close_err;
8924 if (worktree)
8925 got_worktree_close(worktree);
8926 if (pack_fds) {
8927 const struct got_error *pack_err =
8928 got_repo_pack_fds_close(pack_fds);
8929 if (error == NULL)
8930 error = pack_err;
8932 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8933 free(path);
8934 free(cwd);
8935 return error;
8938 __dead static void
8939 usage_commit(void)
8941 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8942 "[-m message] [path ...]\n", getprogname());
8943 exit(1);
8946 struct collect_commit_logmsg_arg {
8947 const char *cmdline_log;
8948 const char *prepared_log;
8949 const char *merged_log;
8950 int non_interactive;
8951 const char *editor;
8952 const char *worktree_path;
8953 const char *branch_name;
8954 const char *repo_path;
8955 char *logmsg_path;
8959 static const struct got_error *
8960 read_prepared_logmsg(char **logmsg, const char *path)
8962 const struct got_error *err = NULL;
8963 FILE *f = NULL;
8964 struct stat sb;
8965 size_t r;
8967 *logmsg = NULL;
8968 memset(&sb, 0, sizeof(sb));
8970 f = fopen(path, "re");
8971 if (f == NULL)
8972 return got_error_from_errno2("fopen", path);
8974 if (fstat(fileno(f), &sb) == -1) {
8975 err = got_error_from_errno2("fstat", path);
8976 goto done;
8978 if (sb.st_size == 0) {
8979 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8980 goto done;
8983 *logmsg = malloc(sb.st_size + 1);
8984 if (*logmsg == NULL) {
8985 err = got_error_from_errno("malloc");
8986 goto done;
8989 r = fread(*logmsg, 1, sb.st_size, f);
8990 if (r != sb.st_size) {
8991 if (ferror(f))
8992 err = got_error_from_errno2("fread", path);
8993 else
8994 err = got_error(GOT_ERR_IO);
8995 goto done;
8997 (*logmsg)[sb.st_size] = '\0';
8998 done:
8999 if (fclose(f) == EOF && err == NULL)
9000 err = got_error_from_errno2("fclose", path);
9001 if (err) {
9002 free(*logmsg);
9003 *logmsg = NULL;
9005 return err;
9008 static const struct got_error *
9009 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9010 const char *diff_path, char **logmsg, void *arg)
9012 char *initial_content = NULL;
9013 struct got_pathlist_entry *pe;
9014 const struct got_error *err = NULL;
9015 char *template = NULL;
9016 char *prepared_msg = NULL, *merged_msg = NULL;
9017 struct collect_commit_logmsg_arg *a = arg;
9018 int initial_content_len;
9019 int fd = -1;
9020 size_t len;
9022 /* if a message was specified on the command line, just use it */
9023 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9024 len = strlen(a->cmdline_log) + 1;
9025 *logmsg = malloc(len + 1);
9026 if (*logmsg == NULL)
9027 return got_error_from_errno("malloc");
9028 strlcpy(*logmsg, a->cmdline_log, len);
9029 return NULL;
9030 } else if (a->prepared_log != NULL && a->non_interactive)
9031 return read_prepared_logmsg(logmsg, a->prepared_log);
9033 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9034 return got_error_from_errno("asprintf");
9036 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9037 if (err)
9038 goto done;
9040 if (a->prepared_log) {
9041 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9042 if (err)
9043 goto done;
9044 } else if (a->merged_log) {
9045 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9046 if (err)
9047 goto done;
9050 initial_content_len = asprintf(&initial_content,
9051 "%s%s\n# changes to be committed on branch %s:\n",
9052 prepared_msg ? prepared_msg : "",
9053 merged_msg ? merged_msg : "", a->branch_name);
9054 if (initial_content_len == -1) {
9055 err = got_error_from_errno("asprintf");
9056 goto done;
9059 if (write(fd, initial_content, initial_content_len) == -1) {
9060 err = got_error_from_errno2("write", a->logmsg_path);
9061 goto done;
9064 TAILQ_FOREACH(pe, commitable_paths, entry) {
9065 struct got_commitable *ct = pe->data;
9066 dprintf(fd, "# %c %s\n",
9067 got_commitable_get_status(ct),
9068 got_commitable_get_path(ct));
9071 if (diff_path) {
9072 dprintf(fd, "# detailed changes can be viewed in %s\n",
9073 diff_path);
9076 if (close(fd) == -1) {
9077 err = got_error_from_errno2("close", a->logmsg_path);
9078 goto done;
9080 fd = -1;
9082 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9083 initial_content_len, a->prepared_log ? 0 : 1);
9084 done:
9085 free(initial_content);
9086 free(template);
9087 free(prepared_msg);
9088 free(merged_msg);
9090 if (fd != -1 && close(fd) == -1 && err == NULL)
9091 err = got_error_from_errno2("close", a->logmsg_path);
9093 /* Editor is done; we can now apply unveil(2) */
9094 if (err == NULL)
9095 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9096 if (err) {
9097 free(*logmsg);
9098 *logmsg = NULL;
9100 return err;
9103 static const struct got_error *
9104 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9105 const char *type, int has_content)
9107 const struct got_error *err = NULL;
9108 char *logmsg = NULL;
9110 err = got_object_commit_get_logmsg(&logmsg, commit);
9111 if (err)
9112 return err;
9114 if (fprintf(f, "%s# log message of %s commit %s:%s",
9115 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9116 err = got_ferror(f, GOT_ERR_IO);
9118 free(logmsg);
9119 return err;
9123 * Lookup "logmsg" references of backed-out and cherrypicked commits
9124 * belonging to the current work tree. If found, and the worktree has
9125 * at least one modified file that was changed in the referenced commit,
9126 * add its log message to a new temporary file at *logmsg_path.
9127 * Add all refs found to matched_refs to be scheduled for removal on
9128 * successful commit.
9130 static const struct got_error *
9131 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9132 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9133 struct got_repository *repo)
9135 const struct got_error *err;
9136 struct got_commit_object *commit = NULL;
9137 struct got_object_id *id = NULL;
9138 struct got_reflist_head refs;
9139 struct got_reflist_entry *re, *re_match;
9140 FILE *f = NULL;
9141 char *uuidstr = NULL;
9142 int added_logmsg = 0;
9144 TAILQ_INIT(&refs);
9146 *logmsg_path = NULL;
9148 err = got_worktree_get_uuid(&uuidstr, worktree);
9149 if (err)
9150 goto done;
9152 err = got_ref_list(&refs, repo, "refs/got/worktree",
9153 got_ref_cmp_by_name, repo);
9154 if (err)
9155 goto done;
9157 TAILQ_FOREACH(re, &refs, entry) {
9158 const char *refname, *type;
9159 struct wt_commitable_path_arg wcpa;
9160 int add_logmsg = 0;
9162 refname = got_ref_get_name(re->ref);
9164 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9165 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9166 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9167 type = "cherrypicked";
9168 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9169 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9170 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9171 type = "backed-out";
9172 } else
9173 continue;
9175 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9176 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9177 else
9178 continue;
9180 err = got_repo_match_object_id(&id, NULL, refname,
9181 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9182 if (err)
9183 goto done;
9185 err = got_object_open_as_commit(&commit, repo, id);
9186 if (err)
9187 goto done;
9189 wcpa.commit_paths = paths;
9190 wcpa.has_changes = &add_logmsg;
9192 err = commit_path_changed_in_worktree(&wcpa, id,
9193 worktree, repo);
9194 if (err)
9195 goto done;
9197 if (add_logmsg) {
9198 if (f == NULL) {
9199 err = got_opentemp_named(logmsg_path, &f,
9200 "got-commit-logmsg", "");
9201 if (err)
9202 goto done;
9204 err = cat_logmsg(f, commit, refname, type,
9205 added_logmsg);
9206 if (err)
9207 goto done;
9208 if (!added_logmsg)
9209 ++added_logmsg;
9211 err = got_reflist_entry_dup(&re_match, re);
9212 if (err)
9213 goto done;
9214 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9217 got_object_commit_close(commit);
9218 commit = NULL;
9219 free(id);
9220 id = NULL;
9223 done:
9224 free(id);
9225 free(uuidstr);
9226 got_ref_list_free(&refs);
9227 if (commit)
9228 got_object_commit_close(commit);
9229 if (f && fclose(f) == EOF && err == NULL)
9230 err = got_error_from_errno("fclose");
9231 if (!added_logmsg) {
9232 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9233 err = got_error_from_errno2("unlink", *logmsg_path);
9234 *logmsg_path = NULL;
9236 return err;
9239 static const struct got_error *
9240 cmd_commit(int argc, char *argv[])
9242 const struct got_error *error = NULL;
9243 struct got_worktree *worktree = NULL;
9244 struct got_repository *repo = NULL;
9245 char *cwd = NULL, *id_str = NULL;
9246 struct got_object_id *id = NULL;
9247 const char *logmsg = NULL;
9248 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9249 struct collect_commit_logmsg_arg cl_arg;
9250 const char *author = NULL;
9251 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9252 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9253 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9254 int show_diff = 1, commit_conflicts = 0;
9255 struct got_pathlist_head paths;
9256 struct got_reflist_head refs;
9257 struct got_reflist_entry *re;
9258 int *pack_fds = NULL;
9260 TAILQ_INIT(&refs);
9261 TAILQ_INIT(&paths);
9262 cl_arg.logmsg_path = NULL;
9264 #ifndef PROFILE
9265 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9266 "unveil", NULL) == -1)
9267 err(1, "pledge");
9268 #endif
9270 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9271 switch (ch) {
9272 case 'A':
9273 author = optarg;
9274 error = valid_author(author);
9275 if (error)
9276 return error;
9277 break;
9278 case 'C':
9279 commit_conflicts = 1;
9280 break;
9281 case 'F':
9282 if (logmsg != NULL)
9283 option_conflict('F', 'm');
9284 prepared_logmsg = realpath(optarg, NULL);
9285 if (prepared_logmsg == NULL)
9286 return got_error_from_errno2("realpath",
9287 optarg);
9288 break;
9289 case 'm':
9290 if (prepared_logmsg)
9291 option_conflict('m', 'F');
9292 logmsg = optarg;
9293 break;
9294 case 'N':
9295 non_interactive = 1;
9296 break;
9297 case 'n':
9298 show_diff = 0;
9299 break;
9300 case 'S':
9301 allow_bad_symlinks = 1;
9302 break;
9303 default:
9304 usage_commit();
9305 /* NOTREACHED */
9309 argc -= optind;
9310 argv += optind;
9312 cwd = getcwd(NULL, 0);
9313 if (cwd == NULL) {
9314 error = got_error_from_errno("getcwd");
9315 goto done;
9318 error = got_repo_pack_fds_open(&pack_fds);
9319 if (error != NULL)
9320 goto done;
9322 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9323 if (error) {
9324 if (error->code == GOT_ERR_NOT_WORKTREE)
9325 error = wrap_not_worktree_error(error, "commit", cwd);
9326 goto done;
9329 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9330 if (error)
9331 goto done;
9332 if (rebase_in_progress) {
9333 error = got_error(GOT_ERR_REBASING);
9334 goto done;
9337 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9338 worktree);
9339 if (error)
9340 goto done;
9342 error = get_gitconfig_path(&gitconfig_path);
9343 if (error)
9344 goto done;
9345 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9346 gitconfig_path, pack_fds);
9347 if (error != NULL)
9348 goto done;
9350 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9351 if (error)
9352 goto done;
9353 if (merge_in_progress) {
9354 error = got_error(GOT_ERR_MERGE_BUSY);
9355 goto done;
9358 error = get_author(&committer, repo, worktree);
9359 if (error)
9360 goto done;
9362 if (author == NULL)
9363 author = committer;
9366 * unveil(2) traverses exec(2); if an editor is used we have
9367 * to apply unveil after the log message has been written.
9369 if (logmsg == NULL || strlen(logmsg) == 0)
9370 error = get_editor(&editor);
9371 else
9372 error = apply_unveil(got_repo_get_path(repo), 0,
9373 got_worktree_get_root_path(worktree));
9374 if (error)
9375 goto done;
9377 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9378 if (error)
9379 goto done;
9381 if (prepared_logmsg == NULL) {
9382 error = lookup_logmsg_ref(&merged_logmsg,
9383 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9384 if (error)
9385 goto done;
9388 cl_arg.editor = editor;
9389 cl_arg.cmdline_log = logmsg;
9390 cl_arg.prepared_log = prepared_logmsg;
9391 cl_arg.merged_log = merged_logmsg;
9392 cl_arg.non_interactive = non_interactive;
9393 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9394 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9395 if (!histedit_in_progress) {
9396 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9397 error = got_error(GOT_ERR_COMMIT_BRANCH);
9398 goto done;
9400 cl_arg.branch_name += 11;
9402 cl_arg.repo_path = got_repo_get_path(repo);
9403 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9404 allow_bad_symlinks, show_diff, commit_conflicts,
9405 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9406 if (error) {
9407 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9408 cl_arg.logmsg_path != NULL)
9409 preserve_logmsg = 1;
9410 goto done;
9413 error = got_object_id_str(&id_str, id);
9414 if (error)
9415 goto done;
9416 printf("Created commit %s\n", id_str);
9418 TAILQ_FOREACH(re, &refs, entry) {
9419 error = got_ref_delete(re->ref, repo);
9420 if (error)
9421 goto done;
9424 done:
9425 if (preserve_logmsg) {
9426 fprintf(stderr, "%s: log message preserved in %s\n",
9427 getprogname(), cl_arg.logmsg_path);
9428 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9429 error == NULL)
9430 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9431 free(cl_arg.logmsg_path);
9432 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9433 error = got_error_from_errno2("unlink", merged_logmsg);
9434 free(merged_logmsg);
9435 if (repo) {
9436 const struct got_error *close_err = got_repo_close(repo);
9437 if (error == NULL)
9438 error = close_err;
9440 if (worktree)
9441 got_worktree_close(worktree);
9442 if (pack_fds) {
9443 const struct got_error *pack_err =
9444 got_repo_pack_fds_close(pack_fds);
9445 if (error == NULL)
9446 error = pack_err;
9448 got_ref_list_free(&refs);
9449 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9450 free(cwd);
9451 free(id_str);
9452 free(gitconfig_path);
9453 free(editor);
9454 free(committer);
9455 free(prepared_logmsg);
9456 return error;
9459 __dead static void
9460 usage_send(void)
9462 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9463 "[-r repository-path] [-t tag] [remote-repository]\n",
9464 getprogname());
9465 exit(1);
9468 static void
9469 print_load_info(int print_colored, int print_found, int print_trees,
9470 int ncolored, int nfound, int ntrees)
9472 if (print_colored) {
9473 printf("%d commit%s colored", ncolored,
9474 ncolored == 1 ? "" : "s");
9476 if (print_found) {
9477 printf("%s%d object%s found",
9478 ncolored > 0 ? "; " : "",
9479 nfound, nfound == 1 ? "" : "s");
9481 if (print_trees) {
9482 printf("; %d tree%s scanned", ntrees,
9483 ntrees == 1 ? "" : "s");
9487 struct got_send_progress_arg {
9488 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9489 int verbosity;
9490 int last_ncolored;
9491 int last_nfound;
9492 int last_ntrees;
9493 int loading_done;
9494 int last_ncommits;
9495 int last_nobj_total;
9496 int last_p_deltify;
9497 int last_p_written;
9498 int last_p_sent;
9499 int printed_something;
9500 int sent_something;
9501 struct got_pathlist_head *delete_branches;
9504 static const struct got_error *
9505 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9506 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9507 int nobj_written, off_t bytes_sent, const char *refname,
9508 const char *errmsg, int success)
9510 struct got_send_progress_arg *a = arg;
9511 char scaled_packsize[FMT_SCALED_STRSIZE];
9512 char scaled_sent[FMT_SCALED_STRSIZE];
9513 int p_deltify = 0, p_written = 0, p_sent = 0;
9514 int print_colored = 0, print_found = 0, print_trees = 0;
9515 int print_searching = 0, print_total = 0;
9516 int print_deltify = 0, print_written = 0, print_sent = 0;
9518 if (a->verbosity < 0)
9519 return NULL;
9521 if (refname) {
9522 const char *status = success ? "accepted" : "rejected";
9524 if (success) {
9525 struct got_pathlist_entry *pe;
9526 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9527 const char *branchname = pe->path;
9528 if (got_path_cmp(branchname, refname,
9529 strlen(branchname), strlen(refname)) == 0) {
9530 status = "deleted";
9531 a->sent_something = 1;
9532 break;
9537 if (a->printed_something)
9538 putchar('\n');
9539 printf("Server has %s %s", status, refname);
9540 if (errmsg)
9541 printf(": %s", errmsg);
9542 a->printed_something = 1;
9543 return NULL;
9546 if (a->last_ncolored != ncolored) {
9547 print_colored = 1;
9548 a->last_ncolored = ncolored;
9551 if (a->last_nfound != nfound) {
9552 print_colored = 1;
9553 print_found = 1;
9554 a->last_nfound = nfound;
9557 if (a->last_ntrees != ntrees) {
9558 print_colored = 1;
9559 print_found = 1;
9560 print_trees = 1;
9561 a->last_ntrees = ntrees;
9564 if ((print_colored || print_found || print_trees) &&
9565 !a->loading_done) {
9566 printf("\r");
9567 print_load_info(print_colored, print_found, print_trees,
9568 ncolored, nfound, ntrees);
9569 a->printed_something = 1;
9570 fflush(stdout);
9571 return NULL;
9572 } else if (!a->loading_done) {
9573 printf("\r");
9574 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9575 printf("\n");
9576 a->loading_done = 1;
9579 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9580 return got_error_from_errno("fmt_scaled");
9581 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9582 return got_error_from_errno("fmt_scaled");
9584 if (a->last_ncommits != ncommits) {
9585 print_searching = 1;
9586 a->last_ncommits = ncommits;
9589 if (a->last_nobj_total != nobj_total) {
9590 print_searching = 1;
9591 print_total = 1;
9592 a->last_nobj_total = nobj_total;
9595 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9596 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9597 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9598 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9599 return got_error(GOT_ERR_NO_SPACE);
9602 if (nobj_deltify > 0 || nobj_written > 0) {
9603 if (nobj_deltify > 0) {
9604 p_deltify = (nobj_deltify * 100) / nobj_total;
9605 if (p_deltify != a->last_p_deltify) {
9606 a->last_p_deltify = p_deltify;
9607 print_searching = 1;
9608 print_total = 1;
9609 print_deltify = 1;
9612 if (nobj_written > 0) {
9613 p_written = (nobj_written * 100) / nobj_total;
9614 if (p_written != a->last_p_written) {
9615 a->last_p_written = p_written;
9616 print_searching = 1;
9617 print_total = 1;
9618 print_deltify = 1;
9619 print_written = 1;
9624 if (bytes_sent > 0) {
9625 p_sent = (bytes_sent * 100) / packfile_size;
9626 if (p_sent != a->last_p_sent) {
9627 a->last_p_sent = p_sent;
9628 print_searching = 1;
9629 print_total = 1;
9630 print_deltify = 1;
9631 print_written = 1;
9632 print_sent = 1;
9634 a->sent_something = 1;
9637 if (print_searching || print_total || print_deltify || print_written ||
9638 print_sent)
9639 printf("\r");
9640 if (print_searching)
9641 printf("packing %d reference%s", ncommits,
9642 ncommits == 1 ? "" : "s");
9643 if (print_total)
9644 printf("; %d object%s", nobj_total,
9645 nobj_total == 1 ? "" : "s");
9646 if (print_deltify)
9647 printf("; deltify: %d%%", p_deltify);
9648 if (print_sent)
9649 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9650 scaled_packsize, p_sent);
9651 else if (print_written)
9652 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9653 scaled_packsize, p_written);
9654 if (print_searching || print_total || print_deltify ||
9655 print_written || print_sent) {
9656 a->printed_something = 1;
9657 fflush(stdout);
9659 return NULL;
9662 static const struct got_error *
9663 cmd_send(int argc, char *argv[])
9665 const struct got_error *error = NULL;
9666 char *cwd = NULL, *repo_path = NULL;
9667 const char *remote_name;
9668 char *proto = NULL, *host = NULL, *port = NULL;
9669 char *repo_name = NULL, *server_path = NULL;
9670 const struct got_remote_repo *remotes, *remote = NULL;
9671 int nremotes, nbranches = 0, ndelete_branches = 0;
9672 struct got_repository *repo = NULL;
9673 struct got_worktree *worktree = NULL;
9674 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9675 struct got_pathlist_head branches;
9676 struct got_pathlist_head tags;
9677 struct got_reflist_head all_branches;
9678 struct got_reflist_head all_tags;
9679 struct got_pathlist_head delete_args;
9680 struct got_pathlist_head delete_branches;
9681 struct got_reflist_entry *re;
9682 struct got_pathlist_entry *pe;
9683 int i, ch, sendfd = -1, sendstatus;
9684 pid_t sendpid = -1;
9685 struct got_send_progress_arg spa;
9686 int verbosity = 0, overwrite_refs = 0;
9687 int send_all_branches = 0, send_all_tags = 0;
9688 struct got_reference *ref = NULL;
9689 int *pack_fds = NULL;
9691 TAILQ_INIT(&branches);
9692 TAILQ_INIT(&tags);
9693 TAILQ_INIT(&all_branches);
9694 TAILQ_INIT(&all_tags);
9695 TAILQ_INIT(&delete_args);
9696 TAILQ_INIT(&delete_branches);
9698 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9699 switch (ch) {
9700 case 'a':
9701 send_all_branches = 1;
9702 break;
9703 case 'b':
9704 error = got_pathlist_append(&branches, optarg, NULL);
9705 if (error)
9706 return error;
9707 nbranches++;
9708 break;
9709 case 'd':
9710 error = got_pathlist_append(&delete_args, optarg, NULL);
9711 if (error)
9712 return error;
9713 break;
9714 case 'f':
9715 overwrite_refs = 1;
9716 break;
9717 case 'q':
9718 verbosity = -1;
9719 break;
9720 case 'r':
9721 repo_path = realpath(optarg, NULL);
9722 if (repo_path == NULL)
9723 return got_error_from_errno2("realpath",
9724 optarg);
9725 got_path_strip_trailing_slashes(repo_path);
9726 break;
9727 case 'T':
9728 send_all_tags = 1;
9729 break;
9730 case 't':
9731 error = got_pathlist_append(&tags, optarg, NULL);
9732 if (error)
9733 return error;
9734 break;
9735 case 'v':
9736 if (verbosity < 0)
9737 verbosity = 0;
9738 else if (verbosity < 3)
9739 verbosity++;
9740 break;
9741 default:
9742 usage_send();
9743 /* NOTREACHED */
9746 argc -= optind;
9747 argv += optind;
9749 if (send_all_branches && !TAILQ_EMPTY(&branches))
9750 option_conflict('a', 'b');
9751 if (send_all_tags && !TAILQ_EMPTY(&tags))
9752 option_conflict('T', 't');
9755 if (argc == 0)
9756 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9757 else if (argc == 1)
9758 remote_name = argv[0];
9759 else
9760 usage_send();
9762 cwd = getcwd(NULL, 0);
9763 if (cwd == NULL) {
9764 error = got_error_from_errno("getcwd");
9765 goto done;
9768 error = got_repo_pack_fds_open(&pack_fds);
9769 if (error != NULL)
9770 goto done;
9772 if (repo_path == NULL) {
9773 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9774 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9775 goto done;
9776 else
9777 error = NULL;
9778 if (worktree) {
9779 repo_path =
9780 strdup(got_worktree_get_repo_path(worktree));
9781 if (repo_path == NULL)
9782 error = got_error_from_errno("strdup");
9783 if (error)
9784 goto done;
9785 } else {
9786 repo_path = strdup(cwd);
9787 if (repo_path == NULL) {
9788 error = got_error_from_errno("strdup");
9789 goto done;
9794 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9795 if (error)
9796 goto done;
9798 if (worktree) {
9799 worktree_conf = got_worktree_get_gotconfig(worktree);
9800 if (worktree_conf) {
9801 got_gotconfig_get_remotes(&nremotes, &remotes,
9802 worktree_conf);
9803 for (i = 0; i < nremotes; i++) {
9804 if (strcmp(remotes[i].name, remote_name) == 0) {
9805 remote = &remotes[i];
9806 break;
9811 if (remote == NULL) {
9812 repo_conf = got_repo_get_gotconfig(repo);
9813 if (repo_conf) {
9814 got_gotconfig_get_remotes(&nremotes, &remotes,
9815 repo_conf);
9816 for (i = 0; i < nremotes; i++) {
9817 if (strcmp(remotes[i].name, remote_name) == 0) {
9818 remote = &remotes[i];
9819 break;
9824 if (remote == NULL) {
9825 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9826 for (i = 0; i < nremotes; i++) {
9827 if (strcmp(remotes[i].name, remote_name) == 0) {
9828 remote = &remotes[i];
9829 break;
9833 if (remote == NULL) {
9834 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9835 goto done;
9838 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9839 &repo_name, remote->send_url);
9840 if (error)
9841 goto done;
9843 if (strcmp(proto, "git") == 0) {
9844 #ifndef PROFILE
9845 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9846 "sendfd dns inet unveil", NULL) == -1)
9847 err(1, "pledge");
9848 #endif
9849 } else if (strcmp(proto, "git+ssh") == 0 ||
9850 strcmp(proto, "ssh") == 0) {
9851 #ifndef PROFILE
9852 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9853 "sendfd unveil", NULL) == -1)
9854 err(1, "pledge");
9855 #endif
9856 } else if (strcmp(proto, "http") == 0 ||
9857 strcmp(proto, "git+http") == 0) {
9858 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9859 goto done;
9860 } else {
9861 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9862 goto done;
9865 error = got_dial_apply_unveil(proto);
9866 if (error)
9867 goto done;
9869 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9870 if (error)
9871 goto done;
9873 if (send_all_branches) {
9874 error = got_ref_list(&all_branches, repo, "refs/heads",
9875 got_ref_cmp_by_name, NULL);
9876 if (error)
9877 goto done;
9878 TAILQ_FOREACH(re, &all_branches, entry) {
9879 const char *branchname = got_ref_get_name(re->ref);
9880 error = got_pathlist_append(&branches,
9881 branchname, NULL);
9882 if (error)
9883 goto done;
9884 nbranches++;
9886 } else if (nbranches == 0) {
9887 for (i = 0; i < remote->nsend_branches; i++) {
9888 error = got_pathlist_append(&branches,
9889 remote->send_branches[i], NULL);
9890 if (error)
9891 goto done;
9895 if (send_all_tags) {
9896 error = got_ref_list(&all_tags, repo, "refs/tags",
9897 got_ref_cmp_by_name, NULL);
9898 if (error)
9899 goto done;
9900 TAILQ_FOREACH(re, &all_tags, entry) {
9901 const char *tagname = got_ref_get_name(re->ref);
9902 error = got_pathlist_append(&tags,
9903 tagname, NULL);
9904 if (error)
9905 goto done;
9910 * To prevent accidents only branches in refs/heads/ can be deleted
9911 * with 'got send -d'.
9912 * Deleting anything else requires local repository access or Git.
9914 TAILQ_FOREACH(pe, &delete_args, entry) {
9915 const char *branchname = pe->path;
9916 char *s;
9917 struct got_pathlist_entry *new;
9918 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9919 s = strdup(branchname);
9920 if (s == NULL) {
9921 error = got_error_from_errno("strdup");
9922 goto done;
9924 } else {
9925 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9926 error = got_error_from_errno("asprintf");
9927 goto done;
9930 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9931 if (error || new == NULL /* duplicate */)
9932 free(s);
9933 if (error)
9934 goto done;
9935 ndelete_branches++;
9938 if (nbranches == 0 && ndelete_branches == 0) {
9939 struct got_reference *head_ref;
9940 if (worktree)
9941 error = got_ref_open(&head_ref, repo,
9942 got_worktree_get_head_ref_name(worktree), 0);
9943 else
9944 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9945 if (error)
9946 goto done;
9947 if (got_ref_is_symbolic(head_ref)) {
9948 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9949 got_ref_close(head_ref);
9950 if (error)
9951 goto done;
9952 } else
9953 ref = head_ref;
9954 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9955 NULL);
9956 if (error)
9957 goto done;
9958 nbranches++;
9961 if (verbosity >= 0) {
9962 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9963 remote->name, proto, host,
9964 port ? ":" : "", port ? port : "",
9965 *server_path == '/' ? "" : "/", server_path);
9968 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9969 server_path, verbosity);
9970 if (error)
9971 goto done;
9973 memset(&spa, 0, sizeof(spa));
9974 spa.last_scaled_packsize[0] = '\0';
9975 spa.last_p_deltify = -1;
9976 spa.last_p_written = -1;
9977 spa.verbosity = verbosity;
9978 spa.delete_branches = &delete_branches;
9979 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9980 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9981 check_cancelled, NULL);
9982 if (spa.printed_something)
9983 putchar('\n');
9984 if (error)
9985 goto done;
9986 if (!spa.sent_something && verbosity >= 0)
9987 printf("Already up-to-date\n");
9988 done:
9989 if (sendpid > 0) {
9990 if (kill(sendpid, SIGTERM) == -1)
9991 error = got_error_from_errno("kill");
9992 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9993 error = got_error_from_errno("waitpid");
9995 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9996 error = got_error_from_errno("close");
9997 if (repo) {
9998 const struct got_error *close_err = got_repo_close(repo);
9999 if (error == NULL)
10000 error = close_err;
10002 if (worktree)
10003 got_worktree_close(worktree);
10004 if (pack_fds) {
10005 const struct got_error *pack_err =
10006 got_repo_pack_fds_close(pack_fds);
10007 if (error == NULL)
10008 error = pack_err;
10010 if (ref)
10011 got_ref_close(ref);
10012 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10013 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10014 got_ref_list_free(&all_branches);
10015 got_ref_list_free(&all_tags);
10016 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10017 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10018 free(cwd);
10019 free(repo_path);
10020 free(proto);
10021 free(host);
10022 free(port);
10023 free(server_path);
10024 free(repo_name);
10025 return error;
10029 * Print and if delete is set delete all ref_prefix references.
10030 * If wanted_ref is not NULL, only print or delete this reference.
10032 static const struct got_error *
10033 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10034 const char *wanted_ref, int delete, struct got_worktree *worktree,
10035 struct got_repository *repo)
10037 const struct got_error *err;
10038 struct got_pathlist_head paths;
10039 struct got_reflist_head refs;
10040 struct got_reflist_entry *re;
10041 struct got_reflist_object_id_map *refs_idmap = NULL;
10042 struct got_commit_object *commit = NULL;
10043 struct got_object_id *id = NULL;
10044 const char *header_prefix;
10045 char *uuidstr = NULL;
10046 int found = 0;
10048 TAILQ_INIT(&refs);
10049 TAILQ_INIT(&paths);
10051 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10052 if (err)
10053 goto done;
10055 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10056 if (err)
10057 goto done;
10059 if (worktree != NULL) {
10060 err = got_worktree_get_uuid(&uuidstr, worktree);
10061 if (err)
10062 goto done;
10065 if (wanted_ref) {
10066 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10067 wanted_ref += 11;
10070 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10071 header_prefix = "backout";
10072 else
10073 header_prefix = "cherrypick";
10075 TAILQ_FOREACH(re, &refs, entry) {
10076 const char *refname, *wt;
10078 refname = got_ref_get_name(re->ref);
10080 err = check_cancelled(NULL);
10081 if (err)
10082 goto done;
10084 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10085 refname += prefix_len + 1; /* skip '-' delimiter */
10086 else
10087 continue;
10089 wt = refname;
10091 if (worktree == NULL || strncmp(refname, uuidstr,
10092 GOT_WORKTREE_UUID_STRLEN) == 0)
10093 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10094 else
10095 continue;
10097 err = got_repo_match_object_id(&id, NULL, refname,
10098 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10099 if (err)
10100 goto done;
10102 err = got_object_open_as_commit(&commit, repo, id);
10103 if (err)
10104 goto done;
10106 if (wanted_ref)
10107 found = strncmp(wanted_ref, refname,
10108 strlen(wanted_ref)) == 0;
10109 if (wanted_ref && !found) {
10110 struct got_reflist_head *ci_refs;
10112 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10113 id);
10115 if (ci_refs) {
10116 char *refs_str = NULL;
10117 char const *r = NULL;
10119 err = build_refs_str(&refs_str, ci_refs, id,
10120 repo, 1);
10121 if (err)
10122 goto done;
10124 r = refs_str;
10125 while (r) {
10126 if (strncmp(r, wanted_ref,
10127 strlen(wanted_ref)) == 0) {
10128 found = 1;
10129 break;
10131 r = strchr(r, ' ');
10132 if (r)
10133 ++r;
10135 free(refs_str);
10139 if (wanted_ref == NULL || found) {
10140 if (delete) {
10141 err = got_ref_delete(re->ref, repo);
10142 if (err)
10143 goto done;
10144 printf("Deleted: ");
10145 err = print_commit_oneline(commit, id, repo,
10146 refs_idmap);
10147 } else {
10149 * Print paths modified by commit to help
10150 * associate commits with worktree changes.
10152 err = get_changed_paths(&paths, commit,
10153 repo, NULL);
10154 if (err)
10155 goto done;
10157 err = print_commit(commit, id, repo, NULL,
10158 &paths, NULL, 0, 0, refs_idmap, NULL,
10159 header_prefix);
10160 got_pathlist_free(&paths,
10161 GOT_PATHLIST_FREE_ALL);
10163 if (worktree == NULL)
10164 printf("work tree: %.*s\n\n",
10165 GOT_WORKTREE_UUID_STRLEN, wt);
10167 if (err || found)
10168 goto done;
10171 got_object_commit_close(commit);
10172 commit = NULL;
10173 free(id);
10174 id = NULL;
10177 if (wanted_ref != NULL && !found)
10178 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10180 done:
10181 free(id);
10182 free(uuidstr);
10183 got_ref_list_free(&refs);
10184 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10185 if (refs_idmap)
10186 got_reflist_object_id_map_free(refs_idmap);
10187 if (commit)
10188 got_object_commit_close(commit);
10189 return err;
10193 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10194 * identified by id for log messages to prepopulate the editor on commit.
10196 static const struct got_error *
10197 logmsg_ref(struct got_object_id *id, const char *prefix,
10198 struct got_worktree *worktree, struct got_repository *repo)
10200 const struct got_error *err = NULL;
10201 char *idstr, *ref = NULL, *refname = NULL;
10202 int histedit_in_progress;
10203 int rebase_in_progress, merge_in_progress;
10206 * Silenty refuse to create merge reference if any histedit, merge,
10207 * or rebase operation is in progress.
10209 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10210 worktree);
10211 if (err)
10212 return err;
10213 if (histedit_in_progress)
10214 return NULL;
10216 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10217 if (err)
10218 return err;
10219 if (rebase_in_progress)
10220 return NULL;
10222 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10223 repo);
10224 if (err)
10225 return err;
10226 if (merge_in_progress)
10227 return NULL;
10229 err = got_object_id_str(&idstr, id);
10230 if (err)
10231 return err;
10233 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10234 if (err)
10235 goto done;
10237 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10238 err = got_error_from_errno("asprintf");
10239 goto done;
10242 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10243 -1, repo);
10244 done:
10245 free(ref);
10246 free(idstr);
10247 free(refname);
10248 return err;
10251 __dead static void
10252 usage_cherrypick(void)
10254 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10255 getprogname());
10256 exit(1);
10259 static const struct got_error *
10260 cmd_cherrypick(int argc, char *argv[])
10262 const struct got_error *error = NULL;
10263 struct got_worktree *worktree = NULL;
10264 struct got_repository *repo = NULL;
10265 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10266 struct got_object_id *commit_id = NULL;
10267 struct got_commit_object *commit = NULL;
10268 struct got_object_qid *pid;
10269 int ch, list_refs = 0, remove_refs = 0;
10270 struct got_update_progress_arg upa;
10271 int *pack_fds = NULL;
10273 #ifndef PROFILE
10274 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10275 "unveil", NULL) == -1)
10276 err(1, "pledge");
10277 #endif
10279 while ((ch = getopt(argc, argv, "lX")) != -1) {
10280 switch (ch) {
10281 case 'l':
10282 list_refs = 1;
10283 break;
10284 case 'X':
10285 remove_refs = 1;
10286 break;
10287 default:
10288 usage_cherrypick();
10289 /* NOTREACHED */
10293 argc -= optind;
10294 argv += optind;
10296 if (list_refs || remove_refs) {
10297 if (argc != 0 && argc != 1)
10298 usage_cherrypick();
10299 } else if (argc != 1)
10300 usage_cherrypick();
10301 if (list_refs && remove_refs)
10302 option_conflict('l', 'X');
10304 cwd = getcwd(NULL, 0);
10305 if (cwd == NULL) {
10306 error = got_error_from_errno("getcwd");
10307 goto done;
10310 error = got_repo_pack_fds_open(&pack_fds);
10311 if (error != NULL)
10312 goto done;
10314 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10315 if (error) {
10316 if (list_refs || remove_refs) {
10317 if (error->code != GOT_ERR_NOT_WORKTREE)
10318 goto done;
10319 } else {
10320 if (error->code == GOT_ERR_NOT_WORKTREE)
10321 error = wrap_not_worktree_error(error,
10322 "cherrypick", cwd);
10323 goto done;
10327 error = got_repo_open(&repo,
10328 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10329 NULL, pack_fds);
10330 if (error != NULL)
10331 goto done;
10333 error = apply_unveil(got_repo_get_path(repo), 0,
10334 worktree ? got_worktree_get_root_path(worktree) : NULL);
10335 if (error)
10336 goto done;
10338 if (list_refs || remove_refs) {
10339 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10340 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10341 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10342 goto done;
10345 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10346 if (error != NULL)
10347 goto done;
10349 error = got_repo_match_object_id(&commit_id, NULL,
10350 keyword_idstr != NULL ? keyword_idstr : argv[0],
10351 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10352 if (error)
10353 goto done;
10354 error = got_object_id_str(&commit_id_str, commit_id);
10355 if (error)
10356 goto done;
10358 error = got_object_open_as_commit(&commit, repo, commit_id);
10359 if (error)
10360 goto done;
10361 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10362 memset(&upa, 0, sizeof(upa));
10363 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10364 commit_id, repo, update_progress, &upa, check_cancelled,
10365 NULL);
10366 if (error != NULL)
10367 goto done;
10369 if (upa.did_something) {
10370 error = logmsg_ref(commit_id,
10371 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10372 if (error)
10373 goto done;
10374 printf("Merged commit %s\n", commit_id_str);
10376 print_merge_progress_stats(&upa);
10377 done:
10378 free(cwd);
10379 free(keyword_idstr);
10380 if (commit)
10381 got_object_commit_close(commit);
10382 free(commit_id_str);
10383 if (worktree)
10384 got_worktree_close(worktree);
10385 if (repo) {
10386 const struct got_error *close_err = got_repo_close(repo);
10387 if (error == NULL)
10388 error = close_err;
10390 if (pack_fds) {
10391 const struct got_error *pack_err =
10392 got_repo_pack_fds_close(pack_fds);
10393 if (error == NULL)
10394 error = pack_err;
10397 return error;
10400 __dead static void
10401 usage_backout(void)
10403 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10404 exit(1);
10407 static const struct got_error *
10408 cmd_backout(int argc, char *argv[])
10410 const struct got_error *error = NULL;
10411 struct got_worktree *worktree = NULL;
10412 struct got_repository *repo = NULL;
10413 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10414 struct got_object_id *commit_id = NULL;
10415 struct got_commit_object *commit = NULL;
10416 struct got_object_qid *pid;
10417 int ch, list_refs = 0, remove_refs = 0;
10418 struct got_update_progress_arg upa;
10419 int *pack_fds = NULL;
10421 #ifndef PROFILE
10422 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10423 "unveil", NULL) == -1)
10424 err(1, "pledge");
10425 #endif
10427 while ((ch = getopt(argc, argv, "lX")) != -1) {
10428 switch (ch) {
10429 case 'l':
10430 list_refs = 1;
10431 break;
10432 case 'X':
10433 remove_refs = 1;
10434 break;
10435 default:
10436 usage_backout();
10437 /* NOTREACHED */
10441 argc -= optind;
10442 argv += optind;
10444 if (list_refs || remove_refs) {
10445 if (argc != 0 && argc != 1)
10446 usage_backout();
10447 } else if (argc != 1)
10448 usage_backout();
10449 if (list_refs && remove_refs)
10450 option_conflict('l', 'X');
10452 cwd = getcwd(NULL, 0);
10453 if (cwd == NULL) {
10454 error = got_error_from_errno("getcwd");
10455 goto done;
10458 error = got_repo_pack_fds_open(&pack_fds);
10459 if (error != NULL)
10460 goto done;
10462 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10463 if (error) {
10464 if (list_refs || remove_refs) {
10465 if (error->code != GOT_ERR_NOT_WORKTREE)
10466 goto done;
10467 } else {
10468 if (error->code == GOT_ERR_NOT_WORKTREE)
10469 error = wrap_not_worktree_error(error,
10470 "backout", cwd);
10471 goto done;
10475 error = got_repo_open(&repo,
10476 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10477 NULL, pack_fds);
10478 if (error != NULL)
10479 goto done;
10481 error = apply_unveil(got_repo_get_path(repo), 0,
10482 worktree ? got_worktree_get_root_path(worktree) : NULL);
10483 if (error)
10484 goto done;
10486 if (list_refs || remove_refs) {
10487 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10488 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10489 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10490 goto done;
10493 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10494 if (error != NULL)
10495 goto done;
10497 error = got_repo_match_object_id(&commit_id, NULL,
10498 keyword_idstr != NULL ? keyword_idstr : argv[0],
10499 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10500 if (error)
10501 goto done;
10502 error = got_object_id_str(&commit_id_str, commit_id);
10503 if (error)
10504 goto done;
10506 error = got_object_open_as_commit(&commit, repo, commit_id);
10507 if (error)
10508 goto done;
10509 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10510 if (pid == NULL) {
10511 error = got_error(GOT_ERR_ROOT_COMMIT);
10512 goto done;
10515 memset(&upa, 0, sizeof(upa));
10516 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10517 repo, update_progress, &upa, check_cancelled, NULL);
10518 if (error != NULL)
10519 goto done;
10521 if (upa.did_something) {
10522 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10523 worktree, repo);
10524 if (error)
10525 goto done;
10526 printf("Backed out commit %s\n", commit_id_str);
10528 print_merge_progress_stats(&upa);
10529 done:
10530 free(cwd);
10531 free(keyword_idstr);
10532 if (commit)
10533 got_object_commit_close(commit);
10534 free(commit_id_str);
10535 if (worktree)
10536 got_worktree_close(worktree);
10537 if (repo) {
10538 const struct got_error *close_err = got_repo_close(repo);
10539 if (error == NULL)
10540 error = close_err;
10542 if (pack_fds) {
10543 const struct got_error *pack_err =
10544 got_repo_pack_fds_close(pack_fds);
10545 if (error == NULL)
10546 error = pack_err;
10548 return error;
10551 __dead static void
10552 usage_rebase(void)
10554 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10555 exit(1);
10558 static void
10559 trim_logmsg(char *logmsg, int limit)
10561 char *nl;
10562 size_t len;
10564 len = strlen(logmsg);
10565 if (len > limit)
10566 len = limit;
10567 logmsg[len] = '\0';
10568 nl = strchr(logmsg, '\n');
10569 if (nl)
10570 *nl = '\0';
10573 static const struct got_error *
10574 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10576 const struct got_error *err;
10577 char *logmsg0 = NULL;
10578 const char *s;
10580 err = got_object_commit_get_logmsg(&logmsg0, commit);
10581 if (err)
10582 return err;
10584 s = logmsg0;
10585 while (isspace((unsigned char)s[0]))
10586 s++;
10588 *logmsg = strdup(s);
10589 if (*logmsg == NULL) {
10590 err = got_error_from_errno("strdup");
10591 goto done;
10594 trim_logmsg(*logmsg, limit);
10595 done:
10596 free(logmsg0);
10597 return err;
10600 static const struct got_error *
10601 show_rebase_merge_conflict(struct got_object_id *id,
10602 struct got_repository *repo)
10604 const struct got_error *err;
10605 struct got_commit_object *commit = NULL;
10606 char *id_str = NULL, *logmsg = NULL;
10608 err = got_object_open_as_commit(&commit, repo, id);
10609 if (err)
10610 return err;
10612 err = got_object_id_str(&id_str, id);
10613 if (err)
10614 goto done;
10616 id_str[12] = '\0';
10618 err = get_short_logmsg(&logmsg, 42, commit);
10619 if (err)
10620 goto done;
10622 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10623 done:
10624 free(id_str);
10625 got_object_commit_close(commit);
10626 free(logmsg);
10627 return err;
10630 static const struct got_error *
10631 show_rebase_progress(struct got_commit_object *commit,
10632 struct got_object_id *old_id, struct got_object_id *new_id)
10634 const struct got_error *err;
10635 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10637 err = got_object_id_str(&old_id_str, old_id);
10638 if (err)
10639 goto done;
10641 if (new_id) {
10642 err = got_object_id_str(&new_id_str, new_id);
10643 if (err)
10644 goto done;
10647 old_id_str[12] = '\0';
10648 if (new_id_str)
10649 new_id_str[12] = '\0';
10651 err = get_short_logmsg(&logmsg, 42, commit);
10652 if (err)
10653 goto done;
10655 printf("%s -> %s: %s\n", old_id_str,
10656 new_id_str ? new_id_str : "no-op change", logmsg);
10657 done:
10658 free(old_id_str);
10659 free(new_id_str);
10660 free(logmsg);
10661 return err;
10664 static const struct got_error *
10665 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10666 struct got_reference *branch, struct got_reference *tmp_branch,
10667 struct got_repository *repo, int create_backup)
10669 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10670 return got_worktree_rebase_complete(worktree, fileindex,
10671 tmp_branch, branch, repo, create_backup);
10674 static const struct got_error *
10675 rebase_commit(struct got_pathlist_head *merged_paths,
10676 struct got_worktree *worktree, struct got_fileindex *fileindex,
10677 struct got_reference *tmp_branch, const char *committer,
10678 struct got_object_id *commit_id, int allow_conflict,
10679 struct got_repository *repo)
10681 const struct got_error *error;
10682 struct got_commit_object *commit;
10683 struct got_object_id *new_commit_id;
10685 error = got_object_open_as_commit(&commit, repo, commit_id);
10686 if (error)
10687 return error;
10689 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10690 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10691 allow_conflict, repo);
10692 if (error) {
10693 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10694 goto done;
10695 error = show_rebase_progress(commit, commit_id, NULL);
10696 } else {
10697 error = show_rebase_progress(commit, commit_id, new_commit_id);
10698 free(new_commit_id);
10700 done:
10701 got_object_commit_close(commit);
10702 return error;
10705 struct check_path_prefix_arg {
10706 const char *path_prefix;
10707 size_t len;
10708 int errcode;
10711 static const struct got_error *
10712 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10713 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10714 struct got_object_id *id1, struct got_object_id *id2,
10715 const char *path1, const char *path2,
10716 mode_t mode1, mode_t mode2, struct got_repository *repo)
10718 struct check_path_prefix_arg *a = arg;
10720 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10721 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10722 return got_error(a->errcode);
10724 return NULL;
10727 static const struct got_error *
10728 check_path_prefix(struct got_object_id *parent_id,
10729 struct got_object_id *commit_id, const char *path_prefix,
10730 int errcode, struct got_repository *repo)
10732 const struct got_error *err;
10733 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10734 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10735 struct check_path_prefix_arg cpp_arg;
10737 if (got_path_is_root_dir(path_prefix))
10738 return NULL;
10740 err = got_object_open_as_commit(&commit, repo, commit_id);
10741 if (err)
10742 goto done;
10744 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10745 if (err)
10746 goto done;
10748 err = got_object_open_as_tree(&tree1, repo,
10749 got_object_commit_get_tree_id(parent_commit));
10750 if (err)
10751 goto done;
10753 err = got_object_open_as_tree(&tree2, repo,
10754 got_object_commit_get_tree_id(commit));
10755 if (err)
10756 goto done;
10758 cpp_arg.path_prefix = path_prefix;
10759 while (cpp_arg.path_prefix[0] == '/')
10760 cpp_arg.path_prefix++;
10761 cpp_arg.len = strlen(cpp_arg.path_prefix);
10762 cpp_arg.errcode = errcode;
10763 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10764 check_path_prefix_in_diff, &cpp_arg, 0);
10765 done:
10766 if (tree1)
10767 got_object_tree_close(tree1);
10768 if (tree2)
10769 got_object_tree_close(tree2);
10770 if (commit)
10771 got_object_commit_close(commit);
10772 if (parent_commit)
10773 got_object_commit_close(parent_commit);
10774 return err;
10777 static const struct got_error *
10778 collect_commits(struct got_object_id_queue *commits,
10779 struct got_object_id *initial_commit_id,
10780 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10781 const char *path_prefix, int path_prefix_errcode,
10782 struct got_repository *repo)
10784 const struct got_error *err = NULL;
10785 struct got_commit_graph *graph = NULL;
10786 struct got_object_id parent_id, commit_id;
10787 struct got_object_qid *qid;
10789 err = got_commit_graph_open(&graph, "/", 1);
10790 if (err)
10791 return err;
10793 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10794 check_cancelled, NULL);
10795 if (err)
10796 goto done;
10798 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10799 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10800 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10801 check_cancelled, NULL);
10802 if (err) {
10803 if (err->code == GOT_ERR_ITER_COMPLETED) {
10804 err = got_error_msg(GOT_ERR_ANCESTRY,
10805 "ran out of commits to rebase before "
10806 "youngest common ancestor commit has "
10807 "been reached?!?");
10809 goto done;
10810 } else {
10811 err = check_path_prefix(&parent_id, &commit_id,
10812 path_prefix, path_prefix_errcode, repo);
10813 if (err)
10814 goto done;
10816 err = got_object_qid_alloc(&qid, &commit_id);
10817 if (err)
10818 goto done;
10819 STAILQ_INSERT_HEAD(commits, qid, entry);
10821 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10824 done:
10825 got_commit_graph_close(graph);
10826 return err;
10829 static const struct got_error *
10830 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10832 const struct got_error *err = NULL;
10833 time_t committer_time;
10834 struct tm tm;
10835 char datebuf[11]; /* YYYY-MM-DD + NUL */
10836 char *author0 = NULL, *author, *smallerthan;
10837 char *logmsg0 = NULL, *logmsg, *newline;
10839 committer_time = got_object_commit_get_committer_time(commit);
10840 if (gmtime_r(&committer_time, &tm) == NULL)
10841 return got_error_from_errno("gmtime_r");
10842 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10843 return got_error(GOT_ERR_NO_SPACE);
10845 author0 = strdup(got_object_commit_get_author(commit));
10846 if (author0 == NULL)
10847 return got_error_from_errno("strdup");
10848 author = author0;
10849 smallerthan = strchr(author, '<');
10850 if (smallerthan && smallerthan[1] != '\0')
10851 author = smallerthan + 1;
10852 author[strcspn(author, "@>")] = '\0';
10854 err = got_object_commit_get_logmsg(&logmsg0, commit);
10855 if (err)
10856 goto done;
10857 logmsg = logmsg0;
10858 while (*logmsg == '\n')
10859 logmsg++;
10860 newline = strchr(logmsg, '\n');
10861 if (newline)
10862 *newline = '\0';
10864 if (asprintf(brief_str, "%s %s %s",
10865 datebuf, author, logmsg) == -1)
10866 err = got_error_from_errno("asprintf");
10867 done:
10868 free(author0);
10869 free(logmsg0);
10870 return err;
10873 static const struct got_error *
10874 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10875 struct got_repository *repo)
10877 const struct got_error *err;
10878 char *id_str;
10880 err = got_object_id_str(&id_str, id);
10881 if (err)
10882 return err;
10884 err = got_ref_delete(ref, repo);
10885 if (err)
10886 goto done;
10888 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10889 done:
10890 free(id_str);
10891 return err;
10894 static const struct got_error *
10895 print_backup_ref(const char *branch_name, const char *new_id_str,
10896 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10897 struct got_reflist_object_id_map *refs_idmap,
10898 struct got_repository *repo)
10900 const struct got_error *err = NULL;
10901 struct got_reflist_head *refs;
10902 char *refs_str = NULL;
10903 struct got_object_id *new_commit_id = NULL;
10904 struct got_commit_object *new_commit = NULL;
10905 char *new_commit_brief_str = NULL;
10906 struct got_object_id *yca_id = NULL;
10907 struct got_commit_object *yca_commit = NULL;
10908 char *yca_id_str = NULL, *yca_brief_str = NULL;
10909 char *custom_refs_str;
10911 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10912 return got_error_from_errno("asprintf");
10914 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10915 0, 0, refs_idmap, custom_refs_str, NULL);
10916 if (err)
10917 goto done;
10919 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10920 if (err)
10921 goto done;
10923 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10924 if (refs) {
10925 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10926 if (err)
10927 goto done;
10930 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10931 if (err)
10932 goto done;
10934 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10935 if (err)
10936 goto done;
10938 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10939 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10940 if (err)
10941 goto done;
10943 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10944 refs_str ? " (" : "", refs_str ? refs_str : "",
10945 refs_str ? ")" : "", new_commit_brief_str);
10946 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10947 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10948 free(refs_str);
10949 refs_str = NULL;
10951 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10952 if (err)
10953 goto done;
10955 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10956 if (err)
10957 goto done;
10959 err = got_object_id_str(&yca_id_str, yca_id);
10960 if (err)
10961 goto done;
10963 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10964 if (refs) {
10965 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10966 if (err)
10967 goto done;
10969 printf("history forked at %s%s%s%s\n %s\n",
10970 yca_id_str,
10971 refs_str ? " (" : "", refs_str ? refs_str : "",
10972 refs_str ? ")" : "", yca_brief_str);
10974 done:
10975 free(custom_refs_str);
10976 free(new_commit_id);
10977 free(refs_str);
10978 free(yca_id);
10979 free(yca_id_str);
10980 free(yca_brief_str);
10981 if (new_commit)
10982 got_object_commit_close(new_commit);
10983 if (yca_commit)
10984 got_object_commit_close(yca_commit);
10986 return err;
10989 static const struct got_error *
10990 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10991 struct got_repository *repo)
10993 const struct got_error *err;
10994 struct got_reflist_head refs;
10995 struct got_reflist_entry *re;
10996 char *uuidstr = NULL;
10997 static char msg[160];
10999 TAILQ_INIT(&refs);
11001 err = got_worktree_get_uuid(&uuidstr, worktree);
11002 if (err)
11003 goto done;
11005 err = got_ref_list(&refs, repo, "refs/got/worktree",
11006 got_ref_cmp_by_name, repo);
11007 if (err)
11008 goto done;
11010 TAILQ_FOREACH(re, &refs, entry) {
11011 const char *cmd, *refname, *type;
11013 refname = got_ref_get_name(re->ref);
11015 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11016 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11017 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11018 cmd = "cherrypick";
11019 type = "cherrypicked";
11020 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11021 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11022 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11023 cmd = "backout";
11024 type = "backed-out";
11025 } else
11026 continue;
11028 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11029 continue;
11031 snprintf(msg, sizeof(msg),
11032 "work tree has references created by %s commits which "
11033 "must be removed with 'got %s -X' before running the %s "
11034 "command", type, cmd, caller);
11035 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11036 goto done;
11039 done:
11040 free(uuidstr);
11041 got_ref_list_free(&refs);
11042 return err;
11045 static const struct got_error *
11046 process_backup_refs(const char *backup_ref_prefix,
11047 const char *wanted_branch_name,
11048 int delete, struct got_repository *repo)
11050 const struct got_error *err;
11051 struct got_reflist_head refs, backup_refs;
11052 struct got_reflist_entry *re;
11053 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11054 struct got_object_id *old_commit_id = NULL;
11055 char *branch_name = NULL;
11056 struct got_commit_object *old_commit = NULL;
11057 struct got_reflist_object_id_map *refs_idmap = NULL;
11058 int wanted_branch_found = 0;
11060 TAILQ_INIT(&refs);
11061 TAILQ_INIT(&backup_refs);
11063 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11064 if (err)
11065 return err;
11067 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11068 if (err)
11069 goto done;
11071 if (wanted_branch_name) {
11072 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11073 wanted_branch_name += 11;
11076 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11077 got_ref_cmp_by_commit_timestamp_descending, repo);
11078 if (err)
11079 goto done;
11081 TAILQ_FOREACH(re, &backup_refs, entry) {
11082 const char *refname = got_ref_get_name(re->ref);
11083 char *slash;
11085 err = check_cancelled(NULL);
11086 if (err)
11087 break;
11089 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11090 if (err)
11091 break;
11093 err = got_object_open_as_commit(&old_commit, repo,
11094 old_commit_id);
11095 if (err)
11096 break;
11098 if (strncmp(backup_ref_prefix, refname,
11099 backup_ref_prefix_len) == 0)
11100 refname += backup_ref_prefix_len;
11102 while (refname[0] == '/')
11103 refname++;
11105 branch_name = strdup(refname);
11106 if (branch_name == NULL) {
11107 err = got_error_from_errno("strdup");
11108 break;
11110 slash = strrchr(branch_name, '/');
11111 if (slash) {
11112 *slash = '\0';
11113 refname += strlen(branch_name) + 1;
11116 if (wanted_branch_name == NULL ||
11117 strcmp(wanted_branch_name, branch_name) == 0) {
11118 wanted_branch_found = 1;
11119 if (delete) {
11120 err = delete_backup_ref(re->ref,
11121 old_commit_id, repo);
11122 } else {
11123 err = print_backup_ref(branch_name, refname,
11124 old_commit_id, old_commit, refs_idmap,
11125 repo);
11127 if (err)
11128 break;
11131 free(old_commit_id);
11132 old_commit_id = NULL;
11133 free(branch_name);
11134 branch_name = NULL;
11135 got_object_commit_close(old_commit);
11136 old_commit = NULL;
11139 if (wanted_branch_name && !wanted_branch_found) {
11140 err = got_error_fmt(GOT_ERR_NOT_REF,
11141 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11143 done:
11144 if (refs_idmap)
11145 got_reflist_object_id_map_free(refs_idmap);
11146 got_ref_list_free(&refs);
11147 got_ref_list_free(&backup_refs);
11148 free(old_commit_id);
11149 free(branch_name);
11150 if (old_commit)
11151 got_object_commit_close(old_commit);
11152 return err;
11155 static const struct got_error *
11156 abort_progress(void *arg, unsigned char status, const char *path)
11159 * Unversioned files should not clutter progress output when
11160 * an operation is aborted.
11162 if (status == GOT_STATUS_UNVERSIONED)
11163 return NULL;
11165 return update_progress(arg, status, path);
11168 static const struct got_error *
11169 cmd_rebase(int argc, char *argv[])
11171 const struct got_error *error = NULL;
11172 struct got_worktree *worktree = NULL;
11173 struct got_repository *repo = NULL;
11174 struct got_fileindex *fileindex = NULL;
11175 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11176 struct got_reference *branch = NULL;
11177 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11178 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11179 struct got_object_id *resume_commit_id = NULL;
11180 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11181 struct got_object_id *head_commit_id = NULL;
11182 struct got_reference *head_ref = NULL;
11183 struct got_commit_object *commit = NULL;
11184 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11185 int histedit_in_progress = 0, merge_in_progress = 0;
11186 int create_backup = 1, list_backups = 0, delete_backups = 0;
11187 int allow_conflict = 0;
11188 struct got_object_id_queue commits;
11189 struct got_pathlist_head merged_paths;
11190 const struct got_object_id_queue *parent_ids;
11191 struct got_object_qid *qid, *pid;
11192 struct got_update_progress_arg upa;
11193 int *pack_fds = NULL;
11195 STAILQ_INIT(&commits);
11196 TAILQ_INIT(&merged_paths);
11197 memset(&upa, 0, sizeof(upa));
11199 #ifndef PROFILE
11200 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11201 "unveil", NULL) == -1)
11202 err(1, "pledge");
11203 #endif
11205 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11206 switch (ch) {
11207 case 'a':
11208 abort_rebase = 1;
11209 break;
11210 case 'C':
11211 allow_conflict = 1;
11212 break;
11213 case 'c':
11214 continue_rebase = 1;
11215 break;
11216 case 'l':
11217 list_backups = 1;
11218 break;
11219 case 'X':
11220 delete_backups = 1;
11221 break;
11222 default:
11223 usage_rebase();
11224 /* NOTREACHED */
11228 argc -= optind;
11229 argv += optind;
11231 if (list_backups) {
11232 if (abort_rebase)
11233 option_conflict('l', 'a');
11234 if (allow_conflict)
11235 option_conflict('l', 'C');
11236 if (continue_rebase)
11237 option_conflict('l', 'c');
11238 if (delete_backups)
11239 option_conflict('l', 'X');
11240 if (argc != 0 && argc != 1)
11241 usage_rebase();
11242 } else if (delete_backups) {
11243 if (abort_rebase)
11244 option_conflict('X', 'a');
11245 if (allow_conflict)
11246 option_conflict('X', 'C');
11247 if (continue_rebase)
11248 option_conflict('X', 'c');
11249 if (list_backups)
11250 option_conflict('l', 'X');
11251 if (argc != 0 && argc != 1)
11252 usage_rebase();
11253 } else if (allow_conflict) {
11254 if (abort_rebase)
11255 option_conflict('C', 'a');
11256 if (!continue_rebase)
11257 errx(1, "-C option requires -c");
11258 } else {
11259 if (abort_rebase && continue_rebase)
11260 usage_rebase();
11261 else if (abort_rebase || continue_rebase) {
11262 if (argc != 0)
11263 usage_rebase();
11264 } else if (argc != 1)
11265 usage_rebase();
11268 cwd = getcwd(NULL, 0);
11269 if (cwd == NULL) {
11270 error = got_error_from_errno("getcwd");
11271 goto done;
11274 error = got_repo_pack_fds_open(&pack_fds);
11275 if (error != NULL)
11276 goto done;
11278 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11279 if (error) {
11280 if (list_backups || delete_backups) {
11281 if (error->code != GOT_ERR_NOT_WORKTREE)
11282 goto done;
11283 } else {
11284 if (error->code == GOT_ERR_NOT_WORKTREE)
11285 error = wrap_not_worktree_error(error,
11286 "rebase", cwd);
11287 goto done;
11291 error = get_gitconfig_path(&gitconfig_path);
11292 if (error)
11293 goto done;
11294 error = got_repo_open(&repo,
11295 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11296 gitconfig_path, pack_fds);
11297 if (error != NULL)
11298 goto done;
11300 if (worktree != NULL && !list_backups && !delete_backups) {
11301 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11302 if (error)
11303 goto done;
11306 error = get_author(&committer, repo, worktree);
11307 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11308 goto done;
11310 error = apply_unveil(got_repo_get_path(repo), 0,
11311 worktree ? got_worktree_get_root_path(worktree) : NULL);
11312 if (error)
11313 goto done;
11315 if (list_backups || delete_backups) {
11316 error = process_backup_refs(
11317 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11318 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11319 goto done; /* nothing else to do */
11322 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11323 worktree);
11324 if (error)
11325 goto done;
11326 if (histedit_in_progress) {
11327 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11328 goto done;
11331 error = got_worktree_merge_in_progress(&merge_in_progress,
11332 worktree, repo);
11333 if (error)
11334 goto done;
11335 if (merge_in_progress) {
11336 error = got_error(GOT_ERR_MERGE_BUSY);
11337 goto done;
11340 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11341 if (error)
11342 goto done;
11344 if (abort_rebase) {
11345 if (!rebase_in_progress) {
11346 error = got_error(GOT_ERR_NOT_REBASING);
11347 goto done;
11349 error = got_worktree_rebase_continue(&resume_commit_id,
11350 &new_base_branch, &tmp_branch, &branch, &fileindex,
11351 worktree, repo);
11352 if (error)
11353 goto done;
11354 printf("Switching work tree to %s\n",
11355 got_ref_get_symref_target(new_base_branch));
11356 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11357 new_base_branch, abort_progress, &upa);
11358 if (error)
11359 goto done;
11360 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11361 print_merge_progress_stats(&upa);
11362 goto done; /* nothing else to do */
11365 if (continue_rebase) {
11366 if (!rebase_in_progress) {
11367 error = got_error(GOT_ERR_NOT_REBASING);
11368 goto done;
11370 error = got_worktree_rebase_continue(&resume_commit_id,
11371 &new_base_branch, &tmp_branch, &branch, &fileindex,
11372 worktree, repo);
11373 if (error)
11374 goto done;
11376 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11377 committer, resume_commit_id, allow_conflict, repo);
11378 if (error)
11379 goto done;
11381 yca_id = got_object_id_dup(resume_commit_id);
11382 if (yca_id == NULL) {
11383 error = got_error_from_errno("got_object_id_dup");
11384 goto done;
11386 } else {
11387 error = got_ref_open(&branch, repo, argv[0], 0);
11388 if (error != NULL)
11389 goto done;
11390 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11391 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11392 "will not rebase a branch which lives outside "
11393 "the \"refs/heads/\" reference namespace");
11394 goto done;
11398 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11399 if (error)
11400 goto done;
11402 if (!continue_rebase) {
11403 struct got_object_id *base_commit_id;
11405 error = got_ref_open(&head_ref, repo,
11406 got_worktree_get_head_ref_name(worktree), 0);
11407 if (error)
11408 goto done;
11409 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11410 if (error)
11411 goto done;
11412 base_commit_id = got_worktree_get_base_commit_id(worktree);
11413 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11414 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11415 goto done;
11418 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11419 base_commit_id, branch_head_commit_id, 1, repo,
11420 check_cancelled, NULL);
11421 if (error) {
11422 if (error->code == GOT_ERR_ANCESTRY) {
11423 error = got_error_msg(GOT_ERR_ANCESTRY,
11424 "specified branch shares no common "
11425 "ancestry with work tree's branch");
11427 goto done;
11430 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11431 struct got_pathlist_head paths;
11432 printf("%s is already based on %s\n",
11433 got_ref_get_name(branch),
11434 got_worktree_get_head_ref_name(worktree));
11435 error = switch_head_ref(branch, branch_head_commit_id,
11436 worktree, repo);
11437 if (error)
11438 goto done;
11439 error = got_worktree_set_base_commit_id(worktree, repo,
11440 branch_head_commit_id);
11441 if (error)
11442 goto done;
11443 TAILQ_INIT(&paths);
11444 error = got_pathlist_append(&paths, "", NULL);
11445 if (error)
11446 goto done;
11447 error = got_worktree_checkout_files(worktree,
11448 &paths, repo, update_progress, &upa,
11449 check_cancelled, NULL);
11450 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11451 if (error)
11452 goto done;
11453 if (upa.did_something) {
11454 char *id_str;
11455 error = got_object_id_str(&id_str,
11456 branch_head_commit_id);
11457 if (error)
11458 goto done;
11459 printf("Updated to %s: %s\n",
11460 got_worktree_get_head_ref_name(worktree),
11461 id_str);
11462 free(id_str);
11463 } else
11464 printf("Already up-to-date\n");
11465 print_update_progress_stats(&upa);
11466 goto done;
11470 commit_id = branch_head_commit_id;
11471 error = got_object_open_as_commit(&commit, repo, commit_id);
11472 if (error)
11473 goto done;
11475 parent_ids = got_object_commit_get_parent_ids(commit);
11476 pid = STAILQ_FIRST(parent_ids);
11477 if (pid) {
11478 error = collect_commits(&commits, commit_id, &pid->id,
11479 yca_id, got_worktree_get_path_prefix(worktree),
11480 GOT_ERR_REBASE_PATH, repo);
11481 if (error)
11482 goto done;
11485 got_object_commit_close(commit);
11486 commit = NULL;
11488 if (!continue_rebase) {
11489 error = got_worktree_rebase_prepare(&new_base_branch,
11490 &tmp_branch, &fileindex, worktree, branch, repo);
11491 if (error)
11492 goto done;
11495 if (STAILQ_EMPTY(&commits)) {
11496 if (continue_rebase) {
11497 error = rebase_complete(worktree, fileindex,
11498 branch, tmp_branch, repo, create_backup);
11499 goto done;
11500 } else {
11501 /* Fast-forward the reference of the branch. */
11502 struct got_object_id *new_head_commit_id;
11503 char *id_str;
11504 error = got_ref_resolve(&new_head_commit_id, repo,
11505 new_base_branch);
11506 if (error)
11507 goto done;
11508 error = got_object_id_str(&id_str, new_head_commit_id);
11509 if (error)
11510 goto done;
11511 printf("Forwarding %s to commit %s\n",
11512 got_ref_get_name(branch), id_str);
11513 free(id_str);
11514 error = got_ref_change_ref(branch,
11515 new_head_commit_id);
11516 if (error)
11517 goto done;
11518 /* No backup needed since objects did not change. */
11519 create_backup = 0;
11523 pid = NULL;
11524 STAILQ_FOREACH(qid, &commits, entry) {
11526 commit_id = &qid->id;
11527 parent_id = pid ? &pid->id : yca_id;
11528 pid = qid;
11530 memset(&upa, 0, sizeof(upa));
11531 error = got_worktree_rebase_merge_files(&merged_paths,
11532 worktree, fileindex, parent_id, commit_id, repo,
11533 update_progress, &upa, check_cancelled, NULL);
11534 if (error)
11535 goto done;
11537 print_merge_progress_stats(&upa);
11538 if (upa.conflicts > 0 || upa.missing > 0 ||
11539 upa.not_deleted > 0 || upa.unversioned > 0) {
11540 if (upa.conflicts > 0) {
11541 error = show_rebase_merge_conflict(&qid->id,
11542 repo);
11543 if (error)
11544 goto done;
11546 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11547 break;
11550 error = rebase_commit(&merged_paths, worktree, fileindex,
11551 tmp_branch, committer, commit_id, 0, repo);
11552 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11553 if (error)
11554 goto done;
11557 if (upa.conflicts > 0 || upa.missing > 0 ||
11558 upa.not_deleted > 0 || upa.unversioned > 0) {
11559 error = got_worktree_rebase_postpone(worktree, fileindex);
11560 if (error)
11561 goto done;
11562 if (upa.conflicts > 0 && upa.missing == 0 &&
11563 upa.not_deleted == 0 && upa.unversioned == 0) {
11564 error = got_error_msg(GOT_ERR_CONFLICTS,
11565 "conflicts must be resolved before rebasing "
11566 "can continue");
11567 } else if (upa.conflicts > 0) {
11568 error = got_error_msg(GOT_ERR_CONFLICTS,
11569 "conflicts must be resolved before rebasing "
11570 "can continue; changes destined for some "
11571 "files were not yet merged and should be "
11572 "merged manually if required before the "
11573 "rebase operation is continued");
11574 } else {
11575 error = got_error_msg(GOT_ERR_CONFLICTS,
11576 "changes destined for some files were not "
11577 "yet merged and should be merged manually "
11578 "if required before the rebase operation "
11579 "is continued");
11581 } else
11582 error = rebase_complete(worktree, fileindex, branch,
11583 tmp_branch, repo, create_backup);
11584 done:
11585 free(cwd);
11586 free(committer);
11587 free(gitconfig_path);
11588 got_object_id_queue_free(&commits);
11589 free(branch_head_commit_id);
11590 free(resume_commit_id);
11591 free(head_commit_id);
11592 free(yca_id);
11593 if (commit)
11594 got_object_commit_close(commit);
11595 if (branch)
11596 got_ref_close(branch);
11597 if (new_base_branch)
11598 got_ref_close(new_base_branch);
11599 if (tmp_branch)
11600 got_ref_close(tmp_branch);
11601 if (head_ref)
11602 got_ref_close(head_ref);
11603 if (worktree)
11604 got_worktree_close(worktree);
11605 if (repo) {
11606 const struct got_error *close_err = got_repo_close(repo);
11607 if (error == NULL)
11608 error = close_err;
11610 if (pack_fds) {
11611 const struct got_error *pack_err =
11612 got_repo_pack_fds_close(pack_fds);
11613 if (error == NULL)
11614 error = pack_err;
11616 return error;
11619 __dead static void
11620 usage_histedit(void)
11622 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11623 "[branch]\n", getprogname());
11624 exit(1);
11627 #define GOT_HISTEDIT_PICK 'p'
11628 #define GOT_HISTEDIT_EDIT 'e'
11629 #define GOT_HISTEDIT_FOLD 'f'
11630 #define GOT_HISTEDIT_DROP 'd'
11631 #define GOT_HISTEDIT_MESG 'm'
11633 static const struct got_histedit_cmd {
11634 unsigned char code;
11635 const char *name;
11636 const char *desc;
11637 } got_histedit_cmds[] = {
11638 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11639 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11640 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11641 "be used" },
11642 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11643 { GOT_HISTEDIT_MESG, "mesg",
11644 "single-line log message for commit above (open editor if empty)" },
11647 struct got_histedit_list_entry {
11648 TAILQ_ENTRY(got_histedit_list_entry) entry;
11649 struct got_object_id *commit_id;
11650 const struct got_histedit_cmd *cmd;
11651 char *logmsg;
11653 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11655 static const struct got_error *
11656 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11657 FILE *f, struct got_repository *repo)
11659 const struct got_error *err = NULL;
11660 char *logmsg = NULL, *id_str = NULL;
11661 struct got_commit_object *commit = NULL;
11662 int n;
11664 err = got_object_open_as_commit(&commit, repo, commit_id);
11665 if (err)
11666 goto done;
11668 err = get_short_logmsg(&logmsg, 34, commit);
11669 if (err)
11670 goto done;
11672 err = got_object_id_str(&id_str, commit_id);
11673 if (err)
11674 goto done;
11676 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11677 if (n < 0)
11678 err = got_ferror(f, GOT_ERR_IO);
11679 done:
11680 if (commit)
11681 got_object_commit_close(commit);
11682 free(id_str);
11683 free(logmsg);
11684 return err;
11687 static const struct got_error *
11688 histedit_write_commit_list(struct got_object_id_queue *commits,
11689 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11690 int edit_only, struct got_repository *repo)
11692 const struct got_error *err = NULL;
11693 struct got_object_qid *qid;
11694 const char *histedit_cmd = NULL;
11696 if (STAILQ_EMPTY(commits))
11697 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11699 STAILQ_FOREACH(qid, commits, entry) {
11700 histedit_cmd = got_histedit_cmds[0].name;
11701 if (drop_only)
11702 histedit_cmd = "drop";
11703 else if (edit_only)
11704 histedit_cmd = "edit";
11705 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11706 histedit_cmd = "fold";
11707 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11708 if (err)
11709 break;
11710 if (edit_logmsg_only) {
11711 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11712 if (n < 0) {
11713 err = got_ferror(f, GOT_ERR_IO);
11714 break;
11719 return err;
11722 static const struct got_error *
11723 write_cmd_list(FILE *f, const char *branch_name,
11724 struct got_object_id_queue *commits)
11726 const struct got_error *err = NULL;
11727 size_t i;
11728 int n;
11729 char *id_str;
11730 struct got_object_qid *qid;
11732 qid = STAILQ_FIRST(commits);
11733 err = got_object_id_str(&id_str, &qid->id);
11734 if (err)
11735 return err;
11737 n = fprintf(f,
11738 "# Editing the history of branch '%s' starting at\n"
11739 "# commit %s\n"
11740 "# Commits will be processed in order from top to "
11741 "bottom of this file.\n", branch_name, id_str);
11742 if (n < 0) {
11743 err = got_ferror(f, GOT_ERR_IO);
11744 goto done;
11747 n = fprintf(f, "# Available histedit commands:\n");
11748 if (n < 0) {
11749 err = got_ferror(f, GOT_ERR_IO);
11750 goto done;
11753 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11754 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11755 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11756 cmd->desc);
11757 if (n < 0) {
11758 err = got_ferror(f, GOT_ERR_IO);
11759 break;
11762 done:
11763 free(id_str);
11764 return err;
11767 static const struct got_error *
11768 histedit_syntax_error(int lineno)
11770 static char msg[42];
11771 int ret;
11773 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11774 lineno);
11775 if (ret < 0 || (size_t)ret >= sizeof(msg))
11776 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11778 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11781 static const struct got_error *
11782 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11783 char *logmsg, struct got_repository *repo)
11785 const struct got_error *err;
11786 struct got_commit_object *folded_commit = NULL;
11787 char *id_str, *folded_logmsg = NULL;
11789 err = got_object_id_str(&id_str, hle->commit_id);
11790 if (err)
11791 return err;
11793 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11794 if (err)
11795 goto done;
11797 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11798 if (err)
11799 goto done;
11800 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11801 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11802 folded_logmsg) == -1) {
11803 err = got_error_from_errno("asprintf");
11805 done:
11806 if (folded_commit)
11807 got_object_commit_close(folded_commit);
11808 free(id_str);
11809 free(folded_logmsg);
11810 return err;
11813 static struct got_histedit_list_entry *
11814 get_folded_commits(struct got_histedit_list_entry *hle)
11816 struct got_histedit_list_entry *prev, *folded = NULL;
11818 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11819 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11820 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11821 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11822 folded = prev;
11823 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11826 return folded;
11829 static const struct got_error *
11830 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11831 struct got_repository *repo)
11833 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11834 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11835 const struct got_error *err = NULL;
11836 struct got_commit_object *commit = NULL;
11837 int logmsg_len;
11838 int fd = -1;
11839 struct got_histedit_list_entry *folded = NULL;
11841 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11842 if (err)
11843 return err;
11845 folded = get_folded_commits(hle);
11846 if (folded) {
11847 while (folded != hle) {
11848 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11849 folded = TAILQ_NEXT(folded, entry);
11850 continue;
11852 err = append_folded_commit_msg(&new_msg, folded,
11853 logmsg, repo);
11854 if (err)
11855 goto done;
11856 free(logmsg);
11857 logmsg = new_msg;
11858 folded = TAILQ_NEXT(folded, entry);
11862 err = got_object_id_str(&id_str, hle->commit_id);
11863 if (err)
11864 goto done;
11865 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11866 if (err)
11867 goto done;
11868 logmsg_len = asprintf(&new_msg,
11869 "%s\n# original log message of commit %s: %s",
11870 logmsg ? logmsg : "", id_str, orig_logmsg);
11871 if (logmsg_len == -1) {
11872 err = got_error_from_errno("asprintf");
11873 goto done;
11875 free(logmsg);
11876 logmsg = new_msg;
11878 err = got_object_id_str(&id_str, hle->commit_id);
11879 if (err)
11880 goto done;
11882 err = got_opentemp_named_fd(&logmsg_path, &fd,
11883 GOT_TMPDIR_STR "/got-logmsg", "");
11884 if (err)
11885 goto done;
11887 if (write(fd, logmsg, logmsg_len) == -1) {
11888 err = got_error_from_errno2("write", logmsg_path);
11889 goto done;
11891 if (close(fd) == -1) {
11892 err = got_error_from_errno2("close", logmsg_path);
11893 goto done;
11895 fd = -1;
11897 err = get_editor(&editor);
11898 if (err)
11899 goto done;
11901 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11902 logmsg_len, 0);
11903 if (err) {
11904 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11905 goto done;
11906 err = NULL;
11907 hle->logmsg = strdup(new_msg);
11908 if (hle->logmsg == NULL)
11909 err = got_error_from_errno("strdup");
11911 done:
11912 if (fd != -1 && close(fd) == -1 && err == NULL)
11913 err = got_error_from_errno2("close", logmsg_path);
11914 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11915 err = got_error_from_errno2("unlink", logmsg_path);
11916 free(logmsg_path);
11917 free(logmsg);
11918 free(orig_logmsg);
11919 free(editor);
11920 if (commit)
11921 got_object_commit_close(commit);
11922 return err;
11925 static const struct got_error *
11926 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11927 FILE *f, struct got_repository *repo)
11929 const struct got_error *err = NULL;
11930 char *line = NULL, *p, *end;
11931 size_t i, linesize = 0;
11932 ssize_t linelen;
11933 int lineno = 0, lastcmd = -1;
11934 const struct got_histedit_cmd *cmd;
11935 struct got_object_id *commit_id = NULL;
11936 struct got_histedit_list_entry *hle = NULL;
11938 for (;;) {
11939 linelen = getline(&line, &linesize, f);
11940 if (linelen == -1) {
11941 const struct got_error *getline_err;
11942 if (feof(f))
11943 break;
11944 getline_err = got_error_from_errno("getline");
11945 err = got_ferror(f, getline_err->code);
11946 break;
11948 lineno++;
11949 p = line;
11950 while (isspace((unsigned char)p[0]))
11951 p++;
11952 if (p[0] == '#' || p[0] == '\0')
11953 continue;
11954 cmd = NULL;
11955 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11956 cmd = &got_histedit_cmds[i];
11957 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11958 isspace((unsigned char)p[strlen(cmd->name)])) {
11959 p += strlen(cmd->name);
11960 break;
11962 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11963 p++;
11964 break;
11967 if (i == nitems(got_histedit_cmds)) {
11968 err = histedit_syntax_error(lineno);
11969 break;
11971 while (isspace((unsigned char)p[0]))
11972 p++;
11973 if (cmd->code == GOT_HISTEDIT_MESG) {
11974 if (lastcmd != GOT_HISTEDIT_PICK &&
11975 lastcmd != GOT_HISTEDIT_EDIT) {
11976 err = got_error(GOT_ERR_HISTEDIT_CMD);
11977 break;
11979 if (p[0] == '\0') {
11980 err = histedit_edit_logmsg(hle, repo);
11981 if (err)
11982 break;
11983 } else {
11984 hle->logmsg = strdup(p);
11985 if (hle->logmsg == NULL) {
11986 err = got_error_from_errno("strdup");
11987 break;
11990 lastcmd = cmd->code;
11991 continue;
11992 } else {
11993 end = p;
11994 while (end[0] && !isspace((unsigned char)end[0]))
11995 end++;
11996 *end = '\0';
11998 err = got_object_resolve_id_str(&commit_id, repo, p);
11999 if (err) {
12000 /* override error code */
12001 err = histedit_syntax_error(lineno);
12002 break;
12005 hle = malloc(sizeof(*hle));
12006 if (hle == NULL) {
12007 err = got_error_from_errno("malloc");
12008 break;
12010 hle->cmd = cmd;
12011 hle->commit_id = commit_id;
12012 hle->logmsg = NULL;
12013 commit_id = NULL;
12014 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12015 lastcmd = cmd->code;
12018 free(line);
12019 free(commit_id);
12020 return err;
12023 static const struct got_error *
12024 histedit_check_script(struct got_histedit_list *histedit_cmds,
12025 struct got_object_id_queue *commits, struct got_repository *repo)
12027 const struct got_error *err = NULL;
12028 struct got_object_qid *qid;
12029 struct got_histedit_list_entry *hle;
12030 static char msg[92];
12031 char *id_str;
12033 if (TAILQ_EMPTY(histedit_cmds))
12034 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12035 "histedit script contains no commands");
12036 if (STAILQ_EMPTY(commits))
12037 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12039 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12040 struct got_histedit_list_entry *hle2;
12041 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12042 if (hle == hle2)
12043 continue;
12044 if (got_object_id_cmp(hle->commit_id,
12045 hle2->commit_id) != 0)
12046 continue;
12047 err = got_object_id_str(&id_str, hle->commit_id);
12048 if (err)
12049 return err;
12050 snprintf(msg, sizeof(msg), "commit %s is listed "
12051 "more than once in histedit script", id_str);
12052 free(id_str);
12053 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12057 STAILQ_FOREACH(qid, commits, entry) {
12058 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12059 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12060 break;
12062 if (hle == NULL) {
12063 err = got_object_id_str(&id_str, &qid->id);
12064 if (err)
12065 return err;
12066 snprintf(msg, sizeof(msg),
12067 "commit %s missing from histedit script", id_str);
12068 free(id_str);
12069 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12073 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12074 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12075 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12076 "last commit in histedit script cannot be folded");
12078 return NULL;
12081 static const struct got_error *
12082 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12083 const char *path, struct got_object_id_queue *commits,
12084 struct got_repository *repo)
12086 const struct got_error *err = NULL;
12087 struct stat st, st2;
12088 struct timespec timeout;
12089 char *editor;
12090 FILE *f = NULL;
12092 err = get_editor(&editor);
12093 if (err)
12094 return err;
12096 if (stat(path, &st) == -1) {
12097 err = got_error_from_errno2("stat", path);
12098 goto done;
12101 if (spawn_editor(editor, path) == -1) {
12102 err = got_error_from_errno("failed spawning editor");
12103 goto done;
12106 timeout.tv_sec = 0;
12107 timeout.tv_nsec = 1;
12108 nanosleep(&timeout, NULL);
12110 if (stat(path, &st2) == -1) {
12111 err = got_error_from_errno2("stat", path);
12112 goto done;
12115 if (st.st_size == st2.st_size &&
12116 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12117 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12118 "no changes made to histedit script, aborting");
12119 goto done;
12122 f = fopen(path, "re");
12123 if (f == NULL) {
12124 err = got_error_from_errno("fopen");
12125 goto done;
12127 err = histedit_parse_list(histedit_cmds, f, repo);
12128 if (err)
12129 goto done;
12131 err = histedit_check_script(histedit_cmds, commits, repo);
12132 done:
12133 if (f && fclose(f) == EOF && err == NULL)
12134 err = got_error_from_errno("fclose");
12135 free(editor);
12136 return err;
12139 static const struct got_error *
12140 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12141 struct got_object_id_queue *, const char *, const char *,
12142 struct got_repository *);
12144 static const struct got_error *
12145 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12146 struct got_object_id_queue *commits, const char *branch_name,
12147 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12148 struct got_repository *repo)
12150 const struct got_error *err;
12151 FILE *f = NULL;
12152 char *path = NULL;
12154 err = got_opentemp_named(&path, &f, "got-histedit", "");
12155 if (err)
12156 return err;
12158 err = write_cmd_list(f, branch_name, commits);
12159 if (err)
12160 goto done;
12162 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12163 fold_only, drop_only, edit_only, repo);
12164 if (err)
12165 goto done;
12167 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12168 rewind(f);
12169 err = histedit_parse_list(histedit_cmds, f, repo);
12170 } else {
12171 if (fclose(f) == EOF) {
12172 err = got_error_from_errno("fclose");
12173 goto done;
12175 f = NULL;
12176 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12177 if (err) {
12178 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12179 err->code != GOT_ERR_HISTEDIT_CMD)
12180 goto done;
12181 err = histedit_edit_list_retry(histedit_cmds, err,
12182 commits, path, branch_name, repo);
12185 done:
12186 if (f && fclose(f) == EOF && err == NULL)
12187 err = got_error_from_errno("fclose");
12188 if (path && unlink(path) != 0 && err == NULL)
12189 err = got_error_from_errno2("unlink", path);
12190 free(path);
12191 return err;
12194 static const struct got_error *
12195 histedit_save_list(struct got_histedit_list *histedit_cmds,
12196 struct got_worktree *worktree, struct got_repository *repo)
12198 const struct got_error *err = NULL;
12199 char *path = NULL;
12200 FILE *f = NULL;
12201 struct got_histedit_list_entry *hle;
12203 err = got_worktree_get_histedit_script_path(&path, worktree);
12204 if (err)
12205 return err;
12207 f = fopen(path, "we");
12208 if (f == NULL) {
12209 err = got_error_from_errno2("fopen", path);
12210 goto done;
12212 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12213 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12214 repo);
12215 if (err)
12216 break;
12218 if (hle->logmsg) {
12219 int n = fprintf(f, "%c %s\n",
12220 GOT_HISTEDIT_MESG, hle->logmsg);
12221 if (n < 0) {
12222 err = got_ferror(f, GOT_ERR_IO);
12223 break;
12227 done:
12228 if (f && fclose(f) == EOF && err == NULL)
12229 err = got_error_from_errno("fclose");
12230 free(path);
12231 return err;
12234 static void
12235 histedit_free_list(struct got_histedit_list *histedit_cmds)
12237 struct got_histedit_list_entry *hle;
12239 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12240 TAILQ_REMOVE(histedit_cmds, hle, entry);
12241 free(hle);
12245 static const struct got_error *
12246 histedit_load_list(struct got_histedit_list *histedit_cmds,
12247 const char *path, struct got_repository *repo)
12249 const struct got_error *err = NULL;
12250 FILE *f = NULL;
12252 f = fopen(path, "re");
12253 if (f == NULL) {
12254 err = got_error_from_errno2("fopen", path);
12255 goto done;
12258 err = histedit_parse_list(histedit_cmds, f, repo);
12259 done:
12260 if (f && fclose(f) == EOF && err == NULL)
12261 err = got_error_from_errno("fclose");
12262 return err;
12265 static const struct got_error *
12266 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12267 const struct got_error *edit_err, struct got_object_id_queue *commits,
12268 const char *path, const char *branch_name, struct got_repository *repo)
12270 const struct got_error *err = NULL, *prev_err = edit_err;
12271 int resp = ' ';
12273 while (resp != 'c' && resp != 'r' && resp != 'a') {
12274 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12275 "or (a)bort: ", getprogname(), prev_err->msg);
12276 resp = getchar();
12277 if (resp == '\n')
12278 resp = getchar();
12279 if (resp == 'c') {
12280 histedit_free_list(histedit_cmds);
12281 err = histedit_run_editor(histedit_cmds, path, commits,
12282 repo);
12283 if (err) {
12284 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12285 err->code != GOT_ERR_HISTEDIT_CMD)
12286 break;
12287 prev_err = err;
12288 resp = ' ';
12289 continue;
12291 break;
12292 } else if (resp == 'r') {
12293 histedit_free_list(histedit_cmds);
12294 err = histedit_edit_script(histedit_cmds,
12295 commits, branch_name, 0, 0, 0, 0, repo);
12296 if (err) {
12297 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12298 err->code != GOT_ERR_HISTEDIT_CMD)
12299 break;
12300 prev_err = err;
12301 resp = ' ';
12302 continue;
12304 break;
12305 } else if (resp == 'a') {
12306 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12307 break;
12308 } else
12309 printf("invalid response '%c'\n", resp);
12312 return err;
12315 static const struct got_error *
12316 histedit_complete(struct got_worktree *worktree,
12317 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12318 struct got_reference *branch, struct got_repository *repo)
12320 printf("Switching work tree to %s\n",
12321 got_ref_get_symref_target(branch));
12322 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12323 branch, repo);
12326 static const struct got_error *
12327 show_histedit_progress(struct got_commit_object *commit,
12328 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12330 const struct got_error *err;
12331 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12333 err = got_object_id_str(&old_id_str, hle->commit_id);
12334 if (err)
12335 goto done;
12337 if (new_id) {
12338 err = got_object_id_str(&new_id_str, new_id);
12339 if (err)
12340 goto done;
12343 old_id_str[12] = '\0';
12344 if (new_id_str)
12345 new_id_str[12] = '\0';
12347 if (hle->logmsg) {
12348 logmsg = strdup(hle->logmsg);
12349 if (logmsg == NULL) {
12350 err = got_error_from_errno("strdup");
12351 goto done;
12353 trim_logmsg(logmsg, 42);
12354 } else {
12355 err = get_short_logmsg(&logmsg, 42, commit);
12356 if (err)
12357 goto done;
12360 switch (hle->cmd->code) {
12361 case GOT_HISTEDIT_PICK:
12362 case GOT_HISTEDIT_EDIT:
12363 printf("%s -> %s: %s\n", old_id_str,
12364 new_id_str ? new_id_str : "no-op change", logmsg);
12365 break;
12366 case GOT_HISTEDIT_DROP:
12367 case GOT_HISTEDIT_FOLD:
12368 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12369 logmsg);
12370 break;
12371 default:
12372 break;
12374 done:
12375 free(old_id_str);
12376 free(new_id_str);
12377 return err;
12380 static const struct got_error *
12381 histedit_commit(struct got_pathlist_head *merged_paths,
12382 struct got_worktree *worktree, struct got_fileindex *fileindex,
12383 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12384 const char *committer, int allow_conflict, struct got_repository *repo)
12386 const struct got_error *err;
12387 struct got_commit_object *commit;
12388 struct got_object_id *new_commit_id;
12390 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12391 && hle->logmsg == NULL) {
12392 err = histedit_edit_logmsg(hle, repo);
12393 if (err)
12394 return err;
12397 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12398 if (err)
12399 return err;
12401 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12402 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12403 hle->logmsg, allow_conflict, repo);
12404 if (err) {
12405 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12406 goto done;
12407 err = show_histedit_progress(commit, hle, NULL);
12408 } else {
12409 err = show_histedit_progress(commit, hle, new_commit_id);
12410 free(new_commit_id);
12412 done:
12413 got_object_commit_close(commit);
12414 return err;
12417 static const struct got_error *
12418 histedit_skip_commit(struct got_histedit_list_entry *hle,
12419 struct got_worktree *worktree, struct got_repository *repo)
12421 const struct got_error *error;
12422 struct got_commit_object *commit;
12424 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12425 repo);
12426 if (error)
12427 return error;
12429 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12430 if (error)
12431 return error;
12433 error = show_histedit_progress(commit, hle, NULL);
12434 got_object_commit_close(commit);
12435 return error;
12438 static const struct got_error *
12439 check_local_changes(void *arg, unsigned char status,
12440 unsigned char staged_status, const char *path,
12441 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12442 struct got_object_id *commit_id, int dirfd, const char *de_name)
12444 int *have_local_changes = arg;
12446 switch (status) {
12447 case GOT_STATUS_ADD:
12448 case GOT_STATUS_DELETE:
12449 case GOT_STATUS_MODIFY:
12450 case GOT_STATUS_CONFLICT:
12451 *have_local_changes = 1;
12452 return got_error(GOT_ERR_CANCELLED);
12453 default:
12454 break;
12457 switch (staged_status) {
12458 case GOT_STATUS_ADD:
12459 case GOT_STATUS_DELETE:
12460 case GOT_STATUS_MODIFY:
12461 *have_local_changes = 1;
12462 return got_error(GOT_ERR_CANCELLED);
12463 default:
12464 break;
12467 return NULL;
12470 static const struct got_error *
12471 cmd_histedit(int argc, char *argv[])
12473 const struct got_error *error = NULL;
12474 struct got_worktree *worktree = NULL;
12475 struct got_fileindex *fileindex = NULL;
12476 struct got_repository *repo = NULL;
12477 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12478 struct got_reference *branch = NULL;
12479 struct got_reference *tmp_branch = NULL;
12480 struct got_object_id *resume_commit_id = NULL;
12481 struct got_object_id *base_commit_id = NULL;
12482 struct got_object_id *head_commit_id = NULL;
12483 struct got_commit_object *commit = NULL;
12484 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12485 struct got_update_progress_arg upa;
12486 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12487 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12488 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12489 const char *edit_script_path = NULL;
12490 struct got_object_id_queue commits;
12491 struct got_pathlist_head merged_paths;
12492 const struct got_object_id_queue *parent_ids;
12493 struct got_object_qid *pid;
12494 struct got_histedit_list histedit_cmds;
12495 struct got_histedit_list_entry *hle;
12496 int *pack_fds = NULL;
12498 STAILQ_INIT(&commits);
12499 TAILQ_INIT(&histedit_cmds);
12500 TAILQ_INIT(&merged_paths);
12501 memset(&upa, 0, sizeof(upa));
12503 #ifndef PROFILE
12504 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12505 "unveil", NULL) == -1)
12506 err(1, "pledge");
12507 #endif
12509 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12510 switch (ch) {
12511 case 'a':
12512 abort_edit = 1;
12513 break;
12514 case 'C':
12515 allow_conflict = 1;
12516 break;
12517 case 'c':
12518 continue_edit = 1;
12519 break;
12520 case 'd':
12521 drop_only = 1;
12522 break;
12523 case 'e':
12524 edit_only = 1;
12525 break;
12526 case 'F':
12527 edit_script_path = optarg;
12528 break;
12529 case 'f':
12530 fold_only = 1;
12531 break;
12532 case 'l':
12533 list_backups = 1;
12534 break;
12535 case 'm':
12536 edit_logmsg_only = 1;
12537 break;
12538 case 'X':
12539 delete_backups = 1;
12540 break;
12541 default:
12542 usage_histedit();
12543 /* NOTREACHED */
12547 argc -= optind;
12548 argv += optind;
12550 if (abort_edit && allow_conflict)
12551 option_conflict('a', 'C');
12552 if (abort_edit && continue_edit)
12553 option_conflict('a', 'c');
12554 if (edit_script_path && allow_conflict)
12555 option_conflict('F', 'C');
12556 if (edit_script_path && edit_logmsg_only)
12557 option_conflict('F', 'm');
12558 if (abort_edit && edit_logmsg_only)
12559 option_conflict('a', 'm');
12560 if (edit_logmsg_only && allow_conflict)
12561 option_conflict('m', 'C');
12562 if (continue_edit && edit_logmsg_only)
12563 option_conflict('c', 'm');
12564 if (abort_edit && fold_only)
12565 option_conflict('a', 'f');
12566 if (fold_only && allow_conflict)
12567 option_conflict('f', 'C');
12568 if (continue_edit && fold_only)
12569 option_conflict('c', 'f');
12570 if (fold_only && edit_logmsg_only)
12571 option_conflict('f', 'm');
12572 if (edit_script_path && fold_only)
12573 option_conflict('F', 'f');
12574 if (abort_edit && edit_only)
12575 option_conflict('a', 'e');
12576 if (continue_edit && edit_only)
12577 option_conflict('c', 'e');
12578 if (edit_only && edit_logmsg_only)
12579 option_conflict('e', 'm');
12580 if (edit_script_path && edit_only)
12581 option_conflict('F', 'e');
12582 if (fold_only && edit_only)
12583 option_conflict('f', 'e');
12584 if (drop_only && abort_edit)
12585 option_conflict('d', 'a');
12586 if (drop_only && allow_conflict)
12587 option_conflict('d', 'C');
12588 if (drop_only && continue_edit)
12589 option_conflict('d', 'c');
12590 if (drop_only && edit_logmsg_only)
12591 option_conflict('d', 'm');
12592 if (drop_only && edit_only)
12593 option_conflict('d', 'e');
12594 if (drop_only && edit_script_path)
12595 option_conflict('d', 'F');
12596 if (drop_only && fold_only)
12597 option_conflict('d', 'f');
12598 if (list_backups) {
12599 if (abort_edit)
12600 option_conflict('l', 'a');
12601 if (allow_conflict)
12602 option_conflict('l', 'C');
12603 if (continue_edit)
12604 option_conflict('l', 'c');
12605 if (edit_script_path)
12606 option_conflict('l', 'F');
12607 if (edit_logmsg_only)
12608 option_conflict('l', 'm');
12609 if (drop_only)
12610 option_conflict('l', 'd');
12611 if (fold_only)
12612 option_conflict('l', 'f');
12613 if (edit_only)
12614 option_conflict('l', 'e');
12615 if (delete_backups)
12616 option_conflict('l', 'X');
12617 if (argc != 0 && argc != 1)
12618 usage_histedit();
12619 } else if (delete_backups) {
12620 if (abort_edit)
12621 option_conflict('X', 'a');
12622 if (allow_conflict)
12623 option_conflict('X', 'C');
12624 if (continue_edit)
12625 option_conflict('X', 'c');
12626 if (drop_only)
12627 option_conflict('X', 'd');
12628 if (edit_script_path)
12629 option_conflict('X', 'F');
12630 if (edit_logmsg_only)
12631 option_conflict('X', 'm');
12632 if (fold_only)
12633 option_conflict('X', 'f');
12634 if (edit_only)
12635 option_conflict('X', 'e');
12636 if (list_backups)
12637 option_conflict('X', 'l');
12638 if (argc != 0 && argc != 1)
12639 usage_histedit();
12640 } else if (allow_conflict && !continue_edit)
12641 errx(1, "-C option requires -c");
12642 else if (argc != 0)
12643 usage_histedit();
12646 * This command cannot apply unveil(2) in all cases because the
12647 * user may choose to run an editor to edit the histedit script
12648 * and to edit individual commit log messages.
12649 * unveil(2) traverses exec(2); if an editor is used we have to
12650 * apply unveil after edit script and log messages have been written.
12651 * XXX TODO: Make use of unveil(2) where possible.
12654 cwd = getcwd(NULL, 0);
12655 if (cwd == NULL) {
12656 error = got_error_from_errno("getcwd");
12657 goto done;
12660 error = got_repo_pack_fds_open(&pack_fds);
12661 if (error != NULL)
12662 goto done;
12664 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12665 if (error) {
12666 if (list_backups || delete_backups) {
12667 if (error->code != GOT_ERR_NOT_WORKTREE)
12668 goto done;
12669 } else {
12670 if (error->code == GOT_ERR_NOT_WORKTREE)
12671 error = wrap_not_worktree_error(error,
12672 "histedit", cwd);
12673 goto done;
12677 if (list_backups || delete_backups) {
12678 error = got_repo_open(&repo,
12679 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12680 NULL, pack_fds);
12681 if (error != NULL)
12682 goto done;
12683 error = apply_unveil(got_repo_get_path(repo), 0,
12684 worktree ? got_worktree_get_root_path(worktree) : NULL);
12685 if (error)
12686 goto done;
12687 error = process_backup_refs(
12688 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12689 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12690 goto done; /* nothing else to do */
12693 error = get_gitconfig_path(&gitconfig_path);
12694 if (error)
12695 goto done;
12696 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12697 gitconfig_path, pack_fds);
12698 if (error != NULL)
12699 goto done;
12701 if (worktree != NULL && !list_backups && !delete_backups) {
12702 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12703 if (error)
12704 goto done;
12707 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12708 if (error)
12709 goto done;
12710 if (rebase_in_progress) {
12711 error = got_error(GOT_ERR_REBASING);
12712 goto done;
12715 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12716 repo);
12717 if (error)
12718 goto done;
12719 if (merge_in_progress) {
12720 error = got_error(GOT_ERR_MERGE_BUSY);
12721 goto done;
12724 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12725 if (error)
12726 goto done;
12728 if (edit_in_progress && edit_logmsg_only) {
12729 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12730 "histedit operation is in progress in this "
12731 "work tree and must be continued or aborted "
12732 "before the -m option can be used");
12733 goto done;
12735 if (edit_in_progress && drop_only) {
12736 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12737 "histedit operation is in progress in this "
12738 "work tree and must be continued or aborted "
12739 "before the -d option can be used");
12740 goto done;
12742 if (edit_in_progress && fold_only) {
12743 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12744 "histedit operation is in progress in this "
12745 "work tree and must be continued or aborted "
12746 "before the -f option can be used");
12747 goto done;
12749 if (edit_in_progress && edit_only) {
12750 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12751 "histedit operation is in progress in this "
12752 "work tree and must be continued or aborted "
12753 "before the -e option can be used");
12754 goto done;
12757 if (edit_in_progress && abort_edit) {
12758 error = got_worktree_histedit_continue(&resume_commit_id,
12759 &tmp_branch, &branch, &base_commit_id, &fileindex,
12760 worktree, repo);
12761 if (error)
12762 goto done;
12763 printf("Switching work tree to %s\n",
12764 got_ref_get_symref_target(branch));
12765 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12766 branch, base_commit_id, abort_progress, &upa);
12767 if (error)
12768 goto done;
12769 printf("Histedit of %s aborted\n",
12770 got_ref_get_symref_target(branch));
12771 print_merge_progress_stats(&upa);
12772 goto done; /* nothing else to do */
12773 } else if (abort_edit) {
12774 error = got_error(GOT_ERR_NOT_HISTEDIT);
12775 goto done;
12778 error = get_author(&committer, repo, worktree);
12779 if (error)
12780 goto done;
12782 if (continue_edit) {
12783 char *path;
12785 if (!edit_in_progress) {
12786 error = got_error(GOT_ERR_NOT_HISTEDIT);
12787 goto done;
12790 error = got_worktree_get_histedit_script_path(&path, worktree);
12791 if (error)
12792 goto done;
12794 error = histedit_load_list(&histedit_cmds, path, repo);
12795 free(path);
12796 if (error)
12797 goto done;
12799 error = got_worktree_histedit_continue(&resume_commit_id,
12800 &tmp_branch, &branch, &base_commit_id, &fileindex,
12801 worktree, repo);
12802 if (error)
12803 goto done;
12805 error = got_ref_resolve(&head_commit_id, repo, branch);
12806 if (error)
12807 goto done;
12809 error = got_object_open_as_commit(&commit, repo,
12810 head_commit_id);
12811 if (error)
12812 goto done;
12813 parent_ids = got_object_commit_get_parent_ids(commit);
12814 pid = STAILQ_FIRST(parent_ids);
12815 if (pid == NULL) {
12816 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12817 goto done;
12819 error = collect_commits(&commits, head_commit_id, &pid->id,
12820 base_commit_id, got_worktree_get_path_prefix(worktree),
12821 GOT_ERR_HISTEDIT_PATH, repo);
12822 got_object_commit_close(commit);
12823 commit = NULL;
12824 if (error)
12825 goto done;
12826 } else {
12827 if (edit_in_progress) {
12828 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12829 goto done;
12832 error = got_ref_open(&branch, repo,
12833 got_worktree_get_head_ref_name(worktree), 0);
12834 if (error != NULL)
12835 goto done;
12837 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12838 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12839 "will not edit commit history of a branch outside "
12840 "the \"refs/heads/\" reference namespace");
12841 goto done;
12844 error = got_ref_resolve(&head_commit_id, repo, branch);
12845 got_ref_close(branch);
12846 branch = NULL;
12847 if (error)
12848 goto done;
12850 error = got_object_open_as_commit(&commit, repo,
12851 head_commit_id);
12852 if (error)
12853 goto done;
12854 parent_ids = got_object_commit_get_parent_ids(commit);
12855 pid = STAILQ_FIRST(parent_ids);
12856 if (pid == NULL) {
12857 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12858 goto done;
12860 error = collect_commits(&commits, head_commit_id, &pid->id,
12861 got_worktree_get_base_commit_id(worktree),
12862 got_worktree_get_path_prefix(worktree),
12863 GOT_ERR_HISTEDIT_PATH, repo);
12864 got_object_commit_close(commit);
12865 commit = NULL;
12866 if (error)
12867 goto done;
12869 if (STAILQ_EMPTY(&commits)) {
12870 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12871 goto done;
12874 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12875 &base_commit_id, &fileindex, worktree, repo);
12876 if (error)
12877 goto done;
12879 if (edit_script_path) {
12880 error = histedit_load_list(&histedit_cmds,
12881 edit_script_path, repo);
12882 if (error) {
12883 got_worktree_histedit_abort(worktree, fileindex,
12884 repo, branch, base_commit_id,
12885 abort_progress, &upa);
12886 print_merge_progress_stats(&upa);
12887 goto done;
12889 } else {
12890 const char *branch_name;
12891 branch_name = got_ref_get_symref_target(branch);
12892 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12893 branch_name += 11;
12894 error = histedit_edit_script(&histedit_cmds, &commits,
12895 branch_name, edit_logmsg_only, fold_only,
12896 drop_only, edit_only, repo);
12897 if (error) {
12898 got_worktree_histedit_abort(worktree, fileindex,
12899 repo, branch, base_commit_id,
12900 abort_progress, &upa);
12901 print_merge_progress_stats(&upa);
12902 goto done;
12907 error = histedit_save_list(&histedit_cmds, worktree,
12908 repo);
12909 if (error) {
12910 got_worktree_histedit_abort(worktree, fileindex,
12911 repo, branch, base_commit_id,
12912 abort_progress, &upa);
12913 print_merge_progress_stats(&upa);
12914 goto done;
12919 error = histedit_check_script(&histedit_cmds, &commits, repo);
12920 if (error)
12921 goto done;
12923 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12924 if (resume_commit_id) {
12925 if (got_object_id_cmp(hle->commit_id,
12926 resume_commit_id) != 0)
12927 continue;
12929 resume_commit_id = NULL;
12930 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12931 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12932 error = histedit_skip_commit(hle, worktree,
12933 repo);
12934 if (error)
12935 goto done;
12936 } else {
12937 struct got_pathlist_head paths;
12938 int have_changes = 0;
12940 TAILQ_INIT(&paths);
12941 error = got_pathlist_append(&paths, "", NULL);
12942 if (error)
12943 goto done;
12944 error = got_worktree_status(worktree, &paths,
12945 repo, 0, check_local_changes, &have_changes,
12946 check_cancelled, NULL);
12947 got_pathlist_free(&paths,
12948 GOT_PATHLIST_FREE_NONE);
12949 if (error) {
12950 if (error->code != GOT_ERR_CANCELLED)
12951 goto done;
12952 if (sigint_received || sigpipe_received)
12953 goto done;
12955 if (have_changes) {
12956 error = histedit_commit(NULL, worktree,
12957 fileindex, tmp_branch, hle,
12958 committer, allow_conflict, repo);
12959 if (error)
12960 goto done;
12961 } else {
12962 error = got_object_open_as_commit(
12963 &commit, repo, hle->commit_id);
12964 if (error)
12965 goto done;
12966 error = show_histedit_progress(commit,
12967 hle, NULL);
12968 got_object_commit_close(commit);
12969 commit = NULL;
12970 if (error)
12971 goto done;
12974 continue;
12977 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12978 error = histedit_skip_commit(hle, worktree, repo);
12979 if (error)
12980 goto done;
12981 continue;
12984 error = got_object_open_as_commit(&commit, repo,
12985 hle->commit_id);
12986 if (error)
12987 goto done;
12988 parent_ids = got_object_commit_get_parent_ids(commit);
12989 pid = STAILQ_FIRST(parent_ids);
12991 error = got_worktree_histedit_merge_files(&merged_paths,
12992 worktree, fileindex, &pid->id, hle->commit_id, repo,
12993 update_progress, &upa, check_cancelled, NULL);
12994 if (error)
12995 goto done;
12996 got_object_commit_close(commit);
12997 commit = NULL;
12999 print_merge_progress_stats(&upa);
13000 if (upa.conflicts > 0 || upa.missing > 0 ||
13001 upa.not_deleted > 0 || upa.unversioned > 0) {
13002 if (upa.conflicts > 0) {
13003 error = show_rebase_merge_conflict(
13004 hle->commit_id, repo);
13005 if (error)
13006 goto done;
13008 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13009 break;
13012 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13013 char *id_str;
13014 error = got_object_id_str(&id_str, hle->commit_id);
13015 if (error)
13016 goto done;
13017 printf("Stopping histedit for amending commit %s\n",
13018 id_str);
13019 free(id_str);
13020 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13021 error = got_worktree_histedit_postpone(worktree,
13022 fileindex);
13023 goto done;
13026 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13027 error = histedit_skip_commit(hle, worktree, repo);
13028 if (error)
13029 goto done;
13030 continue;
13033 error = histedit_commit(&merged_paths, worktree, fileindex,
13034 tmp_branch, hle, committer, allow_conflict, repo);
13035 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13036 if (error)
13037 goto done;
13040 if (upa.conflicts > 0 || upa.missing > 0 ||
13041 upa.not_deleted > 0 || upa.unversioned > 0) {
13042 error = got_worktree_histedit_postpone(worktree, fileindex);
13043 if (error)
13044 goto done;
13045 if (upa.conflicts > 0 && upa.missing == 0 &&
13046 upa.not_deleted == 0 && upa.unversioned == 0) {
13047 error = got_error_msg(GOT_ERR_CONFLICTS,
13048 "conflicts must be resolved before histedit "
13049 "can continue");
13050 } else if (upa.conflicts > 0) {
13051 error = got_error_msg(GOT_ERR_CONFLICTS,
13052 "conflicts must be resolved before histedit "
13053 "can continue; changes destined for some "
13054 "files were not yet merged and should be "
13055 "merged manually if required before the "
13056 "histedit operation is continued");
13057 } else {
13058 error = got_error_msg(GOT_ERR_CONFLICTS,
13059 "changes destined for some files were not "
13060 "yet merged and should be merged manually "
13061 "if required before the histedit operation "
13062 "is continued");
13064 } else
13065 error = histedit_complete(worktree, fileindex, tmp_branch,
13066 branch, repo);
13067 done:
13068 free(cwd);
13069 free(committer);
13070 free(gitconfig_path);
13071 got_object_id_queue_free(&commits);
13072 histedit_free_list(&histedit_cmds);
13073 free(head_commit_id);
13074 free(base_commit_id);
13075 free(resume_commit_id);
13076 if (commit)
13077 got_object_commit_close(commit);
13078 if (branch)
13079 got_ref_close(branch);
13080 if (tmp_branch)
13081 got_ref_close(tmp_branch);
13082 if (worktree)
13083 got_worktree_close(worktree);
13084 if (repo) {
13085 const struct got_error *close_err = got_repo_close(repo);
13086 if (error == NULL)
13087 error = close_err;
13089 if (pack_fds) {
13090 const struct got_error *pack_err =
13091 got_repo_pack_fds_close(pack_fds);
13092 if (error == NULL)
13093 error = pack_err;
13095 return error;
13098 __dead static void
13099 usage_integrate(void)
13101 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13102 exit(1);
13105 static const struct got_error *
13106 cmd_integrate(int argc, char *argv[])
13108 const struct got_error *error = NULL;
13109 struct got_repository *repo = NULL;
13110 struct got_worktree *worktree = NULL;
13111 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13112 const char *branch_arg = NULL;
13113 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13114 struct got_fileindex *fileindex = NULL;
13115 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13116 int ch;
13117 struct got_update_progress_arg upa;
13118 int *pack_fds = NULL;
13120 #ifndef PROFILE
13121 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13122 "unveil", NULL) == -1)
13123 err(1, "pledge");
13124 #endif
13126 while ((ch = getopt(argc, argv, "")) != -1) {
13127 switch (ch) {
13128 default:
13129 usage_integrate();
13130 /* NOTREACHED */
13134 argc -= optind;
13135 argv += optind;
13137 if (argc != 1)
13138 usage_integrate();
13139 branch_arg = argv[0];
13141 cwd = getcwd(NULL, 0);
13142 if (cwd == NULL) {
13143 error = got_error_from_errno("getcwd");
13144 goto done;
13147 error = got_repo_pack_fds_open(&pack_fds);
13148 if (error != NULL)
13149 goto done;
13151 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13152 if (error) {
13153 if (error->code == GOT_ERR_NOT_WORKTREE)
13154 error = wrap_not_worktree_error(error, "integrate",
13155 cwd);
13156 goto done;
13159 error = check_rebase_or_histedit_in_progress(worktree);
13160 if (error)
13161 goto done;
13163 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13164 NULL, pack_fds);
13165 if (error != NULL)
13166 goto done;
13168 error = apply_unveil(got_repo_get_path(repo), 0,
13169 got_worktree_get_root_path(worktree));
13170 if (error)
13171 goto done;
13173 error = check_merge_in_progress(worktree, repo);
13174 if (error)
13175 goto done;
13177 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13178 error = got_error_from_errno("asprintf");
13179 goto done;
13182 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13183 &base_branch_ref, worktree, refname, repo);
13184 if (error)
13185 goto done;
13187 refname = strdup(got_ref_get_name(branch_ref));
13188 if (refname == NULL) {
13189 error = got_error_from_errno("strdup");
13190 got_worktree_integrate_abort(worktree, fileindex, repo,
13191 branch_ref, base_branch_ref);
13192 goto done;
13194 base_refname = strdup(got_ref_get_name(base_branch_ref));
13195 if (base_refname == NULL) {
13196 error = got_error_from_errno("strdup");
13197 got_worktree_integrate_abort(worktree, fileindex, repo,
13198 branch_ref, base_branch_ref);
13199 goto done;
13201 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13202 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13203 got_worktree_integrate_abort(worktree, fileindex, repo,
13204 branch_ref, base_branch_ref);
13205 goto done;
13208 error = got_ref_resolve(&commit_id, repo, branch_ref);
13209 if (error)
13210 goto done;
13212 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13213 if (error)
13214 goto done;
13216 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13217 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13218 "specified branch has already been integrated");
13219 got_worktree_integrate_abort(worktree, fileindex, repo,
13220 branch_ref, base_branch_ref);
13221 goto done;
13224 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13225 if (error) {
13226 if (error->code == GOT_ERR_ANCESTRY)
13227 error = got_error(GOT_ERR_REBASE_REQUIRED);
13228 got_worktree_integrate_abort(worktree, fileindex, repo,
13229 branch_ref, base_branch_ref);
13230 goto done;
13233 memset(&upa, 0, sizeof(upa));
13234 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13235 branch_ref, base_branch_ref, update_progress, &upa,
13236 check_cancelled, NULL);
13237 if (error)
13238 goto done;
13240 printf("Integrated %s into %s\n", refname, base_refname);
13241 print_update_progress_stats(&upa);
13242 done:
13243 if (repo) {
13244 const struct got_error *close_err = got_repo_close(repo);
13245 if (error == NULL)
13246 error = close_err;
13248 if (worktree)
13249 got_worktree_close(worktree);
13250 if (pack_fds) {
13251 const struct got_error *pack_err =
13252 got_repo_pack_fds_close(pack_fds);
13253 if (error == NULL)
13254 error = pack_err;
13256 free(cwd);
13257 free(base_commit_id);
13258 free(commit_id);
13259 free(refname);
13260 free(base_refname);
13261 return error;
13264 __dead static void
13265 usage_merge(void)
13267 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13268 exit(1);
13271 static const struct got_error *
13272 cmd_merge(int argc, char *argv[])
13274 const struct got_error *error = NULL;
13275 struct got_worktree *worktree = NULL;
13276 struct got_repository *repo = NULL;
13277 struct got_fileindex *fileindex = NULL;
13278 char *cwd = NULL, *id_str = NULL, *author = NULL;
13279 char *gitconfig_path = NULL;
13280 struct got_reference *branch = NULL, *wt_branch = NULL;
13281 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13282 struct got_object_id *wt_branch_tip = NULL;
13283 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13284 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13285 struct got_update_progress_arg upa;
13286 struct got_object_id *merge_commit_id = NULL;
13287 char *branch_name = NULL;
13288 int *pack_fds = NULL;
13290 memset(&upa, 0, sizeof(upa));
13292 #ifndef PROFILE
13293 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13294 "unveil", NULL) == -1)
13295 err(1, "pledge");
13296 #endif
13298 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13299 switch (ch) {
13300 case 'a':
13301 abort_merge = 1;
13302 break;
13303 case 'C':
13304 allow_conflict = 1;
13305 break;
13306 case 'c':
13307 continue_merge = 1;
13308 break;
13309 case 'M':
13310 prefer_fast_forward = 0;
13311 break;
13312 case 'n':
13313 interrupt_merge = 1;
13314 break;
13315 default:
13316 usage_merge();
13317 /* NOTREACHED */
13321 argc -= optind;
13322 argv += optind;
13324 if (abort_merge) {
13325 if (continue_merge)
13326 option_conflict('a', 'c');
13327 if (!prefer_fast_forward)
13328 option_conflict('a', 'M');
13329 if (interrupt_merge)
13330 option_conflict('a', 'n');
13331 } else if (continue_merge) {
13332 if (!prefer_fast_forward)
13333 option_conflict('c', 'M');
13334 if (interrupt_merge)
13335 option_conflict('c', 'n');
13337 if (allow_conflict) {
13338 if (!continue_merge)
13339 errx(1, "-C option requires -c");
13341 if (abort_merge || continue_merge) {
13342 if (argc != 0)
13343 usage_merge();
13344 } else if (argc != 1)
13345 usage_merge();
13347 cwd = getcwd(NULL, 0);
13348 if (cwd == NULL) {
13349 error = got_error_from_errno("getcwd");
13350 goto done;
13353 error = got_repo_pack_fds_open(&pack_fds);
13354 if (error != NULL)
13355 goto done;
13357 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13358 if (error) {
13359 if (error->code == GOT_ERR_NOT_WORKTREE)
13360 error = wrap_not_worktree_error(error,
13361 "merge", cwd);
13362 goto done;
13365 error = get_gitconfig_path(&gitconfig_path);
13366 if (error)
13367 goto done;
13368 error = got_repo_open(&repo,
13369 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13370 gitconfig_path, pack_fds);
13371 if (error != NULL)
13372 goto done;
13374 if (worktree != NULL) {
13375 error = worktree_has_logmsg_ref("merge", worktree, repo);
13376 if (error)
13377 goto done;
13380 error = apply_unveil(got_repo_get_path(repo), 0,
13381 worktree ? got_worktree_get_root_path(worktree) : NULL);
13382 if (error)
13383 goto done;
13385 error = check_rebase_or_histedit_in_progress(worktree);
13386 if (error)
13387 goto done;
13389 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13390 repo);
13391 if (error)
13392 goto done;
13394 if (merge_in_progress && !(abort_merge || continue_merge)) {
13395 error = got_error(GOT_ERR_MERGE_BUSY);
13396 goto done;
13399 if (!merge_in_progress && (abort_merge || continue_merge)) {
13400 error = got_error(GOT_ERR_NOT_MERGING);
13401 goto done;
13404 if (abort_merge) {
13405 error = got_worktree_merge_continue(&branch_name,
13406 &branch_tip, &fileindex, worktree, repo);
13407 if (error)
13408 goto done;
13409 error = got_worktree_merge_abort(worktree, fileindex, repo,
13410 abort_progress, &upa);
13411 if (error)
13412 goto done;
13413 printf("Merge of %s aborted\n", branch_name);
13414 goto done; /* nothing else to do */
13417 if (strncmp(got_worktree_get_head_ref_name(worktree),
13418 "refs/heads/", 11) != 0) {
13419 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13420 "work tree's current branch %s is outside the "
13421 "\"refs/heads/\" reference namespace; "
13422 "update -b required",
13423 got_worktree_get_head_ref_name(worktree));
13424 goto done;
13427 error = get_author(&author, repo, worktree);
13428 if (error)
13429 goto done;
13431 error = got_ref_open(&wt_branch, repo,
13432 got_worktree_get_head_ref_name(worktree), 0);
13433 if (error)
13434 goto done;
13435 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13436 if (error)
13437 goto done;
13439 if (continue_merge) {
13440 struct got_object_id *base_commit_id;
13441 base_commit_id = got_worktree_get_base_commit_id(worktree);
13442 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13443 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13444 goto done;
13446 error = got_worktree_merge_continue(&branch_name,
13447 &branch_tip, &fileindex, worktree, repo);
13448 if (error)
13449 goto done;
13450 } else {
13451 error = got_ref_open(&branch, repo, argv[0], 0);
13452 if (error != NULL)
13453 goto done;
13454 branch_name = strdup(got_ref_get_name(branch));
13455 if (branch_name == NULL) {
13456 error = got_error_from_errno("strdup");
13457 goto done;
13459 error = got_ref_resolve(&branch_tip, repo, branch);
13460 if (error)
13461 goto done;
13464 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13465 wt_branch_tip, branch_tip, 0, repo,
13466 check_cancelled, NULL);
13467 if (error && error->code != GOT_ERR_ANCESTRY)
13468 goto done;
13470 if (!continue_merge) {
13471 error = check_path_prefix(wt_branch_tip, branch_tip,
13472 got_worktree_get_path_prefix(worktree),
13473 GOT_ERR_MERGE_PATH, repo);
13474 if (error)
13475 goto done;
13476 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13477 if (error)
13478 goto done;
13479 if (prefer_fast_forward && yca_id &&
13480 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13481 struct got_pathlist_head paths;
13482 if (interrupt_merge) {
13483 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13484 "there are no changes to merge since %s "
13485 "is already based on %s; merge cannot be "
13486 "interrupted for amending; -n",
13487 branch_name, got_ref_get_name(wt_branch));
13488 goto done;
13490 printf("Forwarding %s to %s\n",
13491 got_ref_get_name(wt_branch), branch_name);
13492 error = got_ref_change_ref(wt_branch, branch_tip);
13493 if (error)
13494 goto done;
13495 error = got_ref_write(wt_branch, repo);
13496 if (error)
13497 goto done;
13498 error = got_worktree_set_base_commit_id(worktree, repo,
13499 branch_tip);
13500 if (error)
13501 goto done;
13502 TAILQ_INIT(&paths);
13503 error = got_pathlist_append(&paths, "", NULL);
13504 if (error)
13505 goto done;
13506 error = got_worktree_checkout_files(worktree,
13507 &paths, repo, update_progress, &upa,
13508 check_cancelled, NULL);
13509 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13510 if (error)
13511 goto done;
13512 if (upa.did_something) {
13513 char *id_str;
13514 error = got_object_id_str(&id_str, branch_tip);
13515 if (error)
13516 goto done;
13517 printf("Updated to commit %s\n", id_str);
13518 free(id_str);
13519 } else
13520 printf("Already up-to-date\n");
13521 print_update_progress_stats(&upa);
13522 goto done;
13524 error = got_worktree_merge_write_refs(worktree, branch, repo);
13525 if (error)
13526 goto done;
13528 error = got_worktree_merge_branch(worktree, fileindex,
13529 yca_id, branch_tip, repo, update_progress, &upa,
13530 check_cancelled, NULL);
13531 if (error)
13532 goto done;
13533 print_merge_progress_stats(&upa);
13534 if (!upa.did_something) {
13535 error = got_worktree_merge_abort(worktree, fileindex,
13536 repo, abort_progress, &upa);
13537 if (error)
13538 goto done;
13539 printf("Already up-to-date\n");
13540 goto done;
13544 if (interrupt_merge) {
13545 error = got_worktree_merge_postpone(worktree, fileindex);
13546 if (error)
13547 goto done;
13548 printf("Merge of %s interrupted on request\n", branch_name);
13549 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13550 upa.not_deleted > 0 || upa.unversioned > 0) {
13551 error = got_worktree_merge_postpone(worktree, fileindex);
13552 if (error)
13553 goto done;
13554 if (upa.conflicts > 0 && upa.missing == 0 &&
13555 upa.not_deleted == 0 && upa.unversioned == 0) {
13556 error = got_error_msg(GOT_ERR_CONFLICTS,
13557 "conflicts must be resolved before merging "
13558 "can continue");
13559 } else if (upa.conflicts > 0) {
13560 error = got_error_msg(GOT_ERR_CONFLICTS,
13561 "conflicts must be resolved before merging "
13562 "can continue; changes destined for some "
13563 "files were not yet merged and "
13564 "should be merged manually if required before the "
13565 "merge operation is continued");
13566 } else {
13567 error = got_error_msg(GOT_ERR_CONFLICTS,
13568 "changes destined for some "
13569 "files were not yet merged and should be "
13570 "merged manually if required before the "
13571 "merge operation is continued");
13573 goto done;
13574 } else {
13575 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13576 fileindex, author, NULL, 1, branch_tip, branch_name,
13577 allow_conflict, repo, continue_merge ? print_status : NULL,
13578 NULL);
13579 if (error)
13580 goto done;
13581 error = got_worktree_merge_complete(worktree, fileindex, repo);
13582 if (error)
13583 goto done;
13584 error = got_object_id_str(&id_str, merge_commit_id);
13585 if (error)
13586 goto done;
13587 printf("Merged %s into %s: %s\n", branch_name,
13588 got_worktree_get_head_ref_name(worktree),
13589 id_str);
13592 done:
13593 free(gitconfig_path);
13594 free(id_str);
13595 free(merge_commit_id);
13596 free(author);
13597 free(branch_tip);
13598 free(branch_name);
13599 free(yca_id);
13600 if (branch)
13601 got_ref_close(branch);
13602 if (wt_branch)
13603 got_ref_close(wt_branch);
13604 if (worktree)
13605 got_worktree_close(worktree);
13606 if (repo) {
13607 const struct got_error *close_err = got_repo_close(repo);
13608 if (error == NULL)
13609 error = close_err;
13611 if (pack_fds) {
13612 const struct got_error *pack_err =
13613 got_repo_pack_fds_close(pack_fds);
13614 if (error == NULL)
13615 error = pack_err;
13617 return error;
13620 __dead static void
13621 usage_stage(void)
13623 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13624 "[path ...]\n", getprogname());
13625 exit(1);
13628 static const struct got_error *
13629 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13630 const char *path, struct got_object_id *blob_id,
13631 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13632 int dirfd, const char *de_name)
13634 const struct got_error *err = NULL;
13635 char *id_str = NULL;
13637 if (staged_status != GOT_STATUS_ADD &&
13638 staged_status != GOT_STATUS_MODIFY &&
13639 staged_status != GOT_STATUS_DELETE)
13640 return NULL;
13642 if (staged_status == GOT_STATUS_ADD ||
13643 staged_status == GOT_STATUS_MODIFY)
13644 err = got_object_id_str(&id_str, staged_blob_id);
13645 else
13646 err = got_object_id_str(&id_str, blob_id);
13647 if (err)
13648 return err;
13650 printf("%s %c %s\n", id_str, staged_status, path);
13651 free(id_str);
13652 return NULL;
13655 static const struct got_error *
13656 cmd_stage(int argc, char *argv[])
13658 const struct got_error *error = NULL;
13659 struct got_repository *repo = NULL;
13660 struct got_worktree *worktree = NULL;
13661 char *cwd = NULL;
13662 struct got_pathlist_head paths;
13663 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13664 FILE *patch_script_file = NULL;
13665 const char *patch_script_path = NULL;
13666 struct choose_patch_arg cpa;
13667 int *pack_fds = NULL;
13669 TAILQ_INIT(&paths);
13671 #ifndef PROFILE
13672 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13673 "unveil", NULL) == -1)
13674 err(1, "pledge");
13675 #endif
13677 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13678 switch (ch) {
13679 case 'F':
13680 patch_script_path = optarg;
13681 break;
13682 case 'l':
13683 list_stage = 1;
13684 break;
13685 case 'p':
13686 pflag = 1;
13687 break;
13688 case 'S':
13689 allow_bad_symlinks = 1;
13690 break;
13691 default:
13692 usage_stage();
13693 /* NOTREACHED */
13697 argc -= optind;
13698 argv += optind;
13700 if (list_stage && (pflag || patch_script_path))
13701 errx(1, "-l option cannot be used with other options");
13702 if (patch_script_path && !pflag)
13703 errx(1, "-F option can only be used together with -p option");
13705 cwd = getcwd(NULL, 0);
13706 if (cwd == NULL) {
13707 error = got_error_from_errno("getcwd");
13708 goto done;
13711 error = got_repo_pack_fds_open(&pack_fds);
13712 if (error != NULL)
13713 goto done;
13715 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13716 if (error) {
13717 if (error->code == GOT_ERR_NOT_WORKTREE)
13718 error = wrap_not_worktree_error(error, "stage", cwd);
13719 goto done;
13722 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13723 NULL, pack_fds);
13724 if (error != NULL)
13725 goto done;
13727 if (patch_script_path) {
13728 patch_script_file = fopen(patch_script_path, "re");
13729 if (patch_script_file == NULL) {
13730 error = got_error_from_errno2("fopen",
13731 patch_script_path);
13732 goto done;
13735 error = apply_unveil(got_repo_get_path(repo), 0,
13736 got_worktree_get_root_path(worktree));
13737 if (error)
13738 goto done;
13740 error = check_merge_in_progress(worktree, repo);
13741 if (error)
13742 goto done;
13744 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13745 if (error)
13746 goto done;
13748 if (list_stage)
13749 error = got_worktree_status(worktree, &paths, repo, 0,
13750 print_stage, NULL, check_cancelled, NULL);
13751 else {
13752 cpa.patch_script_file = patch_script_file;
13753 cpa.action = "stage";
13754 error = got_worktree_stage(worktree, &paths,
13755 pflag ? NULL : print_status, NULL,
13756 pflag ? choose_patch : NULL, &cpa,
13757 allow_bad_symlinks, repo);
13759 done:
13760 if (patch_script_file && fclose(patch_script_file) == EOF &&
13761 error == NULL)
13762 error = got_error_from_errno2("fclose", patch_script_path);
13763 if (repo) {
13764 const struct got_error *close_err = got_repo_close(repo);
13765 if (error == NULL)
13766 error = close_err;
13768 if (worktree)
13769 got_worktree_close(worktree);
13770 if (pack_fds) {
13771 const struct got_error *pack_err =
13772 got_repo_pack_fds_close(pack_fds);
13773 if (error == NULL)
13774 error = pack_err;
13776 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13777 free(cwd);
13778 return error;
13781 __dead static void
13782 usage_unstage(void)
13784 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13785 "[path ...]\n", getprogname());
13786 exit(1);
13790 static const struct got_error *
13791 cmd_unstage(int argc, char *argv[])
13793 const struct got_error *error = NULL;
13794 struct got_repository *repo = NULL;
13795 struct got_worktree *worktree = NULL;
13796 char *cwd = NULL;
13797 struct got_pathlist_head paths;
13798 int ch, pflag = 0;
13799 struct got_update_progress_arg upa;
13800 FILE *patch_script_file = NULL;
13801 const char *patch_script_path = NULL;
13802 struct choose_patch_arg cpa;
13803 int *pack_fds = NULL;
13805 TAILQ_INIT(&paths);
13807 #ifndef PROFILE
13808 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13809 "unveil", NULL) == -1)
13810 err(1, "pledge");
13811 #endif
13813 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13814 switch (ch) {
13815 case 'F':
13816 patch_script_path = optarg;
13817 break;
13818 case 'p':
13819 pflag = 1;
13820 break;
13821 default:
13822 usage_unstage();
13823 /* NOTREACHED */
13827 argc -= optind;
13828 argv += optind;
13830 if (patch_script_path && !pflag)
13831 errx(1, "-F option can only be used together with -p option");
13833 cwd = getcwd(NULL, 0);
13834 if (cwd == NULL) {
13835 error = got_error_from_errno("getcwd");
13836 goto done;
13839 error = got_repo_pack_fds_open(&pack_fds);
13840 if (error != NULL)
13841 goto done;
13843 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13844 if (error) {
13845 if (error->code == GOT_ERR_NOT_WORKTREE)
13846 error = wrap_not_worktree_error(error, "unstage", cwd);
13847 goto done;
13850 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13851 NULL, pack_fds);
13852 if (error != NULL)
13853 goto done;
13855 if (patch_script_path) {
13856 patch_script_file = fopen(patch_script_path, "re");
13857 if (patch_script_file == NULL) {
13858 error = got_error_from_errno2("fopen",
13859 patch_script_path);
13860 goto done;
13864 error = apply_unveil(got_repo_get_path(repo), 0,
13865 got_worktree_get_root_path(worktree));
13866 if (error)
13867 goto done;
13869 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13870 if (error)
13871 goto done;
13873 cpa.patch_script_file = patch_script_file;
13874 cpa.action = "unstage";
13875 memset(&upa, 0, sizeof(upa));
13876 error = got_worktree_unstage(worktree, &paths, update_progress,
13877 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13878 if (!error)
13879 print_merge_progress_stats(&upa);
13880 done:
13881 if (patch_script_file && fclose(patch_script_file) == EOF &&
13882 error == NULL)
13883 error = got_error_from_errno2("fclose", patch_script_path);
13884 if (repo) {
13885 const struct got_error *close_err = got_repo_close(repo);
13886 if (error == NULL)
13887 error = close_err;
13889 if (worktree)
13890 got_worktree_close(worktree);
13891 if (pack_fds) {
13892 const struct got_error *pack_err =
13893 got_repo_pack_fds_close(pack_fds);
13894 if (error == NULL)
13895 error = pack_err;
13897 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13898 free(cwd);
13899 return error;
13902 __dead static void
13903 usage_cat(void)
13905 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13906 "arg ...\n", getprogname());
13907 exit(1);
13910 static const struct got_error *
13911 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13913 const struct got_error *err;
13914 struct got_blob_object *blob;
13915 int fd = -1;
13917 fd = got_opentempfd();
13918 if (fd == -1)
13919 return got_error_from_errno("got_opentempfd");
13921 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13922 if (err)
13923 goto done;
13925 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13926 done:
13927 if (fd != -1 && close(fd) == -1 && err == NULL)
13928 err = got_error_from_errno("close");
13929 if (blob)
13930 got_object_blob_close(blob);
13931 return err;
13934 static const struct got_error *
13935 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13937 const struct got_error *err;
13938 struct got_tree_object *tree;
13939 int nentries, i;
13941 err = got_object_open_as_tree(&tree, repo, id);
13942 if (err)
13943 return err;
13945 nentries = got_object_tree_get_nentries(tree);
13946 for (i = 0; i < nentries; i++) {
13947 struct got_tree_entry *te;
13948 char *id_str;
13949 if (sigint_received || sigpipe_received)
13950 break;
13951 te = got_object_tree_get_entry(tree, i);
13952 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13953 if (err)
13954 break;
13955 fprintf(outfile, "%s %.7o %s\n", id_str,
13956 got_tree_entry_get_mode(te),
13957 got_tree_entry_get_name(te));
13958 free(id_str);
13961 got_object_tree_close(tree);
13962 return err;
13965 static const struct got_error *
13966 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13968 const struct got_error *err;
13969 struct got_commit_object *commit;
13970 const struct got_object_id_queue *parent_ids;
13971 struct got_object_qid *pid;
13972 char *id_str = NULL;
13973 const char *logmsg = NULL;
13974 char gmtoff[6];
13976 err = got_object_open_as_commit(&commit, repo, id);
13977 if (err)
13978 return err;
13980 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13981 if (err)
13982 goto done;
13984 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13985 parent_ids = got_object_commit_get_parent_ids(commit);
13986 fprintf(outfile, "numparents %d\n",
13987 got_object_commit_get_nparents(commit));
13988 STAILQ_FOREACH(pid, parent_ids, entry) {
13989 char *pid_str;
13990 err = got_object_id_str(&pid_str, &pid->id);
13991 if (err)
13992 goto done;
13993 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13994 free(pid_str);
13996 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13997 got_object_commit_get_author_gmtoff(commit));
13998 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13999 got_object_commit_get_author(commit),
14000 (long long)got_object_commit_get_author_time(commit),
14001 gmtoff);
14003 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14004 got_object_commit_get_committer_gmtoff(commit));
14005 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14006 got_object_commit_get_committer(commit),
14007 (long long)got_object_commit_get_committer_time(commit),
14008 gmtoff);
14010 logmsg = got_object_commit_get_logmsg_raw(commit);
14011 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14012 fprintf(outfile, "%s", logmsg);
14013 done:
14014 free(id_str);
14015 got_object_commit_close(commit);
14016 return err;
14019 static const struct got_error *
14020 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14022 const struct got_error *err;
14023 struct got_tag_object *tag;
14024 char *id_str = NULL;
14025 const char *tagmsg = NULL;
14026 char gmtoff[6];
14028 err = got_object_open_as_tag(&tag, repo, id);
14029 if (err)
14030 return err;
14032 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14033 if (err)
14034 goto done;
14036 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14038 switch (got_object_tag_get_object_type(tag)) {
14039 case GOT_OBJ_TYPE_BLOB:
14040 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14041 GOT_OBJ_LABEL_BLOB);
14042 break;
14043 case GOT_OBJ_TYPE_TREE:
14044 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14045 GOT_OBJ_LABEL_TREE);
14046 break;
14047 case GOT_OBJ_TYPE_COMMIT:
14048 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14049 GOT_OBJ_LABEL_COMMIT);
14050 break;
14051 case GOT_OBJ_TYPE_TAG:
14052 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14053 GOT_OBJ_LABEL_TAG);
14054 break;
14055 default:
14056 break;
14059 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14060 got_object_tag_get_name(tag));
14062 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14063 got_object_tag_get_tagger_gmtoff(tag));
14064 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14065 got_object_tag_get_tagger(tag),
14066 (long long)got_object_tag_get_tagger_time(tag),
14067 gmtoff);
14069 tagmsg = got_object_tag_get_message(tag);
14070 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14071 fprintf(outfile, "%s", tagmsg);
14072 done:
14073 free(id_str);
14074 got_object_tag_close(tag);
14075 return err;
14078 static const struct got_error *
14079 cmd_cat(int argc, char *argv[])
14081 const struct got_error *error;
14082 struct got_repository *repo = NULL;
14083 struct got_worktree *worktree = NULL;
14084 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14085 char *keyword_idstr = NULL;
14086 const char *commit_id_str = NULL;
14087 struct got_object_id *id = NULL, *commit_id = NULL;
14088 struct got_commit_object *commit = NULL;
14089 int ch, obj_type, i, force_path = 0;
14090 struct got_reflist_head refs;
14091 int *pack_fds = NULL;
14093 TAILQ_INIT(&refs);
14095 #ifndef PROFILE
14096 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14097 NULL) == -1)
14098 err(1, "pledge");
14099 #endif
14101 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14102 switch (ch) {
14103 case 'c':
14104 commit_id_str = optarg;
14105 break;
14106 case 'P':
14107 force_path = 1;
14108 break;
14109 case 'r':
14110 repo_path = realpath(optarg, NULL);
14111 if (repo_path == NULL)
14112 return got_error_from_errno2("realpath",
14113 optarg);
14114 got_path_strip_trailing_slashes(repo_path);
14115 break;
14116 default:
14117 usage_cat();
14118 /* NOTREACHED */
14122 argc -= optind;
14123 argv += optind;
14125 cwd = getcwd(NULL, 0);
14126 if (cwd == NULL) {
14127 error = got_error_from_errno("getcwd");
14128 goto done;
14131 error = got_repo_pack_fds_open(&pack_fds);
14132 if (error != NULL)
14133 goto done;
14135 if (repo_path == NULL) {
14136 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14137 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14138 goto done;
14139 if (worktree) {
14140 repo_path = strdup(
14141 got_worktree_get_repo_path(worktree));
14142 if (repo_path == NULL) {
14143 error = got_error_from_errno("strdup");
14144 goto done;
14147 if (commit_id_str == NULL) {
14148 /* Release work tree lock. */
14149 got_worktree_close(worktree);
14150 worktree = NULL;
14155 if (repo_path == NULL) {
14156 repo_path = strdup(cwd);
14157 if (repo_path == NULL)
14158 return got_error_from_errno("strdup");
14161 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14162 free(repo_path);
14163 if (error != NULL)
14164 goto done;
14166 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14167 if (error)
14168 goto done;
14170 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14171 if (error)
14172 goto done;
14174 if (commit_id_str != NULL) {
14175 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14176 repo, worktree);
14177 if (error != NULL)
14178 goto done;
14179 if (keyword_idstr != NULL)
14180 commit_id_str = keyword_idstr;
14181 if (worktree != NULL) {
14182 got_worktree_close(worktree);
14183 worktree = NULL;
14185 } else
14186 commit_id_str = GOT_REF_HEAD;
14187 error = got_repo_match_object_id(&commit_id, NULL,
14188 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14189 if (error)
14190 goto done;
14192 error = got_object_open_as_commit(&commit, repo, commit_id);
14193 if (error)
14194 goto done;
14196 for (i = 0; i < argc; i++) {
14197 if (force_path) {
14198 error = got_object_id_by_path(&id, repo, commit,
14199 argv[i]);
14200 if (error)
14201 break;
14202 } else {
14203 error = got_repo_match_object_id(&id, &label, argv[i],
14204 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14205 repo);
14206 if (error) {
14207 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14208 error->code != GOT_ERR_NOT_REF)
14209 break;
14210 error = got_object_id_by_path(&id, repo,
14211 commit, argv[i]);
14212 if (error)
14213 break;
14217 error = got_object_get_type(&obj_type, repo, id);
14218 if (error)
14219 break;
14221 switch (obj_type) {
14222 case GOT_OBJ_TYPE_BLOB:
14223 error = cat_blob(id, repo, stdout);
14224 break;
14225 case GOT_OBJ_TYPE_TREE:
14226 error = cat_tree(id, repo, stdout);
14227 break;
14228 case GOT_OBJ_TYPE_COMMIT:
14229 error = cat_commit(id, repo, stdout);
14230 break;
14231 case GOT_OBJ_TYPE_TAG:
14232 error = cat_tag(id, repo, stdout);
14233 break;
14234 default:
14235 error = got_error(GOT_ERR_OBJ_TYPE);
14236 break;
14238 if (error)
14239 break;
14240 free(label);
14241 label = NULL;
14242 free(id);
14243 id = NULL;
14245 done:
14246 free(label);
14247 free(id);
14248 free(commit_id);
14249 free(keyword_idstr);
14250 if (commit)
14251 got_object_commit_close(commit);
14252 if (worktree)
14253 got_worktree_close(worktree);
14254 if (repo) {
14255 const struct got_error *close_err = got_repo_close(repo);
14256 if (error == NULL)
14257 error = close_err;
14259 if (pack_fds) {
14260 const struct got_error *pack_err =
14261 got_repo_pack_fds_close(pack_fds);
14262 if (error == NULL)
14263 error = pack_err;
14266 got_ref_list_free(&refs);
14267 return error;
14270 __dead static void
14271 usage_info(void)
14273 fprintf(stderr, "usage: %s info [path ...]\n",
14274 getprogname());
14275 exit(1);
14278 static const struct got_error *
14279 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14280 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14281 struct got_object_id *commit_id)
14283 const struct got_error *err = NULL;
14284 char *id_str = NULL;
14285 char datebuf[128];
14286 struct tm mytm, *tm;
14287 struct got_pathlist_head *paths = arg;
14288 struct got_pathlist_entry *pe;
14291 * Clear error indication from any of the path arguments which
14292 * would cause this file index entry to be displayed.
14294 TAILQ_FOREACH(pe, paths, entry) {
14295 if (got_path_cmp(path, pe->path, strlen(path),
14296 pe->path_len) == 0 ||
14297 got_path_is_child(path, pe->path, pe->path_len))
14298 pe->data = NULL; /* no error */
14301 printf(GOT_COMMIT_SEP_STR);
14302 if (S_ISLNK(mode))
14303 printf("symlink: %s\n", path);
14304 else if (S_ISREG(mode)) {
14305 printf("file: %s\n", path);
14306 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14307 } else if (S_ISDIR(mode))
14308 printf("directory: %s\n", path);
14309 else
14310 printf("something: %s\n", path);
14312 tm = localtime_r(&mtime, &mytm);
14313 if (tm == NULL)
14314 return NULL;
14315 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14316 return got_error(GOT_ERR_NO_SPACE);
14317 printf("timestamp: %s\n", datebuf);
14319 if (blob_id) {
14320 err = got_object_id_str(&id_str, blob_id);
14321 if (err)
14322 return err;
14323 printf("based on blob: %s\n", id_str);
14324 free(id_str);
14327 if (staged_blob_id) {
14328 err = got_object_id_str(&id_str, staged_blob_id);
14329 if (err)
14330 return err;
14331 printf("based on staged blob: %s\n", id_str);
14332 free(id_str);
14335 if (commit_id) {
14336 err = got_object_id_str(&id_str, commit_id);
14337 if (err)
14338 return err;
14339 printf("based on commit: %s\n", id_str);
14340 free(id_str);
14343 return NULL;
14346 static const struct got_error *
14347 cmd_info(int argc, char *argv[])
14349 const struct got_error *error = NULL;
14350 struct got_worktree *worktree = NULL;
14351 char *cwd = NULL, *id_str = NULL;
14352 struct got_pathlist_head paths;
14353 char *uuidstr = NULL;
14354 int ch, show_files = 0;
14356 TAILQ_INIT(&paths);
14358 #ifndef PROFILE
14359 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14360 NULL) == -1)
14361 err(1, "pledge");
14362 #endif
14364 while ((ch = getopt(argc, argv, "")) != -1) {
14365 switch (ch) {
14366 default:
14367 usage_info();
14368 /* NOTREACHED */
14372 argc -= optind;
14373 argv += optind;
14375 cwd = getcwd(NULL, 0);
14376 if (cwd == NULL) {
14377 error = got_error_from_errno("getcwd");
14378 goto done;
14381 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14382 if (error) {
14383 if (error->code == GOT_ERR_NOT_WORKTREE)
14384 error = wrap_not_worktree_error(error, "info", cwd);
14385 goto done;
14388 #ifndef PROFILE
14389 /* Remove "wpath cpath proc exec sendfd" promises. */
14390 if (pledge("stdio rpath flock unveil", NULL) == -1)
14391 err(1, "pledge");
14392 #endif
14393 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14394 if (error)
14395 goto done;
14397 if (argc >= 1) {
14398 error = get_worktree_paths_from_argv(&paths, argc, argv,
14399 worktree);
14400 if (error)
14401 goto done;
14402 show_files = 1;
14405 error = got_object_id_str(&id_str,
14406 got_worktree_get_base_commit_id(worktree));
14407 if (error)
14408 goto done;
14410 error = got_worktree_get_uuid(&uuidstr, worktree);
14411 if (error)
14412 goto done;
14414 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14415 printf("work tree base commit: %s\n", id_str);
14416 printf("work tree path prefix: %s\n",
14417 got_worktree_get_path_prefix(worktree));
14418 printf("work tree branch reference: %s\n",
14419 got_worktree_get_head_ref_name(worktree));
14420 printf("work tree UUID: %s\n", uuidstr);
14421 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14423 if (show_files) {
14424 struct got_pathlist_entry *pe;
14425 TAILQ_FOREACH(pe, &paths, entry) {
14426 if (pe->path_len == 0)
14427 continue;
14429 * Assume this path will fail. This will be corrected
14430 * in print_path_info() in case the path does suceeed.
14432 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14434 error = got_worktree_path_info(worktree, &paths,
14435 print_path_info, &paths, check_cancelled, NULL);
14436 if (error)
14437 goto done;
14438 TAILQ_FOREACH(pe, &paths, entry) {
14439 if (pe->data != NULL) {
14440 const struct got_error *perr;
14442 perr = pe->data;
14443 error = got_error_fmt(perr->code, "%s",
14444 pe->path);
14445 break;
14449 done:
14450 if (worktree)
14451 got_worktree_close(worktree);
14452 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14453 free(cwd);
14454 free(id_str);
14455 free(uuidstr);
14456 return error;