Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 static volatile sig_atomic_t sigint_received;
72 static volatile sig_atomic_t sigpipe_received;
74 static void
75 catch_sigint(int signo)
76 {
77 sigint_received = 1;
78 }
80 static void
81 catch_sigpipe(int signo)
82 {
83 sigpipe_received = 1;
84 }
87 struct got_cmd {
88 const char *cmd_name;
89 const struct got_error *(*cmd_main)(int, char *[]);
90 void (*cmd_usage)(void);
91 const char *cmd_alias;
92 };
94 __dead static void usage(int, int);
95 __dead static void usage_import(void);
96 __dead static void usage_clone(void);
97 __dead static void usage_fetch(void);
98 __dead static void usage_checkout(void);
99 __dead static void usage_update(void);
100 __dead static void usage_log(void);
101 __dead static void usage_diff(void);
102 __dead static void usage_blame(void);
103 __dead static void usage_tree(void);
104 __dead static void usage_status(void);
105 __dead static void usage_ref(void);
106 __dead static void usage_branch(void);
107 __dead static void usage_tag(void);
108 __dead static void usage_add(void);
109 __dead static void usage_remove(void);
110 __dead static void usage_patch(void);
111 __dead static void usage_revert(void);
112 __dead static void usage_commit(void);
113 __dead static void usage_send(void);
114 __dead static void usage_cherrypick(void);
115 __dead static void usage_backout(void);
116 __dead static void usage_rebase(void);
117 __dead static void usage_histedit(void);
118 __dead static void usage_integrate(void);
119 __dead static void usage_merge(void);
120 __dead static void usage_stage(void);
121 __dead static void usage_unstage(void);
122 __dead static void usage_cat(void);
123 __dead static void usage_info(void);
125 static const struct got_error* cmd_import(int, char *[]);
126 static const struct got_error* cmd_clone(int, char *[]);
127 static const struct got_error* cmd_fetch(int, char *[]);
128 static const struct got_error* cmd_checkout(int, char *[]);
129 static const struct got_error* cmd_update(int, char *[]);
130 static const struct got_error* cmd_log(int, char *[]);
131 static const struct got_error* cmd_diff(int, char *[]);
132 static const struct got_error* cmd_blame(int, char *[]);
133 static const struct got_error* cmd_tree(int, char *[]);
134 static const struct got_error* cmd_status(int, char *[]);
135 static const struct got_error* cmd_ref(int, char *[]);
136 static const struct got_error* cmd_branch(int, char *[]);
137 static const struct got_error* cmd_tag(int, char *[]);
138 static const struct got_error* cmd_add(int, char *[]);
139 static const struct got_error* cmd_remove(int, char *[]);
140 static const struct got_error* cmd_patch(int, char *[]);
141 static const struct got_error* cmd_revert(int, char *[]);
142 static const struct got_error* cmd_commit(int, char *[]);
143 static const struct got_error* cmd_send(int, char *[]);
144 static const struct got_error* cmd_cherrypick(int, char *[]);
145 static const struct got_error* cmd_backout(int, char *[]);
146 static const struct got_error* cmd_rebase(int, char *[]);
147 static const struct got_error* cmd_histedit(int, char *[]);
148 static const struct got_error* cmd_integrate(int, char *[]);
149 static const struct got_error* cmd_merge(int, char *[]);
150 static const struct got_error* cmd_stage(int, char *[]);
151 static const struct got_error* cmd_unstage(int, char *[]);
152 static const struct got_error* cmd_cat(int, char *[]);
153 static const struct got_error* cmd_info(int, char *[]);
155 static const struct got_cmd got_commands[] = {
156 { "import", cmd_import, usage_import, "im" },
157 { "clone", cmd_clone, usage_clone, "cl" },
158 { "fetch", cmd_fetch, usage_fetch, "fe" },
159 { "checkout", cmd_checkout, usage_checkout, "co" },
160 { "update", cmd_update, usage_update, "up" },
161 { "log", cmd_log, usage_log, "" },
162 { "diff", cmd_diff, usage_diff, "di" },
163 { "blame", cmd_blame, usage_blame, "bl" },
164 { "tree", cmd_tree, usage_tree, "tr" },
165 { "status", cmd_status, usage_status, "st" },
166 { "ref", cmd_ref, usage_ref, "" },
167 { "branch", cmd_branch, usage_branch, "br" },
168 { "tag", cmd_tag, usage_tag, "" },
169 { "add", cmd_add, usage_add, "" },
170 { "remove", cmd_remove, usage_remove, "rm" },
171 { "patch", cmd_patch, usage_patch, "pa" },
172 { "revert", cmd_revert, usage_revert, "rv" },
173 { "commit", cmd_commit, usage_commit, "ci" },
174 { "send", cmd_send, usage_send, "se" },
175 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
176 { "backout", cmd_backout, usage_backout, "bo" },
177 { "rebase", cmd_rebase, usage_rebase, "rb" },
178 { "histedit", cmd_histedit, usage_histedit, "he" },
179 { "integrate", cmd_integrate, usage_integrate,"ig" },
180 { "merge", cmd_merge, usage_merge, "mg" },
181 { "stage", cmd_stage, usage_stage, "sg" },
182 { "unstage", cmd_unstage, usage_unstage, "ug" },
183 { "cat", cmd_cat, usage_cat, "" },
184 { "info", cmd_info, usage_info, "" },
185 };
187 static void
188 list_commands(FILE *fp)
190 size_t i;
192 fprintf(fp, "commands:");
193 for (i = 0; i < nitems(got_commands); i++) {
194 const struct got_cmd *cmd = &got_commands[i];
195 fprintf(fp, " %s", cmd->cmd_name);
197 fputc('\n', fp);
200 __dead static void
201 option_conflict(char a, char b)
203 errx(1, "-%c and -%c options are mutually exclusive", a, b);
206 int
207 main(int argc, char *argv[])
209 const struct got_cmd *cmd;
210 size_t i;
211 int ch;
212 int hflag = 0, Vflag = 0;
213 static const struct option longopts[] = {
214 { "version", no_argument, NULL, 'V' },
215 { NULL, 0, NULL, 0 }
216 };
218 setlocale(LC_CTYPE, "");
220 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
221 switch (ch) {
222 case 'h':
223 hflag = 1;
224 break;
225 case 'V':
226 Vflag = 1;
227 break;
228 default:
229 usage(hflag, 1);
230 /* NOTREACHED */
234 argc -= optind;
235 argv += optind;
236 optind = 1;
237 optreset = 1;
239 if (Vflag) {
240 got_version_print_str();
241 return 0;
244 if (argc <= 0)
245 usage(hflag, hflag ? 0 : 1);
247 signal(SIGINT, catch_sigint);
248 signal(SIGPIPE, catch_sigpipe);
250 for (i = 0; i < nitems(got_commands); i++) {
251 const struct got_error *error;
253 cmd = &got_commands[i];
255 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
256 strcmp(cmd->cmd_alias, argv[0]) != 0)
257 continue;
259 if (hflag)
260 cmd->cmd_usage();
262 error = cmd->cmd_main(argc, argv);
263 if (error && error->code != GOT_ERR_CANCELLED &&
264 error->code != GOT_ERR_PRIVSEP_EXIT &&
265 !(sigpipe_received &&
266 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
267 !(sigint_received &&
268 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
269 fflush(stdout);
270 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
271 return 1;
274 return 0;
277 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
278 list_commands(stderr);
279 return 1;
282 __dead static void
283 usage(int hflag, int status)
285 FILE *fp = (status == 0) ? stdout : stderr;
287 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
288 getprogname());
289 if (hflag)
290 list_commands(fp);
291 exit(status);
294 static const struct got_error *
295 get_editor(char **abspath)
297 const struct got_error *err = NULL;
298 const char *editor;
300 *abspath = NULL;
302 editor = getenv("VISUAL");
303 if (editor == NULL)
304 editor = getenv("EDITOR");
306 if (editor) {
307 err = got_path_find_prog(abspath, editor);
308 if (err)
309 return err;
312 if (*abspath == NULL) {
313 *abspath = strdup("/usr/bin/vi");
314 if (*abspath == NULL)
315 return got_error_from_errno("strdup");
318 return NULL;
321 static const struct got_error *
322 apply_unveil(const char *repo_path, int repo_read_only,
323 const char *worktree_path)
325 const struct got_error *err;
327 #ifdef PROFILE
328 if (unveil("gmon.out", "rwc") != 0)
329 return got_error_from_errno2("unveil", "gmon.out");
330 #endif
331 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
332 return got_error_from_errno2("unveil", repo_path);
334 if (worktree_path && unveil(worktree_path, "rwc") != 0)
335 return got_error_from_errno2("unveil", worktree_path);
337 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
338 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
340 err = got_privsep_unveil_exec_helpers();
341 if (err != NULL)
342 return err;
344 if (unveil(NULL, NULL) != 0)
345 return got_error_from_errno("unveil");
347 return NULL;
350 __dead static void
351 usage_import(void)
353 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
354 "[-r repository-path] directory\n", getprogname());
355 exit(1);
358 static int
359 spawn_editor(const char *editor, const char *file)
361 pid_t pid;
362 sig_t sighup, sigint, sigquit;
363 int st = -1;
365 sighup = signal(SIGHUP, SIG_IGN);
366 sigint = signal(SIGINT, SIG_IGN);
367 sigquit = signal(SIGQUIT, SIG_IGN);
369 switch (pid = fork()) {
370 case -1:
371 goto doneediting;
372 case 0:
373 execl(editor, editor, file, (char *)NULL);
374 _exit(127);
377 while (waitpid(pid, &st, 0) == -1)
378 if (errno != EINTR)
379 break;
381 doneediting:
382 (void)signal(SIGHUP, sighup);
383 (void)signal(SIGINT, sigint);
384 (void)signal(SIGQUIT, sigquit);
386 if (!WIFEXITED(st)) {
387 errno = EINTR;
388 return -1;
391 return WEXITSTATUS(st);
394 static const struct got_error *
395 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
397 const struct got_error *err = NULL;
398 char *line = NULL;
399 size_t linesize = 0;
401 *logmsg = NULL;
402 *len = 0;
404 if (fseeko(fp, 0L, SEEK_SET) == -1)
405 return got_error_from_errno("fseeko");
407 *logmsg = malloc(filesize + 1);
408 if (*logmsg == NULL)
409 return got_error_from_errno("malloc");
410 (*logmsg)[0] = '\0';
412 while (getline(&line, &linesize, fp) != -1) {
413 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
414 continue; /* remove comments and leading empty lines */
415 *len = strlcat(*logmsg, line, filesize + 1);
416 if (*len >= filesize + 1) {
417 err = got_error(GOT_ERR_NO_SPACE);
418 goto done;
421 if (ferror(fp)) {
422 err = got_ferror(fp, GOT_ERR_IO);
423 goto done;
426 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
427 (*logmsg)[*len - 1] = '\0';
428 (*len)--;
430 done:
431 free(line);
432 if (err) {
433 free(*logmsg);
434 *logmsg = NULL;
435 *len = 0;
437 return err;
440 static const struct got_error *
441 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
442 const char *initial_content, size_t initial_content_len,
443 int require_modification)
445 const struct got_error *err = NULL;
446 struct stat st, st2;
447 FILE *fp = NULL;
448 size_t logmsg_len;
450 *logmsg = NULL;
452 if (stat(logmsg_path, &st) == -1)
453 return got_error_from_errno2("stat", logmsg_path);
455 if (spawn_editor(editor, logmsg_path) == -1)
456 return got_error_from_errno("failed spawning editor");
458 if (require_modification) {
459 struct timespec timeout;
461 timeout.tv_sec = 0;
462 timeout.tv_nsec = 1;
463 nanosleep(&timeout, NULL);
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno2("stat", logmsg_path);
469 if (require_modification && st.st_size == st2.st_size &&
470 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 fp = fopen(logmsg_path, "re");
475 if (fp == NULL) {
476 err = got_error_from_errno("fopen");
477 goto done;
480 /* strip comments and leading/trailing newlines */
481 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
482 if (err)
483 goto done;
484 if (logmsg_len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 done:
490 if (fp && fclose(fp) == EOF && err == NULL)
491 err = got_error_from_errno("fclose");
492 if (err) {
493 free(*logmsg);
494 *logmsg = NULL;
496 return err;
499 static const struct got_error *
500 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
501 const char *path_dir, const char *branch_name)
503 char *initial_content = NULL;
504 const struct got_error *err = NULL;
505 int initial_content_len;
506 int fd = -1;
508 initial_content_len = asprintf(&initial_content,
509 "\n# %s to be imported to branch %s\n", path_dir,
510 branch_name);
511 if (initial_content_len == -1)
512 return got_error_from_errno("asprintf");
514 err = got_opentemp_named_fd(logmsg_path, &fd,
515 GOT_TMPDIR_STR "/got-importmsg", "");
516 if (err)
517 goto done;
519 if (write(fd, initial_content, initial_content_len) == -1) {
520 err = got_error_from_errno2("write", *logmsg_path);
521 goto done;
523 if (close(fd) == -1) {
524 err = got_error_from_errno2("close", *logmsg_path);
525 goto done;
527 fd = -1;
529 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
530 initial_content_len, 1);
531 done:
532 if (fd != -1 && close(fd) == -1 && err == NULL)
533 err = got_error_from_errno2("close", *logmsg_path);
534 free(initial_content);
535 if (err) {
536 free(*logmsg_path);
537 *logmsg_path = NULL;
539 return err;
542 static const struct got_error *
543 import_progress(void *arg, const char *path)
545 printf("A %s\n", path);
546 return NULL;
549 static const struct got_error *
550 valid_author(const char *author)
552 const char *email = author;
554 /*
555 * Git' expects the author (or committer) to be in the form
556 * "name <email>", which are mostly free form (see the
557 * "committer" description in git-fast-import(1)). We're only
558 * doing this to avoid git's object parser breaking on commits
559 * we create.
560 */
562 while (*author && *author != '\n' && *author != '<' && *author != '>')
563 author++;
564 if (author != email && *author == '<' && *(author - 1) != ' ')
565 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
566 "between author name and email required", email);
567 if (*author++ != '<')
568 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
569 while (*author && *author != '\n' && *author != '<' && *author != '>')
570 author++;
571 if (strcmp(author, ">") != 0)
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 return NULL;
576 static const struct got_error *
577 get_author(char **author, struct got_repository *repo,
578 struct got_worktree *worktree)
580 const struct got_error *err = NULL;
581 const char *got_author = NULL, *name, *email;
582 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
584 *author = NULL;
586 if (worktree)
587 worktree_conf = got_worktree_get_gotconfig(worktree);
588 repo_conf = got_repo_get_gotconfig(repo);
590 /*
591 * Priority of potential author information sources, from most
592 * significant to least significant:
593 * 1) work tree's .got/got.conf file
594 * 2) repository's got.conf file
595 * 3) repository's git config file
596 * 4) environment variables
597 * 5) global git config files (in user's home directory or /etc)
598 */
600 if (worktree_conf)
601 got_author = got_gotconfig_get_author(worktree_conf);
602 if (got_author == NULL)
603 got_author = got_gotconfig_get_author(repo_conf);
604 if (got_author == NULL) {
605 name = got_repo_get_gitconfig_author_name(repo);
606 email = got_repo_get_gitconfig_author_email(repo);
607 if (name && email) {
608 if (asprintf(author, "%s <%s>", name, email) == -1)
609 return got_error_from_errno("asprintf");
610 return NULL;
613 got_author = getenv("GOT_AUTHOR");
614 if (got_author == NULL) {
615 name = got_repo_get_global_gitconfig_author_name(repo);
616 email = got_repo_get_global_gitconfig_author_email(
617 repo);
618 if (name && email) {
619 if (asprintf(author, "%s <%s>", name, email)
620 == -1)
621 return got_error_from_errno("asprintf");
622 return NULL;
624 /* TODO: Look up user in password database? */
625 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
629 *author = strdup(got_author);
630 if (*author == NULL)
631 return got_error_from_errno("strdup");
633 err = valid_author(*author);
634 if (err) {
635 free(*author);
636 *author = NULL;
638 return err;
641 static const struct got_error *
642 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
643 struct got_worktree *worktree)
645 const char *got_allowed_signers = NULL;
646 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
648 *allowed_signers = NULL;
650 if (worktree)
651 worktree_conf = got_worktree_get_gotconfig(worktree);
652 repo_conf = got_repo_get_gotconfig(repo);
654 /*
655 * Priority of potential author information sources, from most
656 * significant to least significant:
657 * 1) work tree's .got/got.conf file
658 * 2) repository's got.conf file
659 */
661 if (worktree_conf)
662 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
663 worktree_conf);
664 if (got_allowed_signers == NULL)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 repo_conf);
668 if (got_allowed_signers) {
669 *allowed_signers = strdup(got_allowed_signers);
670 if (*allowed_signers == NULL)
671 return got_error_from_errno("strdup");
673 return NULL;
676 static const struct got_error *
677 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
678 struct got_worktree *worktree)
680 const char *got_revoked_signers = NULL;
681 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
683 *revoked_signers = NULL;
685 if (worktree)
686 worktree_conf = got_worktree_get_gotconfig(worktree);
687 repo_conf = got_repo_get_gotconfig(repo);
689 /*
690 * Priority of potential author information sources, from most
691 * significant to least significant:
692 * 1) work tree's .got/got.conf file
693 * 2) repository's got.conf file
694 */
696 if (worktree_conf)
697 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
698 worktree_conf);
699 if (got_revoked_signers == NULL)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 repo_conf);
703 if (got_revoked_signers) {
704 *revoked_signers = strdup(got_revoked_signers);
705 if (*revoked_signers == NULL)
706 return got_error_from_errno("strdup");
708 return NULL;
711 static const char *
712 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
714 const char *got_signer_id = NULL;
715 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
717 if (worktree)
718 worktree_conf = got_worktree_get_gotconfig(worktree);
719 repo_conf = got_repo_get_gotconfig(repo);
721 /*
722 * Priority of potential author information sources, from most
723 * significant to least significant:
724 * 1) work tree's .got/got.conf file
725 * 2) repository's got.conf file
726 */
728 if (worktree_conf)
729 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
730 if (got_signer_id == NULL)
731 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
733 return got_signer_id;
736 static const struct got_error *
737 get_gitconfig_path(char **gitconfig_path)
739 const char *homedir = getenv("HOME");
741 *gitconfig_path = NULL;
742 if (homedir) {
743 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
744 return got_error_from_errno("asprintf");
747 return NULL;
750 static const struct got_error *
751 cmd_import(int argc, char *argv[])
753 const struct got_error *error = NULL;
754 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
755 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
756 const char *branch_name = NULL;
757 char *id_str = NULL, *logmsg_path = NULL;
758 char refname[PATH_MAX] = "refs/heads/";
759 struct got_repository *repo = NULL;
760 struct got_reference *branch_ref = NULL, *head_ref = NULL;
761 struct got_object_id *new_commit_id = NULL;
762 int ch, n = 0;
763 struct got_pathlist_head ignores;
764 struct got_pathlist_entry *pe;
765 int preserve_logmsg = 0;
766 int *pack_fds = NULL;
768 TAILQ_INIT(&ignores);
770 #ifndef PROFILE
771 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
772 "unveil",
773 NULL) == -1)
774 err(1, "pledge");
775 #endif
777 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
778 switch (ch) {
779 case 'b':
780 branch_name = optarg;
781 break;
782 case 'I':
783 if (optarg[0] == '\0')
784 break;
785 error = got_pathlist_insert(&pe, &ignores, optarg,
786 NULL);
787 if (error)
788 goto done;
789 break;
790 case 'm':
791 logmsg = strdup(optarg);
792 if (logmsg == NULL) {
793 error = got_error_from_errno("strdup");
794 goto done;
796 break;
797 case 'r':
798 repo_path = realpath(optarg, NULL);
799 if (repo_path == NULL) {
800 error = got_error_from_errno2("realpath",
801 optarg);
802 goto done;
804 break;
805 default:
806 usage_import();
807 /* NOTREACHED */
811 argc -= optind;
812 argv += optind;
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || *logmsg == '\0') {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (repo) {
974 const struct got_error *close_err = got_repo_close(repo);
975 if (error == NULL)
976 error = close_err;
978 if (preserve_logmsg) {
979 fprintf(stderr, "%s: log message preserved in %s\n",
980 getprogname(), logmsg_path);
981 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
982 error = got_error_from_errno2("unlink", logmsg_path);
983 free(logmsg);
984 free(logmsg_path);
985 free(repo_path);
986 free(editor);
987 free(new_commit_id);
988 free(id_str);
989 free(author);
990 free(gitconfig_path);
991 if (branch_ref)
992 got_ref_close(branch_ref);
993 if (head_ref)
994 got_ref_close(head_ref);
995 return error;
998 __dead static void
999 usage_clone(void)
1001 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1002 "repository-URL [directory]\n", getprogname());
1003 exit(1);
1006 struct got_fetch_progress_arg {
1007 char last_scaled_size[FMT_SCALED_STRSIZE];
1008 int last_p_indexed;
1009 int last_p_resolved;
1010 int verbosity;
1012 struct got_repository *repo;
1014 int create_configs;
1015 int configs_created;
1016 struct {
1017 struct got_pathlist_head *symrefs;
1018 struct got_pathlist_head *wanted_branches;
1019 struct got_pathlist_head *wanted_refs;
1020 const char *proto;
1021 const char *host;
1022 const char *port;
1023 const char *remote_repo_path;
1024 const char *git_url;
1025 int fetch_all_branches;
1026 int mirror_references;
1027 } config_info;
1030 /* XXX forward declaration */
1031 static const struct got_error *
1032 create_config_files(const char *proto, const char *host, const char *port,
1033 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1034 int mirror_references, struct got_pathlist_head *symrefs,
1035 struct got_pathlist_head *wanted_branches,
1036 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1038 static const struct got_error *
1039 fetch_progress(void *arg, const char *message, off_t packfile_size,
1040 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1042 const struct got_error *err = NULL;
1043 struct got_fetch_progress_arg *a = arg;
1044 char scaled_size[FMT_SCALED_STRSIZE];
1045 int p_indexed, p_resolved;
1046 int print_size = 0, print_indexed = 0, print_resolved = 0;
1049 * In order to allow a failed clone to be resumed with 'got fetch'
1050 * we try to create configuration files as soon as possible.
1051 * Once the server has sent information about its default branch
1052 * we have all required information.
1054 if (a->create_configs && !a->configs_created &&
1055 !TAILQ_EMPTY(a->config_info.symrefs)) {
1056 err = create_config_files(a->config_info.proto,
1057 a->config_info.host, a->config_info.port,
1058 a->config_info.remote_repo_path,
1059 a->config_info.git_url,
1060 a->config_info.fetch_all_branches,
1061 a->config_info.mirror_references,
1062 a->config_info.symrefs,
1063 a->config_info.wanted_branches,
1064 a->config_info.wanted_refs, a->repo);
1065 if (err)
1066 return err;
1067 a->configs_created = 1;
1070 if (a->verbosity < 0)
1071 return NULL;
1073 if (message && message[0] != '\0') {
1074 printf("\rserver: %s", message);
1075 fflush(stdout);
1076 return NULL;
1079 if (packfile_size > 0 || nobj_indexed > 0) {
1080 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1081 (a->last_scaled_size[0] == '\0' ||
1082 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1083 print_size = 1;
1084 if (strlcpy(a->last_scaled_size, scaled_size,
1085 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1086 return got_error(GOT_ERR_NO_SPACE);
1088 if (nobj_indexed > 0) {
1089 p_indexed = (nobj_indexed * 100) / nobj_total;
1090 if (p_indexed != a->last_p_indexed) {
1091 a->last_p_indexed = p_indexed;
1092 print_indexed = 1;
1093 print_size = 1;
1096 if (nobj_resolved > 0) {
1097 p_resolved = (nobj_resolved * 100) /
1098 (nobj_total - nobj_loose);
1099 if (p_resolved != a->last_p_resolved) {
1100 a->last_p_resolved = p_resolved;
1101 print_resolved = 1;
1102 print_indexed = 1;
1103 print_size = 1;
1108 if (print_size || print_indexed || print_resolved)
1109 printf("\r");
1110 if (print_size)
1111 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1112 if (print_indexed)
1113 printf("; indexing %d%%", p_indexed);
1114 if (print_resolved)
1115 printf("; resolving deltas %d%%", p_resolved);
1116 if (print_size || print_indexed || print_resolved)
1117 fflush(stdout);
1119 return NULL;
1122 static const struct got_error *
1123 create_symref(const char *refname, struct got_reference *target_ref,
1124 int verbosity, struct got_repository *repo)
1126 const struct got_error *err;
1127 struct got_reference *head_symref;
1129 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1130 if (err)
1131 return err;
1133 err = got_ref_write(head_symref, repo);
1134 if (err == NULL && verbosity > 0) {
1135 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1136 got_ref_get_name(target_ref));
1138 got_ref_close(head_symref);
1139 return err;
1142 static const struct got_error *
1143 list_remote_refs(struct got_pathlist_head *symrefs,
1144 struct got_pathlist_head *refs)
1146 const struct got_error *err;
1147 struct got_pathlist_entry *pe;
1149 TAILQ_FOREACH(pe, symrefs, entry) {
1150 const char *refname = pe->path;
1151 const char *targetref = pe->data;
1153 printf("%s: %s\n", refname, targetref);
1156 TAILQ_FOREACH(pe, refs, entry) {
1157 const char *refname = pe->path;
1158 struct got_object_id *id = pe->data;
1159 char *id_str;
1161 err = got_object_id_str(&id_str, id);
1162 if (err)
1163 return err;
1164 printf("%s: %s\n", refname, id_str);
1165 free(id_str);
1168 return NULL;
1171 static const struct got_error *
1172 create_ref(const char *refname, struct got_object_id *id,
1173 int verbosity, struct got_repository *repo)
1175 const struct got_error *err = NULL;
1176 struct got_reference *ref;
1177 char *id_str;
1179 err = got_object_id_str(&id_str, id);
1180 if (err)
1181 return err;
1183 err = got_ref_alloc(&ref, refname, id);
1184 if (err)
1185 goto done;
1187 err = got_ref_write(ref, repo);
1188 got_ref_close(ref);
1190 if (err == NULL && verbosity >= 0)
1191 printf("Created reference %s: %s\n", refname, id_str);
1192 done:
1193 free(id_str);
1194 return err;
1197 static int
1198 match_wanted_ref(const char *refname, const char *wanted_ref)
1200 if (strncmp(refname, "refs/", 5) != 0)
1201 return 0;
1202 refname += 5;
1205 * Prevent fetching of references that won't make any
1206 * sense outside of the remote repository's context.
1208 if (strncmp(refname, "got/", 4) == 0)
1209 return 0;
1210 if (strncmp(refname, "remotes/", 8) == 0)
1211 return 0;
1213 if (strncmp(wanted_ref, "refs/", 5) == 0)
1214 wanted_ref += 5;
1216 /* Allow prefix match. */
1217 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1218 return 1;
1220 /* Allow exact match. */
1221 return (strcmp(refname, wanted_ref) == 0);
1224 static int
1225 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1227 struct got_pathlist_entry *pe;
1229 TAILQ_FOREACH(pe, wanted_refs, entry) {
1230 if (match_wanted_ref(refname, pe->path))
1231 return 1;
1234 return 0;
1237 static const struct got_error *
1238 create_wanted_ref(const char *refname, struct got_object_id *id,
1239 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1241 const struct got_error *err;
1242 char *remote_refname;
1244 if (strncmp("refs/", refname, 5) == 0)
1245 refname += 5;
1247 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1248 remote_repo_name, refname) == -1)
1249 return got_error_from_errno("asprintf");
1251 err = create_ref(remote_refname, id, verbosity, repo);
1252 free(remote_refname);
1253 return err;
1256 static const struct got_error *
1257 create_gotconfig(const char *proto, const char *host, const char *port,
1258 const char *remote_repo_path, const char *default_branch,
1259 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1260 struct got_pathlist_head *wanted_refs, int mirror_references,
1261 struct got_repository *repo)
1263 const struct got_error *err = NULL;
1264 char *gotconfig_path = NULL;
1265 char *gotconfig = NULL;
1266 FILE *gotconfig_file = NULL;
1267 const char *branchname = NULL;
1268 char *branches = NULL, *refs = NULL;
1269 ssize_t n;
1271 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1272 struct got_pathlist_entry *pe;
1273 TAILQ_FOREACH(pe, wanted_branches, entry) {
1274 char *s;
1275 branchname = pe->path;
1276 if (strncmp(branchname, "refs/heads/", 11) == 0)
1277 branchname += 11;
1278 if (asprintf(&s, "%s\"%s\" ",
1279 branches ? branches : "", branchname) == -1) {
1280 err = got_error_from_errno("asprintf");
1281 goto done;
1283 free(branches);
1284 branches = s;
1286 } else if (!fetch_all_branches && default_branch) {
1287 branchname = default_branch;
1288 if (strncmp(branchname, "refs/heads/", 11) == 0)
1289 branchname += 11;
1290 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1291 err = got_error_from_errno("asprintf");
1292 goto done;
1295 if (!TAILQ_EMPTY(wanted_refs)) {
1296 struct got_pathlist_entry *pe;
1297 TAILQ_FOREACH(pe, wanted_refs, entry) {
1298 char *s;
1299 const char *refname = pe->path;
1300 if (strncmp(refname, "refs/", 5) == 0)
1301 branchname += 5;
1302 if (asprintf(&s, "%s\"%s\" ",
1303 refs ? refs : "", refname) == -1) {
1304 err = got_error_from_errno("asprintf");
1305 goto done;
1307 free(refs);
1308 refs = s;
1312 /* Create got.conf(5). */
1313 gotconfig_path = got_repo_get_path_gotconfig(repo);
1314 if (gotconfig_path == NULL) {
1315 err = got_error_from_errno("got_repo_get_path_gotconfig");
1316 goto done;
1318 gotconfig_file = fopen(gotconfig_path, "ae");
1319 if (gotconfig_file == NULL) {
1320 err = got_error_from_errno2("fopen", gotconfig_path);
1321 goto done;
1323 if (asprintf(&gotconfig,
1324 "remote \"%s\" {\n"
1325 "\tserver %s\n"
1326 "\tprotocol %s\n"
1327 "%s%s%s"
1328 "\trepository \"%s\"\n"
1329 "%s%s%s"
1330 "%s%s%s"
1331 "%s"
1332 "%s"
1333 "}\n",
1334 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1335 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1336 remote_repo_path, branches ? "\tbranch { " : "",
1337 branches ? branches : "", branches ? "}\n" : "",
1338 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1339 mirror_references ? "\tmirror_references yes\n" : "",
1340 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1345 if (n != strlen(gotconfig)) {
1346 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1347 goto done;
1350 done:
1351 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1352 err = got_error_from_errno2("fclose", gotconfig_path);
1353 free(gotconfig_path);
1354 free(branches);
1355 return err;
1358 static const struct got_error *
1359 create_gitconfig(const char *git_url, const char *default_branch,
1360 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1361 struct got_pathlist_head *wanted_refs, int mirror_references,
1362 struct got_repository *repo)
1364 const struct got_error *err = NULL;
1365 char *gitconfig_path = NULL;
1366 char *gitconfig = NULL;
1367 FILE *gitconfig_file = NULL;
1368 char *branches = NULL, *refs = NULL;
1369 const char *branchname;
1370 ssize_t n;
1372 /* Create a config file Git can understand. */
1373 gitconfig_path = got_repo_get_path_gitconfig(repo);
1374 if (gitconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gitconfig");
1376 goto done;
1378 gitconfig_file = fopen(gitconfig_path, "ae");
1379 if (gitconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gitconfig_path);
1381 goto done;
1383 if (fetch_all_branches) {
1384 if (mirror_references) {
1385 if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1387 err = got_error_from_errno("asprintf");
1388 goto done;
1390 } else if (asprintf(&branches,
1391 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1392 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 } else if (!TAILQ_EMPTY(wanted_branches)) {
1397 struct got_pathlist_entry *pe;
1398 TAILQ_FOREACH(pe, wanted_branches, entry) {
1399 char *s;
1400 branchname = pe->path;
1401 if (strncmp(branchname, "refs/heads/", 11) == 0)
1402 branchname += 11;
1403 if (mirror_references) {
1404 if (asprintf(&s,
1405 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1406 branches ? branches : "",
1407 branchname, branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 } else if (asprintf(&s,
1412 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1413 branches ? branches : "",
1414 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1415 branchname) == -1) {
1416 err = got_error_from_errno("asprintf");
1417 goto done;
1419 free(branches);
1420 branches = s;
1422 } else {
1424 * If the server specified a default branch, use just that one.
1425 * Otherwise fall back to fetching all branches on next fetch.
1427 if (default_branch) {
1428 branchname = default_branch;
1429 if (strncmp(branchname, "refs/heads/", 11) == 0)
1430 branchname += 11;
1431 } else
1432 branchname = "*"; /* fall back to all branches */
1433 if (mirror_references) {
1434 if (asprintf(&branches,
1435 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1436 branchname, branchname) == -1) {
1437 err = got_error_from_errno("asprintf");
1438 goto done;
1440 } else if (asprintf(&branches,
1441 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1442 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1443 branchname) == -1) {
1444 err = got_error_from_errno("asprintf");
1445 goto done;
1448 if (!TAILQ_EMPTY(wanted_refs)) {
1449 struct got_pathlist_entry *pe;
1450 TAILQ_FOREACH(pe, wanted_refs, entry) {
1451 char *s;
1452 const char *refname = pe->path;
1453 if (strncmp(refname, "refs/", 5) == 0)
1454 refname += 5;
1455 if (mirror_references) {
1456 if (asprintf(&s,
1457 "%s\tfetch = refs/%s:refs/%s\n",
1458 refs ? refs : "", refname, refname) == -1) {
1459 err = got_error_from_errno("asprintf");
1460 goto done;
1462 } else if (asprintf(&s,
1463 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1464 refs ? refs : "",
1465 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1466 refname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 free(refs);
1471 refs = s;
1475 if (asprintf(&gitconfig,
1476 "[remote \"%s\"]\n"
1477 "\turl = %s\n"
1478 "%s"
1479 "%s"
1480 "\tfetch = refs/tags/*:refs/tags/*\n",
1481 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1482 refs ? refs : "") == -1) {
1483 err = got_error_from_errno("asprintf");
1484 goto done;
1486 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1487 if (n != strlen(gitconfig)) {
1488 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1489 goto done;
1491 done:
1492 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1493 err = got_error_from_errno2("fclose", gitconfig_path);
1494 free(gitconfig_path);
1495 free(branches);
1496 return err;
1499 static const struct got_error *
1500 create_config_files(const char *proto, const char *host, const char *port,
1501 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1502 int mirror_references, struct got_pathlist_head *symrefs,
1503 struct got_pathlist_head *wanted_branches,
1504 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1506 const struct got_error *err = NULL;
1507 const char *default_branch = NULL;
1508 struct got_pathlist_entry *pe;
1511 * If we asked for a set of wanted branches then use the first
1512 * one of those.
1514 if (!TAILQ_EMPTY(wanted_branches)) {
1515 pe = TAILQ_FIRST(wanted_branches);
1516 default_branch = pe->path;
1517 } else {
1518 /* First HEAD ref listed by server is the default branch. */
1519 TAILQ_FOREACH(pe, symrefs, entry) {
1520 const char *refname = pe->path;
1521 const char *target = pe->data;
1523 if (strcmp(refname, GOT_REF_HEAD) != 0)
1524 continue;
1526 default_branch = target;
1527 break;
1531 /* Create got.conf(5). */
1532 err = create_gotconfig(proto, host, port, remote_repo_path,
1533 default_branch, fetch_all_branches, wanted_branches,
1534 wanted_refs, mirror_references, repo);
1535 if (err)
1536 return err;
1538 /* Create a config file Git can understand. */
1539 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1540 wanted_branches, wanted_refs, mirror_references, repo);
1543 static const struct got_error *
1544 cmd_clone(int argc, char *argv[])
1546 const struct got_error *error = NULL;
1547 const char *uri, *dirname;
1548 char *proto, *host, *port, *repo_name, *server_path;
1549 char *default_destdir = NULL, *id_str = NULL;
1550 const char *repo_path;
1551 struct got_repository *repo = NULL;
1552 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1553 struct got_pathlist_entry *pe;
1554 struct got_object_id *pack_hash = NULL;
1555 int ch, fetchfd = -1, fetchstatus;
1556 pid_t fetchpid = -1;
1557 struct got_fetch_progress_arg fpa;
1558 char *git_url = NULL;
1559 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1560 int bflag = 0, list_refs_only = 0;
1561 int *pack_fds = NULL;
1563 TAILQ_INIT(&refs);
1564 TAILQ_INIT(&symrefs);
1565 TAILQ_INIT(&wanted_branches);
1566 TAILQ_INIT(&wanted_refs);
1568 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1569 switch (ch) {
1570 case 'a':
1571 fetch_all_branches = 1;
1572 break;
1573 case 'b':
1574 error = got_pathlist_append(&wanted_branches,
1575 optarg, NULL);
1576 if (error)
1577 return error;
1578 bflag = 1;
1579 break;
1580 case 'l':
1581 list_refs_only = 1;
1582 break;
1583 case 'm':
1584 mirror_references = 1;
1585 break;
1586 case 'q':
1587 verbosity = -1;
1588 break;
1589 case 'R':
1590 error = got_pathlist_append(&wanted_refs,
1591 optarg, NULL);
1592 if (error)
1593 return error;
1594 break;
1595 case 'v':
1596 if (verbosity < 0)
1597 verbosity = 0;
1598 else if (verbosity < 3)
1599 verbosity++;
1600 break;
1601 default:
1602 usage_clone();
1603 break;
1606 argc -= optind;
1607 argv += optind;
1609 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1610 option_conflict('a', 'b');
1611 if (list_refs_only) {
1612 if (!TAILQ_EMPTY(&wanted_branches))
1613 option_conflict('l', 'b');
1614 if (fetch_all_branches)
1615 option_conflict('l', 'a');
1616 if (mirror_references)
1617 option_conflict('l', 'm');
1618 if (!TAILQ_EMPTY(&wanted_refs))
1619 option_conflict('l', 'R');
1622 uri = argv[0];
1624 if (argc == 1)
1625 dirname = NULL;
1626 else if (argc == 2)
1627 dirname = argv[1];
1628 else
1629 usage_clone();
1631 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1632 &repo_name, uri);
1633 if (error)
1634 goto done;
1636 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1637 host, port ? ":" : "", port ? port : "",
1638 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1639 error = got_error_from_errno("asprintf");
1640 goto done;
1643 if (strcmp(proto, "git") == 0) {
1644 #ifndef PROFILE
1645 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1646 "sendfd dns inet unveil", NULL) == -1)
1647 err(1, "pledge");
1648 #endif
1649 } else if (strcmp(proto, "git+ssh") == 0 ||
1650 strcmp(proto, "ssh") == 0) {
1651 #ifndef PROFILE
1652 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1653 "sendfd unveil", NULL) == -1)
1654 err(1, "pledge");
1655 #endif
1656 } else if (strcmp(proto, "http") == 0 ||
1657 strcmp(proto, "git+http") == 0) {
1658 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1659 goto done;
1660 } else {
1661 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1662 goto done;
1664 if (dirname == NULL) {
1665 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1666 error = got_error_from_errno("asprintf");
1667 goto done;
1669 repo_path = default_destdir;
1670 } else
1671 repo_path = dirname;
1673 if (!list_refs_only) {
1674 error = got_path_mkdir(repo_path);
1675 if (error &&
1676 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1677 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1678 goto done;
1679 if (!got_path_dir_is_empty(repo_path)) {
1680 error = got_error_path(repo_path,
1681 GOT_ERR_DIR_NOT_EMPTY);
1682 goto done;
1686 error = got_dial_apply_unveil(proto);
1687 if (error)
1688 goto done;
1690 error = apply_unveil(repo_path, 0, NULL);
1691 if (error)
1692 goto done;
1694 if (verbosity >= 0)
1695 printf("Connecting to %s\n", git_url);
1697 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1698 server_path, verbosity);
1699 if (error)
1700 goto done;
1702 if (!list_refs_only) {
1703 error = got_repo_init(repo_path, NULL);
1704 if (error)
1705 goto done;
1706 error = got_repo_pack_fds_open(&pack_fds);
1707 if (error != NULL)
1708 goto done;
1709 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1710 if (error)
1711 goto done;
1714 fpa.last_scaled_size[0] = '\0';
1715 fpa.last_p_indexed = -1;
1716 fpa.last_p_resolved = -1;
1717 fpa.verbosity = verbosity;
1718 fpa.create_configs = 1;
1719 fpa.configs_created = 0;
1720 fpa.repo = repo;
1721 fpa.config_info.symrefs = &symrefs;
1722 fpa.config_info.wanted_branches = &wanted_branches;
1723 fpa.config_info.wanted_refs = &wanted_refs;
1724 fpa.config_info.proto = proto;
1725 fpa.config_info.host = host;
1726 fpa.config_info.port = port;
1727 fpa.config_info.remote_repo_path = server_path;
1728 fpa.config_info.git_url = git_url;
1729 fpa.config_info.fetch_all_branches = fetch_all_branches;
1730 fpa.config_info.mirror_references = mirror_references;
1731 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1732 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1733 fetch_all_branches, &wanted_branches, &wanted_refs,
1734 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1735 fetch_progress, &fpa);
1736 if (error)
1737 goto done;
1739 if (list_refs_only) {
1740 error = list_remote_refs(&symrefs, &refs);
1741 goto done;
1744 if (pack_hash == NULL) {
1745 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1746 "server sent an empty pack file");
1747 goto done;
1749 error = got_object_id_str(&id_str, pack_hash);
1750 if (error)
1751 goto done;
1752 if (verbosity >= 0)
1753 printf("\nFetched %s.pack\n", id_str);
1754 free(id_str);
1756 /* Set up references provided with the pack file. */
1757 TAILQ_FOREACH(pe, &refs, entry) {
1758 const char *refname = pe->path;
1759 struct got_object_id *id = pe->data;
1760 char *remote_refname;
1762 if (is_wanted_ref(&wanted_refs, refname) &&
1763 !mirror_references) {
1764 error = create_wanted_ref(refname, id,
1765 GOT_FETCH_DEFAULT_REMOTE_NAME,
1766 verbosity - 1, repo);
1767 if (error)
1768 goto done;
1769 continue;
1772 error = create_ref(refname, id, verbosity - 1, repo);
1773 if (error)
1774 goto done;
1776 if (mirror_references)
1777 continue;
1779 if (strncmp("refs/heads/", refname, 11) != 0)
1780 continue;
1782 if (asprintf(&remote_refname,
1783 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1784 refname + 11) == -1) {
1785 error = got_error_from_errno("asprintf");
1786 goto done;
1788 error = create_ref(remote_refname, id, verbosity - 1, repo);
1789 free(remote_refname);
1790 if (error)
1791 goto done;
1794 /* Set the HEAD reference if the server provided one. */
1795 TAILQ_FOREACH(pe, &symrefs, entry) {
1796 struct got_reference *target_ref;
1797 const char *refname = pe->path;
1798 const char *target = pe->data;
1799 char *remote_refname = NULL, *remote_target = NULL;
1801 if (strcmp(refname, GOT_REF_HEAD) != 0)
1802 continue;
1804 error = got_ref_open(&target_ref, repo, target, 0);
1805 if (error) {
1806 if (error->code == GOT_ERR_NOT_REF) {
1807 error = NULL;
1808 continue;
1810 goto done;
1813 error = create_symref(refname, target_ref, verbosity, repo);
1814 got_ref_close(target_ref);
1815 if (error)
1816 goto done;
1818 if (mirror_references)
1819 continue;
1821 if (strncmp("refs/heads/", target, 11) != 0)
1822 continue;
1824 if (asprintf(&remote_refname,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 refname) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 goto done;
1830 if (asprintf(&remote_target,
1831 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1832 target + 11) == -1) {
1833 error = got_error_from_errno("asprintf");
1834 free(remote_refname);
1835 goto done;
1837 error = got_ref_open(&target_ref, repo, remote_target, 0);
1838 if (error) {
1839 free(remote_refname);
1840 free(remote_target);
1841 if (error->code == GOT_ERR_NOT_REF) {
1842 error = NULL;
1843 continue;
1845 goto done;
1847 error = create_symref(remote_refname, target_ref,
1848 verbosity - 1, repo);
1849 free(remote_refname);
1850 free(remote_target);
1851 got_ref_close(target_ref);
1852 if (error)
1853 goto done;
1855 if (pe == NULL) {
1857 * We failed to set the HEAD reference. If we asked for
1858 * a set of wanted branches use the first of one of those
1859 * which could be fetched instead.
1861 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1862 const char *target = pe->path;
1863 struct got_reference *target_ref;
1865 error = got_ref_open(&target_ref, repo, target, 0);
1866 if (error) {
1867 if (error->code == GOT_ERR_NOT_REF) {
1868 error = NULL;
1869 continue;
1871 goto done;
1874 error = create_symref(GOT_REF_HEAD, target_ref,
1875 verbosity, repo);
1876 got_ref_close(target_ref);
1877 if (error)
1878 goto done;
1879 break;
1882 if (!fpa.configs_created && pe != NULL) {
1883 error = create_config_files(fpa.config_info.proto,
1884 fpa.config_info.host, fpa.config_info.port,
1885 fpa.config_info.remote_repo_path,
1886 fpa.config_info.git_url,
1887 fpa.config_info.fetch_all_branches,
1888 fpa.config_info.mirror_references,
1889 fpa.config_info.symrefs,
1890 fpa.config_info.wanted_branches,
1891 fpa.config_info.wanted_refs, fpa.repo);
1892 if (error)
1893 goto done;
1897 if (verbosity >= 0)
1898 printf("Created %s repository '%s'\n",
1899 mirror_references ? "mirrored" : "cloned", repo_path);
1900 done:
1901 if (pack_fds) {
1902 const struct got_error *pack_err =
1903 got_repo_pack_fds_close(pack_fds);
1904 if (error == NULL)
1905 error = pack_err;
1907 if (fetchpid > 0) {
1908 if (kill(fetchpid, SIGTERM) == -1)
1909 error = got_error_from_errno("kill");
1910 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1911 error = got_error_from_errno("waitpid");
1913 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1914 error = got_error_from_errno("close");
1915 if (repo) {
1916 const struct got_error *close_err = got_repo_close(repo);
1917 if (error == NULL)
1918 error = close_err;
1920 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1922 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1923 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1924 free(pack_hash);
1925 free(proto);
1926 free(host);
1927 free(port);
1928 free(server_path);
1929 free(repo_name);
1930 free(default_destdir);
1931 free(git_url);
1932 return error;
1935 static const struct got_error *
1936 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1937 int replace_tags, int verbosity, struct got_repository *repo)
1939 const struct got_error *err = NULL;
1940 char *new_id_str = NULL;
1941 struct got_object_id *old_id = NULL;
1943 err = got_object_id_str(&new_id_str, new_id);
1944 if (err)
1945 goto done;
1947 if (!replace_tags &&
1948 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1949 err = got_ref_resolve(&old_id, repo, ref);
1950 if (err)
1951 goto done;
1952 if (got_object_id_cmp(old_id, new_id) == 0)
1953 goto done;
1954 if (verbosity >= 0) {
1955 printf("Rejecting update of existing tag %s: %s\n",
1956 got_ref_get_name(ref), new_id_str);
1958 goto done;
1961 if (got_ref_is_symbolic(ref)) {
1962 if (verbosity >= 0) {
1963 printf("Replacing reference %s: %s\n",
1964 got_ref_get_name(ref),
1965 got_ref_get_symref_target(ref));
1967 err = got_ref_change_symref_to_ref(ref, new_id);
1968 if (err)
1969 goto done;
1970 err = got_ref_write(ref, repo);
1971 if (err)
1972 goto done;
1973 } else {
1974 err = got_ref_resolve(&old_id, repo, ref);
1975 if (err)
1976 goto done;
1977 if (got_object_id_cmp(old_id, new_id) == 0)
1978 goto done;
1980 err = got_ref_change_ref(ref, new_id);
1981 if (err)
1982 goto done;
1983 err = got_ref_write(ref, repo);
1984 if (err)
1985 goto done;
1988 if (verbosity >= 0)
1989 printf("Updated %s: %s\n", got_ref_get_name(ref),
1990 new_id_str);
1991 done:
1992 free(old_id);
1993 free(new_id_str);
1994 return err;
1997 static const struct got_error *
1998 update_symref(const char *refname, struct got_reference *target_ref,
1999 int verbosity, struct got_repository *repo)
2001 const struct got_error *err = NULL, *unlock_err;
2002 struct got_reference *symref;
2003 int symref_is_locked = 0;
2005 err = got_ref_open(&symref, repo, refname, 1);
2006 if (err) {
2007 if (err->code != GOT_ERR_NOT_REF)
2008 return err;
2009 err = got_ref_alloc_symref(&symref, refname, target_ref);
2010 if (err)
2011 goto done;
2013 err = got_ref_write(symref, repo);
2014 if (err)
2015 goto done;
2017 if (verbosity >= 0)
2018 printf("Created reference %s: %s\n",
2019 got_ref_get_name(symref),
2020 got_ref_get_symref_target(symref));
2021 } else {
2022 symref_is_locked = 1;
2024 if (strcmp(got_ref_get_symref_target(symref),
2025 got_ref_get_name(target_ref)) == 0)
2026 goto done;
2028 err = got_ref_change_symref(symref,
2029 got_ref_get_name(target_ref));
2030 if (err)
2031 goto done;
2033 err = got_ref_write(symref, repo);
2034 if (err)
2035 goto done;
2037 if (verbosity >= 0)
2038 printf("Updated %s: %s\n", got_ref_get_name(symref),
2039 got_ref_get_symref_target(symref));
2042 done:
2043 if (symref_is_locked) {
2044 unlock_err = got_ref_unlock(symref);
2045 if (unlock_err && err == NULL)
2046 err = unlock_err;
2048 got_ref_close(symref);
2049 return err;
2052 __dead static void
2053 usage_fetch(void)
2055 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2056 "[-R reference] [-r repository-path] [remote-repository]\n",
2057 getprogname());
2058 exit(1);
2061 static const struct got_error *
2062 delete_missing_ref(struct got_reference *ref,
2063 int verbosity, struct got_repository *repo)
2065 const struct got_error *err = NULL;
2066 struct got_object_id *id = NULL;
2067 char *id_str = NULL;
2069 if (got_ref_is_symbolic(ref)) {
2070 err = got_ref_delete(ref, repo);
2071 if (err)
2072 return err;
2073 if (verbosity >= 0) {
2074 printf("Deleted %s: %s\n",
2075 got_ref_get_name(ref),
2076 got_ref_get_symref_target(ref));
2078 } else {
2079 err = got_ref_resolve(&id, repo, ref);
2080 if (err)
2081 return err;
2082 err = got_object_id_str(&id_str, id);
2083 if (err)
2084 goto done;
2086 err = got_ref_delete(ref, repo);
2087 if (err)
2088 goto done;
2089 if (verbosity >= 0) {
2090 printf("Deleted %s: %s\n",
2091 got_ref_get_name(ref), id_str);
2094 done:
2095 free(id);
2096 free(id_str);
2097 return err;
2100 static const struct got_error *
2101 delete_missing_refs(struct got_pathlist_head *their_refs,
2102 struct got_pathlist_head *their_symrefs,
2103 const struct got_remote_repo *remote,
2104 int verbosity, struct got_repository *repo)
2106 const struct got_error *err = NULL, *unlock_err;
2107 struct got_reflist_head my_refs;
2108 struct got_reflist_entry *re;
2109 struct got_pathlist_entry *pe;
2110 char *remote_namespace = NULL;
2111 char *local_refname = NULL;
2113 TAILQ_INIT(&my_refs);
2115 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2116 == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2120 if (err)
2121 goto done;
2123 TAILQ_FOREACH(re, &my_refs, entry) {
2124 const char *refname = got_ref_get_name(re->ref);
2125 const char *their_refname;
2127 if (remote->mirror_references) {
2128 their_refname = refname;
2129 } else {
2130 if (strncmp(refname, remote_namespace,
2131 strlen(remote_namespace)) == 0) {
2132 if (strcmp(refname + strlen(remote_namespace),
2133 GOT_REF_HEAD) == 0)
2134 continue;
2135 if (asprintf(&local_refname, "refs/heads/%s",
2136 refname + strlen(remote_namespace)) == -1) {
2137 err = got_error_from_errno("asprintf");
2138 goto done;
2140 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2141 continue;
2143 their_refname = local_refname;
2146 TAILQ_FOREACH(pe, their_refs, entry) {
2147 if (strcmp(their_refname, pe->path) == 0)
2148 break;
2150 if (pe != NULL)
2151 continue;
2153 TAILQ_FOREACH(pe, their_symrefs, entry) {
2154 if (strcmp(their_refname, pe->path) == 0)
2155 break;
2157 if (pe != NULL)
2158 continue;
2160 err = delete_missing_ref(re->ref, verbosity, repo);
2161 if (err)
2162 break;
2164 if (local_refname) {
2165 struct got_reference *ref;
2166 err = got_ref_open(&ref, repo, local_refname, 1);
2167 if (err) {
2168 if (err->code != GOT_ERR_NOT_REF)
2169 break;
2170 free(local_refname);
2171 local_refname = NULL;
2172 continue;
2174 err = delete_missing_ref(ref, verbosity, repo);
2175 if (err)
2176 break;
2177 unlock_err = got_ref_unlock(ref);
2178 got_ref_close(ref);
2179 if (unlock_err && err == NULL) {
2180 err = unlock_err;
2181 break;
2184 free(local_refname);
2185 local_refname = NULL;
2188 done:
2189 got_ref_list_free(&my_refs);
2190 free(remote_namespace);
2191 free(local_refname);
2192 return err;
2195 static const struct got_error *
2196 update_wanted_ref(const char *refname, struct got_object_id *id,
2197 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2199 const struct got_error *err, *unlock_err;
2200 char *remote_refname;
2201 struct got_reference *ref;
2203 if (strncmp("refs/", refname, 5) == 0)
2204 refname += 5;
2206 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2207 remote_repo_name, refname) == -1)
2208 return got_error_from_errno("asprintf");
2210 err = got_ref_open(&ref, repo, remote_refname, 1);
2211 if (err) {
2212 if (err->code != GOT_ERR_NOT_REF)
2213 goto done;
2214 err = create_ref(remote_refname, id, verbosity, repo);
2215 } else {
2216 err = update_ref(ref, id, 0, verbosity, repo);
2217 unlock_err = got_ref_unlock(ref);
2218 if (unlock_err && err == NULL)
2219 err = unlock_err;
2220 got_ref_close(ref);
2222 done:
2223 free(remote_refname);
2224 return err;
2227 static const struct got_error *
2228 delete_ref(struct got_repository *repo, struct got_reference *ref)
2230 const struct got_error *err = NULL;
2231 struct got_object_id *id = NULL;
2232 char *id_str = NULL;
2233 const char *target;
2235 if (got_ref_is_symbolic(ref)) {
2236 target = got_ref_get_symref_target(ref);
2237 } else {
2238 err = got_ref_resolve(&id, repo, ref);
2239 if (err)
2240 goto done;
2241 err = got_object_id_str(&id_str, id);
2242 if (err)
2243 goto done;
2244 target = id_str;
2247 err = got_ref_delete(ref, repo);
2248 if (err)
2249 goto done;
2251 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2252 done:
2253 free(id);
2254 free(id_str);
2255 return err;
2258 static const struct got_error *
2259 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2261 const struct got_error *err = NULL;
2262 struct got_reflist_head refs;
2263 struct got_reflist_entry *re;
2264 char *prefix;
2266 TAILQ_INIT(&refs);
2268 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2269 err = got_error_from_errno("asprintf");
2270 goto done;
2272 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2273 if (err)
2274 goto done;
2276 TAILQ_FOREACH(re, &refs, entry)
2277 delete_ref(repo, re->ref);
2278 done:
2279 got_ref_list_free(&refs);
2280 return err;
2283 static const struct got_error *
2284 cmd_fetch(int argc, char *argv[])
2286 const struct got_error *error = NULL, *unlock_err;
2287 char *cwd = NULL, *repo_path = NULL;
2288 const char *remote_name;
2289 char *proto = NULL, *host = NULL, *port = NULL;
2290 char *repo_name = NULL, *server_path = NULL;
2291 const struct got_remote_repo *remotes, *remote = NULL;
2292 int nremotes;
2293 char *id_str = NULL;
2294 struct got_repository *repo = NULL;
2295 struct got_worktree *worktree = NULL;
2296 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2297 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2298 struct got_pathlist_entry *pe;
2299 struct got_reflist_head remote_refs;
2300 struct got_reflist_entry *re;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL, have_bflag = 0;
2308 const char *remote_head = NULL, *worktree_branch = NULL;
2310 TAILQ_INIT(&refs);
2311 TAILQ_INIT(&symrefs);
2312 TAILQ_INIT(&remote_refs);
2313 TAILQ_INIT(&wanted_branches);
2314 TAILQ_INIT(&wanted_refs);
2316 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2317 switch (ch) {
2318 case 'a':
2319 fetch_all_branches = 1;
2320 break;
2321 case 'b':
2322 error = got_pathlist_append(&wanted_branches,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 have_bflag = 1;
2327 break;
2328 case 'd':
2329 delete_refs = 1;
2330 break;
2331 case 'l':
2332 list_refs_only = 1;
2333 break;
2334 case 'q':
2335 verbosity = -1;
2336 break;
2337 case 'R':
2338 error = got_pathlist_append(&wanted_refs,
2339 optarg, NULL);
2340 if (error)
2341 return error;
2342 break;
2343 case 'r':
2344 repo_path = realpath(optarg, NULL);
2345 if (repo_path == NULL)
2346 return got_error_from_errno2("realpath",
2347 optarg);
2348 got_path_strip_trailing_slashes(repo_path);
2349 break;
2350 case 't':
2351 replace_tags = 1;
2352 break;
2353 case 'v':
2354 if (verbosity < 0)
2355 verbosity = 0;
2356 else if (verbosity < 3)
2357 verbosity++;
2358 break;
2359 case 'X':
2360 delete_remote = 1;
2361 break;
2362 default:
2363 usage_fetch();
2364 break;
2367 argc -= optind;
2368 argv += optind;
2370 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('a', 'b');
2372 if (list_refs_only) {
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('l', 'b');
2375 if (fetch_all_branches)
2376 option_conflict('l', 'a');
2377 if (delete_refs)
2378 option_conflict('l', 'd');
2379 if (delete_remote)
2380 option_conflict('l', 'X');
2382 if (delete_remote) {
2383 if (fetch_all_branches)
2384 option_conflict('X', 'a');
2385 if (!TAILQ_EMPTY(&wanted_branches))
2386 option_conflict('X', 'b');
2387 if (delete_refs)
2388 option_conflict('X', 'd');
2389 if (replace_tags)
2390 option_conflict('X', 't');
2391 if (!TAILQ_EMPTY(&wanted_refs))
2392 option_conflict('X', 'R');
2395 if (argc == 0) {
2396 if (delete_remote)
2397 errx(1, "-X option requires a remote name");
2398 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2399 } else if (argc == 1)
2400 remote_name = argv[0];
2401 else
2402 usage_fetch();
2404 cwd = getcwd(NULL, 0);
2405 if (cwd == NULL) {
2406 error = got_error_from_errno("getcwd");
2407 goto done;
2410 error = got_repo_pack_fds_open(&pack_fds);
2411 if (error != NULL)
2412 goto done;
2414 if (repo_path == NULL) {
2415 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2417 goto done;
2418 else
2419 error = NULL;
2420 if (worktree) {
2421 repo_path =
2422 strdup(got_worktree_get_repo_path(worktree));
2423 if (repo_path == NULL)
2424 error = got_error_from_errno("strdup");
2425 if (error)
2426 goto done;
2427 } else {
2428 repo_path = strdup(cwd);
2429 if (repo_path == NULL) {
2430 error = got_error_from_errno("strdup");
2431 goto done;
2436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2437 if (error)
2438 goto done;
2440 if (delete_remote) {
2441 error = delete_refs_for_remote(repo, remote_name);
2442 goto done; /* nothing else to do */
2445 if (worktree) {
2446 worktree_conf = got_worktree_get_gotconfig(worktree);
2447 if (worktree_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 worktree_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 remote = &remotes[i];
2453 break;
2458 if (remote == NULL) {
2459 repo_conf = got_repo_get_gotconfig(repo);
2460 if (repo_conf) {
2461 got_gotconfig_get_remotes(&nremotes, &remotes,
2462 repo_conf);
2463 for (i = 0; i < nremotes; i++) {
2464 if (strcmp(remotes[i].name, remote_name) == 0) {
2465 remote = &remotes[i];
2466 break;
2471 if (remote == NULL) {
2472 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2473 for (i = 0; i < nremotes; i++) {
2474 if (strcmp(remotes[i].name, remote_name) == 0) {
2475 remote = &remotes[i];
2476 break;
2480 if (remote == NULL) {
2481 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2482 goto done;
2485 if (TAILQ_EMPTY(&wanted_branches)) {
2486 if (!fetch_all_branches)
2487 fetch_all_branches = remote->fetch_all_branches;
2488 for (i = 0; i < remote->nfetch_branches; i++) {
2489 error = got_pathlist_append(&wanted_branches,
2490 remote->fetch_branches[i], NULL);
2491 if (error)
2492 goto done;
2495 if (TAILQ_EMPTY(&wanted_refs)) {
2496 for (i = 0; i < remote->nfetch_refs; i++) {
2497 error = got_pathlist_append(&wanted_refs,
2498 remote->fetch_refs[i], NULL);
2499 if (error)
2500 goto done;
2504 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2505 &repo_name, remote->fetch_url);
2506 if (error)
2507 goto done;
2509 if (strcmp(proto, "git") == 0) {
2510 #ifndef PROFILE
2511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2512 "sendfd dns inet unveil", NULL) == -1)
2513 err(1, "pledge");
2514 #endif
2515 } else if (strcmp(proto, "git+ssh") == 0 ||
2516 strcmp(proto, "ssh") == 0) {
2517 #ifndef PROFILE
2518 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2519 "sendfd unveil", NULL) == -1)
2520 err(1, "pledge");
2521 #endif
2522 } else if (strcmp(proto, "http") == 0 ||
2523 strcmp(proto, "git+http") == 0) {
2524 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2525 goto done;
2526 } else {
2527 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2528 goto done;
2531 error = got_dial_apply_unveil(proto);
2532 if (error)
2533 goto done;
2535 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2536 if (error)
2537 goto done;
2539 if (verbosity >= 0) {
2540 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2541 remote->name, proto, host,
2542 port ? ":" : "", port ? port : "",
2543 *server_path == '/' ? "" : "/", server_path);
2546 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2547 server_path, verbosity);
2548 if (error)
2549 goto done;
2551 if (!have_bflag) {
2553 * If set, get this remote's HEAD ref target so
2554 * if it has changed on the server we can fetch it.
2556 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2557 got_ref_cmp_by_name, repo);
2558 if (error)
2559 goto done;
2561 TAILQ_FOREACH(re, &remote_refs, entry) {
2562 const char *remote_refname, *remote_target;
2563 size_t remote_name_len;
2565 if (!got_ref_is_symbolic(re->ref))
2566 continue;
2568 remote_name_len = strlen(remote->name);
2569 remote_refname = got_ref_get_name(re->ref);
2571 /* we only want refs/remotes/$remote->name/HEAD */
2572 if (strncmp(remote_refname + 13, remote->name,
2573 remote_name_len) != 0)
2574 continue;
2576 if (strcmp(remote_refname + remote_name_len + 14,
2577 GOT_REF_HEAD) != 0)
2578 continue;
2581 * Take the name itself because we already
2582 * only match with refs/heads/ in fetch_pack().
2584 remote_target = got_ref_get_symref_target(re->ref);
2585 remote_head = remote_target + remote_name_len + 14;
2586 break;
2589 if (worktree) {
2590 const char *refname;
2592 refname = got_worktree_get_head_ref_name(worktree);
2593 if (strncmp(refname, "refs/heads/", 11) == 0)
2594 worktree_branch = refname;
2598 fpa.last_scaled_size[0] = '\0';
2599 fpa.last_p_indexed = -1;
2600 fpa.last_p_resolved = -1;
2601 fpa.verbosity = verbosity;
2602 fpa.repo = repo;
2603 fpa.create_configs = 0;
2604 fpa.configs_created = 0;
2605 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2607 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2608 remote->mirror_references, fetch_all_branches, &wanted_branches,
2609 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2610 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2611 if (error)
2612 goto done;
2614 if (list_refs_only) {
2615 error = list_remote_refs(&symrefs, &refs);
2616 goto done;
2619 if (pack_hash == NULL) {
2620 if (verbosity >= 0)
2621 printf("Already up-to-date\n");
2622 } else if (verbosity >= 0) {
2623 error = got_object_id_str(&id_str, pack_hash);
2624 if (error)
2625 goto done;
2626 printf("\nFetched %s.pack\n", id_str);
2627 free(id_str);
2628 id_str = NULL;
2631 /* Update references provided with the pack file. */
2632 TAILQ_FOREACH(pe, &refs, entry) {
2633 const char *refname = pe->path;
2634 struct got_object_id *id = pe->data;
2635 struct got_reference *ref;
2636 char *remote_refname;
2638 if (is_wanted_ref(&wanted_refs, refname) &&
2639 !remote->mirror_references) {
2640 error = update_wanted_ref(refname, id,
2641 remote->name, verbosity, repo);
2642 if (error)
2643 goto done;
2644 continue;
2647 if (remote->mirror_references ||
2648 strncmp("refs/tags/", refname, 10) == 0) {
2649 error = got_ref_open(&ref, repo, refname, 1);
2650 if (error) {
2651 if (error->code != GOT_ERR_NOT_REF)
2652 goto done;
2653 error = create_ref(refname, id, verbosity,
2654 repo);
2655 if (error)
2656 goto done;
2657 } else {
2658 error = update_ref(ref, id, replace_tags,
2659 verbosity, repo);
2660 unlock_err = got_ref_unlock(ref);
2661 if (unlock_err && error == NULL)
2662 error = unlock_err;
2663 got_ref_close(ref);
2664 if (error)
2665 goto done;
2667 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2668 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2669 remote_name, refname + 11) == -1) {
2670 error = got_error_from_errno("asprintf");
2671 goto done;
2674 error = got_ref_open(&ref, repo, remote_refname, 1);
2675 if (error) {
2676 if (error->code != GOT_ERR_NOT_REF)
2677 goto done;
2678 error = create_ref(remote_refname, id,
2679 verbosity, repo);
2680 if (error)
2681 goto done;
2682 } else {
2683 error = update_ref(ref, id, replace_tags,
2684 verbosity, repo);
2685 unlock_err = got_ref_unlock(ref);
2686 if (unlock_err && error == NULL)
2687 error = unlock_err;
2688 got_ref_close(ref);
2689 if (error)
2690 goto done;
2693 /* Also create a local branch if none exists yet. */
2694 error = got_ref_open(&ref, repo, refname, 1);
2695 if (error) {
2696 if (error->code != GOT_ERR_NOT_REF)
2697 goto done;
2698 error = create_ref(refname, id, verbosity,
2699 repo);
2700 if (error)
2701 goto done;
2702 } else {
2703 unlock_err = got_ref_unlock(ref);
2704 if (unlock_err && error == NULL)
2705 error = unlock_err;
2706 got_ref_close(ref);
2710 if (delete_refs) {
2711 error = delete_missing_refs(&refs, &symrefs, remote,
2712 verbosity, repo);
2713 if (error)
2714 goto done;
2717 if (!remote->mirror_references) {
2718 /* Update remote HEAD reference if the server provided one. */
2719 TAILQ_FOREACH(pe, &symrefs, entry) {
2720 struct got_reference *target_ref;
2721 const char *refname = pe->path;
2722 const char *target = pe->data;
2723 char *remote_refname = NULL, *remote_target = NULL;
2725 if (strcmp(refname, GOT_REF_HEAD) != 0)
2726 continue;
2728 if (strncmp("refs/heads/", target, 11) != 0)
2729 continue;
2731 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2732 remote->name, refname) == -1) {
2733 error = got_error_from_errno("asprintf");
2734 goto done;
2736 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2737 remote->name, target + 11) == -1) {
2738 error = got_error_from_errno("asprintf");
2739 free(remote_refname);
2740 goto done;
2743 error = got_ref_open(&target_ref, repo, remote_target,
2744 0);
2745 if (error) {
2746 free(remote_refname);
2747 free(remote_target);
2748 if (error->code == GOT_ERR_NOT_REF) {
2749 error = NULL;
2750 continue;
2752 goto done;
2754 error = update_symref(remote_refname, target_ref,
2755 verbosity, repo);
2756 free(remote_refname);
2757 free(remote_target);
2758 got_ref_close(target_ref);
2759 if (error)
2760 goto done;
2763 done:
2764 if (fetchpid > 0) {
2765 if (kill(fetchpid, SIGTERM) == -1)
2766 error = got_error_from_errno("kill");
2767 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2768 error = got_error_from_errno("waitpid");
2770 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2771 error = got_error_from_errno("close");
2772 if (repo) {
2773 const struct got_error *close_err = got_repo_close(repo);
2774 if (error == NULL)
2775 error = close_err;
2777 if (worktree)
2778 got_worktree_close(worktree);
2779 if (pack_fds) {
2780 const struct got_error *pack_err =
2781 got_repo_pack_fds_close(pack_fds);
2782 if (error == NULL)
2783 error = pack_err;
2785 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2787 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2788 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2789 got_ref_list_free(&remote_refs);
2790 free(id_str);
2791 free(cwd);
2792 free(repo_path);
2793 free(pack_hash);
2794 free(proto);
2795 free(host);
2796 free(port);
2797 free(server_path);
2798 free(repo_name);
2799 return error;
2803 __dead static void
2804 usage_checkout(void)
2806 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2807 "[-p path-prefix] repository-path [work-tree-path]\n",
2808 getprogname());
2809 exit(1);
2812 static void
2813 show_worktree_base_ref_warning(void)
2815 fprintf(stderr, "%s: warning: could not create a reference "
2816 "to the work tree's base commit; the commit could be "
2817 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2818 "repository writable and running 'got update' will prevent this\n",
2819 getprogname());
2822 struct got_checkout_progress_arg {
2823 const char *worktree_path;
2824 int had_base_commit_ref_error;
2825 int verbosity;
2828 static const struct got_error *
2829 checkout_progress(void *arg, unsigned char status, const char *path)
2831 struct got_checkout_progress_arg *a = arg;
2833 /* Base commit bump happens silently. */
2834 if (status == GOT_STATUS_BUMP_BASE)
2835 return NULL;
2837 if (status == GOT_STATUS_BASE_REF_ERR) {
2838 a->had_base_commit_ref_error = 1;
2839 return NULL;
2842 while (path[0] == '/')
2843 path++;
2845 if (a->verbosity >= 0)
2846 printf("%c %s/%s\n", status, a->worktree_path, path);
2848 return NULL;
2851 static const struct got_error *
2852 check_cancelled(void *arg)
2854 if (sigint_received || sigpipe_received)
2855 return got_error(GOT_ERR_CANCELLED);
2856 return NULL;
2859 static const struct got_error *
2860 check_linear_ancestry(struct got_object_id *commit_id,
2861 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2862 struct got_repository *repo)
2864 const struct got_error *err = NULL;
2865 struct got_object_id *yca_id;
2867 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2868 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2869 if (err)
2870 return err;
2872 if (yca_id == NULL)
2873 return got_error(GOT_ERR_ANCESTRY);
2876 * Require a straight line of history between the target commit
2877 * and the work tree's base commit.
2879 * Non-linear situations such as this require a rebase:
2881 * (commit) D F (base_commit)
2882 * \ /
2883 * C E
2884 * \ /
2885 * B (yca)
2886 * |
2887 * A
2889 * 'got update' only handles linear cases:
2890 * Update forwards in time: A (base/yca) - B - C - D (commit)
2891 * Update backwards in time: D (base) - C - B - A (commit/yca)
2893 if (allow_forwards_in_time_only) {
2894 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2895 return got_error(GOT_ERR_ANCESTRY);
2896 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2897 got_object_id_cmp(base_commit_id, yca_id) != 0)
2898 return got_error(GOT_ERR_ANCESTRY);
2900 free(yca_id);
2901 return NULL;
2904 static const struct got_error *
2905 check_same_branch(struct got_object_id *commit_id,
2906 struct got_reference *head_ref, struct got_repository *repo)
2908 const struct got_error *err = NULL;
2909 struct got_commit_graph *graph = NULL;
2910 struct got_object_id *head_commit_id = NULL;
2912 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2913 if (err)
2914 goto done;
2916 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2917 goto done;
2919 err = got_commit_graph_open(&graph, "/", 1);
2920 if (err)
2921 goto done;
2923 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2924 check_cancelled, NULL);
2925 if (err)
2926 goto done;
2928 for (;;) {
2929 struct got_object_id id;
2931 err = got_commit_graph_iter_next(&id, graph, repo,
2932 check_cancelled, NULL);
2933 if (err) {
2934 if (err->code == GOT_ERR_ITER_COMPLETED)
2935 err = got_error(GOT_ERR_ANCESTRY);
2936 break;
2939 if (got_object_id_cmp(&id, commit_id) == 0)
2940 break;
2942 done:
2943 if (graph)
2944 got_commit_graph_close(graph);
2945 free(head_commit_id);
2946 return err;
2949 static const struct got_error *
2950 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2952 static char msg[512];
2953 const char *branch_name;
2955 if (got_ref_is_symbolic(ref))
2956 branch_name = got_ref_get_symref_target(ref);
2957 else
2958 branch_name = got_ref_get_name(ref);
2960 if (strncmp("refs/heads/", branch_name, 11) == 0)
2961 branch_name += 11;
2963 snprintf(msg, sizeof(msg),
2964 "target commit is not contained in branch '%s'; "
2965 "the branch to use must be specified with -b; "
2966 "if necessary a new branch can be created for "
2967 "this commit with 'got branch -c %s BRANCH_NAME'",
2968 branch_name, commit_id_str);
2970 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2973 static const struct got_error *
2974 cmd_checkout(int argc, char *argv[])
2976 const struct got_error *error = NULL;
2977 struct got_repository *repo = NULL;
2978 struct got_reference *head_ref = NULL, *ref = NULL;
2979 struct got_worktree *worktree = NULL;
2980 char *repo_path = NULL;
2981 char *worktree_path = NULL;
2982 const char *path_prefix = "";
2983 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2984 char *commit_id_str = NULL, *keyword_idstr = NULL;
2985 struct got_object_id *commit_id = NULL;
2986 char *cwd = NULL;
2987 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2988 struct got_pathlist_head paths;
2989 struct got_checkout_progress_arg cpa;
2990 int *pack_fds = NULL;
2992 TAILQ_INIT(&paths);
2994 #ifndef PROFILE
2995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2996 "unveil", NULL) == -1)
2997 err(1, "pledge");
2998 #endif
3000 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3001 switch (ch) {
3002 case 'b':
3003 branch_name = optarg;
3004 break;
3005 case 'c':
3006 commit_id_str = strdup(optarg);
3007 if (commit_id_str == NULL)
3008 return got_error_from_errno("strdup");
3009 break;
3010 case 'E':
3011 allow_nonempty = 1;
3012 break;
3013 case 'p':
3014 path_prefix = optarg;
3015 break;
3016 case 'q':
3017 verbosity = -1;
3018 break;
3019 default:
3020 usage_checkout();
3021 /* NOTREACHED */
3025 argc -= optind;
3026 argv += optind;
3028 if (argc == 1) {
3029 char *base, *dotgit;
3030 const char *path;
3031 repo_path = realpath(argv[0], NULL);
3032 if (repo_path == NULL)
3033 return got_error_from_errno2("realpath", argv[0]);
3034 cwd = getcwd(NULL, 0);
3035 if (cwd == NULL) {
3036 error = got_error_from_errno("getcwd");
3037 goto done;
3039 if (path_prefix[0])
3040 path = path_prefix;
3041 else
3042 path = repo_path;
3043 error = got_path_basename(&base, path);
3044 if (error)
3045 goto done;
3046 dotgit = strstr(base, ".git");
3047 if (dotgit)
3048 *dotgit = '\0';
3049 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3050 error = got_error_from_errno("asprintf");
3051 free(base);
3052 goto done;
3054 free(base);
3055 } else if (argc == 2) {
3056 repo_path = realpath(argv[0], NULL);
3057 if (repo_path == NULL) {
3058 error = got_error_from_errno2("realpath", argv[0]);
3059 goto done;
3061 worktree_path = realpath(argv[1], NULL);
3062 if (worktree_path == NULL) {
3063 if (errno != ENOENT) {
3064 error = got_error_from_errno2("realpath",
3065 argv[1]);
3066 goto done;
3068 worktree_path = strdup(argv[1]);
3069 if (worktree_path == NULL) {
3070 error = got_error_from_errno("strdup");
3071 goto done;
3074 } else
3075 usage_checkout();
3077 got_path_strip_trailing_slashes(repo_path);
3078 got_path_strip_trailing_slashes(worktree_path);
3080 error = got_repo_pack_fds_open(&pack_fds);
3081 if (error != NULL)
3082 goto done;
3084 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3085 if (error != NULL)
3086 goto done;
3088 /* Pre-create work tree path for unveil(2) */
3089 error = got_path_mkdir(worktree_path);
3090 if (error) {
3091 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3092 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3093 goto done;
3094 if (!allow_nonempty &&
3095 !got_path_dir_is_empty(worktree_path)) {
3096 error = got_error_path(worktree_path,
3097 GOT_ERR_DIR_NOT_EMPTY);
3098 goto done;
3102 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3103 if (error)
3104 goto done;
3106 error = got_ref_open(&head_ref, repo, branch_name, 0);
3107 if (error != NULL)
3108 goto done;
3110 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3111 GOT_WORKTREE_GOT_DIR, repo);
3112 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3113 goto done;
3115 error = got_worktree_open(&worktree, worktree_path,
3116 GOT_WORKTREE_GOT_DIR);
3117 if (error != NULL)
3118 goto done;
3120 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3121 path_prefix);
3122 if (error != NULL)
3123 goto done;
3124 if (!same_path_prefix) {
3125 error = got_error(GOT_ERR_PATH_PREFIX);
3126 goto done;
3129 if (commit_id_str) {
3130 struct got_reflist_head refs;
3131 TAILQ_INIT(&refs);
3132 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3133 NULL);
3134 if (error)
3135 goto done;
3137 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3138 repo, worktree);
3139 if (error != NULL)
3140 goto done;
3141 if (keyword_idstr != NULL) {
3142 free(commit_id_str);
3143 commit_id_str = keyword_idstr;
3146 error = got_repo_match_object_id(&commit_id, NULL,
3147 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3148 got_ref_list_free(&refs);
3149 if (error)
3150 goto done;
3151 error = check_linear_ancestry(commit_id,
3152 got_worktree_get_base_commit_id(worktree), 0, repo);
3153 if (error != NULL) {
3154 if (error->code == GOT_ERR_ANCESTRY) {
3155 error = checkout_ancestry_error(
3156 head_ref, commit_id_str);
3158 goto done;
3160 error = check_same_branch(commit_id, head_ref, repo);
3161 if (error) {
3162 if (error->code == GOT_ERR_ANCESTRY) {
3163 error = checkout_ancestry_error(
3164 head_ref, commit_id_str);
3166 goto done;
3168 error = got_worktree_set_base_commit_id(worktree, repo,
3169 commit_id);
3170 if (error)
3171 goto done;
3172 /* Expand potentially abbreviated commit ID string. */
3173 free(commit_id_str);
3174 error = got_object_id_str(&commit_id_str, commit_id);
3175 if (error)
3176 goto done;
3177 } else {
3178 commit_id = got_object_id_dup(
3179 got_worktree_get_base_commit_id(worktree));
3180 if (commit_id == NULL) {
3181 error = got_error_from_errno("got_object_id_dup");
3182 goto done;
3184 error = got_object_id_str(&commit_id_str, commit_id);
3185 if (error)
3186 goto done;
3189 error = got_pathlist_append(&paths, "", NULL);
3190 if (error)
3191 goto done;
3192 cpa.worktree_path = worktree_path;
3193 cpa.had_base_commit_ref_error = 0;
3194 cpa.verbosity = verbosity;
3195 error = got_worktree_checkout_files(worktree, &paths, repo,
3196 checkout_progress, &cpa, check_cancelled, NULL);
3197 if (error != NULL)
3198 goto done;
3200 if (got_ref_is_symbolic(head_ref)) {
3201 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3202 if (error)
3203 goto done;
3204 refname = got_ref_get_name(ref);
3205 } else
3206 refname = got_ref_get_name(head_ref);
3207 printf("Checked out %s: %s\n", refname, commit_id_str);
3208 printf("Now shut up and hack\n");
3209 if (cpa.had_base_commit_ref_error)
3210 show_worktree_base_ref_warning();
3211 done:
3212 if (pack_fds) {
3213 const struct got_error *pack_err =
3214 got_repo_pack_fds_close(pack_fds);
3215 if (error == NULL)
3216 error = pack_err;
3218 if (head_ref)
3219 got_ref_close(head_ref);
3220 if (ref)
3221 got_ref_close(ref);
3222 if (repo) {
3223 const struct got_error *close_err = got_repo_close(repo);
3224 if (error == NULL)
3225 error = close_err;
3227 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3228 free(commit_id_str);
3229 free(commit_id);
3230 free(repo_path);
3231 free(worktree_path);
3232 free(cwd);
3233 return error;
3236 struct got_update_progress_arg {
3237 int did_something;
3238 int conflicts;
3239 int obstructed;
3240 int not_updated;
3241 int missing;
3242 int not_deleted;
3243 int unversioned;
3244 int verbosity;
3247 static void
3248 print_update_progress_stats(struct got_update_progress_arg *upa)
3250 if (!upa->did_something)
3251 return;
3253 if (upa->conflicts > 0)
3254 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3255 if (upa->obstructed > 0)
3256 printf("File paths obstructed by a non-regular file: %d\n",
3257 upa->obstructed);
3258 if (upa->not_updated > 0)
3259 printf("Files not updated because of existing merge "
3260 "conflicts: %d\n", upa->not_updated);
3264 * The meaning of some status codes differs between merge-style operations and
3265 * update operations. For example, the ! status code means "file was missing"
3266 * if changes were merged into the work tree, and "missing file was restored"
3267 * if the work tree was updated. This function should be used by any operation
3268 * which merges changes into the work tree without updating the work tree.
3270 static void
3271 print_merge_progress_stats(struct got_update_progress_arg *upa)
3273 if (!upa->did_something)
3274 return;
3276 if (upa->conflicts > 0)
3277 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3278 if (upa->obstructed > 0)
3279 printf("File paths obstructed by a non-regular file: %d\n",
3280 upa->obstructed);
3281 if (upa->missing > 0)
3282 printf("Files which had incoming changes but could not be "
3283 "found in the work tree: %d\n", upa->missing);
3284 if (upa->not_deleted > 0)
3285 printf("Files not deleted due to differences in deleted "
3286 "content: %d\n", upa->not_deleted);
3287 if (upa->unversioned > 0)
3288 printf("Files not merged because an unversioned file was "
3289 "found in the work tree: %d\n", upa->unversioned);
3292 __dead static void
3293 usage_update(void)
3295 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3296 "[path ...]\n", getprogname());
3297 exit(1);
3300 static const struct got_error *
3301 update_progress(void *arg, unsigned char status, const char *path)
3303 struct got_update_progress_arg *upa = arg;
3305 if (status == GOT_STATUS_EXISTS ||
3306 status == GOT_STATUS_BASE_REF_ERR)
3307 return NULL;
3309 upa->did_something = 1;
3311 /* Base commit bump happens silently. */
3312 if (status == GOT_STATUS_BUMP_BASE)
3313 return NULL;
3315 if (status == GOT_STATUS_CONFLICT)
3316 upa->conflicts++;
3317 if (status == GOT_STATUS_OBSTRUCTED)
3318 upa->obstructed++;
3319 if (status == GOT_STATUS_CANNOT_UPDATE)
3320 upa->not_updated++;
3321 if (status == GOT_STATUS_MISSING)
3322 upa->missing++;
3323 if (status == GOT_STATUS_CANNOT_DELETE)
3324 upa->not_deleted++;
3325 if (status == GOT_STATUS_UNVERSIONED)
3326 upa->unversioned++;
3328 while (path[0] == '/')
3329 path++;
3330 if (upa->verbosity >= 0)
3331 printf("%c %s\n", status, path);
3333 return NULL;
3336 static const struct got_error *
3337 switch_head_ref(struct got_reference *head_ref,
3338 struct got_object_id *commit_id, struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err = NULL;
3342 char *base_id_str;
3343 int ref_has_moved = 0;
3345 /* Trivial case: switching between two different references. */
3346 if (strcmp(got_ref_get_name(head_ref),
3347 got_worktree_get_head_ref_name(worktree)) != 0) {
3348 printf("Switching work tree from %s to %s\n",
3349 got_worktree_get_head_ref_name(worktree),
3350 got_ref_get_name(head_ref));
3351 return got_worktree_set_head_ref(worktree, head_ref);
3354 err = check_linear_ancestry(commit_id,
3355 got_worktree_get_base_commit_id(worktree), 0, repo);
3356 if (err) {
3357 if (err->code != GOT_ERR_ANCESTRY)
3358 return err;
3359 ref_has_moved = 1;
3361 if (!ref_has_moved)
3362 return NULL;
3364 /* Switching to a rebased branch with the same reference name. */
3365 err = got_object_id_str(&base_id_str,
3366 got_worktree_get_base_commit_id(worktree));
3367 if (err)
3368 return err;
3369 printf("Reference %s now points at a different branch\n",
3370 got_worktree_get_head_ref_name(worktree));
3371 printf("Switching work tree from %s to %s\n", base_id_str,
3372 got_worktree_get_head_ref_name(worktree));
3373 return NULL;
3376 static const struct got_error *
3377 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3379 const struct got_error *err;
3380 int in_progress;
3382 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3383 if (err)
3384 return err;
3385 if (in_progress)
3386 return got_error(GOT_ERR_REBASING);
3388 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3389 if (err)
3390 return err;
3391 if (in_progress)
3392 return got_error(GOT_ERR_HISTEDIT_BUSY);
3394 return NULL;
3397 static const struct got_error *
3398 check_merge_in_progress(struct got_worktree *worktree,
3399 struct got_repository *repo)
3401 const struct got_error *err;
3402 int in_progress;
3404 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3405 if (err)
3406 return err;
3407 if (in_progress)
3408 return got_error(GOT_ERR_MERGE_BUSY);
3410 return NULL;
3413 static const struct got_error *
3414 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3415 char *argv[], struct got_worktree *worktree)
3417 const struct got_error *err = NULL;
3418 char *path;
3419 struct got_pathlist_entry *new;
3420 int i;
3422 if (argc == 0) {
3423 path = strdup("");
3424 if (path == NULL)
3425 return got_error_from_errno("strdup");
3426 return got_pathlist_append(paths, path, NULL);
3429 for (i = 0; i < argc; i++) {
3430 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3431 if (err)
3432 break;
3433 err = got_pathlist_insert(&new, paths, path, NULL);
3434 if (err || new == NULL /* duplicate */) {
3435 free(path);
3436 if (err)
3437 break;
3441 return err;
3444 static const struct got_error *
3445 wrap_not_worktree_error(const struct got_error *orig_err,
3446 const char *cmdname, const char *path)
3448 const struct got_error *err;
3449 struct got_repository *repo;
3450 static char msg[512];
3451 int *pack_fds = NULL;
3453 err = got_repo_pack_fds_open(&pack_fds);
3454 if (err)
3455 return err;
3457 err = got_repo_open(&repo, path, NULL, pack_fds);
3458 if (err)
3459 return orig_err;
3461 snprintf(msg, sizeof(msg),
3462 "'got %s' needs a work tree in addition to a git repository\n"
3463 "Work trees can be checked out from this Git repository with "
3464 "'got checkout'.\n"
3465 "The got(1) manual page contains more information.", cmdname);
3466 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3467 if (repo) {
3468 const struct got_error *close_err = got_repo_close(repo);
3469 if (err == NULL)
3470 err = close_err;
3472 if (pack_fds) {
3473 const struct got_error *pack_err =
3474 got_repo_pack_fds_close(pack_fds);
3475 if (err == NULL)
3476 err = pack_err;
3478 return err;
3481 static const struct got_error *
3482 cmd_update(int argc, char *argv[])
3484 const struct got_error *error = NULL;
3485 struct got_repository *repo = NULL;
3486 struct got_worktree *worktree = NULL;
3487 char *worktree_path = NULL;
3488 struct got_object_id *commit_id = NULL;
3489 char *commit_id_str = NULL;
3490 const char *branch_name = NULL;
3491 struct got_reference *head_ref = NULL;
3492 struct got_pathlist_head paths;
3493 struct got_pathlist_entry *pe;
3494 int ch, verbosity = 0;
3495 struct got_update_progress_arg upa;
3496 int *pack_fds = NULL;
3498 TAILQ_INIT(&paths);
3500 #ifndef PROFILE
3501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3502 "unveil", NULL) == -1)
3503 err(1, "pledge");
3504 #endif
3506 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3507 switch (ch) {
3508 case 'b':
3509 branch_name = optarg;
3510 break;
3511 case 'c':
3512 commit_id_str = strdup(optarg);
3513 if (commit_id_str == NULL)
3514 return got_error_from_errno("strdup");
3515 break;
3516 case 'q':
3517 verbosity = -1;
3518 break;
3519 default:
3520 usage_update();
3521 /* NOTREACHED */
3525 argc -= optind;
3526 argv += optind;
3528 worktree_path = getcwd(NULL, 0);
3529 if (worktree_path == NULL) {
3530 error = got_error_from_errno("getcwd");
3531 goto done;
3534 error = got_repo_pack_fds_open(&pack_fds);
3535 if (error != NULL)
3536 goto done;
3538 error = got_worktree_open(&worktree, worktree_path,
3539 GOT_WORKTREE_GOT_DIR);
3540 if (error) {
3541 if (error->code == GOT_ERR_NOT_WORKTREE)
3542 error = wrap_not_worktree_error(error, "update",
3543 worktree_path);
3544 goto done;
3547 error = check_rebase_or_histedit_in_progress(worktree);
3548 if (error)
3549 goto done;
3551 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3552 NULL, pack_fds);
3553 if (error != NULL)
3554 goto done;
3556 error = apply_unveil(got_repo_get_path(repo), 0,
3557 got_worktree_get_root_path(worktree));
3558 if (error)
3559 goto done;
3561 error = check_merge_in_progress(worktree, repo);
3562 if (error)
3563 goto done;
3565 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3566 if (error)
3567 goto done;
3569 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3570 got_worktree_get_head_ref_name(worktree), 0);
3571 if (error != NULL)
3572 goto done;
3573 if (commit_id_str == NULL) {
3574 error = got_ref_resolve(&commit_id, repo, head_ref);
3575 if (error != NULL)
3576 goto done;
3577 error = got_object_id_str(&commit_id_str, commit_id);
3578 if (error != NULL)
3579 goto done;
3580 } else {
3581 struct got_reflist_head refs;
3582 char *keyword_idstr = NULL;
3584 TAILQ_INIT(&refs);
3586 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3587 NULL);
3588 if (error)
3589 goto done;
3591 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3592 repo, worktree);
3593 if (error != NULL)
3594 goto done;
3595 if (keyword_idstr != NULL) {
3596 free(commit_id_str);
3597 commit_id_str = keyword_idstr;
3600 error = got_repo_match_object_id(&commit_id, NULL,
3601 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3602 got_ref_list_free(&refs);
3603 free(commit_id_str);
3604 commit_id_str = NULL;
3605 if (error)
3606 goto done;
3607 error = got_object_id_str(&commit_id_str, commit_id);
3608 if (error)
3609 goto done;
3612 if (branch_name) {
3613 struct got_object_id *head_commit_id;
3614 TAILQ_FOREACH(pe, &paths, entry) {
3615 if (pe->path_len == 0)
3616 continue;
3617 error = got_error_msg(GOT_ERR_BAD_PATH,
3618 "switching between branches requires that "
3619 "the entire work tree gets updated");
3620 goto done;
3622 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3623 if (error)
3624 goto done;
3625 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3626 repo);
3627 free(head_commit_id);
3628 if (error != NULL)
3629 goto done;
3630 error = check_same_branch(commit_id, head_ref, repo);
3631 if (error)
3632 goto done;
3633 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3634 if (error)
3635 goto done;
3636 } else {
3637 error = check_linear_ancestry(commit_id,
3638 got_worktree_get_base_commit_id(worktree), 0, repo);
3639 if (error != NULL) {
3640 if (error->code == GOT_ERR_ANCESTRY)
3641 error = got_error(GOT_ERR_BRANCH_MOVED);
3642 goto done;
3644 error = check_same_branch(commit_id, head_ref, repo);
3645 if (error)
3646 goto done;
3649 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3650 commit_id) != 0) {
3651 error = got_worktree_set_base_commit_id(worktree, repo,
3652 commit_id);
3653 if (error)
3654 goto done;
3657 memset(&upa, 0, sizeof(upa));
3658 upa.verbosity = verbosity;
3659 error = got_worktree_checkout_files(worktree, &paths, repo,
3660 update_progress, &upa, check_cancelled, NULL);
3661 if (error != NULL)
3662 goto done;
3664 if (upa.did_something) {
3665 printf("Updated to %s: %s\n",
3666 got_worktree_get_head_ref_name(worktree), commit_id_str);
3667 } else
3668 printf("Already up-to-date\n");
3670 print_update_progress_stats(&upa);
3671 done:
3672 if (pack_fds) {
3673 const struct got_error *pack_err =
3674 got_repo_pack_fds_close(pack_fds);
3675 if (error == NULL)
3676 error = pack_err;
3678 if (repo) {
3679 const struct got_error *close_err = got_repo_close(repo);
3680 if (error == NULL)
3681 error = close_err;
3683 if (head_ref != NULL)
3684 got_ref_close(head_ref);
3685 free(worktree_path);
3686 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3687 free(commit_id);
3688 free(commit_id_str);
3689 return error;
3692 static const struct got_error *
3693 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3694 const char *path, int diff_context, int ignore_whitespace,
3695 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3696 struct got_repository *repo, FILE *outfile)
3698 const struct got_error *err = NULL;
3699 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3700 FILE *f1 = NULL, *f2 = NULL;
3701 int fd1 = -1, fd2 = -1;
3703 fd1 = got_opentempfd();
3704 if (fd1 == -1)
3705 return got_error_from_errno("got_opentempfd");
3706 fd2 = got_opentempfd();
3707 if (fd2 == -1) {
3708 err = got_error_from_errno("got_opentempfd");
3709 goto done;
3712 if (blob_id1) {
3713 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3714 fd1);
3715 if (err)
3716 goto done;
3719 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3720 if (err)
3721 goto done;
3723 f1 = got_opentemp();
3724 if (f1 == NULL) {
3725 err = got_error_from_errno("got_opentemp");
3726 goto done;
3728 f2 = got_opentemp();
3729 if (f2 == NULL) {
3730 err = got_error_from_errno("got_opentemp");
3731 goto done;
3734 while (path[0] == '/')
3735 path++;
3736 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3737 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3738 force_text_diff, dsa, outfile);
3739 done:
3740 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3741 err = got_error_from_errno("close");
3742 if (blob1)
3743 got_object_blob_close(blob1);
3744 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3745 err = got_error_from_errno("close");
3746 if (blob2)
3747 got_object_blob_close(blob2);
3748 if (f1 && fclose(f1) == EOF && err == NULL)
3749 err = got_error_from_errno("fclose");
3750 if (f2 && fclose(f2) == EOF && err == NULL)
3751 err = got_error_from_errno("fclose");
3752 return err;
3755 static const struct got_error *
3756 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3757 const char *path, int diff_context, int ignore_whitespace,
3758 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3759 struct got_repository *repo, FILE *outfile)
3761 const struct got_error *err = NULL;
3762 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3763 struct got_diff_blob_output_unidiff_arg arg;
3764 FILE *f1 = NULL, *f2 = NULL;
3765 int fd1 = -1, fd2 = -1;
3767 if (tree_id1) {
3768 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3769 if (err)
3770 goto done;
3771 fd1 = got_opentempfd();
3772 if (fd1 == -1) {
3773 err = got_error_from_errno("got_opentempfd");
3774 goto done;
3778 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3779 if (err)
3780 goto done;
3782 f1 = got_opentemp();
3783 if (f1 == NULL) {
3784 err = got_error_from_errno("got_opentemp");
3785 goto done;
3788 f2 = got_opentemp();
3789 if (f2 == NULL) {
3790 err = got_error_from_errno("got_opentemp");
3791 goto done;
3793 fd2 = got_opentempfd();
3794 if (fd2 == -1) {
3795 err = got_error_from_errno("got_opentempfd");
3796 goto done;
3798 arg.diff_context = diff_context;
3799 arg.ignore_whitespace = ignore_whitespace;
3800 arg.force_text_diff = force_text_diff;
3801 arg.diffstat = dsa;
3802 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3803 arg.outfile = outfile;
3804 arg.lines = NULL;
3805 arg.nlines = 0;
3806 while (path[0] == '/')
3807 path++;
3808 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3809 got_diff_blob_output_unidiff, &arg, 1);
3810 done:
3811 if (tree1)
3812 got_object_tree_close(tree1);
3813 if (tree2)
3814 got_object_tree_close(tree2);
3815 if (f1 && fclose(f1) == EOF && err == NULL)
3816 err = got_error_from_errno("fclose");
3817 if (f2 && fclose(f2) == EOF && err == NULL)
3818 err = got_error_from_errno("fclose");
3819 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3820 err = got_error_from_errno("close");
3821 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3822 err = got_error_from_errno("close");
3823 return err;
3826 static const struct got_error *
3827 get_changed_paths(struct got_pathlist_head *paths,
3828 struct got_commit_object *commit, struct got_repository *repo,
3829 struct got_diffstat_cb_arg *dsa)
3831 const struct got_error *err = NULL;
3832 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3833 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3834 struct got_object_qid *qid;
3835 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3836 FILE *f1 = NULL, *f2 = NULL;
3837 int fd1 = -1, fd2 = -1;
3839 if (dsa) {
3840 cb = got_diff_tree_compute_diffstat;
3842 f1 = got_opentemp();
3843 if (f1 == NULL) {
3844 err = got_error_from_errno("got_opentemp");
3845 goto done;
3847 f2 = got_opentemp();
3848 if (f2 == NULL) {
3849 err = got_error_from_errno("got_opentemp");
3850 goto done;
3852 fd1 = got_opentempfd();
3853 if (fd1 == -1) {
3854 err = got_error_from_errno("got_opentempfd");
3855 goto done;
3857 fd2 = got_opentempfd();
3858 if (fd2 == -1) {
3859 err = got_error_from_errno("got_opentempfd");
3860 goto done;
3864 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3865 if (qid != NULL) {
3866 struct got_commit_object *pcommit;
3867 err = got_object_open_as_commit(&pcommit, repo,
3868 &qid->id);
3869 if (err)
3870 return err;
3872 tree_id1 = got_object_id_dup(
3873 got_object_commit_get_tree_id(pcommit));
3874 if (tree_id1 == NULL) {
3875 got_object_commit_close(pcommit);
3876 return got_error_from_errno("got_object_id_dup");
3878 got_object_commit_close(pcommit);
3882 if (tree_id1) {
3883 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3884 if (err)
3885 goto done;
3888 tree_id2 = got_object_commit_get_tree_id(commit);
3889 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3890 if (err)
3891 goto done;
3893 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3894 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3895 done:
3896 if (tree1)
3897 got_object_tree_close(tree1);
3898 if (tree2)
3899 got_object_tree_close(tree2);
3900 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3901 err = got_error_from_errno("close");
3902 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3903 err = got_error_from_errno("close");
3904 if (f1 && fclose(f1) == EOF && err == NULL)
3905 err = got_error_from_errno("fclose");
3906 if (f2 && fclose(f2) == EOF && err == NULL)
3907 err = got_error_from_errno("fclose");
3908 free(tree_id1);
3909 return err;
3912 static const struct got_error *
3913 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3914 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3915 struct got_repository *repo, FILE *outfile)
3917 const struct got_error *err = NULL;
3918 struct got_commit_object *pcommit = NULL;
3919 char *id_str1 = NULL, *id_str2 = NULL;
3920 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3921 struct got_object_qid *qid;
3923 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3924 if (qid != NULL) {
3925 err = got_object_open_as_commit(&pcommit, repo,
3926 &qid->id);
3927 if (err)
3928 return err;
3929 err = got_object_id_str(&id_str1, &qid->id);
3930 if (err)
3931 goto done;
3934 err = got_object_id_str(&id_str2, id);
3935 if (err)
3936 goto done;
3938 if (path && path[0] != '\0') {
3939 int obj_type;
3940 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3941 if (err)
3942 goto done;
3943 if (pcommit) {
3944 err = got_object_id_by_path(&obj_id1, repo,
3945 pcommit, path);
3946 if (err) {
3947 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3948 free(obj_id2);
3949 goto done;
3953 err = got_object_get_type(&obj_type, repo, obj_id2);
3954 if (err) {
3955 free(obj_id2);
3956 goto done;
3958 fprintf(outfile,
3959 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3960 fprintf(outfile, "commit - %s\n",
3961 id_str1 ? id_str1 : "/dev/null");
3962 fprintf(outfile, "commit + %s\n", id_str2);
3963 switch (obj_type) {
3964 case GOT_OBJ_TYPE_BLOB:
3965 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3966 0, 0, dsa, repo, outfile);
3967 break;
3968 case GOT_OBJ_TYPE_TREE:
3969 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3970 0, 0, dsa, repo, outfile);
3971 break;
3972 default:
3973 err = got_error(GOT_ERR_OBJ_TYPE);
3974 break;
3976 free(obj_id1);
3977 free(obj_id2);
3978 } else {
3979 obj_id2 = got_object_commit_get_tree_id(commit);
3980 if (pcommit)
3981 obj_id1 = got_object_commit_get_tree_id(pcommit);
3982 fprintf(outfile,
3983 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3984 fprintf(outfile, "commit - %s\n",
3985 id_str1 ? id_str1 : "/dev/null");
3986 fprintf(outfile, "commit + %s\n", id_str2);
3987 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3988 dsa, repo, outfile);
3990 done:
3991 free(id_str1);
3992 free(id_str2);
3993 if (pcommit)
3994 got_object_commit_close(pcommit);
3995 return err;
3998 static char *
3999 get_datestr(time_t *time, char *datebuf)
4001 struct tm mytm, *tm;
4002 char *p, *s;
4004 tm = gmtime_r(time, &mytm);
4005 if (tm == NULL)
4006 return NULL;
4007 s = asctime_r(tm, datebuf);
4008 if (s == NULL)
4009 return NULL;
4010 p = strchr(s, '\n');
4011 if (p)
4012 *p = '\0';
4013 return s;
4016 static const struct got_error *
4017 match_commit(int *have_match, struct got_object_id *id,
4018 struct got_commit_object *commit, regex_t *regex)
4020 const struct got_error *err = NULL;
4021 regmatch_t regmatch;
4022 char *id_str = NULL, *logmsg = NULL;
4024 *have_match = 0;
4026 err = got_object_id_str(&id_str, id);
4027 if (err)
4028 return err;
4030 err = got_object_commit_get_logmsg(&logmsg, commit);
4031 if (err)
4032 goto done;
4034 if (regexec(regex, got_object_commit_get_author(commit), 1,
4035 &regmatch, 0) == 0 ||
4036 regexec(regex, got_object_commit_get_committer(commit), 1,
4037 &regmatch, 0) == 0 ||
4038 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4039 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4040 *have_match = 1;
4041 done:
4042 free(id_str);
4043 free(logmsg);
4044 return err;
4047 static void
4048 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4049 regex_t *regex)
4051 regmatch_t regmatch;
4052 struct got_pathlist_entry *pe;
4054 *have_match = 0;
4056 TAILQ_FOREACH(pe, changed_paths, entry) {
4057 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4058 *have_match = 1;
4059 break;
4064 static const struct got_error *
4065 match_patch(int *have_match, struct got_commit_object *commit,
4066 struct got_object_id *id, const char *path, int diff_context,
4067 struct got_repository *repo, regex_t *regex, FILE *f)
4069 const struct got_error *err = NULL;
4070 char *line = NULL;
4071 size_t linesize = 0;
4072 regmatch_t regmatch;
4074 *have_match = 0;
4076 err = got_opentemp_truncate(f);
4077 if (err)
4078 return err;
4080 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4081 if (err)
4082 goto done;
4084 if (fseeko(f, 0L, SEEK_SET) == -1) {
4085 err = got_error_from_errno("fseeko");
4086 goto done;
4089 while (getline(&line, &linesize, f) != -1) {
4090 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4091 *have_match = 1;
4092 break;
4095 done:
4096 free(line);
4097 return err;
4100 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4102 static const struct got_error*
4103 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4104 struct got_object_id *id, struct got_repository *repo,
4105 int local_only)
4107 static const struct got_error *err = NULL;
4108 struct got_reflist_entry *re;
4109 char *s;
4110 const char *name;
4112 *refs_str = NULL;
4114 TAILQ_FOREACH(re, refs, entry) {
4115 struct got_tag_object *tag = NULL;
4116 struct got_object_id *ref_id;
4117 int cmp;
4119 name = got_ref_get_name(re->ref);
4120 if (strcmp(name, GOT_REF_HEAD) == 0)
4121 continue;
4122 if (strncmp(name, "refs/", 5) == 0)
4123 name += 5;
4124 if (strncmp(name, "got/", 4) == 0)
4125 continue;
4126 if (strncmp(name, "heads/", 6) == 0)
4127 name += 6;
4128 if (strncmp(name, "remotes/", 8) == 0) {
4129 if (local_only)
4130 continue;
4131 name += 8;
4132 s = strstr(name, "/" GOT_REF_HEAD);
4133 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4134 continue;
4136 err = got_ref_resolve(&ref_id, repo, re->ref);
4137 if (err)
4138 break;
4139 if (strncmp(name, "tags/", 5) == 0) {
4140 err = got_object_open_as_tag(&tag, repo, ref_id);
4141 if (err) {
4142 if (err->code != GOT_ERR_OBJ_TYPE) {
4143 free(ref_id);
4144 break;
4146 /* Ref points at something other than a tag. */
4147 err = NULL;
4148 tag = NULL;
4151 cmp = got_object_id_cmp(tag ?
4152 got_object_tag_get_object_id(tag) : ref_id, id);
4153 free(ref_id);
4154 if (tag)
4155 got_object_tag_close(tag);
4156 if (cmp != 0)
4157 continue;
4158 s = *refs_str;
4159 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4160 s ? ", " : "", name) == -1) {
4161 err = got_error_from_errno("asprintf");
4162 free(s);
4163 *refs_str = NULL;
4164 break;
4166 free(s);
4169 return err;
4172 static const struct got_error *
4173 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4174 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4176 const struct got_error *err = NULL;
4177 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4178 char *comma, *s, *nl;
4179 struct got_reflist_head *refs;
4180 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4181 struct tm tm;
4182 time_t committer_time;
4184 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4185 if (refs) {
4186 err = build_refs_str(&ref_str, refs, id, repo, 1);
4187 if (err)
4188 return err;
4190 /* Display the first matching ref only. */
4191 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4192 *comma = '\0';
4195 if (ref_str == NULL) {
4196 err = got_object_id_str(&id_str, id);
4197 if (err)
4198 return err;
4201 committer_time = got_object_commit_get_committer_time(commit);
4202 if (gmtime_r(&committer_time, &tm) == NULL) {
4203 err = got_error_from_errno("gmtime_r");
4204 goto done;
4206 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4207 err = got_error(GOT_ERR_NO_SPACE);
4208 goto done;
4211 err = got_object_commit_get_logmsg(&logmsg0, commit);
4212 if (err)
4213 goto done;
4215 s = logmsg0;
4216 while (isspace((unsigned char)s[0]))
4217 s++;
4219 nl = strchr(s, '\n');
4220 if (nl) {
4221 *nl = '\0';
4224 if (ref_str)
4225 printf("%s%-7s %s\n", datebuf, ref_str, s);
4226 else
4227 printf("%s%.7s %s\n", datebuf, id_str, s);
4229 if (fflush(stdout) != 0 && err == NULL)
4230 err = got_error_from_errno("fflush");
4231 done:
4232 free(id_str);
4233 free(ref_str);
4234 free(logmsg0);
4235 return err;
4238 static const struct got_error *
4239 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4241 struct got_pathlist_entry *pe;
4243 if (header != NULL)
4244 printf("%s\n", header);
4246 TAILQ_FOREACH(pe, dsa->paths, entry) {
4247 struct got_diff_changed_path *cp = pe->data;
4248 int pad = dsa->max_path_len - pe->path_len + 1;
4250 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4251 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4253 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4254 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4255 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4257 if (fflush(stdout) != 0)
4258 return got_error_from_errno("fflush");
4260 return NULL;
4263 static const struct got_error *
4264 printfile(FILE *f)
4266 char buf[8192];
4267 size_t r;
4269 if (fseeko(f, 0L, SEEK_SET) == -1)
4270 return got_error_from_errno("fseek");
4272 for (;;) {
4273 r = fread(buf, 1, sizeof(buf), f);
4274 if (r == 0) {
4275 if (ferror(f))
4276 return got_error_from_errno("fread");
4277 if (feof(f))
4278 break;
4280 if (fwrite(buf, 1, r, stdout) != r)
4281 return got_ferror(stdout, GOT_ERR_IO);
4284 return NULL;
4287 static const struct got_error *
4288 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4289 struct got_repository *repo, const char *path,
4290 struct got_pathlist_head *changed_paths,
4291 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4292 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4293 const char *prefix)
4295 const struct got_error *err = NULL;
4296 FILE *f = NULL;
4297 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4298 char datebuf[26];
4299 time_t committer_time;
4300 const char *author, *committer;
4301 char *refs_str = NULL;
4303 err = got_object_id_str(&id_str, id);
4304 if (err)
4305 return err;
4307 if (custom_refs_str == NULL) {
4308 struct got_reflist_head *refs;
4309 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4310 if (refs) {
4311 err = build_refs_str(&refs_str, refs, id, repo, 0);
4312 if (err)
4313 goto done;
4317 printf(GOT_COMMIT_SEP_STR);
4318 if (custom_refs_str)
4319 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4320 custom_refs_str);
4321 else
4322 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4323 refs_str ? " (" : "", refs_str ? refs_str : "",
4324 refs_str ? ")" : "");
4325 free(id_str);
4326 id_str = NULL;
4327 free(refs_str);
4328 refs_str = NULL;
4329 printf("from: %s\n", got_object_commit_get_author(commit));
4330 author = got_object_commit_get_author(commit);
4331 committer = got_object_commit_get_committer(commit);
4332 if (strcmp(author, committer) != 0)
4333 printf("via: %s\n", committer);
4334 committer_time = got_object_commit_get_committer_time(commit);
4335 datestr = get_datestr(&committer_time, datebuf);
4336 if (datestr)
4337 printf("date: %s UTC\n", datestr);
4338 if (got_object_commit_get_nparents(commit) > 1) {
4339 const struct got_object_id_queue *parent_ids;
4340 struct got_object_qid *qid;
4341 int n = 1;
4342 parent_ids = got_object_commit_get_parent_ids(commit);
4343 STAILQ_FOREACH(qid, parent_ids, entry) {
4344 err = got_object_id_str(&id_str, &qid->id);
4345 if (err)
4346 goto done;
4347 printf("parent %d: %s\n", n++, id_str);
4348 free(id_str);
4349 id_str = NULL;
4353 err = got_object_commit_get_logmsg(&logmsg0, commit);
4354 if (err)
4355 goto done;
4357 logmsg = logmsg0;
4358 do {
4359 line = strsep(&logmsg, "\n");
4360 if (line)
4361 printf(" %s\n", line);
4362 } while (line);
4363 free(logmsg0);
4365 if (changed_paths && diffstat == NULL) {
4366 struct got_pathlist_entry *pe;
4368 TAILQ_FOREACH(pe, changed_paths, entry) {
4369 struct got_diff_changed_path *cp = pe->data;
4371 printf(" %c %s\n", cp->status, pe->path);
4373 printf("\n");
4375 if (show_patch) {
4376 if (diffstat) {
4377 f = got_opentemp();
4378 if (f == NULL) {
4379 err = got_error_from_errno("got_opentemp");
4380 goto done;
4384 err = print_patch(commit, id, path, diff_context, diffstat,
4385 repo, diffstat == NULL ? stdout : f);
4386 if (err)
4387 goto done;
4389 if (diffstat) {
4390 err = print_diffstat(diffstat, NULL);
4391 if (err)
4392 goto done;
4393 if (show_patch) {
4394 err = printfile(f);
4395 if (err)
4396 goto done;
4399 if (show_patch)
4400 printf("\n");
4402 if (fflush(stdout) != 0 && err == NULL)
4403 err = got_error_from_errno("fflush");
4404 done:
4405 if (f && fclose(f) == EOF && err == NULL)
4406 err = got_error_from_errno("fclose");
4407 free(id_str);
4408 free(refs_str);
4409 return err;
4412 static const struct got_error *
4413 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4414 struct got_repository *repo, const char *path, int show_changed_paths,
4415 int show_diffstat, int show_patch, const char *search_pattern,
4416 int diff_context, int limit, int log_branches, int reverse_display_order,
4417 struct got_reflist_object_id_map *refs_idmap, int one_line,
4418 FILE *tmpfile)
4420 const struct got_error *err;
4421 struct got_commit_graph *graph;
4422 regex_t regex;
4423 int have_match;
4424 struct got_object_id_queue reversed_commits;
4425 struct got_object_qid *qid;
4426 struct got_commit_object *commit;
4427 struct got_pathlist_head changed_paths;
4429 STAILQ_INIT(&reversed_commits);
4430 TAILQ_INIT(&changed_paths);
4432 if (search_pattern && regcomp(&regex, search_pattern,
4433 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4434 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4436 err = got_commit_graph_open(&graph, path, !log_branches);
4437 if (err)
4438 return err;
4439 err = got_commit_graph_iter_start(graph, root_id, repo,
4440 check_cancelled, NULL);
4441 if (err)
4442 goto done;
4443 for (;;) {
4444 struct got_object_id id;
4445 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4446 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4448 if (sigint_received || sigpipe_received)
4449 break;
4451 err = got_commit_graph_iter_next(&id, graph, repo,
4452 check_cancelled, NULL);
4453 if (err) {
4454 if (err->code == GOT_ERR_ITER_COMPLETED)
4455 err = NULL;
4456 break;
4459 err = got_object_open_as_commit(&commit, repo, &id);
4460 if (err)
4461 break;
4463 if ((show_changed_paths || (show_diffstat && !show_patch))
4464 && !reverse_display_order) {
4465 err = get_changed_paths(&changed_paths, commit, repo,
4466 show_diffstat ? &dsa : NULL);
4467 if (err)
4468 break;
4471 if (search_pattern) {
4472 err = match_commit(&have_match, &id, commit, &regex);
4473 if (err) {
4474 got_object_commit_close(commit);
4475 break;
4477 if (have_match == 0 && show_changed_paths)
4478 match_changed_paths(&have_match,
4479 &changed_paths, &regex);
4480 if (have_match == 0 && show_patch) {
4481 err = match_patch(&have_match, commit, &id,
4482 path, diff_context, repo, &regex, tmpfile);
4483 if (err)
4484 break;
4486 if (have_match == 0) {
4487 got_object_commit_close(commit);
4488 got_pathlist_free(&changed_paths,
4489 GOT_PATHLIST_FREE_ALL);
4490 continue;
4494 if (reverse_display_order) {
4495 err = got_object_qid_alloc(&qid, &id);
4496 if (err)
4497 break;
4498 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4499 got_object_commit_close(commit);
4500 } else {
4501 if (one_line)
4502 err = print_commit_oneline(commit, &id,
4503 repo, refs_idmap);
4504 else
4505 err = print_commit(commit, &id, repo, path,
4506 (show_changed_paths || show_diffstat) ?
4507 &changed_paths : NULL,
4508 show_diffstat ? &dsa : NULL, show_patch,
4509 diff_context, refs_idmap, NULL, NULL);
4510 got_object_commit_close(commit);
4511 if (err)
4512 break;
4514 if ((limit && --limit == 0) ||
4515 (end_id && got_object_id_cmp(&id, end_id) == 0))
4516 break;
4518 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4520 if (reverse_display_order) {
4521 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4522 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4523 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4525 err = got_object_open_as_commit(&commit, repo,
4526 &qid->id);
4527 if (err)
4528 break;
4529 if (show_changed_paths ||
4530 (show_diffstat && !show_patch)) {
4531 err = get_changed_paths(&changed_paths, commit,
4532 repo, show_diffstat ? &dsa : NULL);
4533 if (err)
4534 break;
4536 if (one_line)
4537 err = print_commit_oneline(commit, &qid->id,
4538 repo, refs_idmap);
4539 else
4540 err = print_commit(commit, &qid->id, repo, path,
4541 (show_changed_paths || show_diffstat) ?
4542 &changed_paths : NULL,
4543 show_diffstat ? &dsa : NULL, show_patch,
4544 diff_context, refs_idmap, NULL, NULL);
4545 got_object_commit_close(commit);
4546 if (err)
4547 break;
4548 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4551 done:
4552 while (!STAILQ_EMPTY(&reversed_commits)) {
4553 qid = STAILQ_FIRST(&reversed_commits);
4554 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4555 got_object_qid_free(qid);
4557 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4558 if (search_pattern)
4559 regfree(&regex);
4560 got_commit_graph_close(graph);
4561 return err;
4564 __dead static void
4565 usage_log(void)
4567 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4568 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4569 "[path]\n", getprogname());
4570 exit(1);
4573 static int
4574 get_default_log_limit(void)
4576 const char *got_default_log_limit;
4577 long long n;
4578 const char *errstr;
4580 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4581 if (got_default_log_limit == NULL)
4582 return 0;
4583 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4584 if (errstr != NULL)
4585 return 0;
4586 return n;
4589 static const struct got_error *
4590 cmd_log(int argc, char *argv[])
4592 const struct got_error *error;
4593 struct got_repository *repo = NULL;
4594 struct got_worktree *worktree = NULL;
4595 struct got_object_id *start_id = NULL, *end_id = NULL;
4596 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4597 char *keyword_idstr = NULL;
4598 const char *start_commit = NULL, *end_commit = NULL;
4599 const char *search_pattern = NULL;
4600 int diff_context = -1, ch;
4601 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4602 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4603 const char *errstr;
4604 struct got_reflist_head refs;
4605 struct got_reflist_object_id_map *refs_idmap = NULL;
4606 FILE *tmpfile = NULL;
4607 int *pack_fds = NULL;
4609 TAILQ_INIT(&refs);
4611 #ifndef PROFILE
4612 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4613 NULL)
4614 == -1)
4615 err(1, "pledge");
4616 #endif
4618 limit = get_default_log_limit();
4620 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4621 switch (ch) {
4622 case 'b':
4623 log_branches = 1;
4624 break;
4625 case 'C':
4626 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4627 &errstr);
4628 if (errstr != NULL)
4629 errx(1, "number of context lines is %s: %s",
4630 errstr, optarg);
4631 break;
4632 case 'c':
4633 start_commit = optarg;
4634 break;
4635 case 'd':
4636 show_diffstat = 1;
4637 break;
4638 case 'l':
4639 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4640 if (errstr != NULL)
4641 errx(1, "number of commits is %s: %s",
4642 errstr, optarg);
4643 break;
4644 case 'P':
4645 show_changed_paths = 1;
4646 break;
4647 case 'p':
4648 show_patch = 1;
4649 break;
4650 case 'R':
4651 reverse_display_order = 1;
4652 break;
4653 case 'r':
4654 repo_path = realpath(optarg, NULL);
4655 if (repo_path == NULL)
4656 return got_error_from_errno2("realpath",
4657 optarg);
4658 got_path_strip_trailing_slashes(repo_path);
4659 break;
4660 case 'S':
4661 search_pattern = optarg;
4662 break;
4663 case 's':
4664 one_line = 1;
4665 break;
4666 case 'x':
4667 end_commit = optarg;
4668 break;
4669 default:
4670 usage_log();
4671 /* NOTREACHED */
4675 argc -= optind;
4676 argv += optind;
4678 if (diff_context == -1)
4679 diff_context = 3;
4680 else if (!show_patch)
4681 errx(1, "-C requires -p");
4683 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4684 errx(1, "cannot use -s with -d, -p or -P");
4686 cwd = getcwd(NULL, 0);
4687 if (cwd == NULL) {
4688 error = got_error_from_errno("getcwd");
4689 goto done;
4692 error = got_repo_pack_fds_open(&pack_fds);
4693 if (error != NULL)
4694 goto done;
4696 if (repo_path == NULL) {
4697 error = got_worktree_open(&worktree, cwd,
4698 GOT_WORKTREE_GOT_DIR);
4699 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4700 goto done;
4701 error = NULL;
4704 if (argc == 1) {
4705 if (worktree) {
4706 error = got_worktree_resolve_path(&path, worktree,
4707 argv[0]);
4708 if (error)
4709 goto done;
4710 } else {
4711 path = strdup(argv[0]);
4712 if (path == NULL) {
4713 error = got_error_from_errno("strdup");
4714 goto done;
4717 } else if (argc != 0)
4718 usage_log();
4720 if (repo_path == NULL) {
4721 repo_path = worktree ?
4722 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4724 if (repo_path == NULL) {
4725 error = got_error_from_errno("strdup");
4726 goto done;
4729 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4730 if (error != NULL)
4731 goto done;
4733 error = apply_unveil(got_repo_get_path(repo), 1,
4734 worktree ? got_worktree_get_root_path(worktree) : NULL);
4735 if (error)
4736 goto done;
4738 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4739 if (error)
4740 goto done;
4742 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4743 if (error)
4744 goto done;
4746 if (start_commit == NULL) {
4747 struct got_reference *head_ref;
4748 struct got_commit_object *commit = NULL;
4749 error = got_ref_open(&head_ref, repo,
4750 worktree ? got_worktree_get_head_ref_name(worktree)
4751 : GOT_REF_HEAD, 0);
4752 if (error != NULL)
4753 goto done;
4754 error = got_ref_resolve(&start_id, repo, head_ref);
4755 got_ref_close(head_ref);
4756 if (error != NULL)
4757 goto done;
4758 error = got_object_open_as_commit(&commit, repo,
4759 start_id);
4760 if (error != NULL)
4761 goto done;
4762 got_object_commit_close(commit);
4763 } else {
4764 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4765 repo, worktree);
4766 if (error != NULL)
4767 goto done;
4768 if (keyword_idstr != NULL)
4769 start_commit = keyword_idstr;
4771 error = got_repo_match_object_id(&start_id, NULL,
4772 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4773 if (error != NULL)
4774 goto done;
4776 if (end_commit != NULL) {
4777 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4778 repo, worktree);
4779 if (error != NULL)
4780 goto done;
4781 if (keyword_idstr != NULL)
4782 end_commit = keyword_idstr;
4784 error = got_repo_match_object_id(&end_id, NULL,
4785 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4786 if (error != NULL)
4787 goto done;
4790 if (worktree) {
4792 * If a path was specified on the command line it was resolved
4793 * to a path in the work tree above. Prepend the work tree's
4794 * path prefix to obtain the corresponding in-repository path.
4796 if (path) {
4797 const char *prefix;
4798 prefix = got_worktree_get_path_prefix(worktree);
4799 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4800 (path[0] != '\0') ? "/" : "", path) == -1) {
4801 error = got_error_from_errno("asprintf");
4802 goto done;
4805 } else
4806 error = got_repo_map_path(&in_repo_path, repo,
4807 path ? path : "");
4808 if (error != NULL)
4809 goto done;
4810 if (in_repo_path) {
4811 free(path);
4812 path = in_repo_path;
4815 if (worktree) {
4816 /* Release work tree lock. */
4817 got_worktree_close(worktree);
4818 worktree = NULL;
4821 if (search_pattern && show_patch) {
4822 tmpfile = got_opentemp();
4823 if (tmpfile == NULL) {
4824 error = got_error_from_errno("got_opentemp");
4825 goto done;
4829 error = print_commits(start_id, end_id, repo, path ? path : "",
4830 show_changed_paths, show_diffstat, show_patch, search_pattern,
4831 diff_context, limit, log_branches, reverse_display_order,
4832 refs_idmap, one_line, tmpfile);
4833 done:
4834 free(path);
4835 free(repo_path);
4836 free(cwd);
4837 free(start_id);
4838 free(end_id);
4839 free(keyword_idstr);
4840 if (worktree)
4841 got_worktree_close(worktree);
4842 if (repo) {
4843 const struct got_error *close_err = got_repo_close(repo);
4844 if (error == NULL)
4845 error = close_err;
4847 if (pack_fds) {
4848 const struct got_error *pack_err =
4849 got_repo_pack_fds_close(pack_fds);
4850 if (error == NULL)
4851 error = pack_err;
4853 if (refs_idmap)
4854 got_reflist_object_id_map_free(refs_idmap);
4855 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4856 error = got_error_from_errno("fclose");
4857 got_ref_list_free(&refs);
4858 return error;
4861 __dead static void
4862 usage_diff(void)
4864 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4865 "[-r repository-path] [object1 object2 | path ...]\n",
4866 getprogname());
4867 exit(1);
4870 struct print_diff_arg {
4871 struct got_repository *repo;
4872 struct got_worktree *worktree;
4873 struct got_diffstat_cb_arg *diffstat;
4874 int diff_context;
4875 const char *id_str;
4876 int header_shown;
4877 int diff_staged;
4878 enum got_diff_algorithm diff_algo;
4879 int ignore_whitespace;
4880 int force_text_diff;
4881 FILE *f1;
4882 FILE *f2;
4883 FILE *outfile;
4887 * Create a file which contains the target path of a symlink so we can feed
4888 * it as content to the diff engine.
4890 static const struct got_error *
4891 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4892 const char *abspath)
4894 const struct got_error *err = NULL;
4895 char target_path[PATH_MAX];
4896 ssize_t target_len, outlen;
4898 *fd = -1;
4900 if (dirfd != -1) {
4901 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4902 if (target_len == -1)
4903 return got_error_from_errno2("readlinkat", abspath);
4904 } else {
4905 target_len = readlink(abspath, target_path, PATH_MAX);
4906 if (target_len == -1)
4907 return got_error_from_errno2("readlink", abspath);
4910 *fd = got_opentempfd();
4911 if (*fd == -1)
4912 return got_error_from_errno("got_opentempfd");
4914 outlen = write(*fd, target_path, target_len);
4915 if (outlen == -1) {
4916 err = got_error_from_errno("got_opentempfd");
4917 goto done;
4920 if (lseek(*fd, 0, SEEK_SET) == -1) {
4921 err = got_error_from_errno2("lseek", abspath);
4922 goto done;
4924 done:
4925 if (err) {
4926 close(*fd);
4927 *fd = -1;
4929 return err;
4932 static const struct got_error *
4933 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4934 const char *path, struct got_object_id *blob_id,
4935 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4936 int dirfd, const char *de_name)
4938 struct print_diff_arg *a = arg;
4939 const struct got_error *err = NULL;
4940 struct got_blob_object *blob1 = NULL;
4941 int fd = -1, fd1 = -1, fd2 = -1;
4942 FILE *f2 = NULL;
4943 char *abspath = NULL, *label1 = NULL;
4944 struct stat sb;
4945 off_t size1 = 0;
4946 int f2_exists = 0;
4948 memset(&sb, 0, sizeof(sb));
4950 if (a->diff_staged) {
4951 if (staged_status != GOT_STATUS_MODIFY &&
4952 staged_status != GOT_STATUS_ADD &&
4953 staged_status != GOT_STATUS_DELETE)
4954 return NULL;
4955 } else {
4956 if (staged_status == GOT_STATUS_DELETE)
4957 return NULL;
4958 if (status == GOT_STATUS_NONEXISTENT)
4959 return got_error_set_errno(ENOENT, path);
4960 if (status != GOT_STATUS_MODIFY &&
4961 status != GOT_STATUS_ADD &&
4962 status != GOT_STATUS_DELETE &&
4963 status != GOT_STATUS_CONFLICT)
4964 return NULL;
4967 err = got_opentemp_truncate(a->f1);
4968 if (err)
4969 return got_error_from_errno("got_opentemp_truncate");
4970 err = got_opentemp_truncate(a->f2);
4971 if (err)
4972 return got_error_from_errno("got_opentemp_truncate");
4974 if (!a->header_shown) {
4975 if (fprintf(a->outfile, "diff %s%s\n",
4976 a->diff_staged ? "-s " : "",
4977 got_worktree_get_root_path(a->worktree)) < 0) {
4978 err = got_error_from_errno("fprintf");
4979 goto done;
4981 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4982 err = got_error_from_errno("fprintf");
4983 goto done;
4985 if (fprintf(a->outfile, "path + %s%s\n",
4986 got_worktree_get_root_path(a->worktree),
4987 a->diff_staged ? " (staged changes)" : "") < 0) {
4988 err = got_error_from_errno("fprintf");
4989 goto done;
4991 a->header_shown = 1;
4994 if (a->diff_staged) {
4995 const char *label1 = NULL, *label2 = NULL;
4996 switch (staged_status) {
4997 case GOT_STATUS_MODIFY:
4998 label1 = path;
4999 label2 = path;
5000 break;
5001 case GOT_STATUS_ADD:
5002 label2 = path;
5003 break;
5004 case GOT_STATUS_DELETE:
5005 label1 = path;
5006 break;
5007 default:
5008 return got_error(GOT_ERR_FILE_STATUS);
5010 fd1 = got_opentempfd();
5011 if (fd1 == -1) {
5012 err = got_error_from_errno("got_opentempfd");
5013 goto done;
5015 fd2 = got_opentempfd();
5016 if (fd2 == -1) {
5017 err = got_error_from_errno("got_opentempfd");
5018 goto done;
5020 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5021 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5022 a->diff_algo, a->diff_context, a->ignore_whitespace,
5023 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5024 goto done;
5027 fd1 = got_opentempfd();
5028 if (fd1 == -1) {
5029 err = got_error_from_errno("got_opentempfd");
5030 goto done;
5033 if (staged_status == GOT_STATUS_ADD ||
5034 staged_status == GOT_STATUS_MODIFY) {
5035 char *id_str;
5036 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5037 8192, fd1);
5038 if (err)
5039 goto done;
5040 err = got_object_id_str(&id_str, staged_blob_id);
5041 if (err)
5042 goto done;
5043 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5044 err = got_error_from_errno("asprintf");
5045 free(id_str);
5046 goto done;
5048 free(id_str);
5049 } else if (status != GOT_STATUS_ADD) {
5050 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5051 fd1);
5052 if (err)
5053 goto done;
5056 if (status != GOT_STATUS_DELETE) {
5057 if (asprintf(&abspath, "%s/%s",
5058 got_worktree_get_root_path(a->worktree), path) == -1) {
5059 err = got_error_from_errno("asprintf");
5060 goto done;
5063 if (dirfd != -1) {
5064 fd = openat(dirfd, de_name,
5065 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5066 if (fd == -1) {
5067 if (!got_err_open_nofollow_on_symlink()) {
5068 err = got_error_from_errno2("openat",
5069 abspath);
5070 goto done;
5072 err = get_symlink_target_file(&fd, dirfd,
5073 de_name, abspath);
5074 if (err)
5075 goto done;
5077 } else {
5078 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5079 if (fd == -1) {
5080 if (!got_err_open_nofollow_on_symlink()) {
5081 err = got_error_from_errno2("open",
5082 abspath);
5083 goto done;
5085 err = get_symlink_target_file(&fd, dirfd,
5086 de_name, abspath);
5087 if (err)
5088 goto done;
5091 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5092 err = got_error_from_errno2("fstatat", abspath);
5093 goto done;
5095 f2 = fdopen(fd, "r");
5096 if (f2 == NULL) {
5097 err = got_error_from_errno2("fdopen", abspath);
5098 goto done;
5100 fd = -1;
5101 f2_exists = 1;
5104 if (blob1) {
5105 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5106 a->f1, blob1);
5107 if (err)
5108 goto done;
5111 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5112 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5113 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5114 done:
5115 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5116 err = got_error_from_errno("close");
5117 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5118 err = got_error_from_errno("close");
5119 if (blob1)
5120 got_object_blob_close(blob1);
5121 if (fd != -1 && close(fd) == -1 && err == NULL)
5122 err = got_error_from_errno("close");
5123 if (f2 && fclose(f2) == EOF && err == NULL)
5124 err = got_error_from_errno("fclose");
5125 free(abspath);
5126 return err;
5129 static const struct got_error *
5130 cmd_diff(int argc, char *argv[])
5132 const struct got_error *error;
5133 struct got_repository *repo = NULL;
5134 struct got_worktree *worktree = NULL;
5135 char *cwd = NULL, *repo_path = NULL;
5136 const char *commit_args[2] = { NULL, NULL };
5137 int ncommit_args = 0;
5138 struct got_object_id *ids[2] = { NULL, NULL };
5139 char *labels[2] = { NULL, NULL };
5140 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5141 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5142 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5143 const char *errstr;
5144 struct got_reflist_head refs;
5145 struct got_pathlist_head diffstat_paths, paths;
5146 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5147 int fd1 = -1, fd2 = -1;
5148 int *pack_fds = NULL;
5149 struct got_diffstat_cb_arg dsa;
5151 memset(&dsa, 0, sizeof(dsa));
5153 TAILQ_INIT(&refs);
5154 TAILQ_INIT(&paths);
5155 TAILQ_INIT(&diffstat_paths);
5157 #ifndef PROFILE
5158 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5159 NULL) == -1)
5160 err(1, "pledge");
5161 #endif
5163 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5164 switch (ch) {
5165 case 'a':
5166 force_text_diff = 1;
5167 break;
5168 case 'C':
5169 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5170 &errstr);
5171 if (errstr != NULL)
5172 errx(1, "number of context lines is %s: %s",
5173 errstr, optarg);
5174 break;
5175 case 'c':
5176 if (ncommit_args >= 2)
5177 errx(1, "too many -c options used");
5178 commit_args[ncommit_args++] = optarg;
5179 break;
5180 case 'd':
5181 show_diffstat = 1;
5182 break;
5183 case 'P':
5184 force_path = 1;
5185 break;
5186 case 'r':
5187 repo_path = realpath(optarg, NULL);
5188 if (repo_path == NULL)
5189 return got_error_from_errno2("realpath",
5190 optarg);
5191 got_path_strip_trailing_slashes(repo_path);
5192 rflag = 1;
5193 break;
5194 case 's':
5195 diff_staged = 1;
5196 break;
5197 case 'w':
5198 ignore_whitespace = 1;
5199 break;
5200 default:
5201 usage_diff();
5202 /* NOTREACHED */
5206 argc -= optind;
5207 argv += optind;
5209 cwd = getcwd(NULL, 0);
5210 if (cwd == NULL) {
5211 error = got_error_from_errno("getcwd");
5212 goto done;
5215 error = got_repo_pack_fds_open(&pack_fds);
5216 if (error != NULL)
5217 goto done;
5219 if (repo_path == NULL) {
5220 error = got_worktree_open(&worktree, cwd,
5221 GOT_WORKTREE_GOT_DIR);
5222 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5223 goto done;
5224 else
5225 error = NULL;
5226 if (worktree) {
5227 repo_path =
5228 strdup(got_worktree_get_repo_path(worktree));
5229 if (repo_path == NULL) {
5230 error = got_error_from_errno("strdup");
5231 goto done;
5233 } else {
5234 repo_path = strdup(cwd);
5235 if (repo_path == NULL) {
5236 error = got_error_from_errno("strdup");
5237 goto done;
5242 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5243 free(repo_path);
5244 if (error != NULL)
5245 goto done;
5247 if (show_diffstat) {
5248 dsa.paths = &diffstat_paths;
5249 dsa.force_text = force_text_diff;
5250 dsa.ignore_ws = ignore_whitespace;
5251 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5254 if (rflag || worktree == NULL || ncommit_args > 0) {
5255 if (force_path) {
5256 error = got_error_msg(GOT_ERR_NOT_IMPL,
5257 "-P option can only be used when diffing "
5258 "a work tree");
5259 goto done;
5261 if (diff_staged) {
5262 error = got_error_msg(GOT_ERR_NOT_IMPL,
5263 "-s option can only be used when diffing "
5264 "a work tree");
5265 goto done;
5269 error = apply_unveil(got_repo_get_path(repo), 1,
5270 worktree ? got_worktree_get_root_path(worktree) : NULL);
5271 if (error)
5272 goto done;
5274 if ((!force_path && argc == 2) || ncommit_args > 0) {
5275 int obj_type = (ncommit_args > 0 ?
5276 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5277 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5278 NULL);
5279 if (error)
5280 goto done;
5281 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5282 const char *arg;
5283 char *keyword_idstr = NULL;
5285 if (ncommit_args > 0)
5286 arg = commit_args[i];
5287 else
5288 arg = argv[i];
5290 error = got_keyword_to_idstr(&keyword_idstr, arg,
5291 repo, worktree);
5292 if (error != NULL)
5293 goto done;
5294 if (keyword_idstr != NULL)
5295 arg = keyword_idstr;
5297 error = got_repo_match_object_id(&ids[i], &labels[i],
5298 arg, obj_type, &refs, repo);
5299 free(keyword_idstr);
5300 if (error) {
5301 if (error->code != GOT_ERR_NOT_REF &&
5302 error->code != GOT_ERR_NO_OBJ)
5303 goto done;
5304 if (ncommit_args > 0)
5305 goto done;
5306 error = NULL;
5307 break;
5312 f1 = got_opentemp();
5313 if (f1 == NULL) {
5314 error = got_error_from_errno("got_opentemp");
5315 goto done;
5318 f2 = got_opentemp();
5319 if (f2 == NULL) {
5320 error = got_error_from_errno("got_opentemp");
5321 goto done;
5324 outfile = got_opentemp();
5325 if (outfile == NULL) {
5326 error = got_error_from_errno("got_opentemp");
5327 goto done;
5330 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5331 struct print_diff_arg arg;
5332 char *id_str;
5334 if (worktree == NULL) {
5335 if (argc == 2 && ids[0] == NULL) {
5336 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5337 goto done;
5338 } else if (argc == 2 && ids[1] == NULL) {
5339 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5340 goto done;
5341 } else if (argc > 0) {
5342 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5343 "%s", "specified paths cannot be resolved");
5344 goto done;
5345 } else {
5346 error = got_error(GOT_ERR_NOT_WORKTREE);
5347 goto done;
5351 error = get_worktree_paths_from_argv(&paths, argc, argv,
5352 worktree);
5353 if (error)
5354 goto done;
5356 error = got_object_id_str(&id_str,
5357 got_worktree_get_base_commit_id(worktree));
5358 if (error)
5359 goto done;
5360 arg.repo = repo;
5361 arg.worktree = worktree;
5362 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5363 arg.diff_context = diff_context;
5364 arg.id_str = id_str;
5365 arg.header_shown = 0;
5366 arg.diff_staged = diff_staged;
5367 arg.ignore_whitespace = ignore_whitespace;
5368 arg.force_text_diff = force_text_diff;
5369 arg.diffstat = show_diffstat ? &dsa : NULL;
5370 arg.f1 = f1;
5371 arg.f2 = f2;
5372 arg.outfile = outfile;
5374 error = got_worktree_status(worktree, &paths, repo, 0,
5375 print_diff, &arg, check_cancelled, NULL);
5376 free(id_str);
5377 if (error)
5378 goto done;
5380 if (show_diffstat && dsa.nfiles > 0) {
5381 char *header;
5383 if (asprintf(&header, "diffstat %s%s",
5384 diff_staged ? "-s " : "",
5385 got_worktree_get_root_path(worktree)) == -1) {
5386 error = got_error_from_errno("asprintf");
5387 goto done;
5390 error = print_diffstat(&dsa, header);
5391 free(header);
5392 if (error)
5393 goto done;
5396 error = printfile(outfile);
5397 goto done;
5400 if (ncommit_args == 1) {
5401 struct got_commit_object *commit;
5402 error = got_object_open_as_commit(&commit, repo, ids[0]);
5403 if (error)
5404 goto done;
5406 labels[1] = labels[0];
5407 ids[1] = ids[0];
5408 if (got_object_commit_get_nparents(commit) > 0) {
5409 const struct got_object_id_queue *pids;
5410 struct got_object_qid *pid;
5411 pids = got_object_commit_get_parent_ids(commit);
5412 pid = STAILQ_FIRST(pids);
5413 ids[0] = got_object_id_dup(&pid->id);
5414 if (ids[0] == NULL) {
5415 error = got_error_from_errno(
5416 "got_object_id_dup");
5417 got_object_commit_close(commit);
5418 goto done;
5420 error = got_object_id_str(&labels[0], ids[0]);
5421 if (error) {
5422 got_object_commit_close(commit);
5423 goto done;
5425 } else {
5426 ids[0] = NULL;
5427 labels[0] = strdup("/dev/null");
5428 if (labels[0] == NULL) {
5429 error = got_error_from_errno("strdup");
5430 got_object_commit_close(commit);
5431 goto done;
5435 got_object_commit_close(commit);
5438 if (ncommit_args == 0 && argc > 2) {
5439 error = got_error_msg(GOT_ERR_BAD_PATH,
5440 "path arguments cannot be used when diffing two objects");
5441 goto done;
5444 if (ids[0]) {
5445 error = got_object_get_type(&type1, repo, ids[0]);
5446 if (error)
5447 goto done;
5450 error = got_object_get_type(&type2, repo, ids[1]);
5451 if (error)
5452 goto done;
5453 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5454 error = got_error(GOT_ERR_OBJ_TYPE);
5455 goto done;
5457 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5458 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5459 "path arguments cannot be used when diffing blobs");
5460 goto done;
5463 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5464 char *in_repo_path;
5465 struct got_pathlist_entry *new;
5466 if (worktree) {
5467 const char *prefix;
5468 char *p;
5469 error = got_worktree_resolve_path(&p, worktree,
5470 argv[i]);
5471 if (error)
5472 goto done;
5473 prefix = got_worktree_get_path_prefix(worktree);
5474 while (prefix[0] == '/')
5475 prefix++;
5476 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5477 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5478 p) == -1) {
5479 error = got_error_from_errno("asprintf");
5480 free(p);
5481 goto done;
5483 free(p);
5484 } else {
5485 char *mapped_path, *s;
5486 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5487 if (error)
5488 goto done;
5489 s = mapped_path;
5490 while (s[0] == '/')
5491 s++;
5492 in_repo_path = strdup(s);
5493 if (in_repo_path == NULL) {
5494 error = got_error_from_errno("asprintf");
5495 free(mapped_path);
5496 goto done;
5498 free(mapped_path);
5501 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5502 if (error || new == NULL /* duplicate */)
5503 free(in_repo_path);
5504 if (error)
5505 goto done;
5508 if (worktree) {
5509 /* Release work tree lock. */
5510 got_worktree_close(worktree);
5511 worktree = NULL;
5514 fd1 = got_opentempfd();
5515 if (fd1 == -1) {
5516 error = got_error_from_errno("got_opentempfd");
5517 goto done;
5520 fd2 = got_opentempfd();
5521 if (fd2 == -1) {
5522 error = got_error_from_errno("got_opentempfd");
5523 goto done;
5526 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5527 case GOT_OBJ_TYPE_BLOB:
5528 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5529 fd1, fd2, ids[0], ids[1], NULL, NULL,
5530 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5531 ignore_whitespace, force_text_diff,
5532 show_diffstat ? &dsa : NULL, repo, outfile);
5533 break;
5534 case GOT_OBJ_TYPE_TREE:
5535 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5536 ids[0], ids[1], &paths, "", "",
5537 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5538 ignore_whitespace, force_text_diff,
5539 show_diffstat ? &dsa : NULL, repo, outfile);
5540 break;
5541 case GOT_OBJ_TYPE_COMMIT:
5542 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5543 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5544 fd1, fd2, ids[0], ids[1], &paths,
5545 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5546 ignore_whitespace, force_text_diff,
5547 show_diffstat ? &dsa : NULL, repo, outfile);
5548 break;
5549 default:
5550 error = got_error(GOT_ERR_OBJ_TYPE);
5552 if (error)
5553 goto done;
5555 if (show_diffstat && dsa.nfiles > 0) {
5556 char *header = NULL;
5558 if (asprintf(&header, "diffstat %s %s",
5559 labels[0], labels[1]) == -1) {
5560 error = got_error_from_errno("asprintf");
5561 goto done;
5564 error = print_diffstat(&dsa, header);
5565 free(header);
5566 if (error)
5567 goto done;
5570 error = printfile(outfile);
5572 done:
5573 free(labels[0]);
5574 free(labels[1]);
5575 free(ids[0]);
5576 free(ids[1]);
5577 if (worktree)
5578 got_worktree_close(worktree);
5579 if (repo) {
5580 const struct got_error *close_err = got_repo_close(repo);
5581 if (error == NULL)
5582 error = close_err;
5584 if (pack_fds) {
5585 const struct got_error *pack_err =
5586 got_repo_pack_fds_close(pack_fds);
5587 if (error == NULL)
5588 error = pack_err;
5590 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5591 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5592 got_ref_list_free(&refs);
5593 if (outfile && fclose(outfile) == EOF && error == NULL)
5594 error = got_error_from_errno("fclose");
5595 if (f1 && fclose(f1) == EOF && error == NULL)
5596 error = got_error_from_errno("fclose");
5597 if (f2 && fclose(f2) == EOF && error == NULL)
5598 error = got_error_from_errno("fclose");
5599 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5600 error = got_error_from_errno("close");
5601 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5602 error = got_error_from_errno("close");
5603 return error;
5606 __dead static void
5607 usage_blame(void)
5609 fprintf(stderr,
5610 "usage: %s blame [-c commit] [-r repository-path] path\n",
5611 getprogname());
5612 exit(1);
5615 struct blame_line {
5616 int annotated;
5617 char *id_str;
5618 char *committer;
5619 char datebuf[11]; /* YYYY-MM-DD + NUL */
5622 struct blame_cb_args {
5623 struct blame_line *lines;
5624 int nlines;
5625 int nlines_prec;
5626 int lineno_cur;
5627 off_t *line_offsets;
5628 FILE *f;
5629 struct got_repository *repo;
5632 static const struct got_error *
5633 blame_cb(void *arg, int nlines, int lineno,
5634 struct got_commit_object *commit, struct got_object_id *id)
5636 const struct got_error *err = NULL;
5637 struct blame_cb_args *a = arg;
5638 struct blame_line *bline;
5639 char *line = NULL;
5640 size_t linesize = 0;
5641 off_t offset;
5642 struct tm tm;
5643 time_t committer_time;
5645 if (nlines != a->nlines ||
5646 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5647 return got_error(GOT_ERR_RANGE);
5649 if (sigint_received)
5650 return got_error(GOT_ERR_ITER_COMPLETED);
5652 if (lineno == -1)
5653 return NULL; /* no change in this commit */
5655 /* Annotate this line. */
5656 bline = &a->lines[lineno - 1];
5657 if (bline->annotated)
5658 return NULL;
5659 err = got_object_id_str(&bline->id_str, id);
5660 if (err)
5661 return err;
5663 bline->committer = strdup(got_object_commit_get_committer(commit));
5664 if (bline->committer == NULL) {
5665 err = got_error_from_errno("strdup");
5666 goto done;
5669 committer_time = got_object_commit_get_committer_time(commit);
5670 if (gmtime_r(&committer_time, &tm) == NULL)
5671 return got_error_from_errno("gmtime_r");
5672 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5673 &tm) == 0) {
5674 err = got_error(GOT_ERR_NO_SPACE);
5675 goto done;
5677 bline->annotated = 1;
5679 /* Print lines annotated so far. */
5680 bline = &a->lines[a->lineno_cur - 1];
5681 if (!bline->annotated)
5682 goto done;
5684 offset = a->line_offsets[a->lineno_cur - 1];
5685 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5686 err = got_error_from_errno("fseeko");
5687 goto done;
5690 while (a->lineno_cur <= a->nlines && bline->annotated) {
5691 char *smallerthan, *at, *nl, *committer;
5692 size_t len;
5694 if (getline(&line, &linesize, a->f) == -1) {
5695 if (ferror(a->f))
5696 err = got_error_from_errno("getline");
5697 break;
5700 committer = bline->committer;
5701 smallerthan = strchr(committer, '<');
5702 if (smallerthan && smallerthan[1] != '\0')
5703 committer = smallerthan + 1;
5704 at = strchr(committer, '@');
5705 if (at)
5706 *at = '\0';
5707 len = strlen(committer);
5708 if (len >= 9)
5709 committer[8] = '\0';
5711 nl = strchr(line, '\n');
5712 if (nl)
5713 *nl = '\0';
5714 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5715 bline->id_str, bline->datebuf, committer, line);
5717 a->lineno_cur++;
5718 bline = &a->lines[a->lineno_cur - 1];
5720 done:
5721 free(line);
5722 return err;
5725 static const struct got_error *
5726 cmd_blame(int argc, char *argv[])
5728 const struct got_error *error;
5729 struct got_repository *repo = NULL;
5730 struct got_worktree *worktree = NULL;
5731 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5732 char *link_target = NULL;
5733 struct got_object_id *obj_id = NULL;
5734 struct got_object_id *commit_id = NULL;
5735 struct got_commit_object *commit = NULL;
5736 struct got_blob_object *blob = NULL;
5737 char *commit_id_str = NULL, *keyword_idstr = NULL;
5738 struct blame_cb_args bca;
5739 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5740 off_t filesize;
5741 int *pack_fds = NULL;
5742 FILE *f1 = NULL, *f2 = NULL;
5744 fd1 = got_opentempfd();
5745 if (fd1 == -1)
5746 return got_error_from_errno("got_opentempfd");
5748 memset(&bca, 0, sizeof(bca));
5750 #ifndef PROFILE
5751 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5752 NULL) == -1)
5753 err(1, "pledge");
5754 #endif
5756 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5757 switch (ch) {
5758 case 'c':
5759 commit_id_str = optarg;
5760 break;
5761 case 'r':
5762 repo_path = realpath(optarg, NULL);
5763 if (repo_path == NULL)
5764 return got_error_from_errno2("realpath",
5765 optarg);
5766 got_path_strip_trailing_slashes(repo_path);
5767 break;
5768 default:
5769 usage_blame();
5770 /* NOTREACHED */
5774 argc -= optind;
5775 argv += optind;
5777 if (argc == 1)
5778 path = argv[0];
5779 else
5780 usage_blame();
5782 cwd = getcwd(NULL, 0);
5783 if (cwd == NULL) {
5784 error = got_error_from_errno("getcwd");
5785 goto done;
5788 error = got_repo_pack_fds_open(&pack_fds);
5789 if (error != NULL)
5790 goto done;
5792 if (repo_path == NULL) {
5793 error = got_worktree_open(&worktree, cwd,
5794 GOT_WORKTREE_GOT_DIR);
5795 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5796 goto done;
5797 else
5798 error = NULL;
5799 if (worktree) {
5800 repo_path =
5801 strdup(got_worktree_get_repo_path(worktree));
5802 if (repo_path == NULL) {
5803 error = got_error_from_errno("strdup");
5804 if (error)
5805 goto done;
5807 } else {
5808 repo_path = strdup(cwd);
5809 if (repo_path == NULL) {
5810 error = got_error_from_errno("strdup");
5811 goto done;
5816 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5817 if (error != NULL)
5818 goto done;
5820 if (worktree) {
5821 const char *prefix = got_worktree_get_path_prefix(worktree);
5822 char *p;
5824 error = got_worktree_resolve_path(&p, worktree, path);
5825 if (error)
5826 goto done;
5827 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5828 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5829 p) == -1) {
5830 error = got_error_from_errno("asprintf");
5831 free(p);
5832 goto done;
5834 free(p);
5835 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5836 } else {
5837 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5838 if (error)
5839 goto done;
5840 error = got_repo_map_path(&in_repo_path, repo, path);
5842 if (error)
5843 goto done;
5845 if (commit_id_str == NULL) {
5846 struct got_reference *head_ref;
5847 error = got_ref_open(&head_ref, repo, worktree ?
5848 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5849 if (error != NULL)
5850 goto done;
5851 error = got_ref_resolve(&commit_id, repo, head_ref);
5852 got_ref_close(head_ref);
5853 if (error != NULL)
5854 goto done;
5855 } else {
5856 struct got_reflist_head refs;
5858 TAILQ_INIT(&refs);
5859 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5860 NULL);
5861 if (error)
5862 goto done;
5864 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5865 repo, worktree);
5866 if (error != NULL)
5867 goto done;
5868 if (keyword_idstr != NULL)
5869 commit_id_str = keyword_idstr;
5871 error = got_repo_match_object_id(&commit_id, NULL,
5872 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5873 got_ref_list_free(&refs);
5874 if (error)
5875 goto done;
5878 if (worktree) {
5879 /* Release work tree lock. */
5880 got_worktree_close(worktree);
5881 worktree = NULL;
5884 error = got_object_open_as_commit(&commit, repo, commit_id);
5885 if (error)
5886 goto done;
5888 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5889 commit, repo);
5890 if (error)
5891 goto done;
5893 error = got_object_id_by_path(&obj_id, repo, commit,
5894 link_target ? link_target : in_repo_path);
5895 if (error)
5896 goto done;
5898 error = got_object_get_type(&obj_type, repo, obj_id);
5899 if (error)
5900 goto done;
5902 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5903 error = got_error_path(link_target ? link_target : in_repo_path,
5904 GOT_ERR_OBJ_TYPE);
5905 goto done;
5908 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5909 if (error)
5910 goto done;
5911 bca.f = got_opentemp();
5912 if (bca.f == NULL) {
5913 error = got_error_from_errno("got_opentemp");
5914 goto done;
5916 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5917 &bca.line_offsets, bca.f, blob);
5918 if (error || bca.nlines == 0)
5919 goto done;
5921 /* Don't include \n at EOF in the blame line count. */
5922 if (bca.line_offsets[bca.nlines - 1] == filesize)
5923 bca.nlines--;
5925 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5926 if (bca.lines == NULL) {
5927 error = got_error_from_errno("calloc");
5928 goto done;
5930 bca.lineno_cur = 1;
5931 bca.nlines_prec = 0;
5932 i = bca.nlines;
5933 while (i > 0) {
5934 i /= 10;
5935 bca.nlines_prec++;
5937 bca.repo = repo;
5939 fd2 = got_opentempfd();
5940 if (fd2 == -1) {
5941 error = got_error_from_errno("got_opentempfd");
5942 goto done;
5944 fd3 = got_opentempfd();
5945 if (fd3 == -1) {
5946 error = got_error_from_errno("got_opentempfd");
5947 goto done;
5949 f1 = got_opentemp();
5950 if (f1 == NULL) {
5951 error = got_error_from_errno("got_opentemp");
5952 goto done;
5954 f2 = got_opentemp();
5955 if (f2 == NULL) {
5956 error = got_error_from_errno("got_opentemp");
5957 goto done;
5959 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5960 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5961 check_cancelled, NULL, fd2, fd3, f1, f2);
5962 done:
5963 free(keyword_idstr);
5964 free(in_repo_path);
5965 free(link_target);
5966 free(repo_path);
5967 free(cwd);
5968 free(commit_id);
5969 free(obj_id);
5970 if (commit)
5971 got_object_commit_close(commit);
5973 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5974 error = got_error_from_errno("close");
5975 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5976 error = got_error_from_errno("close");
5977 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5978 error = got_error_from_errno("close");
5979 if (f1 && fclose(f1) == EOF && error == NULL)
5980 error = got_error_from_errno("fclose");
5981 if (f2 && fclose(f2) == EOF && error == NULL)
5982 error = got_error_from_errno("fclose");
5984 if (blob)
5985 got_object_blob_close(blob);
5986 if (worktree)
5987 got_worktree_close(worktree);
5988 if (repo) {
5989 const struct got_error *close_err = got_repo_close(repo);
5990 if (error == NULL)
5991 error = close_err;
5993 if (pack_fds) {
5994 const struct got_error *pack_err =
5995 got_repo_pack_fds_close(pack_fds);
5996 if (error == NULL)
5997 error = pack_err;
5999 if (bca.lines) {
6000 for (i = 0; i < bca.nlines; i++) {
6001 struct blame_line *bline = &bca.lines[i];
6002 free(bline->id_str);
6003 free(bline->committer);
6005 free(bca.lines);
6007 free(bca.line_offsets);
6008 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6009 error = got_error_from_errno("fclose");
6010 return error;
6013 __dead static void
6014 usage_tree(void)
6016 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6017 "[path]\n", getprogname());
6018 exit(1);
6021 static const struct got_error *
6022 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6023 const char *root_path, struct got_repository *repo)
6025 const struct got_error *err = NULL;
6026 int is_root_path = (strcmp(path, root_path) == 0);
6027 const char *modestr = "";
6028 mode_t mode = got_tree_entry_get_mode(te);
6029 char *link_target = NULL;
6031 path += strlen(root_path);
6032 while (path[0] == '/')
6033 path++;
6035 if (got_object_tree_entry_is_submodule(te))
6036 modestr = "$";
6037 else if (S_ISLNK(mode)) {
6038 int i;
6040 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6041 if (err)
6042 return err;
6043 for (i = 0; link_target[i] != '\0'; i++) {
6044 if (!isprint((unsigned char)link_target[i]))
6045 link_target[i] = '?';
6048 modestr = "@";
6050 else if (S_ISDIR(mode))
6051 modestr = "/";
6052 else if (mode & S_IXUSR)
6053 modestr = "*";
6055 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6056 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6057 link_target ? " -> ": "", link_target ? link_target : "");
6059 free(link_target);
6060 return NULL;
6063 static const struct got_error *
6064 print_tree(const char *path, struct got_commit_object *commit,
6065 int show_ids, int recurse, const char *root_path,
6066 struct got_repository *repo)
6068 const struct got_error *err = NULL;
6069 struct got_object_id *tree_id = NULL;
6070 struct got_tree_object *tree = NULL;
6071 int nentries, i;
6073 err = got_object_id_by_path(&tree_id, repo, commit, path);
6074 if (err)
6075 goto done;
6077 err = got_object_open_as_tree(&tree, repo, tree_id);
6078 if (err)
6079 goto done;
6080 nentries = got_object_tree_get_nentries(tree);
6081 for (i = 0; i < nentries; i++) {
6082 struct got_tree_entry *te;
6083 char *id = NULL;
6085 if (sigint_received || sigpipe_received)
6086 break;
6088 te = got_object_tree_get_entry(tree, i);
6089 if (show_ids) {
6090 char *id_str;
6091 err = got_object_id_str(&id_str,
6092 got_tree_entry_get_id(te));
6093 if (err)
6094 goto done;
6095 if (asprintf(&id, "%s ", id_str) == -1) {
6096 err = got_error_from_errno("asprintf");
6097 free(id_str);
6098 goto done;
6100 free(id_str);
6102 err = print_entry(te, id, path, root_path, repo);
6103 free(id);
6104 if (err)
6105 goto done;
6107 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6108 char *child_path;
6109 if (asprintf(&child_path, "%s%s%s", path,
6110 path[0] == '/' && path[1] == '\0' ? "" : "/",
6111 got_tree_entry_get_name(te)) == -1) {
6112 err = got_error_from_errno("asprintf");
6113 goto done;
6115 err = print_tree(child_path, commit, show_ids, 1,
6116 root_path, repo);
6117 free(child_path);
6118 if (err)
6119 goto done;
6122 done:
6123 if (tree)
6124 got_object_tree_close(tree);
6125 free(tree_id);
6126 return err;
6129 static const struct got_error *
6130 cmd_tree(int argc, char *argv[])
6132 const struct got_error *error;
6133 struct got_repository *repo = NULL;
6134 struct got_worktree *worktree = NULL;
6135 const char *path, *refname = NULL;
6136 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6137 struct got_object_id *commit_id = NULL;
6138 struct got_commit_object *commit = NULL;
6139 char *commit_id_str = NULL, *keyword_idstr = NULL;
6140 int show_ids = 0, recurse = 0;
6141 int ch;
6142 int *pack_fds = NULL;
6144 #ifndef PROFILE
6145 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6146 NULL) == -1)
6147 err(1, "pledge");
6148 #endif
6150 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6151 switch (ch) {
6152 case 'c':
6153 commit_id_str = optarg;
6154 break;
6155 case 'i':
6156 show_ids = 1;
6157 break;
6158 case 'R':
6159 recurse = 1;
6160 break;
6161 case 'r':
6162 repo_path = realpath(optarg, NULL);
6163 if (repo_path == NULL)
6164 return got_error_from_errno2("realpath",
6165 optarg);
6166 got_path_strip_trailing_slashes(repo_path);
6167 break;
6168 default:
6169 usage_tree();
6170 /* NOTREACHED */
6174 argc -= optind;
6175 argv += optind;
6177 if (argc == 1)
6178 path = argv[0];
6179 else if (argc > 1)
6180 usage_tree();
6181 else
6182 path = NULL;
6184 cwd = getcwd(NULL, 0);
6185 if (cwd == NULL) {
6186 error = got_error_from_errno("getcwd");
6187 goto done;
6190 error = got_repo_pack_fds_open(&pack_fds);
6191 if (error != NULL)
6192 goto done;
6194 if (repo_path == NULL) {
6195 error = got_worktree_open(&worktree, cwd,
6196 GOT_WORKTREE_GOT_DIR);
6197 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6198 goto done;
6199 else
6200 error = NULL;
6201 if (worktree) {
6202 repo_path =
6203 strdup(got_worktree_get_repo_path(worktree));
6204 if (repo_path == NULL)
6205 error = got_error_from_errno("strdup");
6206 if (error)
6207 goto done;
6208 } else {
6209 repo_path = strdup(cwd);
6210 if (repo_path == NULL) {
6211 error = got_error_from_errno("strdup");
6212 goto done;
6217 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6218 if (error != NULL)
6219 goto done;
6221 if (worktree) {
6222 const char *prefix = got_worktree_get_path_prefix(worktree);
6223 char *p;
6225 if (path == NULL || got_path_is_root_dir(path))
6226 path = "";
6227 error = got_worktree_resolve_path(&p, worktree, path);
6228 if (error)
6229 goto done;
6230 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6231 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6232 p) == -1) {
6233 error = got_error_from_errno("asprintf");
6234 free(p);
6235 goto done;
6237 free(p);
6238 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6239 if (error)
6240 goto done;
6241 } else {
6242 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6243 if (error)
6244 goto done;
6245 if (path == NULL)
6246 path = "/";
6247 error = got_repo_map_path(&in_repo_path, repo, path);
6248 if (error != NULL)
6249 goto done;
6252 if (commit_id_str == NULL) {
6253 struct got_reference *head_ref;
6254 if (worktree)
6255 refname = got_worktree_get_head_ref_name(worktree);
6256 else
6257 refname = GOT_REF_HEAD;
6258 error = got_ref_open(&head_ref, repo, refname, 0);
6259 if (error != NULL)
6260 goto done;
6261 error = got_ref_resolve(&commit_id, repo, head_ref);
6262 got_ref_close(head_ref);
6263 if (error != NULL)
6264 goto done;
6265 } else {
6266 struct got_reflist_head refs;
6268 TAILQ_INIT(&refs);
6269 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6270 NULL);
6271 if (error)
6272 goto done;
6274 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6275 repo, worktree);
6276 if (error != NULL)
6277 goto done;
6278 if (keyword_idstr != NULL)
6279 commit_id_str = keyword_idstr;
6281 error = got_repo_match_object_id(&commit_id, NULL,
6282 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6283 got_ref_list_free(&refs);
6284 if (error)
6285 goto done;
6288 if (worktree) {
6289 /* Release work tree lock. */
6290 got_worktree_close(worktree);
6291 worktree = NULL;
6294 error = got_object_open_as_commit(&commit, repo, commit_id);
6295 if (error)
6296 goto done;
6298 error = print_tree(in_repo_path, commit, show_ids, recurse,
6299 in_repo_path, repo);
6300 done:
6301 free(keyword_idstr);
6302 free(in_repo_path);
6303 free(repo_path);
6304 free(cwd);
6305 free(commit_id);
6306 if (commit)
6307 got_object_commit_close(commit);
6308 if (worktree)
6309 got_worktree_close(worktree);
6310 if (repo) {
6311 const struct got_error *close_err = got_repo_close(repo);
6312 if (error == NULL)
6313 error = close_err;
6315 if (pack_fds) {
6316 const struct got_error *pack_err =
6317 got_repo_pack_fds_close(pack_fds);
6318 if (error == NULL)
6319 error = pack_err;
6321 return error;
6324 __dead static void
6325 usage_status(void)
6327 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6328 "[-s status-codes] [path ...]\n", getprogname());
6329 exit(1);
6332 struct got_status_arg {
6333 char *status_codes;
6334 int suppress;
6337 static const struct got_error *
6338 print_status(void *arg, unsigned char status, unsigned char staged_status,
6339 const char *path, struct got_object_id *blob_id,
6340 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6341 int dirfd, const char *de_name)
6343 struct got_status_arg *st = arg;
6345 if (status == staged_status && (status == GOT_STATUS_DELETE))
6346 status = GOT_STATUS_NO_CHANGE;
6347 if (st != NULL && st->status_codes) {
6348 size_t ncodes = strlen(st->status_codes);
6349 int i, j = 0;
6351 for (i = 0; i < ncodes ; i++) {
6352 if (st->suppress) {
6353 if (status == st->status_codes[i] ||
6354 staged_status == st->status_codes[i]) {
6355 j++;
6356 continue;
6358 } else {
6359 if (status == st->status_codes[i] ||
6360 staged_status == st->status_codes[i])
6361 break;
6365 if (st->suppress && j == 0)
6366 goto print;
6368 if (i == ncodes)
6369 return NULL;
6371 print:
6372 printf("%c%c %s\n", status, staged_status, path);
6373 return NULL;
6376 static const struct got_error *
6377 cmd_status(int argc, char *argv[])
6379 const struct got_error *error = NULL;
6380 struct got_repository *repo = NULL;
6381 struct got_worktree *worktree = NULL;
6382 struct got_status_arg st;
6383 char *cwd = NULL;
6384 struct got_pathlist_head paths;
6385 int ch, i, no_ignores = 0;
6386 int *pack_fds = NULL;
6388 TAILQ_INIT(&paths);
6390 memset(&st, 0, sizeof(st));
6391 st.status_codes = NULL;
6392 st.suppress = 0;
6394 #ifndef PROFILE
6395 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6396 NULL) == -1)
6397 err(1, "pledge");
6398 #endif
6400 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6401 switch (ch) {
6402 case 'I':
6403 no_ignores = 1;
6404 break;
6405 case 'S':
6406 if (st.status_codes != NULL && st.suppress == 0)
6407 option_conflict('S', 's');
6408 st.suppress = 1;
6409 /* fallthrough */
6410 case 's':
6411 for (i = 0; optarg[i] != '\0'; i++) {
6412 switch (optarg[i]) {
6413 case GOT_STATUS_MODIFY:
6414 case GOT_STATUS_ADD:
6415 case GOT_STATUS_DELETE:
6416 case GOT_STATUS_CONFLICT:
6417 case GOT_STATUS_MISSING:
6418 case GOT_STATUS_OBSTRUCTED:
6419 case GOT_STATUS_UNVERSIONED:
6420 case GOT_STATUS_MODE_CHANGE:
6421 case GOT_STATUS_NONEXISTENT:
6422 break;
6423 default:
6424 errx(1, "invalid status code '%c'",
6425 optarg[i]);
6428 if (ch == 's' && st.suppress)
6429 option_conflict('s', 'S');
6430 st.status_codes = optarg;
6431 break;
6432 default:
6433 usage_status();
6434 /* NOTREACHED */
6438 argc -= optind;
6439 argv += optind;
6441 cwd = getcwd(NULL, 0);
6442 if (cwd == NULL) {
6443 error = got_error_from_errno("getcwd");
6444 goto done;
6447 error = got_repo_pack_fds_open(&pack_fds);
6448 if (error != NULL)
6449 goto done;
6451 error = got_worktree_open(&worktree, cwd,
6452 GOT_WORKTREE_GOT_DIR);
6453 if (error) {
6454 if (error->code == GOT_ERR_NOT_WORKTREE)
6455 error = wrap_not_worktree_error(error, "status", cwd);
6456 goto done;
6459 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6460 NULL, pack_fds);
6461 if (error != NULL)
6462 goto done;
6464 error = apply_unveil(got_repo_get_path(repo), 1,
6465 got_worktree_get_root_path(worktree));
6466 if (error)
6467 goto done;
6469 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6470 if (error)
6471 goto done;
6473 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6474 print_status, &st, check_cancelled, NULL);
6475 done:
6476 if (pack_fds) {
6477 const struct got_error *pack_err =
6478 got_repo_pack_fds_close(pack_fds);
6479 if (error == NULL)
6480 error = pack_err;
6482 if (repo) {
6483 const struct got_error *close_err = got_repo_close(repo);
6484 if (error == NULL)
6485 error = close_err;
6488 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6489 free(cwd);
6490 return error;
6493 __dead static void
6494 usage_ref(void)
6496 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6497 "[-s reference] [name]\n", getprogname());
6498 exit(1);
6501 static const struct got_error *
6502 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6504 static const struct got_error *err = NULL;
6505 struct got_reflist_head refs;
6506 struct got_reflist_entry *re;
6508 TAILQ_INIT(&refs);
6509 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6510 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6511 repo);
6512 if (err)
6513 return err;
6515 TAILQ_FOREACH(re, &refs, entry) {
6516 char *refstr;
6517 refstr = got_ref_to_str(re->ref);
6518 if (refstr == NULL) {
6519 err = got_error_from_errno("got_ref_to_str");
6520 break;
6522 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6523 free(refstr);
6526 got_ref_list_free(&refs);
6527 return err;
6530 static const struct got_error *
6531 delete_ref_by_name(struct got_repository *repo, const char *refname)
6533 const struct got_error *err;
6534 struct got_reference *ref;
6536 err = got_ref_open(&ref, repo, refname, 0);
6537 if (err)
6538 return err;
6540 err = delete_ref(repo, ref);
6541 got_ref_close(ref);
6542 return err;
6545 static const struct got_error *
6546 add_ref(struct got_repository *repo, const char *refname, const char *target)
6548 const struct got_error *err = NULL;
6549 struct got_object_id *id = NULL;
6550 struct got_reference *ref = NULL;
6551 struct got_reflist_head refs;
6554 * Don't let the user create a reference name with a leading '-'.
6555 * While technically a valid reference name, this case is usually
6556 * an unintended typo.
6558 if (refname[0] == '-')
6559 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6561 TAILQ_INIT(&refs);
6562 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6563 if (err)
6564 goto done;
6565 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6566 &refs, repo);
6567 got_ref_list_free(&refs);
6568 if (err)
6569 goto done;
6571 err = got_ref_alloc(&ref, refname, id);
6572 if (err)
6573 goto done;
6575 err = got_ref_write(ref, repo);
6576 done:
6577 if (ref)
6578 got_ref_close(ref);
6579 free(id);
6580 return err;
6583 static const struct got_error *
6584 add_symref(struct got_repository *repo, const char *refname, const char *target)
6586 const struct got_error *err = NULL;
6587 struct got_reference *ref = NULL;
6588 struct got_reference *target_ref = NULL;
6591 * Don't let the user create a reference name with a leading '-'.
6592 * While technically a valid reference name, this case is usually
6593 * an unintended typo.
6595 if (refname[0] == '-')
6596 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6598 err = got_ref_open(&target_ref, repo, target, 0);
6599 if (err)
6600 return err;
6602 err = got_ref_alloc_symref(&ref, refname, target_ref);
6603 if (err)
6604 goto done;
6606 err = got_ref_write(ref, repo);
6607 done:
6608 if (target_ref)
6609 got_ref_close(target_ref);
6610 if (ref)
6611 got_ref_close(ref);
6612 return err;
6615 static const struct got_error *
6616 cmd_ref(int argc, char *argv[])
6618 const struct got_error *error = NULL;
6619 struct got_repository *repo = NULL;
6620 struct got_worktree *worktree = NULL;
6621 char *cwd = NULL, *repo_path = NULL;
6622 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6623 const char *obj_arg = NULL, *symref_target= NULL;
6624 char *refname = NULL, *keyword_idstr = NULL;
6625 int *pack_fds = NULL;
6627 #ifndef PROFILE
6628 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6629 "sendfd unveil", NULL) == -1)
6630 err(1, "pledge");
6631 #endif
6633 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6634 switch (ch) {
6635 case 'c':
6636 obj_arg = optarg;
6637 break;
6638 case 'd':
6639 do_delete = 1;
6640 break;
6641 case 'l':
6642 do_list = 1;
6643 break;
6644 case 'r':
6645 repo_path = realpath(optarg, NULL);
6646 if (repo_path == NULL)
6647 return got_error_from_errno2("realpath",
6648 optarg);
6649 got_path_strip_trailing_slashes(repo_path);
6650 break;
6651 case 's':
6652 symref_target = optarg;
6653 break;
6654 case 't':
6655 sort_by_time = 1;
6656 break;
6657 default:
6658 usage_ref();
6659 /* NOTREACHED */
6663 if (obj_arg && do_list)
6664 option_conflict('c', 'l');
6665 if (obj_arg && do_delete)
6666 option_conflict('c', 'd');
6667 if (obj_arg && symref_target)
6668 option_conflict('c', 's');
6669 if (symref_target && do_delete)
6670 option_conflict('s', 'd');
6671 if (symref_target && do_list)
6672 option_conflict('s', 'l');
6673 if (do_delete && do_list)
6674 option_conflict('d', 'l');
6675 if (sort_by_time && !do_list)
6676 errx(1, "-t option requires -l option");
6678 argc -= optind;
6679 argv += optind;
6681 if (do_list) {
6682 if (argc != 0 && argc != 1)
6683 usage_ref();
6684 if (argc == 1) {
6685 refname = strdup(argv[0]);
6686 if (refname == NULL) {
6687 error = got_error_from_errno("strdup");
6688 goto done;
6691 } else {
6692 if (argc != 1)
6693 usage_ref();
6694 refname = strdup(argv[0]);
6695 if (refname == NULL) {
6696 error = got_error_from_errno("strdup");
6697 goto done;
6701 if (refname)
6702 got_path_strip_trailing_slashes(refname);
6704 cwd = getcwd(NULL, 0);
6705 if (cwd == NULL) {
6706 error = got_error_from_errno("getcwd");
6707 goto done;
6710 error = got_repo_pack_fds_open(&pack_fds);
6711 if (error != NULL)
6712 goto done;
6714 if (repo_path == NULL) {
6715 error = got_worktree_open(&worktree, cwd,
6716 GOT_WORKTREE_GOT_DIR);
6717 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6718 goto done;
6719 else
6720 error = NULL;
6721 if (worktree) {
6722 repo_path =
6723 strdup(got_worktree_get_repo_path(worktree));
6724 if (repo_path == NULL)
6725 error = got_error_from_errno("strdup");
6726 if (error)
6727 goto done;
6728 } else {
6729 repo_path = strdup(cwd);
6730 if (repo_path == NULL) {
6731 error = got_error_from_errno("strdup");
6732 goto done;
6737 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6738 if (error != NULL)
6739 goto done;
6741 #ifndef PROFILE
6742 if (do_list) {
6743 /* Remove "cpath" promise. */
6744 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6745 NULL) == -1)
6746 err(1, "pledge");
6748 #endif
6750 error = apply_unveil(got_repo_get_path(repo), do_list,
6751 worktree ? got_worktree_get_root_path(worktree) : NULL);
6752 if (error)
6753 goto done;
6755 if (do_list)
6756 error = list_refs(repo, refname, sort_by_time);
6757 else if (do_delete)
6758 error = delete_ref_by_name(repo, refname);
6759 else if (symref_target)
6760 error = add_symref(repo, refname, symref_target);
6761 else {
6762 if (obj_arg == NULL)
6763 usage_ref();
6765 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6766 repo, worktree);
6767 if (error != NULL)
6768 goto done;
6769 if (keyword_idstr != NULL)
6770 obj_arg = keyword_idstr;
6772 error = add_ref(repo, refname, obj_arg);
6774 done:
6775 free(refname);
6776 if (repo) {
6777 const struct got_error *close_err = got_repo_close(repo);
6778 if (error == NULL)
6779 error = close_err;
6781 if (worktree)
6782 got_worktree_close(worktree);
6783 if (pack_fds) {
6784 const struct got_error *pack_err =
6785 got_repo_pack_fds_close(pack_fds);
6786 if (error == NULL)
6787 error = pack_err;
6789 free(cwd);
6790 free(repo_path);
6791 free(keyword_idstr);
6792 return error;
6795 __dead static void
6796 usage_branch(void)
6798 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6799 "[-r repository-path] [name]\n", getprogname());
6800 exit(1);
6803 static const struct got_error *
6804 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6805 struct got_reference *ref)
6807 const struct got_error *err = NULL;
6808 const char *refname;
6809 char *refstr;
6810 char marker = ' ';
6812 refname = got_ref_get_name(ref);
6813 if (worktree && strcmp(refname,
6814 got_worktree_get_head_ref_name(worktree)) == 0) {
6815 err = got_worktree_get_state(&marker, repo, worktree,
6816 check_cancelled, NULL);
6817 if (err != NULL)
6818 return err;
6821 if (strncmp(refname, "refs/heads/", 11) == 0)
6822 refname += 11;
6823 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6824 refname += 18;
6825 if (strncmp(refname, "refs/remotes/", 13) == 0)
6826 refname += 13;
6828 refstr = got_ref_to_str(ref);
6829 if (refstr == NULL)
6830 return got_error_from_errno("got_ref_to_str");
6832 printf("%c %s: %s\n", marker, refname, refstr);
6833 free(refstr);
6834 return NULL;
6837 static const struct got_error *
6838 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6840 const char *refname;
6842 if (worktree == NULL)
6843 return got_error(GOT_ERR_NOT_WORKTREE);
6845 refname = got_worktree_get_head_ref_name(worktree);
6847 if (strncmp(refname, "refs/heads/", 11) == 0)
6848 refname += 11;
6849 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6850 refname += 18;
6852 printf("%s\n", refname);
6854 return NULL;
6857 static const struct got_error *
6858 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6859 int sort_by_time)
6861 static const struct got_error *err = NULL;
6862 struct got_reflist_head refs;
6863 struct got_reflist_entry *re;
6864 struct got_reference *temp_ref = NULL;
6865 int rebase_in_progress, histedit_in_progress;
6867 TAILQ_INIT(&refs);
6869 if (worktree) {
6870 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6871 worktree);
6872 if (err)
6873 return err;
6875 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6876 worktree);
6877 if (err)
6878 return err;
6880 if (rebase_in_progress || histedit_in_progress) {
6881 err = got_ref_open(&temp_ref, repo,
6882 got_worktree_get_head_ref_name(worktree), 0);
6883 if (err)
6884 return err;
6885 list_branch(repo, worktree, temp_ref);
6886 got_ref_close(temp_ref);
6890 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6891 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6892 repo);
6893 if (err)
6894 return err;
6896 TAILQ_FOREACH(re, &refs, entry)
6897 list_branch(repo, worktree, re->ref);
6899 got_ref_list_free(&refs);
6901 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6902 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6903 repo);
6904 if (err)
6905 return err;
6907 TAILQ_FOREACH(re, &refs, entry)
6908 list_branch(repo, worktree, re->ref);
6910 got_ref_list_free(&refs);
6912 return NULL;
6915 static const struct got_error *
6916 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6917 const char *branch_name)
6919 const struct got_error *err = NULL;
6920 struct got_reference *ref = NULL;
6921 char *refname, *remote_refname = NULL;
6923 if (strncmp(branch_name, "refs/", 5) == 0)
6924 branch_name += 5;
6925 if (strncmp(branch_name, "heads/", 6) == 0)
6926 branch_name += 6;
6927 else if (strncmp(branch_name, "remotes/", 8) == 0)
6928 branch_name += 8;
6930 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6931 return got_error_from_errno("asprintf");
6933 if (asprintf(&remote_refname, "refs/remotes/%s",
6934 branch_name) == -1) {
6935 err = got_error_from_errno("asprintf");
6936 goto done;
6939 err = got_ref_open(&ref, repo, refname, 0);
6940 if (err) {
6941 const struct got_error *err2;
6942 if (err->code != GOT_ERR_NOT_REF)
6943 goto done;
6945 * Keep 'err' intact such that if neither branch exists
6946 * we report "refs/heads" rather than "refs/remotes" in
6947 * our error message.
6949 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6950 if (err2)
6951 goto done;
6952 err = NULL;
6955 if (worktree &&
6956 strcmp(got_worktree_get_head_ref_name(worktree),
6957 got_ref_get_name(ref)) == 0) {
6958 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6959 "will not delete this work tree's current branch");
6960 goto done;
6963 err = delete_ref(repo, ref);
6964 done:
6965 if (ref)
6966 got_ref_close(ref);
6967 free(refname);
6968 free(remote_refname);
6969 return err;
6972 static const struct got_error *
6973 add_branch(struct got_repository *repo, const char *branch_name,
6974 struct got_object_id *base_commit_id)
6976 const struct got_error *err = NULL;
6977 struct got_reference *ref = NULL;
6978 char *refname = NULL;
6981 * Don't let the user create a branch name with a leading '-'.
6982 * While technically a valid reference name, this case is usually
6983 * an unintended typo.
6985 if (branch_name[0] == '-')
6986 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6988 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6989 branch_name += 11;
6991 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6992 err = got_error_from_errno("asprintf");
6993 goto done;
6996 err = got_ref_open(&ref, repo, refname, 0);
6997 if (err == NULL) {
6998 err = got_error(GOT_ERR_BRANCH_EXISTS);
6999 goto done;
7000 } else if (err->code != GOT_ERR_NOT_REF)
7001 goto done;
7003 err = got_ref_alloc(&ref, refname, base_commit_id);
7004 if (err)
7005 goto done;
7007 err = got_ref_write(ref, repo);
7008 done:
7009 if (ref)
7010 got_ref_close(ref);
7011 free(refname);
7012 return err;
7015 static const struct got_error *
7016 cmd_branch(int argc, char *argv[])
7018 const struct got_error *error = NULL;
7019 struct got_repository *repo = NULL;
7020 struct got_worktree *worktree = NULL;
7021 char *cwd = NULL, *repo_path = NULL;
7022 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7023 const char *delref = NULL, *commit_id_arg = NULL;
7024 struct got_reference *ref = NULL;
7025 struct got_pathlist_head paths;
7026 struct got_object_id *commit_id = NULL;
7027 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7028 int *pack_fds = NULL;
7030 TAILQ_INIT(&paths);
7032 #ifndef PROFILE
7033 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7034 "sendfd unveil", NULL) == -1)
7035 err(1, "pledge");
7036 #endif
7038 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7039 switch (ch) {
7040 case 'c':
7041 commit_id_arg = optarg;
7042 break;
7043 case 'd':
7044 delref = optarg;
7045 break;
7046 case 'l':
7047 do_list = 1;
7048 break;
7049 case 'n':
7050 do_update = 0;
7051 break;
7052 case 'r':
7053 repo_path = realpath(optarg, NULL);
7054 if (repo_path == NULL)
7055 return got_error_from_errno2("realpath",
7056 optarg);
7057 got_path_strip_trailing_slashes(repo_path);
7058 break;
7059 case 't':
7060 sort_by_time = 1;
7061 break;
7062 default:
7063 usage_branch();
7064 /* NOTREACHED */
7068 if (do_list && delref)
7069 option_conflict('l', 'd');
7070 if (sort_by_time && !do_list)
7071 errx(1, "-t option requires -l option");
7073 argc -= optind;
7074 argv += optind;
7076 if (!do_list && !delref && argc == 0)
7077 do_show = 1;
7079 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7080 errx(1, "-c option can only be used when creating a branch");
7082 if (do_list || delref) {
7083 if (argc > 0)
7084 usage_branch();
7085 } else if (!do_show && argc != 1)
7086 usage_branch();
7088 cwd = getcwd(NULL, 0);
7089 if (cwd == NULL) {
7090 error = got_error_from_errno("getcwd");
7091 goto done;
7094 error = got_repo_pack_fds_open(&pack_fds);
7095 if (error != NULL)
7096 goto done;
7098 if (repo_path == NULL) {
7099 error = got_worktree_open(&worktree, cwd,
7100 GOT_WORKTREE_GOT_DIR);
7101 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7102 goto done;
7103 else
7104 error = NULL;
7105 if (worktree) {
7106 repo_path =
7107 strdup(got_worktree_get_repo_path(worktree));
7108 if (repo_path == NULL)
7109 error = got_error_from_errno("strdup");
7110 if (error)
7111 goto done;
7112 } else {
7113 repo_path = strdup(cwd);
7114 if (repo_path == NULL) {
7115 error = got_error_from_errno("strdup");
7116 goto done;
7121 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7122 if (error != NULL)
7123 goto done;
7125 #ifndef PROFILE
7126 if (do_list || do_show) {
7127 /* Remove "cpath" promise. */
7128 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7129 NULL) == -1)
7130 err(1, "pledge");
7132 #endif
7134 error = apply_unveil(got_repo_get_path(repo), do_list,
7135 worktree ? got_worktree_get_root_path(worktree) : NULL);
7136 if (error)
7137 goto done;
7139 if (do_show)
7140 error = show_current_branch(repo, worktree);
7141 else if (do_list)
7142 error = list_branches(repo, worktree, sort_by_time);
7143 else if (delref)
7144 error = delete_branch(repo, worktree, delref);
7145 else {
7146 struct got_reflist_head refs;
7147 TAILQ_INIT(&refs);
7148 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7149 NULL);
7150 if (error)
7151 goto done;
7152 if (commit_id_arg == NULL)
7153 commit_id_arg = worktree ?
7154 got_worktree_get_head_ref_name(worktree) :
7155 GOT_REF_HEAD;
7156 else {
7157 error = got_keyword_to_idstr(&keyword_idstr,
7158 commit_id_arg, repo, worktree);
7159 if (error != NULL)
7160 goto done;
7161 if (keyword_idstr != NULL)
7162 commit_id_arg = keyword_idstr;
7164 error = got_repo_match_object_id(&commit_id, NULL,
7165 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7166 got_ref_list_free(&refs);
7167 if (error)
7168 goto done;
7169 error = add_branch(repo, argv[0], commit_id);
7170 if (error)
7171 goto done;
7172 if (worktree && do_update) {
7173 struct got_update_progress_arg upa;
7174 char *branch_refname = NULL;
7176 error = got_object_id_str(&commit_id_str, commit_id);
7177 if (error)
7178 goto done;
7179 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7180 worktree);
7181 if (error)
7182 goto done;
7183 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7184 == -1) {
7185 error = got_error_from_errno("asprintf");
7186 goto done;
7188 error = got_ref_open(&ref, repo, branch_refname, 0);
7189 free(branch_refname);
7190 if (error)
7191 goto done;
7192 error = switch_head_ref(ref, commit_id, worktree,
7193 repo);
7194 if (error)
7195 goto done;
7196 error = got_worktree_set_base_commit_id(worktree, repo,
7197 commit_id);
7198 if (error)
7199 goto done;
7200 memset(&upa, 0, sizeof(upa));
7201 error = got_worktree_checkout_files(worktree, &paths,
7202 repo, update_progress, &upa, check_cancelled,
7203 NULL);
7204 if (error)
7205 goto done;
7206 if (upa.did_something) {
7207 printf("Updated to %s: %s\n",
7208 got_worktree_get_head_ref_name(worktree),
7209 commit_id_str);
7211 print_update_progress_stats(&upa);
7214 done:
7215 free(keyword_idstr);
7216 if (ref)
7217 got_ref_close(ref);
7218 if (repo) {
7219 const struct got_error *close_err = got_repo_close(repo);
7220 if (error == NULL)
7221 error = close_err;
7223 if (worktree)
7224 got_worktree_close(worktree);
7225 if (pack_fds) {
7226 const struct got_error *pack_err =
7227 got_repo_pack_fds_close(pack_fds);
7228 if (error == NULL)
7229 error = pack_err;
7231 free(cwd);
7232 free(repo_path);
7233 free(commit_id);
7234 free(commit_id_str);
7235 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7236 return error;
7240 __dead static void
7241 usage_tag(void)
7243 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7244 "[-r repository-path] [-s signer-id] name\n", getprogname());
7245 exit(1);
7248 #if 0
7249 static const struct got_error *
7250 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7252 const struct got_error *err = NULL;
7253 struct got_reflist_entry *re, *se, *new;
7254 struct got_object_id *re_id, *se_id;
7255 struct got_tag_object *re_tag, *se_tag;
7256 time_t re_time, se_time;
7258 STAILQ_FOREACH(re, tags, entry) {
7259 se = STAILQ_FIRST(sorted);
7260 if (se == NULL) {
7261 err = got_reflist_entry_dup(&new, re);
7262 if (err)
7263 return err;
7264 STAILQ_INSERT_HEAD(sorted, new, entry);
7265 continue;
7266 } else {
7267 err = got_ref_resolve(&re_id, repo, re->ref);
7268 if (err)
7269 break;
7270 err = got_object_open_as_tag(&re_tag, repo, re_id);
7271 free(re_id);
7272 if (err)
7273 break;
7274 re_time = got_object_tag_get_tagger_time(re_tag);
7275 got_object_tag_close(re_tag);
7278 while (se) {
7279 err = got_ref_resolve(&se_id, repo, re->ref);
7280 if (err)
7281 break;
7282 err = got_object_open_as_tag(&se_tag, repo, se_id);
7283 free(se_id);
7284 if (err)
7285 break;
7286 se_time = got_object_tag_get_tagger_time(se_tag);
7287 got_object_tag_close(se_tag);
7289 if (se_time > re_time) {
7290 err = got_reflist_entry_dup(&new, re);
7291 if (err)
7292 return err;
7293 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7294 break;
7296 se = STAILQ_NEXT(se, entry);
7297 continue;
7300 done:
7301 return err;
7303 #endif
7305 static const struct got_error *
7306 get_tag_refname(char **refname, const char *tag_name)
7308 const struct got_error *err;
7310 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7311 *refname = strdup(tag_name);
7312 if (*refname == NULL)
7313 return got_error_from_errno("strdup");
7314 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7315 err = got_error_from_errno("asprintf");
7316 *refname = NULL;
7317 return err;
7320 return NULL;
7323 static const struct got_error *
7324 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7325 const char *allowed_signers, const char *revoked_signers, int verbosity)
7327 static const struct got_error *err = NULL;
7328 struct got_reflist_head refs;
7329 struct got_reflist_entry *re;
7330 char *wanted_refname = NULL;
7331 int bad_sigs = 0;
7333 TAILQ_INIT(&refs);
7335 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7336 if (err)
7337 return err;
7339 if (tag_name) {
7340 struct got_reference *ref;
7341 err = get_tag_refname(&wanted_refname, tag_name);
7342 if (err)
7343 goto done;
7344 /* Wanted tag reference should exist. */
7345 err = got_ref_open(&ref, repo, wanted_refname, 0);
7346 if (err)
7347 goto done;
7348 got_ref_close(ref);
7351 TAILQ_FOREACH(re, &refs, entry) {
7352 const char *refname;
7353 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7354 char datebuf[26];
7355 const char *tagger, *ssh_sig = NULL;
7356 char *sig_msg = NULL;
7357 time_t tagger_time;
7358 struct got_object_id *id;
7359 struct got_tag_object *tag;
7360 struct got_commit_object *commit = NULL;
7362 refname = got_ref_get_name(re->ref);
7363 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7364 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7365 continue;
7366 refname += 10;
7367 refstr = got_ref_to_str(re->ref);
7368 if (refstr == NULL) {
7369 err = got_error_from_errno("got_ref_to_str");
7370 break;
7373 err = got_ref_resolve(&id, repo, re->ref);
7374 if (err)
7375 break;
7376 err = got_object_open_as_tag(&tag, repo, id);
7377 if (err) {
7378 if (err->code != GOT_ERR_OBJ_TYPE) {
7379 free(id);
7380 break;
7382 /* "lightweight" tag */
7383 err = got_object_open_as_commit(&commit, repo, id);
7384 if (err) {
7385 free(id);
7386 break;
7388 tagger = got_object_commit_get_committer(commit);
7389 tagger_time =
7390 got_object_commit_get_committer_time(commit);
7391 err = got_object_id_str(&id_str, id);
7392 free(id);
7393 if (err)
7394 break;
7395 } else {
7396 free(id);
7397 tagger = got_object_tag_get_tagger(tag);
7398 tagger_time = got_object_tag_get_tagger_time(tag);
7399 err = got_object_id_str(&id_str,
7400 got_object_tag_get_object_id(tag));
7401 if (err)
7402 break;
7405 if (tag && verify_tags) {
7406 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7407 got_object_tag_get_message(tag));
7408 if (ssh_sig && allowed_signers == NULL) {
7409 err = got_error_msg(
7410 GOT_ERR_VERIFY_TAG_SIGNATURE,
7411 "SSH signature verification requires "
7412 "setting allowed_signers in "
7413 "got.conf(5)");
7414 break;
7418 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7419 free(refstr);
7420 printf("from: %s\n", tagger);
7421 datestr = get_datestr(&tagger_time, datebuf);
7422 if (datestr)
7423 printf("date: %s UTC\n", datestr);
7424 if (commit)
7425 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7426 else {
7427 switch (got_object_tag_get_object_type(tag)) {
7428 case GOT_OBJ_TYPE_BLOB:
7429 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7430 id_str);
7431 break;
7432 case GOT_OBJ_TYPE_TREE:
7433 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7434 id_str);
7435 break;
7436 case GOT_OBJ_TYPE_COMMIT:
7437 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7438 id_str);
7439 break;
7440 case GOT_OBJ_TYPE_TAG:
7441 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7442 id_str);
7443 break;
7444 default:
7445 break;
7448 free(id_str);
7450 if (ssh_sig) {
7451 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7452 allowed_signers, revoked_signers, verbosity);
7453 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7454 bad_sigs = 1;
7455 else if (err)
7456 break;
7457 printf("signature: %s", sig_msg);
7458 free(sig_msg);
7459 sig_msg = NULL;
7462 if (commit) {
7463 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7464 if (err)
7465 break;
7466 got_object_commit_close(commit);
7467 } else {
7468 tagmsg0 = strdup(got_object_tag_get_message(tag));
7469 got_object_tag_close(tag);
7470 if (tagmsg0 == NULL) {
7471 err = got_error_from_errno("strdup");
7472 break;
7476 tagmsg = tagmsg0;
7477 do {
7478 line = strsep(&tagmsg, "\n");
7479 if (line)
7480 printf(" %s\n", line);
7481 } while (line);
7482 free(tagmsg0);
7484 done:
7485 got_ref_list_free(&refs);
7486 free(wanted_refname);
7488 if (err == NULL && bad_sigs)
7489 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7490 return err;
7493 static const struct got_error *
7494 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7495 const char *tag_name, const char *repo_path)
7497 const struct got_error *err = NULL;
7498 char *template = NULL, *initial_content = NULL;
7499 char *editor = NULL;
7500 int initial_content_len;
7501 int fd = -1;
7503 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7504 err = got_error_from_errno("asprintf");
7505 goto done;
7508 initial_content_len = asprintf(&initial_content,
7509 "\n# tagging commit %s as %s\n",
7510 commit_id_str, tag_name);
7511 if (initial_content_len == -1) {
7512 err = got_error_from_errno("asprintf");
7513 goto done;
7516 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7517 if (err)
7518 goto done;
7520 if (write(fd, initial_content, initial_content_len) == -1) {
7521 err = got_error_from_errno2("write", *tagmsg_path);
7522 goto done;
7524 if (close(fd) == -1) {
7525 err = got_error_from_errno2("close", *tagmsg_path);
7526 goto done;
7528 fd = -1;
7530 err = get_editor(&editor);
7531 if (err)
7532 goto done;
7533 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7534 initial_content_len, 1);
7535 done:
7536 free(initial_content);
7537 free(template);
7538 free(editor);
7540 if (fd != -1 && close(fd) == -1 && err == NULL)
7541 err = got_error_from_errno2("close", *tagmsg_path);
7543 if (err) {
7544 free(*tagmsg);
7545 *tagmsg = NULL;
7547 return err;
7550 static const struct got_error *
7551 add_tag(struct got_repository *repo, const char *tagger,
7552 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7553 const char *signer_id, int verbosity)
7555 const struct got_error *err = NULL;
7556 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7557 char *label = NULL, *commit_id_str = NULL;
7558 struct got_reference *ref = NULL;
7559 char *refname = NULL, *tagmsg = NULL;
7560 char *tagmsg_path = NULL, *tag_id_str = NULL;
7561 int preserve_tagmsg = 0;
7562 struct got_reflist_head refs;
7564 TAILQ_INIT(&refs);
7567 * Don't let the user create a tag name with a leading '-'.
7568 * While technically a valid reference name, this case is usually
7569 * an unintended typo.
7571 if (tag_name[0] == '-')
7572 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7574 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7575 if (err)
7576 goto done;
7578 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7579 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7580 if (err)
7581 goto done;
7583 err = got_object_id_str(&commit_id_str, commit_id);
7584 if (err)
7585 goto done;
7587 err = get_tag_refname(&refname, tag_name);
7588 if (err)
7589 goto done;
7590 if (strncmp("refs/tags/", tag_name, 10) == 0)
7591 tag_name += 10;
7593 err = got_ref_open(&ref, repo, refname, 0);
7594 if (err == NULL) {
7595 err = got_error(GOT_ERR_TAG_EXISTS);
7596 goto done;
7597 } else if (err->code != GOT_ERR_NOT_REF)
7598 goto done;
7600 if (tagmsg_arg == NULL) {
7601 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7602 tag_name, got_repo_get_path(repo));
7603 if (err) {
7604 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7605 tagmsg_path != NULL)
7606 preserve_tagmsg = 1;
7607 goto done;
7609 /* Editor is done; we can now apply unveil(2) */
7610 err = got_sigs_apply_unveil();
7611 if (err)
7612 goto done;
7613 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7614 if (err)
7615 goto done;
7618 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7619 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7620 verbosity);
7621 if (err) {
7622 if (tagmsg_path)
7623 preserve_tagmsg = 1;
7624 goto done;
7627 err = got_ref_alloc(&ref, refname, tag_id);
7628 if (err) {
7629 if (tagmsg_path)
7630 preserve_tagmsg = 1;
7631 goto done;
7634 err = got_ref_write(ref, repo);
7635 if (err) {
7636 if (tagmsg_path)
7637 preserve_tagmsg = 1;
7638 goto done;
7641 err = got_object_id_str(&tag_id_str, tag_id);
7642 if (err) {
7643 if (tagmsg_path)
7644 preserve_tagmsg = 1;
7645 goto done;
7647 printf("Created tag %s\n", tag_id_str);
7648 done:
7649 if (preserve_tagmsg) {
7650 fprintf(stderr, "%s: tag message preserved in %s\n",
7651 getprogname(), tagmsg_path);
7652 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7653 err = got_error_from_errno2("unlink", tagmsg_path);
7654 free(tag_id_str);
7655 if (ref)
7656 got_ref_close(ref);
7657 free(commit_id);
7658 free(commit_id_str);
7659 free(refname);
7660 free(tagmsg);
7661 free(tagmsg_path);
7662 got_ref_list_free(&refs);
7663 return err;
7666 static const struct got_error *
7667 cmd_tag(int argc, char *argv[])
7669 const struct got_error *error = NULL;
7670 struct got_repository *repo = NULL;
7671 struct got_worktree *worktree = NULL;
7672 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7673 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7674 char *allowed_signers = NULL, *revoked_signers = NULL;
7675 const char *signer_id = NULL;
7676 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7677 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7678 int *pack_fds = NULL;
7680 #ifndef PROFILE
7681 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7682 "sendfd unveil", NULL) == -1)
7683 err(1, "pledge");
7684 #endif
7686 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7687 switch (ch) {
7688 case 'c':
7689 commit_id_arg = optarg;
7690 break;
7691 case 'l':
7692 do_list = 1;
7693 break;
7694 case 'm':
7695 tagmsg = optarg;
7696 break;
7697 case 'r':
7698 repo_path = realpath(optarg, NULL);
7699 if (repo_path == NULL) {
7700 error = got_error_from_errno2("realpath",
7701 optarg);
7702 goto done;
7704 got_path_strip_trailing_slashes(repo_path);
7705 break;
7706 case 's':
7707 signer_id = optarg;
7708 break;
7709 case 'V':
7710 verify_tags = 1;
7711 break;
7712 case 'v':
7713 if (verbosity < 0)
7714 verbosity = 0;
7715 else if (verbosity < 3)
7716 verbosity++;
7717 break;
7718 default:
7719 usage_tag();
7720 /* NOTREACHED */
7724 argc -= optind;
7725 argv += optind;
7727 if (do_list || verify_tags) {
7728 if (commit_id_arg != NULL)
7729 errx(1,
7730 "-c option can only be used when creating a tag");
7731 if (tagmsg) {
7732 if (do_list)
7733 option_conflict('l', 'm');
7734 else
7735 option_conflict('V', 'm');
7737 if (signer_id) {
7738 if (do_list)
7739 option_conflict('l', 's');
7740 else
7741 option_conflict('V', 's');
7743 if (argc > 1)
7744 usage_tag();
7745 } else if (argc != 1)
7746 usage_tag();
7748 if (argc == 1)
7749 tag_name = argv[0];
7751 cwd = getcwd(NULL, 0);
7752 if (cwd == NULL) {
7753 error = got_error_from_errno("getcwd");
7754 goto done;
7757 error = got_repo_pack_fds_open(&pack_fds);
7758 if (error != NULL)
7759 goto done;
7761 if (repo_path == NULL) {
7762 error = got_worktree_open(&worktree, cwd,
7763 GOT_WORKTREE_GOT_DIR);
7764 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7765 goto done;
7766 else
7767 error = NULL;
7768 if (worktree) {
7769 repo_path =
7770 strdup(got_worktree_get_repo_path(worktree));
7771 if (repo_path == NULL)
7772 error = got_error_from_errno("strdup");
7773 if (error)
7774 goto done;
7775 } else {
7776 repo_path = strdup(cwd);
7777 if (repo_path == NULL) {
7778 error = got_error_from_errno("strdup");
7779 goto done;
7784 if (do_list || verify_tags) {
7785 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7786 if (error != NULL)
7787 goto done;
7788 error = get_allowed_signers(&allowed_signers, repo, worktree);
7789 if (error)
7790 goto done;
7791 error = get_revoked_signers(&revoked_signers, repo, worktree);
7792 if (error)
7793 goto done;
7794 if (worktree) {
7795 /* Release work tree lock. */
7796 got_worktree_close(worktree);
7797 worktree = NULL;
7801 * Remove "cpath" promise unless needed for signature tmpfile
7802 * creation.
7804 if (verify_tags)
7805 got_sigs_apply_unveil();
7806 else {
7807 #ifndef PROFILE
7808 if (pledge("stdio rpath wpath flock proc exec sendfd "
7809 "unveil", NULL) == -1)
7810 err(1, "pledge");
7811 #endif
7813 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7814 if (error)
7815 goto done;
7816 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7817 revoked_signers, verbosity);
7818 } else {
7819 error = get_gitconfig_path(&gitconfig_path);
7820 if (error)
7821 goto done;
7822 error = got_repo_open(&repo, repo_path, gitconfig_path,
7823 pack_fds);
7824 if (error != NULL)
7825 goto done;
7827 error = get_author(&tagger, repo, worktree);
7828 if (error)
7829 goto done;
7830 if (signer_id == NULL)
7831 signer_id = get_signer_id(repo, worktree);
7833 if (tagmsg) {
7834 if (signer_id) {
7835 error = got_sigs_apply_unveil();
7836 if (error)
7837 goto done;
7839 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7840 if (error)
7841 goto done;
7844 if (commit_id_arg == NULL) {
7845 struct got_reference *head_ref;
7846 struct got_object_id *commit_id;
7847 error = got_ref_open(&head_ref, repo,
7848 worktree ? got_worktree_get_head_ref_name(worktree)
7849 : GOT_REF_HEAD, 0);
7850 if (error)
7851 goto done;
7852 error = got_ref_resolve(&commit_id, repo, head_ref);
7853 got_ref_close(head_ref);
7854 if (error)
7855 goto done;
7856 error = got_object_id_str(&commit_id_str, commit_id);
7857 free(commit_id);
7858 if (error)
7859 goto done;
7860 } else {
7861 error = got_keyword_to_idstr(&keyword_idstr,
7862 commit_id_arg, repo, worktree);
7863 if (error != NULL)
7864 goto done;
7865 commit_id_str = keyword_idstr;
7868 if (worktree) {
7869 /* Release work tree lock. */
7870 got_worktree_close(worktree);
7871 worktree = NULL;
7874 error = add_tag(repo, tagger, tag_name,
7875 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7876 signer_id, verbosity);
7878 done:
7879 if (repo) {
7880 const struct got_error *close_err = got_repo_close(repo);
7881 if (error == NULL)
7882 error = close_err;
7884 if (worktree)
7885 got_worktree_close(worktree);
7886 if (pack_fds) {
7887 const struct got_error *pack_err =
7888 got_repo_pack_fds_close(pack_fds);
7889 if (error == NULL)
7890 error = pack_err;
7892 free(cwd);
7893 free(repo_path);
7894 free(gitconfig_path);
7895 free(commit_id_str);
7896 free(tagger);
7897 free(allowed_signers);
7898 free(revoked_signers);
7899 return error;
7902 __dead static void
7903 usage_add(void)
7905 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7906 exit(1);
7909 static const struct got_error *
7910 add_progress(void *arg, unsigned char status, const char *path)
7912 while (path[0] == '/')
7913 path++;
7914 printf("%c %s\n", status, path);
7915 return NULL;
7918 static const struct got_error *
7919 cmd_add(int argc, char *argv[])
7921 const struct got_error *error = NULL;
7922 struct got_repository *repo = NULL;
7923 struct got_worktree *worktree = NULL;
7924 char *cwd = NULL;
7925 struct got_pathlist_head paths;
7926 struct got_pathlist_entry *pe;
7927 int ch, can_recurse = 0, no_ignores = 0;
7928 int *pack_fds = NULL;
7930 TAILQ_INIT(&paths);
7932 #ifndef PROFILE
7933 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7934 NULL) == -1)
7935 err(1, "pledge");
7936 #endif
7938 while ((ch = getopt(argc, argv, "IR")) != -1) {
7939 switch (ch) {
7940 case 'I':
7941 no_ignores = 1;
7942 break;
7943 case 'R':
7944 can_recurse = 1;
7945 break;
7946 default:
7947 usage_add();
7948 /* NOTREACHED */
7952 argc -= optind;
7953 argv += optind;
7955 if (argc < 1)
7956 usage_add();
7958 cwd = getcwd(NULL, 0);
7959 if (cwd == NULL) {
7960 error = got_error_from_errno("getcwd");
7961 goto done;
7964 error = got_repo_pack_fds_open(&pack_fds);
7965 if (error != NULL)
7966 goto done;
7968 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
7969 if (error) {
7970 if (error->code == GOT_ERR_NOT_WORKTREE)
7971 error = wrap_not_worktree_error(error, "add", cwd);
7972 goto done;
7975 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7976 NULL, pack_fds);
7977 if (error != NULL)
7978 goto done;
7980 error = apply_unveil(got_repo_get_path(repo), 1,
7981 got_worktree_get_root_path(worktree));
7982 if (error)
7983 goto done;
7985 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7986 if (error)
7987 goto done;
7989 if (!can_recurse) {
7990 char *ondisk_path;
7991 struct stat sb;
7992 TAILQ_FOREACH(pe, &paths, entry) {
7993 if (asprintf(&ondisk_path, "%s/%s",
7994 got_worktree_get_root_path(worktree),
7995 pe->path) == -1) {
7996 error = got_error_from_errno("asprintf");
7997 goto done;
7999 if (lstat(ondisk_path, &sb) == -1) {
8000 if (errno == ENOENT) {
8001 free(ondisk_path);
8002 continue;
8004 error = got_error_from_errno2("lstat",
8005 ondisk_path);
8006 free(ondisk_path);
8007 goto done;
8009 free(ondisk_path);
8010 if (S_ISDIR(sb.st_mode)) {
8011 error = got_error_msg(GOT_ERR_BAD_PATH,
8012 "adding directories requires -R option");
8013 goto done;
8018 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8019 NULL, repo, no_ignores);
8020 done:
8021 if (repo) {
8022 const struct got_error *close_err = got_repo_close(repo);
8023 if (error == NULL)
8024 error = close_err;
8026 if (worktree)
8027 got_worktree_close(worktree);
8028 if (pack_fds) {
8029 const struct got_error *pack_err =
8030 got_repo_pack_fds_close(pack_fds);
8031 if (error == NULL)
8032 error = pack_err;
8034 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8035 free(cwd);
8036 return error;
8039 __dead static void
8040 usage_remove(void)
8042 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8043 getprogname());
8044 exit(1);
8047 static const struct got_error *
8048 print_remove_status(void *arg, unsigned char status,
8049 unsigned char staged_status, const char *path)
8051 while (path[0] == '/')
8052 path++;
8053 if (status == GOT_STATUS_NONEXISTENT)
8054 return NULL;
8055 if (status == staged_status && (status == GOT_STATUS_DELETE))
8056 status = GOT_STATUS_NO_CHANGE;
8057 printf("%c%c %s\n", status, staged_status, path);
8058 return NULL;
8061 static const struct got_error *
8062 cmd_remove(int argc, char *argv[])
8064 const struct got_error *error = NULL;
8065 struct got_worktree *worktree = NULL;
8066 struct got_repository *repo = NULL;
8067 const char *status_codes = NULL;
8068 char *cwd = NULL;
8069 struct got_pathlist_head paths;
8070 struct got_pathlist_entry *pe;
8071 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8072 int ignore_missing_paths = 0;
8073 int *pack_fds = NULL;
8075 TAILQ_INIT(&paths);
8077 #ifndef PROFILE
8078 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8079 NULL) == -1)
8080 err(1, "pledge");
8081 #endif
8083 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8084 switch (ch) {
8085 case 'f':
8086 delete_local_mods = 1;
8087 ignore_missing_paths = 1;
8088 break;
8089 case 'k':
8090 keep_on_disk = 1;
8091 break;
8092 case 'R':
8093 can_recurse = 1;
8094 break;
8095 case 's':
8096 for (i = 0; optarg[i] != '\0'; i++) {
8097 switch (optarg[i]) {
8098 case GOT_STATUS_MODIFY:
8099 delete_local_mods = 1;
8100 break;
8101 case GOT_STATUS_MISSING:
8102 ignore_missing_paths = 1;
8103 break;
8104 default:
8105 errx(1, "invalid status code '%c'",
8106 optarg[i]);
8109 status_codes = optarg;
8110 break;
8111 default:
8112 usage_remove();
8113 /* NOTREACHED */
8117 argc -= optind;
8118 argv += optind;
8120 if (argc < 1)
8121 usage_remove();
8123 cwd = getcwd(NULL, 0);
8124 if (cwd == NULL) {
8125 error = got_error_from_errno("getcwd");
8126 goto done;
8129 error = got_repo_pack_fds_open(&pack_fds);
8130 if (error != NULL)
8131 goto done;
8133 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8134 if (error) {
8135 if (error->code == GOT_ERR_NOT_WORKTREE)
8136 error = wrap_not_worktree_error(error, "remove", cwd);
8137 goto done;
8140 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8141 NULL, pack_fds);
8142 if (error)
8143 goto done;
8145 error = apply_unveil(got_repo_get_path(repo), 1,
8146 got_worktree_get_root_path(worktree));
8147 if (error)
8148 goto done;
8150 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8151 if (error)
8152 goto done;
8154 if (!can_recurse) {
8155 char *ondisk_path;
8156 struct stat sb;
8157 TAILQ_FOREACH(pe, &paths, entry) {
8158 if (asprintf(&ondisk_path, "%s/%s",
8159 got_worktree_get_root_path(worktree),
8160 pe->path) == -1) {
8161 error = got_error_from_errno("asprintf");
8162 goto done;
8164 if (lstat(ondisk_path, &sb) == -1) {
8165 if (errno == ENOENT) {
8166 free(ondisk_path);
8167 continue;
8169 error = got_error_from_errno2("lstat",
8170 ondisk_path);
8171 free(ondisk_path);
8172 goto done;
8174 free(ondisk_path);
8175 if (S_ISDIR(sb.st_mode)) {
8176 error = got_error_msg(GOT_ERR_BAD_PATH,
8177 "removing directories requires -R option");
8178 goto done;
8183 error = got_worktree_schedule_delete(worktree, &paths,
8184 delete_local_mods, status_codes, print_remove_status, NULL,
8185 repo, keep_on_disk, ignore_missing_paths);
8186 done:
8187 if (repo) {
8188 const struct got_error *close_err = got_repo_close(repo);
8189 if (error == NULL)
8190 error = close_err;
8192 if (worktree)
8193 got_worktree_close(worktree);
8194 if (pack_fds) {
8195 const struct got_error *pack_err =
8196 got_repo_pack_fds_close(pack_fds);
8197 if (error == NULL)
8198 error = pack_err;
8200 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8201 free(cwd);
8202 return error;
8205 __dead static void
8206 usage_patch(void)
8208 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8209 "[patchfile]\n", getprogname());
8210 exit(1);
8213 static const struct got_error *
8214 patch_from_stdin(int *patchfd)
8216 const struct got_error *err = NULL;
8217 ssize_t r;
8218 char buf[BUFSIZ];
8219 sig_t sighup, sigint, sigquit;
8221 *patchfd = got_opentempfd();
8222 if (*patchfd == -1)
8223 return got_error_from_errno("got_opentempfd");
8225 sighup = signal(SIGHUP, SIG_DFL);
8226 sigint = signal(SIGINT, SIG_DFL);
8227 sigquit = signal(SIGQUIT, SIG_DFL);
8229 for (;;) {
8230 r = read(0, buf, sizeof(buf));
8231 if (r == -1) {
8232 err = got_error_from_errno("read");
8233 break;
8235 if (r == 0)
8236 break;
8237 if (write(*patchfd, buf, r) == -1) {
8238 err = got_error_from_errno("write");
8239 break;
8243 signal(SIGHUP, sighup);
8244 signal(SIGINT, sigint);
8245 signal(SIGQUIT, sigquit);
8247 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8248 err = got_error_from_errno("lseek");
8250 if (err != NULL) {
8251 close(*patchfd);
8252 *patchfd = -1;
8255 return err;
8258 struct got_patch_progress_arg {
8259 int did_something;
8260 int conflicts;
8261 int rejects;
8264 static const struct got_error *
8265 patch_progress(void *arg, const char *old, const char *new,
8266 unsigned char status, const struct got_error *error, int old_from,
8267 int old_lines, int new_from, int new_lines, int offset,
8268 int ws_mangled, const struct got_error *hunk_err)
8270 const char *path = new == NULL ? old : new;
8271 struct got_patch_progress_arg *a = arg;
8273 while (*path == '/')
8274 path++;
8276 if (status != GOT_STATUS_NO_CHANGE &&
8277 status != 0 /* per-hunk progress */) {
8278 printf("%c %s\n", status, path);
8279 a->did_something = 1;
8282 if (hunk_err == NULL) {
8283 if (status == GOT_STATUS_CANNOT_UPDATE)
8284 a->rejects++;
8285 else if (status == GOT_STATUS_CONFLICT)
8286 a->conflicts++;
8289 if (error != NULL)
8290 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8292 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8293 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8294 old_lines, new_from, new_lines);
8295 if (hunk_err != NULL)
8296 printf("%s\n", hunk_err->msg);
8297 else if (offset != 0)
8298 printf("applied with offset %d\n", offset);
8299 else
8300 printf("hunk contains mangled whitespace\n");
8303 return NULL;
8306 static void
8307 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8309 if (!ppa->did_something)
8310 return;
8312 if (ppa->conflicts > 0)
8313 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8315 if (ppa->rejects > 0) {
8316 printf("Files where patch failed to apply: %d\n",
8317 ppa->rejects);
8321 static const struct got_error *
8322 cmd_patch(int argc, char *argv[])
8324 const struct got_error *error = NULL, *close_error = NULL;
8325 struct got_worktree *worktree = NULL;
8326 struct got_repository *repo = NULL;
8327 struct got_reflist_head refs;
8328 struct got_object_id *commit_id = NULL;
8329 const char *commit_id_str = NULL;
8330 struct stat sb;
8331 const char *errstr;
8332 char *cwd = NULL, *keyword_idstr = NULL;
8333 int ch, nop = 0, strip = -1, reverse = 0;
8334 int patchfd;
8335 int *pack_fds = NULL;
8336 struct got_patch_progress_arg ppa;
8338 TAILQ_INIT(&refs);
8340 #ifndef PROFILE
8341 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8342 "unveil", NULL) == -1)
8343 err(1, "pledge");
8344 #endif
8346 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8347 switch (ch) {
8348 case 'c':
8349 commit_id_str = optarg;
8350 break;
8351 case 'n':
8352 nop = 1;
8353 break;
8354 case 'p':
8355 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8356 if (errstr != NULL)
8357 errx(1, "pathname strip count is %s: %s",
8358 errstr, optarg);
8359 break;
8360 case 'R':
8361 reverse = 1;
8362 break;
8363 default:
8364 usage_patch();
8365 /* NOTREACHED */
8369 argc -= optind;
8370 argv += optind;
8372 if (argc == 0) {
8373 error = patch_from_stdin(&patchfd);
8374 if (error)
8375 return error;
8376 } else if (argc == 1) {
8377 patchfd = open(argv[0], O_RDONLY);
8378 if (patchfd == -1) {
8379 error = got_error_from_errno2("open", argv[0]);
8380 return error;
8382 if (fstat(patchfd, &sb) == -1) {
8383 error = got_error_from_errno2("fstat", argv[0]);
8384 goto done;
8386 if (!S_ISREG(sb.st_mode)) {
8387 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8388 goto done;
8390 } else
8391 usage_patch();
8393 if ((cwd = getcwd(NULL, 0)) == NULL) {
8394 error = got_error_from_errno("getcwd");
8395 goto done;
8398 error = got_repo_pack_fds_open(&pack_fds);
8399 if (error != NULL)
8400 goto done;
8402 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8403 if (error != NULL)
8404 goto done;
8406 const char *repo_path = got_worktree_get_repo_path(worktree);
8407 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8408 if (error != NULL)
8409 goto done;
8411 error = apply_unveil(got_repo_get_path(repo), 0,
8412 got_worktree_get_root_path(worktree));
8413 if (error != NULL)
8414 goto done;
8416 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8417 if (error)
8418 goto done;
8420 if (commit_id_str != NULL) {
8421 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8422 repo, worktree);
8423 if (error != NULL)
8424 goto done;
8426 error = got_repo_match_object_id(&commit_id, NULL,
8427 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8428 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8429 if (error)
8430 goto done;
8433 memset(&ppa, 0, sizeof(ppa));
8434 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8435 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8436 print_patch_progress_stats(&ppa);
8437 done:
8438 got_ref_list_free(&refs);
8439 free(keyword_idstr);
8440 free(commit_id);
8441 if (repo) {
8442 close_error = got_repo_close(repo);
8443 if (error == NULL)
8444 error = close_error;
8446 if (worktree != NULL) {
8447 close_error = got_worktree_close(worktree);
8448 if (error == NULL)
8449 error = close_error;
8451 if (pack_fds) {
8452 const struct got_error *pack_err =
8453 got_repo_pack_fds_close(pack_fds);
8454 if (error == NULL)
8455 error = pack_err;
8457 free(cwd);
8458 return error;
8461 __dead static void
8462 usage_revert(void)
8464 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8465 getprogname());
8466 exit(1);
8469 static const struct got_error *
8470 revert_progress(void *arg, unsigned char status, const char *path)
8472 if (status == GOT_STATUS_UNVERSIONED)
8473 return NULL;
8475 while (path[0] == '/')
8476 path++;
8477 printf("%c %s\n", status, path);
8478 return NULL;
8481 struct choose_patch_arg {
8482 FILE *patch_script_file;
8483 const char *action;
8486 static const struct got_error *
8487 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8488 int nchanges, const char *action)
8490 const struct got_error *err;
8491 char *line = NULL;
8492 size_t linesize = 0;
8493 ssize_t linelen;
8495 switch (status) {
8496 case GOT_STATUS_ADD:
8497 printf("A %s\n%s this addition? [y/n] ", path, action);
8498 break;
8499 case GOT_STATUS_DELETE:
8500 printf("D %s\n%s this deletion? [y/n] ", path, action);
8501 break;
8502 case GOT_STATUS_MODIFY:
8503 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8504 return got_error_from_errno("fseek");
8505 printf(GOT_COMMIT_SEP_STR);
8506 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8507 printf("%s", line);
8508 if (linelen == -1 && ferror(patch_file)) {
8509 err = got_error_from_errno("getline");
8510 free(line);
8511 return err;
8513 free(line);
8514 printf(GOT_COMMIT_SEP_STR);
8515 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8516 path, n, nchanges, action);
8517 break;
8518 default:
8519 return got_error_path(path, GOT_ERR_FILE_STATUS);
8522 fflush(stdout);
8523 return NULL;
8526 static const struct got_error *
8527 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8528 FILE *patch_file, int n, int nchanges)
8530 const struct got_error *err = NULL;
8531 char *line = NULL;
8532 size_t linesize = 0;
8533 ssize_t linelen;
8534 int resp = ' ';
8535 struct choose_patch_arg *a = arg;
8537 *choice = GOT_PATCH_CHOICE_NONE;
8539 if (a->patch_script_file) {
8540 char *nl;
8541 err = show_change(status, path, patch_file, n, nchanges,
8542 a->action);
8543 if (err)
8544 return err;
8545 linelen = getline(&line, &linesize, a->patch_script_file);
8546 if (linelen == -1) {
8547 if (ferror(a->patch_script_file))
8548 return got_error_from_errno("getline");
8549 return NULL;
8551 nl = strchr(line, '\n');
8552 if (nl)
8553 *nl = '\0';
8554 if (strcmp(line, "y") == 0) {
8555 *choice = GOT_PATCH_CHOICE_YES;
8556 printf("y\n");
8557 } else if (strcmp(line, "n") == 0) {
8558 *choice = GOT_PATCH_CHOICE_NO;
8559 printf("n\n");
8560 } else if (strcmp(line, "q") == 0 &&
8561 status == GOT_STATUS_MODIFY) {
8562 *choice = GOT_PATCH_CHOICE_QUIT;
8563 printf("q\n");
8564 } else
8565 printf("invalid response '%s'\n", line);
8566 free(line);
8567 return NULL;
8570 while (resp != 'y' && resp != 'n' && resp != 'q') {
8571 err = show_change(status, path, patch_file, n, nchanges,
8572 a->action);
8573 if (err)
8574 return err;
8575 resp = getchar();
8576 if (resp == '\n')
8577 resp = getchar();
8578 if (status == GOT_STATUS_MODIFY) {
8579 if (resp != 'y' && resp != 'n' && resp != 'q') {
8580 printf("invalid response '%c'\n", resp);
8581 resp = ' ';
8583 } else if (resp != 'y' && resp != 'n') {
8584 printf("invalid response '%c'\n", resp);
8585 resp = ' ';
8589 if (resp == 'y')
8590 *choice = GOT_PATCH_CHOICE_YES;
8591 else if (resp == 'n')
8592 *choice = GOT_PATCH_CHOICE_NO;
8593 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8594 *choice = GOT_PATCH_CHOICE_QUIT;
8596 return NULL;
8599 struct wt_commitable_path_arg {
8600 struct got_pathlist_head *commit_paths;
8601 int *has_changes;
8605 * Shortcut work tree status callback to determine if the set of paths scanned
8606 * has at least one versioned path that is being modified and, if not NULL, is
8607 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8608 * soon as a path is passed with a status that satisfies this criteria.
8610 static const struct got_error *
8611 worktree_has_commitable_path(void *arg, unsigned char status,
8612 unsigned char staged_status, const char *path,
8613 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8614 struct got_object_id *commit_id, int dirfd, const char *de_name)
8616 struct wt_commitable_path_arg *a = arg;
8618 if (status == staged_status && (status == GOT_STATUS_DELETE))
8619 status = GOT_STATUS_NO_CHANGE;
8621 if (!(status == GOT_STATUS_NO_CHANGE ||
8622 status == GOT_STATUS_UNVERSIONED) ||
8623 staged_status != GOT_STATUS_NO_CHANGE) {
8624 if (a->commit_paths != NULL) {
8625 struct got_pathlist_entry *pe;
8627 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8628 if (strncmp(path, pe->path,
8629 pe->path_len) == 0) {
8630 *a->has_changes = 1;
8631 break;
8634 } else
8635 *a->has_changes = 1;
8637 if (*a->has_changes)
8638 return got_error(GOT_ERR_FILE_MODIFIED);
8641 return NULL;
8645 * Check that the changeset of the commit identified by id is
8646 * comprised of at least one modified path that is being committed.
8648 static const struct got_error *
8649 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8650 struct got_object_id *id, struct got_worktree *worktree,
8651 struct got_repository *repo)
8653 const struct got_error *err;
8654 struct got_pathlist_head paths;
8655 struct got_commit_object *commit = NULL, *pcommit = NULL;
8656 struct got_tree_object *tree = NULL, *ptree = NULL;
8657 struct got_object_qid *pid;
8659 TAILQ_INIT(&paths);
8661 err = got_object_open_as_commit(&commit, repo, id);
8662 if (err)
8663 goto done;
8665 err = got_object_open_as_tree(&tree, repo,
8666 got_object_commit_get_tree_id(commit));
8667 if (err)
8668 goto done;
8670 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8671 if (pid != NULL) {
8672 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8673 if (err)
8674 goto done;
8676 err = got_object_open_as_tree(&ptree, repo,
8677 got_object_commit_get_tree_id(pcommit));
8678 if (err)
8679 goto done;
8682 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8683 got_diff_tree_collect_changed_paths, &paths, 0);
8684 if (err)
8685 goto done;
8687 err = got_worktree_status(worktree, &paths, repo, 0,
8688 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8689 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8691 * At least one changed path in the referenced commit is
8692 * modified in the work tree, that's all we need to know!
8694 err = NULL;
8697 done:
8698 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8699 if (commit)
8700 got_object_commit_close(commit);
8701 if (pcommit)
8702 got_object_commit_close(pcommit);
8703 if (tree)
8704 got_object_tree_close(tree);
8705 if (ptree)
8706 got_object_tree_close(ptree);
8707 return err;
8711 * Remove any "logmsg" reference comprised entirely of paths that have
8712 * been reverted in this work tree. If any path in the logmsg ref changeset
8713 * remains in a changed state in the worktree, do not remove the reference.
8715 static const struct got_error *
8716 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8718 const struct got_error *err;
8719 struct got_reflist_head refs;
8720 struct got_reflist_entry *re;
8721 struct got_commit_object *commit = NULL;
8722 struct got_object_id *commit_id = NULL;
8723 struct wt_commitable_path_arg wcpa;
8724 char *uuidstr = NULL;
8726 TAILQ_INIT(&refs);
8728 err = got_worktree_get_uuid(&uuidstr, worktree);
8729 if (err)
8730 goto done;
8732 err = got_ref_list(&refs, repo, "refs/got/worktree",
8733 got_ref_cmp_by_name, repo);
8734 if (err)
8735 goto done;
8737 TAILQ_FOREACH(re, &refs, entry) {
8738 const char *refname;
8739 int has_changes = 0;
8741 refname = got_ref_get_name(re->ref);
8743 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8744 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8745 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8746 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8747 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8748 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8749 else
8750 continue;
8752 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8753 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8754 else
8755 continue;
8757 err = got_repo_match_object_id(&commit_id, NULL, refname,
8758 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8759 if (err)
8760 goto done;
8762 err = got_object_open_as_commit(&commit, repo, commit_id);
8763 if (err)
8764 goto done;
8766 wcpa.commit_paths = NULL;
8767 wcpa.has_changes = &has_changes;
8769 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8770 worktree, repo);
8771 if (err)
8772 goto done;
8774 if (!has_changes) {
8775 err = got_ref_delete(re->ref, repo);
8776 if (err)
8777 goto done;
8780 got_object_commit_close(commit);
8781 commit = NULL;
8782 free(commit_id);
8783 commit_id = NULL;
8786 done:
8787 free(uuidstr);
8788 free(commit_id);
8789 got_ref_list_free(&refs);
8790 if (commit)
8791 got_object_commit_close(commit);
8792 return err;
8795 static const struct got_error *
8796 cmd_revert(int argc, char *argv[])
8798 const struct got_error *error = NULL;
8799 struct got_worktree *worktree = NULL;
8800 struct got_repository *repo = NULL;
8801 char *cwd = NULL, *path = NULL;
8802 struct got_pathlist_head paths;
8803 struct got_pathlist_entry *pe;
8804 int ch, can_recurse = 0, pflag = 0;
8805 FILE *patch_script_file = NULL;
8806 const char *patch_script_path = NULL;
8807 struct choose_patch_arg cpa;
8808 int *pack_fds = NULL;
8810 TAILQ_INIT(&paths);
8812 #ifndef PROFILE
8813 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8814 "unveil", NULL) == -1)
8815 err(1, "pledge");
8816 #endif
8818 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8819 switch (ch) {
8820 case 'F':
8821 patch_script_path = optarg;
8822 break;
8823 case 'p':
8824 pflag = 1;
8825 break;
8826 case 'R':
8827 can_recurse = 1;
8828 break;
8829 default:
8830 usage_revert();
8831 /* NOTREACHED */
8835 argc -= optind;
8836 argv += optind;
8838 if (argc < 1)
8839 usage_revert();
8840 if (patch_script_path && !pflag)
8841 errx(1, "-F option can only be used together with -p option");
8843 cwd = getcwd(NULL, 0);
8844 if (cwd == NULL) {
8845 error = got_error_from_errno("getcwd");
8846 goto done;
8849 error = got_repo_pack_fds_open(&pack_fds);
8850 if (error != NULL)
8851 goto done;
8853 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8854 if (error) {
8855 if (error->code == GOT_ERR_NOT_WORKTREE)
8856 error = wrap_not_worktree_error(error, "revert", cwd);
8857 goto done;
8860 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8861 NULL, pack_fds);
8862 if (error != NULL)
8863 goto done;
8865 if (patch_script_path) {
8866 patch_script_file = fopen(patch_script_path, "re");
8867 if (patch_script_file == NULL) {
8868 error = got_error_from_errno2("fopen",
8869 patch_script_path);
8870 goto done;
8875 * XXX "c" perm needed on repo dir to delete merge references.
8877 error = apply_unveil(got_repo_get_path(repo), 0,
8878 got_worktree_get_root_path(worktree));
8879 if (error)
8880 goto done;
8882 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8883 if (error)
8884 goto done;
8886 if (!can_recurse) {
8887 char *ondisk_path;
8888 struct stat sb;
8889 TAILQ_FOREACH(pe, &paths, entry) {
8890 if (asprintf(&ondisk_path, "%s/%s",
8891 got_worktree_get_root_path(worktree),
8892 pe->path) == -1) {
8893 error = got_error_from_errno("asprintf");
8894 goto done;
8896 if (lstat(ondisk_path, &sb) == -1) {
8897 if (errno == ENOENT) {
8898 free(ondisk_path);
8899 continue;
8901 error = got_error_from_errno2("lstat",
8902 ondisk_path);
8903 free(ondisk_path);
8904 goto done;
8906 free(ondisk_path);
8907 if (S_ISDIR(sb.st_mode)) {
8908 error = got_error_msg(GOT_ERR_BAD_PATH,
8909 "reverting directories requires -R option");
8910 goto done;
8915 cpa.patch_script_file = patch_script_file;
8916 cpa.action = "revert";
8917 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8918 pflag ? choose_patch : NULL, &cpa, repo);
8920 error = rm_logmsg_ref(worktree, repo);
8921 done:
8922 if (patch_script_file && fclose(patch_script_file) == EOF &&
8923 error == NULL)
8924 error = got_error_from_errno2("fclose", patch_script_path);
8925 if (repo) {
8926 const struct got_error *close_err = got_repo_close(repo);
8927 if (error == NULL)
8928 error = close_err;
8930 if (worktree)
8931 got_worktree_close(worktree);
8932 if (pack_fds) {
8933 const struct got_error *pack_err =
8934 got_repo_pack_fds_close(pack_fds);
8935 if (error == NULL)
8936 error = pack_err;
8938 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8939 free(path);
8940 free(cwd);
8941 return error;
8944 __dead static void
8945 usage_commit(void)
8947 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8948 "[-m message] [path ...]\n", getprogname());
8949 exit(1);
8952 struct collect_commit_logmsg_arg {
8953 const char *cmdline_log;
8954 const char *prepared_log;
8955 const char *merged_log;
8956 int non_interactive;
8957 const char *editor;
8958 const char *worktree_path;
8959 const char *branch_name;
8960 const char *repo_path;
8961 char *logmsg_path;
8965 static const struct got_error *
8966 read_prepared_logmsg(char **logmsg, const char *path)
8968 const struct got_error *err = NULL;
8969 FILE *f = NULL;
8970 struct stat sb;
8971 size_t r;
8973 *logmsg = NULL;
8974 memset(&sb, 0, sizeof(sb));
8976 f = fopen(path, "re");
8977 if (f == NULL)
8978 return got_error_from_errno2("fopen", path);
8980 if (fstat(fileno(f), &sb) == -1) {
8981 err = got_error_from_errno2("fstat", path);
8982 goto done;
8984 if (sb.st_size == 0) {
8985 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8986 goto done;
8989 *logmsg = malloc(sb.st_size + 1);
8990 if (*logmsg == NULL) {
8991 err = got_error_from_errno("malloc");
8992 goto done;
8995 r = fread(*logmsg, 1, sb.st_size, f);
8996 if (r != sb.st_size) {
8997 if (ferror(f))
8998 err = got_error_from_errno2("fread", path);
8999 else
9000 err = got_error(GOT_ERR_IO);
9001 goto done;
9003 (*logmsg)[sb.st_size] = '\0';
9004 done:
9005 if (fclose(f) == EOF && err == NULL)
9006 err = got_error_from_errno2("fclose", path);
9007 if (err) {
9008 free(*logmsg);
9009 *logmsg = NULL;
9011 return err;
9014 static const struct got_error *
9015 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9016 const char *diff_path, char **logmsg, void *arg)
9018 char *initial_content = NULL;
9019 struct got_pathlist_entry *pe;
9020 const struct got_error *err = NULL;
9021 char *template = NULL;
9022 char *prepared_msg = NULL, *merged_msg = NULL;
9023 struct collect_commit_logmsg_arg *a = arg;
9024 int initial_content_len;
9025 int fd = -1;
9026 size_t len;
9028 /* if a message was specified on the command line, just use it */
9029 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9030 len = strlen(a->cmdline_log) + 1;
9031 *logmsg = malloc(len + 1);
9032 if (*logmsg == NULL)
9033 return got_error_from_errno("malloc");
9034 strlcpy(*logmsg, a->cmdline_log, len);
9035 return NULL;
9036 } else if (a->prepared_log != NULL && a->non_interactive)
9037 return read_prepared_logmsg(logmsg, a->prepared_log);
9039 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9040 return got_error_from_errno("asprintf");
9042 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9043 if (err)
9044 goto done;
9046 if (a->prepared_log) {
9047 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9048 if (err)
9049 goto done;
9050 } else if (a->merged_log) {
9051 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9052 if (err)
9053 goto done;
9056 initial_content_len = asprintf(&initial_content,
9057 "%s%s\n# changes to be committed on branch %s:\n",
9058 prepared_msg ? prepared_msg : "",
9059 merged_msg ? merged_msg : "", a->branch_name);
9060 if (initial_content_len == -1) {
9061 err = got_error_from_errno("asprintf");
9062 goto done;
9065 if (write(fd, initial_content, initial_content_len) == -1) {
9066 err = got_error_from_errno2("write", a->logmsg_path);
9067 goto done;
9070 TAILQ_FOREACH(pe, commitable_paths, entry) {
9071 struct got_commitable *ct = pe->data;
9072 dprintf(fd, "# %c %s\n",
9073 got_commitable_get_status(ct),
9074 got_commitable_get_path(ct));
9077 if (diff_path) {
9078 dprintf(fd, "# detailed changes can be viewed in %s\n",
9079 diff_path);
9082 if (close(fd) == -1) {
9083 err = got_error_from_errno2("close", a->logmsg_path);
9084 goto done;
9086 fd = -1;
9088 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9089 initial_content_len, a->prepared_log ? 0 : 1);
9090 done:
9091 free(initial_content);
9092 free(template);
9093 free(prepared_msg);
9094 free(merged_msg);
9096 if (fd != -1 && close(fd) == -1 && err == NULL)
9097 err = got_error_from_errno2("close", a->logmsg_path);
9099 /* Editor is done; we can now apply unveil(2) */
9100 if (err == NULL)
9101 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9102 if (err) {
9103 free(*logmsg);
9104 *logmsg = NULL;
9106 return err;
9109 static const struct got_error *
9110 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9111 const char *type, int has_content)
9113 const struct got_error *err = NULL;
9114 char *logmsg = NULL;
9116 err = got_object_commit_get_logmsg(&logmsg, commit);
9117 if (err)
9118 return err;
9120 if (fprintf(f, "%s# log message of %s commit %s:%s",
9121 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9122 err = got_ferror(f, GOT_ERR_IO);
9124 free(logmsg);
9125 return err;
9129 * Lookup "logmsg" references of backed-out and cherrypicked commits
9130 * belonging to the current work tree. If found, and the worktree has
9131 * at least one modified file that was changed in the referenced commit,
9132 * add its log message to a new temporary file at *logmsg_path.
9133 * Add all refs found to matched_refs to be scheduled for removal on
9134 * successful commit.
9136 static const struct got_error *
9137 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9138 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9139 struct got_repository *repo)
9141 const struct got_error *err;
9142 struct got_commit_object *commit = NULL;
9143 struct got_object_id *id = NULL;
9144 struct got_reflist_head refs;
9145 struct got_reflist_entry *re, *re_match;
9146 FILE *f = NULL;
9147 char *uuidstr = NULL;
9148 int added_logmsg = 0;
9150 TAILQ_INIT(&refs);
9152 *logmsg_path = NULL;
9154 err = got_worktree_get_uuid(&uuidstr, worktree);
9155 if (err)
9156 goto done;
9158 err = got_ref_list(&refs, repo, "refs/got/worktree",
9159 got_ref_cmp_by_name, repo);
9160 if (err)
9161 goto done;
9163 TAILQ_FOREACH(re, &refs, entry) {
9164 const char *refname, *type;
9165 struct wt_commitable_path_arg wcpa;
9166 int add_logmsg = 0;
9168 refname = got_ref_get_name(re->ref);
9170 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9171 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9172 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9173 type = "cherrypicked";
9174 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9175 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9176 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9177 type = "backed-out";
9178 } else
9179 continue;
9181 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9182 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9183 else
9184 continue;
9186 err = got_repo_match_object_id(&id, NULL, refname,
9187 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9188 if (err)
9189 goto done;
9191 err = got_object_open_as_commit(&commit, repo, id);
9192 if (err)
9193 goto done;
9195 wcpa.commit_paths = paths;
9196 wcpa.has_changes = &add_logmsg;
9198 err = commit_path_changed_in_worktree(&wcpa, id,
9199 worktree, repo);
9200 if (err)
9201 goto done;
9203 if (add_logmsg) {
9204 if (f == NULL) {
9205 err = got_opentemp_named(logmsg_path, &f,
9206 "got-commit-logmsg", "");
9207 if (err)
9208 goto done;
9210 err = cat_logmsg(f, commit, refname, type,
9211 added_logmsg);
9212 if (err)
9213 goto done;
9214 if (!added_logmsg)
9215 ++added_logmsg;
9217 err = got_reflist_entry_dup(&re_match, re);
9218 if (err)
9219 goto done;
9220 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9223 got_object_commit_close(commit);
9224 commit = NULL;
9225 free(id);
9226 id = NULL;
9229 done:
9230 free(id);
9231 free(uuidstr);
9232 got_ref_list_free(&refs);
9233 if (commit)
9234 got_object_commit_close(commit);
9235 if (f && fclose(f) == EOF && err == NULL)
9236 err = got_error_from_errno("fclose");
9237 if (!added_logmsg) {
9238 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9239 err = got_error_from_errno2("unlink", *logmsg_path);
9240 *logmsg_path = NULL;
9242 return err;
9245 static const struct got_error *
9246 cmd_commit(int argc, char *argv[])
9248 const struct got_error *error = NULL;
9249 struct got_worktree *worktree = NULL;
9250 struct got_repository *repo = NULL;
9251 char *cwd = NULL, *id_str = NULL;
9252 struct got_object_id *id = NULL;
9253 const char *logmsg = NULL;
9254 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9255 struct collect_commit_logmsg_arg cl_arg;
9256 const char *author = NULL;
9257 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9258 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9259 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9260 int show_diff = 1, commit_conflicts = 0;
9261 struct got_pathlist_head paths;
9262 struct got_reflist_head refs;
9263 struct got_reflist_entry *re;
9264 int *pack_fds = NULL;
9266 TAILQ_INIT(&refs);
9267 TAILQ_INIT(&paths);
9268 cl_arg.logmsg_path = NULL;
9270 #ifndef PROFILE
9271 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9272 "unveil", NULL) == -1)
9273 err(1, "pledge");
9274 #endif
9276 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9277 switch (ch) {
9278 case 'A':
9279 author = optarg;
9280 error = valid_author(author);
9281 if (error)
9282 return error;
9283 break;
9284 case 'C':
9285 commit_conflicts = 1;
9286 break;
9287 case 'F':
9288 if (logmsg != NULL)
9289 option_conflict('F', 'm');
9290 prepared_logmsg = realpath(optarg, NULL);
9291 if (prepared_logmsg == NULL)
9292 return got_error_from_errno2("realpath",
9293 optarg);
9294 break;
9295 case 'm':
9296 if (prepared_logmsg)
9297 option_conflict('m', 'F');
9298 logmsg = optarg;
9299 break;
9300 case 'N':
9301 non_interactive = 1;
9302 break;
9303 case 'n':
9304 show_diff = 0;
9305 break;
9306 case 'S':
9307 allow_bad_symlinks = 1;
9308 break;
9309 default:
9310 usage_commit();
9311 /* NOTREACHED */
9315 argc -= optind;
9316 argv += optind;
9318 cwd = getcwd(NULL, 0);
9319 if (cwd == NULL) {
9320 error = got_error_from_errno("getcwd");
9321 goto done;
9324 error = got_repo_pack_fds_open(&pack_fds);
9325 if (error != NULL)
9326 goto done;
9328 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9329 if (error) {
9330 if (error->code == GOT_ERR_NOT_WORKTREE)
9331 error = wrap_not_worktree_error(error, "commit", cwd);
9332 goto done;
9335 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9336 if (error)
9337 goto done;
9338 if (rebase_in_progress) {
9339 error = got_error(GOT_ERR_REBASING);
9340 goto done;
9343 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9344 worktree);
9345 if (error)
9346 goto done;
9348 error = get_gitconfig_path(&gitconfig_path);
9349 if (error)
9350 goto done;
9351 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9352 gitconfig_path, pack_fds);
9353 if (error != NULL)
9354 goto done;
9356 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9357 if (error)
9358 goto done;
9359 if (merge_in_progress) {
9360 error = got_error(GOT_ERR_MERGE_BUSY);
9361 goto done;
9364 error = get_author(&committer, repo, worktree);
9365 if (error)
9366 goto done;
9368 if (author == NULL)
9369 author = committer;
9372 * unveil(2) traverses exec(2); if an editor is used we have
9373 * to apply unveil after the log message has been written.
9375 if (logmsg == NULL || strlen(logmsg) == 0)
9376 error = get_editor(&editor);
9377 else
9378 error = apply_unveil(got_repo_get_path(repo), 0,
9379 got_worktree_get_root_path(worktree));
9380 if (error)
9381 goto done;
9383 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9384 if (error)
9385 goto done;
9387 if (prepared_logmsg == NULL) {
9388 error = lookup_logmsg_ref(&merged_logmsg,
9389 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9390 if (error)
9391 goto done;
9394 cl_arg.editor = editor;
9395 cl_arg.cmdline_log = logmsg;
9396 cl_arg.prepared_log = prepared_logmsg;
9397 cl_arg.merged_log = merged_logmsg;
9398 cl_arg.non_interactive = non_interactive;
9399 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9400 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9401 if (!histedit_in_progress) {
9402 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9403 error = got_error(GOT_ERR_COMMIT_BRANCH);
9404 goto done;
9406 cl_arg.branch_name += 11;
9408 cl_arg.repo_path = got_repo_get_path(repo);
9409 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9410 allow_bad_symlinks, show_diff, commit_conflicts,
9411 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9412 if (error) {
9413 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9414 cl_arg.logmsg_path != NULL)
9415 preserve_logmsg = 1;
9416 goto done;
9419 error = got_object_id_str(&id_str, id);
9420 if (error)
9421 goto done;
9422 printf("Created commit %s\n", id_str);
9424 TAILQ_FOREACH(re, &refs, entry) {
9425 error = got_ref_delete(re->ref, repo);
9426 if (error)
9427 goto done;
9430 done:
9431 if (preserve_logmsg) {
9432 fprintf(stderr, "%s: log message preserved in %s\n",
9433 getprogname(), cl_arg.logmsg_path);
9434 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9435 error == NULL)
9436 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9437 free(cl_arg.logmsg_path);
9438 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9439 error = got_error_from_errno2("unlink", merged_logmsg);
9440 free(merged_logmsg);
9441 if (repo) {
9442 const struct got_error *close_err = got_repo_close(repo);
9443 if (error == NULL)
9444 error = close_err;
9446 if (worktree)
9447 got_worktree_close(worktree);
9448 if (pack_fds) {
9449 const struct got_error *pack_err =
9450 got_repo_pack_fds_close(pack_fds);
9451 if (error == NULL)
9452 error = pack_err;
9454 got_ref_list_free(&refs);
9455 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9456 free(cwd);
9457 free(id_str);
9458 free(gitconfig_path);
9459 free(editor);
9460 free(committer);
9461 free(prepared_logmsg);
9462 return error;
9465 __dead static void
9466 usage_send(void)
9468 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9469 "[-r repository-path] [-t tag] [remote-repository]\n",
9470 getprogname());
9471 exit(1);
9474 static void
9475 print_load_info(int print_colored, int print_found, int print_trees,
9476 int ncolored, int nfound, int ntrees)
9478 if (print_colored) {
9479 printf("%d commit%s colored", ncolored,
9480 ncolored == 1 ? "" : "s");
9482 if (print_found) {
9483 printf("%s%d object%s found",
9484 ncolored > 0 ? "; " : "",
9485 nfound, nfound == 1 ? "" : "s");
9487 if (print_trees) {
9488 printf("; %d tree%s scanned", ntrees,
9489 ntrees == 1 ? "" : "s");
9493 struct got_send_progress_arg {
9494 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9495 int verbosity;
9496 int last_ncolored;
9497 int last_nfound;
9498 int last_ntrees;
9499 int loading_done;
9500 int last_ncommits;
9501 int last_nobj_total;
9502 int last_p_deltify;
9503 int last_p_written;
9504 int last_p_sent;
9505 int printed_something;
9506 int sent_something;
9507 struct got_pathlist_head *delete_branches;
9510 static const struct got_error *
9511 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9512 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9513 int nobj_written, off_t bytes_sent, const char *refname,
9514 const char *errmsg, int success)
9516 struct got_send_progress_arg *a = arg;
9517 char scaled_packsize[FMT_SCALED_STRSIZE];
9518 char scaled_sent[FMT_SCALED_STRSIZE];
9519 int p_deltify = 0, p_written = 0, p_sent = 0;
9520 int print_colored = 0, print_found = 0, print_trees = 0;
9521 int print_searching = 0, print_total = 0;
9522 int print_deltify = 0, print_written = 0, print_sent = 0;
9524 if (a->verbosity < 0)
9525 return NULL;
9527 if (refname) {
9528 const char *status = success ? "accepted" : "rejected";
9530 if (success) {
9531 struct got_pathlist_entry *pe;
9532 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9533 const char *branchname = pe->path;
9534 if (got_path_cmp(branchname, refname,
9535 strlen(branchname), strlen(refname)) == 0) {
9536 status = "deleted";
9537 a->sent_something = 1;
9538 break;
9543 if (a->printed_something)
9544 putchar('\n');
9545 printf("Server has %s %s", status, refname);
9546 if (errmsg)
9547 printf(": %s", errmsg);
9548 a->printed_something = 1;
9549 return NULL;
9552 if (a->last_ncolored != ncolored) {
9553 print_colored = 1;
9554 a->last_ncolored = ncolored;
9557 if (a->last_nfound != nfound) {
9558 print_colored = 1;
9559 print_found = 1;
9560 a->last_nfound = nfound;
9563 if (a->last_ntrees != ntrees) {
9564 print_colored = 1;
9565 print_found = 1;
9566 print_trees = 1;
9567 a->last_ntrees = ntrees;
9570 if ((print_colored || print_found || print_trees) &&
9571 !a->loading_done) {
9572 printf("\r");
9573 print_load_info(print_colored, print_found, print_trees,
9574 ncolored, nfound, ntrees);
9575 a->printed_something = 1;
9576 fflush(stdout);
9577 return NULL;
9578 } else if (!a->loading_done) {
9579 printf("\r");
9580 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9581 printf("\n");
9582 a->loading_done = 1;
9585 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9586 return got_error_from_errno("fmt_scaled");
9587 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9588 return got_error_from_errno("fmt_scaled");
9590 if (a->last_ncommits != ncommits) {
9591 print_searching = 1;
9592 a->last_ncommits = ncommits;
9595 if (a->last_nobj_total != nobj_total) {
9596 print_searching = 1;
9597 print_total = 1;
9598 a->last_nobj_total = nobj_total;
9601 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9602 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9603 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9604 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9605 return got_error(GOT_ERR_NO_SPACE);
9608 if (nobj_deltify > 0 || nobj_written > 0) {
9609 if (nobj_deltify > 0) {
9610 p_deltify = (nobj_deltify * 100) / nobj_total;
9611 if (p_deltify != a->last_p_deltify) {
9612 a->last_p_deltify = p_deltify;
9613 print_searching = 1;
9614 print_total = 1;
9615 print_deltify = 1;
9618 if (nobj_written > 0) {
9619 p_written = (nobj_written * 100) / nobj_total;
9620 if (p_written != a->last_p_written) {
9621 a->last_p_written = p_written;
9622 print_searching = 1;
9623 print_total = 1;
9624 print_deltify = 1;
9625 print_written = 1;
9630 if (bytes_sent > 0) {
9631 p_sent = (bytes_sent * 100) / packfile_size;
9632 if (p_sent != a->last_p_sent) {
9633 a->last_p_sent = p_sent;
9634 print_searching = 1;
9635 print_total = 1;
9636 print_deltify = 1;
9637 print_written = 1;
9638 print_sent = 1;
9640 a->sent_something = 1;
9643 if (print_searching || print_total || print_deltify || print_written ||
9644 print_sent)
9645 printf("\r");
9646 if (print_searching)
9647 printf("packing %d reference%s", ncommits,
9648 ncommits == 1 ? "" : "s");
9649 if (print_total)
9650 printf("; %d object%s", nobj_total,
9651 nobj_total == 1 ? "" : "s");
9652 if (print_deltify)
9653 printf("; deltify: %d%%", p_deltify);
9654 if (print_sent)
9655 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9656 scaled_packsize, p_sent);
9657 else if (print_written)
9658 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9659 scaled_packsize, p_written);
9660 if (print_searching || print_total || print_deltify ||
9661 print_written || print_sent) {
9662 a->printed_something = 1;
9663 fflush(stdout);
9665 return NULL;
9668 static const struct got_error *
9669 cmd_send(int argc, char *argv[])
9671 const struct got_error *error = NULL;
9672 char *cwd = NULL, *repo_path = NULL;
9673 const char *remote_name;
9674 char *proto = NULL, *host = NULL, *port = NULL;
9675 char *repo_name = NULL, *server_path = NULL;
9676 const struct got_remote_repo *remotes, *remote = NULL;
9677 int nremotes, nbranches = 0, ndelete_branches = 0;
9678 struct got_repository *repo = NULL;
9679 struct got_worktree *worktree = NULL;
9680 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9681 struct got_pathlist_head branches;
9682 struct got_pathlist_head tags;
9683 struct got_reflist_head all_branches;
9684 struct got_reflist_head all_tags;
9685 struct got_pathlist_head delete_args;
9686 struct got_pathlist_head delete_branches;
9687 struct got_reflist_entry *re;
9688 struct got_pathlist_entry *pe;
9689 int i, ch, sendfd = -1, sendstatus;
9690 pid_t sendpid = -1;
9691 struct got_send_progress_arg spa;
9692 int verbosity = 0, overwrite_refs = 0;
9693 int send_all_branches = 0, send_all_tags = 0;
9694 struct got_reference *ref = NULL;
9695 int *pack_fds = NULL;
9697 TAILQ_INIT(&branches);
9698 TAILQ_INIT(&tags);
9699 TAILQ_INIT(&all_branches);
9700 TAILQ_INIT(&all_tags);
9701 TAILQ_INIT(&delete_args);
9702 TAILQ_INIT(&delete_branches);
9704 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9705 switch (ch) {
9706 case 'a':
9707 send_all_branches = 1;
9708 break;
9709 case 'b':
9710 error = got_pathlist_append(&branches, optarg, NULL);
9711 if (error)
9712 return error;
9713 nbranches++;
9714 break;
9715 case 'd':
9716 error = got_pathlist_append(&delete_args, optarg, NULL);
9717 if (error)
9718 return error;
9719 break;
9720 case 'f':
9721 overwrite_refs = 1;
9722 break;
9723 case 'q':
9724 verbosity = -1;
9725 break;
9726 case 'r':
9727 repo_path = realpath(optarg, NULL);
9728 if (repo_path == NULL)
9729 return got_error_from_errno2("realpath",
9730 optarg);
9731 got_path_strip_trailing_slashes(repo_path);
9732 break;
9733 case 'T':
9734 send_all_tags = 1;
9735 break;
9736 case 't':
9737 error = got_pathlist_append(&tags, optarg, NULL);
9738 if (error)
9739 return error;
9740 break;
9741 case 'v':
9742 if (verbosity < 0)
9743 verbosity = 0;
9744 else if (verbosity < 3)
9745 verbosity++;
9746 break;
9747 default:
9748 usage_send();
9749 /* NOTREACHED */
9752 argc -= optind;
9753 argv += optind;
9755 if (send_all_branches && !TAILQ_EMPTY(&branches))
9756 option_conflict('a', 'b');
9757 if (send_all_tags && !TAILQ_EMPTY(&tags))
9758 option_conflict('T', 't');
9761 if (argc == 0)
9762 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9763 else if (argc == 1)
9764 remote_name = argv[0];
9765 else
9766 usage_send();
9768 cwd = getcwd(NULL, 0);
9769 if (cwd == NULL) {
9770 error = got_error_from_errno("getcwd");
9771 goto done;
9774 error = got_repo_pack_fds_open(&pack_fds);
9775 if (error != NULL)
9776 goto done;
9778 if (repo_path == NULL) {
9779 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9780 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9781 goto done;
9782 else
9783 error = NULL;
9784 if (worktree) {
9785 repo_path =
9786 strdup(got_worktree_get_repo_path(worktree));
9787 if (repo_path == NULL)
9788 error = got_error_from_errno("strdup");
9789 if (error)
9790 goto done;
9791 } else {
9792 repo_path = strdup(cwd);
9793 if (repo_path == NULL) {
9794 error = got_error_from_errno("strdup");
9795 goto done;
9800 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9801 if (error)
9802 goto done;
9804 if (worktree) {
9805 worktree_conf = got_worktree_get_gotconfig(worktree);
9806 if (worktree_conf) {
9807 got_gotconfig_get_remotes(&nremotes, &remotes,
9808 worktree_conf);
9809 for (i = 0; i < nremotes; i++) {
9810 if (strcmp(remotes[i].name, remote_name) == 0) {
9811 remote = &remotes[i];
9812 break;
9817 if (remote == NULL) {
9818 repo_conf = got_repo_get_gotconfig(repo);
9819 if (repo_conf) {
9820 got_gotconfig_get_remotes(&nremotes, &remotes,
9821 repo_conf);
9822 for (i = 0; i < nremotes; i++) {
9823 if (strcmp(remotes[i].name, remote_name) == 0) {
9824 remote = &remotes[i];
9825 break;
9830 if (remote == NULL) {
9831 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9832 for (i = 0; i < nremotes; i++) {
9833 if (strcmp(remotes[i].name, remote_name) == 0) {
9834 remote = &remotes[i];
9835 break;
9839 if (remote == NULL) {
9840 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9841 goto done;
9844 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9845 &repo_name, remote->send_url);
9846 if (error)
9847 goto done;
9849 if (strcmp(proto, "git") == 0) {
9850 #ifndef PROFILE
9851 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9852 "sendfd dns inet unveil", NULL) == -1)
9853 err(1, "pledge");
9854 #endif
9855 } else if (strcmp(proto, "git+ssh") == 0 ||
9856 strcmp(proto, "ssh") == 0) {
9857 #ifndef PROFILE
9858 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9859 "sendfd unveil", NULL) == -1)
9860 err(1, "pledge");
9861 #endif
9862 } else if (strcmp(proto, "http") == 0 ||
9863 strcmp(proto, "git+http") == 0) {
9864 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9865 goto done;
9866 } else {
9867 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9868 goto done;
9871 error = got_dial_apply_unveil(proto);
9872 if (error)
9873 goto done;
9875 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9876 if (error)
9877 goto done;
9879 if (send_all_branches) {
9880 error = got_ref_list(&all_branches, repo, "refs/heads",
9881 got_ref_cmp_by_name, NULL);
9882 if (error)
9883 goto done;
9884 TAILQ_FOREACH(re, &all_branches, entry) {
9885 const char *branchname = got_ref_get_name(re->ref);
9886 error = got_pathlist_append(&branches,
9887 branchname, NULL);
9888 if (error)
9889 goto done;
9890 nbranches++;
9892 } else if (nbranches == 0) {
9893 for (i = 0; i < remote->nsend_branches; i++) {
9894 error = got_pathlist_append(&branches,
9895 remote->send_branches[i], NULL);
9896 if (error)
9897 goto done;
9901 if (send_all_tags) {
9902 error = got_ref_list(&all_tags, repo, "refs/tags",
9903 got_ref_cmp_by_name, NULL);
9904 if (error)
9905 goto done;
9906 TAILQ_FOREACH(re, &all_tags, entry) {
9907 const char *tagname = got_ref_get_name(re->ref);
9908 error = got_pathlist_append(&tags,
9909 tagname, NULL);
9910 if (error)
9911 goto done;
9916 * To prevent accidents only branches in refs/heads/ can be deleted
9917 * with 'got send -d'.
9918 * Deleting anything else requires local repository access or Git.
9920 TAILQ_FOREACH(pe, &delete_args, entry) {
9921 const char *branchname = pe->path;
9922 char *s;
9923 struct got_pathlist_entry *new;
9924 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9925 s = strdup(branchname);
9926 if (s == NULL) {
9927 error = got_error_from_errno("strdup");
9928 goto done;
9930 } else {
9931 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9932 error = got_error_from_errno("asprintf");
9933 goto done;
9936 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9937 if (error || new == NULL /* duplicate */)
9938 free(s);
9939 if (error)
9940 goto done;
9941 ndelete_branches++;
9944 if (nbranches == 0 && ndelete_branches == 0) {
9945 struct got_reference *head_ref;
9946 if (worktree)
9947 error = got_ref_open(&head_ref, repo,
9948 got_worktree_get_head_ref_name(worktree), 0);
9949 else
9950 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9951 if (error)
9952 goto done;
9953 if (got_ref_is_symbolic(head_ref)) {
9954 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9955 got_ref_close(head_ref);
9956 if (error)
9957 goto done;
9958 } else
9959 ref = head_ref;
9960 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9961 NULL);
9962 if (error)
9963 goto done;
9964 nbranches++;
9967 if (verbosity >= 0) {
9968 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9969 remote->name, proto, host,
9970 port ? ":" : "", port ? port : "",
9971 *server_path == '/' ? "" : "/", server_path);
9974 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9975 server_path, verbosity);
9976 if (error)
9977 goto done;
9979 memset(&spa, 0, sizeof(spa));
9980 spa.last_scaled_packsize[0] = '\0';
9981 spa.last_p_deltify = -1;
9982 spa.last_p_written = -1;
9983 spa.verbosity = verbosity;
9984 spa.delete_branches = &delete_branches;
9985 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9986 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9987 check_cancelled, NULL);
9988 if (spa.printed_something)
9989 putchar('\n');
9990 if (error)
9991 goto done;
9992 if (!spa.sent_something && verbosity >= 0)
9993 printf("Already up-to-date\n");
9994 done:
9995 if (sendpid > 0) {
9996 if (kill(sendpid, SIGTERM) == -1)
9997 error = got_error_from_errno("kill");
9998 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9999 error = got_error_from_errno("waitpid");
10001 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10002 error = got_error_from_errno("close");
10003 if (repo) {
10004 const struct got_error *close_err = got_repo_close(repo);
10005 if (error == NULL)
10006 error = close_err;
10008 if (worktree)
10009 got_worktree_close(worktree);
10010 if (pack_fds) {
10011 const struct got_error *pack_err =
10012 got_repo_pack_fds_close(pack_fds);
10013 if (error == NULL)
10014 error = pack_err;
10016 if (ref)
10017 got_ref_close(ref);
10018 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10019 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10020 got_ref_list_free(&all_branches);
10021 got_ref_list_free(&all_tags);
10022 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10023 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10024 free(cwd);
10025 free(repo_path);
10026 free(proto);
10027 free(host);
10028 free(port);
10029 free(server_path);
10030 free(repo_name);
10031 return error;
10035 * Print and if delete is set delete all ref_prefix references.
10036 * If wanted_ref is not NULL, only print or delete this reference.
10038 static const struct got_error *
10039 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10040 const char *wanted_ref, int delete, struct got_worktree *worktree,
10041 struct got_repository *repo)
10043 const struct got_error *err;
10044 struct got_pathlist_head paths;
10045 struct got_reflist_head refs;
10046 struct got_reflist_entry *re;
10047 struct got_reflist_object_id_map *refs_idmap = NULL;
10048 struct got_commit_object *commit = NULL;
10049 struct got_object_id *id = NULL;
10050 const char *header_prefix;
10051 char *uuidstr = NULL;
10052 int found = 0;
10054 TAILQ_INIT(&refs);
10055 TAILQ_INIT(&paths);
10057 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10058 if (err)
10059 goto done;
10061 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10062 if (err)
10063 goto done;
10065 if (worktree != NULL) {
10066 err = got_worktree_get_uuid(&uuidstr, worktree);
10067 if (err)
10068 goto done;
10071 if (wanted_ref) {
10072 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10073 wanted_ref += 11;
10076 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10077 header_prefix = "backout";
10078 else
10079 header_prefix = "cherrypick";
10081 TAILQ_FOREACH(re, &refs, entry) {
10082 const char *refname, *wt;
10084 refname = got_ref_get_name(re->ref);
10086 err = check_cancelled(NULL);
10087 if (err)
10088 goto done;
10090 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10091 refname += prefix_len + 1; /* skip '-' delimiter */
10092 else
10093 continue;
10095 wt = refname;
10097 if (worktree == NULL || strncmp(refname, uuidstr,
10098 GOT_WORKTREE_UUID_STRLEN) == 0)
10099 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10100 else
10101 continue;
10103 err = got_repo_match_object_id(&id, NULL, refname,
10104 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10105 if (err)
10106 goto done;
10108 err = got_object_open_as_commit(&commit, repo, id);
10109 if (err)
10110 goto done;
10112 if (wanted_ref)
10113 found = strncmp(wanted_ref, refname,
10114 strlen(wanted_ref)) == 0;
10115 if (wanted_ref && !found) {
10116 struct got_reflist_head *ci_refs;
10118 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10119 id);
10121 if (ci_refs) {
10122 char *refs_str = NULL;
10123 char const *r = NULL;
10125 err = build_refs_str(&refs_str, ci_refs, id,
10126 repo, 1);
10127 if (err)
10128 goto done;
10130 r = refs_str;
10131 while (r) {
10132 if (strncmp(r, wanted_ref,
10133 strlen(wanted_ref)) == 0) {
10134 found = 1;
10135 break;
10137 r = strchr(r, ' ');
10138 if (r)
10139 ++r;
10141 free(refs_str);
10145 if (wanted_ref == NULL || found) {
10146 if (delete) {
10147 err = got_ref_delete(re->ref, repo);
10148 if (err)
10149 goto done;
10150 printf("Deleted: ");
10151 err = print_commit_oneline(commit, id, repo,
10152 refs_idmap);
10153 } else {
10155 * Print paths modified by commit to help
10156 * associate commits with worktree changes.
10158 err = get_changed_paths(&paths, commit,
10159 repo, NULL);
10160 if (err)
10161 goto done;
10163 err = print_commit(commit, id, repo, NULL,
10164 &paths, NULL, 0, 0, refs_idmap, NULL,
10165 header_prefix);
10166 got_pathlist_free(&paths,
10167 GOT_PATHLIST_FREE_ALL);
10169 if (worktree == NULL)
10170 printf("work tree: %.*s\n\n",
10171 GOT_WORKTREE_UUID_STRLEN, wt);
10173 if (err || found)
10174 goto done;
10177 got_object_commit_close(commit);
10178 commit = NULL;
10179 free(id);
10180 id = NULL;
10183 if (wanted_ref != NULL && !found)
10184 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10186 done:
10187 free(id);
10188 free(uuidstr);
10189 got_ref_list_free(&refs);
10190 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10191 if (refs_idmap)
10192 got_reflist_object_id_map_free(refs_idmap);
10193 if (commit)
10194 got_object_commit_close(commit);
10195 return err;
10199 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10200 * identified by id for log messages to prepopulate the editor on commit.
10202 static const struct got_error *
10203 logmsg_ref(struct got_object_id *id, const char *prefix,
10204 struct got_worktree *worktree, struct got_repository *repo)
10206 const struct got_error *err = NULL;
10207 char *idstr, *ref = NULL, *refname = NULL;
10208 int histedit_in_progress;
10209 int rebase_in_progress, merge_in_progress;
10212 * Silenty refuse to create merge reference if any histedit, merge,
10213 * or rebase operation is in progress.
10215 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10216 worktree);
10217 if (err)
10218 return err;
10219 if (histedit_in_progress)
10220 return NULL;
10222 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10223 if (err)
10224 return err;
10225 if (rebase_in_progress)
10226 return NULL;
10228 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10229 repo);
10230 if (err)
10231 return err;
10232 if (merge_in_progress)
10233 return NULL;
10235 err = got_object_id_str(&idstr, id);
10236 if (err)
10237 return err;
10239 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10240 if (err)
10241 goto done;
10243 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10244 err = got_error_from_errno("asprintf");
10245 goto done;
10248 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10249 -1, repo);
10250 done:
10251 free(ref);
10252 free(idstr);
10253 free(refname);
10254 return err;
10257 __dead static void
10258 usage_cherrypick(void)
10260 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10261 getprogname());
10262 exit(1);
10265 static const struct got_error *
10266 cmd_cherrypick(int argc, char *argv[])
10268 const struct got_error *error = NULL;
10269 struct got_worktree *worktree = NULL;
10270 struct got_repository *repo = NULL;
10271 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10272 struct got_object_id *commit_id = NULL;
10273 struct got_commit_object *commit = NULL;
10274 struct got_object_qid *pid;
10275 int ch, list_refs = 0, remove_refs = 0;
10276 struct got_update_progress_arg upa;
10277 int *pack_fds = NULL;
10279 #ifndef PROFILE
10280 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10281 "unveil", NULL) == -1)
10282 err(1, "pledge");
10283 #endif
10285 while ((ch = getopt(argc, argv, "lX")) != -1) {
10286 switch (ch) {
10287 case 'l':
10288 list_refs = 1;
10289 break;
10290 case 'X':
10291 remove_refs = 1;
10292 break;
10293 default:
10294 usage_cherrypick();
10295 /* NOTREACHED */
10299 argc -= optind;
10300 argv += optind;
10302 if (list_refs || remove_refs) {
10303 if (argc != 0 && argc != 1)
10304 usage_cherrypick();
10305 } else if (argc != 1)
10306 usage_cherrypick();
10307 if (list_refs && remove_refs)
10308 option_conflict('l', 'X');
10310 cwd = getcwd(NULL, 0);
10311 if (cwd == NULL) {
10312 error = got_error_from_errno("getcwd");
10313 goto done;
10316 error = got_repo_pack_fds_open(&pack_fds);
10317 if (error != NULL)
10318 goto done;
10320 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10321 if (error) {
10322 if (list_refs || remove_refs) {
10323 if (error->code != GOT_ERR_NOT_WORKTREE)
10324 goto done;
10325 } else {
10326 if (error->code == GOT_ERR_NOT_WORKTREE)
10327 error = wrap_not_worktree_error(error,
10328 "cherrypick", cwd);
10329 goto done;
10333 error = got_repo_open(&repo,
10334 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10335 NULL, pack_fds);
10336 if (error != NULL)
10337 goto done;
10339 error = apply_unveil(got_repo_get_path(repo), 0,
10340 worktree ? got_worktree_get_root_path(worktree) : NULL);
10341 if (error)
10342 goto done;
10344 if (list_refs || remove_refs) {
10345 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10346 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10347 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10348 goto done;
10351 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10352 if (error != NULL)
10353 goto done;
10355 error = got_repo_match_object_id(&commit_id, NULL,
10356 keyword_idstr != NULL ? keyword_idstr : argv[0],
10357 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10358 if (error)
10359 goto done;
10360 error = got_object_id_str(&commit_id_str, commit_id);
10361 if (error)
10362 goto done;
10364 error = got_object_open_as_commit(&commit, repo, commit_id);
10365 if (error)
10366 goto done;
10367 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10368 memset(&upa, 0, sizeof(upa));
10369 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10370 commit_id, repo, update_progress, &upa, check_cancelled,
10371 NULL);
10372 if (error != NULL)
10373 goto done;
10375 if (upa.did_something) {
10376 error = logmsg_ref(commit_id,
10377 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10378 if (error)
10379 goto done;
10380 printf("Merged commit %s\n", commit_id_str);
10382 print_merge_progress_stats(&upa);
10383 done:
10384 free(cwd);
10385 free(keyword_idstr);
10386 if (commit)
10387 got_object_commit_close(commit);
10388 free(commit_id_str);
10389 if (worktree)
10390 got_worktree_close(worktree);
10391 if (repo) {
10392 const struct got_error *close_err = got_repo_close(repo);
10393 if (error == NULL)
10394 error = close_err;
10396 if (pack_fds) {
10397 const struct got_error *pack_err =
10398 got_repo_pack_fds_close(pack_fds);
10399 if (error == NULL)
10400 error = pack_err;
10403 return error;
10406 __dead static void
10407 usage_backout(void)
10409 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10410 exit(1);
10413 static const struct got_error *
10414 cmd_backout(int argc, char *argv[])
10416 const struct got_error *error = NULL;
10417 struct got_worktree *worktree = NULL;
10418 struct got_repository *repo = NULL;
10419 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10420 struct got_object_id *commit_id = NULL;
10421 struct got_commit_object *commit = NULL;
10422 struct got_object_qid *pid;
10423 int ch, list_refs = 0, remove_refs = 0;
10424 struct got_update_progress_arg upa;
10425 int *pack_fds = NULL;
10427 #ifndef PROFILE
10428 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10429 "unveil", NULL) == -1)
10430 err(1, "pledge");
10431 #endif
10433 while ((ch = getopt(argc, argv, "lX")) != -1) {
10434 switch (ch) {
10435 case 'l':
10436 list_refs = 1;
10437 break;
10438 case 'X':
10439 remove_refs = 1;
10440 break;
10441 default:
10442 usage_backout();
10443 /* NOTREACHED */
10447 argc -= optind;
10448 argv += optind;
10450 if (list_refs || remove_refs) {
10451 if (argc != 0 && argc != 1)
10452 usage_backout();
10453 } else if (argc != 1)
10454 usage_backout();
10455 if (list_refs && remove_refs)
10456 option_conflict('l', 'X');
10458 cwd = getcwd(NULL, 0);
10459 if (cwd == NULL) {
10460 error = got_error_from_errno("getcwd");
10461 goto done;
10464 error = got_repo_pack_fds_open(&pack_fds);
10465 if (error != NULL)
10466 goto done;
10468 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10469 if (error) {
10470 if (list_refs || remove_refs) {
10471 if (error->code != GOT_ERR_NOT_WORKTREE)
10472 goto done;
10473 } else {
10474 if (error->code == GOT_ERR_NOT_WORKTREE)
10475 error = wrap_not_worktree_error(error,
10476 "backout", cwd);
10477 goto done;
10481 error = got_repo_open(&repo,
10482 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10483 NULL, pack_fds);
10484 if (error != NULL)
10485 goto done;
10487 error = apply_unveil(got_repo_get_path(repo), 0,
10488 worktree ? got_worktree_get_root_path(worktree) : NULL);
10489 if (error)
10490 goto done;
10492 if (list_refs || remove_refs) {
10493 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10494 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10495 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10496 goto done;
10499 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10500 if (error != NULL)
10501 goto done;
10503 error = got_repo_match_object_id(&commit_id, NULL,
10504 keyword_idstr != NULL ? keyword_idstr : argv[0],
10505 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10506 if (error)
10507 goto done;
10508 error = got_object_id_str(&commit_id_str, commit_id);
10509 if (error)
10510 goto done;
10512 error = got_object_open_as_commit(&commit, repo, commit_id);
10513 if (error)
10514 goto done;
10515 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10516 if (pid == NULL) {
10517 error = got_error(GOT_ERR_ROOT_COMMIT);
10518 goto done;
10521 memset(&upa, 0, sizeof(upa));
10522 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10523 repo, update_progress, &upa, check_cancelled, NULL);
10524 if (error != NULL)
10525 goto done;
10527 if (upa.did_something) {
10528 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10529 worktree, repo);
10530 if (error)
10531 goto done;
10532 printf("Backed out commit %s\n", commit_id_str);
10534 print_merge_progress_stats(&upa);
10535 done:
10536 free(cwd);
10537 free(keyword_idstr);
10538 if (commit)
10539 got_object_commit_close(commit);
10540 free(commit_id_str);
10541 if (worktree)
10542 got_worktree_close(worktree);
10543 if (repo) {
10544 const struct got_error *close_err = got_repo_close(repo);
10545 if (error == NULL)
10546 error = close_err;
10548 if (pack_fds) {
10549 const struct got_error *pack_err =
10550 got_repo_pack_fds_close(pack_fds);
10551 if (error == NULL)
10552 error = pack_err;
10554 return error;
10557 __dead static void
10558 usage_rebase(void)
10560 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10561 exit(1);
10564 static void
10565 trim_logmsg(char *logmsg, int limit)
10567 char *nl;
10568 size_t len;
10570 len = strlen(logmsg);
10571 if (len > limit)
10572 len = limit;
10573 logmsg[len] = '\0';
10574 nl = strchr(logmsg, '\n');
10575 if (nl)
10576 *nl = '\0';
10579 static const struct got_error *
10580 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10582 const struct got_error *err;
10583 char *logmsg0 = NULL;
10584 const char *s;
10586 err = got_object_commit_get_logmsg(&logmsg0, commit);
10587 if (err)
10588 return err;
10590 s = logmsg0;
10591 while (isspace((unsigned char)s[0]))
10592 s++;
10594 *logmsg = strdup(s);
10595 if (*logmsg == NULL) {
10596 err = got_error_from_errno("strdup");
10597 goto done;
10600 trim_logmsg(*logmsg, limit);
10601 done:
10602 free(logmsg0);
10603 return err;
10606 static const struct got_error *
10607 show_rebase_merge_conflict(struct got_object_id *id,
10608 struct got_repository *repo)
10610 const struct got_error *err;
10611 struct got_commit_object *commit = NULL;
10612 char *id_str = NULL, *logmsg = NULL;
10614 err = got_object_open_as_commit(&commit, repo, id);
10615 if (err)
10616 return err;
10618 err = got_object_id_str(&id_str, id);
10619 if (err)
10620 goto done;
10622 id_str[12] = '\0';
10624 err = get_short_logmsg(&logmsg, 42, commit);
10625 if (err)
10626 goto done;
10628 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10629 done:
10630 free(id_str);
10631 got_object_commit_close(commit);
10632 free(logmsg);
10633 return err;
10636 static const struct got_error *
10637 show_rebase_progress(struct got_commit_object *commit,
10638 struct got_object_id *old_id, struct got_object_id *new_id)
10640 const struct got_error *err;
10641 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10643 err = got_object_id_str(&old_id_str, old_id);
10644 if (err)
10645 goto done;
10647 if (new_id) {
10648 err = got_object_id_str(&new_id_str, new_id);
10649 if (err)
10650 goto done;
10653 old_id_str[12] = '\0';
10654 if (new_id_str)
10655 new_id_str[12] = '\0';
10657 err = get_short_logmsg(&logmsg, 42, commit);
10658 if (err)
10659 goto done;
10661 printf("%s -> %s: %s\n", old_id_str,
10662 new_id_str ? new_id_str : "no-op change", logmsg);
10663 done:
10664 free(old_id_str);
10665 free(new_id_str);
10666 free(logmsg);
10667 return err;
10670 static const struct got_error *
10671 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10672 struct got_reference *branch, struct got_reference *tmp_branch,
10673 struct got_repository *repo, int create_backup)
10675 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10676 return got_worktree_rebase_complete(worktree, fileindex,
10677 tmp_branch, branch, repo, create_backup);
10680 static const struct got_error *
10681 rebase_commit(struct got_pathlist_head *merged_paths,
10682 struct got_worktree *worktree, struct got_fileindex *fileindex,
10683 struct got_reference *tmp_branch, const char *committer,
10684 struct got_object_id *commit_id, int allow_conflict,
10685 struct got_repository *repo)
10687 const struct got_error *error;
10688 struct got_commit_object *commit;
10689 struct got_object_id *new_commit_id;
10691 error = got_object_open_as_commit(&commit, repo, commit_id);
10692 if (error)
10693 return error;
10695 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10696 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10697 allow_conflict, repo);
10698 if (error) {
10699 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10700 goto done;
10701 error = show_rebase_progress(commit, commit_id, NULL);
10702 } else {
10703 error = show_rebase_progress(commit, commit_id, new_commit_id);
10704 free(new_commit_id);
10706 done:
10707 got_object_commit_close(commit);
10708 return error;
10711 struct check_path_prefix_arg {
10712 const char *path_prefix;
10713 size_t len;
10714 int errcode;
10717 static const struct got_error *
10718 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10719 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10720 struct got_object_id *id1, struct got_object_id *id2,
10721 const char *path1, const char *path2,
10722 mode_t mode1, mode_t mode2, struct got_repository *repo)
10724 struct check_path_prefix_arg *a = arg;
10726 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10727 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10728 return got_error(a->errcode);
10730 return NULL;
10733 static const struct got_error *
10734 check_path_prefix(struct got_object_id *parent_id,
10735 struct got_object_id *commit_id, const char *path_prefix,
10736 int errcode, struct got_repository *repo)
10738 const struct got_error *err;
10739 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10740 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10741 struct check_path_prefix_arg cpp_arg;
10743 if (got_path_is_root_dir(path_prefix))
10744 return NULL;
10746 err = got_object_open_as_commit(&commit, repo, commit_id);
10747 if (err)
10748 goto done;
10750 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10751 if (err)
10752 goto done;
10754 err = got_object_open_as_tree(&tree1, repo,
10755 got_object_commit_get_tree_id(parent_commit));
10756 if (err)
10757 goto done;
10759 err = got_object_open_as_tree(&tree2, repo,
10760 got_object_commit_get_tree_id(commit));
10761 if (err)
10762 goto done;
10764 cpp_arg.path_prefix = path_prefix;
10765 while (cpp_arg.path_prefix[0] == '/')
10766 cpp_arg.path_prefix++;
10767 cpp_arg.len = strlen(cpp_arg.path_prefix);
10768 cpp_arg.errcode = errcode;
10769 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10770 check_path_prefix_in_diff, &cpp_arg, 0);
10771 done:
10772 if (tree1)
10773 got_object_tree_close(tree1);
10774 if (tree2)
10775 got_object_tree_close(tree2);
10776 if (commit)
10777 got_object_commit_close(commit);
10778 if (parent_commit)
10779 got_object_commit_close(parent_commit);
10780 return err;
10783 static const struct got_error *
10784 collect_commits(struct got_object_id_queue *commits,
10785 struct got_object_id *initial_commit_id,
10786 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10787 const char *path_prefix, int path_prefix_errcode,
10788 struct got_repository *repo)
10790 const struct got_error *err = NULL;
10791 struct got_commit_graph *graph = NULL;
10792 struct got_object_id parent_id, commit_id;
10793 struct got_object_qid *qid;
10795 err = got_commit_graph_open(&graph, "/", 1);
10796 if (err)
10797 return err;
10799 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10800 check_cancelled, NULL);
10801 if (err)
10802 goto done;
10804 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10805 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10806 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10807 check_cancelled, NULL);
10808 if (err) {
10809 if (err->code == GOT_ERR_ITER_COMPLETED) {
10810 err = got_error_msg(GOT_ERR_ANCESTRY,
10811 "ran out of commits to rebase before "
10812 "youngest common ancestor commit has "
10813 "been reached?!?");
10815 goto done;
10816 } else {
10817 err = check_path_prefix(&parent_id, &commit_id,
10818 path_prefix, path_prefix_errcode, repo);
10819 if (err)
10820 goto done;
10822 err = got_object_qid_alloc(&qid, &commit_id);
10823 if (err)
10824 goto done;
10825 STAILQ_INSERT_HEAD(commits, qid, entry);
10827 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10830 done:
10831 got_commit_graph_close(graph);
10832 return err;
10835 static const struct got_error *
10836 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10838 const struct got_error *err = NULL;
10839 time_t committer_time;
10840 struct tm tm;
10841 char datebuf[11]; /* YYYY-MM-DD + NUL */
10842 char *author0 = NULL, *author, *smallerthan;
10843 char *logmsg0 = NULL, *logmsg, *newline;
10845 committer_time = got_object_commit_get_committer_time(commit);
10846 if (gmtime_r(&committer_time, &tm) == NULL)
10847 return got_error_from_errno("gmtime_r");
10848 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10849 return got_error(GOT_ERR_NO_SPACE);
10851 author0 = strdup(got_object_commit_get_author(commit));
10852 if (author0 == NULL)
10853 return got_error_from_errno("strdup");
10854 author = author0;
10855 smallerthan = strchr(author, '<');
10856 if (smallerthan && smallerthan[1] != '\0')
10857 author = smallerthan + 1;
10858 author[strcspn(author, "@>")] = '\0';
10860 err = got_object_commit_get_logmsg(&logmsg0, commit);
10861 if (err)
10862 goto done;
10863 logmsg = logmsg0;
10864 while (*logmsg == '\n')
10865 logmsg++;
10866 newline = strchr(logmsg, '\n');
10867 if (newline)
10868 *newline = '\0';
10870 if (asprintf(brief_str, "%s %s %s",
10871 datebuf, author, logmsg) == -1)
10872 err = got_error_from_errno("asprintf");
10873 done:
10874 free(author0);
10875 free(logmsg0);
10876 return err;
10879 static const struct got_error *
10880 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10881 struct got_repository *repo)
10883 const struct got_error *err;
10884 char *id_str;
10886 err = got_object_id_str(&id_str, id);
10887 if (err)
10888 return err;
10890 err = got_ref_delete(ref, repo);
10891 if (err)
10892 goto done;
10894 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10895 done:
10896 free(id_str);
10897 return err;
10900 static const struct got_error *
10901 print_backup_ref(const char *branch_name, const char *new_id_str,
10902 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10903 struct got_reflist_object_id_map *refs_idmap,
10904 struct got_repository *repo)
10906 const struct got_error *err = NULL;
10907 struct got_reflist_head *refs;
10908 char *refs_str = NULL;
10909 struct got_object_id *new_commit_id = NULL;
10910 struct got_commit_object *new_commit = NULL;
10911 char *new_commit_brief_str = NULL;
10912 struct got_object_id *yca_id = NULL;
10913 struct got_commit_object *yca_commit = NULL;
10914 char *yca_id_str = NULL, *yca_brief_str = NULL;
10915 char *custom_refs_str;
10917 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10918 return got_error_from_errno("asprintf");
10920 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10921 0, 0, refs_idmap, custom_refs_str, NULL);
10922 if (err)
10923 goto done;
10925 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10926 if (err)
10927 goto done;
10929 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10930 if (refs) {
10931 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10932 if (err)
10933 goto done;
10936 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10937 if (err)
10938 goto done;
10940 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10941 if (err)
10942 goto done;
10944 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10945 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10946 if (err)
10947 goto done;
10949 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10950 refs_str ? " (" : "", refs_str ? refs_str : "",
10951 refs_str ? ")" : "", new_commit_brief_str);
10952 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10953 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10954 free(refs_str);
10955 refs_str = NULL;
10957 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10958 if (err)
10959 goto done;
10961 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10962 if (err)
10963 goto done;
10965 err = got_object_id_str(&yca_id_str, yca_id);
10966 if (err)
10967 goto done;
10969 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10970 if (refs) {
10971 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10972 if (err)
10973 goto done;
10975 printf("history forked at %s%s%s%s\n %s\n",
10976 yca_id_str,
10977 refs_str ? " (" : "", refs_str ? refs_str : "",
10978 refs_str ? ")" : "", yca_brief_str);
10980 done:
10981 free(custom_refs_str);
10982 free(new_commit_id);
10983 free(refs_str);
10984 free(yca_id);
10985 free(yca_id_str);
10986 free(yca_brief_str);
10987 if (new_commit)
10988 got_object_commit_close(new_commit);
10989 if (yca_commit)
10990 got_object_commit_close(yca_commit);
10992 return err;
10995 static const struct got_error *
10996 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10997 struct got_repository *repo)
10999 const struct got_error *err;
11000 struct got_reflist_head refs;
11001 struct got_reflist_entry *re;
11002 char *uuidstr = NULL;
11003 static char msg[160];
11005 TAILQ_INIT(&refs);
11007 err = got_worktree_get_uuid(&uuidstr, worktree);
11008 if (err)
11009 goto done;
11011 err = got_ref_list(&refs, repo, "refs/got/worktree",
11012 got_ref_cmp_by_name, repo);
11013 if (err)
11014 goto done;
11016 TAILQ_FOREACH(re, &refs, entry) {
11017 const char *cmd, *refname, *type;
11019 refname = got_ref_get_name(re->ref);
11021 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11022 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11023 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11024 cmd = "cherrypick";
11025 type = "cherrypicked";
11026 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11027 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11028 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11029 cmd = "backout";
11030 type = "backed-out";
11031 } else
11032 continue;
11034 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11035 continue;
11037 snprintf(msg, sizeof(msg),
11038 "work tree has references created by %s commits which "
11039 "must be removed with 'got %s -X' before running the %s "
11040 "command", type, cmd, caller);
11041 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11042 goto done;
11045 done:
11046 free(uuidstr);
11047 got_ref_list_free(&refs);
11048 return err;
11051 static const struct got_error *
11052 process_backup_refs(const char *backup_ref_prefix,
11053 const char *wanted_branch_name,
11054 int delete, struct got_repository *repo)
11056 const struct got_error *err;
11057 struct got_reflist_head refs, backup_refs;
11058 struct got_reflist_entry *re;
11059 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11060 struct got_object_id *old_commit_id = NULL;
11061 char *branch_name = NULL;
11062 struct got_commit_object *old_commit = NULL;
11063 struct got_reflist_object_id_map *refs_idmap = NULL;
11064 int wanted_branch_found = 0;
11066 TAILQ_INIT(&refs);
11067 TAILQ_INIT(&backup_refs);
11069 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11070 if (err)
11071 return err;
11073 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11074 if (err)
11075 goto done;
11077 if (wanted_branch_name) {
11078 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11079 wanted_branch_name += 11;
11082 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11083 got_ref_cmp_by_commit_timestamp_descending, repo);
11084 if (err)
11085 goto done;
11087 TAILQ_FOREACH(re, &backup_refs, entry) {
11088 const char *refname = got_ref_get_name(re->ref);
11089 char *slash;
11091 err = check_cancelled(NULL);
11092 if (err)
11093 break;
11095 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11096 if (err)
11097 break;
11099 err = got_object_open_as_commit(&old_commit, repo,
11100 old_commit_id);
11101 if (err)
11102 break;
11104 if (strncmp(backup_ref_prefix, refname,
11105 backup_ref_prefix_len) == 0)
11106 refname += backup_ref_prefix_len;
11108 while (refname[0] == '/')
11109 refname++;
11111 branch_name = strdup(refname);
11112 if (branch_name == NULL) {
11113 err = got_error_from_errno("strdup");
11114 break;
11116 slash = strrchr(branch_name, '/');
11117 if (slash) {
11118 *slash = '\0';
11119 refname += strlen(branch_name) + 1;
11122 if (wanted_branch_name == NULL ||
11123 strcmp(wanted_branch_name, branch_name) == 0) {
11124 wanted_branch_found = 1;
11125 if (delete) {
11126 err = delete_backup_ref(re->ref,
11127 old_commit_id, repo);
11128 } else {
11129 err = print_backup_ref(branch_name, refname,
11130 old_commit_id, old_commit, refs_idmap,
11131 repo);
11133 if (err)
11134 break;
11137 free(old_commit_id);
11138 old_commit_id = NULL;
11139 free(branch_name);
11140 branch_name = NULL;
11141 got_object_commit_close(old_commit);
11142 old_commit = NULL;
11145 if (wanted_branch_name && !wanted_branch_found) {
11146 err = got_error_fmt(GOT_ERR_NOT_REF,
11147 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11149 done:
11150 if (refs_idmap)
11151 got_reflist_object_id_map_free(refs_idmap);
11152 got_ref_list_free(&refs);
11153 got_ref_list_free(&backup_refs);
11154 free(old_commit_id);
11155 free(branch_name);
11156 if (old_commit)
11157 got_object_commit_close(old_commit);
11158 return err;
11161 static const struct got_error *
11162 abort_progress(void *arg, unsigned char status, const char *path)
11165 * Unversioned files should not clutter progress output when
11166 * an operation is aborted.
11168 if (status == GOT_STATUS_UNVERSIONED)
11169 return NULL;
11171 return update_progress(arg, status, path);
11174 static const struct got_error *
11175 cmd_rebase(int argc, char *argv[])
11177 const struct got_error *error = NULL;
11178 struct got_worktree *worktree = NULL;
11179 struct got_repository *repo = NULL;
11180 struct got_fileindex *fileindex = NULL;
11181 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11182 struct got_reference *branch = NULL;
11183 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11184 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11185 struct got_object_id *resume_commit_id = NULL;
11186 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11187 struct got_object_id *head_commit_id = NULL;
11188 struct got_reference *head_ref = NULL;
11189 struct got_commit_object *commit = NULL;
11190 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11191 int histedit_in_progress = 0, merge_in_progress = 0;
11192 int create_backup = 1, list_backups = 0, delete_backups = 0;
11193 int allow_conflict = 0;
11194 struct got_object_id_queue commits;
11195 struct got_pathlist_head merged_paths;
11196 const struct got_object_id_queue *parent_ids;
11197 struct got_object_qid *qid, *pid;
11198 struct got_update_progress_arg upa;
11199 int *pack_fds = NULL;
11201 STAILQ_INIT(&commits);
11202 TAILQ_INIT(&merged_paths);
11203 memset(&upa, 0, sizeof(upa));
11205 #ifndef PROFILE
11206 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11207 "unveil", NULL) == -1)
11208 err(1, "pledge");
11209 #endif
11211 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11212 switch (ch) {
11213 case 'a':
11214 abort_rebase = 1;
11215 break;
11216 case 'C':
11217 allow_conflict = 1;
11218 break;
11219 case 'c':
11220 continue_rebase = 1;
11221 break;
11222 case 'l':
11223 list_backups = 1;
11224 break;
11225 case 'X':
11226 delete_backups = 1;
11227 break;
11228 default:
11229 usage_rebase();
11230 /* NOTREACHED */
11234 argc -= optind;
11235 argv += optind;
11237 if (list_backups) {
11238 if (abort_rebase)
11239 option_conflict('l', 'a');
11240 if (allow_conflict)
11241 option_conflict('l', 'C');
11242 if (continue_rebase)
11243 option_conflict('l', 'c');
11244 if (delete_backups)
11245 option_conflict('l', 'X');
11246 if (argc != 0 && argc != 1)
11247 usage_rebase();
11248 } else if (delete_backups) {
11249 if (abort_rebase)
11250 option_conflict('X', 'a');
11251 if (allow_conflict)
11252 option_conflict('X', 'C');
11253 if (continue_rebase)
11254 option_conflict('X', 'c');
11255 if (list_backups)
11256 option_conflict('l', 'X');
11257 if (argc != 0 && argc != 1)
11258 usage_rebase();
11259 } else if (allow_conflict) {
11260 if (abort_rebase)
11261 option_conflict('C', 'a');
11262 if (!continue_rebase)
11263 errx(1, "-C option requires -c");
11264 } else {
11265 if (abort_rebase && continue_rebase)
11266 usage_rebase();
11267 else if (abort_rebase || continue_rebase) {
11268 if (argc != 0)
11269 usage_rebase();
11270 } else if (argc != 1)
11271 usage_rebase();
11274 cwd = getcwd(NULL, 0);
11275 if (cwd == NULL) {
11276 error = got_error_from_errno("getcwd");
11277 goto done;
11280 error = got_repo_pack_fds_open(&pack_fds);
11281 if (error != NULL)
11282 goto done;
11284 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11285 if (error) {
11286 if (list_backups || delete_backups) {
11287 if (error->code != GOT_ERR_NOT_WORKTREE)
11288 goto done;
11289 } else {
11290 if (error->code == GOT_ERR_NOT_WORKTREE)
11291 error = wrap_not_worktree_error(error,
11292 "rebase", cwd);
11293 goto done;
11297 error = get_gitconfig_path(&gitconfig_path);
11298 if (error)
11299 goto done;
11300 error = got_repo_open(&repo,
11301 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11302 gitconfig_path, pack_fds);
11303 if (error != NULL)
11304 goto done;
11306 if (worktree != NULL && !list_backups && !delete_backups) {
11307 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11308 if (error)
11309 goto done;
11312 error = get_author(&committer, repo, worktree);
11313 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11314 goto done;
11316 error = apply_unveil(got_repo_get_path(repo), 0,
11317 worktree ? got_worktree_get_root_path(worktree) : NULL);
11318 if (error)
11319 goto done;
11321 if (list_backups || delete_backups) {
11322 error = process_backup_refs(
11323 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11324 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11325 goto done; /* nothing else to do */
11328 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11329 worktree);
11330 if (error)
11331 goto done;
11332 if (histedit_in_progress) {
11333 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11334 goto done;
11337 error = got_worktree_merge_in_progress(&merge_in_progress,
11338 worktree, repo);
11339 if (error)
11340 goto done;
11341 if (merge_in_progress) {
11342 error = got_error(GOT_ERR_MERGE_BUSY);
11343 goto done;
11346 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11347 if (error)
11348 goto done;
11350 if (abort_rebase) {
11351 if (!rebase_in_progress) {
11352 error = got_error(GOT_ERR_NOT_REBASING);
11353 goto done;
11355 error = got_worktree_rebase_continue(&resume_commit_id,
11356 &new_base_branch, &tmp_branch, &branch, &fileindex,
11357 worktree, repo);
11358 if (error)
11359 goto done;
11360 printf("Switching work tree to %s\n",
11361 got_ref_get_symref_target(new_base_branch));
11362 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11363 new_base_branch, abort_progress, &upa);
11364 if (error)
11365 goto done;
11366 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11367 print_merge_progress_stats(&upa);
11368 goto done; /* nothing else to do */
11371 if (continue_rebase) {
11372 if (!rebase_in_progress) {
11373 error = got_error(GOT_ERR_NOT_REBASING);
11374 goto done;
11376 error = got_worktree_rebase_continue(&resume_commit_id,
11377 &new_base_branch, &tmp_branch, &branch, &fileindex,
11378 worktree, repo);
11379 if (error)
11380 goto done;
11382 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11383 committer, resume_commit_id, allow_conflict, repo);
11384 if (error)
11385 goto done;
11387 yca_id = got_object_id_dup(resume_commit_id);
11388 if (yca_id == NULL) {
11389 error = got_error_from_errno("got_object_id_dup");
11390 goto done;
11392 } else {
11393 error = got_ref_open(&branch, repo, argv[0], 0);
11394 if (error != NULL)
11395 goto done;
11396 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11397 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11398 "will not rebase a branch which lives outside "
11399 "the \"refs/heads/\" reference namespace");
11400 goto done;
11404 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11405 if (error)
11406 goto done;
11408 if (!continue_rebase) {
11409 struct got_object_id *base_commit_id;
11411 error = got_ref_open(&head_ref, repo,
11412 got_worktree_get_head_ref_name(worktree), 0);
11413 if (error)
11414 goto done;
11415 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11416 if (error)
11417 goto done;
11418 base_commit_id = got_worktree_get_base_commit_id(worktree);
11419 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11420 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11421 goto done;
11424 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11425 base_commit_id, branch_head_commit_id, 1, repo,
11426 check_cancelled, NULL);
11427 if (error) {
11428 if (error->code == GOT_ERR_ANCESTRY) {
11429 error = got_error_msg(GOT_ERR_ANCESTRY,
11430 "specified branch shares no common "
11431 "ancestry with work tree's branch");
11433 goto done;
11436 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11437 struct got_pathlist_head paths;
11438 printf("%s is already based on %s\n",
11439 got_ref_get_name(branch),
11440 got_worktree_get_head_ref_name(worktree));
11441 error = switch_head_ref(branch, branch_head_commit_id,
11442 worktree, repo);
11443 if (error)
11444 goto done;
11445 error = got_worktree_set_base_commit_id(worktree, repo,
11446 branch_head_commit_id);
11447 if (error)
11448 goto done;
11449 TAILQ_INIT(&paths);
11450 error = got_pathlist_append(&paths, "", NULL);
11451 if (error)
11452 goto done;
11453 error = got_worktree_checkout_files(worktree,
11454 &paths, repo, update_progress, &upa,
11455 check_cancelled, NULL);
11456 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11457 if (error)
11458 goto done;
11459 if (upa.did_something) {
11460 char *id_str;
11461 error = got_object_id_str(&id_str,
11462 branch_head_commit_id);
11463 if (error)
11464 goto done;
11465 printf("Updated to %s: %s\n",
11466 got_worktree_get_head_ref_name(worktree),
11467 id_str);
11468 free(id_str);
11469 } else
11470 printf("Already up-to-date\n");
11471 print_update_progress_stats(&upa);
11472 goto done;
11476 commit_id = branch_head_commit_id;
11477 error = got_object_open_as_commit(&commit, repo, commit_id);
11478 if (error)
11479 goto done;
11481 parent_ids = got_object_commit_get_parent_ids(commit);
11482 pid = STAILQ_FIRST(parent_ids);
11483 if (pid) {
11484 error = collect_commits(&commits, commit_id, &pid->id,
11485 yca_id, got_worktree_get_path_prefix(worktree),
11486 GOT_ERR_REBASE_PATH, repo);
11487 if (error)
11488 goto done;
11491 got_object_commit_close(commit);
11492 commit = NULL;
11494 if (!continue_rebase) {
11495 error = got_worktree_rebase_prepare(&new_base_branch,
11496 &tmp_branch, &fileindex, worktree, branch, repo);
11497 if (error)
11498 goto done;
11501 if (STAILQ_EMPTY(&commits)) {
11502 if (continue_rebase) {
11503 error = rebase_complete(worktree, fileindex,
11504 branch, tmp_branch, repo, create_backup);
11505 goto done;
11506 } else {
11507 /* Fast-forward the reference of the branch. */
11508 struct got_object_id *new_head_commit_id;
11509 char *id_str;
11510 error = got_ref_resolve(&new_head_commit_id, repo,
11511 new_base_branch);
11512 if (error)
11513 goto done;
11514 error = got_object_id_str(&id_str, new_head_commit_id);
11515 if (error)
11516 goto done;
11517 printf("Forwarding %s to commit %s\n",
11518 got_ref_get_name(branch), id_str);
11519 free(id_str);
11520 error = got_ref_change_ref(branch,
11521 new_head_commit_id);
11522 if (error)
11523 goto done;
11524 /* No backup needed since objects did not change. */
11525 create_backup = 0;
11529 pid = NULL;
11530 STAILQ_FOREACH(qid, &commits, entry) {
11532 commit_id = &qid->id;
11533 parent_id = pid ? &pid->id : yca_id;
11534 pid = qid;
11536 memset(&upa, 0, sizeof(upa));
11537 error = got_worktree_rebase_merge_files(&merged_paths,
11538 worktree, fileindex, parent_id, commit_id, repo,
11539 update_progress, &upa, check_cancelled, NULL);
11540 if (error)
11541 goto done;
11543 print_merge_progress_stats(&upa);
11544 if (upa.conflicts > 0 || upa.missing > 0 ||
11545 upa.not_deleted > 0 || upa.unversioned > 0) {
11546 if (upa.conflicts > 0) {
11547 error = show_rebase_merge_conflict(&qid->id,
11548 repo);
11549 if (error)
11550 goto done;
11552 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11553 break;
11556 error = rebase_commit(&merged_paths, worktree, fileindex,
11557 tmp_branch, committer, commit_id, 0, repo);
11558 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11559 if (error)
11560 goto done;
11563 if (upa.conflicts > 0 || upa.missing > 0 ||
11564 upa.not_deleted > 0 || upa.unversioned > 0) {
11565 error = got_worktree_rebase_postpone(worktree, fileindex);
11566 if (error)
11567 goto done;
11568 if (upa.conflicts > 0 && upa.missing == 0 &&
11569 upa.not_deleted == 0 && upa.unversioned == 0) {
11570 error = got_error_msg(GOT_ERR_CONFLICTS,
11571 "conflicts must be resolved before rebasing "
11572 "can continue");
11573 } else if (upa.conflicts > 0) {
11574 error = got_error_msg(GOT_ERR_CONFLICTS,
11575 "conflicts must be resolved before rebasing "
11576 "can continue; changes destined for some "
11577 "files were not yet merged and should be "
11578 "merged manually if required before the "
11579 "rebase operation is continued");
11580 } else {
11581 error = got_error_msg(GOT_ERR_CONFLICTS,
11582 "changes destined for some files were not "
11583 "yet merged and should be merged manually "
11584 "if required before the rebase operation "
11585 "is continued");
11587 } else
11588 error = rebase_complete(worktree, fileindex, branch,
11589 tmp_branch, repo, create_backup);
11590 done:
11591 free(cwd);
11592 free(committer);
11593 free(gitconfig_path);
11594 got_object_id_queue_free(&commits);
11595 free(branch_head_commit_id);
11596 free(resume_commit_id);
11597 free(head_commit_id);
11598 free(yca_id);
11599 if (commit)
11600 got_object_commit_close(commit);
11601 if (branch)
11602 got_ref_close(branch);
11603 if (new_base_branch)
11604 got_ref_close(new_base_branch);
11605 if (tmp_branch)
11606 got_ref_close(tmp_branch);
11607 if (head_ref)
11608 got_ref_close(head_ref);
11609 if (worktree)
11610 got_worktree_close(worktree);
11611 if (repo) {
11612 const struct got_error *close_err = got_repo_close(repo);
11613 if (error == NULL)
11614 error = close_err;
11616 if (pack_fds) {
11617 const struct got_error *pack_err =
11618 got_repo_pack_fds_close(pack_fds);
11619 if (error == NULL)
11620 error = pack_err;
11622 return error;
11625 __dead static void
11626 usage_histedit(void)
11628 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11629 "[branch]\n", getprogname());
11630 exit(1);
11633 #define GOT_HISTEDIT_PICK 'p'
11634 #define GOT_HISTEDIT_EDIT 'e'
11635 #define GOT_HISTEDIT_FOLD 'f'
11636 #define GOT_HISTEDIT_DROP 'd'
11637 #define GOT_HISTEDIT_MESG 'm'
11639 static const struct got_histedit_cmd {
11640 unsigned char code;
11641 const char *name;
11642 const char *desc;
11643 } got_histedit_cmds[] = {
11644 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11645 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11646 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11647 "be used" },
11648 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11649 { GOT_HISTEDIT_MESG, "mesg",
11650 "single-line log message for commit above (open editor if empty)" },
11653 struct got_histedit_list_entry {
11654 TAILQ_ENTRY(got_histedit_list_entry) entry;
11655 struct got_object_id *commit_id;
11656 const struct got_histedit_cmd *cmd;
11657 char *logmsg;
11659 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11661 static const struct got_error *
11662 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11663 FILE *f, struct got_repository *repo)
11665 const struct got_error *err = NULL;
11666 char *logmsg = NULL, *id_str = NULL;
11667 struct got_commit_object *commit = NULL;
11668 int n;
11670 err = got_object_open_as_commit(&commit, repo, commit_id);
11671 if (err)
11672 goto done;
11674 err = get_short_logmsg(&logmsg, 34, commit);
11675 if (err)
11676 goto done;
11678 err = got_object_id_str(&id_str, commit_id);
11679 if (err)
11680 goto done;
11682 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11683 if (n < 0)
11684 err = got_ferror(f, GOT_ERR_IO);
11685 done:
11686 if (commit)
11687 got_object_commit_close(commit);
11688 free(id_str);
11689 free(logmsg);
11690 return err;
11693 static const struct got_error *
11694 histedit_write_commit_list(struct got_object_id_queue *commits,
11695 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11696 int edit_only, struct got_repository *repo)
11698 const struct got_error *err = NULL;
11699 struct got_object_qid *qid;
11700 const char *histedit_cmd = NULL;
11702 if (STAILQ_EMPTY(commits))
11703 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11705 STAILQ_FOREACH(qid, commits, entry) {
11706 histedit_cmd = got_histedit_cmds[0].name;
11707 if (drop_only)
11708 histedit_cmd = "drop";
11709 else if (edit_only)
11710 histedit_cmd = "edit";
11711 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11712 histedit_cmd = "fold";
11713 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11714 if (err)
11715 break;
11716 if (edit_logmsg_only) {
11717 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11718 if (n < 0) {
11719 err = got_ferror(f, GOT_ERR_IO);
11720 break;
11725 return err;
11728 static const struct got_error *
11729 write_cmd_list(FILE *f, const char *branch_name,
11730 struct got_object_id_queue *commits)
11732 const struct got_error *err = NULL;
11733 size_t i;
11734 int n;
11735 char *id_str;
11736 struct got_object_qid *qid;
11738 qid = STAILQ_FIRST(commits);
11739 err = got_object_id_str(&id_str, &qid->id);
11740 if (err)
11741 return err;
11743 n = fprintf(f,
11744 "# Editing the history of branch '%s' starting at\n"
11745 "# commit %s\n"
11746 "# Commits will be processed in order from top to "
11747 "bottom of this file.\n", branch_name, id_str);
11748 if (n < 0) {
11749 err = got_ferror(f, GOT_ERR_IO);
11750 goto done;
11753 n = fprintf(f, "# Available histedit commands:\n");
11754 if (n < 0) {
11755 err = got_ferror(f, GOT_ERR_IO);
11756 goto done;
11759 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11760 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11761 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11762 cmd->desc);
11763 if (n < 0) {
11764 err = got_ferror(f, GOT_ERR_IO);
11765 break;
11768 done:
11769 free(id_str);
11770 return err;
11773 static const struct got_error *
11774 histedit_syntax_error(int lineno)
11776 static char msg[42];
11777 int ret;
11779 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11780 lineno);
11781 if (ret < 0 || (size_t)ret >= sizeof(msg))
11782 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11784 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11787 static const struct got_error *
11788 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11789 char *logmsg, struct got_repository *repo)
11791 const struct got_error *err;
11792 struct got_commit_object *folded_commit = NULL;
11793 char *id_str, *folded_logmsg = NULL;
11795 err = got_object_id_str(&id_str, hle->commit_id);
11796 if (err)
11797 return err;
11799 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11800 if (err)
11801 goto done;
11803 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11804 if (err)
11805 goto done;
11806 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11807 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11808 folded_logmsg) == -1) {
11809 err = got_error_from_errno("asprintf");
11811 done:
11812 if (folded_commit)
11813 got_object_commit_close(folded_commit);
11814 free(id_str);
11815 free(folded_logmsg);
11816 return err;
11819 static struct got_histedit_list_entry *
11820 get_folded_commits(struct got_histedit_list_entry *hle)
11822 struct got_histedit_list_entry *prev, *folded = NULL;
11824 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11825 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11826 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11827 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11828 folded = prev;
11829 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11832 return folded;
11835 static const struct got_error *
11836 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11837 struct got_repository *repo)
11839 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11840 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11841 const struct got_error *err = NULL;
11842 struct got_commit_object *commit = NULL;
11843 int logmsg_len;
11844 int fd = -1;
11845 struct got_histedit_list_entry *folded = NULL;
11847 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11848 if (err)
11849 return err;
11851 folded = get_folded_commits(hle);
11852 if (folded) {
11853 while (folded != hle) {
11854 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11855 folded = TAILQ_NEXT(folded, entry);
11856 continue;
11858 err = append_folded_commit_msg(&new_msg, folded,
11859 logmsg, repo);
11860 if (err)
11861 goto done;
11862 free(logmsg);
11863 logmsg = new_msg;
11864 folded = TAILQ_NEXT(folded, entry);
11868 err = got_object_id_str(&id_str, hle->commit_id);
11869 if (err)
11870 goto done;
11871 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11872 if (err)
11873 goto done;
11874 logmsg_len = asprintf(&new_msg,
11875 "%s\n# original log message of commit %s: %s",
11876 logmsg ? logmsg : "", id_str, orig_logmsg);
11877 if (logmsg_len == -1) {
11878 err = got_error_from_errno("asprintf");
11879 goto done;
11881 free(logmsg);
11882 logmsg = new_msg;
11884 err = got_object_id_str(&id_str, hle->commit_id);
11885 if (err)
11886 goto done;
11888 err = got_opentemp_named_fd(&logmsg_path, &fd,
11889 GOT_TMPDIR_STR "/got-logmsg", "");
11890 if (err)
11891 goto done;
11893 if (write(fd, logmsg, logmsg_len) == -1) {
11894 err = got_error_from_errno2("write", logmsg_path);
11895 goto done;
11897 if (close(fd) == -1) {
11898 err = got_error_from_errno2("close", logmsg_path);
11899 goto done;
11901 fd = -1;
11903 err = get_editor(&editor);
11904 if (err)
11905 goto done;
11907 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11908 logmsg_len, 0);
11909 if (err) {
11910 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11911 goto done;
11912 err = NULL;
11913 hle->logmsg = strdup(new_msg);
11914 if (hle->logmsg == NULL)
11915 err = got_error_from_errno("strdup");
11917 done:
11918 if (fd != -1 && close(fd) == -1 && err == NULL)
11919 err = got_error_from_errno2("close", logmsg_path);
11920 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11921 err = got_error_from_errno2("unlink", logmsg_path);
11922 free(logmsg_path);
11923 free(logmsg);
11924 free(orig_logmsg);
11925 free(editor);
11926 if (commit)
11927 got_object_commit_close(commit);
11928 return err;
11931 static const struct got_error *
11932 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11933 FILE *f, struct got_repository *repo)
11935 const struct got_error *err = NULL;
11936 char *line = NULL, *p, *end;
11937 size_t i, linesize = 0;
11938 ssize_t linelen;
11939 int lineno = 0, lastcmd = -1;
11940 const struct got_histedit_cmd *cmd;
11941 struct got_object_id *commit_id = NULL;
11942 struct got_histedit_list_entry *hle = NULL;
11944 for (;;) {
11945 linelen = getline(&line, &linesize, f);
11946 if (linelen == -1) {
11947 const struct got_error *getline_err;
11948 if (feof(f))
11949 break;
11950 getline_err = got_error_from_errno("getline");
11951 err = got_ferror(f, getline_err->code);
11952 break;
11954 lineno++;
11955 p = line;
11956 while (isspace((unsigned char)p[0]))
11957 p++;
11958 if (p[0] == '#' || p[0] == '\0')
11959 continue;
11960 cmd = NULL;
11961 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11962 cmd = &got_histedit_cmds[i];
11963 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11964 isspace((unsigned char)p[strlen(cmd->name)])) {
11965 p += strlen(cmd->name);
11966 break;
11968 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11969 p++;
11970 break;
11973 if (i == nitems(got_histedit_cmds)) {
11974 err = histedit_syntax_error(lineno);
11975 break;
11977 while (isspace((unsigned char)p[0]))
11978 p++;
11979 if (cmd->code == GOT_HISTEDIT_MESG) {
11980 if (lastcmd != GOT_HISTEDIT_PICK &&
11981 lastcmd != GOT_HISTEDIT_EDIT) {
11982 err = got_error(GOT_ERR_HISTEDIT_CMD);
11983 break;
11985 if (p[0] == '\0') {
11986 err = histedit_edit_logmsg(hle, repo);
11987 if (err)
11988 break;
11989 } else {
11990 hle->logmsg = strdup(p);
11991 if (hle->logmsg == NULL) {
11992 err = got_error_from_errno("strdup");
11993 break;
11996 lastcmd = cmd->code;
11997 continue;
11998 } else {
11999 end = p;
12000 while (end[0] && !isspace((unsigned char)end[0]))
12001 end++;
12002 *end = '\0';
12004 err = got_object_resolve_id_str(&commit_id, repo, p);
12005 if (err) {
12006 /* override error code */
12007 err = histedit_syntax_error(lineno);
12008 break;
12011 hle = malloc(sizeof(*hle));
12012 if (hle == NULL) {
12013 err = got_error_from_errno("malloc");
12014 break;
12016 hle->cmd = cmd;
12017 hle->commit_id = commit_id;
12018 hle->logmsg = NULL;
12019 commit_id = NULL;
12020 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12021 lastcmd = cmd->code;
12024 free(line);
12025 free(commit_id);
12026 return err;
12029 static const struct got_error *
12030 histedit_check_script(struct got_histedit_list *histedit_cmds,
12031 struct got_object_id_queue *commits, struct got_repository *repo)
12033 const struct got_error *err = NULL;
12034 struct got_object_qid *qid;
12035 struct got_histedit_list_entry *hle;
12036 static char msg[92];
12037 char *id_str;
12039 if (TAILQ_EMPTY(histedit_cmds))
12040 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12041 "histedit script contains no commands");
12042 if (STAILQ_EMPTY(commits))
12043 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12045 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12046 struct got_histedit_list_entry *hle2;
12047 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12048 if (hle == hle2)
12049 continue;
12050 if (got_object_id_cmp(hle->commit_id,
12051 hle2->commit_id) != 0)
12052 continue;
12053 err = got_object_id_str(&id_str, hle->commit_id);
12054 if (err)
12055 return err;
12056 snprintf(msg, sizeof(msg), "commit %s is listed "
12057 "more than once in histedit script", id_str);
12058 free(id_str);
12059 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12063 STAILQ_FOREACH(qid, commits, entry) {
12064 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12065 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12066 break;
12068 if (hle == NULL) {
12069 err = got_object_id_str(&id_str, &qid->id);
12070 if (err)
12071 return err;
12072 snprintf(msg, sizeof(msg),
12073 "commit %s missing from histedit script", id_str);
12074 free(id_str);
12075 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12079 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12080 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12081 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12082 "last commit in histedit script cannot be folded");
12084 return NULL;
12087 static const struct got_error *
12088 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12089 const char *path, struct got_object_id_queue *commits,
12090 struct got_repository *repo)
12092 const struct got_error *err = NULL;
12093 struct stat st, st2;
12094 struct timespec timeout;
12095 char *editor;
12096 FILE *f = NULL;
12098 err = get_editor(&editor);
12099 if (err)
12100 return err;
12102 if (stat(path, &st) == -1) {
12103 err = got_error_from_errno2("stat", path);
12104 goto done;
12107 if (spawn_editor(editor, path) == -1) {
12108 err = got_error_from_errno("failed spawning editor");
12109 goto done;
12112 timeout.tv_sec = 0;
12113 timeout.tv_nsec = 1;
12114 nanosleep(&timeout, NULL);
12116 if (stat(path, &st2) == -1) {
12117 err = got_error_from_errno2("stat", path);
12118 goto done;
12121 if (st.st_size == st2.st_size &&
12122 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12123 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12124 "no changes made to histedit script, aborting");
12125 goto done;
12128 f = fopen(path, "re");
12129 if (f == NULL) {
12130 err = got_error_from_errno("fopen");
12131 goto done;
12133 err = histedit_parse_list(histedit_cmds, f, repo);
12134 if (err)
12135 goto done;
12137 err = histedit_check_script(histedit_cmds, commits, repo);
12138 done:
12139 if (f && fclose(f) == EOF && err == NULL)
12140 err = got_error_from_errno("fclose");
12141 free(editor);
12142 return err;
12145 static const struct got_error *
12146 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12147 struct got_object_id_queue *, const char *, const char *,
12148 struct got_repository *);
12150 static const struct got_error *
12151 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12152 struct got_object_id_queue *commits, const char *branch_name,
12153 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12154 struct got_repository *repo)
12156 const struct got_error *err;
12157 FILE *f = NULL;
12158 char *path = NULL;
12160 err = got_opentemp_named(&path, &f, "got-histedit", "");
12161 if (err)
12162 return err;
12164 err = write_cmd_list(f, branch_name, commits);
12165 if (err)
12166 goto done;
12168 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12169 fold_only, drop_only, edit_only, repo);
12170 if (err)
12171 goto done;
12173 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12174 rewind(f);
12175 err = histedit_parse_list(histedit_cmds, f, repo);
12176 } else {
12177 if (fclose(f) == EOF) {
12178 err = got_error_from_errno("fclose");
12179 goto done;
12181 f = NULL;
12182 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12183 if (err) {
12184 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12185 err->code != GOT_ERR_HISTEDIT_CMD)
12186 goto done;
12187 err = histedit_edit_list_retry(histedit_cmds, err,
12188 commits, path, branch_name, repo);
12191 done:
12192 if (f && fclose(f) == EOF && err == NULL)
12193 err = got_error_from_errno("fclose");
12194 if (path && unlink(path) != 0 && err == NULL)
12195 err = got_error_from_errno2("unlink", path);
12196 free(path);
12197 return err;
12200 static const struct got_error *
12201 histedit_save_list(struct got_histedit_list *histedit_cmds,
12202 struct got_worktree *worktree, struct got_repository *repo)
12204 const struct got_error *err = NULL;
12205 char *path = NULL;
12206 FILE *f = NULL;
12207 struct got_histedit_list_entry *hle;
12209 err = got_worktree_get_histedit_script_path(&path, worktree);
12210 if (err)
12211 return err;
12213 f = fopen(path, "we");
12214 if (f == NULL) {
12215 err = got_error_from_errno2("fopen", path);
12216 goto done;
12218 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12219 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12220 repo);
12221 if (err)
12222 break;
12224 if (hle->logmsg) {
12225 int n = fprintf(f, "%c %s\n",
12226 GOT_HISTEDIT_MESG, hle->logmsg);
12227 if (n < 0) {
12228 err = got_ferror(f, GOT_ERR_IO);
12229 break;
12233 done:
12234 if (f && fclose(f) == EOF && err == NULL)
12235 err = got_error_from_errno("fclose");
12236 free(path);
12237 return err;
12240 static void
12241 histedit_free_list(struct got_histedit_list *histedit_cmds)
12243 struct got_histedit_list_entry *hle;
12245 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12246 TAILQ_REMOVE(histedit_cmds, hle, entry);
12247 free(hle);
12251 static const struct got_error *
12252 histedit_load_list(struct got_histedit_list *histedit_cmds,
12253 const char *path, struct got_repository *repo)
12255 const struct got_error *err = NULL;
12256 FILE *f = NULL;
12258 f = fopen(path, "re");
12259 if (f == NULL) {
12260 err = got_error_from_errno2("fopen", path);
12261 goto done;
12264 err = histedit_parse_list(histedit_cmds, f, repo);
12265 done:
12266 if (f && fclose(f) == EOF && err == NULL)
12267 err = got_error_from_errno("fclose");
12268 return err;
12271 static const struct got_error *
12272 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12273 const struct got_error *edit_err, struct got_object_id_queue *commits,
12274 const char *path, const char *branch_name, struct got_repository *repo)
12276 const struct got_error *err = NULL, *prev_err = edit_err;
12277 int resp = ' ';
12279 while (resp != 'c' && resp != 'r' && resp != 'a') {
12280 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12281 "or (a)bort: ", getprogname(), prev_err->msg);
12282 resp = getchar();
12283 if (resp == '\n')
12284 resp = getchar();
12285 if (resp == 'c') {
12286 histedit_free_list(histedit_cmds);
12287 err = histedit_run_editor(histedit_cmds, path, commits,
12288 repo);
12289 if (err) {
12290 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12291 err->code != GOT_ERR_HISTEDIT_CMD)
12292 break;
12293 prev_err = err;
12294 resp = ' ';
12295 continue;
12297 break;
12298 } else if (resp == 'r') {
12299 histedit_free_list(histedit_cmds);
12300 err = histedit_edit_script(histedit_cmds,
12301 commits, branch_name, 0, 0, 0, 0, repo);
12302 if (err) {
12303 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12304 err->code != GOT_ERR_HISTEDIT_CMD)
12305 break;
12306 prev_err = err;
12307 resp = ' ';
12308 continue;
12310 break;
12311 } else if (resp == 'a') {
12312 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12313 break;
12314 } else
12315 printf("invalid response '%c'\n", resp);
12318 return err;
12321 static const struct got_error *
12322 histedit_complete(struct got_worktree *worktree,
12323 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12324 struct got_reference *branch, struct got_repository *repo)
12326 printf("Switching work tree to %s\n",
12327 got_ref_get_symref_target(branch));
12328 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12329 branch, repo);
12332 static const struct got_error *
12333 show_histedit_progress(struct got_commit_object *commit,
12334 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12336 const struct got_error *err;
12337 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12339 err = got_object_id_str(&old_id_str, hle->commit_id);
12340 if (err)
12341 goto done;
12343 if (new_id) {
12344 err = got_object_id_str(&new_id_str, new_id);
12345 if (err)
12346 goto done;
12349 old_id_str[12] = '\0';
12350 if (new_id_str)
12351 new_id_str[12] = '\0';
12353 if (hle->logmsg) {
12354 logmsg = strdup(hle->logmsg);
12355 if (logmsg == NULL) {
12356 err = got_error_from_errno("strdup");
12357 goto done;
12359 trim_logmsg(logmsg, 42);
12360 } else {
12361 err = get_short_logmsg(&logmsg, 42, commit);
12362 if (err)
12363 goto done;
12366 switch (hle->cmd->code) {
12367 case GOT_HISTEDIT_PICK:
12368 case GOT_HISTEDIT_EDIT:
12369 printf("%s -> %s: %s\n", old_id_str,
12370 new_id_str ? new_id_str : "no-op change", logmsg);
12371 break;
12372 case GOT_HISTEDIT_DROP:
12373 case GOT_HISTEDIT_FOLD:
12374 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12375 logmsg);
12376 break;
12377 default:
12378 break;
12380 done:
12381 free(old_id_str);
12382 free(new_id_str);
12383 return err;
12386 static const struct got_error *
12387 histedit_commit(struct got_pathlist_head *merged_paths,
12388 struct got_worktree *worktree, struct got_fileindex *fileindex,
12389 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12390 const char *committer, int allow_conflict, struct got_repository *repo)
12392 const struct got_error *err;
12393 struct got_commit_object *commit;
12394 struct got_object_id *new_commit_id;
12396 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12397 && hle->logmsg == NULL) {
12398 err = histedit_edit_logmsg(hle, repo);
12399 if (err)
12400 return err;
12403 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12404 if (err)
12405 return err;
12407 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12408 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12409 hle->logmsg, allow_conflict, repo);
12410 if (err) {
12411 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12412 goto done;
12413 err = show_histedit_progress(commit, hle, NULL);
12414 } else {
12415 err = show_histedit_progress(commit, hle, new_commit_id);
12416 free(new_commit_id);
12418 done:
12419 got_object_commit_close(commit);
12420 return err;
12423 static const struct got_error *
12424 histedit_skip_commit(struct got_histedit_list_entry *hle,
12425 struct got_worktree *worktree, struct got_repository *repo)
12427 const struct got_error *error;
12428 struct got_commit_object *commit;
12430 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12431 repo);
12432 if (error)
12433 return error;
12435 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12436 if (error)
12437 return error;
12439 error = show_histedit_progress(commit, hle, NULL);
12440 got_object_commit_close(commit);
12441 return error;
12444 static const struct got_error *
12445 check_local_changes(void *arg, unsigned char status,
12446 unsigned char staged_status, const char *path,
12447 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12448 struct got_object_id *commit_id, int dirfd, const char *de_name)
12450 int *have_local_changes = arg;
12452 switch (status) {
12453 case GOT_STATUS_ADD:
12454 case GOT_STATUS_DELETE:
12455 case GOT_STATUS_MODIFY:
12456 case GOT_STATUS_CONFLICT:
12457 *have_local_changes = 1;
12458 return got_error(GOT_ERR_CANCELLED);
12459 default:
12460 break;
12463 switch (staged_status) {
12464 case GOT_STATUS_ADD:
12465 case GOT_STATUS_DELETE:
12466 case GOT_STATUS_MODIFY:
12467 *have_local_changes = 1;
12468 return got_error(GOT_ERR_CANCELLED);
12469 default:
12470 break;
12473 return NULL;
12476 static const struct got_error *
12477 cmd_histedit(int argc, char *argv[])
12479 const struct got_error *error = NULL;
12480 struct got_worktree *worktree = NULL;
12481 struct got_fileindex *fileindex = NULL;
12482 struct got_repository *repo = NULL;
12483 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12484 struct got_reference *branch = NULL;
12485 struct got_reference *tmp_branch = NULL;
12486 struct got_object_id *resume_commit_id = NULL;
12487 struct got_object_id *base_commit_id = NULL;
12488 struct got_object_id *head_commit_id = NULL;
12489 struct got_commit_object *commit = NULL;
12490 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12491 struct got_update_progress_arg upa;
12492 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12493 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12494 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12495 const char *edit_script_path = NULL;
12496 struct got_object_id_queue commits;
12497 struct got_pathlist_head merged_paths;
12498 const struct got_object_id_queue *parent_ids;
12499 struct got_object_qid *pid;
12500 struct got_histedit_list histedit_cmds;
12501 struct got_histedit_list_entry *hle;
12502 int *pack_fds = NULL;
12504 STAILQ_INIT(&commits);
12505 TAILQ_INIT(&histedit_cmds);
12506 TAILQ_INIT(&merged_paths);
12507 memset(&upa, 0, sizeof(upa));
12509 #ifndef PROFILE
12510 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12511 "unveil", NULL) == -1)
12512 err(1, "pledge");
12513 #endif
12515 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12516 switch (ch) {
12517 case 'a':
12518 abort_edit = 1;
12519 break;
12520 case 'C':
12521 allow_conflict = 1;
12522 break;
12523 case 'c':
12524 continue_edit = 1;
12525 break;
12526 case 'd':
12527 drop_only = 1;
12528 break;
12529 case 'e':
12530 edit_only = 1;
12531 break;
12532 case 'F':
12533 edit_script_path = optarg;
12534 break;
12535 case 'f':
12536 fold_only = 1;
12537 break;
12538 case 'l':
12539 list_backups = 1;
12540 break;
12541 case 'm':
12542 edit_logmsg_only = 1;
12543 break;
12544 case 'X':
12545 delete_backups = 1;
12546 break;
12547 default:
12548 usage_histedit();
12549 /* NOTREACHED */
12553 argc -= optind;
12554 argv += optind;
12556 if (abort_edit && allow_conflict)
12557 option_conflict('a', 'C');
12558 if (abort_edit && continue_edit)
12559 option_conflict('a', 'c');
12560 if (edit_script_path && allow_conflict)
12561 option_conflict('F', 'C');
12562 if (edit_script_path && edit_logmsg_only)
12563 option_conflict('F', 'm');
12564 if (abort_edit && edit_logmsg_only)
12565 option_conflict('a', 'm');
12566 if (edit_logmsg_only && allow_conflict)
12567 option_conflict('m', 'C');
12568 if (continue_edit && edit_logmsg_only)
12569 option_conflict('c', 'm');
12570 if (abort_edit && fold_only)
12571 option_conflict('a', 'f');
12572 if (fold_only && allow_conflict)
12573 option_conflict('f', 'C');
12574 if (continue_edit && fold_only)
12575 option_conflict('c', 'f');
12576 if (fold_only && edit_logmsg_only)
12577 option_conflict('f', 'm');
12578 if (edit_script_path && fold_only)
12579 option_conflict('F', 'f');
12580 if (abort_edit && edit_only)
12581 option_conflict('a', 'e');
12582 if (continue_edit && edit_only)
12583 option_conflict('c', 'e');
12584 if (edit_only && edit_logmsg_only)
12585 option_conflict('e', 'm');
12586 if (edit_script_path && edit_only)
12587 option_conflict('F', 'e');
12588 if (fold_only && edit_only)
12589 option_conflict('f', 'e');
12590 if (drop_only && abort_edit)
12591 option_conflict('d', 'a');
12592 if (drop_only && allow_conflict)
12593 option_conflict('d', 'C');
12594 if (drop_only && continue_edit)
12595 option_conflict('d', 'c');
12596 if (drop_only && edit_logmsg_only)
12597 option_conflict('d', 'm');
12598 if (drop_only && edit_only)
12599 option_conflict('d', 'e');
12600 if (drop_only && edit_script_path)
12601 option_conflict('d', 'F');
12602 if (drop_only && fold_only)
12603 option_conflict('d', 'f');
12604 if (list_backups) {
12605 if (abort_edit)
12606 option_conflict('l', 'a');
12607 if (allow_conflict)
12608 option_conflict('l', 'C');
12609 if (continue_edit)
12610 option_conflict('l', 'c');
12611 if (edit_script_path)
12612 option_conflict('l', 'F');
12613 if (edit_logmsg_only)
12614 option_conflict('l', 'm');
12615 if (drop_only)
12616 option_conflict('l', 'd');
12617 if (fold_only)
12618 option_conflict('l', 'f');
12619 if (edit_only)
12620 option_conflict('l', 'e');
12621 if (delete_backups)
12622 option_conflict('l', 'X');
12623 if (argc != 0 && argc != 1)
12624 usage_histedit();
12625 } else if (delete_backups) {
12626 if (abort_edit)
12627 option_conflict('X', 'a');
12628 if (allow_conflict)
12629 option_conflict('X', 'C');
12630 if (continue_edit)
12631 option_conflict('X', 'c');
12632 if (drop_only)
12633 option_conflict('X', 'd');
12634 if (edit_script_path)
12635 option_conflict('X', 'F');
12636 if (edit_logmsg_only)
12637 option_conflict('X', 'm');
12638 if (fold_only)
12639 option_conflict('X', 'f');
12640 if (edit_only)
12641 option_conflict('X', 'e');
12642 if (list_backups)
12643 option_conflict('X', 'l');
12644 if (argc != 0 && argc != 1)
12645 usage_histedit();
12646 } else if (allow_conflict && !continue_edit)
12647 errx(1, "-C option requires -c");
12648 else if (argc != 0)
12649 usage_histedit();
12652 * This command cannot apply unveil(2) in all cases because the
12653 * user may choose to run an editor to edit the histedit script
12654 * and to edit individual commit log messages.
12655 * unveil(2) traverses exec(2); if an editor is used we have to
12656 * apply unveil after edit script and log messages have been written.
12657 * XXX TODO: Make use of unveil(2) where possible.
12660 cwd = getcwd(NULL, 0);
12661 if (cwd == NULL) {
12662 error = got_error_from_errno("getcwd");
12663 goto done;
12666 error = got_repo_pack_fds_open(&pack_fds);
12667 if (error != NULL)
12668 goto done;
12670 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12671 if (error) {
12672 if (list_backups || delete_backups) {
12673 if (error->code != GOT_ERR_NOT_WORKTREE)
12674 goto done;
12675 } else {
12676 if (error->code == GOT_ERR_NOT_WORKTREE)
12677 error = wrap_not_worktree_error(error,
12678 "histedit", cwd);
12679 goto done;
12683 if (list_backups || delete_backups) {
12684 error = got_repo_open(&repo,
12685 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12686 NULL, pack_fds);
12687 if (error != NULL)
12688 goto done;
12689 error = apply_unveil(got_repo_get_path(repo), 0,
12690 worktree ? got_worktree_get_root_path(worktree) : NULL);
12691 if (error)
12692 goto done;
12693 error = process_backup_refs(
12694 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12695 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12696 goto done; /* nothing else to do */
12699 error = get_gitconfig_path(&gitconfig_path);
12700 if (error)
12701 goto done;
12702 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12703 gitconfig_path, pack_fds);
12704 if (error != NULL)
12705 goto done;
12707 if (worktree != NULL && !list_backups && !delete_backups) {
12708 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12709 if (error)
12710 goto done;
12713 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12714 if (error)
12715 goto done;
12716 if (rebase_in_progress) {
12717 error = got_error(GOT_ERR_REBASING);
12718 goto done;
12721 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12722 repo);
12723 if (error)
12724 goto done;
12725 if (merge_in_progress) {
12726 error = got_error(GOT_ERR_MERGE_BUSY);
12727 goto done;
12730 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12731 if (error)
12732 goto done;
12734 if (edit_in_progress && edit_logmsg_only) {
12735 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12736 "histedit operation is in progress in this "
12737 "work tree and must be continued or aborted "
12738 "before the -m option can be used");
12739 goto done;
12741 if (edit_in_progress && drop_only) {
12742 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12743 "histedit operation is in progress in this "
12744 "work tree and must be continued or aborted "
12745 "before the -d option can be used");
12746 goto done;
12748 if (edit_in_progress && fold_only) {
12749 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12750 "histedit operation is in progress in this "
12751 "work tree and must be continued or aborted "
12752 "before the -f option can be used");
12753 goto done;
12755 if (edit_in_progress && edit_only) {
12756 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12757 "histedit operation is in progress in this "
12758 "work tree and must be continued or aborted "
12759 "before the -e option can be used");
12760 goto done;
12763 if (edit_in_progress && abort_edit) {
12764 error = got_worktree_histedit_continue(&resume_commit_id,
12765 &tmp_branch, &branch, &base_commit_id, &fileindex,
12766 worktree, repo);
12767 if (error)
12768 goto done;
12769 printf("Switching work tree to %s\n",
12770 got_ref_get_symref_target(branch));
12771 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12772 branch, base_commit_id, abort_progress, &upa);
12773 if (error)
12774 goto done;
12775 printf("Histedit of %s aborted\n",
12776 got_ref_get_symref_target(branch));
12777 print_merge_progress_stats(&upa);
12778 goto done; /* nothing else to do */
12779 } else if (abort_edit) {
12780 error = got_error(GOT_ERR_NOT_HISTEDIT);
12781 goto done;
12784 error = get_author(&committer, repo, worktree);
12785 if (error)
12786 goto done;
12788 if (continue_edit) {
12789 char *path;
12791 if (!edit_in_progress) {
12792 error = got_error(GOT_ERR_NOT_HISTEDIT);
12793 goto done;
12796 error = got_worktree_get_histedit_script_path(&path, worktree);
12797 if (error)
12798 goto done;
12800 error = histedit_load_list(&histedit_cmds, path, repo);
12801 free(path);
12802 if (error)
12803 goto done;
12805 error = got_worktree_histedit_continue(&resume_commit_id,
12806 &tmp_branch, &branch, &base_commit_id, &fileindex,
12807 worktree, repo);
12808 if (error)
12809 goto done;
12811 error = got_ref_resolve(&head_commit_id, repo, branch);
12812 if (error)
12813 goto done;
12815 error = got_object_open_as_commit(&commit, repo,
12816 head_commit_id);
12817 if (error)
12818 goto done;
12819 parent_ids = got_object_commit_get_parent_ids(commit);
12820 pid = STAILQ_FIRST(parent_ids);
12821 if (pid == NULL) {
12822 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12823 goto done;
12825 error = collect_commits(&commits, head_commit_id, &pid->id,
12826 base_commit_id, got_worktree_get_path_prefix(worktree),
12827 GOT_ERR_HISTEDIT_PATH, repo);
12828 got_object_commit_close(commit);
12829 commit = NULL;
12830 if (error)
12831 goto done;
12832 } else {
12833 if (edit_in_progress) {
12834 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12835 goto done;
12838 error = got_ref_open(&branch, repo,
12839 got_worktree_get_head_ref_name(worktree), 0);
12840 if (error != NULL)
12841 goto done;
12843 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12844 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12845 "will not edit commit history of a branch outside "
12846 "the \"refs/heads/\" reference namespace");
12847 goto done;
12850 error = got_ref_resolve(&head_commit_id, repo, branch);
12851 got_ref_close(branch);
12852 branch = NULL;
12853 if (error)
12854 goto done;
12856 error = got_object_open_as_commit(&commit, repo,
12857 head_commit_id);
12858 if (error)
12859 goto done;
12860 parent_ids = got_object_commit_get_parent_ids(commit);
12861 pid = STAILQ_FIRST(parent_ids);
12862 if (pid == NULL) {
12863 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12864 goto done;
12866 error = collect_commits(&commits, head_commit_id, &pid->id,
12867 got_worktree_get_base_commit_id(worktree),
12868 got_worktree_get_path_prefix(worktree),
12869 GOT_ERR_HISTEDIT_PATH, repo);
12870 got_object_commit_close(commit);
12871 commit = NULL;
12872 if (error)
12873 goto done;
12875 if (STAILQ_EMPTY(&commits)) {
12876 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12877 goto done;
12880 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12881 &base_commit_id, &fileindex, worktree, repo);
12882 if (error)
12883 goto done;
12885 if (edit_script_path) {
12886 error = histedit_load_list(&histedit_cmds,
12887 edit_script_path, repo);
12888 if (error) {
12889 got_worktree_histedit_abort(worktree, fileindex,
12890 repo, branch, base_commit_id,
12891 abort_progress, &upa);
12892 print_merge_progress_stats(&upa);
12893 goto done;
12895 } else {
12896 const char *branch_name;
12897 branch_name = got_ref_get_symref_target(branch);
12898 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12899 branch_name += 11;
12900 error = histedit_edit_script(&histedit_cmds, &commits,
12901 branch_name, edit_logmsg_only, fold_only,
12902 drop_only, edit_only, repo);
12903 if (error) {
12904 got_worktree_histedit_abort(worktree, fileindex,
12905 repo, branch, base_commit_id,
12906 abort_progress, &upa);
12907 print_merge_progress_stats(&upa);
12908 goto done;
12913 error = histedit_save_list(&histedit_cmds, worktree,
12914 repo);
12915 if (error) {
12916 got_worktree_histedit_abort(worktree, fileindex,
12917 repo, branch, base_commit_id,
12918 abort_progress, &upa);
12919 print_merge_progress_stats(&upa);
12920 goto done;
12925 error = histedit_check_script(&histedit_cmds, &commits, repo);
12926 if (error)
12927 goto done;
12929 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12930 if (resume_commit_id) {
12931 if (got_object_id_cmp(hle->commit_id,
12932 resume_commit_id) != 0)
12933 continue;
12935 resume_commit_id = NULL;
12936 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12937 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12938 error = histedit_skip_commit(hle, worktree,
12939 repo);
12940 if (error)
12941 goto done;
12942 } else {
12943 struct got_pathlist_head paths;
12944 int have_changes = 0;
12946 TAILQ_INIT(&paths);
12947 error = got_pathlist_append(&paths, "", NULL);
12948 if (error)
12949 goto done;
12950 error = got_worktree_status(worktree, &paths,
12951 repo, 0, check_local_changes, &have_changes,
12952 check_cancelled, NULL);
12953 got_pathlist_free(&paths,
12954 GOT_PATHLIST_FREE_NONE);
12955 if (error) {
12956 if (error->code != GOT_ERR_CANCELLED)
12957 goto done;
12958 if (sigint_received || sigpipe_received)
12959 goto done;
12961 if (have_changes) {
12962 error = histedit_commit(NULL, worktree,
12963 fileindex, tmp_branch, hle,
12964 committer, allow_conflict, repo);
12965 if (error)
12966 goto done;
12967 } else {
12968 error = got_object_open_as_commit(
12969 &commit, repo, hle->commit_id);
12970 if (error)
12971 goto done;
12972 error = show_histedit_progress(commit,
12973 hle, NULL);
12974 got_object_commit_close(commit);
12975 commit = NULL;
12976 if (error)
12977 goto done;
12980 continue;
12983 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12984 error = histedit_skip_commit(hle, worktree, repo);
12985 if (error)
12986 goto done;
12987 continue;
12990 error = got_object_open_as_commit(&commit, repo,
12991 hle->commit_id);
12992 if (error)
12993 goto done;
12994 parent_ids = got_object_commit_get_parent_ids(commit);
12995 pid = STAILQ_FIRST(parent_ids);
12997 error = got_worktree_histedit_merge_files(&merged_paths,
12998 worktree, fileindex, &pid->id, hle->commit_id, repo,
12999 update_progress, &upa, check_cancelled, NULL);
13000 if (error)
13001 goto done;
13002 got_object_commit_close(commit);
13003 commit = NULL;
13005 print_merge_progress_stats(&upa);
13006 if (upa.conflicts > 0 || upa.missing > 0 ||
13007 upa.not_deleted > 0 || upa.unversioned > 0) {
13008 if (upa.conflicts > 0) {
13009 error = show_rebase_merge_conflict(
13010 hle->commit_id, repo);
13011 if (error)
13012 goto done;
13014 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13015 break;
13018 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13019 char *id_str;
13020 error = got_object_id_str(&id_str, hle->commit_id);
13021 if (error)
13022 goto done;
13023 printf("Stopping histedit for amending commit %s\n",
13024 id_str);
13025 free(id_str);
13026 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13027 error = got_worktree_histedit_postpone(worktree,
13028 fileindex);
13029 goto done;
13032 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13033 error = histedit_skip_commit(hle, worktree, repo);
13034 if (error)
13035 goto done;
13036 continue;
13039 error = histedit_commit(&merged_paths, worktree, fileindex,
13040 tmp_branch, hle, committer, allow_conflict, repo);
13041 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13042 if (error)
13043 goto done;
13046 if (upa.conflicts > 0 || upa.missing > 0 ||
13047 upa.not_deleted > 0 || upa.unversioned > 0) {
13048 error = got_worktree_histedit_postpone(worktree, fileindex);
13049 if (error)
13050 goto done;
13051 if (upa.conflicts > 0 && upa.missing == 0 &&
13052 upa.not_deleted == 0 && upa.unversioned == 0) {
13053 error = got_error_msg(GOT_ERR_CONFLICTS,
13054 "conflicts must be resolved before histedit "
13055 "can continue");
13056 } else if (upa.conflicts > 0) {
13057 error = got_error_msg(GOT_ERR_CONFLICTS,
13058 "conflicts must be resolved before histedit "
13059 "can continue; changes destined for some "
13060 "files were not yet merged and should be "
13061 "merged manually if required before the "
13062 "histedit operation is continued");
13063 } else {
13064 error = got_error_msg(GOT_ERR_CONFLICTS,
13065 "changes destined for some files were not "
13066 "yet merged and should be merged manually "
13067 "if required before the histedit operation "
13068 "is continued");
13070 } else
13071 error = histedit_complete(worktree, fileindex, tmp_branch,
13072 branch, repo);
13073 done:
13074 free(cwd);
13075 free(committer);
13076 free(gitconfig_path);
13077 got_object_id_queue_free(&commits);
13078 histedit_free_list(&histedit_cmds);
13079 free(head_commit_id);
13080 free(base_commit_id);
13081 free(resume_commit_id);
13082 if (commit)
13083 got_object_commit_close(commit);
13084 if (branch)
13085 got_ref_close(branch);
13086 if (tmp_branch)
13087 got_ref_close(tmp_branch);
13088 if (worktree)
13089 got_worktree_close(worktree);
13090 if (repo) {
13091 const struct got_error *close_err = got_repo_close(repo);
13092 if (error == NULL)
13093 error = close_err;
13095 if (pack_fds) {
13096 const struct got_error *pack_err =
13097 got_repo_pack_fds_close(pack_fds);
13098 if (error == NULL)
13099 error = pack_err;
13101 return error;
13104 __dead static void
13105 usage_integrate(void)
13107 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13108 exit(1);
13111 static const struct got_error *
13112 cmd_integrate(int argc, char *argv[])
13114 const struct got_error *error = NULL;
13115 struct got_repository *repo = NULL;
13116 struct got_worktree *worktree = NULL;
13117 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13118 const char *branch_arg = NULL;
13119 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13120 struct got_fileindex *fileindex = NULL;
13121 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13122 int ch;
13123 struct got_update_progress_arg upa;
13124 int *pack_fds = NULL;
13126 #ifndef PROFILE
13127 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13128 "unveil", NULL) == -1)
13129 err(1, "pledge");
13130 #endif
13132 while ((ch = getopt(argc, argv, "")) != -1) {
13133 switch (ch) {
13134 default:
13135 usage_integrate();
13136 /* NOTREACHED */
13140 argc -= optind;
13141 argv += optind;
13143 if (argc != 1)
13144 usage_integrate();
13145 branch_arg = argv[0];
13147 cwd = getcwd(NULL, 0);
13148 if (cwd == NULL) {
13149 error = got_error_from_errno("getcwd");
13150 goto done;
13153 error = got_repo_pack_fds_open(&pack_fds);
13154 if (error != NULL)
13155 goto done;
13157 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13158 if (error) {
13159 if (error->code == GOT_ERR_NOT_WORKTREE)
13160 error = wrap_not_worktree_error(error, "integrate",
13161 cwd);
13162 goto done;
13165 error = check_rebase_or_histedit_in_progress(worktree);
13166 if (error)
13167 goto done;
13169 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13170 NULL, pack_fds);
13171 if (error != NULL)
13172 goto done;
13174 error = apply_unveil(got_repo_get_path(repo), 0,
13175 got_worktree_get_root_path(worktree));
13176 if (error)
13177 goto done;
13179 error = check_merge_in_progress(worktree, repo);
13180 if (error)
13181 goto done;
13183 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13184 error = got_error_from_errno("asprintf");
13185 goto done;
13188 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13189 &base_branch_ref, worktree, refname, repo);
13190 if (error)
13191 goto done;
13193 refname = strdup(got_ref_get_name(branch_ref));
13194 if (refname == NULL) {
13195 error = got_error_from_errno("strdup");
13196 got_worktree_integrate_abort(worktree, fileindex, repo,
13197 branch_ref, base_branch_ref);
13198 goto done;
13200 base_refname = strdup(got_ref_get_name(base_branch_ref));
13201 if (base_refname == NULL) {
13202 error = got_error_from_errno("strdup");
13203 got_worktree_integrate_abort(worktree, fileindex, repo,
13204 branch_ref, base_branch_ref);
13205 goto done;
13207 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13208 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13209 got_worktree_integrate_abort(worktree, fileindex, repo,
13210 branch_ref, base_branch_ref);
13211 goto done;
13214 error = got_ref_resolve(&commit_id, repo, branch_ref);
13215 if (error)
13216 goto done;
13218 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13219 if (error)
13220 goto done;
13222 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13223 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13224 "specified branch has already been integrated");
13225 got_worktree_integrate_abort(worktree, fileindex, repo,
13226 branch_ref, base_branch_ref);
13227 goto done;
13230 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13231 if (error) {
13232 if (error->code == GOT_ERR_ANCESTRY)
13233 error = got_error(GOT_ERR_REBASE_REQUIRED);
13234 got_worktree_integrate_abort(worktree, fileindex, repo,
13235 branch_ref, base_branch_ref);
13236 goto done;
13239 memset(&upa, 0, sizeof(upa));
13240 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13241 branch_ref, base_branch_ref, update_progress, &upa,
13242 check_cancelled, NULL);
13243 if (error)
13244 goto done;
13246 printf("Integrated %s into %s\n", refname, base_refname);
13247 print_update_progress_stats(&upa);
13248 done:
13249 if (repo) {
13250 const struct got_error *close_err = got_repo_close(repo);
13251 if (error == NULL)
13252 error = close_err;
13254 if (worktree)
13255 got_worktree_close(worktree);
13256 if (pack_fds) {
13257 const struct got_error *pack_err =
13258 got_repo_pack_fds_close(pack_fds);
13259 if (error == NULL)
13260 error = pack_err;
13262 free(cwd);
13263 free(base_commit_id);
13264 free(commit_id);
13265 free(refname);
13266 free(base_refname);
13267 return error;
13270 __dead static void
13271 usage_merge(void)
13273 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13274 exit(1);
13277 static const struct got_error *
13278 cmd_merge(int argc, char *argv[])
13280 const struct got_error *error = NULL;
13281 struct got_worktree *worktree = NULL;
13282 struct got_repository *repo = NULL;
13283 struct got_fileindex *fileindex = NULL;
13284 char *cwd = NULL, *id_str = NULL, *author = NULL;
13285 char *gitconfig_path = NULL;
13286 struct got_reference *branch = NULL, *wt_branch = NULL;
13287 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13288 struct got_object_id *wt_branch_tip = NULL;
13289 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13290 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13291 struct got_update_progress_arg upa;
13292 struct got_object_id *merge_commit_id = NULL;
13293 char *branch_name = NULL;
13294 int *pack_fds = NULL;
13296 memset(&upa, 0, sizeof(upa));
13298 #ifndef PROFILE
13299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13300 "unveil", NULL) == -1)
13301 err(1, "pledge");
13302 #endif
13304 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13305 switch (ch) {
13306 case 'a':
13307 abort_merge = 1;
13308 break;
13309 case 'C':
13310 allow_conflict = 1;
13311 break;
13312 case 'c':
13313 continue_merge = 1;
13314 break;
13315 case 'M':
13316 prefer_fast_forward = 0;
13317 break;
13318 case 'n':
13319 interrupt_merge = 1;
13320 break;
13321 default:
13322 usage_merge();
13323 /* NOTREACHED */
13327 argc -= optind;
13328 argv += optind;
13330 if (abort_merge) {
13331 if (continue_merge)
13332 option_conflict('a', 'c');
13333 if (!prefer_fast_forward)
13334 option_conflict('a', 'M');
13335 if (interrupt_merge)
13336 option_conflict('a', 'n');
13337 } else if (continue_merge) {
13338 if (!prefer_fast_forward)
13339 option_conflict('c', 'M');
13340 if (interrupt_merge)
13341 option_conflict('c', 'n');
13343 if (allow_conflict) {
13344 if (!continue_merge)
13345 errx(1, "-C option requires -c");
13347 if (abort_merge || continue_merge) {
13348 if (argc != 0)
13349 usage_merge();
13350 } else if (argc != 1)
13351 usage_merge();
13353 cwd = getcwd(NULL, 0);
13354 if (cwd == NULL) {
13355 error = got_error_from_errno("getcwd");
13356 goto done;
13359 error = got_repo_pack_fds_open(&pack_fds);
13360 if (error != NULL)
13361 goto done;
13363 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13364 if (error) {
13365 if (error->code == GOT_ERR_NOT_WORKTREE)
13366 error = wrap_not_worktree_error(error,
13367 "merge", cwd);
13368 goto done;
13371 error = get_gitconfig_path(&gitconfig_path);
13372 if (error)
13373 goto done;
13374 error = got_repo_open(&repo,
13375 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13376 gitconfig_path, pack_fds);
13377 if (error != NULL)
13378 goto done;
13380 if (worktree != NULL) {
13381 error = worktree_has_logmsg_ref("merge", worktree, repo);
13382 if (error)
13383 goto done;
13386 error = apply_unveil(got_repo_get_path(repo), 0,
13387 worktree ? got_worktree_get_root_path(worktree) : NULL);
13388 if (error)
13389 goto done;
13391 error = check_rebase_or_histedit_in_progress(worktree);
13392 if (error)
13393 goto done;
13395 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13396 repo);
13397 if (error)
13398 goto done;
13400 if (merge_in_progress && !(abort_merge || continue_merge)) {
13401 error = got_error(GOT_ERR_MERGE_BUSY);
13402 goto done;
13405 if (!merge_in_progress && (abort_merge || continue_merge)) {
13406 error = got_error(GOT_ERR_NOT_MERGING);
13407 goto done;
13410 if (abort_merge) {
13411 error = got_worktree_merge_continue(&branch_name,
13412 &branch_tip, &fileindex, worktree, repo);
13413 if (error)
13414 goto done;
13415 error = got_worktree_merge_abort(worktree, fileindex, repo,
13416 abort_progress, &upa);
13417 if (error)
13418 goto done;
13419 printf("Merge of %s aborted\n", branch_name);
13420 goto done; /* nothing else to do */
13423 if (strncmp(got_worktree_get_head_ref_name(worktree),
13424 "refs/heads/", 11) != 0) {
13425 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13426 "work tree's current branch %s is outside the "
13427 "\"refs/heads/\" reference namespace; "
13428 "update -b required",
13429 got_worktree_get_head_ref_name(worktree));
13430 goto done;
13433 error = get_author(&author, repo, worktree);
13434 if (error)
13435 goto done;
13437 error = got_ref_open(&wt_branch, repo,
13438 got_worktree_get_head_ref_name(worktree), 0);
13439 if (error)
13440 goto done;
13441 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13442 if (error)
13443 goto done;
13445 if (continue_merge) {
13446 struct got_object_id *base_commit_id;
13447 base_commit_id = got_worktree_get_base_commit_id(worktree);
13448 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13449 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13450 goto done;
13452 error = got_worktree_merge_continue(&branch_name,
13453 &branch_tip, &fileindex, worktree, repo);
13454 if (error)
13455 goto done;
13456 } else {
13457 error = got_ref_open(&branch, repo, argv[0], 0);
13458 if (error != NULL)
13459 goto done;
13460 branch_name = strdup(got_ref_get_name(branch));
13461 if (branch_name == NULL) {
13462 error = got_error_from_errno("strdup");
13463 goto done;
13465 error = got_ref_resolve(&branch_tip, repo, branch);
13466 if (error)
13467 goto done;
13470 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13471 wt_branch_tip, branch_tip, 0, repo,
13472 check_cancelled, NULL);
13473 if (error && error->code != GOT_ERR_ANCESTRY)
13474 goto done;
13476 if (!continue_merge) {
13477 error = check_path_prefix(wt_branch_tip, branch_tip,
13478 got_worktree_get_path_prefix(worktree),
13479 GOT_ERR_MERGE_PATH, repo);
13480 if (error)
13481 goto done;
13482 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13483 if (error)
13484 goto done;
13485 if (prefer_fast_forward && yca_id &&
13486 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13487 struct got_pathlist_head paths;
13488 if (interrupt_merge) {
13489 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13490 "there are no changes to merge since %s "
13491 "is already based on %s; merge cannot be "
13492 "interrupted for amending; -n",
13493 branch_name, got_ref_get_name(wt_branch));
13494 goto done;
13496 printf("Forwarding %s to %s\n",
13497 got_ref_get_name(wt_branch), branch_name);
13498 error = got_ref_change_ref(wt_branch, branch_tip);
13499 if (error)
13500 goto done;
13501 error = got_ref_write(wt_branch, repo);
13502 if (error)
13503 goto done;
13504 error = got_worktree_set_base_commit_id(worktree, repo,
13505 branch_tip);
13506 if (error)
13507 goto done;
13508 TAILQ_INIT(&paths);
13509 error = got_pathlist_append(&paths, "", NULL);
13510 if (error)
13511 goto done;
13512 error = got_worktree_checkout_files(worktree,
13513 &paths, repo, update_progress, &upa,
13514 check_cancelled, NULL);
13515 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13516 if (error)
13517 goto done;
13518 if (upa.did_something) {
13519 char *id_str;
13520 error = got_object_id_str(&id_str, branch_tip);
13521 if (error)
13522 goto done;
13523 printf("Updated to commit %s\n", id_str);
13524 free(id_str);
13525 } else
13526 printf("Already up-to-date\n");
13527 print_update_progress_stats(&upa);
13528 goto done;
13530 error = got_worktree_merge_write_refs(worktree, branch, repo);
13531 if (error)
13532 goto done;
13534 error = got_worktree_merge_branch(worktree, fileindex,
13535 yca_id, branch_tip, repo, update_progress, &upa,
13536 check_cancelled, NULL);
13537 if (error)
13538 goto done;
13539 print_merge_progress_stats(&upa);
13540 if (!upa.did_something) {
13541 error = got_worktree_merge_abort(worktree, fileindex,
13542 repo, abort_progress, &upa);
13543 if (error)
13544 goto done;
13545 printf("Already up-to-date\n");
13546 goto done;
13550 if (interrupt_merge) {
13551 error = got_worktree_merge_postpone(worktree, fileindex);
13552 if (error)
13553 goto done;
13554 printf("Merge of %s interrupted on request\n", branch_name);
13555 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13556 upa.not_deleted > 0 || upa.unversioned > 0) {
13557 error = got_worktree_merge_postpone(worktree, fileindex);
13558 if (error)
13559 goto done;
13560 if (upa.conflicts > 0 && upa.missing == 0 &&
13561 upa.not_deleted == 0 && upa.unversioned == 0) {
13562 error = got_error_msg(GOT_ERR_CONFLICTS,
13563 "conflicts must be resolved before merging "
13564 "can continue");
13565 } else if (upa.conflicts > 0) {
13566 error = got_error_msg(GOT_ERR_CONFLICTS,
13567 "conflicts must be resolved before merging "
13568 "can continue; changes destined for some "
13569 "files were not yet merged and "
13570 "should be merged manually if required before the "
13571 "merge operation is continued");
13572 } else {
13573 error = got_error_msg(GOT_ERR_CONFLICTS,
13574 "changes destined for some "
13575 "files were not yet merged and should be "
13576 "merged manually if required before the "
13577 "merge operation is continued");
13579 goto done;
13580 } else {
13581 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13582 fileindex, author, NULL, 1, branch_tip, branch_name,
13583 allow_conflict, repo, continue_merge ? print_status : NULL,
13584 NULL);
13585 if (error)
13586 goto done;
13587 error = got_worktree_merge_complete(worktree, fileindex, repo);
13588 if (error)
13589 goto done;
13590 error = got_object_id_str(&id_str, merge_commit_id);
13591 if (error)
13592 goto done;
13593 printf("Merged %s into %s: %s\n", branch_name,
13594 got_worktree_get_head_ref_name(worktree),
13595 id_str);
13598 done:
13599 free(gitconfig_path);
13600 free(id_str);
13601 free(merge_commit_id);
13602 free(author);
13603 free(branch_tip);
13604 free(branch_name);
13605 free(yca_id);
13606 if (branch)
13607 got_ref_close(branch);
13608 if (wt_branch)
13609 got_ref_close(wt_branch);
13610 if (worktree)
13611 got_worktree_close(worktree);
13612 if (repo) {
13613 const struct got_error *close_err = got_repo_close(repo);
13614 if (error == NULL)
13615 error = close_err;
13617 if (pack_fds) {
13618 const struct got_error *pack_err =
13619 got_repo_pack_fds_close(pack_fds);
13620 if (error == NULL)
13621 error = pack_err;
13623 return error;
13626 __dead static void
13627 usage_stage(void)
13629 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13630 "[path ...]\n", getprogname());
13631 exit(1);
13634 static const struct got_error *
13635 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13636 const char *path, struct got_object_id *blob_id,
13637 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13638 int dirfd, const char *de_name)
13640 const struct got_error *err = NULL;
13641 char *id_str = NULL;
13643 if (staged_status != GOT_STATUS_ADD &&
13644 staged_status != GOT_STATUS_MODIFY &&
13645 staged_status != GOT_STATUS_DELETE)
13646 return NULL;
13648 if (staged_status == GOT_STATUS_ADD ||
13649 staged_status == GOT_STATUS_MODIFY)
13650 err = got_object_id_str(&id_str, staged_blob_id);
13651 else
13652 err = got_object_id_str(&id_str, blob_id);
13653 if (err)
13654 return err;
13656 printf("%s %c %s\n", id_str, staged_status, path);
13657 free(id_str);
13658 return NULL;
13661 static const struct got_error *
13662 cmd_stage(int argc, char *argv[])
13664 const struct got_error *error = NULL;
13665 struct got_repository *repo = NULL;
13666 struct got_worktree *worktree = NULL;
13667 char *cwd = NULL;
13668 struct got_pathlist_head paths;
13669 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13670 FILE *patch_script_file = NULL;
13671 const char *patch_script_path = NULL;
13672 struct choose_patch_arg cpa;
13673 int *pack_fds = NULL;
13675 TAILQ_INIT(&paths);
13677 #ifndef PROFILE
13678 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13679 "unveil", NULL) == -1)
13680 err(1, "pledge");
13681 #endif
13683 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13684 switch (ch) {
13685 case 'F':
13686 patch_script_path = optarg;
13687 break;
13688 case 'l':
13689 list_stage = 1;
13690 break;
13691 case 'p':
13692 pflag = 1;
13693 break;
13694 case 'S':
13695 allow_bad_symlinks = 1;
13696 break;
13697 default:
13698 usage_stage();
13699 /* NOTREACHED */
13703 argc -= optind;
13704 argv += optind;
13706 if (list_stage && (pflag || patch_script_path))
13707 errx(1, "-l option cannot be used with other options");
13708 if (patch_script_path && !pflag)
13709 errx(1, "-F option can only be used together with -p option");
13711 cwd = getcwd(NULL, 0);
13712 if (cwd == NULL) {
13713 error = got_error_from_errno("getcwd");
13714 goto done;
13717 error = got_repo_pack_fds_open(&pack_fds);
13718 if (error != NULL)
13719 goto done;
13721 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13722 if (error) {
13723 if (error->code == GOT_ERR_NOT_WORKTREE)
13724 error = wrap_not_worktree_error(error, "stage", cwd);
13725 goto done;
13728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13729 NULL, pack_fds);
13730 if (error != NULL)
13731 goto done;
13733 if (patch_script_path) {
13734 patch_script_file = fopen(patch_script_path, "re");
13735 if (patch_script_file == NULL) {
13736 error = got_error_from_errno2("fopen",
13737 patch_script_path);
13738 goto done;
13741 error = apply_unveil(got_repo_get_path(repo), 0,
13742 got_worktree_get_root_path(worktree));
13743 if (error)
13744 goto done;
13746 error = check_merge_in_progress(worktree, repo);
13747 if (error)
13748 goto done;
13750 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13751 if (error)
13752 goto done;
13754 if (list_stage)
13755 error = got_worktree_status(worktree, &paths, repo, 0,
13756 print_stage, NULL, check_cancelled, NULL);
13757 else {
13758 cpa.patch_script_file = patch_script_file;
13759 cpa.action = "stage";
13760 error = got_worktree_stage(worktree, &paths,
13761 pflag ? NULL : print_status, NULL,
13762 pflag ? choose_patch : NULL, &cpa,
13763 allow_bad_symlinks, repo);
13765 done:
13766 if (patch_script_file && fclose(patch_script_file) == EOF &&
13767 error == NULL)
13768 error = got_error_from_errno2("fclose", patch_script_path);
13769 if (repo) {
13770 const struct got_error *close_err = got_repo_close(repo);
13771 if (error == NULL)
13772 error = close_err;
13774 if (worktree)
13775 got_worktree_close(worktree);
13776 if (pack_fds) {
13777 const struct got_error *pack_err =
13778 got_repo_pack_fds_close(pack_fds);
13779 if (error == NULL)
13780 error = pack_err;
13782 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13783 free(cwd);
13784 return error;
13787 __dead static void
13788 usage_unstage(void)
13790 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13791 "[path ...]\n", getprogname());
13792 exit(1);
13796 static const struct got_error *
13797 cmd_unstage(int argc, char *argv[])
13799 const struct got_error *error = NULL;
13800 struct got_repository *repo = NULL;
13801 struct got_worktree *worktree = NULL;
13802 char *cwd = NULL;
13803 struct got_pathlist_head paths;
13804 int ch, pflag = 0;
13805 struct got_update_progress_arg upa;
13806 FILE *patch_script_file = NULL;
13807 const char *patch_script_path = NULL;
13808 struct choose_patch_arg cpa;
13809 int *pack_fds = NULL;
13811 TAILQ_INIT(&paths);
13813 #ifndef PROFILE
13814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13815 "unveil", NULL) == -1)
13816 err(1, "pledge");
13817 #endif
13819 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13820 switch (ch) {
13821 case 'F':
13822 patch_script_path = optarg;
13823 break;
13824 case 'p':
13825 pflag = 1;
13826 break;
13827 default:
13828 usage_unstage();
13829 /* NOTREACHED */
13833 argc -= optind;
13834 argv += optind;
13836 if (patch_script_path && !pflag)
13837 errx(1, "-F option can only be used together with -p option");
13839 cwd = getcwd(NULL, 0);
13840 if (cwd == NULL) {
13841 error = got_error_from_errno("getcwd");
13842 goto done;
13845 error = got_repo_pack_fds_open(&pack_fds);
13846 if (error != NULL)
13847 goto done;
13849 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13850 if (error) {
13851 if (error->code == GOT_ERR_NOT_WORKTREE)
13852 error = wrap_not_worktree_error(error, "unstage", cwd);
13853 goto done;
13856 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13857 NULL, pack_fds);
13858 if (error != NULL)
13859 goto done;
13861 if (patch_script_path) {
13862 patch_script_file = fopen(patch_script_path, "re");
13863 if (patch_script_file == NULL) {
13864 error = got_error_from_errno2("fopen",
13865 patch_script_path);
13866 goto done;
13870 error = apply_unveil(got_repo_get_path(repo), 0,
13871 got_worktree_get_root_path(worktree));
13872 if (error)
13873 goto done;
13875 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13876 if (error)
13877 goto done;
13879 cpa.patch_script_file = patch_script_file;
13880 cpa.action = "unstage";
13881 memset(&upa, 0, sizeof(upa));
13882 error = got_worktree_unstage(worktree, &paths, update_progress,
13883 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13884 if (!error)
13885 print_merge_progress_stats(&upa);
13886 done:
13887 if (patch_script_file && fclose(patch_script_file) == EOF &&
13888 error == NULL)
13889 error = got_error_from_errno2("fclose", patch_script_path);
13890 if (repo) {
13891 const struct got_error *close_err = got_repo_close(repo);
13892 if (error == NULL)
13893 error = close_err;
13895 if (worktree)
13896 got_worktree_close(worktree);
13897 if (pack_fds) {
13898 const struct got_error *pack_err =
13899 got_repo_pack_fds_close(pack_fds);
13900 if (error == NULL)
13901 error = pack_err;
13903 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13904 free(cwd);
13905 return error;
13908 __dead static void
13909 usage_cat(void)
13911 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13912 "arg ...\n", getprogname());
13913 exit(1);
13916 static const struct got_error *
13917 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13919 const struct got_error *err;
13920 struct got_blob_object *blob;
13921 int fd = -1;
13923 fd = got_opentempfd();
13924 if (fd == -1)
13925 return got_error_from_errno("got_opentempfd");
13927 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13928 if (err)
13929 goto done;
13931 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13932 done:
13933 if (fd != -1 && close(fd) == -1 && err == NULL)
13934 err = got_error_from_errno("close");
13935 if (blob)
13936 got_object_blob_close(blob);
13937 return err;
13940 static const struct got_error *
13941 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13943 const struct got_error *err;
13944 struct got_tree_object *tree;
13945 int nentries, i;
13947 err = got_object_open_as_tree(&tree, repo, id);
13948 if (err)
13949 return err;
13951 nentries = got_object_tree_get_nentries(tree);
13952 for (i = 0; i < nentries; i++) {
13953 struct got_tree_entry *te;
13954 char *id_str;
13955 if (sigint_received || sigpipe_received)
13956 break;
13957 te = got_object_tree_get_entry(tree, i);
13958 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13959 if (err)
13960 break;
13961 fprintf(outfile, "%s %.7o %s\n", id_str,
13962 got_tree_entry_get_mode(te),
13963 got_tree_entry_get_name(te));
13964 free(id_str);
13967 got_object_tree_close(tree);
13968 return err;
13971 static const struct got_error *
13972 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13974 const struct got_error *err;
13975 struct got_commit_object *commit;
13976 const struct got_object_id_queue *parent_ids;
13977 struct got_object_qid *pid;
13978 char *id_str = NULL;
13979 const char *logmsg = NULL;
13980 char gmtoff[6];
13982 err = got_object_open_as_commit(&commit, repo, id);
13983 if (err)
13984 return err;
13986 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13987 if (err)
13988 goto done;
13990 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13991 parent_ids = got_object_commit_get_parent_ids(commit);
13992 fprintf(outfile, "numparents %d\n",
13993 got_object_commit_get_nparents(commit));
13994 STAILQ_FOREACH(pid, parent_ids, entry) {
13995 char *pid_str;
13996 err = got_object_id_str(&pid_str, &pid->id);
13997 if (err)
13998 goto done;
13999 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14000 free(pid_str);
14002 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14003 got_object_commit_get_author_gmtoff(commit));
14004 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14005 got_object_commit_get_author(commit),
14006 (long long)got_object_commit_get_author_time(commit),
14007 gmtoff);
14009 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14010 got_object_commit_get_committer_gmtoff(commit));
14011 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14012 got_object_commit_get_committer(commit),
14013 (long long)got_object_commit_get_committer_time(commit),
14014 gmtoff);
14016 logmsg = got_object_commit_get_logmsg_raw(commit);
14017 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14018 fprintf(outfile, "%s", logmsg);
14019 done:
14020 free(id_str);
14021 got_object_commit_close(commit);
14022 return err;
14025 static const struct got_error *
14026 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14028 const struct got_error *err;
14029 struct got_tag_object *tag;
14030 char *id_str = NULL;
14031 const char *tagmsg = NULL;
14032 char gmtoff[6];
14034 err = got_object_open_as_tag(&tag, repo, id);
14035 if (err)
14036 return err;
14038 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14039 if (err)
14040 goto done;
14042 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14044 switch (got_object_tag_get_object_type(tag)) {
14045 case GOT_OBJ_TYPE_BLOB:
14046 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14047 GOT_OBJ_LABEL_BLOB);
14048 break;
14049 case GOT_OBJ_TYPE_TREE:
14050 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14051 GOT_OBJ_LABEL_TREE);
14052 break;
14053 case GOT_OBJ_TYPE_COMMIT:
14054 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14055 GOT_OBJ_LABEL_COMMIT);
14056 break;
14057 case GOT_OBJ_TYPE_TAG:
14058 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14059 GOT_OBJ_LABEL_TAG);
14060 break;
14061 default:
14062 break;
14065 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14066 got_object_tag_get_name(tag));
14068 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14069 got_object_tag_get_tagger_gmtoff(tag));
14070 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14071 got_object_tag_get_tagger(tag),
14072 (long long)got_object_tag_get_tagger_time(tag),
14073 gmtoff);
14075 tagmsg = got_object_tag_get_message(tag);
14076 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14077 fprintf(outfile, "%s", tagmsg);
14078 done:
14079 free(id_str);
14080 got_object_tag_close(tag);
14081 return err;
14084 static const struct got_error *
14085 cmd_cat(int argc, char *argv[])
14087 const struct got_error *error;
14088 struct got_repository *repo = NULL;
14089 struct got_worktree *worktree = NULL;
14090 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14091 char *keyword_idstr = NULL;
14092 const char *commit_id_str = NULL;
14093 struct got_object_id *id = NULL, *commit_id = NULL;
14094 struct got_commit_object *commit = NULL;
14095 int ch, obj_type, i, force_path = 0;
14096 struct got_reflist_head refs;
14097 int *pack_fds = NULL;
14099 TAILQ_INIT(&refs);
14101 #ifndef PROFILE
14102 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14103 NULL) == -1)
14104 err(1, "pledge");
14105 #endif
14107 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14108 switch (ch) {
14109 case 'c':
14110 commit_id_str = optarg;
14111 break;
14112 case 'P':
14113 force_path = 1;
14114 break;
14115 case 'r':
14116 repo_path = realpath(optarg, NULL);
14117 if (repo_path == NULL)
14118 return got_error_from_errno2("realpath",
14119 optarg);
14120 got_path_strip_trailing_slashes(repo_path);
14121 break;
14122 default:
14123 usage_cat();
14124 /* NOTREACHED */
14128 argc -= optind;
14129 argv += optind;
14131 cwd = getcwd(NULL, 0);
14132 if (cwd == NULL) {
14133 error = got_error_from_errno("getcwd");
14134 goto done;
14137 error = got_repo_pack_fds_open(&pack_fds);
14138 if (error != NULL)
14139 goto done;
14141 if (repo_path == NULL) {
14142 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14143 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14144 goto done;
14145 if (worktree) {
14146 repo_path = strdup(
14147 got_worktree_get_repo_path(worktree));
14148 if (repo_path == NULL) {
14149 error = got_error_from_errno("strdup");
14150 goto done;
14153 if (commit_id_str == NULL) {
14154 /* Release work tree lock. */
14155 got_worktree_close(worktree);
14156 worktree = NULL;
14161 if (repo_path == NULL) {
14162 repo_path = strdup(cwd);
14163 if (repo_path == NULL)
14164 return got_error_from_errno("strdup");
14167 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14168 free(repo_path);
14169 if (error != NULL)
14170 goto done;
14172 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14173 if (error)
14174 goto done;
14176 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14177 if (error)
14178 goto done;
14180 if (commit_id_str != NULL) {
14181 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14182 repo, worktree);
14183 if (error != NULL)
14184 goto done;
14185 if (keyword_idstr != NULL)
14186 commit_id_str = keyword_idstr;
14187 if (worktree != NULL) {
14188 got_worktree_close(worktree);
14189 worktree = NULL;
14191 } else
14192 commit_id_str = GOT_REF_HEAD;
14193 error = got_repo_match_object_id(&commit_id, NULL,
14194 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14195 if (error)
14196 goto done;
14198 error = got_object_open_as_commit(&commit, repo, commit_id);
14199 if (error)
14200 goto done;
14202 for (i = 0; i < argc; i++) {
14203 if (force_path) {
14204 error = got_object_id_by_path(&id, repo, commit,
14205 argv[i]);
14206 if (error)
14207 break;
14208 } else {
14209 error = got_repo_match_object_id(&id, &label, argv[i],
14210 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14211 repo);
14212 if (error) {
14213 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14214 error->code != GOT_ERR_NOT_REF)
14215 break;
14216 error = got_object_id_by_path(&id, repo,
14217 commit, argv[i]);
14218 if (error)
14219 break;
14223 error = got_object_get_type(&obj_type, repo, id);
14224 if (error)
14225 break;
14227 switch (obj_type) {
14228 case GOT_OBJ_TYPE_BLOB:
14229 error = cat_blob(id, repo, stdout);
14230 break;
14231 case GOT_OBJ_TYPE_TREE:
14232 error = cat_tree(id, repo, stdout);
14233 break;
14234 case GOT_OBJ_TYPE_COMMIT:
14235 error = cat_commit(id, repo, stdout);
14236 break;
14237 case GOT_OBJ_TYPE_TAG:
14238 error = cat_tag(id, repo, stdout);
14239 break;
14240 default:
14241 error = got_error(GOT_ERR_OBJ_TYPE);
14242 break;
14244 if (error)
14245 break;
14246 free(label);
14247 label = NULL;
14248 free(id);
14249 id = NULL;
14251 done:
14252 free(label);
14253 free(id);
14254 free(commit_id);
14255 free(keyword_idstr);
14256 if (commit)
14257 got_object_commit_close(commit);
14258 if (worktree)
14259 got_worktree_close(worktree);
14260 if (repo) {
14261 const struct got_error *close_err = got_repo_close(repo);
14262 if (error == NULL)
14263 error = close_err;
14265 if (pack_fds) {
14266 const struct got_error *pack_err =
14267 got_repo_pack_fds_close(pack_fds);
14268 if (error == NULL)
14269 error = pack_err;
14272 got_ref_list_free(&refs);
14273 return error;
14276 __dead static void
14277 usage_info(void)
14279 fprintf(stderr, "usage: %s info [path ...]\n",
14280 getprogname());
14281 exit(1);
14284 static const struct got_error *
14285 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14286 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14287 struct got_object_id *commit_id)
14289 const struct got_error *err = NULL;
14290 char *id_str = NULL;
14291 char datebuf[128];
14292 struct tm mytm, *tm;
14293 struct got_pathlist_head *paths = arg;
14294 struct got_pathlist_entry *pe;
14297 * Clear error indication from any of the path arguments which
14298 * would cause this file index entry to be displayed.
14300 TAILQ_FOREACH(pe, paths, entry) {
14301 if (got_path_cmp(path, pe->path, strlen(path),
14302 pe->path_len) == 0 ||
14303 got_path_is_child(path, pe->path, pe->path_len))
14304 pe->data = NULL; /* no error */
14307 printf(GOT_COMMIT_SEP_STR);
14308 if (S_ISLNK(mode))
14309 printf("symlink: %s\n", path);
14310 else if (S_ISREG(mode)) {
14311 printf("file: %s\n", path);
14312 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14313 } else if (S_ISDIR(mode))
14314 printf("directory: %s\n", path);
14315 else
14316 printf("something: %s\n", path);
14318 tm = localtime_r(&mtime, &mytm);
14319 if (tm == NULL)
14320 return NULL;
14321 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14322 return got_error(GOT_ERR_NO_SPACE);
14323 printf("timestamp: %s\n", datebuf);
14325 if (blob_id) {
14326 err = got_object_id_str(&id_str, blob_id);
14327 if (err)
14328 return err;
14329 printf("based on blob: %s\n", id_str);
14330 free(id_str);
14333 if (staged_blob_id) {
14334 err = got_object_id_str(&id_str, staged_blob_id);
14335 if (err)
14336 return err;
14337 printf("based on staged blob: %s\n", id_str);
14338 free(id_str);
14341 if (commit_id) {
14342 err = got_object_id_str(&id_str, commit_id);
14343 if (err)
14344 return err;
14345 printf("based on commit: %s\n", id_str);
14346 free(id_str);
14349 return NULL;
14352 static const struct got_error *
14353 cmd_info(int argc, char *argv[])
14355 const struct got_error *error = NULL;
14356 struct got_worktree *worktree = NULL;
14357 char *cwd = NULL, *id_str = NULL;
14358 struct got_pathlist_head paths;
14359 char *uuidstr = NULL;
14360 int ch, show_files = 0;
14362 TAILQ_INIT(&paths);
14364 #ifndef PROFILE
14365 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14366 NULL) == -1)
14367 err(1, "pledge");
14368 #endif
14370 while ((ch = getopt(argc, argv, "")) != -1) {
14371 switch (ch) {
14372 default:
14373 usage_info();
14374 /* NOTREACHED */
14378 argc -= optind;
14379 argv += optind;
14381 cwd = getcwd(NULL, 0);
14382 if (cwd == NULL) {
14383 error = got_error_from_errno("getcwd");
14384 goto done;
14387 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14388 if (error) {
14389 if (error->code == GOT_ERR_NOT_WORKTREE)
14390 error = wrap_not_worktree_error(error, "info", cwd);
14391 goto done;
14394 #ifndef PROFILE
14395 /* Remove "wpath cpath proc exec sendfd" promises. */
14396 if (pledge("stdio rpath flock unveil", NULL) == -1)
14397 err(1, "pledge");
14398 #endif
14399 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14400 if (error)
14401 goto done;
14403 if (argc >= 1) {
14404 error = get_worktree_paths_from_argv(&paths, argc, argv,
14405 worktree);
14406 if (error)
14407 goto done;
14408 show_files = 1;
14411 error = got_object_id_str(&id_str,
14412 got_worktree_get_base_commit_id(worktree));
14413 if (error)
14414 goto done;
14416 error = got_worktree_get_uuid(&uuidstr, worktree);
14417 if (error)
14418 goto done;
14420 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14421 printf("work tree base commit: %s\n", id_str);
14422 printf("work tree path prefix: %s\n",
14423 got_worktree_get_path_prefix(worktree));
14424 printf("work tree branch reference: %s\n",
14425 got_worktree_get_head_ref_name(worktree));
14426 printf("work tree UUID: %s\n", uuidstr);
14427 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14429 if (show_files) {
14430 struct got_pathlist_entry *pe;
14431 TAILQ_FOREACH(pe, &paths, entry) {
14432 if (pe->path_len == 0)
14433 continue;
14435 * Assume this path will fail. This will be corrected
14436 * in print_path_info() in case the path does suceeed.
14438 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14440 error = got_worktree_path_info(worktree, &paths,
14441 print_path_info, &paths, check_cancelled, NULL);
14442 if (error)
14443 goto done;
14444 TAILQ_FOREACH(pe, &paths, entry) {
14445 if (pe->data != NULL) {
14446 const struct got_error *perr;
14448 perr = pe->data;
14449 error = got_error_fmt(perr->code, "%s",
14450 pe->path);
14451 break;
14455 done:
14456 if (worktree)
14457 got_worktree_close(worktree);
14458 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14459 free(cwd);
14460 free(id_str);
14461 free(uuidstr);
14462 return error;