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) ||
4464 (show_diffstat && !show_patch))
4465 && !reverse_display_order) {
4466 err = get_changed_paths(&changed_paths, commit, repo,
4467 show_diffstat ? &dsa : NULL);
4468 if (err)
4469 break;
4472 if (search_pattern) {
4473 err = match_commit(&have_match, &id, commit, &regex);
4474 if (err) {
4475 got_object_commit_close(commit);
4476 break;
4478 if (have_match == 0 && show_changed_paths)
4479 match_changed_paths(&have_match,
4480 &changed_paths, &regex);
4481 if (have_match == 0 && show_patch) {
4482 err = match_patch(&have_match, commit, &id,
4483 path, diff_context, repo, &regex, tmpfile);
4484 if (err)
4485 break;
4487 if (have_match == 0) {
4488 got_object_commit_close(commit);
4489 got_pathlist_free(&changed_paths,
4490 GOT_PATHLIST_FREE_ALL);
4491 continue;
4495 if (reverse_display_order) {
4496 err = got_object_qid_alloc(&qid, &id);
4497 if (err)
4498 break;
4499 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4500 got_object_commit_close(commit);
4501 } else {
4502 if (one_line)
4503 err = print_commit_oneline(commit, &id,
4504 repo, refs_idmap);
4505 else
4506 err = print_commit(commit, &id, repo, path,
4507 (show_changed_paths || show_diffstat) ?
4508 &changed_paths : NULL,
4509 show_diffstat ? &dsa : NULL, show_patch,
4510 diff_context, refs_idmap, NULL, NULL);
4511 got_object_commit_close(commit);
4512 if (err)
4513 break;
4515 if ((limit && --limit == 0) ||
4516 (end_id && got_object_id_cmp(&id, end_id) == 0))
4517 break;
4519 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4521 if (reverse_display_order) {
4522 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4523 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4524 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4526 err = got_object_open_as_commit(&commit, repo,
4527 &qid->id);
4528 if (err)
4529 break;
4530 if ((show_changed_paths && !show_diffstat) ||
4531 (show_diffstat && !show_patch)) {
4532 err = get_changed_paths(&changed_paths, commit,
4533 repo, show_diffstat ? &dsa : NULL);
4534 if (err)
4535 break;
4537 if (one_line)
4538 err = print_commit_oneline(commit, &qid->id,
4539 repo, refs_idmap);
4540 else
4541 err = print_commit(commit, &qid->id, repo, path,
4542 (show_changed_paths || show_diffstat) ?
4543 &changed_paths : NULL,
4544 show_diffstat ? &dsa : NULL, show_patch,
4545 diff_context, refs_idmap, NULL, NULL);
4546 got_object_commit_close(commit);
4547 if (err)
4548 break;
4549 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4552 done:
4553 while (!STAILQ_EMPTY(&reversed_commits)) {
4554 qid = STAILQ_FIRST(&reversed_commits);
4555 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4556 got_object_qid_free(qid);
4558 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4559 if (search_pattern)
4560 regfree(&regex);
4561 got_commit_graph_close(graph);
4562 return err;
4565 __dead static void
4566 usage_log(void)
4568 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4569 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4570 "[path]\n", getprogname());
4571 exit(1);
4574 static int
4575 get_default_log_limit(void)
4577 const char *got_default_log_limit;
4578 long long n;
4579 const char *errstr;
4581 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4582 if (got_default_log_limit == NULL)
4583 return 0;
4584 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4585 if (errstr != NULL)
4586 return 0;
4587 return n;
4590 static const struct got_error *
4591 cmd_log(int argc, char *argv[])
4593 const struct got_error *error;
4594 struct got_repository *repo = NULL;
4595 struct got_worktree *worktree = NULL;
4596 struct got_object_id *start_id = NULL, *end_id = NULL;
4597 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4598 char *keyword_idstr = NULL;
4599 const char *start_commit = NULL, *end_commit = NULL;
4600 const char *search_pattern = NULL;
4601 int diff_context = -1, ch;
4602 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4603 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4604 const char *errstr;
4605 struct got_reflist_head refs;
4606 struct got_reflist_object_id_map *refs_idmap = NULL;
4607 FILE *tmpfile = NULL;
4608 int *pack_fds = NULL;
4610 TAILQ_INIT(&refs);
4612 #ifndef PROFILE
4613 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4614 NULL)
4615 == -1)
4616 err(1, "pledge");
4617 #endif
4619 limit = get_default_log_limit();
4621 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4622 switch (ch) {
4623 case 'b':
4624 log_branches = 1;
4625 break;
4626 case 'C':
4627 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4628 &errstr);
4629 if (errstr != NULL)
4630 errx(1, "number of context lines is %s: %s",
4631 errstr, optarg);
4632 break;
4633 case 'c':
4634 start_commit = optarg;
4635 break;
4636 case 'd':
4637 show_diffstat = 1;
4638 break;
4639 case 'l':
4640 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4641 if (errstr != NULL)
4642 errx(1, "number of commits is %s: %s",
4643 errstr, optarg);
4644 break;
4645 case 'P':
4646 show_changed_paths = 1;
4647 break;
4648 case 'p':
4649 show_patch = 1;
4650 break;
4651 case 'R':
4652 reverse_display_order = 1;
4653 break;
4654 case 'r':
4655 repo_path = realpath(optarg, NULL);
4656 if (repo_path == NULL)
4657 return got_error_from_errno2("realpath",
4658 optarg);
4659 got_path_strip_trailing_slashes(repo_path);
4660 break;
4661 case 'S':
4662 search_pattern = optarg;
4663 break;
4664 case 's':
4665 one_line = 1;
4666 break;
4667 case 'x':
4668 end_commit = optarg;
4669 break;
4670 default:
4671 usage_log();
4672 /* NOTREACHED */
4676 argc -= optind;
4677 argv += optind;
4679 if (diff_context == -1)
4680 diff_context = 3;
4681 else if (!show_patch)
4682 errx(1, "-C requires -p");
4684 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4685 errx(1, "cannot use -s with -d, -p or -P");
4687 cwd = getcwd(NULL, 0);
4688 if (cwd == NULL) {
4689 error = got_error_from_errno("getcwd");
4690 goto done;
4693 error = got_repo_pack_fds_open(&pack_fds);
4694 if (error != NULL)
4695 goto done;
4697 if (repo_path == NULL) {
4698 error = got_worktree_open(&worktree, cwd,
4699 GOT_WORKTREE_GOT_DIR);
4700 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4701 goto done;
4702 error = NULL;
4705 if (argc == 1) {
4706 if (worktree) {
4707 error = got_worktree_resolve_path(&path, worktree,
4708 argv[0]);
4709 if (error)
4710 goto done;
4711 } else {
4712 path = strdup(argv[0]);
4713 if (path == NULL) {
4714 error = got_error_from_errno("strdup");
4715 goto done;
4718 } else if (argc != 0)
4719 usage_log();
4721 if (repo_path == NULL) {
4722 repo_path = worktree ?
4723 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4725 if (repo_path == NULL) {
4726 error = got_error_from_errno("strdup");
4727 goto done;
4730 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4731 if (error != NULL)
4732 goto done;
4734 error = apply_unveil(got_repo_get_path(repo), 1,
4735 worktree ? got_worktree_get_root_path(worktree) : NULL);
4736 if (error)
4737 goto done;
4739 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4740 if (error)
4741 goto done;
4743 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4744 if (error)
4745 goto done;
4747 if (start_commit == NULL) {
4748 struct got_reference *head_ref;
4749 struct got_commit_object *commit = NULL;
4750 error = got_ref_open(&head_ref, repo,
4751 worktree ? got_worktree_get_head_ref_name(worktree)
4752 : GOT_REF_HEAD, 0);
4753 if (error != NULL)
4754 goto done;
4755 error = got_ref_resolve(&start_id, repo, head_ref);
4756 got_ref_close(head_ref);
4757 if (error != NULL)
4758 goto done;
4759 error = got_object_open_as_commit(&commit, repo,
4760 start_id);
4761 if (error != NULL)
4762 goto done;
4763 got_object_commit_close(commit);
4764 } else {
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 if (error != NULL)
4775 goto done;
4777 if (end_commit != NULL) {
4778 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4779 repo, worktree);
4780 if (error != NULL)
4781 goto done;
4782 if (keyword_idstr != NULL)
4783 end_commit = keyword_idstr;
4785 error = got_repo_match_object_id(&end_id, NULL,
4786 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4787 if (error != NULL)
4788 goto done;
4791 if (worktree) {
4793 * If a path was specified on the command line it was resolved
4794 * to a path in the work tree above. Prepend the work tree's
4795 * path prefix to obtain the corresponding in-repository path.
4797 if (path) {
4798 const char *prefix;
4799 prefix = got_worktree_get_path_prefix(worktree);
4800 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4801 (path[0] != '\0') ? "/" : "", path) == -1) {
4802 error = got_error_from_errno("asprintf");
4803 goto done;
4806 } else
4807 error = got_repo_map_path(&in_repo_path, repo,
4808 path ? path : "");
4809 if (error != NULL)
4810 goto done;
4811 if (in_repo_path) {
4812 free(path);
4813 path = in_repo_path;
4816 if (worktree) {
4817 /* Release work tree lock. */
4818 got_worktree_close(worktree);
4819 worktree = NULL;
4822 if (search_pattern && show_patch) {
4823 tmpfile = got_opentemp();
4824 if (tmpfile == NULL) {
4825 error = got_error_from_errno("got_opentemp");
4826 goto done;
4830 error = print_commits(start_id, end_id, repo, path ? path : "",
4831 show_changed_paths, show_diffstat, show_patch, search_pattern,
4832 diff_context, limit, log_branches, reverse_display_order,
4833 refs_idmap, one_line, tmpfile);
4834 done:
4835 free(path);
4836 free(repo_path);
4837 free(cwd);
4838 free(start_id);
4839 free(end_id);
4840 free(keyword_idstr);
4841 if (worktree)
4842 got_worktree_close(worktree);
4843 if (repo) {
4844 const struct got_error *close_err = got_repo_close(repo);
4845 if (error == NULL)
4846 error = close_err;
4848 if (pack_fds) {
4849 const struct got_error *pack_err =
4850 got_repo_pack_fds_close(pack_fds);
4851 if (error == NULL)
4852 error = pack_err;
4854 if (refs_idmap)
4855 got_reflist_object_id_map_free(refs_idmap);
4856 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4857 error = got_error_from_errno("fclose");
4858 got_ref_list_free(&refs);
4859 return error;
4862 __dead static void
4863 usage_diff(void)
4865 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4866 "[-r repository-path] [object1 object2 | path ...]\n",
4867 getprogname());
4868 exit(1);
4871 struct print_diff_arg {
4872 struct got_repository *repo;
4873 struct got_worktree *worktree;
4874 struct got_diffstat_cb_arg *diffstat;
4875 int diff_context;
4876 const char *id_str;
4877 int header_shown;
4878 int diff_staged;
4879 enum got_diff_algorithm diff_algo;
4880 int ignore_whitespace;
4881 int force_text_diff;
4882 FILE *f1;
4883 FILE *f2;
4884 FILE *outfile;
4888 * Create a file which contains the target path of a symlink so we can feed
4889 * it as content to the diff engine.
4891 static const struct got_error *
4892 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4893 const char *abspath)
4895 const struct got_error *err = NULL;
4896 char target_path[PATH_MAX];
4897 ssize_t target_len, outlen;
4899 *fd = -1;
4901 if (dirfd != -1) {
4902 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4903 if (target_len == -1)
4904 return got_error_from_errno2("readlinkat", abspath);
4905 } else {
4906 target_len = readlink(abspath, target_path, PATH_MAX);
4907 if (target_len == -1)
4908 return got_error_from_errno2("readlink", abspath);
4911 *fd = got_opentempfd();
4912 if (*fd == -1)
4913 return got_error_from_errno("got_opentempfd");
4915 outlen = write(*fd, target_path, target_len);
4916 if (outlen == -1) {
4917 err = got_error_from_errno("got_opentempfd");
4918 goto done;
4921 if (lseek(*fd, 0, SEEK_SET) == -1) {
4922 err = got_error_from_errno2("lseek", abspath);
4923 goto done;
4925 done:
4926 if (err) {
4927 close(*fd);
4928 *fd = -1;
4930 return err;
4933 static const struct got_error *
4934 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4935 const char *path, struct got_object_id *blob_id,
4936 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4937 int dirfd, const char *de_name)
4939 struct print_diff_arg *a = arg;
4940 const struct got_error *err = NULL;
4941 struct got_blob_object *blob1 = NULL;
4942 int fd = -1, fd1 = -1, fd2 = -1;
4943 FILE *f2 = NULL;
4944 char *abspath = NULL, *label1 = NULL;
4945 struct stat sb;
4946 off_t size1 = 0;
4947 int f2_exists = 0;
4949 memset(&sb, 0, sizeof(sb));
4951 if (a->diff_staged) {
4952 if (staged_status != GOT_STATUS_MODIFY &&
4953 staged_status != GOT_STATUS_ADD &&
4954 staged_status != GOT_STATUS_DELETE)
4955 return NULL;
4956 } else {
4957 if (staged_status == GOT_STATUS_DELETE)
4958 return NULL;
4959 if (status == GOT_STATUS_NONEXISTENT)
4960 return got_error_set_errno(ENOENT, path);
4961 if (status != GOT_STATUS_MODIFY &&
4962 status != GOT_STATUS_ADD &&
4963 status != GOT_STATUS_DELETE &&
4964 status != GOT_STATUS_CONFLICT)
4965 return NULL;
4968 err = got_opentemp_truncate(a->f1);
4969 if (err)
4970 return got_error_from_errno("got_opentemp_truncate");
4971 err = got_opentemp_truncate(a->f2);
4972 if (err)
4973 return got_error_from_errno("got_opentemp_truncate");
4975 if (!a->header_shown) {
4976 if (fprintf(a->outfile, "diff %s%s\n",
4977 a->diff_staged ? "-s " : "",
4978 got_worktree_get_root_path(a->worktree)) < 0) {
4979 err = got_error_from_errno("fprintf");
4980 goto done;
4982 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4983 err = got_error_from_errno("fprintf");
4984 goto done;
4986 if (fprintf(a->outfile, "path + %s%s\n",
4987 got_worktree_get_root_path(a->worktree),
4988 a->diff_staged ? " (staged changes)" : "") < 0) {
4989 err = got_error_from_errno("fprintf");
4990 goto done;
4992 a->header_shown = 1;
4995 if (a->diff_staged) {
4996 const char *label1 = NULL, *label2 = NULL;
4997 switch (staged_status) {
4998 case GOT_STATUS_MODIFY:
4999 label1 = path;
5000 label2 = path;
5001 break;
5002 case GOT_STATUS_ADD:
5003 label2 = path;
5004 break;
5005 case GOT_STATUS_DELETE:
5006 label1 = path;
5007 break;
5008 default:
5009 return got_error(GOT_ERR_FILE_STATUS);
5011 fd1 = got_opentempfd();
5012 if (fd1 == -1) {
5013 err = got_error_from_errno("got_opentempfd");
5014 goto done;
5016 fd2 = got_opentempfd();
5017 if (fd2 == -1) {
5018 err = got_error_from_errno("got_opentempfd");
5019 goto done;
5021 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5022 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5023 a->diff_algo, a->diff_context, a->ignore_whitespace,
5024 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5025 goto done;
5028 fd1 = got_opentempfd();
5029 if (fd1 == -1) {
5030 err = got_error_from_errno("got_opentempfd");
5031 goto done;
5034 if (staged_status == GOT_STATUS_ADD ||
5035 staged_status == GOT_STATUS_MODIFY) {
5036 char *id_str;
5037 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5038 8192, fd1);
5039 if (err)
5040 goto done;
5041 err = got_object_id_str(&id_str, staged_blob_id);
5042 if (err)
5043 goto done;
5044 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5045 err = got_error_from_errno("asprintf");
5046 free(id_str);
5047 goto done;
5049 free(id_str);
5050 } else if (status != GOT_STATUS_ADD) {
5051 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5052 fd1);
5053 if (err)
5054 goto done;
5057 if (status != GOT_STATUS_DELETE) {
5058 if (asprintf(&abspath, "%s/%s",
5059 got_worktree_get_root_path(a->worktree), path) == -1) {
5060 err = got_error_from_errno("asprintf");
5061 goto done;
5064 if (dirfd != -1) {
5065 fd = openat(dirfd, de_name,
5066 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5067 if (fd == -1) {
5068 if (!got_err_open_nofollow_on_symlink()) {
5069 err = got_error_from_errno2("openat",
5070 abspath);
5071 goto done;
5073 err = get_symlink_target_file(&fd, dirfd,
5074 de_name, abspath);
5075 if (err)
5076 goto done;
5078 } else {
5079 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5080 if (fd == -1) {
5081 if (!got_err_open_nofollow_on_symlink()) {
5082 err = got_error_from_errno2("open",
5083 abspath);
5084 goto done;
5086 err = get_symlink_target_file(&fd, dirfd,
5087 de_name, abspath);
5088 if (err)
5089 goto done;
5092 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5093 err = got_error_from_errno2("fstatat", abspath);
5094 goto done;
5096 f2 = fdopen(fd, "r");
5097 if (f2 == NULL) {
5098 err = got_error_from_errno2("fdopen", abspath);
5099 goto done;
5101 fd = -1;
5102 f2_exists = 1;
5105 if (blob1) {
5106 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5107 a->f1, blob1);
5108 if (err)
5109 goto done;
5112 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5113 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5114 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5115 done:
5116 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5117 err = got_error_from_errno("close");
5118 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5119 err = got_error_from_errno("close");
5120 if (blob1)
5121 got_object_blob_close(blob1);
5122 if (fd != -1 && close(fd) == -1 && err == NULL)
5123 err = got_error_from_errno("close");
5124 if (f2 && fclose(f2) == EOF && err == NULL)
5125 err = got_error_from_errno("fclose");
5126 free(abspath);
5127 return err;
5130 static const struct got_error *
5131 cmd_diff(int argc, char *argv[])
5133 const struct got_error *error;
5134 struct got_repository *repo = NULL;
5135 struct got_worktree *worktree = NULL;
5136 char *cwd = NULL, *repo_path = NULL;
5137 const char *commit_args[2] = { NULL, NULL };
5138 int ncommit_args = 0;
5139 struct got_object_id *ids[2] = { NULL, NULL };
5140 char *labels[2] = { NULL, NULL };
5141 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5142 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5143 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5144 const char *errstr;
5145 struct got_reflist_head refs;
5146 struct got_pathlist_head diffstat_paths, paths;
5147 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5148 int fd1 = -1, fd2 = -1;
5149 int *pack_fds = NULL;
5150 struct got_diffstat_cb_arg dsa;
5152 memset(&dsa, 0, sizeof(dsa));
5154 TAILQ_INIT(&refs);
5155 TAILQ_INIT(&paths);
5156 TAILQ_INIT(&diffstat_paths);
5158 #ifndef PROFILE
5159 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5160 NULL) == -1)
5161 err(1, "pledge");
5162 #endif
5164 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5165 switch (ch) {
5166 case 'a':
5167 force_text_diff = 1;
5168 break;
5169 case 'C':
5170 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5171 &errstr);
5172 if (errstr != NULL)
5173 errx(1, "number of context lines is %s: %s",
5174 errstr, optarg);
5175 break;
5176 case 'c':
5177 if (ncommit_args >= 2)
5178 errx(1, "too many -c options used");
5179 commit_args[ncommit_args++] = optarg;
5180 break;
5181 case 'd':
5182 show_diffstat = 1;
5183 break;
5184 case 'P':
5185 force_path = 1;
5186 break;
5187 case 'r':
5188 repo_path = realpath(optarg, NULL);
5189 if (repo_path == NULL)
5190 return got_error_from_errno2("realpath",
5191 optarg);
5192 got_path_strip_trailing_slashes(repo_path);
5193 rflag = 1;
5194 break;
5195 case 's':
5196 diff_staged = 1;
5197 break;
5198 case 'w':
5199 ignore_whitespace = 1;
5200 break;
5201 default:
5202 usage_diff();
5203 /* NOTREACHED */
5207 argc -= optind;
5208 argv += optind;
5210 cwd = getcwd(NULL, 0);
5211 if (cwd == NULL) {
5212 error = got_error_from_errno("getcwd");
5213 goto done;
5216 error = got_repo_pack_fds_open(&pack_fds);
5217 if (error != NULL)
5218 goto done;
5220 if (repo_path == NULL) {
5221 error = got_worktree_open(&worktree, cwd,
5222 GOT_WORKTREE_GOT_DIR);
5223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5224 goto done;
5225 else
5226 error = NULL;
5227 if (worktree) {
5228 repo_path =
5229 strdup(got_worktree_get_repo_path(worktree));
5230 if (repo_path == NULL) {
5231 error = got_error_from_errno("strdup");
5232 goto done;
5234 } else {
5235 repo_path = strdup(cwd);
5236 if (repo_path == NULL) {
5237 error = got_error_from_errno("strdup");
5238 goto done;
5243 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5244 free(repo_path);
5245 if (error != NULL)
5246 goto done;
5248 if (show_diffstat) {
5249 dsa.paths = &diffstat_paths;
5250 dsa.force_text = force_text_diff;
5251 dsa.ignore_ws = ignore_whitespace;
5252 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5255 if (rflag || worktree == NULL || ncommit_args > 0) {
5256 if (force_path) {
5257 error = got_error_msg(GOT_ERR_NOT_IMPL,
5258 "-P option can only be used when diffing "
5259 "a work tree");
5260 goto done;
5262 if (diff_staged) {
5263 error = got_error_msg(GOT_ERR_NOT_IMPL,
5264 "-s option can only be used when diffing "
5265 "a work tree");
5266 goto done;
5270 error = apply_unveil(got_repo_get_path(repo), 1,
5271 worktree ? got_worktree_get_root_path(worktree) : NULL);
5272 if (error)
5273 goto done;
5275 if ((!force_path && argc == 2) || ncommit_args > 0) {
5276 int obj_type = (ncommit_args > 0 ?
5277 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5278 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5279 NULL);
5280 if (error)
5281 goto done;
5282 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5283 const char *arg;
5284 char *keyword_idstr = NULL;
5286 if (ncommit_args > 0)
5287 arg = commit_args[i];
5288 else
5289 arg = argv[i];
5291 error = got_keyword_to_idstr(&keyword_idstr, arg,
5292 repo, worktree);
5293 if (error != NULL)
5294 goto done;
5295 if (keyword_idstr != NULL)
5296 arg = keyword_idstr;
5298 error = got_repo_match_object_id(&ids[i], &labels[i],
5299 arg, obj_type, &refs, repo);
5300 free(keyword_idstr);
5301 if (error) {
5302 if (error->code != GOT_ERR_NOT_REF &&
5303 error->code != GOT_ERR_NO_OBJ)
5304 goto done;
5305 if (ncommit_args > 0)
5306 goto done;
5307 error = NULL;
5308 break;
5313 f1 = got_opentemp();
5314 if (f1 == NULL) {
5315 error = got_error_from_errno("got_opentemp");
5316 goto done;
5319 f2 = got_opentemp();
5320 if (f2 == NULL) {
5321 error = got_error_from_errno("got_opentemp");
5322 goto done;
5325 outfile = got_opentemp();
5326 if (outfile == NULL) {
5327 error = got_error_from_errno("got_opentemp");
5328 goto done;
5331 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5332 struct print_diff_arg arg;
5333 char *id_str;
5335 if (worktree == NULL) {
5336 if (argc == 2 && ids[0] == NULL) {
5337 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5338 goto done;
5339 } else if (argc == 2 && ids[1] == NULL) {
5340 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5341 goto done;
5342 } else if (argc > 0) {
5343 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5344 "%s", "specified paths cannot be resolved");
5345 goto done;
5346 } else {
5347 error = got_error(GOT_ERR_NOT_WORKTREE);
5348 goto done;
5352 error = get_worktree_paths_from_argv(&paths, argc, argv,
5353 worktree);
5354 if (error)
5355 goto done;
5357 error = got_object_id_str(&id_str,
5358 got_worktree_get_base_commit_id(worktree));
5359 if (error)
5360 goto done;
5361 arg.repo = repo;
5362 arg.worktree = worktree;
5363 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5364 arg.diff_context = diff_context;
5365 arg.id_str = id_str;
5366 arg.header_shown = 0;
5367 arg.diff_staged = diff_staged;
5368 arg.ignore_whitespace = ignore_whitespace;
5369 arg.force_text_diff = force_text_diff;
5370 arg.diffstat = show_diffstat ? &dsa : NULL;
5371 arg.f1 = f1;
5372 arg.f2 = f2;
5373 arg.outfile = outfile;
5375 error = got_worktree_status(worktree, &paths, repo, 0,
5376 print_diff, &arg, check_cancelled, NULL);
5377 free(id_str);
5378 if (error)
5379 goto done;
5381 if (show_diffstat && dsa.nfiles > 0) {
5382 char *header;
5384 if (asprintf(&header, "diffstat %s%s",
5385 diff_staged ? "-s " : "",
5386 got_worktree_get_root_path(worktree)) == -1) {
5387 error = got_error_from_errno("asprintf");
5388 goto done;
5391 error = print_diffstat(&dsa, header);
5392 free(header);
5393 if (error)
5394 goto done;
5397 error = printfile(outfile);
5398 goto done;
5401 if (ncommit_args == 1) {
5402 struct got_commit_object *commit;
5403 error = got_object_open_as_commit(&commit, repo, ids[0]);
5404 if (error)
5405 goto done;
5407 labels[1] = labels[0];
5408 ids[1] = ids[0];
5409 if (got_object_commit_get_nparents(commit) > 0) {
5410 const struct got_object_id_queue *pids;
5411 struct got_object_qid *pid;
5412 pids = got_object_commit_get_parent_ids(commit);
5413 pid = STAILQ_FIRST(pids);
5414 ids[0] = got_object_id_dup(&pid->id);
5415 if (ids[0] == NULL) {
5416 error = got_error_from_errno(
5417 "got_object_id_dup");
5418 got_object_commit_close(commit);
5419 goto done;
5421 error = got_object_id_str(&labels[0], ids[0]);
5422 if (error) {
5423 got_object_commit_close(commit);
5424 goto done;
5426 } else {
5427 ids[0] = NULL;
5428 labels[0] = strdup("/dev/null");
5429 if (labels[0] == NULL) {
5430 error = got_error_from_errno("strdup");
5431 got_object_commit_close(commit);
5432 goto done;
5436 got_object_commit_close(commit);
5439 if (ncommit_args == 0 && argc > 2) {
5440 error = got_error_msg(GOT_ERR_BAD_PATH,
5441 "path arguments cannot be used when diffing two objects");
5442 goto done;
5445 if (ids[0]) {
5446 error = got_object_get_type(&type1, repo, ids[0]);
5447 if (error)
5448 goto done;
5451 error = got_object_get_type(&type2, repo, ids[1]);
5452 if (error)
5453 goto done;
5454 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5455 error = got_error(GOT_ERR_OBJ_TYPE);
5456 goto done;
5458 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5459 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5460 "path arguments cannot be used when diffing blobs");
5461 goto done;
5464 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5465 char *in_repo_path;
5466 struct got_pathlist_entry *new;
5467 if (worktree) {
5468 const char *prefix;
5469 char *p;
5470 error = got_worktree_resolve_path(&p, worktree,
5471 argv[i]);
5472 if (error)
5473 goto done;
5474 prefix = got_worktree_get_path_prefix(worktree);
5475 while (prefix[0] == '/')
5476 prefix++;
5477 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5478 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5479 p) == -1) {
5480 error = got_error_from_errno("asprintf");
5481 free(p);
5482 goto done;
5484 free(p);
5485 } else {
5486 char *mapped_path, *s;
5487 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5488 if (error)
5489 goto done;
5490 s = mapped_path;
5491 while (s[0] == '/')
5492 s++;
5493 in_repo_path = strdup(s);
5494 if (in_repo_path == NULL) {
5495 error = got_error_from_errno("asprintf");
5496 free(mapped_path);
5497 goto done;
5499 free(mapped_path);
5502 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5503 if (error || new == NULL /* duplicate */)
5504 free(in_repo_path);
5505 if (error)
5506 goto done;
5509 if (worktree) {
5510 /* Release work tree lock. */
5511 got_worktree_close(worktree);
5512 worktree = NULL;
5515 fd1 = got_opentempfd();
5516 if (fd1 == -1) {
5517 error = got_error_from_errno("got_opentempfd");
5518 goto done;
5521 fd2 = got_opentempfd();
5522 if (fd2 == -1) {
5523 error = got_error_from_errno("got_opentempfd");
5524 goto done;
5527 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5528 case GOT_OBJ_TYPE_BLOB:
5529 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5530 fd1, fd2, ids[0], ids[1], NULL, NULL,
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_TREE:
5536 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5537 ids[0], ids[1], &paths, "", "",
5538 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5539 ignore_whitespace, force_text_diff,
5540 show_diffstat ? &dsa : NULL, repo, outfile);
5541 break;
5542 case GOT_OBJ_TYPE_COMMIT:
5543 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5544 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5545 fd1, fd2, ids[0], ids[1], &paths,
5546 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5547 ignore_whitespace, force_text_diff,
5548 show_diffstat ? &dsa : NULL, repo, outfile);
5549 break;
5550 default:
5551 error = got_error(GOT_ERR_OBJ_TYPE);
5553 if (error)
5554 goto done;
5556 if (show_diffstat && dsa.nfiles > 0) {
5557 char *header = NULL;
5559 if (asprintf(&header, "diffstat %s %s",
5560 labels[0], labels[1]) == -1) {
5561 error = got_error_from_errno("asprintf");
5562 goto done;
5565 error = print_diffstat(&dsa, header);
5566 free(header);
5567 if (error)
5568 goto done;
5571 error = printfile(outfile);
5573 done:
5574 free(labels[0]);
5575 free(labels[1]);
5576 free(ids[0]);
5577 free(ids[1]);
5578 if (worktree)
5579 got_worktree_close(worktree);
5580 if (repo) {
5581 const struct got_error *close_err = got_repo_close(repo);
5582 if (error == NULL)
5583 error = close_err;
5585 if (pack_fds) {
5586 const struct got_error *pack_err =
5587 got_repo_pack_fds_close(pack_fds);
5588 if (error == NULL)
5589 error = pack_err;
5591 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5592 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5593 got_ref_list_free(&refs);
5594 if (outfile && fclose(outfile) == EOF && error == NULL)
5595 error = got_error_from_errno("fclose");
5596 if (f1 && fclose(f1) == EOF && error == NULL)
5597 error = got_error_from_errno("fclose");
5598 if (f2 && fclose(f2) == EOF && error == NULL)
5599 error = got_error_from_errno("fclose");
5600 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5601 error = got_error_from_errno("close");
5602 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5603 error = got_error_from_errno("close");
5604 return error;
5607 __dead static void
5608 usage_blame(void)
5610 fprintf(stderr,
5611 "usage: %s blame [-c commit] [-r repository-path] path\n",
5612 getprogname());
5613 exit(1);
5616 struct blame_line {
5617 int annotated;
5618 char *id_str;
5619 char *committer;
5620 char datebuf[11]; /* YYYY-MM-DD + NUL */
5623 struct blame_cb_args {
5624 struct blame_line *lines;
5625 int nlines;
5626 int nlines_prec;
5627 int lineno_cur;
5628 off_t *line_offsets;
5629 FILE *f;
5630 struct got_repository *repo;
5633 static const struct got_error *
5634 blame_cb(void *arg, int nlines, int lineno,
5635 struct got_commit_object *commit, struct got_object_id *id)
5637 const struct got_error *err = NULL;
5638 struct blame_cb_args *a = arg;
5639 struct blame_line *bline;
5640 char *line = NULL;
5641 size_t linesize = 0;
5642 off_t offset;
5643 struct tm tm;
5644 time_t committer_time;
5646 if (nlines != a->nlines ||
5647 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5648 return got_error(GOT_ERR_RANGE);
5650 if (sigint_received)
5651 return got_error(GOT_ERR_ITER_COMPLETED);
5653 if (lineno == -1)
5654 return NULL; /* no change in this commit */
5656 /* Annotate this line. */
5657 bline = &a->lines[lineno - 1];
5658 if (bline->annotated)
5659 return NULL;
5660 err = got_object_id_str(&bline->id_str, id);
5661 if (err)
5662 return err;
5664 bline->committer = strdup(got_object_commit_get_committer(commit));
5665 if (bline->committer == NULL) {
5666 err = got_error_from_errno("strdup");
5667 goto done;
5670 committer_time = got_object_commit_get_committer_time(commit);
5671 if (gmtime_r(&committer_time, &tm) == NULL)
5672 return got_error_from_errno("gmtime_r");
5673 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5674 &tm) == 0) {
5675 err = got_error(GOT_ERR_NO_SPACE);
5676 goto done;
5678 bline->annotated = 1;
5680 /* Print lines annotated so far. */
5681 bline = &a->lines[a->lineno_cur - 1];
5682 if (!bline->annotated)
5683 goto done;
5685 offset = a->line_offsets[a->lineno_cur - 1];
5686 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5687 err = got_error_from_errno("fseeko");
5688 goto done;
5691 while (a->lineno_cur <= a->nlines && bline->annotated) {
5692 char *smallerthan, *at, *nl, *committer;
5693 size_t len;
5695 if (getline(&line, &linesize, a->f) == -1) {
5696 if (ferror(a->f))
5697 err = got_error_from_errno("getline");
5698 break;
5701 committer = bline->committer;
5702 smallerthan = strchr(committer, '<');
5703 if (smallerthan && smallerthan[1] != '\0')
5704 committer = smallerthan + 1;
5705 at = strchr(committer, '@');
5706 if (at)
5707 *at = '\0';
5708 len = strlen(committer);
5709 if (len >= 9)
5710 committer[8] = '\0';
5712 nl = strchr(line, '\n');
5713 if (nl)
5714 *nl = '\0';
5715 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5716 bline->id_str, bline->datebuf, committer, line);
5718 a->lineno_cur++;
5719 bline = &a->lines[a->lineno_cur - 1];
5721 done:
5722 free(line);
5723 return err;
5726 static const struct got_error *
5727 cmd_blame(int argc, char *argv[])
5729 const struct got_error *error;
5730 struct got_repository *repo = NULL;
5731 struct got_worktree *worktree = NULL;
5732 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5733 char *link_target = NULL;
5734 struct got_object_id *obj_id = NULL;
5735 struct got_object_id *commit_id = NULL;
5736 struct got_commit_object *commit = NULL;
5737 struct got_blob_object *blob = NULL;
5738 char *commit_id_str = NULL, *keyword_idstr = NULL;
5739 struct blame_cb_args bca;
5740 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5741 off_t filesize;
5742 int *pack_fds = NULL;
5743 FILE *f1 = NULL, *f2 = NULL;
5745 fd1 = got_opentempfd();
5746 if (fd1 == -1)
5747 return got_error_from_errno("got_opentempfd");
5749 memset(&bca, 0, sizeof(bca));
5751 #ifndef PROFILE
5752 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5753 NULL) == -1)
5754 err(1, "pledge");
5755 #endif
5757 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5758 switch (ch) {
5759 case 'c':
5760 commit_id_str = optarg;
5761 break;
5762 case 'r':
5763 repo_path = realpath(optarg, NULL);
5764 if (repo_path == NULL)
5765 return got_error_from_errno2("realpath",
5766 optarg);
5767 got_path_strip_trailing_slashes(repo_path);
5768 break;
5769 default:
5770 usage_blame();
5771 /* NOTREACHED */
5775 argc -= optind;
5776 argv += optind;
5778 if (argc == 1)
5779 path = argv[0];
5780 else
5781 usage_blame();
5783 cwd = getcwd(NULL, 0);
5784 if (cwd == NULL) {
5785 error = got_error_from_errno("getcwd");
5786 goto done;
5789 error = got_repo_pack_fds_open(&pack_fds);
5790 if (error != NULL)
5791 goto done;
5793 if (repo_path == NULL) {
5794 error = got_worktree_open(&worktree, cwd,
5795 GOT_WORKTREE_GOT_DIR);
5796 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5797 goto done;
5798 else
5799 error = NULL;
5800 if (worktree) {
5801 repo_path =
5802 strdup(got_worktree_get_repo_path(worktree));
5803 if (repo_path == NULL) {
5804 error = got_error_from_errno("strdup");
5805 if (error)
5806 goto done;
5808 } else {
5809 repo_path = strdup(cwd);
5810 if (repo_path == NULL) {
5811 error = got_error_from_errno("strdup");
5812 goto done;
5817 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5818 if (error != NULL)
5819 goto done;
5821 if (worktree) {
5822 const char *prefix = got_worktree_get_path_prefix(worktree);
5823 char *p;
5825 error = got_worktree_resolve_path(&p, worktree, path);
5826 if (error)
5827 goto done;
5828 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5829 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5830 p) == -1) {
5831 error = got_error_from_errno("asprintf");
5832 free(p);
5833 goto done;
5835 free(p);
5836 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5837 } else {
5838 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5839 if (error)
5840 goto done;
5841 error = got_repo_map_path(&in_repo_path, repo, path);
5843 if (error)
5844 goto done;
5846 if (commit_id_str == NULL) {
5847 struct got_reference *head_ref;
5848 error = got_ref_open(&head_ref, repo, worktree ?
5849 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5850 if (error != NULL)
5851 goto done;
5852 error = got_ref_resolve(&commit_id, repo, head_ref);
5853 got_ref_close(head_ref);
5854 if (error != NULL)
5855 goto done;
5856 } else {
5857 struct got_reflist_head refs;
5859 TAILQ_INIT(&refs);
5860 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5861 NULL);
5862 if (error)
5863 goto done;
5865 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5866 repo, worktree);
5867 if (error != NULL)
5868 goto done;
5869 if (keyword_idstr != NULL)
5870 commit_id_str = keyword_idstr;
5872 error = got_repo_match_object_id(&commit_id, NULL,
5873 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5874 got_ref_list_free(&refs);
5875 if (error)
5876 goto done;
5879 if (worktree) {
5880 /* Release work tree lock. */
5881 got_worktree_close(worktree);
5882 worktree = NULL;
5885 error = got_object_open_as_commit(&commit, repo, commit_id);
5886 if (error)
5887 goto done;
5889 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5890 commit, repo);
5891 if (error)
5892 goto done;
5894 error = got_object_id_by_path(&obj_id, repo, commit,
5895 link_target ? link_target : in_repo_path);
5896 if (error)
5897 goto done;
5899 error = got_object_get_type(&obj_type, repo, obj_id);
5900 if (error)
5901 goto done;
5903 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5904 error = got_error_path(link_target ? link_target : in_repo_path,
5905 GOT_ERR_OBJ_TYPE);
5906 goto done;
5909 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5910 if (error)
5911 goto done;
5912 bca.f = got_opentemp();
5913 if (bca.f == NULL) {
5914 error = got_error_from_errno("got_opentemp");
5915 goto done;
5917 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5918 &bca.line_offsets, bca.f, blob);
5919 if (error || bca.nlines == 0)
5920 goto done;
5922 /* Don't include \n at EOF in the blame line count. */
5923 if (bca.line_offsets[bca.nlines - 1] == filesize)
5924 bca.nlines--;
5926 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5927 if (bca.lines == NULL) {
5928 error = got_error_from_errno("calloc");
5929 goto done;
5931 bca.lineno_cur = 1;
5932 bca.nlines_prec = 0;
5933 i = bca.nlines;
5934 while (i > 0) {
5935 i /= 10;
5936 bca.nlines_prec++;
5938 bca.repo = repo;
5940 fd2 = got_opentempfd();
5941 if (fd2 == -1) {
5942 error = got_error_from_errno("got_opentempfd");
5943 goto done;
5945 fd3 = got_opentempfd();
5946 if (fd3 == -1) {
5947 error = got_error_from_errno("got_opentempfd");
5948 goto done;
5950 f1 = got_opentemp();
5951 if (f1 == NULL) {
5952 error = got_error_from_errno("got_opentemp");
5953 goto done;
5955 f2 = got_opentemp();
5956 if (f2 == NULL) {
5957 error = got_error_from_errno("got_opentemp");
5958 goto done;
5960 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5961 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5962 check_cancelled, NULL, fd2, fd3, f1, f2);
5963 done:
5964 free(keyword_idstr);
5965 free(in_repo_path);
5966 free(link_target);
5967 free(repo_path);
5968 free(cwd);
5969 free(commit_id);
5970 free(obj_id);
5971 if (commit)
5972 got_object_commit_close(commit);
5974 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5975 error = got_error_from_errno("close");
5976 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5977 error = got_error_from_errno("close");
5978 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5979 error = got_error_from_errno("close");
5980 if (f1 && fclose(f1) == EOF && error == NULL)
5981 error = got_error_from_errno("fclose");
5982 if (f2 && fclose(f2) == EOF && error == NULL)
5983 error = got_error_from_errno("fclose");
5985 if (blob)
5986 got_object_blob_close(blob);
5987 if (worktree)
5988 got_worktree_close(worktree);
5989 if (repo) {
5990 const struct got_error *close_err = got_repo_close(repo);
5991 if (error == NULL)
5992 error = close_err;
5994 if (pack_fds) {
5995 const struct got_error *pack_err =
5996 got_repo_pack_fds_close(pack_fds);
5997 if (error == NULL)
5998 error = pack_err;
6000 if (bca.lines) {
6001 for (i = 0; i < bca.nlines; i++) {
6002 struct blame_line *bline = &bca.lines[i];
6003 free(bline->id_str);
6004 free(bline->committer);
6006 free(bca.lines);
6008 free(bca.line_offsets);
6009 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6010 error = got_error_from_errno("fclose");
6011 return error;
6014 __dead static void
6015 usage_tree(void)
6017 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6018 "[path]\n", getprogname());
6019 exit(1);
6022 static const struct got_error *
6023 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6024 const char *root_path, struct got_repository *repo)
6026 const struct got_error *err = NULL;
6027 int is_root_path = (strcmp(path, root_path) == 0);
6028 const char *modestr = "";
6029 mode_t mode = got_tree_entry_get_mode(te);
6030 char *link_target = NULL;
6032 path += strlen(root_path);
6033 while (path[0] == '/')
6034 path++;
6036 if (got_object_tree_entry_is_submodule(te))
6037 modestr = "$";
6038 else if (S_ISLNK(mode)) {
6039 int i;
6041 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6042 if (err)
6043 return err;
6044 for (i = 0; link_target[i] != '\0'; i++) {
6045 if (!isprint((unsigned char)link_target[i]))
6046 link_target[i] = '?';
6049 modestr = "@";
6051 else if (S_ISDIR(mode))
6052 modestr = "/";
6053 else if (mode & S_IXUSR)
6054 modestr = "*";
6056 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6057 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6058 link_target ? " -> ": "", link_target ? link_target : "");
6060 free(link_target);
6061 return NULL;
6064 static const struct got_error *
6065 print_tree(const char *path, struct got_commit_object *commit,
6066 int show_ids, int recurse, const char *root_path,
6067 struct got_repository *repo)
6069 const struct got_error *err = NULL;
6070 struct got_object_id *tree_id = NULL;
6071 struct got_tree_object *tree = NULL;
6072 int nentries, i;
6074 err = got_object_id_by_path(&tree_id, repo, commit, path);
6075 if (err)
6076 goto done;
6078 err = got_object_open_as_tree(&tree, repo, tree_id);
6079 if (err)
6080 goto done;
6081 nentries = got_object_tree_get_nentries(tree);
6082 for (i = 0; i < nentries; i++) {
6083 struct got_tree_entry *te;
6084 char *id = NULL;
6086 if (sigint_received || sigpipe_received)
6087 break;
6089 te = got_object_tree_get_entry(tree, i);
6090 if (show_ids) {
6091 char *id_str;
6092 err = got_object_id_str(&id_str,
6093 got_tree_entry_get_id(te));
6094 if (err)
6095 goto done;
6096 if (asprintf(&id, "%s ", id_str) == -1) {
6097 err = got_error_from_errno("asprintf");
6098 free(id_str);
6099 goto done;
6101 free(id_str);
6103 err = print_entry(te, id, path, root_path, repo);
6104 free(id);
6105 if (err)
6106 goto done;
6108 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6109 char *child_path;
6110 if (asprintf(&child_path, "%s%s%s", path,
6111 path[0] == '/' && path[1] == '\0' ? "" : "/",
6112 got_tree_entry_get_name(te)) == -1) {
6113 err = got_error_from_errno("asprintf");
6114 goto done;
6116 err = print_tree(child_path, commit, show_ids, 1,
6117 root_path, repo);
6118 free(child_path);
6119 if (err)
6120 goto done;
6123 done:
6124 if (tree)
6125 got_object_tree_close(tree);
6126 free(tree_id);
6127 return err;
6130 static const struct got_error *
6131 cmd_tree(int argc, char *argv[])
6133 const struct got_error *error;
6134 struct got_repository *repo = NULL;
6135 struct got_worktree *worktree = NULL;
6136 const char *path, *refname = NULL;
6137 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6138 struct got_object_id *commit_id = NULL;
6139 struct got_commit_object *commit = NULL;
6140 char *commit_id_str = NULL, *keyword_idstr = NULL;
6141 int show_ids = 0, recurse = 0;
6142 int ch;
6143 int *pack_fds = NULL;
6145 #ifndef PROFILE
6146 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6147 NULL) == -1)
6148 err(1, "pledge");
6149 #endif
6151 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6152 switch (ch) {
6153 case 'c':
6154 commit_id_str = optarg;
6155 break;
6156 case 'i':
6157 show_ids = 1;
6158 break;
6159 case 'R':
6160 recurse = 1;
6161 break;
6162 case 'r':
6163 repo_path = realpath(optarg, NULL);
6164 if (repo_path == NULL)
6165 return got_error_from_errno2("realpath",
6166 optarg);
6167 got_path_strip_trailing_slashes(repo_path);
6168 break;
6169 default:
6170 usage_tree();
6171 /* NOTREACHED */
6175 argc -= optind;
6176 argv += optind;
6178 if (argc == 1)
6179 path = argv[0];
6180 else if (argc > 1)
6181 usage_tree();
6182 else
6183 path = NULL;
6185 cwd = getcwd(NULL, 0);
6186 if (cwd == NULL) {
6187 error = got_error_from_errno("getcwd");
6188 goto done;
6191 error = got_repo_pack_fds_open(&pack_fds);
6192 if (error != NULL)
6193 goto done;
6195 if (repo_path == NULL) {
6196 error = got_worktree_open(&worktree, cwd,
6197 GOT_WORKTREE_GOT_DIR);
6198 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6199 goto done;
6200 else
6201 error = NULL;
6202 if (worktree) {
6203 repo_path =
6204 strdup(got_worktree_get_repo_path(worktree));
6205 if (repo_path == NULL)
6206 error = got_error_from_errno("strdup");
6207 if (error)
6208 goto done;
6209 } else {
6210 repo_path = strdup(cwd);
6211 if (repo_path == NULL) {
6212 error = got_error_from_errno("strdup");
6213 goto done;
6218 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6219 if (error != NULL)
6220 goto done;
6222 if (worktree) {
6223 const char *prefix = got_worktree_get_path_prefix(worktree);
6224 char *p;
6226 if (path == NULL || got_path_is_root_dir(path))
6227 path = "";
6228 error = got_worktree_resolve_path(&p, worktree, path);
6229 if (error)
6230 goto done;
6231 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6232 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6233 p) == -1) {
6234 error = got_error_from_errno("asprintf");
6235 free(p);
6236 goto done;
6238 free(p);
6239 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6240 if (error)
6241 goto done;
6242 } else {
6243 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6244 if (error)
6245 goto done;
6246 if (path == NULL)
6247 path = "/";
6248 error = got_repo_map_path(&in_repo_path, repo, path);
6249 if (error != NULL)
6250 goto done;
6253 if (commit_id_str == NULL) {
6254 struct got_reference *head_ref;
6255 if (worktree)
6256 refname = got_worktree_get_head_ref_name(worktree);
6257 else
6258 refname = GOT_REF_HEAD;
6259 error = got_ref_open(&head_ref, repo, refname, 0);
6260 if (error != NULL)
6261 goto done;
6262 error = got_ref_resolve(&commit_id, repo, head_ref);
6263 got_ref_close(head_ref);
6264 if (error != NULL)
6265 goto done;
6266 } else {
6267 struct got_reflist_head refs;
6269 TAILQ_INIT(&refs);
6270 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6271 NULL);
6272 if (error)
6273 goto done;
6275 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6276 repo, worktree);
6277 if (error != NULL)
6278 goto done;
6279 if (keyword_idstr != NULL)
6280 commit_id_str = keyword_idstr;
6282 error = got_repo_match_object_id(&commit_id, NULL,
6283 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6284 got_ref_list_free(&refs);
6285 if (error)
6286 goto done;
6289 if (worktree) {
6290 /* Release work tree lock. */
6291 got_worktree_close(worktree);
6292 worktree = NULL;
6295 error = got_object_open_as_commit(&commit, repo, commit_id);
6296 if (error)
6297 goto done;
6299 error = print_tree(in_repo_path, commit, show_ids, recurse,
6300 in_repo_path, repo);
6301 done:
6302 free(keyword_idstr);
6303 free(in_repo_path);
6304 free(repo_path);
6305 free(cwd);
6306 free(commit_id);
6307 if (commit)
6308 got_object_commit_close(commit);
6309 if (worktree)
6310 got_worktree_close(worktree);
6311 if (repo) {
6312 const struct got_error *close_err = got_repo_close(repo);
6313 if (error == NULL)
6314 error = close_err;
6316 if (pack_fds) {
6317 const struct got_error *pack_err =
6318 got_repo_pack_fds_close(pack_fds);
6319 if (error == NULL)
6320 error = pack_err;
6322 return error;
6325 __dead static void
6326 usage_status(void)
6328 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6329 "[-s status-codes] [path ...]\n", getprogname());
6330 exit(1);
6333 struct got_status_arg {
6334 char *status_codes;
6335 int suppress;
6338 static const struct got_error *
6339 print_status(void *arg, unsigned char status, unsigned char staged_status,
6340 const char *path, struct got_object_id *blob_id,
6341 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6342 int dirfd, const char *de_name)
6344 struct got_status_arg *st = arg;
6346 if (status == staged_status && (status == GOT_STATUS_DELETE))
6347 status = GOT_STATUS_NO_CHANGE;
6348 if (st != NULL && st->status_codes) {
6349 size_t ncodes = strlen(st->status_codes);
6350 int i, j = 0;
6352 for (i = 0; i < ncodes ; i++) {
6353 if (st->suppress) {
6354 if (status == st->status_codes[i] ||
6355 staged_status == st->status_codes[i]) {
6356 j++;
6357 continue;
6359 } else {
6360 if (status == st->status_codes[i] ||
6361 staged_status == st->status_codes[i])
6362 break;
6366 if (st->suppress && j == 0)
6367 goto print;
6369 if (i == ncodes)
6370 return NULL;
6372 print:
6373 printf("%c%c %s\n", status, staged_status, path);
6374 return NULL;
6377 static const struct got_error *
6378 cmd_status(int argc, char *argv[])
6380 const struct got_error *error = NULL;
6381 struct got_repository *repo = NULL;
6382 struct got_worktree *worktree = NULL;
6383 struct got_status_arg st;
6384 char *cwd = NULL;
6385 struct got_pathlist_head paths;
6386 int ch, i, no_ignores = 0;
6387 int *pack_fds = NULL;
6389 TAILQ_INIT(&paths);
6391 memset(&st, 0, sizeof(st));
6392 st.status_codes = NULL;
6393 st.suppress = 0;
6395 #ifndef PROFILE
6396 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6397 NULL) == -1)
6398 err(1, "pledge");
6399 #endif
6401 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6402 switch (ch) {
6403 case 'I':
6404 no_ignores = 1;
6405 break;
6406 case 'S':
6407 if (st.status_codes != NULL && st.suppress == 0)
6408 option_conflict('S', 's');
6409 st.suppress = 1;
6410 /* fallthrough */
6411 case 's':
6412 for (i = 0; optarg[i] != '\0'; i++) {
6413 switch (optarg[i]) {
6414 case GOT_STATUS_MODIFY:
6415 case GOT_STATUS_ADD:
6416 case GOT_STATUS_DELETE:
6417 case GOT_STATUS_CONFLICT:
6418 case GOT_STATUS_MISSING:
6419 case GOT_STATUS_OBSTRUCTED:
6420 case GOT_STATUS_UNVERSIONED:
6421 case GOT_STATUS_MODE_CHANGE:
6422 case GOT_STATUS_NONEXISTENT:
6423 break;
6424 default:
6425 errx(1, "invalid status code '%c'",
6426 optarg[i]);
6429 if (ch == 's' && st.suppress)
6430 option_conflict('s', 'S');
6431 st.status_codes = optarg;
6432 break;
6433 default:
6434 usage_status();
6435 /* NOTREACHED */
6439 argc -= optind;
6440 argv += optind;
6442 cwd = getcwd(NULL, 0);
6443 if (cwd == NULL) {
6444 error = got_error_from_errno("getcwd");
6445 goto done;
6448 error = got_repo_pack_fds_open(&pack_fds);
6449 if (error != NULL)
6450 goto done;
6452 error = got_worktree_open(&worktree, cwd,
6453 GOT_WORKTREE_GOT_DIR);
6454 if (error) {
6455 if (error->code == GOT_ERR_NOT_WORKTREE)
6456 error = wrap_not_worktree_error(error, "status", cwd);
6457 goto done;
6460 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6461 NULL, pack_fds);
6462 if (error != NULL)
6463 goto done;
6465 error = apply_unveil(got_repo_get_path(repo), 1,
6466 got_worktree_get_root_path(worktree));
6467 if (error)
6468 goto done;
6470 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6471 if (error)
6472 goto done;
6474 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6475 print_status, &st, check_cancelled, NULL);
6476 done:
6477 if (pack_fds) {
6478 const struct got_error *pack_err =
6479 got_repo_pack_fds_close(pack_fds);
6480 if (error == NULL)
6481 error = pack_err;
6483 if (repo) {
6484 const struct got_error *close_err = got_repo_close(repo);
6485 if (error == NULL)
6486 error = close_err;
6489 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6490 free(cwd);
6491 return error;
6494 __dead static void
6495 usage_ref(void)
6497 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6498 "[-s reference] [name]\n", getprogname());
6499 exit(1);
6502 static const struct got_error *
6503 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6505 static const struct got_error *err = NULL;
6506 struct got_reflist_head refs;
6507 struct got_reflist_entry *re;
6509 TAILQ_INIT(&refs);
6510 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6511 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6512 repo);
6513 if (err)
6514 return err;
6516 TAILQ_FOREACH(re, &refs, entry) {
6517 char *refstr;
6518 refstr = got_ref_to_str(re->ref);
6519 if (refstr == NULL) {
6520 err = got_error_from_errno("got_ref_to_str");
6521 break;
6523 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6524 free(refstr);
6527 got_ref_list_free(&refs);
6528 return err;
6531 static const struct got_error *
6532 delete_ref_by_name(struct got_repository *repo, const char *refname)
6534 const struct got_error *err;
6535 struct got_reference *ref;
6537 err = got_ref_open(&ref, repo, refname, 0);
6538 if (err)
6539 return err;
6541 err = delete_ref(repo, ref);
6542 got_ref_close(ref);
6543 return err;
6546 static const struct got_error *
6547 add_ref(struct got_repository *repo, const char *refname, const char *target)
6549 const struct got_error *err = NULL;
6550 struct got_object_id *id = NULL;
6551 struct got_reference *ref = NULL;
6552 struct got_reflist_head refs;
6555 * Don't let the user create a reference name with a leading '-'.
6556 * While technically a valid reference name, this case is usually
6557 * an unintended typo.
6559 if (refname[0] == '-')
6560 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6562 TAILQ_INIT(&refs);
6563 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6564 if (err)
6565 goto done;
6566 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6567 &refs, repo);
6568 got_ref_list_free(&refs);
6569 if (err)
6570 goto done;
6572 err = got_ref_alloc(&ref, refname, id);
6573 if (err)
6574 goto done;
6576 err = got_ref_write(ref, repo);
6577 done:
6578 if (ref)
6579 got_ref_close(ref);
6580 free(id);
6581 return err;
6584 static const struct got_error *
6585 add_symref(struct got_repository *repo, const char *refname, const char *target)
6587 const struct got_error *err = NULL;
6588 struct got_reference *ref = NULL;
6589 struct got_reference *target_ref = NULL;
6592 * Don't let the user create a reference name with a leading '-'.
6593 * While technically a valid reference name, this case is usually
6594 * an unintended typo.
6596 if (refname[0] == '-')
6597 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6599 err = got_ref_open(&target_ref, repo, target, 0);
6600 if (err)
6601 return err;
6603 err = got_ref_alloc_symref(&ref, refname, target_ref);
6604 if (err)
6605 goto done;
6607 err = got_ref_write(ref, repo);
6608 done:
6609 if (target_ref)
6610 got_ref_close(target_ref);
6611 if (ref)
6612 got_ref_close(ref);
6613 return err;
6616 static const struct got_error *
6617 cmd_ref(int argc, char *argv[])
6619 const struct got_error *error = NULL;
6620 struct got_repository *repo = NULL;
6621 struct got_worktree *worktree = NULL;
6622 char *cwd = NULL, *repo_path = NULL;
6623 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6624 const char *obj_arg = NULL, *symref_target= NULL;
6625 char *refname = NULL, *keyword_idstr = NULL;
6626 int *pack_fds = NULL;
6628 #ifndef PROFILE
6629 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6630 "sendfd unveil", NULL) == -1)
6631 err(1, "pledge");
6632 #endif
6634 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6635 switch (ch) {
6636 case 'c':
6637 obj_arg = optarg;
6638 break;
6639 case 'd':
6640 do_delete = 1;
6641 break;
6642 case 'l':
6643 do_list = 1;
6644 break;
6645 case 'r':
6646 repo_path = realpath(optarg, NULL);
6647 if (repo_path == NULL)
6648 return got_error_from_errno2("realpath",
6649 optarg);
6650 got_path_strip_trailing_slashes(repo_path);
6651 break;
6652 case 's':
6653 symref_target = optarg;
6654 break;
6655 case 't':
6656 sort_by_time = 1;
6657 break;
6658 default:
6659 usage_ref();
6660 /* NOTREACHED */
6664 if (obj_arg && do_list)
6665 option_conflict('c', 'l');
6666 if (obj_arg && do_delete)
6667 option_conflict('c', 'd');
6668 if (obj_arg && symref_target)
6669 option_conflict('c', 's');
6670 if (symref_target && do_delete)
6671 option_conflict('s', 'd');
6672 if (symref_target && do_list)
6673 option_conflict('s', 'l');
6674 if (do_delete && do_list)
6675 option_conflict('d', 'l');
6676 if (sort_by_time && !do_list)
6677 errx(1, "-t option requires -l option");
6679 argc -= optind;
6680 argv += optind;
6682 if (do_list) {
6683 if (argc != 0 && argc != 1)
6684 usage_ref();
6685 if (argc == 1) {
6686 refname = strdup(argv[0]);
6687 if (refname == NULL) {
6688 error = got_error_from_errno("strdup");
6689 goto done;
6692 } else {
6693 if (argc != 1)
6694 usage_ref();
6695 refname = strdup(argv[0]);
6696 if (refname == NULL) {
6697 error = got_error_from_errno("strdup");
6698 goto done;
6702 if (refname)
6703 got_path_strip_trailing_slashes(refname);
6705 cwd = getcwd(NULL, 0);
6706 if (cwd == NULL) {
6707 error = got_error_from_errno("getcwd");
6708 goto done;
6711 error = got_repo_pack_fds_open(&pack_fds);
6712 if (error != NULL)
6713 goto done;
6715 if (repo_path == NULL) {
6716 error = got_worktree_open(&worktree, cwd,
6717 GOT_WORKTREE_GOT_DIR);
6718 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6719 goto done;
6720 else
6721 error = NULL;
6722 if (worktree) {
6723 repo_path =
6724 strdup(got_worktree_get_repo_path(worktree));
6725 if (repo_path == NULL)
6726 error = got_error_from_errno("strdup");
6727 if (error)
6728 goto done;
6729 } else {
6730 repo_path = strdup(cwd);
6731 if (repo_path == NULL) {
6732 error = got_error_from_errno("strdup");
6733 goto done;
6738 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6739 if (error != NULL)
6740 goto done;
6742 #ifndef PROFILE
6743 if (do_list) {
6744 /* Remove "cpath" promise. */
6745 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6746 NULL) == -1)
6747 err(1, "pledge");
6749 #endif
6751 error = apply_unveil(got_repo_get_path(repo), do_list,
6752 worktree ? got_worktree_get_root_path(worktree) : NULL);
6753 if (error)
6754 goto done;
6756 if (do_list)
6757 error = list_refs(repo, refname, sort_by_time);
6758 else if (do_delete)
6759 error = delete_ref_by_name(repo, refname);
6760 else if (symref_target)
6761 error = add_symref(repo, refname, symref_target);
6762 else {
6763 if (obj_arg == NULL)
6764 usage_ref();
6766 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6767 repo, worktree);
6768 if (error != NULL)
6769 goto done;
6770 if (keyword_idstr != NULL)
6771 obj_arg = keyword_idstr;
6773 error = add_ref(repo, refname, obj_arg);
6775 done:
6776 free(refname);
6777 if (repo) {
6778 const struct got_error *close_err = got_repo_close(repo);
6779 if (error == NULL)
6780 error = close_err;
6782 if (worktree)
6783 got_worktree_close(worktree);
6784 if (pack_fds) {
6785 const struct got_error *pack_err =
6786 got_repo_pack_fds_close(pack_fds);
6787 if (error == NULL)
6788 error = pack_err;
6790 free(cwd);
6791 free(repo_path);
6792 free(keyword_idstr);
6793 return error;
6796 __dead static void
6797 usage_branch(void)
6799 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6800 "[-r repository-path] [name]\n", getprogname());
6801 exit(1);
6804 static const struct got_error *
6805 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6806 struct got_reference *ref)
6808 const struct got_error *err = NULL;
6809 const char *refname;
6810 char *refstr;
6811 char marker = ' ';
6813 refname = got_ref_get_name(ref);
6814 if (worktree && strcmp(refname,
6815 got_worktree_get_head_ref_name(worktree)) == 0) {
6816 err = got_worktree_get_state(&marker, repo, worktree,
6817 check_cancelled, NULL);
6818 if (err != NULL)
6819 return err;
6822 if (strncmp(refname, "refs/heads/", 11) == 0)
6823 refname += 11;
6824 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6825 refname += 18;
6826 if (strncmp(refname, "refs/remotes/", 13) == 0)
6827 refname += 13;
6829 refstr = got_ref_to_str(ref);
6830 if (refstr == NULL)
6831 return got_error_from_errno("got_ref_to_str");
6833 printf("%c %s: %s\n", marker, refname, refstr);
6834 free(refstr);
6835 return NULL;
6838 static const struct got_error *
6839 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6841 const char *refname;
6843 if (worktree == NULL)
6844 return got_error(GOT_ERR_NOT_WORKTREE);
6846 refname = got_worktree_get_head_ref_name(worktree);
6848 if (strncmp(refname, "refs/heads/", 11) == 0)
6849 refname += 11;
6850 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6851 refname += 18;
6853 printf("%s\n", refname);
6855 return NULL;
6858 static const struct got_error *
6859 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6860 int sort_by_time)
6862 static const struct got_error *err = NULL;
6863 struct got_reflist_head refs;
6864 struct got_reflist_entry *re;
6865 struct got_reference *temp_ref = NULL;
6866 int rebase_in_progress, histedit_in_progress;
6868 TAILQ_INIT(&refs);
6870 if (worktree) {
6871 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6872 worktree);
6873 if (err)
6874 return err;
6876 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6877 worktree);
6878 if (err)
6879 return err;
6881 if (rebase_in_progress || histedit_in_progress) {
6882 err = got_ref_open(&temp_ref, repo,
6883 got_worktree_get_head_ref_name(worktree), 0);
6884 if (err)
6885 return err;
6886 list_branch(repo, worktree, temp_ref);
6887 got_ref_close(temp_ref);
6891 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6892 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6893 repo);
6894 if (err)
6895 return err;
6897 TAILQ_FOREACH(re, &refs, entry)
6898 list_branch(repo, worktree, re->ref);
6900 got_ref_list_free(&refs);
6902 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6903 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6904 repo);
6905 if (err)
6906 return err;
6908 TAILQ_FOREACH(re, &refs, entry)
6909 list_branch(repo, worktree, re->ref);
6911 got_ref_list_free(&refs);
6913 return NULL;
6916 static const struct got_error *
6917 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6918 const char *branch_name)
6920 const struct got_error *err = NULL;
6921 struct got_reference *ref = NULL;
6922 char *refname, *remote_refname = NULL;
6924 if (strncmp(branch_name, "refs/", 5) == 0)
6925 branch_name += 5;
6926 if (strncmp(branch_name, "heads/", 6) == 0)
6927 branch_name += 6;
6928 else if (strncmp(branch_name, "remotes/", 8) == 0)
6929 branch_name += 8;
6931 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6932 return got_error_from_errno("asprintf");
6934 if (asprintf(&remote_refname, "refs/remotes/%s",
6935 branch_name) == -1) {
6936 err = got_error_from_errno("asprintf");
6937 goto done;
6940 err = got_ref_open(&ref, repo, refname, 0);
6941 if (err) {
6942 const struct got_error *err2;
6943 if (err->code != GOT_ERR_NOT_REF)
6944 goto done;
6946 * Keep 'err' intact such that if neither branch exists
6947 * we report "refs/heads" rather than "refs/remotes" in
6948 * our error message.
6950 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6951 if (err2)
6952 goto done;
6953 err = NULL;
6956 if (worktree &&
6957 strcmp(got_worktree_get_head_ref_name(worktree),
6958 got_ref_get_name(ref)) == 0) {
6959 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6960 "will not delete this work tree's current branch");
6961 goto done;
6964 err = delete_ref(repo, ref);
6965 done:
6966 if (ref)
6967 got_ref_close(ref);
6968 free(refname);
6969 free(remote_refname);
6970 return err;
6973 static const struct got_error *
6974 add_branch(struct got_repository *repo, const char *branch_name,
6975 struct got_object_id *base_commit_id)
6977 const struct got_error *err = NULL;
6978 struct got_reference *ref = NULL;
6979 char *refname = NULL;
6982 * Don't let the user create a branch name with a leading '-'.
6983 * While technically a valid reference name, this case is usually
6984 * an unintended typo.
6986 if (branch_name[0] == '-')
6987 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6989 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6990 branch_name += 11;
6992 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6993 err = got_error_from_errno("asprintf");
6994 goto done;
6997 err = got_ref_open(&ref, repo, refname, 0);
6998 if (err == NULL) {
6999 err = got_error(GOT_ERR_BRANCH_EXISTS);
7000 goto done;
7001 } else if (err->code != GOT_ERR_NOT_REF)
7002 goto done;
7004 err = got_ref_alloc(&ref, refname, base_commit_id);
7005 if (err)
7006 goto done;
7008 err = got_ref_write(ref, repo);
7009 done:
7010 if (ref)
7011 got_ref_close(ref);
7012 free(refname);
7013 return err;
7016 static const struct got_error *
7017 cmd_branch(int argc, char *argv[])
7019 const struct got_error *error = NULL;
7020 struct got_repository *repo = NULL;
7021 struct got_worktree *worktree = NULL;
7022 char *cwd = NULL, *repo_path = NULL;
7023 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7024 const char *delref = NULL, *commit_id_arg = NULL;
7025 struct got_reference *ref = NULL;
7026 struct got_pathlist_head paths;
7027 struct got_object_id *commit_id = NULL;
7028 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7029 int *pack_fds = NULL;
7031 TAILQ_INIT(&paths);
7033 #ifndef PROFILE
7034 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7035 "sendfd unveil", NULL) == -1)
7036 err(1, "pledge");
7037 #endif
7039 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7040 switch (ch) {
7041 case 'c':
7042 commit_id_arg = optarg;
7043 break;
7044 case 'd':
7045 delref = optarg;
7046 break;
7047 case 'l':
7048 do_list = 1;
7049 break;
7050 case 'n':
7051 do_update = 0;
7052 break;
7053 case 'r':
7054 repo_path = realpath(optarg, NULL);
7055 if (repo_path == NULL)
7056 return got_error_from_errno2("realpath",
7057 optarg);
7058 got_path_strip_trailing_slashes(repo_path);
7059 break;
7060 case 't':
7061 sort_by_time = 1;
7062 break;
7063 default:
7064 usage_branch();
7065 /* NOTREACHED */
7069 if (do_list && delref)
7070 option_conflict('l', 'd');
7071 if (sort_by_time && !do_list)
7072 errx(1, "-t option requires -l option");
7074 argc -= optind;
7075 argv += optind;
7077 if (!do_list && !delref && argc == 0)
7078 do_show = 1;
7080 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7081 errx(1, "-c option can only be used when creating a branch");
7083 if (do_list || delref) {
7084 if (argc > 0)
7085 usage_branch();
7086 } else if (!do_show && argc != 1)
7087 usage_branch();
7089 cwd = getcwd(NULL, 0);
7090 if (cwd == NULL) {
7091 error = got_error_from_errno("getcwd");
7092 goto done;
7095 error = got_repo_pack_fds_open(&pack_fds);
7096 if (error != NULL)
7097 goto done;
7099 if (repo_path == NULL) {
7100 error = got_worktree_open(&worktree, cwd,
7101 GOT_WORKTREE_GOT_DIR);
7102 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7103 goto done;
7104 else
7105 error = NULL;
7106 if (worktree) {
7107 repo_path =
7108 strdup(got_worktree_get_repo_path(worktree));
7109 if (repo_path == NULL)
7110 error = got_error_from_errno("strdup");
7111 if (error)
7112 goto done;
7113 } else {
7114 repo_path = strdup(cwd);
7115 if (repo_path == NULL) {
7116 error = got_error_from_errno("strdup");
7117 goto done;
7122 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7123 if (error != NULL)
7124 goto done;
7126 #ifndef PROFILE
7127 if (do_list || do_show) {
7128 /* Remove "cpath" promise. */
7129 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7130 NULL) == -1)
7131 err(1, "pledge");
7133 #endif
7135 error = apply_unveil(got_repo_get_path(repo), do_list,
7136 worktree ? got_worktree_get_root_path(worktree) : NULL);
7137 if (error)
7138 goto done;
7140 if (do_show)
7141 error = show_current_branch(repo, worktree);
7142 else if (do_list)
7143 error = list_branches(repo, worktree, sort_by_time);
7144 else if (delref)
7145 error = delete_branch(repo, worktree, delref);
7146 else {
7147 struct got_reflist_head refs;
7148 TAILQ_INIT(&refs);
7149 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7150 NULL);
7151 if (error)
7152 goto done;
7153 if (commit_id_arg == NULL)
7154 commit_id_arg = worktree ?
7155 got_worktree_get_head_ref_name(worktree) :
7156 GOT_REF_HEAD;
7157 else {
7158 error = got_keyword_to_idstr(&keyword_idstr,
7159 commit_id_arg, repo, worktree);
7160 if (error != NULL)
7161 goto done;
7162 if (keyword_idstr != NULL)
7163 commit_id_arg = keyword_idstr;
7165 error = got_repo_match_object_id(&commit_id, NULL,
7166 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7167 got_ref_list_free(&refs);
7168 if (error)
7169 goto done;
7170 error = add_branch(repo, argv[0], commit_id);
7171 if (error)
7172 goto done;
7173 if (worktree && do_update) {
7174 struct got_update_progress_arg upa;
7175 char *branch_refname = NULL;
7177 error = got_object_id_str(&commit_id_str, commit_id);
7178 if (error)
7179 goto done;
7180 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7181 worktree);
7182 if (error)
7183 goto done;
7184 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7185 == -1) {
7186 error = got_error_from_errno("asprintf");
7187 goto done;
7189 error = got_ref_open(&ref, repo, branch_refname, 0);
7190 free(branch_refname);
7191 if (error)
7192 goto done;
7193 error = switch_head_ref(ref, commit_id, worktree,
7194 repo);
7195 if (error)
7196 goto done;
7197 error = got_worktree_set_base_commit_id(worktree, repo,
7198 commit_id);
7199 if (error)
7200 goto done;
7201 memset(&upa, 0, sizeof(upa));
7202 error = got_worktree_checkout_files(worktree, &paths,
7203 repo, update_progress, &upa, check_cancelled,
7204 NULL);
7205 if (error)
7206 goto done;
7207 if (upa.did_something) {
7208 printf("Updated to %s: %s\n",
7209 got_worktree_get_head_ref_name(worktree),
7210 commit_id_str);
7212 print_update_progress_stats(&upa);
7215 done:
7216 free(keyword_idstr);
7217 if (ref)
7218 got_ref_close(ref);
7219 if (repo) {
7220 const struct got_error *close_err = got_repo_close(repo);
7221 if (error == NULL)
7222 error = close_err;
7224 if (worktree)
7225 got_worktree_close(worktree);
7226 if (pack_fds) {
7227 const struct got_error *pack_err =
7228 got_repo_pack_fds_close(pack_fds);
7229 if (error == NULL)
7230 error = pack_err;
7232 free(cwd);
7233 free(repo_path);
7234 free(commit_id);
7235 free(commit_id_str);
7236 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7237 return error;
7241 __dead static void
7242 usage_tag(void)
7244 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7245 "[-r repository-path] [-s signer-id] name\n", getprogname());
7246 exit(1);
7249 #if 0
7250 static const struct got_error *
7251 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7253 const struct got_error *err = NULL;
7254 struct got_reflist_entry *re, *se, *new;
7255 struct got_object_id *re_id, *se_id;
7256 struct got_tag_object *re_tag, *se_tag;
7257 time_t re_time, se_time;
7259 STAILQ_FOREACH(re, tags, entry) {
7260 se = STAILQ_FIRST(sorted);
7261 if (se == NULL) {
7262 err = got_reflist_entry_dup(&new, re);
7263 if (err)
7264 return err;
7265 STAILQ_INSERT_HEAD(sorted, new, entry);
7266 continue;
7267 } else {
7268 err = got_ref_resolve(&re_id, repo, re->ref);
7269 if (err)
7270 break;
7271 err = got_object_open_as_tag(&re_tag, repo, re_id);
7272 free(re_id);
7273 if (err)
7274 break;
7275 re_time = got_object_tag_get_tagger_time(re_tag);
7276 got_object_tag_close(re_tag);
7279 while (se) {
7280 err = got_ref_resolve(&se_id, repo, re->ref);
7281 if (err)
7282 break;
7283 err = got_object_open_as_tag(&se_tag, repo, se_id);
7284 free(se_id);
7285 if (err)
7286 break;
7287 se_time = got_object_tag_get_tagger_time(se_tag);
7288 got_object_tag_close(se_tag);
7290 if (se_time > re_time) {
7291 err = got_reflist_entry_dup(&new, re);
7292 if (err)
7293 return err;
7294 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7295 break;
7297 se = STAILQ_NEXT(se, entry);
7298 continue;
7301 done:
7302 return err;
7304 #endif
7306 static const struct got_error *
7307 get_tag_refname(char **refname, const char *tag_name)
7309 const struct got_error *err;
7311 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7312 *refname = strdup(tag_name);
7313 if (*refname == NULL)
7314 return got_error_from_errno("strdup");
7315 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7316 err = got_error_from_errno("asprintf");
7317 *refname = NULL;
7318 return err;
7321 return NULL;
7324 static const struct got_error *
7325 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7326 const char *allowed_signers, const char *revoked_signers, int verbosity)
7328 static const struct got_error *err = NULL;
7329 struct got_reflist_head refs;
7330 struct got_reflist_entry *re;
7331 char *wanted_refname = NULL;
7332 int bad_sigs = 0;
7334 TAILQ_INIT(&refs);
7336 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7337 if (err)
7338 return err;
7340 if (tag_name) {
7341 struct got_reference *ref;
7342 err = get_tag_refname(&wanted_refname, tag_name);
7343 if (err)
7344 goto done;
7345 /* Wanted tag reference should exist. */
7346 err = got_ref_open(&ref, repo, wanted_refname, 0);
7347 if (err)
7348 goto done;
7349 got_ref_close(ref);
7352 TAILQ_FOREACH(re, &refs, entry) {
7353 const char *refname;
7354 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7355 char datebuf[26];
7356 const char *tagger, *ssh_sig = NULL;
7357 char *sig_msg = NULL;
7358 time_t tagger_time;
7359 struct got_object_id *id;
7360 struct got_tag_object *tag;
7361 struct got_commit_object *commit = NULL;
7363 refname = got_ref_get_name(re->ref);
7364 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7365 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7366 continue;
7367 refname += 10;
7368 refstr = got_ref_to_str(re->ref);
7369 if (refstr == NULL) {
7370 err = got_error_from_errno("got_ref_to_str");
7371 break;
7374 err = got_ref_resolve(&id, repo, re->ref);
7375 if (err)
7376 break;
7377 err = got_object_open_as_tag(&tag, repo, id);
7378 if (err) {
7379 if (err->code != GOT_ERR_OBJ_TYPE) {
7380 free(id);
7381 break;
7383 /* "lightweight" tag */
7384 err = got_object_open_as_commit(&commit, repo, id);
7385 if (err) {
7386 free(id);
7387 break;
7389 tagger = got_object_commit_get_committer(commit);
7390 tagger_time =
7391 got_object_commit_get_committer_time(commit);
7392 err = got_object_id_str(&id_str, id);
7393 free(id);
7394 if (err)
7395 break;
7396 } else {
7397 free(id);
7398 tagger = got_object_tag_get_tagger(tag);
7399 tagger_time = got_object_tag_get_tagger_time(tag);
7400 err = got_object_id_str(&id_str,
7401 got_object_tag_get_object_id(tag));
7402 if (err)
7403 break;
7406 if (tag && verify_tags) {
7407 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7408 got_object_tag_get_message(tag));
7409 if (ssh_sig && allowed_signers == NULL) {
7410 err = got_error_msg(
7411 GOT_ERR_VERIFY_TAG_SIGNATURE,
7412 "SSH signature verification requires "
7413 "setting allowed_signers in "
7414 "got.conf(5)");
7415 break;
7419 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7420 free(refstr);
7421 printf("from: %s\n", tagger);
7422 datestr = get_datestr(&tagger_time, datebuf);
7423 if (datestr)
7424 printf("date: %s UTC\n", datestr);
7425 if (commit)
7426 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7427 else {
7428 switch (got_object_tag_get_object_type(tag)) {
7429 case GOT_OBJ_TYPE_BLOB:
7430 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7431 id_str);
7432 break;
7433 case GOT_OBJ_TYPE_TREE:
7434 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7435 id_str);
7436 break;
7437 case GOT_OBJ_TYPE_COMMIT:
7438 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7439 id_str);
7440 break;
7441 case GOT_OBJ_TYPE_TAG:
7442 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7443 id_str);
7444 break;
7445 default:
7446 break;
7449 free(id_str);
7451 if (ssh_sig) {
7452 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7453 allowed_signers, revoked_signers, verbosity);
7454 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7455 bad_sigs = 1;
7456 else if (err)
7457 break;
7458 printf("signature: %s", sig_msg);
7459 free(sig_msg);
7460 sig_msg = NULL;
7463 if (commit) {
7464 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7465 if (err)
7466 break;
7467 got_object_commit_close(commit);
7468 } else {
7469 tagmsg0 = strdup(got_object_tag_get_message(tag));
7470 got_object_tag_close(tag);
7471 if (tagmsg0 == NULL) {
7472 err = got_error_from_errno("strdup");
7473 break;
7477 tagmsg = tagmsg0;
7478 do {
7479 line = strsep(&tagmsg, "\n");
7480 if (line)
7481 printf(" %s\n", line);
7482 } while (line);
7483 free(tagmsg0);
7485 done:
7486 got_ref_list_free(&refs);
7487 free(wanted_refname);
7489 if (err == NULL && bad_sigs)
7490 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7491 return err;
7494 static const struct got_error *
7495 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7496 const char *tag_name, const char *repo_path)
7498 const struct got_error *err = NULL;
7499 char *template = NULL, *initial_content = NULL;
7500 char *editor = NULL;
7501 int initial_content_len;
7502 int fd = -1;
7504 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7505 err = got_error_from_errno("asprintf");
7506 goto done;
7509 initial_content_len = asprintf(&initial_content,
7510 "\n# tagging commit %s as %s\n",
7511 commit_id_str, tag_name);
7512 if (initial_content_len == -1) {
7513 err = got_error_from_errno("asprintf");
7514 goto done;
7517 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7518 if (err)
7519 goto done;
7521 if (write(fd, initial_content, initial_content_len) == -1) {
7522 err = got_error_from_errno2("write", *tagmsg_path);
7523 goto done;
7525 if (close(fd) == -1) {
7526 err = got_error_from_errno2("close", *tagmsg_path);
7527 goto done;
7529 fd = -1;
7531 err = get_editor(&editor);
7532 if (err)
7533 goto done;
7534 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7535 initial_content_len, 1);
7536 done:
7537 free(initial_content);
7538 free(template);
7539 free(editor);
7541 if (fd != -1 && close(fd) == -1 && err == NULL)
7542 err = got_error_from_errno2("close", *tagmsg_path);
7544 if (err) {
7545 free(*tagmsg);
7546 *tagmsg = NULL;
7548 return err;
7551 static const struct got_error *
7552 add_tag(struct got_repository *repo, const char *tagger,
7553 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7554 const char *signer_id, int verbosity)
7556 const struct got_error *err = NULL;
7557 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7558 char *label = NULL, *commit_id_str = NULL;
7559 struct got_reference *ref = NULL;
7560 char *refname = NULL, *tagmsg = NULL;
7561 char *tagmsg_path = NULL, *tag_id_str = NULL;
7562 int preserve_tagmsg = 0;
7563 struct got_reflist_head refs;
7565 TAILQ_INIT(&refs);
7568 * Don't let the user create a tag name with a leading '-'.
7569 * While technically a valid reference name, this case is usually
7570 * an unintended typo.
7572 if (tag_name[0] == '-')
7573 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7575 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7576 if (err)
7577 goto done;
7579 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7580 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7581 if (err)
7582 goto done;
7584 err = got_object_id_str(&commit_id_str, commit_id);
7585 if (err)
7586 goto done;
7588 err = get_tag_refname(&refname, tag_name);
7589 if (err)
7590 goto done;
7591 if (strncmp("refs/tags/", tag_name, 10) == 0)
7592 tag_name += 10;
7594 err = got_ref_open(&ref, repo, refname, 0);
7595 if (err == NULL) {
7596 err = got_error(GOT_ERR_TAG_EXISTS);
7597 goto done;
7598 } else if (err->code != GOT_ERR_NOT_REF)
7599 goto done;
7601 if (tagmsg_arg == NULL) {
7602 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7603 tag_name, got_repo_get_path(repo));
7604 if (err) {
7605 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7606 tagmsg_path != NULL)
7607 preserve_tagmsg = 1;
7608 goto done;
7610 /* Editor is done; we can now apply unveil(2) */
7611 err = got_sigs_apply_unveil();
7612 if (err)
7613 goto done;
7614 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7615 if (err)
7616 goto done;
7619 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7620 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7621 verbosity);
7622 if (err) {
7623 if (tagmsg_path)
7624 preserve_tagmsg = 1;
7625 goto done;
7628 err = got_ref_alloc(&ref, refname, tag_id);
7629 if (err) {
7630 if (tagmsg_path)
7631 preserve_tagmsg = 1;
7632 goto done;
7635 err = got_ref_write(ref, repo);
7636 if (err) {
7637 if (tagmsg_path)
7638 preserve_tagmsg = 1;
7639 goto done;
7642 err = got_object_id_str(&tag_id_str, tag_id);
7643 if (err) {
7644 if (tagmsg_path)
7645 preserve_tagmsg = 1;
7646 goto done;
7648 printf("Created tag %s\n", tag_id_str);
7649 done:
7650 if (preserve_tagmsg) {
7651 fprintf(stderr, "%s: tag message preserved in %s\n",
7652 getprogname(), tagmsg_path);
7653 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7654 err = got_error_from_errno2("unlink", tagmsg_path);
7655 free(tag_id_str);
7656 if (ref)
7657 got_ref_close(ref);
7658 free(commit_id);
7659 free(commit_id_str);
7660 free(refname);
7661 free(tagmsg);
7662 free(tagmsg_path);
7663 got_ref_list_free(&refs);
7664 return err;
7667 static const struct got_error *
7668 cmd_tag(int argc, char *argv[])
7670 const struct got_error *error = NULL;
7671 struct got_repository *repo = NULL;
7672 struct got_worktree *worktree = NULL;
7673 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7674 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7675 char *allowed_signers = NULL, *revoked_signers = NULL;
7676 const char *signer_id = NULL;
7677 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7678 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7679 int *pack_fds = NULL;
7681 #ifndef PROFILE
7682 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7683 "sendfd unveil", NULL) == -1)
7684 err(1, "pledge");
7685 #endif
7687 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7688 switch (ch) {
7689 case 'c':
7690 commit_id_arg = optarg;
7691 break;
7692 case 'l':
7693 do_list = 1;
7694 break;
7695 case 'm':
7696 tagmsg = optarg;
7697 break;
7698 case 'r':
7699 repo_path = realpath(optarg, NULL);
7700 if (repo_path == NULL) {
7701 error = got_error_from_errno2("realpath",
7702 optarg);
7703 goto done;
7705 got_path_strip_trailing_slashes(repo_path);
7706 break;
7707 case 's':
7708 signer_id = optarg;
7709 break;
7710 case 'V':
7711 verify_tags = 1;
7712 break;
7713 case 'v':
7714 if (verbosity < 0)
7715 verbosity = 0;
7716 else if (verbosity < 3)
7717 verbosity++;
7718 break;
7719 default:
7720 usage_tag();
7721 /* NOTREACHED */
7725 argc -= optind;
7726 argv += optind;
7728 if (do_list || verify_tags) {
7729 if (commit_id_arg != NULL)
7730 errx(1,
7731 "-c option can only be used when creating a tag");
7732 if (tagmsg) {
7733 if (do_list)
7734 option_conflict('l', 'm');
7735 else
7736 option_conflict('V', 'm');
7738 if (signer_id) {
7739 if (do_list)
7740 option_conflict('l', 's');
7741 else
7742 option_conflict('V', 's');
7744 if (argc > 1)
7745 usage_tag();
7746 } else if (argc != 1)
7747 usage_tag();
7749 if (argc == 1)
7750 tag_name = argv[0];
7752 cwd = getcwd(NULL, 0);
7753 if (cwd == NULL) {
7754 error = got_error_from_errno("getcwd");
7755 goto done;
7758 error = got_repo_pack_fds_open(&pack_fds);
7759 if (error != NULL)
7760 goto done;
7762 if (repo_path == NULL) {
7763 error = got_worktree_open(&worktree, cwd,
7764 GOT_WORKTREE_GOT_DIR);
7765 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7766 goto done;
7767 else
7768 error = NULL;
7769 if (worktree) {
7770 repo_path =
7771 strdup(got_worktree_get_repo_path(worktree));
7772 if (repo_path == NULL)
7773 error = got_error_from_errno("strdup");
7774 if (error)
7775 goto done;
7776 } else {
7777 repo_path = strdup(cwd);
7778 if (repo_path == NULL) {
7779 error = got_error_from_errno("strdup");
7780 goto done;
7785 if (do_list || verify_tags) {
7786 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7787 if (error != NULL)
7788 goto done;
7789 error = get_allowed_signers(&allowed_signers, repo, worktree);
7790 if (error)
7791 goto done;
7792 error = get_revoked_signers(&revoked_signers, repo, worktree);
7793 if (error)
7794 goto done;
7795 if (worktree) {
7796 /* Release work tree lock. */
7797 got_worktree_close(worktree);
7798 worktree = NULL;
7802 * Remove "cpath" promise unless needed for signature tmpfile
7803 * creation.
7805 if (verify_tags)
7806 got_sigs_apply_unveil();
7807 else {
7808 #ifndef PROFILE
7809 if (pledge("stdio rpath wpath flock proc exec sendfd "
7810 "unveil", NULL) == -1)
7811 err(1, "pledge");
7812 #endif
7814 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7815 if (error)
7816 goto done;
7817 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7818 revoked_signers, verbosity);
7819 } else {
7820 error = get_gitconfig_path(&gitconfig_path);
7821 if (error)
7822 goto done;
7823 error = got_repo_open(&repo, repo_path, gitconfig_path,
7824 pack_fds);
7825 if (error != NULL)
7826 goto done;
7828 error = get_author(&tagger, repo, worktree);
7829 if (error)
7830 goto done;
7831 if (signer_id == NULL)
7832 signer_id = get_signer_id(repo, worktree);
7834 if (tagmsg) {
7835 if (signer_id) {
7836 error = got_sigs_apply_unveil();
7837 if (error)
7838 goto done;
7840 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7841 if (error)
7842 goto done;
7845 if (commit_id_arg == NULL) {
7846 struct got_reference *head_ref;
7847 struct got_object_id *commit_id;
7848 error = got_ref_open(&head_ref, repo,
7849 worktree ? got_worktree_get_head_ref_name(worktree)
7850 : GOT_REF_HEAD, 0);
7851 if (error)
7852 goto done;
7853 error = got_ref_resolve(&commit_id, repo, head_ref);
7854 got_ref_close(head_ref);
7855 if (error)
7856 goto done;
7857 error = got_object_id_str(&commit_id_str, commit_id);
7858 free(commit_id);
7859 if (error)
7860 goto done;
7861 } else {
7862 error = got_keyword_to_idstr(&keyword_idstr,
7863 commit_id_arg, repo, worktree);
7864 if (error != NULL)
7865 goto done;
7866 commit_id_str = keyword_idstr;
7869 if (worktree) {
7870 /* Release work tree lock. */
7871 got_worktree_close(worktree);
7872 worktree = NULL;
7875 error = add_tag(repo, tagger, tag_name,
7876 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7877 signer_id, verbosity);
7879 done:
7880 if (repo) {
7881 const struct got_error *close_err = got_repo_close(repo);
7882 if (error == NULL)
7883 error = close_err;
7885 if (worktree)
7886 got_worktree_close(worktree);
7887 if (pack_fds) {
7888 const struct got_error *pack_err =
7889 got_repo_pack_fds_close(pack_fds);
7890 if (error == NULL)
7891 error = pack_err;
7893 free(cwd);
7894 free(repo_path);
7895 free(gitconfig_path);
7896 free(commit_id_str);
7897 free(tagger);
7898 free(allowed_signers);
7899 free(revoked_signers);
7900 return error;
7903 __dead static void
7904 usage_add(void)
7906 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7907 exit(1);
7910 static const struct got_error *
7911 add_progress(void *arg, unsigned char status, const char *path)
7913 while (path[0] == '/')
7914 path++;
7915 printf("%c %s\n", status, path);
7916 return NULL;
7919 static const struct got_error *
7920 cmd_add(int argc, char *argv[])
7922 const struct got_error *error = NULL;
7923 struct got_repository *repo = NULL;
7924 struct got_worktree *worktree = NULL;
7925 char *cwd = NULL;
7926 struct got_pathlist_head paths;
7927 struct got_pathlist_entry *pe;
7928 int ch, can_recurse = 0, no_ignores = 0;
7929 int *pack_fds = NULL;
7931 TAILQ_INIT(&paths);
7933 #ifndef PROFILE
7934 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7935 NULL) == -1)
7936 err(1, "pledge");
7937 #endif
7939 while ((ch = getopt(argc, argv, "IR")) != -1) {
7940 switch (ch) {
7941 case 'I':
7942 no_ignores = 1;
7943 break;
7944 case 'R':
7945 can_recurse = 1;
7946 break;
7947 default:
7948 usage_add();
7949 /* NOTREACHED */
7953 argc -= optind;
7954 argv += optind;
7956 if (argc < 1)
7957 usage_add();
7959 cwd = getcwd(NULL, 0);
7960 if (cwd == NULL) {
7961 error = got_error_from_errno("getcwd");
7962 goto done;
7965 error = got_repo_pack_fds_open(&pack_fds);
7966 if (error != NULL)
7967 goto done;
7969 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7970 if (error) {
7971 if (error->code == GOT_ERR_NOT_WORKTREE)
7972 error = wrap_not_worktree_error(error, "add", cwd);
7973 goto done;
7976 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7977 NULL, pack_fds);
7978 if (error != NULL)
7979 goto done;
7981 error = apply_unveil(got_repo_get_path(repo), 1,
7982 got_worktree_get_root_path(worktree));
7983 if (error)
7984 goto done;
7986 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7987 if (error)
7988 goto done;
7990 if (!can_recurse) {
7991 char *ondisk_path;
7992 struct stat sb;
7993 TAILQ_FOREACH(pe, &paths, entry) {
7994 if (asprintf(&ondisk_path, "%s/%s",
7995 got_worktree_get_root_path(worktree),
7996 pe->path) == -1) {
7997 error = got_error_from_errno("asprintf");
7998 goto done;
8000 if (lstat(ondisk_path, &sb) == -1) {
8001 if (errno == ENOENT) {
8002 free(ondisk_path);
8003 continue;
8005 error = got_error_from_errno2("lstat",
8006 ondisk_path);
8007 free(ondisk_path);
8008 goto done;
8010 free(ondisk_path);
8011 if (S_ISDIR(sb.st_mode)) {
8012 error = got_error_msg(GOT_ERR_BAD_PATH,
8013 "adding directories requires -R option");
8014 goto done;
8019 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8020 NULL, repo, no_ignores);
8021 done:
8022 if (repo) {
8023 const struct got_error *close_err = got_repo_close(repo);
8024 if (error == NULL)
8025 error = close_err;
8027 if (worktree)
8028 got_worktree_close(worktree);
8029 if (pack_fds) {
8030 const struct got_error *pack_err =
8031 got_repo_pack_fds_close(pack_fds);
8032 if (error == NULL)
8033 error = pack_err;
8035 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8036 free(cwd);
8037 return error;
8040 __dead static void
8041 usage_remove(void)
8043 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8044 getprogname());
8045 exit(1);
8048 static const struct got_error *
8049 print_remove_status(void *arg, unsigned char status,
8050 unsigned char staged_status, const char *path)
8052 while (path[0] == '/')
8053 path++;
8054 if (status == GOT_STATUS_NONEXISTENT)
8055 return NULL;
8056 if (status == staged_status && (status == GOT_STATUS_DELETE))
8057 status = GOT_STATUS_NO_CHANGE;
8058 printf("%c%c %s\n", status, staged_status, path);
8059 return NULL;
8062 static const struct got_error *
8063 cmd_remove(int argc, char *argv[])
8065 const struct got_error *error = NULL;
8066 struct got_worktree *worktree = NULL;
8067 struct got_repository *repo = NULL;
8068 const char *status_codes = NULL;
8069 char *cwd = NULL;
8070 struct got_pathlist_head paths;
8071 struct got_pathlist_entry *pe;
8072 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8073 int ignore_missing_paths = 0;
8074 int *pack_fds = NULL;
8076 TAILQ_INIT(&paths);
8078 #ifndef PROFILE
8079 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8080 NULL) == -1)
8081 err(1, "pledge");
8082 #endif
8084 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8085 switch (ch) {
8086 case 'f':
8087 delete_local_mods = 1;
8088 ignore_missing_paths = 1;
8089 break;
8090 case 'k':
8091 keep_on_disk = 1;
8092 break;
8093 case 'R':
8094 can_recurse = 1;
8095 break;
8096 case 's':
8097 for (i = 0; optarg[i] != '\0'; i++) {
8098 switch (optarg[i]) {
8099 case GOT_STATUS_MODIFY:
8100 delete_local_mods = 1;
8101 break;
8102 case GOT_STATUS_MISSING:
8103 ignore_missing_paths = 1;
8104 break;
8105 default:
8106 errx(1, "invalid status code '%c'",
8107 optarg[i]);
8110 status_codes = optarg;
8111 break;
8112 default:
8113 usage_remove();
8114 /* NOTREACHED */
8118 argc -= optind;
8119 argv += optind;
8121 if (argc < 1)
8122 usage_remove();
8124 cwd = getcwd(NULL, 0);
8125 if (cwd == NULL) {
8126 error = got_error_from_errno("getcwd");
8127 goto done;
8130 error = got_repo_pack_fds_open(&pack_fds);
8131 if (error != NULL)
8132 goto done;
8134 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8135 if (error) {
8136 if (error->code == GOT_ERR_NOT_WORKTREE)
8137 error = wrap_not_worktree_error(error, "remove", cwd);
8138 goto done;
8141 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8142 NULL, pack_fds);
8143 if (error)
8144 goto done;
8146 error = apply_unveil(got_repo_get_path(repo), 1,
8147 got_worktree_get_root_path(worktree));
8148 if (error)
8149 goto done;
8151 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8152 if (error)
8153 goto done;
8155 if (!can_recurse) {
8156 char *ondisk_path;
8157 struct stat sb;
8158 TAILQ_FOREACH(pe, &paths, entry) {
8159 if (asprintf(&ondisk_path, "%s/%s",
8160 got_worktree_get_root_path(worktree),
8161 pe->path) == -1) {
8162 error = got_error_from_errno("asprintf");
8163 goto done;
8165 if (lstat(ondisk_path, &sb) == -1) {
8166 if (errno == ENOENT) {
8167 free(ondisk_path);
8168 continue;
8170 error = got_error_from_errno2("lstat",
8171 ondisk_path);
8172 free(ondisk_path);
8173 goto done;
8175 free(ondisk_path);
8176 if (S_ISDIR(sb.st_mode)) {
8177 error = got_error_msg(GOT_ERR_BAD_PATH,
8178 "removing directories requires -R option");
8179 goto done;
8184 error = got_worktree_schedule_delete(worktree, &paths,
8185 delete_local_mods, status_codes, print_remove_status, NULL,
8186 repo, keep_on_disk, ignore_missing_paths);
8187 done:
8188 if (repo) {
8189 const struct got_error *close_err = got_repo_close(repo);
8190 if (error == NULL)
8191 error = close_err;
8193 if (worktree)
8194 got_worktree_close(worktree);
8195 if (pack_fds) {
8196 const struct got_error *pack_err =
8197 got_repo_pack_fds_close(pack_fds);
8198 if (error == NULL)
8199 error = pack_err;
8201 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8202 free(cwd);
8203 return error;
8206 __dead static void
8207 usage_patch(void)
8209 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8210 "[patchfile]\n", getprogname());
8211 exit(1);
8214 static const struct got_error *
8215 patch_from_stdin(int *patchfd)
8217 const struct got_error *err = NULL;
8218 ssize_t r;
8219 char buf[BUFSIZ];
8220 sig_t sighup, sigint, sigquit;
8222 *patchfd = got_opentempfd();
8223 if (*patchfd == -1)
8224 return got_error_from_errno("got_opentempfd");
8226 sighup = signal(SIGHUP, SIG_DFL);
8227 sigint = signal(SIGINT, SIG_DFL);
8228 sigquit = signal(SIGQUIT, SIG_DFL);
8230 for (;;) {
8231 r = read(0, buf, sizeof(buf));
8232 if (r == -1) {
8233 err = got_error_from_errno("read");
8234 break;
8236 if (r == 0)
8237 break;
8238 if (write(*patchfd, buf, r) == -1) {
8239 err = got_error_from_errno("write");
8240 break;
8244 signal(SIGHUP, sighup);
8245 signal(SIGINT, sigint);
8246 signal(SIGQUIT, sigquit);
8248 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8249 err = got_error_from_errno("lseek");
8251 if (err != NULL) {
8252 close(*patchfd);
8253 *patchfd = -1;
8256 return err;
8259 struct got_patch_progress_arg {
8260 int did_something;
8261 int conflicts;
8262 int rejects;
8265 static const struct got_error *
8266 patch_progress(void *arg, const char *old, const char *new,
8267 unsigned char status, const struct got_error *error, int old_from,
8268 int old_lines, int new_from, int new_lines, int offset,
8269 int ws_mangled, const struct got_error *hunk_err)
8271 const char *path = new == NULL ? old : new;
8272 struct got_patch_progress_arg *a = arg;
8274 while (*path == '/')
8275 path++;
8277 if (status != GOT_STATUS_NO_CHANGE &&
8278 status != 0 /* per-hunk progress */) {
8279 printf("%c %s\n", status, path);
8280 a->did_something = 1;
8283 if (hunk_err == NULL) {
8284 if (status == GOT_STATUS_CANNOT_UPDATE)
8285 a->rejects++;
8286 else if (status == GOT_STATUS_CONFLICT)
8287 a->conflicts++;
8290 if (error != NULL)
8291 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8293 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8294 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8295 old_lines, new_from, new_lines);
8296 if (hunk_err != NULL)
8297 printf("%s\n", hunk_err->msg);
8298 else if (offset != 0)
8299 printf("applied with offset %d\n", offset);
8300 else
8301 printf("hunk contains mangled whitespace\n");
8304 return NULL;
8307 static void
8308 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8310 if (!ppa->did_something)
8311 return;
8313 if (ppa->conflicts > 0)
8314 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8316 if (ppa->rejects > 0) {
8317 printf("Files where patch failed to apply: %d\n",
8318 ppa->rejects);
8322 static const struct got_error *
8323 cmd_patch(int argc, char *argv[])
8325 const struct got_error *error = NULL, *close_error = NULL;
8326 struct got_worktree *worktree = NULL;
8327 struct got_repository *repo = NULL;
8328 struct got_reflist_head refs;
8329 struct got_object_id *commit_id = NULL;
8330 const char *commit_id_str = NULL;
8331 struct stat sb;
8332 const char *errstr;
8333 char *cwd = NULL, *keyword_idstr = NULL;
8334 int ch, nop = 0, strip = -1, reverse = 0;
8335 int patchfd;
8336 int *pack_fds = NULL;
8337 struct got_patch_progress_arg ppa;
8339 TAILQ_INIT(&refs);
8341 #ifndef PROFILE
8342 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8343 "unveil", NULL) == -1)
8344 err(1, "pledge");
8345 #endif
8347 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8348 switch (ch) {
8349 case 'c':
8350 commit_id_str = optarg;
8351 break;
8352 case 'n':
8353 nop = 1;
8354 break;
8355 case 'p':
8356 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8357 if (errstr != NULL)
8358 errx(1, "pathname strip count is %s: %s",
8359 errstr, optarg);
8360 break;
8361 case 'R':
8362 reverse = 1;
8363 break;
8364 default:
8365 usage_patch();
8366 /* NOTREACHED */
8370 argc -= optind;
8371 argv += optind;
8373 if (argc == 0) {
8374 error = patch_from_stdin(&patchfd);
8375 if (error)
8376 return error;
8377 } else if (argc == 1) {
8378 patchfd = open(argv[0], O_RDONLY);
8379 if (patchfd == -1) {
8380 error = got_error_from_errno2("open", argv[0]);
8381 return error;
8383 if (fstat(patchfd, &sb) == -1) {
8384 error = got_error_from_errno2("fstat", argv[0]);
8385 goto done;
8387 if (!S_ISREG(sb.st_mode)) {
8388 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8389 goto done;
8391 } else
8392 usage_patch();
8394 if ((cwd = getcwd(NULL, 0)) == NULL) {
8395 error = got_error_from_errno("getcwd");
8396 goto done;
8399 error = got_repo_pack_fds_open(&pack_fds);
8400 if (error != NULL)
8401 goto done;
8403 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8404 if (error != NULL)
8405 goto done;
8407 const char *repo_path = got_worktree_get_repo_path(worktree);
8408 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8409 if (error != NULL)
8410 goto done;
8412 error = apply_unveil(got_repo_get_path(repo), 0,
8413 got_worktree_get_root_path(worktree));
8414 if (error != NULL)
8415 goto done;
8417 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8418 if (error)
8419 goto done;
8421 if (commit_id_str != NULL) {
8422 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8423 repo, worktree);
8424 if (error != NULL)
8425 goto done;
8427 error = got_repo_match_object_id(&commit_id, NULL,
8428 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8429 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8430 if (error)
8431 goto done;
8434 memset(&ppa, 0, sizeof(ppa));
8435 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8436 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8437 print_patch_progress_stats(&ppa);
8438 done:
8439 got_ref_list_free(&refs);
8440 free(keyword_idstr);
8441 free(commit_id);
8442 if (repo) {
8443 close_error = got_repo_close(repo);
8444 if (error == NULL)
8445 error = close_error;
8447 if (worktree != NULL) {
8448 close_error = got_worktree_close(worktree);
8449 if (error == NULL)
8450 error = close_error;
8452 if (pack_fds) {
8453 const struct got_error *pack_err =
8454 got_repo_pack_fds_close(pack_fds);
8455 if (error == NULL)
8456 error = pack_err;
8458 free(cwd);
8459 return error;
8462 __dead static void
8463 usage_revert(void)
8465 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8466 getprogname());
8467 exit(1);
8470 static const struct got_error *
8471 revert_progress(void *arg, unsigned char status, const char *path)
8473 if (status == GOT_STATUS_UNVERSIONED)
8474 return NULL;
8476 while (path[0] == '/')
8477 path++;
8478 printf("%c %s\n", status, path);
8479 return NULL;
8482 struct choose_patch_arg {
8483 FILE *patch_script_file;
8484 const char *action;
8487 static const struct got_error *
8488 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8489 int nchanges, const char *action)
8491 const struct got_error *err;
8492 char *line = NULL;
8493 size_t linesize = 0;
8494 ssize_t linelen;
8496 switch (status) {
8497 case GOT_STATUS_ADD:
8498 printf("A %s\n%s this addition? [y/n] ", path, action);
8499 break;
8500 case GOT_STATUS_DELETE:
8501 printf("D %s\n%s this deletion? [y/n] ", path, action);
8502 break;
8503 case GOT_STATUS_MODIFY:
8504 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8505 return got_error_from_errno("fseek");
8506 printf(GOT_COMMIT_SEP_STR);
8507 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8508 printf("%s", line);
8509 if (linelen == -1 && ferror(patch_file)) {
8510 err = got_error_from_errno("getline");
8511 free(line);
8512 return err;
8514 free(line);
8515 printf(GOT_COMMIT_SEP_STR);
8516 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8517 path, n, nchanges, action);
8518 break;
8519 default:
8520 return got_error_path(path, GOT_ERR_FILE_STATUS);
8523 fflush(stdout);
8524 return NULL;
8527 static const struct got_error *
8528 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8529 FILE *patch_file, int n, int nchanges)
8531 const struct got_error *err = NULL;
8532 char *line = NULL;
8533 size_t linesize = 0;
8534 ssize_t linelen;
8535 int resp = ' ';
8536 struct choose_patch_arg *a = arg;
8538 *choice = GOT_PATCH_CHOICE_NONE;
8540 if (a->patch_script_file) {
8541 char *nl;
8542 err = show_change(status, path, patch_file, n, nchanges,
8543 a->action);
8544 if (err)
8545 return err;
8546 linelen = getline(&line, &linesize, a->patch_script_file);
8547 if (linelen == -1) {
8548 if (ferror(a->patch_script_file))
8549 return got_error_from_errno("getline");
8550 return NULL;
8552 nl = strchr(line, '\n');
8553 if (nl)
8554 *nl = '\0';
8555 if (strcmp(line, "y") == 0) {
8556 *choice = GOT_PATCH_CHOICE_YES;
8557 printf("y\n");
8558 } else if (strcmp(line, "n") == 0) {
8559 *choice = GOT_PATCH_CHOICE_NO;
8560 printf("n\n");
8561 } else if (strcmp(line, "q") == 0 &&
8562 status == GOT_STATUS_MODIFY) {
8563 *choice = GOT_PATCH_CHOICE_QUIT;
8564 printf("q\n");
8565 } else
8566 printf("invalid response '%s'\n", line);
8567 free(line);
8568 return NULL;
8571 while (resp != 'y' && resp != 'n' && resp != 'q') {
8572 err = show_change(status, path, patch_file, n, nchanges,
8573 a->action);
8574 if (err)
8575 return err;
8576 resp = getchar();
8577 if (resp == '\n')
8578 resp = getchar();
8579 if (status == GOT_STATUS_MODIFY) {
8580 if (resp != 'y' && resp != 'n' && resp != 'q') {
8581 printf("invalid response '%c'\n", resp);
8582 resp = ' ';
8584 } else if (resp != 'y' && resp != 'n') {
8585 printf("invalid response '%c'\n", resp);
8586 resp = ' ';
8590 if (resp == 'y')
8591 *choice = GOT_PATCH_CHOICE_YES;
8592 else if (resp == 'n')
8593 *choice = GOT_PATCH_CHOICE_NO;
8594 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8595 *choice = GOT_PATCH_CHOICE_QUIT;
8597 return NULL;
8600 struct wt_commitable_path_arg {
8601 struct got_pathlist_head *commit_paths;
8602 int *has_changes;
8606 * Shortcut work tree status callback to determine if the set of paths scanned
8607 * has at least one versioned path that is being modified and, if not NULL, is
8608 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8609 * soon as a path is passed with a status that satisfies this criteria.
8611 static const struct got_error *
8612 worktree_has_commitable_path(void *arg, unsigned char status,
8613 unsigned char staged_status, const char *path,
8614 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8615 struct got_object_id *commit_id, int dirfd, const char *de_name)
8617 struct wt_commitable_path_arg *a = arg;
8619 if (status == staged_status && (status == GOT_STATUS_DELETE))
8620 status = GOT_STATUS_NO_CHANGE;
8622 if (!(status == GOT_STATUS_NO_CHANGE ||
8623 status == GOT_STATUS_UNVERSIONED) ||
8624 staged_status != GOT_STATUS_NO_CHANGE) {
8625 if (a->commit_paths != NULL) {
8626 struct got_pathlist_entry *pe;
8628 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8629 if (strncmp(path, pe->path,
8630 pe->path_len) == 0) {
8631 *a->has_changes = 1;
8632 break;
8635 } else
8636 *a->has_changes = 1;
8638 if (*a->has_changes)
8639 return got_error(GOT_ERR_FILE_MODIFIED);
8642 return NULL;
8646 * Check that the changeset of the commit identified by id is
8647 * comprised of at least one modified path that is being committed.
8649 static const struct got_error *
8650 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8651 struct got_object_id *id, struct got_worktree *worktree,
8652 struct got_repository *repo)
8654 const struct got_error *err;
8655 struct got_pathlist_head paths;
8656 struct got_commit_object *commit = NULL, *pcommit = NULL;
8657 struct got_tree_object *tree = NULL, *ptree = NULL;
8658 struct got_object_qid *pid;
8660 TAILQ_INIT(&paths);
8662 err = got_object_open_as_commit(&commit, repo, id);
8663 if (err)
8664 goto done;
8666 err = got_object_open_as_tree(&tree, repo,
8667 got_object_commit_get_tree_id(commit));
8668 if (err)
8669 goto done;
8671 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8672 if (pid != NULL) {
8673 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8674 if (err)
8675 goto done;
8677 err = got_object_open_as_tree(&ptree, repo,
8678 got_object_commit_get_tree_id(pcommit));
8679 if (err)
8680 goto done;
8683 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8684 got_diff_tree_collect_changed_paths, &paths, 0);
8685 if (err)
8686 goto done;
8688 err = got_worktree_status(worktree, &paths, repo, 0,
8689 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8690 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8692 * At least one changed path in the referenced commit is
8693 * modified in the work tree, that's all we need to know!
8695 err = NULL;
8698 done:
8699 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8700 if (commit)
8701 got_object_commit_close(commit);
8702 if (pcommit)
8703 got_object_commit_close(pcommit);
8704 if (tree)
8705 got_object_tree_close(tree);
8706 if (ptree)
8707 got_object_tree_close(ptree);
8708 return err;
8712 * Remove any "logmsg" reference comprised entirely of paths that have
8713 * been reverted in this work tree. If any path in the logmsg ref changeset
8714 * remains in a changed state in the worktree, do not remove the reference.
8716 static const struct got_error *
8717 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8719 const struct got_error *err;
8720 struct got_reflist_head refs;
8721 struct got_reflist_entry *re;
8722 struct got_commit_object *commit = NULL;
8723 struct got_object_id *commit_id = NULL;
8724 struct wt_commitable_path_arg wcpa;
8725 char *uuidstr = NULL;
8727 TAILQ_INIT(&refs);
8729 err = got_worktree_get_uuid(&uuidstr, worktree);
8730 if (err)
8731 goto done;
8733 err = got_ref_list(&refs, repo, "refs/got/worktree",
8734 got_ref_cmp_by_name, repo);
8735 if (err)
8736 goto done;
8738 TAILQ_FOREACH(re, &refs, entry) {
8739 const char *refname;
8740 int has_changes = 0;
8742 refname = got_ref_get_name(re->ref);
8744 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8745 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8746 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8747 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8748 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8749 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8750 else
8751 continue;
8753 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8754 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8755 else
8756 continue;
8758 err = got_repo_match_object_id(&commit_id, NULL, refname,
8759 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8760 if (err)
8761 goto done;
8763 err = got_object_open_as_commit(&commit, repo, commit_id);
8764 if (err)
8765 goto done;
8767 wcpa.commit_paths = NULL;
8768 wcpa.has_changes = &has_changes;
8770 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8771 worktree, repo);
8772 if (err)
8773 goto done;
8775 if (!has_changes) {
8776 err = got_ref_delete(re->ref, repo);
8777 if (err)
8778 goto done;
8781 got_object_commit_close(commit);
8782 commit = NULL;
8783 free(commit_id);
8784 commit_id = NULL;
8787 done:
8788 free(uuidstr);
8789 free(commit_id);
8790 got_ref_list_free(&refs);
8791 if (commit)
8792 got_object_commit_close(commit);
8793 return err;
8796 static const struct got_error *
8797 cmd_revert(int argc, char *argv[])
8799 const struct got_error *error = NULL;
8800 struct got_worktree *worktree = NULL;
8801 struct got_repository *repo = NULL;
8802 char *cwd = NULL, *path = NULL;
8803 struct got_pathlist_head paths;
8804 struct got_pathlist_entry *pe;
8805 int ch, can_recurse = 0, pflag = 0;
8806 FILE *patch_script_file = NULL;
8807 const char *patch_script_path = NULL;
8808 struct choose_patch_arg cpa;
8809 int *pack_fds = NULL;
8811 TAILQ_INIT(&paths);
8813 #ifndef PROFILE
8814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8815 "unveil", NULL) == -1)
8816 err(1, "pledge");
8817 #endif
8819 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8820 switch (ch) {
8821 case 'F':
8822 patch_script_path = optarg;
8823 break;
8824 case 'p':
8825 pflag = 1;
8826 break;
8827 case 'R':
8828 can_recurse = 1;
8829 break;
8830 default:
8831 usage_revert();
8832 /* NOTREACHED */
8836 argc -= optind;
8837 argv += optind;
8839 if (argc < 1)
8840 usage_revert();
8841 if (patch_script_path && !pflag)
8842 errx(1, "-F option can only be used together with -p option");
8844 cwd = getcwd(NULL, 0);
8845 if (cwd == NULL) {
8846 error = got_error_from_errno("getcwd");
8847 goto done;
8850 error = got_repo_pack_fds_open(&pack_fds);
8851 if (error != NULL)
8852 goto done;
8854 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8855 if (error) {
8856 if (error->code == GOT_ERR_NOT_WORKTREE)
8857 error = wrap_not_worktree_error(error, "revert", cwd);
8858 goto done;
8861 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8862 NULL, pack_fds);
8863 if (error != NULL)
8864 goto done;
8866 if (patch_script_path) {
8867 patch_script_file = fopen(patch_script_path, "re");
8868 if (patch_script_file == NULL) {
8869 error = got_error_from_errno2("fopen",
8870 patch_script_path);
8871 goto done;
8876 * XXX "c" perm needed on repo dir to delete merge references.
8878 error = apply_unveil(got_repo_get_path(repo), 0,
8879 got_worktree_get_root_path(worktree));
8880 if (error)
8881 goto done;
8883 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8884 if (error)
8885 goto done;
8887 if (!can_recurse) {
8888 char *ondisk_path;
8889 struct stat sb;
8890 TAILQ_FOREACH(pe, &paths, entry) {
8891 if (asprintf(&ondisk_path, "%s/%s",
8892 got_worktree_get_root_path(worktree),
8893 pe->path) == -1) {
8894 error = got_error_from_errno("asprintf");
8895 goto done;
8897 if (lstat(ondisk_path, &sb) == -1) {
8898 if (errno == ENOENT) {
8899 free(ondisk_path);
8900 continue;
8902 error = got_error_from_errno2("lstat",
8903 ondisk_path);
8904 free(ondisk_path);
8905 goto done;
8907 free(ondisk_path);
8908 if (S_ISDIR(sb.st_mode)) {
8909 error = got_error_msg(GOT_ERR_BAD_PATH,
8910 "reverting directories requires -R option");
8911 goto done;
8916 cpa.patch_script_file = patch_script_file;
8917 cpa.action = "revert";
8918 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8919 pflag ? choose_patch : NULL, &cpa, repo);
8921 error = rm_logmsg_ref(worktree, repo);
8922 done:
8923 if (patch_script_file && fclose(patch_script_file) == EOF &&
8924 error == NULL)
8925 error = got_error_from_errno2("fclose", patch_script_path);
8926 if (repo) {
8927 const struct got_error *close_err = got_repo_close(repo);
8928 if (error == NULL)
8929 error = close_err;
8931 if (worktree)
8932 got_worktree_close(worktree);
8933 if (pack_fds) {
8934 const struct got_error *pack_err =
8935 got_repo_pack_fds_close(pack_fds);
8936 if (error == NULL)
8937 error = pack_err;
8939 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8940 free(path);
8941 free(cwd);
8942 return error;
8945 __dead static void
8946 usage_commit(void)
8948 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8949 "[-m message] [path ...]\n", getprogname());
8950 exit(1);
8953 struct collect_commit_logmsg_arg {
8954 const char *cmdline_log;
8955 const char *prepared_log;
8956 const char *merged_log;
8957 int non_interactive;
8958 const char *editor;
8959 const char *worktree_path;
8960 const char *branch_name;
8961 const char *repo_path;
8962 char *logmsg_path;
8966 static const struct got_error *
8967 read_prepared_logmsg(char **logmsg, const char *path)
8969 const struct got_error *err = NULL;
8970 FILE *f = NULL;
8971 struct stat sb;
8972 size_t r;
8974 *logmsg = NULL;
8975 memset(&sb, 0, sizeof(sb));
8977 f = fopen(path, "re");
8978 if (f == NULL)
8979 return got_error_from_errno2("fopen", path);
8981 if (fstat(fileno(f), &sb) == -1) {
8982 err = got_error_from_errno2("fstat", path);
8983 goto done;
8985 if (sb.st_size == 0) {
8986 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8987 goto done;
8990 *logmsg = malloc(sb.st_size + 1);
8991 if (*logmsg == NULL) {
8992 err = got_error_from_errno("malloc");
8993 goto done;
8996 r = fread(*logmsg, 1, sb.st_size, f);
8997 if (r != sb.st_size) {
8998 if (ferror(f))
8999 err = got_error_from_errno2("fread", path);
9000 else
9001 err = got_error(GOT_ERR_IO);
9002 goto done;
9004 (*logmsg)[sb.st_size] = '\0';
9005 done:
9006 if (fclose(f) == EOF && err == NULL)
9007 err = got_error_from_errno2("fclose", path);
9008 if (err) {
9009 free(*logmsg);
9010 *logmsg = NULL;
9012 return err;
9015 static const struct got_error *
9016 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9017 const char *diff_path, char **logmsg, void *arg)
9019 char *initial_content = NULL;
9020 struct got_pathlist_entry *pe;
9021 const struct got_error *err = NULL;
9022 char *template = NULL;
9023 char *prepared_msg = NULL, *merged_msg = NULL;
9024 struct collect_commit_logmsg_arg *a = arg;
9025 int initial_content_len;
9026 int fd = -1;
9027 size_t len;
9029 /* if a message was specified on the command line, just use it */
9030 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9031 len = strlen(a->cmdline_log) + 1;
9032 *logmsg = malloc(len + 1);
9033 if (*logmsg == NULL)
9034 return got_error_from_errno("malloc");
9035 strlcpy(*logmsg, a->cmdline_log, len);
9036 return NULL;
9037 } else if (a->prepared_log != NULL && a->non_interactive)
9038 return read_prepared_logmsg(logmsg, a->prepared_log);
9040 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9041 return got_error_from_errno("asprintf");
9043 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9044 if (err)
9045 goto done;
9047 if (a->prepared_log) {
9048 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9049 if (err)
9050 goto done;
9051 } else if (a->merged_log) {
9052 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9053 if (err)
9054 goto done;
9057 initial_content_len = asprintf(&initial_content,
9058 "%s%s\n# changes to be committed on branch %s:\n",
9059 prepared_msg ? prepared_msg : "",
9060 merged_msg ? merged_msg : "", a->branch_name);
9061 if (initial_content_len == -1) {
9062 err = got_error_from_errno("asprintf");
9063 goto done;
9066 if (write(fd, initial_content, initial_content_len) == -1) {
9067 err = got_error_from_errno2("write", a->logmsg_path);
9068 goto done;
9071 TAILQ_FOREACH(pe, commitable_paths, entry) {
9072 struct got_commitable *ct = pe->data;
9073 dprintf(fd, "# %c %s\n",
9074 got_commitable_get_status(ct),
9075 got_commitable_get_path(ct));
9078 if (diff_path) {
9079 dprintf(fd, "# detailed changes can be viewed in %s\n",
9080 diff_path);
9083 if (close(fd) == -1) {
9084 err = got_error_from_errno2("close", a->logmsg_path);
9085 goto done;
9087 fd = -1;
9089 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9090 initial_content_len, a->prepared_log ? 0 : 1);
9091 done:
9092 free(initial_content);
9093 free(template);
9094 free(prepared_msg);
9095 free(merged_msg);
9097 if (fd != -1 && close(fd) == -1 && err == NULL)
9098 err = got_error_from_errno2("close", a->logmsg_path);
9100 /* Editor is done; we can now apply unveil(2) */
9101 if (err == NULL)
9102 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9103 if (err) {
9104 free(*logmsg);
9105 *logmsg = NULL;
9107 return err;
9110 static const struct got_error *
9111 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9112 const char *type, int has_content)
9114 const struct got_error *err = NULL;
9115 char *logmsg = NULL;
9117 err = got_object_commit_get_logmsg(&logmsg, commit);
9118 if (err)
9119 return err;
9121 if (fprintf(f, "%s# log message of %s commit %s:%s",
9122 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9123 err = got_ferror(f, GOT_ERR_IO);
9125 free(logmsg);
9126 return err;
9130 * Lookup "logmsg" references of backed-out and cherrypicked commits
9131 * belonging to the current work tree. If found, and the worktree has
9132 * at least one modified file that was changed in the referenced commit,
9133 * add its log message to a new temporary file at *logmsg_path.
9134 * Add all refs found to matched_refs to be scheduled for removal on
9135 * successful commit.
9137 static const struct got_error *
9138 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9139 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9140 struct got_repository *repo)
9142 const struct got_error *err;
9143 struct got_commit_object *commit = NULL;
9144 struct got_object_id *id = NULL;
9145 struct got_reflist_head refs;
9146 struct got_reflist_entry *re, *re_match;
9147 FILE *f = NULL;
9148 char *uuidstr = NULL;
9149 int added_logmsg = 0;
9151 TAILQ_INIT(&refs);
9153 *logmsg_path = NULL;
9155 err = got_worktree_get_uuid(&uuidstr, worktree);
9156 if (err)
9157 goto done;
9159 err = got_ref_list(&refs, repo, "refs/got/worktree",
9160 got_ref_cmp_by_name, repo);
9161 if (err)
9162 goto done;
9164 TAILQ_FOREACH(re, &refs, entry) {
9165 const char *refname, *type;
9166 struct wt_commitable_path_arg wcpa;
9167 int add_logmsg = 0;
9169 refname = got_ref_get_name(re->ref);
9171 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9172 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9173 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9174 type = "cherrypicked";
9175 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9176 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9177 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9178 type = "backed-out";
9179 } else
9180 continue;
9182 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9183 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9184 else
9185 continue;
9187 err = got_repo_match_object_id(&id, NULL, refname,
9188 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9189 if (err)
9190 goto done;
9192 err = got_object_open_as_commit(&commit, repo, id);
9193 if (err)
9194 goto done;
9196 wcpa.commit_paths = paths;
9197 wcpa.has_changes = &add_logmsg;
9199 err = commit_path_changed_in_worktree(&wcpa, id,
9200 worktree, repo);
9201 if (err)
9202 goto done;
9204 if (add_logmsg) {
9205 if (f == NULL) {
9206 err = got_opentemp_named(logmsg_path, &f,
9207 "got-commit-logmsg", "");
9208 if (err)
9209 goto done;
9211 err = cat_logmsg(f, commit, refname, type,
9212 added_logmsg);
9213 if (err)
9214 goto done;
9215 if (!added_logmsg)
9216 ++added_logmsg;
9218 err = got_reflist_entry_dup(&re_match, re);
9219 if (err)
9220 goto done;
9221 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9224 got_object_commit_close(commit);
9225 commit = NULL;
9226 free(id);
9227 id = NULL;
9230 done:
9231 free(id);
9232 free(uuidstr);
9233 got_ref_list_free(&refs);
9234 if (commit)
9235 got_object_commit_close(commit);
9236 if (f && fclose(f) == EOF && err == NULL)
9237 err = got_error_from_errno("fclose");
9238 if (!added_logmsg) {
9239 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9240 err = got_error_from_errno2("unlink", *logmsg_path);
9241 *logmsg_path = NULL;
9243 return err;
9246 static const struct got_error *
9247 cmd_commit(int argc, char *argv[])
9249 const struct got_error *error = NULL;
9250 struct got_worktree *worktree = NULL;
9251 struct got_repository *repo = NULL;
9252 char *cwd = NULL, *id_str = NULL;
9253 struct got_object_id *id = NULL;
9254 const char *logmsg = NULL;
9255 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9256 struct collect_commit_logmsg_arg cl_arg;
9257 const char *author = NULL;
9258 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9259 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9260 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9261 int show_diff = 1, commit_conflicts = 0;
9262 struct got_pathlist_head paths;
9263 struct got_reflist_head refs;
9264 struct got_reflist_entry *re;
9265 int *pack_fds = NULL;
9267 TAILQ_INIT(&refs);
9268 TAILQ_INIT(&paths);
9269 cl_arg.logmsg_path = NULL;
9271 #ifndef PROFILE
9272 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9273 "unveil", NULL) == -1)
9274 err(1, "pledge");
9275 #endif
9277 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9278 switch (ch) {
9279 case 'A':
9280 author = optarg;
9281 error = valid_author(author);
9282 if (error)
9283 return error;
9284 break;
9285 case 'C':
9286 commit_conflicts = 1;
9287 break;
9288 case 'F':
9289 if (logmsg != NULL)
9290 option_conflict('F', 'm');
9291 prepared_logmsg = realpath(optarg, NULL);
9292 if (prepared_logmsg == NULL)
9293 return got_error_from_errno2("realpath",
9294 optarg);
9295 break;
9296 case 'm':
9297 if (prepared_logmsg)
9298 option_conflict('m', 'F');
9299 logmsg = optarg;
9300 break;
9301 case 'N':
9302 non_interactive = 1;
9303 break;
9304 case 'n':
9305 show_diff = 0;
9306 break;
9307 case 'S':
9308 allow_bad_symlinks = 1;
9309 break;
9310 default:
9311 usage_commit();
9312 /* NOTREACHED */
9316 argc -= optind;
9317 argv += optind;
9319 cwd = getcwd(NULL, 0);
9320 if (cwd == NULL) {
9321 error = got_error_from_errno("getcwd");
9322 goto done;
9325 error = got_repo_pack_fds_open(&pack_fds);
9326 if (error != NULL)
9327 goto done;
9329 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9330 if (error) {
9331 if (error->code == GOT_ERR_NOT_WORKTREE)
9332 error = wrap_not_worktree_error(error, "commit", cwd);
9333 goto done;
9336 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9337 if (error)
9338 goto done;
9339 if (rebase_in_progress) {
9340 error = got_error(GOT_ERR_REBASING);
9341 goto done;
9344 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9345 worktree);
9346 if (error)
9347 goto done;
9349 error = get_gitconfig_path(&gitconfig_path);
9350 if (error)
9351 goto done;
9352 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9353 gitconfig_path, pack_fds);
9354 if (error != NULL)
9355 goto done;
9357 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9358 if (error)
9359 goto done;
9360 if (merge_in_progress) {
9361 error = got_error(GOT_ERR_MERGE_BUSY);
9362 goto done;
9365 error = get_author(&committer, repo, worktree);
9366 if (error)
9367 goto done;
9369 if (author == NULL)
9370 author = committer;
9373 * unveil(2) traverses exec(2); if an editor is used we have
9374 * to apply unveil after the log message has been written.
9376 if (logmsg == NULL || strlen(logmsg) == 0)
9377 error = get_editor(&editor);
9378 else
9379 error = apply_unveil(got_repo_get_path(repo), 0,
9380 got_worktree_get_root_path(worktree));
9381 if (error)
9382 goto done;
9384 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9385 if (error)
9386 goto done;
9388 if (prepared_logmsg == NULL) {
9389 error = lookup_logmsg_ref(&merged_logmsg,
9390 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9391 if (error)
9392 goto done;
9395 cl_arg.editor = editor;
9396 cl_arg.cmdline_log = logmsg;
9397 cl_arg.prepared_log = prepared_logmsg;
9398 cl_arg.merged_log = merged_logmsg;
9399 cl_arg.non_interactive = non_interactive;
9400 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9401 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9402 if (!histedit_in_progress) {
9403 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9404 error = got_error(GOT_ERR_COMMIT_BRANCH);
9405 goto done;
9407 cl_arg.branch_name += 11;
9409 cl_arg.repo_path = got_repo_get_path(repo);
9410 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9411 allow_bad_symlinks, show_diff, commit_conflicts,
9412 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9413 if (error) {
9414 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9415 cl_arg.logmsg_path != NULL)
9416 preserve_logmsg = 1;
9417 goto done;
9420 error = got_object_id_str(&id_str, id);
9421 if (error)
9422 goto done;
9423 printf("Created commit %s\n", id_str);
9425 TAILQ_FOREACH(re, &refs, entry) {
9426 error = got_ref_delete(re->ref, repo);
9427 if (error)
9428 goto done;
9431 done:
9432 if (preserve_logmsg) {
9433 fprintf(stderr, "%s: log message preserved in %s\n",
9434 getprogname(), cl_arg.logmsg_path);
9435 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9436 error == NULL)
9437 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9438 free(cl_arg.logmsg_path);
9439 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9440 error = got_error_from_errno2("unlink", merged_logmsg);
9441 free(merged_logmsg);
9442 if (repo) {
9443 const struct got_error *close_err = got_repo_close(repo);
9444 if (error == NULL)
9445 error = close_err;
9447 if (worktree)
9448 got_worktree_close(worktree);
9449 if (pack_fds) {
9450 const struct got_error *pack_err =
9451 got_repo_pack_fds_close(pack_fds);
9452 if (error == NULL)
9453 error = pack_err;
9455 got_ref_list_free(&refs);
9456 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9457 free(cwd);
9458 free(id_str);
9459 free(gitconfig_path);
9460 free(editor);
9461 free(committer);
9462 free(prepared_logmsg);
9463 return error;
9466 __dead static void
9467 usage_send(void)
9469 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9470 "[-r repository-path] [-t tag] [remote-repository]\n",
9471 getprogname());
9472 exit(1);
9475 static void
9476 print_load_info(int print_colored, int print_found, int print_trees,
9477 int ncolored, int nfound, int ntrees)
9479 if (print_colored) {
9480 printf("%d commit%s colored", ncolored,
9481 ncolored == 1 ? "" : "s");
9483 if (print_found) {
9484 printf("%s%d object%s found",
9485 ncolored > 0 ? "; " : "",
9486 nfound, nfound == 1 ? "" : "s");
9488 if (print_trees) {
9489 printf("; %d tree%s scanned", ntrees,
9490 ntrees == 1 ? "" : "s");
9494 struct got_send_progress_arg {
9495 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9496 int verbosity;
9497 int last_ncolored;
9498 int last_nfound;
9499 int last_ntrees;
9500 int loading_done;
9501 int last_ncommits;
9502 int last_nobj_total;
9503 int last_p_deltify;
9504 int last_p_written;
9505 int last_p_sent;
9506 int printed_something;
9507 int sent_something;
9508 struct got_pathlist_head *delete_branches;
9511 static const struct got_error *
9512 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9513 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9514 int nobj_written, off_t bytes_sent, const char *refname,
9515 const char *errmsg, int success)
9517 struct got_send_progress_arg *a = arg;
9518 char scaled_packsize[FMT_SCALED_STRSIZE];
9519 char scaled_sent[FMT_SCALED_STRSIZE];
9520 int p_deltify = 0, p_written = 0, p_sent = 0;
9521 int print_colored = 0, print_found = 0, print_trees = 0;
9522 int print_searching = 0, print_total = 0;
9523 int print_deltify = 0, print_written = 0, print_sent = 0;
9525 if (a->verbosity < 0)
9526 return NULL;
9528 if (refname) {
9529 const char *status = success ? "accepted" : "rejected";
9531 if (success) {
9532 struct got_pathlist_entry *pe;
9533 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9534 const char *branchname = pe->path;
9535 if (got_path_cmp(branchname, refname,
9536 strlen(branchname), strlen(refname)) == 0) {
9537 status = "deleted";
9538 a->sent_something = 1;
9539 break;
9544 if (a->printed_something)
9545 putchar('\n');
9546 printf("Server has %s %s", status, refname);
9547 if (errmsg)
9548 printf(": %s", errmsg);
9549 a->printed_something = 1;
9550 return NULL;
9553 if (a->last_ncolored != ncolored) {
9554 print_colored = 1;
9555 a->last_ncolored = ncolored;
9558 if (a->last_nfound != nfound) {
9559 print_colored = 1;
9560 print_found = 1;
9561 a->last_nfound = nfound;
9564 if (a->last_ntrees != ntrees) {
9565 print_colored = 1;
9566 print_found = 1;
9567 print_trees = 1;
9568 a->last_ntrees = ntrees;
9571 if ((print_colored || print_found || print_trees) &&
9572 !a->loading_done) {
9573 printf("\r");
9574 print_load_info(print_colored, print_found, print_trees,
9575 ncolored, nfound, ntrees);
9576 a->printed_something = 1;
9577 fflush(stdout);
9578 return NULL;
9579 } else if (!a->loading_done) {
9580 printf("\r");
9581 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9582 printf("\n");
9583 a->loading_done = 1;
9586 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9587 return got_error_from_errno("fmt_scaled");
9588 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9589 return got_error_from_errno("fmt_scaled");
9591 if (a->last_ncommits != ncommits) {
9592 print_searching = 1;
9593 a->last_ncommits = ncommits;
9596 if (a->last_nobj_total != nobj_total) {
9597 print_searching = 1;
9598 print_total = 1;
9599 a->last_nobj_total = nobj_total;
9602 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9603 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9604 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9605 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9606 return got_error(GOT_ERR_NO_SPACE);
9609 if (nobj_deltify > 0 || nobj_written > 0) {
9610 if (nobj_deltify > 0) {
9611 p_deltify = (nobj_deltify * 100) / nobj_total;
9612 if (p_deltify != a->last_p_deltify) {
9613 a->last_p_deltify = p_deltify;
9614 print_searching = 1;
9615 print_total = 1;
9616 print_deltify = 1;
9619 if (nobj_written > 0) {
9620 p_written = (nobj_written * 100) / nobj_total;
9621 if (p_written != a->last_p_written) {
9622 a->last_p_written = p_written;
9623 print_searching = 1;
9624 print_total = 1;
9625 print_deltify = 1;
9626 print_written = 1;
9631 if (bytes_sent > 0) {
9632 p_sent = (bytes_sent * 100) / packfile_size;
9633 if (p_sent != a->last_p_sent) {
9634 a->last_p_sent = p_sent;
9635 print_searching = 1;
9636 print_total = 1;
9637 print_deltify = 1;
9638 print_written = 1;
9639 print_sent = 1;
9641 a->sent_something = 1;
9644 if (print_searching || print_total || print_deltify || print_written ||
9645 print_sent)
9646 printf("\r");
9647 if (print_searching)
9648 printf("packing %d reference%s", ncommits,
9649 ncommits == 1 ? "" : "s");
9650 if (print_total)
9651 printf("; %d object%s", nobj_total,
9652 nobj_total == 1 ? "" : "s");
9653 if (print_deltify)
9654 printf("; deltify: %d%%", p_deltify);
9655 if (print_sent)
9656 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9657 scaled_packsize, p_sent);
9658 else if (print_written)
9659 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9660 scaled_packsize, p_written);
9661 if (print_searching || print_total || print_deltify ||
9662 print_written || print_sent) {
9663 a->printed_something = 1;
9664 fflush(stdout);
9666 return NULL;
9669 static const struct got_error *
9670 cmd_send(int argc, char *argv[])
9672 const struct got_error *error = NULL;
9673 char *cwd = NULL, *repo_path = NULL;
9674 const char *remote_name;
9675 char *proto = NULL, *host = NULL, *port = NULL;
9676 char *repo_name = NULL, *server_path = NULL;
9677 const struct got_remote_repo *remotes, *remote = NULL;
9678 int nremotes, nbranches = 0, ndelete_branches = 0;
9679 struct got_repository *repo = NULL;
9680 struct got_worktree *worktree = NULL;
9681 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9682 struct got_pathlist_head branches;
9683 struct got_pathlist_head tags;
9684 struct got_reflist_head all_branches;
9685 struct got_reflist_head all_tags;
9686 struct got_pathlist_head delete_args;
9687 struct got_pathlist_head delete_branches;
9688 struct got_reflist_entry *re;
9689 struct got_pathlist_entry *pe;
9690 int i, ch, sendfd = -1, sendstatus;
9691 pid_t sendpid = -1;
9692 struct got_send_progress_arg spa;
9693 int verbosity = 0, overwrite_refs = 0;
9694 int send_all_branches = 0, send_all_tags = 0;
9695 struct got_reference *ref = NULL;
9696 int *pack_fds = NULL;
9698 TAILQ_INIT(&branches);
9699 TAILQ_INIT(&tags);
9700 TAILQ_INIT(&all_branches);
9701 TAILQ_INIT(&all_tags);
9702 TAILQ_INIT(&delete_args);
9703 TAILQ_INIT(&delete_branches);
9705 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9706 switch (ch) {
9707 case 'a':
9708 send_all_branches = 1;
9709 break;
9710 case 'b':
9711 error = got_pathlist_append(&branches, optarg, NULL);
9712 if (error)
9713 return error;
9714 nbranches++;
9715 break;
9716 case 'd':
9717 error = got_pathlist_append(&delete_args, optarg, NULL);
9718 if (error)
9719 return error;
9720 break;
9721 case 'f':
9722 overwrite_refs = 1;
9723 break;
9724 case 'q':
9725 verbosity = -1;
9726 break;
9727 case 'r':
9728 repo_path = realpath(optarg, NULL);
9729 if (repo_path == NULL)
9730 return got_error_from_errno2("realpath",
9731 optarg);
9732 got_path_strip_trailing_slashes(repo_path);
9733 break;
9734 case 'T':
9735 send_all_tags = 1;
9736 break;
9737 case 't':
9738 error = got_pathlist_append(&tags, optarg, NULL);
9739 if (error)
9740 return error;
9741 break;
9742 case 'v':
9743 if (verbosity < 0)
9744 verbosity = 0;
9745 else if (verbosity < 3)
9746 verbosity++;
9747 break;
9748 default:
9749 usage_send();
9750 /* NOTREACHED */
9753 argc -= optind;
9754 argv += optind;
9756 if (send_all_branches && !TAILQ_EMPTY(&branches))
9757 option_conflict('a', 'b');
9758 if (send_all_tags && !TAILQ_EMPTY(&tags))
9759 option_conflict('T', 't');
9762 if (argc == 0)
9763 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9764 else if (argc == 1)
9765 remote_name = argv[0];
9766 else
9767 usage_send();
9769 cwd = getcwd(NULL, 0);
9770 if (cwd == NULL) {
9771 error = got_error_from_errno("getcwd");
9772 goto done;
9775 error = got_repo_pack_fds_open(&pack_fds);
9776 if (error != NULL)
9777 goto done;
9779 if (repo_path == NULL) {
9780 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9781 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9782 goto done;
9783 else
9784 error = NULL;
9785 if (worktree) {
9786 repo_path =
9787 strdup(got_worktree_get_repo_path(worktree));
9788 if (repo_path == NULL)
9789 error = got_error_from_errno("strdup");
9790 if (error)
9791 goto done;
9792 } else {
9793 repo_path = strdup(cwd);
9794 if (repo_path == NULL) {
9795 error = got_error_from_errno("strdup");
9796 goto done;
9801 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9802 if (error)
9803 goto done;
9805 if (worktree) {
9806 worktree_conf = got_worktree_get_gotconfig(worktree);
9807 if (worktree_conf) {
9808 got_gotconfig_get_remotes(&nremotes, &remotes,
9809 worktree_conf);
9810 for (i = 0; i < nremotes; i++) {
9811 if (strcmp(remotes[i].name, remote_name) == 0) {
9812 remote = &remotes[i];
9813 break;
9818 if (remote == NULL) {
9819 repo_conf = got_repo_get_gotconfig(repo);
9820 if (repo_conf) {
9821 got_gotconfig_get_remotes(&nremotes, &remotes,
9822 repo_conf);
9823 for (i = 0; i < nremotes; i++) {
9824 if (strcmp(remotes[i].name, remote_name) == 0) {
9825 remote = &remotes[i];
9826 break;
9831 if (remote == NULL) {
9832 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9833 for (i = 0; i < nremotes; i++) {
9834 if (strcmp(remotes[i].name, remote_name) == 0) {
9835 remote = &remotes[i];
9836 break;
9840 if (remote == NULL) {
9841 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9842 goto done;
9845 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9846 &repo_name, remote->send_url);
9847 if (error)
9848 goto done;
9850 if (strcmp(proto, "git") == 0) {
9851 #ifndef PROFILE
9852 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9853 "sendfd dns inet unveil", NULL) == -1)
9854 err(1, "pledge");
9855 #endif
9856 } else if (strcmp(proto, "git+ssh") == 0 ||
9857 strcmp(proto, "ssh") == 0) {
9858 #ifndef PROFILE
9859 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9860 "sendfd unveil", NULL) == -1)
9861 err(1, "pledge");
9862 #endif
9863 } else if (strcmp(proto, "http") == 0 ||
9864 strcmp(proto, "git+http") == 0) {
9865 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9866 goto done;
9867 } else {
9868 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9869 goto done;
9872 error = got_dial_apply_unveil(proto);
9873 if (error)
9874 goto done;
9876 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9877 if (error)
9878 goto done;
9880 if (send_all_branches) {
9881 error = got_ref_list(&all_branches, repo, "refs/heads",
9882 got_ref_cmp_by_name, NULL);
9883 if (error)
9884 goto done;
9885 TAILQ_FOREACH(re, &all_branches, entry) {
9886 const char *branchname = got_ref_get_name(re->ref);
9887 error = got_pathlist_append(&branches,
9888 branchname, NULL);
9889 if (error)
9890 goto done;
9891 nbranches++;
9893 } else if (nbranches == 0) {
9894 for (i = 0; i < remote->nsend_branches; i++) {
9895 error = got_pathlist_append(&branches,
9896 remote->send_branches[i], NULL);
9897 if (error)
9898 goto done;
9902 if (send_all_tags) {
9903 error = got_ref_list(&all_tags, repo, "refs/tags",
9904 got_ref_cmp_by_name, NULL);
9905 if (error)
9906 goto done;
9907 TAILQ_FOREACH(re, &all_tags, entry) {
9908 const char *tagname = got_ref_get_name(re->ref);
9909 error = got_pathlist_append(&tags,
9910 tagname, NULL);
9911 if (error)
9912 goto done;
9917 * To prevent accidents only branches in refs/heads/ can be deleted
9918 * with 'got send -d'.
9919 * Deleting anything else requires local repository access or Git.
9921 TAILQ_FOREACH(pe, &delete_args, entry) {
9922 const char *branchname = pe->path;
9923 char *s;
9924 struct got_pathlist_entry *new;
9925 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9926 s = strdup(branchname);
9927 if (s == NULL) {
9928 error = got_error_from_errno("strdup");
9929 goto done;
9931 } else {
9932 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9933 error = got_error_from_errno("asprintf");
9934 goto done;
9937 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9938 if (error || new == NULL /* duplicate */)
9939 free(s);
9940 if (error)
9941 goto done;
9942 ndelete_branches++;
9945 if (nbranches == 0 && ndelete_branches == 0) {
9946 struct got_reference *head_ref;
9947 if (worktree)
9948 error = got_ref_open(&head_ref, repo,
9949 got_worktree_get_head_ref_name(worktree), 0);
9950 else
9951 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9952 if (error)
9953 goto done;
9954 if (got_ref_is_symbolic(head_ref)) {
9955 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9956 got_ref_close(head_ref);
9957 if (error)
9958 goto done;
9959 } else
9960 ref = head_ref;
9961 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9962 NULL);
9963 if (error)
9964 goto done;
9965 nbranches++;
9968 if (verbosity >= 0) {
9969 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9970 remote->name, proto, host,
9971 port ? ":" : "", port ? port : "",
9972 *server_path == '/' ? "" : "/", server_path);
9975 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9976 server_path, verbosity);
9977 if (error)
9978 goto done;
9980 memset(&spa, 0, sizeof(spa));
9981 spa.last_scaled_packsize[0] = '\0';
9982 spa.last_p_deltify = -1;
9983 spa.last_p_written = -1;
9984 spa.verbosity = verbosity;
9985 spa.delete_branches = &delete_branches;
9986 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9987 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9988 check_cancelled, NULL);
9989 if (spa.printed_something)
9990 putchar('\n');
9991 if (error)
9992 goto done;
9993 if (!spa.sent_something && verbosity >= 0)
9994 printf("Already up-to-date\n");
9995 done:
9996 if (sendpid > 0) {
9997 if (kill(sendpid, SIGTERM) == -1)
9998 error = got_error_from_errno("kill");
9999 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10000 error = got_error_from_errno("waitpid");
10002 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10003 error = got_error_from_errno("close");
10004 if (repo) {
10005 const struct got_error *close_err = got_repo_close(repo);
10006 if (error == NULL)
10007 error = close_err;
10009 if (worktree)
10010 got_worktree_close(worktree);
10011 if (pack_fds) {
10012 const struct got_error *pack_err =
10013 got_repo_pack_fds_close(pack_fds);
10014 if (error == NULL)
10015 error = pack_err;
10017 if (ref)
10018 got_ref_close(ref);
10019 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10020 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10021 got_ref_list_free(&all_branches);
10022 got_ref_list_free(&all_tags);
10023 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10024 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10025 free(cwd);
10026 free(repo_path);
10027 free(proto);
10028 free(host);
10029 free(port);
10030 free(server_path);
10031 free(repo_name);
10032 return error;
10036 * Print and if delete is set delete all ref_prefix references.
10037 * If wanted_ref is not NULL, only print or delete this reference.
10039 static const struct got_error *
10040 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10041 const char *wanted_ref, int delete, struct got_worktree *worktree,
10042 struct got_repository *repo)
10044 const struct got_error *err;
10045 struct got_pathlist_head paths;
10046 struct got_reflist_head refs;
10047 struct got_reflist_entry *re;
10048 struct got_reflist_object_id_map *refs_idmap = NULL;
10049 struct got_commit_object *commit = NULL;
10050 struct got_object_id *id = NULL;
10051 const char *header_prefix;
10052 char *uuidstr = NULL;
10053 int found = 0;
10055 TAILQ_INIT(&refs);
10056 TAILQ_INIT(&paths);
10058 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10059 if (err)
10060 goto done;
10062 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10063 if (err)
10064 goto done;
10066 if (worktree != NULL) {
10067 err = got_worktree_get_uuid(&uuidstr, worktree);
10068 if (err)
10069 goto done;
10072 if (wanted_ref) {
10073 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10074 wanted_ref += 11;
10077 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10078 header_prefix = "backout";
10079 else
10080 header_prefix = "cherrypick";
10082 TAILQ_FOREACH(re, &refs, entry) {
10083 const char *refname, *wt;
10085 refname = got_ref_get_name(re->ref);
10087 err = check_cancelled(NULL);
10088 if (err)
10089 goto done;
10091 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10092 refname += prefix_len + 1; /* skip '-' delimiter */
10093 else
10094 continue;
10096 wt = refname;
10098 if (worktree == NULL || strncmp(refname, uuidstr,
10099 GOT_WORKTREE_UUID_STRLEN) == 0)
10100 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10101 else
10102 continue;
10104 err = got_repo_match_object_id(&id, NULL, refname,
10105 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10106 if (err)
10107 goto done;
10109 err = got_object_open_as_commit(&commit, repo, id);
10110 if (err)
10111 goto done;
10113 if (wanted_ref)
10114 found = strncmp(wanted_ref, refname,
10115 strlen(wanted_ref)) == 0;
10116 if (wanted_ref && !found) {
10117 struct got_reflist_head *ci_refs;
10119 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10120 id);
10122 if (ci_refs) {
10123 char *refs_str = NULL;
10124 char const *r = NULL;
10126 err = build_refs_str(&refs_str, ci_refs, id,
10127 repo, 1);
10128 if (err)
10129 goto done;
10131 r = refs_str;
10132 while (r) {
10133 if (strncmp(r, wanted_ref,
10134 strlen(wanted_ref)) == 0) {
10135 found = 1;
10136 break;
10138 r = strchr(r, ' ');
10139 if (r)
10140 ++r;
10142 free(refs_str);
10146 if (wanted_ref == NULL || found) {
10147 if (delete) {
10148 err = got_ref_delete(re->ref, repo);
10149 if (err)
10150 goto done;
10151 printf("Deleted: ");
10152 err = print_commit_oneline(commit, id, repo,
10153 refs_idmap);
10154 } else {
10156 * Print paths modified by commit to help
10157 * associate commits with worktree changes.
10159 err = get_changed_paths(&paths, commit,
10160 repo, NULL);
10161 if (err)
10162 goto done;
10164 err = print_commit(commit, id, repo, NULL,
10165 &paths, NULL, 0, 0, refs_idmap, NULL,
10166 header_prefix);
10167 got_pathlist_free(&paths,
10168 GOT_PATHLIST_FREE_ALL);
10170 if (worktree == NULL)
10171 printf("work tree: %.*s\n\n",
10172 GOT_WORKTREE_UUID_STRLEN, wt);
10174 if (err || found)
10175 goto done;
10178 got_object_commit_close(commit);
10179 commit = NULL;
10180 free(id);
10181 id = NULL;
10184 if (wanted_ref != NULL && !found)
10185 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10187 done:
10188 free(id);
10189 free(uuidstr);
10190 got_ref_list_free(&refs);
10191 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10192 if (refs_idmap)
10193 got_reflist_object_id_map_free(refs_idmap);
10194 if (commit)
10195 got_object_commit_close(commit);
10196 return err;
10200 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10201 * identified by id for log messages to prepopulate the editor on commit.
10203 static const struct got_error *
10204 logmsg_ref(struct got_object_id *id, const char *prefix,
10205 struct got_worktree *worktree, struct got_repository *repo)
10207 const struct got_error *err = NULL;
10208 char *idstr, *ref = NULL, *refname = NULL;
10209 int histedit_in_progress;
10210 int rebase_in_progress, merge_in_progress;
10213 * Silenty refuse to create merge reference if any histedit, merge,
10214 * or rebase operation is in progress.
10216 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10217 worktree);
10218 if (err)
10219 return err;
10220 if (histedit_in_progress)
10221 return NULL;
10223 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10224 if (err)
10225 return err;
10226 if (rebase_in_progress)
10227 return NULL;
10229 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10230 repo);
10231 if (err)
10232 return err;
10233 if (merge_in_progress)
10234 return NULL;
10236 err = got_object_id_str(&idstr, id);
10237 if (err)
10238 return err;
10240 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10241 if (err)
10242 goto done;
10244 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10245 err = got_error_from_errno("asprintf");
10246 goto done;
10249 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10250 -1, repo);
10251 done:
10252 free(ref);
10253 free(idstr);
10254 free(refname);
10255 return err;
10258 __dead static void
10259 usage_cherrypick(void)
10261 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10262 getprogname());
10263 exit(1);
10266 static const struct got_error *
10267 cmd_cherrypick(int argc, char *argv[])
10269 const struct got_error *error = NULL;
10270 struct got_worktree *worktree = NULL;
10271 struct got_repository *repo = NULL;
10272 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10273 struct got_object_id *commit_id = NULL;
10274 struct got_commit_object *commit = NULL;
10275 struct got_object_qid *pid;
10276 int ch, list_refs = 0, remove_refs = 0;
10277 struct got_update_progress_arg upa;
10278 int *pack_fds = NULL;
10280 #ifndef PROFILE
10281 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10282 "unveil", NULL) == -1)
10283 err(1, "pledge");
10284 #endif
10286 while ((ch = getopt(argc, argv, "lX")) != -1) {
10287 switch (ch) {
10288 case 'l':
10289 list_refs = 1;
10290 break;
10291 case 'X':
10292 remove_refs = 1;
10293 break;
10294 default:
10295 usage_cherrypick();
10296 /* NOTREACHED */
10300 argc -= optind;
10301 argv += optind;
10303 if (list_refs || remove_refs) {
10304 if (argc != 0 && argc != 1)
10305 usage_cherrypick();
10306 } else if (argc != 1)
10307 usage_cherrypick();
10308 if (list_refs && remove_refs)
10309 option_conflict('l', 'X');
10311 cwd = getcwd(NULL, 0);
10312 if (cwd == NULL) {
10313 error = got_error_from_errno("getcwd");
10314 goto done;
10317 error = got_repo_pack_fds_open(&pack_fds);
10318 if (error != NULL)
10319 goto done;
10321 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10322 if (error) {
10323 if (list_refs || remove_refs) {
10324 if (error->code != GOT_ERR_NOT_WORKTREE)
10325 goto done;
10326 } else {
10327 if (error->code == GOT_ERR_NOT_WORKTREE)
10328 error = wrap_not_worktree_error(error,
10329 "cherrypick", cwd);
10330 goto done;
10334 error = got_repo_open(&repo,
10335 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10336 NULL, pack_fds);
10337 if (error != NULL)
10338 goto done;
10340 error = apply_unveil(got_repo_get_path(repo), 0,
10341 worktree ? got_worktree_get_root_path(worktree) : NULL);
10342 if (error)
10343 goto done;
10345 if (list_refs || remove_refs) {
10346 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10347 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10348 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10349 goto done;
10352 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10353 if (error != NULL)
10354 goto done;
10356 error = got_repo_match_object_id(&commit_id, NULL,
10357 keyword_idstr != NULL ? keyword_idstr : argv[0],
10358 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10359 if (error)
10360 goto done;
10361 error = got_object_id_str(&commit_id_str, commit_id);
10362 if (error)
10363 goto done;
10365 error = got_object_open_as_commit(&commit, repo, commit_id);
10366 if (error)
10367 goto done;
10368 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10369 memset(&upa, 0, sizeof(upa));
10370 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10371 commit_id, repo, update_progress, &upa, check_cancelled,
10372 NULL);
10373 if (error != NULL)
10374 goto done;
10376 if (upa.did_something) {
10377 error = logmsg_ref(commit_id,
10378 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10379 if (error)
10380 goto done;
10381 printf("Merged commit %s\n", commit_id_str);
10383 print_merge_progress_stats(&upa);
10384 done:
10385 free(cwd);
10386 free(keyword_idstr);
10387 if (commit)
10388 got_object_commit_close(commit);
10389 free(commit_id_str);
10390 if (worktree)
10391 got_worktree_close(worktree);
10392 if (repo) {
10393 const struct got_error *close_err = got_repo_close(repo);
10394 if (error == NULL)
10395 error = close_err;
10397 if (pack_fds) {
10398 const struct got_error *pack_err =
10399 got_repo_pack_fds_close(pack_fds);
10400 if (error == NULL)
10401 error = pack_err;
10404 return error;
10407 __dead static void
10408 usage_backout(void)
10410 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10411 exit(1);
10414 static const struct got_error *
10415 cmd_backout(int argc, char *argv[])
10417 const struct got_error *error = NULL;
10418 struct got_worktree *worktree = NULL;
10419 struct got_repository *repo = NULL;
10420 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10421 struct got_object_id *commit_id = NULL;
10422 struct got_commit_object *commit = NULL;
10423 struct got_object_qid *pid;
10424 int ch, list_refs = 0, remove_refs = 0;
10425 struct got_update_progress_arg upa;
10426 int *pack_fds = NULL;
10428 #ifndef PROFILE
10429 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10430 "unveil", NULL) == -1)
10431 err(1, "pledge");
10432 #endif
10434 while ((ch = getopt(argc, argv, "lX")) != -1) {
10435 switch (ch) {
10436 case 'l':
10437 list_refs = 1;
10438 break;
10439 case 'X':
10440 remove_refs = 1;
10441 break;
10442 default:
10443 usage_backout();
10444 /* NOTREACHED */
10448 argc -= optind;
10449 argv += optind;
10451 if (list_refs || remove_refs) {
10452 if (argc != 0 && argc != 1)
10453 usage_backout();
10454 } else if (argc != 1)
10455 usage_backout();
10456 if (list_refs && remove_refs)
10457 option_conflict('l', 'X');
10459 cwd = getcwd(NULL, 0);
10460 if (cwd == NULL) {
10461 error = got_error_from_errno("getcwd");
10462 goto done;
10465 error = got_repo_pack_fds_open(&pack_fds);
10466 if (error != NULL)
10467 goto done;
10469 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10470 if (error) {
10471 if (list_refs || remove_refs) {
10472 if (error->code != GOT_ERR_NOT_WORKTREE)
10473 goto done;
10474 } else {
10475 if (error->code == GOT_ERR_NOT_WORKTREE)
10476 error = wrap_not_worktree_error(error,
10477 "backout", cwd);
10478 goto done;
10482 error = got_repo_open(&repo,
10483 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10484 NULL, pack_fds);
10485 if (error != NULL)
10486 goto done;
10488 error = apply_unveil(got_repo_get_path(repo), 0,
10489 worktree ? got_worktree_get_root_path(worktree) : NULL);
10490 if (error)
10491 goto done;
10493 if (list_refs || remove_refs) {
10494 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10495 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10496 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10497 goto done;
10500 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10501 if (error != NULL)
10502 goto done;
10504 error = got_repo_match_object_id(&commit_id, NULL,
10505 keyword_idstr != NULL ? keyword_idstr : argv[0],
10506 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10507 if (error)
10508 goto done;
10509 error = got_object_id_str(&commit_id_str, commit_id);
10510 if (error)
10511 goto done;
10513 error = got_object_open_as_commit(&commit, repo, commit_id);
10514 if (error)
10515 goto done;
10516 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10517 if (pid == NULL) {
10518 error = got_error(GOT_ERR_ROOT_COMMIT);
10519 goto done;
10522 memset(&upa, 0, sizeof(upa));
10523 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10524 repo, update_progress, &upa, check_cancelled, NULL);
10525 if (error != NULL)
10526 goto done;
10528 if (upa.did_something) {
10529 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10530 worktree, repo);
10531 if (error)
10532 goto done;
10533 printf("Backed out commit %s\n", commit_id_str);
10535 print_merge_progress_stats(&upa);
10536 done:
10537 free(cwd);
10538 free(keyword_idstr);
10539 if (commit)
10540 got_object_commit_close(commit);
10541 free(commit_id_str);
10542 if (worktree)
10543 got_worktree_close(worktree);
10544 if (repo) {
10545 const struct got_error *close_err = got_repo_close(repo);
10546 if (error == NULL)
10547 error = close_err;
10549 if (pack_fds) {
10550 const struct got_error *pack_err =
10551 got_repo_pack_fds_close(pack_fds);
10552 if (error == NULL)
10553 error = pack_err;
10555 return error;
10558 __dead static void
10559 usage_rebase(void)
10561 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10562 exit(1);
10565 static void
10566 trim_logmsg(char *logmsg, int limit)
10568 char *nl;
10569 size_t len;
10571 len = strlen(logmsg);
10572 if (len > limit)
10573 len = limit;
10574 logmsg[len] = '\0';
10575 nl = strchr(logmsg, '\n');
10576 if (nl)
10577 *nl = '\0';
10580 static const struct got_error *
10581 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10583 const struct got_error *err;
10584 char *logmsg0 = NULL;
10585 const char *s;
10587 err = got_object_commit_get_logmsg(&logmsg0, commit);
10588 if (err)
10589 return err;
10591 s = logmsg0;
10592 while (isspace((unsigned char)s[0]))
10593 s++;
10595 *logmsg = strdup(s);
10596 if (*logmsg == NULL) {
10597 err = got_error_from_errno("strdup");
10598 goto done;
10601 trim_logmsg(*logmsg, limit);
10602 done:
10603 free(logmsg0);
10604 return err;
10607 static const struct got_error *
10608 show_rebase_merge_conflict(struct got_object_id *id,
10609 struct got_repository *repo)
10611 const struct got_error *err;
10612 struct got_commit_object *commit = NULL;
10613 char *id_str = NULL, *logmsg = NULL;
10615 err = got_object_open_as_commit(&commit, repo, id);
10616 if (err)
10617 return err;
10619 err = got_object_id_str(&id_str, id);
10620 if (err)
10621 goto done;
10623 id_str[12] = '\0';
10625 err = get_short_logmsg(&logmsg, 42, commit);
10626 if (err)
10627 goto done;
10629 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10630 done:
10631 free(id_str);
10632 got_object_commit_close(commit);
10633 free(logmsg);
10634 return err;
10637 static const struct got_error *
10638 show_rebase_progress(struct got_commit_object *commit,
10639 struct got_object_id *old_id, struct got_object_id *new_id)
10641 const struct got_error *err;
10642 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10644 err = got_object_id_str(&old_id_str, old_id);
10645 if (err)
10646 goto done;
10648 if (new_id) {
10649 err = got_object_id_str(&new_id_str, new_id);
10650 if (err)
10651 goto done;
10654 old_id_str[12] = '\0';
10655 if (new_id_str)
10656 new_id_str[12] = '\0';
10658 err = get_short_logmsg(&logmsg, 42, commit);
10659 if (err)
10660 goto done;
10662 printf("%s -> %s: %s\n", old_id_str,
10663 new_id_str ? new_id_str : "no-op change", logmsg);
10664 done:
10665 free(old_id_str);
10666 free(new_id_str);
10667 free(logmsg);
10668 return err;
10671 static const struct got_error *
10672 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10673 struct got_reference *branch, struct got_reference *tmp_branch,
10674 struct got_repository *repo, int create_backup)
10676 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10677 return got_worktree_rebase_complete(worktree, fileindex,
10678 tmp_branch, branch, repo, create_backup);
10681 static const struct got_error *
10682 rebase_commit(struct got_pathlist_head *merged_paths,
10683 struct got_worktree *worktree, struct got_fileindex *fileindex,
10684 struct got_reference *tmp_branch, const char *committer,
10685 struct got_object_id *commit_id, int allow_conflict,
10686 struct got_repository *repo)
10688 const struct got_error *error;
10689 struct got_commit_object *commit;
10690 struct got_object_id *new_commit_id;
10692 error = got_object_open_as_commit(&commit, repo, commit_id);
10693 if (error)
10694 return error;
10696 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10697 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10698 allow_conflict, repo);
10699 if (error) {
10700 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10701 goto done;
10702 error = show_rebase_progress(commit, commit_id, NULL);
10703 } else {
10704 error = show_rebase_progress(commit, commit_id, new_commit_id);
10705 free(new_commit_id);
10707 done:
10708 got_object_commit_close(commit);
10709 return error;
10712 struct check_path_prefix_arg {
10713 const char *path_prefix;
10714 size_t len;
10715 int errcode;
10718 static const struct got_error *
10719 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10720 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10721 struct got_object_id *id1, struct got_object_id *id2,
10722 const char *path1, const char *path2,
10723 mode_t mode1, mode_t mode2, struct got_repository *repo)
10725 struct check_path_prefix_arg *a = arg;
10727 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10728 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10729 return got_error(a->errcode);
10731 return NULL;
10734 static const struct got_error *
10735 check_path_prefix(struct got_object_id *parent_id,
10736 struct got_object_id *commit_id, const char *path_prefix,
10737 int errcode, struct got_repository *repo)
10739 const struct got_error *err;
10740 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10741 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10742 struct check_path_prefix_arg cpp_arg;
10744 if (got_path_is_root_dir(path_prefix))
10745 return NULL;
10747 err = got_object_open_as_commit(&commit, repo, commit_id);
10748 if (err)
10749 goto done;
10751 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10752 if (err)
10753 goto done;
10755 err = got_object_open_as_tree(&tree1, repo,
10756 got_object_commit_get_tree_id(parent_commit));
10757 if (err)
10758 goto done;
10760 err = got_object_open_as_tree(&tree2, repo,
10761 got_object_commit_get_tree_id(commit));
10762 if (err)
10763 goto done;
10765 cpp_arg.path_prefix = path_prefix;
10766 while (cpp_arg.path_prefix[0] == '/')
10767 cpp_arg.path_prefix++;
10768 cpp_arg.len = strlen(cpp_arg.path_prefix);
10769 cpp_arg.errcode = errcode;
10770 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10771 check_path_prefix_in_diff, &cpp_arg, 0);
10772 done:
10773 if (tree1)
10774 got_object_tree_close(tree1);
10775 if (tree2)
10776 got_object_tree_close(tree2);
10777 if (commit)
10778 got_object_commit_close(commit);
10779 if (parent_commit)
10780 got_object_commit_close(parent_commit);
10781 return err;
10784 static const struct got_error *
10785 collect_commits(struct got_object_id_queue *commits,
10786 struct got_object_id *initial_commit_id,
10787 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10788 const char *path_prefix, int path_prefix_errcode,
10789 struct got_repository *repo)
10791 const struct got_error *err = NULL;
10792 struct got_commit_graph *graph = NULL;
10793 struct got_object_id parent_id, commit_id;
10794 struct got_object_qid *qid;
10796 err = got_commit_graph_open(&graph, "/", 1);
10797 if (err)
10798 return err;
10800 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10801 check_cancelled, NULL);
10802 if (err)
10803 goto done;
10805 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10806 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10807 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10808 check_cancelled, NULL);
10809 if (err) {
10810 if (err->code == GOT_ERR_ITER_COMPLETED) {
10811 err = got_error_msg(GOT_ERR_ANCESTRY,
10812 "ran out of commits to rebase before "
10813 "youngest common ancestor commit has "
10814 "been reached?!?");
10816 goto done;
10817 } else {
10818 err = check_path_prefix(&parent_id, &commit_id,
10819 path_prefix, path_prefix_errcode, repo);
10820 if (err)
10821 goto done;
10823 err = got_object_qid_alloc(&qid, &commit_id);
10824 if (err)
10825 goto done;
10826 STAILQ_INSERT_HEAD(commits, qid, entry);
10828 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10831 done:
10832 got_commit_graph_close(graph);
10833 return err;
10836 static const struct got_error *
10837 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10839 const struct got_error *err = NULL;
10840 time_t committer_time;
10841 struct tm tm;
10842 char datebuf[11]; /* YYYY-MM-DD + NUL */
10843 char *author0 = NULL, *author, *smallerthan;
10844 char *logmsg0 = NULL, *logmsg, *newline;
10846 committer_time = got_object_commit_get_committer_time(commit);
10847 if (gmtime_r(&committer_time, &tm) == NULL)
10848 return got_error_from_errno("gmtime_r");
10849 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10850 return got_error(GOT_ERR_NO_SPACE);
10852 author0 = strdup(got_object_commit_get_author(commit));
10853 if (author0 == NULL)
10854 return got_error_from_errno("strdup");
10855 author = author0;
10856 smallerthan = strchr(author, '<');
10857 if (smallerthan && smallerthan[1] != '\0')
10858 author = smallerthan + 1;
10859 author[strcspn(author, "@>")] = '\0';
10861 err = got_object_commit_get_logmsg(&logmsg0, commit);
10862 if (err)
10863 goto done;
10864 logmsg = logmsg0;
10865 while (*logmsg == '\n')
10866 logmsg++;
10867 newline = strchr(logmsg, '\n');
10868 if (newline)
10869 *newline = '\0';
10871 if (asprintf(brief_str, "%s %s %s",
10872 datebuf, author, logmsg) == -1)
10873 err = got_error_from_errno("asprintf");
10874 done:
10875 free(author0);
10876 free(logmsg0);
10877 return err;
10880 static const struct got_error *
10881 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10882 struct got_repository *repo)
10884 const struct got_error *err;
10885 char *id_str;
10887 err = got_object_id_str(&id_str, id);
10888 if (err)
10889 return err;
10891 err = got_ref_delete(ref, repo);
10892 if (err)
10893 goto done;
10895 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10896 done:
10897 free(id_str);
10898 return err;
10901 static const struct got_error *
10902 print_backup_ref(const char *branch_name, const char *new_id_str,
10903 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10904 struct got_reflist_object_id_map *refs_idmap,
10905 struct got_repository *repo)
10907 const struct got_error *err = NULL;
10908 struct got_reflist_head *refs;
10909 char *refs_str = NULL;
10910 struct got_object_id *new_commit_id = NULL;
10911 struct got_commit_object *new_commit = NULL;
10912 char *new_commit_brief_str = NULL;
10913 struct got_object_id *yca_id = NULL;
10914 struct got_commit_object *yca_commit = NULL;
10915 char *yca_id_str = NULL, *yca_brief_str = NULL;
10916 char *custom_refs_str;
10918 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10919 return got_error_from_errno("asprintf");
10921 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10922 0, 0, refs_idmap, custom_refs_str, NULL);
10923 if (err)
10924 goto done;
10926 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10927 if (err)
10928 goto done;
10930 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10931 if (refs) {
10932 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10933 if (err)
10934 goto done;
10937 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10938 if (err)
10939 goto done;
10941 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10942 if (err)
10943 goto done;
10945 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10946 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10947 if (err)
10948 goto done;
10950 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10951 refs_str ? " (" : "", refs_str ? refs_str : "",
10952 refs_str ? ")" : "", new_commit_brief_str);
10953 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10954 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10955 free(refs_str);
10956 refs_str = NULL;
10958 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10959 if (err)
10960 goto done;
10962 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10963 if (err)
10964 goto done;
10966 err = got_object_id_str(&yca_id_str, yca_id);
10967 if (err)
10968 goto done;
10970 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10971 if (refs) {
10972 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10973 if (err)
10974 goto done;
10976 printf("history forked at %s%s%s%s\n %s\n",
10977 yca_id_str,
10978 refs_str ? " (" : "", refs_str ? refs_str : "",
10979 refs_str ? ")" : "", yca_brief_str);
10981 done:
10982 free(custom_refs_str);
10983 free(new_commit_id);
10984 free(refs_str);
10985 free(yca_id);
10986 free(yca_id_str);
10987 free(yca_brief_str);
10988 if (new_commit)
10989 got_object_commit_close(new_commit);
10990 if (yca_commit)
10991 got_object_commit_close(yca_commit);
10993 return err;
10996 static const struct got_error *
10997 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10998 struct got_repository *repo)
11000 const struct got_error *err;
11001 struct got_reflist_head refs;
11002 struct got_reflist_entry *re;
11003 char *uuidstr = NULL;
11004 static char msg[160];
11006 TAILQ_INIT(&refs);
11008 err = got_worktree_get_uuid(&uuidstr, worktree);
11009 if (err)
11010 goto done;
11012 err = got_ref_list(&refs, repo, "refs/got/worktree",
11013 got_ref_cmp_by_name, repo);
11014 if (err)
11015 goto done;
11017 TAILQ_FOREACH(re, &refs, entry) {
11018 const char *cmd, *refname, *type;
11020 refname = got_ref_get_name(re->ref);
11022 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11023 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11024 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11025 cmd = "cherrypick";
11026 type = "cherrypicked";
11027 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11028 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11029 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11030 cmd = "backout";
11031 type = "backed-out";
11032 } else
11033 continue;
11035 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11036 continue;
11038 snprintf(msg, sizeof(msg),
11039 "work tree has references created by %s commits which "
11040 "must be removed with 'got %s -X' before running the %s "
11041 "command", type, cmd, caller);
11042 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11043 goto done;
11046 done:
11047 free(uuidstr);
11048 got_ref_list_free(&refs);
11049 return err;
11052 static const struct got_error *
11053 process_backup_refs(const char *backup_ref_prefix,
11054 const char *wanted_branch_name,
11055 int delete, struct got_repository *repo)
11057 const struct got_error *err;
11058 struct got_reflist_head refs, backup_refs;
11059 struct got_reflist_entry *re;
11060 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11061 struct got_object_id *old_commit_id = NULL;
11062 char *branch_name = NULL;
11063 struct got_commit_object *old_commit = NULL;
11064 struct got_reflist_object_id_map *refs_idmap = NULL;
11065 int wanted_branch_found = 0;
11067 TAILQ_INIT(&refs);
11068 TAILQ_INIT(&backup_refs);
11070 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11071 if (err)
11072 return err;
11074 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11075 if (err)
11076 goto done;
11078 if (wanted_branch_name) {
11079 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11080 wanted_branch_name += 11;
11083 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11084 got_ref_cmp_by_commit_timestamp_descending, repo);
11085 if (err)
11086 goto done;
11088 TAILQ_FOREACH(re, &backup_refs, entry) {
11089 const char *refname = got_ref_get_name(re->ref);
11090 char *slash;
11092 err = check_cancelled(NULL);
11093 if (err)
11094 break;
11096 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11097 if (err)
11098 break;
11100 err = got_object_open_as_commit(&old_commit, repo,
11101 old_commit_id);
11102 if (err)
11103 break;
11105 if (strncmp(backup_ref_prefix, refname,
11106 backup_ref_prefix_len) == 0)
11107 refname += backup_ref_prefix_len;
11109 while (refname[0] == '/')
11110 refname++;
11112 branch_name = strdup(refname);
11113 if (branch_name == NULL) {
11114 err = got_error_from_errno("strdup");
11115 break;
11117 slash = strrchr(branch_name, '/');
11118 if (slash) {
11119 *slash = '\0';
11120 refname += strlen(branch_name) + 1;
11123 if (wanted_branch_name == NULL ||
11124 strcmp(wanted_branch_name, branch_name) == 0) {
11125 wanted_branch_found = 1;
11126 if (delete) {
11127 err = delete_backup_ref(re->ref,
11128 old_commit_id, repo);
11129 } else {
11130 err = print_backup_ref(branch_name, refname,
11131 old_commit_id, old_commit, refs_idmap,
11132 repo);
11134 if (err)
11135 break;
11138 free(old_commit_id);
11139 old_commit_id = NULL;
11140 free(branch_name);
11141 branch_name = NULL;
11142 got_object_commit_close(old_commit);
11143 old_commit = NULL;
11146 if (wanted_branch_name && !wanted_branch_found) {
11147 err = got_error_fmt(GOT_ERR_NOT_REF,
11148 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11150 done:
11151 if (refs_idmap)
11152 got_reflist_object_id_map_free(refs_idmap);
11153 got_ref_list_free(&refs);
11154 got_ref_list_free(&backup_refs);
11155 free(old_commit_id);
11156 free(branch_name);
11157 if (old_commit)
11158 got_object_commit_close(old_commit);
11159 return err;
11162 static const struct got_error *
11163 abort_progress(void *arg, unsigned char status, const char *path)
11166 * Unversioned files should not clutter progress output when
11167 * an operation is aborted.
11169 if (status == GOT_STATUS_UNVERSIONED)
11170 return NULL;
11172 return update_progress(arg, status, path);
11175 static const struct got_error *
11176 cmd_rebase(int argc, char *argv[])
11178 const struct got_error *error = NULL;
11179 struct got_worktree *worktree = NULL;
11180 struct got_repository *repo = NULL;
11181 struct got_fileindex *fileindex = NULL;
11182 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11183 struct got_reference *branch = NULL;
11184 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11185 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11186 struct got_object_id *resume_commit_id = NULL;
11187 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11188 struct got_object_id *head_commit_id = NULL;
11189 struct got_reference *head_ref = NULL;
11190 struct got_commit_object *commit = NULL;
11191 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11192 int histedit_in_progress = 0, merge_in_progress = 0;
11193 int create_backup = 1, list_backups = 0, delete_backups = 0;
11194 int allow_conflict = 0;
11195 struct got_object_id_queue commits;
11196 struct got_pathlist_head merged_paths;
11197 const struct got_object_id_queue *parent_ids;
11198 struct got_object_qid *qid, *pid;
11199 struct got_update_progress_arg upa;
11200 int *pack_fds = NULL;
11202 STAILQ_INIT(&commits);
11203 TAILQ_INIT(&merged_paths);
11204 memset(&upa, 0, sizeof(upa));
11206 #ifndef PROFILE
11207 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11208 "unveil", NULL) == -1)
11209 err(1, "pledge");
11210 #endif
11212 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11213 switch (ch) {
11214 case 'a':
11215 abort_rebase = 1;
11216 break;
11217 case 'C':
11218 allow_conflict = 1;
11219 break;
11220 case 'c':
11221 continue_rebase = 1;
11222 break;
11223 case 'l':
11224 list_backups = 1;
11225 break;
11226 case 'X':
11227 delete_backups = 1;
11228 break;
11229 default:
11230 usage_rebase();
11231 /* NOTREACHED */
11235 argc -= optind;
11236 argv += optind;
11238 if (list_backups) {
11239 if (abort_rebase)
11240 option_conflict('l', 'a');
11241 if (allow_conflict)
11242 option_conflict('l', 'C');
11243 if (continue_rebase)
11244 option_conflict('l', 'c');
11245 if (delete_backups)
11246 option_conflict('l', 'X');
11247 if (argc != 0 && argc != 1)
11248 usage_rebase();
11249 } else if (delete_backups) {
11250 if (abort_rebase)
11251 option_conflict('X', 'a');
11252 if (allow_conflict)
11253 option_conflict('X', 'C');
11254 if (continue_rebase)
11255 option_conflict('X', 'c');
11256 if (list_backups)
11257 option_conflict('l', 'X');
11258 if (argc != 0 && argc != 1)
11259 usage_rebase();
11260 } else if (allow_conflict) {
11261 if (abort_rebase)
11262 option_conflict('C', 'a');
11263 if (!continue_rebase)
11264 errx(1, "-C option requires -c");
11265 } else {
11266 if (abort_rebase && continue_rebase)
11267 usage_rebase();
11268 else if (abort_rebase || continue_rebase) {
11269 if (argc != 0)
11270 usage_rebase();
11271 } else if (argc != 1)
11272 usage_rebase();
11275 cwd = getcwd(NULL, 0);
11276 if (cwd == NULL) {
11277 error = got_error_from_errno("getcwd");
11278 goto done;
11281 error = got_repo_pack_fds_open(&pack_fds);
11282 if (error != NULL)
11283 goto done;
11285 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11286 if (error) {
11287 if (list_backups || delete_backups) {
11288 if (error->code != GOT_ERR_NOT_WORKTREE)
11289 goto done;
11290 } else {
11291 if (error->code == GOT_ERR_NOT_WORKTREE)
11292 error = wrap_not_worktree_error(error,
11293 "rebase", cwd);
11294 goto done;
11298 error = get_gitconfig_path(&gitconfig_path);
11299 if (error)
11300 goto done;
11301 error = got_repo_open(&repo,
11302 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11303 gitconfig_path, pack_fds);
11304 if (error != NULL)
11305 goto done;
11307 if (worktree != NULL && !list_backups && !delete_backups) {
11308 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11309 if (error)
11310 goto done;
11313 error = get_author(&committer, repo, worktree);
11314 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11315 goto done;
11317 error = apply_unveil(got_repo_get_path(repo), 0,
11318 worktree ? got_worktree_get_root_path(worktree) : NULL);
11319 if (error)
11320 goto done;
11322 if (list_backups || delete_backups) {
11323 error = process_backup_refs(
11324 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11325 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11326 goto done; /* nothing else to do */
11329 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11330 worktree);
11331 if (error)
11332 goto done;
11333 if (histedit_in_progress) {
11334 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11335 goto done;
11338 error = got_worktree_merge_in_progress(&merge_in_progress,
11339 worktree, repo);
11340 if (error)
11341 goto done;
11342 if (merge_in_progress) {
11343 error = got_error(GOT_ERR_MERGE_BUSY);
11344 goto done;
11347 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11348 if (error)
11349 goto done;
11351 if (abort_rebase) {
11352 if (!rebase_in_progress) {
11353 error = got_error(GOT_ERR_NOT_REBASING);
11354 goto done;
11356 error = got_worktree_rebase_continue(&resume_commit_id,
11357 &new_base_branch, &tmp_branch, &branch, &fileindex,
11358 worktree, repo);
11359 if (error)
11360 goto done;
11361 printf("Switching work tree to %s\n",
11362 got_ref_get_symref_target(new_base_branch));
11363 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11364 new_base_branch, abort_progress, &upa);
11365 if (error)
11366 goto done;
11367 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11368 print_merge_progress_stats(&upa);
11369 goto done; /* nothing else to do */
11372 if (continue_rebase) {
11373 if (!rebase_in_progress) {
11374 error = got_error(GOT_ERR_NOT_REBASING);
11375 goto done;
11377 error = got_worktree_rebase_continue(&resume_commit_id,
11378 &new_base_branch, &tmp_branch, &branch, &fileindex,
11379 worktree, repo);
11380 if (error)
11381 goto done;
11383 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11384 committer, resume_commit_id, allow_conflict, repo);
11385 if (error)
11386 goto done;
11388 yca_id = got_object_id_dup(resume_commit_id);
11389 if (yca_id == NULL) {
11390 error = got_error_from_errno("got_object_id_dup");
11391 goto done;
11393 } else {
11394 error = got_ref_open(&branch, repo, argv[0], 0);
11395 if (error != NULL)
11396 goto done;
11397 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11398 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11399 "will not rebase a branch which lives outside "
11400 "the \"refs/heads/\" reference namespace");
11401 goto done;
11405 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11406 if (error)
11407 goto done;
11409 if (!continue_rebase) {
11410 struct got_object_id *base_commit_id;
11412 error = got_ref_open(&head_ref, repo,
11413 got_worktree_get_head_ref_name(worktree), 0);
11414 if (error)
11415 goto done;
11416 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11417 if (error)
11418 goto done;
11419 base_commit_id = got_worktree_get_base_commit_id(worktree);
11420 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11421 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11422 goto done;
11425 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11426 base_commit_id, branch_head_commit_id, 1, repo,
11427 check_cancelled, NULL);
11428 if (error) {
11429 if (error->code == GOT_ERR_ANCESTRY) {
11430 error = got_error_msg(GOT_ERR_ANCESTRY,
11431 "specified branch shares no common "
11432 "ancestry with work tree's branch");
11434 goto done;
11437 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11438 struct got_pathlist_head paths;
11439 printf("%s is already based on %s\n",
11440 got_ref_get_name(branch),
11441 got_worktree_get_head_ref_name(worktree));
11442 error = switch_head_ref(branch, branch_head_commit_id,
11443 worktree, repo);
11444 if (error)
11445 goto done;
11446 error = got_worktree_set_base_commit_id(worktree, repo,
11447 branch_head_commit_id);
11448 if (error)
11449 goto done;
11450 TAILQ_INIT(&paths);
11451 error = got_pathlist_append(&paths, "", NULL);
11452 if (error)
11453 goto done;
11454 error = got_worktree_checkout_files(worktree,
11455 &paths, repo, update_progress, &upa,
11456 check_cancelled, NULL);
11457 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11458 if (error)
11459 goto done;
11460 if (upa.did_something) {
11461 char *id_str;
11462 error = got_object_id_str(&id_str,
11463 branch_head_commit_id);
11464 if (error)
11465 goto done;
11466 printf("Updated to %s: %s\n",
11467 got_worktree_get_head_ref_name(worktree),
11468 id_str);
11469 free(id_str);
11470 } else
11471 printf("Already up-to-date\n");
11472 print_update_progress_stats(&upa);
11473 goto done;
11477 commit_id = branch_head_commit_id;
11478 error = got_object_open_as_commit(&commit, repo, commit_id);
11479 if (error)
11480 goto done;
11482 parent_ids = got_object_commit_get_parent_ids(commit);
11483 pid = STAILQ_FIRST(parent_ids);
11484 if (pid) {
11485 error = collect_commits(&commits, commit_id, &pid->id,
11486 yca_id, got_worktree_get_path_prefix(worktree),
11487 GOT_ERR_REBASE_PATH, repo);
11488 if (error)
11489 goto done;
11492 got_object_commit_close(commit);
11493 commit = NULL;
11495 if (!continue_rebase) {
11496 error = got_worktree_rebase_prepare(&new_base_branch,
11497 &tmp_branch, &fileindex, worktree, branch, repo);
11498 if (error)
11499 goto done;
11502 if (STAILQ_EMPTY(&commits)) {
11503 if (continue_rebase) {
11504 error = rebase_complete(worktree, fileindex,
11505 branch, tmp_branch, repo, create_backup);
11506 goto done;
11507 } else {
11508 /* Fast-forward the reference of the branch. */
11509 struct got_object_id *new_head_commit_id;
11510 char *id_str;
11511 error = got_ref_resolve(&new_head_commit_id, repo,
11512 new_base_branch);
11513 if (error)
11514 goto done;
11515 error = got_object_id_str(&id_str, new_head_commit_id);
11516 if (error)
11517 goto done;
11518 printf("Forwarding %s to commit %s\n",
11519 got_ref_get_name(branch), id_str);
11520 free(id_str);
11521 error = got_ref_change_ref(branch,
11522 new_head_commit_id);
11523 if (error)
11524 goto done;
11525 /* No backup needed since objects did not change. */
11526 create_backup = 0;
11530 pid = NULL;
11531 STAILQ_FOREACH(qid, &commits, entry) {
11533 commit_id = &qid->id;
11534 parent_id = pid ? &pid->id : yca_id;
11535 pid = qid;
11537 memset(&upa, 0, sizeof(upa));
11538 error = got_worktree_rebase_merge_files(&merged_paths,
11539 worktree, fileindex, parent_id, commit_id, repo,
11540 update_progress, &upa, check_cancelled, NULL);
11541 if (error)
11542 goto done;
11544 print_merge_progress_stats(&upa);
11545 if (upa.conflicts > 0 || upa.missing > 0 ||
11546 upa.not_deleted > 0 || upa.unversioned > 0) {
11547 if (upa.conflicts > 0) {
11548 error = show_rebase_merge_conflict(&qid->id,
11549 repo);
11550 if (error)
11551 goto done;
11553 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11554 break;
11557 error = rebase_commit(&merged_paths, worktree, fileindex,
11558 tmp_branch, committer, commit_id, 0, repo);
11559 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11560 if (error)
11561 goto done;
11564 if (upa.conflicts > 0 || upa.missing > 0 ||
11565 upa.not_deleted > 0 || upa.unversioned > 0) {
11566 error = got_worktree_rebase_postpone(worktree, fileindex);
11567 if (error)
11568 goto done;
11569 if (upa.conflicts > 0 && upa.missing == 0 &&
11570 upa.not_deleted == 0 && upa.unversioned == 0) {
11571 error = got_error_msg(GOT_ERR_CONFLICTS,
11572 "conflicts must be resolved before rebasing "
11573 "can continue");
11574 } else if (upa.conflicts > 0) {
11575 error = got_error_msg(GOT_ERR_CONFLICTS,
11576 "conflicts must be resolved before rebasing "
11577 "can continue; changes destined for some "
11578 "files were not yet merged and should be "
11579 "merged manually if required before the "
11580 "rebase operation is continued");
11581 } else {
11582 error = got_error_msg(GOT_ERR_CONFLICTS,
11583 "changes destined for some files were not "
11584 "yet merged and should be merged manually "
11585 "if required before the rebase operation "
11586 "is continued");
11588 } else
11589 error = rebase_complete(worktree, fileindex, branch,
11590 tmp_branch, repo, create_backup);
11591 done:
11592 free(cwd);
11593 free(committer);
11594 free(gitconfig_path);
11595 got_object_id_queue_free(&commits);
11596 free(branch_head_commit_id);
11597 free(resume_commit_id);
11598 free(head_commit_id);
11599 free(yca_id);
11600 if (commit)
11601 got_object_commit_close(commit);
11602 if (branch)
11603 got_ref_close(branch);
11604 if (new_base_branch)
11605 got_ref_close(new_base_branch);
11606 if (tmp_branch)
11607 got_ref_close(tmp_branch);
11608 if (head_ref)
11609 got_ref_close(head_ref);
11610 if (worktree)
11611 got_worktree_close(worktree);
11612 if (repo) {
11613 const struct got_error *close_err = got_repo_close(repo);
11614 if (error == NULL)
11615 error = close_err;
11617 if (pack_fds) {
11618 const struct got_error *pack_err =
11619 got_repo_pack_fds_close(pack_fds);
11620 if (error == NULL)
11621 error = pack_err;
11623 return error;
11626 __dead static void
11627 usage_histedit(void)
11629 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11630 "[branch]\n", getprogname());
11631 exit(1);
11634 #define GOT_HISTEDIT_PICK 'p'
11635 #define GOT_HISTEDIT_EDIT 'e'
11636 #define GOT_HISTEDIT_FOLD 'f'
11637 #define GOT_HISTEDIT_DROP 'd'
11638 #define GOT_HISTEDIT_MESG 'm'
11640 static const struct got_histedit_cmd {
11641 unsigned char code;
11642 const char *name;
11643 const char *desc;
11644 } got_histedit_cmds[] = {
11645 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11646 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11647 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11648 "be used" },
11649 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11650 { GOT_HISTEDIT_MESG, "mesg",
11651 "single-line log message for commit above (open editor if empty)" },
11654 struct got_histedit_list_entry {
11655 TAILQ_ENTRY(got_histedit_list_entry) entry;
11656 struct got_object_id *commit_id;
11657 const struct got_histedit_cmd *cmd;
11658 char *logmsg;
11660 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11662 static const struct got_error *
11663 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11664 FILE *f, struct got_repository *repo)
11666 const struct got_error *err = NULL;
11667 char *logmsg = NULL, *id_str = NULL;
11668 struct got_commit_object *commit = NULL;
11669 int n;
11671 err = got_object_open_as_commit(&commit, repo, commit_id);
11672 if (err)
11673 goto done;
11675 err = get_short_logmsg(&logmsg, 34, commit);
11676 if (err)
11677 goto done;
11679 err = got_object_id_str(&id_str, commit_id);
11680 if (err)
11681 goto done;
11683 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11684 if (n < 0)
11685 err = got_ferror(f, GOT_ERR_IO);
11686 done:
11687 if (commit)
11688 got_object_commit_close(commit);
11689 free(id_str);
11690 free(logmsg);
11691 return err;
11694 static const struct got_error *
11695 histedit_write_commit_list(struct got_object_id_queue *commits,
11696 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11697 int edit_only, struct got_repository *repo)
11699 const struct got_error *err = NULL;
11700 struct got_object_qid *qid;
11701 const char *histedit_cmd = NULL;
11703 if (STAILQ_EMPTY(commits))
11704 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11706 STAILQ_FOREACH(qid, commits, entry) {
11707 histedit_cmd = got_histedit_cmds[0].name;
11708 if (drop_only)
11709 histedit_cmd = "drop";
11710 else if (edit_only)
11711 histedit_cmd = "edit";
11712 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11713 histedit_cmd = "fold";
11714 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11715 if (err)
11716 break;
11717 if (edit_logmsg_only) {
11718 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11719 if (n < 0) {
11720 err = got_ferror(f, GOT_ERR_IO);
11721 break;
11726 return err;
11729 static const struct got_error *
11730 write_cmd_list(FILE *f, const char *branch_name,
11731 struct got_object_id_queue *commits)
11733 const struct got_error *err = NULL;
11734 size_t i;
11735 int n;
11736 char *id_str;
11737 struct got_object_qid *qid;
11739 qid = STAILQ_FIRST(commits);
11740 err = got_object_id_str(&id_str, &qid->id);
11741 if (err)
11742 return err;
11744 n = fprintf(f,
11745 "# Editing the history of branch '%s' starting at\n"
11746 "# commit %s\n"
11747 "# Commits will be processed in order from top to "
11748 "bottom of this file.\n", branch_name, id_str);
11749 if (n < 0) {
11750 err = got_ferror(f, GOT_ERR_IO);
11751 goto done;
11754 n = fprintf(f, "# Available histedit commands:\n");
11755 if (n < 0) {
11756 err = got_ferror(f, GOT_ERR_IO);
11757 goto done;
11760 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11761 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11762 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11763 cmd->desc);
11764 if (n < 0) {
11765 err = got_ferror(f, GOT_ERR_IO);
11766 break;
11769 done:
11770 free(id_str);
11771 return err;
11774 static const struct got_error *
11775 histedit_syntax_error(int lineno)
11777 static char msg[42];
11778 int ret;
11780 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11781 lineno);
11782 if (ret < 0 || (size_t)ret >= sizeof(msg))
11783 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11785 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11788 static const struct got_error *
11789 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11790 char *logmsg, struct got_repository *repo)
11792 const struct got_error *err;
11793 struct got_commit_object *folded_commit = NULL;
11794 char *id_str, *folded_logmsg = NULL;
11796 err = got_object_id_str(&id_str, hle->commit_id);
11797 if (err)
11798 return err;
11800 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11801 if (err)
11802 goto done;
11804 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11805 if (err)
11806 goto done;
11807 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11808 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11809 folded_logmsg) == -1) {
11810 err = got_error_from_errno("asprintf");
11812 done:
11813 if (folded_commit)
11814 got_object_commit_close(folded_commit);
11815 free(id_str);
11816 free(folded_logmsg);
11817 return err;
11820 static struct got_histedit_list_entry *
11821 get_folded_commits(struct got_histedit_list_entry *hle)
11823 struct got_histedit_list_entry *prev, *folded = NULL;
11825 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11826 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11827 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11828 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11829 folded = prev;
11830 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11833 return folded;
11836 static const struct got_error *
11837 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11838 struct got_repository *repo)
11840 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11841 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11842 const struct got_error *err = NULL;
11843 struct got_commit_object *commit = NULL;
11844 int logmsg_len;
11845 int fd = -1;
11846 struct got_histedit_list_entry *folded = NULL;
11848 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11849 if (err)
11850 return err;
11852 folded = get_folded_commits(hle);
11853 if (folded) {
11854 while (folded != hle) {
11855 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11856 folded = TAILQ_NEXT(folded, entry);
11857 continue;
11859 err = append_folded_commit_msg(&new_msg, folded,
11860 logmsg, repo);
11861 if (err)
11862 goto done;
11863 free(logmsg);
11864 logmsg = new_msg;
11865 folded = TAILQ_NEXT(folded, entry);
11869 err = got_object_id_str(&id_str, hle->commit_id);
11870 if (err)
11871 goto done;
11872 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11873 if (err)
11874 goto done;
11875 logmsg_len = asprintf(&new_msg,
11876 "%s\n# original log message of commit %s: %s",
11877 logmsg ? logmsg : "", id_str, orig_logmsg);
11878 if (logmsg_len == -1) {
11879 err = got_error_from_errno("asprintf");
11880 goto done;
11882 free(logmsg);
11883 logmsg = new_msg;
11885 err = got_object_id_str(&id_str, hle->commit_id);
11886 if (err)
11887 goto done;
11889 err = got_opentemp_named_fd(&logmsg_path, &fd,
11890 GOT_TMPDIR_STR "/got-logmsg", "");
11891 if (err)
11892 goto done;
11894 if (write(fd, logmsg, logmsg_len) == -1) {
11895 err = got_error_from_errno2("write", logmsg_path);
11896 goto done;
11898 if (close(fd) == -1) {
11899 err = got_error_from_errno2("close", logmsg_path);
11900 goto done;
11902 fd = -1;
11904 err = get_editor(&editor);
11905 if (err)
11906 goto done;
11908 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11909 logmsg_len, 0);
11910 if (err) {
11911 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11912 goto done;
11913 err = NULL;
11914 hle->logmsg = strdup(new_msg);
11915 if (hle->logmsg == NULL)
11916 err = got_error_from_errno("strdup");
11918 done:
11919 if (fd != -1 && close(fd) == -1 && err == NULL)
11920 err = got_error_from_errno2("close", logmsg_path);
11921 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11922 err = got_error_from_errno2("unlink", logmsg_path);
11923 free(logmsg_path);
11924 free(logmsg);
11925 free(orig_logmsg);
11926 free(editor);
11927 if (commit)
11928 got_object_commit_close(commit);
11929 return err;
11932 static const struct got_error *
11933 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11934 FILE *f, struct got_repository *repo)
11936 const struct got_error *err = NULL;
11937 char *line = NULL, *p, *end;
11938 size_t i, linesize = 0;
11939 ssize_t linelen;
11940 int lineno = 0, lastcmd = -1;
11941 const struct got_histedit_cmd *cmd;
11942 struct got_object_id *commit_id = NULL;
11943 struct got_histedit_list_entry *hle = NULL;
11945 for (;;) {
11946 linelen = getline(&line, &linesize, f);
11947 if (linelen == -1) {
11948 const struct got_error *getline_err;
11949 if (feof(f))
11950 break;
11951 getline_err = got_error_from_errno("getline");
11952 err = got_ferror(f, getline_err->code);
11953 break;
11955 lineno++;
11956 p = line;
11957 while (isspace((unsigned char)p[0]))
11958 p++;
11959 if (p[0] == '#' || p[0] == '\0')
11960 continue;
11961 cmd = NULL;
11962 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11963 cmd = &got_histedit_cmds[i];
11964 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11965 isspace((unsigned char)p[strlen(cmd->name)])) {
11966 p += strlen(cmd->name);
11967 break;
11969 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11970 p++;
11971 break;
11974 if (i == nitems(got_histedit_cmds)) {
11975 err = histedit_syntax_error(lineno);
11976 break;
11978 while (isspace((unsigned char)p[0]))
11979 p++;
11980 if (cmd->code == GOT_HISTEDIT_MESG) {
11981 if (lastcmd != GOT_HISTEDIT_PICK &&
11982 lastcmd != GOT_HISTEDIT_EDIT) {
11983 err = got_error(GOT_ERR_HISTEDIT_CMD);
11984 break;
11986 if (p[0] == '\0') {
11987 err = histedit_edit_logmsg(hle, repo);
11988 if (err)
11989 break;
11990 } else {
11991 hle->logmsg = strdup(p);
11992 if (hle->logmsg == NULL) {
11993 err = got_error_from_errno("strdup");
11994 break;
11997 lastcmd = cmd->code;
11998 continue;
11999 } else {
12000 end = p;
12001 while (end[0] && !isspace((unsigned char)end[0]))
12002 end++;
12003 *end = '\0';
12005 err = got_object_resolve_id_str(&commit_id, repo, p);
12006 if (err) {
12007 /* override error code */
12008 err = histedit_syntax_error(lineno);
12009 break;
12012 hle = malloc(sizeof(*hle));
12013 if (hle == NULL) {
12014 err = got_error_from_errno("malloc");
12015 break;
12017 hle->cmd = cmd;
12018 hle->commit_id = commit_id;
12019 hle->logmsg = NULL;
12020 commit_id = NULL;
12021 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12022 lastcmd = cmd->code;
12025 free(line);
12026 free(commit_id);
12027 return err;
12030 static const struct got_error *
12031 histedit_check_script(struct got_histedit_list *histedit_cmds,
12032 struct got_object_id_queue *commits, struct got_repository *repo)
12034 const struct got_error *err = NULL;
12035 struct got_object_qid *qid;
12036 struct got_histedit_list_entry *hle;
12037 static char msg[92];
12038 char *id_str;
12040 if (TAILQ_EMPTY(histedit_cmds))
12041 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12042 "histedit script contains no commands");
12043 if (STAILQ_EMPTY(commits))
12044 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12046 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12047 struct got_histedit_list_entry *hle2;
12048 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12049 if (hle == hle2)
12050 continue;
12051 if (got_object_id_cmp(hle->commit_id,
12052 hle2->commit_id) != 0)
12053 continue;
12054 err = got_object_id_str(&id_str, hle->commit_id);
12055 if (err)
12056 return err;
12057 snprintf(msg, sizeof(msg), "commit %s is listed "
12058 "more than once in histedit script", id_str);
12059 free(id_str);
12060 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12064 STAILQ_FOREACH(qid, commits, entry) {
12065 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12066 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12067 break;
12069 if (hle == NULL) {
12070 err = got_object_id_str(&id_str, &qid->id);
12071 if (err)
12072 return err;
12073 snprintf(msg, sizeof(msg),
12074 "commit %s missing from histedit script", id_str);
12075 free(id_str);
12076 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12080 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12081 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12082 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12083 "last commit in histedit script cannot be folded");
12085 return NULL;
12088 static const struct got_error *
12089 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12090 const char *path, struct got_object_id_queue *commits,
12091 struct got_repository *repo)
12093 const struct got_error *err = NULL;
12094 struct stat st, st2;
12095 struct timespec timeout;
12096 char *editor;
12097 FILE *f = NULL;
12099 err = get_editor(&editor);
12100 if (err)
12101 return err;
12103 if (stat(path, &st) == -1) {
12104 err = got_error_from_errno2("stat", path);
12105 goto done;
12108 if (spawn_editor(editor, path) == -1) {
12109 err = got_error_from_errno("failed spawning editor");
12110 goto done;
12113 timeout.tv_sec = 0;
12114 timeout.tv_nsec = 1;
12115 nanosleep(&timeout, NULL);
12117 if (stat(path, &st2) == -1) {
12118 err = got_error_from_errno2("stat", path);
12119 goto done;
12122 if (st.st_size == st2.st_size &&
12123 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12124 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12125 "no changes made to histedit script, aborting");
12126 goto done;
12129 f = fopen(path, "re");
12130 if (f == NULL) {
12131 err = got_error_from_errno("fopen");
12132 goto done;
12134 err = histedit_parse_list(histedit_cmds, f, repo);
12135 if (err)
12136 goto done;
12138 err = histedit_check_script(histedit_cmds, commits, repo);
12139 done:
12140 if (f && fclose(f) == EOF && err == NULL)
12141 err = got_error_from_errno("fclose");
12142 free(editor);
12143 return err;
12146 static const struct got_error *
12147 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12148 struct got_object_id_queue *, const char *, const char *,
12149 struct got_repository *);
12151 static const struct got_error *
12152 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12153 struct got_object_id_queue *commits, const char *branch_name,
12154 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12155 struct got_repository *repo)
12157 const struct got_error *err;
12158 FILE *f = NULL;
12159 char *path = NULL;
12161 err = got_opentemp_named(&path, &f, "got-histedit", "");
12162 if (err)
12163 return err;
12165 err = write_cmd_list(f, branch_name, commits);
12166 if (err)
12167 goto done;
12169 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12170 fold_only, drop_only, edit_only, repo);
12171 if (err)
12172 goto done;
12174 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12175 rewind(f);
12176 err = histedit_parse_list(histedit_cmds, f, repo);
12177 } else {
12178 if (fclose(f) == EOF) {
12179 err = got_error_from_errno("fclose");
12180 goto done;
12182 f = NULL;
12183 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12184 if (err) {
12185 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12186 err->code != GOT_ERR_HISTEDIT_CMD)
12187 goto done;
12188 err = histedit_edit_list_retry(histedit_cmds, err,
12189 commits, path, branch_name, repo);
12192 done:
12193 if (f && fclose(f) == EOF && err == NULL)
12194 err = got_error_from_errno("fclose");
12195 if (path && unlink(path) != 0 && err == NULL)
12196 err = got_error_from_errno2("unlink", path);
12197 free(path);
12198 return err;
12201 static const struct got_error *
12202 histedit_save_list(struct got_histedit_list *histedit_cmds,
12203 struct got_worktree *worktree, struct got_repository *repo)
12205 const struct got_error *err = NULL;
12206 char *path = NULL;
12207 FILE *f = NULL;
12208 struct got_histedit_list_entry *hle;
12210 err = got_worktree_get_histedit_script_path(&path, worktree);
12211 if (err)
12212 return err;
12214 f = fopen(path, "we");
12215 if (f == NULL) {
12216 err = got_error_from_errno2("fopen", path);
12217 goto done;
12219 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12220 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12221 repo);
12222 if (err)
12223 break;
12225 if (hle->logmsg) {
12226 int n = fprintf(f, "%c %s\n",
12227 GOT_HISTEDIT_MESG, hle->logmsg);
12228 if (n < 0) {
12229 err = got_ferror(f, GOT_ERR_IO);
12230 break;
12234 done:
12235 if (f && fclose(f) == EOF && err == NULL)
12236 err = got_error_from_errno("fclose");
12237 free(path);
12238 return err;
12241 static void
12242 histedit_free_list(struct got_histedit_list *histedit_cmds)
12244 struct got_histedit_list_entry *hle;
12246 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12247 TAILQ_REMOVE(histedit_cmds, hle, entry);
12248 free(hle);
12252 static const struct got_error *
12253 histedit_load_list(struct got_histedit_list *histedit_cmds,
12254 const char *path, struct got_repository *repo)
12256 const struct got_error *err = NULL;
12257 FILE *f = NULL;
12259 f = fopen(path, "re");
12260 if (f == NULL) {
12261 err = got_error_from_errno2("fopen", path);
12262 goto done;
12265 err = histedit_parse_list(histedit_cmds, f, repo);
12266 done:
12267 if (f && fclose(f) == EOF && err == NULL)
12268 err = got_error_from_errno("fclose");
12269 return err;
12272 static const struct got_error *
12273 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12274 const struct got_error *edit_err, struct got_object_id_queue *commits,
12275 const char *path, const char *branch_name, struct got_repository *repo)
12277 const struct got_error *err = NULL, *prev_err = edit_err;
12278 int resp = ' ';
12280 while (resp != 'c' && resp != 'r' && resp != 'a') {
12281 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12282 "or (a)bort: ", getprogname(), prev_err->msg);
12283 resp = getchar();
12284 if (resp == '\n')
12285 resp = getchar();
12286 if (resp == 'c') {
12287 histedit_free_list(histedit_cmds);
12288 err = histedit_run_editor(histedit_cmds, path, commits,
12289 repo);
12290 if (err) {
12291 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12292 err->code != GOT_ERR_HISTEDIT_CMD)
12293 break;
12294 prev_err = err;
12295 resp = ' ';
12296 continue;
12298 break;
12299 } else if (resp == 'r') {
12300 histedit_free_list(histedit_cmds);
12301 err = histedit_edit_script(histedit_cmds,
12302 commits, branch_name, 0, 0, 0, 0, repo);
12303 if (err) {
12304 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12305 err->code != GOT_ERR_HISTEDIT_CMD)
12306 break;
12307 prev_err = err;
12308 resp = ' ';
12309 continue;
12311 break;
12312 } else if (resp == 'a') {
12313 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12314 break;
12315 } else
12316 printf("invalid response '%c'\n", resp);
12319 return err;
12322 static const struct got_error *
12323 histedit_complete(struct got_worktree *worktree,
12324 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12325 struct got_reference *branch, struct got_repository *repo)
12327 printf("Switching work tree to %s\n",
12328 got_ref_get_symref_target(branch));
12329 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12330 branch, repo);
12333 static const struct got_error *
12334 show_histedit_progress(struct got_commit_object *commit,
12335 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12337 const struct got_error *err;
12338 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12340 err = got_object_id_str(&old_id_str, hle->commit_id);
12341 if (err)
12342 goto done;
12344 if (new_id) {
12345 err = got_object_id_str(&new_id_str, new_id);
12346 if (err)
12347 goto done;
12350 old_id_str[12] = '\0';
12351 if (new_id_str)
12352 new_id_str[12] = '\0';
12354 if (hle->logmsg) {
12355 logmsg = strdup(hle->logmsg);
12356 if (logmsg == NULL) {
12357 err = got_error_from_errno("strdup");
12358 goto done;
12360 trim_logmsg(logmsg, 42);
12361 } else {
12362 err = get_short_logmsg(&logmsg, 42, commit);
12363 if (err)
12364 goto done;
12367 switch (hle->cmd->code) {
12368 case GOT_HISTEDIT_PICK:
12369 case GOT_HISTEDIT_EDIT:
12370 printf("%s -> %s: %s\n", old_id_str,
12371 new_id_str ? new_id_str : "no-op change", logmsg);
12372 break;
12373 case GOT_HISTEDIT_DROP:
12374 case GOT_HISTEDIT_FOLD:
12375 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12376 logmsg);
12377 break;
12378 default:
12379 break;
12381 done:
12382 free(old_id_str);
12383 free(new_id_str);
12384 return err;
12387 static const struct got_error *
12388 histedit_commit(struct got_pathlist_head *merged_paths,
12389 struct got_worktree *worktree, struct got_fileindex *fileindex,
12390 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12391 const char *committer, int allow_conflict, struct got_repository *repo)
12393 const struct got_error *err;
12394 struct got_commit_object *commit;
12395 struct got_object_id *new_commit_id;
12397 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12398 && hle->logmsg == NULL) {
12399 err = histedit_edit_logmsg(hle, repo);
12400 if (err)
12401 return err;
12404 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12405 if (err)
12406 return err;
12408 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12409 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12410 hle->logmsg, allow_conflict, repo);
12411 if (err) {
12412 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12413 goto done;
12414 err = show_histedit_progress(commit, hle, NULL);
12415 } else {
12416 err = show_histedit_progress(commit, hle, new_commit_id);
12417 free(new_commit_id);
12419 done:
12420 got_object_commit_close(commit);
12421 return err;
12424 static const struct got_error *
12425 histedit_skip_commit(struct got_histedit_list_entry *hle,
12426 struct got_worktree *worktree, struct got_repository *repo)
12428 const struct got_error *error;
12429 struct got_commit_object *commit;
12431 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12432 repo);
12433 if (error)
12434 return error;
12436 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12437 if (error)
12438 return error;
12440 error = show_histedit_progress(commit, hle, NULL);
12441 got_object_commit_close(commit);
12442 return error;
12445 static const struct got_error *
12446 check_local_changes(void *arg, unsigned char status,
12447 unsigned char staged_status, const char *path,
12448 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12449 struct got_object_id *commit_id, int dirfd, const char *de_name)
12451 int *have_local_changes = arg;
12453 switch (status) {
12454 case GOT_STATUS_ADD:
12455 case GOT_STATUS_DELETE:
12456 case GOT_STATUS_MODIFY:
12457 case GOT_STATUS_CONFLICT:
12458 *have_local_changes = 1;
12459 return got_error(GOT_ERR_CANCELLED);
12460 default:
12461 break;
12464 switch (staged_status) {
12465 case GOT_STATUS_ADD:
12466 case GOT_STATUS_DELETE:
12467 case GOT_STATUS_MODIFY:
12468 *have_local_changes = 1;
12469 return got_error(GOT_ERR_CANCELLED);
12470 default:
12471 break;
12474 return NULL;
12477 static const struct got_error *
12478 cmd_histedit(int argc, char *argv[])
12480 const struct got_error *error = NULL;
12481 struct got_worktree *worktree = NULL;
12482 struct got_fileindex *fileindex = NULL;
12483 struct got_repository *repo = NULL;
12484 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12485 struct got_reference *branch = NULL;
12486 struct got_reference *tmp_branch = NULL;
12487 struct got_object_id *resume_commit_id = NULL;
12488 struct got_object_id *base_commit_id = NULL;
12489 struct got_object_id *head_commit_id = NULL;
12490 struct got_commit_object *commit = NULL;
12491 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12492 struct got_update_progress_arg upa;
12493 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12494 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12495 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12496 const char *edit_script_path = NULL;
12497 struct got_object_id_queue commits;
12498 struct got_pathlist_head merged_paths;
12499 const struct got_object_id_queue *parent_ids;
12500 struct got_object_qid *pid;
12501 struct got_histedit_list histedit_cmds;
12502 struct got_histedit_list_entry *hle;
12503 int *pack_fds = NULL;
12505 STAILQ_INIT(&commits);
12506 TAILQ_INIT(&histedit_cmds);
12507 TAILQ_INIT(&merged_paths);
12508 memset(&upa, 0, sizeof(upa));
12510 #ifndef PROFILE
12511 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12512 "unveil", NULL) == -1)
12513 err(1, "pledge");
12514 #endif
12516 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12517 switch (ch) {
12518 case 'a':
12519 abort_edit = 1;
12520 break;
12521 case 'C':
12522 allow_conflict = 1;
12523 break;
12524 case 'c':
12525 continue_edit = 1;
12526 break;
12527 case 'd':
12528 drop_only = 1;
12529 break;
12530 case 'e':
12531 edit_only = 1;
12532 break;
12533 case 'F':
12534 edit_script_path = optarg;
12535 break;
12536 case 'f':
12537 fold_only = 1;
12538 break;
12539 case 'l':
12540 list_backups = 1;
12541 break;
12542 case 'm':
12543 edit_logmsg_only = 1;
12544 break;
12545 case 'X':
12546 delete_backups = 1;
12547 break;
12548 default:
12549 usage_histedit();
12550 /* NOTREACHED */
12554 argc -= optind;
12555 argv += optind;
12557 if (abort_edit && allow_conflict)
12558 option_conflict('a', 'C');
12559 if (abort_edit && continue_edit)
12560 option_conflict('a', 'c');
12561 if (edit_script_path && allow_conflict)
12562 option_conflict('F', 'C');
12563 if (edit_script_path && edit_logmsg_only)
12564 option_conflict('F', 'm');
12565 if (abort_edit && edit_logmsg_only)
12566 option_conflict('a', 'm');
12567 if (edit_logmsg_only && allow_conflict)
12568 option_conflict('m', 'C');
12569 if (continue_edit && edit_logmsg_only)
12570 option_conflict('c', 'm');
12571 if (abort_edit && fold_only)
12572 option_conflict('a', 'f');
12573 if (fold_only && allow_conflict)
12574 option_conflict('f', 'C');
12575 if (continue_edit && fold_only)
12576 option_conflict('c', 'f');
12577 if (fold_only && edit_logmsg_only)
12578 option_conflict('f', 'm');
12579 if (edit_script_path && fold_only)
12580 option_conflict('F', 'f');
12581 if (abort_edit && edit_only)
12582 option_conflict('a', 'e');
12583 if (continue_edit && edit_only)
12584 option_conflict('c', 'e');
12585 if (edit_only && edit_logmsg_only)
12586 option_conflict('e', 'm');
12587 if (edit_script_path && edit_only)
12588 option_conflict('F', 'e');
12589 if (fold_only && edit_only)
12590 option_conflict('f', 'e');
12591 if (drop_only && abort_edit)
12592 option_conflict('d', 'a');
12593 if (drop_only && allow_conflict)
12594 option_conflict('d', 'C');
12595 if (drop_only && continue_edit)
12596 option_conflict('d', 'c');
12597 if (drop_only && edit_logmsg_only)
12598 option_conflict('d', 'm');
12599 if (drop_only && edit_only)
12600 option_conflict('d', 'e');
12601 if (drop_only && edit_script_path)
12602 option_conflict('d', 'F');
12603 if (drop_only && fold_only)
12604 option_conflict('d', 'f');
12605 if (list_backups) {
12606 if (abort_edit)
12607 option_conflict('l', 'a');
12608 if (allow_conflict)
12609 option_conflict('l', 'C');
12610 if (continue_edit)
12611 option_conflict('l', 'c');
12612 if (edit_script_path)
12613 option_conflict('l', 'F');
12614 if (edit_logmsg_only)
12615 option_conflict('l', 'm');
12616 if (drop_only)
12617 option_conflict('l', 'd');
12618 if (fold_only)
12619 option_conflict('l', 'f');
12620 if (edit_only)
12621 option_conflict('l', 'e');
12622 if (delete_backups)
12623 option_conflict('l', 'X');
12624 if (argc != 0 && argc != 1)
12625 usage_histedit();
12626 } else if (delete_backups) {
12627 if (abort_edit)
12628 option_conflict('X', 'a');
12629 if (allow_conflict)
12630 option_conflict('X', 'C');
12631 if (continue_edit)
12632 option_conflict('X', 'c');
12633 if (drop_only)
12634 option_conflict('X', 'd');
12635 if (edit_script_path)
12636 option_conflict('X', 'F');
12637 if (edit_logmsg_only)
12638 option_conflict('X', 'm');
12639 if (fold_only)
12640 option_conflict('X', 'f');
12641 if (edit_only)
12642 option_conflict('X', 'e');
12643 if (list_backups)
12644 option_conflict('X', 'l');
12645 if (argc != 0 && argc != 1)
12646 usage_histedit();
12647 } else if (allow_conflict && !continue_edit)
12648 errx(1, "-C option requires -c");
12649 else if (argc != 0)
12650 usage_histedit();
12653 * This command cannot apply unveil(2) in all cases because the
12654 * user may choose to run an editor to edit the histedit script
12655 * and to edit individual commit log messages.
12656 * unveil(2) traverses exec(2); if an editor is used we have to
12657 * apply unveil after edit script and log messages have been written.
12658 * XXX TODO: Make use of unveil(2) where possible.
12661 cwd = getcwd(NULL, 0);
12662 if (cwd == NULL) {
12663 error = got_error_from_errno("getcwd");
12664 goto done;
12667 error = got_repo_pack_fds_open(&pack_fds);
12668 if (error != NULL)
12669 goto done;
12671 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12672 if (error) {
12673 if (list_backups || delete_backups) {
12674 if (error->code != GOT_ERR_NOT_WORKTREE)
12675 goto done;
12676 } else {
12677 if (error->code == GOT_ERR_NOT_WORKTREE)
12678 error = wrap_not_worktree_error(error,
12679 "histedit", cwd);
12680 goto done;
12684 if (list_backups || delete_backups) {
12685 error = got_repo_open(&repo,
12686 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12687 NULL, pack_fds);
12688 if (error != NULL)
12689 goto done;
12690 error = apply_unveil(got_repo_get_path(repo), 0,
12691 worktree ? got_worktree_get_root_path(worktree) : NULL);
12692 if (error)
12693 goto done;
12694 error = process_backup_refs(
12695 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12696 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12697 goto done; /* nothing else to do */
12700 error = get_gitconfig_path(&gitconfig_path);
12701 if (error)
12702 goto done;
12703 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12704 gitconfig_path, pack_fds);
12705 if (error != NULL)
12706 goto done;
12708 if (worktree != NULL && !list_backups && !delete_backups) {
12709 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12710 if (error)
12711 goto done;
12714 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12715 if (error)
12716 goto done;
12717 if (rebase_in_progress) {
12718 error = got_error(GOT_ERR_REBASING);
12719 goto done;
12722 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12723 repo);
12724 if (error)
12725 goto done;
12726 if (merge_in_progress) {
12727 error = got_error(GOT_ERR_MERGE_BUSY);
12728 goto done;
12731 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12732 if (error)
12733 goto done;
12735 if (edit_in_progress && edit_logmsg_only) {
12736 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12737 "histedit operation is in progress in this "
12738 "work tree and must be continued or aborted "
12739 "before the -m option can be used");
12740 goto done;
12742 if (edit_in_progress && drop_only) {
12743 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12744 "histedit operation is in progress in this "
12745 "work tree and must be continued or aborted "
12746 "before the -d option can be used");
12747 goto done;
12749 if (edit_in_progress && fold_only) {
12750 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12751 "histedit operation is in progress in this "
12752 "work tree and must be continued or aborted "
12753 "before the -f option can be used");
12754 goto done;
12756 if (edit_in_progress && edit_only) {
12757 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12758 "histedit operation is in progress in this "
12759 "work tree and must be continued or aborted "
12760 "before the -e option can be used");
12761 goto done;
12764 if (edit_in_progress && abort_edit) {
12765 error = got_worktree_histedit_continue(&resume_commit_id,
12766 &tmp_branch, &branch, &base_commit_id, &fileindex,
12767 worktree, repo);
12768 if (error)
12769 goto done;
12770 printf("Switching work tree to %s\n",
12771 got_ref_get_symref_target(branch));
12772 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12773 branch, base_commit_id, abort_progress, &upa);
12774 if (error)
12775 goto done;
12776 printf("Histedit of %s aborted\n",
12777 got_ref_get_symref_target(branch));
12778 print_merge_progress_stats(&upa);
12779 goto done; /* nothing else to do */
12780 } else if (abort_edit) {
12781 error = got_error(GOT_ERR_NOT_HISTEDIT);
12782 goto done;
12785 error = get_author(&committer, repo, worktree);
12786 if (error)
12787 goto done;
12789 if (continue_edit) {
12790 char *path;
12792 if (!edit_in_progress) {
12793 error = got_error(GOT_ERR_NOT_HISTEDIT);
12794 goto done;
12797 error = got_worktree_get_histedit_script_path(&path, worktree);
12798 if (error)
12799 goto done;
12801 error = histedit_load_list(&histedit_cmds, path, repo);
12802 free(path);
12803 if (error)
12804 goto done;
12806 error = got_worktree_histedit_continue(&resume_commit_id,
12807 &tmp_branch, &branch, &base_commit_id, &fileindex,
12808 worktree, repo);
12809 if (error)
12810 goto done;
12812 error = got_ref_resolve(&head_commit_id, repo, branch);
12813 if (error)
12814 goto done;
12816 error = got_object_open_as_commit(&commit, repo,
12817 head_commit_id);
12818 if (error)
12819 goto done;
12820 parent_ids = got_object_commit_get_parent_ids(commit);
12821 pid = STAILQ_FIRST(parent_ids);
12822 if (pid == NULL) {
12823 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12824 goto done;
12826 error = collect_commits(&commits, head_commit_id, &pid->id,
12827 base_commit_id, got_worktree_get_path_prefix(worktree),
12828 GOT_ERR_HISTEDIT_PATH, repo);
12829 got_object_commit_close(commit);
12830 commit = NULL;
12831 if (error)
12832 goto done;
12833 } else {
12834 if (edit_in_progress) {
12835 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12836 goto done;
12839 error = got_ref_open(&branch, repo,
12840 got_worktree_get_head_ref_name(worktree), 0);
12841 if (error != NULL)
12842 goto done;
12844 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12845 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12846 "will not edit commit history of a branch outside "
12847 "the \"refs/heads/\" reference namespace");
12848 goto done;
12851 error = got_ref_resolve(&head_commit_id, repo, branch);
12852 got_ref_close(branch);
12853 branch = NULL;
12854 if (error)
12855 goto done;
12857 error = got_object_open_as_commit(&commit, repo,
12858 head_commit_id);
12859 if (error)
12860 goto done;
12861 parent_ids = got_object_commit_get_parent_ids(commit);
12862 pid = STAILQ_FIRST(parent_ids);
12863 if (pid == NULL) {
12864 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12865 goto done;
12867 error = collect_commits(&commits, head_commit_id, &pid->id,
12868 got_worktree_get_base_commit_id(worktree),
12869 got_worktree_get_path_prefix(worktree),
12870 GOT_ERR_HISTEDIT_PATH, repo);
12871 got_object_commit_close(commit);
12872 commit = NULL;
12873 if (error)
12874 goto done;
12876 if (STAILQ_EMPTY(&commits)) {
12877 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12878 goto done;
12881 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12882 &base_commit_id, &fileindex, worktree, repo);
12883 if (error)
12884 goto done;
12886 if (edit_script_path) {
12887 error = histedit_load_list(&histedit_cmds,
12888 edit_script_path, repo);
12889 if (error) {
12890 got_worktree_histedit_abort(worktree, fileindex,
12891 repo, branch, base_commit_id,
12892 abort_progress, &upa);
12893 print_merge_progress_stats(&upa);
12894 goto done;
12896 } else {
12897 const char *branch_name;
12898 branch_name = got_ref_get_symref_target(branch);
12899 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12900 branch_name += 11;
12901 error = histedit_edit_script(&histedit_cmds, &commits,
12902 branch_name, edit_logmsg_only, fold_only,
12903 drop_only, edit_only, repo);
12904 if (error) {
12905 got_worktree_histedit_abort(worktree, fileindex,
12906 repo, branch, base_commit_id,
12907 abort_progress, &upa);
12908 print_merge_progress_stats(&upa);
12909 goto done;
12914 error = histedit_save_list(&histedit_cmds, worktree,
12915 repo);
12916 if (error) {
12917 got_worktree_histedit_abort(worktree, fileindex,
12918 repo, branch, base_commit_id,
12919 abort_progress, &upa);
12920 print_merge_progress_stats(&upa);
12921 goto done;
12926 error = histedit_check_script(&histedit_cmds, &commits, repo);
12927 if (error)
12928 goto done;
12930 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12931 if (resume_commit_id) {
12932 if (got_object_id_cmp(hle->commit_id,
12933 resume_commit_id) != 0)
12934 continue;
12936 resume_commit_id = NULL;
12937 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12938 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12939 error = histedit_skip_commit(hle, worktree,
12940 repo);
12941 if (error)
12942 goto done;
12943 } else {
12944 struct got_pathlist_head paths;
12945 int have_changes = 0;
12947 TAILQ_INIT(&paths);
12948 error = got_pathlist_append(&paths, "", NULL);
12949 if (error)
12950 goto done;
12951 error = got_worktree_status(worktree, &paths,
12952 repo, 0, check_local_changes, &have_changes,
12953 check_cancelled, NULL);
12954 got_pathlist_free(&paths,
12955 GOT_PATHLIST_FREE_NONE);
12956 if (error) {
12957 if (error->code != GOT_ERR_CANCELLED)
12958 goto done;
12959 if (sigint_received || sigpipe_received)
12960 goto done;
12962 if (have_changes) {
12963 error = histedit_commit(NULL, worktree,
12964 fileindex, tmp_branch, hle,
12965 committer, allow_conflict, repo);
12966 if (error)
12967 goto done;
12968 } else {
12969 error = got_object_open_as_commit(
12970 &commit, repo, hle->commit_id);
12971 if (error)
12972 goto done;
12973 error = show_histedit_progress(commit,
12974 hle, NULL);
12975 got_object_commit_close(commit);
12976 commit = NULL;
12977 if (error)
12978 goto done;
12981 continue;
12984 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12985 error = histedit_skip_commit(hle, worktree, repo);
12986 if (error)
12987 goto done;
12988 continue;
12991 error = got_object_open_as_commit(&commit, repo,
12992 hle->commit_id);
12993 if (error)
12994 goto done;
12995 parent_ids = got_object_commit_get_parent_ids(commit);
12996 pid = STAILQ_FIRST(parent_ids);
12998 error = got_worktree_histedit_merge_files(&merged_paths,
12999 worktree, fileindex, &pid->id, hle->commit_id, repo,
13000 update_progress, &upa, check_cancelled, NULL);
13001 if (error)
13002 goto done;
13003 got_object_commit_close(commit);
13004 commit = NULL;
13006 print_merge_progress_stats(&upa);
13007 if (upa.conflicts > 0 || upa.missing > 0 ||
13008 upa.not_deleted > 0 || upa.unversioned > 0) {
13009 if (upa.conflicts > 0) {
13010 error = show_rebase_merge_conflict(
13011 hle->commit_id, repo);
13012 if (error)
13013 goto done;
13015 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13016 break;
13019 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13020 char *id_str;
13021 error = got_object_id_str(&id_str, hle->commit_id);
13022 if (error)
13023 goto done;
13024 printf("Stopping histedit for amending commit %s\n",
13025 id_str);
13026 free(id_str);
13027 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13028 error = got_worktree_histedit_postpone(worktree,
13029 fileindex);
13030 goto done;
13033 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13034 error = histedit_skip_commit(hle, worktree, repo);
13035 if (error)
13036 goto done;
13037 continue;
13040 error = histedit_commit(&merged_paths, worktree, fileindex,
13041 tmp_branch, hle, committer, allow_conflict, repo);
13042 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13043 if (error)
13044 goto done;
13047 if (upa.conflicts > 0 || upa.missing > 0 ||
13048 upa.not_deleted > 0 || upa.unversioned > 0) {
13049 error = got_worktree_histedit_postpone(worktree, fileindex);
13050 if (error)
13051 goto done;
13052 if (upa.conflicts > 0 && upa.missing == 0 &&
13053 upa.not_deleted == 0 && upa.unversioned == 0) {
13054 error = got_error_msg(GOT_ERR_CONFLICTS,
13055 "conflicts must be resolved before histedit "
13056 "can continue");
13057 } else if (upa.conflicts > 0) {
13058 error = got_error_msg(GOT_ERR_CONFLICTS,
13059 "conflicts must be resolved before histedit "
13060 "can continue; changes destined for some "
13061 "files were not yet merged and should be "
13062 "merged manually if required before the "
13063 "histedit operation is continued");
13064 } else {
13065 error = got_error_msg(GOT_ERR_CONFLICTS,
13066 "changes destined for some files were not "
13067 "yet merged and should be merged manually "
13068 "if required before the histedit operation "
13069 "is continued");
13071 } else
13072 error = histedit_complete(worktree, fileindex, tmp_branch,
13073 branch, repo);
13074 done:
13075 free(cwd);
13076 free(committer);
13077 free(gitconfig_path);
13078 got_object_id_queue_free(&commits);
13079 histedit_free_list(&histedit_cmds);
13080 free(head_commit_id);
13081 free(base_commit_id);
13082 free(resume_commit_id);
13083 if (commit)
13084 got_object_commit_close(commit);
13085 if (branch)
13086 got_ref_close(branch);
13087 if (tmp_branch)
13088 got_ref_close(tmp_branch);
13089 if (worktree)
13090 got_worktree_close(worktree);
13091 if (repo) {
13092 const struct got_error *close_err = got_repo_close(repo);
13093 if (error == NULL)
13094 error = close_err;
13096 if (pack_fds) {
13097 const struct got_error *pack_err =
13098 got_repo_pack_fds_close(pack_fds);
13099 if (error == NULL)
13100 error = pack_err;
13102 return error;
13105 __dead static void
13106 usage_integrate(void)
13108 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13109 exit(1);
13112 static const struct got_error *
13113 cmd_integrate(int argc, char *argv[])
13115 const struct got_error *error = NULL;
13116 struct got_repository *repo = NULL;
13117 struct got_worktree *worktree = NULL;
13118 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13119 const char *branch_arg = NULL;
13120 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13121 struct got_fileindex *fileindex = NULL;
13122 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13123 int ch;
13124 struct got_update_progress_arg upa;
13125 int *pack_fds = NULL;
13127 #ifndef PROFILE
13128 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13129 "unveil", NULL) == -1)
13130 err(1, "pledge");
13131 #endif
13133 while ((ch = getopt(argc, argv, "")) != -1) {
13134 switch (ch) {
13135 default:
13136 usage_integrate();
13137 /* NOTREACHED */
13141 argc -= optind;
13142 argv += optind;
13144 if (argc != 1)
13145 usage_integrate();
13146 branch_arg = argv[0];
13148 cwd = getcwd(NULL, 0);
13149 if (cwd == NULL) {
13150 error = got_error_from_errno("getcwd");
13151 goto done;
13154 error = got_repo_pack_fds_open(&pack_fds);
13155 if (error != NULL)
13156 goto done;
13158 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13159 if (error) {
13160 if (error->code == GOT_ERR_NOT_WORKTREE)
13161 error = wrap_not_worktree_error(error, "integrate",
13162 cwd);
13163 goto done;
13166 error = check_rebase_or_histedit_in_progress(worktree);
13167 if (error)
13168 goto done;
13170 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13171 NULL, pack_fds);
13172 if (error != NULL)
13173 goto done;
13175 error = apply_unveil(got_repo_get_path(repo), 0,
13176 got_worktree_get_root_path(worktree));
13177 if (error)
13178 goto done;
13180 error = check_merge_in_progress(worktree, repo);
13181 if (error)
13182 goto done;
13184 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13185 error = got_error_from_errno("asprintf");
13186 goto done;
13189 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13190 &base_branch_ref, worktree, refname, repo);
13191 if (error)
13192 goto done;
13194 refname = strdup(got_ref_get_name(branch_ref));
13195 if (refname == NULL) {
13196 error = got_error_from_errno("strdup");
13197 got_worktree_integrate_abort(worktree, fileindex, repo,
13198 branch_ref, base_branch_ref);
13199 goto done;
13201 base_refname = strdup(got_ref_get_name(base_branch_ref));
13202 if (base_refname == NULL) {
13203 error = got_error_from_errno("strdup");
13204 got_worktree_integrate_abort(worktree, fileindex, repo,
13205 branch_ref, base_branch_ref);
13206 goto done;
13208 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13209 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13210 got_worktree_integrate_abort(worktree, fileindex, repo,
13211 branch_ref, base_branch_ref);
13212 goto done;
13215 error = got_ref_resolve(&commit_id, repo, branch_ref);
13216 if (error)
13217 goto done;
13219 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13220 if (error)
13221 goto done;
13223 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13224 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13225 "specified branch has already been integrated");
13226 got_worktree_integrate_abort(worktree, fileindex, repo,
13227 branch_ref, base_branch_ref);
13228 goto done;
13231 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13232 if (error) {
13233 if (error->code == GOT_ERR_ANCESTRY)
13234 error = got_error(GOT_ERR_REBASE_REQUIRED);
13235 got_worktree_integrate_abort(worktree, fileindex, repo,
13236 branch_ref, base_branch_ref);
13237 goto done;
13240 memset(&upa, 0, sizeof(upa));
13241 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13242 branch_ref, base_branch_ref, update_progress, &upa,
13243 check_cancelled, NULL);
13244 if (error)
13245 goto done;
13247 printf("Integrated %s into %s\n", refname, base_refname);
13248 print_update_progress_stats(&upa);
13249 done:
13250 if (repo) {
13251 const struct got_error *close_err = got_repo_close(repo);
13252 if (error == NULL)
13253 error = close_err;
13255 if (worktree)
13256 got_worktree_close(worktree);
13257 if (pack_fds) {
13258 const struct got_error *pack_err =
13259 got_repo_pack_fds_close(pack_fds);
13260 if (error == NULL)
13261 error = pack_err;
13263 free(cwd);
13264 free(base_commit_id);
13265 free(commit_id);
13266 free(refname);
13267 free(base_refname);
13268 return error;
13271 __dead static void
13272 usage_merge(void)
13274 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13275 exit(1);
13278 static const struct got_error *
13279 cmd_merge(int argc, char *argv[])
13281 const struct got_error *error = NULL;
13282 struct got_worktree *worktree = NULL;
13283 struct got_repository *repo = NULL;
13284 struct got_fileindex *fileindex = NULL;
13285 char *cwd = NULL, *id_str = NULL, *author = NULL;
13286 char *gitconfig_path = NULL;
13287 struct got_reference *branch = NULL, *wt_branch = NULL;
13288 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13289 struct got_object_id *wt_branch_tip = NULL;
13290 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13291 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13292 struct got_update_progress_arg upa;
13293 struct got_object_id *merge_commit_id = NULL;
13294 char *branch_name = NULL;
13295 int *pack_fds = NULL;
13297 memset(&upa, 0, sizeof(upa));
13299 #ifndef PROFILE
13300 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13301 "unveil", NULL) == -1)
13302 err(1, "pledge");
13303 #endif
13305 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13306 switch (ch) {
13307 case 'a':
13308 abort_merge = 1;
13309 break;
13310 case 'C':
13311 allow_conflict = 1;
13312 break;
13313 case 'c':
13314 continue_merge = 1;
13315 break;
13316 case 'M':
13317 prefer_fast_forward = 0;
13318 break;
13319 case 'n':
13320 interrupt_merge = 1;
13321 break;
13322 default:
13323 usage_merge();
13324 /* NOTREACHED */
13328 argc -= optind;
13329 argv += optind;
13331 if (abort_merge) {
13332 if (continue_merge)
13333 option_conflict('a', 'c');
13334 if (!prefer_fast_forward)
13335 option_conflict('a', 'M');
13336 if (interrupt_merge)
13337 option_conflict('a', 'n');
13338 } else if (continue_merge) {
13339 if (!prefer_fast_forward)
13340 option_conflict('c', 'M');
13341 if (interrupt_merge)
13342 option_conflict('c', 'n');
13344 if (allow_conflict) {
13345 if (!continue_merge)
13346 errx(1, "-C option requires -c");
13348 if (abort_merge || continue_merge) {
13349 if (argc != 0)
13350 usage_merge();
13351 } else if (argc != 1)
13352 usage_merge();
13354 cwd = getcwd(NULL, 0);
13355 if (cwd == NULL) {
13356 error = got_error_from_errno("getcwd");
13357 goto done;
13360 error = got_repo_pack_fds_open(&pack_fds);
13361 if (error != NULL)
13362 goto done;
13364 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13365 if (error) {
13366 if (error->code == GOT_ERR_NOT_WORKTREE)
13367 error = wrap_not_worktree_error(error,
13368 "merge", cwd);
13369 goto done;
13372 error = get_gitconfig_path(&gitconfig_path);
13373 if (error)
13374 goto done;
13375 error = got_repo_open(&repo,
13376 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13377 gitconfig_path, pack_fds);
13378 if (error != NULL)
13379 goto done;
13381 if (worktree != NULL) {
13382 error = worktree_has_logmsg_ref("merge", worktree, repo);
13383 if (error)
13384 goto done;
13387 error = apply_unveil(got_repo_get_path(repo), 0,
13388 worktree ? got_worktree_get_root_path(worktree) : NULL);
13389 if (error)
13390 goto done;
13392 error = check_rebase_or_histedit_in_progress(worktree);
13393 if (error)
13394 goto done;
13396 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13397 repo);
13398 if (error)
13399 goto done;
13401 if (merge_in_progress && !(abort_merge || continue_merge)) {
13402 error = got_error(GOT_ERR_MERGE_BUSY);
13403 goto done;
13406 if (!merge_in_progress && (abort_merge || continue_merge)) {
13407 error = got_error(GOT_ERR_NOT_MERGING);
13408 goto done;
13411 if (abort_merge) {
13412 error = got_worktree_merge_continue(&branch_name,
13413 &branch_tip, &fileindex, worktree, repo);
13414 if (error)
13415 goto done;
13416 error = got_worktree_merge_abort(worktree, fileindex, repo,
13417 abort_progress, &upa);
13418 if (error)
13419 goto done;
13420 printf("Merge of %s aborted\n", branch_name);
13421 goto done; /* nothing else to do */
13424 if (strncmp(got_worktree_get_head_ref_name(worktree),
13425 "refs/heads/", 11) != 0) {
13426 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13427 "work tree's current branch %s is outside the "
13428 "\"refs/heads/\" reference namespace; "
13429 "update -b required",
13430 got_worktree_get_head_ref_name(worktree));
13431 goto done;
13434 error = get_author(&author, repo, worktree);
13435 if (error)
13436 goto done;
13438 error = got_ref_open(&wt_branch, repo,
13439 got_worktree_get_head_ref_name(worktree), 0);
13440 if (error)
13441 goto done;
13442 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13443 if (error)
13444 goto done;
13446 if (continue_merge) {
13447 struct got_object_id *base_commit_id;
13448 base_commit_id = got_worktree_get_base_commit_id(worktree);
13449 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13450 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13451 goto done;
13453 error = got_worktree_merge_continue(&branch_name,
13454 &branch_tip, &fileindex, worktree, repo);
13455 if (error)
13456 goto done;
13457 } else {
13458 error = got_ref_open(&branch, repo, argv[0], 0);
13459 if (error != NULL)
13460 goto done;
13461 branch_name = strdup(got_ref_get_name(branch));
13462 if (branch_name == NULL) {
13463 error = got_error_from_errno("strdup");
13464 goto done;
13466 error = got_ref_resolve(&branch_tip, repo, branch);
13467 if (error)
13468 goto done;
13471 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13472 wt_branch_tip, branch_tip, 0, repo,
13473 check_cancelled, NULL);
13474 if (error && error->code != GOT_ERR_ANCESTRY)
13475 goto done;
13477 if (!continue_merge) {
13478 error = check_path_prefix(wt_branch_tip, branch_tip,
13479 got_worktree_get_path_prefix(worktree),
13480 GOT_ERR_MERGE_PATH, repo);
13481 if (error)
13482 goto done;
13483 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13484 if (error)
13485 goto done;
13486 if (prefer_fast_forward && yca_id &&
13487 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13488 struct got_pathlist_head paths;
13489 if (interrupt_merge) {
13490 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13491 "there are no changes to merge since %s "
13492 "is already based on %s; merge cannot be "
13493 "interrupted for amending; -n",
13494 branch_name, got_ref_get_name(wt_branch));
13495 goto done;
13497 printf("Forwarding %s to %s\n",
13498 got_ref_get_name(wt_branch), branch_name);
13499 error = got_ref_change_ref(wt_branch, branch_tip);
13500 if (error)
13501 goto done;
13502 error = got_ref_write(wt_branch, repo);
13503 if (error)
13504 goto done;
13505 error = got_worktree_set_base_commit_id(worktree, repo,
13506 branch_tip);
13507 if (error)
13508 goto done;
13509 TAILQ_INIT(&paths);
13510 error = got_pathlist_append(&paths, "", NULL);
13511 if (error)
13512 goto done;
13513 error = got_worktree_checkout_files(worktree,
13514 &paths, repo, update_progress, &upa,
13515 check_cancelled, NULL);
13516 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13517 if (error)
13518 goto done;
13519 if (upa.did_something) {
13520 char *id_str;
13521 error = got_object_id_str(&id_str, branch_tip);
13522 if (error)
13523 goto done;
13524 printf("Updated to commit %s\n", id_str);
13525 free(id_str);
13526 } else
13527 printf("Already up-to-date\n");
13528 print_update_progress_stats(&upa);
13529 goto done;
13531 error = got_worktree_merge_write_refs(worktree, branch, repo);
13532 if (error)
13533 goto done;
13535 error = got_worktree_merge_branch(worktree, fileindex,
13536 yca_id, branch_tip, repo, update_progress, &upa,
13537 check_cancelled, NULL);
13538 if (error)
13539 goto done;
13540 print_merge_progress_stats(&upa);
13541 if (!upa.did_something) {
13542 error = got_worktree_merge_abort(worktree, fileindex,
13543 repo, abort_progress, &upa);
13544 if (error)
13545 goto done;
13546 printf("Already up-to-date\n");
13547 goto done;
13551 if (interrupt_merge) {
13552 error = got_worktree_merge_postpone(worktree, fileindex);
13553 if (error)
13554 goto done;
13555 printf("Merge of %s interrupted on request\n", branch_name);
13556 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13557 upa.not_deleted > 0 || upa.unversioned > 0) {
13558 error = got_worktree_merge_postpone(worktree, fileindex);
13559 if (error)
13560 goto done;
13561 if (upa.conflicts > 0 && upa.missing == 0 &&
13562 upa.not_deleted == 0 && upa.unversioned == 0) {
13563 error = got_error_msg(GOT_ERR_CONFLICTS,
13564 "conflicts must be resolved before merging "
13565 "can continue");
13566 } else if (upa.conflicts > 0) {
13567 error = got_error_msg(GOT_ERR_CONFLICTS,
13568 "conflicts must be resolved before merging "
13569 "can continue; changes destined for some "
13570 "files were not yet merged and "
13571 "should be merged manually if required before the "
13572 "merge operation is continued");
13573 } else {
13574 error = got_error_msg(GOT_ERR_CONFLICTS,
13575 "changes destined for some "
13576 "files were not yet merged and should be "
13577 "merged manually if required before the "
13578 "merge operation is continued");
13580 goto done;
13581 } else {
13582 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13583 fileindex, author, NULL, 1, branch_tip, branch_name,
13584 allow_conflict, repo, continue_merge ? print_status : NULL,
13585 NULL);
13586 if (error)
13587 goto done;
13588 error = got_worktree_merge_complete(worktree, fileindex, repo);
13589 if (error)
13590 goto done;
13591 error = got_object_id_str(&id_str, merge_commit_id);
13592 if (error)
13593 goto done;
13594 printf("Merged %s into %s: %s\n", branch_name,
13595 got_worktree_get_head_ref_name(worktree),
13596 id_str);
13599 done:
13600 free(gitconfig_path);
13601 free(id_str);
13602 free(merge_commit_id);
13603 free(author);
13604 free(branch_tip);
13605 free(branch_name);
13606 free(yca_id);
13607 if (branch)
13608 got_ref_close(branch);
13609 if (wt_branch)
13610 got_ref_close(wt_branch);
13611 if (worktree)
13612 got_worktree_close(worktree);
13613 if (repo) {
13614 const struct got_error *close_err = got_repo_close(repo);
13615 if (error == NULL)
13616 error = close_err;
13618 if (pack_fds) {
13619 const struct got_error *pack_err =
13620 got_repo_pack_fds_close(pack_fds);
13621 if (error == NULL)
13622 error = pack_err;
13624 return error;
13627 __dead static void
13628 usage_stage(void)
13630 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13631 "[path ...]\n", getprogname());
13632 exit(1);
13635 static const struct got_error *
13636 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13637 const char *path, struct got_object_id *blob_id,
13638 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13639 int dirfd, const char *de_name)
13641 const struct got_error *err = NULL;
13642 char *id_str = NULL;
13644 if (staged_status != GOT_STATUS_ADD &&
13645 staged_status != GOT_STATUS_MODIFY &&
13646 staged_status != GOT_STATUS_DELETE)
13647 return NULL;
13649 if (staged_status == GOT_STATUS_ADD ||
13650 staged_status == GOT_STATUS_MODIFY)
13651 err = got_object_id_str(&id_str, staged_blob_id);
13652 else
13653 err = got_object_id_str(&id_str, blob_id);
13654 if (err)
13655 return err;
13657 printf("%s %c %s\n", id_str, staged_status, path);
13658 free(id_str);
13659 return NULL;
13662 static const struct got_error *
13663 cmd_stage(int argc, char *argv[])
13665 const struct got_error *error = NULL;
13666 struct got_repository *repo = NULL;
13667 struct got_worktree *worktree = NULL;
13668 char *cwd = NULL;
13669 struct got_pathlist_head paths;
13670 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13671 FILE *patch_script_file = NULL;
13672 const char *patch_script_path = NULL;
13673 struct choose_patch_arg cpa;
13674 int *pack_fds = NULL;
13676 TAILQ_INIT(&paths);
13678 #ifndef PROFILE
13679 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13680 "unveil", NULL) == -1)
13681 err(1, "pledge");
13682 #endif
13684 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13685 switch (ch) {
13686 case 'F':
13687 patch_script_path = optarg;
13688 break;
13689 case 'l':
13690 list_stage = 1;
13691 break;
13692 case 'p':
13693 pflag = 1;
13694 break;
13695 case 'S':
13696 allow_bad_symlinks = 1;
13697 break;
13698 default:
13699 usage_stage();
13700 /* NOTREACHED */
13704 argc -= optind;
13705 argv += optind;
13707 if (list_stage && (pflag || patch_script_path))
13708 errx(1, "-l option cannot be used with other options");
13709 if (patch_script_path && !pflag)
13710 errx(1, "-F option can only be used together with -p option");
13712 cwd = getcwd(NULL, 0);
13713 if (cwd == NULL) {
13714 error = got_error_from_errno("getcwd");
13715 goto done;
13718 error = got_repo_pack_fds_open(&pack_fds);
13719 if (error != NULL)
13720 goto done;
13722 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13723 if (error) {
13724 if (error->code == GOT_ERR_NOT_WORKTREE)
13725 error = wrap_not_worktree_error(error, "stage", cwd);
13726 goto done;
13729 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13730 NULL, pack_fds);
13731 if (error != NULL)
13732 goto done;
13734 if (patch_script_path) {
13735 patch_script_file = fopen(patch_script_path, "re");
13736 if (patch_script_file == NULL) {
13737 error = got_error_from_errno2("fopen",
13738 patch_script_path);
13739 goto done;
13742 error = apply_unveil(got_repo_get_path(repo), 0,
13743 got_worktree_get_root_path(worktree));
13744 if (error)
13745 goto done;
13747 error = check_merge_in_progress(worktree, repo);
13748 if (error)
13749 goto done;
13751 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13752 if (error)
13753 goto done;
13755 if (list_stage)
13756 error = got_worktree_status(worktree, &paths, repo, 0,
13757 print_stage, NULL, check_cancelled, NULL);
13758 else {
13759 cpa.patch_script_file = patch_script_file;
13760 cpa.action = "stage";
13761 error = got_worktree_stage(worktree, &paths,
13762 pflag ? NULL : print_status, NULL,
13763 pflag ? choose_patch : NULL, &cpa,
13764 allow_bad_symlinks, repo);
13766 done:
13767 if (patch_script_file && fclose(patch_script_file) == EOF &&
13768 error == NULL)
13769 error = got_error_from_errno2("fclose", patch_script_path);
13770 if (repo) {
13771 const struct got_error *close_err = got_repo_close(repo);
13772 if (error == NULL)
13773 error = close_err;
13775 if (worktree)
13776 got_worktree_close(worktree);
13777 if (pack_fds) {
13778 const struct got_error *pack_err =
13779 got_repo_pack_fds_close(pack_fds);
13780 if (error == NULL)
13781 error = pack_err;
13783 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13784 free(cwd);
13785 return error;
13788 __dead static void
13789 usage_unstage(void)
13791 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13792 "[path ...]\n", getprogname());
13793 exit(1);
13797 static const struct got_error *
13798 cmd_unstage(int argc, char *argv[])
13800 const struct got_error *error = NULL;
13801 struct got_repository *repo = NULL;
13802 struct got_worktree *worktree = NULL;
13803 char *cwd = NULL;
13804 struct got_pathlist_head paths;
13805 int ch, pflag = 0;
13806 struct got_update_progress_arg upa;
13807 FILE *patch_script_file = NULL;
13808 const char *patch_script_path = NULL;
13809 struct choose_patch_arg cpa;
13810 int *pack_fds = NULL;
13812 TAILQ_INIT(&paths);
13814 #ifndef PROFILE
13815 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13816 "unveil", NULL) == -1)
13817 err(1, "pledge");
13818 #endif
13820 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13821 switch (ch) {
13822 case 'F':
13823 patch_script_path = optarg;
13824 break;
13825 case 'p':
13826 pflag = 1;
13827 break;
13828 default:
13829 usage_unstage();
13830 /* NOTREACHED */
13834 argc -= optind;
13835 argv += optind;
13837 if (patch_script_path && !pflag)
13838 errx(1, "-F option can only be used together with -p option");
13840 cwd = getcwd(NULL, 0);
13841 if (cwd == NULL) {
13842 error = got_error_from_errno("getcwd");
13843 goto done;
13846 error = got_repo_pack_fds_open(&pack_fds);
13847 if (error != NULL)
13848 goto done;
13850 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13851 if (error) {
13852 if (error->code == GOT_ERR_NOT_WORKTREE)
13853 error = wrap_not_worktree_error(error, "unstage", cwd);
13854 goto done;
13857 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13858 NULL, pack_fds);
13859 if (error != NULL)
13860 goto done;
13862 if (patch_script_path) {
13863 patch_script_file = fopen(patch_script_path, "re");
13864 if (patch_script_file == NULL) {
13865 error = got_error_from_errno2("fopen",
13866 patch_script_path);
13867 goto done;
13871 error = apply_unveil(got_repo_get_path(repo), 0,
13872 got_worktree_get_root_path(worktree));
13873 if (error)
13874 goto done;
13876 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13877 if (error)
13878 goto done;
13880 cpa.patch_script_file = patch_script_file;
13881 cpa.action = "unstage";
13882 memset(&upa, 0, sizeof(upa));
13883 error = got_worktree_unstage(worktree, &paths, update_progress,
13884 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13885 if (!error)
13886 print_merge_progress_stats(&upa);
13887 done:
13888 if (patch_script_file && fclose(patch_script_file) == EOF &&
13889 error == NULL)
13890 error = got_error_from_errno2("fclose", patch_script_path);
13891 if (repo) {
13892 const struct got_error *close_err = got_repo_close(repo);
13893 if (error == NULL)
13894 error = close_err;
13896 if (worktree)
13897 got_worktree_close(worktree);
13898 if (pack_fds) {
13899 const struct got_error *pack_err =
13900 got_repo_pack_fds_close(pack_fds);
13901 if (error == NULL)
13902 error = pack_err;
13904 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13905 free(cwd);
13906 return error;
13909 __dead static void
13910 usage_cat(void)
13912 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13913 "arg ...\n", getprogname());
13914 exit(1);
13917 static const struct got_error *
13918 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13920 const struct got_error *err;
13921 struct got_blob_object *blob;
13922 int fd = -1;
13924 fd = got_opentempfd();
13925 if (fd == -1)
13926 return got_error_from_errno("got_opentempfd");
13928 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13929 if (err)
13930 goto done;
13932 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13933 done:
13934 if (fd != -1 && close(fd) == -1 && err == NULL)
13935 err = got_error_from_errno("close");
13936 if (blob)
13937 got_object_blob_close(blob);
13938 return err;
13941 static const struct got_error *
13942 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13944 const struct got_error *err;
13945 struct got_tree_object *tree;
13946 int nentries, i;
13948 err = got_object_open_as_tree(&tree, repo, id);
13949 if (err)
13950 return err;
13952 nentries = got_object_tree_get_nentries(tree);
13953 for (i = 0; i < nentries; i++) {
13954 struct got_tree_entry *te;
13955 char *id_str;
13956 if (sigint_received || sigpipe_received)
13957 break;
13958 te = got_object_tree_get_entry(tree, i);
13959 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13960 if (err)
13961 break;
13962 fprintf(outfile, "%s %.7o %s\n", id_str,
13963 got_tree_entry_get_mode(te),
13964 got_tree_entry_get_name(te));
13965 free(id_str);
13968 got_object_tree_close(tree);
13969 return err;
13972 static const struct got_error *
13973 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13975 const struct got_error *err;
13976 struct got_commit_object *commit;
13977 const struct got_object_id_queue *parent_ids;
13978 struct got_object_qid *pid;
13979 char *id_str = NULL;
13980 const char *logmsg = NULL;
13981 char gmtoff[6];
13983 err = got_object_open_as_commit(&commit, repo, id);
13984 if (err)
13985 return err;
13987 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13988 if (err)
13989 goto done;
13991 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13992 parent_ids = got_object_commit_get_parent_ids(commit);
13993 fprintf(outfile, "numparents %d\n",
13994 got_object_commit_get_nparents(commit));
13995 STAILQ_FOREACH(pid, parent_ids, entry) {
13996 char *pid_str;
13997 err = got_object_id_str(&pid_str, &pid->id);
13998 if (err)
13999 goto done;
14000 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14001 free(pid_str);
14003 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14004 got_object_commit_get_author_gmtoff(commit));
14005 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14006 got_object_commit_get_author(commit),
14007 (long long)got_object_commit_get_author_time(commit),
14008 gmtoff);
14010 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14011 got_object_commit_get_committer_gmtoff(commit));
14012 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14013 got_object_commit_get_committer(commit),
14014 (long long)got_object_commit_get_committer_time(commit),
14015 gmtoff);
14017 logmsg = got_object_commit_get_logmsg_raw(commit);
14018 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14019 fprintf(outfile, "%s", logmsg);
14020 done:
14021 free(id_str);
14022 got_object_commit_close(commit);
14023 return err;
14026 static const struct got_error *
14027 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14029 const struct got_error *err;
14030 struct got_tag_object *tag;
14031 char *id_str = NULL;
14032 const char *tagmsg = NULL;
14033 char gmtoff[6];
14035 err = got_object_open_as_tag(&tag, repo, id);
14036 if (err)
14037 return err;
14039 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14040 if (err)
14041 goto done;
14043 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14045 switch (got_object_tag_get_object_type(tag)) {
14046 case GOT_OBJ_TYPE_BLOB:
14047 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14048 GOT_OBJ_LABEL_BLOB);
14049 break;
14050 case GOT_OBJ_TYPE_TREE:
14051 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14052 GOT_OBJ_LABEL_TREE);
14053 break;
14054 case GOT_OBJ_TYPE_COMMIT:
14055 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14056 GOT_OBJ_LABEL_COMMIT);
14057 break;
14058 case GOT_OBJ_TYPE_TAG:
14059 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14060 GOT_OBJ_LABEL_TAG);
14061 break;
14062 default:
14063 break;
14066 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14067 got_object_tag_get_name(tag));
14069 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14070 got_object_tag_get_tagger_gmtoff(tag));
14071 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14072 got_object_tag_get_tagger(tag),
14073 (long long)got_object_tag_get_tagger_time(tag),
14074 gmtoff);
14076 tagmsg = got_object_tag_get_message(tag);
14077 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14078 fprintf(outfile, "%s", tagmsg);
14079 done:
14080 free(id_str);
14081 got_object_tag_close(tag);
14082 return err;
14085 static const struct got_error *
14086 cmd_cat(int argc, char *argv[])
14088 const struct got_error *error;
14089 struct got_repository *repo = NULL;
14090 struct got_worktree *worktree = NULL;
14091 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14092 char *keyword_idstr = NULL;
14093 const char *commit_id_str = NULL;
14094 struct got_object_id *id = NULL, *commit_id = NULL;
14095 struct got_commit_object *commit = NULL;
14096 int ch, obj_type, i, force_path = 0;
14097 struct got_reflist_head refs;
14098 int *pack_fds = NULL;
14100 TAILQ_INIT(&refs);
14102 #ifndef PROFILE
14103 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14104 NULL) == -1)
14105 err(1, "pledge");
14106 #endif
14108 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14109 switch (ch) {
14110 case 'c':
14111 commit_id_str = optarg;
14112 break;
14113 case 'P':
14114 force_path = 1;
14115 break;
14116 case 'r':
14117 repo_path = realpath(optarg, NULL);
14118 if (repo_path == NULL)
14119 return got_error_from_errno2("realpath",
14120 optarg);
14121 got_path_strip_trailing_slashes(repo_path);
14122 break;
14123 default:
14124 usage_cat();
14125 /* NOTREACHED */
14129 argc -= optind;
14130 argv += optind;
14132 cwd = getcwd(NULL, 0);
14133 if (cwd == NULL) {
14134 error = got_error_from_errno("getcwd");
14135 goto done;
14138 error = got_repo_pack_fds_open(&pack_fds);
14139 if (error != NULL)
14140 goto done;
14142 if (repo_path == NULL) {
14143 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14144 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14145 goto done;
14146 if (worktree) {
14147 repo_path = strdup(
14148 got_worktree_get_repo_path(worktree));
14149 if (repo_path == NULL) {
14150 error = got_error_from_errno("strdup");
14151 goto done;
14154 if (commit_id_str == NULL) {
14155 /* Release work tree lock. */
14156 got_worktree_close(worktree);
14157 worktree = NULL;
14162 if (repo_path == NULL) {
14163 repo_path = strdup(cwd);
14164 if (repo_path == NULL)
14165 return got_error_from_errno("strdup");
14168 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14169 free(repo_path);
14170 if (error != NULL)
14171 goto done;
14173 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14174 if (error)
14175 goto done;
14177 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14178 if (error)
14179 goto done;
14181 if (commit_id_str != NULL) {
14182 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14183 repo, worktree);
14184 if (error != NULL)
14185 goto done;
14186 if (keyword_idstr != NULL)
14187 commit_id_str = keyword_idstr;
14188 if (worktree != NULL) {
14189 got_worktree_close(worktree);
14190 worktree = NULL;
14192 } else
14193 commit_id_str = GOT_REF_HEAD;
14194 error = got_repo_match_object_id(&commit_id, NULL,
14195 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14196 if (error)
14197 goto done;
14199 error = got_object_open_as_commit(&commit, repo, commit_id);
14200 if (error)
14201 goto done;
14203 for (i = 0; i < argc; i++) {
14204 if (force_path) {
14205 error = got_object_id_by_path(&id, repo, commit,
14206 argv[i]);
14207 if (error)
14208 break;
14209 } else {
14210 error = got_repo_match_object_id(&id, &label, argv[i],
14211 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14212 repo);
14213 if (error) {
14214 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14215 error->code != GOT_ERR_NOT_REF)
14216 break;
14217 error = got_object_id_by_path(&id, repo,
14218 commit, argv[i]);
14219 if (error)
14220 break;
14224 error = got_object_get_type(&obj_type, repo, id);
14225 if (error)
14226 break;
14228 switch (obj_type) {
14229 case GOT_OBJ_TYPE_BLOB:
14230 error = cat_blob(id, repo, stdout);
14231 break;
14232 case GOT_OBJ_TYPE_TREE:
14233 error = cat_tree(id, repo, stdout);
14234 break;
14235 case GOT_OBJ_TYPE_COMMIT:
14236 error = cat_commit(id, repo, stdout);
14237 break;
14238 case GOT_OBJ_TYPE_TAG:
14239 error = cat_tag(id, repo, stdout);
14240 break;
14241 default:
14242 error = got_error(GOT_ERR_OBJ_TYPE);
14243 break;
14245 if (error)
14246 break;
14247 free(label);
14248 label = NULL;
14249 free(id);
14250 id = NULL;
14252 done:
14253 free(label);
14254 free(id);
14255 free(commit_id);
14256 free(keyword_idstr);
14257 if (commit)
14258 got_object_commit_close(commit);
14259 if (worktree)
14260 got_worktree_close(worktree);
14261 if (repo) {
14262 const struct got_error *close_err = got_repo_close(repo);
14263 if (error == NULL)
14264 error = close_err;
14266 if (pack_fds) {
14267 const struct got_error *pack_err =
14268 got_repo_pack_fds_close(pack_fds);
14269 if (error == NULL)
14270 error = pack_err;
14273 got_ref_list_free(&refs);
14274 return error;
14277 __dead static void
14278 usage_info(void)
14280 fprintf(stderr, "usage: %s info [path ...]\n",
14281 getprogname());
14282 exit(1);
14285 static const struct got_error *
14286 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14287 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14288 struct got_object_id *commit_id)
14290 const struct got_error *err = NULL;
14291 char *id_str = NULL;
14292 char datebuf[128];
14293 struct tm mytm, *tm;
14294 struct got_pathlist_head *paths = arg;
14295 struct got_pathlist_entry *pe;
14298 * Clear error indication from any of the path arguments which
14299 * would cause this file index entry to be displayed.
14301 TAILQ_FOREACH(pe, paths, entry) {
14302 if (got_path_cmp(path, pe->path, strlen(path),
14303 pe->path_len) == 0 ||
14304 got_path_is_child(path, pe->path, pe->path_len))
14305 pe->data = NULL; /* no error */
14308 printf(GOT_COMMIT_SEP_STR);
14309 if (S_ISLNK(mode))
14310 printf("symlink: %s\n", path);
14311 else if (S_ISREG(mode)) {
14312 printf("file: %s\n", path);
14313 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14314 } else if (S_ISDIR(mode))
14315 printf("directory: %s\n", path);
14316 else
14317 printf("something: %s\n", path);
14319 tm = localtime_r(&mtime, &mytm);
14320 if (tm == NULL)
14321 return NULL;
14322 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14323 return got_error(GOT_ERR_NO_SPACE);
14324 printf("timestamp: %s\n", datebuf);
14326 if (blob_id) {
14327 err = got_object_id_str(&id_str, blob_id);
14328 if (err)
14329 return err;
14330 printf("based on blob: %s\n", id_str);
14331 free(id_str);
14334 if (staged_blob_id) {
14335 err = got_object_id_str(&id_str, staged_blob_id);
14336 if (err)
14337 return err;
14338 printf("based on staged blob: %s\n", id_str);
14339 free(id_str);
14342 if (commit_id) {
14343 err = got_object_id_str(&id_str, commit_id);
14344 if (err)
14345 return err;
14346 printf("based on commit: %s\n", id_str);
14347 free(id_str);
14350 return NULL;
14353 static const struct got_error *
14354 cmd_info(int argc, char *argv[])
14356 const struct got_error *error = NULL;
14357 struct got_worktree *worktree = NULL;
14358 char *cwd = NULL, *id_str = NULL;
14359 struct got_pathlist_head paths;
14360 char *uuidstr = NULL;
14361 int ch, show_files = 0;
14363 TAILQ_INIT(&paths);
14365 #ifndef PROFILE
14366 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14367 NULL) == -1)
14368 err(1, "pledge");
14369 #endif
14371 while ((ch = getopt(argc, argv, "")) != -1) {
14372 switch (ch) {
14373 default:
14374 usage_info();
14375 /* NOTREACHED */
14379 argc -= optind;
14380 argv += optind;
14382 cwd = getcwd(NULL, 0);
14383 if (cwd == NULL) {
14384 error = got_error_from_errno("getcwd");
14385 goto done;
14388 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14389 if (error) {
14390 if (error->code == GOT_ERR_NOT_WORKTREE)
14391 error = wrap_not_worktree_error(error, "info", cwd);
14392 goto done;
14395 #ifndef PROFILE
14396 /* Remove "wpath cpath proc exec sendfd" promises. */
14397 if (pledge("stdio rpath flock unveil", NULL) == -1)
14398 err(1, "pledge");
14399 #endif
14400 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14401 if (error)
14402 goto done;
14404 if (argc >= 1) {
14405 error = get_worktree_paths_from_argv(&paths, argc, argv,
14406 worktree);
14407 if (error)
14408 goto done;
14409 show_files = 1;
14412 error = got_object_id_str(&id_str,
14413 got_worktree_get_base_commit_id(worktree));
14414 if (error)
14415 goto done;
14417 error = got_worktree_get_uuid(&uuidstr, worktree);
14418 if (error)
14419 goto done;
14421 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14422 printf("work tree base commit: %s\n", id_str);
14423 printf("work tree path prefix: %s\n",
14424 got_worktree_get_path_prefix(worktree));
14425 printf("work tree branch reference: %s\n",
14426 got_worktree_get_head_ref_name(worktree));
14427 printf("work tree UUID: %s\n", uuidstr);
14428 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14430 if (show_files) {
14431 struct got_pathlist_entry *pe;
14432 TAILQ_FOREACH(pe, &paths, entry) {
14433 if (pe->path_len == 0)
14434 continue;
14436 * Assume this path will fail. This will be corrected
14437 * in print_path_info() in case the path does suceeed.
14439 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14441 error = got_worktree_path_info(worktree, &paths,
14442 print_path_info, &paths, check_cancelled, NULL);
14443 if (error)
14444 goto done;
14445 TAILQ_FOREACH(pe, &paths, entry) {
14446 if (pe->data != NULL) {
14447 const struct got_error *perr;
14449 perr = pe->data;
14450 error = got_error_fmt(perr->code, "%s",
14451 pe->path);
14452 break;
14456 done:
14457 if (worktree)
14458 got_worktree_close(worktree);
14459 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14460 free(cwd);
14461 free(id_str);
14462 free(uuidstr);
14463 return error;