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 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3081 got_path_is_child(repo_path, worktree_path,
3082 strlen(worktree_path))) {
3083 error = got_error_fmt(GOT_ERR_BAD_PATH,
3084 "work tree and repository paths may not overlap: %s",
3085 worktree_path);
3086 goto done;
3089 error = got_repo_pack_fds_open(&pack_fds);
3090 if (error != NULL)
3091 goto done;
3093 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3094 if (error != NULL)
3095 goto done;
3097 /* Pre-create work tree path for unveil(2) */
3098 error = got_path_mkdir(worktree_path);
3099 if (error) {
3100 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3101 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3102 goto done;
3103 if (!allow_nonempty &&
3104 !got_path_dir_is_empty(worktree_path)) {
3105 error = got_error_path(worktree_path,
3106 GOT_ERR_DIR_NOT_EMPTY);
3107 goto done;
3111 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3112 if (error)
3113 goto done;
3115 error = got_ref_open(&head_ref, repo, branch_name, 0);
3116 if (error != NULL)
3117 goto done;
3119 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3120 GOT_WORKTREE_GOT_DIR, repo);
3121 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3122 goto done;
3124 error = got_worktree_open(&worktree, worktree_path,
3125 GOT_WORKTREE_GOT_DIR);
3126 if (error != NULL)
3127 goto done;
3129 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3130 path_prefix);
3131 if (error != NULL)
3132 goto done;
3133 if (!same_path_prefix) {
3134 error = got_error(GOT_ERR_PATH_PREFIX);
3135 goto done;
3138 if (commit_id_str) {
3139 struct got_reflist_head refs;
3140 TAILQ_INIT(&refs);
3141 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3142 NULL);
3143 if (error)
3144 goto done;
3146 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3147 repo, worktree);
3148 if (error != NULL)
3149 goto done;
3150 if (keyword_idstr != NULL) {
3151 free(commit_id_str);
3152 commit_id_str = keyword_idstr;
3155 error = got_repo_match_object_id(&commit_id, NULL,
3156 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3157 got_ref_list_free(&refs);
3158 if (error)
3159 goto done;
3160 error = check_linear_ancestry(commit_id,
3161 got_worktree_get_base_commit_id(worktree), 0, repo);
3162 if (error != NULL) {
3163 if (error->code == GOT_ERR_ANCESTRY) {
3164 error = checkout_ancestry_error(
3165 head_ref, commit_id_str);
3167 goto done;
3169 error = check_same_branch(commit_id, head_ref, repo);
3170 if (error) {
3171 if (error->code == GOT_ERR_ANCESTRY) {
3172 error = checkout_ancestry_error(
3173 head_ref, commit_id_str);
3175 goto done;
3177 error = got_worktree_set_base_commit_id(worktree, repo,
3178 commit_id);
3179 if (error)
3180 goto done;
3181 /* Expand potentially abbreviated commit ID string. */
3182 free(commit_id_str);
3183 error = got_object_id_str(&commit_id_str, commit_id);
3184 if (error)
3185 goto done;
3186 } else {
3187 commit_id = got_object_id_dup(
3188 got_worktree_get_base_commit_id(worktree));
3189 if (commit_id == NULL) {
3190 error = got_error_from_errno("got_object_id_dup");
3191 goto done;
3193 error = got_object_id_str(&commit_id_str, commit_id);
3194 if (error)
3195 goto done;
3198 error = got_pathlist_append(&paths, "", NULL);
3199 if (error)
3200 goto done;
3201 cpa.worktree_path = worktree_path;
3202 cpa.had_base_commit_ref_error = 0;
3203 cpa.verbosity = verbosity;
3204 error = got_worktree_checkout_files(worktree, &paths, repo,
3205 checkout_progress, &cpa, check_cancelled, NULL);
3206 if (error != NULL)
3207 goto done;
3209 if (got_ref_is_symbolic(head_ref)) {
3210 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3211 if (error)
3212 goto done;
3213 refname = got_ref_get_name(ref);
3214 } else
3215 refname = got_ref_get_name(head_ref);
3216 printf("Checked out %s: %s\n", refname, commit_id_str);
3217 printf("Now shut up and hack\n");
3218 if (cpa.had_base_commit_ref_error)
3219 show_worktree_base_ref_warning();
3220 done:
3221 if (pack_fds) {
3222 const struct got_error *pack_err =
3223 got_repo_pack_fds_close(pack_fds);
3224 if (error == NULL)
3225 error = pack_err;
3227 if (head_ref)
3228 got_ref_close(head_ref);
3229 if (ref)
3230 got_ref_close(ref);
3231 if (repo) {
3232 const struct got_error *close_err = got_repo_close(repo);
3233 if (error == NULL)
3234 error = close_err;
3236 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3237 free(commit_id_str);
3238 free(commit_id);
3239 free(repo_path);
3240 free(worktree_path);
3241 free(cwd);
3242 return error;
3245 struct got_update_progress_arg {
3246 int did_something;
3247 int conflicts;
3248 int obstructed;
3249 int not_updated;
3250 int missing;
3251 int not_deleted;
3252 int unversioned;
3253 int verbosity;
3256 static void
3257 print_update_progress_stats(struct got_update_progress_arg *upa)
3259 if (!upa->did_something)
3260 return;
3262 if (upa->conflicts > 0)
3263 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3264 if (upa->obstructed > 0)
3265 printf("File paths obstructed by a non-regular file: %d\n",
3266 upa->obstructed);
3267 if (upa->not_updated > 0)
3268 printf("Files not updated because of existing merge "
3269 "conflicts: %d\n", upa->not_updated);
3273 * The meaning of some status codes differs between merge-style operations and
3274 * update operations. For example, the ! status code means "file was missing"
3275 * if changes were merged into the work tree, and "missing file was restored"
3276 * if the work tree was updated. This function should be used by any operation
3277 * which merges changes into the work tree without updating the work tree.
3279 static void
3280 print_merge_progress_stats(struct got_update_progress_arg *upa)
3282 if (!upa->did_something)
3283 return;
3285 if (upa->conflicts > 0)
3286 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3287 if (upa->obstructed > 0)
3288 printf("File paths obstructed by a non-regular file: %d\n",
3289 upa->obstructed);
3290 if (upa->missing > 0)
3291 printf("Files which had incoming changes but could not be "
3292 "found in the work tree: %d\n", upa->missing);
3293 if (upa->not_deleted > 0)
3294 printf("Files not deleted due to differences in deleted "
3295 "content: %d\n", upa->not_deleted);
3296 if (upa->unversioned > 0)
3297 printf("Files not merged because an unversioned file was "
3298 "found in the work tree: %d\n", upa->unversioned);
3301 __dead static void
3302 usage_update(void)
3304 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3305 "[path ...]\n", getprogname());
3306 exit(1);
3309 static const struct got_error *
3310 update_progress(void *arg, unsigned char status, const char *path)
3312 struct got_update_progress_arg *upa = arg;
3314 if (status == GOT_STATUS_EXISTS ||
3315 status == GOT_STATUS_BASE_REF_ERR)
3316 return NULL;
3318 upa->did_something = 1;
3320 /* Base commit bump happens silently. */
3321 if (status == GOT_STATUS_BUMP_BASE)
3322 return NULL;
3324 if (status == GOT_STATUS_CONFLICT)
3325 upa->conflicts++;
3326 if (status == GOT_STATUS_OBSTRUCTED)
3327 upa->obstructed++;
3328 if (status == GOT_STATUS_CANNOT_UPDATE)
3329 upa->not_updated++;
3330 if (status == GOT_STATUS_MISSING)
3331 upa->missing++;
3332 if (status == GOT_STATUS_CANNOT_DELETE)
3333 upa->not_deleted++;
3334 if (status == GOT_STATUS_UNVERSIONED)
3335 upa->unversioned++;
3337 while (path[0] == '/')
3338 path++;
3339 if (upa->verbosity >= 0)
3340 printf("%c %s\n", status, path);
3342 return NULL;
3345 static const struct got_error *
3346 switch_head_ref(struct got_reference *head_ref,
3347 struct got_object_id *commit_id, struct got_worktree *worktree,
3348 struct got_repository *repo)
3350 const struct got_error *err = NULL;
3351 char *base_id_str;
3352 int ref_has_moved = 0;
3354 /* Trivial case: switching between two different references. */
3355 if (strcmp(got_ref_get_name(head_ref),
3356 got_worktree_get_head_ref_name(worktree)) != 0) {
3357 printf("Switching work tree from %s to %s\n",
3358 got_worktree_get_head_ref_name(worktree),
3359 got_ref_get_name(head_ref));
3360 return got_worktree_set_head_ref(worktree, head_ref);
3363 err = check_linear_ancestry(commit_id,
3364 got_worktree_get_base_commit_id(worktree), 0, repo);
3365 if (err) {
3366 if (err->code != GOT_ERR_ANCESTRY)
3367 return err;
3368 ref_has_moved = 1;
3370 if (!ref_has_moved)
3371 return NULL;
3373 /* Switching to a rebased branch with the same reference name. */
3374 err = got_object_id_str(&base_id_str,
3375 got_worktree_get_base_commit_id(worktree));
3376 if (err)
3377 return err;
3378 printf("Reference %s now points at a different branch\n",
3379 got_worktree_get_head_ref_name(worktree));
3380 printf("Switching work tree from %s to %s\n", base_id_str,
3381 got_worktree_get_head_ref_name(worktree));
3382 return NULL;
3385 static const struct got_error *
3386 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3388 const struct got_error *err;
3389 int in_progress;
3391 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3392 if (err)
3393 return err;
3394 if (in_progress)
3395 return got_error(GOT_ERR_REBASING);
3397 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3398 if (err)
3399 return err;
3400 if (in_progress)
3401 return got_error(GOT_ERR_HISTEDIT_BUSY);
3403 return NULL;
3406 static const struct got_error *
3407 check_merge_in_progress(struct got_worktree *worktree,
3408 struct got_repository *repo)
3410 const struct got_error *err;
3411 int in_progress;
3413 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3414 if (err)
3415 return err;
3416 if (in_progress)
3417 return got_error(GOT_ERR_MERGE_BUSY);
3419 return NULL;
3422 static const struct got_error *
3423 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3424 char *argv[], struct got_worktree *worktree)
3426 const struct got_error *err = NULL;
3427 char *path;
3428 struct got_pathlist_entry *new;
3429 int i;
3431 if (argc == 0) {
3432 path = strdup("");
3433 if (path == NULL)
3434 return got_error_from_errno("strdup");
3435 return got_pathlist_append(paths, path, NULL);
3438 for (i = 0; i < argc; i++) {
3439 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3440 if (err)
3441 break;
3442 err = got_pathlist_insert(&new, paths, path, NULL);
3443 if (err || new == NULL /* duplicate */) {
3444 free(path);
3445 if (err)
3446 break;
3450 return err;
3453 static const struct got_error *
3454 wrap_not_worktree_error(const struct got_error *orig_err,
3455 const char *cmdname, const char *path)
3457 const struct got_error *err;
3458 struct got_repository *repo;
3459 static char msg[512];
3460 int *pack_fds = NULL;
3462 err = got_repo_pack_fds_open(&pack_fds);
3463 if (err)
3464 return err;
3466 err = got_repo_open(&repo, path, NULL, pack_fds);
3467 if (err)
3468 return orig_err;
3470 snprintf(msg, sizeof(msg),
3471 "'got %s' needs a work tree in addition to a git repository\n"
3472 "Work trees can be checked out from this Git repository with "
3473 "'got checkout'.\n"
3474 "The got(1) manual page contains more information.", cmdname);
3475 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3476 if (repo) {
3477 const struct got_error *close_err = got_repo_close(repo);
3478 if (err == NULL)
3479 err = close_err;
3481 if (pack_fds) {
3482 const struct got_error *pack_err =
3483 got_repo_pack_fds_close(pack_fds);
3484 if (err == NULL)
3485 err = pack_err;
3487 return err;
3490 static const struct got_error *
3491 cmd_update(int argc, char *argv[])
3493 const struct got_error *error = NULL;
3494 struct got_repository *repo = NULL;
3495 struct got_worktree *worktree = NULL;
3496 char *worktree_path = NULL;
3497 struct got_object_id *commit_id = NULL;
3498 char *commit_id_str = NULL;
3499 const char *branch_name = NULL;
3500 struct got_reference *head_ref = NULL;
3501 struct got_pathlist_head paths;
3502 struct got_pathlist_entry *pe;
3503 int ch, verbosity = 0;
3504 struct got_update_progress_arg upa;
3505 int *pack_fds = NULL;
3507 TAILQ_INIT(&paths);
3509 #ifndef PROFILE
3510 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3511 "unveil", NULL) == -1)
3512 err(1, "pledge");
3513 #endif
3515 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3516 switch (ch) {
3517 case 'b':
3518 branch_name = optarg;
3519 break;
3520 case 'c':
3521 commit_id_str = strdup(optarg);
3522 if (commit_id_str == NULL)
3523 return got_error_from_errno("strdup");
3524 break;
3525 case 'q':
3526 verbosity = -1;
3527 break;
3528 default:
3529 usage_update();
3530 /* NOTREACHED */
3534 argc -= optind;
3535 argv += optind;
3537 worktree_path = getcwd(NULL, 0);
3538 if (worktree_path == NULL) {
3539 error = got_error_from_errno("getcwd");
3540 goto done;
3543 error = got_repo_pack_fds_open(&pack_fds);
3544 if (error != NULL)
3545 goto done;
3547 error = got_worktree_open(&worktree, worktree_path,
3548 GOT_WORKTREE_GOT_DIR);
3549 if (error) {
3550 if (error->code == GOT_ERR_NOT_WORKTREE)
3551 error = wrap_not_worktree_error(error, "update",
3552 worktree_path);
3553 goto done;
3556 error = check_rebase_or_histedit_in_progress(worktree);
3557 if (error)
3558 goto done;
3560 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3561 NULL, pack_fds);
3562 if (error != NULL)
3563 goto done;
3565 error = apply_unveil(got_repo_get_path(repo), 0,
3566 got_worktree_get_root_path(worktree));
3567 if (error)
3568 goto done;
3570 error = check_merge_in_progress(worktree, repo);
3571 if (error)
3572 goto done;
3574 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3575 if (error)
3576 goto done;
3578 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3579 got_worktree_get_head_ref_name(worktree), 0);
3580 if (error != NULL)
3581 goto done;
3582 if (commit_id_str == NULL) {
3583 error = got_ref_resolve(&commit_id, repo, head_ref);
3584 if (error != NULL)
3585 goto done;
3586 error = got_object_id_str(&commit_id_str, commit_id);
3587 if (error != NULL)
3588 goto done;
3589 } else {
3590 struct got_reflist_head refs;
3591 char *keyword_idstr = NULL;
3593 TAILQ_INIT(&refs);
3595 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3596 NULL);
3597 if (error)
3598 goto done;
3600 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3601 repo, worktree);
3602 if (error != NULL)
3603 goto done;
3604 if (keyword_idstr != NULL) {
3605 free(commit_id_str);
3606 commit_id_str = keyword_idstr;
3609 error = got_repo_match_object_id(&commit_id, NULL,
3610 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3611 got_ref_list_free(&refs);
3612 free(commit_id_str);
3613 commit_id_str = NULL;
3614 if (error)
3615 goto done;
3616 error = got_object_id_str(&commit_id_str, commit_id);
3617 if (error)
3618 goto done;
3621 if (branch_name) {
3622 struct got_object_id *head_commit_id;
3623 TAILQ_FOREACH(pe, &paths, entry) {
3624 if (pe->path_len == 0)
3625 continue;
3626 error = got_error_msg(GOT_ERR_BAD_PATH,
3627 "switching between branches requires that "
3628 "the entire work tree gets updated");
3629 goto done;
3631 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3632 if (error)
3633 goto done;
3634 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3635 repo);
3636 free(head_commit_id);
3637 if (error != NULL)
3638 goto done;
3639 error = check_same_branch(commit_id, head_ref, repo);
3640 if (error)
3641 goto done;
3642 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3643 if (error)
3644 goto done;
3645 } else {
3646 error = check_linear_ancestry(commit_id,
3647 got_worktree_get_base_commit_id(worktree), 0, repo);
3648 if (error != NULL) {
3649 if (error->code == GOT_ERR_ANCESTRY)
3650 error = got_error(GOT_ERR_BRANCH_MOVED);
3651 goto done;
3653 error = check_same_branch(commit_id, head_ref, repo);
3654 if (error)
3655 goto done;
3658 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3659 commit_id) != 0) {
3660 error = got_worktree_set_base_commit_id(worktree, repo,
3661 commit_id);
3662 if (error)
3663 goto done;
3666 memset(&upa, 0, sizeof(upa));
3667 upa.verbosity = verbosity;
3668 error = got_worktree_checkout_files(worktree, &paths, repo,
3669 update_progress, &upa, check_cancelled, NULL);
3670 if (error != NULL)
3671 goto done;
3673 if (upa.did_something) {
3674 printf("Updated to %s: %s\n",
3675 got_worktree_get_head_ref_name(worktree), commit_id_str);
3676 } else
3677 printf("Already up-to-date\n");
3679 print_update_progress_stats(&upa);
3680 done:
3681 if (pack_fds) {
3682 const struct got_error *pack_err =
3683 got_repo_pack_fds_close(pack_fds);
3684 if (error == NULL)
3685 error = pack_err;
3687 if (repo) {
3688 const struct got_error *close_err = got_repo_close(repo);
3689 if (error == NULL)
3690 error = close_err;
3692 if (head_ref != NULL)
3693 got_ref_close(head_ref);
3694 free(worktree_path);
3695 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3696 free(commit_id);
3697 free(commit_id_str);
3698 return error;
3701 static const struct got_error *
3702 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3703 const char *path, int diff_context, int ignore_whitespace,
3704 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3705 struct got_repository *repo, FILE *outfile)
3707 const struct got_error *err = NULL;
3708 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3709 FILE *f1 = NULL, *f2 = NULL;
3710 int fd1 = -1, fd2 = -1;
3712 fd1 = got_opentempfd();
3713 if (fd1 == -1)
3714 return got_error_from_errno("got_opentempfd");
3715 fd2 = got_opentempfd();
3716 if (fd2 == -1) {
3717 err = got_error_from_errno("got_opentempfd");
3718 goto done;
3721 if (blob_id1) {
3722 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3723 fd1);
3724 if (err)
3725 goto done;
3728 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3729 if (err)
3730 goto done;
3732 f1 = got_opentemp();
3733 if (f1 == NULL) {
3734 err = got_error_from_errno("got_opentemp");
3735 goto done;
3737 f2 = got_opentemp();
3738 if (f2 == NULL) {
3739 err = got_error_from_errno("got_opentemp");
3740 goto done;
3743 while (path[0] == '/')
3744 path++;
3745 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3746 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3747 force_text_diff, dsa, outfile);
3748 done:
3749 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3750 err = got_error_from_errno("close");
3751 if (blob1)
3752 got_object_blob_close(blob1);
3753 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3754 err = got_error_from_errno("close");
3755 if (blob2)
3756 got_object_blob_close(blob2);
3757 if (f1 && fclose(f1) == EOF && err == NULL)
3758 err = got_error_from_errno("fclose");
3759 if (f2 && fclose(f2) == EOF && err == NULL)
3760 err = got_error_from_errno("fclose");
3761 return err;
3764 static const struct got_error *
3765 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3766 const char *path, int diff_context, int ignore_whitespace,
3767 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3768 struct got_repository *repo, FILE *outfile)
3770 const struct got_error *err = NULL;
3771 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3772 struct got_diff_blob_output_unidiff_arg arg;
3773 FILE *f1 = NULL, *f2 = NULL;
3774 int fd1 = -1, fd2 = -1;
3776 if (tree_id1) {
3777 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3778 if (err)
3779 goto done;
3780 fd1 = got_opentempfd();
3781 if (fd1 == -1) {
3782 err = got_error_from_errno("got_opentempfd");
3783 goto done;
3787 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3788 if (err)
3789 goto done;
3791 f1 = got_opentemp();
3792 if (f1 == NULL) {
3793 err = got_error_from_errno("got_opentemp");
3794 goto done;
3797 f2 = got_opentemp();
3798 if (f2 == NULL) {
3799 err = got_error_from_errno("got_opentemp");
3800 goto done;
3802 fd2 = got_opentempfd();
3803 if (fd2 == -1) {
3804 err = got_error_from_errno("got_opentempfd");
3805 goto done;
3807 arg.diff_context = diff_context;
3808 arg.ignore_whitespace = ignore_whitespace;
3809 arg.force_text_diff = force_text_diff;
3810 arg.diffstat = dsa;
3811 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3812 arg.outfile = outfile;
3813 arg.lines = NULL;
3814 arg.nlines = 0;
3815 while (path[0] == '/')
3816 path++;
3817 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3818 got_diff_blob_output_unidiff, &arg, 1);
3819 done:
3820 if (tree1)
3821 got_object_tree_close(tree1);
3822 if (tree2)
3823 got_object_tree_close(tree2);
3824 if (f1 && fclose(f1) == EOF && err == NULL)
3825 err = got_error_from_errno("fclose");
3826 if (f2 && fclose(f2) == EOF && err == NULL)
3827 err = got_error_from_errno("fclose");
3828 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3829 err = got_error_from_errno("close");
3830 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3831 err = got_error_from_errno("close");
3832 return err;
3835 static const struct got_error *
3836 get_changed_paths(struct got_pathlist_head *paths,
3837 struct got_commit_object *commit, struct got_repository *repo,
3838 struct got_diffstat_cb_arg *dsa)
3840 const struct got_error *err = NULL;
3841 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3842 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3843 struct got_object_qid *qid;
3844 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3845 FILE *f1 = NULL, *f2 = NULL;
3846 int fd1 = -1, fd2 = -1;
3848 if (dsa) {
3849 cb = got_diff_tree_compute_diffstat;
3851 f1 = got_opentemp();
3852 if (f1 == NULL) {
3853 err = got_error_from_errno("got_opentemp");
3854 goto done;
3856 f2 = got_opentemp();
3857 if (f2 == NULL) {
3858 err = got_error_from_errno("got_opentemp");
3859 goto done;
3861 fd1 = got_opentempfd();
3862 if (fd1 == -1) {
3863 err = got_error_from_errno("got_opentempfd");
3864 goto done;
3866 fd2 = got_opentempfd();
3867 if (fd2 == -1) {
3868 err = got_error_from_errno("got_opentempfd");
3869 goto done;
3873 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3874 if (qid != NULL) {
3875 struct got_commit_object *pcommit;
3876 err = got_object_open_as_commit(&pcommit, repo,
3877 &qid->id);
3878 if (err)
3879 return err;
3881 tree_id1 = got_object_id_dup(
3882 got_object_commit_get_tree_id(pcommit));
3883 if (tree_id1 == NULL) {
3884 got_object_commit_close(pcommit);
3885 return got_error_from_errno("got_object_id_dup");
3887 got_object_commit_close(pcommit);
3891 if (tree_id1) {
3892 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3893 if (err)
3894 goto done;
3897 tree_id2 = got_object_commit_get_tree_id(commit);
3898 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3899 if (err)
3900 goto done;
3902 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3903 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3904 done:
3905 if (tree1)
3906 got_object_tree_close(tree1);
3907 if (tree2)
3908 got_object_tree_close(tree2);
3909 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3910 err = got_error_from_errno("close");
3911 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3912 err = got_error_from_errno("close");
3913 if (f1 && fclose(f1) == EOF && err == NULL)
3914 err = got_error_from_errno("fclose");
3915 if (f2 && fclose(f2) == EOF && err == NULL)
3916 err = got_error_from_errno("fclose");
3917 free(tree_id1);
3918 return err;
3921 static const struct got_error *
3922 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3923 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3924 struct got_repository *repo, FILE *outfile)
3926 const struct got_error *err = NULL;
3927 struct got_commit_object *pcommit = NULL;
3928 char *id_str1 = NULL, *id_str2 = NULL;
3929 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3930 struct got_object_qid *qid;
3932 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3933 if (qid != NULL) {
3934 err = got_object_open_as_commit(&pcommit, repo,
3935 &qid->id);
3936 if (err)
3937 return err;
3938 err = got_object_id_str(&id_str1, &qid->id);
3939 if (err)
3940 goto done;
3943 err = got_object_id_str(&id_str2, id);
3944 if (err)
3945 goto done;
3947 if (path && path[0] != '\0') {
3948 int obj_type;
3949 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3950 if (err)
3951 goto done;
3952 if (pcommit) {
3953 err = got_object_id_by_path(&obj_id1, repo,
3954 pcommit, path);
3955 if (err) {
3956 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3957 free(obj_id2);
3958 goto done;
3962 err = got_object_get_type(&obj_type, repo, obj_id2);
3963 if (err) {
3964 free(obj_id2);
3965 goto done;
3967 fprintf(outfile,
3968 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3969 fprintf(outfile, "commit - %s\n",
3970 id_str1 ? id_str1 : "/dev/null");
3971 fprintf(outfile, "commit + %s\n", id_str2);
3972 switch (obj_type) {
3973 case GOT_OBJ_TYPE_BLOB:
3974 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3975 0, 0, dsa, repo, outfile);
3976 break;
3977 case GOT_OBJ_TYPE_TREE:
3978 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3979 0, 0, dsa, repo, outfile);
3980 break;
3981 default:
3982 err = got_error(GOT_ERR_OBJ_TYPE);
3983 break;
3985 free(obj_id1);
3986 free(obj_id2);
3987 } else {
3988 obj_id2 = got_object_commit_get_tree_id(commit);
3989 if (pcommit)
3990 obj_id1 = got_object_commit_get_tree_id(pcommit);
3991 fprintf(outfile,
3992 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3993 fprintf(outfile, "commit - %s\n",
3994 id_str1 ? id_str1 : "/dev/null");
3995 fprintf(outfile, "commit + %s\n", id_str2);
3996 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3997 dsa, repo, outfile);
3999 done:
4000 free(id_str1);
4001 free(id_str2);
4002 if (pcommit)
4003 got_object_commit_close(pcommit);
4004 return err;
4007 static char *
4008 get_datestr(time_t *time, char *datebuf)
4010 struct tm mytm, *tm;
4011 char *p, *s;
4013 tm = gmtime_r(time, &mytm);
4014 if (tm == NULL)
4015 return NULL;
4016 s = asctime_r(tm, datebuf);
4017 if (s == NULL)
4018 return NULL;
4019 p = strchr(s, '\n');
4020 if (p)
4021 *p = '\0';
4022 return s;
4025 static const struct got_error *
4026 match_commit(int *have_match, struct got_object_id *id,
4027 struct got_commit_object *commit, regex_t *regex)
4029 const struct got_error *err = NULL;
4030 regmatch_t regmatch;
4031 char *id_str = NULL, *logmsg = NULL;
4033 *have_match = 0;
4035 err = got_object_id_str(&id_str, id);
4036 if (err)
4037 return err;
4039 err = got_object_commit_get_logmsg(&logmsg, commit);
4040 if (err)
4041 goto done;
4043 if (regexec(regex, got_object_commit_get_author(commit), 1,
4044 &regmatch, 0) == 0 ||
4045 regexec(regex, got_object_commit_get_committer(commit), 1,
4046 &regmatch, 0) == 0 ||
4047 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4048 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4049 *have_match = 1;
4050 done:
4051 free(id_str);
4052 free(logmsg);
4053 return err;
4056 static void
4057 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4058 regex_t *regex)
4060 regmatch_t regmatch;
4061 struct got_pathlist_entry *pe;
4063 *have_match = 0;
4065 TAILQ_FOREACH(pe, changed_paths, entry) {
4066 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4067 *have_match = 1;
4068 break;
4073 static const struct got_error *
4074 match_patch(int *have_match, struct got_commit_object *commit,
4075 struct got_object_id *id, const char *path, int diff_context,
4076 struct got_repository *repo, regex_t *regex, FILE *f)
4078 const struct got_error *err = NULL;
4079 char *line = NULL;
4080 size_t linesize = 0;
4081 regmatch_t regmatch;
4083 *have_match = 0;
4085 err = got_opentemp_truncate(f);
4086 if (err)
4087 return err;
4089 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4090 if (err)
4091 goto done;
4093 if (fseeko(f, 0L, SEEK_SET) == -1) {
4094 err = got_error_from_errno("fseeko");
4095 goto done;
4098 while (getline(&line, &linesize, f) != -1) {
4099 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4100 *have_match = 1;
4101 break;
4104 done:
4105 free(line);
4106 return err;
4109 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4111 static const struct got_error*
4112 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4113 struct got_object_id *id, struct got_repository *repo,
4114 int local_only)
4116 static const struct got_error *err = NULL;
4117 struct got_reflist_entry *re;
4118 char *s;
4119 const char *name;
4121 *refs_str = NULL;
4123 TAILQ_FOREACH(re, refs, entry) {
4124 struct got_tag_object *tag = NULL;
4125 struct got_object_id *ref_id;
4126 int cmp;
4128 name = got_ref_get_name(re->ref);
4129 if (strcmp(name, GOT_REF_HEAD) == 0)
4130 continue;
4131 if (strncmp(name, "refs/", 5) == 0)
4132 name += 5;
4133 if (strncmp(name, "got/", 4) == 0)
4134 continue;
4135 if (strncmp(name, "heads/", 6) == 0)
4136 name += 6;
4137 if (strncmp(name, "remotes/", 8) == 0) {
4138 if (local_only)
4139 continue;
4140 name += 8;
4141 s = strstr(name, "/" GOT_REF_HEAD);
4142 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4143 continue;
4145 err = got_ref_resolve(&ref_id, repo, re->ref);
4146 if (err)
4147 break;
4148 if (strncmp(name, "tags/", 5) == 0) {
4149 err = got_object_open_as_tag(&tag, repo, ref_id);
4150 if (err) {
4151 if (err->code != GOT_ERR_OBJ_TYPE) {
4152 free(ref_id);
4153 break;
4155 /* Ref points at something other than a tag. */
4156 err = NULL;
4157 tag = NULL;
4160 cmp = got_object_id_cmp(tag ?
4161 got_object_tag_get_object_id(tag) : ref_id, id);
4162 free(ref_id);
4163 if (tag)
4164 got_object_tag_close(tag);
4165 if (cmp != 0)
4166 continue;
4167 s = *refs_str;
4168 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4169 s ? ", " : "", name) == -1) {
4170 err = got_error_from_errno("asprintf");
4171 free(s);
4172 *refs_str = NULL;
4173 break;
4175 free(s);
4178 return err;
4181 static const struct got_error *
4182 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4183 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4185 const struct got_error *err = NULL;
4186 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4187 char *comma, *s, *nl;
4188 struct got_reflist_head *refs;
4189 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4190 struct tm tm;
4191 time_t committer_time;
4193 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4194 if (refs) {
4195 err = build_refs_str(&ref_str, refs, id, repo, 1);
4196 if (err)
4197 return err;
4199 /* Display the first matching ref only. */
4200 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4201 *comma = '\0';
4204 if (ref_str == NULL) {
4205 err = got_object_id_str(&id_str, id);
4206 if (err)
4207 return err;
4210 committer_time = got_object_commit_get_committer_time(commit);
4211 if (gmtime_r(&committer_time, &tm) == NULL) {
4212 err = got_error_from_errno("gmtime_r");
4213 goto done;
4215 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4216 err = got_error(GOT_ERR_NO_SPACE);
4217 goto done;
4220 err = got_object_commit_get_logmsg(&logmsg0, commit);
4221 if (err)
4222 goto done;
4224 s = logmsg0;
4225 while (isspace((unsigned char)s[0]))
4226 s++;
4228 nl = strchr(s, '\n');
4229 if (nl) {
4230 *nl = '\0';
4233 if (ref_str)
4234 printf("%s%-7s %s\n", datebuf, ref_str, s);
4235 else
4236 printf("%s%.7s %s\n", datebuf, id_str, s);
4238 if (fflush(stdout) != 0 && err == NULL)
4239 err = got_error_from_errno("fflush");
4240 done:
4241 free(id_str);
4242 free(ref_str);
4243 free(logmsg0);
4244 return err;
4247 static const struct got_error *
4248 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4250 struct got_pathlist_entry *pe;
4252 if (header != NULL)
4253 printf("%s\n", header);
4255 TAILQ_FOREACH(pe, dsa->paths, entry) {
4256 struct got_diff_changed_path *cp = pe->data;
4257 int pad = dsa->max_path_len - pe->path_len + 1;
4259 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4260 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4262 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4263 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4264 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4266 if (fflush(stdout) != 0)
4267 return got_error_from_errno("fflush");
4269 return NULL;
4272 static const struct got_error *
4273 printfile(FILE *f)
4275 char buf[8192];
4276 size_t r;
4278 if (fseeko(f, 0L, SEEK_SET) == -1)
4279 return got_error_from_errno("fseek");
4281 for (;;) {
4282 r = fread(buf, 1, sizeof(buf), f);
4283 if (r == 0) {
4284 if (ferror(f))
4285 return got_error_from_errno("fread");
4286 if (feof(f))
4287 break;
4289 if (fwrite(buf, 1, r, stdout) != r)
4290 return got_ferror(stdout, GOT_ERR_IO);
4293 return NULL;
4296 static const struct got_error *
4297 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4298 struct got_repository *repo, const char *path,
4299 struct got_pathlist_head *changed_paths,
4300 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4301 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4302 const char *prefix)
4304 const struct got_error *err = NULL;
4305 FILE *f = NULL;
4306 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4307 char datebuf[26];
4308 time_t committer_time;
4309 const char *author, *committer;
4310 char *refs_str = NULL;
4312 err = got_object_id_str(&id_str, id);
4313 if (err)
4314 return err;
4316 if (custom_refs_str == NULL) {
4317 struct got_reflist_head *refs;
4318 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4319 if (refs) {
4320 err = build_refs_str(&refs_str, refs, id, repo, 0);
4321 if (err)
4322 goto done;
4326 printf(GOT_COMMIT_SEP_STR);
4327 if (custom_refs_str)
4328 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4329 custom_refs_str);
4330 else
4331 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4332 refs_str ? " (" : "", refs_str ? refs_str : "",
4333 refs_str ? ")" : "");
4334 free(id_str);
4335 id_str = NULL;
4336 free(refs_str);
4337 refs_str = NULL;
4338 printf("from: %s\n", got_object_commit_get_author(commit));
4339 author = got_object_commit_get_author(commit);
4340 committer = got_object_commit_get_committer(commit);
4341 if (strcmp(author, committer) != 0)
4342 printf("via: %s\n", committer);
4343 committer_time = got_object_commit_get_committer_time(commit);
4344 datestr = get_datestr(&committer_time, datebuf);
4345 if (datestr)
4346 printf("date: %s UTC\n", datestr);
4347 if (got_object_commit_get_nparents(commit) > 1) {
4348 const struct got_object_id_queue *parent_ids;
4349 struct got_object_qid *qid;
4350 int n = 1;
4351 parent_ids = got_object_commit_get_parent_ids(commit);
4352 STAILQ_FOREACH(qid, parent_ids, entry) {
4353 err = got_object_id_str(&id_str, &qid->id);
4354 if (err)
4355 goto done;
4356 printf("parent %d: %s\n", n++, id_str);
4357 free(id_str);
4358 id_str = NULL;
4362 err = got_object_commit_get_logmsg(&logmsg0, commit);
4363 if (err)
4364 goto done;
4366 logmsg = logmsg0;
4367 do {
4368 line = strsep(&logmsg, "\n");
4369 if (line)
4370 printf(" %s\n", line);
4371 } while (line);
4372 free(logmsg0);
4374 if (changed_paths && diffstat == NULL) {
4375 struct got_pathlist_entry *pe;
4377 TAILQ_FOREACH(pe, changed_paths, entry) {
4378 struct got_diff_changed_path *cp = pe->data;
4380 printf(" %c %s\n", cp->status, pe->path);
4382 printf("\n");
4384 if (show_patch) {
4385 if (diffstat) {
4386 f = got_opentemp();
4387 if (f == NULL) {
4388 err = got_error_from_errno("got_opentemp");
4389 goto done;
4393 err = print_patch(commit, id, path, diff_context, diffstat,
4394 repo, diffstat == NULL ? stdout : f);
4395 if (err)
4396 goto done;
4398 if (diffstat) {
4399 err = print_diffstat(diffstat, NULL);
4400 if (err)
4401 goto done;
4402 if (show_patch) {
4403 err = printfile(f);
4404 if (err)
4405 goto done;
4408 if (show_patch)
4409 printf("\n");
4411 if (fflush(stdout) != 0 && err == NULL)
4412 err = got_error_from_errno("fflush");
4413 done:
4414 if (f && fclose(f) == EOF && err == NULL)
4415 err = got_error_from_errno("fclose");
4416 free(id_str);
4417 free(refs_str);
4418 return err;
4421 static const struct got_error *
4422 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4423 struct got_repository *repo, const char *path, int show_changed_paths,
4424 int show_diffstat, int show_patch, const char *search_pattern,
4425 int diff_context, int limit, int log_branches, int reverse_display_order,
4426 struct got_reflist_object_id_map *refs_idmap, int one_line,
4427 FILE *tmpfile)
4429 const struct got_error *err;
4430 struct got_commit_graph *graph;
4431 regex_t regex;
4432 int have_match;
4433 struct got_object_id_queue reversed_commits;
4434 struct got_object_qid *qid;
4435 struct got_commit_object *commit;
4436 struct got_pathlist_head changed_paths;
4438 STAILQ_INIT(&reversed_commits);
4439 TAILQ_INIT(&changed_paths);
4441 if (search_pattern && regcomp(&regex, search_pattern,
4442 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4443 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4445 err = got_commit_graph_open(&graph, path, !log_branches);
4446 if (err)
4447 return err;
4448 err = got_commit_graph_iter_start(graph, root_id, repo,
4449 check_cancelled, NULL);
4450 if (err)
4451 goto done;
4452 for (;;) {
4453 struct got_object_id id;
4454 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4455 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4457 if (sigint_received || sigpipe_received)
4458 break;
4460 err = got_commit_graph_iter_next(&id, graph, repo,
4461 check_cancelled, NULL);
4462 if (err) {
4463 if (err->code == GOT_ERR_ITER_COMPLETED)
4464 err = NULL;
4465 break;
4468 err = got_object_open_as_commit(&commit, repo, &id);
4469 if (err)
4470 break;
4472 if (((show_changed_paths && !show_diffstat) ||
4473 (show_diffstat && !show_patch))
4474 && !reverse_display_order) {
4475 err = get_changed_paths(&changed_paths, commit, repo,
4476 show_diffstat ? &dsa : NULL);
4477 if (err)
4478 break;
4481 if (search_pattern) {
4482 err = match_commit(&have_match, &id, commit, &regex);
4483 if (err) {
4484 got_object_commit_close(commit);
4485 break;
4487 if (have_match == 0 && show_changed_paths)
4488 match_changed_paths(&have_match,
4489 &changed_paths, &regex);
4490 if (have_match == 0 && show_patch) {
4491 err = match_patch(&have_match, commit, &id,
4492 path, diff_context, repo, &regex, tmpfile);
4493 if (err)
4494 break;
4496 if (have_match == 0) {
4497 got_object_commit_close(commit);
4498 got_pathlist_free(&changed_paths,
4499 GOT_PATHLIST_FREE_ALL);
4500 continue;
4504 if (reverse_display_order) {
4505 err = got_object_qid_alloc(&qid, &id);
4506 if (err)
4507 break;
4508 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4509 got_object_commit_close(commit);
4510 } else {
4511 if (one_line)
4512 err = print_commit_oneline(commit, &id,
4513 repo, refs_idmap);
4514 else
4515 err = print_commit(commit, &id, repo, path,
4516 (show_changed_paths || show_diffstat) ?
4517 &changed_paths : NULL,
4518 show_diffstat ? &dsa : NULL, show_patch,
4519 diff_context, refs_idmap, NULL, NULL);
4520 got_object_commit_close(commit);
4521 if (err)
4522 break;
4524 if ((limit && --limit == 0) ||
4525 (end_id && got_object_id_cmp(&id, end_id) == 0))
4526 break;
4528 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4530 if (reverse_display_order) {
4531 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4532 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4533 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4535 err = got_object_open_as_commit(&commit, repo,
4536 &qid->id);
4537 if (err)
4538 break;
4539 if ((show_changed_paths && !show_diffstat) ||
4540 (show_diffstat && !show_patch)) {
4541 err = get_changed_paths(&changed_paths, commit,
4542 repo, show_diffstat ? &dsa : NULL);
4543 if (err)
4544 break;
4546 if (one_line)
4547 err = print_commit_oneline(commit, &qid->id,
4548 repo, refs_idmap);
4549 else
4550 err = print_commit(commit, &qid->id, repo, path,
4551 (show_changed_paths || show_diffstat) ?
4552 &changed_paths : NULL,
4553 show_diffstat ? &dsa : NULL, show_patch,
4554 diff_context, refs_idmap, NULL, NULL);
4555 got_object_commit_close(commit);
4556 if (err)
4557 break;
4558 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4561 done:
4562 while (!STAILQ_EMPTY(&reversed_commits)) {
4563 qid = STAILQ_FIRST(&reversed_commits);
4564 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4565 got_object_qid_free(qid);
4567 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4568 if (search_pattern)
4569 regfree(&regex);
4570 got_commit_graph_close(graph);
4571 return err;
4574 __dead static void
4575 usage_log(void)
4577 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4578 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4579 "[path]\n", getprogname());
4580 exit(1);
4583 static int
4584 get_default_log_limit(void)
4586 const char *got_default_log_limit;
4587 long long n;
4588 const char *errstr;
4590 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4591 if (got_default_log_limit == NULL)
4592 return 0;
4593 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4594 if (errstr != NULL)
4595 return 0;
4596 return n;
4599 static const struct got_error *
4600 cmd_log(int argc, char *argv[])
4602 const struct got_error *error;
4603 struct got_repository *repo = NULL;
4604 struct got_worktree *worktree = NULL;
4605 struct got_object_id *start_id = NULL, *end_id = NULL;
4606 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4607 char *keyword_idstr = NULL;
4608 const char *start_commit = NULL, *end_commit = NULL;
4609 const char *search_pattern = NULL;
4610 int diff_context = -1, ch;
4611 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4612 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4613 const char *errstr;
4614 struct got_reflist_head refs;
4615 struct got_reflist_object_id_map *refs_idmap = NULL;
4616 FILE *tmpfile = NULL;
4617 int *pack_fds = NULL;
4619 TAILQ_INIT(&refs);
4621 #ifndef PROFILE
4622 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4623 NULL)
4624 == -1)
4625 err(1, "pledge");
4626 #endif
4628 limit = get_default_log_limit();
4630 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4631 switch (ch) {
4632 case 'b':
4633 log_branches = 1;
4634 break;
4635 case 'C':
4636 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4637 &errstr);
4638 if (errstr != NULL)
4639 errx(1, "number of context lines is %s: %s",
4640 errstr, optarg);
4641 break;
4642 case 'c':
4643 start_commit = optarg;
4644 break;
4645 case 'd':
4646 show_diffstat = 1;
4647 break;
4648 case 'l':
4649 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4650 if (errstr != NULL)
4651 errx(1, "number of commits is %s: %s",
4652 errstr, optarg);
4653 break;
4654 case 'P':
4655 show_changed_paths = 1;
4656 break;
4657 case 'p':
4658 show_patch = 1;
4659 break;
4660 case 'R':
4661 reverse_display_order = 1;
4662 break;
4663 case 'r':
4664 repo_path = realpath(optarg, NULL);
4665 if (repo_path == NULL)
4666 return got_error_from_errno2("realpath",
4667 optarg);
4668 got_path_strip_trailing_slashes(repo_path);
4669 break;
4670 case 'S':
4671 search_pattern = optarg;
4672 break;
4673 case 's':
4674 one_line = 1;
4675 break;
4676 case 'x':
4677 end_commit = optarg;
4678 break;
4679 default:
4680 usage_log();
4681 /* NOTREACHED */
4685 argc -= optind;
4686 argv += optind;
4688 if (diff_context == -1)
4689 diff_context = 3;
4690 else if (!show_patch)
4691 errx(1, "-C requires -p");
4693 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4694 errx(1, "cannot use -s with -d, -p or -P");
4696 cwd = getcwd(NULL, 0);
4697 if (cwd == NULL) {
4698 error = got_error_from_errno("getcwd");
4699 goto done;
4702 error = got_repo_pack_fds_open(&pack_fds);
4703 if (error != NULL)
4704 goto done;
4706 if (repo_path == NULL) {
4707 error = got_worktree_open(&worktree, cwd,
4708 GOT_WORKTREE_GOT_DIR);
4709 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4710 goto done;
4711 error = NULL;
4714 if (argc == 1) {
4715 if (worktree) {
4716 error = got_worktree_resolve_path(&path, worktree,
4717 argv[0]);
4718 if (error)
4719 goto done;
4720 } else {
4721 path = strdup(argv[0]);
4722 if (path == NULL) {
4723 error = got_error_from_errno("strdup");
4724 goto done;
4727 } else if (argc != 0)
4728 usage_log();
4730 if (repo_path == NULL) {
4731 repo_path = worktree ?
4732 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4734 if (repo_path == NULL) {
4735 error = got_error_from_errno("strdup");
4736 goto done;
4739 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4740 if (error != NULL)
4741 goto done;
4743 error = apply_unveil(got_repo_get_path(repo), 1,
4744 worktree ? got_worktree_get_root_path(worktree) : NULL);
4745 if (error)
4746 goto done;
4748 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4749 if (error)
4750 goto done;
4752 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4753 if (error)
4754 goto done;
4756 if (start_commit == NULL) {
4757 struct got_reference *head_ref;
4758 struct got_commit_object *commit = NULL;
4759 error = got_ref_open(&head_ref, repo,
4760 worktree ? got_worktree_get_head_ref_name(worktree)
4761 : GOT_REF_HEAD, 0);
4762 if (error != NULL)
4763 goto done;
4764 error = got_ref_resolve(&start_id, repo, head_ref);
4765 got_ref_close(head_ref);
4766 if (error != NULL)
4767 goto done;
4768 error = got_object_open_as_commit(&commit, repo,
4769 start_id);
4770 if (error != NULL)
4771 goto done;
4772 got_object_commit_close(commit);
4773 } else {
4774 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4775 repo, worktree);
4776 if (error != NULL)
4777 goto done;
4778 if (keyword_idstr != NULL)
4779 start_commit = keyword_idstr;
4781 error = got_repo_match_object_id(&start_id, NULL,
4782 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4783 if (error != NULL)
4784 goto done;
4786 if (end_commit != NULL) {
4787 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4788 repo, worktree);
4789 if (error != NULL)
4790 goto done;
4791 if (keyword_idstr != NULL)
4792 end_commit = keyword_idstr;
4794 error = got_repo_match_object_id(&end_id, NULL,
4795 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4796 if (error != NULL)
4797 goto done;
4800 if (worktree) {
4802 * If a path was specified on the command line it was resolved
4803 * to a path in the work tree above. Prepend the work tree's
4804 * path prefix to obtain the corresponding in-repository path.
4806 if (path) {
4807 const char *prefix;
4808 prefix = got_worktree_get_path_prefix(worktree);
4809 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4810 (path[0] != '\0') ? "/" : "", path) == -1) {
4811 error = got_error_from_errno("asprintf");
4812 goto done;
4815 } else
4816 error = got_repo_map_path(&in_repo_path, repo,
4817 path ? path : "");
4818 if (error != NULL)
4819 goto done;
4820 if (in_repo_path) {
4821 free(path);
4822 path = in_repo_path;
4825 if (worktree) {
4826 /* Release work tree lock. */
4827 got_worktree_close(worktree);
4828 worktree = NULL;
4831 if (search_pattern && show_patch) {
4832 tmpfile = got_opentemp();
4833 if (tmpfile == NULL) {
4834 error = got_error_from_errno("got_opentemp");
4835 goto done;
4839 error = print_commits(start_id, end_id, repo, path ? path : "",
4840 show_changed_paths, show_diffstat, show_patch, search_pattern,
4841 diff_context, limit, log_branches, reverse_display_order,
4842 refs_idmap, one_line, tmpfile);
4843 done:
4844 free(path);
4845 free(repo_path);
4846 free(cwd);
4847 free(start_id);
4848 free(end_id);
4849 free(keyword_idstr);
4850 if (worktree)
4851 got_worktree_close(worktree);
4852 if (repo) {
4853 const struct got_error *close_err = got_repo_close(repo);
4854 if (error == NULL)
4855 error = close_err;
4857 if (pack_fds) {
4858 const struct got_error *pack_err =
4859 got_repo_pack_fds_close(pack_fds);
4860 if (error == NULL)
4861 error = pack_err;
4863 if (refs_idmap)
4864 got_reflist_object_id_map_free(refs_idmap);
4865 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4866 error = got_error_from_errno("fclose");
4867 got_ref_list_free(&refs);
4868 return error;
4871 __dead static void
4872 usage_diff(void)
4874 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4875 "[-r repository-path] [object1 object2 | path ...]\n",
4876 getprogname());
4877 exit(1);
4880 struct print_diff_arg {
4881 struct got_repository *repo;
4882 struct got_worktree *worktree;
4883 struct got_diffstat_cb_arg *diffstat;
4884 int diff_context;
4885 const char *id_str;
4886 int header_shown;
4887 int diff_staged;
4888 enum got_diff_algorithm diff_algo;
4889 int ignore_whitespace;
4890 int force_text_diff;
4891 FILE *f1;
4892 FILE *f2;
4893 FILE *outfile;
4897 * Create a file which contains the target path of a symlink so we can feed
4898 * it as content to the diff engine.
4900 static const struct got_error *
4901 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4902 const char *abspath)
4904 const struct got_error *err = NULL;
4905 char target_path[PATH_MAX];
4906 ssize_t target_len, outlen;
4908 *fd = -1;
4910 if (dirfd != -1) {
4911 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4912 if (target_len == -1)
4913 return got_error_from_errno2("readlinkat", abspath);
4914 } else {
4915 target_len = readlink(abspath, target_path, PATH_MAX);
4916 if (target_len == -1)
4917 return got_error_from_errno2("readlink", abspath);
4920 *fd = got_opentempfd();
4921 if (*fd == -1)
4922 return got_error_from_errno("got_opentempfd");
4924 outlen = write(*fd, target_path, target_len);
4925 if (outlen == -1) {
4926 err = got_error_from_errno("got_opentempfd");
4927 goto done;
4930 if (lseek(*fd, 0, SEEK_SET) == -1) {
4931 err = got_error_from_errno2("lseek", abspath);
4932 goto done;
4934 done:
4935 if (err) {
4936 close(*fd);
4937 *fd = -1;
4939 return err;
4942 static const struct got_error *
4943 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4944 const char *path, struct got_object_id *blob_id,
4945 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4946 int dirfd, const char *de_name)
4948 struct print_diff_arg *a = arg;
4949 const struct got_error *err = NULL;
4950 struct got_blob_object *blob1 = NULL;
4951 int fd = -1, fd1 = -1, fd2 = -1;
4952 FILE *f2 = NULL;
4953 char *abspath = NULL, *label1 = NULL;
4954 struct stat sb;
4955 off_t size1 = 0;
4956 int f2_exists = 0;
4958 memset(&sb, 0, sizeof(sb));
4960 if (a->diff_staged) {
4961 if (staged_status != GOT_STATUS_MODIFY &&
4962 staged_status != GOT_STATUS_ADD &&
4963 staged_status != GOT_STATUS_DELETE)
4964 return NULL;
4965 } else {
4966 if (staged_status == GOT_STATUS_DELETE)
4967 return NULL;
4968 if (status == GOT_STATUS_NONEXISTENT)
4969 return got_error_set_errno(ENOENT, path);
4970 if (status != GOT_STATUS_MODIFY &&
4971 status != GOT_STATUS_ADD &&
4972 status != GOT_STATUS_DELETE &&
4973 status != GOT_STATUS_CONFLICT)
4974 return NULL;
4977 err = got_opentemp_truncate(a->f1);
4978 if (err)
4979 return got_error_from_errno("got_opentemp_truncate");
4980 err = got_opentemp_truncate(a->f2);
4981 if (err)
4982 return got_error_from_errno("got_opentemp_truncate");
4984 if (!a->header_shown) {
4985 if (fprintf(a->outfile, "diff %s%s\n",
4986 a->diff_staged ? "-s " : "",
4987 got_worktree_get_root_path(a->worktree)) < 0) {
4988 err = got_error_from_errno("fprintf");
4989 goto done;
4991 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4992 err = got_error_from_errno("fprintf");
4993 goto done;
4995 if (fprintf(a->outfile, "path + %s%s\n",
4996 got_worktree_get_root_path(a->worktree),
4997 a->diff_staged ? " (staged changes)" : "") < 0) {
4998 err = got_error_from_errno("fprintf");
4999 goto done;
5001 a->header_shown = 1;
5004 if (a->diff_staged) {
5005 const char *label1 = NULL, *label2 = NULL;
5006 switch (staged_status) {
5007 case GOT_STATUS_MODIFY:
5008 label1 = path;
5009 label2 = path;
5010 break;
5011 case GOT_STATUS_ADD:
5012 label2 = path;
5013 break;
5014 case GOT_STATUS_DELETE:
5015 label1 = path;
5016 break;
5017 default:
5018 return got_error(GOT_ERR_FILE_STATUS);
5020 fd1 = got_opentempfd();
5021 if (fd1 == -1) {
5022 err = got_error_from_errno("got_opentempfd");
5023 goto done;
5025 fd2 = got_opentempfd();
5026 if (fd2 == -1) {
5027 err = got_error_from_errno("got_opentempfd");
5028 goto done;
5030 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5031 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5032 a->diff_algo, a->diff_context, a->ignore_whitespace,
5033 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5034 goto done;
5037 fd1 = got_opentempfd();
5038 if (fd1 == -1) {
5039 err = got_error_from_errno("got_opentempfd");
5040 goto done;
5043 if (staged_status == GOT_STATUS_ADD ||
5044 staged_status == GOT_STATUS_MODIFY) {
5045 char *id_str;
5046 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5047 8192, fd1);
5048 if (err)
5049 goto done;
5050 err = got_object_id_str(&id_str, staged_blob_id);
5051 if (err)
5052 goto done;
5053 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5054 err = got_error_from_errno("asprintf");
5055 free(id_str);
5056 goto done;
5058 free(id_str);
5059 } else if (status != GOT_STATUS_ADD) {
5060 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5061 fd1);
5062 if (err)
5063 goto done;
5066 if (status != GOT_STATUS_DELETE) {
5067 if (asprintf(&abspath, "%s/%s",
5068 got_worktree_get_root_path(a->worktree), path) == -1) {
5069 err = got_error_from_errno("asprintf");
5070 goto done;
5073 if (dirfd != -1) {
5074 fd = openat(dirfd, de_name,
5075 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5076 if (fd == -1) {
5077 if (!got_err_open_nofollow_on_symlink()) {
5078 err = got_error_from_errno2("openat",
5079 abspath);
5080 goto done;
5082 err = get_symlink_target_file(&fd, dirfd,
5083 de_name, abspath);
5084 if (err)
5085 goto done;
5087 } else {
5088 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5089 if (fd == -1) {
5090 if (!got_err_open_nofollow_on_symlink()) {
5091 err = got_error_from_errno2("open",
5092 abspath);
5093 goto done;
5095 err = get_symlink_target_file(&fd, dirfd,
5096 de_name, abspath);
5097 if (err)
5098 goto done;
5101 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5102 err = got_error_from_errno2("fstatat", abspath);
5103 goto done;
5105 f2 = fdopen(fd, "r");
5106 if (f2 == NULL) {
5107 err = got_error_from_errno2("fdopen", abspath);
5108 goto done;
5110 fd = -1;
5111 f2_exists = 1;
5114 if (blob1) {
5115 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5116 a->f1, blob1);
5117 if (err)
5118 goto done;
5121 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5122 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5123 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5124 done:
5125 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5126 err = got_error_from_errno("close");
5127 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5128 err = got_error_from_errno("close");
5129 if (blob1)
5130 got_object_blob_close(blob1);
5131 if (fd != -1 && close(fd) == -1 && err == NULL)
5132 err = got_error_from_errno("close");
5133 if (f2 && fclose(f2) == EOF && err == NULL)
5134 err = got_error_from_errno("fclose");
5135 free(abspath);
5136 return err;
5139 static const struct got_error *
5140 cmd_diff(int argc, char *argv[])
5142 const struct got_error *error;
5143 struct got_repository *repo = NULL;
5144 struct got_worktree *worktree = NULL;
5145 char *cwd = NULL, *repo_path = NULL;
5146 const char *commit_args[2] = { NULL, NULL };
5147 int ncommit_args = 0;
5148 struct got_object_id *ids[2] = { NULL, NULL };
5149 char *labels[2] = { NULL, NULL };
5150 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5151 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5152 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5153 const char *errstr;
5154 struct got_reflist_head refs;
5155 struct got_pathlist_head diffstat_paths, paths;
5156 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5157 int fd1 = -1, fd2 = -1;
5158 int *pack_fds = NULL;
5159 struct got_diffstat_cb_arg dsa;
5161 memset(&dsa, 0, sizeof(dsa));
5163 TAILQ_INIT(&refs);
5164 TAILQ_INIT(&paths);
5165 TAILQ_INIT(&diffstat_paths);
5167 #ifndef PROFILE
5168 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5169 NULL) == -1)
5170 err(1, "pledge");
5171 #endif
5173 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5174 switch (ch) {
5175 case 'a':
5176 force_text_diff = 1;
5177 break;
5178 case 'C':
5179 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5180 &errstr);
5181 if (errstr != NULL)
5182 errx(1, "number of context lines is %s: %s",
5183 errstr, optarg);
5184 break;
5185 case 'c':
5186 if (ncommit_args >= 2)
5187 errx(1, "too many -c options used");
5188 commit_args[ncommit_args++] = optarg;
5189 break;
5190 case 'd':
5191 show_diffstat = 1;
5192 break;
5193 case 'P':
5194 force_path = 1;
5195 break;
5196 case 'r':
5197 repo_path = realpath(optarg, NULL);
5198 if (repo_path == NULL)
5199 return got_error_from_errno2("realpath",
5200 optarg);
5201 got_path_strip_trailing_slashes(repo_path);
5202 rflag = 1;
5203 break;
5204 case 's':
5205 diff_staged = 1;
5206 break;
5207 case 'w':
5208 ignore_whitespace = 1;
5209 break;
5210 default:
5211 usage_diff();
5212 /* NOTREACHED */
5216 argc -= optind;
5217 argv += optind;
5219 cwd = getcwd(NULL, 0);
5220 if (cwd == NULL) {
5221 error = got_error_from_errno("getcwd");
5222 goto done;
5225 error = got_repo_pack_fds_open(&pack_fds);
5226 if (error != NULL)
5227 goto done;
5229 if (repo_path == NULL) {
5230 error = got_worktree_open(&worktree, cwd,
5231 GOT_WORKTREE_GOT_DIR);
5232 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5233 goto done;
5234 else
5235 error = NULL;
5236 if (worktree) {
5237 repo_path =
5238 strdup(got_worktree_get_repo_path(worktree));
5239 if (repo_path == NULL) {
5240 error = got_error_from_errno("strdup");
5241 goto done;
5243 } else {
5244 repo_path = strdup(cwd);
5245 if (repo_path == NULL) {
5246 error = got_error_from_errno("strdup");
5247 goto done;
5252 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5253 free(repo_path);
5254 if (error != NULL)
5255 goto done;
5257 if (show_diffstat) {
5258 dsa.paths = &diffstat_paths;
5259 dsa.force_text = force_text_diff;
5260 dsa.ignore_ws = ignore_whitespace;
5261 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5264 if (rflag || worktree == NULL || ncommit_args > 0) {
5265 if (force_path) {
5266 error = got_error_msg(GOT_ERR_NOT_IMPL,
5267 "-P option can only be used when diffing "
5268 "a work tree");
5269 goto done;
5271 if (diff_staged) {
5272 error = got_error_msg(GOT_ERR_NOT_IMPL,
5273 "-s option can only be used when diffing "
5274 "a work tree");
5275 goto done;
5279 error = apply_unveil(got_repo_get_path(repo), 1,
5280 worktree ? got_worktree_get_root_path(worktree) : NULL);
5281 if (error)
5282 goto done;
5284 if ((!force_path && argc == 2) || ncommit_args > 0) {
5285 int obj_type = (ncommit_args > 0 ?
5286 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5287 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5288 NULL);
5289 if (error)
5290 goto done;
5291 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5292 const char *arg;
5293 char *keyword_idstr = NULL;
5295 if (ncommit_args > 0)
5296 arg = commit_args[i];
5297 else
5298 arg = argv[i];
5300 error = got_keyword_to_idstr(&keyword_idstr, arg,
5301 repo, worktree);
5302 if (error != NULL)
5303 goto done;
5304 if (keyword_idstr != NULL)
5305 arg = keyword_idstr;
5307 error = got_repo_match_object_id(&ids[i], &labels[i],
5308 arg, obj_type, &refs, repo);
5309 free(keyword_idstr);
5310 if (error) {
5311 if (error->code != GOT_ERR_NOT_REF &&
5312 error->code != GOT_ERR_NO_OBJ)
5313 goto done;
5314 if (ncommit_args > 0)
5315 goto done;
5316 error = NULL;
5317 break;
5322 f1 = got_opentemp();
5323 if (f1 == NULL) {
5324 error = got_error_from_errno("got_opentemp");
5325 goto done;
5328 f2 = got_opentemp();
5329 if (f2 == NULL) {
5330 error = got_error_from_errno("got_opentemp");
5331 goto done;
5334 outfile = got_opentemp();
5335 if (outfile == NULL) {
5336 error = got_error_from_errno("got_opentemp");
5337 goto done;
5340 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5341 struct print_diff_arg arg;
5342 char *id_str;
5344 if (worktree == NULL) {
5345 if (argc == 2 && ids[0] == NULL) {
5346 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5347 goto done;
5348 } else if (argc == 2 && ids[1] == NULL) {
5349 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5350 goto done;
5351 } else if (argc > 0) {
5352 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5353 "%s", "specified paths cannot be resolved");
5354 goto done;
5355 } else {
5356 error = got_error(GOT_ERR_NOT_WORKTREE);
5357 goto done;
5361 error = get_worktree_paths_from_argv(&paths, argc, argv,
5362 worktree);
5363 if (error)
5364 goto done;
5366 error = got_object_id_str(&id_str,
5367 got_worktree_get_base_commit_id(worktree));
5368 if (error)
5369 goto done;
5370 arg.repo = repo;
5371 arg.worktree = worktree;
5372 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5373 arg.diff_context = diff_context;
5374 arg.id_str = id_str;
5375 arg.header_shown = 0;
5376 arg.diff_staged = diff_staged;
5377 arg.ignore_whitespace = ignore_whitespace;
5378 arg.force_text_diff = force_text_diff;
5379 arg.diffstat = show_diffstat ? &dsa : NULL;
5380 arg.f1 = f1;
5381 arg.f2 = f2;
5382 arg.outfile = outfile;
5384 error = got_worktree_status(worktree, &paths, repo, 0,
5385 print_diff, &arg, check_cancelled, NULL);
5386 free(id_str);
5387 if (error)
5388 goto done;
5390 if (show_diffstat && dsa.nfiles > 0) {
5391 char *header;
5393 if (asprintf(&header, "diffstat %s%s",
5394 diff_staged ? "-s " : "",
5395 got_worktree_get_root_path(worktree)) == -1) {
5396 error = got_error_from_errno("asprintf");
5397 goto done;
5400 error = print_diffstat(&dsa, header);
5401 free(header);
5402 if (error)
5403 goto done;
5406 error = printfile(outfile);
5407 goto done;
5410 if (ncommit_args == 1) {
5411 struct got_commit_object *commit;
5412 error = got_object_open_as_commit(&commit, repo, ids[0]);
5413 if (error)
5414 goto done;
5416 labels[1] = labels[0];
5417 ids[1] = ids[0];
5418 if (got_object_commit_get_nparents(commit) > 0) {
5419 const struct got_object_id_queue *pids;
5420 struct got_object_qid *pid;
5421 pids = got_object_commit_get_parent_ids(commit);
5422 pid = STAILQ_FIRST(pids);
5423 ids[0] = got_object_id_dup(&pid->id);
5424 if (ids[0] == NULL) {
5425 error = got_error_from_errno(
5426 "got_object_id_dup");
5427 got_object_commit_close(commit);
5428 goto done;
5430 error = got_object_id_str(&labels[0], ids[0]);
5431 if (error) {
5432 got_object_commit_close(commit);
5433 goto done;
5435 } else {
5436 ids[0] = NULL;
5437 labels[0] = strdup("/dev/null");
5438 if (labels[0] == NULL) {
5439 error = got_error_from_errno("strdup");
5440 got_object_commit_close(commit);
5441 goto done;
5445 got_object_commit_close(commit);
5448 if (ncommit_args == 0 && argc > 2) {
5449 error = got_error_msg(GOT_ERR_BAD_PATH,
5450 "path arguments cannot be used when diffing two objects");
5451 goto done;
5454 if (ids[0]) {
5455 error = got_object_get_type(&type1, repo, ids[0]);
5456 if (error)
5457 goto done;
5460 error = got_object_get_type(&type2, repo, ids[1]);
5461 if (error)
5462 goto done;
5463 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5464 error = got_error(GOT_ERR_OBJ_TYPE);
5465 goto done;
5467 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5468 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5469 "path arguments cannot be used when diffing blobs");
5470 goto done;
5473 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5474 char *in_repo_path;
5475 struct got_pathlist_entry *new;
5476 if (worktree) {
5477 const char *prefix;
5478 char *p;
5479 error = got_worktree_resolve_path(&p, worktree,
5480 argv[i]);
5481 if (error)
5482 goto done;
5483 prefix = got_worktree_get_path_prefix(worktree);
5484 while (prefix[0] == '/')
5485 prefix++;
5486 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5487 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5488 p) == -1) {
5489 error = got_error_from_errno("asprintf");
5490 free(p);
5491 goto done;
5493 free(p);
5494 } else {
5495 char *mapped_path, *s;
5496 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5497 if (error)
5498 goto done;
5499 s = mapped_path;
5500 while (s[0] == '/')
5501 s++;
5502 in_repo_path = strdup(s);
5503 if (in_repo_path == NULL) {
5504 error = got_error_from_errno("asprintf");
5505 free(mapped_path);
5506 goto done;
5508 free(mapped_path);
5511 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5512 if (error || new == NULL /* duplicate */)
5513 free(in_repo_path);
5514 if (error)
5515 goto done;
5518 if (worktree) {
5519 /* Release work tree lock. */
5520 got_worktree_close(worktree);
5521 worktree = NULL;
5524 fd1 = got_opentempfd();
5525 if (fd1 == -1) {
5526 error = got_error_from_errno("got_opentempfd");
5527 goto done;
5530 fd2 = got_opentempfd();
5531 if (fd2 == -1) {
5532 error = got_error_from_errno("got_opentempfd");
5533 goto done;
5536 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5537 case GOT_OBJ_TYPE_BLOB:
5538 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5539 fd1, fd2, ids[0], ids[1], NULL, NULL,
5540 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5541 ignore_whitespace, force_text_diff,
5542 show_diffstat ? &dsa : NULL, repo, outfile);
5543 break;
5544 case GOT_OBJ_TYPE_TREE:
5545 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5546 ids[0], ids[1], &paths, "", "",
5547 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5548 ignore_whitespace, force_text_diff,
5549 show_diffstat ? &dsa : NULL, repo, outfile);
5550 break;
5551 case GOT_OBJ_TYPE_COMMIT:
5552 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5553 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5554 fd1, fd2, ids[0], ids[1], &paths,
5555 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5556 ignore_whitespace, force_text_diff,
5557 show_diffstat ? &dsa : NULL, repo, outfile);
5558 break;
5559 default:
5560 error = got_error(GOT_ERR_OBJ_TYPE);
5562 if (error)
5563 goto done;
5565 if (show_diffstat && dsa.nfiles > 0) {
5566 char *header = NULL;
5568 if (asprintf(&header, "diffstat %s %s",
5569 labels[0], labels[1]) == -1) {
5570 error = got_error_from_errno("asprintf");
5571 goto done;
5574 error = print_diffstat(&dsa, header);
5575 free(header);
5576 if (error)
5577 goto done;
5580 error = printfile(outfile);
5582 done:
5583 free(labels[0]);
5584 free(labels[1]);
5585 free(ids[0]);
5586 free(ids[1]);
5587 if (worktree)
5588 got_worktree_close(worktree);
5589 if (repo) {
5590 const struct got_error *close_err = got_repo_close(repo);
5591 if (error == NULL)
5592 error = close_err;
5594 if (pack_fds) {
5595 const struct got_error *pack_err =
5596 got_repo_pack_fds_close(pack_fds);
5597 if (error == NULL)
5598 error = pack_err;
5600 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5601 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5602 got_ref_list_free(&refs);
5603 if (outfile && fclose(outfile) == EOF && error == NULL)
5604 error = got_error_from_errno("fclose");
5605 if (f1 && fclose(f1) == EOF && error == NULL)
5606 error = got_error_from_errno("fclose");
5607 if (f2 && fclose(f2) == EOF && error == NULL)
5608 error = got_error_from_errno("fclose");
5609 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5610 error = got_error_from_errno("close");
5611 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5612 error = got_error_from_errno("close");
5613 return error;
5616 __dead static void
5617 usage_blame(void)
5619 fprintf(stderr,
5620 "usage: %s blame [-c commit] [-r repository-path] path\n",
5621 getprogname());
5622 exit(1);
5625 struct blame_line {
5626 int annotated;
5627 char *id_str;
5628 char *committer;
5629 char datebuf[11]; /* YYYY-MM-DD + NUL */
5632 struct blame_cb_args {
5633 struct blame_line *lines;
5634 int nlines;
5635 int nlines_prec;
5636 int lineno_cur;
5637 off_t *line_offsets;
5638 FILE *f;
5639 struct got_repository *repo;
5642 static const struct got_error *
5643 blame_cb(void *arg, int nlines, int lineno,
5644 struct got_commit_object *commit, struct got_object_id *id)
5646 const struct got_error *err = NULL;
5647 struct blame_cb_args *a = arg;
5648 struct blame_line *bline;
5649 char *line = NULL;
5650 size_t linesize = 0;
5651 off_t offset;
5652 struct tm tm;
5653 time_t committer_time;
5655 if (nlines != a->nlines ||
5656 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5657 return got_error(GOT_ERR_RANGE);
5659 if (sigint_received)
5660 return got_error(GOT_ERR_ITER_COMPLETED);
5662 if (lineno == -1)
5663 return NULL; /* no change in this commit */
5665 /* Annotate this line. */
5666 bline = &a->lines[lineno - 1];
5667 if (bline->annotated)
5668 return NULL;
5669 err = got_object_id_str(&bline->id_str, id);
5670 if (err)
5671 return err;
5673 bline->committer = strdup(got_object_commit_get_committer(commit));
5674 if (bline->committer == NULL) {
5675 err = got_error_from_errno("strdup");
5676 goto done;
5679 committer_time = got_object_commit_get_committer_time(commit);
5680 if (gmtime_r(&committer_time, &tm) == NULL)
5681 return got_error_from_errno("gmtime_r");
5682 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5683 &tm) == 0) {
5684 err = got_error(GOT_ERR_NO_SPACE);
5685 goto done;
5687 bline->annotated = 1;
5689 /* Print lines annotated so far. */
5690 bline = &a->lines[a->lineno_cur - 1];
5691 if (!bline->annotated)
5692 goto done;
5694 offset = a->line_offsets[a->lineno_cur - 1];
5695 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5696 err = got_error_from_errno("fseeko");
5697 goto done;
5700 while (a->lineno_cur <= a->nlines && bline->annotated) {
5701 char *smallerthan, *at, *nl, *committer;
5702 size_t len;
5704 if (getline(&line, &linesize, a->f) == -1) {
5705 if (ferror(a->f))
5706 err = got_error_from_errno("getline");
5707 break;
5710 committer = bline->committer;
5711 smallerthan = strchr(committer, '<');
5712 if (smallerthan && smallerthan[1] != '\0')
5713 committer = smallerthan + 1;
5714 at = strchr(committer, '@');
5715 if (at)
5716 *at = '\0';
5717 len = strlen(committer);
5718 if (len >= 9)
5719 committer[8] = '\0';
5721 nl = strchr(line, '\n');
5722 if (nl)
5723 *nl = '\0';
5724 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5725 bline->id_str, bline->datebuf, committer, line);
5727 a->lineno_cur++;
5728 bline = &a->lines[a->lineno_cur - 1];
5730 done:
5731 free(line);
5732 return err;
5735 static const struct got_error *
5736 cmd_blame(int argc, char *argv[])
5738 const struct got_error *error;
5739 struct got_repository *repo = NULL;
5740 struct got_worktree *worktree = NULL;
5741 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5742 char *link_target = NULL;
5743 struct got_object_id *obj_id = NULL;
5744 struct got_object_id *commit_id = NULL;
5745 struct got_commit_object *commit = NULL;
5746 struct got_blob_object *blob = NULL;
5747 char *commit_id_str = NULL, *keyword_idstr = NULL;
5748 struct blame_cb_args bca;
5749 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5750 off_t filesize;
5751 int *pack_fds = NULL;
5752 FILE *f1 = NULL, *f2 = NULL;
5754 fd1 = got_opentempfd();
5755 if (fd1 == -1)
5756 return got_error_from_errno("got_opentempfd");
5758 memset(&bca, 0, sizeof(bca));
5760 #ifndef PROFILE
5761 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5762 NULL) == -1)
5763 err(1, "pledge");
5764 #endif
5766 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5767 switch (ch) {
5768 case 'c':
5769 commit_id_str = optarg;
5770 break;
5771 case 'r':
5772 repo_path = realpath(optarg, NULL);
5773 if (repo_path == NULL)
5774 return got_error_from_errno2("realpath",
5775 optarg);
5776 got_path_strip_trailing_slashes(repo_path);
5777 break;
5778 default:
5779 usage_blame();
5780 /* NOTREACHED */
5784 argc -= optind;
5785 argv += optind;
5787 if (argc == 1)
5788 path = argv[0];
5789 else
5790 usage_blame();
5792 cwd = getcwd(NULL, 0);
5793 if (cwd == NULL) {
5794 error = got_error_from_errno("getcwd");
5795 goto done;
5798 error = got_repo_pack_fds_open(&pack_fds);
5799 if (error != NULL)
5800 goto done;
5802 if (repo_path == NULL) {
5803 error = got_worktree_open(&worktree, cwd,
5804 GOT_WORKTREE_GOT_DIR);
5805 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5806 goto done;
5807 else
5808 error = NULL;
5809 if (worktree) {
5810 repo_path =
5811 strdup(got_worktree_get_repo_path(worktree));
5812 if (repo_path == NULL) {
5813 error = got_error_from_errno("strdup");
5814 if (error)
5815 goto done;
5817 } else {
5818 repo_path = strdup(cwd);
5819 if (repo_path == NULL) {
5820 error = got_error_from_errno("strdup");
5821 goto done;
5826 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5827 if (error != NULL)
5828 goto done;
5830 if (worktree) {
5831 const char *prefix = got_worktree_get_path_prefix(worktree);
5832 char *p;
5834 error = got_worktree_resolve_path(&p, worktree, path);
5835 if (error)
5836 goto done;
5837 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5838 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5839 p) == -1) {
5840 error = got_error_from_errno("asprintf");
5841 free(p);
5842 goto done;
5844 free(p);
5845 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5846 } else {
5847 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5848 if (error)
5849 goto done;
5850 error = got_repo_map_path(&in_repo_path, repo, path);
5852 if (error)
5853 goto done;
5855 if (commit_id_str == NULL) {
5856 struct got_reference *head_ref;
5857 error = got_ref_open(&head_ref, repo, worktree ?
5858 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5859 if (error != NULL)
5860 goto done;
5861 error = got_ref_resolve(&commit_id, repo, head_ref);
5862 got_ref_close(head_ref);
5863 if (error != NULL)
5864 goto done;
5865 } else {
5866 struct got_reflist_head refs;
5868 TAILQ_INIT(&refs);
5869 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5870 NULL);
5871 if (error)
5872 goto done;
5874 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5875 repo, worktree);
5876 if (error != NULL)
5877 goto done;
5878 if (keyword_idstr != NULL)
5879 commit_id_str = keyword_idstr;
5881 error = got_repo_match_object_id(&commit_id, NULL,
5882 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5883 got_ref_list_free(&refs);
5884 if (error)
5885 goto done;
5888 if (worktree) {
5889 /* Release work tree lock. */
5890 got_worktree_close(worktree);
5891 worktree = NULL;
5894 error = got_object_open_as_commit(&commit, repo, commit_id);
5895 if (error)
5896 goto done;
5898 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5899 commit, repo);
5900 if (error)
5901 goto done;
5903 error = got_object_id_by_path(&obj_id, repo, commit,
5904 link_target ? link_target : in_repo_path);
5905 if (error)
5906 goto done;
5908 error = got_object_get_type(&obj_type, repo, obj_id);
5909 if (error)
5910 goto done;
5912 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5913 error = got_error_path(link_target ? link_target : in_repo_path,
5914 GOT_ERR_OBJ_TYPE);
5915 goto done;
5918 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5919 if (error)
5920 goto done;
5921 bca.f = got_opentemp();
5922 if (bca.f == NULL) {
5923 error = got_error_from_errno("got_opentemp");
5924 goto done;
5926 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5927 &bca.line_offsets, bca.f, blob);
5928 if (error || bca.nlines == 0)
5929 goto done;
5931 /* Don't include \n at EOF in the blame line count. */
5932 if (bca.line_offsets[bca.nlines - 1] == filesize)
5933 bca.nlines--;
5935 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5936 if (bca.lines == NULL) {
5937 error = got_error_from_errno("calloc");
5938 goto done;
5940 bca.lineno_cur = 1;
5941 bca.nlines_prec = 0;
5942 i = bca.nlines;
5943 while (i > 0) {
5944 i /= 10;
5945 bca.nlines_prec++;
5947 bca.repo = repo;
5949 fd2 = got_opentempfd();
5950 if (fd2 == -1) {
5951 error = got_error_from_errno("got_opentempfd");
5952 goto done;
5954 fd3 = got_opentempfd();
5955 if (fd3 == -1) {
5956 error = got_error_from_errno("got_opentempfd");
5957 goto done;
5959 f1 = got_opentemp();
5960 if (f1 == NULL) {
5961 error = got_error_from_errno("got_opentemp");
5962 goto done;
5964 f2 = got_opentemp();
5965 if (f2 == NULL) {
5966 error = got_error_from_errno("got_opentemp");
5967 goto done;
5969 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5970 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5971 check_cancelled, NULL, fd2, fd3, f1, f2);
5972 done:
5973 free(keyword_idstr);
5974 free(in_repo_path);
5975 free(link_target);
5976 free(repo_path);
5977 free(cwd);
5978 free(commit_id);
5979 free(obj_id);
5980 if (commit)
5981 got_object_commit_close(commit);
5983 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5984 error = got_error_from_errno("close");
5985 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5986 error = got_error_from_errno("close");
5987 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5988 error = got_error_from_errno("close");
5989 if (f1 && fclose(f1) == EOF && error == NULL)
5990 error = got_error_from_errno("fclose");
5991 if (f2 && fclose(f2) == EOF && error == NULL)
5992 error = got_error_from_errno("fclose");
5994 if (blob)
5995 got_object_blob_close(blob);
5996 if (worktree)
5997 got_worktree_close(worktree);
5998 if (repo) {
5999 const struct got_error *close_err = got_repo_close(repo);
6000 if (error == NULL)
6001 error = close_err;
6003 if (pack_fds) {
6004 const struct got_error *pack_err =
6005 got_repo_pack_fds_close(pack_fds);
6006 if (error == NULL)
6007 error = pack_err;
6009 if (bca.lines) {
6010 for (i = 0; i < bca.nlines; i++) {
6011 struct blame_line *bline = &bca.lines[i];
6012 free(bline->id_str);
6013 free(bline->committer);
6015 free(bca.lines);
6017 free(bca.line_offsets);
6018 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6019 error = got_error_from_errno("fclose");
6020 return error;
6023 __dead static void
6024 usage_tree(void)
6026 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6027 "[path]\n", getprogname());
6028 exit(1);
6031 static const struct got_error *
6032 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6033 const char *root_path, struct got_repository *repo)
6035 const struct got_error *err = NULL;
6036 int is_root_path = (strcmp(path, root_path) == 0);
6037 const char *modestr = "";
6038 mode_t mode = got_tree_entry_get_mode(te);
6039 char *link_target = NULL;
6041 path += strlen(root_path);
6042 while (path[0] == '/')
6043 path++;
6045 if (got_object_tree_entry_is_submodule(te))
6046 modestr = "$";
6047 else if (S_ISLNK(mode)) {
6048 int i;
6050 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6051 if (err)
6052 return err;
6053 for (i = 0; link_target[i] != '\0'; i++) {
6054 if (!isprint((unsigned char)link_target[i]))
6055 link_target[i] = '?';
6058 modestr = "@";
6060 else if (S_ISDIR(mode))
6061 modestr = "/";
6062 else if (mode & S_IXUSR)
6063 modestr = "*";
6065 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6066 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6067 link_target ? " -> ": "", link_target ? link_target : "");
6069 free(link_target);
6070 return NULL;
6073 static const struct got_error *
6074 print_tree(const char *path, struct got_commit_object *commit,
6075 int show_ids, int recurse, const char *root_path,
6076 struct got_repository *repo)
6078 const struct got_error *err = NULL;
6079 struct got_object_id *tree_id = NULL;
6080 struct got_tree_object *tree = NULL;
6081 int nentries, i;
6083 err = got_object_id_by_path(&tree_id, repo, commit, path);
6084 if (err)
6085 goto done;
6087 err = got_object_open_as_tree(&tree, repo, tree_id);
6088 if (err)
6089 goto done;
6090 nentries = got_object_tree_get_nentries(tree);
6091 for (i = 0; i < nentries; i++) {
6092 struct got_tree_entry *te;
6093 char *id = NULL;
6095 if (sigint_received || sigpipe_received)
6096 break;
6098 te = got_object_tree_get_entry(tree, i);
6099 if (show_ids) {
6100 char *id_str;
6101 err = got_object_id_str(&id_str,
6102 got_tree_entry_get_id(te));
6103 if (err)
6104 goto done;
6105 if (asprintf(&id, "%s ", id_str) == -1) {
6106 err = got_error_from_errno("asprintf");
6107 free(id_str);
6108 goto done;
6110 free(id_str);
6112 err = print_entry(te, id, path, root_path, repo);
6113 free(id);
6114 if (err)
6115 goto done;
6117 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6118 char *child_path;
6119 if (asprintf(&child_path, "%s%s%s", path,
6120 path[0] == '/' && path[1] == '\0' ? "" : "/",
6121 got_tree_entry_get_name(te)) == -1) {
6122 err = got_error_from_errno("asprintf");
6123 goto done;
6125 err = print_tree(child_path, commit, show_ids, 1,
6126 root_path, repo);
6127 free(child_path);
6128 if (err)
6129 goto done;
6132 done:
6133 if (tree)
6134 got_object_tree_close(tree);
6135 free(tree_id);
6136 return err;
6139 static const struct got_error *
6140 cmd_tree(int argc, char *argv[])
6142 const struct got_error *error;
6143 struct got_repository *repo = NULL;
6144 struct got_worktree *worktree = NULL;
6145 const char *path, *refname = NULL;
6146 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6147 struct got_object_id *commit_id = NULL;
6148 struct got_commit_object *commit = NULL;
6149 char *commit_id_str = NULL, *keyword_idstr = NULL;
6150 int show_ids = 0, recurse = 0;
6151 int ch;
6152 int *pack_fds = NULL;
6154 #ifndef PROFILE
6155 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6156 NULL) == -1)
6157 err(1, "pledge");
6158 #endif
6160 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6161 switch (ch) {
6162 case 'c':
6163 commit_id_str = optarg;
6164 break;
6165 case 'i':
6166 show_ids = 1;
6167 break;
6168 case 'R':
6169 recurse = 1;
6170 break;
6171 case 'r':
6172 repo_path = realpath(optarg, NULL);
6173 if (repo_path == NULL)
6174 return got_error_from_errno2("realpath",
6175 optarg);
6176 got_path_strip_trailing_slashes(repo_path);
6177 break;
6178 default:
6179 usage_tree();
6180 /* NOTREACHED */
6184 argc -= optind;
6185 argv += optind;
6187 if (argc == 1)
6188 path = argv[0];
6189 else if (argc > 1)
6190 usage_tree();
6191 else
6192 path = NULL;
6194 cwd = getcwd(NULL, 0);
6195 if (cwd == NULL) {
6196 error = got_error_from_errno("getcwd");
6197 goto done;
6200 error = got_repo_pack_fds_open(&pack_fds);
6201 if (error != NULL)
6202 goto done;
6204 if (repo_path == NULL) {
6205 error = got_worktree_open(&worktree, cwd,
6206 GOT_WORKTREE_GOT_DIR);
6207 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6208 goto done;
6209 else
6210 error = NULL;
6211 if (worktree) {
6212 repo_path =
6213 strdup(got_worktree_get_repo_path(worktree));
6214 if (repo_path == NULL)
6215 error = got_error_from_errno("strdup");
6216 if (error)
6217 goto done;
6218 } else {
6219 repo_path = strdup(cwd);
6220 if (repo_path == NULL) {
6221 error = got_error_from_errno("strdup");
6222 goto done;
6227 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6228 if (error != NULL)
6229 goto done;
6231 if (worktree) {
6232 const char *prefix = got_worktree_get_path_prefix(worktree);
6233 char *p;
6235 if (path == NULL || got_path_is_root_dir(path))
6236 path = "";
6237 error = got_worktree_resolve_path(&p, worktree, path);
6238 if (error)
6239 goto done;
6240 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6241 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6242 p) == -1) {
6243 error = got_error_from_errno("asprintf");
6244 free(p);
6245 goto done;
6247 free(p);
6248 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6249 if (error)
6250 goto done;
6251 } else {
6252 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6253 if (error)
6254 goto done;
6255 if (path == NULL)
6256 path = "/";
6257 error = got_repo_map_path(&in_repo_path, repo, path);
6258 if (error != NULL)
6259 goto done;
6262 if (commit_id_str == NULL) {
6263 struct got_reference *head_ref;
6264 if (worktree)
6265 refname = got_worktree_get_head_ref_name(worktree);
6266 else
6267 refname = GOT_REF_HEAD;
6268 error = got_ref_open(&head_ref, repo, refname, 0);
6269 if (error != NULL)
6270 goto done;
6271 error = got_ref_resolve(&commit_id, repo, head_ref);
6272 got_ref_close(head_ref);
6273 if (error != NULL)
6274 goto done;
6275 } else {
6276 struct got_reflist_head refs;
6278 TAILQ_INIT(&refs);
6279 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6280 NULL);
6281 if (error)
6282 goto done;
6284 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6285 repo, worktree);
6286 if (error != NULL)
6287 goto done;
6288 if (keyword_idstr != NULL)
6289 commit_id_str = keyword_idstr;
6291 error = got_repo_match_object_id(&commit_id, NULL,
6292 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6293 got_ref_list_free(&refs);
6294 if (error)
6295 goto done;
6298 if (worktree) {
6299 /* Release work tree lock. */
6300 got_worktree_close(worktree);
6301 worktree = NULL;
6304 error = got_object_open_as_commit(&commit, repo, commit_id);
6305 if (error)
6306 goto done;
6308 error = print_tree(in_repo_path, commit, show_ids, recurse,
6309 in_repo_path, repo);
6310 done:
6311 free(keyword_idstr);
6312 free(in_repo_path);
6313 free(repo_path);
6314 free(cwd);
6315 free(commit_id);
6316 if (commit)
6317 got_object_commit_close(commit);
6318 if (worktree)
6319 got_worktree_close(worktree);
6320 if (repo) {
6321 const struct got_error *close_err = got_repo_close(repo);
6322 if (error == NULL)
6323 error = close_err;
6325 if (pack_fds) {
6326 const struct got_error *pack_err =
6327 got_repo_pack_fds_close(pack_fds);
6328 if (error == NULL)
6329 error = pack_err;
6331 return error;
6334 __dead static void
6335 usage_status(void)
6337 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6338 "[-s status-codes] [path ...]\n", getprogname());
6339 exit(1);
6342 struct got_status_arg {
6343 char *status_codes;
6344 int suppress;
6347 static const struct got_error *
6348 print_status(void *arg, unsigned char status, unsigned char staged_status,
6349 const char *path, struct got_object_id *blob_id,
6350 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6351 int dirfd, const char *de_name)
6353 struct got_status_arg *st = arg;
6355 if (status == staged_status && (status == GOT_STATUS_DELETE))
6356 status = GOT_STATUS_NO_CHANGE;
6357 if (st != NULL && st->status_codes) {
6358 size_t ncodes = strlen(st->status_codes);
6359 int i, j = 0;
6361 for (i = 0; i < ncodes ; i++) {
6362 if (st->suppress) {
6363 if (status == st->status_codes[i] ||
6364 staged_status == st->status_codes[i]) {
6365 j++;
6366 continue;
6368 } else {
6369 if (status == st->status_codes[i] ||
6370 staged_status == st->status_codes[i])
6371 break;
6375 if (st->suppress && j == 0)
6376 goto print;
6378 if (i == ncodes)
6379 return NULL;
6381 print:
6382 printf("%c%c %s\n", status, staged_status, path);
6383 return NULL;
6386 static const struct got_error *
6387 cmd_status(int argc, char *argv[])
6389 const struct got_error *error = NULL;
6390 struct got_repository *repo = NULL;
6391 struct got_worktree *worktree = NULL;
6392 struct got_status_arg st;
6393 char *cwd = NULL;
6394 struct got_pathlist_head paths;
6395 int ch, i, no_ignores = 0;
6396 int *pack_fds = NULL;
6398 TAILQ_INIT(&paths);
6400 memset(&st, 0, sizeof(st));
6401 st.status_codes = NULL;
6402 st.suppress = 0;
6404 #ifndef PROFILE
6405 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6406 NULL) == -1)
6407 err(1, "pledge");
6408 #endif
6410 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6411 switch (ch) {
6412 case 'I':
6413 no_ignores = 1;
6414 break;
6415 case 'S':
6416 if (st.status_codes != NULL && st.suppress == 0)
6417 option_conflict('S', 's');
6418 st.suppress = 1;
6419 /* fallthrough */
6420 case 's':
6421 for (i = 0; optarg[i] != '\0'; i++) {
6422 switch (optarg[i]) {
6423 case GOT_STATUS_MODIFY:
6424 case GOT_STATUS_ADD:
6425 case GOT_STATUS_DELETE:
6426 case GOT_STATUS_CONFLICT:
6427 case GOT_STATUS_MISSING:
6428 case GOT_STATUS_OBSTRUCTED:
6429 case GOT_STATUS_UNVERSIONED:
6430 case GOT_STATUS_MODE_CHANGE:
6431 case GOT_STATUS_NONEXISTENT:
6432 break;
6433 default:
6434 errx(1, "invalid status code '%c'",
6435 optarg[i]);
6438 if (ch == 's' && st.suppress)
6439 option_conflict('s', 'S');
6440 st.status_codes = optarg;
6441 break;
6442 default:
6443 usage_status();
6444 /* NOTREACHED */
6448 argc -= optind;
6449 argv += optind;
6451 cwd = getcwd(NULL, 0);
6452 if (cwd == NULL) {
6453 error = got_error_from_errno("getcwd");
6454 goto done;
6457 error = got_repo_pack_fds_open(&pack_fds);
6458 if (error != NULL)
6459 goto done;
6461 error = got_worktree_open(&worktree, cwd,
6462 GOT_WORKTREE_GOT_DIR);
6463 if (error) {
6464 if (error->code == GOT_ERR_NOT_WORKTREE)
6465 error = wrap_not_worktree_error(error, "status", cwd);
6466 goto done;
6469 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6470 NULL, pack_fds);
6471 if (error != NULL)
6472 goto done;
6474 error = apply_unveil(got_repo_get_path(repo), 1,
6475 got_worktree_get_root_path(worktree));
6476 if (error)
6477 goto done;
6479 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6480 if (error)
6481 goto done;
6483 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6484 print_status, &st, check_cancelled, NULL);
6485 done:
6486 if (pack_fds) {
6487 const struct got_error *pack_err =
6488 got_repo_pack_fds_close(pack_fds);
6489 if (error == NULL)
6490 error = pack_err;
6492 if (repo) {
6493 const struct got_error *close_err = got_repo_close(repo);
6494 if (error == NULL)
6495 error = close_err;
6498 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6499 free(cwd);
6500 return error;
6503 __dead static void
6504 usage_ref(void)
6506 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6507 "[-s reference] [name]\n", getprogname());
6508 exit(1);
6511 static const struct got_error *
6512 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6514 static const struct got_error *err = NULL;
6515 struct got_reflist_head refs;
6516 struct got_reflist_entry *re;
6518 TAILQ_INIT(&refs);
6519 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6520 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6521 repo);
6522 if (err)
6523 return err;
6525 TAILQ_FOREACH(re, &refs, entry) {
6526 char *refstr;
6527 refstr = got_ref_to_str(re->ref);
6528 if (refstr == NULL) {
6529 err = got_error_from_errno("got_ref_to_str");
6530 break;
6532 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6533 free(refstr);
6536 got_ref_list_free(&refs);
6537 return err;
6540 static const struct got_error *
6541 delete_ref_by_name(struct got_repository *repo, const char *refname)
6543 const struct got_error *err;
6544 struct got_reference *ref;
6546 err = got_ref_open(&ref, repo, refname, 0);
6547 if (err)
6548 return err;
6550 err = delete_ref(repo, ref);
6551 got_ref_close(ref);
6552 return err;
6555 static const struct got_error *
6556 add_ref(struct got_repository *repo, const char *refname, const char *target)
6558 const struct got_error *err = NULL;
6559 struct got_object_id *id = NULL;
6560 struct got_reference *ref = NULL;
6561 struct got_reflist_head refs;
6564 * Don't let the user create a reference name with a leading '-'.
6565 * While technically a valid reference name, this case is usually
6566 * an unintended typo.
6568 if (refname[0] == '-')
6569 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6571 TAILQ_INIT(&refs);
6572 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6573 if (err)
6574 goto done;
6575 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6576 &refs, repo);
6577 got_ref_list_free(&refs);
6578 if (err)
6579 goto done;
6581 err = got_ref_alloc(&ref, refname, id);
6582 if (err)
6583 goto done;
6585 err = got_ref_write(ref, repo);
6586 done:
6587 if (ref)
6588 got_ref_close(ref);
6589 free(id);
6590 return err;
6593 static const struct got_error *
6594 add_symref(struct got_repository *repo, const char *refname, const char *target)
6596 const struct got_error *err = NULL;
6597 struct got_reference *ref = NULL;
6598 struct got_reference *target_ref = NULL;
6601 * Don't let the user create a reference name with a leading '-'.
6602 * While technically a valid reference name, this case is usually
6603 * an unintended typo.
6605 if (refname[0] == '-')
6606 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6608 err = got_ref_open(&target_ref, repo, target, 0);
6609 if (err)
6610 return err;
6612 err = got_ref_alloc_symref(&ref, refname, target_ref);
6613 if (err)
6614 goto done;
6616 err = got_ref_write(ref, repo);
6617 done:
6618 if (target_ref)
6619 got_ref_close(target_ref);
6620 if (ref)
6621 got_ref_close(ref);
6622 return err;
6625 static const struct got_error *
6626 cmd_ref(int argc, char *argv[])
6628 const struct got_error *error = NULL;
6629 struct got_repository *repo = NULL;
6630 struct got_worktree *worktree = NULL;
6631 char *cwd = NULL, *repo_path = NULL;
6632 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6633 const char *obj_arg = NULL, *symref_target= NULL;
6634 char *refname = NULL, *keyword_idstr = NULL;
6635 int *pack_fds = NULL;
6637 #ifndef PROFILE
6638 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6639 "sendfd unveil", NULL) == -1)
6640 err(1, "pledge");
6641 #endif
6643 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6644 switch (ch) {
6645 case 'c':
6646 obj_arg = optarg;
6647 break;
6648 case 'd':
6649 do_delete = 1;
6650 break;
6651 case 'l':
6652 do_list = 1;
6653 break;
6654 case 'r':
6655 repo_path = realpath(optarg, NULL);
6656 if (repo_path == NULL)
6657 return got_error_from_errno2("realpath",
6658 optarg);
6659 got_path_strip_trailing_slashes(repo_path);
6660 break;
6661 case 's':
6662 symref_target = optarg;
6663 break;
6664 case 't':
6665 sort_by_time = 1;
6666 break;
6667 default:
6668 usage_ref();
6669 /* NOTREACHED */
6673 if (obj_arg && do_list)
6674 option_conflict('c', 'l');
6675 if (obj_arg && do_delete)
6676 option_conflict('c', 'd');
6677 if (obj_arg && symref_target)
6678 option_conflict('c', 's');
6679 if (symref_target && do_delete)
6680 option_conflict('s', 'd');
6681 if (symref_target && do_list)
6682 option_conflict('s', 'l');
6683 if (do_delete && do_list)
6684 option_conflict('d', 'l');
6685 if (sort_by_time && !do_list)
6686 errx(1, "-t option requires -l option");
6688 argc -= optind;
6689 argv += optind;
6691 if (do_list) {
6692 if (argc != 0 && argc != 1)
6693 usage_ref();
6694 if (argc == 1) {
6695 refname = strdup(argv[0]);
6696 if (refname == NULL) {
6697 error = got_error_from_errno("strdup");
6698 goto done;
6701 } else {
6702 if (argc != 1)
6703 usage_ref();
6704 refname = strdup(argv[0]);
6705 if (refname == NULL) {
6706 error = got_error_from_errno("strdup");
6707 goto done;
6711 if (refname)
6712 got_path_strip_trailing_slashes(refname);
6714 cwd = getcwd(NULL, 0);
6715 if (cwd == NULL) {
6716 error = got_error_from_errno("getcwd");
6717 goto done;
6720 error = got_repo_pack_fds_open(&pack_fds);
6721 if (error != NULL)
6722 goto done;
6724 if (repo_path == NULL) {
6725 error = got_worktree_open(&worktree, cwd,
6726 GOT_WORKTREE_GOT_DIR);
6727 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6728 goto done;
6729 else
6730 error = NULL;
6731 if (worktree) {
6732 repo_path =
6733 strdup(got_worktree_get_repo_path(worktree));
6734 if (repo_path == NULL)
6735 error = got_error_from_errno("strdup");
6736 if (error)
6737 goto done;
6738 } else {
6739 repo_path = strdup(cwd);
6740 if (repo_path == NULL) {
6741 error = got_error_from_errno("strdup");
6742 goto done;
6747 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6748 if (error != NULL)
6749 goto done;
6751 #ifndef PROFILE
6752 if (do_list) {
6753 /* Remove "cpath" promise. */
6754 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6755 NULL) == -1)
6756 err(1, "pledge");
6758 #endif
6760 error = apply_unveil(got_repo_get_path(repo), do_list,
6761 worktree ? got_worktree_get_root_path(worktree) : NULL);
6762 if (error)
6763 goto done;
6765 if (do_list)
6766 error = list_refs(repo, refname, sort_by_time);
6767 else if (do_delete)
6768 error = delete_ref_by_name(repo, refname);
6769 else if (symref_target)
6770 error = add_symref(repo, refname, symref_target);
6771 else {
6772 if (obj_arg == NULL)
6773 usage_ref();
6775 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6776 repo, worktree);
6777 if (error != NULL)
6778 goto done;
6779 if (keyword_idstr != NULL)
6780 obj_arg = keyword_idstr;
6782 error = add_ref(repo, refname, obj_arg);
6784 done:
6785 free(refname);
6786 if (repo) {
6787 const struct got_error *close_err = got_repo_close(repo);
6788 if (error == NULL)
6789 error = close_err;
6791 if (worktree)
6792 got_worktree_close(worktree);
6793 if (pack_fds) {
6794 const struct got_error *pack_err =
6795 got_repo_pack_fds_close(pack_fds);
6796 if (error == NULL)
6797 error = pack_err;
6799 free(cwd);
6800 free(repo_path);
6801 free(keyword_idstr);
6802 return error;
6805 __dead static void
6806 usage_branch(void)
6808 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6809 "[-r repository-path] [name]\n", getprogname());
6810 exit(1);
6813 static const struct got_error *
6814 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6815 struct got_reference *ref)
6817 const struct got_error *err = NULL;
6818 const char *refname;
6819 char *refstr;
6820 char marker = ' ';
6822 refname = got_ref_get_name(ref);
6823 if (worktree && strcmp(refname,
6824 got_worktree_get_head_ref_name(worktree)) == 0) {
6825 err = got_worktree_get_state(&marker, repo, worktree,
6826 check_cancelled, NULL);
6827 if (err != NULL)
6828 return err;
6831 if (strncmp(refname, "refs/heads/", 11) == 0)
6832 refname += 11;
6833 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6834 refname += 18;
6835 if (strncmp(refname, "refs/remotes/", 13) == 0)
6836 refname += 13;
6838 refstr = got_ref_to_str(ref);
6839 if (refstr == NULL)
6840 return got_error_from_errno("got_ref_to_str");
6842 printf("%c %s: %s\n", marker, refname, refstr);
6843 free(refstr);
6844 return NULL;
6847 static const struct got_error *
6848 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6850 const char *refname;
6852 if (worktree == NULL)
6853 return got_error(GOT_ERR_NOT_WORKTREE);
6855 refname = got_worktree_get_head_ref_name(worktree);
6857 if (strncmp(refname, "refs/heads/", 11) == 0)
6858 refname += 11;
6859 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6860 refname += 18;
6862 printf("%s\n", refname);
6864 return NULL;
6867 static const struct got_error *
6868 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6869 int sort_by_time)
6871 static const struct got_error *err = NULL;
6872 struct got_reflist_head refs;
6873 struct got_reflist_entry *re;
6874 struct got_reference *temp_ref = NULL;
6875 int rebase_in_progress, histedit_in_progress;
6877 TAILQ_INIT(&refs);
6879 if (worktree) {
6880 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6881 worktree);
6882 if (err)
6883 return err;
6885 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6886 worktree);
6887 if (err)
6888 return err;
6890 if (rebase_in_progress || histedit_in_progress) {
6891 err = got_ref_open(&temp_ref, repo,
6892 got_worktree_get_head_ref_name(worktree), 0);
6893 if (err)
6894 return err;
6895 list_branch(repo, worktree, temp_ref);
6896 got_ref_close(temp_ref);
6900 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6901 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6902 repo);
6903 if (err)
6904 return err;
6906 TAILQ_FOREACH(re, &refs, entry)
6907 list_branch(repo, worktree, re->ref);
6909 got_ref_list_free(&refs);
6911 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6912 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6913 repo);
6914 if (err)
6915 return err;
6917 TAILQ_FOREACH(re, &refs, entry)
6918 list_branch(repo, worktree, re->ref);
6920 got_ref_list_free(&refs);
6922 return NULL;
6925 static const struct got_error *
6926 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6927 const char *branch_name)
6929 const struct got_error *err = NULL;
6930 struct got_reference *ref = NULL;
6931 char *refname, *remote_refname = NULL;
6933 if (strncmp(branch_name, "refs/", 5) == 0)
6934 branch_name += 5;
6935 if (strncmp(branch_name, "heads/", 6) == 0)
6936 branch_name += 6;
6937 else if (strncmp(branch_name, "remotes/", 8) == 0)
6938 branch_name += 8;
6940 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6941 return got_error_from_errno("asprintf");
6943 if (asprintf(&remote_refname, "refs/remotes/%s",
6944 branch_name) == -1) {
6945 err = got_error_from_errno("asprintf");
6946 goto done;
6949 err = got_ref_open(&ref, repo, refname, 0);
6950 if (err) {
6951 const struct got_error *err2;
6952 if (err->code != GOT_ERR_NOT_REF)
6953 goto done;
6955 * Keep 'err' intact such that if neither branch exists
6956 * we report "refs/heads" rather than "refs/remotes" in
6957 * our error message.
6959 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6960 if (err2)
6961 goto done;
6962 err = NULL;
6965 if (worktree &&
6966 strcmp(got_worktree_get_head_ref_name(worktree),
6967 got_ref_get_name(ref)) == 0) {
6968 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6969 "will not delete this work tree's current branch");
6970 goto done;
6973 err = delete_ref(repo, ref);
6974 done:
6975 if (ref)
6976 got_ref_close(ref);
6977 free(refname);
6978 free(remote_refname);
6979 return err;
6982 static const struct got_error *
6983 add_branch(struct got_repository *repo, const char *branch_name,
6984 struct got_object_id *base_commit_id)
6986 const struct got_error *err = NULL;
6987 struct got_reference *ref = NULL;
6988 char *refname = NULL;
6991 * Don't let the user create a branch name with a leading '-'.
6992 * While technically a valid reference name, this case is usually
6993 * an unintended typo.
6995 if (branch_name[0] == '-')
6996 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6998 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6999 branch_name += 11;
7001 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7002 err = got_error_from_errno("asprintf");
7003 goto done;
7006 err = got_ref_open(&ref, repo, refname, 0);
7007 if (err == NULL) {
7008 err = got_error(GOT_ERR_BRANCH_EXISTS);
7009 goto done;
7010 } else if (err->code != GOT_ERR_NOT_REF)
7011 goto done;
7013 err = got_ref_alloc(&ref, refname, base_commit_id);
7014 if (err)
7015 goto done;
7017 err = got_ref_write(ref, repo);
7018 done:
7019 if (ref)
7020 got_ref_close(ref);
7021 free(refname);
7022 return err;
7025 static const struct got_error *
7026 cmd_branch(int argc, char *argv[])
7028 const struct got_error *error = NULL;
7029 struct got_repository *repo = NULL;
7030 struct got_worktree *worktree = NULL;
7031 char *cwd = NULL, *repo_path = NULL;
7032 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7033 const char *delref = NULL, *commit_id_arg = NULL;
7034 struct got_reference *ref = NULL;
7035 struct got_pathlist_head paths;
7036 struct got_object_id *commit_id = NULL;
7037 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7038 int *pack_fds = NULL;
7040 TAILQ_INIT(&paths);
7042 #ifndef PROFILE
7043 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7044 "sendfd unveil", NULL) == -1)
7045 err(1, "pledge");
7046 #endif
7048 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7049 switch (ch) {
7050 case 'c':
7051 commit_id_arg = optarg;
7052 break;
7053 case 'd':
7054 delref = optarg;
7055 break;
7056 case 'l':
7057 do_list = 1;
7058 break;
7059 case 'n':
7060 do_update = 0;
7061 break;
7062 case 'r':
7063 repo_path = realpath(optarg, NULL);
7064 if (repo_path == NULL)
7065 return got_error_from_errno2("realpath",
7066 optarg);
7067 got_path_strip_trailing_slashes(repo_path);
7068 break;
7069 case 't':
7070 sort_by_time = 1;
7071 break;
7072 default:
7073 usage_branch();
7074 /* NOTREACHED */
7078 if (do_list && delref)
7079 option_conflict('l', 'd');
7080 if (sort_by_time && !do_list)
7081 errx(1, "-t option requires -l option");
7083 argc -= optind;
7084 argv += optind;
7086 if (!do_list && !delref && argc == 0)
7087 do_show = 1;
7089 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7090 errx(1, "-c option can only be used when creating a branch");
7092 if (do_list || delref) {
7093 if (argc > 0)
7094 usage_branch();
7095 } else if (!do_show && argc != 1)
7096 usage_branch();
7098 cwd = getcwd(NULL, 0);
7099 if (cwd == NULL) {
7100 error = got_error_from_errno("getcwd");
7101 goto done;
7104 error = got_repo_pack_fds_open(&pack_fds);
7105 if (error != NULL)
7106 goto done;
7108 if (repo_path == NULL) {
7109 error = got_worktree_open(&worktree, cwd,
7110 GOT_WORKTREE_GOT_DIR);
7111 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7112 goto done;
7113 else
7114 error = NULL;
7115 if (worktree) {
7116 repo_path =
7117 strdup(got_worktree_get_repo_path(worktree));
7118 if (repo_path == NULL)
7119 error = got_error_from_errno("strdup");
7120 if (error)
7121 goto done;
7122 } else {
7123 repo_path = strdup(cwd);
7124 if (repo_path == NULL) {
7125 error = got_error_from_errno("strdup");
7126 goto done;
7131 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7132 if (error != NULL)
7133 goto done;
7135 #ifndef PROFILE
7136 if (do_list || do_show) {
7137 /* Remove "cpath" promise. */
7138 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7139 NULL) == -1)
7140 err(1, "pledge");
7142 #endif
7144 error = apply_unveil(got_repo_get_path(repo), do_list,
7145 worktree ? got_worktree_get_root_path(worktree) : NULL);
7146 if (error)
7147 goto done;
7149 if (do_show)
7150 error = show_current_branch(repo, worktree);
7151 else if (do_list)
7152 error = list_branches(repo, worktree, sort_by_time);
7153 else if (delref)
7154 error = delete_branch(repo, worktree, delref);
7155 else {
7156 struct got_reflist_head refs;
7157 TAILQ_INIT(&refs);
7158 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7159 NULL);
7160 if (error)
7161 goto done;
7162 if (commit_id_arg == NULL)
7163 commit_id_arg = worktree ?
7164 got_worktree_get_head_ref_name(worktree) :
7165 GOT_REF_HEAD;
7166 else {
7167 error = got_keyword_to_idstr(&keyword_idstr,
7168 commit_id_arg, repo, worktree);
7169 if (error != NULL)
7170 goto done;
7171 if (keyword_idstr != NULL)
7172 commit_id_arg = keyword_idstr;
7174 error = got_repo_match_object_id(&commit_id, NULL,
7175 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7176 got_ref_list_free(&refs);
7177 if (error)
7178 goto done;
7179 error = add_branch(repo, argv[0], commit_id);
7180 if (error)
7181 goto done;
7182 if (worktree && do_update) {
7183 struct got_update_progress_arg upa;
7184 char *branch_refname = NULL;
7186 error = got_object_id_str(&commit_id_str, commit_id);
7187 if (error)
7188 goto done;
7189 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7190 worktree);
7191 if (error)
7192 goto done;
7193 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7194 == -1) {
7195 error = got_error_from_errno("asprintf");
7196 goto done;
7198 error = got_ref_open(&ref, repo, branch_refname, 0);
7199 free(branch_refname);
7200 if (error)
7201 goto done;
7202 error = switch_head_ref(ref, commit_id, worktree,
7203 repo);
7204 if (error)
7205 goto done;
7206 error = got_worktree_set_base_commit_id(worktree, repo,
7207 commit_id);
7208 if (error)
7209 goto done;
7210 memset(&upa, 0, sizeof(upa));
7211 error = got_worktree_checkout_files(worktree, &paths,
7212 repo, update_progress, &upa, check_cancelled,
7213 NULL);
7214 if (error)
7215 goto done;
7216 if (upa.did_something) {
7217 printf("Updated to %s: %s\n",
7218 got_worktree_get_head_ref_name(worktree),
7219 commit_id_str);
7221 print_update_progress_stats(&upa);
7224 done:
7225 free(keyword_idstr);
7226 if (ref)
7227 got_ref_close(ref);
7228 if (repo) {
7229 const struct got_error *close_err = got_repo_close(repo);
7230 if (error == NULL)
7231 error = close_err;
7233 if (worktree)
7234 got_worktree_close(worktree);
7235 if (pack_fds) {
7236 const struct got_error *pack_err =
7237 got_repo_pack_fds_close(pack_fds);
7238 if (error == NULL)
7239 error = pack_err;
7241 free(cwd);
7242 free(repo_path);
7243 free(commit_id);
7244 free(commit_id_str);
7245 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7246 return error;
7250 __dead static void
7251 usage_tag(void)
7253 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7254 "[-r repository-path] [-s signer-id] name\n", getprogname());
7255 exit(1);
7258 #if 0
7259 static const struct got_error *
7260 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7262 const struct got_error *err = NULL;
7263 struct got_reflist_entry *re, *se, *new;
7264 struct got_object_id *re_id, *se_id;
7265 struct got_tag_object *re_tag, *se_tag;
7266 time_t re_time, se_time;
7268 STAILQ_FOREACH(re, tags, entry) {
7269 se = STAILQ_FIRST(sorted);
7270 if (se == NULL) {
7271 err = got_reflist_entry_dup(&new, re);
7272 if (err)
7273 return err;
7274 STAILQ_INSERT_HEAD(sorted, new, entry);
7275 continue;
7276 } else {
7277 err = got_ref_resolve(&re_id, repo, re->ref);
7278 if (err)
7279 break;
7280 err = got_object_open_as_tag(&re_tag, repo, re_id);
7281 free(re_id);
7282 if (err)
7283 break;
7284 re_time = got_object_tag_get_tagger_time(re_tag);
7285 got_object_tag_close(re_tag);
7288 while (se) {
7289 err = got_ref_resolve(&se_id, repo, re->ref);
7290 if (err)
7291 break;
7292 err = got_object_open_as_tag(&se_tag, repo, se_id);
7293 free(se_id);
7294 if (err)
7295 break;
7296 se_time = got_object_tag_get_tagger_time(se_tag);
7297 got_object_tag_close(se_tag);
7299 if (se_time > re_time) {
7300 err = got_reflist_entry_dup(&new, re);
7301 if (err)
7302 return err;
7303 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7304 break;
7306 se = STAILQ_NEXT(se, entry);
7307 continue;
7310 done:
7311 return err;
7313 #endif
7315 static const struct got_error *
7316 get_tag_refname(char **refname, const char *tag_name)
7318 const struct got_error *err;
7320 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7321 *refname = strdup(tag_name);
7322 if (*refname == NULL)
7323 return got_error_from_errno("strdup");
7324 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7325 err = got_error_from_errno("asprintf");
7326 *refname = NULL;
7327 return err;
7330 return NULL;
7333 static const struct got_error *
7334 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7335 const char *allowed_signers, const char *revoked_signers, int verbosity)
7337 static const struct got_error *err = NULL;
7338 struct got_reflist_head refs;
7339 struct got_reflist_entry *re;
7340 char *wanted_refname = NULL;
7341 int bad_sigs = 0;
7343 TAILQ_INIT(&refs);
7345 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7346 if (err)
7347 return err;
7349 if (tag_name) {
7350 struct got_reference *ref;
7351 err = get_tag_refname(&wanted_refname, tag_name);
7352 if (err)
7353 goto done;
7354 /* Wanted tag reference should exist. */
7355 err = got_ref_open(&ref, repo, wanted_refname, 0);
7356 if (err)
7357 goto done;
7358 got_ref_close(ref);
7361 TAILQ_FOREACH(re, &refs, entry) {
7362 const char *refname;
7363 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7364 char datebuf[26];
7365 const char *tagger, *ssh_sig = NULL;
7366 char *sig_msg = NULL;
7367 time_t tagger_time;
7368 struct got_object_id *id;
7369 struct got_tag_object *tag;
7370 struct got_commit_object *commit = NULL;
7372 refname = got_ref_get_name(re->ref);
7373 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7374 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7375 continue;
7376 refname += 10;
7377 refstr = got_ref_to_str(re->ref);
7378 if (refstr == NULL) {
7379 err = got_error_from_errno("got_ref_to_str");
7380 break;
7383 err = got_ref_resolve(&id, repo, re->ref);
7384 if (err)
7385 break;
7386 err = got_object_open_as_tag(&tag, repo, id);
7387 if (err) {
7388 if (err->code != GOT_ERR_OBJ_TYPE) {
7389 free(id);
7390 break;
7392 /* "lightweight" tag */
7393 err = got_object_open_as_commit(&commit, repo, id);
7394 if (err) {
7395 free(id);
7396 break;
7398 tagger = got_object_commit_get_committer(commit);
7399 tagger_time =
7400 got_object_commit_get_committer_time(commit);
7401 err = got_object_id_str(&id_str, id);
7402 free(id);
7403 if (err)
7404 break;
7405 } else {
7406 free(id);
7407 tagger = got_object_tag_get_tagger(tag);
7408 tagger_time = got_object_tag_get_tagger_time(tag);
7409 err = got_object_id_str(&id_str,
7410 got_object_tag_get_object_id(tag));
7411 if (err)
7412 break;
7415 if (tag && verify_tags) {
7416 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7417 got_object_tag_get_message(tag));
7418 if (ssh_sig && allowed_signers == NULL) {
7419 err = got_error_msg(
7420 GOT_ERR_VERIFY_TAG_SIGNATURE,
7421 "SSH signature verification requires "
7422 "setting allowed_signers in "
7423 "got.conf(5)");
7424 break;
7428 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7429 free(refstr);
7430 printf("from: %s\n", tagger);
7431 datestr = get_datestr(&tagger_time, datebuf);
7432 if (datestr)
7433 printf("date: %s UTC\n", datestr);
7434 if (commit)
7435 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7436 else {
7437 switch (got_object_tag_get_object_type(tag)) {
7438 case GOT_OBJ_TYPE_BLOB:
7439 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7440 id_str);
7441 break;
7442 case GOT_OBJ_TYPE_TREE:
7443 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7444 id_str);
7445 break;
7446 case GOT_OBJ_TYPE_COMMIT:
7447 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7448 id_str);
7449 break;
7450 case GOT_OBJ_TYPE_TAG:
7451 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7452 id_str);
7453 break;
7454 default:
7455 break;
7458 free(id_str);
7460 if (ssh_sig) {
7461 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7462 allowed_signers, revoked_signers, verbosity);
7463 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7464 bad_sigs = 1;
7465 else if (err)
7466 break;
7467 printf("signature: %s", sig_msg);
7468 free(sig_msg);
7469 sig_msg = NULL;
7472 if (commit) {
7473 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7474 if (err)
7475 break;
7476 got_object_commit_close(commit);
7477 } else {
7478 tagmsg0 = strdup(got_object_tag_get_message(tag));
7479 got_object_tag_close(tag);
7480 if (tagmsg0 == NULL) {
7481 err = got_error_from_errno("strdup");
7482 break;
7486 tagmsg = tagmsg0;
7487 do {
7488 line = strsep(&tagmsg, "\n");
7489 if (line)
7490 printf(" %s\n", line);
7491 } while (line);
7492 free(tagmsg0);
7494 done:
7495 got_ref_list_free(&refs);
7496 free(wanted_refname);
7498 if (err == NULL && bad_sigs)
7499 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7500 return err;
7503 static const struct got_error *
7504 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7505 const char *tag_name, const char *repo_path)
7507 const struct got_error *err = NULL;
7508 char *template = NULL, *initial_content = NULL;
7509 char *editor = NULL;
7510 int initial_content_len;
7511 int fd = -1;
7513 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7514 err = got_error_from_errno("asprintf");
7515 goto done;
7518 initial_content_len = asprintf(&initial_content,
7519 "\n# tagging commit %s as %s\n",
7520 commit_id_str, tag_name);
7521 if (initial_content_len == -1) {
7522 err = got_error_from_errno("asprintf");
7523 goto done;
7526 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7527 if (err)
7528 goto done;
7530 if (write(fd, initial_content, initial_content_len) == -1) {
7531 err = got_error_from_errno2("write", *tagmsg_path);
7532 goto done;
7534 if (close(fd) == -1) {
7535 err = got_error_from_errno2("close", *tagmsg_path);
7536 goto done;
7538 fd = -1;
7540 err = get_editor(&editor);
7541 if (err)
7542 goto done;
7543 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7544 initial_content_len, 1);
7545 done:
7546 free(initial_content);
7547 free(template);
7548 free(editor);
7550 if (fd != -1 && close(fd) == -1 && err == NULL)
7551 err = got_error_from_errno2("close", *tagmsg_path);
7553 if (err) {
7554 free(*tagmsg);
7555 *tagmsg = NULL;
7557 return err;
7560 static const struct got_error *
7561 add_tag(struct got_repository *repo, const char *tagger,
7562 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7563 const char *signer_id, int verbosity)
7565 const struct got_error *err = NULL;
7566 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7567 char *label = NULL, *commit_id_str = NULL;
7568 struct got_reference *ref = NULL;
7569 char *refname = NULL, *tagmsg = NULL;
7570 char *tagmsg_path = NULL, *tag_id_str = NULL;
7571 int preserve_tagmsg = 0;
7572 struct got_reflist_head refs;
7574 TAILQ_INIT(&refs);
7577 * Don't let the user create a tag name with a leading '-'.
7578 * While technically a valid reference name, this case is usually
7579 * an unintended typo.
7581 if (tag_name[0] == '-')
7582 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7584 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7585 if (err)
7586 goto done;
7588 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7589 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7590 if (err)
7591 goto done;
7593 err = got_object_id_str(&commit_id_str, commit_id);
7594 if (err)
7595 goto done;
7597 err = get_tag_refname(&refname, tag_name);
7598 if (err)
7599 goto done;
7600 if (strncmp("refs/tags/", tag_name, 10) == 0)
7601 tag_name += 10;
7603 err = got_ref_open(&ref, repo, refname, 0);
7604 if (err == NULL) {
7605 err = got_error(GOT_ERR_TAG_EXISTS);
7606 goto done;
7607 } else if (err->code != GOT_ERR_NOT_REF)
7608 goto done;
7610 if (tagmsg_arg == NULL) {
7611 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7612 tag_name, got_repo_get_path(repo));
7613 if (err) {
7614 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7615 tagmsg_path != NULL)
7616 preserve_tagmsg = 1;
7617 goto done;
7619 /* Editor is done; we can now apply unveil(2) */
7620 err = got_sigs_apply_unveil();
7621 if (err)
7622 goto done;
7623 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7624 if (err)
7625 goto done;
7628 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7629 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7630 verbosity);
7631 if (err) {
7632 if (tagmsg_path)
7633 preserve_tagmsg = 1;
7634 goto done;
7637 err = got_ref_alloc(&ref, refname, tag_id);
7638 if (err) {
7639 if (tagmsg_path)
7640 preserve_tagmsg = 1;
7641 goto done;
7644 err = got_ref_write(ref, repo);
7645 if (err) {
7646 if (tagmsg_path)
7647 preserve_tagmsg = 1;
7648 goto done;
7651 err = got_object_id_str(&tag_id_str, tag_id);
7652 if (err) {
7653 if (tagmsg_path)
7654 preserve_tagmsg = 1;
7655 goto done;
7657 printf("Created tag %s\n", tag_id_str);
7658 done:
7659 if (preserve_tagmsg) {
7660 fprintf(stderr, "%s: tag message preserved in %s\n",
7661 getprogname(), tagmsg_path);
7662 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7663 err = got_error_from_errno2("unlink", tagmsg_path);
7664 free(tag_id_str);
7665 if (ref)
7666 got_ref_close(ref);
7667 free(commit_id);
7668 free(commit_id_str);
7669 free(refname);
7670 free(tagmsg);
7671 free(tagmsg_path);
7672 got_ref_list_free(&refs);
7673 return err;
7676 static const struct got_error *
7677 cmd_tag(int argc, char *argv[])
7679 const struct got_error *error = NULL;
7680 struct got_repository *repo = NULL;
7681 struct got_worktree *worktree = NULL;
7682 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7683 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7684 char *allowed_signers = NULL, *revoked_signers = NULL;
7685 const char *signer_id = NULL;
7686 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7687 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7688 int *pack_fds = NULL;
7690 #ifndef PROFILE
7691 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7692 "sendfd unveil", NULL) == -1)
7693 err(1, "pledge");
7694 #endif
7696 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7697 switch (ch) {
7698 case 'c':
7699 commit_id_arg = optarg;
7700 break;
7701 case 'l':
7702 do_list = 1;
7703 break;
7704 case 'm':
7705 tagmsg = optarg;
7706 break;
7707 case 'r':
7708 repo_path = realpath(optarg, NULL);
7709 if (repo_path == NULL) {
7710 error = got_error_from_errno2("realpath",
7711 optarg);
7712 goto done;
7714 got_path_strip_trailing_slashes(repo_path);
7715 break;
7716 case 's':
7717 signer_id = optarg;
7718 break;
7719 case 'V':
7720 verify_tags = 1;
7721 break;
7722 case 'v':
7723 if (verbosity < 0)
7724 verbosity = 0;
7725 else if (verbosity < 3)
7726 verbosity++;
7727 break;
7728 default:
7729 usage_tag();
7730 /* NOTREACHED */
7734 argc -= optind;
7735 argv += optind;
7737 if (do_list || verify_tags) {
7738 if (commit_id_arg != NULL)
7739 errx(1,
7740 "-c option can only be used when creating a tag");
7741 if (tagmsg) {
7742 if (do_list)
7743 option_conflict('l', 'm');
7744 else
7745 option_conflict('V', 'm');
7747 if (signer_id) {
7748 if (do_list)
7749 option_conflict('l', 's');
7750 else
7751 option_conflict('V', 's');
7753 if (argc > 1)
7754 usage_tag();
7755 } else if (argc != 1)
7756 usage_tag();
7758 if (argc == 1)
7759 tag_name = argv[0];
7761 cwd = getcwd(NULL, 0);
7762 if (cwd == NULL) {
7763 error = got_error_from_errno("getcwd");
7764 goto done;
7767 error = got_repo_pack_fds_open(&pack_fds);
7768 if (error != NULL)
7769 goto done;
7771 if (repo_path == NULL) {
7772 error = got_worktree_open(&worktree, cwd,
7773 GOT_WORKTREE_GOT_DIR);
7774 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7775 goto done;
7776 else
7777 error = NULL;
7778 if (worktree) {
7779 repo_path =
7780 strdup(got_worktree_get_repo_path(worktree));
7781 if (repo_path == NULL)
7782 error = got_error_from_errno("strdup");
7783 if (error)
7784 goto done;
7785 } else {
7786 repo_path = strdup(cwd);
7787 if (repo_path == NULL) {
7788 error = got_error_from_errno("strdup");
7789 goto done;
7794 if (do_list || verify_tags) {
7795 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7796 if (error != NULL)
7797 goto done;
7798 error = get_allowed_signers(&allowed_signers, repo, worktree);
7799 if (error)
7800 goto done;
7801 error = get_revoked_signers(&revoked_signers, repo, worktree);
7802 if (error)
7803 goto done;
7804 if (worktree) {
7805 /* Release work tree lock. */
7806 got_worktree_close(worktree);
7807 worktree = NULL;
7811 * Remove "cpath" promise unless needed for signature tmpfile
7812 * creation.
7814 if (verify_tags)
7815 got_sigs_apply_unveil();
7816 else {
7817 #ifndef PROFILE
7818 if (pledge("stdio rpath wpath flock proc exec sendfd "
7819 "unveil", NULL) == -1)
7820 err(1, "pledge");
7821 #endif
7823 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7824 if (error)
7825 goto done;
7826 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7827 revoked_signers, verbosity);
7828 } else {
7829 error = get_gitconfig_path(&gitconfig_path);
7830 if (error)
7831 goto done;
7832 error = got_repo_open(&repo, repo_path, gitconfig_path,
7833 pack_fds);
7834 if (error != NULL)
7835 goto done;
7837 error = get_author(&tagger, repo, worktree);
7838 if (error)
7839 goto done;
7840 if (signer_id == NULL)
7841 signer_id = get_signer_id(repo, worktree);
7843 if (tagmsg) {
7844 if (signer_id) {
7845 error = got_sigs_apply_unveil();
7846 if (error)
7847 goto done;
7849 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7850 if (error)
7851 goto done;
7854 if (commit_id_arg == NULL) {
7855 struct got_reference *head_ref;
7856 struct got_object_id *commit_id;
7857 error = got_ref_open(&head_ref, repo,
7858 worktree ? got_worktree_get_head_ref_name(worktree)
7859 : GOT_REF_HEAD, 0);
7860 if (error)
7861 goto done;
7862 error = got_ref_resolve(&commit_id, repo, head_ref);
7863 got_ref_close(head_ref);
7864 if (error)
7865 goto done;
7866 error = got_object_id_str(&commit_id_str, commit_id);
7867 free(commit_id);
7868 if (error)
7869 goto done;
7870 } else {
7871 error = got_keyword_to_idstr(&keyword_idstr,
7872 commit_id_arg, repo, worktree);
7873 if (error != NULL)
7874 goto done;
7875 commit_id_str = keyword_idstr;
7878 if (worktree) {
7879 /* Release work tree lock. */
7880 got_worktree_close(worktree);
7881 worktree = NULL;
7884 error = add_tag(repo, tagger, tag_name,
7885 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7886 signer_id, verbosity);
7888 done:
7889 if (repo) {
7890 const struct got_error *close_err = got_repo_close(repo);
7891 if (error == NULL)
7892 error = close_err;
7894 if (worktree)
7895 got_worktree_close(worktree);
7896 if (pack_fds) {
7897 const struct got_error *pack_err =
7898 got_repo_pack_fds_close(pack_fds);
7899 if (error == NULL)
7900 error = pack_err;
7902 free(cwd);
7903 free(repo_path);
7904 free(gitconfig_path);
7905 free(commit_id_str);
7906 free(tagger);
7907 free(allowed_signers);
7908 free(revoked_signers);
7909 return error;
7912 __dead static void
7913 usage_add(void)
7915 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7916 exit(1);
7919 static const struct got_error *
7920 add_progress(void *arg, unsigned char status, const char *path)
7922 while (path[0] == '/')
7923 path++;
7924 printf("%c %s\n", status, path);
7925 return NULL;
7928 static const struct got_error *
7929 cmd_add(int argc, char *argv[])
7931 const struct got_error *error = NULL;
7932 struct got_repository *repo = NULL;
7933 struct got_worktree *worktree = NULL;
7934 char *cwd = NULL;
7935 struct got_pathlist_head paths;
7936 struct got_pathlist_entry *pe;
7937 int ch, can_recurse = 0, no_ignores = 0;
7938 int *pack_fds = NULL;
7940 TAILQ_INIT(&paths);
7942 #ifndef PROFILE
7943 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7944 NULL) == -1)
7945 err(1, "pledge");
7946 #endif
7948 while ((ch = getopt(argc, argv, "IR")) != -1) {
7949 switch (ch) {
7950 case 'I':
7951 no_ignores = 1;
7952 break;
7953 case 'R':
7954 can_recurse = 1;
7955 break;
7956 default:
7957 usage_add();
7958 /* NOTREACHED */
7962 argc -= optind;
7963 argv += optind;
7965 if (argc < 1)
7966 usage_add();
7968 cwd = getcwd(NULL, 0);
7969 if (cwd == NULL) {
7970 error = got_error_from_errno("getcwd");
7971 goto done;
7974 error = got_repo_pack_fds_open(&pack_fds);
7975 if (error != NULL)
7976 goto done;
7978 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7979 if (error) {
7980 if (error->code == GOT_ERR_NOT_WORKTREE)
7981 error = wrap_not_worktree_error(error, "add", cwd);
7982 goto done;
7985 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7986 NULL, pack_fds);
7987 if (error != NULL)
7988 goto done;
7990 error = apply_unveil(got_repo_get_path(repo), 1,
7991 got_worktree_get_root_path(worktree));
7992 if (error)
7993 goto done;
7995 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7996 if (error)
7997 goto done;
7999 if (!can_recurse) {
8000 char *ondisk_path;
8001 struct stat sb;
8002 TAILQ_FOREACH(pe, &paths, entry) {
8003 if (asprintf(&ondisk_path, "%s/%s",
8004 got_worktree_get_root_path(worktree),
8005 pe->path) == -1) {
8006 error = got_error_from_errno("asprintf");
8007 goto done;
8009 if (lstat(ondisk_path, &sb) == -1) {
8010 if (errno == ENOENT) {
8011 free(ondisk_path);
8012 continue;
8014 error = got_error_from_errno2("lstat",
8015 ondisk_path);
8016 free(ondisk_path);
8017 goto done;
8019 free(ondisk_path);
8020 if (S_ISDIR(sb.st_mode)) {
8021 error = got_error_msg(GOT_ERR_BAD_PATH,
8022 "adding directories requires -R option");
8023 goto done;
8028 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8029 NULL, repo, no_ignores);
8030 done:
8031 if (repo) {
8032 const struct got_error *close_err = got_repo_close(repo);
8033 if (error == NULL)
8034 error = close_err;
8036 if (worktree)
8037 got_worktree_close(worktree);
8038 if (pack_fds) {
8039 const struct got_error *pack_err =
8040 got_repo_pack_fds_close(pack_fds);
8041 if (error == NULL)
8042 error = pack_err;
8044 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8045 free(cwd);
8046 return error;
8049 __dead static void
8050 usage_remove(void)
8052 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8053 getprogname());
8054 exit(1);
8057 static const struct got_error *
8058 print_remove_status(void *arg, unsigned char status,
8059 unsigned char staged_status, const char *path)
8061 while (path[0] == '/')
8062 path++;
8063 if (status == GOT_STATUS_NONEXISTENT)
8064 return NULL;
8065 if (status == staged_status && (status == GOT_STATUS_DELETE))
8066 status = GOT_STATUS_NO_CHANGE;
8067 printf("%c%c %s\n", status, staged_status, path);
8068 return NULL;
8071 static const struct got_error *
8072 cmd_remove(int argc, char *argv[])
8074 const struct got_error *error = NULL;
8075 struct got_worktree *worktree = NULL;
8076 struct got_repository *repo = NULL;
8077 const char *status_codes = NULL;
8078 char *cwd = NULL;
8079 struct got_pathlist_head paths;
8080 struct got_pathlist_entry *pe;
8081 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8082 int ignore_missing_paths = 0;
8083 int *pack_fds = NULL;
8085 TAILQ_INIT(&paths);
8087 #ifndef PROFILE
8088 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8089 NULL) == -1)
8090 err(1, "pledge");
8091 #endif
8093 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8094 switch (ch) {
8095 case 'f':
8096 delete_local_mods = 1;
8097 ignore_missing_paths = 1;
8098 break;
8099 case 'k':
8100 keep_on_disk = 1;
8101 break;
8102 case 'R':
8103 can_recurse = 1;
8104 break;
8105 case 's':
8106 for (i = 0; optarg[i] != '\0'; i++) {
8107 switch (optarg[i]) {
8108 case GOT_STATUS_MODIFY:
8109 delete_local_mods = 1;
8110 break;
8111 case GOT_STATUS_MISSING:
8112 ignore_missing_paths = 1;
8113 break;
8114 default:
8115 errx(1, "invalid status code '%c'",
8116 optarg[i]);
8119 status_codes = optarg;
8120 break;
8121 default:
8122 usage_remove();
8123 /* NOTREACHED */
8127 argc -= optind;
8128 argv += optind;
8130 if (argc < 1)
8131 usage_remove();
8133 cwd = getcwd(NULL, 0);
8134 if (cwd == NULL) {
8135 error = got_error_from_errno("getcwd");
8136 goto done;
8139 error = got_repo_pack_fds_open(&pack_fds);
8140 if (error != NULL)
8141 goto done;
8143 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8144 if (error) {
8145 if (error->code == GOT_ERR_NOT_WORKTREE)
8146 error = wrap_not_worktree_error(error, "remove", cwd);
8147 goto done;
8150 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8151 NULL, pack_fds);
8152 if (error)
8153 goto done;
8155 error = apply_unveil(got_repo_get_path(repo), 1,
8156 got_worktree_get_root_path(worktree));
8157 if (error)
8158 goto done;
8160 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8161 if (error)
8162 goto done;
8164 if (!can_recurse) {
8165 char *ondisk_path;
8166 struct stat sb;
8167 TAILQ_FOREACH(pe, &paths, entry) {
8168 if (asprintf(&ondisk_path, "%s/%s",
8169 got_worktree_get_root_path(worktree),
8170 pe->path) == -1) {
8171 error = got_error_from_errno("asprintf");
8172 goto done;
8174 if (lstat(ondisk_path, &sb) == -1) {
8175 if (errno == ENOENT) {
8176 free(ondisk_path);
8177 continue;
8179 error = got_error_from_errno2("lstat",
8180 ondisk_path);
8181 free(ondisk_path);
8182 goto done;
8184 free(ondisk_path);
8185 if (S_ISDIR(sb.st_mode)) {
8186 error = got_error_msg(GOT_ERR_BAD_PATH,
8187 "removing directories requires -R option");
8188 goto done;
8193 error = got_worktree_schedule_delete(worktree, &paths,
8194 delete_local_mods, status_codes, print_remove_status, NULL,
8195 repo, keep_on_disk, ignore_missing_paths);
8196 done:
8197 if (repo) {
8198 const struct got_error *close_err = got_repo_close(repo);
8199 if (error == NULL)
8200 error = close_err;
8202 if (worktree)
8203 got_worktree_close(worktree);
8204 if (pack_fds) {
8205 const struct got_error *pack_err =
8206 got_repo_pack_fds_close(pack_fds);
8207 if (error == NULL)
8208 error = pack_err;
8210 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8211 free(cwd);
8212 return error;
8215 __dead static void
8216 usage_patch(void)
8218 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8219 "[patchfile]\n", getprogname());
8220 exit(1);
8223 static const struct got_error *
8224 patch_from_stdin(int *patchfd)
8226 const struct got_error *err = NULL;
8227 ssize_t r;
8228 char buf[BUFSIZ];
8229 sig_t sighup, sigint, sigquit;
8231 *patchfd = got_opentempfd();
8232 if (*patchfd == -1)
8233 return got_error_from_errno("got_opentempfd");
8235 sighup = signal(SIGHUP, SIG_DFL);
8236 sigint = signal(SIGINT, SIG_DFL);
8237 sigquit = signal(SIGQUIT, SIG_DFL);
8239 for (;;) {
8240 r = read(0, buf, sizeof(buf));
8241 if (r == -1) {
8242 err = got_error_from_errno("read");
8243 break;
8245 if (r == 0)
8246 break;
8247 if (write(*patchfd, buf, r) == -1) {
8248 err = got_error_from_errno("write");
8249 break;
8253 signal(SIGHUP, sighup);
8254 signal(SIGINT, sigint);
8255 signal(SIGQUIT, sigquit);
8257 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8258 err = got_error_from_errno("lseek");
8260 if (err != NULL) {
8261 close(*patchfd);
8262 *patchfd = -1;
8265 return err;
8268 struct got_patch_progress_arg {
8269 int did_something;
8270 int conflicts;
8271 int rejects;
8274 static const struct got_error *
8275 patch_progress(void *arg, const char *old, const char *new,
8276 unsigned char status, const struct got_error *error, int old_from,
8277 int old_lines, int new_from, int new_lines, int offset,
8278 int ws_mangled, const struct got_error *hunk_err)
8280 const char *path = new == NULL ? old : new;
8281 struct got_patch_progress_arg *a = arg;
8283 while (*path == '/')
8284 path++;
8286 if (status != GOT_STATUS_NO_CHANGE &&
8287 status != 0 /* per-hunk progress */) {
8288 printf("%c %s\n", status, path);
8289 a->did_something = 1;
8292 if (hunk_err == NULL) {
8293 if (status == GOT_STATUS_CANNOT_UPDATE)
8294 a->rejects++;
8295 else if (status == GOT_STATUS_CONFLICT)
8296 a->conflicts++;
8299 if (error != NULL)
8300 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8302 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8303 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8304 old_lines, new_from, new_lines);
8305 if (hunk_err != NULL)
8306 printf("%s\n", hunk_err->msg);
8307 else if (offset != 0)
8308 printf("applied with offset %d\n", offset);
8309 else
8310 printf("hunk contains mangled whitespace\n");
8313 return NULL;
8316 static void
8317 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8319 if (!ppa->did_something)
8320 return;
8322 if (ppa->conflicts > 0)
8323 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8325 if (ppa->rejects > 0) {
8326 printf("Files where patch failed to apply: %d\n",
8327 ppa->rejects);
8331 static const struct got_error *
8332 cmd_patch(int argc, char *argv[])
8334 const struct got_error *error = NULL, *close_error = NULL;
8335 struct got_worktree *worktree = NULL;
8336 struct got_repository *repo = NULL;
8337 struct got_reflist_head refs;
8338 struct got_object_id *commit_id = NULL;
8339 const char *commit_id_str = NULL;
8340 struct stat sb;
8341 const char *errstr;
8342 char *cwd = NULL, *keyword_idstr = NULL;
8343 int ch, nop = 0, strip = -1, reverse = 0;
8344 int patchfd;
8345 int *pack_fds = NULL;
8346 struct got_patch_progress_arg ppa;
8348 TAILQ_INIT(&refs);
8350 #ifndef PROFILE
8351 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8352 "unveil", NULL) == -1)
8353 err(1, "pledge");
8354 #endif
8356 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8357 switch (ch) {
8358 case 'c':
8359 commit_id_str = optarg;
8360 break;
8361 case 'n':
8362 nop = 1;
8363 break;
8364 case 'p':
8365 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8366 if (errstr != NULL)
8367 errx(1, "pathname strip count is %s: %s",
8368 errstr, optarg);
8369 break;
8370 case 'R':
8371 reverse = 1;
8372 break;
8373 default:
8374 usage_patch();
8375 /* NOTREACHED */
8379 argc -= optind;
8380 argv += optind;
8382 if (argc == 0) {
8383 error = patch_from_stdin(&patchfd);
8384 if (error)
8385 return error;
8386 } else if (argc == 1) {
8387 patchfd = open(argv[0], O_RDONLY);
8388 if (patchfd == -1) {
8389 error = got_error_from_errno2("open", argv[0]);
8390 return error;
8392 if (fstat(patchfd, &sb) == -1) {
8393 error = got_error_from_errno2("fstat", argv[0]);
8394 goto done;
8396 if (!S_ISREG(sb.st_mode)) {
8397 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8398 goto done;
8400 } else
8401 usage_patch();
8403 if ((cwd = getcwd(NULL, 0)) == NULL) {
8404 error = got_error_from_errno("getcwd");
8405 goto done;
8408 error = got_repo_pack_fds_open(&pack_fds);
8409 if (error != NULL)
8410 goto done;
8412 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8413 if (error != NULL)
8414 goto done;
8416 const char *repo_path = got_worktree_get_repo_path(worktree);
8417 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8418 if (error != NULL)
8419 goto done;
8421 error = apply_unveil(got_repo_get_path(repo), 0,
8422 got_worktree_get_root_path(worktree));
8423 if (error != NULL)
8424 goto done;
8426 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8427 if (error)
8428 goto done;
8430 if (commit_id_str != NULL) {
8431 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8432 repo, worktree);
8433 if (error != NULL)
8434 goto done;
8436 error = got_repo_match_object_id(&commit_id, NULL,
8437 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8438 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8439 if (error)
8440 goto done;
8443 memset(&ppa, 0, sizeof(ppa));
8444 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8445 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8446 print_patch_progress_stats(&ppa);
8447 done:
8448 got_ref_list_free(&refs);
8449 free(keyword_idstr);
8450 free(commit_id);
8451 if (repo) {
8452 close_error = got_repo_close(repo);
8453 if (error == NULL)
8454 error = close_error;
8456 if (worktree != NULL) {
8457 close_error = got_worktree_close(worktree);
8458 if (error == NULL)
8459 error = close_error;
8461 if (pack_fds) {
8462 const struct got_error *pack_err =
8463 got_repo_pack_fds_close(pack_fds);
8464 if (error == NULL)
8465 error = pack_err;
8467 free(cwd);
8468 return error;
8471 __dead static void
8472 usage_revert(void)
8474 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8475 getprogname());
8476 exit(1);
8479 static const struct got_error *
8480 revert_progress(void *arg, unsigned char status, const char *path)
8482 if (status == GOT_STATUS_UNVERSIONED)
8483 return NULL;
8485 while (path[0] == '/')
8486 path++;
8487 printf("%c %s\n", status, path);
8488 return NULL;
8491 struct choose_patch_arg {
8492 FILE *patch_script_file;
8493 const char *action;
8496 static const struct got_error *
8497 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8498 int nchanges, const char *action)
8500 const struct got_error *err;
8501 char *line = NULL;
8502 size_t linesize = 0;
8503 ssize_t linelen;
8505 switch (status) {
8506 case GOT_STATUS_ADD:
8507 printf("A %s\n%s this addition? [y/n] ", path, action);
8508 break;
8509 case GOT_STATUS_DELETE:
8510 printf("D %s\n%s this deletion? [y/n] ", path, action);
8511 break;
8512 case GOT_STATUS_MODIFY:
8513 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8514 return got_error_from_errno("fseek");
8515 printf(GOT_COMMIT_SEP_STR);
8516 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8517 printf("%s", line);
8518 if (linelen == -1 && ferror(patch_file)) {
8519 err = got_error_from_errno("getline");
8520 free(line);
8521 return err;
8523 free(line);
8524 printf(GOT_COMMIT_SEP_STR);
8525 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8526 path, n, nchanges, action);
8527 break;
8528 default:
8529 return got_error_path(path, GOT_ERR_FILE_STATUS);
8532 fflush(stdout);
8533 return NULL;
8536 static const struct got_error *
8537 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8538 FILE *patch_file, int n, int nchanges)
8540 const struct got_error *err = NULL;
8541 char *line = NULL;
8542 size_t linesize = 0;
8543 ssize_t linelen;
8544 int resp = ' ';
8545 struct choose_patch_arg *a = arg;
8547 *choice = GOT_PATCH_CHOICE_NONE;
8549 if (a->patch_script_file) {
8550 char *nl;
8551 err = show_change(status, path, patch_file, n, nchanges,
8552 a->action);
8553 if (err)
8554 return err;
8555 linelen = getline(&line, &linesize, a->patch_script_file);
8556 if (linelen == -1) {
8557 if (ferror(a->patch_script_file))
8558 return got_error_from_errno("getline");
8559 return NULL;
8561 nl = strchr(line, '\n');
8562 if (nl)
8563 *nl = '\0';
8564 if (strcmp(line, "y") == 0) {
8565 *choice = GOT_PATCH_CHOICE_YES;
8566 printf("y\n");
8567 } else if (strcmp(line, "n") == 0) {
8568 *choice = GOT_PATCH_CHOICE_NO;
8569 printf("n\n");
8570 } else if (strcmp(line, "q") == 0 &&
8571 status == GOT_STATUS_MODIFY) {
8572 *choice = GOT_PATCH_CHOICE_QUIT;
8573 printf("q\n");
8574 } else
8575 printf("invalid response '%s'\n", line);
8576 free(line);
8577 return NULL;
8580 while (resp != 'y' && resp != 'n' && resp != 'q') {
8581 err = show_change(status, path, patch_file, n, nchanges,
8582 a->action);
8583 if (err)
8584 return err;
8585 resp = getchar();
8586 if (resp == '\n')
8587 resp = getchar();
8588 if (status == GOT_STATUS_MODIFY) {
8589 if (resp != 'y' && resp != 'n' && resp != 'q') {
8590 printf("invalid response '%c'\n", resp);
8591 resp = ' ';
8593 } else if (resp != 'y' && resp != 'n') {
8594 printf("invalid response '%c'\n", resp);
8595 resp = ' ';
8599 if (resp == 'y')
8600 *choice = GOT_PATCH_CHOICE_YES;
8601 else if (resp == 'n')
8602 *choice = GOT_PATCH_CHOICE_NO;
8603 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8604 *choice = GOT_PATCH_CHOICE_QUIT;
8606 return NULL;
8609 struct wt_commitable_path_arg {
8610 struct got_pathlist_head *commit_paths;
8611 int *has_changes;
8615 * Shortcut work tree status callback to determine if the set of paths scanned
8616 * has at least one versioned path that is being modified and, if not NULL, is
8617 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8618 * soon as a path is passed with a status that satisfies this criteria.
8620 static const struct got_error *
8621 worktree_has_commitable_path(void *arg, unsigned char status,
8622 unsigned char staged_status, const char *path,
8623 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8624 struct got_object_id *commit_id, int dirfd, const char *de_name)
8626 struct wt_commitable_path_arg *a = arg;
8628 if (status == staged_status && (status == GOT_STATUS_DELETE))
8629 status = GOT_STATUS_NO_CHANGE;
8631 if (!(status == GOT_STATUS_NO_CHANGE ||
8632 status == GOT_STATUS_UNVERSIONED) ||
8633 staged_status != GOT_STATUS_NO_CHANGE) {
8634 if (a->commit_paths != NULL) {
8635 struct got_pathlist_entry *pe;
8637 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8638 if (strncmp(path, pe->path,
8639 pe->path_len) == 0) {
8640 *a->has_changes = 1;
8641 break;
8644 } else
8645 *a->has_changes = 1;
8647 if (*a->has_changes)
8648 return got_error(GOT_ERR_FILE_MODIFIED);
8651 return NULL;
8655 * Check that the changeset of the commit identified by id is
8656 * comprised of at least one modified path that is being committed.
8658 static const struct got_error *
8659 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8660 struct got_object_id *id, struct got_worktree *worktree,
8661 struct got_repository *repo)
8663 const struct got_error *err;
8664 struct got_pathlist_head paths;
8665 struct got_commit_object *commit = NULL, *pcommit = NULL;
8666 struct got_tree_object *tree = NULL, *ptree = NULL;
8667 struct got_object_qid *pid;
8669 TAILQ_INIT(&paths);
8671 err = got_object_open_as_commit(&commit, repo, id);
8672 if (err)
8673 goto done;
8675 err = got_object_open_as_tree(&tree, repo,
8676 got_object_commit_get_tree_id(commit));
8677 if (err)
8678 goto done;
8680 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8681 if (pid != NULL) {
8682 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8683 if (err)
8684 goto done;
8686 err = got_object_open_as_tree(&ptree, repo,
8687 got_object_commit_get_tree_id(pcommit));
8688 if (err)
8689 goto done;
8692 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8693 got_diff_tree_collect_changed_paths, &paths, 0);
8694 if (err)
8695 goto done;
8697 err = got_worktree_status(worktree, &paths, repo, 0,
8698 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8699 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8701 * At least one changed path in the referenced commit is
8702 * modified in the work tree, that's all we need to know!
8704 err = NULL;
8707 done:
8708 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8709 if (commit)
8710 got_object_commit_close(commit);
8711 if (pcommit)
8712 got_object_commit_close(pcommit);
8713 if (tree)
8714 got_object_tree_close(tree);
8715 if (ptree)
8716 got_object_tree_close(ptree);
8717 return err;
8721 * Remove any "logmsg" reference comprised entirely of paths that have
8722 * been reverted in this work tree. If any path in the logmsg ref changeset
8723 * remains in a changed state in the worktree, do not remove the reference.
8725 static const struct got_error *
8726 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8728 const struct got_error *err;
8729 struct got_reflist_head refs;
8730 struct got_reflist_entry *re;
8731 struct got_commit_object *commit = NULL;
8732 struct got_object_id *commit_id = NULL;
8733 struct wt_commitable_path_arg wcpa;
8734 char *uuidstr = NULL;
8736 TAILQ_INIT(&refs);
8738 err = got_worktree_get_uuid(&uuidstr, worktree);
8739 if (err)
8740 goto done;
8742 err = got_ref_list(&refs, repo, "refs/got/worktree",
8743 got_ref_cmp_by_name, repo);
8744 if (err)
8745 goto done;
8747 TAILQ_FOREACH(re, &refs, entry) {
8748 const char *refname;
8749 int has_changes = 0;
8751 refname = got_ref_get_name(re->ref);
8753 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8754 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8755 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8756 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8757 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8758 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8759 else
8760 continue;
8762 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8763 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8764 else
8765 continue;
8767 err = got_repo_match_object_id(&commit_id, NULL, refname,
8768 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8769 if (err)
8770 goto done;
8772 err = got_object_open_as_commit(&commit, repo, commit_id);
8773 if (err)
8774 goto done;
8776 wcpa.commit_paths = NULL;
8777 wcpa.has_changes = &has_changes;
8779 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8780 worktree, repo);
8781 if (err)
8782 goto done;
8784 if (!has_changes) {
8785 err = got_ref_delete(re->ref, repo);
8786 if (err)
8787 goto done;
8790 got_object_commit_close(commit);
8791 commit = NULL;
8792 free(commit_id);
8793 commit_id = NULL;
8796 done:
8797 free(uuidstr);
8798 free(commit_id);
8799 got_ref_list_free(&refs);
8800 if (commit)
8801 got_object_commit_close(commit);
8802 return err;
8805 static const struct got_error *
8806 cmd_revert(int argc, char *argv[])
8808 const struct got_error *error = NULL;
8809 struct got_worktree *worktree = NULL;
8810 struct got_repository *repo = NULL;
8811 char *cwd = NULL, *path = NULL;
8812 struct got_pathlist_head paths;
8813 struct got_pathlist_entry *pe;
8814 int ch, can_recurse = 0, pflag = 0;
8815 FILE *patch_script_file = NULL;
8816 const char *patch_script_path = NULL;
8817 struct choose_patch_arg cpa;
8818 int *pack_fds = NULL;
8820 TAILQ_INIT(&paths);
8822 #ifndef PROFILE
8823 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8824 "unveil", NULL) == -1)
8825 err(1, "pledge");
8826 #endif
8828 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8829 switch (ch) {
8830 case 'F':
8831 patch_script_path = optarg;
8832 break;
8833 case 'p':
8834 pflag = 1;
8835 break;
8836 case 'R':
8837 can_recurse = 1;
8838 break;
8839 default:
8840 usage_revert();
8841 /* NOTREACHED */
8845 argc -= optind;
8846 argv += optind;
8848 if (argc < 1)
8849 usage_revert();
8850 if (patch_script_path && !pflag)
8851 errx(1, "-F option can only be used together with -p option");
8853 cwd = getcwd(NULL, 0);
8854 if (cwd == NULL) {
8855 error = got_error_from_errno("getcwd");
8856 goto done;
8859 error = got_repo_pack_fds_open(&pack_fds);
8860 if (error != NULL)
8861 goto done;
8863 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8864 if (error) {
8865 if (error->code == GOT_ERR_NOT_WORKTREE)
8866 error = wrap_not_worktree_error(error, "revert", cwd);
8867 goto done;
8870 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8871 NULL, pack_fds);
8872 if (error != NULL)
8873 goto done;
8875 if (patch_script_path) {
8876 patch_script_file = fopen(patch_script_path, "re");
8877 if (patch_script_file == NULL) {
8878 error = got_error_from_errno2("fopen",
8879 patch_script_path);
8880 goto done;
8885 * XXX "c" perm needed on repo dir to delete merge references.
8887 error = apply_unveil(got_repo_get_path(repo), 0,
8888 got_worktree_get_root_path(worktree));
8889 if (error)
8890 goto done;
8892 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8893 if (error)
8894 goto done;
8896 if (!can_recurse) {
8897 char *ondisk_path;
8898 struct stat sb;
8899 TAILQ_FOREACH(pe, &paths, entry) {
8900 if (asprintf(&ondisk_path, "%s/%s",
8901 got_worktree_get_root_path(worktree),
8902 pe->path) == -1) {
8903 error = got_error_from_errno("asprintf");
8904 goto done;
8906 if (lstat(ondisk_path, &sb) == -1) {
8907 if (errno == ENOENT) {
8908 free(ondisk_path);
8909 continue;
8911 error = got_error_from_errno2("lstat",
8912 ondisk_path);
8913 free(ondisk_path);
8914 goto done;
8916 free(ondisk_path);
8917 if (S_ISDIR(sb.st_mode)) {
8918 error = got_error_msg(GOT_ERR_BAD_PATH,
8919 "reverting directories requires -R option");
8920 goto done;
8925 cpa.patch_script_file = patch_script_file;
8926 cpa.action = "revert";
8927 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8928 pflag ? choose_patch : NULL, &cpa, repo);
8930 error = rm_logmsg_ref(worktree, repo);
8931 done:
8932 if (patch_script_file && fclose(patch_script_file) == EOF &&
8933 error == NULL)
8934 error = got_error_from_errno2("fclose", patch_script_path);
8935 if (repo) {
8936 const struct got_error *close_err = got_repo_close(repo);
8937 if (error == NULL)
8938 error = close_err;
8940 if (worktree)
8941 got_worktree_close(worktree);
8942 if (pack_fds) {
8943 const struct got_error *pack_err =
8944 got_repo_pack_fds_close(pack_fds);
8945 if (error == NULL)
8946 error = pack_err;
8948 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8949 free(path);
8950 free(cwd);
8951 return error;
8954 __dead static void
8955 usage_commit(void)
8957 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8958 "[-m message] [path ...]\n", getprogname());
8959 exit(1);
8962 struct collect_commit_logmsg_arg {
8963 const char *cmdline_log;
8964 const char *prepared_log;
8965 const char *merged_log;
8966 int non_interactive;
8967 const char *editor;
8968 const char *worktree_path;
8969 const char *branch_name;
8970 const char *repo_path;
8971 char *logmsg_path;
8975 static const struct got_error *
8976 read_prepared_logmsg(char **logmsg, const char *path)
8978 const struct got_error *err = NULL;
8979 FILE *f = NULL;
8980 struct stat sb;
8981 size_t r;
8983 *logmsg = NULL;
8984 memset(&sb, 0, sizeof(sb));
8986 f = fopen(path, "re");
8987 if (f == NULL)
8988 return got_error_from_errno2("fopen", path);
8990 if (fstat(fileno(f), &sb) == -1) {
8991 err = got_error_from_errno2("fstat", path);
8992 goto done;
8994 if (sb.st_size == 0) {
8995 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8996 goto done;
8999 *logmsg = malloc(sb.st_size + 1);
9000 if (*logmsg == NULL) {
9001 err = got_error_from_errno("malloc");
9002 goto done;
9005 r = fread(*logmsg, 1, sb.st_size, f);
9006 if (r != sb.st_size) {
9007 if (ferror(f))
9008 err = got_error_from_errno2("fread", path);
9009 else
9010 err = got_error(GOT_ERR_IO);
9011 goto done;
9013 (*logmsg)[sb.st_size] = '\0';
9014 done:
9015 if (fclose(f) == EOF && err == NULL)
9016 err = got_error_from_errno2("fclose", path);
9017 if (err) {
9018 free(*logmsg);
9019 *logmsg = NULL;
9021 return err;
9024 static const struct got_error *
9025 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9026 const char *diff_path, char **logmsg, void *arg)
9028 char *initial_content = NULL;
9029 struct got_pathlist_entry *pe;
9030 const struct got_error *err = NULL;
9031 char *template = NULL;
9032 char *prepared_msg = NULL, *merged_msg = NULL;
9033 struct collect_commit_logmsg_arg *a = arg;
9034 int initial_content_len;
9035 int fd = -1;
9036 size_t len;
9038 /* if a message was specified on the command line, just use it */
9039 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9040 len = strlen(a->cmdline_log) + 1;
9041 *logmsg = malloc(len + 1);
9042 if (*logmsg == NULL)
9043 return got_error_from_errno("malloc");
9044 strlcpy(*logmsg, a->cmdline_log, len);
9045 return NULL;
9046 } else if (a->prepared_log != NULL && a->non_interactive)
9047 return read_prepared_logmsg(logmsg, a->prepared_log);
9049 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9050 return got_error_from_errno("asprintf");
9052 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9053 if (err)
9054 goto done;
9056 if (a->prepared_log) {
9057 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9058 if (err)
9059 goto done;
9060 } else if (a->merged_log) {
9061 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9062 if (err)
9063 goto done;
9066 initial_content_len = asprintf(&initial_content,
9067 "%s%s\n# changes to be committed on branch %s:\n",
9068 prepared_msg ? prepared_msg : "",
9069 merged_msg ? merged_msg : "", a->branch_name);
9070 if (initial_content_len == -1) {
9071 err = got_error_from_errno("asprintf");
9072 goto done;
9075 if (write(fd, initial_content, initial_content_len) == -1) {
9076 err = got_error_from_errno2("write", a->logmsg_path);
9077 goto done;
9080 TAILQ_FOREACH(pe, commitable_paths, entry) {
9081 struct got_commitable *ct = pe->data;
9082 dprintf(fd, "# %c %s\n",
9083 got_commitable_get_status(ct),
9084 got_commitable_get_path(ct));
9087 if (diff_path) {
9088 dprintf(fd, "# detailed changes can be viewed in %s\n",
9089 diff_path);
9092 if (close(fd) == -1) {
9093 err = got_error_from_errno2("close", a->logmsg_path);
9094 goto done;
9096 fd = -1;
9098 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9099 initial_content_len, a->prepared_log ? 0 : 1);
9100 done:
9101 free(initial_content);
9102 free(template);
9103 free(prepared_msg);
9104 free(merged_msg);
9106 if (fd != -1 && close(fd) == -1 && err == NULL)
9107 err = got_error_from_errno2("close", a->logmsg_path);
9109 /* Editor is done; we can now apply unveil(2) */
9110 if (err == NULL)
9111 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9112 if (err) {
9113 free(*logmsg);
9114 *logmsg = NULL;
9116 return err;
9119 static const struct got_error *
9120 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9121 const char *type, int has_content)
9123 const struct got_error *err = NULL;
9124 char *logmsg = NULL;
9126 err = got_object_commit_get_logmsg(&logmsg, commit);
9127 if (err)
9128 return err;
9130 if (fprintf(f, "%s# log message of %s commit %s:%s",
9131 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9132 err = got_ferror(f, GOT_ERR_IO);
9134 free(logmsg);
9135 return err;
9139 * Lookup "logmsg" references of backed-out and cherrypicked commits
9140 * belonging to the current work tree. If found, and the worktree has
9141 * at least one modified file that was changed in the referenced commit,
9142 * add its log message to a new temporary file at *logmsg_path.
9143 * Add all refs found to matched_refs to be scheduled for removal on
9144 * successful commit.
9146 static const struct got_error *
9147 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9148 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9149 struct got_repository *repo)
9151 const struct got_error *err;
9152 struct got_commit_object *commit = NULL;
9153 struct got_object_id *id = NULL;
9154 struct got_reflist_head refs;
9155 struct got_reflist_entry *re, *re_match;
9156 FILE *f = NULL;
9157 char *uuidstr = NULL;
9158 int added_logmsg = 0;
9160 TAILQ_INIT(&refs);
9162 *logmsg_path = NULL;
9164 err = got_worktree_get_uuid(&uuidstr, worktree);
9165 if (err)
9166 goto done;
9168 err = got_ref_list(&refs, repo, "refs/got/worktree",
9169 got_ref_cmp_by_name, repo);
9170 if (err)
9171 goto done;
9173 TAILQ_FOREACH(re, &refs, entry) {
9174 const char *refname, *type;
9175 struct wt_commitable_path_arg wcpa;
9176 int add_logmsg = 0;
9178 refname = got_ref_get_name(re->ref);
9180 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9181 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9182 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9183 type = "cherrypicked";
9184 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9185 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9186 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9187 type = "backed-out";
9188 } else
9189 continue;
9191 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9192 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9193 else
9194 continue;
9196 err = got_repo_match_object_id(&id, NULL, refname,
9197 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9198 if (err)
9199 goto done;
9201 err = got_object_open_as_commit(&commit, repo, id);
9202 if (err)
9203 goto done;
9205 wcpa.commit_paths = paths;
9206 wcpa.has_changes = &add_logmsg;
9208 err = commit_path_changed_in_worktree(&wcpa, id,
9209 worktree, repo);
9210 if (err)
9211 goto done;
9213 if (add_logmsg) {
9214 if (f == NULL) {
9215 err = got_opentemp_named(logmsg_path, &f,
9216 "got-commit-logmsg", "");
9217 if (err)
9218 goto done;
9220 err = cat_logmsg(f, commit, refname, type,
9221 added_logmsg);
9222 if (err)
9223 goto done;
9224 if (!added_logmsg)
9225 ++added_logmsg;
9227 err = got_reflist_entry_dup(&re_match, re);
9228 if (err)
9229 goto done;
9230 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9233 got_object_commit_close(commit);
9234 commit = NULL;
9235 free(id);
9236 id = NULL;
9239 done:
9240 free(id);
9241 free(uuidstr);
9242 got_ref_list_free(&refs);
9243 if (commit)
9244 got_object_commit_close(commit);
9245 if (f && fclose(f) == EOF && err == NULL)
9246 err = got_error_from_errno("fclose");
9247 if (!added_logmsg) {
9248 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9249 err = got_error_from_errno2("unlink", *logmsg_path);
9250 *logmsg_path = NULL;
9252 return err;
9255 static const struct got_error *
9256 cmd_commit(int argc, char *argv[])
9258 const struct got_error *error = NULL;
9259 struct got_worktree *worktree = NULL;
9260 struct got_repository *repo = NULL;
9261 char *cwd = NULL, *id_str = NULL;
9262 struct got_object_id *id = NULL;
9263 const char *logmsg = NULL;
9264 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9265 struct collect_commit_logmsg_arg cl_arg;
9266 const char *author = NULL;
9267 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9268 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9269 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9270 int show_diff = 1, commit_conflicts = 0;
9271 struct got_pathlist_head paths;
9272 struct got_reflist_head refs;
9273 struct got_reflist_entry *re;
9274 int *pack_fds = NULL;
9276 TAILQ_INIT(&refs);
9277 TAILQ_INIT(&paths);
9278 cl_arg.logmsg_path = NULL;
9280 #ifndef PROFILE
9281 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9282 "unveil", NULL) == -1)
9283 err(1, "pledge");
9284 #endif
9286 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9287 switch (ch) {
9288 case 'A':
9289 author = optarg;
9290 error = valid_author(author);
9291 if (error)
9292 return error;
9293 break;
9294 case 'C':
9295 commit_conflicts = 1;
9296 break;
9297 case 'F':
9298 if (logmsg != NULL)
9299 option_conflict('F', 'm');
9300 prepared_logmsg = realpath(optarg, NULL);
9301 if (prepared_logmsg == NULL)
9302 return got_error_from_errno2("realpath",
9303 optarg);
9304 break;
9305 case 'm':
9306 if (prepared_logmsg)
9307 option_conflict('m', 'F');
9308 logmsg = optarg;
9309 break;
9310 case 'N':
9311 non_interactive = 1;
9312 break;
9313 case 'n':
9314 show_diff = 0;
9315 break;
9316 case 'S':
9317 allow_bad_symlinks = 1;
9318 break;
9319 default:
9320 usage_commit();
9321 /* NOTREACHED */
9325 argc -= optind;
9326 argv += optind;
9328 cwd = getcwd(NULL, 0);
9329 if (cwd == NULL) {
9330 error = got_error_from_errno("getcwd");
9331 goto done;
9334 error = got_repo_pack_fds_open(&pack_fds);
9335 if (error != NULL)
9336 goto done;
9338 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9339 if (error) {
9340 if (error->code == GOT_ERR_NOT_WORKTREE)
9341 error = wrap_not_worktree_error(error, "commit", cwd);
9342 goto done;
9345 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9346 if (error)
9347 goto done;
9348 if (rebase_in_progress) {
9349 error = got_error(GOT_ERR_REBASING);
9350 goto done;
9353 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9354 worktree);
9355 if (error)
9356 goto done;
9358 error = get_gitconfig_path(&gitconfig_path);
9359 if (error)
9360 goto done;
9361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9362 gitconfig_path, pack_fds);
9363 if (error != NULL)
9364 goto done;
9366 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9367 if (error)
9368 goto done;
9369 if (merge_in_progress) {
9370 error = got_error(GOT_ERR_MERGE_BUSY);
9371 goto done;
9374 error = get_author(&committer, repo, worktree);
9375 if (error)
9376 goto done;
9378 if (author == NULL)
9379 author = committer;
9382 * unveil(2) traverses exec(2); if an editor is used we have
9383 * to apply unveil after the log message has been written.
9385 if (logmsg == NULL || strlen(logmsg) == 0)
9386 error = get_editor(&editor);
9387 else
9388 error = apply_unveil(got_repo_get_path(repo), 0,
9389 got_worktree_get_root_path(worktree));
9390 if (error)
9391 goto done;
9393 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9394 if (error)
9395 goto done;
9397 if (prepared_logmsg == NULL) {
9398 error = lookup_logmsg_ref(&merged_logmsg,
9399 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9400 if (error)
9401 goto done;
9404 cl_arg.editor = editor;
9405 cl_arg.cmdline_log = logmsg;
9406 cl_arg.prepared_log = prepared_logmsg;
9407 cl_arg.merged_log = merged_logmsg;
9408 cl_arg.non_interactive = non_interactive;
9409 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9410 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9411 if (!histedit_in_progress) {
9412 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9413 error = got_error(GOT_ERR_COMMIT_BRANCH);
9414 goto done;
9416 cl_arg.branch_name += 11;
9418 cl_arg.repo_path = got_repo_get_path(repo);
9419 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9420 allow_bad_symlinks, show_diff, commit_conflicts,
9421 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9422 if (error) {
9423 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9424 cl_arg.logmsg_path != NULL)
9425 preserve_logmsg = 1;
9426 goto done;
9429 error = got_object_id_str(&id_str, id);
9430 if (error)
9431 goto done;
9432 printf("Created commit %s\n", id_str);
9434 TAILQ_FOREACH(re, &refs, entry) {
9435 error = got_ref_delete(re->ref, repo);
9436 if (error)
9437 goto done;
9440 done:
9441 if (preserve_logmsg) {
9442 fprintf(stderr, "%s: log message preserved in %s\n",
9443 getprogname(), cl_arg.logmsg_path);
9444 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9445 error == NULL)
9446 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9447 free(cl_arg.logmsg_path);
9448 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9449 error = got_error_from_errno2("unlink", merged_logmsg);
9450 free(merged_logmsg);
9451 if (repo) {
9452 const struct got_error *close_err = got_repo_close(repo);
9453 if (error == NULL)
9454 error = close_err;
9456 if (worktree)
9457 got_worktree_close(worktree);
9458 if (pack_fds) {
9459 const struct got_error *pack_err =
9460 got_repo_pack_fds_close(pack_fds);
9461 if (error == NULL)
9462 error = pack_err;
9464 got_ref_list_free(&refs);
9465 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9466 free(cwd);
9467 free(id_str);
9468 free(gitconfig_path);
9469 free(editor);
9470 free(committer);
9471 free(prepared_logmsg);
9472 return error;
9475 __dead static void
9476 usage_send(void)
9478 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9479 "[-r repository-path] [-t tag] [remote-repository]\n",
9480 getprogname());
9481 exit(1);
9484 static void
9485 print_load_info(int print_colored, int print_found, int print_trees,
9486 int ncolored, int nfound, int ntrees)
9488 if (print_colored) {
9489 printf("%d commit%s colored", ncolored,
9490 ncolored == 1 ? "" : "s");
9492 if (print_found) {
9493 printf("%s%d object%s found",
9494 ncolored > 0 ? "; " : "",
9495 nfound, nfound == 1 ? "" : "s");
9497 if (print_trees) {
9498 printf("; %d tree%s scanned", ntrees,
9499 ntrees == 1 ? "" : "s");
9503 struct got_send_progress_arg {
9504 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9505 int verbosity;
9506 int last_ncolored;
9507 int last_nfound;
9508 int last_ntrees;
9509 int loading_done;
9510 int last_ncommits;
9511 int last_nobj_total;
9512 int last_p_deltify;
9513 int last_p_written;
9514 int last_p_sent;
9515 int printed_something;
9516 int sent_something;
9517 struct got_pathlist_head *delete_branches;
9520 static const struct got_error *
9521 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9522 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9523 int nobj_written, off_t bytes_sent, const char *refname,
9524 const char *errmsg, int success)
9526 struct got_send_progress_arg *a = arg;
9527 char scaled_packsize[FMT_SCALED_STRSIZE];
9528 char scaled_sent[FMT_SCALED_STRSIZE];
9529 int p_deltify = 0, p_written = 0, p_sent = 0;
9530 int print_colored = 0, print_found = 0, print_trees = 0;
9531 int print_searching = 0, print_total = 0;
9532 int print_deltify = 0, print_written = 0, print_sent = 0;
9534 if (a->verbosity < 0)
9535 return NULL;
9537 if (refname) {
9538 const char *status = success ? "accepted" : "rejected";
9540 if (success) {
9541 struct got_pathlist_entry *pe;
9542 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9543 const char *branchname = pe->path;
9544 if (got_path_cmp(branchname, refname,
9545 strlen(branchname), strlen(refname)) == 0) {
9546 status = "deleted";
9547 a->sent_something = 1;
9548 break;
9553 if (a->printed_something)
9554 putchar('\n');
9555 printf("Server has %s %s", status, refname);
9556 if (errmsg)
9557 printf(": %s", errmsg);
9558 a->printed_something = 1;
9559 return NULL;
9562 if (a->last_ncolored != ncolored) {
9563 print_colored = 1;
9564 a->last_ncolored = ncolored;
9567 if (a->last_nfound != nfound) {
9568 print_colored = 1;
9569 print_found = 1;
9570 a->last_nfound = nfound;
9573 if (a->last_ntrees != ntrees) {
9574 print_colored = 1;
9575 print_found = 1;
9576 print_trees = 1;
9577 a->last_ntrees = ntrees;
9580 if ((print_colored || print_found || print_trees) &&
9581 !a->loading_done) {
9582 printf("\r");
9583 print_load_info(print_colored, print_found, print_trees,
9584 ncolored, nfound, ntrees);
9585 a->printed_something = 1;
9586 fflush(stdout);
9587 return NULL;
9588 } else if (!a->loading_done) {
9589 printf("\r");
9590 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9591 printf("\n");
9592 a->loading_done = 1;
9595 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9596 return got_error_from_errno("fmt_scaled");
9597 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9598 return got_error_from_errno("fmt_scaled");
9600 if (a->last_ncommits != ncommits) {
9601 print_searching = 1;
9602 a->last_ncommits = ncommits;
9605 if (a->last_nobj_total != nobj_total) {
9606 print_searching = 1;
9607 print_total = 1;
9608 a->last_nobj_total = nobj_total;
9611 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9612 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9613 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9614 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9615 return got_error(GOT_ERR_NO_SPACE);
9618 if (nobj_deltify > 0 || nobj_written > 0) {
9619 if (nobj_deltify > 0) {
9620 p_deltify = (nobj_deltify * 100) / nobj_total;
9621 if (p_deltify != a->last_p_deltify) {
9622 a->last_p_deltify = p_deltify;
9623 print_searching = 1;
9624 print_total = 1;
9625 print_deltify = 1;
9628 if (nobj_written > 0) {
9629 p_written = (nobj_written * 100) / nobj_total;
9630 if (p_written != a->last_p_written) {
9631 a->last_p_written = p_written;
9632 print_searching = 1;
9633 print_total = 1;
9634 print_deltify = 1;
9635 print_written = 1;
9640 if (bytes_sent > 0) {
9641 p_sent = (bytes_sent * 100) / packfile_size;
9642 if (p_sent != a->last_p_sent) {
9643 a->last_p_sent = p_sent;
9644 print_searching = 1;
9645 print_total = 1;
9646 print_deltify = 1;
9647 print_written = 1;
9648 print_sent = 1;
9650 a->sent_something = 1;
9653 if (print_searching || print_total || print_deltify || print_written ||
9654 print_sent)
9655 printf("\r");
9656 if (print_searching)
9657 printf("packing %d reference%s", ncommits,
9658 ncommits == 1 ? "" : "s");
9659 if (print_total)
9660 printf("; %d object%s", nobj_total,
9661 nobj_total == 1 ? "" : "s");
9662 if (print_deltify)
9663 printf("; deltify: %d%%", p_deltify);
9664 if (print_sent)
9665 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9666 scaled_packsize, p_sent);
9667 else if (print_written)
9668 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9669 scaled_packsize, p_written);
9670 if (print_searching || print_total || print_deltify ||
9671 print_written || print_sent) {
9672 a->printed_something = 1;
9673 fflush(stdout);
9675 return NULL;
9678 static const struct got_error *
9679 cmd_send(int argc, char *argv[])
9681 const struct got_error *error = NULL;
9682 char *cwd = NULL, *repo_path = NULL;
9683 const char *remote_name;
9684 char *proto = NULL, *host = NULL, *port = NULL;
9685 char *repo_name = NULL, *server_path = NULL;
9686 const struct got_remote_repo *remotes, *remote = NULL;
9687 int nremotes, nbranches = 0, ndelete_branches = 0;
9688 struct got_repository *repo = NULL;
9689 struct got_worktree *worktree = NULL;
9690 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9691 struct got_pathlist_head branches;
9692 struct got_pathlist_head tags;
9693 struct got_reflist_head all_branches;
9694 struct got_reflist_head all_tags;
9695 struct got_pathlist_head delete_args;
9696 struct got_pathlist_head delete_branches;
9697 struct got_reflist_entry *re;
9698 struct got_pathlist_entry *pe;
9699 int i, ch, sendfd = -1, sendstatus;
9700 pid_t sendpid = -1;
9701 struct got_send_progress_arg spa;
9702 int verbosity = 0, overwrite_refs = 0;
9703 int send_all_branches = 0, send_all_tags = 0;
9704 struct got_reference *ref = NULL;
9705 int *pack_fds = NULL;
9707 TAILQ_INIT(&branches);
9708 TAILQ_INIT(&tags);
9709 TAILQ_INIT(&all_branches);
9710 TAILQ_INIT(&all_tags);
9711 TAILQ_INIT(&delete_args);
9712 TAILQ_INIT(&delete_branches);
9714 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9715 switch (ch) {
9716 case 'a':
9717 send_all_branches = 1;
9718 break;
9719 case 'b':
9720 error = got_pathlist_append(&branches, optarg, NULL);
9721 if (error)
9722 return error;
9723 nbranches++;
9724 break;
9725 case 'd':
9726 error = got_pathlist_append(&delete_args, optarg, NULL);
9727 if (error)
9728 return error;
9729 break;
9730 case 'f':
9731 overwrite_refs = 1;
9732 break;
9733 case 'q':
9734 verbosity = -1;
9735 break;
9736 case 'r':
9737 repo_path = realpath(optarg, NULL);
9738 if (repo_path == NULL)
9739 return got_error_from_errno2("realpath",
9740 optarg);
9741 got_path_strip_trailing_slashes(repo_path);
9742 break;
9743 case 'T':
9744 send_all_tags = 1;
9745 break;
9746 case 't':
9747 error = got_pathlist_append(&tags, optarg, NULL);
9748 if (error)
9749 return error;
9750 break;
9751 case 'v':
9752 if (verbosity < 0)
9753 verbosity = 0;
9754 else if (verbosity < 3)
9755 verbosity++;
9756 break;
9757 default:
9758 usage_send();
9759 /* NOTREACHED */
9762 argc -= optind;
9763 argv += optind;
9765 if (send_all_branches && !TAILQ_EMPTY(&branches))
9766 option_conflict('a', 'b');
9767 if (send_all_tags && !TAILQ_EMPTY(&tags))
9768 option_conflict('T', 't');
9771 if (argc == 0)
9772 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9773 else if (argc == 1)
9774 remote_name = argv[0];
9775 else
9776 usage_send();
9778 cwd = getcwd(NULL, 0);
9779 if (cwd == NULL) {
9780 error = got_error_from_errno("getcwd");
9781 goto done;
9784 error = got_repo_pack_fds_open(&pack_fds);
9785 if (error != NULL)
9786 goto done;
9788 if (repo_path == NULL) {
9789 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9790 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9791 goto done;
9792 else
9793 error = NULL;
9794 if (worktree) {
9795 repo_path =
9796 strdup(got_worktree_get_repo_path(worktree));
9797 if (repo_path == NULL)
9798 error = got_error_from_errno("strdup");
9799 if (error)
9800 goto done;
9801 } else {
9802 repo_path = strdup(cwd);
9803 if (repo_path == NULL) {
9804 error = got_error_from_errno("strdup");
9805 goto done;
9810 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9811 if (error)
9812 goto done;
9814 if (worktree) {
9815 worktree_conf = got_worktree_get_gotconfig(worktree);
9816 if (worktree_conf) {
9817 got_gotconfig_get_remotes(&nremotes, &remotes,
9818 worktree_conf);
9819 for (i = 0; i < nremotes; i++) {
9820 if (strcmp(remotes[i].name, remote_name) == 0) {
9821 remote = &remotes[i];
9822 break;
9827 if (remote == NULL) {
9828 repo_conf = got_repo_get_gotconfig(repo);
9829 if (repo_conf) {
9830 got_gotconfig_get_remotes(&nremotes, &remotes,
9831 repo_conf);
9832 for (i = 0; i < nremotes; i++) {
9833 if (strcmp(remotes[i].name, remote_name) == 0) {
9834 remote = &remotes[i];
9835 break;
9840 if (remote == NULL) {
9841 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9842 for (i = 0; i < nremotes; i++) {
9843 if (strcmp(remotes[i].name, remote_name) == 0) {
9844 remote = &remotes[i];
9845 break;
9849 if (remote == NULL) {
9850 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9851 goto done;
9854 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9855 &repo_name, remote->send_url);
9856 if (error)
9857 goto done;
9859 if (strcmp(proto, "git") == 0) {
9860 #ifndef PROFILE
9861 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9862 "sendfd dns inet unveil", NULL) == -1)
9863 err(1, "pledge");
9864 #endif
9865 } else if (strcmp(proto, "git+ssh") == 0 ||
9866 strcmp(proto, "ssh") == 0) {
9867 #ifndef PROFILE
9868 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9869 "sendfd unveil", NULL) == -1)
9870 err(1, "pledge");
9871 #endif
9872 } else if (strcmp(proto, "http") == 0 ||
9873 strcmp(proto, "git+http") == 0) {
9874 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9875 goto done;
9876 } else {
9877 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9878 goto done;
9881 error = got_dial_apply_unveil(proto);
9882 if (error)
9883 goto done;
9885 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9886 if (error)
9887 goto done;
9889 if (send_all_branches) {
9890 error = got_ref_list(&all_branches, repo, "refs/heads",
9891 got_ref_cmp_by_name, NULL);
9892 if (error)
9893 goto done;
9894 TAILQ_FOREACH(re, &all_branches, entry) {
9895 const char *branchname = got_ref_get_name(re->ref);
9896 error = got_pathlist_append(&branches,
9897 branchname, NULL);
9898 if (error)
9899 goto done;
9900 nbranches++;
9902 } else if (nbranches == 0) {
9903 for (i = 0; i < remote->nsend_branches; i++) {
9904 error = got_pathlist_append(&branches,
9905 remote->send_branches[i], NULL);
9906 if (error)
9907 goto done;
9911 if (send_all_tags) {
9912 error = got_ref_list(&all_tags, repo, "refs/tags",
9913 got_ref_cmp_by_name, NULL);
9914 if (error)
9915 goto done;
9916 TAILQ_FOREACH(re, &all_tags, entry) {
9917 const char *tagname = got_ref_get_name(re->ref);
9918 error = got_pathlist_append(&tags,
9919 tagname, NULL);
9920 if (error)
9921 goto done;
9926 * To prevent accidents only branches in refs/heads/ can be deleted
9927 * with 'got send -d'.
9928 * Deleting anything else requires local repository access or Git.
9930 TAILQ_FOREACH(pe, &delete_args, entry) {
9931 const char *branchname = pe->path;
9932 char *s;
9933 struct got_pathlist_entry *new;
9934 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9935 s = strdup(branchname);
9936 if (s == NULL) {
9937 error = got_error_from_errno("strdup");
9938 goto done;
9940 } else {
9941 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9942 error = got_error_from_errno("asprintf");
9943 goto done;
9946 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9947 if (error || new == NULL /* duplicate */)
9948 free(s);
9949 if (error)
9950 goto done;
9951 ndelete_branches++;
9954 if (nbranches == 0 && ndelete_branches == 0) {
9955 struct got_reference *head_ref;
9956 if (worktree)
9957 error = got_ref_open(&head_ref, repo,
9958 got_worktree_get_head_ref_name(worktree), 0);
9959 else
9960 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9961 if (error)
9962 goto done;
9963 if (got_ref_is_symbolic(head_ref)) {
9964 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9965 got_ref_close(head_ref);
9966 if (error)
9967 goto done;
9968 } else
9969 ref = head_ref;
9970 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9971 NULL);
9972 if (error)
9973 goto done;
9974 nbranches++;
9977 if (verbosity >= 0) {
9978 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9979 remote->name, proto, host,
9980 port ? ":" : "", port ? port : "",
9981 *server_path == '/' ? "" : "/", server_path);
9984 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9985 server_path, verbosity);
9986 if (error)
9987 goto done;
9989 memset(&spa, 0, sizeof(spa));
9990 spa.last_scaled_packsize[0] = '\0';
9991 spa.last_p_deltify = -1;
9992 spa.last_p_written = -1;
9993 spa.verbosity = verbosity;
9994 spa.delete_branches = &delete_branches;
9995 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9996 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9997 check_cancelled, NULL);
9998 if (spa.printed_something)
9999 putchar('\n');
10000 if (error)
10001 goto done;
10002 if (!spa.sent_something && verbosity >= 0)
10003 printf("Already up-to-date\n");
10004 done:
10005 if (sendpid > 0) {
10006 if (kill(sendpid, SIGTERM) == -1)
10007 error = got_error_from_errno("kill");
10008 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10009 error = got_error_from_errno("waitpid");
10011 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10012 error = got_error_from_errno("close");
10013 if (repo) {
10014 const struct got_error *close_err = got_repo_close(repo);
10015 if (error == NULL)
10016 error = close_err;
10018 if (worktree)
10019 got_worktree_close(worktree);
10020 if (pack_fds) {
10021 const struct got_error *pack_err =
10022 got_repo_pack_fds_close(pack_fds);
10023 if (error == NULL)
10024 error = pack_err;
10026 if (ref)
10027 got_ref_close(ref);
10028 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10029 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10030 got_ref_list_free(&all_branches);
10031 got_ref_list_free(&all_tags);
10032 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10033 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10034 free(cwd);
10035 free(repo_path);
10036 free(proto);
10037 free(host);
10038 free(port);
10039 free(server_path);
10040 free(repo_name);
10041 return error;
10045 * Print and if delete is set delete all ref_prefix references.
10046 * If wanted_ref is not NULL, only print or delete this reference.
10048 static const struct got_error *
10049 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10050 const char *wanted_ref, int delete, struct got_worktree *worktree,
10051 struct got_repository *repo)
10053 const struct got_error *err;
10054 struct got_pathlist_head paths;
10055 struct got_reflist_head refs;
10056 struct got_reflist_entry *re;
10057 struct got_reflist_object_id_map *refs_idmap = NULL;
10058 struct got_commit_object *commit = NULL;
10059 struct got_object_id *id = NULL;
10060 const char *header_prefix;
10061 char *uuidstr = NULL;
10062 int found = 0;
10064 TAILQ_INIT(&refs);
10065 TAILQ_INIT(&paths);
10067 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10068 if (err)
10069 goto done;
10071 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10072 if (err)
10073 goto done;
10075 if (worktree != NULL) {
10076 err = got_worktree_get_uuid(&uuidstr, worktree);
10077 if (err)
10078 goto done;
10081 if (wanted_ref) {
10082 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10083 wanted_ref += 11;
10086 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10087 header_prefix = "backout";
10088 else
10089 header_prefix = "cherrypick";
10091 TAILQ_FOREACH(re, &refs, entry) {
10092 const char *refname, *wt;
10094 refname = got_ref_get_name(re->ref);
10096 err = check_cancelled(NULL);
10097 if (err)
10098 goto done;
10100 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10101 refname += prefix_len + 1; /* skip '-' delimiter */
10102 else
10103 continue;
10105 wt = refname;
10107 if (worktree == NULL || strncmp(refname, uuidstr,
10108 GOT_WORKTREE_UUID_STRLEN) == 0)
10109 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10110 else
10111 continue;
10113 err = got_repo_match_object_id(&id, NULL, refname,
10114 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10115 if (err)
10116 goto done;
10118 err = got_object_open_as_commit(&commit, repo, id);
10119 if (err)
10120 goto done;
10122 if (wanted_ref)
10123 found = strncmp(wanted_ref, refname,
10124 strlen(wanted_ref)) == 0;
10125 if (wanted_ref && !found) {
10126 struct got_reflist_head *ci_refs;
10128 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10129 id);
10131 if (ci_refs) {
10132 char *refs_str = NULL;
10133 char const *r = NULL;
10135 err = build_refs_str(&refs_str, ci_refs, id,
10136 repo, 1);
10137 if (err)
10138 goto done;
10140 r = refs_str;
10141 while (r) {
10142 if (strncmp(r, wanted_ref,
10143 strlen(wanted_ref)) == 0) {
10144 found = 1;
10145 break;
10147 r = strchr(r, ' ');
10148 if (r)
10149 ++r;
10151 free(refs_str);
10155 if (wanted_ref == NULL || found) {
10156 if (delete) {
10157 err = got_ref_delete(re->ref, repo);
10158 if (err)
10159 goto done;
10160 printf("Deleted: ");
10161 err = print_commit_oneline(commit, id, repo,
10162 refs_idmap);
10163 } else {
10165 * Print paths modified by commit to help
10166 * associate commits with worktree changes.
10168 err = get_changed_paths(&paths, commit,
10169 repo, NULL);
10170 if (err)
10171 goto done;
10173 err = print_commit(commit, id, repo, NULL,
10174 &paths, NULL, 0, 0, refs_idmap, NULL,
10175 header_prefix);
10176 got_pathlist_free(&paths,
10177 GOT_PATHLIST_FREE_ALL);
10179 if (worktree == NULL)
10180 printf("work tree: %.*s\n\n",
10181 GOT_WORKTREE_UUID_STRLEN, wt);
10183 if (err || found)
10184 goto done;
10187 got_object_commit_close(commit);
10188 commit = NULL;
10189 free(id);
10190 id = NULL;
10193 if (wanted_ref != NULL && !found)
10194 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10196 done:
10197 free(id);
10198 free(uuidstr);
10199 got_ref_list_free(&refs);
10200 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10201 if (refs_idmap)
10202 got_reflist_object_id_map_free(refs_idmap);
10203 if (commit)
10204 got_object_commit_close(commit);
10205 return err;
10209 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10210 * identified by id for log messages to prepopulate the editor on commit.
10212 static const struct got_error *
10213 logmsg_ref(struct got_object_id *id, const char *prefix,
10214 struct got_worktree *worktree, struct got_repository *repo)
10216 const struct got_error *err = NULL;
10217 char *idstr, *ref = NULL, *refname = NULL;
10218 int histedit_in_progress;
10219 int rebase_in_progress, merge_in_progress;
10222 * Silenty refuse to create merge reference if any histedit, merge,
10223 * or rebase operation is in progress.
10225 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10226 worktree);
10227 if (err)
10228 return err;
10229 if (histedit_in_progress)
10230 return NULL;
10232 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10233 if (err)
10234 return err;
10235 if (rebase_in_progress)
10236 return NULL;
10238 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10239 repo);
10240 if (err)
10241 return err;
10242 if (merge_in_progress)
10243 return NULL;
10245 err = got_object_id_str(&idstr, id);
10246 if (err)
10247 return err;
10249 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10250 if (err)
10251 goto done;
10253 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10254 err = got_error_from_errno("asprintf");
10255 goto done;
10258 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10259 -1, repo);
10260 done:
10261 free(ref);
10262 free(idstr);
10263 free(refname);
10264 return err;
10267 __dead static void
10268 usage_cherrypick(void)
10270 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10271 getprogname());
10272 exit(1);
10275 static const struct got_error *
10276 cmd_cherrypick(int argc, char *argv[])
10278 const struct got_error *error = NULL;
10279 struct got_worktree *worktree = NULL;
10280 struct got_repository *repo = NULL;
10281 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10282 struct got_object_id *commit_id = NULL;
10283 struct got_commit_object *commit = NULL;
10284 struct got_object_qid *pid;
10285 int ch, list_refs = 0, remove_refs = 0;
10286 struct got_update_progress_arg upa;
10287 int *pack_fds = NULL;
10289 #ifndef PROFILE
10290 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10291 "unveil", NULL) == -1)
10292 err(1, "pledge");
10293 #endif
10295 while ((ch = getopt(argc, argv, "lX")) != -1) {
10296 switch (ch) {
10297 case 'l':
10298 list_refs = 1;
10299 break;
10300 case 'X':
10301 remove_refs = 1;
10302 break;
10303 default:
10304 usage_cherrypick();
10305 /* NOTREACHED */
10309 argc -= optind;
10310 argv += optind;
10312 if (list_refs || remove_refs) {
10313 if (argc != 0 && argc != 1)
10314 usage_cherrypick();
10315 } else if (argc != 1)
10316 usage_cherrypick();
10317 if (list_refs && remove_refs)
10318 option_conflict('l', 'X');
10320 cwd = getcwd(NULL, 0);
10321 if (cwd == NULL) {
10322 error = got_error_from_errno("getcwd");
10323 goto done;
10326 error = got_repo_pack_fds_open(&pack_fds);
10327 if (error != NULL)
10328 goto done;
10330 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10331 if (error) {
10332 if (list_refs || remove_refs) {
10333 if (error->code != GOT_ERR_NOT_WORKTREE)
10334 goto done;
10335 } else {
10336 if (error->code == GOT_ERR_NOT_WORKTREE)
10337 error = wrap_not_worktree_error(error,
10338 "cherrypick", cwd);
10339 goto done;
10343 error = got_repo_open(&repo,
10344 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10345 NULL, pack_fds);
10346 if (error != NULL)
10347 goto done;
10349 error = apply_unveil(got_repo_get_path(repo), 0,
10350 worktree ? got_worktree_get_root_path(worktree) : NULL);
10351 if (error)
10352 goto done;
10354 if (list_refs || remove_refs) {
10355 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10356 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10357 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10358 goto done;
10361 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10362 if (error != NULL)
10363 goto done;
10365 error = got_repo_match_object_id(&commit_id, NULL,
10366 keyword_idstr != NULL ? keyword_idstr : argv[0],
10367 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10368 if (error)
10369 goto done;
10370 error = got_object_id_str(&commit_id_str, commit_id);
10371 if (error)
10372 goto done;
10374 error = got_object_open_as_commit(&commit, repo, commit_id);
10375 if (error)
10376 goto done;
10377 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10378 memset(&upa, 0, sizeof(upa));
10379 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10380 commit_id, repo, update_progress, &upa, check_cancelled,
10381 NULL);
10382 if (error != NULL)
10383 goto done;
10385 if (upa.did_something) {
10386 error = logmsg_ref(commit_id,
10387 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10388 if (error)
10389 goto done;
10390 printf("Merged commit %s\n", commit_id_str);
10392 print_merge_progress_stats(&upa);
10393 done:
10394 free(cwd);
10395 free(keyword_idstr);
10396 if (commit)
10397 got_object_commit_close(commit);
10398 free(commit_id_str);
10399 if (worktree)
10400 got_worktree_close(worktree);
10401 if (repo) {
10402 const struct got_error *close_err = got_repo_close(repo);
10403 if (error == NULL)
10404 error = close_err;
10406 if (pack_fds) {
10407 const struct got_error *pack_err =
10408 got_repo_pack_fds_close(pack_fds);
10409 if (error == NULL)
10410 error = pack_err;
10413 return error;
10416 __dead static void
10417 usage_backout(void)
10419 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10420 exit(1);
10423 static const struct got_error *
10424 cmd_backout(int argc, char *argv[])
10426 const struct got_error *error = NULL;
10427 struct got_worktree *worktree = NULL;
10428 struct got_repository *repo = NULL;
10429 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10430 struct got_object_id *commit_id = NULL;
10431 struct got_commit_object *commit = NULL;
10432 struct got_object_qid *pid;
10433 int ch, list_refs = 0, remove_refs = 0;
10434 struct got_update_progress_arg upa;
10435 int *pack_fds = NULL;
10437 #ifndef PROFILE
10438 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10439 "unveil", NULL) == -1)
10440 err(1, "pledge");
10441 #endif
10443 while ((ch = getopt(argc, argv, "lX")) != -1) {
10444 switch (ch) {
10445 case 'l':
10446 list_refs = 1;
10447 break;
10448 case 'X':
10449 remove_refs = 1;
10450 break;
10451 default:
10452 usage_backout();
10453 /* NOTREACHED */
10457 argc -= optind;
10458 argv += optind;
10460 if (list_refs || remove_refs) {
10461 if (argc != 0 && argc != 1)
10462 usage_backout();
10463 } else if (argc != 1)
10464 usage_backout();
10465 if (list_refs && remove_refs)
10466 option_conflict('l', 'X');
10468 cwd = getcwd(NULL, 0);
10469 if (cwd == NULL) {
10470 error = got_error_from_errno("getcwd");
10471 goto done;
10474 error = got_repo_pack_fds_open(&pack_fds);
10475 if (error != NULL)
10476 goto done;
10478 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10479 if (error) {
10480 if (list_refs || remove_refs) {
10481 if (error->code != GOT_ERR_NOT_WORKTREE)
10482 goto done;
10483 } else {
10484 if (error->code == GOT_ERR_NOT_WORKTREE)
10485 error = wrap_not_worktree_error(error,
10486 "backout", cwd);
10487 goto done;
10491 error = got_repo_open(&repo,
10492 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10493 NULL, pack_fds);
10494 if (error != NULL)
10495 goto done;
10497 error = apply_unveil(got_repo_get_path(repo), 0,
10498 worktree ? got_worktree_get_root_path(worktree) : NULL);
10499 if (error)
10500 goto done;
10502 if (list_refs || remove_refs) {
10503 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10504 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10505 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10506 goto done;
10509 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10510 if (error != NULL)
10511 goto done;
10513 error = got_repo_match_object_id(&commit_id, NULL,
10514 keyword_idstr != NULL ? keyword_idstr : argv[0],
10515 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10516 if (error)
10517 goto done;
10518 error = got_object_id_str(&commit_id_str, commit_id);
10519 if (error)
10520 goto done;
10522 error = got_object_open_as_commit(&commit, repo, commit_id);
10523 if (error)
10524 goto done;
10525 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10526 if (pid == NULL) {
10527 error = got_error(GOT_ERR_ROOT_COMMIT);
10528 goto done;
10531 memset(&upa, 0, sizeof(upa));
10532 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10533 repo, update_progress, &upa, check_cancelled, NULL);
10534 if (error != NULL)
10535 goto done;
10537 if (upa.did_something) {
10538 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10539 worktree, repo);
10540 if (error)
10541 goto done;
10542 printf("Backed out commit %s\n", commit_id_str);
10544 print_merge_progress_stats(&upa);
10545 done:
10546 free(cwd);
10547 free(keyword_idstr);
10548 if (commit)
10549 got_object_commit_close(commit);
10550 free(commit_id_str);
10551 if (worktree)
10552 got_worktree_close(worktree);
10553 if (repo) {
10554 const struct got_error *close_err = got_repo_close(repo);
10555 if (error == NULL)
10556 error = close_err;
10558 if (pack_fds) {
10559 const struct got_error *pack_err =
10560 got_repo_pack_fds_close(pack_fds);
10561 if (error == NULL)
10562 error = pack_err;
10564 return error;
10567 __dead static void
10568 usage_rebase(void)
10570 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10571 exit(1);
10574 static void
10575 trim_logmsg(char *logmsg, int limit)
10577 char *nl;
10578 size_t len;
10580 len = strlen(logmsg);
10581 if (len > limit)
10582 len = limit;
10583 logmsg[len] = '\0';
10584 nl = strchr(logmsg, '\n');
10585 if (nl)
10586 *nl = '\0';
10589 static const struct got_error *
10590 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10592 const struct got_error *err;
10593 char *logmsg0 = NULL;
10594 const char *s;
10596 err = got_object_commit_get_logmsg(&logmsg0, commit);
10597 if (err)
10598 return err;
10600 s = logmsg0;
10601 while (isspace((unsigned char)s[0]))
10602 s++;
10604 *logmsg = strdup(s);
10605 if (*logmsg == NULL) {
10606 err = got_error_from_errno("strdup");
10607 goto done;
10610 trim_logmsg(*logmsg, limit);
10611 done:
10612 free(logmsg0);
10613 return err;
10616 static const struct got_error *
10617 show_rebase_merge_conflict(struct got_object_id *id,
10618 struct got_repository *repo)
10620 const struct got_error *err;
10621 struct got_commit_object *commit = NULL;
10622 char *id_str = NULL, *logmsg = NULL;
10624 err = got_object_open_as_commit(&commit, repo, id);
10625 if (err)
10626 return err;
10628 err = got_object_id_str(&id_str, id);
10629 if (err)
10630 goto done;
10632 id_str[12] = '\0';
10634 err = get_short_logmsg(&logmsg, 42, commit);
10635 if (err)
10636 goto done;
10638 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10639 done:
10640 free(id_str);
10641 got_object_commit_close(commit);
10642 free(logmsg);
10643 return err;
10646 static const struct got_error *
10647 show_rebase_progress(struct got_commit_object *commit,
10648 struct got_object_id *old_id, struct got_object_id *new_id)
10650 const struct got_error *err;
10651 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10653 err = got_object_id_str(&old_id_str, old_id);
10654 if (err)
10655 goto done;
10657 if (new_id) {
10658 err = got_object_id_str(&new_id_str, new_id);
10659 if (err)
10660 goto done;
10663 old_id_str[12] = '\0';
10664 if (new_id_str)
10665 new_id_str[12] = '\0';
10667 err = get_short_logmsg(&logmsg, 42, commit);
10668 if (err)
10669 goto done;
10671 printf("%s -> %s: %s\n", old_id_str,
10672 new_id_str ? new_id_str : "no-op change", logmsg);
10673 done:
10674 free(old_id_str);
10675 free(new_id_str);
10676 free(logmsg);
10677 return err;
10680 static const struct got_error *
10681 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10682 struct got_reference *branch, struct got_reference *tmp_branch,
10683 struct got_repository *repo, int create_backup)
10685 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10686 return got_worktree_rebase_complete(worktree, fileindex,
10687 tmp_branch, branch, repo, create_backup);
10690 static const struct got_error *
10691 rebase_commit(struct got_pathlist_head *merged_paths,
10692 struct got_worktree *worktree, struct got_fileindex *fileindex,
10693 struct got_reference *tmp_branch, const char *committer,
10694 struct got_object_id *commit_id, int allow_conflict,
10695 struct got_repository *repo)
10697 const struct got_error *error;
10698 struct got_commit_object *commit;
10699 struct got_object_id *new_commit_id;
10701 error = got_object_open_as_commit(&commit, repo, commit_id);
10702 if (error)
10703 return error;
10705 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10706 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10707 allow_conflict, repo);
10708 if (error) {
10709 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10710 goto done;
10711 error = show_rebase_progress(commit, commit_id, NULL);
10712 } else {
10713 error = show_rebase_progress(commit, commit_id, new_commit_id);
10714 free(new_commit_id);
10716 done:
10717 got_object_commit_close(commit);
10718 return error;
10721 struct check_path_prefix_arg {
10722 const char *path_prefix;
10723 size_t len;
10724 int errcode;
10727 static const struct got_error *
10728 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10729 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10730 struct got_object_id *id1, struct got_object_id *id2,
10731 const char *path1, const char *path2,
10732 mode_t mode1, mode_t mode2, struct got_repository *repo)
10734 struct check_path_prefix_arg *a = arg;
10736 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10737 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10738 return got_error(a->errcode);
10740 return NULL;
10743 static const struct got_error *
10744 check_path_prefix(struct got_object_id *parent_id,
10745 struct got_object_id *commit_id, const char *path_prefix,
10746 int errcode, struct got_repository *repo)
10748 const struct got_error *err;
10749 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10750 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10751 struct check_path_prefix_arg cpp_arg;
10753 if (got_path_is_root_dir(path_prefix))
10754 return NULL;
10756 err = got_object_open_as_commit(&commit, repo, commit_id);
10757 if (err)
10758 goto done;
10760 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10761 if (err)
10762 goto done;
10764 err = got_object_open_as_tree(&tree1, repo,
10765 got_object_commit_get_tree_id(parent_commit));
10766 if (err)
10767 goto done;
10769 err = got_object_open_as_tree(&tree2, repo,
10770 got_object_commit_get_tree_id(commit));
10771 if (err)
10772 goto done;
10774 cpp_arg.path_prefix = path_prefix;
10775 while (cpp_arg.path_prefix[0] == '/')
10776 cpp_arg.path_prefix++;
10777 cpp_arg.len = strlen(cpp_arg.path_prefix);
10778 cpp_arg.errcode = errcode;
10779 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10780 check_path_prefix_in_diff, &cpp_arg, 0);
10781 done:
10782 if (tree1)
10783 got_object_tree_close(tree1);
10784 if (tree2)
10785 got_object_tree_close(tree2);
10786 if (commit)
10787 got_object_commit_close(commit);
10788 if (parent_commit)
10789 got_object_commit_close(parent_commit);
10790 return err;
10793 static const struct got_error *
10794 collect_commits(struct got_object_id_queue *commits,
10795 struct got_object_id *initial_commit_id,
10796 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10797 const char *path_prefix, int path_prefix_errcode,
10798 struct got_repository *repo)
10800 const struct got_error *err = NULL;
10801 struct got_commit_graph *graph = NULL;
10802 struct got_object_id parent_id, commit_id;
10803 struct got_object_qid *qid;
10805 err = got_commit_graph_open(&graph, "/", 1);
10806 if (err)
10807 return err;
10809 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10810 check_cancelled, NULL);
10811 if (err)
10812 goto done;
10814 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10815 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10816 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10817 check_cancelled, NULL);
10818 if (err) {
10819 if (err->code == GOT_ERR_ITER_COMPLETED) {
10820 err = got_error_msg(GOT_ERR_ANCESTRY,
10821 "ran out of commits to rebase before "
10822 "youngest common ancestor commit has "
10823 "been reached?!?");
10825 goto done;
10826 } else {
10827 err = check_path_prefix(&parent_id, &commit_id,
10828 path_prefix, path_prefix_errcode, repo);
10829 if (err)
10830 goto done;
10832 err = got_object_qid_alloc(&qid, &commit_id);
10833 if (err)
10834 goto done;
10835 STAILQ_INSERT_HEAD(commits, qid, entry);
10837 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10840 done:
10841 got_commit_graph_close(graph);
10842 return err;
10845 static const struct got_error *
10846 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10848 const struct got_error *err = NULL;
10849 time_t committer_time;
10850 struct tm tm;
10851 char datebuf[11]; /* YYYY-MM-DD + NUL */
10852 char *author0 = NULL, *author, *smallerthan;
10853 char *logmsg0 = NULL, *logmsg, *newline;
10855 committer_time = got_object_commit_get_committer_time(commit);
10856 if (gmtime_r(&committer_time, &tm) == NULL)
10857 return got_error_from_errno("gmtime_r");
10858 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10859 return got_error(GOT_ERR_NO_SPACE);
10861 author0 = strdup(got_object_commit_get_author(commit));
10862 if (author0 == NULL)
10863 return got_error_from_errno("strdup");
10864 author = author0;
10865 smallerthan = strchr(author, '<');
10866 if (smallerthan && smallerthan[1] != '\0')
10867 author = smallerthan + 1;
10868 author[strcspn(author, "@>")] = '\0';
10870 err = got_object_commit_get_logmsg(&logmsg0, commit);
10871 if (err)
10872 goto done;
10873 logmsg = logmsg0;
10874 while (*logmsg == '\n')
10875 logmsg++;
10876 newline = strchr(logmsg, '\n');
10877 if (newline)
10878 *newline = '\0';
10880 if (asprintf(brief_str, "%s %s %s",
10881 datebuf, author, logmsg) == -1)
10882 err = got_error_from_errno("asprintf");
10883 done:
10884 free(author0);
10885 free(logmsg0);
10886 return err;
10889 static const struct got_error *
10890 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10891 struct got_repository *repo)
10893 const struct got_error *err;
10894 char *id_str;
10896 err = got_object_id_str(&id_str, id);
10897 if (err)
10898 return err;
10900 err = got_ref_delete(ref, repo);
10901 if (err)
10902 goto done;
10904 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10905 done:
10906 free(id_str);
10907 return err;
10910 static const struct got_error *
10911 print_backup_ref(const char *branch_name, const char *new_id_str,
10912 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10913 struct got_reflist_object_id_map *refs_idmap,
10914 struct got_repository *repo)
10916 const struct got_error *err = NULL;
10917 struct got_reflist_head *refs;
10918 char *refs_str = NULL;
10919 struct got_object_id *new_commit_id = NULL;
10920 struct got_commit_object *new_commit = NULL;
10921 char *new_commit_brief_str = NULL;
10922 struct got_object_id *yca_id = NULL;
10923 struct got_commit_object *yca_commit = NULL;
10924 char *yca_id_str = NULL, *yca_brief_str = NULL;
10925 char *custom_refs_str;
10927 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10928 return got_error_from_errno("asprintf");
10930 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10931 0, 0, refs_idmap, custom_refs_str, NULL);
10932 if (err)
10933 goto done;
10935 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10936 if (err)
10937 goto done;
10939 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10940 if (refs) {
10941 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10942 if (err)
10943 goto done;
10946 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10947 if (err)
10948 goto done;
10950 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10951 if (err)
10952 goto done;
10954 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10955 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10956 if (err)
10957 goto done;
10959 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10960 refs_str ? " (" : "", refs_str ? refs_str : "",
10961 refs_str ? ")" : "", new_commit_brief_str);
10962 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10963 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10964 free(refs_str);
10965 refs_str = NULL;
10967 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10968 if (err)
10969 goto done;
10971 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10972 if (err)
10973 goto done;
10975 err = got_object_id_str(&yca_id_str, yca_id);
10976 if (err)
10977 goto done;
10979 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10980 if (refs) {
10981 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10982 if (err)
10983 goto done;
10985 printf("history forked at %s%s%s%s\n %s\n",
10986 yca_id_str,
10987 refs_str ? " (" : "", refs_str ? refs_str : "",
10988 refs_str ? ")" : "", yca_brief_str);
10990 done:
10991 free(custom_refs_str);
10992 free(new_commit_id);
10993 free(refs_str);
10994 free(yca_id);
10995 free(yca_id_str);
10996 free(yca_brief_str);
10997 if (new_commit)
10998 got_object_commit_close(new_commit);
10999 if (yca_commit)
11000 got_object_commit_close(yca_commit);
11002 return err;
11005 static const struct got_error *
11006 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11007 struct got_repository *repo)
11009 const struct got_error *err;
11010 struct got_reflist_head refs;
11011 struct got_reflist_entry *re;
11012 char *uuidstr = NULL;
11013 static char msg[160];
11015 TAILQ_INIT(&refs);
11017 err = got_worktree_get_uuid(&uuidstr, worktree);
11018 if (err)
11019 goto done;
11021 err = got_ref_list(&refs, repo, "refs/got/worktree",
11022 got_ref_cmp_by_name, repo);
11023 if (err)
11024 goto done;
11026 TAILQ_FOREACH(re, &refs, entry) {
11027 const char *cmd, *refname, *type;
11029 refname = got_ref_get_name(re->ref);
11031 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11032 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11033 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11034 cmd = "cherrypick";
11035 type = "cherrypicked";
11036 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11037 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11038 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11039 cmd = "backout";
11040 type = "backed-out";
11041 } else
11042 continue;
11044 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11045 continue;
11047 snprintf(msg, sizeof(msg),
11048 "work tree has references created by %s commits which "
11049 "must be removed with 'got %s -X' before running the %s "
11050 "command", type, cmd, caller);
11051 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11052 goto done;
11055 done:
11056 free(uuidstr);
11057 got_ref_list_free(&refs);
11058 return err;
11061 static const struct got_error *
11062 process_backup_refs(const char *backup_ref_prefix,
11063 const char *wanted_branch_name,
11064 int delete, struct got_repository *repo)
11066 const struct got_error *err;
11067 struct got_reflist_head refs, backup_refs;
11068 struct got_reflist_entry *re;
11069 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11070 struct got_object_id *old_commit_id = NULL;
11071 char *branch_name = NULL;
11072 struct got_commit_object *old_commit = NULL;
11073 struct got_reflist_object_id_map *refs_idmap = NULL;
11074 int wanted_branch_found = 0;
11076 TAILQ_INIT(&refs);
11077 TAILQ_INIT(&backup_refs);
11079 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11080 if (err)
11081 return err;
11083 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11084 if (err)
11085 goto done;
11087 if (wanted_branch_name) {
11088 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11089 wanted_branch_name += 11;
11092 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11093 got_ref_cmp_by_commit_timestamp_descending, repo);
11094 if (err)
11095 goto done;
11097 TAILQ_FOREACH(re, &backup_refs, entry) {
11098 const char *refname = got_ref_get_name(re->ref);
11099 char *slash;
11101 err = check_cancelled(NULL);
11102 if (err)
11103 break;
11105 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11106 if (err)
11107 break;
11109 err = got_object_open_as_commit(&old_commit, repo,
11110 old_commit_id);
11111 if (err)
11112 break;
11114 if (strncmp(backup_ref_prefix, refname,
11115 backup_ref_prefix_len) == 0)
11116 refname += backup_ref_prefix_len;
11118 while (refname[0] == '/')
11119 refname++;
11121 branch_name = strdup(refname);
11122 if (branch_name == NULL) {
11123 err = got_error_from_errno("strdup");
11124 break;
11126 slash = strrchr(branch_name, '/');
11127 if (slash) {
11128 *slash = '\0';
11129 refname += strlen(branch_name) + 1;
11132 if (wanted_branch_name == NULL ||
11133 strcmp(wanted_branch_name, branch_name) == 0) {
11134 wanted_branch_found = 1;
11135 if (delete) {
11136 err = delete_backup_ref(re->ref,
11137 old_commit_id, repo);
11138 } else {
11139 err = print_backup_ref(branch_name, refname,
11140 old_commit_id, old_commit, refs_idmap,
11141 repo);
11143 if (err)
11144 break;
11147 free(old_commit_id);
11148 old_commit_id = NULL;
11149 free(branch_name);
11150 branch_name = NULL;
11151 got_object_commit_close(old_commit);
11152 old_commit = NULL;
11155 if (wanted_branch_name && !wanted_branch_found) {
11156 err = got_error_fmt(GOT_ERR_NOT_REF,
11157 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11159 done:
11160 if (refs_idmap)
11161 got_reflist_object_id_map_free(refs_idmap);
11162 got_ref_list_free(&refs);
11163 got_ref_list_free(&backup_refs);
11164 free(old_commit_id);
11165 free(branch_name);
11166 if (old_commit)
11167 got_object_commit_close(old_commit);
11168 return err;
11171 static const struct got_error *
11172 abort_progress(void *arg, unsigned char status, const char *path)
11175 * Unversioned files should not clutter progress output when
11176 * an operation is aborted.
11178 if (status == GOT_STATUS_UNVERSIONED)
11179 return NULL;
11181 return update_progress(arg, status, path);
11184 static const struct got_error *
11185 cmd_rebase(int argc, char *argv[])
11187 const struct got_error *error = NULL;
11188 struct got_worktree *worktree = NULL;
11189 struct got_repository *repo = NULL;
11190 struct got_fileindex *fileindex = NULL;
11191 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11192 struct got_reference *branch = NULL;
11193 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11194 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11195 struct got_object_id *resume_commit_id = NULL;
11196 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11197 struct got_object_id *head_commit_id = NULL;
11198 struct got_reference *head_ref = NULL;
11199 struct got_commit_object *commit = NULL;
11200 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11201 int histedit_in_progress = 0, merge_in_progress = 0;
11202 int create_backup = 1, list_backups = 0, delete_backups = 0;
11203 int allow_conflict = 0;
11204 struct got_object_id_queue commits;
11205 struct got_pathlist_head merged_paths;
11206 const struct got_object_id_queue *parent_ids;
11207 struct got_object_qid *qid, *pid;
11208 struct got_update_progress_arg upa;
11209 int *pack_fds = NULL;
11211 STAILQ_INIT(&commits);
11212 TAILQ_INIT(&merged_paths);
11213 memset(&upa, 0, sizeof(upa));
11215 #ifndef PROFILE
11216 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11217 "unveil", NULL) == -1)
11218 err(1, "pledge");
11219 #endif
11221 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11222 switch (ch) {
11223 case 'a':
11224 abort_rebase = 1;
11225 break;
11226 case 'C':
11227 allow_conflict = 1;
11228 break;
11229 case 'c':
11230 continue_rebase = 1;
11231 break;
11232 case 'l':
11233 list_backups = 1;
11234 break;
11235 case 'X':
11236 delete_backups = 1;
11237 break;
11238 default:
11239 usage_rebase();
11240 /* NOTREACHED */
11244 argc -= optind;
11245 argv += optind;
11247 if (list_backups) {
11248 if (abort_rebase)
11249 option_conflict('l', 'a');
11250 if (allow_conflict)
11251 option_conflict('l', 'C');
11252 if (continue_rebase)
11253 option_conflict('l', 'c');
11254 if (delete_backups)
11255 option_conflict('l', 'X');
11256 if (argc != 0 && argc != 1)
11257 usage_rebase();
11258 } else if (delete_backups) {
11259 if (abort_rebase)
11260 option_conflict('X', 'a');
11261 if (allow_conflict)
11262 option_conflict('X', 'C');
11263 if (continue_rebase)
11264 option_conflict('X', 'c');
11265 if (list_backups)
11266 option_conflict('l', 'X');
11267 if (argc != 0 && argc != 1)
11268 usage_rebase();
11269 } else if (allow_conflict) {
11270 if (abort_rebase)
11271 option_conflict('C', 'a');
11272 if (!continue_rebase)
11273 errx(1, "-C option requires -c");
11274 } else {
11275 if (abort_rebase && continue_rebase)
11276 usage_rebase();
11277 else if (abort_rebase || continue_rebase) {
11278 if (argc != 0)
11279 usage_rebase();
11280 } else if (argc != 1)
11281 usage_rebase();
11284 cwd = getcwd(NULL, 0);
11285 if (cwd == NULL) {
11286 error = got_error_from_errno("getcwd");
11287 goto done;
11290 error = got_repo_pack_fds_open(&pack_fds);
11291 if (error != NULL)
11292 goto done;
11294 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11295 if (error) {
11296 if (list_backups || delete_backups) {
11297 if (error->code != GOT_ERR_NOT_WORKTREE)
11298 goto done;
11299 } else {
11300 if (error->code == GOT_ERR_NOT_WORKTREE)
11301 error = wrap_not_worktree_error(error,
11302 "rebase", cwd);
11303 goto done;
11307 error = get_gitconfig_path(&gitconfig_path);
11308 if (error)
11309 goto done;
11310 error = got_repo_open(&repo,
11311 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11312 gitconfig_path, pack_fds);
11313 if (error != NULL)
11314 goto done;
11316 if (worktree != NULL && !list_backups && !delete_backups) {
11317 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11318 if (error)
11319 goto done;
11322 error = get_author(&committer, repo, worktree);
11323 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11324 goto done;
11326 error = apply_unveil(got_repo_get_path(repo), 0,
11327 worktree ? got_worktree_get_root_path(worktree) : NULL);
11328 if (error)
11329 goto done;
11331 if (list_backups || delete_backups) {
11332 error = process_backup_refs(
11333 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11334 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11335 goto done; /* nothing else to do */
11338 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11339 worktree);
11340 if (error)
11341 goto done;
11342 if (histedit_in_progress) {
11343 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11344 goto done;
11347 error = got_worktree_merge_in_progress(&merge_in_progress,
11348 worktree, repo);
11349 if (error)
11350 goto done;
11351 if (merge_in_progress) {
11352 error = got_error(GOT_ERR_MERGE_BUSY);
11353 goto done;
11356 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11357 if (error)
11358 goto done;
11360 if (abort_rebase) {
11361 if (!rebase_in_progress) {
11362 error = got_error(GOT_ERR_NOT_REBASING);
11363 goto done;
11365 error = got_worktree_rebase_continue(&resume_commit_id,
11366 &new_base_branch, &tmp_branch, &branch, &fileindex,
11367 worktree, repo);
11368 if (error)
11369 goto done;
11370 printf("Switching work tree to %s\n",
11371 got_ref_get_symref_target(new_base_branch));
11372 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11373 new_base_branch, abort_progress, &upa);
11374 if (error)
11375 goto done;
11376 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11377 print_merge_progress_stats(&upa);
11378 goto done; /* nothing else to do */
11381 if (continue_rebase) {
11382 if (!rebase_in_progress) {
11383 error = got_error(GOT_ERR_NOT_REBASING);
11384 goto done;
11386 error = got_worktree_rebase_continue(&resume_commit_id,
11387 &new_base_branch, &tmp_branch, &branch, &fileindex,
11388 worktree, repo);
11389 if (error)
11390 goto done;
11392 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11393 committer, resume_commit_id, allow_conflict, repo);
11394 if (error)
11395 goto done;
11397 yca_id = got_object_id_dup(resume_commit_id);
11398 if (yca_id == NULL) {
11399 error = got_error_from_errno("got_object_id_dup");
11400 goto done;
11402 } else {
11403 error = got_ref_open(&branch, repo, argv[0], 0);
11404 if (error != NULL)
11405 goto done;
11406 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11407 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11408 "will not rebase a branch which lives outside "
11409 "the \"refs/heads/\" reference namespace");
11410 goto done;
11414 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11415 if (error)
11416 goto done;
11418 if (!continue_rebase) {
11419 struct got_object_id *base_commit_id;
11421 error = got_ref_open(&head_ref, repo,
11422 got_worktree_get_head_ref_name(worktree), 0);
11423 if (error)
11424 goto done;
11425 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11426 if (error)
11427 goto done;
11428 base_commit_id = got_worktree_get_base_commit_id(worktree);
11429 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11430 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11431 goto done;
11434 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11435 base_commit_id, branch_head_commit_id, 1, repo,
11436 check_cancelled, NULL);
11437 if (error) {
11438 if (error->code == GOT_ERR_ANCESTRY) {
11439 error = got_error_msg(GOT_ERR_ANCESTRY,
11440 "specified branch shares no common "
11441 "ancestry with work tree's branch");
11443 goto done;
11446 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11447 struct got_pathlist_head paths;
11448 printf("%s is already based on %s\n",
11449 got_ref_get_name(branch),
11450 got_worktree_get_head_ref_name(worktree));
11451 error = switch_head_ref(branch, branch_head_commit_id,
11452 worktree, repo);
11453 if (error)
11454 goto done;
11455 error = got_worktree_set_base_commit_id(worktree, repo,
11456 branch_head_commit_id);
11457 if (error)
11458 goto done;
11459 TAILQ_INIT(&paths);
11460 error = got_pathlist_append(&paths, "", NULL);
11461 if (error)
11462 goto done;
11463 error = got_worktree_checkout_files(worktree,
11464 &paths, repo, update_progress, &upa,
11465 check_cancelled, NULL);
11466 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11467 if (error)
11468 goto done;
11469 if (upa.did_something) {
11470 char *id_str;
11471 error = got_object_id_str(&id_str,
11472 branch_head_commit_id);
11473 if (error)
11474 goto done;
11475 printf("Updated to %s: %s\n",
11476 got_worktree_get_head_ref_name(worktree),
11477 id_str);
11478 free(id_str);
11479 } else
11480 printf("Already up-to-date\n");
11481 print_update_progress_stats(&upa);
11482 goto done;
11486 commit_id = branch_head_commit_id;
11487 error = got_object_open_as_commit(&commit, repo, commit_id);
11488 if (error)
11489 goto done;
11491 parent_ids = got_object_commit_get_parent_ids(commit);
11492 pid = STAILQ_FIRST(parent_ids);
11493 if (pid) {
11494 error = collect_commits(&commits, commit_id, &pid->id,
11495 yca_id, got_worktree_get_path_prefix(worktree),
11496 GOT_ERR_REBASE_PATH, repo);
11497 if (error)
11498 goto done;
11501 got_object_commit_close(commit);
11502 commit = NULL;
11504 if (!continue_rebase) {
11505 error = got_worktree_rebase_prepare(&new_base_branch,
11506 &tmp_branch, &fileindex, worktree, branch, repo);
11507 if (error)
11508 goto done;
11511 if (STAILQ_EMPTY(&commits)) {
11512 if (continue_rebase) {
11513 error = rebase_complete(worktree, fileindex,
11514 branch, tmp_branch, repo, create_backup);
11515 goto done;
11516 } else {
11517 /* Fast-forward the reference of the branch. */
11518 struct got_object_id *new_head_commit_id;
11519 char *id_str;
11520 error = got_ref_resolve(&new_head_commit_id, repo,
11521 new_base_branch);
11522 if (error)
11523 goto done;
11524 error = got_object_id_str(&id_str, new_head_commit_id);
11525 if (error)
11526 goto done;
11527 printf("Forwarding %s to commit %s\n",
11528 got_ref_get_name(branch), id_str);
11529 free(id_str);
11530 error = got_ref_change_ref(branch,
11531 new_head_commit_id);
11532 if (error)
11533 goto done;
11534 /* No backup needed since objects did not change. */
11535 create_backup = 0;
11539 pid = NULL;
11540 STAILQ_FOREACH(qid, &commits, entry) {
11542 commit_id = &qid->id;
11543 parent_id = pid ? &pid->id : yca_id;
11544 pid = qid;
11546 memset(&upa, 0, sizeof(upa));
11547 error = got_worktree_rebase_merge_files(&merged_paths,
11548 worktree, fileindex, parent_id, commit_id, repo,
11549 update_progress, &upa, check_cancelled, NULL);
11550 if (error)
11551 goto done;
11553 print_merge_progress_stats(&upa);
11554 if (upa.conflicts > 0 || upa.missing > 0 ||
11555 upa.not_deleted > 0 || upa.unversioned > 0) {
11556 if (upa.conflicts > 0) {
11557 error = show_rebase_merge_conflict(&qid->id,
11558 repo);
11559 if (error)
11560 goto done;
11562 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11563 break;
11566 error = rebase_commit(&merged_paths, worktree, fileindex,
11567 tmp_branch, committer, commit_id, 0, repo);
11568 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11569 if (error)
11570 goto done;
11573 if (upa.conflicts > 0 || upa.missing > 0 ||
11574 upa.not_deleted > 0 || upa.unversioned > 0) {
11575 error = got_worktree_rebase_postpone(worktree, fileindex);
11576 if (error)
11577 goto done;
11578 if (upa.conflicts > 0 && upa.missing == 0 &&
11579 upa.not_deleted == 0 && upa.unversioned == 0) {
11580 error = got_error_msg(GOT_ERR_CONFLICTS,
11581 "conflicts must be resolved before rebasing "
11582 "can continue");
11583 } else if (upa.conflicts > 0) {
11584 error = got_error_msg(GOT_ERR_CONFLICTS,
11585 "conflicts must be resolved before rebasing "
11586 "can continue; changes destined for some "
11587 "files were not yet merged and should be "
11588 "merged manually if required before the "
11589 "rebase operation is continued");
11590 } else {
11591 error = got_error_msg(GOT_ERR_CONFLICTS,
11592 "changes destined for some files were not "
11593 "yet merged and should be merged manually "
11594 "if required before the rebase operation "
11595 "is continued");
11597 } else
11598 error = rebase_complete(worktree, fileindex, branch,
11599 tmp_branch, repo, create_backup);
11600 done:
11601 free(cwd);
11602 free(committer);
11603 free(gitconfig_path);
11604 got_object_id_queue_free(&commits);
11605 free(branch_head_commit_id);
11606 free(resume_commit_id);
11607 free(head_commit_id);
11608 free(yca_id);
11609 if (commit)
11610 got_object_commit_close(commit);
11611 if (branch)
11612 got_ref_close(branch);
11613 if (new_base_branch)
11614 got_ref_close(new_base_branch);
11615 if (tmp_branch)
11616 got_ref_close(tmp_branch);
11617 if (head_ref)
11618 got_ref_close(head_ref);
11619 if (worktree)
11620 got_worktree_close(worktree);
11621 if (repo) {
11622 const struct got_error *close_err = got_repo_close(repo);
11623 if (error == NULL)
11624 error = close_err;
11626 if (pack_fds) {
11627 const struct got_error *pack_err =
11628 got_repo_pack_fds_close(pack_fds);
11629 if (error == NULL)
11630 error = pack_err;
11632 return error;
11635 __dead static void
11636 usage_histedit(void)
11638 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11639 "[branch]\n", getprogname());
11640 exit(1);
11643 #define GOT_HISTEDIT_PICK 'p'
11644 #define GOT_HISTEDIT_EDIT 'e'
11645 #define GOT_HISTEDIT_FOLD 'f'
11646 #define GOT_HISTEDIT_DROP 'd'
11647 #define GOT_HISTEDIT_MESG 'm'
11649 static const struct got_histedit_cmd {
11650 unsigned char code;
11651 const char *name;
11652 const char *desc;
11653 } got_histedit_cmds[] = {
11654 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11655 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11656 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11657 "be used" },
11658 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11659 { GOT_HISTEDIT_MESG, "mesg",
11660 "single-line log message for commit above (open editor if empty)" },
11663 struct got_histedit_list_entry {
11664 TAILQ_ENTRY(got_histedit_list_entry) entry;
11665 struct got_object_id *commit_id;
11666 const struct got_histedit_cmd *cmd;
11667 char *logmsg;
11669 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11671 static const struct got_error *
11672 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11673 FILE *f, struct got_repository *repo)
11675 const struct got_error *err = NULL;
11676 char *logmsg = NULL, *id_str = NULL;
11677 struct got_commit_object *commit = NULL;
11678 int n;
11680 err = got_object_open_as_commit(&commit, repo, commit_id);
11681 if (err)
11682 goto done;
11684 err = get_short_logmsg(&logmsg, 34, commit);
11685 if (err)
11686 goto done;
11688 err = got_object_id_str(&id_str, commit_id);
11689 if (err)
11690 goto done;
11692 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11693 if (n < 0)
11694 err = got_ferror(f, GOT_ERR_IO);
11695 done:
11696 if (commit)
11697 got_object_commit_close(commit);
11698 free(id_str);
11699 free(logmsg);
11700 return err;
11703 static const struct got_error *
11704 histedit_write_commit_list(struct got_object_id_queue *commits,
11705 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11706 int edit_only, struct got_repository *repo)
11708 const struct got_error *err = NULL;
11709 struct got_object_qid *qid;
11710 const char *histedit_cmd = NULL;
11712 if (STAILQ_EMPTY(commits))
11713 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11715 STAILQ_FOREACH(qid, commits, entry) {
11716 histedit_cmd = got_histedit_cmds[0].name;
11717 if (drop_only)
11718 histedit_cmd = "drop";
11719 else if (edit_only)
11720 histedit_cmd = "edit";
11721 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11722 histedit_cmd = "fold";
11723 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11724 if (err)
11725 break;
11726 if (edit_logmsg_only) {
11727 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11728 if (n < 0) {
11729 err = got_ferror(f, GOT_ERR_IO);
11730 break;
11735 return err;
11738 static const struct got_error *
11739 write_cmd_list(FILE *f, const char *branch_name,
11740 struct got_object_id_queue *commits)
11742 const struct got_error *err = NULL;
11743 size_t i;
11744 int n;
11745 char *id_str;
11746 struct got_object_qid *qid;
11748 qid = STAILQ_FIRST(commits);
11749 err = got_object_id_str(&id_str, &qid->id);
11750 if (err)
11751 return err;
11753 n = fprintf(f,
11754 "# Editing the history of branch '%s' starting at\n"
11755 "# commit %s\n"
11756 "# Commits will be processed in order from top to "
11757 "bottom of this file.\n", branch_name, id_str);
11758 if (n < 0) {
11759 err = got_ferror(f, GOT_ERR_IO);
11760 goto done;
11763 n = fprintf(f, "# Available histedit commands:\n");
11764 if (n < 0) {
11765 err = got_ferror(f, GOT_ERR_IO);
11766 goto done;
11769 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11770 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11771 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11772 cmd->desc);
11773 if (n < 0) {
11774 err = got_ferror(f, GOT_ERR_IO);
11775 break;
11778 done:
11779 free(id_str);
11780 return err;
11783 static const struct got_error *
11784 histedit_syntax_error(int lineno)
11786 static char msg[42];
11787 int ret;
11789 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11790 lineno);
11791 if (ret < 0 || (size_t)ret >= sizeof(msg))
11792 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11794 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11797 static const struct got_error *
11798 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11799 char *logmsg, struct got_repository *repo)
11801 const struct got_error *err;
11802 struct got_commit_object *folded_commit = NULL;
11803 char *id_str, *folded_logmsg = NULL;
11805 err = got_object_id_str(&id_str, hle->commit_id);
11806 if (err)
11807 return err;
11809 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11810 if (err)
11811 goto done;
11813 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11814 if (err)
11815 goto done;
11816 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11817 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11818 folded_logmsg) == -1) {
11819 err = got_error_from_errno("asprintf");
11821 done:
11822 if (folded_commit)
11823 got_object_commit_close(folded_commit);
11824 free(id_str);
11825 free(folded_logmsg);
11826 return err;
11829 static struct got_histedit_list_entry *
11830 get_folded_commits(struct got_histedit_list_entry *hle)
11832 struct got_histedit_list_entry *prev, *folded = NULL;
11834 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11835 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11836 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11837 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11838 folded = prev;
11839 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11842 return folded;
11845 static const struct got_error *
11846 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11847 struct got_repository *repo)
11849 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11850 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11851 const struct got_error *err = NULL;
11852 struct got_commit_object *commit = NULL;
11853 int logmsg_len;
11854 int fd = -1;
11855 struct got_histedit_list_entry *folded = NULL;
11857 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11858 if (err)
11859 return err;
11861 folded = get_folded_commits(hle);
11862 if (folded) {
11863 while (folded != hle) {
11864 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11865 folded = TAILQ_NEXT(folded, entry);
11866 continue;
11868 err = append_folded_commit_msg(&new_msg, folded,
11869 logmsg, repo);
11870 if (err)
11871 goto done;
11872 free(logmsg);
11873 logmsg = new_msg;
11874 folded = TAILQ_NEXT(folded, entry);
11878 err = got_object_id_str(&id_str, hle->commit_id);
11879 if (err)
11880 goto done;
11881 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11882 if (err)
11883 goto done;
11884 logmsg_len = asprintf(&new_msg,
11885 "%s\n# original log message of commit %s: %s",
11886 logmsg ? logmsg : "", id_str, orig_logmsg);
11887 if (logmsg_len == -1) {
11888 err = got_error_from_errno("asprintf");
11889 goto done;
11891 free(logmsg);
11892 logmsg = new_msg;
11894 err = got_object_id_str(&id_str, hle->commit_id);
11895 if (err)
11896 goto done;
11898 err = got_opentemp_named_fd(&logmsg_path, &fd,
11899 GOT_TMPDIR_STR "/got-logmsg", "");
11900 if (err)
11901 goto done;
11903 if (write(fd, logmsg, logmsg_len) == -1) {
11904 err = got_error_from_errno2("write", logmsg_path);
11905 goto done;
11907 if (close(fd) == -1) {
11908 err = got_error_from_errno2("close", logmsg_path);
11909 goto done;
11911 fd = -1;
11913 err = get_editor(&editor);
11914 if (err)
11915 goto done;
11917 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11918 logmsg_len, 0);
11919 if (err) {
11920 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11921 goto done;
11922 err = NULL;
11923 hle->logmsg = strdup(new_msg);
11924 if (hle->logmsg == NULL)
11925 err = got_error_from_errno("strdup");
11927 done:
11928 if (fd != -1 && close(fd) == -1 && err == NULL)
11929 err = got_error_from_errno2("close", logmsg_path);
11930 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11931 err = got_error_from_errno2("unlink", logmsg_path);
11932 free(logmsg_path);
11933 free(logmsg);
11934 free(orig_logmsg);
11935 free(editor);
11936 if (commit)
11937 got_object_commit_close(commit);
11938 return err;
11941 static const struct got_error *
11942 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11943 FILE *f, struct got_repository *repo)
11945 const struct got_error *err = NULL;
11946 char *line = NULL, *p, *end;
11947 size_t i, linesize = 0;
11948 ssize_t linelen;
11949 int lineno = 0, lastcmd = -1;
11950 const struct got_histedit_cmd *cmd;
11951 struct got_object_id *commit_id = NULL;
11952 struct got_histedit_list_entry *hle = NULL;
11954 for (;;) {
11955 linelen = getline(&line, &linesize, f);
11956 if (linelen == -1) {
11957 const struct got_error *getline_err;
11958 if (feof(f))
11959 break;
11960 getline_err = got_error_from_errno("getline");
11961 err = got_ferror(f, getline_err->code);
11962 break;
11964 lineno++;
11965 p = line;
11966 while (isspace((unsigned char)p[0]))
11967 p++;
11968 if (p[0] == '#' || p[0] == '\0')
11969 continue;
11970 cmd = NULL;
11971 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11972 cmd = &got_histedit_cmds[i];
11973 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11974 isspace((unsigned char)p[strlen(cmd->name)])) {
11975 p += strlen(cmd->name);
11976 break;
11978 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11979 p++;
11980 break;
11983 if (i == nitems(got_histedit_cmds)) {
11984 err = histedit_syntax_error(lineno);
11985 break;
11987 while (isspace((unsigned char)p[0]))
11988 p++;
11989 if (cmd->code == GOT_HISTEDIT_MESG) {
11990 if (lastcmd != GOT_HISTEDIT_PICK &&
11991 lastcmd != GOT_HISTEDIT_EDIT) {
11992 err = got_error(GOT_ERR_HISTEDIT_CMD);
11993 break;
11995 if (p[0] == '\0') {
11996 err = histedit_edit_logmsg(hle, repo);
11997 if (err)
11998 break;
11999 } else {
12000 hle->logmsg = strdup(p);
12001 if (hle->logmsg == NULL) {
12002 err = got_error_from_errno("strdup");
12003 break;
12006 lastcmd = cmd->code;
12007 continue;
12008 } else {
12009 end = p;
12010 while (end[0] && !isspace((unsigned char)end[0]))
12011 end++;
12012 *end = '\0';
12014 err = got_object_resolve_id_str(&commit_id, repo, p);
12015 if (err) {
12016 /* override error code */
12017 err = histedit_syntax_error(lineno);
12018 break;
12021 hle = malloc(sizeof(*hle));
12022 if (hle == NULL) {
12023 err = got_error_from_errno("malloc");
12024 break;
12026 hle->cmd = cmd;
12027 hle->commit_id = commit_id;
12028 hle->logmsg = NULL;
12029 commit_id = NULL;
12030 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12031 lastcmd = cmd->code;
12034 free(line);
12035 free(commit_id);
12036 return err;
12039 static const struct got_error *
12040 histedit_check_script(struct got_histedit_list *histedit_cmds,
12041 struct got_object_id_queue *commits, struct got_repository *repo)
12043 const struct got_error *err = NULL;
12044 struct got_object_qid *qid;
12045 struct got_histedit_list_entry *hle;
12046 static char msg[92];
12047 char *id_str;
12049 if (TAILQ_EMPTY(histedit_cmds))
12050 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12051 "histedit script contains no commands");
12052 if (STAILQ_EMPTY(commits))
12053 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12055 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12056 struct got_histedit_list_entry *hle2;
12057 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12058 if (hle == hle2)
12059 continue;
12060 if (got_object_id_cmp(hle->commit_id,
12061 hle2->commit_id) != 0)
12062 continue;
12063 err = got_object_id_str(&id_str, hle->commit_id);
12064 if (err)
12065 return err;
12066 snprintf(msg, sizeof(msg), "commit %s is listed "
12067 "more than once in histedit script", id_str);
12068 free(id_str);
12069 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12073 STAILQ_FOREACH(qid, commits, entry) {
12074 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12075 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12076 break;
12078 if (hle == NULL) {
12079 err = got_object_id_str(&id_str, &qid->id);
12080 if (err)
12081 return err;
12082 snprintf(msg, sizeof(msg),
12083 "commit %s missing from histedit script", id_str);
12084 free(id_str);
12085 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12089 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12090 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12091 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12092 "last commit in histedit script cannot be folded");
12094 return NULL;
12097 static const struct got_error *
12098 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12099 const char *path, struct got_object_id_queue *commits,
12100 struct got_repository *repo)
12102 const struct got_error *err = NULL;
12103 struct stat st, st2;
12104 struct timespec timeout;
12105 char *editor;
12106 FILE *f = NULL;
12108 err = get_editor(&editor);
12109 if (err)
12110 return err;
12112 if (stat(path, &st) == -1) {
12113 err = got_error_from_errno2("stat", path);
12114 goto done;
12117 if (spawn_editor(editor, path) == -1) {
12118 err = got_error_from_errno("failed spawning editor");
12119 goto done;
12122 timeout.tv_sec = 0;
12123 timeout.tv_nsec = 1;
12124 nanosleep(&timeout, NULL);
12126 if (stat(path, &st2) == -1) {
12127 err = got_error_from_errno2("stat", path);
12128 goto done;
12131 if (st.st_size == st2.st_size &&
12132 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12133 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12134 "no changes made to histedit script, aborting");
12135 goto done;
12138 f = fopen(path, "re");
12139 if (f == NULL) {
12140 err = got_error_from_errno("fopen");
12141 goto done;
12143 err = histedit_parse_list(histedit_cmds, f, repo);
12144 if (err)
12145 goto done;
12147 err = histedit_check_script(histedit_cmds, commits, repo);
12148 done:
12149 if (f && fclose(f) == EOF && err == NULL)
12150 err = got_error_from_errno("fclose");
12151 free(editor);
12152 return err;
12155 static const struct got_error *
12156 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12157 struct got_object_id_queue *, const char *, const char *,
12158 struct got_repository *);
12160 static const struct got_error *
12161 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12162 struct got_object_id_queue *commits, const char *branch_name,
12163 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12164 struct got_repository *repo)
12166 const struct got_error *err;
12167 FILE *f = NULL;
12168 char *path = NULL;
12170 err = got_opentemp_named(&path, &f, "got-histedit", "");
12171 if (err)
12172 return err;
12174 err = write_cmd_list(f, branch_name, commits);
12175 if (err)
12176 goto done;
12178 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12179 fold_only, drop_only, edit_only, repo);
12180 if (err)
12181 goto done;
12183 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12184 rewind(f);
12185 err = histedit_parse_list(histedit_cmds, f, repo);
12186 } else {
12187 if (fclose(f) == EOF) {
12188 err = got_error_from_errno("fclose");
12189 goto done;
12191 f = NULL;
12192 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12193 if (err) {
12194 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12195 err->code != GOT_ERR_HISTEDIT_CMD)
12196 goto done;
12197 err = histedit_edit_list_retry(histedit_cmds, err,
12198 commits, path, branch_name, repo);
12201 done:
12202 if (f && fclose(f) == EOF && err == NULL)
12203 err = got_error_from_errno("fclose");
12204 if (path && unlink(path) != 0 && err == NULL)
12205 err = got_error_from_errno2("unlink", path);
12206 free(path);
12207 return err;
12210 static const struct got_error *
12211 histedit_save_list(struct got_histedit_list *histedit_cmds,
12212 struct got_worktree *worktree, struct got_repository *repo)
12214 const struct got_error *err = NULL;
12215 char *path = NULL;
12216 FILE *f = NULL;
12217 struct got_histedit_list_entry *hle;
12219 err = got_worktree_get_histedit_script_path(&path, worktree);
12220 if (err)
12221 return err;
12223 f = fopen(path, "we");
12224 if (f == NULL) {
12225 err = got_error_from_errno2("fopen", path);
12226 goto done;
12228 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12229 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12230 repo);
12231 if (err)
12232 break;
12234 if (hle->logmsg) {
12235 int n = fprintf(f, "%c %s\n",
12236 GOT_HISTEDIT_MESG, hle->logmsg);
12237 if (n < 0) {
12238 err = got_ferror(f, GOT_ERR_IO);
12239 break;
12243 done:
12244 if (f && fclose(f) == EOF && err == NULL)
12245 err = got_error_from_errno("fclose");
12246 free(path);
12247 return err;
12250 static void
12251 histedit_free_list(struct got_histedit_list *histedit_cmds)
12253 struct got_histedit_list_entry *hle;
12255 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12256 TAILQ_REMOVE(histedit_cmds, hle, entry);
12257 free(hle);
12261 static const struct got_error *
12262 histedit_load_list(struct got_histedit_list *histedit_cmds,
12263 const char *path, struct got_repository *repo)
12265 const struct got_error *err = NULL;
12266 FILE *f = NULL;
12268 f = fopen(path, "re");
12269 if (f == NULL) {
12270 err = got_error_from_errno2("fopen", path);
12271 goto done;
12274 err = histedit_parse_list(histedit_cmds, f, repo);
12275 done:
12276 if (f && fclose(f) == EOF && err == NULL)
12277 err = got_error_from_errno("fclose");
12278 return err;
12281 static const struct got_error *
12282 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12283 const struct got_error *edit_err, struct got_object_id_queue *commits,
12284 const char *path, const char *branch_name, struct got_repository *repo)
12286 const struct got_error *err = NULL, *prev_err = edit_err;
12287 int resp = ' ';
12289 while (resp != 'c' && resp != 'r' && resp != 'a') {
12290 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12291 "or (a)bort: ", getprogname(), prev_err->msg);
12292 resp = getchar();
12293 if (resp == '\n')
12294 resp = getchar();
12295 if (resp == 'c') {
12296 histedit_free_list(histedit_cmds);
12297 err = histedit_run_editor(histedit_cmds, path, commits,
12298 repo);
12299 if (err) {
12300 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12301 err->code != GOT_ERR_HISTEDIT_CMD)
12302 break;
12303 prev_err = err;
12304 resp = ' ';
12305 continue;
12307 break;
12308 } else if (resp == 'r') {
12309 histedit_free_list(histedit_cmds);
12310 err = histedit_edit_script(histedit_cmds,
12311 commits, branch_name, 0, 0, 0, 0, repo);
12312 if (err) {
12313 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12314 err->code != GOT_ERR_HISTEDIT_CMD)
12315 break;
12316 prev_err = err;
12317 resp = ' ';
12318 continue;
12320 break;
12321 } else if (resp == 'a') {
12322 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12323 break;
12324 } else
12325 printf("invalid response '%c'\n", resp);
12328 return err;
12331 static const struct got_error *
12332 histedit_complete(struct got_worktree *worktree,
12333 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12334 struct got_reference *branch, struct got_repository *repo)
12336 printf("Switching work tree to %s\n",
12337 got_ref_get_symref_target(branch));
12338 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12339 branch, repo);
12342 static const struct got_error *
12343 show_histedit_progress(struct got_commit_object *commit,
12344 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12346 const struct got_error *err;
12347 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12349 err = got_object_id_str(&old_id_str, hle->commit_id);
12350 if (err)
12351 goto done;
12353 if (new_id) {
12354 err = got_object_id_str(&new_id_str, new_id);
12355 if (err)
12356 goto done;
12359 old_id_str[12] = '\0';
12360 if (new_id_str)
12361 new_id_str[12] = '\0';
12363 if (hle->logmsg) {
12364 logmsg = strdup(hle->logmsg);
12365 if (logmsg == NULL) {
12366 err = got_error_from_errno("strdup");
12367 goto done;
12369 trim_logmsg(logmsg, 42);
12370 } else {
12371 err = get_short_logmsg(&logmsg, 42, commit);
12372 if (err)
12373 goto done;
12376 switch (hle->cmd->code) {
12377 case GOT_HISTEDIT_PICK:
12378 case GOT_HISTEDIT_EDIT:
12379 printf("%s -> %s: %s\n", old_id_str,
12380 new_id_str ? new_id_str : "no-op change", logmsg);
12381 break;
12382 case GOT_HISTEDIT_DROP:
12383 case GOT_HISTEDIT_FOLD:
12384 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12385 logmsg);
12386 break;
12387 default:
12388 break;
12390 done:
12391 free(old_id_str);
12392 free(new_id_str);
12393 return err;
12396 static const struct got_error *
12397 histedit_commit(struct got_pathlist_head *merged_paths,
12398 struct got_worktree *worktree, struct got_fileindex *fileindex,
12399 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12400 const char *committer, int allow_conflict, struct got_repository *repo)
12402 const struct got_error *err;
12403 struct got_commit_object *commit;
12404 struct got_object_id *new_commit_id;
12406 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12407 && hle->logmsg == NULL) {
12408 err = histedit_edit_logmsg(hle, repo);
12409 if (err)
12410 return err;
12413 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12414 if (err)
12415 return err;
12417 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12418 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12419 hle->logmsg, allow_conflict, repo);
12420 if (err) {
12421 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12422 goto done;
12423 err = show_histedit_progress(commit, hle, NULL);
12424 } else {
12425 err = show_histedit_progress(commit, hle, new_commit_id);
12426 free(new_commit_id);
12428 done:
12429 got_object_commit_close(commit);
12430 return err;
12433 static const struct got_error *
12434 histedit_skip_commit(struct got_histedit_list_entry *hle,
12435 struct got_worktree *worktree, struct got_repository *repo)
12437 const struct got_error *error;
12438 struct got_commit_object *commit;
12440 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12441 repo);
12442 if (error)
12443 return error;
12445 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12446 if (error)
12447 return error;
12449 error = show_histedit_progress(commit, hle, NULL);
12450 got_object_commit_close(commit);
12451 return error;
12454 static const struct got_error *
12455 check_local_changes(void *arg, unsigned char status,
12456 unsigned char staged_status, const char *path,
12457 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12458 struct got_object_id *commit_id, int dirfd, const char *de_name)
12460 int *have_local_changes = arg;
12462 switch (status) {
12463 case GOT_STATUS_ADD:
12464 case GOT_STATUS_DELETE:
12465 case GOT_STATUS_MODIFY:
12466 case GOT_STATUS_CONFLICT:
12467 *have_local_changes = 1;
12468 return got_error(GOT_ERR_CANCELLED);
12469 default:
12470 break;
12473 switch (staged_status) {
12474 case GOT_STATUS_ADD:
12475 case GOT_STATUS_DELETE:
12476 case GOT_STATUS_MODIFY:
12477 *have_local_changes = 1;
12478 return got_error(GOT_ERR_CANCELLED);
12479 default:
12480 break;
12483 return NULL;
12486 static const struct got_error *
12487 cmd_histedit(int argc, char *argv[])
12489 const struct got_error *error = NULL;
12490 struct got_worktree *worktree = NULL;
12491 struct got_fileindex *fileindex = NULL;
12492 struct got_repository *repo = NULL;
12493 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12494 struct got_reference *branch = NULL;
12495 struct got_reference *tmp_branch = NULL;
12496 struct got_object_id *resume_commit_id = NULL;
12497 struct got_object_id *base_commit_id = NULL;
12498 struct got_object_id *head_commit_id = NULL;
12499 struct got_commit_object *commit = NULL;
12500 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12501 struct got_update_progress_arg upa;
12502 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12503 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12504 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12505 const char *edit_script_path = NULL;
12506 struct got_object_id_queue commits;
12507 struct got_pathlist_head merged_paths;
12508 const struct got_object_id_queue *parent_ids;
12509 struct got_object_qid *pid;
12510 struct got_histedit_list histedit_cmds;
12511 struct got_histedit_list_entry *hle;
12512 int *pack_fds = NULL;
12514 STAILQ_INIT(&commits);
12515 TAILQ_INIT(&histedit_cmds);
12516 TAILQ_INIT(&merged_paths);
12517 memset(&upa, 0, sizeof(upa));
12519 #ifndef PROFILE
12520 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12521 "unveil", NULL) == -1)
12522 err(1, "pledge");
12523 #endif
12525 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12526 switch (ch) {
12527 case 'a':
12528 abort_edit = 1;
12529 break;
12530 case 'C':
12531 allow_conflict = 1;
12532 break;
12533 case 'c':
12534 continue_edit = 1;
12535 break;
12536 case 'd':
12537 drop_only = 1;
12538 break;
12539 case 'e':
12540 edit_only = 1;
12541 break;
12542 case 'F':
12543 edit_script_path = optarg;
12544 break;
12545 case 'f':
12546 fold_only = 1;
12547 break;
12548 case 'l':
12549 list_backups = 1;
12550 break;
12551 case 'm':
12552 edit_logmsg_only = 1;
12553 break;
12554 case 'X':
12555 delete_backups = 1;
12556 break;
12557 default:
12558 usage_histedit();
12559 /* NOTREACHED */
12563 argc -= optind;
12564 argv += optind;
12566 if (abort_edit && allow_conflict)
12567 option_conflict('a', 'C');
12568 if (abort_edit && continue_edit)
12569 option_conflict('a', 'c');
12570 if (edit_script_path && allow_conflict)
12571 option_conflict('F', 'C');
12572 if (edit_script_path && edit_logmsg_only)
12573 option_conflict('F', 'm');
12574 if (abort_edit && edit_logmsg_only)
12575 option_conflict('a', 'm');
12576 if (edit_logmsg_only && allow_conflict)
12577 option_conflict('m', 'C');
12578 if (continue_edit && edit_logmsg_only)
12579 option_conflict('c', 'm');
12580 if (abort_edit && fold_only)
12581 option_conflict('a', 'f');
12582 if (fold_only && allow_conflict)
12583 option_conflict('f', 'C');
12584 if (continue_edit && fold_only)
12585 option_conflict('c', 'f');
12586 if (fold_only && edit_logmsg_only)
12587 option_conflict('f', 'm');
12588 if (edit_script_path && fold_only)
12589 option_conflict('F', 'f');
12590 if (abort_edit && edit_only)
12591 option_conflict('a', 'e');
12592 if (continue_edit && edit_only)
12593 option_conflict('c', 'e');
12594 if (edit_only && edit_logmsg_only)
12595 option_conflict('e', 'm');
12596 if (edit_script_path && edit_only)
12597 option_conflict('F', 'e');
12598 if (fold_only && edit_only)
12599 option_conflict('f', 'e');
12600 if (drop_only && abort_edit)
12601 option_conflict('d', 'a');
12602 if (drop_only && allow_conflict)
12603 option_conflict('d', 'C');
12604 if (drop_only && continue_edit)
12605 option_conflict('d', 'c');
12606 if (drop_only && edit_logmsg_only)
12607 option_conflict('d', 'm');
12608 if (drop_only && edit_only)
12609 option_conflict('d', 'e');
12610 if (drop_only && edit_script_path)
12611 option_conflict('d', 'F');
12612 if (drop_only && fold_only)
12613 option_conflict('d', 'f');
12614 if (list_backups) {
12615 if (abort_edit)
12616 option_conflict('l', 'a');
12617 if (allow_conflict)
12618 option_conflict('l', 'C');
12619 if (continue_edit)
12620 option_conflict('l', 'c');
12621 if (edit_script_path)
12622 option_conflict('l', 'F');
12623 if (edit_logmsg_only)
12624 option_conflict('l', 'm');
12625 if (drop_only)
12626 option_conflict('l', 'd');
12627 if (fold_only)
12628 option_conflict('l', 'f');
12629 if (edit_only)
12630 option_conflict('l', 'e');
12631 if (delete_backups)
12632 option_conflict('l', 'X');
12633 if (argc != 0 && argc != 1)
12634 usage_histedit();
12635 } else if (delete_backups) {
12636 if (abort_edit)
12637 option_conflict('X', 'a');
12638 if (allow_conflict)
12639 option_conflict('X', 'C');
12640 if (continue_edit)
12641 option_conflict('X', 'c');
12642 if (drop_only)
12643 option_conflict('X', 'd');
12644 if (edit_script_path)
12645 option_conflict('X', 'F');
12646 if (edit_logmsg_only)
12647 option_conflict('X', 'm');
12648 if (fold_only)
12649 option_conflict('X', 'f');
12650 if (edit_only)
12651 option_conflict('X', 'e');
12652 if (list_backups)
12653 option_conflict('X', 'l');
12654 if (argc != 0 && argc != 1)
12655 usage_histedit();
12656 } else if (allow_conflict && !continue_edit)
12657 errx(1, "-C option requires -c");
12658 else if (argc != 0)
12659 usage_histedit();
12662 * This command cannot apply unveil(2) in all cases because the
12663 * user may choose to run an editor to edit the histedit script
12664 * and to edit individual commit log messages.
12665 * unveil(2) traverses exec(2); if an editor is used we have to
12666 * apply unveil after edit script and log messages have been written.
12667 * XXX TODO: Make use of unveil(2) where possible.
12670 cwd = getcwd(NULL, 0);
12671 if (cwd == NULL) {
12672 error = got_error_from_errno("getcwd");
12673 goto done;
12676 error = got_repo_pack_fds_open(&pack_fds);
12677 if (error != NULL)
12678 goto done;
12680 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12681 if (error) {
12682 if (list_backups || delete_backups) {
12683 if (error->code != GOT_ERR_NOT_WORKTREE)
12684 goto done;
12685 } else {
12686 if (error->code == GOT_ERR_NOT_WORKTREE)
12687 error = wrap_not_worktree_error(error,
12688 "histedit", cwd);
12689 goto done;
12693 if (list_backups || delete_backups) {
12694 error = got_repo_open(&repo,
12695 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12696 NULL, pack_fds);
12697 if (error != NULL)
12698 goto done;
12699 error = apply_unveil(got_repo_get_path(repo), 0,
12700 worktree ? got_worktree_get_root_path(worktree) : NULL);
12701 if (error)
12702 goto done;
12703 error = process_backup_refs(
12704 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12705 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12706 goto done; /* nothing else to do */
12709 error = get_gitconfig_path(&gitconfig_path);
12710 if (error)
12711 goto done;
12712 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12713 gitconfig_path, pack_fds);
12714 if (error != NULL)
12715 goto done;
12717 if (worktree != NULL && !list_backups && !delete_backups) {
12718 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12719 if (error)
12720 goto done;
12723 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12724 if (error)
12725 goto done;
12726 if (rebase_in_progress) {
12727 error = got_error(GOT_ERR_REBASING);
12728 goto done;
12731 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12732 repo);
12733 if (error)
12734 goto done;
12735 if (merge_in_progress) {
12736 error = got_error(GOT_ERR_MERGE_BUSY);
12737 goto done;
12740 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12741 if (error)
12742 goto done;
12744 if (edit_in_progress && edit_logmsg_only) {
12745 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12746 "histedit operation is in progress in this "
12747 "work tree and must be continued or aborted "
12748 "before the -m option can be used");
12749 goto done;
12751 if (edit_in_progress && drop_only) {
12752 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12753 "histedit operation is in progress in this "
12754 "work tree and must be continued or aborted "
12755 "before the -d option can be used");
12756 goto done;
12758 if (edit_in_progress && fold_only) {
12759 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12760 "histedit operation is in progress in this "
12761 "work tree and must be continued or aborted "
12762 "before the -f option can be used");
12763 goto done;
12765 if (edit_in_progress && edit_only) {
12766 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12767 "histedit operation is in progress in this "
12768 "work tree and must be continued or aborted "
12769 "before the -e option can be used");
12770 goto done;
12773 if (edit_in_progress && abort_edit) {
12774 error = got_worktree_histedit_continue(&resume_commit_id,
12775 &tmp_branch, &branch, &base_commit_id, &fileindex,
12776 worktree, repo);
12777 if (error)
12778 goto done;
12779 printf("Switching work tree to %s\n",
12780 got_ref_get_symref_target(branch));
12781 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12782 branch, base_commit_id, abort_progress, &upa);
12783 if (error)
12784 goto done;
12785 printf("Histedit of %s aborted\n",
12786 got_ref_get_symref_target(branch));
12787 print_merge_progress_stats(&upa);
12788 goto done; /* nothing else to do */
12789 } else if (abort_edit) {
12790 error = got_error(GOT_ERR_NOT_HISTEDIT);
12791 goto done;
12794 error = get_author(&committer, repo, worktree);
12795 if (error)
12796 goto done;
12798 if (continue_edit) {
12799 char *path;
12801 if (!edit_in_progress) {
12802 error = got_error(GOT_ERR_NOT_HISTEDIT);
12803 goto done;
12806 error = got_worktree_get_histedit_script_path(&path, worktree);
12807 if (error)
12808 goto done;
12810 error = histedit_load_list(&histedit_cmds, path, repo);
12811 free(path);
12812 if (error)
12813 goto done;
12815 error = got_worktree_histedit_continue(&resume_commit_id,
12816 &tmp_branch, &branch, &base_commit_id, &fileindex,
12817 worktree, repo);
12818 if (error)
12819 goto done;
12821 error = got_ref_resolve(&head_commit_id, repo, branch);
12822 if (error)
12823 goto done;
12825 error = got_object_open_as_commit(&commit, repo,
12826 head_commit_id);
12827 if (error)
12828 goto done;
12829 parent_ids = got_object_commit_get_parent_ids(commit);
12830 pid = STAILQ_FIRST(parent_ids);
12831 if (pid == NULL) {
12832 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12833 goto done;
12835 error = collect_commits(&commits, head_commit_id, &pid->id,
12836 base_commit_id, got_worktree_get_path_prefix(worktree),
12837 GOT_ERR_HISTEDIT_PATH, repo);
12838 got_object_commit_close(commit);
12839 commit = NULL;
12840 if (error)
12841 goto done;
12842 } else {
12843 if (edit_in_progress) {
12844 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12845 goto done;
12848 error = got_ref_open(&branch, repo,
12849 got_worktree_get_head_ref_name(worktree), 0);
12850 if (error != NULL)
12851 goto done;
12853 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12854 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12855 "will not edit commit history of a branch outside "
12856 "the \"refs/heads/\" reference namespace");
12857 goto done;
12860 error = got_ref_resolve(&head_commit_id, repo, branch);
12861 got_ref_close(branch);
12862 branch = NULL;
12863 if (error)
12864 goto done;
12866 error = got_object_open_as_commit(&commit, repo,
12867 head_commit_id);
12868 if (error)
12869 goto done;
12870 parent_ids = got_object_commit_get_parent_ids(commit);
12871 pid = STAILQ_FIRST(parent_ids);
12872 if (pid == NULL) {
12873 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12874 goto done;
12876 error = collect_commits(&commits, head_commit_id, &pid->id,
12877 got_worktree_get_base_commit_id(worktree),
12878 got_worktree_get_path_prefix(worktree),
12879 GOT_ERR_HISTEDIT_PATH, repo);
12880 got_object_commit_close(commit);
12881 commit = NULL;
12882 if (error)
12883 goto done;
12885 if (STAILQ_EMPTY(&commits)) {
12886 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12887 goto done;
12890 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12891 &base_commit_id, &fileindex, worktree, repo);
12892 if (error)
12893 goto done;
12895 if (edit_script_path) {
12896 error = histedit_load_list(&histedit_cmds,
12897 edit_script_path, repo);
12898 if (error) {
12899 got_worktree_histedit_abort(worktree, fileindex,
12900 repo, branch, base_commit_id,
12901 abort_progress, &upa);
12902 print_merge_progress_stats(&upa);
12903 goto done;
12905 } else {
12906 const char *branch_name;
12907 branch_name = got_ref_get_symref_target(branch);
12908 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12909 branch_name += 11;
12910 error = histedit_edit_script(&histedit_cmds, &commits,
12911 branch_name, edit_logmsg_only, fold_only,
12912 drop_only, edit_only, repo);
12913 if (error) {
12914 got_worktree_histedit_abort(worktree, fileindex,
12915 repo, branch, base_commit_id,
12916 abort_progress, &upa);
12917 print_merge_progress_stats(&upa);
12918 goto done;
12923 error = histedit_save_list(&histedit_cmds, worktree,
12924 repo);
12925 if (error) {
12926 got_worktree_histedit_abort(worktree, fileindex,
12927 repo, branch, base_commit_id,
12928 abort_progress, &upa);
12929 print_merge_progress_stats(&upa);
12930 goto done;
12935 error = histedit_check_script(&histedit_cmds, &commits, repo);
12936 if (error)
12937 goto done;
12939 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12940 if (resume_commit_id) {
12941 if (got_object_id_cmp(hle->commit_id,
12942 resume_commit_id) != 0)
12943 continue;
12945 resume_commit_id = NULL;
12946 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12947 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12948 error = histedit_skip_commit(hle, worktree,
12949 repo);
12950 if (error)
12951 goto done;
12952 } else {
12953 struct got_pathlist_head paths;
12954 int have_changes = 0;
12956 TAILQ_INIT(&paths);
12957 error = got_pathlist_append(&paths, "", NULL);
12958 if (error)
12959 goto done;
12960 error = got_worktree_status(worktree, &paths,
12961 repo, 0, check_local_changes, &have_changes,
12962 check_cancelled, NULL);
12963 got_pathlist_free(&paths,
12964 GOT_PATHLIST_FREE_NONE);
12965 if (error) {
12966 if (error->code != GOT_ERR_CANCELLED)
12967 goto done;
12968 if (sigint_received || sigpipe_received)
12969 goto done;
12971 if (have_changes) {
12972 error = histedit_commit(NULL, worktree,
12973 fileindex, tmp_branch, hle,
12974 committer, allow_conflict, repo);
12975 if (error)
12976 goto done;
12977 } else {
12978 error = got_object_open_as_commit(
12979 &commit, repo, hle->commit_id);
12980 if (error)
12981 goto done;
12982 error = show_histedit_progress(commit,
12983 hle, NULL);
12984 got_object_commit_close(commit);
12985 commit = NULL;
12986 if (error)
12987 goto done;
12990 continue;
12993 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12994 error = histedit_skip_commit(hle, worktree, repo);
12995 if (error)
12996 goto done;
12997 continue;
13000 error = got_object_open_as_commit(&commit, repo,
13001 hle->commit_id);
13002 if (error)
13003 goto done;
13004 parent_ids = got_object_commit_get_parent_ids(commit);
13005 pid = STAILQ_FIRST(parent_ids);
13007 error = got_worktree_histedit_merge_files(&merged_paths,
13008 worktree, fileindex, &pid->id, hle->commit_id, repo,
13009 update_progress, &upa, check_cancelled, NULL);
13010 if (error)
13011 goto done;
13012 got_object_commit_close(commit);
13013 commit = NULL;
13015 print_merge_progress_stats(&upa);
13016 if (upa.conflicts > 0 || upa.missing > 0 ||
13017 upa.not_deleted > 0 || upa.unversioned > 0) {
13018 if (upa.conflicts > 0) {
13019 error = show_rebase_merge_conflict(
13020 hle->commit_id, repo);
13021 if (error)
13022 goto done;
13024 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13025 break;
13028 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13029 char *id_str;
13030 error = got_object_id_str(&id_str, hle->commit_id);
13031 if (error)
13032 goto done;
13033 printf("Stopping histedit for amending commit %s\n",
13034 id_str);
13035 free(id_str);
13036 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13037 error = got_worktree_histedit_postpone(worktree,
13038 fileindex);
13039 goto done;
13042 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13043 error = histedit_skip_commit(hle, worktree, repo);
13044 if (error)
13045 goto done;
13046 continue;
13049 error = histedit_commit(&merged_paths, worktree, fileindex,
13050 tmp_branch, hle, committer, allow_conflict, repo);
13051 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13052 if (error)
13053 goto done;
13056 if (upa.conflicts > 0 || upa.missing > 0 ||
13057 upa.not_deleted > 0 || upa.unversioned > 0) {
13058 error = got_worktree_histedit_postpone(worktree, fileindex);
13059 if (error)
13060 goto done;
13061 if (upa.conflicts > 0 && upa.missing == 0 &&
13062 upa.not_deleted == 0 && upa.unversioned == 0) {
13063 error = got_error_msg(GOT_ERR_CONFLICTS,
13064 "conflicts must be resolved before histedit "
13065 "can continue");
13066 } else if (upa.conflicts > 0) {
13067 error = got_error_msg(GOT_ERR_CONFLICTS,
13068 "conflicts must be resolved before histedit "
13069 "can continue; changes destined for some "
13070 "files were not yet merged and should be "
13071 "merged manually if required before the "
13072 "histedit operation is continued");
13073 } else {
13074 error = got_error_msg(GOT_ERR_CONFLICTS,
13075 "changes destined for some files were not "
13076 "yet merged and should be merged manually "
13077 "if required before the histedit operation "
13078 "is continued");
13080 } else
13081 error = histedit_complete(worktree, fileindex, tmp_branch,
13082 branch, repo);
13083 done:
13084 free(cwd);
13085 free(committer);
13086 free(gitconfig_path);
13087 got_object_id_queue_free(&commits);
13088 histedit_free_list(&histedit_cmds);
13089 free(head_commit_id);
13090 free(base_commit_id);
13091 free(resume_commit_id);
13092 if (commit)
13093 got_object_commit_close(commit);
13094 if (branch)
13095 got_ref_close(branch);
13096 if (tmp_branch)
13097 got_ref_close(tmp_branch);
13098 if (worktree)
13099 got_worktree_close(worktree);
13100 if (repo) {
13101 const struct got_error *close_err = got_repo_close(repo);
13102 if (error == NULL)
13103 error = close_err;
13105 if (pack_fds) {
13106 const struct got_error *pack_err =
13107 got_repo_pack_fds_close(pack_fds);
13108 if (error == NULL)
13109 error = pack_err;
13111 return error;
13114 __dead static void
13115 usage_integrate(void)
13117 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13118 exit(1);
13121 static const struct got_error *
13122 cmd_integrate(int argc, char *argv[])
13124 const struct got_error *error = NULL;
13125 struct got_repository *repo = NULL;
13126 struct got_worktree *worktree = NULL;
13127 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13128 const char *branch_arg = NULL;
13129 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13130 struct got_fileindex *fileindex = NULL;
13131 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13132 int ch;
13133 struct got_update_progress_arg upa;
13134 int *pack_fds = NULL;
13136 #ifndef PROFILE
13137 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13138 "unveil", NULL) == -1)
13139 err(1, "pledge");
13140 #endif
13142 while ((ch = getopt(argc, argv, "")) != -1) {
13143 switch (ch) {
13144 default:
13145 usage_integrate();
13146 /* NOTREACHED */
13150 argc -= optind;
13151 argv += optind;
13153 if (argc != 1)
13154 usage_integrate();
13155 branch_arg = argv[0];
13157 cwd = getcwd(NULL, 0);
13158 if (cwd == NULL) {
13159 error = got_error_from_errno("getcwd");
13160 goto done;
13163 error = got_repo_pack_fds_open(&pack_fds);
13164 if (error != NULL)
13165 goto done;
13167 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13168 if (error) {
13169 if (error->code == GOT_ERR_NOT_WORKTREE)
13170 error = wrap_not_worktree_error(error, "integrate",
13171 cwd);
13172 goto done;
13175 error = check_rebase_or_histedit_in_progress(worktree);
13176 if (error)
13177 goto done;
13179 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13180 NULL, pack_fds);
13181 if (error != NULL)
13182 goto done;
13184 error = apply_unveil(got_repo_get_path(repo), 0,
13185 got_worktree_get_root_path(worktree));
13186 if (error)
13187 goto done;
13189 error = check_merge_in_progress(worktree, repo);
13190 if (error)
13191 goto done;
13193 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13194 error = got_error_from_errno("asprintf");
13195 goto done;
13198 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13199 &base_branch_ref, worktree, refname, repo);
13200 if (error)
13201 goto done;
13203 refname = strdup(got_ref_get_name(branch_ref));
13204 if (refname == NULL) {
13205 error = got_error_from_errno("strdup");
13206 got_worktree_integrate_abort(worktree, fileindex, repo,
13207 branch_ref, base_branch_ref);
13208 goto done;
13210 base_refname = strdup(got_ref_get_name(base_branch_ref));
13211 if (base_refname == NULL) {
13212 error = got_error_from_errno("strdup");
13213 got_worktree_integrate_abort(worktree, fileindex, repo,
13214 branch_ref, base_branch_ref);
13215 goto done;
13217 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13218 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13219 got_worktree_integrate_abort(worktree, fileindex, repo,
13220 branch_ref, base_branch_ref);
13221 goto done;
13224 error = got_ref_resolve(&commit_id, repo, branch_ref);
13225 if (error)
13226 goto done;
13228 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13229 if (error)
13230 goto done;
13232 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13233 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13234 "specified branch has already been integrated");
13235 got_worktree_integrate_abort(worktree, fileindex, repo,
13236 branch_ref, base_branch_ref);
13237 goto done;
13240 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13241 if (error) {
13242 if (error->code == GOT_ERR_ANCESTRY)
13243 error = got_error(GOT_ERR_REBASE_REQUIRED);
13244 got_worktree_integrate_abort(worktree, fileindex, repo,
13245 branch_ref, base_branch_ref);
13246 goto done;
13249 memset(&upa, 0, sizeof(upa));
13250 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13251 branch_ref, base_branch_ref, update_progress, &upa,
13252 check_cancelled, NULL);
13253 if (error)
13254 goto done;
13256 printf("Integrated %s into %s\n", refname, base_refname);
13257 print_update_progress_stats(&upa);
13258 done:
13259 if (repo) {
13260 const struct got_error *close_err = got_repo_close(repo);
13261 if (error == NULL)
13262 error = close_err;
13264 if (worktree)
13265 got_worktree_close(worktree);
13266 if (pack_fds) {
13267 const struct got_error *pack_err =
13268 got_repo_pack_fds_close(pack_fds);
13269 if (error == NULL)
13270 error = pack_err;
13272 free(cwd);
13273 free(base_commit_id);
13274 free(commit_id);
13275 free(refname);
13276 free(base_refname);
13277 return error;
13280 __dead static void
13281 usage_merge(void)
13283 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13284 exit(1);
13287 static const struct got_error *
13288 cmd_merge(int argc, char *argv[])
13290 const struct got_error *error = NULL;
13291 struct got_worktree *worktree = NULL;
13292 struct got_repository *repo = NULL;
13293 struct got_fileindex *fileindex = NULL;
13294 char *cwd = NULL, *id_str = NULL, *author = NULL;
13295 char *gitconfig_path = NULL;
13296 struct got_reference *branch = NULL, *wt_branch = NULL;
13297 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13298 struct got_object_id *wt_branch_tip = NULL;
13299 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13300 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13301 struct got_update_progress_arg upa;
13302 struct got_object_id *merge_commit_id = NULL;
13303 char *branch_name = NULL;
13304 int *pack_fds = NULL;
13306 memset(&upa, 0, sizeof(upa));
13308 #ifndef PROFILE
13309 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13310 "unveil", NULL) == -1)
13311 err(1, "pledge");
13312 #endif
13314 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13315 switch (ch) {
13316 case 'a':
13317 abort_merge = 1;
13318 break;
13319 case 'C':
13320 allow_conflict = 1;
13321 break;
13322 case 'c':
13323 continue_merge = 1;
13324 break;
13325 case 'M':
13326 prefer_fast_forward = 0;
13327 break;
13328 case 'n':
13329 interrupt_merge = 1;
13330 break;
13331 default:
13332 usage_merge();
13333 /* NOTREACHED */
13337 argc -= optind;
13338 argv += optind;
13340 if (abort_merge) {
13341 if (continue_merge)
13342 option_conflict('a', 'c');
13343 if (!prefer_fast_forward)
13344 option_conflict('a', 'M');
13345 if (interrupt_merge)
13346 option_conflict('a', 'n');
13347 } else if (continue_merge) {
13348 if (!prefer_fast_forward)
13349 option_conflict('c', 'M');
13350 if (interrupt_merge)
13351 option_conflict('c', 'n');
13353 if (allow_conflict) {
13354 if (!continue_merge)
13355 errx(1, "-C option requires -c");
13357 if (abort_merge || continue_merge) {
13358 if (argc != 0)
13359 usage_merge();
13360 } else if (argc != 1)
13361 usage_merge();
13363 cwd = getcwd(NULL, 0);
13364 if (cwd == NULL) {
13365 error = got_error_from_errno("getcwd");
13366 goto done;
13369 error = got_repo_pack_fds_open(&pack_fds);
13370 if (error != NULL)
13371 goto done;
13373 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13374 if (error) {
13375 if (error->code == GOT_ERR_NOT_WORKTREE)
13376 error = wrap_not_worktree_error(error,
13377 "merge", cwd);
13378 goto done;
13381 error = get_gitconfig_path(&gitconfig_path);
13382 if (error)
13383 goto done;
13384 error = got_repo_open(&repo,
13385 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13386 gitconfig_path, pack_fds);
13387 if (error != NULL)
13388 goto done;
13390 if (worktree != NULL) {
13391 error = worktree_has_logmsg_ref("merge", worktree, repo);
13392 if (error)
13393 goto done;
13396 error = apply_unveil(got_repo_get_path(repo), 0,
13397 worktree ? got_worktree_get_root_path(worktree) : NULL);
13398 if (error)
13399 goto done;
13401 error = check_rebase_or_histedit_in_progress(worktree);
13402 if (error)
13403 goto done;
13405 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13406 repo);
13407 if (error)
13408 goto done;
13410 if (merge_in_progress && !(abort_merge || continue_merge)) {
13411 error = got_error(GOT_ERR_MERGE_BUSY);
13412 goto done;
13415 if (!merge_in_progress && (abort_merge || continue_merge)) {
13416 error = got_error(GOT_ERR_NOT_MERGING);
13417 goto done;
13420 if (abort_merge) {
13421 error = got_worktree_merge_continue(&branch_name,
13422 &branch_tip, &fileindex, worktree, repo);
13423 if (error)
13424 goto done;
13425 error = got_worktree_merge_abort(worktree, fileindex, repo,
13426 abort_progress, &upa);
13427 if (error)
13428 goto done;
13429 printf("Merge of %s aborted\n", branch_name);
13430 goto done; /* nothing else to do */
13433 if (strncmp(got_worktree_get_head_ref_name(worktree),
13434 "refs/heads/", 11) != 0) {
13435 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13436 "work tree's current branch %s is outside the "
13437 "\"refs/heads/\" reference namespace; "
13438 "update -b required",
13439 got_worktree_get_head_ref_name(worktree));
13440 goto done;
13443 error = get_author(&author, repo, worktree);
13444 if (error)
13445 goto done;
13447 error = got_ref_open(&wt_branch, repo,
13448 got_worktree_get_head_ref_name(worktree), 0);
13449 if (error)
13450 goto done;
13451 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13452 if (error)
13453 goto done;
13455 if (continue_merge) {
13456 struct got_object_id *base_commit_id;
13457 base_commit_id = got_worktree_get_base_commit_id(worktree);
13458 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13459 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13460 goto done;
13462 error = got_worktree_merge_continue(&branch_name,
13463 &branch_tip, &fileindex, worktree, repo);
13464 if (error)
13465 goto done;
13466 } else {
13467 error = got_ref_open(&branch, repo, argv[0], 0);
13468 if (error != NULL)
13469 goto done;
13470 branch_name = strdup(got_ref_get_name(branch));
13471 if (branch_name == NULL) {
13472 error = got_error_from_errno("strdup");
13473 goto done;
13475 error = got_ref_resolve(&branch_tip, repo, branch);
13476 if (error)
13477 goto done;
13480 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13481 wt_branch_tip, branch_tip, 0, repo,
13482 check_cancelled, NULL);
13483 if (error && error->code != GOT_ERR_ANCESTRY)
13484 goto done;
13486 if (!continue_merge) {
13487 error = check_path_prefix(wt_branch_tip, branch_tip,
13488 got_worktree_get_path_prefix(worktree),
13489 GOT_ERR_MERGE_PATH, repo);
13490 if (error)
13491 goto done;
13492 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13493 if (error)
13494 goto done;
13495 if (prefer_fast_forward && yca_id &&
13496 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13497 struct got_pathlist_head paths;
13498 if (interrupt_merge) {
13499 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13500 "there are no changes to merge since %s "
13501 "is already based on %s; merge cannot be "
13502 "interrupted for amending; -n",
13503 branch_name, got_ref_get_name(wt_branch));
13504 goto done;
13506 printf("Forwarding %s to %s\n",
13507 got_ref_get_name(wt_branch), branch_name);
13508 error = got_ref_change_ref(wt_branch, branch_tip);
13509 if (error)
13510 goto done;
13511 error = got_ref_write(wt_branch, repo);
13512 if (error)
13513 goto done;
13514 error = got_worktree_set_base_commit_id(worktree, repo,
13515 branch_tip);
13516 if (error)
13517 goto done;
13518 TAILQ_INIT(&paths);
13519 error = got_pathlist_append(&paths, "", NULL);
13520 if (error)
13521 goto done;
13522 error = got_worktree_checkout_files(worktree,
13523 &paths, repo, update_progress, &upa,
13524 check_cancelled, NULL);
13525 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13526 if (error)
13527 goto done;
13528 if (upa.did_something) {
13529 char *id_str;
13530 error = got_object_id_str(&id_str, branch_tip);
13531 if (error)
13532 goto done;
13533 printf("Updated to commit %s\n", id_str);
13534 free(id_str);
13535 } else
13536 printf("Already up-to-date\n");
13537 print_update_progress_stats(&upa);
13538 goto done;
13540 error = got_worktree_merge_write_refs(worktree, branch, repo);
13541 if (error)
13542 goto done;
13544 error = got_worktree_merge_branch(worktree, fileindex,
13545 yca_id, branch_tip, repo, update_progress, &upa,
13546 check_cancelled, NULL);
13547 if (error)
13548 goto done;
13549 print_merge_progress_stats(&upa);
13550 if (!upa.did_something) {
13551 error = got_worktree_merge_abort(worktree, fileindex,
13552 repo, abort_progress, &upa);
13553 if (error)
13554 goto done;
13555 printf("Already up-to-date\n");
13556 goto done;
13560 if (interrupt_merge) {
13561 error = got_worktree_merge_postpone(worktree, fileindex);
13562 if (error)
13563 goto done;
13564 printf("Merge of %s interrupted on request\n", branch_name);
13565 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13566 upa.not_deleted > 0 || upa.unversioned > 0) {
13567 error = got_worktree_merge_postpone(worktree, fileindex);
13568 if (error)
13569 goto done;
13570 if (upa.conflicts > 0 && upa.missing == 0 &&
13571 upa.not_deleted == 0 && upa.unversioned == 0) {
13572 error = got_error_msg(GOT_ERR_CONFLICTS,
13573 "conflicts must be resolved before merging "
13574 "can continue");
13575 } else if (upa.conflicts > 0) {
13576 error = got_error_msg(GOT_ERR_CONFLICTS,
13577 "conflicts must be resolved before merging "
13578 "can continue; changes destined for some "
13579 "files were not yet merged and "
13580 "should be merged manually if required before the "
13581 "merge operation is continued");
13582 } else {
13583 error = got_error_msg(GOT_ERR_CONFLICTS,
13584 "changes destined for some "
13585 "files were not yet merged and should be "
13586 "merged manually if required before the "
13587 "merge operation is continued");
13589 goto done;
13590 } else {
13591 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13592 fileindex, author, NULL, 1, branch_tip, branch_name,
13593 allow_conflict, repo, continue_merge ? print_status : NULL,
13594 NULL);
13595 if (error)
13596 goto done;
13597 error = got_worktree_merge_complete(worktree, fileindex, repo);
13598 if (error)
13599 goto done;
13600 error = got_object_id_str(&id_str, merge_commit_id);
13601 if (error)
13602 goto done;
13603 printf("Merged %s into %s: %s\n", branch_name,
13604 got_worktree_get_head_ref_name(worktree),
13605 id_str);
13608 done:
13609 free(gitconfig_path);
13610 free(id_str);
13611 free(merge_commit_id);
13612 free(author);
13613 free(branch_tip);
13614 free(branch_name);
13615 free(yca_id);
13616 if (branch)
13617 got_ref_close(branch);
13618 if (wt_branch)
13619 got_ref_close(wt_branch);
13620 if (worktree)
13621 got_worktree_close(worktree);
13622 if (repo) {
13623 const struct got_error *close_err = got_repo_close(repo);
13624 if (error == NULL)
13625 error = close_err;
13627 if (pack_fds) {
13628 const struct got_error *pack_err =
13629 got_repo_pack_fds_close(pack_fds);
13630 if (error == NULL)
13631 error = pack_err;
13633 return error;
13636 __dead static void
13637 usage_stage(void)
13639 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13640 "[path ...]\n", getprogname());
13641 exit(1);
13644 static const struct got_error *
13645 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13646 const char *path, struct got_object_id *blob_id,
13647 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13648 int dirfd, const char *de_name)
13650 const struct got_error *err = NULL;
13651 char *id_str = NULL;
13653 if (staged_status != GOT_STATUS_ADD &&
13654 staged_status != GOT_STATUS_MODIFY &&
13655 staged_status != GOT_STATUS_DELETE)
13656 return NULL;
13658 if (staged_status == GOT_STATUS_ADD ||
13659 staged_status == GOT_STATUS_MODIFY)
13660 err = got_object_id_str(&id_str, staged_blob_id);
13661 else
13662 err = got_object_id_str(&id_str, blob_id);
13663 if (err)
13664 return err;
13666 printf("%s %c %s\n", id_str, staged_status, path);
13667 free(id_str);
13668 return NULL;
13671 static const struct got_error *
13672 cmd_stage(int argc, char *argv[])
13674 const struct got_error *error = NULL;
13675 struct got_repository *repo = NULL;
13676 struct got_worktree *worktree = NULL;
13677 char *cwd = NULL;
13678 struct got_pathlist_head paths;
13679 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13680 FILE *patch_script_file = NULL;
13681 const char *patch_script_path = NULL;
13682 struct choose_patch_arg cpa;
13683 int *pack_fds = NULL;
13685 TAILQ_INIT(&paths);
13687 #ifndef PROFILE
13688 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13689 "unveil", NULL) == -1)
13690 err(1, "pledge");
13691 #endif
13693 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13694 switch (ch) {
13695 case 'F':
13696 patch_script_path = optarg;
13697 break;
13698 case 'l':
13699 list_stage = 1;
13700 break;
13701 case 'p':
13702 pflag = 1;
13703 break;
13704 case 'S':
13705 allow_bad_symlinks = 1;
13706 break;
13707 default:
13708 usage_stage();
13709 /* NOTREACHED */
13713 argc -= optind;
13714 argv += optind;
13716 if (list_stage && (pflag || patch_script_path))
13717 errx(1, "-l option cannot be used with other options");
13718 if (patch_script_path && !pflag)
13719 errx(1, "-F option can only be used together with -p option");
13721 cwd = getcwd(NULL, 0);
13722 if (cwd == NULL) {
13723 error = got_error_from_errno("getcwd");
13724 goto done;
13727 error = got_repo_pack_fds_open(&pack_fds);
13728 if (error != NULL)
13729 goto done;
13731 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13732 if (error) {
13733 if (error->code == GOT_ERR_NOT_WORKTREE)
13734 error = wrap_not_worktree_error(error, "stage", cwd);
13735 goto done;
13738 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13739 NULL, pack_fds);
13740 if (error != NULL)
13741 goto done;
13743 if (patch_script_path) {
13744 patch_script_file = fopen(patch_script_path, "re");
13745 if (patch_script_file == NULL) {
13746 error = got_error_from_errno2("fopen",
13747 patch_script_path);
13748 goto done;
13751 error = apply_unveil(got_repo_get_path(repo), 0,
13752 got_worktree_get_root_path(worktree));
13753 if (error)
13754 goto done;
13756 error = check_merge_in_progress(worktree, repo);
13757 if (error)
13758 goto done;
13760 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13761 if (error)
13762 goto done;
13764 if (list_stage)
13765 error = got_worktree_status(worktree, &paths, repo, 0,
13766 print_stage, NULL, check_cancelled, NULL);
13767 else {
13768 cpa.patch_script_file = patch_script_file;
13769 cpa.action = "stage";
13770 error = got_worktree_stage(worktree, &paths,
13771 pflag ? NULL : print_status, NULL,
13772 pflag ? choose_patch : NULL, &cpa,
13773 allow_bad_symlinks, repo);
13775 done:
13776 if (patch_script_file && fclose(patch_script_file) == EOF &&
13777 error == NULL)
13778 error = got_error_from_errno2("fclose", patch_script_path);
13779 if (repo) {
13780 const struct got_error *close_err = got_repo_close(repo);
13781 if (error == NULL)
13782 error = close_err;
13784 if (worktree)
13785 got_worktree_close(worktree);
13786 if (pack_fds) {
13787 const struct got_error *pack_err =
13788 got_repo_pack_fds_close(pack_fds);
13789 if (error == NULL)
13790 error = pack_err;
13792 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13793 free(cwd);
13794 return error;
13797 __dead static void
13798 usage_unstage(void)
13800 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13801 "[path ...]\n", getprogname());
13802 exit(1);
13806 static const struct got_error *
13807 cmd_unstage(int argc, char *argv[])
13809 const struct got_error *error = NULL;
13810 struct got_repository *repo = NULL;
13811 struct got_worktree *worktree = NULL;
13812 char *cwd = NULL;
13813 struct got_pathlist_head paths;
13814 int ch, pflag = 0;
13815 struct got_update_progress_arg upa;
13816 FILE *patch_script_file = NULL;
13817 const char *patch_script_path = NULL;
13818 struct choose_patch_arg cpa;
13819 int *pack_fds = NULL;
13821 TAILQ_INIT(&paths);
13823 #ifndef PROFILE
13824 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13825 "unveil", NULL) == -1)
13826 err(1, "pledge");
13827 #endif
13829 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13830 switch (ch) {
13831 case 'F':
13832 patch_script_path = optarg;
13833 break;
13834 case 'p':
13835 pflag = 1;
13836 break;
13837 default:
13838 usage_unstage();
13839 /* NOTREACHED */
13843 argc -= optind;
13844 argv += optind;
13846 if (patch_script_path && !pflag)
13847 errx(1, "-F option can only be used together with -p option");
13849 cwd = getcwd(NULL, 0);
13850 if (cwd == NULL) {
13851 error = got_error_from_errno("getcwd");
13852 goto done;
13855 error = got_repo_pack_fds_open(&pack_fds);
13856 if (error != NULL)
13857 goto done;
13859 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13860 if (error) {
13861 if (error->code == GOT_ERR_NOT_WORKTREE)
13862 error = wrap_not_worktree_error(error, "unstage", cwd);
13863 goto done;
13866 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13867 NULL, pack_fds);
13868 if (error != NULL)
13869 goto done;
13871 if (patch_script_path) {
13872 patch_script_file = fopen(patch_script_path, "re");
13873 if (patch_script_file == NULL) {
13874 error = got_error_from_errno2("fopen",
13875 patch_script_path);
13876 goto done;
13880 error = apply_unveil(got_repo_get_path(repo), 0,
13881 got_worktree_get_root_path(worktree));
13882 if (error)
13883 goto done;
13885 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13886 if (error)
13887 goto done;
13889 cpa.patch_script_file = patch_script_file;
13890 cpa.action = "unstage";
13891 memset(&upa, 0, sizeof(upa));
13892 error = got_worktree_unstage(worktree, &paths, update_progress,
13893 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13894 if (!error)
13895 print_merge_progress_stats(&upa);
13896 done:
13897 if (patch_script_file && fclose(patch_script_file) == EOF &&
13898 error == NULL)
13899 error = got_error_from_errno2("fclose", patch_script_path);
13900 if (repo) {
13901 const struct got_error *close_err = got_repo_close(repo);
13902 if (error == NULL)
13903 error = close_err;
13905 if (worktree)
13906 got_worktree_close(worktree);
13907 if (pack_fds) {
13908 const struct got_error *pack_err =
13909 got_repo_pack_fds_close(pack_fds);
13910 if (error == NULL)
13911 error = pack_err;
13913 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13914 free(cwd);
13915 return error;
13918 __dead static void
13919 usage_cat(void)
13921 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13922 "arg ...\n", getprogname());
13923 exit(1);
13926 static const struct got_error *
13927 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13929 const struct got_error *err;
13930 struct got_blob_object *blob;
13931 int fd = -1;
13933 fd = got_opentempfd();
13934 if (fd == -1)
13935 return got_error_from_errno("got_opentempfd");
13937 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13938 if (err)
13939 goto done;
13941 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13942 done:
13943 if (fd != -1 && close(fd) == -1 && err == NULL)
13944 err = got_error_from_errno("close");
13945 if (blob)
13946 got_object_blob_close(blob);
13947 return err;
13950 static const struct got_error *
13951 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13953 const struct got_error *err;
13954 struct got_tree_object *tree;
13955 int nentries, i;
13957 err = got_object_open_as_tree(&tree, repo, id);
13958 if (err)
13959 return err;
13961 nentries = got_object_tree_get_nentries(tree);
13962 for (i = 0; i < nentries; i++) {
13963 struct got_tree_entry *te;
13964 char *id_str;
13965 if (sigint_received || sigpipe_received)
13966 break;
13967 te = got_object_tree_get_entry(tree, i);
13968 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13969 if (err)
13970 break;
13971 fprintf(outfile, "%s %.7o %s\n", id_str,
13972 got_tree_entry_get_mode(te),
13973 got_tree_entry_get_name(te));
13974 free(id_str);
13977 got_object_tree_close(tree);
13978 return err;
13981 static const struct got_error *
13982 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13984 const struct got_error *err;
13985 struct got_commit_object *commit;
13986 const struct got_object_id_queue *parent_ids;
13987 struct got_object_qid *pid;
13988 char *id_str = NULL;
13989 const char *logmsg = NULL;
13990 char gmtoff[6];
13992 err = got_object_open_as_commit(&commit, repo, id);
13993 if (err)
13994 return err;
13996 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13997 if (err)
13998 goto done;
14000 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14001 parent_ids = got_object_commit_get_parent_ids(commit);
14002 fprintf(outfile, "numparents %d\n",
14003 got_object_commit_get_nparents(commit));
14004 STAILQ_FOREACH(pid, parent_ids, entry) {
14005 char *pid_str;
14006 err = got_object_id_str(&pid_str, &pid->id);
14007 if (err)
14008 goto done;
14009 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14010 free(pid_str);
14012 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14013 got_object_commit_get_author_gmtoff(commit));
14014 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14015 got_object_commit_get_author(commit),
14016 (long long)got_object_commit_get_author_time(commit),
14017 gmtoff);
14019 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14020 got_object_commit_get_committer_gmtoff(commit));
14021 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14022 got_object_commit_get_committer(commit),
14023 (long long)got_object_commit_get_committer_time(commit),
14024 gmtoff);
14026 logmsg = got_object_commit_get_logmsg_raw(commit);
14027 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14028 fprintf(outfile, "%s", logmsg);
14029 done:
14030 free(id_str);
14031 got_object_commit_close(commit);
14032 return err;
14035 static const struct got_error *
14036 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14038 const struct got_error *err;
14039 struct got_tag_object *tag;
14040 char *id_str = NULL;
14041 const char *tagmsg = NULL;
14042 char gmtoff[6];
14044 err = got_object_open_as_tag(&tag, repo, id);
14045 if (err)
14046 return err;
14048 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14049 if (err)
14050 goto done;
14052 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14054 switch (got_object_tag_get_object_type(tag)) {
14055 case GOT_OBJ_TYPE_BLOB:
14056 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14057 GOT_OBJ_LABEL_BLOB);
14058 break;
14059 case GOT_OBJ_TYPE_TREE:
14060 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14061 GOT_OBJ_LABEL_TREE);
14062 break;
14063 case GOT_OBJ_TYPE_COMMIT:
14064 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14065 GOT_OBJ_LABEL_COMMIT);
14066 break;
14067 case GOT_OBJ_TYPE_TAG:
14068 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14069 GOT_OBJ_LABEL_TAG);
14070 break;
14071 default:
14072 break;
14075 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14076 got_object_tag_get_name(tag));
14078 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14079 got_object_tag_get_tagger_gmtoff(tag));
14080 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14081 got_object_tag_get_tagger(tag),
14082 (long long)got_object_tag_get_tagger_time(tag),
14083 gmtoff);
14085 tagmsg = got_object_tag_get_message(tag);
14086 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14087 fprintf(outfile, "%s", tagmsg);
14088 done:
14089 free(id_str);
14090 got_object_tag_close(tag);
14091 return err;
14094 static const struct got_error *
14095 cmd_cat(int argc, char *argv[])
14097 const struct got_error *error;
14098 struct got_repository *repo = NULL;
14099 struct got_worktree *worktree = NULL;
14100 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14101 char *keyword_idstr = NULL;
14102 const char *commit_id_str = NULL;
14103 struct got_object_id *id = NULL, *commit_id = NULL;
14104 struct got_commit_object *commit = NULL;
14105 int ch, obj_type, i, force_path = 0;
14106 struct got_reflist_head refs;
14107 int *pack_fds = NULL;
14109 TAILQ_INIT(&refs);
14111 #ifndef PROFILE
14112 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14113 NULL) == -1)
14114 err(1, "pledge");
14115 #endif
14117 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14118 switch (ch) {
14119 case 'c':
14120 commit_id_str = optarg;
14121 break;
14122 case 'P':
14123 force_path = 1;
14124 break;
14125 case 'r':
14126 repo_path = realpath(optarg, NULL);
14127 if (repo_path == NULL)
14128 return got_error_from_errno2("realpath",
14129 optarg);
14130 got_path_strip_trailing_slashes(repo_path);
14131 break;
14132 default:
14133 usage_cat();
14134 /* NOTREACHED */
14138 argc -= optind;
14139 argv += optind;
14141 cwd = getcwd(NULL, 0);
14142 if (cwd == NULL) {
14143 error = got_error_from_errno("getcwd");
14144 goto done;
14147 error = got_repo_pack_fds_open(&pack_fds);
14148 if (error != NULL)
14149 goto done;
14151 if (repo_path == NULL) {
14152 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14153 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14154 goto done;
14155 if (worktree) {
14156 repo_path = strdup(
14157 got_worktree_get_repo_path(worktree));
14158 if (repo_path == NULL) {
14159 error = got_error_from_errno("strdup");
14160 goto done;
14163 if (commit_id_str == NULL) {
14164 /* Release work tree lock. */
14165 got_worktree_close(worktree);
14166 worktree = NULL;
14171 if (repo_path == NULL) {
14172 repo_path = strdup(cwd);
14173 if (repo_path == NULL)
14174 return got_error_from_errno("strdup");
14177 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14178 free(repo_path);
14179 if (error != NULL)
14180 goto done;
14182 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14183 if (error)
14184 goto done;
14186 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14187 if (error)
14188 goto done;
14190 if (commit_id_str != NULL) {
14191 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14192 repo, worktree);
14193 if (error != NULL)
14194 goto done;
14195 if (keyword_idstr != NULL)
14196 commit_id_str = keyword_idstr;
14197 if (worktree != NULL) {
14198 got_worktree_close(worktree);
14199 worktree = NULL;
14201 } else
14202 commit_id_str = GOT_REF_HEAD;
14203 error = got_repo_match_object_id(&commit_id, NULL,
14204 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14205 if (error)
14206 goto done;
14208 error = got_object_open_as_commit(&commit, repo, commit_id);
14209 if (error)
14210 goto done;
14212 for (i = 0; i < argc; i++) {
14213 if (force_path) {
14214 error = got_object_id_by_path(&id, repo, commit,
14215 argv[i]);
14216 if (error)
14217 break;
14218 } else {
14219 error = got_repo_match_object_id(&id, &label, argv[i],
14220 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14221 repo);
14222 if (error) {
14223 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14224 error->code != GOT_ERR_NOT_REF)
14225 break;
14226 error = got_object_id_by_path(&id, repo,
14227 commit, argv[i]);
14228 if (error)
14229 break;
14233 error = got_object_get_type(&obj_type, repo, id);
14234 if (error)
14235 break;
14237 switch (obj_type) {
14238 case GOT_OBJ_TYPE_BLOB:
14239 error = cat_blob(id, repo, stdout);
14240 break;
14241 case GOT_OBJ_TYPE_TREE:
14242 error = cat_tree(id, repo, stdout);
14243 break;
14244 case GOT_OBJ_TYPE_COMMIT:
14245 error = cat_commit(id, repo, stdout);
14246 break;
14247 case GOT_OBJ_TYPE_TAG:
14248 error = cat_tag(id, repo, stdout);
14249 break;
14250 default:
14251 error = got_error(GOT_ERR_OBJ_TYPE);
14252 break;
14254 if (error)
14255 break;
14256 free(label);
14257 label = NULL;
14258 free(id);
14259 id = NULL;
14261 done:
14262 free(label);
14263 free(id);
14264 free(commit_id);
14265 free(keyword_idstr);
14266 if (commit)
14267 got_object_commit_close(commit);
14268 if (worktree)
14269 got_worktree_close(worktree);
14270 if (repo) {
14271 const struct got_error *close_err = got_repo_close(repo);
14272 if (error == NULL)
14273 error = close_err;
14275 if (pack_fds) {
14276 const struct got_error *pack_err =
14277 got_repo_pack_fds_close(pack_fds);
14278 if (error == NULL)
14279 error = pack_err;
14282 got_ref_list_free(&refs);
14283 return error;
14286 __dead static void
14287 usage_info(void)
14289 fprintf(stderr, "usage: %s info [path ...]\n",
14290 getprogname());
14291 exit(1);
14294 static const struct got_error *
14295 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14296 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14297 struct got_object_id *commit_id)
14299 const struct got_error *err = NULL;
14300 char *id_str = NULL;
14301 char datebuf[128];
14302 struct tm mytm, *tm;
14303 struct got_pathlist_head *paths = arg;
14304 struct got_pathlist_entry *pe;
14307 * Clear error indication from any of the path arguments which
14308 * would cause this file index entry to be displayed.
14310 TAILQ_FOREACH(pe, paths, entry) {
14311 if (got_path_cmp(path, pe->path, strlen(path),
14312 pe->path_len) == 0 ||
14313 got_path_is_child(path, pe->path, pe->path_len))
14314 pe->data = NULL; /* no error */
14317 printf(GOT_COMMIT_SEP_STR);
14318 if (S_ISLNK(mode))
14319 printf("symlink: %s\n", path);
14320 else if (S_ISREG(mode)) {
14321 printf("file: %s\n", path);
14322 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14323 } else if (S_ISDIR(mode))
14324 printf("directory: %s\n", path);
14325 else
14326 printf("something: %s\n", path);
14328 tm = localtime_r(&mtime, &mytm);
14329 if (tm == NULL)
14330 return NULL;
14331 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14332 return got_error(GOT_ERR_NO_SPACE);
14333 printf("timestamp: %s\n", datebuf);
14335 if (blob_id) {
14336 err = got_object_id_str(&id_str, blob_id);
14337 if (err)
14338 return err;
14339 printf("based on blob: %s\n", id_str);
14340 free(id_str);
14343 if (staged_blob_id) {
14344 err = got_object_id_str(&id_str, staged_blob_id);
14345 if (err)
14346 return err;
14347 printf("based on staged blob: %s\n", id_str);
14348 free(id_str);
14351 if (commit_id) {
14352 err = got_object_id_str(&id_str, commit_id);
14353 if (err)
14354 return err;
14355 printf("based on commit: %s\n", id_str);
14356 free(id_str);
14359 return NULL;
14362 static const struct got_error *
14363 cmd_info(int argc, char *argv[])
14365 const struct got_error *error = NULL;
14366 struct got_worktree *worktree = NULL;
14367 char *cwd = NULL, *id_str = NULL;
14368 struct got_pathlist_head paths;
14369 char *uuidstr = NULL;
14370 int ch, show_files = 0;
14372 TAILQ_INIT(&paths);
14374 #ifndef PROFILE
14375 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14376 NULL) == -1)
14377 err(1, "pledge");
14378 #endif
14380 while ((ch = getopt(argc, argv, "")) != -1) {
14381 switch (ch) {
14382 default:
14383 usage_info();
14384 /* NOTREACHED */
14388 argc -= optind;
14389 argv += optind;
14391 cwd = getcwd(NULL, 0);
14392 if (cwd == NULL) {
14393 error = got_error_from_errno("getcwd");
14394 goto done;
14397 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14398 if (error) {
14399 if (error->code == GOT_ERR_NOT_WORKTREE)
14400 error = wrap_not_worktree_error(error, "info", cwd);
14401 goto done;
14404 #ifndef PROFILE
14405 /* Remove "wpath cpath proc exec sendfd" promises. */
14406 if (pledge("stdio rpath flock unveil", NULL) == -1)
14407 err(1, "pledge");
14408 #endif
14409 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14410 if (error)
14411 goto done;
14413 if (argc >= 1) {
14414 error = get_worktree_paths_from_argv(&paths, argc, argv,
14415 worktree);
14416 if (error)
14417 goto done;
14418 show_files = 1;
14421 error = got_object_id_str(&id_str,
14422 got_worktree_get_base_commit_id(worktree));
14423 if (error)
14424 goto done;
14426 error = got_worktree_get_uuid(&uuidstr, worktree);
14427 if (error)
14428 goto done;
14430 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14431 printf("work tree base commit: %s\n", id_str);
14432 printf("work tree path prefix: %s\n",
14433 got_worktree_get_path_prefix(worktree));
14434 printf("work tree branch reference: %s\n",
14435 got_worktree_get_head_ref_name(worktree));
14436 printf("work tree UUID: %s\n", uuidstr);
14437 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14439 if (show_files) {
14440 struct got_pathlist_entry *pe;
14441 TAILQ_FOREACH(pe, &paths, entry) {
14442 if (pe->path_len == 0)
14443 continue;
14445 * Assume this path will fail. This will be corrected
14446 * in print_path_info() in case the path does suceeed.
14448 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14450 error = got_worktree_path_info(worktree, &paths,
14451 print_path_info, &paths, check_cancelled, NULL);
14452 if (error)
14453 goto done;
14454 TAILQ_FOREACH(pe, &paths, entry) {
14455 if (pe->data != NULL) {
14456 const struct got_error *perr;
14458 perr = pe->data;
14459 error = got_error_fmt(perr->code, "%s",
14460 pe->path);
14461 break;
14465 done:
14466 if (worktree)
14467 got_worktree_close(worktree);
14468 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14469 free(cwd);
14470 free(id_str);
14471 free(uuidstr);
14472 return error;