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 if (err != NULL)
6811 return err;
6814 if (strncmp(refname, "refs/heads/", 11) == 0)
6815 refname += 11;
6816 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6817 refname += 18;
6818 if (strncmp(refname, "refs/remotes/", 13) == 0)
6819 refname += 13;
6821 refstr = got_ref_to_str(ref);
6822 if (refstr == NULL)
6823 return got_error_from_errno("got_ref_to_str");
6825 printf("%c %s: %s\n", marker, refname, refstr);
6826 free(refstr);
6827 return NULL;
6830 static const struct got_error *
6831 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6833 const char *refname;
6835 if (worktree == NULL)
6836 return got_error(GOT_ERR_NOT_WORKTREE);
6838 refname = got_worktree_get_head_ref_name(worktree);
6840 if (strncmp(refname, "refs/heads/", 11) == 0)
6841 refname += 11;
6842 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6843 refname += 18;
6845 printf("%s\n", refname);
6847 return NULL;
6850 static const struct got_error *
6851 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6852 int sort_by_time)
6854 static const struct got_error *err = NULL;
6855 struct got_reflist_head refs;
6856 struct got_reflist_entry *re;
6857 struct got_reference *temp_ref = NULL;
6858 int rebase_in_progress, histedit_in_progress;
6860 TAILQ_INIT(&refs);
6862 if (worktree) {
6863 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6864 worktree);
6865 if (err)
6866 return err;
6868 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6869 worktree);
6870 if (err)
6871 return err;
6873 if (rebase_in_progress || histedit_in_progress) {
6874 err = got_ref_open(&temp_ref, repo,
6875 got_worktree_get_head_ref_name(worktree), 0);
6876 if (err)
6877 return err;
6878 list_branch(repo, worktree, temp_ref);
6879 got_ref_close(temp_ref);
6883 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6884 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6885 repo);
6886 if (err)
6887 return err;
6889 TAILQ_FOREACH(re, &refs, entry)
6890 list_branch(repo, worktree, re->ref);
6892 got_ref_list_free(&refs);
6894 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6895 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6896 repo);
6897 if (err)
6898 return err;
6900 TAILQ_FOREACH(re, &refs, entry)
6901 list_branch(repo, worktree, re->ref);
6903 got_ref_list_free(&refs);
6905 return NULL;
6908 static const struct got_error *
6909 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6910 const char *branch_name)
6912 const struct got_error *err = NULL;
6913 struct got_reference *ref = NULL;
6914 char *refname, *remote_refname = NULL;
6916 if (strncmp(branch_name, "refs/", 5) == 0)
6917 branch_name += 5;
6918 if (strncmp(branch_name, "heads/", 6) == 0)
6919 branch_name += 6;
6920 else if (strncmp(branch_name, "remotes/", 8) == 0)
6921 branch_name += 8;
6923 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6924 return got_error_from_errno("asprintf");
6926 if (asprintf(&remote_refname, "refs/remotes/%s",
6927 branch_name) == -1) {
6928 err = got_error_from_errno("asprintf");
6929 goto done;
6932 err = got_ref_open(&ref, repo, refname, 0);
6933 if (err) {
6934 const struct got_error *err2;
6935 if (err->code != GOT_ERR_NOT_REF)
6936 goto done;
6938 * Keep 'err' intact such that if neither branch exists
6939 * we report "refs/heads" rather than "refs/remotes" in
6940 * our error message.
6942 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6943 if (err2)
6944 goto done;
6945 err = NULL;
6948 if (worktree &&
6949 strcmp(got_worktree_get_head_ref_name(worktree),
6950 got_ref_get_name(ref)) == 0) {
6951 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6952 "will not delete this work tree's current branch");
6953 goto done;
6956 err = delete_ref(repo, ref);
6957 done:
6958 if (ref)
6959 got_ref_close(ref);
6960 free(refname);
6961 free(remote_refname);
6962 return err;
6965 static const struct got_error *
6966 add_branch(struct got_repository *repo, const char *branch_name,
6967 struct got_object_id *base_commit_id)
6969 const struct got_error *err = NULL;
6970 struct got_reference *ref = NULL;
6971 char *refname = NULL;
6974 * Don't let the user create a branch name with a leading '-'.
6975 * While technically a valid reference name, this case is usually
6976 * an unintended typo.
6978 if (branch_name[0] == '-')
6979 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6981 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6982 branch_name += 11;
6984 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6985 err = got_error_from_errno("asprintf");
6986 goto done;
6989 err = got_ref_open(&ref, repo, refname, 0);
6990 if (err == NULL) {
6991 err = got_error(GOT_ERR_BRANCH_EXISTS);
6992 goto done;
6993 } else if (err->code != GOT_ERR_NOT_REF)
6994 goto done;
6996 err = got_ref_alloc(&ref, refname, base_commit_id);
6997 if (err)
6998 goto done;
7000 err = got_ref_write(ref, repo);
7001 done:
7002 if (ref)
7003 got_ref_close(ref);
7004 free(refname);
7005 return err;
7008 static const struct got_error *
7009 cmd_branch(int argc, char *argv[])
7011 const struct got_error *error = NULL;
7012 struct got_repository *repo = NULL;
7013 struct got_worktree *worktree = NULL;
7014 char *cwd = NULL, *repo_path = NULL;
7015 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7016 const char *delref = NULL, *commit_id_arg = NULL;
7017 struct got_reference *ref = NULL;
7018 struct got_pathlist_head paths;
7019 struct got_object_id *commit_id = NULL;
7020 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7021 int *pack_fds = NULL;
7023 TAILQ_INIT(&paths);
7025 #ifndef PROFILE
7026 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7027 "sendfd unveil", NULL) == -1)
7028 err(1, "pledge");
7029 #endif
7031 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7032 switch (ch) {
7033 case 'c':
7034 commit_id_arg = optarg;
7035 break;
7036 case 'd':
7037 delref = optarg;
7038 break;
7039 case 'l':
7040 do_list = 1;
7041 break;
7042 case 'n':
7043 do_update = 0;
7044 break;
7045 case 'r':
7046 repo_path = realpath(optarg, NULL);
7047 if (repo_path == NULL)
7048 return got_error_from_errno2("realpath",
7049 optarg);
7050 got_path_strip_trailing_slashes(repo_path);
7051 break;
7052 case 't':
7053 sort_by_time = 1;
7054 break;
7055 default:
7056 usage_branch();
7057 /* NOTREACHED */
7061 if (do_list && delref)
7062 option_conflict('l', 'd');
7063 if (sort_by_time && !do_list)
7064 errx(1, "-t option requires -l option");
7066 argc -= optind;
7067 argv += optind;
7069 if (!do_list && !delref && argc == 0)
7070 do_show = 1;
7072 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7073 errx(1, "-c option can only be used when creating a branch");
7075 if (do_list || delref) {
7076 if (argc > 0)
7077 usage_branch();
7078 } else if (!do_show && argc != 1)
7079 usage_branch();
7081 cwd = getcwd(NULL, 0);
7082 if (cwd == NULL) {
7083 error = got_error_from_errno("getcwd");
7084 goto done;
7087 error = got_repo_pack_fds_open(&pack_fds);
7088 if (error != NULL)
7089 goto done;
7091 if (repo_path == NULL) {
7092 error = got_worktree_open(&worktree, cwd,
7093 GOT_WORKTREE_GOT_DIR);
7094 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7095 goto done;
7096 else
7097 error = NULL;
7098 if (worktree) {
7099 repo_path =
7100 strdup(got_worktree_get_repo_path(worktree));
7101 if (repo_path == NULL)
7102 error = got_error_from_errno("strdup");
7103 if (error)
7104 goto done;
7105 } else {
7106 repo_path = strdup(cwd);
7107 if (repo_path == NULL) {
7108 error = got_error_from_errno("strdup");
7109 goto done;
7114 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7115 if (error != NULL)
7116 goto done;
7118 #ifndef PROFILE
7119 if (do_list || do_show) {
7120 /* Remove "cpath" promise. */
7121 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7122 NULL) == -1)
7123 err(1, "pledge");
7125 #endif
7127 error = apply_unveil(got_repo_get_path(repo), do_list,
7128 worktree ? got_worktree_get_root_path(worktree) : NULL);
7129 if (error)
7130 goto done;
7132 if (do_show)
7133 error = show_current_branch(repo, worktree);
7134 else if (do_list)
7135 error = list_branches(repo, worktree, sort_by_time);
7136 else if (delref)
7137 error = delete_branch(repo, worktree, delref);
7138 else {
7139 struct got_reflist_head refs;
7140 TAILQ_INIT(&refs);
7141 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7142 NULL);
7143 if (error)
7144 goto done;
7145 if (commit_id_arg == NULL)
7146 commit_id_arg = worktree ?
7147 got_worktree_get_head_ref_name(worktree) :
7148 GOT_REF_HEAD;
7149 else {
7150 error = got_keyword_to_idstr(&keyword_idstr,
7151 commit_id_arg, repo, worktree);
7152 if (error != NULL)
7153 goto done;
7154 if (keyword_idstr != NULL)
7155 commit_id_arg = keyword_idstr;
7157 error = got_repo_match_object_id(&commit_id, NULL,
7158 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7159 got_ref_list_free(&refs);
7160 if (error)
7161 goto done;
7162 error = add_branch(repo, argv[0], commit_id);
7163 if (error)
7164 goto done;
7165 if (worktree && do_update) {
7166 struct got_update_progress_arg upa;
7167 char *branch_refname = NULL;
7169 error = got_object_id_str(&commit_id_str, commit_id);
7170 if (error)
7171 goto done;
7172 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7173 worktree);
7174 if (error)
7175 goto done;
7176 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7177 == -1) {
7178 error = got_error_from_errno("asprintf");
7179 goto done;
7181 error = got_ref_open(&ref, repo, branch_refname, 0);
7182 free(branch_refname);
7183 if (error)
7184 goto done;
7185 error = switch_head_ref(ref, commit_id, worktree,
7186 repo);
7187 if (error)
7188 goto done;
7189 error = got_worktree_set_base_commit_id(worktree, repo,
7190 commit_id);
7191 if (error)
7192 goto done;
7193 memset(&upa, 0, sizeof(upa));
7194 error = got_worktree_checkout_files(worktree, &paths,
7195 repo, update_progress, &upa, check_cancelled,
7196 NULL);
7197 if (error)
7198 goto done;
7199 if (upa.did_something) {
7200 printf("Updated to %s: %s\n",
7201 got_worktree_get_head_ref_name(worktree),
7202 commit_id_str);
7204 print_update_progress_stats(&upa);
7207 done:
7208 free(keyword_idstr);
7209 if (ref)
7210 got_ref_close(ref);
7211 if (repo) {
7212 const struct got_error *close_err = got_repo_close(repo);
7213 if (error == NULL)
7214 error = close_err;
7216 if (worktree)
7217 got_worktree_close(worktree);
7218 if (pack_fds) {
7219 const struct got_error *pack_err =
7220 got_repo_pack_fds_close(pack_fds);
7221 if (error == NULL)
7222 error = pack_err;
7224 free(cwd);
7225 free(repo_path);
7226 free(commit_id);
7227 free(commit_id_str);
7228 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7229 return error;
7233 __dead static void
7234 usage_tag(void)
7236 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7237 "[-r repository-path] [-s signer-id] name\n", getprogname());
7238 exit(1);
7241 #if 0
7242 static const struct got_error *
7243 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7245 const struct got_error *err = NULL;
7246 struct got_reflist_entry *re, *se, *new;
7247 struct got_object_id *re_id, *se_id;
7248 struct got_tag_object *re_tag, *se_tag;
7249 time_t re_time, se_time;
7251 STAILQ_FOREACH(re, tags, entry) {
7252 se = STAILQ_FIRST(sorted);
7253 if (se == NULL) {
7254 err = got_reflist_entry_dup(&new, re);
7255 if (err)
7256 return err;
7257 STAILQ_INSERT_HEAD(sorted, new, entry);
7258 continue;
7259 } else {
7260 err = got_ref_resolve(&re_id, repo, re->ref);
7261 if (err)
7262 break;
7263 err = got_object_open_as_tag(&re_tag, repo, re_id);
7264 free(re_id);
7265 if (err)
7266 break;
7267 re_time = got_object_tag_get_tagger_time(re_tag);
7268 got_object_tag_close(re_tag);
7271 while (se) {
7272 err = got_ref_resolve(&se_id, repo, re->ref);
7273 if (err)
7274 break;
7275 err = got_object_open_as_tag(&se_tag, repo, se_id);
7276 free(se_id);
7277 if (err)
7278 break;
7279 se_time = got_object_tag_get_tagger_time(se_tag);
7280 got_object_tag_close(se_tag);
7282 if (se_time > re_time) {
7283 err = got_reflist_entry_dup(&new, re);
7284 if (err)
7285 return err;
7286 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7287 break;
7289 se = STAILQ_NEXT(se, entry);
7290 continue;
7293 done:
7294 return err;
7296 #endif
7298 static const struct got_error *
7299 get_tag_refname(char **refname, const char *tag_name)
7301 const struct got_error *err;
7303 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7304 *refname = strdup(tag_name);
7305 if (*refname == NULL)
7306 return got_error_from_errno("strdup");
7307 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7308 err = got_error_from_errno("asprintf");
7309 *refname = NULL;
7310 return err;
7313 return NULL;
7316 static const struct got_error *
7317 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7318 const char *allowed_signers, const char *revoked_signers, int verbosity)
7320 static const struct got_error *err = NULL;
7321 struct got_reflist_head refs;
7322 struct got_reflist_entry *re;
7323 char *wanted_refname = NULL;
7324 int bad_sigs = 0;
7326 TAILQ_INIT(&refs);
7328 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7329 if (err)
7330 return err;
7332 if (tag_name) {
7333 struct got_reference *ref;
7334 err = get_tag_refname(&wanted_refname, tag_name);
7335 if (err)
7336 goto done;
7337 /* Wanted tag reference should exist. */
7338 err = got_ref_open(&ref, repo, wanted_refname, 0);
7339 if (err)
7340 goto done;
7341 got_ref_close(ref);
7344 TAILQ_FOREACH(re, &refs, entry) {
7345 const char *refname;
7346 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7347 char datebuf[26];
7348 const char *tagger, *ssh_sig = NULL;
7349 char *sig_msg = NULL;
7350 time_t tagger_time;
7351 struct got_object_id *id;
7352 struct got_tag_object *tag;
7353 struct got_commit_object *commit = NULL;
7355 refname = got_ref_get_name(re->ref);
7356 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7357 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7358 continue;
7359 refname += 10;
7360 refstr = got_ref_to_str(re->ref);
7361 if (refstr == NULL) {
7362 err = got_error_from_errno("got_ref_to_str");
7363 break;
7366 err = got_ref_resolve(&id, repo, re->ref);
7367 if (err)
7368 break;
7369 err = got_object_open_as_tag(&tag, repo, id);
7370 if (err) {
7371 if (err->code != GOT_ERR_OBJ_TYPE) {
7372 free(id);
7373 break;
7375 /* "lightweight" tag */
7376 err = got_object_open_as_commit(&commit, repo, id);
7377 if (err) {
7378 free(id);
7379 break;
7381 tagger = got_object_commit_get_committer(commit);
7382 tagger_time =
7383 got_object_commit_get_committer_time(commit);
7384 err = got_object_id_str(&id_str, id);
7385 free(id);
7386 if (err)
7387 break;
7388 } else {
7389 free(id);
7390 tagger = got_object_tag_get_tagger(tag);
7391 tagger_time = got_object_tag_get_tagger_time(tag);
7392 err = got_object_id_str(&id_str,
7393 got_object_tag_get_object_id(tag));
7394 if (err)
7395 break;
7398 if (tag && verify_tags) {
7399 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7400 got_object_tag_get_message(tag));
7401 if (ssh_sig && allowed_signers == NULL) {
7402 err = got_error_msg(
7403 GOT_ERR_VERIFY_TAG_SIGNATURE,
7404 "SSH signature verification requires "
7405 "setting allowed_signers in "
7406 "got.conf(5)");
7407 break;
7411 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7412 free(refstr);
7413 printf("from: %s\n", tagger);
7414 datestr = get_datestr(&tagger_time, datebuf);
7415 if (datestr)
7416 printf("date: %s UTC\n", datestr);
7417 if (commit)
7418 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7419 else {
7420 switch (got_object_tag_get_object_type(tag)) {
7421 case GOT_OBJ_TYPE_BLOB:
7422 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7423 id_str);
7424 break;
7425 case GOT_OBJ_TYPE_TREE:
7426 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7427 id_str);
7428 break;
7429 case GOT_OBJ_TYPE_COMMIT:
7430 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7431 id_str);
7432 break;
7433 case GOT_OBJ_TYPE_TAG:
7434 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7435 id_str);
7436 break;
7437 default:
7438 break;
7441 free(id_str);
7443 if (ssh_sig) {
7444 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7445 allowed_signers, revoked_signers, verbosity);
7446 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7447 bad_sigs = 1;
7448 else if (err)
7449 break;
7450 printf("signature: %s", sig_msg);
7451 free(sig_msg);
7452 sig_msg = NULL;
7455 if (commit) {
7456 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7457 if (err)
7458 break;
7459 got_object_commit_close(commit);
7460 } else {
7461 tagmsg0 = strdup(got_object_tag_get_message(tag));
7462 got_object_tag_close(tag);
7463 if (tagmsg0 == NULL) {
7464 err = got_error_from_errno("strdup");
7465 break;
7469 tagmsg = tagmsg0;
7470 do {
7471 line = strsep(&tagmsg, "\n");
7472 if (line)
7473 printf(" %s\n", line);
7474 } while (line);
7475 free(tagmsg0);
7477 done:
7478 got_ref_list_free(&refs);
7479 free(wanted_refname);
7481 if (err == NULL && bad_sigs)
7482 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7483 return err;
7486 static const struct got_error *
7487 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7488 const char *tag_name, const char *repo_path)
7490 const struct got_error *err = NULL;
7491 char *template = NULL, *initial_content = NULL;
7492 char *editor = NULL;
7493 int initial_content_len;
7494 int fd = -1;
7496 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7497 err = got_error_from_errno("asprintf");
7498 goto done;
7501 initial_content_len = asprintf(&initial_content,
7502 "\n# tagging commit %s as %s\n",
7503 commit_id_str, tag_name);
7504 if (initial_content_len == -1) {
7505 err = got_error_from_errno("asprintf");
7506 goto done;
7509 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7510 if (err)
7511 goto done;
7513 if (write(fd, initial_content, initial_content_len) == -1) {
7514 err = got_error_from_errno2("write", *tagmsg_path);
7515 goto done;
7517 if (close(fd) == -1) {
7518 err = got_error_from_errno2("close", *tagmsg_path);
7519 goto done;
7521 fd = -1;
7523 err = get_editor(&editor);
7524 if (err)
7525 goto done;
7526 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7527 initial_content_len, 1);
7528 done:
7529 free(initial_content);
7530 free(template);
7531 free(editor);
7533 if (fd != -1 && close(fd) == -1 && err == NULL)
7534 err = got_error_from_errno2("close", *tagmsg_path);
7536 if (err) {
7537 free(*tagmsg);
7538 *tagmsg = NULL;
7540 return err;
7543 static const struct got_error *
7544 add_tag(struct got_repository *repo, const char *tagger,
7545 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7546 const char *signer_id, int verbosity)
7548 const struct got_error *err = NULL;
7549 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7550 char *label = NULL, *commit_id_str = NULL;
7551 struct got_reference *ref = NULL;
7552 char *refname = NULL, *tagmsg = NULL;
7553 char *tagmsg_path = NULL, *tag_id_str = NULL;
7554 int preserve_tagmsg = 0;
7555 struct got_reflist_head refs;
7557 TAILQ_INIT(&refs);
7560 * Don't let the user create a tag name with a leading '-'.
7561 * While technically a valid reference name, this case is usually
7562 * an unintended typo.
7564 if (tag_name[0] == '-')
7565 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7567 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7568 if (err)
7569 goto done;
7571 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7572 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7573 if (err)
7574 goto done;
7576 err = got_object_id_str(&commit_id_str, commit_id);
7577 if (err)
7578 goto done;
7580 err = get_tag_refname(&refname, tag_name);
7581 if (err)
7582 goto done;
7583 if (strncmp("refs/tags/", tag_name, 10) == 0)
7584 tag_name += 10;
7586 err = got_ref_open(&ref, repo, refname, 0);
7587 if (err == NULL) {
7588 err = got_error(GOT_ERR_TAG_EXISTS);
7589 goto done;
7590 } else if (err->code != GOT_ERR_NOT_REF)
7591 goto done;
7593 if (tagmsg_arg == NULL) {
7594 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7595 tag_name, got_repo_get_path(repo));
7596 if (err) {
7597 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7598 tagmsg_path != NULL)
7599 preserve_tagmsg = 1;
7600 goto done;
7602 /* Editor is done; we can now apply unveil(2) */
7603 err = got_sigs_apply_unveil();
7604 if (err)
7605 goto done;
7606 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7607 if (err)
7608 goto done;
7611 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7612 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7613 verbosity);
7614 if (err) {
7615 if (tagmsg_path)
7616 preserve_tagmsg = 1;
7617 goto done;
7620 err = got_ref_alloc(&ref, refname, tag_id);
7621 if (err) {
7622 if (tagmsg_path)
7623 preserve_tagmsg = 1;
7624 goto done;
7627 err = got_ref_write(ref, repo);
7628 if (err) {
7629 if (tagmsg_path)
7630 preserve_tagmsg = 1;
7631 goto done;
7634 err = got_object_id_str(&tag_id_str, tag_id);
7635 if (err) {
7636 if (tagmsg_path)
7637 preserve_tagmsg = 1;
7638 goto done;
7640 printf("Created tag %s\n", tag_id_str);
7641 done:
7642 if (preserve_tagmsg) {
7643 fprintf(stderr, "%s: tag message preserved in %s\n",
7644 getprogname(), tagmsg_path);
7645 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7646 err = got_error_from_errno2("unlink", tagmsg_path);
7647 free(tag_id_str);
7648 if (ref)
7649 got_ref_close(ref);
7650 free(commit_id);
7651 free(commit_id_str);
7652 free(refname);
7653 free(tagmsg);
7654 free(tagmsg_path);
7655 got_ref_list_free(&refs);
7656 return err;
7659 static const struct got_error *
7660 cmd_tag(int argc, char *argv[])
7662 const struct got_error *error = NULL;
7663 struct got_repository *repo = NULL;
7664 struct got_worktree *worktree = NULL;
7665 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7666 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7667 char *allowed_signers = NULL, *revoked_signers = NULL;
7668 const char *signer_id = NULL;
7669 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7670 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7671 int *pack_fds = NULL;
7673 #ifndef PROFILE
7674 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7675 "sendfd unveil", NULL) == -1)
7676 err(1, "pledge");
7677 #endif
7679 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7680 switch (ch) {
7681 case 'c':
7682 commit_id_arg = optarg;
7683 break;
7684 case 'l':
7685 do_list = 1;
7686 break;
7687 case 'm':
7688 tagmsg = optarg;
7689 break;
7690 case 'r':
7691 repo_path = realpath(optarg, NULL);
7692 if (repo_path == NULL) {
7693 error = got_error_from_errno2("realpath",
7694 optarg);
7695 goto done;
7697 got_path_strip_trailing_slashes(repo_path);
7698 break;
7699 case 's':
7700 signer_id = optarg;
7701 break;
7702 case 'V':
7703 verify_tags = 1;
7704 break;
7705 case 'v':
7706 if (verbosity < 0)
7707 verbosity = 0;
7708 else if (verbosity < 3)
7709 verbosity++;
7710 break;
7711 default:
7712 usage_tag();
7713 /* NOTREACHED */
7717 argc -= optind;
7718 argv += optind;
7720 if (do_list || verify_tags) {
7721 if (commit_id_arg != NULL)
7722 errx(1,
7723 "-c option can only be used when creating a tag");
7724 if (tagmsg) {
7725 if (do_list)
7726 option_conflict('l', 'm');
7727 else
7728 option_conflict('V', 'm');
7730 if (signer_id) {
7731 if (do_list)
7732 option_conflict('l', 's');
7733 else
7734 option_conflict('V', 's');
7736 if (argc > 1)
7737 usage_tag();
7738 } else if (argc != 1)
7739 usage_tag();
7741 if (argc == 1)
7742 tag_name = argv[0];
7744 cwd = getcwd(NULL, 0);
7745 if (cwd == NULL) {
7746 error = got_error_from_errno("getcwd");
7747 goto done;
7750 error = got_repo_pack_fds_open(&pack_fds);
7751 if (error != NULL)
7752 goto done;
7754 if (repo_path == NULL) {
7755 error = got_worktree_open(&worktree, cwd,
7756 GOT_WORKTREE_GOT_DIR);
7757 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7758 goto done;
7759 else
7760 error = NULL;
7761 if (worktree) {
7762 repo_path =
7763 strdup(got_worktree_get_repo_path(worktree));
7764 if (repo_path == NULL)
7765 error = got_error_from_errno("strdup");
7766 if (error)
7767 goto done;
7768 } else {
7769 repo_path = strdup(cwd);
7770 if (repo_path == NULL) {
7771 error = got_error_from_errno("strdup");
7772 goto done;
7777 if (do_list || verify_tags) {
7778 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7779 if (error != NULL)
7780 goto done;
7781 error = get_allowed_signers(&allowed_signers, repo, worktree);
7782 if (error)
7783 goto done;
7784 error = get_revoked_signers(&revoked_signers, repo, worktree);
7785 if (error)
7786 goto done;
7787 if (worktree) {
7788 /* Release work tree lock. */
7789 got_worktree_close(worktree);
7790 worktree = NULL;
7794 * Remove "cpath" promise unless needed for signature tmpfile
7795 * creation.
7797 if (verify_tags)
7798 got_sigs_apply_unveil();
7799 else {
7800 #ifndef PROFILE
7801 if (pledge("stdio rpath wpath flock proc exec sendfd "
7802 "unveil", NULL) == -1)
7803 err(1, "pledge");
7804 #endif
7806 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7807 if (error)
7808 goto done;
7809 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7810 revoked_signers, verbosity);
7811 } else {
7812 error = get_gitconfig_path(&gitconfig_path);
7813 if (error)
7814 goto done;
7815 error = got_repo_open(&repo, repo_path, gitconfig_path,
7816 pack_fds);
7817 if (error != NULL)
7818 goto done;
7820 error = get_author(&tagger, repo, worktree);
7821 if (error)
7822 goto done;
7823 if (signer_id == NULL)
7824 signer_id = get_signer_id(repo, worktree);
7826 if (tagmsg) {
7827 if (signer_id) {
7828 error = got_sigs_apply_unveil();
7829 if (error)
7830 goto done;
7832 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7833 if (error)
7834 goto done;
7837 if (commit_id_arg == NULL) {
7838 struct got_reference *head_ref;
7839 struct got_object_id *commit_id;
7840 error = got_ref_open(&head_ref, repo,
7841 worktree ? got_worktree_get_head_ref_name(worktree)
7842 : GOT_REF_HEAD, 0);
7843 if (error)
7844 goto done;
7845 error = got_ref_resolve(&commit_id, repo, head_ref);
7846 got_ref_close(head_ref);
7847 if (error)
7848 goto done;
7849 error = got_object_id_str(&commit_id_str, commit_id);
7850 free(commit_id);
7851 if (error)
7852 goto done;
7853 } else {
7854 error = got_keyword_to_idstr(&keyword_idstr,
7855 commit_id_arg, repo, worktree);
7856 if (error != NULL)
7857 goto done;
7858 commit_id_str = keyword_idstr;
7861 if (worktree) {
7862 /* Release work tree lock. */
7863 got_worktree_close(worktree);
7864 worktree = NULL;
7867 error = add_tag(repo, tagger, tag_name,
7868 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7869 signer_id, verbosity);
7871 done:
7872 if (repo) {
7873 const struct got_error *close_err = got_repo_close(repo);
7874 if (error == NULL)
7875 error = close_err;
7877 if (worktree)
7878 got_worktree_close(worktree);
7879 if (pack_fds) {
7880 const struct got_error *pack_err =
7881 got_repo_pack_fds_close(pack_fds);
7882 if (error == NULL)
7883 error = pack_err;
7885 free(cwd);
7886 free(repo_path);
7887 free(gitconfig_path);
7888 free(commit_id_str);
7889 free(tagger);
7890 free(allowed_signers);
7891 free(revoked_signers);
7892 return error;
7895 __dead static void
7896 usage_add(void)
7898 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7899 exit(1);
7902 static const struct got_error *
7903 add_progress(void *arg, unsigned char status, const char *path)
7905 while (path[0] == '/')
7906 path++;
7907 printf("%c %s\n", status, path);
7908 return NULL;
7911 static const struct got_error *
7912 cmd_add(int argc, char *argv[])
7914 const struct got_error *error = NULL;
7915 struct got_repository *repo = NULL;
7916 struct got_worktree *worktree = NULL;
7917 char *cwd = NULL;
7918 struct got_pathlist_head paths;
7919 struct got_pathlist_entry *pe;
7920 int ch, can_recurse = 0, no_ignores = 0;
7921 int *pack_fds = NULL;
7923 TAILQ_INIT(&paths);
7925 #ifndef PROFILE
7926 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7927 NULL) == -1)
7928 err(1, "pledge");
7929 #endif
7931 while ((ch = getopt(argc, argv, "IR")) != -1) {
7932 switch (ch) {
7933 case 'I':
7934 no_ignores = 1;
7935 break;
7936 case 'R':
7937 can_recurse = 1;
7938 break;
7939 default:
7940 usage_add();
7941 /* NOTREACHED */
7945 argc -= optind;
7946 argv += optind;
7948 if (argc < 1)
7949 usage_add();
7951 cwd = getcwd(NULL, 0);
7952 if (cwd == NULL) {
7953 error = got_error_from_errno("getcwd");
7954 goto done;
7957 error = got_repo_pack_fds_open(&pack_fds);
7958 if (error != NULL)
7959 goto done;
7961 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7962 if (error) {
7963 if (error->code == GOT_ERR_NOT_WORKTREE)
7964 error = wrap_not_worktree_error(error, "add", cwd);
7965 goto done;
7968 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7969 NULL, pack_fds);
7970 if (error != NULL)
7971 goto done;
7973 error = apply_unveil(got_repo_get_path(repo), 1,
7974 got_worktree_get_root_path(worktree));
7975 if (error)
7976 goto done;
7978 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7979 if (error)
7980 goto done;
7982 if (!can_recurse) {
7983 char *ondisk_path;
7984 struct stat sb;
7985 TAILQ_FOREACH(pe, &paths, entry) {
7986 if (asprintf(&ondisk_path, "%s/%s",
7987 got_worktree_get_root_path(worktree),
7988 pe->path) == -1) {
7989 error = got_error_from_errno("asprintf");
7990 goto done;
7992 if (lstat(ondisk_path, &sb) == -1) {
7993 if (errno == ENOENT) {
7994 free(ondisk_path);
7995 continue;
7997 error = got_error_from_errno2("lstat",
7998 ondisk_path);
7999 free(ondisk_path);
8000 goto done;
8002 free(ondisk_path);
8003 if (S_ISDIR(sb.st_mode)) {
8004 error = got_error_msg(GOT_ERR_BAD_PATH,
8005 "adding directories requires -R option");
8006 goto done;
8011 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8012 NULL, repo, no_ignores);
8013 done:
8014 if (repo) {
8015 const struct got_error *close_err = got_repo_close(repo);
8016 if (error == NULL)
8017 error = close_err;
8019 if (worktree)
8020 got_worktree_close(worktree);
8021 if (pack_fds) {
8022 const struct got_error *pack_err =
8023 got_repo_pack_fds_close(pack_fds);
8024 if (error == NULL)
8025 error = pack_err;
8027 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8028 free(cwd);
8029 return error;
8032 __dead static void
8033 usage_remove(void)
8035 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8036 getprogname());
8037 exit(1);
8040 static const struct got_error *
8041 print_remove_status(void *arg, unsigned char status,
8042 unsigned char staged_status, const char *path)
8044 while (path[0] == '/')
8045 path++;
8046 if (status == GOT_STATUS_NONEXISTENT)
8047 return NULL;
8048 if (status == staged_status && (status == GOT_STATUS_DELETE))
8049 status = GOT_STATUS_NO_CHANGE;
8050 printf("%c%c %s\n", status, staged_status, path);
8051 return NULL;
8054 static const struct got_error *
8055 cmd_remove(int argc, char *argv[])
8057 const struct got_error *error = NULL;
8058 struct got_worktree *worktree = NULL;
8059 struct got_repository *repo = NULL;
8060 const char *status_codes = NULL;
8061 char *cwd = NULL;
8062 struct got_pathlist_head paths;
8063 struct got_pathlist_entry *pe;
8064 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8065 int ignore_missing_paths = 0;
8066 int *pack_fds = NULL;
8068 TAILQ_INIT(&paths);
8070 #ifndef PROFILE
8071 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8072 NULL) == -1)
8073 err(1, "pledge");
8074 #endif
8076 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8077 switch (ch) {
8078 case 'f':
8079 delete_local_mods = 1;
8080 ignore_missing_paths = 1;
8081 break;
8082 case 'k':
8083 keep_on_disk = 1;
8084 break;
8085 case 'R':
8086 can_recurse = 1;
8087 break;
8088 case 's':
8089 for (i = 0; optarg[i] != '\0'; i++) {
8090 switch (optarg[i]) {
8091 case GOT_STATUS_MODIFY:
8092 delete_local_mods = 1;
8093 break;
8094 case GOT_STATUS_MISSING:
8095 ignore_missing_paths = 1;
8096 break;
8097 default:
8098 errx(1, "invalid status code '%c'",
8099 optarg[i]);
8102 status_codes = optarg;
8103 break;
8104 default:
8105 usage_remove();
8106 /* NOTREACHED */
8110 argc -= optind;
8111 argv += optind;
8113 if (argc < 1)
8114 usage_remove();
8116 cwd = getcwd(NULL, 0);
8117 if (cwd == NULL) {
8118 error = got_error_from_errno("getcwd");
8119 goto done;
8122 error = got_repo_pack_fds_open(&pack_fds);
8123 if (error != NULL)
8124 goto done;
8126 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8127 if (error) {
8128 if (error->code == GOT_ERR_NOT_WORKTREE)
8129 error = wrap_not_worktree_error(error, "remove", cwd);
8130 goto done;
8133 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8134 NULL, pack_fds);
8135 if (error)
8136 goto done;
8138 error = apply_unveil(got_repo_get_path(repo), 1,
8139 got_worktree_get_root_path(worktree));
8140 if (error)
8141 goto done;
8143 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8144 if (error)
8145 goto done;
8147 if (!can_recurse) {
8148 char *ondisk_path;
8149 struct stat sb;
8150 TAILQ_FOREACH(pe, &paths, entry) {
8151 if (asprintf(&ondisk_path, "%s/%s",
8152 got_worktree_get_root_path(worktree),
8153 pe->path) == -1) {
8154 error = got_error_from_errno("asprintf");
8155 goto done;
8157 if (lstat(ondisk_path, &sb) == -1) {
8158 if (errno == ENOENT) {
8159 free(ondisk_path);
8160 continue;
8162 error = got_error_from_errno2("lstat",
8163 ondisk_path);
8164 free(ondisk_path);
8165 goto done;
8167 free(ondisk_path);
8168 if (S_ISDIR(sb.st_mode)) {
8169 error = got_error_msg(GOT_ERR_BAD_PATH,
8170 "removing directories requires -R option");
8171 goto done;
8176 error = got_worktree_schedule_delete(worktree, &paths,
8177 delete_local_mods, status_codes, print_remove_status, NULL,
8178 repo, keep_on_disk, ignore_missing_paths);
8179 done:
8180 if (repo) {
8181 const struct got_error *close_err = got_repo_close(repo);
8182 if (error == NULL)
8183 error = close_err;
8185 if (worktree)
8186 got_worktree_close(worktree);
8187 if (pack_fds) {
8188 const struct got_error *pack_err =
8189 got_repo_pack_fds_close(pack_fds);
8190 if (error == NULL)
8191 error = pack_err;
8193 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8194 free(cwd);
8195 return error;
8198 __dead static void
8199 usage_patch(void)
8201 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8202 "[patchfile]\n", getprogname());
8203 exit(1);
8206 static const struct got_error *
8207 patch_from_stdin(int *patchfd)
8209 const struct got_error *err = NULL;
8210 ssize_t r;
8211 char buf[BUFSIZ];
8212 sig_t sighup, sigint, sigquit;
8214 *patchfd = got_opentempfd();
8215 if (*patchfd == -1)
8216 return got_error_from_errno("got_opentempfd");
8218 sighup = signal(SIGHUP, SIG_DFL);
8219 sigint = signal(SIGINT, SIG_DFL);
8220 sigquit = signal(SIGQUIT, SIG_DFL);
8222 for (;;) {
8223 r = read(0, buf, sizeof(buf));
8224 if (r == -1) {
8225 err = got_error_from_errno("read");
8226 break;
8228 if (r == 0)
8229 break;
8230 if (write(*patchfd, buf, r) == -1) {
8231 err = got_error_from_errno("write");
8232 break;
8236 signal(SIGHUP, sighup);
8237 signal(SIGINT, sigint);
8238 signal(SIGQUIT, sigquit);
8240 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8241 err = got_error_from_errno("lseek");
8243 if (err != NULL) {
8244 close(*patchfd);
8245 *patchfd = -1;
8248 return err;
8251 struct got_patch_progress_arg {
8252 int did_something;
8253 int conflicts;
8254 int rejects;
8257 static const struct got_error *
8258 patch_progress(void *arg, const char *old, const char *new,
8259 unsigned char status, const struct got_error *error, int old_from,
8260 int old_lines, int new_from, int new_lines, int offset,
8261 int ws_mangled, const struct got_error *hunk_err)
8263 const char *path = new == NULL ? old : new;
8264 struct got_patch_progress_arg *a = arg;
8266 while (*path == '/')
8267 path++;
8269 if (status != GOT_STATUS_NO_CHANGE &&
8270 status != 0 /* per-hunk progress */) {
8271 printf("%c %s\n", status, path);
8272 a->did_something = 1;
8275 if (hunk_err == NULL) {
8276 if (status == GOT_STATUS_CANNOT_UPDATE)
8277 a->rejects++;
8278 else if (status == GOT_STATUS_CONFLICT)
8279 a->conflicts++;
8282 if (error != NULL)
8283 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8285 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8286 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8287 old_lines, new_from, new_lines);
8288 if (hunk_err != NULL)
8289 printf("%s\n", hunk_err->msg);
8290 else if (offset != 0)
8291 printf("applied with offset %d\n", offset);
8292 else
8293 printf("hunk contains mangled whitespace\n");
8296 return NULL;
8299 static void
8300 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8302 if (!ppa->did_something)
8303 return;
8305 if (ppa->conflicts > 0)
8306 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8308 if (ppa->rejects > 0) {
8309 printf("Files where patch failed to apply: %d\n",
8310 ppa->rejects);
8314 static const struct got_error *
8315 cmd_patch(int argc, char *argv[])
8317 const struct got_error *error = NULL, *close_error = NULL;
8318 struct got_worktree *worktree = NULL;
8319 struct got_repository *repo = NULL;
8320 struct got_reflist_head refs;
8321 struct got_object_id *commit_id = NULL;
8322 const char *commit_id_str = NULL;
8323 struct stat sb;
8324 const char *errstr;
8325 char *cwd = NULL, *keyword_idstr = NULL;
8326 int ch, nop = 0, strip = -1, reverse = 0;
8327 int patchfd;
8328 int *pack_fds = NULL;
8329 struct got_patch_progress_arg ppa;
8331 TAILQ_INIT(&refs);
8333 #ifndef PROFILE
8334 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8335 "unveil", NULL) == -1)
8336 err(1, "pledge");
8337 #endif
8339 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8340 switch (ch) {
8341 case 'c':
8342 commit_id_str = optarg;
8343 break;
8344 case 'n':
8345 nop = 1;
8346 break;
8347 case 'p':
8348 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8349 if (errstr != NULL)
8350 errx(1, "pathname strip count is %s: %s",
8351 errstr, optarg);
8352 break;
8353 case 'R':
8354 reverse = 1;
8355 break;
8356 default:
8357 usage_patch();
8358 /* NOTREACHED */
8362 argc -= optind;
8363 argv += optind;
8365 if (argc == 0) {
8366 error = patch_from_stdin(&patchfd);
8367 if (error)
8368 return error;
8369 } else if (argc == 1) {
8370 patchfd = open(argv[0], O_RDONLY);
8371 if (patchfd == -1) {
8372 error = got_error_from_errno2("open", argv[0]);
8373 return error;
8375 if (fstat(patchfd, &sb) == -1) {
8376 error = got_error_from_errno2("fstat", argv[0]);
8377 goto done;
8379 if (!S_ISREG(sb.st_mode)) {
8380 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8381 goto done;
8383 } else
8384 usage_patch();
8386 if ((cwd = getcwd(NULL, 0)) == NULL) {
8387 error = got_error_from_errno("getcwd");
8388 goto done;
8391 error = got_repo_pack_fds_open(&pack_fds);
8392 if (error != NULL)
8393 goto done;
8395 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8396 if (error != NULL)
8397 goto done;
8399 const char *repo_path = got_worktree_get_repo_path(worktree);
8400 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8401 if (error != NULL)
8402 goto done;
8404 error = apply_unveil(got_repo_get_path(repo), 0,
8405 got_worktree_get_root_path(worktree));
8406 if (error != NULL)
8407 goto done;
8409 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8410 if (error)
8411 goto done;
8413 if (commit_id_str != NULL) {
8414 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8415 repo, worktree);
8416 if (error != NULL)
8417 goto done;
8419 error = got_repo_match_object_id(&commit_id, NULL,
8420 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8421 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8422 if (error)
8423 goto done;
8426 memset(&ppa, 0, sizeof(ppa));
8427 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8428 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8429 print_patch_progress_stats(&ppa);
8430 done:
8431 got_ref_list_free(&refs);
8432 free(keyword_idstr);
8433 free(commit_id);
8434 if (repo) {
8435 close_error = got_repo_close(repo);
8436 if (error == NULL)
8437 error = close_error;
8439 if (worktree != NULL) {
8440 close_error = got_worktree_close(worktree);
8441 if (error == NULL)
8442 error = close_error;
8444 if (pack_fds) {
8445 const struct got_error *pack_err =
8446 got_repo_pack_fds_close(pack_fds);
8447 if (error == NULL)
8448 error = pack_err;
8450 free(cwd);
8451 return error;
8454 __dead static void
8455 usage_revert(void)
8457 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8458 getprogname());
8459 exit(1);
8462 static const struct got_error *
8463 revert_progress(void *arg, unsigned char status, const char *path)
8465 if (status == GOT_STATUS_UNVERSIONED)
8466 return NULL;
8468 while (path[0] == '/')
8469 path++;
8470 printf("%c %s\n", status, path);
8471 return NULL;
8474 struct choose_patch_arg {
8475 FILE *patch_script_file;
8476 const char *action;
8479 static const struct got_error *
8480 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8481 int nchanges, const char *action)
8483 const struct got_error *err;
8484 char *line = NULL;
8485 size_t linesize = 0;
8486 ssize_t linelen;
8488 switch (status) {
8489 case GOT_STATUS_ADD:
8490 printf("A %s\n%s this addition? [y/n] ", path, action);
8491 break;
8492 case GOT_STATUS_DELETE:
8493 printf("D %s\n%s this deletion? [y/n] ", path, action);
8494 break;
8495 case GOT_STATUS_MODIFY:
8496 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8497 return got_error_from_errno("fseek");
8498 printf(GOT_COMMIT_SEP_STR);
8499 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8500 printf("%s", line);
8501 if (linelen == -1 && ferror(patch_file)) {
8502 err = got_error_from_errno("getline");
8503 free(line);
8504 return err;
8506 free(line);
8507 printf(GOT_COMMIT_SEP_STR);
8508 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8509 path, n, nchanges, action);
8510 break;
8511 default:
8512 return got_error_path(path, GOT_ERR_FILE_STATUS);
8515 fflush(stdout);
8516 return NULL;
8519 static const struct got_error *
8520 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8521 FILE *patch_file, int n, int nchanges)
8523 const struct got_error *err = NULL;
8524 char *line = NULL;
8525 size_t linesize = 0;
8526 ssize_t linelen;
8527 int resp = ' ';
8528 struct choose_patch_arg *a = arg;
8530 *choice = GOT_PATCH_CHOICE_NONE;
8532 if (a->patch_script_file) {
8533 char *nl;
8534 err = show_change(status, path, patch_file, n, nchanges,
8535 a->action);
8536 if (err)
8537 return err;
8538 linelen = getline(&line, &linesize, a->patch_script_file);
8539 if (linelen == -1) {
8540 if (ferror(a->patch_script_file))
8541 return got_error_from_errno("getline");
8542 return NULL;
8544 nl = strchr(line, '\n');
8545 if (nl)
8546 *nl = '\0';
8547 if (strcmp(line, "y") == 0) {
8548 *choice = GOT_PATCH_CHOICE_YES;
8549 printf("y\n");
8550 } else if (strcmp(line, "n") == 0) {
8551 *choice = GOT_PATCH_CHOICE_NO;
8552 printf("n\n");
8553 } else if (strcmp(line, "q") == 0 &&
8554 status == GOT_STATUS_MODIFY) {
8555 *choice = GOT_PATCH_CHOICE_QUIT;
8556 printf("q\n");
8557 } else
8558 printf("invalid response '%s'\n", line);
8559 free(line);
8560 return NULL;
8563 while (resp != 'y' && resp != 'n' && resp != 'q') {
8564 err = show_change(status, path, patch_file, n, nchanges,
8565 a->action);
8566 if (err)
8567 return err;
8568 resp = getchar();
8569 if (resp == '\n')
8570 resp = getchar();
8571 if (status == GOT_STATUS_MODIFY) {
8572 if (resp != 'y' && resp != 'n' && resp != 'q') {
8573 printf("invalid response '%c'\n", resp);
8574 resp = ' ';
8576 } else if (resp != 'y' && resp != 'n') {
8577 printf("invalid response '%c'\n", resp);
8578 resp = ' ';
8582 if (resp == 'y')
8583 *choice = GOT_PATCH_CHOICE_YES;
8584 else if (resp == 'n')
8585 *choice = GOT_PATCH_CHOICE_NO;
8586 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8587 *choice = GOT_PATCH_CHOICE_QUIT;
8589 return NULL;
8592 struct wt_commitable_path_arg {
8593 struct got_pathlist_head *commit_paths;
8594 int *has_changes;
8598 * Shortcut work tree status callback to determine if the set of paths scanned
8599 * has at least one versioned path that is being modified and, if not NULL, is
8600 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8601 * soon as a path is passed with a status that satisfies this criteria.
8603 static const struct got_error *
8604 worktree_has_commitable_path(void *arg, unsigned char status,
8605 unsigned char staged_status, const char *path,
8606 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8607 struct got_object_id *commit_id, int dirfd, const char *de_name)
8609 struct wt_commitable_path_arg *a = arg;
8611 if (status == staged_status && (status == GOT_STATUS_DELETE))
8612 status = GOT_STATUS_NO_CHANGE;
8614 if (!(status == GOT_STATUS_NO_CHANGE ||
8615 status == GOT_STATUS_UNVERSIONED) ||
8616 staged_status != GOT_STATUS_NO_CHANGE) {
8617 if (a->commit_paths != NULL) {
8618 struct got_pathlist_entry *pe;
8620 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8621 if (strncmp(path, pe->path,
8622 pe->path_len) == 0) {
8623 *a->has_changes = 1;
8624 break;
8627 } else
8628 *a->has_changes = 1;
8630 if (*a->has_changes)
8631 return got_error(GOT_ERR_FILE_MODIFIED);
8634 return NULL;
8638 * Check that the changeset of the commit identified by id is
8639 * comprised of at least one modified path that is being committed.
8641 static const struct got_error *
8642 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8643 struct got_object_id *id, struct got_worktree *worktree,
8644 struct got_repository *repo)
8646 const struct got_error *err;
8647 struct got_pathlist_head paths;
8648 struct got_commit_object *commit = NULL, *pcommit = NULL;
8649 struct got_tree_object *tree = NULL, *ptree = NULL;
8650 struct got_object_qid *pid;
8652 TAILQ_INIT(&paths);
8654 err = got_object_open_as_commit(&commit, repo, id);
8655 if (err)
8656 goto done;
8658 err = got_object_open_as_tree(&tree, repo,
8659 got_object_commit_get_tree_id(commit));
8660 if (err)
8661 goto done;
8663 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8664 if (pid != NULL) {
8665 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8666 if (err)
8667 goto done;
8669 err = got_object_open_as_tree(&ptree, repo,
8670 got_object_commit_get_tree_id(pcommit));
8671 if (err)
8672 goto done;
8675 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8676 got_diff_tree_collect_changed_paths, &paths, 0);
8677 if (err)
8678 goto done;
8680 err = got_worktree_status(worktree, &paths, repo, 0,
8681 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8682 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8684 * At least one changed path in the referenced commit is
8685 * modified in the work tree, that's all we need to know!
8687 err = NULL;
8690 done:
8691 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8692 if (commit)
8693 got_object_commit_close(commit);
8694 if (pcommit)
8695 got_object_commit_close(pcommit);
8696 if (tree)
8697 got_object_tree_close(tree);
8698 if (ptree)
8699 got_object_tree_close(ptree);
8700 return err;
8704 * Remove any "logmsg" reference comprised entirely of paths that have
8705 * been reverted in this work tree. If any path in the logmsg ref changeset
8706 * remains in a changed state in the worktree, do not remove the reference.
8708 static const struct got_error *
8709 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8711 const struct got_error *err;
8712 struct got_reflist_head refs;
8713 struct got_reflist_entry *re;
8714 struct got_commit_object *commit = NULL;
8715 struct got_object_id *commit_id = NULL;
8716 struct wt_commitable_path_arg wcpa;
8717 char *uuidstr = NULL;
8719 TAILQ_INIT(&refs);
8721 err = got_worktree_get_uuid(&uuidstr, worktree);
8722 if (err)
8723 goto done;
8725 err = got_ref_list(&refs, repo, "refs/got/worktree",
8726 got_ref_cmp_by_name, repo);
8727 if (err)
8728 goto done;
8730 TAILQ_FOREACH(re, &refs, entry) {
8731 const char *refname;
8732 int has_changes = 0;
8734 refname = got_ref_get_name(re->ref);
8736 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8737 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8738 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8739 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8740 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8741 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8742 else
8743 continue;
8745 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8746 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8747 else
8748 continue;
8750 err = got_repo_match_object_id(&commit_id, NULL, refname,
8751 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8752 if (err)
8753 goto done;
8755 err = got_object_open_as_commit(&commit, repo, commit_id);
8756 if (err)
8757 goto done;
8759 wcpa.commit_paths = NULL;
8760 wcpa.has_changes = &has_changes;
8762 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8763 worktree, repo);
8764 if (err)
8765 goto done;
8767 if (!has_changes) {
8768 err = got_ref_delete(re->ref, repo);
8769 if (err)
8770 goto done;
8773 got_object_commit_close(commit);
8774 commit = NULL;
8775 free(commit_id);
8776 commit_id = NULL;
8779 done:
8780 free(uuidstr);
8781 free(commit_id);
8782 got_ref_list_free(&refs);
8783 if (commit)
8784 got_object_commit_close(commit);
8785 return err;
8788 static const struct got_error *
8789 cmd_revert(int argc, char *argv[])
8791 const struct got_error *error = NULL;
8792 struct got_worktree *worktree = NULL;
8793 struct got_repository *repo = NULL;
8794 char *cwd = NULL, *path = NULL;
8795 struct got_pathlist_head paths;
8796 struct got_pathlist_entry *pe;
8797 int ch, can_recurse = 0, pflag = 0;
8798 FILE *patch_script_file = NULL;
8799 const char *patch_script_path = NULL;
8800 struct choose_patch_arg cpa;
8801 int *pack_fds = NULL;
8803 TAILQ_INIT(&paths);
8805 #ifndef PROFILE
8806 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8807 "unveil", NULL) == -1)
8808 err(1, "pledge");
8809 #endif
8811 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8812 switch (ch) {
8813 case 'F':
8814 patch_script_path = optarg;
8815 break;
8816 case 'p':
8817 pflag = 1;
8818 break;
8819 case 'R':
8820 can_recurse = 1;
8821 break;
8822 default:
8823 usage_revert();
8824 /* NOTREACHED */
8828 argc -= optind;
8829 argv += optind;
8831 if (argc < 1)
8832 usage_revert();
8833 if (patch_script_path && !pflag)
8834 errx(1, "-F option can only be used together with -p option");
8836 cwd = getcwd(NULL, 0);
8837 if (cwd == NULL) {
8838 error = got_error_from_errno("getcwd");
8839 goto done;
8842 error = got_repo_pack_fds_open(&pack_fds);
8843 if (error != NULL)
8844 goto done;
8846 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8847 if (error) {
8848 if (error->code == GOT_ERR_NOT_WORKTREE)
8849 error = wrap_not_worktree_error(error, "revert", cwd);
8850 goto done;
8853 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8854 NULL, pack_fds);
8855 if (error != NULL)
8856 goto done;
8858 if (patch_script_path) {
8859 patch_script_file = fopen(patch_script_path, "re");
8860 if (patch_script_file == NULL) {
8861 error = got_error_from_errno2("fopen",
8862 patch_script_path);
8863 goto done;
8868 * XXX "c" perm needed on repo dir to delete merge references.
8870 error = apply_unveil(got_repo_get_path(repo), 0,
8871 got_worktree_get_root_path(worktree));
8872 if (error)
8873 goto done;
8875 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8876 if (error)
8877 goto done;
8879 if (!can_recurse) {
8880 char *ondisk_path;
8881 struct stat sb;
8882 TAILQ_FOREACH(pe, &paths, entry) {
8883 if (asprintf(&ondisk_path, "%s/%s",
8884 got_worktree_get_root_path(worktree),
8885 pe->path) == -1) {
8886 error = got_error_from_errno("asprintf");
8887 goto done;
8889 if (lstat(ondisk_path, &sb) == -1) {
8890 if (errno == ENOENT) {
8891 free(ondisk_path);
8892 continue;
8894 error = got_error_from_errno2("lstat",
8895 ondisk_path);
8896 free(ondisk_path);
8897 goto done;
8899 free(ondisk_path);
8900 if (S_ISDIR(sb.st_mode)) {
8901 error = got_error_msg(GOT_ERR_BAD_PATH,
8902 "reverting directories requires -R option");
8903 goto done;
8908 cpa.patch_script_file = patch_script_file;
8909 cpa.action = "revert";
8910 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8911 pflag ? choose_patch : NULL, &cpa, repo);
8913 error = rm_logmsg_ref(worktree, repo);
8914 done:
8915 if (patch_script_file && fclose(patch_script_file) == EOF &&
8916 error == NULL)
8917 error = got_error_from_errno2("fclose", patch_script_path);
8918 if (repo) {
8919 const struct got_error *close_err = got_repo_close(repo);
8920 if (error == NULL)
8921 error = close_err;
8923 if (worktree)
8924 got_worktree_close(worktree);
8925 if (pack_fds) {
8926 const struct got_error *pack_err =
8927 got_repo_pack_fds_close(pack_fds);
8928 if (error == NULL)
8929 error = pack_err;
8931 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8932 free(path);
8933 free(cwd);
8934 return error;
8937 __dead static void
8938 usage_commit(void)
8940 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8941 "[-m message] [path ...]\n", getprogname());
8942 exit(1);
8945 struct collect_commit_logmsg_arg {
8946 const char *cmdline_log;
8947 const char *prepared_log;
8948 const char *merged_log;
8949 int non_interactive;
8950 const char *editor;
8951 const char *worktree_path;
8952 const char *branch_name;
8953 const char *repo_path;
8954 char *logmsg_path;
8958 static const struct got_error *
8959 read_prepared_logmsg(char **logmsg, const char *path)
8961 const struct got_error *err = NULL;
8962 FILE *f = NULL;
8963 struct stat sb;
8964 size_t r;
8966 *logmsg = NULL;
8967 memset(&sb, 0, sizeof(sb));
8969 f = fopen(path, "re");
8970 if (f == NULL)
8971 return got_error_from_errno2("fopen", path);
8973 if (fstat(fileno(f), &sb) == -1) {
8974 err = got_error_from_errno2("fstat", path);
8975 goto done;
8977 if (sb.st_size == 0) {
8978 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8979 goto done;
8982 *logmsg = malloc(sb.st_size + 1);
8983 if (*logmsg == NULL) {
8984 err = got_error_from_errno("malloc");
8985 goto done;
8988 r = fread(*logmsg, 1, sb.st_size, f);
8989 if (r != sb.st_size) {
8990 if (ferror(f))
8991 err = got_error_from_errno2("fread", path);
8992 else
8993 err = got_error(GOT_ERR_IO);
8994 goto done;
8996 (*logmsg)[sb.st_size] = '\0';
8997 done:
8998 if (fclose(f) == EOF && err == NULL)
8999 err = got_error_from_errno2("fclose", path);
9000 if (err) {
9001 free(*logmsg);
9002 *logmsg = NULL;
9004 return err;
9007 static const struct got_error *
9008 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9009 const char *diff_path, char **logmsg, void *arg)
9011 char *initial_content = NULL;
9012 struct got_pathlist_entry *pe;
9013 const struct got_error *err = NULL;
9014 char *template = NULL;
9015 char *prepared_msg = NULL, *merged_msg = NULL;
9016 struct collect_commit_logmsg_arg *a = arg;
9017 int initial_content_len;
9018 int fd = -1;
9019 size_t len;
9021 /* if a message was specified on the command line, just use it */
9022 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9023 len = strlen(a->cmdline_log) + 1;
9024 *logmsg = malloc(len + 1);
9025 if (*logmsg == NULL)
9026 return got_error_from_errno("malloc");
9027 strlcpy(*logmsg, a->cmdline_log, len);
9028 return NULL;
9029 } else if (a->prepared_log != NULL && a->non_interactive)
9030 return read_prepared_logmsg(logmsg, a->prepared_log);
9032 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9033 return got_error_from_errno("asprintf");
9035 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9036 if (err)
9037 goto done;
9039 if (a->prepared_log) {
9040 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9041 if (err)
9042 goto done;
9043 } else if (a->merged_log) {
9044 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9045 if (err)
9046 goto done;
9049 initial_content_len = asprintf(&initial_content,
9050 "%s%s\n# changes to be committed on branch %s:\n",
9051 prepared_msg ? prepared_msg : "",
9052 merged_msg ? merged_msg : "", a->branch_name);
9053 if (initial_content_len == -1) {
9054 err = got_error_from_errno("asprintf");
9055 goto done;
9058 if (write(fd, initial_content, initial_content_len) == -1) {
9059 err = got_error_from_errno2("write", a->logmsg_path);
9060 goto done;
9063 TAILQ_FOREACH(pe, commitable_paths, entry) {
9064 struct got_commitable *ct = pe->data;
9065 dprintf(fd, "# %c %s\n",
9066 got_commitable_get_status(ct),
9067 got_commitable_get_path(ct));
9070 if (diff_path) {
9071 dprintf(fd, "# detailed changes can be viewed in %s\n",
9072 diff_path);
9075 if (close(fd) == -1) {
9076 err = got_error_from_errno2("close", a->logmsg_path);
9077 goto done;
9079 fd = -1;
9081 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9082 initial_content_len, a->prepared_log ? 0 : 1);
9083 done:
9084 free(initial_content);
9085 free(template);
9086 free(prepared_msg);
9087 free(merged_msg);
9089 if (fd != -1 && close(fd) == -1 && err == NULL)
9090 err = got_error_from_errno2("close", a->logmsg_path);
9092 /* Editor is done; we can now apply unveil(2) */
9093 if (err == NULL)
9094 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9095 if (err) {
9096 free(*logmsg);
9097 *logmsg = NULL;
9099 return err;
9102 static const struct got_error *
9103 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9104 const char *type, int has_content)
9106 const struct got_error *err = NULL;
9107 char *logmsg = NULL;
9109 err = got_object_commit_get_logmsg(&logmsg, commit);
9110 if (err)
9111 return err;
9113 if (fprintf(f, "%s# log message of %s commit %s:%s",
9114 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9115 err = got_ferror(f, GOT_ERR_IO);
9117 free(logmsg);
9118 return err;
9122 * Lookup "logmsg" references of backed-out and cherrypicked commits
9123 * belonging to the current work tree. If found, and the worktree has
9124 * at least one modified file that was changed in the referenced commit,
9125 * add its log message to a new temporary file at *logmsg_path.
9126 * Add all refs found to matched_refs to be scheduled for removal on
9127 * successful commit.
9129 static const struct got_error *
9130 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9131 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9132 struct got_repository *repo)
9134 const struct got_error *err;
9135 struct got_commit_object *commit = NULL;
9136 struct got_object_id *id = NULL;
9137 struct got_reflist_head refs;
9138 struct got_reflist_entry *re, *re_match;
9139 FILE *f = NULL;
9140 char *uuidstr = NULL;
9141 int added_logmsg = 0;
9143 TAILQ_INIT(&refs);
9145 *logmsg_path = NULL;
9147 err = got_worktree_get_uuid(&uuidstr, worktree);
9148 if (err)
9149 goto done;
9151 err = got_ref_list(&refs, repo, "refs/got/worktree",
9152 got_ref_cmp_by_name, repo);
9153 if (err)
9154 goto done;
9156 TAILQ_FOREACH(re, &refs, entry) {
9157 const char *refname, *type;
9158 struct wt_commitable_path_arg wcpa;
9159 int add_logmsg = 0;
9161 refname = got_ref_get_name(re->ref);
9163 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9164 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9165 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9166 type = "cherrypicked";
9167 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9168 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9169 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9170 type = "backed-out";
9171 } else
9172 continue;
9174 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9175 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9176 else
9177 continue;
9179 err = got_repo_match_object_id(&id, NULL, refname,
9180 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9181 if (err)
9182 goto done;
9184 err = got_object_open_as_commit(&commit, repo, id);
9185 if (err)
9186 goto done;
9188 wcpa.commit_paths = paths;
9189 wcpa.has_changes = &add_logmsg;
9191 err = commit_path_changed_in_worktree(&wcpa, id,
9192 worktree, repo);
9193 if (err)
9194 goto done;
9196 if (add_logmsg) {
9197 if (f == NULL) {
9198 err = got_opentemp_named(logmsg_path, &f,
9199 "got-commit-logmsg", "");
9200 if (err)
9201 goto done;
9203 err = cat_logmsg(f, commit, refname, type,
9204 added_logmsg);
9205 if (err)
9206 goto done;
9207 if (!added_logmsg)
9208 ++added_logmsg;
9210 err = got_reflist_entry_dup(&re_match, re);
9211 if (err)
9212 goto done;
9213 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9216 got_object_commit_close(commit);
9217 commit = NULL;
9218 free(id);
9219 id = NULL;
9222 done:
9223 free(id);
9224 free(uuidstr);
9225 got_ref_list_free(&refs);
9226 if (commit)
9227 got_object_commit_close(commit);
9228 if (f && fclose(f) == EOF && err == NULL)
9229 err = got_error_from_errno("fclose");
9230 if (!added_logmsg) {
9231 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9232 err = got_error_from_errno2("unlink", *logmsg_path);
9233 *logmsg_path = NULL;
9235 return err;
9238 static const struct got_error *
9239 cmd_commit(int argc, char *argv[])
9241 const struct got_error *error = NULL;
9242 struct got_worktree *worktree = NULL;
9243 struct got_repository *repo = NULL;
9244 char *cwd = NULL, *id_str = NULL;
9245 struct got_object_id *id = NULL;
9246 const char *logmsg = NULL;
9247 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9248 struct collect_commit_logmsg_arg cl_arg;
9249 const char *author = NULL;
9250 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9251 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9252 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9253 int show_diff = 1, commit_conflicts = 0;
9254 struct got_pathlist_head paths;
9255 struct got_reflist_head refs;
9256 struct got_reflist_entry *re;
9257 int *pack_fds = NULL;
9259 TAILQ_INIT(&refs);
9260 TAILQ_INIT(&paths);
9261 cl_arg.logmsg_path = NULL;
9263 #ifndef PROFILE
9264 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9265 "unveil", NULL) == -1)
9266 err(1, "pledge");
9267 #endif
9269 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9270 switch (ch) {
9271 case 'A':
9272 author = optarg;
9273 error = valid_author(author);
9274 if (error)
9275 return error;
9276 break;
9277 case 'C':
9278 commit_conflicts = 1;
9279 break;
9280 case 'F':
9281 if (logmsg != NULL)
9282 option_conflict('F', 'm');
9283 prepared_logmsg = realpath(optarg, NULL);
9284 if (prepared_logmsg == NULL)
9285 return got_error_from_errno2("realpath",
9286 optarg);
9287 break;
9288 case 'm':
9289 if (prepared_logmsg)
9290 option_conflict('m', 'F');
9291 logmsg = optarg;
9292 break;
9293 case 'N':
9294 non_interactive = 1;
9295 break;
9296 case 'n':
9297 show_diff = 0;
9298 break;
9299 case 'S':
9300 allow_bad_symlinks = 1;
9301 break;
9302 default:
9303 usage_commit();
9304 /* NOTREACHED */
9308 argc -= optind;
9309 argv += optind;
9311 cwd = getcwd(NULL, 0);
9312 if (cwd == NULL) {
9313 error = got_error_from_errno("getcwd");
9314 goto done;
9317 error = got_repo_pack_fds_open(&pack_fds);
9318 if (error != NULL)
9319 goto done;
9321 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9322 if (error) {
9323 if (error->code == GOT_ERR_NOT_WORKTREE)
9324 error = wrap_not_worktree_error(error, "commit", cwd);
9325 goto done;
9328 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9329 if (error)
9330 goto done;
9331 if (rebase_in_progress) {
9332 error = got_error(GOT_ERR_REBASING);
9333 goto done;
9336 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9337 worktree);
9338 if (error)
9339 goto done;
9341 error = get_gitconfig_path(&gitconfig_path);
9342 if (error)
9343 goto done;
9344 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9345 gitconfig_path, pack_fds);
9346 if (error != NULL)
9347 goto done;
9349 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9350 if (error)
9351 goto done;
9352 if (merge_in_progress) {
9353 error = got_error(GOT_ERR_MERGE_BUSY);
9354 goto done;
9357 error = get_author(&committer, repo, worktree);
9358 if (error)
9359 goto done;
9361 if (author == NULL)
9362 author = committer;
9365 * unveil(2) traverses exec(2); if an editor is used we have
9366 * to apply unveil after the log message has been written.
9368 if (logmsg == NULL || strlen(logmsg) == 0)
9369 error = get_editor(&editor);
9370 else
9371 error = apply_unveil(got_repo_get_path(repo), 0,
9372 got_worktree_get_root_path(worktree));
9373 if (error)
9374 goto done;
9376 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9377 if (error)
9378 goto done;
9380 if (prepared_logmsg == NULL) {
9381 error = lookup_logmsg_ref(&merged_logmsg,
9382 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9383 if (error)
9384 goto done;
9387 cl_arg.editor = editor;
9388 cl_arg.cmdline_log = logmsg;
9389 cl_arg.prepared_log = prepared_logmsg;
9390 cl_arg.merged_log = merged_logmsg;
9391 cl_arg.non_interactive = non_interactive;
9392 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9393 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9394 if (!histedit_in_progress) {
9395 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9396 error = got_error(GOT_ERR_COMMIT_BRANCH);
9397 goto done;
9399 cl_arg.branch_name += 11;
9401 cl_arg.repo_path = got_repo_get_path(repo);
9402 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9403 allow_bad_symlinks, show_diff, commit_conflicts,
9404 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9405 if (error) {
9406 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9407 cl_arg.logmsg_path != NULL)
9408 preserve_logmsg = 1;
9409 goto done;
9412 error = got_object_id_str(&id_str, id);
9413 if (error)
9414 goto done;
9415 printf("Created commit %s\n", id_str);
9417 TAILQ_FOREACH(re, &refs, entry) {
9418 error = got_ref_delete(re->ref, repo);
9419 if (error)
9420 goto done;
9423 done:
9424 if (preserve_logmsg) {
9425 fprintf(stderr, "%s: log message preserved in %s\n",
9426 getprogname(), cl_arg.logmsg_path);
9427 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9428 error == NULL)
9429 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9430 free(cl_arg.logmsg_path);
9431 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9432 error = got_error_from_errno2("unlink", merged_logmsg);
9433 free(merged_logmsg);
9434 if (repo) {
9435 const struct got_error *close_err = got_repo_close(repo);
9436 if (error == NULL)
9437 error = close_err;
9439 if (worktree)
9440 got_worktree_close(worktree);
9441 if (pack_fds) {
9442 const struct got_error *pack_err =
9443 got_repo_pack_fds_close(pack_fds);
9444 if (error == NULL)
9445 error = pack_err;
9447 got_ref_list_free(&refs);
9448 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9449 free(cwd);
9450 free(id_str);
9451 free(gitconfig_path);
9452 free(editor);
9453 free(committer);
9454 free(prepared_logmsg);
9455 return error;
9458 __dead static void
9459 usage_send(void)
9461 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9462 "[-r repository-path] [-t tag] [remote-repository]\n",
9463 getprogname());
9464 exit(1);
9467 static void
9468 print_load_info(int print_colored, int print_found, int print_trees,
9469 int ncolored, int nfound, int ntrees)
9471 if (print_colored) {
9472 printf("%d commit%s colored", ncolored,
9473 ncolored == 1 ? "" : "s");
9475 if (print_found) {
9476 printf("%s%d object%s found",
9477 ncolored > 0 ? "; " : "",
9478 nfound, nfound == 1 ? "" : "s");
9480 if (print_trees) {
9481 printf("; %d tree%s scanned", ntrees,
9482 ntrees == 1 ? "" : "s");
9486 struct got_send_progress_arg {
9487 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9488 int verbosity;
9489 int last_ncolored;
9490 int last_nfound;
9491 int last_ntrees;
9492 int loading_done;
9493 int last_ncommits;
9494 int last_nobj_total;
9495 int last_p_deltify;
9496 int last_p_written;
9497 int last_p_sent;
9498 int printed_something;
9499 int sent_something;
9500 struct got_pathlist_head *delete_branches;
9503 static const struct got_error *
9504 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9505 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9506 int nobj_written, off_t bytes_sent, const char *refname,
9507 const char *errmsg, int success)
9509 struct got_send_progress_arg *a = arg;
9510 char scaled_packsize[FMT_SCALED_STRSIZE];
9511 char scaled_sent[FMT_SCALED_STRSIZE];
9512 int p_deltify = 0, p_written = 0, p_sent = 0;
9513 int print_colored = 0, print_found = 0, print_trees = 0;
9514 int print_searching = 0, print_total = 0;
9515 int print_deltify = 0, print_written = 0, print_sent = 0;
9517 if (a->verbosity < 0)
9518 return NULL;
9520 if (refname) {
9521 const char *status = success ? "accepted" : "rejected";
9523 if (success) {
9524 struct got_pathlist_entry *pe;
9525 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9526 const char *branchname = pe->path;
9527 if (got_path_cmp(branchname, refname,
9528 strlen(branchname), strlen(refname)) == 0) {
9529 status = "deleted";
9530 a->sent_something = 1;
9531 break;
9536 if (a->printed_something)
9537 putchar('\n');
9538 printf("Server has %s %s", status, refname);
9539 if (errmsg)
9540 printf(": %s", errmsg);
9541 a->printed_something = 1;
9542 return NULL;
9545 if (a->last_ncolored != ncolored) {
9546 print_colored = 1;
9547 a->last_ncolored = ncolored;
9550 if (a->last_nfound != nfound) {
9551 print_colored = 1;
9552 print_found = 1;
9553 a->last_nfound = nfound;
9556 if (a->last_ntrees != ntrees) {
9557 print_colored = 1;
9558 print_found = 1;
9559 print_trees = 1;
9560 a->last_ntrees = ntrees;
9563 if ((print_colored || print_found || print_trees) &&
9564 !a->loading_done) {
9565 printf("\r");
9566 print_load_info(print_colored, print_found, print_trees,
9567 ncolored, nfound, ntrees);
9568 a->printed_something = 1;
9569 fflush(stdout);
9570 return NULL;
9571 } else if (!a->loading_done) {
9572 printf("\r");
9573 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9574 printf("\n");
9575 a->loading_done = 1;
9578 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9579 return got_error_from_errno("fmt_scaled");
9580 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9581 return got_error_from_errno("fmt_scaled");
9583 if (a->last_ncommits != ncommits) {
9584 print_searching = 1;
9585 a->last_ncommits = ncommits;
9588 if (a->last_nobj_total != nobj_total) {
9589 print_searching = 1;
9590 print_total = 1;
9591 a->last_nobj_total = nobj_total;
9594 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9595 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9596 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9597 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9598 return got_error(GOT_ERR_NO_SPACE);
9601 if (nobj_deltify > 0 || nobj_written > 0) {
9602 if (nobj_deltify > 0) {
9603 p_deltify = (nobj_deltify * 100) / nobj_total;
9604 if (p_deltify != a->last_p_deltify) {
9605 a->last_p_deltify = p_deltify;
9606 print_searching = 1;
9607 print_total = 1;
9608 print_deltify = 1;
9611 if (nobj_written > 0) {
9612 p_written = (nobj_written * 100) / nobj_total;
9613 if (p_written != a->last_p_written) {
9614 a->last_p_written = p_written;
9615 print_searching = 1;
9616 print_total = 1;
9617 print_deltify = 1;
9618 print_written = 1;
9623 if (bytes_sent > 0) {
9624 p_sent = (bytes_sent * 100) / packfile_size;
9625 if (p_sent != a->last_p_sent) {
9626 a->last_p_sent = p_sent;
9627 print_searching = 1;
9628 print_total = 1;
9629 print_deltify = 1;
9630 print_written = 1;
9631 print_sent = 1;
9633 a->sent_something = 1;
9636 if (print_searching || print_total || print_deltify || print_written ||
9637 print_sent)
9638 printf("\r");
9639 if (print_searching)
9640 printf("packing %d reference%s", ncommits,
9641 ncommits == 1 ? "" : "s");
9642 if (print_total)
9643 printf("; %d object%s", nobj_total,
9644 nobj_total == 1 ? "" : "s");
9645 if (print_deltify)
9646 printf("; deltify: %d%%", p_deltify);
9647 if (print_sent)
9648 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9649 scaled_packsize, p_sent);
9650 else if (print_written)
9651 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9652 scaled_packsize, p_written);
9653 if (print_searching || print_total || print_deltify ||
9654 print_written || print_sent) {
9655 a->printed_something = 1;
9656 fflush(stdout);
9658 return NULL;
9661 static const struct got_error *
9662 cmd_send(int argc, char *argv[])
9664 const struct got_error *error = NULL;
9665 char *cwd = NULL, *repo_path = NULL;
9666 const char *remote_name;
9667 char *proto = NULL, *host = NULL, *port = NULL;
9668 char *repo_name = NULL, *server_path = NULL;
9669 const struct got_remote_repo *remotes, *remote = NULL;
9670 int nremotes, nbranches = 0, ndelete_branches = 0;
9671 struct got_repository *repo = NULL;
9672 struct got_worktree *worktree = NULL;
9673 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9674 struct got_pathlist_head branches;
9675 struct got_pathlist_head tags;
9676 struct got_reflist_head all_branches;
9677 struct got_reflist_head all_tags;
9678 struct got_pathlist_head delete_args;
9679 struct got_pathlist_head delete_branches;
9680 struct got_reflist_entry *re;
9681 struct got_pathlist_entry *pe;
9682 int i, ch, sendfd = -1, sendstatus;
9683 pid_t sendpid = -1;
9684 struct got_send_progress_arg spa;
9685 int verbosity = 0, overwrite_refs = 0;
9686 int send_all_branches = 0, send_all_tags = 0;
9687 struct got_reference *ref = NULL;
9688 int *pack_fds = NULL;
9690 TAILQ_INIT(&branches);
9691 TAILQ_INIT(&tags);
9692 TAILQ_INIT(&all_branches);
9693 TAILQ_INIT(&all_tags);
9694 TAILQ_INIT(&delete_args);
9695 TAILQ_INIT(&delete_branches);
9697 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9698 switch (ch) {
9699 case 'a':
9700 send_all_branches = 1;
9701 break;
9702 case 'b':
9703 error = got_pathlist_append(&branches, optarg, NULL);
9704 if (error)
9705 return error;
9706 nbranches++;
9707 break;
9708 case 'd':
9709 error = got_pathlist_append(&delete_args, optarg, NULL);
9710 if (error)
9711 return error;
9712 break;
9713 case 'f':
9714 overwrite_refs = 1;
9715 break;
9716 case 'q':
9717 verbosity = -1;
9718 break;
9719 case 'r':
9720 repo_path = realpath(optarg, NULL);
9721 if (repo_path == NULL)
9722 return got_error_from_errno2("realpath",
9723 optarg);
9724 got_path_strip_trailing_slashes(repo_path);
9725 break;
9726 case 'T':
9727 send_all_tags = 1;
9728 break;
9729 case 't':
9730 error = got_pathlist_append(&tags, optarg, NULL);
9731 if (error)
9732 return error;
9733 break;
9734 case 'v':
9735 if (verbosity < 0)
9736 verbosity = 0;
9737 else if (verbosity < 3)
9738 verbosity++;
9739 break;
9740 default:
9741 usage_send();
9742 /* NOTREACHED */
9745 argc -= optind;
9746 argv += optind;
9748 if (send_all_branches && !TAILQ_EMPTY(&branches))
9749 option_conflict('a', 'b');
9750 if (send_all_tags && !TAILQ_EMPTY(&tags))
9751 option_conflict('T', 't');
9754 if (argc == 0)
9755 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9756 else if (argc == 1)
9757 remote_name = argv[0];
9758 else
9759 usage_send();
9761 cwd = getcwd(NULL, 0);
9762 if (cwd == NULL) {
9763 error = got_error_from_errno("getcwd");
9764 goto done;
9767 error = got_repo_pack_fds_open(&pack_fds);
9768 if (error != NULL)
9769 goto done;
9771 if (repo_path == NULL) {
9772 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9773 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9774 goto done;
9775 else
9776 error = NULL;
9777 if (worktree) {
9778 repo_path =
9779 strdup(got_worktree_get_repo_path(worktree));
9780 if (repo_path == NULL)
9781 error = got_error_from_errno("strdup");
9782 if (error)
9783 goto done;
9784 } else {
9785 repo_path = strdup(cwd);
9786 if (repo_path == NULL) {
9787 error = got_error_from_errno("strdup");
9788 goto done;
9793 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9794 if (error)
9795 goto done;
9797 if (worktree) {
9798 worktree_conf = got_worktree_get_gotconfig(worktree);
9799 if (worktree_conf) {
9800 got_gotconfig_get_remotes(&nremotes, &remotes,
9801 worktree_conf);
9802 for (i = 0; i < nremotes; i++) {
9803 if (strcmp(remotes[i].name, remote_name) == 0) {
9804 remote = &remotes[i];
9805 break;
9810 if (remote == NULL) {
9811 repo_conf = got_repo_get_gotconfig(repo);
9812 if (repo_conf) {
9813 got_gotconfig_get_remotes(&nremotes, &remotes,
9814 repo_conf);
9815 for (i = 0; i < nremotes; i++) {
9816 if (strcmp(remotes[i].name, remote_name) == 0) {
9817 remote = &remotes[i];
9818 break;
9823 if (remote == NULL) {
9824 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9825 for (i = 0; i < nremotes; i++) {
9826 if (strcmp(remotes[i].name, remote_name) == 0) {
9827 remote = &remotes[i];
9828 break;
9832 if (remote == NULL) {
9833 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9834 goto done;
9837 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9838 &repo_name, remote->send_url);
9839 if (error)
9840 goto done;
9842 if (strcmp(proto, "git") == 0) {
9843 #ifndef PROFILE
9844 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9845 "sendfd dns inet unveil", NULL) == -1)
9846 err(1, "pledge");
9847 #endif
9848 } else if (strcmp(proto, "git+ssh") == 0 ||
9849 strcmp(proto, "ssh") == 0) {
9850 #ifndef PROFILE
9851 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9852 "sendfd unveil", NULL) == -1)
9853 err(1, "pledge");
9854 #endif
9855 } else if (strcmp(proto, "http") == 0 ||
9856 strcmp(proto, "git+http") == 0) {
9857 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9858 goto done;
9859 } else {
9860 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9861 goto done;
9864 error = got_dial_apply_unveil(proto);
9865 if (error)
9866 goto done;
9868 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9869 if (error)
9870 goto done;
9872 if (send_all_branches) {
9873 error = got_ref_list(&all_branches, repo, "refs/heads",
9874 got_ref_cmp_by_name, NULL);
9875 if (error)
9876 goto done;
9877 TAILQ_FOREACH(re, &all_branches, entry) {
9878 const char *branchname = got_ref_get_name(re->ref);
9879 error = got_pathlist_append(&branches,
9880 branchname, NULL);
9881 if (error)
9882 goto done;
9883 nbranches++;
9885 } else if (nbranches == 0) {
9886 for (i = 0; i < remote->nsend_branches; i++) {
9887 error = got_pathlist_append(&branches,
9888 remote->send_branches[i], NULL);
9889 if (error)
9890 goto done;
9894 if (send_all_tags) {
9895 error = got_ref_list(&all_tags, repo, "refs/tags",
9896 got_ref_cmp_by_name, NULL);
9897 if (error)
9898 goto done;
9899 TAILQ_FOREACH(re, &all_tags, entry) {
9900 const char *tagname = got_ref_get_name(re->ref);
9901 error = got_pathlist_append(&tags,
9902 tagname, NULL);
9903 if (error)
9904 goto done;
9909 * To prevent accidents only branches in refs/heads/ can be deleted
9910 * with 'got send -d'.
9911 * Deleting anything else requires local repository access or Git.
9913 TAILQ_FOREACH(pe, &delete_args, entry) {
9914 const char *branchname = pe->path;
9915 char *s;
9916 struct got_pathlist_entry *new;
9917 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9918 s = strdup(branchname);
9919 if (s == NULL) {
9920 error = got_error_from_errno("strdup");
9921 goto done;
9923 } else {
9924 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9925 error = got_error_from_errno("asprintf");
9926 goto done;
9929 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9930 if (error || new == NULL /* duplicate */)
9931 free(s);
9932 if (error)
9933 goto done;
9934 ndelete_branches++;
9937 if (nbranches == 0 && ndelete_branches == 0) {
9938 struct got_reference *head_ref;
9939 if (worktree)
9940 error = got_ref_open(&head_ref, repo,
9941 got_worktree_get_head_ref_name(worktree), 0);
9942 else
9943 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9944 if (error)
9945 goto done;
9946 if (got_ref_is_symbolic(head_ref)) {
9947 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9948 got_ref_close(head_ref);
9949 if (error)
9950 goto done;
9951 } else
9952 ref = head_ref;
9953 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9954 NULL);
9955 if (error)
9956 goto done;
9957 nbranches++;
9960 if (verbosity >= 0) {
9961 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9962 remote->name, proto, host,
9963 port ? ":" : "", port ? port : "",
9964 *server_path == '/' ? "" : "/", server_path);
9967 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9968 server_path, verbosity);
9969 if (error)
9970 goto done;
9972 memset(&spa, 0, sizeof(spa));
9973 spa.last_scaled_packsize[0] = '\0';
9974 spa.last_p_deltify = -1;
9975 spa.last_p_written = -1;
9976 spa.verbosity = verbosity;
9977 spa.delete_branches = &delete_branches;
9978 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9979 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9980 check_cancelled, NULL);
9981 if (spa.printed_something)
9982 putchar('\n');
9983 if (error)
9984 goto done;
9985 if (!spa.sent_something && verbosity >= 0)
9986 printf("Already up-to-date\n");
9987 done:
9988 if (sendpid > 0) {
9989 if (kill(sendpid, SIGTERM) == -1)
9990 error = got_error_from_errno("kill");
9991 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9992 error = got_error_from_errno("waitpid");
9994 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9995 error = got_error_from_errno("close");
9996 if (repo) {
9997 const struct got_error *close_err = got_repo_close(repo);
9998 if (error == NULL)
9999 error = close_err;
10001 if (worktree)
10002 got_worktree_close(worktree);
10003 if (pack_fds) {
10004 const struct got_error *pack_err =
10005 got_repo_pack_fds_close(pack_fds);
10006 if (error == NULL)
10007 error = pack_err;
10009 if (ref)
10010 got_ref_close(ref);
10011 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10012 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10013 got_ref_list_free(&all_branches);
10014 got_ref_list_free(&all_tags);
10015 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10016 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10017 free(cwd);
10018 free(repo_path);
10019 free(proto);
10020 free(host);
10021 free(port);
10022 free(server_path);
10023 free(repo_name);
10024 return error;
10028 * Print and if delete is set delete all ref_prefix references.
10029 * If wanted_ref is not NULL, only print or delete this reference.
10031 static const struct got_error *
10032 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10033 const char *wanted_ref, int delete, struct got_worktree *worktree,
10034 struct got_repository *repo)
10036 const struct got_error *err;
10037 struct got_pathlist_head paths;
10038 struct got_reflist_head refs;
10039 struct got_reflist_entry *re;
10040 struct got_reflist_object_id_map *refs_idmap = NULL;
10041 struct got_commit_object *commit = NULL;
10042 struct got_object_id *id = NULL;
10043 const char *header_prefix;
10044 char *uuidstr = NULL;
10045 int found = 0;
10047 TAILQ_INIT(&refs);
10048 TAILQ_INIT(&paths);
10050 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10051 if (err)
10052 goto done;
10054 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10055 if (err)
10056 goto done;
10058 if (worktree != NULL) {
10059 err = got_worktree_get_uuid(&uuidstr, worktree);
10060 if (err)
10061 goto done;
10064 if (wanted_ref) {
10065 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10066 wanted_ref += 11;
10069 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10070 header_prefix = "backout";
10071 else
10072 header_prefix = "cherrypick";
10074 TAILQ_FOREACH(re, &refs, entry) {
10075 const char *refname, *wt;
10077 refname = got_ref_get_name(re->ref);
10079 err = check_cancelled(NULL);
10080 if (err)
10081 goto done;
10083 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10084 refname += prefix_len + 1; /* skip '-' delimiter */
10085 else
10086 continue;
10088 wt = refname;
10090 if (worktree == NULL || strncmp(refname, uuidstr,
10091 GOT_WORKTREE_UUID_STRLEN) == 0)
10092 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10093 else
10094 continue;
10096 err = got_repo_match_object_id(&id, NULL, refname,
10097 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10098 if (err)
10099 goto done;
10101 err = got_object_open_as_commit(&commit, repo, id);
10102 if (err)
10103 goto done;
10105 if (wanted_ref)
10106 found = strncmp(wanted_ref, refname,
10107 strlen(wanted_ref)) == 0;
10108 if (wanted_ref && !found) {
10109 struct got_reflist_head *ci_refs;
10111 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10112 id);
10114 if (ci_refs) {
10115 char *refs_str = NULL;
10116 char const *r = NULL;
10118 err = build_refs_str(&refs_str, ci_refs, id,
10119 repo, 1);
10120 if (err)
10121 goto done;
10123 r = refs_str;
10124 while (r) {
10125 if (strncmp(r, wanted_ref,
10126 strlen(wanted_ref)) == 0) {
10127 found = 1;
10128 break;
10130 r = strchr(r, ' ');
10131 if (r)
10132 ++r;
10134 free(refs_str);
10138 if (wanted_ref == NULL || found) {
10139 if (delete) {
10140 err = got_ref_delete(re->ref, repo);
10141 if (err)
10142 goto done;
10143 printf("Deleted: ");
10144 err = print_commit_oneline(commit, id, repo,
10145 refs_idmap);
10146 } else {
10148 * Print paths modified by commit to help
10149 * associate commits with worktree changes.
10151 err = get_changed_paths(&paths, commit,
10152 repo, NULL);
10153 if (err)
10154 goto done;
10156 err = print_commit(commit, id, repo, NULL,
10157 &paths, NULL, 0, 0, refs_idmap, NULL,
10158 header_prefix);
10159 got_pathlist_free(&paths,
10160 GOT_PATHLIST_FREE_ALL);
10162 if (worktree == NULL)
10163 printf("work tree: %.*s\n\n",
10164 GOT_WORKTREE_UUID_STRLEN, wt);
10166 if (err || found)
10167 goto done;
10170 got_object_commit_close(commit);
10171 commit = NULL;
10172 free(id);
10173 id = NULL;
10176 if (wanted_ref != NULL && !found)
10177 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10179 done:
10180 free(id);
10181 free(uuidstr);
10182 got_ref_list_free(&refs);
10183 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10184 if (refs_idmap)
10185 got_reflist_object_id_map_free(refs_idmap);
10186 if (commit)
10187 got_object_commit_close(commit);
10188 return err;
10192 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10193 * identified by id for log messages to prepopulate the editor on commit.
10195 static const struct got_error *
10196 logmsg_ref(struct got_object_id *id, const char *prefix,
10197 struct got_worktree *worktree, struct got_repository *repo)
10199 const struct got_error *err = NULL;
10200 char *idstr, *ref = NULL, *refname = NULL;
10201 int histedit_in_progress;
10202 int rebase_in_progress, merge_in_progress;
10205 * Silenty refuse to create merge reference if any histedit, merge,
10206 * or rebase operation is in progress.
10208 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10209 worktree);
10210 if (err)
10211 return err;
10212 if (histedit_in_progress)
10213 return NULL;
10215 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10216 if (err)
10217 return err;
10218 if (rebase_in_progress)
10219 return NULL;
10221 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10222 repo);
10223 if (err)
10224 return err;
10225 if (merge_in_progress)
10226 return NULL;
10228 err = got_object_id_str(&idstr, id);
10229 if (err)
10230 return err;
10232 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10233 if (err)
10234 goto done;
10236 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10237 err = got_error_from_errno("asprintf");
10238 goto done;
10241 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10242 -1, repo);
10243 done:
10244 free(ref);
10245 free(idstr);
10246 free(refname);
10247 return err;
10250 __dead static void
10251 usage_cherrypick(void)
10253 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10254 getprogname());
10255 exit(1);
10258 static const struct got_error *
10259 cmd_cherrypick(int argc, char *argv[])
10261 const struct got_error *error = NULL;
10262 struct got_worktree *worktree = NULL;
10263 struct got_repository *repo = NULL;
10264 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10265 struct got_object_id *commit_id = NULL;
10266 struct got_commit_object *commit = NULL;
10267 struct got_object_qid *pid;
10268 int ch, list_refs = 0, remove_refs = 0;
10269 struct got_update_progress_arg upa;
10270 int *pack_fds = NULL;
10272 #ifndef PROFILE
10273 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10274 "unveil", NULL) == -1)
10275 err(1, "pledge");
10276 #endif
10278 while ((ch = getopt(argc, argv, "lX")) != -1) {
10279 switch (ch) {
10280 case 'l':
10281 list_refs = 1;
10282 break;
10283 case 'X':
10284 remove_refs = 1;
10285 break;
10286 default:
10287 usage_cherrypick();
10288 /* NOTREACHED */
10292 argc -= optind;
10293 argv += optind;
10295 if (list_refs || remove_refs) {
10296 if (argc != 0 && argc != 1)
10297 usage_cherrypick();
10298 } else if (argc != 1)
10299 usage_cherrypick();
10300 if (list_refs && remove_refs)
10301 option_conflict('l', 'X');
10303 cwd = getcwd(NULL, 0);
10304 if (cwd == NULL) {
10305 error = got_error_from_errno("getcwd");
10306 goto done;
10309 error = got_repo_pack_fds_open(&pack_fds);
10310 if (error != NULL)
10311 goto done;
10313 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10314 if (error) {
10315 if (list_refs || remove_refs) {
10316 if (error->code != GOT_ERR_NOT_WORKTREE)
10317 goto done;
10318 } else {
10319 if (error->code == GOT_ERR_NOT_WORKTREE)
10320 error = wrap_not_worktree_error(error,
10321 "cherrypick", cwd);
10322 goto done;
10326 error = got_repo_open(&repo,
10327 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10328 NULL, pack_fds);
10329 if (error != NULL)
10330 goto done;
10332 error = apply_unveil(got_repo_get_path(repo), 0,
10333 worktree ? got_worktree_get_root_path(worktree) : NULL);
10334 if (error)
10335 goto done;
10337 if (list_refs || remove_refs) {
10338 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10339 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10340 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10341 goto done;
10344 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10345 if (error != NULL)
10346 goto done;
10348 error = got_repo_match_object_id(&commit_id, NULL,
10349 keyword_idstr != NULL ? keyword_idstr : argv[0],
10350 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10351 if (error)
10352 goto done;
10353 error = got_object_id_str(&commit_id_str, commit_id);
10354 if (error)
10355 goto done;
10357 error = got_object_open_as_commit(&commit, repo, commit_id);
10358 if (error)
10359 goto done;
10360 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10361 memset(&upa, 0, sizeof(upa));
10362 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10363 commit_id, repo, update_progress, &upa, check_cancelled,
10364 NULL);
10365 if (error != NULL)
10366 goto done;
10368 if (upa.did_something) {
10369 error = logmsg_ref(commit_id,
10370 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10371 if (error)
10372 goto done;
10373 printf("Merged commit %s\n", commit_id_str);
10375 print_merge_progress_stats(&upa);
10376 done:
10377 free(cwd);
10378 free(keyword_idstr);
10379 if (commit)
10380 got_object_commit_close(commit);
10381 free(commit_id_str);
10382 if (worktree)
10383 got_worktree_close(worktree);
10384 if (repo) {
10385 const struct got_error *close_err = got_repo_close(repo);
10386 if (error == NULL)
10387 error = close_err;
10389 if (pack_fds) {
10390 const struct got_error *pack_err =
10391 got_repo_pack_fds_close(pack_fds);
10392 if (error == NULL)
10393 error = pack_err;
10396 return error;
10399 __dead static void
10400 usage_backout(void)
10402 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10403 exit(1);
10406 static const struct got_error *
10407 cmd_backout(int argc, char *argv[])
10409 const struct got_error *error = NULL;
10410 struct got_worktree *worktree = NULL;
10411 struct got_repository *repo = NULL;
10412 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10413 struct got_object_id *commit_id = NULL;
10414 struct got_commit_object *commit = NULL;
10415 struct got_object_qid *pid;
10416 int ch, list_refs = 0, remove_refs = 0;
10417 struct got_update_progress_arg upa;
10418 int *pack_fds = NULL;
10420 #ifndef PROFILE
10421 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10422 "unveil", NULL) == -1)
10423 err(1, "pledge");
10424 #endif
10426 while ((ch = getopt(argc, argv, "lX")) != -1) {
10427 switch (ch) {
10428 case 'l':
10429 list_refs = 1;
10430 break;
10431 case 'X':
10432 remove_refs = 1;
10433 break;
10434 default:
10435 usage_backout();
10436 /* NOTREACHED */
10440 argc -= optind;
10441 argv += optind;
10443 if (list_refs || remove_refs) {
10444 if (argc != 0 && argc != 1)
10445 usage_backout();
10446 } else if (argc != 1)
10447 usage_backout();
10448 if (list_refs && remove_refs)
10449 option_conflict('l', 'X');
10451 cwd = getcwd(NULL, 0);
10452 if (cwd == NULL) {
10453 error = got_error_from_errno("getcwd");
10454 goto done;
10457 error = got_repo_pack_fds_open(&pack_fds);
10458 if (error != NULL)
10459 goto done;
10461 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10462 if (error) {
10463 if (list_refs || remove_refs) {
10464 if (error->code != GOT_ERR_NOT_WORKTREE)
10465 goto done;
10466 } else {
10467 if (error->code == GOT_ERR_NOT_WORKTREE)
10468 error = wrap_not_worktree_error(error,
10469 "backout", cwd);
10470 goto done;
10474 error = got_repo_open(&repo,
10475 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10476 NULL, pack_fds);
10477 if (error != NULL)
10478 goto done;
10480 error = apply_unveil(got_repo_get_path(repo), 0,
10481 worktree ? got_worktree_get_root_path(worktree) : NULL);
10482 if (error)
10483 goto done;
10485 if (list_refs || remove_refs) {
10486 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10487 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10488 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10489 goto done;
10492 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10493 if (error != NULL)
10494 goto done;
10496 error = got_repo_match_object_id(&commit_id, NULL,
10497 keyword_idstr != NULL ? keyword_idstr : argv[0],
10498 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10499 if (error)
10500 goto done;
10501 error = got_object_id_str(&commit_id_str, commit_id);
10502 if (error)
10503 goto done;
10505 error = got_object_open_as_commit(&commit, repo, commit_id);
10506 if (error)
10507 goto done;
10508 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10509 if (pid == NULL) {
10510 error = got_error(GOT_ERR_ROOT_COMMIT);
10511 goto done;
10514 memset(&upa, 0, sizeof(upa));
10515 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10516 repo, update_progress, &upa, check_cancelled, NULL);
10517 if (error != NULL)
10518 goto done;
10520 if (upa.did_something) {
10521 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10522 worktree, repo);
10523 if (error)
10524 goto done;
10525 printf("Backed out commit %s\n", commit_id_str);
10527 print_merge_progress_stats(&upa);
10528 done:
10529 free(cwd);
10530 free(keyword_idstr);
10531 if (commit)
10532 got_object_commit_close(commit);
10533 free(commit_id_str);
10534 if (worktree)
10535 got_worktree_close(worktree);
10536 if (repo) {
10537 const struct got_error *close_err = got_repo_close(repo);
10538 if (error == NULL)
10539 error = close_err;
10541 if (pack_fds) {
10542 const struct got_error *pack_err =
10543 got_repo_pack_fds_close(pack_fds);
10544 if (error == NULL)
10545 error = pack_err;
10547 return error;
10550 __dead static void
10551 usage_rebase(void)
10553 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10554 exit(1);
10557 static void
10558 trim_logmsg(char *logmsg, int limit)
10560 char *nl;
10561 size_t len;
10563 len = strlen(logmsg);
10564 if (len > limit)
10565 len = limit;
10566 logmsg[len] = '\0';
10567 nl = strchr(logmsg, '\n');
10568 if (nl)
10569 *nl = '\0';
10572 static const struct got_error *
10573 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10575 const struct got_error *err;
10576 char *logmsg0 = NULL;
10577 const char *s;
10579 err = got_object_commit_get_logmsg(&logmsg0, commit);
10580 if (err)
10581 return err;
10583 s = logmsg0;
10584 while (isspace((unsigned char)s[0]))
10585 s++;
10587 *logmsg = strdup(s);
10588 if (*logmsg == NULL) {
10589 err = got_error_from_errno("strdup");
10590 goto done;
10593 trim_logmsg(*logmsg, limit);
10594 done:
10595 free(logmsg0);
10596 return err;
10599 static const struct got_error *
10600 show_rebase_merge_conflict(struct got_object_id *id,
10601 struct got_repository *repo)
10603 const struct got_error *err;
10604 struct got_commit_object *commit = NULL;
10605 char *id_str = NULL, *logmsg = NULL;
10607 err = got_object_open_as_commit(&commit, repo, id);
10608 if (err)
10609 return err;
10611 err = got_object_id_str(&id_str, id);
10612 if (err)
10613 goto done;
10615 id_str[12] = '\0';
10617 err = get_short_logmsg(&logmsg, 42, commit);
10618 if (err)
10619 goto done;
10621 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10622 done:
10623 free(id_str);
10624 got_object_commit_close(commit);
10625 free(logmsg);
10626 return err;
10629 static const struct got_error *
10630 show_rebase_progress(struct got_commit_object *commit,
10631 struct got_object_id *old_id, struct got_object_id *new_id)
10633 const struct got_error *err;
10634 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10636 err = got_object_id_str(&old_id_str, old_id);
10637 if (err)
10638 goto done;
10640 if (new_id) {
10641 err = got_object_id_str(&new_id_str, new_id);
10642 if (err)
10643 goto done;
10646 old_id_str[12] = '\0';
10647 if (new_id_str)
10648 new_id_str[12] = '\0';
10650 err = get_short_logmsg(&logmsg, 42, commit);
10651 if (err)
10652 goto done;
10654 printf("%s -> %s: %s\n", old_id_str,
10655 new_id_str ? new_id_str : "no-op change", logmsg);
10656 done:
10657 free(old_id_str);
10658 free(new_id_str);
10659 free(logmsg);
10660 return err;
10663 static const struct got_error *
10664 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10665 struct got_reference *branch, struct got_reference *tmp_branch,
10666 struct got_repository *repo, int create_backup)
10668 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10669 return got_worktree_rebase_complete(worktree, fileindex,
10670 tmp_branch, branch, repo, create_backup);
10673 static const struct got_error *
10674 rebase_commit(struct got_pathlist_head *merged_paths,
10675 struct got_worktree *worktree, struct got_fileindex *fileindex,
10676 struct got_reference *tmp_branch, const char *committer,
10677 struct got_object_id *commit_id, int allow_conflict,
10678 struct got_repository *repo)
10680 const struct got_error *error;
10681 struct got_commit_object *commit;
10682 struct got_object_id *new_commit_id;
10684 error = got_object_open_as_commit(&commit, repo, commit_id);
10685 if (error)
10686 return error;
10688 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10689 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10690 allow_conflict, repo);
10691 if (error) {
10692 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10693 goto done;
10694 error = show_rebase_progress(commit, commit_id, NULL);
10695 } else {
10696 error = show_rebase_progress(commit, commit_id, new_commit_id);
10697 free(new_commit_id);
10699 done:
10700 got_object_commit_close(commit);
10701 return error;
10704 struct check_path_prefix_arg {
10705 const char *path_prefix;
10706 size_t len;
10707 int errcode;
10710 static const struct got_error *
10711 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10712 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10713 struct got_object_id *id1, struct got_object_id *id2,
10714 const char *path1, const char *path2,
10715 mode_t mode1, mode_t mode2, struct got_repository *repo)
10717 struct check_path_prefix_arg *a = arg;
10719 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10720 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10721 return got_error(a->errcode);
10723 return NULL;
10726 static const struct got_error *
10727 check_path_prefix(struct got_object_id *parent_id,
10728 struct got_object_id *commit_id, const char *path_prefix,
10729 int errcode, struct got_repository *repo)
10731 const struct got_error *err;
10732 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10733 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10734 struct check_path_prefix_arg cpp_arg;
10736 if (got_path_is_root_dir(path_prefix))
10737 return NULL;
10739 err = got_object_open_as_commit(&commit, repo, commit_id);
10740 if (err)
10741 goto done;
10743 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10744 if (err)
10745 goto done;
10747 err = got_object_open_as_tree(&tree1, repo,
10748 got_object_commit_get_tree_id(parent_commit));
10749 if (err)
10750 goto done;
10752 err = got_object_open_as_tree(&tree2, repo,
10753 got_object_commit_get_tree_id(commit));
10754 if (err)
10755 goto done;
10757 cpp_arg.path_prefix = path_prefix;
10758 while (cpp_arg.path_prefix[0] == '/')
10759 cpp_arg.path_prefix++;
10760 cpp_arg.len = strlen(cpp_arg.path_prefix);
10761 cpp_arg.errcode = errcode;
10762 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10763 check_path_prefix_in_diff, &cpp_arg, 0);
10764 done:
10765 if (tree1)
10766 got_object_tree_close(tree1);
10767 if (tree2)
10768 got_object_tree_close(tree2);
10769 if (commit)
10770 got_object_commit_close(commit);
10771 if (parent_commit)
10772 got_object_commit_close(parent_commit);
10773 return err;
10776 static const struct got_error *
10777 collect_commits(struct got_object_id_queue *commits,
10778 struct got_object_id *initial_commit_id,
10779 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10780 const char *path_prefix, int path_prefix_errcode,
10781 struct got_repository *repo)
10783 const struct got_error *err = NULL;
10784 struct got_commit_graph *graph = NULL;
10785 struct got_object_id parent_id, commit_id;
10786 struct got_object_qid *qid;
10788 err = got_commit_graph_open(&graph, "/", 1);
10789 if (err)
10790 return err;
10792 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10793 check_cancelled, NULL);
10794 if (err)
10795 goto done;
10797 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10798 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10799 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10800 check_cancelled, NULL);
10801 if (err) {
10802 if (err->code == GOT_ERR_ITER_COMPLETED) {
10803 err = got_error_msg(GOT_ERR_ANCESTRY,
10804 "ran out of commits to rebase before "
10805 "youngest common ancestor commit has "
10806 "been reached?!?");
10808 goto done;
10809 } else {
10810 err = check_path_prefix(&parent_id, &commit_id,
10811 path_prefix, path_prefix_errcode, repo);
10812 if (err)
10813 goto done;
10815 err = got_object_qid_alloc(&qid, &commit_id);
10816 if (err)
10817 goto done;
10818 STAILQ_INSERT_HEAD(commits, qid, entry);
10820 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10823 done:
10824 got_commit_graph_close(graph);
10825 return err;
10828 static const struct got_error *
10829 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10831 const struct got_error *err = NULL;
10832 time_t committer_time;
10833 struct tm tm;
10834 char datebuf[11]; /* YYYY-MM-DD + NUL */
10835 char *author0 = NULL, *author, *smallerthan;
10836 char *logmsg0 = NULL, *logmsg, *newline;
10838 committer_time = got_object_commit_get_committer_time(commit);
10839 if (gmtime_r(&committer_time, &tm) == NULL)
10840 return got_error_from_errno("gmtime_r");
10841 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10842 return got_error(GOT_ERR_NO_SPACE);
10844 author0 = strdup(got_object_commit_get_author(commit));
10845 if (author0 == NULL)
10846 return got_error_from_errno("strdup");
10847 author = author0;
10848 smallerthan = strchr(author, '<');
10849 if (smallerthan && smallerthan[1] != '\0')
10850 author = smallerthan + 1;
10851 author[strcspn(author, "@>")] = '\0';
10853 err = got_object_commit_get_logmsg(&logmsg0, commit);
10854 if (err)
10855 goto done;
10856 logmsg = logmsg0;
10857 while (*logmsg == '\n')
10858 logmsg++;
10859 newline = strchr(logmsg, '\n');
10860 if (newline)
10861 *newline = '\0';
10863 if (asprintf(brief_str, "%s %s %s",
10864 datebuf, author, logmsg) == -1)
10865 err = got_error_from_errno("asprintf");
10866 done:
10867 free(author0);
10868 free(logmsg0);
10869 return err;
10872 static const struct got_error *
10873 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10874 struct got_repository *repo)
10876 const struct got_error *err;
10877 char *id_str;
10879 err = got_object_id_str(&id_str, id);
10880 if (err)
10881 return err;
10883 err = got_ref_delete(ref, repo);
10884 if (err)
10885 goto done;
10887 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10888 done:
10889 free(id_str);
10890 return err;
10893 static const struct got_error *
10894 print_backup_ref(const char *branch_name, const char *new_id_str,
10895 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10896 struct got_reflist_object_id_map *refs_idmap,
10897 struct got_repository *repo)
10899 const struct got_error *err = NULL;
10900 struct got_reflist_head *refs;
10901 char *refs_str = NULL;
10902 struct got_object_id *new_commit_id = NULL;
10903 struct got_commit_object *new_commit = NULL;
10904 char *new_commit_brief_str = NULL;
10905 struct got_object_id *yca_id = NULL;
10906 struct got_commit_object *yca_commit = NULL;
10907 char *yca_id_str = NULL, *yca_brief_str = NULL;
10908 char *custom_refs_str;
10910 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10911 return got_error_from_errno("asprintf");
10913 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10914 0, 0, refs_idmap, custom_refs_str, NULL);
10915 if (err)
10916 goto done;
10918 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10919 if (err)
10920 goto done;
10922 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10923 if (refs) {
10924 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10925 if (err)
10926 goto done;
10929 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10930 if (err)
10931 goto done;
10933 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10934 if (err)
10935 goto done;
10937 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10938 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10939 if (err)
10940 goto done;
10942 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10943 refs_str ? " (" : "", refs_str ? refs_str : "",
10944 refs_str ? ")" : "", new_commit_brief_str);
10945 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10946 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10947 free(refs_str);
10948 refs_str = NULL;
10950 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10951 if (err)
10952 goto done;
10954 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10955 if (err)
10956 goto done;
10958 err = got_object_id_str(&yca_id_str, yca_id);
10959 if (err)
10960 goto done;
10962 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10963 if (refs) {
10964 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10965 if (err)
10966 goto done;
10968 printf("history forked at %s%s%s%s\n %s\n",
10969 yca_id_str,
10970 refs_str ? " (" : "", refs_str ? refs_str : "",
10971 refs_str ? ")" : "", yca_brief_str);
10973 done:
10974 free(custom_refs_str);
10975 free(new_commit_id);
10976 free(refs_str);
10977 free(yca_id);
10978 free(yca_id_str);
10979 free(yca_brief_str);
10980 if (new_commit)
10981 got_object_commit_close(new_commit);
10982 if (yca_commit)
10983 got_object_commit_close(yca_commit);
10985 return err;
10988 static const struct got_error *
10989 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10990 struct got_repository *repo)
10992 const struct got_error *err;
10993 struct got_reflist_head refs;
10994 struct got_reflist_entry *re;
10995 char *uuidstr = NULL;
10996 static char msg[160];
10998 TAILQ_INIT(&refs);
11000 err = got_worktree_get_uuid(&uuidstr, worktree);
11001 if (err)
11002 goto done;
11004 err = got_ref_list(&refs, repo, "refs/got/worktree",
11005 got_ref_cmp_by_name, repo);
11006 if (err)
11007 goto done;
11009 TAILQ_FOREACH(re, &refs, entry) {
11010 const char *cmd, *refname, *type;
11012 refname = got_ref_get_name(re->ref);
11014 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11015 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11016 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11017 cmd = "cherrypick";
11018 type = "cherrypicked";
11019 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11020 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11021 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11022 cmd = "backout";
11023 type = "backed-out";
11024 } else
11025 continue;
11027 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11028 continue;
11030 snprintf(msg, sizeof(msg),
11031 "work tree has references created by %s commits which "
11032 "must be removed with 'got %s -X' before running the %s "
11033 "command", type, cmd, caller);
11034 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11035 goto done;
11038 done:
11039 free(uuidstr);
11040 got_ref_list_free(&refs);
11041 return err;
11044 static const struct got_error *
11045 process_backup_refs(const char *backup_ref_prefix,
11046 const char *wanted_branch_name,
11047 int delete, struct got_repository *repo)
11049 const struct got_error *err;
11050 struct got_reflist_head refs, backup_refs;
11051 struct got_reflist_entry *re;
11052 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11053 struct got_object_id *old_commit_id = NULL;
11054 char *branch_name = NULL;
11055 struct got_commit_object *old_commit = NULL;
11056 struct got_reflist_object_id_map *refs_idmap = NULL;
11057 int wanted_branch_found = 0;
11059 TAILQ_INIT(&refs);
11060 TAILQ_INIT(&backup_refs);
11062 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11063 if (err)
11064 return err;
11066 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11067 if (err)
11068 goto done;
11070 if (wanted_branch_name) {
11071 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11072 wanted_branch_name += 11;
11075 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11076 got_ref_cmp_by_commit_timestamp_descending, repo);
11077 if (err)
11078 goto done;
11080 TAILQ_FOREACH(re, &backup_refs, entry) {
11081 const char *refname = got_ref_get_name(re->ref);
11082 char *slash;
11084 err = check_cancelled(NULL);
11085 if (err)
11086 break;
11088 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11089 if (err)
11090 break;
11092 err = got_object_open_as_commit(&old_commit, repo,
11093 old_commit_id);
11094 if (err)
11095 break;
11097 if (strncmp(backup_ref_prefix, refname,
11098 backup_ref_prefix_len) == 0)
11099 refname += backup_ref_prefix_len;
11101 while (refname[0] == '/')
11102 refname++;
11104 branch_name = strdup(refname);
11105 if (branch_name == NULL) {
11106 err = got_error_from_errno("strdup");
11107 break;
11109 slash = strrchr(branch_name, '/');
11110 if (slash) {
11111 *slash = '\0';
11112 refname += strlen(branch_name) + 1;
11115 if (wanted_branch_name == NULL ||
11116 strcmp(wanted_branch_name, branch_name) == 0) {
11117 wanted_branch_found = 1;
11118 if (delete) {
11119 err = delete_backup_ref(re->ref,
11120 old_commit_id, repo);
11121 } else {
11122 err = print_backup_ref(branch_name, refname,
11123 old_commit_id, old_commit, refs_idmap,
11124 repo);
11126 if (err)
11127 break;
11130 free(old_commit_id);
11131 old_commit_id = NULL;
11132 free(branch_name);
11133 branch_name = NULL;
11134 got_object_commit_close(old_commit);
11135 old_commit = NULL;
11138 if (wanted_branch_name && !wanted_branch_found) {
11139 err = got_error_fmt(GOT_ERR_NOT_REF,
11140 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11142 done:
11143 if (refs_idmap)
11144 got_reflist_object_id_map_free(refs_idmap);
11145 got_ref_list_free(&refs);
11146 got_ref_list_free(&backup_refs);
11147 free(old_commit_id);
11148 free(branch_name);
11149 if (old_commit)
11150 got_object_commit_close(old_commit);
11151 return err;
11154 static const struct got_error *
11155 abort_progress(void *arg, unsigned char status, const char *path)
11158 * Unversioned files should not clutter progress output when
11159 * an operation is aborted.
11161 if (status == GOT_STATUS_UNVERSIONED)
11162 return NULL;
11164 return update_progress(arg, status, path);
11167 static const struct got_error *
11168 cmd_rebase(int argc, char *argv[])
11170 const struct got_error *error = NULL;
11171 struct got_worktree *worktree = NULL;
11172 struct got_repository *repo = NULL;
11173 struct got_fileindex *fileindex = NULL;
11174 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11175 struct got_reference *branch = NULL;
11176 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11177 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11178 struct got_object_id *resume_commit_id = NULL;
11179 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11180 struct got_object_id *head_commit_id = NULL;
11181 struct got_reference *head_ref = NULL;
11182 struct got_commit_object *commit = NULL;
11183 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11184 int histedit_in_progress = 0, merge_in_progress = 0;
11185 int create_backup = 1, list_backups = 0, delete_backups = 0;
11186 int allow_conflict = 0;
11187 struct got_object_id_queue commits;
11188 struct got_pathlist_head merged_paths;
11189 const struct got_object_id_queue *parent_ids;
11190 struct got_object_qid *qid, *pid;
11191 struct got_update_progress_arg upa;
11192 int *pack_fds = NULL;
11194 STAILQ_INIT(&commits);
11195 TAILQ_INIT(&merged_paths);
11196 memset(&upa, 0, sizeof(upa));
11198 #ifndef PROFILE
11199 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11200 "unveil", NULL) == -1)
11201 err(1, "pledge");
11202 #endif
11204 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11205 switch (ch) {
11206 case 'a':
11207 abort_rebase = 1;
11208 break;
11209 case 'C':
11210 allow_conflict = 1;
11211 break;
11212 case 'c':
11213 continue_rebase = 1;
11214 break;
11215 case 'l':
11216 list_backups = 1;
11217 break;
11218 case 'X':
11219 delete_backups = 1;
11220 break;
11221 default:
11222 usage_rebase();
11223 /* NOTREACHED */
11227 argc -= optind;
11228 argv += optind;
11230 if (list_backups) {
11231 if (abort_rebase)
11232 option_conflict('l', 'a');
11233 if (allow_conflict)
11234 option_conflict('l', 'C');
11235 if (continue_rebase)
11236 option_conflict('l', 'c');
11237 if (delete_backups)
11238 option_conflict('l', 'X');
11239 if (argc != 0 && argc != 1)
11240 usage_rebase();
11241 } else if (delete_backups) {
11242 if (abort_rebase)
11243 option_conflict('X', 'a');
11244 if (allow_conflict)
11245 option_conflict('X', 'C');
11246 if (continue_rebase)
11247 option_conflict('X', 'c');
11248 if (list_backups)
11249 option_conflict('l', 'X');
11250 if (argc != 0 && argc != 1)
11251 usage_rebase();
11252 } else if (allow_conflict) {
11253 if (abort_rebase)
11254 option_conflict('C', 'a');
11255 if (!continue_rebase)
11256 errx(1, "-C option requires -c");
11257 } else {
11258 if (abort_rebase && continue_rebase)
11259 usage_rebase();
11260 else if (abort_rebase || continue_rebase) {
11261 if (argc != 0)
11262 usage_rebase();
11263 } else if (argc != 1)
11264 usage_rebase();
11267 cwd = getcwd(NULL, 0);
11268 if (cwd == NULL) {
11269 error = got_error_from_errno("getcwd");
11270 goto done;
11273 error = got_repo_pack_fds_open(&pack_fds);
11274 if (error != NULL)
11275 goto done;
11277 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11278 if (error) {
11279 if (list_backups || delete_backups) {
11280 if (error->code != GOT_ERR_NOT_WORKTREE)
11281 goto done;
11282 } else {
11283 if (error->code == GOT_ERR_NOT_WORKTREE)
11284 error = wrap_not_worktree_error(error,
11285 "rebase", cwd);
11286 goto done;
11290 error = get_gitconfig_path(&gitconfig_path);
11291 if (error)
11292 goto done;
11293 error = got_repo_open(&repo,
11294 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11295 gitconfig_path, pack_fds);
11296 if (error != NULL)
11297 goto done;
11299 if (worktree != NULL && !list_backups && !delete_backups) {
11300 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11301 if (error)
11302 goto done;
11305 error = get_author(&committer, repo, worktree);
11306 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11307 goto done;
11309 error = apply_unveil(got_repo_get_path(repo), 0,
11310 worktree ? got_worktree_get_root_path(worktree) : NULL);
11311 if (error)
11312 goto done;
11314 if (list_backups || delete_backups) {
11315 error = process_backup_refs(
11316 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11317 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11318 goto done; /* nothing else to do */
11321 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11322 worktree);
11323 if (error)
11324 goto done;
11325 if (histedit_in_progress) {
11326 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11327 goto done;
11330 error = got_worktree_merge_in_progress(&merge_in_progress,
11331 worktree, repo);
11332 if (error)
11333 goto done;
11334 if (merge_in_progress) {
11335 error = got_error(GOT_ERR_MERGE_BUSY);
11336 goto done;
11339 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11340 if (error)
11341 goto done;
11343 if (abort_rebase) {
11344 if (!rebase_in_progress) {
11345 error = got_error(GOT_ERR_NOT_REBASING);
11346 goto done;
11348 error = got_worktree_rebase_continue(&resume_commit_id,
11349 &new_base_branch, &tmp_branch, &branch, &fileindex,
11350 worktree, repo);
11351 if (error)
11352 goto done;
11353 printf("Switching work tree to %s\n",
11354 got_ref_get_symref_target(new_base_branch));
11355 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11356 new_base_branch, abort_progress, &upa);
11357 if (error)
11358 goto done;
11359 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11360 print_merge_progress_stats(&upa);
11361 goto done; /* nothing else to do */
11364 if (continue_rebase) {
11365 if (!rebase_in_progress) {
11366 error = got_error(GOT_ERR_NOT_REBASING);
11367 goto done;
11369 error = got_worktree_rebase_continue(&resume_commit_id,
11370 &new_base_branch, &tmp_branch, &branch, &fileindex,
11371 worktree, repo);
11372 if (error)
11373 goto done;
11375 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11376 committer, resume_commit_id, allow_conflict, repo);
11377 if (error)
11378 goto done;
11380 yca_id = got_object_id_dup(resume_commit_id);
11381 if (yca_id == NULL) {
11382 error = got_error_from_errno("got_object_id_dup");
11383 goto done;
11385 } else {
11386 error = got_ref_open(&branch, repo, argv[0], 0);
11387 if (error != NULL)
11388 goto done;
11389 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11390 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11391 "will not rebase a branch which lives outside "
11392 "the \"refs/heads/\" reference namespace");
11393 goto done;
11397 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11398 if (error)
11399 goto done;
11401 if (!continue_rebase) {
11402 struct got_object_id *base_commit_id;
11404 error = got_ref_open(&head_ref, repo,
11405 got_worktree_get_head_ref_name(worktree), 0);
11406 if (error)
11407 goto done;
11408 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11409 if (error)
11410 goto done;
11411 base_commit_id = got_worktree_get_base_commit_id(worktree);
11412 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11413 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11414 goto done;
11417 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11418 base_commit_id, branch_head_commit_id, 1, repo,
11419 check_cancelled, NULL);
11420 if (error) {
11421 if (error->code == GOT_ERR_ANCESTRY) {
11422 error = got_error_msg(GOT_ERR_ANCESTRY,
11423 "specified branch shares no common "
11424 "ancestry with work tree's branch");
11426 goto done;
11429 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11430 struct got_pathlist_head paths;
11431 printf("%s is already based on %s\n",
11432 got_ref_get_name(branch),
11433 got_worktree_get_head_ref_name(worktree));
11434 error = switch_head_ref(branch, branch_head_commit_id,
11435 worktree, repo);
11436 if (error)
11437 goto done;
11438 error = got_worktree_set_base_commit_id(worktree, repo,
11439 branch_head_commit_id);
11440 if (error)
11441 goto done;
11442 TAILQ_INIT(&paths);
11443 error = got_pathlist_append(&paths, "", NULL);
11444 if (error)
11445 goto done;
11446 error = got_worktree_checkout_files(worktree,
11447 &paths, repo, update_progress, &upa,
11448 check_cancelled, NULL);
11449 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11450 if (error)
11451 goto done;
11452 if (upa.did_something) {
11453 char *id_str;
11454 error = got_object_id_str(&id_str,
11455 branch_head_commit_id);
11456 if (error)
11457 goto done;
11458 printf("Updated to %s: %s\n",
11459 got_worktree_get_head_ref_name(worktree),
11460 id_str);
11461 free(id_str);
11462 } else
11463 printf("Already up-to-date\n");
11464 print_update_progress_stats(&upa);
11465 goto done;
11469 commit_id = branch_head_commit_id;
11470 error = got_object_open_as_commit(&commit, repo, commit_id);
11471 if (error)
11472 goto done;
11474 parent_ids = got_object_commit_get_parent_ids(commit);
11475 pid = STAILQ_FIRST(parent_ids);
11476 if (pid) {
11477 error = collect_commits(&commits, commit_id, &pid->id,
11478 yca_id, got_worktree_get_path_prefix(worktree),
11479 GOT_ERR_REBASE_PATH, repo);
11480 if (error)
11481 goto done;
11484 got_object_commit_close(commit);
11485 commit = NULL;
11487 if (!continue_rebase) {
11488 error = got_worktree_rebase_prepare(&new_base_branch,
11489 &tmp_branch, &fileindex, worktree, branch, repo);
11490 if (error)
11491 goto done;
11494 if (STAILQ_EMPTY(&commits)) {
11495 if (continue_rebase) {
11496 error = rebase_complete(worktree, fileindex,
11497 branch, tmp_branch, repo, create_backup);
11498 goto done;
11499 } else {
11500 /* Fast-forward the reference of the branch. */
11501 struct got_object_id *new_head_commit_id;
11502 char *id_str;
11503 error = got_ref_resolve(&new_head_commit_id, repo,
11504 new_base_branch);
11505 if (error)
11506 goto done;
11507 error = got_object_id_str(&id_str, new_head_commit_id);
11508 if (error)
11509 goto done;
11510 printf("Forwarding %s to commit %s\n",
11511 got_ref_get_name(branch), id_str);
11512 free(id_str);
11513 error = got_ref_change_ref(branch,
11514 new_head_commit_id);
11515 if (error)
11516 goto done;
11517 /* No backup needed since objects did not change. */
11518 create_backup = 0;
11522 pid = NULL;
11523 STAILQ_FOREACH(qid, &commits, entry) {
11525 commit_id = &qid->id;
11526 parent_id = pid ? &pid->id : yca_id;
11527 pid = qid;
11529 memset(&upa, 0, sizeof(upa));
11530 error = got_worktree_rebase_merge_files(&merged_paths,
11531 worktree, fileindex, parent_id, commit_id, repo,
11532 update_progress, &upa, check_cancelled, NULL);
11533 if (error)
11534 goto done;
11536 print_merge_progress_stats(&upa);
11537 if (upa.conflicts > 0 || upa.missing > 0 ||
11538 upa.not_deleted > 0 || upa.unversioned > 0) {
11539 if (upa.conflicts > 0) {
11540 error = show_rebase_merge_conflict(&qid->id,
11541 repo);
11542 if (error)
11543 goto done;
11545 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11546 break;
11549 error = rebase_commit(&merged_paths, worktree, fileindex,
11550 tmp_branch, committer, commit_id, 0, repo);
11551 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11552 if (error)
11553 goto done;
11556 if (upa.conflicts > 0 || upa.missing > 0 ||
11557 upa.not_deleted > 0 || upa.unversioned > 0) {
11558 error = got_worktree_rebase_postpone(worktree, fileindex);
11559 if (error)
11560 goto done;
11561 if (upa.conflicts > 0 && upa.missing == 0 &&
11562 upa.not_deleted == 0 && upa.unversioned == 0) {
11563 error = got_error_msg(GOT_ERR_CONFLICTS,
11564 "conflicts must be resolved before rebasing "
11565 "can continue");
11566 } else if (upa.conflicts > 0) {
11567 error = got_error_msg(GOT_ERR_CONFLICTS,
11568 "conflicts must be resolved before rebasing "
11569 "can continue; changes destined for some "
11570 "files were not yet merged and should be "
11571 "merged manually if required before the "
11572 "rebase operation is continued");
11573 } else {
11574 error = got_error_msg(GOT_ERR_CONFLICTS,
11575 "changes destined for some files were not "
11576 "yet merged and should be merged manually "
11577 "if required before the rebase operation "
11578 "is continued");
11580 } else
11581 error = rebase_complete(worktree, fileindex, branch,
11582 tmp_branch, repo, create_backup);
11583 done:
11584 free(cwd);
11585 free(committer);
11586 free(gitconfig_path);
11587 got_object_id_queue_free(&commits);
11588 free(branch_head_commit_id);
11589 free(resume_commit_id);
11590 free(head_commit_id);
11591 free(yca_id);
11592 if (commit)
11593 got_object_commit_close(commit);
11594 if (branch)
11595 got_ref_close(branch);
11596 if (new_base_branch)
11597 got_ref_close(new_base_branch);
11598 if (tmp_branch)
11599 got_ref_close(tmp_branch);
11600 if (head_ref)
11601 got_ref_close(head_ref);
11602 if (worktree)
11603 got_worktree_close(worktree);
11604 if (repo) {
11605 const struct got_error *close_err = got_repo_close(repo);
11606 if (error == NULL)
11607 error = close_err;
11609 if (pack_fds) {
11610 const struct got_error *pack_err =
11611 got_repo_pack_fds_close(pack_fds);
11612 if (error == NULL)
11613 error = pack_err;
11615 return error;
11618 __dead static void
11619 usage_histedit(void)
11621 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11622 "[branch]\n", getprogname());
11623 exit(1);
11626 #define GOT_HISTEDIT_PICK 'p'
11627 #define GOT_HISTEDIT_EDIT 'e'
11628 #define GOT_HISTEDIT_FOLD 'f'
11629 #define GOT_HISTEDIT_DROP 'd'
11630 #define GOT_HISTEDIT_MESG 'm'
11632 static const struct got_histedit_cmd {
11633 unsigned char code;
11634 const char *name;
11635 const char *desc;
11636 } got_histedit_cmds[] = {
11637 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11638 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11639 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11640 "be used" },
11641 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11642 { GOT_HISTEDIT_MESG, "mesg",
11643 "single-line log message for commit above (open editor if empty)" },
11646 struct got_histedit_list_entry {
11647 TAILQ_ENTRY(got_histedit_list_entry) entry;
11648 struct got_object_id *commit_id;
11649 const struct got_histedit_cmd *cmd;
11650 char *logmsg;
11652 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11654 static const struct got_error *
11655 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11656 FILE *f, struct got_repository *repo)
11658 const struct got_error *err = NULL;
11659 char *logmsg = NULL, *id_str = NULL;
11660 struct got_commit_object *commit = NULL;
11661 int n;
11663 err = got_object_open_as_commit(&commit, repo, commit_id);
11664 if (err)
11665 goto done;
11667 err = get_short_logmsg(&logmsg, 34, commit);
11668 if (err)
11669 goto done;
11671 err = got_object_id_str(&id_str, commit_id);
11672 if (err)
11673 goto done;
11675 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11676 if (n < 0)
11677 err = got_ferror(f, GOT_ERR_IO);
11678 done:
11679 if (commit)
11680 got_object_commit_close(commit);
11681 free(id_str);
11682 free(logmsg);
11683 return err;
11686 static const struct got_error *
11687 histedit_write_commit_list(struct got_object_id_queue *commits,
11688 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11689 int edit_only, struct got_repository *repo)
11691 const struct got_error *err = NULL;
11692 struct got_object_qid *qid;
11693 const char *histedit_cmd = NULL;
11695 if (STAILQ_EMPTY(commits))
11696 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11698 STAILQ_FOREACH(qid, commits, entry) {
11699 histedit_cmd = got_histedit_cmds[0].name;
11700 if (drop_only)
11701 histedit_cmd = "drop";
11702 else if (edit_only)
11703 histedit_cmd = "edit";
11704 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11705 histedit_cmd = "fold";
11706 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11707 if (err)
11708 break;
11709 if (edit_logmsg_only) {
11710 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11711 if (n < 0) {
11712 err = got_ferror(f, GOT_ERR_IO);
11713 break;
11718 return err;
11721 static const struct got_error *
11722 write_cmd_list(FILE *f, const char *branch_name,
11723 struct got_object_id_queue *commits)
11725 const struct got_error *err = NULL;
11726 size_t i;
11727 int n;
11728 char *id_str;
11729 struct got_object_qid *qid;
11731 qid = STAILQ_FIRST(commits);
11732 err = got_object_id_str(&id_str, &qid->id);
11733 if (err)
11734 return err;
11736 n = fprintf(f,
11737 "# Editing the history of branch '%s' starting at\n"
11738 "# commit %s\n"
11739 "# Commits will be processed in order from top to "
11740 "bottom of this file.\n", branch_name, id_str);
11741 if (n < 0) {
11742 err = got_ferror(f, GOT_ERR_IO);
11743 goto done;
11746 n = fprintf(f, "# Available histedit commands:\n");
11747 if (n < 0) {
11748 err = got_ferror(f, GOT_ERR_IO);
11749 goto done;
11752 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11753 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11754 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11755 cmd->desc);
11756 if (n < 0) {
11757 err = got_ferror(f, GOT_ERR_IO);
11758 break;
11761 done:
11762 free(id_str);
11763 return err;
11766 static const struct got_error *
11767 histedit_syntax_error(int lineno)
11769 static char msg[42];
11770 int ret;
11772 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11773 lineno);
11774 if (ret < 0 || (size_t)ret >= sizeof(msg))
11775 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11777 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11780 static const struct got_error *
11781 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11782 char *logmsg, struct got_repository *repo)
11784 const struct got_error *err;
11785 struct got_commit_object *folded_commit = NULL;
11786 char *id_str, *folded_logmsg = NULL;
11788 err = got_object_id_str(&id_str, hle->commit_id);
11789 if (err)
11790 return err;
11792 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11793 if (err)
11794 goto done;
11796 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11797 if (err)
11798 goto done;
11799 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11800 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11801 folded_logmsg) == -1) {
11802 err = got_error_from_errno("asprintf");
11804 done:
11805 if (folded_commit)
11806 got_object_commit_close(folded_commit);
11807 free(id_str);
11808 free(folded_logmsg);
11809 return err;
11812 static struct got_histedit_list_entry *
11813 get_folded_commits(struct got_histedit_list_entry *hle)
11815 struct got_histedit_list_entry *prev, *folded = NULL;
11817 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11818 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11819 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11820 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11821 folded = prev;
11822 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11825 return folded;
11828 static const struct got_error *
11829 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11830 struct got_repository *repo)
11832 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11833 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11834 const struct got_error *err = NULL;
11835 struct got_commit_object *commit = NULL;
11836 int logmsg_len;
11837 int fd = -1;
11838 struct got_histedit_list_entry *folded = NULL;
11840 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11841 if (err)
11842 return err;
11844 folded = get_folded_commits(hle);
11845 if (folded) {
11846 while (folded != hle) {
11847 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11848 folded = TAILQ_NEXT(folded, entry);
11849 continue;
11851 err = append_folded_commit_msg(&new_msg, folded,
11852 logmsg, repo);
11853 if (err)
11854 goto done;
11855 free(logmsg);
11856 logmsg = new_msg;
11857 folded = TAILQ_NEXT(folded, entry);
11861 err = got_object_id_str(&id_str, hle->commit_id);
11862 if (err)
11863 goto done;
11864 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11865 if (err)
11866 goto done;
11867 logmsg_len = asprintf(&new_msg,
11868 "%s\n# original log message of commit %s: %s",
11869 logmsg ? logmsg : "", id_str, orig_logmsg);
11870 if (logmsg_len == -1) {
11871 err = got_error_from_errno("asprintf");
11872 goto done;
11874 free(logmsg);
11875 logmsg = new_msg;
11877 err = got_object_id_str(&id_str, hle->commit_id);
11878 if (err)
11879 goto done;
11881 err = got_opentemp_named_fd(&logmsg_path, &fd,
11882 GOT_TMPDIR_STR "/got-logmsg", "");
11883 if (err)
11884 goto done;
11886 if (write(fd, logmsg, logmsg_len) == -1) {
11887 err = got_error_from_errno2("write", logmsg_path);
11888 goto done;
11890 if (close(fd) == -1) {
11891 err = got_error_from_errno2("close", logmsg_path);
11892 goto done;
11894 fd = -1;
11896 err = get_editor(&editor);
11897 if (err)
11898 goto done;
11900 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11901 logmsg_len, 0);
11902 if (err) {
11903 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11904 goto done;
11905 err = NULL;
11906 hle->logmsg = strdup(new_msg);
11907 if (hle->logmsg == NULL)
11908 err = got_error_from_errno("strdup");
11910 done:
11911 if (fd != -1 && close(fd) == -1 && err == NULL)
11912 err = got_error_from_errno2("close", logmsg_path);
11913 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11914 err = got_error_from_errno2("unlink", logmsg_path);
11915 free(logmsg_path);
11916 free(logmsg);
11917 free(orig_logmsg);
11918 free(editor);
11919 if (commit)
11920 got_object_commit_close(commit);
11921 return err;
11924 static const struct got_error *
11925 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11926 FILE *f, struct got_repository *repo)
11928 const struct got_error *err = NULL;
11929 char *line = NULL, *p, *end;
11930 size_t i, linesize = 0;
11931 ssize_t linelen;
11932 int lineno = 0, lastcmd = -1;
11933 const struct got_histedit_cmd *cmd;
11934 struct got_object_id *commit_id = NULL;
11935 struct got_histedit_list_entry *hle = NULL;
11937 for (;;) {
11938 linelen = getline(&line, &linesize, f);
11939 if (linelen == -1) {
11940 const struct got_error *getline_err;
11941 if (feof(f))
11942 break;
11943 getline_err = got_error_from_errno("getline");
11944 err = got_ferror(f, getline_err->code);
11945 break;
11947 lineno++;
11948 p = line;
11949 while (isspace((unsigned char)p[0]))
11950 p++;
11951 if (p[0] == '#' || p[0] == '\0')
11952 continue;
11953 cmd = NULL;
11954 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11955 cmd = &got_histedit_cmds[i];
11956 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11957 isspace((unsigned char)p[strlen(cmd->name)])) {
11958 p += strlen(cmd->name);
11959 break;
11961 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11962 p++;
11963 break;
11966 if (i == nitems(got_histedit_cmds)) {
11967 err = histedit_syntax_error(lineno);
11968 break;
11970 while (isspace((unsigned char)p[0]))
11971 p++;
11972 if (cmd->code == GOT_HISTEDIT_MESG) {
11973 if (lastcmd != GOT_HISTEDIT_PICK &&
11974 lastcmd != GOT_HISTEDIT_EDIT) {
11975 err = got_error(GOT_ERR_HISTEDIT_CMD);
11976 break;
11978 if (p[0] == '\0') {
11979 err = histedit_edit_logmsg(hle, repo);
11980 if (err)
11981 break;
11982 } else {
11983 hle->logmsg = strdup(p);
11984 if (hle->logmsg == NULL) {
11985 err = got_error_from_errno("strdup");
11986 break;
11989 lastcmd = cmd->code;
11990 continue;
11991 } else {
11992 end = p;
11993 while (end[0] && !isspace((unsigned char)end[0]))
11994 end++;
11995 *end = '\0';
11997 err = got_object_resolve_id_str(&commit_id, repo, p);
11998 if (err) {
11999 /* override error code */
12000 err = histedit_syntax_error(lineno);
12001 break;
12004 hle = malloc(sizeof(*hle));
12005 if (hle == NULL) {
12006 err = got_error_from_errno("malloc");
12007 break;
12009 hle->cmd = cmd;
12010 hle->commit_id = commit_id;
12011 hle->logmsg = NULL;
12012 commit_id = NULL;
12013 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12014 lastcmd = cmd->code;
12017 free(line);
12018 free(commit_id);
12019 return err;
12022 static const struct got_error *
12023 histedit_check_script(struct got_histedit_list *histedit_cmds,
12024 struct got_object_id_queue *commits, struct got_repository *repo)
12026 const struct got_error *err = NULL;
12027 struct got_object_qid *qid;
12028 struct got_histedit_list_entry *hle;
12029 static char msg[92];
12030 char *id_str;
12032 if (TAILQ_EMPTY(histedit_cmds))
12033 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12034 "histedit script contains no commands");
12035 if (STAILQ_EMPTY(commits))
12036 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12038 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12039 struct got_histedit_list_entry *hle2;
12040 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12041 if (hle == hle2)
12042 continue;
12043 if (got_object_id_cmp(hle->commit_id,
12044 hle2->commit_id) != 0)
12045 continue;
12046 err = got_object_id_str(&id_str, hle->commit_id);
12047 if (err)
12048 return err;
12049 snprintf(msg, sizeof(msg), "commit %s is listed "
12050 "more than once in histedit script", id_str);
12051 free(id_str);
12052 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12056 STAILQ_FOREACH(qid, commits, entry) {
12057 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12058 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12059 break;
12061 if (hle == NULL) {
12062 err = got_object_id_str(&id_str, &qid->id);
12063 if (err)
12064 return err;
12065 snprintf(msg, sizeof(msg),
12066 "commit %s missing from histedit script", id_str);
12067 free(id_str);
12068 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12072 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12073 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12074 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12075 "last commit in histedit script cannot be folded");
12077 return NULL;
12080 static const struct got_error *
12081 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12082 const char *path, struct got_object_id_queue *commits,
12083 struct got_repository *repo)
12085 const struct got_error *err = NULL;
12086 struct stat st, st2;
12087 struct timespec timeout;
12088 char *editor;
12089 FILE *f = NULL;
12091 err = get_editor(&editor);
12092 if (err)
12093 return err;
12095 if (stat(path, &st) == -1) {
12096 err = got_error_from_errno2("stat", path);
12097 goto done;
12100 if (spawn_editor(editor, path) == -1) {
12101 err = got_error_from_errno("failed spawning editor");
12102 goto done;
12105 timeout.tv_sec = 0;
12106 timeout.tv_nsec = 1;
12107 nanosleep(&timeout, NULL);
12109 if (stat(path, &st2) == -1) {
12110 err = got_error_from_errno2("stat", path);
12111 goto done;
12114 if (st.st_size == st2.st_size &&
12115 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12116 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12117 "no changes made to histedit script, aborting");
12118 goto done;
12121 f = fopen(path, "re");
12122 if (f == NULL) {
12123 err = got_error_from_errno("fopen");
12124 goto done;
12126 err = histedit_parse_list(histedit_cmds, f, repo);
12127 if (err)
12128 goto done;
12130 err = histedit_check_script(histedit_cmds, commits, repo);
12131 done:
12132 if (f && fclose(f) == EOF && err == NULL)
12133 err = got_error_from_errno("fclose");
12134 free(editor);
12135 return err;
12138 static const struct got_error *
12139 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12140 struct got_object_id_queue *, const char *, const char *,
12141 struct got_repository *);
12143 static const struct got_error *
12144 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12145 struct got_object_id_queue *commits, const char *branch_name,
12146 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12147 struct got_repository *repo)
12149 const struct got_error *err;
12150 FILE *f = NULL;
12151 char *path = NULL;
12153 err = got_opentemp_named(&path, &f, "got-histedit", "");
12154 if (err)
12155 return err;
12157 err = write_cmd_list(f, branch_name, commits);
12158 if (err)
12159 goto done;
12161 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12162 fold_only, drop_only, edit_only, repo);
12163 if (err)
12164 goto done;
12166 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12167 rewind(f);
12168 err = histedit_parse_list(histedit_cmds, f, repo);
12169 } else {
12170 if (fclose(f) == EOF) {
12171 err = got_error_from_errno("fclose");
12172 goto done;
12174 f = NULL;
12175 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12176 if (err) {
12177 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12178 err->code != GOT_ERR_HISTEDIT_CMD)
12179 goto done;
12180 err = histedit_edit_list_retry(histedit_cmds, err,
12181 commits, path, branch_name, repo);
12184 done:
12185 if (f && fclose(f) == EOF && err == NULL)
12186 err = got_error_from_errno("fclose");
12187 if (path && unlink(path) != 0 && err == NULL)
12188 err = got_error_from_errno2("unlink", path);
12189 free(path);
12190 return err;
12193 static const struct got_error *
12194 histedit_save_list(struct got_histedit_list *histedit_cmds,
12195 struct got_worktree *worktree, struct got_repository *repo)
12197 const struct got_error *err = NULL;
12198 char *path = NULL;
12199 FILE *f = NULL;
12200 struct got_histedit_list_entry *hle;
12201 struct got_commit_object *commit = NULL;
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 if (commit)
12232 got_object_commit_close(commit);
12233 return err;
12236 static void
12237 histedit_free_list(struct got_histedit_list *histedit_cmds)
12239 struct got_histedit_list_entry *hle;
12241 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12242 TAILQ_REMOVE(histedit_cmds, hle, entry);
12243 free(hle);
12247 static const struct got_error *
12248 histedit_load_list(struct got_histedit_list *histedit_cmds,
12249 const char *path, struct got_repository *repo)
12251 const struct got_error *err = NULL;
12252 FILE *f = NULL;
12254 f = fopen(path, "re");
12255 if (f == NULL) {
12256 err = got_error_from_errno2("fopen", path);
12257 goto done;
12260 err = histedit_parse_list(histedit_cmds, f, repo);
12261 done:
12262 if (f && fclose(f) == EOF && err == NULL)
12263 err = got_error_from_errno("fclose");
12264 return err;
12267 static const struct got_error *
12268 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12269 const struct got_error *edit_err, struct got_object_id_queue *commits,
12270 const char *path, const char *branch_name, struct got_repository *repo)
12272 const struct got_error *err = NULL, *prev_err = edit_err;
12273 int resp = ' ';
12275 while (resp != 'c' && resp != 'r' && resp != 'a') {
12276 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12277 "or (a)bort: ", getprogname(), prev_err->msg);
12278 resp = getchar();
12279 if (resp == '\n')
12280 resp = getchar();
12281 if (resp == 'c') {
12282 histedit_free_list(histedit_cmds);
12283 err = histedit_run_editor(histedit_cmds, path, commits,
12284 repo);
12285 if (err) {
12286 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12287 err->code != GOT_ERR_HISTEDIT_CMD)
12288 break;
12289 prev_err = err;
12290 resp = ' ';
12291 continue;
12293 break;
12294 } else if (resp == 'r') {
12295 histedit_free_list(histedit_cmds);
12296 err = histedit_edit_script(histedit_cmds,
12297 commits, branch_name, 0, 0, 0, 0, repo);
12298 if (err) {
12299 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12300 err->code != GOT_ERR_HISTEDIT_CMD)
12301 break;
12302 prev_err = err;
12303 resp = ' ';
12304 continue;
12306 break;
12307 } else if (resp == 'a') {
12308 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12309 break;
12310 } else
12311 printf("invalid response '%c'\n", resp);
12314 return err;
12317 static const struct got_error *
12318 histedit_complete(struct got_worktree *worktree,
12319 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12320 struct got_reference *branch, struct got_repository *repo)
12322 printf("Switching work tree to %s\n",
12323 got_ref_get_symref_target(branch));
12324 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12325 branch, repo);
12328 static const struct got_error *
12329 show_histedit_progress(struct got_commit_object *commit,
12330 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12332 const struct got_error *err;
12333 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12335 err = got_object_id_str(&old_id_str, hle->commit_id);
12336 if (err)
12337 goto done;
12339 if (new_id) {
12340 err = got_object_id_str(&new_id_str, new_id);
12341 if (err)
12342 goto done;
12345 old_id_str[12] = '\0';
12346 if (new_id_str)
12347 new_id_str[12] = '\0';
12349 if (hle->logmsg) {
12350 logmsg = strdup(hle->logmsg);
12351 if (logmsg == NULL) {
12352 err = got_error_from_errno("strdup");
12353 goto done;
12355 trim_logmsg(logmsg, 42);
12356 } else {
12357 err = get_short_logmsg(&logmsg, 42, commit);
12358 if (err)
12359 goto done;
12362 switch (hle->cmd->code) {
12363 case GOT_HISTEDIT_PICK:
12364 case GOT_HISTEDIT_EDIT:
12365 printf("%s -> %s: %s\n", old_id_str,
12366 new_id_str ? new_id_str : "no-op change", logmsg);
12367 break;
12368 case GOT_HISTEDIT_DROP:
12369 case GOT_HISTEDIT_FOLD:
12370 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12371 logmsg);
12372 break;
12373 default:
12374 break;
12376 done:
12377 free(old_id_str);
12378 free(new_id_str);
12379 return err;
12382 static const struct got_error *
12383 histedit_commit(struct got_pathlist_head *merged_paths,
12384 struct got_worktree *worktree, struct got_fileindex *fileindex,
12385 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12386 const char *committer, int allow_conflict, struct got_repository *repo)
12388 const struct got_error *err;
12389 struct got_commit_object *commit;
12390 struct got_object_id *new_commit_id;
12392 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12393 && hle->logmsg == NULL) {
12394 err = histedit_edit_logmsg(hle, repo);
12395 if (err)
12396 return err;
12399 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12400 if (err)
12401 return err;
12403 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12404 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12405 hle->logmsg, allow_conflict, repo);
12406 if (err) {
12407 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12408 goto done;
12409 err = show_histedit_progress(commit, hle, NULL);
12410 } else {
12411 err = show_histedit_progress(commit, hle, new_commit_id);
12412 free(new_commit_id);
12414 done:
12415 got_object_commit_close(commit);
12416 return err;
12419 static const struct got_error *
12420 histedit_skip_commit(struct got_histedit_list_entry *hle,
12421 struct got_worktree *worktree, struct got_repository *repo)
12423 const struct got_error *error;
12424 struct got_commit_object *commit;
12426 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12427 repo);
12428 if (error)
12429 return error;
12431 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12432 if (error)
12433 return error;
12435 error = show_histedit_progress(commit, hle, NULL);
12436 got_object_commit_close(commit);
12437 return error;
12440 static const struct got_error *
12441 check_local_changes(void *arg, unsigned char status,
12442 unsigned char staged_status, const char *path,
12443 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12444 struct got_object_id *commit_id, int dirfd, const char *de_name)
12446 int *have_local_changes = arg;
12448 switch (status) {
12449 case GOT_STATUS_ADD:
12450 case GOT_STATUS_DELETE:
12451 case GOT_STATUS_MODIFY:
12452 case GOT_STATUS_CONFLICT:
12453 *have_local_changes = 1;
12454 return got_error(GOT_ERR_CANCELLED);
12455 default:
12456 break;
12459 switch (staged_status) {
12460 case GOT_STATUS_ADD:
12461 case GOT_STATUS_DELETE:
12462 case GOT_STATUS_MODIFY:
12463 *have_local_changes = 1;
12464 return got_error(GOT_ERR_CANCELLED);
12465 default:
12466 break;
12469 return NULL;
12472 static const struct got_error *
12473 cmd_histedit(int argc, char *argv[])
12475 const struct got_error *error = NULL;
12476 struct got_worktree *worktree = NULL;
12477 struct got_fileindex *fileindex = NULL;
12478 struct got_repository *repo = NULL;
12479 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12480 struct got_reference *branch = NULL;
12481 struct got_reference *tmp_branch = NULL;
12482 struct got_object_id *resume_commit_id = NULL;
12483 struct got_object_id *base_commit_id = NULL;
12484 struct got_object_id *head_commit_id = NULL;
12485 struct got_commit_object *commit = NULL;
12486 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12487 struct got_update_progress_arg upa;
12488 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12489 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12490 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12491 const char *edit_script_path = NULL;
12492 struct got_object_id_queue commits;
12493 struct got_pathlist_head merged_paths;
12494 const struct got_object_id_queue *parent_ids;
12495 struct got_object_qid *pid;
12496 struct got_histedit_list histedit_cmds;
12497 struct got_histedit_list_entry *hle;
12498 int *pack_fds = NULL;
12500 STAILQ_INIT(&commits);
12501 TAILQ_INIT(&histedit_cmds);
12502 TAILQ_INIT(&merged_paths);
12503 memset(&upa, 0, sizeof(upa));
12505 #ifndef PROFILE
12506 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12507 "unveil", NULL) == -1)
12508 err(1, "pledge");
12509 #endif
12511 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12512 switch (ch) {
12513 case 'a':
12514 abort_edit = 1;
12515 break;
12516 case 'C':
12517 allow_conflict = 1;
12518 break;
12519 case 'c':
12520 continue_edit = 1;
12521 break;
12522 case 'd':
12523 drop_only = 1;
12524 break;
12525 case 'e':
12526 edit_only = 1;
12527 break;
12528 case 'F':
12529 edit_script_path = optarg;
12530 break;
12531 case 'f':
12532 fold_only = 1;
12533 break;
12534 case 'l':
12535 list_backups = 1;
12536 break;
12537 case 'm':
12538 edit_logmsg_only = 1;
12539 break;
12540 case 'X':
12541 delete_backups = 1;
12542 break;
12543 default:
12544 usage_histedit();
12545 /* NOTREACHED */
12549 argc -= optind;
12550 argv += optind;
12552 if (abort_edit && allow_conflict)
12553 option_conflict('a', 'C');
12554 if (abort_edit && continue_edit)
12555 option_conflict('a', 'c');
12556 if (edit_script_path && allow_conflict)
12557 option_conflict('F', 'C');
12558 if (edit_script_path && edit_logmsg_only)
12559 option_conflict('F', 'm');
12560 if (abort_edit && edit_logmsg_only)
12561 option_conflict('a', 'm');
12562 if (edit_logmsg_only && allow_conflict)
12563 option_conflict('m', 'C');
12564 if (continue_edit && edit_logmsg_only)
12565 option_conflict('c', 'm');
12566 if (abort_edit && fold_only)
12567 option_conflict('a', 'f');
12568 if (fold_only && allow_conflict)
12569 option_conflict('f', 'C');
12570 if (continue_edit && fold_only)
12571 option_conflict('c', 'f');
12572 if (fold_only && edit_logmsg_only)
12573 option_conflict('f', 'm');
12574 if (edit_script_path && fold_only)
12575 option_conflict('F', 'f');
12576 if (abort_edit && edit_only)
12577 option_conflict('a', 'e');
12578 if (continue_edit && edit_only)
12579 option_conflict('c', 'e');
12580 if (edit_only && edit_logmsg_only)
12581 option_conflict('e', 'm');
12582 if (edit_script_path && edit_only)
12583 option_conflict('F', 'e');
12584 if (fold_only && edit_only)
12585 option_conflict('f', 'e');
12586 if (drop_only && abort_edit)
12587 option_conflict('d', 'a');
12588 if (drop_only && allow_conflict)
12589 option_conflict('d', 'C');
12590 if (drop_only && continue_edit)
12591 option_conflict('d', 'c');
12592 if (drop_only && edit_logmsg_only)
12593 option_conflict('d', 'm');
12594 if (drop_only && edit_only)
12595 option_conflict('d', 'e');
12596 if (drop_only && edit_script_path)
12597 option_conflict('d', 'F');
12598 if (drop_only && fold_only)
12599 option_conflict('d', 'f');
12600 if (list_backups) {
12601 if (abort_edit)
12602 option_conflict('l', 'a');
12603 if (allow_conflict)
12604 option_conflict('l', 'C');
12605 if (continue_edit)
12606 option_conflict('l', 'c');
12607 if (edit_script_path)
12608 option_conflict('l', 'F');
12609 if (edit_logmsg_only)
12610 option_conflict('l', 'm');
12611 if (drop_only)
12612 option_conflict('l', 'd');
12613 if (fold_only)
12614 option_conflict('l', 'f');
12615 if (edit_only)
12616 option_conflict('l', 'e');
12617 if (delete_backups)
12618 option_conflict('l', 'X');
12619 if (argc != 0 && argc != 1)
12620 usage_histedit();
12621 } else if (delete_backups) {
12622 if (abort_edit)
12623 option_conflict('X', 'a');
12624 if (allow_conflict)
12625 option_conflict('X', 'C');
12626 if (continue_edit)
12627 option_conflict('X', 'c');
12628 if (drop_only)
12629 option_conflict('X', 'd');
12630 if (edit_script_path)
12631 option_conflict('X', 'F');
12632 if (edit_logmsg_only)
12633 option_conflict('X', 'm');
12634 if (fold_only)
12635 option_conflict('X', 'f');
12636 if (edit_only)
12637 option_conflict('X', 'e');
12638 if (list_backups)
12639 option_conflict('X', 'l');
12640 if (argc != 0 && argc != 1)
12641 usage_histedit();
12642 } else if (allow_conflict && !continue_edit)
12643 errx(1, "-C option requires -c");
12644 else if (argc != 0)
12645 usage_histedit();
12648 * This command cannot apply unveil(2) in all cases because the
12649 * user may choose to run an editor to edit the histedit script
12650 * and to edit individual commit log messages.
12651 * unveil(2) traverses exec(2); if an editor is used we have to
12652 * apply unveil after edit script and log messages have been written.
12653 * XXX TODO: Make use of unveil(2) where possible.
12656 cwd = getcwd(NULL, 0);
12657 if (cwd == NULL) {
12658 error = got_error_from_errno("getcwd");
12659 goto done;
12662 error = got_repo_pack_fds_open(&pack_fds);
12663 if (error != NULL)
12664 goto done;
12666 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12667 if (error) {
12668 if (list_backups || delete_backups) {
12669 if (error->code != GOT_ERR_NOT_WORKTREE)
12670 goto done;
12671 } else {
12672 if (error->code == GOT_ERR_NOT_WORKTREE)
12673 error = wrap_not_worktree_error(error,
12674 "histedit", cwd);
12675 goto done;
12679 if (list_backups || delete_backups) {
12680 error = got_repo_open(&repo,
12681 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12682 NULL, pack_fds);
12683 if (error != NULL)
12684 goto done;
12685 error = apply_unveil(got_repo_get_path(repo), 0,
12686 worktree ? got_worktree_get_root_path(worktree) : NULL);
12687 if (error)
12688 goto done;
12689 error = process_backup_refs(
12690 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12691 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12692 goto done; /* nothing else to do */
12695 error = get_gitconfig_path(&gitconfig_path);
12696 if (error)
12697 goto done;
12698 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12699 gitconfig_path, pack_fds);
12700 if (error != NULL)
12701 goto done;
12703 if (worktree != NULL && !list_backups && !delete_backups) {
12704 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12705 if (error)
12706 goto done;
12709 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12710 if (error)
12711 goto done;
12712 if (rebase_in_progress) {
12713 error = got_error(GOT_ERR_REBASING);
12714 goto done;
12717 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12718 repo);
12719 if (error)
12720 goto done;
12721 if (merge_in_progress) {
12722 error = got_error(GOT_ERR_MERGE_BUSY);
12723 goto done;
12726 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12727 if (error)
12728 goto done;
12730 if (edit_in_progress && edit_logmsg_only) {
12731 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12732 "histedit operation is in progress in this "
12733 "work tree and must be continued or aborted "
12734 "before the -m option can be used");
12735 goto done;
12737 if (edit_in_progress && drop_only) {
12738 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12739 "histedit operation is in progress in this "
12740 "work tree and must be continued or aborted "
12741 "before the -d option can be used");
12742 goto done;
12744 if (edit_in_progress && fold_only) {
12745 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12746 "histedit operation is in progress in this "
12747 "work tree and must be continued or aborted "
12748 "before the -f option can be used");
12749 goto done;
12751 if (edit_in_progress && edit_only) {
12752 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12753 "histedit operation is in progress in this "
12754 "work tree and must be continued or aborted "
12755 "before the -e option can be used");
12756 goto done;
12759 if (edit_in_progress && abort_edit) {
12760 error = got_worktree_histedit_continue(&resume_commit_id,
12761 &tmp_branch, &branch, &base_commit_id, &fileindex,
12762 worktree, repo);
12763 if (error)
12764 goto done;
12765 printf("Switching work tree to %s\n",
12766 got_ref_get_symref_target(branch));
12767 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12768 branch, base_commit_id, abort_progress, &upa);
12769 if (error)
12770 goto done;
12771 printf("Histedit of %s aborted\n",
12772 got_ref_get_symref_target(branch));
12773 print_merge_progress_stats(&upa);
12774 goto done; /* nothing else to do */
12775 } else if (abort_edit) {
12776 error = got_error(GOT_ERR_NOT_HISTEDIT);
12777 goto done;
12780 error = get_author(&committer, repo, worktree);
12781 if (error)
12782 goto done;
12784 if (continue_edit) {
12785 char *path;
12787 if (!edit_in_progress) {
12788 error = got_error(GOT_ERR_NOT_HISTEDIT);
12789 goto done;
12792 error = got_worktree_get_histedit_script_path(&path, worktree);
12793 if (error)
12794 goto done;
12796 error = histedit_load_list(&histedit_cmds, path, repo);
12797 free(path);
12798 if (error)
12799 goto done;
12801 error = got_worktree_histedit_continue(&resume_commit_id,
12802 &tmp_branch, &branch, &base_commit_id, &fileindex,
12803 worktree, repo);
12804 if (error)
12805 goto done;
12807 error = got_ref_resolve(&head_commit_id, repo, branch);
12808 if (error)
12809 goto done;
12811 error = got_object_open_as_commit(&commit, repo,
12812 head_commit_id);
12813 if (error)
12814 goto done;
12815 parent_ids = got_object_commit_get_parent_ids(commit);
12816 pid = STAILQ_FIRST(parent_ids);
12817 if (pid == NULL) {
12818 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12819 goto done;
12821 error = collect_commits(&commits, head_commit_id, &pid->id,
12822 base_commit_id, got_worktree_get_path_prefix(worktree),
12823 GOT_ERR_HISTEDIT_PATH, repo);
12824 got_object_commit_close(commit);
12825 commit = NULL;
12826 if (error)
12827 goto done;
12828 } else {
12829 if (edit_in_progress) {
12830 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12831 goto done;
12834 error = got_ref_open(&branch, repo,
12835 got_worktree_get_head_ref_name(worktree), 0);
12836 if (error != NULL)
12837 goto done;
12839 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12840 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12841 "will not edit commit history of a branch outside "
12842 "the \"refs/heads/\" reference namespace");
12843 goto done;
12846 error = got_ref_resolve(&head_commit_id, repo, branch);
12847 got_ref_close(branch);
12848 branch = NULL;
12849 if (error)
12850 goto done;
12852 error = got_object_open_as_commit(&commit, repo,
12853 head_commit_id);
12854 if (error)
12855 goto done;
12856 parent_ids = got_object_commit_get_parent_ids(commit);
12857 pid = STAILQ_FIRST(parent_ids);
12858 if (pid == NULL) {
12859 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12860 goto done;
12862 error = collect_commits(&commits, head_commit_id, &pid->id,
12863 got_worktree_get_base_commit_id(worktree),
12864 got_worktree_get_path_prefix(worktree),
12865 GOT_ERR_HISTEDIT_PATH, repo);
12866 got_object_commit_close(commit);
12867 commit = NULL;
12868 if (error)
12869 goto done;
12871 if (STAILQ_EMPTY(&commits)) {
12872 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12873 goto done;
12876 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12877 &base_commit_id, &fileindex, worktree, repo);
12878 if (error)
12879 goto done;
12881 if (edit_script_path) {
12882 error = histedit_load_list(&histedit_cmds,
12883 edit_script_path, repo);
12884 if (error) {
12885 got_worktree_histedit_abort(worktree, fileindex,
12886 repo, branch, base_commit_id,
12887 abort_progress, &upa);
12888 print_merge_progress_stats(&upa);
12889 goto done;
12891 } else {
12892 const char *branch_name;
12893 branch_name = got_ref_get_symref_target(branch);
12894 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12895 branch_name += 11;
12896 error = histedit_edit_script(&histedit_cmds, &commits,
12897 branch_name, edit_logmsg_only, fold_only,
12898 drop_only, edit_only, repo);
12899 if (error) {
12900 got_worktree_histedit_abort(worktree, fileindex,
12901 repo, branch, base_commit_id,
12902 abort_progress, &upa);
12903 print_merge_progress_stats(&upa);
12904 goto done;
12909 error = histedit_save_list(&histedit_cmds, worktree,
12910 repo);
12911 if (error) {
12912 got_worktree_histedit_abort(worktree, fileindex,
12913 repo, branch, base_commit_id,
12914 abort_progress, &upa);
12915 print_merge_progress_stats(&upa);
12916 goto done;
12921 error = histedit_check_script(&histedit_cmds, &commits, repo);
12922 if (error)
12923 goto done;
12925 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12926 if (resume_commit_id) {
12927 if (got_object_id_cmp(hle->commit_id,
12928 resume_commit_id) != 0)
12929 continue;
12931 resume_commit_id = NULL;
12932 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12933 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12934 error = histedit_skip_commit(hle, worktree,
12935 repo);
12936 if (error)
12937 goto done;
12938 } else {
12939 struct got_pathlist_head paths;
12940 int have_changes = 0;
12942 TAILQ_INIT(&paths);
12943 error = got_pathlist_append(&paths, "", NULL);
12944 if (error)
12945 goto done;
12946 error = got_worktree_status(worktree, &paths,
12947 repo, 0, check_local_changes, &have_changes,
12948 check_cancelled, NULL);
12949 got_pathlist_free(&paths,
12950 GOT_PATHLIST_FREE_NONE);
12951 if (error) {
12952 if (error->code != GOT_ERR_CANCELLED)
12953 goto done;
12954 if (sigint_received || sigpipe_received)
12955 goto done;
12957 if (have_changes) {
12958 error = histedit_commit(NULL, worktree,
12959 fileindex, tmp_branch, hle,
12960 committer, allow_conflict, repo);
12961 if (error)
12962 goto done;
12963 } else {
12964 error = got_object_open_as_commit(
12965 &commit, repo, hle->commit_id);
12966 if (error)
12967 goto done;
12968 error = show_histedit_progress(commit,
12969 hle, NULL);
12970 got_object_commit_close(commit);
12971 commit = NULL;
12972 if (error)
12973 goto done;
12976 continue;
12979 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12980 error = histedit_skip_commit(hle, worktree, repo);
12981 if (error)
12982 goto done;
12983 continue;
12986 error = got_object_open_as_commit(&commit, repo,
12987 hle->commit_id);
12988 if (error)
12989 goto done;
12990 parent_ids = got_object_commit_get_parent_ids(commit);
12991 pid = STAILQ_FIRST(parent_ids);
12993 error = got_worktree_histedit_merge_files(&merged_paths,
12994 worktree, fileindex, &pid->id, hle->commit_id, repo,
12995 update_progress, &upa, check_cancelled, NULL);
12996 if (error)
12997 goto done;
12998 got_object_commit_close(commit);
12999 commit = NULL;
13001 print_merge_progress_stats(&upa);
13002 if (upa.conflicts > 0 || upa.missing > 0 ||
13003 upa.not_deleted > 0 || upa.unversioned > 0) {
13004 if (upa.conflicts > 0) {
13005 error = show_rebase_merge_conflict(
13006 hle->commit_id, repo);
13007 if (error)
13008 goto done;
13010 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13011 break;
13014 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13015 char *id_str;
13016 error = got_object_id_str(&id_str, hle->commit_id);
13017 if (error)
13018 goto done;
13019 printf("Stopping histedit for amending commit %s\n",
13020 id_str);
13021 free(id_str);
13022 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13023 error = got_worktree_histedit_postpone(worktree,
13024 fileindex);
13025 goto done;
13028 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13029 error = histedit_skip_commit(hle, worktree, repo);
13030 if (error)
13031 goto done;
13032 continue;
13035 error = histedit_commit(&merged_paths, worktree, fileindex,
13036 tmp_branch, hle, committer, allow_conflict, repo);
13037 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13038 if (error)
13039 goto done;
13042 if (upa.conflicts > 0 || upa.missing > 0 ||
13043 upa.not_deleted > 0 || upa.unversioned > 0) {
13044 error = got_worktree_histedit_postpone(worktree, fileindex);
13045 if (error)
13046 goto done;
13047 if (upa.conflicts > 0 && upa.missing == 0 &&
13048 upa.not_deleted == 0 && upa.unversioned == 0) {
13049 error = got_error_msg(GOT_ERR_CONFLICTS,
13050 "conflicts must be resolved before histedit "
13051 "can continue");
13052 } else if (upa.conflicts > 0) {
13053 error = got_error_msg(GOT_ERR_CONFLICTS,
13054 "conflicts must be resolved before histedit "
13055 "can continue; changes destined for some "
13056 "files were not yet merged and should be "
13057 "merged manually if required before the "
13058 "histedit operation is continued");
13059 } else {
13060 error = got_error_msg(GOT_ERR_CONFLICTS,
13061 "changes destined for some files were not "
13062 "yet merged and should be merged manually "
13063 "if required before the histedit operation "
13064 "is continued");
13066 } else
13067 error = histedit_complete(worktree, fileindex, tmp_branch,
13068 branch, repo);
13069 done:
13070 free(cwd);
13071 free(committer);
13072 free(gitconfig_path);
13073 got_object_id_queue_free(&commits);
13074 histedit_free_list(&histedit_cmds);
13075 free(head_commit_id);
13076 free(base_commit_id);
13077 free(resume_commit_id);
13078 if (commit)
13079 got_object_commit_close(commit);
13080 if (branch)
13081 got_ref_close(branch);
13082 if (tmp_branch)
13083 got_ref_close(tmp_branch);
13084 if (worktree)
13085 got_worktree_close(worktree);
13086 if (repo) {
13087 const struct got_error *close_err = got_repo_close(repo);
13088 if (error == NULL)
13089 error = close_err;
13091 if (pack_fds) {
13092 const struct got_error *pack_err =
13093 got_repo_pack_fds_close(pack_fds);
13094 if (error == NULL)
13095 error = pack_err;
13097 return error;
13100 __dead static void
13101 usage_integrate(void)
13103 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13104 exit(1);
13107 static const struct got_error *
13108 cmd_integrate(int argc, char *argv[])
13110 const struct got_error *error = NULL;
13111 struct got_repository *repo = NULL;
13112 struct got_worktree *worktree = NULL;
13113 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13114 const char *branch_arg = NULL;
13115 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13116 struct got_fileindex *fileindex = NULL;
13117 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13118 int ch;
13119 struct got_update_progress_arg upa;
13120 int *pack_fds = NULL;
13122 #ifndef PROFILE
13123 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13124 "unveil", NULL) == -1)
13125 err(1, "pledge");
13126 #endif
13128 while ((ch = getopt(argc, argv, "")) != -1) {
13129 switch (ch) {
13130 default:
13131 usage_integrate();
13132 /* NOTREACHED */
13136 argc -= optind;
13137 argv += optind;
13139 if (argc != 1)
13140 usage_integrate();
13141 branch_arg = argv[0];
13143 cwd = getcwd(NULL, 0);
13144 if (cwd == NULL) {
13145 error = got_error_from_errno("getcwd");
13146 goto done;
13149 error = got_repo_pack_fds_open(&pack_fds);
13150 if (error != NULL)
13151 goto done;
13153 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13154 if (error) {
13155 if (error->code == GOT_ERR_NOT_WORKTREE)
13156 error = wrap_not_worktree_error(error, "integrate",
13157 cwd);
13158 goto done;
13161 error = check_rebase_or_histedit_in_progress(worktree);
13162 if (error)
13163 goto done;
13165 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13166 NULL, pack_fds);
13167 if (error != NULL)
13168 goto done;
13170 error = apply_unveil(got_repo_get_path(repo), 0,
13171 got_worktree_get_root_path(worktree));
13172 if (error)
13173 goto done;
13175 error = check_merge_in_progress(worktree, repo);
13176 if (error)
13177 goto done;
13179 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13180 error = got_error_from_errno("asprintf");
13181 goto done;
13184 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13185 &base_branch_ref, worktree, refname, repo);
13186 if (error)
13187 goto done;
13189 refname = strdup(got_ref_get_name(branch_ref));
13190 if (refname == NULL) {
13191 error = got_error_from_errno("strdup");
13192 got_worktree_integrate_abort(worktree, fileindex, repo,
13193 branch_ref, base_branch_ref);
13194 goto done;
13196 base_refname = strdup(got_ref_get_name(base_branch_ref));
13197 if (base_refname == NULL) {
13198 error = got_error_from_errno("strdup");
13199 got_worktree_integrate_abort(worktree, fileindex, repo,
13200 branch_ref, base_branch_ref);
13201 goto done;
13203 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13204 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13205 got_worktree_integrate_abort(worktree, fileindex, repo,
13206 branch_ref, base_branch_ref);
13207 goto done;
13210 error = got_ref_resolve(&commit_id, repo, branch_ref);
13211 if (error)
13212 goto done;
13214 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13215 if (error)
13216 goto done;
13218 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13219 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13220 "specified branch has already been integrated");
13221 got_worktree_integrate_abort(worktree, fileindex, repo,
13222 branch_ref, base_branch_ref);
13223 goto done;
13226 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13227 if (error) {
13228 if (error->code == GOT_ERR_ANCESTRY)
13229 error = got_error(GOT_ERR_REBASE_REQUIRED);
13230 got_worktree_integrate_abort(worktree, fileindex, repo,
13231 branch_ref, base_branch_ref);
13232 goto done;
13235 memset(&upa, 0, sizeof(upa));
13236 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13237 branch_ref, base_branch_ref, update_progress, &upa,
13238 check_cancelled, NULL);
13239 if (error)
13240 goto done;
13242 printf("Integrated %s into %s\n", refname, base_refname);
13243 print_update_progress_stats(&upa);
13244 done:
13245 if (repo) {
13246 const struct got_error *close_err = got_repo_close(repo);
13247 if (error == NULL)
13248 error = close_err;
13250 if (worktree)
13251 got_worktree_close(worktree);
13252 if (pack_fds) {
13253 const struct got_error *pack_err =
13254 got_repo_pack_fds_close(pack_fds);
13255 if (error == NULL)
13256 error = pack_err;
13258 free(cwd);
13259 free(base_commit_id);
13260 free(commit_id);
13261 free(refname);
13262 free(base_refname);
13263 return error;
13266 __dead static void
13267 usage_merge(void)
13269 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13270 exit(1);
13273 static const struct got_error *
13274 cmd_merge(int argc, char *argv[])
13276 const struct got_error *error = NULL;
13277 struct got_worktree *worktree = NULL;
13278 struct got_repository *repo = NULL;
13279 struct got_fileindex *fileindex = NULL;
13280 char *cwd = NULL, *id_str = NULL, *author = NULL;
13281 char *gitconfig_path = NULL;
13282 struct got_reference *branch = NULL, *wt_branch = NULL;
13283 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13284 struct got_object_id *wt_branch_tip = NULL;
13285 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13286 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13287 struct got_update_progress_arg upa;
13288 struct got_object_id *merge_commit_id = NULL;
13289 char *branch_name = NULL;
13290 int *pack_fds = NULL;
13292 memset(&upa, 0, sizeof(upa));
13294 #ifndef PROFILE
13295 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13296 "unveil", NULL) == -1)
13297 err(1, "pledge");
13298 #endif
13300 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13301 switch (ch) {
13302 case 'a':
13303 abort_merge = 1;
13304 break;
13305 case 'C':
13306 allow_conflict = 1;
13307 break;
13308 case 'c':
13309 continue_merge = 1;
13310 break;
13311 case 'M':
13312 prefer_fast_forward = 0;
13313 break;
13314 case 'n':
13315 interrupt_merge = 1;
13316 break;
13317 default:
13318 usage_merge();
13319 /* NOTREACHED */
13323 argc -= optind;
13324 argv += optind;
13326 if (abort_merge) {
13327 if (continue_merge)
13328 option_conflict('a', 'c');
13329 if (!prefer_fast_forward)
13330 option_conflict('a', 'M');
13331 if (interrupt_merge)
13332 option_conflict('a', 'n');
13333 } else if (continue_merge) {
13334 if (!prefer_fast_forward)
13335 option_conflict('c', 'M');
13336 if (interrupt_merge)
13337 option_conflict('c', 'n');
13339 if (allow_conflict) {
13340 if (!continue_merge)
13341 errx(1, "-C option requires -c");
13343 if (abort_merge || continue_merge) {
13344 if (argc != 0)
13345 usage_merge();
13346 } else if (argc != 1)
13347 usage_merge();
13349 cwd = getcwd(NULL, 0);
13350 if (cwd == NULL) {
13351 error = got_error_from_errno("getcwd");
13352 goto done;
13355 error = got_repo_pack_fds_open(&pack_fds);
13356 if (error != NULL)
13357 goto done;
13359 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13360 if (error) {
13361 if (error->code == GOT_ERR_NOT_WORKTREE)
13362 error = wrap_not_worktree_error(error,
13363 "merge", cwd);
13364 goto done;
13367 error = get_gitconfig_path(&gitconfig_path);
13368 if (error)
13369 goto done;
13370 error = got_repo_open(&repo,
13371 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13372 gitconfig_path, pack_fds);
13373 if (error != NULL)
13374 goto done;
13376 if (worktree != NULL) {
13377 error = worktree_has_logmsg_ref("merge", worktree, repo);
13378 if (error)
13379 goto done;
13382 error = apply_unveil(got_repo_get_path(repo), 0,
13383 worktree ? got_worktree_get_root_path(worktree) : NULL);
13384 if (error)
13385 goto done;
13387 error = check_rebase_or_histedit_in_progress(worktree);
13388 if (error)
13389 goto done;
13391 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13392 repo);
13393 if (error)
13394 goto done;
13396 if (merge_in_progress && !(abort_merge || continue_merge)) {
13397 error = got_error(GOT_ERR_MERGE_BUSY);
13398 goto done;
13401 if (!merge_in_progress && (abort_merge || continue_merge)) {
13402 error = got_error(GOT_ERR_NOT_MERGING);
13403 goto done;
13406 if (abort_merge) {
13407 error = got_worktree_merge_continue(&branch_name,
13408 &branch_tip, &fileindex, worktree, repo);
13409 if (error)
13410 goto done;
13411 error = got_worktree_merge_abort(worktree, fileindex, repo,
13412 abort_progress, &upa);
13413 if (error)
13414 goto done;
13415 printf("Merge of %s aborted\n", branch_name);
13416 goto done; /* nothing else to do */
13419 if (strncmp(got_worktree_get_head_ref_name(worktree),
13420 "refs/heads/", 11) != 0) {
13421 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13422 "work tree's current branch %s is outside the "
13423 "\"refs/heads/\" reference namespace; "
13424 "update -b required",
13425 got_worktree_get_head_ref_name(worktree));
13426 goto done;
13429 error = get_author(&author, repo, worktree);
13430 if (error)
13431 goto done;
13433 error = got_ref_open(&wt_branch, repo,
13434 got_worktree_get_head_ref_name(worktree), 0);
13435 if (error)
13436 goto done;
13437 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13438 if (error)
13439 goto done;
13441 if (continue_merge) {
13442 struct got_object_id *base_commit_id;
13443 base_commit_id = got_worktree_get_base_commit_id(worktree);
13444 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13445 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13446 goto done;
13448 error = got_worktree_merge_continue(&branch_name,
13449 &branch_tip, &fileindex, worktree, repo);
13450 if (error)
13451 goto done;
13452 } else {
13453 error = got_ref_open(&branch, repo, argv[0], 0);
13454 if (error != NULL)
13455 goto done;
13456 branch_name = strdup(got_ref_get_name(branch));
13457 if (branch_name == NULL) {
13458 error = got_error_from_errno("strdup");
13459 goto done;
13461 error = got_ref_resolve(&branch_tip, repo, branch);
13462 if (error)
13463 goto done;
13466 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13467 wt_branch_tip, branch_tip, 0, repo,
13468 check_cancelled, NULL);
13469 if (error && error->code != GOT_ERR_ANCESTRY)
13470 goto done;
13472 if (!continue_merge) {
13473 error = check_path_prefix(wt_branch_tip, branch_tip,
13474 got_worktree_get_path_prefix(worktree),
13475 GOT_ERR_MERGE_PATH, repo);
13476 if (error)
13477 goto done;
13478 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13479 if (error)
13480 goto done;
13481 if (prefer_fast_forward && yca_id &&
13482 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13483 struct got_pathlist_head paths;
13484 if (interrupt_merge) {
13485 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13486 "there are no changes to merge since %s "
13487 "is already based on %s; merge cannot be "
13488 "interrupted for amending; -n",
13489 branch_name, got_ref_get_name(wt_branch));
13490 goto done;
13492 printf("Forwarding %s to %s\n",
13493 got_ref_get_name(wt_branch), branch_name);
13494 error = got_ref_change_ref(wt_branch, branch_tip);
13495 if (error)
13496 goto done;
13497 error = got_ref_write(wt_branch, repo);
13498 if (error)
13499 goto done;
13500 error = got_worktree_set_base_commit_id(worktree, repo,
13501 branch_tip);
13502 if (error)
13503 goto done;
13504 TAILQ_INIT(&paths);
13505 error = got_pathlist_append(&paths, "", NULL);
13506 if (error)
13507 goto done;
13508 error = got_worktree_checkout_files(worktree,
13509 &paths, repo, update_progress, &upa,
13510 check_cancelled, NULL);
13511 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13512 if (error)
13513 goto done;
13514 if (upa.did_something) {
13515 char *id_str;
13516 error = got_object_id_str(&id_str, branch_tip);
13517 if (error)
13518 goto done;
13519 printf("Updated to commit %s\n", id_str);
13520 free(id_str);
13521 } else
13522 printf("Already up-to-date\n");
13523 print_update_progress_stats(&upa);
13524 goto done;
13526 error = got_worktree_merge_write_refs(worktree, branch, repo);
13527 if (error)
13528 goto done;
13530 error = got_worktree_merge_branch(worktree, fileindex,
13531 yca_id, branch_tip, repo, update_progress, &upa,
13532 check_cancelled, NULL);
13533 if (error)
13534 goto done;
13535 print_merge_progress_stats(&upa);
13536 if (!upa.did_something) {
13537 error = got_worktree_merge_abort(worktree, fileindex,
13538 repo, abort_progress, &upa);
13539 if (error)
13540 goto done;
13541 printf("Already up-to-date\n");
13542 goto done;
13546 if (interrupt_merge) {
13547 error = got_worktree_merge_postpone(worktree, fileindex);
13548 if (error)
13549 goto done;
13550 printf("Merge of %s interrupted on request\n", branch_name);
13551 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13552 upa.not_deleted > 0 || upa.unversioned > 0) {
13553 error = got_worktree_merge_postpone(worktree, fileindex);
13554 if (error)
13555 goto done;
13556 if (upa.conflicts > 0 && upa.missing == 0 &&
13557 upa.not_deleted == 0 && upa.unversioned == 0) {
13558 error = got_error_msg(GOT_ERR_CONFLICTS,
13559 "conflicts must be resolved before merging "
13560 "can continue");
13561 } else if (upa.conflicts > 0) {
13562 error = got_error_msg(GOT_ERR_CONFLICTS,
13563 "conflicts must be resolved before merging "
13564 "can continue; changes destined for some "
13565 "files were not yet merged and "
13566 "should be merged manually if required before the "
13567 "merge operation is continued");
13568 } else {
13569 error = got_error_msg(GOT_ERR_CONFLICTS,
13570 "changes destined for some "
13571 "files were not yet merged and should be "
13572 "merged manually if required before the "
13573 "merge operation is continued");
13575 goto done;
13576 } else {
13577 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13578 fileindex, author, NULL, 1, branch_tip, branch_name,
13579 allow_conflict, repo, continue_merge ? print_status : NULL,
13580 NULL);
13581 if (error)
13582 goto done;
13583 error = got_worktree_merge_complete(worktree, fileindex, repo);
13584 if (error)
13585 goto done;
13586 error = got_object_id_str(&id_str, merge_commit_id);
13587 if (error)
13588 goto done;
13589 printf("Merged %s into %s: %s\n", branch_name,
13590 got_worktree_get_head_ref_name(worktree),
13591 id_str);
13594 done:
13595 free(gitconfig_path);
13596 free(id_str);
13597 free(merge_commit_id);
13598 free(author);
13599 free(branch_tip);
13600 free(branch_name);
13601 free(yca_id);
13602 if (branch)
13603 got_ref_close(branch);
13604 if (wt_branch)
13605 got_ref_close(wt_branch);
13606 if (worktree)
13607 got_worktree_close(worktree);
13608 if (repo) {
13609 const struct got_error *close_err = got_repo_close(repo);
13610 if (error == NULL)
13611 error = close_err;
13613 if (pack_fds) {
13614 const struct got_error *pack_err =
13615 got_repo_pack_fds_close(pack_fds);
13616 if (error == NULL)
13617 error = pack_err;
13619 return error;
13622 __dead static void
13623 usage_stage(void)
13625 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13626 "[path ...]\n", getprogname());
13627 exit(1);
13630 static const struct got_error *
13631 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13632 const char *path, struct got_object_id *blob_id,
13633 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13634 int dirfd, const char *de_name)
13636 const struct got_error *err = NULL;
13637 char *id_str = NULL;
13639 if (staged_status != GOT_STATUS_ADD &&
13640 staged_status != GOT_STATUS_MODIFY &&
13641 staged_status != GOT_STATUS_DELETE)
13642 return NULL;
13644 if (staged_status == GOT_STATUS_ADD ||
13645 staged_status == GOT_STATUS_MODIFY)
13646 err = got_object_id_str(&id_str, staged_blob_id);
13647 else
13648 err = got_object_id_str(&id_str, blob_id);
13649 if (err)
13650 return err;
13652 printf("%s %c %s\n", id_str, staged_status, path);
13653 free(id_str);
13654 return NULL;
13657 static const struct got_error *
13658 cmd_stage(int argc, char *argv[])
13660 const struct got_error *error = NULL;
13661 struct got_repository *repo = NULL;
13662 struct got_worktree *worktree = NULL;
13663 char *cwd = NULL;
13664 struct got_pathlist_head paths;
13665 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13666 FILE *patch_script_file = NULL;
13667 const char *patch_script_path = NULL;
13668 struct choose_patch_arg cpa;
13669 int *pack_fds = NULL;
13671 TAILQ_INIT(&paths);
13673 #ifndef PROFILE
13674 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13675 "unveil", NULL) == -1)
13676 err(1, "pledge");
13677 #endif
13679 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13680 switch (ch) {
13681 case 'F':
13682 patch_script_path = optarg;
13683 break;
13684 case 'l':
13685 list_stage = 1;
13686 break;
13687 case 'p':
13688 pflag = 1;
13689 break;
13690 case 'S':
13691 allow_bad_symlinks = 1;
13692 break;
13693 default:
13694 usage_stage();
13695 /* NOTREACHED */
13699 argc -= optind;
13700 argv += optind;
13702 if (list_stage && (pflag || patch_script_path))
13703 errx(1, "-l option cannot be used with other options");
13704 if (patch_script_path && !pflag)
13705 errx(1, "-F option can only be used together with -p option");
13707 cwd = getcwd(NULL, 0);
13708 if (cwd == NULL) {
13709 error = got_error_from_errno("getcwd");
13710 goto done;
13713 error = got_repo_pack_fds_open(&pack_fds);
13714 if (error != NULL)
13715 goto done;
13717 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13718 if (error) {
13719 if (error->code == GOT_ERR_NOT_WORKTREE)
13720 error = wrap_not_worktree_error(error, "stage", cwd);
13721 goto done;
13724 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13725 NULL, pack_fds);
13726 if (error != NULL)
13727 goto done;
13729 if (patch_script_path) {
13730 patch_script_file = fopen(patch_script_path, "re");
13731 if (patch_script_file == NULL) {
13732 error = got_error_from_errno2("fopen",
13733 patch_script_path);
13734 goto done;
13737 error = apply_unveil(got_repo_get_path(repo), 0,
13738 got_worktree_get_root_path(worktree));
13739 if (error)
13740 goto done;
13742 error = check_merge_in_progress(worktree, repo);
13743 if (error)
13744 goto done;
13746 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13747 if (error)
13748 goto done;
13750 if (list_stage)
13751 error = got_worktree_status(worktree, &paths, repo, 0,
13752 print_stage, NULL, check_cancelled, NULL);
13753 else {
13754 cpa.patch_script_file = patch_script_file;
13755 cpa.action = "stage";
13756 error = got_worktree_stage(worktree, &paths,
13757 pflag ? NULL : print_status, NULL,
13758 pflag ? choose_patch : NULL, &cpa,
13759 allow_bad_symlinks, repo);
13761 done:
13762 if (patch_script_file && fclose(patch_script_file) == EOF &&
13763 error == NULL)
13764 error = got_error_from_errno2("fclose", patch_script_path);
13765 if (repo) {
13766 const struct got_error *close_err = got_repo_close(repo);
13767 if (error == NULL)
13768 error = close_err;
13770 if (worktree)
13771 got_worktree_close(worktree);
13772 if (pack_fds) {
13773 const struct got_error *pack_err =
13774 got_repo_pack_fds_close(pack_fds);
13775 if (error == NULL)
13776 error = pack_err;
13778 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13779 free(cwd);
13780 return error;
13783 __dead static void
13784 usage_unstage(void)
13786 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13787 "[path ...]\n", getprogname());
13788 exit(1);
13792 static const struct got_error *
13793 cmd_unstage(int argc, char *argv[])
13795 const struct got_error *error = NULL;
13796 struct got_repository *repo = NULL;
13797 struct got_worktree *worktree = NULL;
13798 char *cwd = NULL;
13799 struct got_pathlist_head paths;
13800 int ch, pflag = 0;
13801 struct got_update_progress_arg upa;
13802 FILE *patch_script_file = NULL;
13803 const char *patch_script_path = NULL;
13804 struct choose_patch_arg cpa;
13805 int *pack_fds = NULL;
13807 TAILQ_INIT(&paths);
13809 #ifndef PROFILE
13810 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13811 "unveil", NULL) == -1)
13812 err(1, "pledge");
13813 #endif
13815 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13816 switch (ch) {
13817 case 'F':
13818 patch_script_path = optarg;
13819 break;
13820 case 'p':
13821 pflag = 1;
13822 break;
13823 default:
13824 usage_unstage();
13825 /* NOTREACHED */
13829 argc -= optind;
13830 argv += optind;
13832 if (patch_script_path && !pflag)
13833 errx(1, "-F option can only be used together with -p option");
13835 cwd = getcwd(NULL, 0);
13836 if (cwd == NULL) {
13837 error = got_error_from_errno("getcwd");
13838 goto done;
13841 error = got_repo_pack_fds_open(&pack_fds);
13842 if (error != NULL)
13843 goto done;
13845 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13846 if (error) {
13847 if (error->code == GOT_ERR_NOT_WORKTREE)
13848 error = wrap_not_worktree_error(error, "unstage", cwd);
13849 goto done;
13852 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13853 NULL, pack_fds);
13854 if (error != NULL)
13855 goto done;
13857 if (patch_script_path) {
13858 patch_script_file = fopen(patch_script_path, "re");
13859 if (patch_script_file == NULL) {
13860 error = got_error_from_errno2("fopen",
13861 patch_script_path);
13862 goto done;
13866 error = apply_unveil(got_repo_get_path(repo), 0,
13867 got_worktree_get_root_path(worktree));
13868 if (error)
13869 goto done;
13871 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13872 if (error)
13873 goto done;
13875 cpa.patch_script_file = patch_script_file;
13876 cpa.action = "unstage";
13877 memset(&upa, 0, sizeof(upa));
13878 error = got_worktree_unstage(worktree, &paths, update_progress,
13879 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13880 if (!error)
13881 print_merge_progress_stats(&upa);
13882 done:
13883 if (patch_script_file && fclose(patch_script_file) == EOF &&
13884 error == NULL)
13885 error = got_error_from_errno2("fclose", patch_script_path);
13886 if (repo) {
13887 const struct got_error *close_err = got_repo_close(repo);
13888 if (error == NULL)
13889 error = close_err;
13891 if (worktree)
13892 got_worktree_close(worktree);
13893 if (pack_fds) {
13894 const struct got_error *pack_err =
13895 got_repo_pack_fds_close(pack_fds);
13896 if (error == NULL)
13897 error = pack_err;
13899 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13900 free(cwd);
13901 return error;
13904 __dead static void
13905 usage_cat(void)
13907 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13908 "arg ...\n", getprogname());
13909 exit(1);
13912 static const struct got_error *
13913 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13915 const struct got_error *err;
13916 struct got_blob_object *blob;
13917 int fd = -1;
13919 fd = got_opentempfd();
13920 if (fd == -1)
13921 return got_error_from_errno("got_opentempfd");
13923 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13924 if (err)
13925 goto done;
13927 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13928 done:
13929 if (fd != -1 && close(fd) == -1 && err == NULL)
13930 err = got_error_from_errno("close");
13931 if (blob)
13932 got_object_blob_close(blob);
13933 return err;
13936 static const struct got_error *
13937 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13939 const struct got_error *err;
13940 struct got_tree_object *tree;
13941 int nentries, i;
13943 err = got_object_open_as_tree(&tree, repo, id);
13944 if (err)
13945 return err;
13947 nentries = got_object_tree_get_nentries(tree);
13948 for (i = 0; i < nentries; i++) {
13949 struct got_tree_entry *te;
13950 char *id_str;
13951 if (sigint_received || sigpipe_received)
13952 break;
13953 te = got_object_tree_get_entry(tree, i);
13954 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13955 if (err)
13956 break;
13957 fprintf(outfile, "%s %.7o %s\n", id_str,
13958 got_tree_entry_get_mode(te),
13959 got_tree_entry_get_name(te));
13960 free(id_str);
13963 got_object_tree_close(tree);
13964 return err;
13967 static const struct got_error *
13968 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13970 const struct got_error *err;
13971 struct got_commit_object *commit;
13972 const struct got_object_id_queue *parent_ids;
13973 struct got_object_qid *pid;
13974 char *id_str = NULL;
13975 const char *logmsg = NULL;
13976 char gmtoff[6];
13978 err = got_object_open_as_commit(&commit, repo, id);
13979 if (err)
13980 return err;
13982 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13983 if (err)
13984 goto done;
13986 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13987 parent_ids = got_object_commit_get_parent_ids(commit);
13988 fprintf(outfile, "numparents %d\n",
13989 got_object_commit_get_nparents(commit));
13990 STAILQ_FOREACH(pid, parent_ids, entry) {
13991 char *pid_str;
13992 err = got_object_id_str(&pid_str, &pid->id);
13993 if (err)
13994 goto done;
13995 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13996 free(pid_str);
13998 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13999 got_object_commit_get_author_gmtoff(commit));
14000 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14001 got_object_commit_get_author(commit),
14002 (long long)got_object_commit_get_author_time(commit),
14003 gmtoff);
14005 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14006 got_object_commit_get_committer_gmtoff(commit));
14007 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14008 got_object_commit_get_committer(commit),
14009 (long long)got_object_commit_get_committer_time(commit),
14010 gmtoff);
14012 logmsg = got_object_commit_get_logmsg_raw(commit);
14013 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14014 fprintf(outfile, "%s", logmsg);
14015 done:
14016 free(id_str);
14017 got_object_commit_close(commit);
14018 return err;
14021 static const struct got_error *
14022 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14024 const struct got_error *err;
14025 struct got_tag_object *tag;
14026 char *id_str = NULL;
14027 const char *tagmsg = NULL;
14028 char gmtoff[6];
14030 err = got_object_open_as_tag(&tag, repo, id);
14031 if (err)
14032 return err;
14034 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14035 if (err)
14036 goto done;
14038 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14040 switch (got_object_tag_get_object_type(tag)) {
14041 case GOT_OBJ_TYPE_BLOB:
14042 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14043 GOT_OBJ_LABEL_BLOB);
14044 break;
14045 case GOT_OBJ_TYPE_TREE:
14046 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14047 GOT_OBJ_LABEL_TREE);
14048 break;
14049 case GOT_OBJ_TYPE_COMMIT:
14050 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14051 GOT_OBJ_LABEL_COMMIT);
14052 break;
14053 case GOT_OBJ_TYPE_TAG:
14054 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14055 GOT_OBJ_LABEL_TAG);
14056 break;
14057 default:
14058 break;
14061 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14062 got_object_tag_get_name(tag));
14064 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14065 got_object_tag_get_tagger_gmtoff(tag));
14066 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14067 got_object_tag_get_tagger(tag),
14068 (long long)got_object_tag_get_tagger_time(tag),
14069 gmtoff);
14071 tagmsg = got_object_tag_get_message(tag);
14072 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14073 fprintf(outfile, "%s", tagmsg);
14074 done:
14075 free(id_str);
14076 got_object_tag_close(tag);
14077 return err;
14080 static const struct got_error *
14081 cmd_cat(int argc, char *argv[])
14083 const struct got_error *error;
14084 struct got_repository *repo = NULL;
14085 struct got_worktree *worktree = NULL;
14086 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14087 char *keyword_idstr = NULL;
14088 const char *commit_id_str = NULL;
14089 struct got_object_id *id = NULL, *commit_id = NULL;
14090 struct got_commit_object *commit = NULL;
14091 int ch, obj_type, i, force_path = 0;
14092 struct got_reflist_head refs;
14093 int *pack_fds = NULL;
14095 TAILQ_INIT(&refs);
14097 #ifndef PROFILE
14098 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14099 NULL) == -1)
14100 err(1, "pledge");
14101 #endif
14103 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14104 switch (ch) {
14105 case 'c':
14106 commit_id_str = optarg;
14107 break;
14108 case 'P':
14109 force_path = 1;
14110 break;
14111 case 'r':
14112 repo_path = realpath(optarg, NULL);
14113 if (repo_path == NULL)
14114 return got_error_from_errno2("realpath",
14115 optarg);
14116 got_path_strip_trailing_slashes(repo_path);
14117 break;
14118 default:
14119 usage_cat();
14120 /* NOTREACHED */
14124 argc -= optind;
14125 argv += optind;
14127 cwd = getcwd(NULL, 0);
14128 if (cwd == NULL) {
14129 error = got_error_from_errno("getcwd");
14130 goto done;
14133 error = got_repo_pack_fds_open(&pack_fds);
14134 if (error != NULL)
14135 goto done;
14137 if (repo_path == NULL) {
14138 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14139 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14140 goto done;
14141 if (worktree) {
14142 repo_path = strdup(
14143 got_worktree_get_repo_path(worktree));
14144 if (repo_path == NULL) {
14145 error = got_error_from_errno("strdup");
14146 goto done;
14149 if (commit_id_str == NULL) {
14150 /* Release work tree lock. */
14151 got_worktree_close(worktree);
14152 worktree = NULL;
14157 if (repo_path == NULL) {
14158 repo_path = strdup(cwd);
14159 if (repo_path == NULL)
14160 return got_error_from_errno("strdup");
14163 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14164 free(repo_path);
14165 if (error != NULL)
14166 goto done;
14168 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14169 if (error)
14170 goto done;
14172 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14173 if (error)
14174 goto done;
14176 if (commit_id_str != NULL) {
14177 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14178 repo, worktree);
14179 if (error != NULL)
14180 goto done;
14181 if (keyword_idstr != NULL)
14182 commit_id_str = keyword_idstr;
14183 if (worktree != NULL) {
14184 got_worktree_close(worktree);
14185 worktree = NULL;
14187 } else
14188 commit_id_str = GOT_REF_HEAD;
14189 error = got_repo_match_object_id(&commit_id, NULL,
14190 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14191 if (error)
14192 goto done;
14194 error = got_object_open_as_commit(&commit, repo, commit_id);
14195 if (error)
14196 goto done;
14198 for (i = 0; i < argc; i++) {
14199 if (force_path) {
14200 error = got_object_id_by_path(&id, repo, commit,
14201 argv[i]);
14202 if (error)
14203 break;
14204 } else {
14205 error = got_repo_match_object_id(&id, &label, argv[i],
14206 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14207 repo);
14208 if (error) {
14209 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14210 error->code != GOT_ERR_NOT_REF)
14211 break;
14212 error = got_object_id_by_path(&id, repo,
14213 commit, argv[i]);
14214 if (error)
14215 break;
14219 error = got_object_get_type(&obj_type, repo, id);
14220 if (error)
14221 break;
14223 switch (obj_type) {
14224 case GOT_OBJ_TYPE_BLOB:
14225 error = cat_blob(id, repo, stdout);
14226 break;
14227 case GOT_OBJ_TYPE_TREE:
14228 error = cat_tree(id, repo, stdout);
14229 break;
14230 case GOT_OBJ_TYPE_COMMIT:
14231 error = cat_commit(id, repo, stdout);
14232 break;
14233 case GOT_OBJ_TYPE_TAG:
14234 error = cat_tag(id, repo, stdout);
14235 break;
14236 default:
14237 error = got_error(GOT_ERR_OBJ_TYPE);
14238 break;
14240 if (error)
14241 break;
14242 free(label);
14243 label = NULL;
14244 free(id);
14245 id = NULL;
14247 done:
14248 free(label);
14249 free(id);
14250 free(commit_id);
14251 free(keyword_idstr);
14252 if (commit)
14253 got_object_commit_close(commit);
14254 if (worktree)
14255 got_worktree_close(worktree);
14256 if (repo) {
14257 const struct got_error *close_err = got_repo_close(repo);
14258 if (error == NULL)
14259 error = close_err;
14261 if (pack_fds) {
14262 const struct got_error *pack_err =
14263 got_repo_pack_fds_close(pack_fds);
14264 if (error == NULL)
14265 error = pack_err;
14268 got_ref_list_free(&refs);
14269 return error;
14272 __dead static void
14273 usage_info(void)
14275 fprintf(stderr, "usage: %s info [path ...]\n",
14276 getprogname());
14277 exit(1);
14280 static const struct got_error *
14281 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14282 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14283 struct got_object_id *commit_id)
14285 const struct got_error *err = NULL;
14286 char *id_str = NULL;
14287 char datebuf[128];
14288 struct tm mytm, *tm;
14289 struct got_pathlist_head *paths = arg;
14290 struct got_pathlist_entry *pe;
14293 * Clear error indication from any of the path arguments which
14294 * would cause this file index entry to be displayed.
14296 TAILQ_FOREACH(pe, paths, entry) {
14297 if (got_path_cmp(path, pe->path, strlen(path),
14298 pe->path_len) == 0 ||
14299 got_path_is_child(path, pe->path, pe->path_len))
14300 pe->data = NULL; /* no error */
14303 printf(GOT_COMMIT_SEP_STR);
14304 if (S_ISLNK(mode))
14305 printf("symlink: %s\n", path);
14306 else if (S_ISREG(mode)) {
14307 printf("file: %s\n", path);
14308 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14309 } else if (S_ISDIR(mode))
14310 printf("directory: %s\n", path);
14311 else
14312 printf("something: %s\n", path);
14314 tm = localtime_r(&mtime, &mytm);
14315 if (tm == NULL)
14316 return NULL;
14317 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14318 return got_error(GOT_ERR_NO_SPACE);
14319 printf("timestamp: %s\n", datebuf);
14321 if (blob_id) {
14322 err = got_object_id_str(&id_str, blob_id);
14323 if (err)
14324 return err;
14325 printf("based on blob: %s\n", id_str);
14326 free(id_str);
14329 if (staged_blob_id) {
14330 err = got_object_id_str(&id_str, staged_blob_id);
14331 if (err)
14332 return err;
14333 printf("based on staged blob: %s\n", id_str);
14334 free(id_str);
14337 if (commit_id) {
14338 err = got_object_id_str(&id_str, commit_id);
14339 if (err)
14340 return err;
14341 printf("based on commit: %s\n", id_str);
14342 free(id_str);
14345 return NULL;
14348 static const struct got_error *
14349 cmd_info(int argc, char *argv[])
14351 const struct got_error *error = NULL;
14352 struct got_worktree *worktree = NULL;
14353 char *cwd = NULL, *id_str = NULL;
14354 struct got_pathlist_head paths;
14355 char *uuidstr = NULL;
14356 int ch, show_files = 0;
14358 TAILQ_INIT(&paths);
14360 #ifndef PROFILE
14361 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14362 NULL) == -1)
14363 err(1, "pledge");
14364 #endif
14366 while ((ch = getopt(argc, argv, "")) != -1) {
14367 switch (ch) {
14368 default:
14369 usage_info();
14370 /* NOTREACHED */
14374 argc -= optind;
14375 argv += optind;
14377 cwd = getcwd(NULL, 0);
14378 if (cwd == NULL) {
14379 error = got_error_from_errno("getcwd");
14380 goto done;
14383 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14384 if (error) {
14385 if (error->code == GOT_ERR_NOT_WORKTREE)
14386 error = wrap_not_worktree_error(error, "info", cwd);
14387 goto done;
14390 #ifndef PROFILE
14391 /* Remove "wpath cpath proc exec sendfd" promises. */
14392 if (pledge("stdio rpath flock unveil", NULL) == -1)
14393 err(1, "pledge");
14394 #endif
14395 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14396 if (error)
14397 goto done;
14399 if (argc >= 1) {
14400 error = get_worktree_paths_from_argv(&paths, argc, argv,
14401 worktree);
14402 if (error)
14403 goto done;
14404 show_files = 1;
14407 error = got_object_id_str(&id_str,
14408 got_worktree_get_base_commit_id(worktree));
14409 if (error)
14410 goto done;
14412 error = got_worktree_get_uuid(&uuidstr, worktree);
14413 if (error)
14414 goto done;
14416 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14417 printf("work tree base commit: %s\n", id_str);
14418 printf("work tree path prefix: %s\n",
14419 got_worktree_get_path_prefix(worktree));
14420 printf("work tree branch reference: %s\n",
14421 got_worktree_get_head_ref_name(worktree));
14422 printf("work tree UUID: %s\n", uuidstr);
14423 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14425 if (show_files) {
14426 struct got_pathlist_entry *pe;
14427 TAILQ_FOREACH(pe, &paths, entry) {
14428 if (pe->path_len == 0)
14429 continue;
14431 * Assume this path will fail. This will be corrected
14432 * in print_path_info() in case the path does suceeed.
14434 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14436 error = got_worktree_path_info(worktree, &paths,
14437 print_path_info, &paths, check_cancelled, NULL);
14438 if (error)
14439 goto done;
14440 TAILQ_FOREACH(pe, &paths, entry) {
14441 if (pe->data != NULL) {
14442 const struct got_error *perr;
14444 perr = pe->data;
14445 error = got_error_fmt(perr->code, "%s",
14446 pe->path);
14447 break;
14451 done:
14452 if (worktree)
14453 got_worktree_close(worktree);
14454 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14455 free(cwd);
14456 free(id_str);
14457 free(uuidstr);
14458 return error;