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;
2292 struct got_remote_repo *remote = NULL;
2293 int nremotes;
2294 char *id_str = NULL;
2295 struct got_repository *repo = NULL;
2296 struct got_worktree *worktree = NULL;
2297 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2298 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2299 char *head_refname = NULL;
2300 struct got_pathlist_entry *pe;
2301 struct got_reflist_head remote_refs;
2302 struct got_reflist_entry *re;
2303 struct got_object_id *pack_hash = NULL;
2304 int i, ch, fetchfd = -1, fetchstatus;
2305 pid_t fetchpid = -1;
2306 struct got_fetch_progress_arg fpa;
2307 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2308 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2309 int *pack_fds = NULL, have_bflag = 0;
2310 const char *remote_head = NULL, *worktree_branch = NULL;
2312 TAILQ_INIT(&refs);
2313 TAILQ_INIT(&symrefs);
2314 TAILQ_INIT(&remote_refs);
2315 TAILQ_INIT(&wanted_branches);
2316 TAILQ_INIT(&wanted_refs);
2318 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2319 switch (ch) {
2320 case 'a':
2321 fetch_all_branches = 1;
2322 break;
2323 case 'b':
2324 error = got_pathlist_append(&wanted_branches,
2325 optarg, NULL);
2326 if (error)
2327 return error;
2328 have_bflag = 1;
2329 break;
2330 case 'd':
2331 delete_refs = 1;
2332 break;
2333 case 'l':
2334 list_refs_only = 1;
2335 break;
2336 case 'q':
2337 verbosity = -1;
2338 break;
2339 case 'R':
2340 error = got_pathlist_append(&wanted_refs,
2341 optarg, NULL);
2342 if (error)
2343 return error;
2344 break;
2345 case 'r':
2346 repo_path = realpath(optarg, NULL);
2347 if (repo_path == NULL)
2348 return got_error_from_errno2("realpath",
2349 optarg);
2350 got_path_strip_trailing_slashes(repo_path);
2351 break;
2352 case 't':
2353 replace_tags = 1;
2354 break;
2355 case 'v':
2356 if (verbosity < 0)
2357 verbosity = 0;
2358 else if (verbosity < 3)
2359 verbosity++;
2360 break;
2361 case 'X':
2362 delete_remote = 1;
2363 break;
2364 default:
2365 usage_fetch();
2366 break;
2369 argc -= optind;
2370 argv += optind;
2372 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('a', 'b');
2374 if (list_refs_only) {
2375 if (!TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('l', 'b');
2377 if (fetch_all_branches)
2378 option_conflict('l', 'a');
2379 if (delete_refs)
2380 option_conflict('l', 'd');
2381 if (delete_remote)
2382 option_conflict('l', 'X');
2384 if (delete_remote) {
2385 if (fetch_all_branches)
2386 option_conflict('X', 'a');
2387 if (!TAILQ_EMPTY(&wanted_branches))
2388 option_conflict('X', 'b');
2389 if (delete_refs)
2390 option_conflict('X', 'd');
2391 if (replace_tags)
2392 option_conflict('X', 't');
2393 if (!TAILQ_EMPTY(&wanted_refs))
2394 option_conflict('X', 'R');
2397 if (argc == 0) {
2398 if (delete_remote)
2399 errx(1, "-X option requires a remote name");
2400 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2401 } else if (argc == 1)
2402 remote_name = argv[0];
2403 else
2404 usage_fetch();
2406 cwd = getcwd(NULL, 0);
2407 if (cwd == NULL) {
2408 error = got_error_from_errno("getcwd");
2409 goto done;
2412 error = got_repo_pack_fds_open(&pack_fds);
2413 if (error != NULL)
2414 goto done;
2416 if (repo_path == NULL) {
2417 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2418 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2419 goto done;
2420 else
2421 error = NULL;
2422 if (worktree) {
2423 repo_path =
2424 strdup(got_worktree_get_repo_path(worktree));
2425 if (repo_path == NULL)
2426 error = got_error_from_errno("strdup");
2427 if (error)
2428 goto done;
2429 } else {
2430 repo_path = strdup(cwd);
2431 if (repo_path == NULL) {
2432 error = got_error_from_errno("strdup");
2433 goto done;
2438 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2439 if (error)
2440 goto done;
2442 if (delete_remote) {
2443 error = delete_refs_for_remote(repo, remote_name);
2444 goto done; /* nothing else to do */
2447 if (worktree) {
2448 worktree_conf = got_worktree_get_gotconfig(worktree);
2449 if (worktree_conf) {
2450 got_gotconfig_get_remotes(&nremotes, &remotes,
2451 worktree_conf);
2452 for (i = 0; i < nremotes; i++) {
2453 if (strcmp(remotes[i].name, remote_name) == 0) {
2454 error = got_repo_remote_repo_dup(&remote,
2455 &remotes[i]);
2456 if (error)
2457 goto done;
2458 break;
2463 if (remote == NULL) {
2464 repo_conf = got_repo_get_gotconfig(repo);
2465 if (repo_conf) {
2466 got_gotconfig_get_remotes(&nremotes, &remotes,
2467 repo_conf);
2468 for (i = 0; i < nremotes; i++) {
2469 if (strcmp(remotes[i].name, remote_name) == 0) {
2470 error = got_repo_remote_repo_dup(&remote,
2471 &remotes[i]);
2472 if (error)
2473 goto done;
2474 break;
2479 if (remote == NULL) {
2480 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2481 for (i = 0; i < nremotes; i++) {
2482 if (strcmp(remotes[i].name, remote_name) == 0) {
2483 error = got_repo_remote_repo_dup(&remote,
2484 &remotes[i]);
2485 if (error)
2486 goto done;
2487 break;
2491 if (remote == NULL) {
2492 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2493 goto done;
2496 if (TAILQ_EMPTY(&wanted_branches)) {
2497 if (!fetch_all_branches)
2498 fetch_all_branches = remote->fetch_all_branches;
2499 for (i = 0; i < remote->nfetch_branches; i++) {
2500 error = got_pathlist_append(&wanted_branches,
2501 remote->fetch_branches[i], NULL);
2502 if (error)
2503 goto done;
2506 if (TAILQ_EMPTY(&wanted_refs)) {
2507 for (i = 0; i < remote->nfetch_refs; i++) {
2508 error = got_pathlist_append(&wanted_refs,
2509 remote->fetch_refs[i], NULL);
2510 if (error)
2511 goto done;
2515 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2516 &repo_name, remote->fetch_url);
2517 if (error)
2518 goto done;
2520 if (strcmp(proto, "git") == 0) {
2521 #ifndef PROFILE
2522 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2523 "sendfd dns inet unveil", NULL) == -1)
2524 err(1, "pledge");
2525 #endif
2526 } else if (strcmp(proto, "git+ssh") == 0 ||
2527 strcmp(proto, "ssh") == 0) {
2528 #ifndef PROFILE
2529 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2530 "sendfd unveil", NULL) == -1)
2531 err(1, "pledge");
2532 #endif
2533 } else if (strcmp(proto, "http") == 0 ||
2534 strcmp(proto, "git+http") == 0) {
2535 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2536 goto done;
2537 } else {
2538 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2539 goto done;
2542 error = got_dial_apply_unveil(proto);
2543 if (error)
2544 goto done;
2546 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2547 if (error)
2548 goto done;
2550 if (worktree) {
2551 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2552 if (head_refname == NULL) {
2553 error = got_error_from_errno("strdup");
2554 goto done;
2557 /* Release work tree lock. */
2558 got_worktree_close(worktree);
2559 worktree = NULL;
2562 if (verbosity >= 0) {
2563 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2564 remote->name, proto, host,
2565 port ? ":" : "", port ? port : "",
2566 *server_path == '/' ? "" : "/", server_path);
2569 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2570 server_path, verbosity);
2571 if (error)
2572 goto done;
2574 if (!have_bflag) {
2576 * If set, get this remote's HEAD ref target so
2577 * if it has changed on the server we can fetch it.
2579 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2580 got_ref_cmp_by_name, repo);
2581 if (error)
2582 goto done;
2584 TAILQ_FOREACH(re, &remote_refs, entry) {
2585 const char *remote_refname, *remote_target;
2586 size_t remote_name_len;
2588 if (!got_ref_is_symbolic(re->ref))
2589 continue;
2591 remote_name_len = strlen(remote->name);
2592 remote_refname = got_ref_get_name(re->ref);
2594 /* we only want refs/remotes/$remote->name/HEAD */
2595 if (strncmp(remote_refname + 13, remote->name,
2596 remote_name_len) != 0)
2597 continue;
2599 if (strcmp(remote_refname + remote_name_len + 14,
2600 GOT_REF_HEAD) != 0)
2601 continue;
2604 * Take the name itself because we already
2605 * only match with refs/heads/ in fetch_pack().
2607 remote_target = got_ref_get_symref_target(re->ref);
2608 remote_head = remote_target + remote_name_len + 14;
2609 break;
2612 if (head_refname &&
2613 strncmp(head_refname, "refs/heads/", 11) == 0)
2614 worktree_branch = head_refname;
2617 fpa.last_scaled_size[0] = '\0';
2618 fpa.last_p_indexed = -1;
2619 fpa.last_p_resolved = -1;
2620 fpa.verbosity = verbosity;
2621 fpa.repo = repo;
2622 fpa.create_configs = 0;
2623 fpa.configs_created = 0;
2624 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2626 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2627 remote->mirror_references, fetch_all_branches, &wanted_branches,
2628 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2629 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2630 if (error)
2631 goto done;
2633 if (list_refs_only) {
2634 error = list_remote_refs(&symrefs, &refs);
2635 goto done;
2638 if (pack_hash == NULL) {
2639 if (verbosity >= 0)
2640 printf("Already up-to-date\n");
2641 } else if (verbosity >= 0) {
2642 error = got_object_id_str(&id_str, pack_hash);
2643 if (error)
2644 goto done;
2645 printf("\nFetched %s.pack\n", id_str);
2646 free(id_str);
2647 id_str = NULL;
2650 /* Update references provided with the pack file. */
2651 TAILQ_FOREACH(pe, &refs, entry) {
2652 const char *refname = pe->path;
2653 struct got_object_id *id = pe->data;
2654 struct got_reference *ref;
2655 char *remote_refname;
2657 if (is_wanted_ref(&wanted_refs, refname) &&
2658 !remote->mirror_references) {
2659 error = update_wanted_ref(refname, id,
2660 remote->name, verbosity, repo);
2661 if (error)
2662 goto done;
2663 continue;
2666 if (remote->mirror_references ||
2667 strncmp("refs/tags/", refname, 10) == 0) {
2668 error = got_ref_open(&ref, repo, refname, 1);
2669 if (error) {
2670 if (error->code != GOT_ERR_NOT_REF)
2671 goto done;
2672 error = create_ref(refname, id, verbosity,
2673 repo);
2674 if (error)
2675 goto done;
2676 } else {
2677 error = update_ref(ref, id, replace_tags,
2678 verbosity, repo);
2679 unlock_err = got_ref_unlock(ref);
2680 if (unlock_err && error == NULL)
2681 error = unlock_err;
2682 got_ref_close(ref);
2683 if (error)
2684 goto done;
2686 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2687 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2688 remote_name, refname + 11) == -1) {
2689 error = got_error_from_errno("asprintf");
2690 goto done;
2693 error = got_ref_open(&ref, repo, remote_refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(remote_refname, id,
2698 verbosity, repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 error = update_ref(ref, id, replace_tags,
2703 verbosity, repo);
2704 unlock_err = got_ref_unlock(ref);
2705 if (unlock_err && error == NULL)
2706 error = unlock_err;
2707 got_ref_close(ref);
2708 if (error)
2709 goto done;
2712 /* Also create a local branch if none exists yet. */
2713 error = got_ref_open(&ref, repo, refname, 1);
2714 if (error) {
2715 if (error->code != GOT_ERR_NOT_REF)
2716 goto done;
2717 error = create_ref(refname, id, verbosity,
2718 repo);
2719 if (error)
2720 goto done;
2721 } else {
2722 unlock_err = got_ref_unlock(ref);
2723 if (unlock_err && error == NULL)
2724 error = unlock_err;
2725 got_ref_close(ref);
2729 if (delete_refs) {
2730 error = delete_missing_refs(&refs, &symrefs, remote,
2731 verbosity, repo);
2732 if (error)
2733 goto done;
2736 if (!remote->mirror_references) {
2737 /* Update remote HEAD reference if the server provided one. */
2738 TAILQ_FOREACH(pe, &symrefs, entry) {
2739 struct got_reference *target_ref;
2740 const char *refname = pe->path;
2741 const char *target = pe->data;
2742 char *remote_refname = NULL, *remote_target = NULL;
2744 if (strcmp(refname, GOT_REF_HEAD) != 0)
2745 continue;
2747 if (strncmp("refs/heads/", target, 11) != 0)
2748 continue;
2750 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2751 remote->name, refname) == -1) {
2752 error = got_error_from_errno("asprintf");
2753 goto done;
2755 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2756 remote->name, target + 11) == -1) {
2757 error = got_error_from_errno("asprintf");
2758 free(remote_refname);
2759 goto done;
2762 error = got_ref_open(&target_ref, repo, remote_target,
2763 0);
2764 if (error) {
2765 free(remote_refname);
2766 free(remote_target);
2767 if (error->code == GOT_ERR_NOT_REF) {
2768 error = NULL;
2769 continue;
2771 goto done;
2773 error = update_symref(remote_refname, target_ref,
2774 verbosity, repo);
2775 free(remote_refname);
2776 free(remote_target);
2777 got_ref_close(target_ref);
2778 if (error)
2779 goto done;
2782 done:
2783 if (fetchpid > 0) {
2784 if (kill(fetchpid, SIGTERM) == -1)
2785 error = got_error_from_errno("kill");
2786 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2787 error = got_error_from_errno("waitpid");
2789 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2790 error = got_error_from_errno("close");
2791 if (repo) {
2792 const struct got_error *close_err = got_repo_close(repo);
2793 if (error == NULL)
2794 error = close_err;
2796 if (worktree)
2797 got_worktree_close(worktree);
2798 if (pack_fds) {
2799 const struct got_error *pack_err =
2800 got_repo_pack_fds_close(pack_fds);
2801 if (error == NULL)
2802 error = pack_err;
2804 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2805 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2806 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2807 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2808 got_ref_list_free(&remote_refs);
2809 got_repo_free_remote_repo_data(remote);
2810 free(remote);
2811 free(head_refname);
2812 free(id_str);
2813 free(cwd);
2814 free(repo_path);
2815 free(pack_hash);
2816 free(proto);
2817 free(host);
2818 free(port);
2819 free(server_path);
2820 free(repo_name);
2821 return error;
2825 __dead static void
2826 usage_checkout(void)
2828 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2829 "[-p path-prefix] repository-path [work-tree-path]\n",
2830 getprogname());
2831 exit(1);
2834 static void
2835 show_worktree_base_ref_warning(void)
2837 fprintf(stderr, "%s: warning: could not create a reference "
2838 "to the work tree's base commit; the commit could be "
2839 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2840 "repository writable and running 'got update' will prevent this\n",
2841 getprogname());
2844 struct got_checkout_progress_arg {
2845 const char *worktree_path;
2846 int had_base_commit_ref_error;
2847 int verbosity;
2850 static const struct got_error *
2851 checkout_progress(void *arg, unsigned char status, const char *path)
2853 struct got_checkout_progress_arg *a = arg;
2855 /* Base commit bump happens silently. */
2856 if (status == GOT_STATUS_BUMP_BASE)
2857 return NULL;
2859 if (status == GOT_STATUS_BASE_REF_ERR) {
2860 a->had_base_commit_ref_error = 1;
2861 return NULL;
2864 while (path[0] == '/')
2865 path++;
2867 if (a->verbosity >= 0)
2868 printf("%c %s/%s\n", status, a->worktree_path, path);
2870 return NULL;
2873 static const struct got_error *
2874 check_cancelled(void *arg)
2876 if (sigint_received || sigpipe_received)
2877 return got_error(GOT_ERR_CANCELLED);
2878 return NULL;
2881 static const struct got_error *
2882 check_linear_ancestry(struct got_object_id *commit_id,
2883 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2884 struct got_repository *repo)
2886 const struct got_error *err = NULL;
2887 struct got_object_id *yca_id;
2889 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2890 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2891 if (err)
2892 return err;
2894 if (yca_id == NULL)
2895 return got_error(GOT_ERR_ANCESTRY);
2898 * Require a straight line of history between the target commit
2899 * and the work tree's base commit.
2901 * Non-linear situations such as this require a rebase:
2903 * (commit) D F (base_commit)
2904 * \ /
2905 * C E
2906 * \ /
2907 * B (yca)
2908 * |
2909 * A
2911 * 'got update' only handles linear cases:
2912 * Update forwards in time: A (base/yca) - B - C - D (commit)
2913 * Update backwards in time: D (base) - C - B - A (commit/yca)
2915 if (allow_forwards_in_time_only) {
2916 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2917 return got_error(GOT_ERR_ANCESTRY);
2918 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2919 got_object_id_cmp(base_commit_id, yca_id) != 0)
2920 return got_error(GOT_ERR_ANCESTRY);
2922 free(yca_id);
2923 return NULL;
2926 static const struct got_error *
2927 check_same_branch(struct got_object_id *commit_id,
2928 struct got_reference *head_ref, struct got_repository *repo)
2930 const struct got_error *err = NULL;
2931 struct got_commit_graph *graph = NULL;
2932 struct got_object_id *head_commit_id = NULL;
2934 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2935 if (err)
2936 goto done;
2938 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2939 goto done;
2941 err = got_commit_graph_open(&graph, "/", 1);
2942 if (err)
2943 goto done;
2945 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2946 check_cancelled, NULL);
2947 if (err)
2948 goto done;
2950 for (;;) {
2951 struct got_object_id id;
2953 err = got_commit_graph_iter_next(&id, graph, repo,
2954 check_cancelled, NULL);
2955 if (err) {
2956 if (err->code == GOT_ERR_ITER_COMPLETED)
2957 err = got_error(GOT_ERR_ANCESTRY);
2958 break;
2961 if (got_object_id_cmp(&id, commit_id) == 0)
2962 break;
2964 done:
2965 if (graph)
2966 got_commit_graph_close(graph);
2967 free(head_commit_id);
2968 return err;
2971 static const struct got_error *
2972 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2974 static char msg[512];
2975 const char *branch_name;
2977 if (got_ref_is_symbolic(ref))
2978 branch_name = got_ref_get_symref_target(ref);
2979 else
2980 branch_name = got_ref_get_name(ref);
2982 if (strncmp("refs/heads/", branch_name, 11) == 0)
2983 branch_name += 11;
2985 snprintf(msg, sizeof(msg),
2986 "target commit is not contained in branch '%s'; "
2987 "the branch to use must be specified with -b; "
2988 "if necessary a new branch can be created for "
2989 "this commit with 'got branch -c %s BRANCH_NAME'",
2990 branch_name, commit_id_str);
2992 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2995 static const struct got_error *
2996 cmd_checkout(int argc, char *argv[])
2998 const struct got_error *error = NULL;
2999 struct got_repository *repo = NULL;
3000 struct got_reference *head_ref = NULL, *ref = NULL;
3001 struct got_worktree *worktree = NULL;
3002 char *repo_path = NULL;
3003 char *worktree_path = NULL;
3004 const char *path_prefix = "";
3005 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3006 char *commit_id_str = NULL, *keyword_idstr = NULL;
3007 struct got_object_id *commit_id = NULL;
3008 char *cwd = NULL;
3009 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3010 struct got_pathlist_head paths;
3011 struct got_checkout_progress_arg cpa;
3012 int *pack_fds = NULL;
3014 TAILQ_INIT(&paths);
3016 #ifndef PROFILE
3017 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3018 "unveil", NULL) == -1)
3019 err(1, "pledge");
3020 #endif
3022 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3023 switch (ch) {
3024 case 'b':
3025 branch_name = optarg;
3026 break;
3027 case 'c':
3028 commit_id_str = strdup(optarg);
3029 if (commit_id_str == NULL)
3030 return got_error_from_errno("strdup");
3031 break;
3032 case 'E':
3033 allow_nonempty = 1;
3034 break;
3035 case 'p':
3036 path_prefix = optarg;
3037 break;
3038 case 'q':
3039 verbosity = -1;
3040 break;
3041 default:
3042 usage_checkout();
3043 /* NOTREACHED */
3047 argc -= optind;
3048 argv += optind;
3050 if (argc == 1) {
3051 char *base, *dotgit;
3052 const char *path;
3053 repo_path = realpath(argv[0], NULL);
3054 if (repo_path == NULL)
3055 return got_error_from_errno2("realpath", argv[0]);
3056 cwd = getcwd(NULL, 0);
3057 if (cwd == NULL) {
3058 error = got_error_from_errno("getcwd");
3059 goto done;
3061 if (path_prefix[0])
3062 path = path_prefix;
3063 else
3064 path = repo_path;
3065 error = got_path_basename(&base, path);
3066 if (error)
3067 goto done;
3068 dotgit = strstr(base, ".git");
3069 if (dotgit)
3070 *dotgit = '\0';
3071 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3072 error = got_error_from_errno("asprintf");
3073 free(base);
3074 goto done;
3076 free(base);
3077 } else if (argc == 2) {
3078 repo_path = realpath(argv[0], NULL);
3079 if (repo_path == NULL) {
3080 error = got_error_from_errno2("realpath", argv[0]);
3081 goto done;
3083 worktree_path = realpath(argv[1], NULL);
3084 if (worktree_path == NULL) {
3085 if (errno != ENOENT) {
3086 error = got_error_from_errno2("realpath",
3087 argv[1]);
3088 goto done;
3090 worktree_path = strdup(argv[1]);
3091 if (worktree_path == NULL) {
3092 error = got_error_from_errno("strdup");
3093 goto done;
3096 } else
3097 usage_checkout();
3099 got_path_strip_trailing_slashes(repo_path);
3100 got_path_strip_trailing_slashes(worktree_path);
3102 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3103 got_path_is_child(repo_path, worktree_path,
3104 strlen(worktree_path))) {
3105 error = got_error_fmt(GOT_ERR_BAD_PATH,
3106 "work tree and repository paths may not overlap: %s",
3107 worktree_path);
3108 goto done;
3111 error = got_repo_pack_fds_open(&pack_fds);
3112 if (error != NULL)
3113 goto done;
3115 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3116 if (error != NULL)
3117 goto done;
3119 /* Pre-create work tree path for unveil(2) */
3120 error = got_path_mkdir(worktree_path);
3121 if (error) {
3122 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3123 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3124 goto done;
3125 if (!allow_nonempty &&
3126 !got_path_dir_is_empty(worktree_path)) {
3127 error = got_error_path(worktree_path,
3128 GOT_ERR_DIR_NOT_EMPTY);
3129 goto done;
3133 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3134 if (error)
3135 goto done;
3137 error = got_ref_open(&head_ref, repo, branch_name, 0);
3138 if (error != NULL)
3139 goto done;
3141 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3142 GOT_WORKTREE_GOT_DIR, repo);
3143 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3144 goto done;
3146 error = got_worktree_open(&worktree, worktree_path,
3147 GOT_WORKTREE_GOT_DIR);
3148 if (error != NULL)
3149 goto done;
3151 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3152 path_prefix);
3153 if (error != NULL)
3154 goto done;
3155 if (!same_path_prefix) {
3156 error = got_error(GOT_ERR_PATH_PREFIX);
3157 goto done;
3160 if (commit_id_str) {
3161 struct got_reflist_head refs;
3162 TAILQ_INIT(&refs);
3163 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3164 NULL);
3165 if (error)
3166 goto done;
3168 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3169 repo, worktree);
3170 if (error != NULL)
3171 goto done;
3172 if (keyword_idstr != NULL) {
3173 free(commit_id_str);
3174 commit_id_str = keyword_idstr;
3177 error = got_repo_match_object_id(&commit_id, NULL,
3178 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3179 got_ref_list_free(&refs);
3180 if (error)
3181 goto done;
3182 error = check_linear_ancestry(commit_id,
3183 got_worktree_get_base_commit_id(worktree), 0, repo);
3184 if (error != NULL) {
3185 if (error->code == GOT_ERR_ANCESTRY) {
3186 error = checkout_ancestry_error(
3187 head_ref, commit_id_str);
3189 goto done;
3191 error = check_same_branch(commit_id, head_ref, repo);
3192 if (error) {
3193 if (error->code == GOT_ERR_ANCESTRY) {
3194 error = checkout_ancestry_error(
3195 head_ref, commit_id_str);
3197 goto done;
3199 error = got_worktree_set_base_commit_id(worktree, repo,
3200 commit_id);
3201 if (error)
3202 goto done;
3203 /* Expand potentially abbreviated commit ID string. */
3204 free(commit_id_str);
3205 error = got_object_id_str(&commit_id_str, commit_id);
3206 if (error)
3207 goto done;
3208 } else {
3209 commit_id = got_object_id_dup(
3210 got_worktree_get_base_commit_id(worktree));
3211 if (commit_id == NULL) {
3212 error = got_error_from_errno("got_object_id_dup");
3213 goto done;
3215 error = got_object_id_str(&commit_id_str, commit_id);
3216 if (error)
3217 goto done;
3220 error = got_pathlist_append(&paths, "", NULL);
3221 if (error)
3222 goto done;
3223 cpa.worktree_path = worktree_path;
3224 cpa.had_base_commit_ref_error = 0;
3225 cpa.verbosity = verbosity;
3226 error = got_worktree_checkout_files(worktree, &paths, repo,
3227 checkout_progress, &cpa, check_cancelled, NULL);
3228 if (error != NULL)
3229 goto done;
3231 if (got_ref_is_symbolic(head_ref)) {
3232 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3233 if (error)
3234 goto done;
3235 refname = got_ref_get_name(ref);
3236 } else
3237 refname = got_ref_get_name(head_ref);
3238 printf("Checked out %s: %s\n", refname, commit_id_str);
3239 printf("Now shut up and hack\n");
3240 if (cpa.had_base_commit_ref_error)
3241 show_worktree_base_ref_warning();
3242 done:
3243 if (pack_fds) {
3244 const struct got_error *pack_err =
3245 got_repo_pack_fds_close(pack_fds);
3246 if (error == NULL)
3247 error = pack_err;
3249 if (head_ref)
3250 got_ref_close(head_ref);
3251 if (ref)
3252 got_ref_close(ref);
3253 if (repo) {
3254 const struct got_error *close_err = got_repo_close(repo);
3255 if (error == NULL)
3256 error = close_err;
3258 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3259 free(commit_id_str);
3260 free(commit_id);
3261 free(repo_path);
3262 free(worktree_path);
3263 free(cwd);
3264 return error;
3267 struct got_update_progress_arg {
3268 int did_something;
3269 int conflicts;
3270 int obstructed;
3271 int not_updated;
3272 int missing;
3273 int not_deleted;
3274 int unversioned;
3275 int verbosity;
3278 static void
3279 print_update_progress_stats(struct got_update_progress_arg *upa)
3281 if (!upa->did_something)
3282 return;
3284 if (upa->conflicts > 0)
3285 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3286 if (upa->obstructed > 0)
3287 printf("File paths obstructed by a non-regular file: %d\n",
3288 upa->obstructed);
3289 if (upa->not_updated > 0)
3290 printf("Files not updated because of existing merge "
3291 "conflicts: %d\n", upa->not_updated);
3295 * The meaning of some status codes differs between merge-style operations and
3296 * update operations. For example, the ! status code means "file was missing"
3297 * if changes were merged into the work tree, and "missing file was restored"
3298 * if the work tree was updated. This function should be used by any operation
3299 * which merges changes into the work tree without updating the work tree.
3301 static void
3302 print_merge_progress_stats(struct got_update_progress_arg *upa)
3304 if (!upa->did_something)
3305 return;
3307 if (upa->conflicts > 0)
3308 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3309 if (upa->obstructed > 0)
3310 printf("File paths obstructed by a non-regular file: %d\n",
3311 upa->obstructed);
3312 if (upa->missing > 0)
3313 printf("Files which had incoming changes but could not be "
3314 "found in the work tree: %d\n", upa->missing);
3315 if (upa->not_deleted > 0)
3316 printf("Files not deleted due to differences in deleted "
3317 "content: %d\n", upa->not_deleted);
3318 if (upa->unversioned > 0)
3319 printf("Files not merged because an unversioned file was "
3320 "found in the work tree: %d\n", upa->unversioned);
3323 __dead static void
3324 usage_update(void)
3326 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3327 "[path ...]\n", getprogname());
3328 exit(1);
3331 static const struct got_error *
3332 update_progress(void *arg, unsigned char status, const char *path)
3334 struct got_update_progress_arg *upa = arg;
3336 if (status == GOT_STATUS_EXISTS ||
3337 status == GOT_STATUS_BASE_REF_ERR)
3338 return NULL;
3340 upa->did_something = 1;
3342 /* Base commit bump happens silently. */
3343 if (status == GOT_STATUS_BUMP_BASE)
3344 return NULL;
3346 if (status == GOT_STATUS_CONFLICT)
3347 upa->conflicts++;
3348 if (status == GOT_STATUS_OBSTRUCTED)
3349 upa->obstructed++;
3350 if (status == GOT_STATUS_CANNOT_UPDATE)
3351 upa->not_updated++;
3352 if (status == GOT_STATUS_MISSING)
3353 upa->missing++;
3354 if (status == GOT_STATUS_CANNOT_DELETE)
3355 upa->not_deleted++;
3356 if (status == GOT_STATUS_UNVERSIONED)
3357 upa->unversioned++;
3359 while (path[0] == '/')
3360 path++;
3361 if (upa->verbosity >= 0)
3362 printf("%c %s\n", status, path);
3364 return NULL;
3367 static const struct got_error *
3368 switch_head_ref(struct got_reference *head_ref,
3369 struct got_object_id *commit_id, struct got_worktree *worktree,
3370 struct got_repository *repo)
3372 const struct got_error *err = NULL;
3373 char *base_id_str;
3374 int ref_has_moved = 0;
3376 /* Trivial case: switching between two different references. */
3377 if (strcmp(got_ref_get_name(head_ref),
3378 got_worktree_get_head_ref_name(worktree)) != 0) {
3379 printf("Switching work tree from %s to %s\n",
3380 got_worktree_get_head_ref_name(worktree),
3381 got_ref_get_name(head_ref));
3382 return got_worktree_set_head_ref(worktree, head_ref);
3385 err = check_linear_ancestry(commit_id,
3386 got_worktree_get_base_commit_id(worktree), 0, repo);
3387 if (err) {
3388 if (err->code != GOT_ERR_ANCESTRY)
3389 return err;
3390 ref_has_moved = 1;
3392 if (!ref_has_moved)
3393 return NULL;
3395 /* Switching to a rebased branch with the same reference name. */
3396 err = got_object_id_str(&base_id_str,
3397 got_worktree_get_base_commit_id(worktree));
3398 if (err)
3399 return err;
3400 printf("Reference %s now points at a different branch\n",
3401 got_worktree_get_head_ref_name(worktree));
3402 printf("Switching work tree from %s to %s\n", base_id_str,
3403 got_worktree_get_head_ref_name(worktree));
3404 return NULL;
3407 static const struct got_error *
3408 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3410 const struct got_error *err;
3411 int in_progress;
3413 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3414 if (err)
3415 return err;
3416 if (in_progress)
3417 return got_error(GOT_ERR_REBASING);
3419 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3420 if (err)
3421 return err;
3422 if (in_progress)
3423 return got_error(GOT_ERR_HISTEDIT_BUSY);
3425 return NULL;
3428 static const struct got_error *
3429 check_merge_in_progress(struct got_worktree *worktree,
3430 struct got_repository *repo)
3432 const struct got_error *err;
3433 int in_progress;
3435 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3436 if (err)
3437 return err;
3438 if (in_progress)
3439 return got_error(GOT_ERR_MERGE_BUSY);
3441 return NULL;
3444 static const struct got_error *
3445 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3446 char *argv[], struct got_worktree *worktree)
3448 const struct got_error *err = NULL;
3449 char *path;
3450 struct got_pathlist_entry *new;
3451 int i;
3453 if (argc == 0) {
3454 path = strdup("");
3455 if (path == NULL)
3456 return got_error_from_errno("strdup");
3457 return got_pathlist_append(paths, path, NULL);
3460 for (i = 0; i < argc; i++) {
3461 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3462 if (err)
3463 break;
3464 err = got_pathlist_insert(&new, paths, path, NULL);
3465 if (err || new == NULL /* duplicate */) {
3466 free(path);
3467 if (err)
3468 break;
3472 return err;
3475 static const struct got_error *
3476 wrap_not_worktree_error(const struct got_error *orig_err,
3477 const char *cmdname, const char *path)
3479 const struct got_error *err;
3480 struct got_repository *repo;
3481 static char msg[512];
3482 int *pack_fds = NULL;
3484 err = got_repo_pack_fds_open(&pack_fds);
3485 if (err)
3486 return err;
3488 err = got_repo_open(&repo, path, NULL, pack_fds);
3489 if (err)
3490 return orig_err;
3492 snprintf(msg, sizeof(msg),
3493 "'got %s' needs a work tree in addition to a git repository\n"
3494 "Work trees can be checked out from this Git repository with "
3495 "'got checkout'.\n"
3496 "The got(1) manual page contains more information.", cmdname);
3497 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3498 if (repo) {
3499 const struct got_error *close_err = got_repo_close(repo);
3500 if (err == NULL)
3501 err = close_err;
3503 if (pack_fds) {
3504 const struct got_error *pack_err =
3505 got_repo_pack_fds_close(pack_fds);
3506 if (err == NULL)
3507 err = pack_err;
3509 return err;
3512 static const struct got_error *
3513 cmd_update(int argc, char *argv[])
3515 const struct got_error *error = NULL;
3516 struct got_repository *repo = NULL;
3517 struct got_worktree *worktree = NULL;
3518 char *worktree_path = NULL;
3519 struct got_object_id *commit_id = NULL;
3520 char *commit_id_str = NULL;
3521 const char *branch_name = NULL;
3522 struct got_reference *head_ref = NULL;
3523 struct got_pathlist_head paths;
3524 struct got_pathlist_entry *pe;
3525 int ch, verbosity = 0;
3526 struct got_update_progress_arg upa;
3527 int *pack_fds = NULL;
3529 TAILQ_INIT(&paths);
3531 #ifndef PROFILE
3532 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3533 "unveil", NULL) == -1)
3534 err(1, "pledge");
3535 #endif
3537 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3538 switch (ch) {
3539 case 'b':
3540 branch_name = optarg;
3541 break;
3542 case 'c':
3543 commit_id_str = strdup(optarg);
3544 if (commit_id_str == NULL)
3545 return got_error_from_errno("strdup");
3546 break;
3547 case 'q':
3548 verbosity = -1;
3549 break;
3550 default:
3551 usage_update();
3552 /* NOTREACHED */
3556 argc -= optind;
3557 argv += optind;
3559 worktree_path = getcwd(NULL, 0);
3560 if (worktree_path == NULL) {
3561 error = got_error_from_errno("getcwd");
3562 goto done;
3565 error = got_repo_pack_fds_open(&pack_fds);
3566 if (error != NULL)
3567 goto done;
3569 error = got_worktree_open(&worktree, worktree_path,
3570 GOT_WORKTREE_GOT_DIR);
3571 if (error) {
3572 if (error->code == GOT_ERR_NOT_WORKTREE)
3573 error = wrap_not_worktree_error(error, "update",
3574 worktree_path);
3575 goto done;
3578 error = check_rebase_or_histedit_in_progress(worktree);
3579 if (error)
3580 goto done;
3582 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3583 NULL, pack_fds);
3584 if (error != NULL)
3585 goto done;
3587 error = apply_unveil(got_repo_get_path(repo), 0,
3588 got_worktree_get_root_path(worktree));
3589 if (error)
3590 goto done;
3592 error = check_merge_in_progress(worktree, repo);
3593 if (error)
3594 goto done;
3596 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3597 if (error)
3598 goto done;
3600 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3601 got_worktree_get_head_ref_name(worktree), 0);
3602 if (error != NULL)
3603 goto done;
3604 if (commit_id_str == NULL) {
3605 error = got_ref_resolve(&commit_id, repo, head_ref);
3606 if (error != NULL)
3607 goto done;
3608 error = got_object_id_str(&commit_id_str, commit_id);
3609 if (error != NULL)
3610 goto done;
3611 } else {
3612 struct got_reflist_head refs;
3613 char *keyword_idstr = NULL;
3615 TAILQ_INIT(&refs);
3617 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3618 NULL);
3619 if (error)
3620 goto done;
3622 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3623 repo, worktree);
3624 if (error != NULL)
3625 goto done;
3626 if (keyword_idstr != NULL) {
3627 free(commit_id_str);
3628 commit_id_str = keyword_idstr;
3631 error = got_repo_match_object_id(&commit_id, NULL,
3632 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3633 got_ref_list_free(&refs);
3634 free(commit_id_str);
3635 commit_id_str = NULL;
3636 if (error)
3637 goto done;
3638 error = got_object_id_str(&commit_id_str, commit_id);
3639 if (error)
3640 goto done;
3643 if (branch_name) {
3644 struct got_object_id *head_commit_id;
3645 TAILQ_FOREACH(pe, &paths, entry) {
3646 if (pe->path_len == 0)
3647 continue;
3648 error = got_error_msg(GOT_ERR_BAD_PATH,
3649 "switching between branches requires that "
3650 "the entire work tree gets updated");
3651 goto done;
3653 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3654 if (error)
3655 goto done;
3656 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3657 repo);
3658 free(head_commit_id);
3659 if (error != NULL)
3660 goto done;
3661 error = check_same_branch(commit_id, head_ref, repo);
3662 if (error)
3663 goto done;
3664 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3665 if (error)
3666 goto done;
3667 } else {
3668 error = check_linear_ancestry(commit_id,
3669 got_worktree_get_base_commit_id(worktree), 0, repo);
3670 if (error != NULL) {
3671 if (error->code == GOT_ERR_ANCESTRY)
3672 error = got_error(GOT_ERR_BRANCH_MOVED);
3673 goto done;
3675 error = check_same_branch(commit_id, head_ref, repo);
3676 if (error)
3677 goto done;
3680 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3681 commit_id) != 0) {
3682 error = got_worktree_set_base_commit_id(worktree, repo,
3683 commit_id);
3684 if (error)
3685 goto done;
3688 memset(&upa, 0, sizeof(upa));
3689 upa.verbosity = verbosity;
3690 error = got_worktree_checkout_files(worktree, &paths, repo,
3691 update_progress, &upa, check_cancelled, NULL);
3692 if (error != NULL)
3693 goto done;
3695 if (upa.did_something) {
3696 printf("Updated to %s: %s\n",
3697 got_worktree_get_head_ref_name(worktree), commit_id_str);
3698 } else
3699 printf("Already up-to-date\n");
3701 print_update_progress_stats(&upa);
3702 done:
3703 if (pack_fds) {
3704 const struct got_error *pack_err =
3705 got_repo_pack_fds_close(pack_fds);
3706 if (error == NULL)
3707 error = pack_err;
3709 if (repo) {
3710 const struct got_error *close_err = got_repo_close(repo);
3711 if (error == NULL)
3712 error = close_err;
3714 if (head_ref != NULL)
3715 got_ref_close(head_ref);
3716 free(worktree_path);
3717 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3718 free(commit_id);
3719 free(commit_id_str);
3720 return error;
3723 static const struct got_error *
3724 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3725 const char *path, int diff_context, int ignore_whitespace,
3726 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3727 struct got_repository *repo, FILE *outfile)
3729 const struct got_error *err = NULL;
3730 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3731 FILE *f1 = NULL, *f2 = NULL;
3732 int fd1 = -1, fd2 = -1;
3734 fd1 = got_opentempfd();
3735 if (fd1 == -1)
3736 return got_error_from_errno("got_opentempfd");
3737 fd2 = got_opentempfd();
3738 if (fd2 == -1) {
3739 err = got_error_from_errno("got_opentempfd");
3740 goto done;
3743 if (blob_id1) {
3744 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3745 fd1);
3746 if (err)
3747 goto done;
3750 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3751 if (err)
3752 goto done;
3754 f1 = got_opentemp();
3755 if (f1 == NULL) {
3756 err = got_error_from_errno("got_opentemp");
3757 goto done;
3759 f2 = got_opentemp();
3760 if (f2 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3765 while (path[0] == '/')
3766 path++;
3767 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3768 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3769 force_text_diff, dsa, outfile);
3770 done:
3771 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3772 err = got_error_from_errno("close");
3773 if (blob1)
3774 got_object_blob_close(blob1);
3775 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3776 err = got_error_from_errno("close");
3777 if (blob2)
3778 got_object_blob_close(blob2);
3779 if (f1 && fclose(f1) == EOF && err == NULL)
3780 err = got_error_from_errno("fclose");
3781 if (f2 && fclose(f2) == EOF && err == NULL)
3782 err = got_error_from_errno("fclose");
3783 return err;
3786 static const struct got_error *
3787 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3788 const char *path, int diff_context, int ignore_whitespace,
3789 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3790 struct got_repository *repo, FILE *outfile)
3792 const struct got_error *err = NULL;
3793 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3794 struct got_diff_blob_output_unidiff_arg arg;
3795 FILE *f1 = NULL, *f2 = NULL;
3796 int fd1 = -1, fd2 = -1;
3798 if (tree_id1) {
3799 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3800 if (err)
3801 goto done;
3802 fd1 = got_opentempfd();
3803 if (fd1 == -1) {
3804 err = got_error_from_errno("got_opentempfd");
3805 goto done;
3809 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3810 if (err)
3811 goto done;
3813 f1 = got_opentemp();
3814 if (f1 == NULL) {
3815 err = got_error_from_errno("got_opentemp");
3816 goto done;
3819 f2 = got_opentemp();
3820 if (f2 == NULL) {
3821 err = got_error_from_errno("got_opentemp");
3822 goto done;
3824 fd2 = got_opentempfd();
3825 if (fd2 == -1) {
3826 err = got_error_from_errno("got_opentempfd");
3827 goto done;
3829 arg.diff_context = diff_context;
3830 arg.ignore_whitespace = ignore_whitespace;
3831 arg.force_text_diff = force_text_diff;
3832 arg.diffstat = dsa;
3833 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3834 arg.outfile = outfile;
3835 arg.lines = NULL;
3836 arg.nlines = 0;
3837 while (path[0] == '/')
3838 path++;
3839 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3840 got_diff_blob_output_unidiff, &arg, 1);
3841 done:
3842 if (tree1)
3843 got_object_tree_close(tree1);
3844 if (tree2)
3845 got_object_tree_close(tree2);
3846 if (f1 && fclose(f1) == EOF && err == NULL)
3847 err = got_error_from_errno("fclose");
3848 if (f2 && fclose(f2) == EOF && err == NULL)
3849 err = got_error_from_errno("fclose");
3850 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3851 err = got_error_from_errno("close");
3852 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3853 err = got_error_from_errno("close");
3854 return err;
3857 static const struct got_error *
3858 get_changed_paths(struct got_pathlist_head *paths,
3859 struct got_commit_object *commit, struct got_repository *repo,
3860 struct got_diffstat_cb_arg *dsa)
3862 const struct got_error *err = NULL;
3863 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3864 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3865 struct got_object_qid *qid;
3866 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3867 FILE *f1 = NULL, *f2 = NULL;
3868 int fd1 = -1, fd2 = -1;
3870 if (dsa) {
3871 cb = got_diff_tree_compute_diffstat;
3873 f1 = got_opentemp();
3874 if (f1 == NULL) {
3875 err = got_error_from_errno("got_opentemp");
3876 goto done;
3878 f2 = got_opentemp();
3879 if (f2 == NULL) {
3880 err = got_error_from_errno("got_opentemp");
3881 goto done;
3883 fd1 = got_opentempfd();
3884 if (fd1 == -1) {
3885 err = got_error_from_errno("got_opentempfd");
3886 goto done;
3888 fd2 = got_opentempfd();
3889 if (fd2 == -1) {
3890 err = got_error_from_errno("got_opentempfd");
3891 goto done;
3895 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3896 if (qid != NULL) {
3897 struct got_commit_object *pcommit;
3898 err = got_object_open_as_commit(&pcommit, repo,
3899 &qid->id);
3900 if (err)
3901 return err;
3903 tree_id1 = got_object_id_dup(
3904 got_object_commit_get_tree_id(pcommit));
3905 if (tree_id1 == NULL) {
3906 got_object_commit_close(pcommit);
3907 return got_error_from_errno("got_object_id_dup");
3909 got_object_commit_close(pcommit);
3913 if (tree_id1) {
3914 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3915 if (err)
3916 goto done;
3919 tree_id2 = got_object_commit_get_tree_id(commit);
3920 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3921 if (err)
3922 goto done;
3924 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3925 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3926 done:
3927 if (tree1)
3928 got_object_tree_close(tree1);
3929 if (tree2)
3930 got_object_tree_close(tree2);
3931 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3932 err = got_error_from_errno("close");
3933 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3934 err = got_error_from_errno("close");
3935 if (f1 && fclose(f1) == EOF && err == NULL)
3936 err = got_error_from_errno("fclose");
3937 if (f2 && fclose(f2) == EOF && err == NULL)
3938 err = got_error_from_errno("fclose");
3939 free(tree_id1);
3940 return err;
3943 static const struct got_error *
3944 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3945 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3946 struct got_repository *repo, FILE *outfile)
3948 const struct got_error *err = NULL;
3949 struct got_commit_object *pcommit = NULL;
3950 char *id_str1 = NULL, *id_str2 = NULL;
3951 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3952 struct got_object_qid *qid;
3954 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3955 if (qid != NULL) {
3956 err = got_object_open_as_commit(&pcommit, repo,
3957 &qid->id);
3958 if (err)
3959 return err;
3960 err = got_object_id_str(&id_str1, &qid->id);
3961 if (err)
3962 goto done;
3965 err = got_object_id_str(&id_str2, id);
3966 if (err)
3967 goto done;
3969 if (path && path[0] != '\0') {
3970 int obj_type;
3971 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3972 if (err)
3973 goto done;
3974 if (pcommit) {
3975 err = got_object_id_by_path(&obj_id1, repo,
3976 pcommit, path);
3977 if (err) {
3978 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3979 free(obj_id2);
3980 goto done;
3984 err = got_object_get_type(&obj_type, repo, obj_id2);
3985 if (err) {
3986 free(obj_id2);
3987 goto done;
3989 fprintf(outfile,
3990 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3991 fprintf(outfile, "commit - %s\n",
3992 id_str1 ? id_str1 : "/dev/null");
3993 fprintf(outfile, "commit + %s\n", id_str2);
3994 switch (obj_type) {
3995 case GOT_OBJ_TYPE_BLOB:
3996 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3997 0, 0, dsa, repo, outfile);
3998 break;
3999 case GOT_OBJ_TYPE_TREE:
4000 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4001 0, 0, dsa, repo, outfile);
4002 break;
4003 default:
4004 err = got_error(GOT_ERR_OBJ_TYPE);
4005 break;
4007 free(obj_id1);
4008 free(obj_id2);
4009 } else {
4010 obj_id2 = got_object_commit_get_tree_id(commit);
4011 if (pcommit)
4012 obj_id1 = got_object_commit_get_tree_id(pcommit);
4013 fprintf(outfile,
4014 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4015 fprintf(outfile, "commit - %s\n",
4016 id_str1 ? id_str1 : "/dev/null");
4017 fprintf(outfile, "commit + %s\n", id_str2);
4018 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4019 dsa, repo, outfile);
4021 done:
4022 free(id_str1);
4023 free(id_str2);
4024 if (pcommit)
4025 got_object_commit_close(pcommit);
4026 return err;
4029 static char *
4030 get_datestr(time_t *time, char *datebuf)
4032 struct tm mytm, *tm;
4033 char *p, *s;
4035 tm = gmtime_r(time, &mytm);
4036 if (tm == NULL)
4037 return NULL;
4038 s = asctime_r(tm, datebuf);
4039 if (s == NULL)
4040 return NULL;
4041 p = strchr(s, '\n');
4042 if (p)
4043 *p = '\0';
4044 return s;
4047 static const struct got_error *
4048 match_commit(int *have_match, struct got_object_id *id,
4049 struct got_commit_object *commit, regex_t *regex)
4051 const struct got_error *err = NULL;
4052 regmatch_t regmatch;
4053 char *id_str = NULL, *logmsg = NULL;
4055 *have_match = 0;
4057 err = got_object_id_str(&id_str, id);
4058 if (err)
4059 return err;
4061 err = got_object_commit_get_logmsg(&logmsg, commit);
4062 if (err)
4063 goto done;
4065 if (regexec(regex, got_object_commit_get_author(commit), 1,
4066 &regmatch, 0) == 0 ||
4067 regexec(regex, got_object_commit_get_committer(commit), 1,
4068 &regmatch, 0) == 0 ||
4069 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4070 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4071 *have_match = 1;
4072 done:
4073 free(id_str);
4074 free(logmsg);
4075 return err;
4078 static void
4079 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4080 regex_t *regex)
4082 regmatch_t regmatch;
4083 struct got_pathlist_entry *pe;
4085 *have_match = 0;
4087 TAILQ_FOREACH(pe, changed_paths, entry) {
4088 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4089 *have_match = 1;
4090 break;
4095 static const struct got_error *
4096 match_patch(int *have_match, struct got_commit_object *commit,
4097 struct got_object_id *id, const char *path, int diff_context,
4098 struct got_repository *repo, regex_t *regex, FILE *f)
4100 const struct got_error *err = NULL;
4101 char *line = NULL;
4102 size_t linesize = 0;
4103 regmatch_t regmatch;
4105 *have_match = 0;
4107 err = got_opentemp_truncate(f);
4108 if (err)
4109 return err;
4111 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4112 if (err)
4113 goto done;
4115 if (fseeko(f, 0L, SEEK_SET) == -1) {
4116 err = got_error_from_errno("fseeko");
4117 goto done;
4120 while (getline(&line, &linesize, f) != -1) {
4121 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4122 *have_match = 1;
4123 break;
4126 done:
4127 free(line);
4128 return err;
4131 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4133 static const struct got_error*
4134 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4135 struct got_object_id *id, struct got_repository *repo,
4136 int local_only)
4138 static const struct got_error *err = NULL;
4139 struct got_reflist_entry *re;
4140 char *s;
4141 const char *name;
4143 *refs_str = NULL;
4145 TAILQ_FOREACH(re, refs, entry) {
4146 struct got_tag_object *tag = NULL;
4147 struct got_object_id *ref_id;
4148 int cmp;
4150 name = got_ref_get_name(re->ref);
4151 if (strcmp(name, GOT_REF_HEAD) == 0)
4152 continue;
4153 if (strncmp(name, "refs/", 5) == 0)
4154 name += 5;
4155 if (strncmp(name, "got/", 4) == 0)
4156 continue;
4157 if (strncmp(name, "heads/", 6) == 0)
4158 name += 6;
4159 if (strncmp(name, "remotes/", 8) == 0) {
4160 if (local_only)
4161 continue;
4162 name += 8;
4163 s = strstr(name, "/" GOT_REF_HEAD);
4164 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4165 continue;
4167 err = got_ref_resolve(&ref_id, repo, re->ref);
4168 if (err)
4169 break;
4170 if (strncmp(name, "tags/", 5) == 0) {
4171 err = got_object_open_as_tag(&tag, repo, ref_id);
4172 if (err) {
4173 if (err->code != GOT_ERR_OBJ_TYPE) {
4174 free(ref_id);
4175 break;
4177 /* Ref points at something other than a tag. */
4178 err = NULL;
4179 tag = NULL;
4182 cmp = got_object_id_cmp(tag ?
4183 got_object_tag_get_object_id(tag) : ref_id, id);
4184 free(ref_id);
4185 if (tag)
4186 got_object_tag_close(tag);
4187 if (cmp != 0)
4188 continue;
4189 s = *refs_str;
4190 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4191 s ? ", " : "", name) == -1) {
4192 err = got_error_from_errno("asprintf");
4193 free(s);
4194 *refs_str = NULL;
4195 break;
4197 free(s);
4200 return err;
4203 static const struct got_error *
4204 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4205 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4207 const struct got_error *err = NULL;
4208 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4209 char *comma, *s, *nl;
4210 struct got_reflist_head *refs;
4211 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4212 struct tm tm;
4213 time_t committer_time;
4215 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4216 if (refs) {
4217 err = build_refs_str(&ref_str, refs, id, repo, 1);
4218 if (err)
4219 return err;
4221 /* Display the first matching ref only. */
4222 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4223 *comma = '\0';
4226 if (ref_str == NULL) {
4227 err = got_object_id_str(&id_str, id);
4228 if (err)
4229 return err;
4232 committer_time = got_object_commit_get_committer_time(commit);
4233 if (gmtime_r(&committer_time, &tm) == NULL) {
4234 err = got_error_from_errno("gmtime_r");
4235 goto done;
4237 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4238 err = got_error(GOT_ERR_NO_SPACE);
4239 goto done;
4242 err = got_object_commit_get_logmsg(&logmsg0, commit);
4243 if (err)
4244 goto done;
4246 s = logmsg0;
4247 while (isspace((unsigned char)s[0]))
4248 s++;
4250 nl = strchr(s, '\n');
4251 if (nl) {
4252 *nl = '\0';
4255 if (ref_str)
4256 printf("%s%-7s %s\n", datebuf, ref_str, s);
4257 else
4258 printf("%s%.7s %s\n", datebuf, id_str, s);
4260 if (fflush(stdout) != 0 && err == NULL)
4261 err = got_error_from_errno("fflush");
4262 done:
4263 free(id_str);
4264 free(ref_str);
4265 free(logmsg0);
4266 return err;
4269 static const struct got_error *
4270 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4272 struct got_pathlist_entry *pe;
4274 if (header != NULL)
4275 printf("%s\n", header);
4277 TAILQ_FOREACH(pe, dsa->paths, entry) {
4278 struct got_diff_changed_path *cp = pe->data;
4279 int pad = dsa->max_path_len - pe->path_len + 1;
4281 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4282 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4284 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4285 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4286 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4288 if (fflush(stdout) != 0)
4289 return got_error_from_errno("fflush");
4291 return NULL;
4294 static const struct got_error *
4295 printfile(FILE *f)
4297 char buf[8192];
4298 size_t r;
4300 if (fseeko(f, 0L, SEEK_SET) == -1)
4301 return got_error_from_errno("fseek");
4303 for (;;) {
4304 r = fread(buf, 1, sizeof(buf), f);
4305 if (r == 0) {
4306 if (ferror(f))
4307 return got_error_from_errno("fread");
4308 if (feof(f))
4309 break;
4311 if (fwrite(buf, 1, r, stdout) != r)
4312 return got_ferror(stdout, GOT_ERR_IO);
4315 return NULL;
4318 static const struct got_error *
4319 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4320 struct got_repository *repo, const char *path,
4321 struct got_pathlist_head *changed_paths,
4322 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4323 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4324 const char *prefix)
4326 const struct got_error *err = NULL;
4327 FILE *f = NULL;
4328 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4329 char datebuf[26];
4330 time_t committer_time;
4331 const char *author, *committer;
4332 char *refs_str = NULL;
4334 err = got_object_id_str(&id_str, id);
4335 if (err)
4336 return err;
4338 if (custom_refs_str == NULL) {
4339 struct got_reflist_head *refs;
4340 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4341 if (refs) {
4342 err = build_refs_str(&refs_str, refs, id, repo, 0);
4343 if (err)
4344 goto done;
4348 printf(GOT_COMMIT_SEP_STR);
4349 if (custom_refs_str)
4350 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4351 custom_refs_str);
4352 else
4353 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4354 refs_str ? " (" : "", refs_str ? refs_str : "",
4355 refs_str ? ")" : "");
4356 free(id_str);
4357 id_str = NULL;
4358 free(refs_str);
4359 refs_str = NULL;
4360 printf("from: %s\n", got_object_commit_get_author(commit));
4361 author = got_object_commit_get_author(commit);
4362 committer = got_object_commit_get_committer(commit);
4363 if (strcmp(author, committer) != 0)
4364 printf("via: %s\n", committer);
4365 committer_time = got_object_commit_get_committer_time(commit);
4366 datestr = get_datestr(&committer_time, datebuf);
4367 if (datestr)
4368 printf("date: %s UTC\n", datestr);
4369 if (got_object_commit_get_nparents(commit) > 1) {
4370 const struct got_object_id_queue *parent_ids;
4371 struct got_object_qid *qid;
4372 int n = 1;
4373 parent_ids = got_object_commit_get_parent_ids(commit);
4374 STAILQ_FOREACH(qid, parent_ids, entry) {
4375 err = got_object_id_str(&id_str, &qid->id);
4376 if (err)
4377 goto done;
4378 printf("parent %d: %s\n", n++, id_str);
4379 free(id_str);
4380 id_str = NULL;
4384 err = got_object_commit_get_logmsg(&logmsg0, commit);
4385 if (err)
4386 goto done;
4388 logmsg = logmsg0;
4389 do {
4390 line = strsep(&logmsg, "\n");
4391 if (line)
4392 printf(" %s\n", line);
4393 } while (line);
4394 free(logmsg0);
4396 if (changed_paths && diffstat == NULL) {
4397 struct got_pathlist_entry *pe;
4399 TAILQ_FOREACH(pe, changed_paths, entry) {
4400 struct got_diff_changed_path *cp = pe->data;
4402 printf(" %c %s\n", cp->status, pe->path);
4404 printf("\n");
4406 if (show_patch) {
4407 if (diffstat) {
4408 f = got_opentemp();
4409 if (f == NULL) {
4410 err = got_error_from_errno("got_opentemp");
4411 goto done;
4415 err = print_patch(commit, id, path, diff_context, diffstat,
4416 repo, diffstat == NULL ? stdout : f);
4417 if (err)
4418 goto done;
4420 if (diffstat) {
4421 err = print_diffstat(diffstat, NULL);
4422 if (err)
4423 goto done;
4424 if (show_patch) {
4425 err = printfile(f);
4426 if (err)
4427 goto done;
4430 if (show_patch)
4431 printf("\n");
4433 if (fflush(stdout) != 0 && err == NULL)
4434 err = got_error_from_errno("fflush");
4435 done:
4436 if (f && fclose(f) == EOF && err == NULL)
4437 err = got_error_from_errno("fclose");
4438 free(id_str);
4439 free(refs_str);
4440 return err;
4443 static const struct got_error *
4444 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4445 struct got_repository *repo, const char *path, int show_changed_paths,
4446 int show_diffstat, int show_patch, const char *search_pattern,
4447 int diff_context, int limit, int log_branches, int reverse_display_order,
4448 struct got_reflist_object_id_map *refs_idmap, int one_line,
4449 FILE *tmpfile)
4451 const struct got_error *err;
4452 struct got_commit_graph *graph;
4453 regex_t regex;
4454 int have_match;
4455 struct got_object_id_queue reversed_commits;
4456 struct got_object_qid *qid;
4457 struct got_commit_object *commit;
4458 struct got_pathlist_head changed_paths;
4460 STAILQ_INIT(&reversed_commits);
4461 TAILQ_INIT(&changed_paths);
4463 if (search_pattern && regcomp(&regex, search_pattern,
4464 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4465 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4467 err = got_commit_graph_open(&graph, path, !log_branches);
4468 if (err)
4469 return err;
4470 err = got_commit_graph_iter_start(graph, root_id, repo,
4471 check_cancelled, NULL);
4472 if (err)
4473 goto done;
4474 for (;;) {
4475 struct got_object_id id;
4476 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4477 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4479 if (sigint_received || sigpipe_received)
4480 break;
4482 err = got_commit_graph_iter_next(&id, graph, repo,
4483 check_cancelled, NULL);
4484 if (err) {
4485 if (err->code == GOT_ERR_ITER_COMPLETED)
4486 err = NULL;
4487 break;
4490 err = got_object_open_as_commit(&commit, repo, &id);
4491 if (err)
4492 break;
4494 if (((show_changed_paths && !show_diffstat) ||
4495 (show_diffstat && !show_patch))
4496 && !reverse_display_order) {
4497 err = get_changed_paths(&changed_paths, commit, repo,
4498 show_diffstat ? &dsa : NULL);
4499 if (err)
4500 break;
4503 if (search_pattern) {
4504 err = match_commit(&have_match, &id, commit, &regex);
4505 if (err) {
4506 got_object_commit_close(commit);
4507 break;
4509 if (have_match == 0 && show_changed_paths)
4510 match_changed_paths(&have_match,
4511 &changed_paths, &regex);
4512 if (have_match == 0 && show_patch) {
4513 err = match_patch(&have_match, commit, &id,
4514 path, diff_context, repo, &regex, tmpfile);
4515 if (err)
4516 break;
4518 if (have_match == 0) {
4519 got_object_commit_close(commit);
4520 got_pathlist_free(&changed_paths,
4521 GOT_PATHLIST_FREE_ALL);
4522 continue;
4526 if (reverse_display_order) {
4527 err = got_object_qid_alloc(&qid, &id);
4528 if (err)
4529 break;
4530 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4531 got_object_commit_close(commit);
4532 } else {
4533 if (one_line)
4534 err = print_commit_oneline(commit, &id,
4535 repo, refs_idmap);
4536 else
4537 err = print_commit(commit, &id, repo, path,
4538 (show_changed_paths || show_diffstat) ?
4539 &changed_paths : NULL,
4540 show_diffstat ? &dsa : NULL, show_patch,
4541 diff_context, refs_idmap, NULL, NULL);
4542 got_object_commit_close(commit);
4543 if (err)
4544 break;
4546 if ((limit && --limit == 0) ||
4547 (end_id && got_object_id_cmp(&id, end_id) == 0))
4548 break;
4550 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4552 if (reverse_display_order) {
4553 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4554 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4555 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4557 err = got_object_open_as_commit(&commit, repo,
4558 &qid->id);
4559 if (err)
4560 break;
4561 if ((show_changed_paths && !show_diffstat) ||
4562 (show_diffstat && !show_patch)) {
4563 err = get_changed_paths(&changed_paths, commit,
4564 repo, show_diffstat ? &dsa : NULL);
4565 if (err)
4566 break;
4568 if (one_line)
4569 err = print_commit_oneline(commit, &qid->id,
4570 repo, refs_idmap);
4571 else
4572 err = print_commit(commit, &qid->id, repo, path,
4573 (show_changed_paths || show_diffstat) ?
4574 &changed_paths : NULL,
4575 show_diffstat ? &dsa : NULL, show_patch,
4576 diff_context, refs_idmap, NULL, NULL);
4577 got_object_commit_close(commit);
4578 if (err)
4579 break;
4580 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4583 done:
4584 while (!STAILQ_EMPTY(&reversed_commits)) {
4585 qid = STAILQ_FIRST(&reversed_commits);
4586 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4587 got_object_qid_free(qid);
4589 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4590 if (search_pattern)
4591 regfree(&regex);
4592 got_commit_graph_close(graph);
4593 return err;
4596 __dead static void
4597 usage_log(void)
4599 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4600 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4601 "[path]\n", getprogname());
4602 exit(1);
4605 static int
4606 get_default_log_limit(void)
4608 const char *got_default_log_limit;
4609 long long n;
4610 const char *errstr;
4612 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4613 if (got_default_log_limit == NULL)
4614 return 0;
4615 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4616 if (errstr != NULL)
4617 return 0;
4618 return n;
4621 static const struct got_error *
4622 cmd_log(int argc, char *argv[])
4624 const struct got_error *error;
4625 struct got_repository *repo = NULL;
4626 struct got_worktree *worktree = NULL;
4627 struct got_object_id *start_id = NULL, *end_id = NULL;
4628 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4629 char *keyword_idstr = NULL;
4630 const char *start_commit = NULL, *end_commit = NULL;
4631 const char *search_pattern = NULL;
4632 int diff_context = -1, ch;
4633 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4634 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4635 const char *errstr;
4636 struct got_reflist_head refs;
4637 struct got_reflist_object_id_map *refs_idmap = NULL;
4638 FILE *tmpfile = NULL;
4639 int *pack_fds = NULL;
4641 TAILQ_INIT(&refs);
4643 #ifndef PROFILE
4644 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4645 NULL)
4646 == -1)
4647 err(1, "pledge");
4648 #endif
4650 limit = get_default_log_limit();
4652 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4653 switch (ch) {
4654 case 'b':
4655 log_branches = 1;
4656 break;
4657 case 'C':
4658 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4659 &errstr);
4660 if (errstr != NULL)
4661 errx(1, "number of context lines is %s: %s",
4662 errstr, optarg);
4663 break;
4664 case 'c':
4665 start_commit = optarg;
4666 break;
4667 case 'd':
4668 show_diffstat = 1;
4669 break;
4670 case 'l':
4671 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4672 if (errstr != NULL)
4673 errx(1, "number of commits is %s: %s",
4674 errstr, optarg);
4675 break;
4676 case 'P':
4677 show_changed_paths = 1;
4678 break;
4679 case 'p':
4680 show_patch = 1;
4681 break;
4682 case 'R':
4683 reverse_display_order = 1;
4684 break;
4685 case 'r':
4686 repo_path = realpath(optarg, NULL);
4687 if (repo_path == NULL)
4688 return got_error_from_errno2("realpath",
4689 optarg);
4690 got_path_strip_trailing_slashes(repo_path);
4691 break;
4692 case 'S':
4693 search_pattern = optarg;
4694 break;
4695 case 's':
4696 one_line = 1;
4697 break;
4698 case 'x':
4699 end_commit = optarg;
4700 break;
4701 default:
4702 usage_log();
4703 /* NOTREACHED */
4707 argc -= optind;
4708 argv += optind;
4710 if (diff_context == -1)
4711 diff_context = 3;
4712 else if (!show_patch)
4713 errx(1, "-C requires -p");
4715 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4716 errx(1, "cannot use -s with -d, -p or -P");
4718 cwd = getcwd(NULL, 0);
4719 if (cwd == NULL) {
4720 error = got_error_from_errno("getcwd");
4721 goto done;
4724 error = got_repo_pack_fds_open(&pack_fds);
4725 if (error != NULL)
4726 goto done;
4728 if (repo_path == NULL) {
4729 error = got_worktree_open(&worktree, cwd,
4730 GOT_WORKTREE_GOT_DIR);
4731 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4732 goto done;
4733 error = NULL;
4736 if (argc == 1) {
4737 if (worktree) {
4738 error = got_worktree_resolve_path(&path, worktree,
4739 argv[0]);
4740 if (error)
4741 goto done;
4742 } else {
4743 path = strdup(argv[0]);
4744 if (path == NULL) {
4745 error = got_error_from_errno("strdup");
4746 goto done;
4749 } else if (argc != 0)
4750 usage_log();
4752 if (repo_path == NULL) {
4753 repo_path = worktree ?
4754 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4756 if (repo_path == NULL) {
4757 error = got_error_from_errno("strdup");
4758 goto done;
4761 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4762 if (error != NULL)
4763 goto done;
4765 error = apply_unveil(got_repo_get_path(repo), 1,
4766 worktree ? got_worktree_get_root_path(worktree) : NULL);
4767 if (error)
4768 goto done;
4770 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4771 if (error)
4772 goto done;
4774 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4775 if (error)
4776 goto done;
4778 if (start_commit == NULL) {
4779 struct got_reference *head_ref;
4780 struct got_commit_object *commit = NULL;
4781 error = got_ref_open(&head_ref, repo,
4782 worktree ? got_worktree_get_head_ref_name(worktree)
4783 : GOT_REF_HEAD, 0);
4784 if (error != NULL)
4785 goto done;
4786 error = got_ref_resolve(&start_id, repo, head_ref);
4787 got_ref_close(head_ref);
4788 if (error != NULL)
4789 goto done;
4790 error = got_object_open_as_commit(&commit, repo,
4791 start_id);
4792 if (error != NULL)
4793 goto done;
4794 got_object_commit_close(commit);
4795 } else {
4796 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4797 repo, worktree);
4798 if (error != NULL)
4799 goto done;
4800 if (keyword_idstr != NULL)
4801 start_commit = keyword_idstr;
4803 error = got_repo_match_object_id(&start_id, NULL,
4804 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4805 if (error != NULL)
4806 goto done;
4808 if (end_commit != NULL) {
4809 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4810 repo, worktree);
4811 if (error != NULL)
4812 goto done;
4813 if (keyword_idstr != NULL)
4814 end_commit = keyword_idstr;
4816 error = got_repo_match_object_id(&end_id, NULL,
4817 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4818 if (error != NULL)
4819 goto done;
4822 if (worktree) {
4824 * If a path was specified on the command line it was resolved
4825 * to a path in the work tree above. Prepend the work tree's
4826 * path prefix to obtain the corresponding in-repository path.
4828 if (path) {
4829 const char *prefix;
4830 prefix = got_worktree_get_path_prefix(worktree);
4831 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4832 (path[0] != '\0') ? "/" : "", path) == -1) {
4833 error = got_error_from_errno("asprintf");
4834 goto done;
4837 } else
4838 error = got_repo_map_path(&in_repo_path, repo,
4839 path ? path : "");
4840 if (error != NULL)
4841 goto done;
4842 if (in_repo_path) {
4843 free(path);
4844 path = in_repo_path;
4847 if (worktree) {
4848 /* Release work tree lock. */
4849 got_worktree_close(worktree);
4850 worktree = NULL;
4853 if (search_pattern && show_patch) {
4854 tmpfile = got_opentemp();
4855 if (tmpfile == NULL) {
4856 error = got_error_from_errno("got_opentemp");
4857 goto done;
4861 error = print_commits(start_id, end_id, repo, path ? path : "",
4862 show_changed_paths, show_diffstat, show_patch, search_pattern,
4863 diff_context, limit, log_branches, reverse_display_order,
4864 refs_idmap, one_line, tmpfile);
4865 done:
4866 free(path);
4867 free(repo_path);
4868 free(cwd);
4869 free(start_id);
4870 free(end_id);
4871 free(keyword_idstr);
4872 if (worktree)
4873 got_worktree_close(worktree);
4874 if (repo) {
4875 const struct got_error *close_err = got_repo_close(repo);
4876 if (error == NULL)
4877 error = close_err;
4879 if (pack_fds) {
4880 const struct got_error *pack_err =
4881 got_repo_pack_fds_close(pack_fds);
4882 if (error == NULL)
4883 error = pack_err;
4885 if (refs_idmap)
4886 got_reflist_object_id_map_free(refs_idmap);
4887 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4888 error = got_error_from_errno("fclose");
4889 got_ref_list_free(&refs);
4890 return error;
4893 __dead static void
4894 usage_diff(void)
4896 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4897 "[-r repository-path] [object1 object2 | path ...]\n",
4898 getprogname());
4899 exit(1);
4902 struct print_diff_arg {
4903 struct got_repository *repo;
4904 struct got_worktree *worktree;
4905 struct got_diffstat_cb_arg *diffstat;
4906 int diff_context;
4907 const char *id_str;
4908 int header_shown;
4909 int diff_staged;
4910 enum got_diff_algorithm diff_algo;
4911 int ignore_whitespace;
4912 int force_text_diff;
4913 FILE *f1;
4914 FILE *f2;
4915 FILE *outfile;
4919 * Create a file which contains the target path of a symlink so we can feed
4920 * it as content to the diff engine.
4922 static const struct got_error *
4923 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4924 const char *abspath)
4926 const struct got_error *err = NULL;
4927 char target_path[PATH_MAX];
4928 ssize_t target_len, outlen;
4930 *fd = -1;
4932 if (dirfd != -1) {
4933 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4934 if (target_len == -1)
4935 return got_error_from_errno2("readlinkat", abspath);
4936 } else {
4937 target_len = readlink(abspath, target_path, PATH_MAX);
4938 if (target_len == -1)
4939 return got_error_from_errno2("readlink", abspath);
4942 *fd = got_opentempfd();
4943 if (*fd == -1)
4944 return got_error_from_errno("got_opentempfd");
4946 outlen = write(*fd, target_path, target_len);
4947 if (outlen == -1) {
4948 err = got_error_from_errno("got_opentempfd");
4949 goto done;
4952 if (lseek(*fd, 0, SEEK_SET) == -1) {
4953 err = got_error_from_errno2("lseek", abspath);
4954 goto done;
4956 done:
4957 if (err) {
4958 close(*fd);
4959 *fd = -1;
4961 return err;
4964 static const struct got_error *
4965 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4966 const char *path, struct got_object_id *blob_id,
4967 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4968 int dirfd, const char *de_name)
4970 struct print_diff_arg *a = arg;
4971 const struct got_error *err = NULL;
4972 struct got_blob_object *blob1 = NULL;
4973 int fd = -1, fd1 = -1, fd2 = -1;
4974 FILE *f2 = NULL;
4975 char *abspath = NULL, *label1 = NULL;
4976 struct stat sb;
4977 off_t size1 = 0;
4978 int f2_exists = 0;
4980 memset(&sb, 0, sizeof(sb));
4982 if (a->diff_staged) {
4983 if (staged_status != GOT_STATUS_MODIFY &&
4984 staged_status != GOT_STATUS_ADD &&
4985 staged_status != GOT_STATUS_DELETE)
4986 return NULL;
4987 } else {
4988 if (staged_status == GOT_STATUS_DELETE)
4989 return NULL;
4990 if (status == GOT_STATUS_NONEXISTENT)
4991 return got_error_set_errno(ENOENT, path);
4992 if (status != GOT_STATUS_MODIFY &&
4993 status != GOT_STATUS_ADD &&
4994 status != GOT_STATUS_DELETE &&
4995 status != GOT_STATUS_CONFLICT)
4996 return NULL;
4999 err = got_opentemp_truncate(a->f1);
5000 if (err)
5001 return got_error_from_errno("got_opentemp_truncate");
5002 err = got_opentemp_truncate(a->f2);
5003 if (err)
5004 return got_error_from_errno("got_opentemp_truncate");
5006 if (!a->header_shown) {
5007 if (fprintf(a->outfile, "diff %s%s\n",
5008 a->diff_staged ? "-s " : "",
5009 got_worktree_get_root_path(a->worktree)) < 0) {
5010 err = got_error_from_errno("fprintf");
5011 goto done;
5013 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5014 err = got_error_from_errno("fprintf");
5015 goto done;
5017 if (fprintf(a->outfile, "path + %s%s\n",
5018 got_worktree_get_root_path(a->worktree),
5019 a->diff_staged ? " (staged changes)" : "") < 0) {
5020 err = got_error_from_errno("fprintf");
5021 goto done;
5023 a->header_shown = 1;
5026 if (a->diff_staged) {
5027 const char *label1 = NULL, *label2 = NULL;
5028 switch (staged_status) {
5029 case GOT_STATUS_MODIFY:
5030 label1 = path;
5031 label2 = path;
5032 break;
5033 case GOT_STATUS_ADD:
5034 label2 = path;
5035 break;
5036 case GOT_STATUS_DELETE:
5037 label1 = path;
5038 break;
5039 default:
5040 return got_error(GOT_ERR_FILE_STATUS);
5042 fd1 = got_opentempfd();
5043 if (fd1 == -1) {
5044 err = got_error_from_errno("got_opentempfd");
5045 goto done;
5047 fd2 = got_opentempfd();
5048 if (fd2 == -1) {
5049 err = got_error_from_errno("got_opentempfd");
5050 goto done;
5052 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5053 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5054 a->diff_algo, a->diff_context, a->ignore_whitespace,
5055 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5056 goto done;
5059 fd1 = got_opentempfd();
5060 if (fd1 == -1) {
5061 err = got_error_from_errno("got_opentempfd");
5062 goto done;
5065 if (staged_status == GOT_STATUS_ADD ||
5066 staged_status == GOT_STATUS_MODIFY) {
5067 char *id_str;
5068 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5069 8192, fd1);
5070 if (err)
5071 goto done;
5072 err = got_object_id_str(&id_str, staged_blob_id);
5073 if (err)
5074 goto done;
5075 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5076 err = got_error_from_errno("asprintf");
5077 free(id_str);
5078 goto done;
5080 free(id_str);
5081 } else if (status != GOT_STATUS_ADD) {
5082 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5083 fd1);
5084 if (err)
5085 goto done;
5088 if (status != GOT_STATUS_DELETE) {
5089 if (asprintf(&abspath, "%s/%s",
5090 got_worktree_get_root_path(a->worktree), path) == -1) {
5091 err = got_error_from_errno("asprintf");
5092 goto done;
5095 if (dirfd != -1) {
5096 fd = openat(dirfd, de_name,
5097 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5098 if (fd == -1) {
5099 if (!got_err_open_nofollow_on_symlink()) {
5100 err = got_error_from_errno2("openat",
5101 abspath);
5102 goto done;
5104 err = get_symlink_target_file(&fd, dirfd,
5105 de_name, abspath);
5106 if (err)
5107 goto done;
5109 } else {
5110 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5111 if (fd == -1) {
5112 if (!got_err_open_nofollow_on_symlink()) {
5113 err = got_error_from_errno2("open",
5114 abspath);
5115 goto done;
5117 err = get_symlink_target_file(&fd, dirfd,
5118 de_name, abspath);
5119 if (err)
5120 goto done;
5123 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5124 err = got_error_from_errno2("fstatat", abspath);
5125 goto done;
5127 f2 = fdopen(fd, "r");
5128 if (f2 == NULL) {
5129 err = got_error_from_errno2("fdopen", abspath);
5130 goto done;
5132 fd = -1;
5133 f2_exists = 1;
5136 if (blob1) {
5137 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5138 a->f1, blob1);
5139 if (err)
5140 goto done;
5143 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5144 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5145 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5146 done:
5147 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5148 err = got_error_from_errno("close");
5149 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5150 err = got_error_from_errno("close");
5151 if (blob1)
5152 got_object_blob_close(blob1);
5153 if (fd != -1 && close(fd) == -1 && err == NULL)
5154 err = got_error_from_errno("close");
5155 if (f2 && fclose(f2) == EOF && err == NULL)
5156 err = got_error_from_errno("fclose");
5157 free(abspath);
5158 return err;
5161 static const struct got_error *
5162 cmd_diff(int argc, char *argv[])
5164 const struct got_error *error;
5165 struct got_repository *repo = NULL;
5166 struct got_worktree *worktree = NULL;
5167 char *cwd = NULL, *repo_path = NULL;
5168 const char *commit_args[2] = { NULL, NULL };
5169 int ncommit_args = 0;
5170 struct got_object_id *ids[2] = { NULL, NULL };
5171 char *labels[2] = { NULL, NULL };
5172 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5173 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5174 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5175 const char *errstr;
5176 struct got_reflist_head refs;
5177 struct got_pathlist_head diffstat_paths, paths;
5178 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5179 int fd1 = -1, fd2 = -1;
5180 int *pack_fds = NULL;
5181 struct got_diffstat_cb_arg dsa;
5183 memset(&dsa, 0, sizeof(dsa));
5185 TAILQ_INIT(&refs);
5186 TAILQ_INIT(&paths);
5187 TAILQ_INIT(&diffstat_paths);
5189 #ifndef PROFILE
5190 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5191 NULL) == -1)
5192 err(1, "pledge");
5193 #endif
5195 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5196 switch (ch) {
5197 case 'a':
5198 force_text_diff = 1;
5199 break;
5200 case 'C':
5201 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5202 &errstr);
5203 if (errstr != NULL)
5204 errx(1, "number of context lines is %s: %s",
5205 errstr, optarg);
5206 break;
5207 case 'c':
5208 if (ncommit_args >= 2)
5209 errx(1, "too many -c options used");
5210 commit_args[ncommit_args++] = optarg;
5211 break;
5212 case 'd':
5213 show_diffstat = 1;
5214 break;
5215 case 'P':
5216 force_path = 1;
5217 break;
5218 case 'r':
5219 repo_path = realpath(optarg, NULL);
5220 if (repo_path == NULL)
5221 return got_error_from_errno2("realpath",
5222 optarg);
5223 got_path_strip_trailing_slashes(repo_path);
5224 rflag = 1;
5225 break;
5226 case 's':
5227 diff_staged = 1;
5228 break;
5229 case 'w':
5230 ignore_whitespace = 1;
5231 break;
5232 default:
5233 usage_diff();
5234 /* NOTREACHED */
5238 argc -= optind;
5239 argv += optind;
5241 cwd = getcwd(NULL, 0);
5242 if (cwd == NULL) {
5243 error = got_error_from_errno("getcwd");
5244 goto done;
5247 error = got_repo_pack_fds_open(&pack_fds);
5248 if (error != NULL)
5249 goto done;
5251 if (repo_path == NULL) {
5252 error = got_worktree_open(&worktree, cwd,
5253 GOT_WORKTREE_GOT_DIR);
5254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5255 goto done;
5256 else
5257 error = NULL;
5258 if (worktree) {
5259 repo_path =
5260 strdup(got_worktree_get_repo_path(worktree));
5261 if (repo_path == NULL) {
5262 error = got_error_from_errno("strdup");
5263 goto done;
5265 } else {
5266 repo_path = strdup(cwd);
5267 if (repo_path == NULL) {
5268 error = got_error_from_errno("strdup");
5269 goto done;
5274 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5275 free(repo_path);
5276 if (error != NULL)
5277 goto done;
5279 if (show_diffstat) {
5280 dsa.paths = &diffstat_paths;
5281 dsa.force_text = force_text_diff;
5282 dsa.ignore_ws = ignore_whitespace;
5283 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5286 if (rflag || worktree == NULL || ncommit_args > 0) {
5287 if (force_path) {
5288 error = got_error_msg(GOT_ERR_NOT_IMPL,
5289 "-P option can only be used when diffing "
5290 "a work tree");
5291 goto done;
5293 if (diff_staged) {
5294 error = got_error_msg(GOT_ERR_NOT_IMPL,
5295 "-s option can only be used when diffing "
5296 "a work tree");
5297 goto done;
5301 error = apply_unveil(got_repo_get_path(repo), 1,
5302 worktree ? got_worktree_get_root_path(worktree) : NULL);
5303 if (error)
5304 goto done;
5306 if ((!force_path && argc == 2) || ncommit_args > 0) {
5307 int obj_type = (ncommit_args > 0 ?
5308 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5309 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5310 NULL);
5311 if (error)
5312 goto done;
5313 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5314 const char *arg;
5315 char *keyword_idstr = NULL;
5317 if (ncommit_args > 0)
5318 arg = commit_args[i];
5319 else
5320 arg = argv[i];
5322 error = got_keyword_to_idstr(&keyword_idstr, arg,
5323 repo, worktree);
5324 if (error != NULL)
5325 goto done;
5326 if (keyword_idstr != NULL)
5327 arg = keyword_idstr;
5329 error = got_repo_match_object_id(&ids[i], &labels[i],
5330 arg, obj_type, &refs, repo);
5331 free(keyword_idstr);
5332 if (error) {
5333 if (error->code != GOT_ERR_NOT_REF &&
5334 error->code != GOT_ERR_NO_OBJ)
5335 goto done;
5336 if (ncommit_args > 0)
5337 goto done;
5338 error = NULL;
5339 break;
5344 f1 = got_opentemp();
5345 if (f1 == NULL) {
5346 error = got_error_from_errno("got_opentemp");
5347 goto done;
5350 f2 = got_opentemp();
5351 if (f2 == NULL) {
5352 error = got_error_from_errno("got_opentemp");
5353 goto done;
5356 outfile = got_opentemp();
5357 if (outfile == NULL) {
5358 error = got_error_from_errno("got_opentemp");
5359 goto done;
5362 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5363 struct print_diff_arg arg;
5364 char *id_str;
5366 if (worktree == NULL) {
5367 if (argc == 2 && ids[0] == NULL) {
5368 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5369 goto done;
5370 } else if (argc == 2 && ids[1] == NULL) {
5371 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5372 goto done;
5373 } else if (argc > 0) {
5374 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5375 "%s", "specified paths cannot be resolved");
5376 goto done;
5377 } else {
5378 error = got_error(GOT_ERR_NOT_WORKTREE);
5379 goto done;
5383 error = get_worktree_paths_from_argv(&paths, argc, argv,
5384 worktree);
5385 if (error)
5386 goto done;
5388 error = got_object_id_str(&id_str,
5389 got_worktree_get_base_commit_id(worktree));
5390 if (error)
5391 goto done;
5392 arg.repo = repo;
5393 arg.worktree = worktree;
5394 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5395 arg.diff_context = diff_context;
5396 arg.id_str = id_str;
5397 arg.header_shown = 0;
5398 arg.diff_staged = diff_staged;
5399 arg.ignore_whitespace = ignore_whitespace;
5400 arg.force_text_diff = force_text_diff;
5401 arg.diffstat = show_diffstat ? &dsa : NULL;
5402 arg.f1 = f1;
5403 arg.f2 = f2;
5404 arg.outfile = outfile;
5406 error = got_worktree_status(worktree, &paths, repo, 0,
5407 print_diff, &arg, check_cancelled, NULL);
5408 free(id_str);
5409 if (error)
5410 goto done;
5412 if (show_diffstat && dsa.nfiles > 0) {
5413 char *header;
5415 if (asprintf(&header, "diffstat %s%s",
5416 diff_staged ? "-s " : "",
5417 got_worktree_get_root_path(worktree)) == -1) {
5418 error = got_error_from_errno("asprintf");
5419 goto done;
5422 error = print_diffstat(&dsa, header);
5423 free(header);
5424 if (error)
5425 goto done;
5428 error = printfile(outfile);
5429 goto done;
5432 if (ncommit_args == 1) {
5433 struct got_commit_object *commit;
5434 error = got_object_open_as_commit(&commit, repo, ids[0]);
5435 if (error)
5436 goto done;
5438 labels[1] = labels[0];
5439 ids[1] = ids[0];
5440 if (got_object_commit_get_nparents(commit) > 0) {
5441 const struct got_object_id_queue *pids;
5442 struct got_object_qid *pid;
5443 pids = got_object_commit_get_parent_ids(commit);
5444 pid = STAILQ_FIRST(pids);
5445 ids[0] = got_object_id_dup(&pid->id);
5446 if (ids[0] == NULL) {
5447 error = got_error_from_errno(
5448 "got_object_id_dup");
5449 got_object_commit_close(commit);
5450 goto done;
5452 error = got_object_id_str(&labels[0], ids[0]);
5453 if (error) {
5454 got_object_commit_close(commit);
5455 goto done;
5457 } else {
5458 ids[0] = NULL;
5459 labels[0] = strdup("/dev/null");
5460 if (labels[0] == NULL) {
5461 error = got_error_from_errno("strdup");
5462 got_object_commit_close(commit);
5463 goto done;
5467 got_object_commit_close(commit);
5470 if (ncommit_args == 0 && argc > 2) {
5471 error = got_error_msg(GOT_ERR_BAD_PATH,
5472 "path arguments cannot be used when diffing two objects");
5473 goto done;
5476 if (ids[0]) {
5477 error = got_object_get_type(&type1, repo, ids[0]);
5478 if (error)
5479 goto done;
5482 error = got_object_get_type(&type2, repo, ids[1]);
5483 if (error)
5484 goto done;
5485 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5486 error = got_error(GOT_ERR_OBJ_TYPE);
5487 goto done;
5489 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5490 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5491 "path arguments cannot be used when diffing blobs");
5492 goto done;
5495 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5496 char *in_repo_path;
5497 struct got_pathlist_entry *new;
5498 if (worktree) {
5499 const char *prefix;
5500 char *p;
5501 error = got_worktree_resolve_path(&p, worktree,
5502 argv[i]);
5503 if (error)
5504 goto done;
5505 prefix = got_worktree_get_path_prefix(worktree);
5506 while (prefix[0] == '/')
5507 prefix++;
5508 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5509 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5510 p) == -1) {
5511 error = got_error_from_errno("asprintf");
5512 free(p);
5513 goto done;
5515 free(p);
5516 } else {
5517 char *mapped_path, *s;
5518 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5519 if (error)
5520 goto done;
5521 s = mapped_path;
5522 while (s[0] == '/')
5523 s++;
5524 in_repo_path = strdup(s);
5525 if (in_repo_path == NULL) {
5526 error = got_error_from_errno("asprintf");
5527 free(mapped_path);
5528 goto done;
5530 free(mapped_path);
5533 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5534 if (error || new == NULL /* duplicate */)
5535 free(in_repo_path);
5536 if (error)
5537 goto done;
5540 if (worktree) {
5541 /* Release work tree lock. */
5542 got_worktree_close(worktree);
5543 worktree = NULL;
5546 fd1 = got_opentempfd();
5547 if (fd1 == -1) {
5548 error = got_error_from_errno("got_opentempfd");
5549 goto done;
5552 fd2 = got_opentempfd();
5553 if (fd2 == -1) {
5554 error = got_error_from_errno("got_opentempfd");
5555 goto done;
5558 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5559 case GOT_OBJ_TYPE_BLOB:
5560 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5561 fd1, fd2, ids[0], ids[1], NULL, NULL,
5562 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5563 ignore_whitespace, force_text_diff,
5564 show_diffstat ? &dsa : NULL, repo, outfile);
5565 break;
5566 case GOT_OBJ_TYPE_TREE:
5567 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5568 ids[0], ids[1], &paths, "", "",
5569 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5570 ignore_whitespace, force_text_diff,
5571 show_diffstat ? &dsa : NULL, repo, outfile);
5572 break;
5573 case GOT_OBJ_TYPE_COMMIT:
5574 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5575 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5576 fd1, fd2, ids[0], ids[1], &paths,
5577 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5578 ignore_whitespace, force_text_diff,
5579 show_diffstat ? &dsa : NULL, repo, outfile);
5580 break;
5581 default:
5582 error = got_error(GOT_ERR_OBJ_TYPE);
5584 if (error)
5585 goto done;
5587 if (show_diffstat && dsa.nfiles > 0) {
5588 char *header = NULL;
5590 if (asprintf(&header, "diffstat %s %s",
5591 labels[0], labels[1]) == -1) {
5592 error = got_error_from_errno("asprintf");
5593 goto done;
5596 error = print_diffstat(&dsa, header);
5597 free(header);
5598 if (error)
5599 goto done;
5602 error = printfile(outfile);
5604 done:
5605 free(labels[0]);
5606 free(labels[1]);
5607 free(ids[0]);
5608 free(ids[1]);
5609 if (worktree)
5610 got_worktree_close(worktree);
5611 if (repo) {
5612 const struct got_error *close_err = got_repo_close(repo);
5613 if (error == NULL)
5614 error = close_err;
5616 if (pack_fds) {
5617 const struct got_error *pack_err =
5618 got_repo_pack_fds_close(pack_fds);
5619 if (error == NULL)
5620 error = pack_err;
5622 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5623 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5624 got_ref_list_free(&refs);
5625 if (outfile && fclose(outfile) == EOF && error == NULL)
5626 error = got_error_from_errno("fclose");
5627 if (f1 && fclose(f1) == EOF && error == NULL)
5628 error = got_error_from_errno("fclose");
5629 if (f2 && fclose(f2) == EOF && error == NULL)
5630 error = got_error_from_errno("fclose");
5631 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5632 error = got_error_from_errno("close");
5633 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5634 error = got_error_from_errno("close");
5635 return error;
5638 __dead static void
5639 usage_blame(void)
5641 fprintf(stderr,
5642 "usage: %s blame [-c commit] [-r repository-path] path\n",
5643 getprogname());
5644 exit(1);
5647 struct blame_line {
5648 int annotated;
5649 char *id_str;
5650 char *committer;
5651 char datebuf[11]; /* YYYY-MM-DD + NUL */
5654 struct blame_cb_args {
5655 struct blame_line *lines;
5656 int nlines;
5657 int nlines_prec;
5658 int lineno_cur;
5659 off_t *line_offsets;
5660 FILE *f;
5661 struct got_repository *repo;
5664 static const struct got_error *
5665 blame_cb(void *arg, int nlines, int lineno,
5666 struct got_commit_object *commit, struct got_object_id *id)
5668 const struct got_error *err = NULL;
5669 struct blame_cb_args *a = arg;
5670 struct blame_line *bline;
5671 char *line = NULL;
5672 size_t linesize = 0;
5673 off_t offset;
5674 struct tm tm;
5675 time_t committer_time;
5677 if (nlines != a->nlines ||
5678 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5679 return got_error(GOT_ERR_RANGE);
5681 if (sigint_received)
5682 return got_error(GOT_ERR_ITER_COMPLETED);
5684 if (lineno == -1)
5685 return NULL; /* no change in this commit */
5687 /* Annotate this line. */
5688 bline = &a->lines[lineno - 1];
5689 if (bline->annotated)
5690 return NULL;
5691 err = got_object_id_str(&bline->id_str, id);
5692 if (err)
5693 return err;
5695 bline->committer = strdup(got_object_commit_get_committer(commit));
5696 if (bline->committer == NULL) {
5697 err = got_error_from_errno("strdup");
5698 goto done;
5701 committer_time = got_object_commit_get_committer_time(commit);
5702 if (gmtime_r(&committer_time, &tm) == NULL)
5703 return got_error_from_errno("gmtime_r");
5704 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5705 &tm) == 0) {
5706 err = got_error(GOT_ERR_NO_SPACE);
5707 goto done;
5709 bline->annotated = 1;
5711 /* Print lines annotated so far. */
5712 bline = &a->lines[a->lineno_cur - 1];
5713 if (!bline->annotated)
5714 goto done;
5716 offset = a->line_offsets[a->lineno_cur - 1];
5717 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5718 err = got_error_from_errno("fseeko");
5719 goto done;
5722 while (a->lineno_cur <= a->nlines && bline->annotated) {
5723 char *smallerthan, *at, *nl, *committer;
5724 size_t len;
5726 if (getline(&line, &linesize, a->f) == -1) {
5727 if (ferror(a->f))
5728 err = got_error_from_errno("getline");
5729 break;
5732 committer = bline->committer;
5733 smallerthan = strchr(committer, '<');
5734 if (smallerthan && smallerthan[1] != '\0')
5735 committer = smallerthan + 1;
5736 at = strchr(committer, '@');
5737 if (at)
5738 *at = '\0';
5739 len = strlen(committer);
5740 if (len >= 9)
5741 committer[8] = '\0';
5743 nl = strchr(line, '\n');
5744 if (nl)
5745 *nl = '\0';
5746 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5747 bline->id_str, bline->datebuf, committer, line);
5749 a->lineno_cur++;
5750 bline = &a->lines[a->lineno_cur - 1];
5752 done:
5753 free(line);
5754 return err;
5757 static const struct got_error *
5758 cmd_blame(int argc, char *argv[])
5760 const struct got_error *error;
5761 struct got_repository *repo = NULL;
5762 struct got_worktree *worktree = NULL;
5763 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5764 char *link_target = NULL;
5765 struct got_object_id *obj_id = NULL;
5766 struct got_object_id *commit_id = NULL;
5767 struct got_commit_object *commit = NULL;
5768 struct got_blob_object *blob = NULL;
5769 char *commit_id_str = NULL, *keyword_idstr = NULL;
5770 struct blame_cb_args bca;
5771 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5772 off_t filesize;
5773 int *pack_fds = NULL;
5774 FILE *f1 = NULL, *f2 = NULL;
5776 fd1 = got_opentempfd();
5777 if (fd1 == -1)
5778 return got_error_from_errno("got_opentempfd");
5780 memset(&bca, 0, sizeof(bca));
5782 #ifndef PROFILE
5783 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5784 NULL) == -1)
5785 err(1, "pledge");
5786 #endif
5788 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5789 switch (ch) {
5790 case 'c':
5791 commit_id_str = optarg;
5792 break;
5793 case 'r':
5794 repo_path = realpath(optarg, NULL);
5795 if (repo_path == NULL)
5796 return got_error_from_errno2("realpath",
5797 optarg);
5798 got_path_strip_trailing_slashes(repo_path);
5799 break;
5800 default:
5801 usage_blame();
5802 /* NOTREACHED */
5806 argc -= optind;
5807 argv += optind;
5809 if (argc == 1)
5810 path = argv[0];
5811 else
5812 usage_blame();
5814 cwd = getcwd(NULL, 0);
5815 if (cwd == NULL) {
5816 error = got_error_from_errno("getcwd");
5817 goto done;
5820 error = got_repo_pack_fds_open(&pack_fds);
5821 if (error != NULL)
5822 goto done;
5824 if (repo_path == NULL) {
5825 error = got_worktree_open(&worktree, cwd,
5826 GOT_WORKTREE_GOT_DIR);
5827 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5828 goto done;
5829 else
5830 error = NULL;
5831 if (worktree) {
5832 repo_path =
5833 strdup(got_worktree_get_repo_path(worktree));
5834 if (repo_path == NULL) {
5835 error = got_error_from_errno("strdup");
5836 if (error)
5837 goto done;
5839 } else {
5840 repo_path = strdup(cwd);
5841 if (repo_path == NULL) {
5842 error = got_error_from_errno("strdup");
5843 goto done;
5848 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5849 if (error != NULL)
5850 goto done;
5852 if (worktree) {
5853 const char *prefix = got_worktree_get_path_prefix(worktree);
5854 char *p;
5856 error = got_worktree_resolve_path(&p, worktree, path);
5857 if (error)
5858 goto done;
5859 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5860 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5861 p) == -1) {
5862 error = got_error_from_errno("asprintf");
5863 free(p);
5864 goto done;
5866 free(p);
5867 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5868 } else {
5869 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5870 if (error)
5871 goto done;
5872 error = got_repo_map_path(&in_repo_path, repo, path);
5874 if (error)
5875 goto done;
5877 if (commit_id_str == NULL) {
5878 struct got_reference *head_ref;
5879 error = got_ref_open(&head_ref, repo, worktree ?
5880 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5881 if (error != NULL)
5882 goto done;
5883 error = got_ref_resolve(&commit_id, repo, head_ref);
5884 got_ref_close(head_ref);
5885 if (error != NULL)
5886 goto done;
5887 } else {
5888 struct got_reflist_head refs;
5890 TAILQ_INIT(&refs);
5891 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5892 NULL);
5893 if (error)
5894 goto done;
5896 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5897 repo, worktree);
5898 if (error != NULL)
5899 goto done;
5900 if (keyword_idstr != NULL)
5901 commit_id_str = keyword_idstr;
5903 error = got_repo_match_object_id(&commit_id, NULL,
5904 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5905 got_ref_list_free(&refs);
5906 if (error)
5907 goto done;
5910 if (worktree) {
5911 /* Release work tree lock. */
5912 got_worktree_close(worktree);
5913 worktree = NULL;
5916 error = got_object_open_as_commit(&commit, repo, commit_id);
5917 if (error)
5918 goto done;
5920 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5921 commit, repo);
5922 if (error)
5923 goto done;
5925 error = got_object_id_by_path(&obj_id, repo, commit,
5926 link_target ? link_target : in_repo_path);
5927 if (error)
5928 goto done;
5930 error = got_object_get_type(&obj_type, repo, obj_id);
5931 if (error)
5932 goto done;
5934 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5935 error = got_error_path(link_target ? link_target : in_repo_path,
5936 GOT_ERR_OBJ_TYPE);
5937 goto done;
5940 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5941 if (error)
5942 goto done;
5943 bca.f = got_opentemp();
5944 if (bca.f == NULL) {
5945 error = got_error_from_errno("got_opentemp");
5946 goto done;
5948 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5949 &bca.line_offsets, bca.f, blob);
5950 if (error || bca.nlines == 0)
5951 goto done;
5953 /* Don't include \n at EOF in the blame line count. */
5954 if (bca.line_offsets[bca.nlines - 1] == filesize)
5955 bca.nlines--;
5957 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5958 if (bca.lines == NULL) {
5959 error = got_error_from_errno("calloc");
5960 goto done;
5962 bca.lineno_cur = 1;
5963 bca.nlines_prec = 0;
5964 i = bca.nlines;
5965 while (i > 0) {
5966 i /= 10;
5967 bca.nlines_prec++;
5969 bca.repo = repo;
5971 fd2 = got_opentempfd();
5972 if (fd2 == -1) {
5973 error = got_error_from_errno("got_opentempfd");
5974 goto done;
5976 fd3 = got_opentempfd();
5977 if (fd3 == -1) {
5978 error = got_error_from_errno("got_opentempfd");
5979 goto done;
5981 f1 = got_opentemp();
5982 if (f1 == NULL) {
5983 error = got_error_from_errno("got_opentemp");
5984 goto done;
5986 f2 = got_opentemp();
5987 if (f2 == NULL) {
5988 error = got_error_from_errno("got_opentemp");
5989 goto done;
5991 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5992 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5993 check_cancelled, NULL, fd2, fd3, f1, f2);
5994 done:
5995 free(keyword_idstr);
5996 free(in_repo_path);
5997 free(link_target);
5998 free(repo_path);
5999 free(cwd);
6000 free(commit_id);
6001 free(obj_id);
6002 if (commit)
6003 got_object_commit_close(commit);
6005 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6006 error = got_error_from_errno("close");
6007 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6008 error = got_error_from_errno("close");
6009 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6010 error = got_error_from_errno("close");
6011 if (f1 && fclose(f1) == EOF && error == NULL)
6012 error = got_error_from_errno("fclose");
6013 if (f2 && fclose(f2) == EOF && error == NULL)
6014 error = got_error_from_errno("fclose");
6016 if (blob)
6017 got_object_blob_close(blob);
6018 if (worktree)
6019 got_worktree_close(worktree);
6020 if (repo) {
6021 const struct got_error *close_err = got_repo_close(repo);
6022 if (error == NULL)
6023 error = close_err;
6025 if (pack_fds) {
6026 const struct got_error *pack_err =
6027 got_repo_pack_fds_close(pack_fds);
6028 if (error == NULL)
6029 error = pack_err;
6031 if (bca.lines) {
6032 for (i = 0; i < bca.nlines; i++) {
6033 struct blame_line *bline = &bca.lines[i];
6034 free(bline->id_str);
6035 free(bline->committer);
6037 free(bca.lines);
6039 free(bca.line_offsets);
6040 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6041 error = got_error_from_errno("fclose");
6042 return error;
6045 __dead static void
6046 usage_tree(void)
6048 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6049 "[path]\n", getprogname());
6050 exit(1);
6053 static const struct got_error *
6054 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6055 const char *root_path, struct got_repository *repo)
6057 const struct got_error *err = NULL;
6058 int is_root_path = (strcmp(path, root_path) == 0);
6059 const char *modestr = "";
6060 mode_t mode = got_tree_entry_get_mode(te);
6061 char *link_target = NULL;
6063 path += strlen(root_path);
6064 while (path[0] == '/')
6065 path++;
6067 if (got_object_tree_entry_is_submodule(te))
6068 modestr = "$";
6069 else if (S_ISLNK(mode)) {
6070 int i;
6072 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6073 if (err)
6074 return err;
6075 for (i = 0; link_target[i] != '\0'; i++) {
6076 if (!isprint((unsigned char)link_target[i]))
6077 link_target[i] = '?';
6080 modestr = "@";
6082 else if (S_ISDIR(mode))
6083 modestr = "/";
6084 else if (mode & S_IXUSR)
6085 modestr = "*";
6087 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6088 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6089 link_target ? " -> ": "", link_target ? link_target : "");
6091 free(link_target);
6092 return NULL;
6095 static const struct got_error *
6096 print_tree(const char *path, struct got_commit_object *commit,
6097 int show_ids, int recurse, const char *root_path,
6098 struct got_repository *repo)
6100 const struct got_error *err = NULL;
6101 struct got_object_id *tree_id = NULL;
6102 struct got_tree_object *tree = NULL;
6103 int nentries, i;
6105 err = got_object_id_by_path(&tree_id, repo, commit, path);
6106 if (err)
6107 goto done;
6109 err = got_object_open_as_tree(&tree, repo, tree_id);
6110 if (err)
6111 goto done;
6112 nentries = got_object_tree_get_nentries(tree);
6113 for (i = 0; i < nentries; i++) {
6114 struct got_tree_entry *te;
6115 char *id = NULL;
6117 if (sigint_received || sigpipe_received)
6118 break;
6120 te = got_object_tree_get_entry(tree, i);
6121 if (show_ids) {
6122 char *id_str;
6123 err = got_object_id_str(&id_str,
6124 got_tree_entry_get_id(te));
6125 if (err)
6126 goto done;
6127 if (asprintf(&id, "%s ", id_str) == -1) {
6128 err = got_error_from_errno("asprintf");
6129 free(id_str);
6130 goto done;
6132 free(id_str);
6134 err = print_entry(te, id, path, root_path, repo);
6135 free(id);
6136 if (err)
6137 goto done;
6139 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6140 char *child_path;
6141 if (asprintf(&child_path, "%s%s%s", path,
6142 path[0] == '/' && path[1] == '\0' ? "" : "/",
6143 got_tree_entry_get_name(te)) == -1) {
6144 err = got_error_from_errno("asprintf");
6145 goto done;
6147 err = print_tree(child_path, commit, show_ids, 1,
6148 root_path, repo);
6149 free(child_path);
6150 if (err)
6151 goto done;
6154 done:
6155 if (tree)
6156 got_object_tree_close(tree);
6157 free(tree_id);
6158 return err;
6161 static const struct got_error *
6162 cmd_tree(int argc, char *argv[])
6164 const struct got_error *error;
6165 struct got_repository *repo = NULL;
6166 struct got_worktree *worktree = NULL;
6167 const char *path, *refname = NULL;
6168 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6169 struct got_object_id *commit_id = NULL;
6170 struct got_commit_object *commit = NULL;
6171 char *commit_id_str = NULL, *keyword_idstr = NULL;
6172 int show_ids = 0, recurse = 0;
6173 int ch;
6174 int *pack_fds = NULL;
6176 #ifndef PROFILE
6177 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6178 NULL) == -1)
6179 err(1, "pledge");
6180 #endif
6182 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6183 switch (ch) {
6184 case 'c':
6185 commit_id_str = optarg;
6186 break;
6187 case 'i':
6188 show_ids = 1;
6189 break;
6190 case 'R':
6191 recurse = 1;
6192 break;
6193 case 'r':
6194 repo_path = realpath(optarg, NULL);
6195 if (repo_path == NULL)
6196 return got_error_from_errno2("realpath",
6197 optarg);
6198 got_path_strip_trailing_slashes(repo_path);
6199 break;
6200 default:
6201 usage_tree();
6202 /* NOTREACHED */
6206 argc -= optind;
6207 argv += optind;
6209 if (argc == 1)
6210 path = argv[0];
6211 else if (argc > 1)
6212 usage_tree();
6213 else
6214 path = NULL;
6216 cwd = getcwd(NULL, 0);
6217 if (cwd == NULL) {
6218 error = got_error_from_errno("getcwd");
6219 goto done;
6222 error = got_repo_pack_fds_open(&pack_fds);
6223 if (error != NULL)
6224 goto done;
6226 if (repo_path == NULL) {
6227 error = got_worktree_open(&worktree, cwd,
6228 GOT_WORKTREE_GOT_DIR);
6229 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6230 goto done;
6231 else
6232 error = NULL;
6233 if (worktree) {
6234 repo_path =
6235 strdup(got_worktree_get_repo_path(worktree));
6236 if (repo_path == NULL)
6237 error = got_error_from_errno("strdup");
6238 if (error)
6239 goto done;
6240 } else {
6241 repo_path = strdup(cwd);
6242 if (repo_path == NULL) {
6243 error = got_error_from_errno("strdup");
6244 goto done;
6249 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6250 if (error != NULL)
6251 goto done;
6253 if (worktree) {
6254 const char *prefix = got_worktree_get_path_prefix(worktree);
6255 char *p;
6257 if (path == NULL || got_path_is_root_dir(path))
6258 path = "";
6259 error = got_worktree_resolve_path(&p, worktree, path);
6260 if (error)
6261 goto done;
6262 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6263 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6264 p) == -1) {
6265 error = got_error_from_errno("asprintf");
6266 free(p);
6267 goto done;
6269 free(p);
6270 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6271 if (error)
6272 goto done;
6273 } else {
6274 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6275 if (error)
6276 goto done;
6277 if (path == NULL)
6278 path = "/";
6279 error = got_repo_map_path(&in_repo_path, repo, path);
6280 if (error != NULL)
6281 goto done;
6284 if (commit_id_str == NULL) {
6285 struct got_reference *head_ref;
6286 if (worktree)
6287 refname = got_worktree_get_head_ref_name(worktree);
6288 else
6289 refname = GOT_REF_HEAD;
6290 error = got_ref_open(&head_ref, repo, refname, 0);
6291 if (error != NULL)
6292 goto done;
6293 error = got_ref_resolve(&commit_id, repo, head_ref);
6294 got_ref_close(head_ref);
6295 if (error != NULL)
6296 goto done;
6297 } else {
6298 struct got_reflist_head refs;
6300 TAILQ_INIT(&refs);
6301 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6302 NULL);
6303 if (error)
6304 goto done;
6306 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6307 repo, worktree);
6308 if (error != NULL)
6309 goto done;
6310 if (keyword_idstr != NULL)
6311 commit_id_str = keyword_idstr;
6313 error = got_repo_match_object_id(&commit_id, NULL,
6314 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6315 got_ref_list_free(&refs);
6316 if (error)
6317 goto done;
6320 if (worktree) {
6321 /* Release work tree lock. */
6322 got_worktree_close(worktree);
6323 worktree = NULL;
6326 error = got_object_open_as_commit(&commit, repo, commit_id);
6327 if (error)
6328 goto done;
6330 error = print_tree(in_repo_path, commit, show_ids, recurse,
6331 in_repo_path, repo);
6332 done:
6333 free(keyword_idstr);
6334 free(in_repo_path);
6335 free(repo_path);
6336 free(cwd);
6337 free(commit_id);
6338 if (commit)
6339 got_object_commit_close(commit);
6340 if (worktree)
6341 got_worktree_close(worktree);
6342 if (repo) {
6343 const struct got_error *close_err = got_repo_close(repo);
6344 if (error == NULL)
6345 error = close_err;
6347 if (pack_fds) {
6348 const struct got_error *pack_err =
6349 got_repo_pack_fds_close(pack_fds);
6350 if (error == NULL)
6351 error = pack_err;
6353 return error;
6356 __dead static void
6357 usage_status(void)
6359 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6360 "[-s status-codes] [path ...]\n", getprogname());
6361 exit(1);
6364 struct got_status_arg {
6365 char *status_codes;
6366 int suppress;
6369 static const struct got_error *
6370 print_status(void *arg, unsigned char status, unsigned char staged_status,
6371 const char *path, struct got_object_id *blob_id,
6372 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6373 int dirfd, const char *de_name)
6375 struct got_status_arg *st = arg;
6377 if (status == staged_status && (status == GOT_STATUS_DELETE))
6378 status = GOT_STATUS_NO_CHANGE;
6379 if (st != NULL && st->status_codes) {
6380 size_t ncodes = strlen(st->status_codes);
6381 int i, j = 0;
6383 for (i = 0; i < ncodes ; i++) {
6384 if (st->suppress) {
6385 if (status == st->status_codes[i] ||
6386 staged_status == st->status_codes[i]) {
6387 j++;
6388 continue;
6390 } else {
6391 if (status == st->status_codes[i] ||
6392 staged_status == st->status_codes[i])
6393 break;
6397 if (st->suppress && j == 0)
6398 goto print;
6400 if (i == ncodes)
6401 return NULL;
6403 print:
6404 printf("%c%c %s\n", status, staged_status, path);
6405 return NULL;
6408 static const struct got_error *
6409 cmd_status(int argc, char *argv[])
6411 const struct got_error *error = NULL;
6412 struct got_repository *repo = NULL;
6413 struct got_worktree *worktree = NULL;
6414 struct got_status_arg st;
6415 char *cwd = NULL;
6416 struct got_pathlist_head paths;
6417 int ch, i, no_ignores = 0;
6418 int *pack_fds = NULL;
6420 TAILQ_INIT(&paths);
6422 memset(&st, 0, sizeof(st));
6423 st.status_codes = NULL;
6424 st.suppress = 0;
6426 #ifndef PROFILE
6427 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6428 NULL) == -1)
6429 err(1, "pledge");
6430 #endif
6432 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6433 switch (ch) {
6434 case 'I':
6435 no_ignores = 1;
6436 break;
6437 case 'S':
6438 if (st.status_codes != NULL && st.suppress == 0)
6439 option_conflict('S', 's');
6440 st.suppress = 1;
6441 /* fallthrough */
6442 case 's':
6443 for (i = 0; optarg[i] != '\0'; i++) {
6444 switch (optarg[i]) {
6445 case GOT_STATUS_MODIFY:
6446 case GOT_STATUS_ADD:
6447 case GOT_STATUS_DELETE:
6448 case GOT_STATUS_CONFLICT:
6449 case GOT_STATUS_MISSING:
6450 case GOT_STATUS_OBSTRUCTED:
6451 case GOT_STATUS_UNVERSIONED:
6452 case GOT_STATUS_MODE_CHANGE:
6453 case GOT_STATUS_NONEXISTENT:
6454 break;
6455 default:
6456 errx(1, "invalid status code '%c'",
6457 optarg[i]);
6460 if (ch == 's' && st.suppress)
6461 option_conflict('s', 'S');
6462 st.status_codes = optarg;
6463 break;
6464 default:
6465 usage_status();
6466 /* NOTREACHED */
6470 argc -= optind;
6471 argv += optind;
6473 cwd = getcwd(NULL, 0);
6474 if (cwd == NULL) {
6475 error = got_error_from_errno("getcwd");
6476 goto done;
6479 error = got_repo_pack_fds_open(&pack_fds);
6480 if (error != NULL)
6481 goto done;
6483 error = got_worktree_open(&worktree, cwd,
6484 GOT_WORKTREE_GOT_DIR);
6485 if (error) {
6486 if (error->code == GOT_ERR_NOT_WORKTREE)
6487 error = wrap_not_worktree_error(error, "status", cwd);
6488 goto done;
6491 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6492 NULL, pack_fds);
6493 if (error != NULL)
6494 goto done;
6496 error = apply_unveil(got_repo_get_path(repo), 1,
6497 got_worktree_get_root_path(worktree));
6498 if (error)
6499 goto done;
6501 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6502 if (error)
6503 goto done;
6505 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6506 print_status, &st, check_cancelled, NULL);
6507 done:
6508 if (pack_fds) {
6509 const struct got_error *pack_err =
6510 got_repo_pack_fds_close(pack_fds);
6511 if (error == NULL)
6512 error = pack_err;
6514 if (repo) {
6515 const struct got_error *close_err = got_repo_close(repo);
6516 if (error == NULL)
6517 error = close_err;
6520 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6521 free(cwd);
6522 return error;
6525 __dead static void
6526 usage_ref(void)
6528 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6529 "[-s reference] [name]\n", getprogname());
6530 exit(1);
6533 static const struct got_error *
6534 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6536 static const struct got_error *err = NULL;
6537 struct got_reflist_head refs;
6538 struct got_reflist_entry *re;
6540 TAILQ_INIT(&refs);
6541 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6542 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6543 repo);
6544 if (err)
6545 return err;
6547 TAILQ_FOREACH(re, &refs, entry) {
6548 char *refstr;
6549 refstr = got_ref_to_str(re->ref);
6550 if (refstr == NULL) {
6551 err = got_error_from_errno("got_ref_to_str");
6552 break;
6554 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6555 free(refstr);
6558 got_ref_list_free(&refs);
6559 return err;
6562 static const struct got_error *
6563 delete_ref_by_name(struct got_repository *repo, const char *refname)
6565 const struct got_error *err;
6566 struct got_reference *ref;
6568 err = got_ref_open(&ref, repo, refname, 0);
6569 if (err)
6570 return err;
6572 err = delete_ref(repo, ref);
6573 got_ref_close(ref);
6574 return err;
6577 static const struct got_error *
6578 add_ref(struct got_repository *repo, const char *refname, const char *target)
6580 const struct got_error *err = NULL;
6581 struct got_object_id *id = NULL;
6582 struct got_reference *ref = NULL;
6583 struct got_reflist_head refs;
6586 * Don't let the user create a reference name with a leading '-'.
6587 * While technically a valid reference name, this case is usually
6588 * an unintended typo.
6590 if (refname[0] == '-')
6591 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6593 TAILQ_INIT(&refs);
6594 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6595 if (err)
6596 goto done;
6597 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6598 &refs, repo);
6599 got_ref_list_free(&refs);
6600 if (err)
6601 goto done;
6603 err = got_ref_alloc(&ref, refname, id);
6604 if (err)
6605 goto done;
6607 err = got_ref_write(ref, repo);
6608 done:
6609 if (ref)
6610 got_ref_close(ref);
6611 free(id);
6612 return err;
6615 static const struct got_error *
6616 add_symref(struct got_repository *repo, const char *refname, const char *target)
6618 const struct got_error *err = NULL;
6619 struct got_reference *ref = NULL;
6620 struct got_reference *target_ref = NULL;
6623 * Don't let the user create a reference name with a leading '-'.
6624 * While technically a valid reference name, this case is usually
6625 * an unintended typo.
6627 if (refname[0] == '-')
6628 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6630 err = got_ref_open(&target_ref, repo, target, 0);
6631 if (err)
6632 return err;
6634 err = got_ref_alloc_symref(&ref, refname, target_ref);
6635 if (err)
6636 goto done;
6638 err = got_ref_write(ref, repo);
6639 done:
6640 if (target_ref)
6641 got_ref_close(target_ref);
6642 if (ref)
6643 got_ref_close(ref);
6644 return err;
6647 static const struct got_error *
6648 cmd_ref(int argc, char *argv[])
6650 const struct got_error *error = NULL;
6651 struct got_repository *repo = NULL;
6652 struct got_worktree *worktree = NULL;
6653 char *cwd = NULL, *repo_path = NULL;
6654 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6655 const char *obj_arg = NULL, *symref_target= NULL;
6656 char *refname = NULL, *keyword_idstr = NULL;
6657 int *pack_fds = NULL;
6659 #ifndef PROFILE
6660 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6661 "sendfd unveil", NULL) == -1)
6662 err(1, "pledge");
6663 #endif
6665 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6666 switch (ch) {
6667 case 'c':
6668 obj_arg = optarg;
6669 break;
6670 case 'd':
6671 do_delete = 1;
6672 break;
6673 case 'l':
6674 do_list = 1;
6675 break;
6676 case 'r':
6677 repo_path = realpath(optarg, NULL);
6678 if (repo_path == NULL)
6679 return got_error_from_errno2("realpath",
6680 optarg);
6681 got_path_strip_trailing_slashes(repo_path);
6682 break;
6683 case 's':
6684 symref_target = optarg;
6685 break;
6686 case 't':
6687 sort_by_time = 1;
6688 break;
6689 default:
6690 usage_ref();
6691 /* NOTREACHED */
6695 if (obj_arg && do_list)
6696 option_conflict('c', 'l');
6697 if (obj_arg && do_delete)
6698 option_conflict('c', 'd');
6699 if (obj_arg && symref_target)
6700 option_conflict('c', 's');
6701 if (symref_target && do_delete)
6702 option_conflict('s', 'd');
6703 if (symref_target && do_list)
6704 option_conflict('s', 'l');
6705 if (do_delete && do_list)
6706 option_conflict('d', 'l');
6707 if (sort_by_time && !do_list)
6708 errx(1, "-t option requires -l option");
6710 argc -= optind;
6711 argv += optind;
6713 if (do_list) {
6714 if (argc != 0 && argc != 1)
6715 usage_ref();
6716 if (argc == 1) {
6717 refname = strdup(argv[0]);
6718 if (refname == NULL) {
6719 error = got_error_from_errno("strdup");
6720 goto done;
6723 } else {
6724 if (argc != 1)
6725 usage_ref();
6726 refname = strdup(argv[0]);
6727 if (refname == NULL) {
6728 error = got_error_from_errno("strdup");
6729 goto done;
6733 if (refname)
6734 got_path_strip_trailing_slashes(refname);
6736 cwd = getcwd(NULL, 0);
6737 if (cwd == NULL) {
6738 error = got_error_from_errno("getcwd");
6739 goto done;
6742 error = got_repo_pack_fds_open(&pack_fds);
6743 if (error != NULL)
6744 goto done;
6746 if (repo_path == NULL) {
6747 error = got_worktree_open(&worktree, cwd,
6748 GOT_WORKTREE_GOT_DIR);
6749 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6750 goto done;
6751 else
6752 error = NULL;
6753 if (worktree) {
6754 repo_path =
6755 strdup(got_worktree_get_repo_path(worktree));
6756 if (repo_path == NULL)
6757 error = got_error_from_errno("strdup");
6758 if (error)
6759 goto done;
6760 } else {
6761 repo_path = strdup(cwd);
6762 if (repo_path == NULL) {
6763 error = got_error_from_errno("strdup");
6764 goto done;
6769 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 #ifndef PROFILE
6774 if (do_list) {
6775 /* Remove "cpath" promise. */
6776 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6777 NULL) == -1)
6778 err(1, "pledge");
6780 #endif
6782 error = apply_unveil(got_repo_get_path(repo), do_list,
6783 worktree ? got_worktree_get_root_path(worktree) : NULL);
6784 if (error)
6785 goto done;
6787 if (do_list)
6788 error = list_refs(repo, refname, sort_by_time);
6789 else if (do_delete)
6790 error = delete_ref_by_name(repo, refname);
6791 else if (symref_target)
6792 error = add_symref(repo, refname, symref_target);
6793 else {
6794 if (obj_arg == NULL)
6795 usage_ref();
6797 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6798 repo, worktree);
6799 if (error != NULL)
6800 goto done;
6801 if (keyword_idstr != NULL)
6802 obj_arg = keyword_idstr;
6804 error = add_ref(repo, refname, obj_arg);
6806 done:
6807 free(refname);
6808 if (repo) {
6809 const struct got_error *close_err = got_repo_close(repo);
6810 if (error == NULL)
6811 error = close_err;
6813 if (worktree)
6814 got_worktree_close(worktree);
6815 if (pack_fds) {
6816 const struct got_error *pack_err =
6817 got_repo_pack_fds_close(pack_fds);
6818 if (error == NULL)
6819 error = pack_err;
6821 free(cwd);
6822 free(repo_path);
6823 free(keyword_idstr);
6824 return error;
6827 __dead static void
6828 usage_branch(void)
6830 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6831 "[-r repository-path] [name]\n", getprogname());
6832 exit(1);
6835 static const struct got_error *
6836 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6837 struct got_reference *ref)
6839 const struct got_error *err = NULL;
6840 const char *refname;
6841 char *refstr;
6842 char marker = ' ';
6844 refname = got_ref_get_name(ref);
6845 if (worktree && strcmp(refname,
6846 got_worktree_get_head_ref_name(worktree)) == 0) {
6847 err = got_worktree_get_state(&marker, repo, worktree,
6848 check_cancelled, NULL);
6849 if (err != NULL)
6850 return err;
6853 if (strncmp(refname, "refs/heads/", 11) == 0)
6854 refname += 11;
6855 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6856 refname += 18;
6857 if (strncmp(refname, "refs/remotes/", 13) == 0)
6858 refname += 13;
6860 refstr = got_ref_to_str(ref);
6861 if (refstr == NULL)
6862 return got_error_from_errno("got_ref_to_str");
6864 printf("%c %s: %s\n", marker, refname, refstr);
6865 free(refstr);
6866 return NULL;
6869 static const struct got_error *
6870 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6872 const char *refname;
6874 if (worktree == NULL)
6875 return got_error(GOT_ERR_NOT_WORKTREE);
6877 refname = got_worktree_get_head_ref_name(worktree);
6879 if (strncmp(refname, "refs/heads/", 11) == 0)
6880 refname += 11;
6881 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6882 refname += 18;
6884 printf("%s\n", refname);
6886 return NULL;
6889 static const struct got_error *
6890 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6891 int sort_by_time)
6893 static const struct got_error *err = NULL;
6894 struct got_reflist_head refs;
6895 struct got_reflist_entry *re;
6896 struct got_reference *temp_ref = NULL;
6897 int rebase_in_progress, histedit_in_progress;
6899 TAILQ_INIT(&refs);
6901 if (worktree) {
6902 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6903 worktree);
6904 if (err)
6905 return err;
6907 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6908 worktree);
6909 if (err)
6910 return err;
6912 if (rebase_in_progress || histedit_in_progress) {
6913 err = got_ref_open(&temp_ref, repo,
6914 got_worktree_get_head_ref_name(worktree), 0);
6915 if (err)
6916 return err;
6917 list_branch(repo, worktree, temp_ref);
6918 got_ref_close(temp_ref);
6922 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6923 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6924 repo);
6925 if (err)
6926 return err;
6928 TAILQ_FOREACH(re, &refs, entry)
6929 list_branch(repo, worktree, re->ref);
6931 got_ref_list_free(&refs);
6933 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6934 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6935 repo);
6936 if (err)
6937 return err;
6939 TAILQ_FOREACH(re, &refs, entry)
6940 list_branch(repo, worktree, re->ref);
6942 got_ref_list_free(&refs);
6944 return NULL;
6947 static const struct got_error *
6948 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6949 const char *branch_name)
6951 const struct got_error *err = NULL;
6952 struct got_reference *ref = NULL;
6953 char *refname, *remote_refname = NULL;
6955 if (strncmp(branch_name, "refs/", 5) == 0)
6956 branch_name += 5;
6957 if (strncmp(branch_name, "heads/", 6) == 0)
6958 branch_name += 6;
6959 else if (strncmp(branch_name, "remotes/", 8) == 0)
6960 branch_name += 8;
6962 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6963 return got_error_from_errno("asprintf");
6965 if (asprintf(&remote_refname, "refs/remotes/%s",
6966 branch_name) == -1) {
6967 err = got_error_from_errno("asprintf");
6968 goto done;
6971 err = got_ref_open(&ref, repo, refname, 0);
6972 if (err) {
6973 const struct got_error *err2;
6974 if (err->code != GOT_ERR_NOT_REF)
6975 goto done;
6977 * Keep 'err' intact such that if neither branch exists
6978 * we report "refs/heads" rather than "refs/remotes" in
6979 * our error message.
6981 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6982 if (err2)
6983 goto done;
6984 err = NULL;
6987 if (worktree &&
6988 strcmp(got_worktree_get_head_ref_name(worktree),
6989 got_ref_get_name(ref)) == 0) {
6990 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6991 "will not delete this work tree's current branch");
6992 goto done;
6995 err = delete_ref(repo, ref);
6996 done:
6997 if (ref)
6998 got_ref_close(ref);
6999 free(refname);
7000 free(remote_refname);
7001 return err;
7004 static const struct got_error *
7005 add_branch(struct got_repository *repo, const char *branch_name,
7006 struct got_object_id *base_commit_id)
7008 const struct got_error *err = NULL;
7009 struct got_reference *ref = NULL;
7010 char *refname = NULL;
7013 * Don't let the user create a branch name with a leading '-'.
7014 * While technically a valid reference name, this case is usually
7015 * an unintended typo.
7017 if (branch_name[0] == '-')
7018 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7020 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7021 branch_name += 11;
7023 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7024 err = got_error_from_errno("asprintf");
7025 goto done;
7028 err = got_ref_open(&ref, repo, refname, 0);
7029 if (err == NULL) {
7030 err = got_error(GOT_ERR_BRANCH_EXISTS);
7031 goto done;
7032 } else if (err->code != GOT_ERR_NOT_REF)
7033 goto done;
7035 err = got_ref_alloc(&ref, refname, base_commit_id);
7036 if (err)
7037 goto done;
7039 err = got_ref_write(ref, repo);
7040 done:
7041 if (ref)
7042 got_ref_close(ref);
7043 free(refname);
7044 return err;
7047 static const struct got_error *
7048 cmd_branch(int argc, char *argv[])
7050 const struct got_error *error = NULL;
7051 struct got_repository *repo = NULL;
7052 struct got_worktree *worktree = NULL;
7053 char *cwd = NULL, *repo_path = NULL;
7054 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7055 const char *delref = NULL, *commit_id_arg = NULL;
7056 struct got_reference *ref = NULL;
7057 struct got_pathlist_head paths;
7058 struct got_object_id *commit_id = NULL;
7059 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7060 int *pack_fds = NULL;
7062 TAILQ_INIT(&paths);
7064 #ifndef PROFILE
7065 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7066 "sendfd unveil", NULL) == -1)
7067 err(1, "pledge");
7068 #endif
7070 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7071 switch (ch) {
7072 case 'c':
7073 commit_id_arg = optarg;
7074 break;
7075 case 'd':
7076 delref = optarg;
7077 break;
7078 case 'l':
7079 do_list = 1;
7080 break;
7081 case 'n':
7082 do_update = 0;
7083 break;
7084 case 'r':
7085 repo_path = realpath(optarg, NULL);
7086 if (repo_path == NULL)
7087 return got_error_from_errno2("realpath",
7088 optarg);
7089 got_path_strip_trailing_slashes(repo_path);
7090 break;
7091 case 't':
7092 sort_by_time = 1;
7093 break;
7094 default:
7095 usage_branch();
7096 /* NOTREACHED */
7100 if (do_list && delref)
7101 option_conflict('l', 'd');
7102 if (sort_by_time && !do_list)
7103 errx(1, "-t option requires -l option");
7105 argc -= optind;
7106 argv += optind;
7108 if (!do_list && !delref && argc == 0)
7109 do_show = 1;
7111 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7112 errx(1, "-c option can only be used when creating a branch");
7114 if (do_list || delref) {
7115 if (argc > 0)
7116 usage_branch();
7117 } else if (!do_show && argc != 1)
7118 usage_branch();
7120 cwd = getcwd(NULL, 0);
7121 if (cwd == NULL) {
7122 error = got_error_from_errno("getcwd");
7123 goto done;
7126 error = got_repo_pack_fds_open(&pack_fds);
7127 if (error != NULL)
7128 goto done;
7130 if (repo_path == NULL) {
7131 error = got_worktree_open(&worktree, cwd,
7132 GOT_WORKTREE_GOT_DIR);
7133 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7134 goto done;
7135 else
7136 error = NULL;
7137 if (worktree) {
7138 repo_path =
7139 strdup(got_worktree_get_repo_path(worktree));
7140 if (repo_path == NULL)
7141 error = got_error_from_errno("strdup");
7142 if (error)
7143 goto done;
7144 } else {
7145 repo_path = strdup(cwd);
7146 if (repo_path == NULL) {
7147 error = got_error_from_errno("strdup");
7148 goto done;
7153 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7154 if (error != NULL)
7155 goto done;
7157 #ifndef PROFILE
7158 if (do_list || do_show) {
7159 /* Remove "cpath" promise. */
7160 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7161 NULL) == -1)
7162 err(1, "pledge");
7164 #endif
7166 error = apply_unveil(got_repo_get_path(repo), do_list,
7167 worktree ? got_worktree_get_root_path(worktree) : NULL);
7168 if (error)
7169 goto done;
7171 if (do_show)
7172 error = show_current_branch(repo, worktree);
7173 else if (do_list)
7174 error = list_branches(repo, worktree, sort_by_time);
7175 else if (delref)
7176 error = delete_branch(repo, worktree, delref);
7177 else {
7178 struct got_reflist_head refs;
7179 TAILQ_INIT(&refs);
7180 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7181 NULL);
7182 if (error)
7183 goto done;
7184 if (commit_id_arg == NULL)
7185 commit_id_arg = worktree ?
7186 got_worktree_get_head_ref_name(worktree) :
7187 GOT_REF_HEAD;
7188 else {
7189 error = got_keyword_to_idstr(&keyword_idstr,
7190 commit_id_arg, repo, worktree);
7191 if (error != NULL)
7192 goto done;
7193 if (keyword_idstr != NULL)
7194 commit_id_arg = keyword_idstr;
7196 error = got_repo_match_object_id(&commit_id, NULL,
7197 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7198 got_ref_list_free(&refs);
7199 if (error)
7200 goto done;
7201 error = add_branch(repo, argv[0], commit_id);
7202 if (error)
7203 goto done;
7204 if (worktree && do_update) {
7205 struct got_update_progress_arg upa;
7206 char *branch_refname = NULL;
7208 error = got_object_id_str(&commit_id_str, commit_id);
7209 if (error)
7210 goto done;
7211 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7212 worktree);
7213 if (error)
7214 goto done;
7215 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7216 == -1) {
7217 error = got_error_from_errno("asprintf");
7218 goto done;
7220 error = got_ref_open(&ref, repo, branch_refname, 0);
7221 free(branch_refname);
7222 if (error)
7223 goto done;
7224 error = switch_head_ref(ref, commit_id, worktree,
7225 repo);
7226 if (error)
7227 goto done;
7228 error = got_worktree_set_base_commit_id(worktree, repo,
7229 commit_id);
7230 if (error)
7231 goto done;
7232 memset(&upa, 0, sizeof(upa));
7233 error = got_worktree_checkout_files(worktree, &paths,
7234 repo, update_progress, &upa, check_cancelled,
7235 NULL);
7236 if (error)
7237 goto done;
7238 if (upa.did_something) {
7239 printf("Updated to %s: %s\n",
7240 got_worktree_get_head_ref_name(worktree),
7241 commit_id_str);
7243 print_update_progress_stats(&upa);
7246 done:
7247 free(keyword_idstr);
7248 if (ref)
7249 got_ref_close(ref);
7250 if (repo) {
7251 const struct got_error *close_err = got_repo_close(repo);
7252 if (error == NULL)
7253 error = close_err;
7255 if (worktree)
7256 got_worktree_close(worktree);
7257 if (pack_fds) {
7258 const struct got_error *pack_err =
7259 got_repo_pack_fds_close(pack_fds);
7260 if (error == NULL)
7261 error = pack_err;
7263 free(cwd);
7264 free(repo_path);
7265 free(commit_id);
7266 free(commit_id_str);
7267 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7268 return error;
7272 __dead static void
7273 usage_tag(void)
7275 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7276 "[-r repository-path] [-s signer-id] name\n", getprogname());
7277 exit(1);
7280 #if 0
7281 static const struct got_error *
7282 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7284 const struct got_error *err = NULL;
7285 struct got_reflist_entry *re, *se, *new;
7286 struct got_object_id *re_id, *se_id;
7287 struct got_tag_object *re_tag, *se_tag;
7288 time_t re_time, se_time;
7290 STAILQ_FOREACH(re, tags, entry) {
7291 se = STAILQ_FIRST(sorted);
7292 if (se == NULL) {
7293 err = got_reflist_entry_dup(&new, re);
7294 if (err)
7295 return err;
7296 STAILQ_INSERT_HEAD(sorted, new, entry);
7297 continue;
7298 } else {
7299 err = got_ref_resolve(&re_id, repo, re->ref);
7300 if (err)
7301 break;
7302 err = got_object_open_as_tag(&re_tag, repo, re_id);
7303 free(re_id);
7304 if (err)
7305 break;
7306 re_time = got_object_tag_get_tagger_time(re_tag);
7307 got_object_tag_close(re_tag);
7310 while (se) {
7311 err = got_ref_resolve(&se_id, repo, re->ref);
7312 if (err)
7313 break;
7314 err = got_object_open_as_tag(&se_tag, repo, se_id);
7315 free(se_id);
7316 if (err)
7317 break;
7318 se_time = got_object_tag_get_tagger_time(se_tag);
7319 got_object_tag_close(se_tag);
7321 if (se_time > re_time) {
7322 err = got_reflist_entry_dup(&new, re);
7323 if (err)
7324 return err;
7325 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7326 break;
7328 se = STAILQ_NEXT(se, entry);
7329 continue;
7332 done:
7333 return err;
7335 #endif
7337 static const struct got_error *
7338 get_tag_refname(char **refname, const char *tag_name)
7340 const struct got_error *err;
7342 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7343 *refname = strdup(tag_name);
7344 if (*refname == NULL)
7345 return got_error_from_errno("strdup");
7346 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7347 err = got_error_from_errno("asprintf");
7348 *refname = NULL;
7349 return err;
7352 return NULL;
7355 static const struct got_error *
7356 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7357 const char *allowed_signers, const char *revoked_signers, int verbosity)
7359 static const struct got_error *err = NULL;
7360 struct got_reflist_head refs;
7361 struct got_reflist_entry *re;
7362 char *wanted_refname = NULL;
7363 int bad_sigs = 0;
7365 TAILQ_INIT(&refs);
7367 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7368 if (err)
7369 return err;
7371 if (tag_name) {
7372 struct got_reference *ref;
7373 err = get_tag_refname(&wanted_refname, tag_name);
7374 if (err)
7375 goto done;
7376 /* Wanted tag reference should exist. */
7377 err = got_ref_open(&ref, repo, wanted_refname, 0);
7378 if (err)
7379 goto done;
7380 got_ref_close(ref);
7383 TAILQ_FOREACH(re, &refs, entry) {
7384 const char *refname;
7385 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7386 char datebuf[26];
7387 const char *tagger, *ssh_sig = NULL;
7388 char *sig_msg = NULL;
7389 time_t tagger_time;
7390 struct got_object_id *id;
7391 struct got_tag_object *tag;
7392 struct got_commit_object *commit = NULL;
7394 refname = got_ref_get_name(re->ref);
7395 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7396 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7397 continue;
7398 refname += 10;
7399 refstr = got_ref_to_str(re->ref);
7400 if (refstr == NULL) {
7401 err = got_error_from_errno("got_ref_to_str");
7402 break;
7405 err = got_ref_resolve(&id, repo, re->ref);
7406 if (err)
7407 break;
7408 err = got_object_open_as_tag(&tag, repo, id);
7409 if (err) {
7410 if (err->code != GOT_ERR_OBJ_TYPE) {
7411 free(id);
7412 break;
7414 /* "lightweight" tag */
7415 err = got_object_open_as_commit(&commit, repo, id);
7416 if (err) {
7417 free(id);
7418 break;
7420 tagger = got_object_commit_get_committer(commit);
7421 tagger_time =
7422 got_object_commit_get_committer_time(commit);
7423 err = got_object_id_str(&id_str, id);
7424 free(id);
7425 if (err)
7426 break;
7427 } else {
7428 free(id);
7429 tagger = got_object_tag_get_tagger(tag);
7430 tagger_time = got_object_tag_get_tagger_time(tag);
7431 err = got_object_id_str(&id_str,
7432 got_object_tag_get_object_id(tag));
7433 if (err)
7434 break;
7437 if (tag && verify_tags) {
7438 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7439 got_object_tag_get_message(tag));
7440 if (ssh_sig && allowed_signers == NULL) {
7441 err = got_error_msg(
7442 GOT_ERR_VERIFY_TAG_SIGNATURE,
7443 "SSH signature verification requires "
7444 "setting allowed_signers in "
7445 "got.conf(5)");
7446 break;
7450 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7451 free(refstr);
7452 printf("from: %s\n", tagger);
7453 datestr = get_datestr(&tagger_time, datebuf);
7454 if (datestr)
7455 printf("date: %s UTC\n", datestr);
7456 if (commit)
7457 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7458 else {
7459 switch (got_object_tag_get_object_type(tag)) {
7460 case GOT_OBJ_TYPE_BLOB:
7461 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7462 id_str);
7463 break;
7464 case GOT_OBJ_TYPE_TREE:
7465 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7466 id_str);
7467 break;
7468 case GOT_OBJ_TYPE_COMMIT:
7469 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7470 id_str);
7471 break;
7472 case GOT_OBJ_TYPE_TAG:
7473 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7474 id_str);
7475 break;
7476 default:
7477 break;
7480 free(id_str);
7482 if (ssh_sig) {
7483 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7484 allowed_signers, revoked_signers, verbosity);
7485 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7486 bad_sigs = 1;
7487 else if (err)
7488 break;
7489 printf("signature: %s", sig_msg);
7490 free(sig_msg);
7491 sig_msg = NULL;
7494 if (commit) {
7495 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7496 if (err)
7497 break;
7498 got_object_commit_close(commit);
7499 } else {
7500 tagmsg0 = strdup(got_object_tag_get_message(tag));
7501 got_object_tag_close(tag);
7502 if (tagmsg0 == NULL) {
7503 err = got_error_from_errno("strdup");
7504 break;
7508 tagmsg = tagmsg0;
7509 do {
7510 line = strsep(&tagmsg, "\n");
7511 if (line)
7512 printf(" %s\n", line);
7513 } while (line);
7514 free(tagmsg0);
7516 done:
7517 got_ref_list_free(&refs);
7518 free(wanted_refname);
7520 if (err == NULL && bad_sigs)
7521 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7522 return err;
7525 static const struct got_error *
7526 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7527 const char *tag_name, const char *repo_path)
7529 const struct got_error *err = NULL;
7530 char *template = NULL, *initial_content = NULL;
7531 char *editor = NULL;
7532 int initial_content_len;
7533 int fd = -1;
7535 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7536 err = got_error_from_errno("asprintf");
7537 goto done;
7540 initial_content_len = asprintf(&initial_content,
7541 "\n# tagging commit %s as %s\n",
7542 commit_id_str, tag_name);
7543 if (initial_content_len == -1) {
7544 err = got_error_from_errno("asprintf");
7545 goto done;
7548 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7549 if (err)
7550 goto done;
7552 if (write(fd, initial_content, initial_content_len) == -1) {
7553 err = got_error_from_errno2("write", *tagmsg_path);
7554 goto done;
7556 if (close(fd) == -1) {
7557 err = got_error_from_errno2("close", *tagmsg_path);
7558 goto done;
7560 fd = -1;
7562 err = get_editor(&editor);
7563 if (err)
7564 goto done;
7565 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7566 initial_content_len, 1);
7567 done:
7568 free(initial_content);
7569 free(template);
7570 free(editor);
7572 if (fd != -1 && close(fd) == -1 && err == NULL)
7573 err = got_error_from_errno2("close", *tagmsg_path);
7575 if (err) {
7576 free(*tagmsg);
7577 *tagmsg = NULL;
7579 return err;
7582 static const struct got_error *
7583 add_tag(struct got_repository *repo, const char *tagger,
7584 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7585 const char *signer_id, int verbosity)
7587 const struct got_error *err = NULL;
7588 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7589 char *label = NULL, *commit_id_str = NULL;
7590 struct got_reference *ref = NULL;
7591 char *refname = NULL, *tagmsg = NULL;
7592 char *tagmsg_path = NULL, *tag_id_str = NULL;
7593 int preserve_tagmsg = 0;
7594 struct got_reflist_head refs;
7596 TAILQ_INIT(&refs);
7599 * Don't let the user create a tag name with a leading '-'.
7600 * While technically a valid reference name, this case is usually
7601 * an unintended typo.
7603 if (tag_name[0] == '-')
7604 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7606 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7607 if (err)
7608 goto done;
7610 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7611 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7612 if (err)
7613 goto done;
7615 err = got_object_id_str(&commit_id_str, commit_id);
7616 if (err)
7617 goto done;
7619 err = get_tag_refname(&refname, tag_name);
7620 if (err)
7621 goto done;
7622 if (strncmp("refs/tags/", tag_name, 10) == 0)
7623 tag_name += 10;
7625 err = got_ref_open(&ref, repo, refname, 0);
7626 if (err == NULL) {
7627 err = got_error(GOT_ERR_TAG_EXISTS);
7628 goto done;
7629 } else if (err->code != GOT_ERR_NOT_REF)
7630 goto done;
7632 if (tagmsg_arg == NULL) {
7633 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7634 tag_name, got_repo_get_path(repo));
7635 if (err) {
7636 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7637 tagmsg_path != NULL)
7638 preserve_tagmsg = 1;
7639 goto done;
7641 /* Editor is done; we can now apply unveil(2) */
7642 err = got_sigs_apply_unveil();
7643 if (err)
7644 goto done;
7645 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7646 if (err)
7647 goto done;
7650 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7651 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7652 verbosity);
7653 if (err) {
7654 if (tagmsg_path)
7655 preserve_tagmsg = 1;
7656 goto done;
7659 err = got_ref_alloc(&ref, refname, tag_id);
7660 if (err) {
7661 if (tagmsg_path)
7662 preserve_tagmsg = 1;
7663 goto done;
7666 err = got_ref_write(ref, repo);
7667 if (err) {
7668 if (tagmsg_path)
7669 preserve_tagmsg = 1;
7670 goto done;
7673 err = got_object_id_str(&tag_id_str, tag_id);
7674 if (err) {
7675 if (tagmsg_path)
7676 preserve_tagmsg = 1;
7677 goto done;
7679 printf("Created tag %s\n", tag_id_str);
7680 done:
7681 if (preserve_tagmsg) {
7682 fprintf(stderr, "%s: tag message preserved in %s\n",
7683 getprogname(), tagmsg_path);
7684 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7685 err = got_error_from_errno2("unlink", tagmsg_path);
7686 free(tag_id_str);
7687 if (ref)
7688 got_ref_close(ref);
7689 free(commit_id);
7690 free(commit_id_str);
7691 free(refname);
7692 free(tagmsg);
7693 free(tagmsg_path);
7694 got_ref_list_free(&refs);
7695 return err;
7698 static const struct got_error *
7699 cmd_tag(int argc, char *argv[])
7701 const struct got_error *error = NULL;
7702 struct got_repository *repo = NULL;
7703 struct got_worktree *worktree = NULL;
7704 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7705 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7706 char *allowed_signers = NULL, *revoked_signers = NULL;
7707 const char *signer_id = NULL;
7708 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7709 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7710 int *pack_fds = NULL;
7712 #ifndef PROFILE
7713 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7714 "sendfd unveil", NULL) == -1)
7715 err(1, "pledge");
7716 #endif
7718 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7719 switch (ch) {
7720 case 'c':
7721 commit_id_arg = optarg;
7722 break;
7723 case 'l':
7724 do_list = 1;
7725 break;
7726 case 'm':
7727 tagmsg = optarg;
7728 break;
7729 case 'r':
7730 repo_path = realpath(optarg, NULL);
7731 if (repo_path == NULL) {
7732 error = got_error_from_errno2("realpath",
7733 optarg);
7734 goto done;
7736 got_path_strip_trailing_slashes(repo_path);
7737 break;
7738 case 's':
7739 signer_id = optarg;
7740 break;
7741 case 'V':
7742 verify_tags = 1;
7743 break;
7744 case 'v':
7745 if (verbosity < 0)
7746 verbosity = 0;
7747 else if (verbosity < 3)
7748 verbosity++;
7749 break;
7750 default:
7751 usage_tag();
7752 /* NOTREACHED */
7756 argc -= optind;
7757 argv += optind;
7759 if (do_list || verify_tags) {
7760 if (commit_id_arg != NULL)
7761 errx(1,
7762 "-c option can only be used when creating a tag");
7763 if (tagmsg) {
7764 if (do_list)
7765 option_conflict('l', 'm');
7766 else
7767 option_conflict('V', 'm');
7769 if (signer_id) {
7770 if (do_list)
7771 option_conflict('l', 's');
7772 else
7773 option_conflict('V', 's');
7775 if (argc > 1)
7776 usage_tag();
7777 } else if (argc != 1)
7778 usage_tag();
7780 if (argc == 1)
7781 tag_name = argv[0];
7783 cwd = getcwd(NULL, 0);
7784 if (cwd == NULL) {
7785 error = got_error_from_errno("getcwd");
7786 goto done;
7789 error = got_repo_pack_fds_open(&pack_fds);
7790 if (error != NULL)
7791 goto done;
7793 if (repo_path == NULL) {
7794 error = got_worktree_open(&worktree, cwd,
7795 GOT_WORKTREE_GOT_DIR);
7796 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7797 goto done;
7798 else
7799 error = NULL;
7800 if (worktree) {
7801 repo_path =
7802 strdup(got_worktree_get_repo_path(worktree));
7803 if (repo_path == NULL)
7804 error = got_error_from_errno("strdup");
7805 if (error)
7806 goto done;
7807 } else {
7808 repo_path = strdup(cwd);
7809 if (repo_path == NULL) {
7810 error = got_error_from_errno("strdup");
7811 goto done;
7816 if (do_list || verify_tags) {
7817 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7818 if (error != NULL)
7819 goto done;
7820 error = get_allowed_signers(&allowed_signers, repo, worktree);
7821 if (error)
7822 goto done;
7823 error = get_revoked_signers(&revoked_signers, repo, worktree);
7824 if (error)
7825 goto done;
7826 if (worktree) {
7827 /* Release work tree lock. */
7828 got_worktree_close(worktree);
7829 worktree = NULL;
7833 * Remove "cpath" promise unless needed for signature tmpfile
7834 * creation.
7836 if (verify_tags)
7837 got_sigs_apply_unveil();
7838 else {
7839 #ifndef PROFILE
7840 if (pledge("stdio rpath wpath flock proc exec sendfd "
7841 "unveil", NULL) == -1)
7842 err(1, "pledge");
7843 #endif
7845 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7846 if (error)
7847 goto done;
7848 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7849 revoked_signers, verbosity);
7850 } else {
7851 error = get_gitconfig_path(&gitconfig_path);
7852 if (error)
7853 goto done;
7854 error = got_repo_open(&repo, repo_path, gitconfig_path,
7855 pack_fds);
7856 if (error != NULL)
7857 goto done;
7859 error = get_author(&tagger, repo, worktree);
7860 if (error)
7861 goto done;
7862 if (signer_id == NULL)
7863 signer_id = get_signer_id(repo, worktree);
7865 if (tagmsg) {
7866 if (signer_id) {
7867 error = got_sigs_apply_unveil();
7868 if (error)
7869 goto done;
7871 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7872 if (error)
7873 goto done;
7876 if (commit_id_arg == NULL) {
7877 struct got_reference *head_ref;
7878 struct got_object_id *commit_id;
7879 error = got_ref_open(&head_ref, repo,
7880 worktree ? got_worktree_get_head_ref_name(worktree)
7881 : GOT_REF_HEAD, 0);
7882 if (error)
7883 goto done;
7884 error = got_ref_resolve(&commit_id, repo, head_ref);
7885 got_ref_close(head_ref);
7886 if (error)
7887 goto done;
7888 error = got_object_id_str(&commit_id_str, commit_id);
7889 free(commit_id);
7890 if (error)
7891 goto done;
7892 } else {
7893 error = got_keyword_to_idstr(&keyword_idstr,
7894 commit_id_arg, repo, worktree);
7895 if (error != NULL)
7896 goto done;
7897 commit_id_str = keyword_idstr;
7900 if (worktree) {
7901 /* Release work tree lock. */
7902 got_worktree_close(worktree);
7903 worktree = NULL;
7906 error = add_tag(repo, tagger, tag_name,
7907 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7908 signer_id, verbosity);
7910 done:
7911 if (repo) {
7912 const struct got_error *close_err = got_repo_close(repo);
7913 if (error == NULL)
7914 error = close_err;
7916 if (worktree)
7917 got_worktree_close(worktree);
7918 if (pack_fds) {
7919 const struct got_error *pack_err =
7920 got_repo_pack_fds_close(pack_fds);
7921 if (error == NULL)
7922 error = pack_err;
7924 free(cwd);
7925 free(repo_path);
7926 free(gitconfig_path);
7927 free(commit_id_str);
7928 free(tagger);
7929 free(allowed_signers);
7930 free(revoked_signers);
7931 return error;
7934 __dead static void
7935 usage_add(void)
7937 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7938 exit(1);
7941 static const struct got_error *
7942 add_progress(void *arg, unsigned char status, const char *path)
7944 while (path[0] == '/')
7945 path++;
7946 printf("%c %s\n", status, path);
7947 return NULL;
7950 static const struct got_error *
7951 cmd_add(int argc, char *argv[])
7953 const struct got_error *error = NULL;
7954 struct got_repository *repo = NULL;
7955 struct got_worktree *worktree = NULL;
7956 char *cwd = NULL;
7957 struct got_pathlist_head paths;
7958 struct got_pathlist_entry *pe;
7959 int ch, can_recurse = 0, no_ignores = 0;
7960 int *pack_fds = NULL;
7962 TAILQ_INIT(&paths);
7964 #ifndef PROFILE
7965 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7966 NULL) == -1)
7967 err(1, "pledge");
7968 #endif
7970 while ((ch = getopt(argc, argv, "IR")) != -1) {
7971 switch (ch) {
7972 case 'I':
7973 no_ignores = 1;
7974 break;
7975 case 'R':
7976 can_recurse = 1;
7977 break;
7978 default:
7979 usage_add();
7980 /* NOTREACHED */
7984 argc -= optind;
7985 argv += optind;
7987 if (argc < 1)
7988 usage_add();
7990 cwd = getcwd(NULL, 0);
7991 if (cwd == NULL) {
7992 error = got_error_from_errno("getcwd");
7993 goto done;
7996 error = got_repo_pack_fds_open(&pack_fds);
7997 if (error != NULL)
7998 goto done;
8000 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8001 if (error) {
8002 if (error->code == GOT_ERR_NOT_WORKTREE)
8003 error = wrap_not_worktree_error(error, "add", cwd);
8004 goto done;
8007 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8008 NULL, pack_fds);
8009 if (error != NULL)
8010 goto done;
8012 error = apply_unveil(got_repo_get_path(repo), 1,
8013 got_worktree_get_root_path(worktree));
8014 if (error)
8015 goto done;
8017 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8018 if (error)
8019 goto done;
8021 if (!can_recurse) {
8022 char *ondisk_path;
8023 struct stat sb;
8024 TAILQ_FOREACH(pe, &paths, entry) {
8025 if (asprintf(&ondisk_path, "%s/%s",
8026 got_worktree_get_root_path(worktree),
8027 pe->path) == -1) {
8028 error = got_error_from_errno("asprintf");
8029 goto done;
8031 if (lstat(ondisk_path, &sb) == -1) {
8032 if (errno == ENOENT) {
8033 free(ondisk_path);
8034 continue;
8036 error = got_error_from_errno2("lstat",
8037 ondisk_path);
8038 free(ondisk_path);
8039 goto done;
8041 free(ondisk_path);
8042 if (S_ISDIR(sb.st_mode)) {
8043 error = got_error_msg(GOT_ERR_BAD_PATH,
8044 "adding directories requires -R option");
8045 goto done;
8050 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8051 NULL, repo, no_ignores);
8052 done:
8053 if (repo) {
8054 const struct got_error *close_err = got_repo_close(repo);
8055 if (error == NULL)
8056 error = close_err;
8058 if (worktree)
8059 got_worktree_close(worktree);
8060 if (pack_fds) {
8061 const struct got_error *pack_err =
8062 got_repo_pack_fds_close(pack_fds);
8063 if (error == NULL)
8064 error = pack_err;
8066 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8067 free(cwd);
8068 return error;
8071 __dead static void
8072 usage_remove(void)
8074 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8075 getprogname());
8076 exit(1);
8079 static const struct got_error *
8080 print_remove_status(void *arg, unsigned char status,
8081 unsigned char staged_status, const char *path)
8083 while (path[0] == '/')
8084 path++;
8085 if (status == GOT_STATUS_NONEXISTENT)
8086 return NULL;
8087 if (status == staged_status && (status == GOT_STATUS_DELETE))
8088 status = GOT_STATUS_NO_CHANGE;
8089 printf("%c%c %s\n", status, staged_status, path);
8090 return NULL;
8093 static const struct got_error *
8094 cmd_remove(int argc, char *argv[])
8096 const struct got_error *error = NULL;
8097 struct got_worktree *worktree = NULL;
8098 struct got_repository *repo = NULL;
8099 const char *status_codes = NULL;
8100 char *cwd = NULL;
8101 struct got_pathlist_head paths;
8102 struct got_pathlist_entry *pe;
8103 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8104 int ignore_missing_paths = 0;
8105 int *pack_fds = NULL;
8107 TAILQ_INIT(&paths);
8109 #ifndef PROFILE
8110 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8111 NULL) == -1)
8112 err(1, "pledge");
8113 #endif
8115 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8116 switch (ch) {
8117 case 'f':
8118 delete_local_mods = 1;
8119 ignore_missing_paths = 1;
8120 break;
8121 case 'k':
8122 keep_on_disk = 1;
8123 break;
8124 case 'R':
8125 can_recurse = 1;
8126 break;
8127 case 's':
8128 for (i = 0; optarg[i] != '\0'; i++) {
8129 switch (optarg[i]) {
8130 case GOT_STATUS_MODIFY:
8131 delete_local_mods = 1;
8132 break;
8133 case GOT_STATUS_MISSING:
8134 ignore_missing_paths = 1;
8135 break;
8136 default:
8137 errx(1, "invalid status code '%c'",
8138 optarg[i]);
8141 status_codes = optarg;
8142 break;
8143 default:
8144 usage_remove();
8145 /* NOTREACHED */
8149 argc -= optind;
8150 argv += optind;
8152 if (argc < 1)
8153 usage_remove();
8155 cwd = getcwd(NULL, 0);
8156 if (cwd == NULL) {
8157 error = got_error_from_errno("getcwd");
8158 goto done;
8161 error = got_repo_pack_fds_open(&pack_fds);
8162 if (error != NULL)
8163 goto done;
8165 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8166 if (error) {
8167 if (error->code == GOT_ERR_NOT_WORKTREE)
8168 error = wrap_not_worktree_error(error, "remove", cwd);
8169 goto done;
8172 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8173 NULL, pack_fds);
8174 if (error)
8175 goto done;
8177 error = apply_unveil(got_repo_get_path(repo), 1,
8178 got_worktree_get_root_path(worktree));
8179 if (error)
8180 goto done;
8182 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8183 if (error)
8184 goto done;
8186 if (!can_recurse) {
8187 char *ondisk_path;
8188 struct stat sb;
8189 TAILQ_FOREACH(pe, &paths, entry) {
8190 if (asprintf(&ondisk_path, "%s/%s",
8191 got_worktree_get_root_path(worktree),
8192 pe->path) == -1) {
8193 error = got_error_from_errno("asprintf");
8194 goto done;
8196 if (lstat(ondisk_path, &sb) == -1) {
8197 if (errno == ENOENT) {
8198 free(ondisk_path);
8199 continue;
8201 error = got_error_from_errno2("lstat",
8202 ondisk_path);
8203 free(ondisk_path);
8204 goto done;
8206 free(ondisk_path);
8207 if (S_ISDIR(sb.st_mode)) {
8208 error = got_error_msg(GOT_ERR_BAD_PATH,
8209 "removing directories requires -R option");
8210 goto done;
8215 error = got_worktree_schedule_delete(worktree, &paths,
8216 delete_local_mods, status_codes, print_remove_status, NULL,
8217 repo, keep_on_disk, ignore_missing_paths);
8218 done:
8219 if (repo) {
8220 const struct got_error *close_err = got_repo_close(repo);
8221 if (error == NULL)
8222 error = close_err;
8224 if (worktree)
8225 got_worktree_close(worktree);
8226 if (pack_fds) {
8227 const struct got_error *pack_err =
8228 got_repo_pack_fds_close(pack_fds);
8229 if (error == NULL)
8230 error = pack_err;
8232 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8233 free(cwd);
8234 return error;
8237 __dead static void
8238 usage_patch(void)
8240 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8241 "[patchfile]\n", getprogname());
8242 exit(1);
8245 static const struct got_error *
8246 patch_from_stdin(int *patchfd)
8248 const struct got_error *err = NULL;
8249 ssize_t r;
8250 char buf[BUFSIZ];
8251 sig_t sighup, sigint, sigquit;
8253 *patchfd = got_opentempfd();
8254 if (*patchfd == -1)
8255 return got_error_from_errno("got_opentempfd");
8257 sighup = signal(SIGHUP, SIG_DFL);
8258 sigint = signal(SIGINT, SIG_DFL);
8259 sigquit = signal(SIGQUIT, SIG_DFL);
8261 for (;;) {
8262 r = read(0, buf, sizeof(buf));
8263 if (r == -1) {
8264 err = got_error_from_errno("read");
8265 break;
8267 if (r == 0)
8268 break;
8269 if (write(*patchfd, buf, r) == -1) {
8270 err = got_error_from_errno("write");
8271 break;
8275 signal(SIGHUP, sighup);
8276 signal(SIGINT, sigint);
8277 signal(SIGQUIT, sigquit);
8279 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8280 err = got_error_from_errno("lseek");
8282 if (err != NULL) {
8283 close(*patchfd);
8284 *patchfd = -1;
8287 return err;
8290 struct got_patch_progress_arg {
8291 int did_something;
8292 int conflicts;
8293 int rejects;
8296 static const struct got_error *
8297 patch_progress(void *arg, const char *old, const char *new,
8298 unsigned char status, const struct got_error *error, int old_from,
8299 int old_lines, int new_from, int new_lines, int offset,
8300 int ws_mangled, const struct got_error *hunk_err)
8302 const char *path = new == NULL ? old : new;
8303 struct got_patch_progress_arg *a = arg;
8305 while (*path == '/')
8306 path++;
8308 if (status != GOT_STATUS_NO_CHANGE &&
8309 status != 0 /* per-hunk progress */) {
8310 printf("%c %s\n", status, path);
8311 a->did_something = 1;
8314 if (hunk_err == NULL) {
8315 if (status == GOT_STATUS_CANNOT_UPDATE)
8316 a->rejects++;
8317 else if (status == GOT_STATUS_CONFLICT)
8318 a->conflicts++;
8321 if (error != NULL)
8322 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8324 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8325 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8326 old_lines, new_from, new_lines);
8327 if (hunk_err != NULL)
8328 printf("%s\n", hunk_err->msg);
8329 else if (offset != 0)
8330 printf("applied with offset %d\n", offset);
8331 else
8332 printf("hunk contains mangled whitespace\n");
8335 return NULL;
8338 static void
8339 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8341 if (!ppa->did_something)
8342 return;
8344 if (ppa->conflicts > 0)
8345 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8347 if (ppa->rejects > 0) {
8348 printf("Files where patch failed to apply: %d\n",
8349 ppa->rejects);
8353 static const struct got_error *
8354 cmd_patch(int argc, char *argv[])
8356 const struct got_error *error = NULL, *close_error = NULL;
8357 struct got_worktree *worktree = NULL;
8358 struct got_repository *repo = NULL;
8359 struct got_reflist_head refs;
8360 struct got_object_id *commit_id = NULL;
8361 const char *commit_id_str = NULL;
8362 struct stat sb;
8363 const char *errstr;
8364 char *cwd = NULL, *keyword_idstr = NULL;
8365 int ch, nop = 0, strip = -1, reverse = 0;
8366 int patchfd;
8367 int *pack_fds = NULL;
8368 struct got_patch_progress_arg ppa;
8370 TAILQ_INIT(&refs);
8372 #ifndef PROFILE
8373 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8374 "unveil", NULL) == -1)
8375 err(1, "pledge");
8376 #endif
8378 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8379 switch (ch) {
8380 case 'c':
8381 commit_id_str = optarg;
8382 break;
8383 case 'n':
8384 nop = 1;
8385 break;
8386 case 'p':
8387 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8388 if (errstr != NULL)
8389 errx(1, "pathname strip count is %s: %s",
8390 errstr, optarg);
8391 break;
8392 case 'R':
8393 reverse = 1;
8394 break;
8395 default:
8396 usage_patch();
8397 /* NOTREACHED */
8401 argc -= optind;
8402 argv += optind;
8404 if (argc == 0) {
8405 error = patch_from_stdin(&patchfd);
8406 if (error)
8407 return error;
8408 } else if (argc == 1) {
8409 patchfd = open(argv[0], O_RDONLY);
8410 if (patchfd == -1) {
8411 error = got_error_from_errno2("open", argv[0]);
8412 return error;
8414 if (fstat(patchfd, &sb) == -1) {
8415 error = got_error_from_errno2("fstat", argv[0]);
8416 goto done;
8418 if (!S_ISREG(sb.st_mode)) {
8419 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8420 goto done;
8422 } else
8423 usage_patch();
8425 if ((cwd = getcwd(NULL, 0)) == NULL) {
8426 error = got_error_from_errno("getcwd");
8427 goto done;
8430 error = got_repo_pack_fds_open(&pack_fds);
8431 if (error != NULL)
8432 goto done;
8434 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8435 if (error != NULL)
8436 goto done;
8438 const char *repo_path = got_worktree_get_repo_path(worktree);
8439 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8440 if (error != NULL)
8441 goto done;
8443 error = apply_unveil(got_repo_get_path(repo), 0,
8444 got_worktree_get_root_path(worktree));
8445 if (error != NULL)
8446 goto done;
8448 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8449 if (error)
8450 goto done;
8452 if (commit_id_str != NULL) {
8453 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8454 repo, worktree);
8455 if (error != NULL)
8456 goto done;
8458 error = got_repo_match_object_id(&commit_id, NULL,
8459 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8460 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8461 if (error)
8462 goto done;
8465 memset(&ppa, 0, sizeof(ppa));
8466 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8467 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8468 print_patch_progress_stats(&ppa);
8469 done:
8470 got_ref_list_free(&refs);
8471 free(keyword_idstr);
8472 free(commit_id);
8473 if (repo) {
8474 close_error = got_repo_close(repo);
8475 if (error == NULL)
8476 error = close_error;
8478 if (worktree != NULL) {
8479 close_error = got_worktree_close(worktree);
8480 if (error == NULL)
8481 error = close_error;
8483 if (pack_fds) {
8484 const struct got_error *pack_err =
8485 got_repo_pack_fds_close(pack_fds);
8486 if (error == NULL)
8487 error = pack_err;
8489 free(cwd);
8490 return error;
8493 __dead static void
8494 usage_revert(void)
8496 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8497 getprogname());
8498 exit(1);
8501 static const struct got_error *
8502 revert_progress(void *arg, unsigned char status, const char *path)
8504 if (status == GOT_STATUS_UNVERSIONED)
8505 return NULL;
8507 while (path[0] == '/')
8508 path++;
8509 printf("%c %s\n", status, path);
8510 return NULL;
8513 struct choose_patch_arg {
8514 FILE *patch_script_file;
8515 const char *action;
8518 static const struct got_error *
8519 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8520 int nchanges, const char *action)
8522 const struct got_error *err;
8523 char *line = NULL;
8524 size_t linesize = 0;
8525 ssize_t linelen;
8527 switch (status) {
8528 case GOT_STATUS_ADD:
8529 printf("A %s\n%s this addition? [y/n] ", path, action);
8530 break;
8531 case GOT_STATUS_DELETE:
8532 printf("D %s\n%s this deletion? [y/n] ", path, action);
8533 break;
8534 case GOT_STATUS_MODIFY:
8535 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8536 return got_error_from_errno("fseek");
8537 printf(GOT_COMMIT_SEP_STR);
8538 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8539 printf("%s", line);
8540 if (linelen == -1 && ferror(patch_file)) {
8541 err = got_error_from_errno("getline");
8542 free(line);
8543 return err;
8545 free(line);
8546 printf(GOT_COMMIT_SEP_STR);
8547 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8548 path, n, nchanges, action);
8549 break;
8550 default:
8551 return got_error_path(path, GOT_ERR_FILE_STATUS);
8554 fflush(stdout);
8555 return NULL;
8558 static const struct got_error *
8559 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8560 FILE *patch_file, int n, int nchanges)
8562 const struct got_error *err = NULL;
8563 char *line = NULL;
8564 size_t linesize = 0;
8565 ssize_t linelen;
8566 int resp = ' ';
8567 struct choose_patch_arg *a = arg;
8569 *choice = GOT_PATCH_CHOICE_NONE;
8571 if (a->patch_script_file) {
8572 char *nl;
8573 err = show_change(status, path, patch_file, n, nchanges,
8574 a->action);
8575 if (err)
8576 return err;
8577 linelen = getline(&line, &linesize, a->patch_script_file);
8578 if (linelen == -1) {
8579 if (ferror(a->patch_script_file))
8580 return got_error_from_errno("getline");
8581 return NULL;
8583 nl = strchr(line, '\n');
8584 if (nl)
8585 *nl = '\0';
8586 if (strcmp(line, "y") == 0) {
8587 *choice = GOT_PATCH_CHOICE_YES;
8588 printf("y\n");
8589 } else if (strcmp(line, "n") == 0) {
8590 *choice = GOT_PATCH_CHOICE_NO;
8591 printf("n\n");
8592 } else if (strcmp(line, "q") == 0 &&
8593 status == GOT_STATUS_MODIFY) {
8594 *choice = GOT_PATCH_CHOICE_QUIT;
8595 printf("q\n");
8596 } else
8597 printf("invalid response '%s'\n", line);
8598 free(line);
8599 return NULL;
8602 while (resp != 'y' && resp != 'n' && resp != 'q') {
8603 err = show_change(status, path, patch_file, n, nchanges,
8604 a->action);
8605 if (err)
8606 return err;
8607 resp = getchar();
8608 if (resp == '\n')
8609 resp = getchar();
8610 if (status == GOT_STATUS_MODIFY) {
8611 if (resp != 'y' && resp != 'n' && resp != 'q') {
8612 printf("invalid response '%c'\n", resp);
8613 resp = ' ';
8615 } else if (resp != 'y' && resp != 'n') {
8616 printf("invalid response '%c'\n", resp);
8617 resp = ' ';
8621 if (resp == 'y')
8622 *choice = GOT_PATCH_CHOICE_YES;
8623 else if (resp == 'n')
8624 *choice = GOT_PATCH_CHOICE_NO;
8625 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8626 *choice = GOT_PATCH_CHOICE_QUIT;
8628 return NULL;
8631 struct wt_commitable_path_arg {
8632 struct got_pathlist_head *commit_paths;
8633 int *has_changes;
8637 * Shortcut work tree status callback to determine if the set of paths scanned
8638 * has at least one versioned path that is being modified and, if not NULL, is
8639 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8640 * soon as a path is passed with a status that satisfies this criteria.
8642 static const struct got_error *
8643 worktree_has_commitable_path(void *arg, unsigned char status,
8644 unsigned char staged_status, const char *path,
8645 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8646 struct got_object_id *commit_id, int dirfd, const char *de_name)
8648 struct wt_commitable_path_arg *a = arg;
8650 if (status == staged_status && (status == GOT_STATUS_DELETE))
8651 status = GOT_STATUS_NO_CHANGE;
8653 if (!(status == GOT_STATUS_NO_CHANGE ||
8654 status == GOT_STATUS_UNVERSIONED) ||
8655 staged_status != GOT_STATUS_NO_CHANGE) {
8656 if (a->commit_paths != NULL) {
8657 struct got_pathlist_entry *pe;
8659 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8660 if (strncmp(path, pe->path,
8661 pe->path_len) == 0) {
8662 *a->has_changes = 1;
8663 break;
8666 } else
8667 *a->has_changes = 1;
8669 if (*a->has_changes)
8670 return got_error(GOT_ERR_FILE_MODIFIED);
8673 return NULL;
8677 * Check that the changeset of the commit identified by id is
8678 * comprised of at least one modified path that is being committed.
8680 static const struct got_error *
8681 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8682 struct got_object_id *id, struct got_worktree *worktree,
8683 struct got_repository *repo)
8685 const struct got_error *err;
8686 struct got_pathlist_head paths;
8687 struct got_commit_object *commit = NULL, *pcommit = NULL;
8688 struct got_tree_object *tree = NULL, *ptree = NULL;
8689 struct got_object_qid *pid;
8691 TAILQ_INIT(&paths);
8693 err = got_object_open_as_commit(&commit, repo, id);
8694 if (err)
8695 goto done;
8697 err = got_object_open_as_tree(&tree, repo,
8698 got_object_commit_get_tree_id(commit));
8699 if (err)
8700 goto done;
8702 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8703 if (pid != NULL) {
8704 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8705 if (err)
8706 goto done;
8708 err = got_object_open_as_tree(&ptree, repo,
8709 got_object_commit_get_tree_id(pcommit));
8710 if (err)
8711 goto done;
8714 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8715 got_diff_tree_collect_changed_paths, &paths, 0);
8716 if (err)
8717 goto done;
8719 err = got_worktree_status(worktree, &paths, repo, 0,
8720 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8721 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8723 * At least one changed path in the referenced commit is
8724 * modified in the work tree, that's all we need to know!
8726 err = NULL;
8729 done:
8730 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8731 if (commit)
8732 got_object_commit_close(commit);
8733 if (pcommit)
8734 got_object_commit_close(pcommit);
8735 if (tree)
8736 got_object_tree_close(tree);
8737 if (ptree)
8738 got_object_tree_close(ptree);
8739 return err;
8743 * Remove any "logmsg" reference comprised entirely of paths that have
8744 * been reverted in this work tree. If any path in the logmsg ref changeset
8745 * remains in a changed state in the worktree, do not remove the reference.
8747 static const struct got_error *
8748 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8750 const struct got_error *err;
8751 struct got_reflist_head refs;
8752 struct got_reflist_entry *re;
8753 struct got_commit_object *commit = NULL;
8754 struct got_object_id *commit_id = NULL;
8755 struct wt_commitable_path_arg wcpa;
8756 char *uuidstr = NULL;
8758 TAILQ_INIT(&refs);
8760 err = got_worktree_get_uuid(&uuidstr, worktree);
8761 if (err)
8762 goto done;
8764 err = got_ref_list(&refs, repo, "refs/got/worktree",
8765 got_ref_cmp_by_name, repo);
8766 if (err)
8767 goto done;
8769 TAILQ_FOREACH(re, &refs, entry) {
8770 const char *refname;
8771 int has_changes = 0;
8773 refname = got_ref_get_name(re->ref);
8775 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8776 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8777 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8778 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8779 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8780 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8781 else
8782 continue;
8784 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8785 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8786 else
8787 continue;
8789 err = got_repo_match_object_id(&commit_id, NULL, refname,
8790 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8791 if (err)
8792 goto done;
8794 err = got_object_open_as_commit(&commit, repo, commit_id);
8795 if (err)
8796 goto done;
8798 wcpa.commit_paths = NULL;
8799 wcpa.has_changes = &has_changes;
8801 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8802 worktree, repo);
8803 if (err)
8804 goto done;
8806 if (!has_changes) {
8807 err = got_ref_delete(re->ref, repo);
8808 if (err)
8809 goto done;
8812 got_object_commit_close(commit);
8813 commit = NULL;
8814 free(commit_id);
8815 commit_id = NULL;
8818 done:
8819 free(uuidstr);
8820 free(commit_id);
8821 got_ref_list_free(&refs);
8822 if (commit)
8823 got_object_commit_close(commit);
8824 return err;
8827 static const struct got_error *
8828 cmd_revert(int argc, char *argv[])
8830 const struct got_error *error = NULL;
8831 struct got_worktree *worktree = NULL;
8832 struct got_repository *repo = NULL;
8833 char *cwd = NULL, *path = NULL;
8834 struct got_pathlist_head paths;
8835 struct got_pathlist_entry *pe;
8836 int ch, can_recurse = 0, pflag = 0;
8837 FILE *patch_script_file = NULL;
8838 const char *patch_script_path = NULL;
8839 struct choose_patch_arg cpa;
8840 int *pack_fds = NULL;
8842 TAILQ_INIT(&paths);
8844 #ifndef PROFILE
8845 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8846 "unveil", NULL) == -1)
8847 err(1, "pledge");
8848 #endif
8850 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8851 switch (ch) {
8852 case 'F':
8853 patch_script_path = optarg;
8854 break;
8855 case 'p':
8856 pflag = 1;
8857 break;
8858 case 'R':
8859 can_recurse = 1;
8860 break;
8861 default:
8862 usage_revert();
8863 /* NOTREACHED */
8867 argc -= optind;
8868 argv += optind;
8870 if (argc < 1)
8871 usage_revert();
8872 if (patch_script_path && !pflag)
8873 errx(1, "-F option can only be used together with -p option");
8875 cwd = getcwd(NULL, 0);
8876 if (cwd == NULL) {
8877 error = got_error_from_errno("getcwd");
8878 goto done;
8881 error = got_repo_pack_fds_open(&pack_fds);
8882 if (error != NULL)
8883 goto done;
8885 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8886 if (error) {
8887 if (error->code == GOT_ERR_NOT_WORKTREE)
8888 error = wrap_not_worktree_error(error, "revert", cwd);
8889 goto done;
8892 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8893 NULL, pack_fds);
8894 if (error != NULL)
8895 goto done;
8897 if (patch_script_path) {
8898 patch_script_file = fopen(patch_script_path, "re");
8899 if (patch_script_file == NULL) {
8900 error = got_error_from_errno2("fopen",
8901 patch_script_path);
8902 goto done;
8907 * XXX "c" perm needed on repo dir to delete merge references.
8909 error = apply_unveil(got_repo_get_path(repo), 0,
8910 got_worktree_get_root_path(worktree));
8911 if (error)
8912 goto done;
8914 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8915 if (error)
8916 goto done;
8918 if (!can_recurse) {
8919 char *ondisk_path;
8920 struct stat sb;
8921 TAILQ_FOREACH(pe, &paths, entry) {
8922 if (asprintf(&ondisk_path, "%s/%s",
8923 got_worktree_get_root_path(worktree),
8924 pe->path) == -1) {
8925 error = got_error_from_errno("asprintf");
8926 goto done;
8928 if (lstat(ondisk_path, &sb) == -1) {
8929 if (errno == ENOENT) {
8930 free(ondisk_path);
8931 continue;
8933 error = got_error_from_errno2("lstat",
8934 ondisk_path);
8935 free(ondisk_path);
8936 goto done;
8938 free(ondisk_path);
8939 if (S_ISDIR(sb.st_mode)) {
8940 error = got_error_msg(GOT_ERR_BAD_PATH,
8941 "reverting directories requires -R option");
8942 goto done;
8947 cpa.patch_script_file = patch_script_file;
8948 cpa.action = "revert";
8949 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8950 pflag ? choose_patch : NULL, &cpa, repo);
8952 error = rm_logmsg_ref(worktree, repo);
8953 done:
8954 if (patch_script_file && fclose(patch_script_file) == EOF &&
8955 error == NULL)
8956 error = got_error_from_errno2("fclose", patch_script_path);
8957 if (repo) {
8958 const struct got_error *close_err = got_repo_close(repo);
8959 if (error == NULL)
8960 error = close_err;
8962 if (worktree)
8963 got_worktree_close(worktree);
8964 if (pack_fds) {
8965 const struct got_error *pack_err =
8966 got_repo_pack_fds_close(pack_fds);
8967 if (error == NULL)
8968 error = pack_err;
8970 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8971 free(path);
8972 free(cwd);
8973 return error;
8976 __dead static void
8977 usage_commit(void)
8979 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8980 "[-m message] [path ...]\n", getprogname());
8981 exit(1);
8984 struct collect_commit_logmsg_arg {
8985 const char *cmdline_log;
8986 const char *prepared_log;
8987 const char *merged_log;
8988 int non_interactive;
8989 const char *editor;
8990 const char *worktree_path;
8991 const char *branch_name;
8992 const char *repo_path;
8993 char *logmsg_path;
8997 static const struct got_error *
8998 read_prepared_logmsg(char **logmsg, const char *path)
9000 const struct got_error *err = NULL;
9001 FILE *f = NULL;
9002 struct stat sb;
9003 size_t r;
9005 *logmsg = NULL;
9006 memset(&sb, 0, sizeof(sb));
9008 f = fopen(path, "re");
9009 if (f == NULL)
9010 return got_error_from_errno2("fopen", path);
9012 if (fstat(fileno(f), &sb) == -1) {
9013 err = got_error_from_errno2("fstat", path);
9014 goto done;
9016 if (sb.st_size == 0) {
9017 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9018 goto done;
9021 *logmsg = malloc(sb.st_size + 1);
9022 if (*logmsg == NULL) {
9023 err = got_error_from_errno("malloc");
9024 goto done;
9027 r = fread(*logmsg, 1, sb.st_size, f);
9028 if (r != sb.st_size) {
9029 if (ferror(f))
9030 err = got_error_from_errno2("fread", path);
9031 else
9032 err = got_error(GOT_ERR_IO);
9033 goto done;
9035 (*logmsg)[sb.st_size] = '\0';
9036 done:
9037 if (fclose(f) == EOF && err == NULL)
9038 err = got_error_from_errno2("fclose", path);
9039 if (err) {
9040 free(*logmsg);
9041 *logmsg = NULL;
9043 return err;
9046 static const struct got_error *
9047 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9048 const char *diff_path, char **logmsg, void *arg)
9050 char *initial_content = NULL;
9051 struct got_pathlist_entry *pe;
9052 const struct got_error *err = NULL;
9053 char *template = NULL;
9054 char *prepared_msg = NULL, *merged_msg = NULL;
9055 struct collect_commit_logmsg_arg *a = arg;
9056 int initial_content_len;
9057 int fd = -1;
9058 size_t len;
9060 /* if a message was specified on the command line, just use it */
9061 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9062 len = strlen(a->cmdline_log) + 1;
9063 *logmsg = malloc(len + 1);
9064 if (*logmsg == NULL)
9065 return got_error_from_errno("malloc");
9066 strlcpy(*logmsg, a->cmdline_log, len);
9067 return NULL;
9068 } else if (a->prepared_log != NULL && a->non_interactive)
9069 return read_prepared_logmsg(logmsg, a->prepared_log);
9071 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9072 return got_error_from_errno("asprintf");
9074 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9075 if (err)
9076 goto done;
9078 if (a->prepared_log) {
9079 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9080 if (err)
9081 goto done;
9082 } else if (a->merged_log) {
9083 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9084 if (err)
9085 goto done;
9088 initial_content_len = asprintf(&initial_content,
9089 "%s%s\n# changes to be committed on branch %s:\n",
9090 prepared_msg ? prepared_msg : "",
9091 merged_msg ? merged_msg : "", a->branch_name);
9092 if (initial_content_len == -1) {
9093 err = got_error_from_errno("asprintf");
9094 goto done;
9097 if (write(fd, initial_content, initial_content_len) == -1) {
9098 err = got_error_from_errno2("write", a->logmsg_path);
9099 goto done;
9102 TAILQ_FOREACH(pe, commitable_paths, entry) {
9103 struct got_commitable *ct = pe->data;
9104 dprintf(fd, "# %c %s\n",
9105 got_commitable_get_status(ct),
9106 got_commitable_get_path(ct));
9109 if (diff_path) {
9110 dprintf(fd, "# detailed changes can be viewed in %s\n",
9111 diff_path);
9114 if (close(fd) == -1) {
9115 err = got_error_from_errno2("close", a->logmsg_path);
9116 goto done;
9118 fd = -1;
9120 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9121 initial_content_len, a->prepared_log ? 0 : 1);
9122 done:
9123 free(initial_content);
9124 free(template);
9125 free(prepared_msg);
9126 free(merged_msg);
9128 if (fd != -1 && close(fd) == -1 && err == NULL)
9129 err = got_error_from_errno2("close", a->logmsg_path);
9131 /* Editor is done; we can now apply unveil(2) */
9132 if (err == NULL)
9133 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9134 if (err) {
9135 free(*logmsg);
9136 *logmsg = NULL;
9138 return err;
9141 static const struct got_error *
9142 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9143 const char *type, int has_content)
9145 const struct got_error *err = NULL;
9146 char *logmsg = NULL;
9148 err = got_object_commit_get_logmsg(&logmsg, commit);
9149 if (err)
9150 return err;
9152 if (fprintf(f, "%s# log message of %s commit %s:%s",
9153 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9154 err = got_ferror(f, GOT_ERR_IO);
9156 free(logmsg);
9157 return err;
9161 * Lookup "logmsg" references of backed-out and cherrypicked commits
9162 * belonging to the current work tree. If found, and the worktree has
9163 * at least one modified file that was changed in the referenced commit,
9164 * add its log message to a new temporary file at *logmsg_path.
9165 * Add all refs found to matched_refs to be scheduled for removal on
9166 * successful commit.
9168 static const struct got_error *
9169 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9170 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9171 struct got_repository *repo)
9173 const struct got_error *err;
9174 struct got_commit_object *commit = NULL;
9175 struct got_object_id *id = NULL;
9176 struct got_reflist_head refs;
9177 struct got_reflist_entry *re, *re_match;
9178 FILE *f = NULL;
9179 char *uuidstr = NULL;
9180 int added_logmsg = 0;
9182 TAILQ_INIT(&refs);
9184 *logmsg_path = NULL;
9186 err = got_worktree_get_uuid(&uuidstr, worktree);
9187 if (err)
9188 goto done;
9190 err = got_ref_list(&refs, repo, "refs/got/worktree",
9191 got_ref_cmp_by_name, repo);
9192 if (err)
9193 goto done;
9195 TAILQ_FOREACH(re, &refs, entry) {
9196 const char *refname, *type;
9197 struct wt_commitable_path_arg wcpa;
9198 int add_logmsg = 0;
9200 refname = got_ref_get_name(re->ref);
9202 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9203 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9204 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9205 type = "cherrypicked";
9206 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9207 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9208 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9209 type = "backed-out";
9210 } else
9211 continue;
9213 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9214 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9215 else
9216 continue;
9218 err = got_repo_match_object_id(&id, NULL, refname,
9219 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9220 if (err)
9221 goto done;
9223 err = got_object_open_as_commit(&commit, repo, id);
9224 if (err)
9225 goto done;
9227 wcpa.commit_paths = paths;
9228 wcpa.has_changes = &add_logmsg;
9230 err = commit_path_changed_in_worktree(&wcpa, id,
9231 worktree, repo);
9232 if (err)
9233 goto done;
9235 if (add_logmsg) {
9236 if (f == NULL) {
9237 err = got_opentemp_named(logmsg_path, &f,
9238 "got-commit-logmsg", "");
9239 if (err)
9240 goto done;
9242 err = cat_logmsg(f, commit, refname, type,
9243 added_logmsg);
9244 if (err)
9245 goto done;
9246 if (!added_logmsg)
9247 ++added_logmsg;
9249 err = got_reflist_entry_dup(&re_match, re);
9250 if (err)
9251 goto done;
9252 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9255 got_object_commit_close(commit);
9256 commit = NULL;
9257 free(id);
9258 id = NULL;
9261 done:
9262 free(id);
9263 free(uuidstr);
9264 got_ref_list_free(&refs);
9265 if (commit)
9266 got_object_commit_close(commit);
9267 if (f && fclose(f) == EOF && err == NULL)
9268 err = got_error_from_errno("fclose");
9269 if (!added_logmsg) {
9270 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9271 err = got_error_from_errno2("unlink", *logmsg_path);
9272 *logmsg_path = NULL;
9274 return err;
9277 static const struct got_error *
9278 cmd_commit(int argc, char *argv[])
9280 const struct got_error *error = NULL;
9281 struct got_worktree *worktree = NULL;
9282 struct got_repository *repo = NULL;
9283 char *cwd = NULL, *id_str = NULL;
9284 struct got_object_id *id = NULL;
9285 const char *logmsg = NULL;
9286 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9287 struct collect_commit_logmsg_arg cl_arg;
9288 const char *author = NULL;
9289 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9290 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9291 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9292 int show_diff = 1, commit_conflicts = 0;
9293 struct got_pathlist_head paths;
9294 struct got_reflist_head refs;
9295 struct got_reflist_entry *re;
9296 int *pack_fds = NULL;
9298 TAILQ_INIT(&refs);
9299 TAILQ_INIT(&paths);
9300 cl_arg.logmsg_path = NULL;
9302 #ifndef PROFILE
9303 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9304 "unveil", NULL) == -1)
9305 err(1, "pledge");
9306 #endif
9308 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9309 switch (ch) {
9310 case 'A':
9311 author = optarg;
9312 error = valid_author(author);
9313 if (error)
9314 return error;
9315 break;
9316 case 'C':
9317 commit_conflicts = 1;
9318 break;
9319 case 'F':
9320 if (logmsg != NULL)
9321 option_conflict('F', 'm');
9322 prepared_logmsg = realpath(optarg, NULL);
9323 if (prepared_logmsg == NULL)
9324 return got_error_from_errno2("realpath",
9325 optarg);
9326 break;
9327 case 'm':
9328 if (prepared_logmsg)
9329 option_conflict('m', 'F');
9330 logmsg = optarg;
9331 break;
9332 case 'N':
9333 non_interactive = 1;
9334 break;
9335 case 'n':
9336 show_diff = 0;
9337 break;
9338 case 'S':
9339 allow_bad_symlinks = 1;
9340 break;
9341 default:
9342 usage_commit();
9343 /* NOTREACHED */
9347 argc -= optind;
9348 argv += optind;
9350 cwd = getcwd(NULL, 0);
9351 if (cwd == NULL) {
9352 error = got_error_from_errno("getcwd");
9353 goto done;
9356 error = got_repo_pack_fds_open(&pack_fds);
9357 if (error != NULL)
9358 goto done;
9360 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9361 if (error) {
9362 if (error->code == GOT_ERR_NOT_WORKTREE)
9363 error = wrap_not_worktree_error(error, "commit", cwd);
9364 goto done;
9367 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9368 if (error)
9369 goto done;
9370 if (rebase_in_progress) {
9371 error = got_error(GOT_ERR_REBASING);
9372 goto done;
9375 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9376 worktree);
9377 if (error)
9378 goto done;
9380 error = get_gitconfig_path(&gitconfig_path);
9381 if (error)
9382 goto done;
9383 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9384 gitconfig_path, pack_fds);
9385 if (error != NULL)
9386 goto done;
9388 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9389 if (error)
9390 goto done;
9391 if (merge_in_progress) {
9392 error = got_error(GOT_ERR_MERGE_BUSY);
9393 goto done;
9396 error = get_author(&committer, repo, worktree);
9397 if (error)
9398 goto done;
9400 if (author == NULL)
9401 author = committer;
9404 * unveil(2) traverses exec(2); if an editor is used we have
9405 * to apply unveil after the log message has been written.
9407 if (logmsg == NULL || strlen(logmsg) == 0)
9408 error = get_editor(&editor);
9409 else
9410 error = apply_unveil(got_repo_get_path(repo), 0,
9411 got_worktree_get_root_path(worktree));
9412 if (error)
9413 goto done;
9415 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9416 if (error)
9417 goto done;
9419 if (prepared_logmsg == NULL) {
9420 error = lookup_logmsg_ref(&merged_logmsg,
9421 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9422 if (error)
9423 goto done;
9426 cl_arg.editor = editor;
9427 cl_arg.cmdline_log = logmsg;
9428 cl_arg.prepared_log = prepared_logmsg;
9429 cl_arg.merged_log = merged_logmsg;
9430 cl_arg.non_interactive = non_interactive;
9431 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9432 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9433 if (!histedit_in_progress) {
9434 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9435 error = got_error(GOT_ERR_COMMIT_BRANCH);
9436 goto done;
9438 cl_arg.branch_name += 11;
9440 cl_arg.repo_path = got_repo_get_path(repo);
9441 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9442 allow_bad_symlinks, show_diff, commit_conflicts,
9443 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9444 if (error) {
9445 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9446 cl_arg.logmsg_path != NULL)
9447 preserve_logmsg = 1;
9448 goto done;
9451 error = got_object_id_str(&id_str, id);
9452 if (error)
9453 goto done;
9454 printf("Created commit %s\n", id_str);
9456 TAILQ_FOREACH(re, &refs, entry) {
9457 error = got_ref_delete(re->ref, repo);
9458 if (error)
9459 goto done;
9462 done:
9463 if (preserve_logmsg) {
9464 fprintf(stderr, "%s: log message preserved in %s\n",
9465 getprogname(), cl_arg.logmsg_path);
9466 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9467 error == NULL)
9468 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9469 free(cl_arg.logmsg_path);
9470 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9471 error = got_error_from_errno2("unlink", merged_logmsg);
9472 free(merged_logmsg);
9473 if (repo) {
9474 const struct got_error *close_err = got_repo_close(repo);
9475 if (error == NULL)
9476 error = close_err;
9478 if (worktree)
9479 got_worktree_close(worktree);
9480 if (pack_fds) {
9481 const struct got_error *pack_err =
9482 got_repo_pack_fds_close(pack_fds);
9483 if (error == NULL)
9484 error = pack_err;
9486 got_ref_list_free(&refs);
9487 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9488 free(cwd);
9489 free(id_str);
9490 free(gitconfig_path);
9491 free(editor);
9492 free(committer);
9493 free(prepared_logmsg);
9494 return error;
9497 __dead static void
9498 usage_send(void)
9500 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9501 "[-r repository-path] [-t tag] [remote-repository]\n",
9502 getprogname());
9503 exit(1);
9506 static void
9507 print_load_info(int print_colored, int print_found, int print_trees,
9508 int ncolored, int nfound, int ntrees)
9510 if (print_colored) {
9511 printf("%d commit%s colored", ncolored,
9512 ncolored == 1 ? "" : "s");
9514 if (print_found) {
9515 printf("%s%d object%s found",
9516 ncolored > 0 ? "; " : "",
9517 nfound, nfound == 1 ? "" : "s");
9519 if (print_trees) {
9520 printf("; %d tree%s scanned", ntrees,
9521 ntrees == 1 ? "" : "s");
9525 struct got_send_progress_arg {
9526 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9527 int verbosity;
9528 int last_ncolored;
9529 int last_nfound;
9530 int last_ntrees;
9531 int loading_done;
9532 int last_ncommits;
9533 int last_nobj_total;
9534 int last_p_deltify;
9535 int last_p_written;
9536 int last_p_sent;
9537 int printed_something;
9538 int sent_something;
9539 struct got_pathlist_head *delete_branches;
9542 static const struct got_error *
9543 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9544 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9545 int nobj_written, off_t bytes_sent, const char *refname,
9546 const char *errmsg, int success)
9548 struct got_send_progress_arg *a = arg;
9549 char scaled_packsize[FMT_SCALED_STRSIZE];
9550 char scaled_sent[FMT_SCALED_STRSIZE];
9551 int p_deltify = 0, p_written = 0, p_sent = 0;
9552 int print_colored = 0, print_found = 0, print_trees = 0;
9553 int print_searching = 0, print_total = 0;
9554 int print_deltify = 0, print_written = 0, print_sent = 0;
9556 if (a->verbosity < 0)
9557 return NULL;
9559 if (refname) {
9560 const char *status = success ? "accepted" : "rejected";
9562 if (success) {
9563 struct got_pathlist_entry *pe;
9564 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9565 const char *branchname = pe->path;
9566 if (got_path_cmp(branchname, refname,
9567 strlen(branchname), strlen(refname)) == 0) {
9568 status = "deleted";
9569 a->sent_something = 1;
9570 break;
9575 if (a->printed_something)
9576 putchar('\n');
9577 printf("Server has %s %s", status, refname);
9578 if (errmsg)
9579 printf(": %s", errmsg);
9580 a->printed_something = 1;
9581 return NULL;
9584 if (a->last_ncolored != ncolored) {
9585 print_colored = 1;
9586 a->last_ncolored = ncolored;
9589 if (a->last_nfound != nfound) {
9590 print_colored = 1;
9591 print_found = 1;
9592 a->last_nfound = nfound;
9595 if (a->last_ntrees != ntrees) {
9596 print_colored = 1;
9597 print_found = 1;
9598 print_trees = 1;
9599 a->last_ntrees = ntrees;
9602 if ((print_colored || print_found || print_trees) &&
9603 !a->loading_done) {
9604 printf("\r");
9605 print_load_info(print_colored, print_found, print_trees,
9606 ncolored, nfound, ntrees);
9607 a->printed_something = 1;
9608 fflush(stdout);
9609 return NULL;
9610 } else if (!a->loading_done) {
9611 printf("\r");
9612 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9613 printf("\n");
9614 a->loading_done = 1;
9617 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9618 return got_error_from_errno("fmt_scaled");
9619 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9620 return got_error_from_errno("fmt_scaled");
9622 if (a->last_ncommits != ncommits) {
9623 print_searching = 1;
9624 a->last_ncommits = ncommits;
9627 if (a->last_nobj_total != nobj_total) {
9628 print_searching = 1;
9629 print_total = 1;
9630 a->last_nobj_total = nobj_total;
9633 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9634 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9635 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9636 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9637 return got_error(GOT_ERR_NO_SPACE);
9640 if (nobj_deltify > 0 || nobj_written > 0) {
9641 if (nobj_deltify > 0) {
9642 p_deltify = (nobj_deltify * 100) / nobj_total;
9643 if (p_deltify != a->last_p_deltify) {
9644 a->last_p_deltify = p_deltify;
9645 print_searching = 1;
9646 print_total = 1;
9647 print_deltify = 1;
9650 if (nobj_written > 0) {
9651 p_written = (nobj_written * 100) / nobj_total;
9652 if (p_written != a->last_p_written) {
9653 a->last_p_written = p_written;
9654 print_searching = 1;
9655 print_total = 1;
9656 print_deltify = 1;
9657 print_written = 1;
9662 if (bytes_sent > 0) {
9663 p_sent = (bytes_sent * 100) / packfile_size;
9664 if (p_sent != a->last_p_sent) {
9665 a->last_p_sent = p_sent;
9666 print_searching = 1;
9667 print_total = 1;
9668 print_deltify = 1;
9669 print_written = 1;
9670 print_sent = 1;
9672 a->sent_something = 1;
9675 if (print_searching || print_total || print_deltify || print_written ||
9676 print_sent)
9677 printf("\r");
9678 if (print_searching)
9679 printf("packing %d reference%s", ncommits,
9680 ncommits == 1 ? "" : "s");
9681 if (print_total)
9682 printf("; %d object%s", nobj_total,
9683 nobj_total == 1 ? "" : "s");
9684 if (print_deltify)
9685 printf("; deltify: %d%%", p_deltify);
9686 if (print_sent)
9687 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9688 scaled_packsize, p_sent);
9689 else if (print_written)
9690 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9691 scaled_packsize, p_written);
9692 if (print_searching || print_total || print_deltify ||
9693 print_written || print_sent) {
9694 a->printed_something = 1;
9695 fflush(stdout);
9697 return NULL;
9700 static const struct got_error *
9701 cmd_send(int argc, char *argv[])
9703 const struct got_error *error = NULL;
9704 char *cwd = NULL, *repo_path = NULL;
9705 const char *remote_name;
9706 char *proto = NULL, *host = NULL, *port = NULL;
9707 char *repo_name = NULL, *server_path = NULL;
9708 const struct got_remote_repo *remotes;
9709 struct got_remote_repo *remote = NULL;
9710 int nremotes, nbranches = 0, ndelete_branches = 0;
9711 struct got_repository *repo = NULL;
9712 struct got_worktree *worktree = NULL;
9713 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9714 struct got_pathlist_head branches;
9715 struct got_pathlist_head tags;
9716 struct got_reflist_head all_branches;
9717 struct got_reflist_head all_tags;
9718 struct got_pathlist_head delete_args;
9719 struct got_pathlist_head delete_branches;
9720 struct got_reflist_entry *re;
9721 struct got_pathlist_entry *pe;
9722 int i, ch, sendfd = -1, sendstatus;
9723 pid_t sendpid = -1;
9724 struct got_send_progress_arg spa;
9725 int verbosity = 0, overwrite_refs = 0;
9726 int send_all_branches = 0, send_all_tags = 0;
9727 struct got_reference *ref = NULL;
9728 int *pack_fds = NULL;
9730 TAILQ_INIT(&branches);
9731 TAILQ_INIT(&tags);
9732 TAILQ_INIT(&all_branches);
9733 TAILQ_INIT(&all_tags);
9734 TAILQ_INIT(&delete_args);
9735 TAILQ_INIT(&delete_branches);
9737 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9738 switch (ch) {
9739 case 'a':
9740 send_all_branches = 1;
9741 break;
9742 case 'b':
9743 error = got_pathlist_append(&branches, optarg, NULL);
9744 if (error)
9745 return error;
9746 nbranches++;
9747 break;
9748 case 'd':
9749 error = got_pathlist_append(&delete_args, optarg, NULL);
9750 if (error)
9751 return error;
9752 break;
9753 case 'f':
9754 overwrite_refs = 1;
9755 break;
9756 case 'q':
9757 verbosity = -1;
9758 break;
9759 case 'r':
9760 repo_path = realpath(optarg, NULL);
9761 if (repo_path == NULL)
9762 return got_error_from_errno2("realpath",
9763 optarg);
9764 got_path_strip_trailing_slashes(repo_path);
9765 break;
9766 case 'T':
9767 send_all_tags = 1;
9768 break;
9769 case 't':
9770 error = got_pathlist_append(&tags, optarg, NULL);
9771 if (error)
9772 return error;
9773 break;
9774 case 'v':
9775 if (verbosity < 0)
9776 verbosity = 0;
9777 else if (verbosity < 3)
9778 verbosity++;
9779 break;
9780 default:
9781 usage_send();
9782 /* NOTREACHED */
9785 argc -= optind;
9786 argv += optind;
9788 if (send_all_branches && !TAILQ_EMPTY(&branches))
9789 option_conflict('a', 'b');
9790 if (send_all_tags && !TAILQ_EMPTY(&tags))
9791 option_conflict('T', 't');
9794 if (argc == 0)
9795 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9796 else if (argc == 1)
9797 remote_name = argv[0];
9798 else
9799 usage_send();
9801 cwd = getcwd(NULL, 0);
9802 if (cwd == NULL) {
9803 error = got_error_from_errno("getcwd");
9804 goto done;
9807 error = got_repo_pack_fds_open(&pack_fds);
9808 if (error != NULL)
9809 goto done;
9811 if (repo_path == NULL) {
9812 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9813 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9814 goto done;
9815 else
9816 error = NULL;
9817 if (worktree) {
9818 repo_path =
9819 strdup(got_worktree_get_repo_path(worktree));
9820 if (repo_path == NULL)
9821 error = got_error_from_errno("strdup");
9822 if (error)
9823 goto done;
9824 } else {
9825 repo_path = strdup(cwd);
9826 if (repo_path == NULL) {
9827 error = got_error_from_errno("strdup");
9828 goto done;
9833 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9834 if (error)
9835 goto done;
9837 if (worktree) {
9838 worktree_conf = got_worktree_get_gotconfig(worktree);
9839 if (worktree_conf) {
9840 got_gotconfig_get_remotes(&nremotes, &remotes,
9841 worktree_conf);
9842 for (i = 0; i < nremotes; i++) {
9843 if (strcmp(remotes[i].name, remote_name) == 0) {
9844 error = got_repo_remote_repo_dup(&remote,
9845 &remotes[i]);
9846 if (error)
9847 goto done;
9848 break;
9853 if (remote == NULL) {
9854 repo_conf = got_repo_get_gotconfig(repo);
9855 if (repo_conf) {
9856 got_gotconfig_get_remotes(&nremotes, &remotes,
9857 repo_conf);
9858 for (i = 0; i < nremotes; i++) {
9859 if (strcmp(remotes[i].name, remote_name) == 0) {
9860 error = got_repo_remote_repo_dup(&remote,
9861 &remotes[i]);
9862 if (error)
9863 goto done;
9864 break;
9869 if (remote == NULL) {
9870 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9871 for (i = 0; i < nremotes; i++) {
9872 if (strcmp(remotes[i].name, remote_name) == 0) {
9873 error = got_repo_remote_repo_dup(&remote,
9874 &remotes[i]);
9875 if (error)
9876 goto done;
9877 break;
9881 if (remote == NULL) {
9882 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9883 goto done;
9886 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9887 &repo_name, remote->send_url);
9888 if (error)
9889 goto done;
9891 if (strcmp(proto, "git") == 0) {
9892 #ifndef PROFILE
9893 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9894 "sendfd dns inet unveil", NULL) == -1)
9895 err(1, "pledge");
9896 #endif
9897 } else if (strcmp(proto, "git+ssh") == 0 ||
9898 strcmp(proto, "ssh") == 0) {
9899 #ifndef PROFILE
9900 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9901 "sendfd unveil", NULL) == -1)
9902 err(1, "pledge");
9903 #endif
9904 } else if (strcmp(proto, "http") == 0 ||
9905 strcmp(proto, "git+http") == 0) {
9906 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9907 goto done;
9908 } else {
9909 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9910 goto done;
9913 error = got_dial_apply_unveil(proto);
9914 if (error)
9915 goto done;
9917 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9918 if (error)
9919 goto done;
9921 if (send_all_branches) {
9922 error = got_ref_list(&all_branches, repo, "refs/heads",
9923 got_ref_cmp_by_name, NULL);
9924 if (error)
9925 goto done;
9926 TAILQ_FOREACH(re, &all_branches, entry) {
9927 const char *branchname = got_ref_get_name(re->ref);
9928 error = got_pathlist_append(&branches,
9929 branchname, NULL);
9930 if (error)
9931 goto done;
9932 nbranches++;
9934 } else if (nbranches == 0) {
9935 for (i = 0; i < remote->nsend_branches; i++) {
9936 error = got_pathlist_append(&branches,
9937 remote->send_branches[i], NULL);
9938 if (error)
9939 goto done;
9943 if (send_all_tags) {
9944 error = got_ref_list(&all_tags, repo, "refs/tags",
9945 got_ref_cmp_by_name, NULL);
9946 if (error)
9947 goto done;
9948 TAILQ_FOREACH(re, &all_tags, entry) {
9949 const char *tagname = got_ref_get_name(re->ref);
9950 error = got_pathlist_append(&tags,
9951 tagname, NULL);
9952 if (error)
9953 goto done;
9958 * To prevent accidents only branches in refs/heads/ can be deleted
9959 * with 'got send -d'.
9960 * Deleting anything else requires local repository access or Git.
9962 TAILQ_FOREACH(pe, &delete_args, entry) {
9963 const char *branchname = pe->path;
9964 char *s;
9965 struct got_pathlist_entry *new;
9966 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9967 s = strdup(branchname);
9968 if (s == NULL) {
9969 error = got_error_from_errno("strdup");
9970 goto done;
9972 } else {
9973 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9974 error = got_error_from_errno("asprintf");
9975 goto done;
9978 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9979 if (error || new == NULL /* duplicate */)
9980 free(s);
9981 if (error)
9982 goto done;
9983 ndelete_branches++;
9986 if (nbranches == 0 && ndelete_branches == 0) {
9987 struct got_reference *head_ref;
9988 if (worktree)
9989 error = got_ref_open(&head_ref, repo,
9990 got_worktree_get_head_ref_name(worktree), 0);
9991 else
9992 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9993 if (error)
9994 goto done;
9995 if (got_ref_is_symbolic(head_ref)) {
9996 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9997 got_ref_close(head_ref);
9998 if (error)
9999 goto done;
10000 } else
10001 ref = head_ref;
10002 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10003 NULL);
10004 if (error)
10005 goto done;
10006 nbranches++;
10009 if (worktree) {
10010 /* Release work tree lock. */
10011 got_worktree_close(worktree);
10012 worktree = NULL;
10015 if (verbosity >= 0) {
10016 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10017 remote->name, proto, host,
10018 port ? ":" : "", port ? port : "",
10019 *server_path == '/' ? "" : "/", server_path);
10022 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10023 server_path, verbosity);
10024 if (error)
10025 goto done;
10027 memset(&spa, 0, sizeof(spa));
10028 spa.last_scaled_packsize[0] = '\0';
10029 spa.last_p_deltify = -1;
10030 spa.last_p_written = -1;
10031 spa.verbosity = verbosity;
10032 spa.delete_branches = &delete_branches;
10033 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10034 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10035 check_cancelled, NULL);
10036 if (spa.printed_something)
10037 putchar('\n');
10038 if (error)
10039 goto done;
10040 if (!spa.sent_something && verbosity >= 0)
10041 printf("Already up-to-date\n");
10042 done:
10043 if (sendpid > 0) {
10044 if (kill(sendpid, SIGTERM) == -1)
10045 error = got_error_from_errno("kill");
10046 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10047 error = got_error_from_errno("waitpid");
10049 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10050 error = got_error_from_errno("close");
10051 if (repo) {
10052 const struct got_error *close_err = got_repo_close(repo);
10053 if (error == NULL)
10054 error = close_err;
10056 if (worktree)
10057 got_worktree_close(worktree);
10058 if (pack_fds) {
10059 const struct got_error *pack_err =
10060 got_repo_pack_fds_close(pack_fds);
10061 if (error == NULL)
10062 error = pack_err;
10064 if (ref)
10065 got_ref_close(ref);
10066 got_repo_free_remote_repo_data(remote);
10067 free(remote);
10068 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10069 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10070 got_ref_list_free(&all_branches);
10071 got_ref_list_free(&all_tags);
10072 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10073 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10074 free(cwd);
10075 free(repo_path);
10076 free(proto);
10077 free(host);
10078 free(port);
10079 free(server_path);
10080 free(repo_name);
10081 return error;
10085 * Print and if delete is set delete all ref_prefix references.
10086 * If wanted_ref is not NULL, only print or delete this reference.
10088 static const struct got_error *
10089 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10090 const char *wanted_ref, int delete, struct got_worktree *worktree,
10091 struct got_repository *repo)
10093 const struct got_error *err;
10094 struct got_pathlist_head paths;
10095 struct got_reflist_head refs;
10096 struct got_reflist_entry *re;
10097 struct got_reflist_object_id_map *refs_idmap = NULL;
10098 struct got_commit_object *commit = NULL;
10099 struct got_object_id *id = NULL;
10100 const char *header_prefix;
10101 char *uuidstr = NULL;
10102 int found = 0;
10104 TAILQ_INIT(&refs);
10105 TAILQ_INIT(&paths);
10107 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10108 if (err)
10109 goto done;
10111 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10112 if (err)
10113 goto done;
10115 if (worktree != NULL) {
10116 err = got_worktree_get_uuid(&uuidstr, worktree);
10117 if (err)
10118 goto done;
10121 if (wanted_ref) {
10122 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10123 wanted_ref += 11;
10126 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10127 header_prefix = "backout";
10128 else
10129 header_prefix = "cherrypick";
10131 TAILQ_FOREACH(re, &refs, entry) {
10132 const char *refname, *wt;
10134 refname = got_ref_get_name(re->ref);
10136 err = check_cancelled(NULL);
10137 if (err)
10138 goto done;
10140 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10141 refname += prefix_len + 1; /* skip '-' delimiter */
10142 else
10143 continue;
10145 wt = refname;
10147 if (worktree == NULL || strncmp(refname, uuidstr,
10148 GOT_WORKTREE_UUID_STRLEN) == 0)
10149 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10150 else
10151 continue;
10153 err = got_repo_match_object_id(&id, NULL, refname,
10154 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10155 if (err)
10156 goto done;
10158 err = got_object_open_as_commit(&commit, repo, id);
10159 if (err)
10160 goto done;
10162 if (wanted_ref)
10163 found = strncmp(wanted_ref, refname,
10164 strlen(wanted_ref)) == 0;
10165 if (wanted_ref && !found) {
10166 struct got_reflist_head *ci_refs;
10168 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10169 id);
10171 if (ci_refs) {
10172 char *refs_str = NULL;
10173 char const *r = NULL;
10175 err = build_refs_str(&refs_str, ci_refs, id,
10176 repo, 1);
10177 if (err)
10178 goto done;
10180 r = refs_str;
10181 while (r) {
10182 if (strncmp(r, wanted_ref,
10183 strlen(wanted_ref)) == 0) {
10184 found = 1;
10185 break;
10187 r = strchr(r, ' ');
10188 if (r)
10189 ++r;
10191 free(refs_str);
10195 if (wanted_ref == NULL || found) {
10196 if (delete) {
10197 err = got_ref_delete(re->ref, repo);
10198 if (err)
10199 goto done;
10200 printf("Deleted: ");
10201 err = print_commit_oneline(commit, id, repo,
10202 refs_idmap);
10203 } else {
10205 * Print paths modified by commit to help
10206 * associate commits with worktree changes.
10208 err = get_changed_paths(&paths, commit,
10209 repo, NULL);
10210 if (err)
10211 goto done;
10213 err = print_commit(commit, id, repo, NULL,
10214 &paths, NULL, 0, 0, refs_idmap, NULL,
10215 header_prefix);
10216 got_pathlist_free(&paths,
10217 GOT_PATHLIST_FREE_ALL);
10219 if (worktree == NULL)
10220 printf("work tree: %.*s\n\n",
10221 GOT_WORKTREE_UUID_STRLEN, wt);
10223 if (err || found)
10224 goto done;
10227 got_object_commit_close(commit);
10228 commit = NULL;
10229 free(id);
10230 id = NULL;
10233 if (wanted_ref != NULL && !found)
10234 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10236 done:
10237 free(id);
10238 free(uuidstr);
10239 got_ref_list_free(&refs);
10240 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10241 if (refs_idmap)
10242 got_reflist_object_id_map_free(refs_idmap);
10243 if (commit)
10244 got_object_commit_close(commit);
10245 return err;
10249 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10250 * identified by id for log messages to prepopulate the editor on commit.
10252 static const struct got_error *
10253 logmsg_ref(struct got_object_id *id, const char *prefix,
10254 struct got_worktree *worktree, struct got_repository *repo)
10256 const struct got_error *err = NULL;
10257 char *idstr, *ref = NULL, *refname = NULL;
10258 int histedit_in_progress;
10259 int rebase_in_progress, merge_in_progress;
10262 * Silenty refuse to create merge reference if any histedit, merge,
10263 * or rebase operation is in progress.
10265 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10266 worktree);
10267 if (err)
10268 return err;
10269 if (histedit_in_progress)
10270 return NULL;
10272 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10273 if (err)
10274 return err;
10275 if (rebase_in_progress)
10276 return NULL;
10278 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10279 repo);
10280 if (err)
10281 return err;
10282 if (merge_in_progress)
10283 return NULL;
10285 err = got_object_id_str(&idstr, id);
10286 if (err)
10287 return err;
10289 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10290 if (err)
10291 goto done;
10293 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10294 err = got_error_from_errno("asprintf");
10295 goto done;
10298 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10299 -1, repo);
10300 done:
10301 free(ref);
10302 free(idstr);
10303 free(refname);
10304 return err;
10307 __dead static void
10308 usage_cherrypick(void)
10310 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10311 getprogname());
10312 exit(1);
10315 static const struct got_error *
10316 cmd_cherrypick(int argc, char *argv[])
10318 const struct got_error *error = NULL;
10319 struct got_worktree *worktree = NULL;
10320 struct got_repository *repo = NULL;
10321 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10322 struct got_object_id *commit_id = NULL;
10323 struct got_commit_object *commit = NULL;
10324 struct got_object_qid *pid;
10325 int ch, list_refs = 0, remove_refs = 0;
10326 struct got_update_progress_arg upa;
10327 int *pack_fds = NULL;
10329 #ifndef PROFILE
10330 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10331 "unveil", NULL) == -1)
10332 err(1, "pledge");
10333 #endif
10335 while ((ch = getopt(argc, argv, "lX")) != -1) {
10336 switch (ch) {
10337 case 'l':
10338 list_refs = 1;
10339 break;
10340 case 'X':
10341 remove_refs = 1;
10342 break;
10343 default:
10344 usage_cherrypick();
10345 /* NOTREACHED */
10349 argc -= optind;
10350 argv += optind;
10352 if (list_refs || remove_refs) {
10353 if (argc != 0 && argc != 1)
10354 usage_cherrypick();
10355 } else if (argc != 1)
10356 usage_cherrypick();
10357 if (list_refs && remove_refs)
10358 option_conflict('l', 'X');
10360 cwd = getcwd(NULL, 0);
10361 if (cwd == NULL) {
10362 error = got_error_from_errno("getcwd");
10363 goto done;
10366 error = got_repo_pack_fds_open(&pack_fds);
10367 if (error != NULL)
10368 goto done;
10370 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10371 if (error) {
10372 if (list_refs || remove_refs) {
10373 if (error->code != GOT_ERR_NOT_WORKTREE)
10374 goto done;
10375 } else {
10376 if (error->code == GOT_ERR_NOT_WORKTREE)
10377 error = wrap_not_worktree_error(error,
10378 "cherrypick", cwd);
10379 goto done;
10383 error = got_repo_open(&repo,
10384 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10385 NULL, pack_fds);
10386 if (error != NULL)
10387 goto done;
10389 error = apply_unveil(got_repo_get_path(repo), 0,
10390 worktree ? got_worktree_get_root_path(worktree) : NULL);
10391 if (error)
10392 goto done;
10394 if (list_refs || remove_refs) {
10395 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10396 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10397 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10398 goto done;
10401 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10402 if (error != NULL)
10403 goto done;
10405 error = got_repo_match_object_id(&commit_id, NULL,
10406 keyword_idstr != NULL ? keyword_idstr : argv[0],
10407 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10408 if (error)
10409 goto done;
10410 error = got_object_id_str(&commit_id_str, commit_id);
10411 if (error)
10412 goto done;
10414 error = got_object_open_as_commit(&commit, repo, commit_id);
10415 if (error)
10416 goto done;
10417 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10418 memset(&upa, 0, sizeof(upa));
10419 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10420 commit_id, repo, update_progress, &upa, check_cancelled,
10421 NULL);
10422 if (error != NULL)
10423 goto done;
10425 if (upa.did_something) {
10426 error = logmsg_ref(commit_id,
10427 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10428 if (error)
10429 goto done;
10430 printf("Merged commit %s\n", commit_id_str);
10432 print_merge_progress_stats(&upa);
10433 done:
10434 free(cwd);
10435 free(keyword_idstr);
10436 if (commit)
10437 got_object_commit_close(commit);
10438 free(commit_id_str);
10439 if (worktree)
10440 got_worktree_close(worktree);
10441 if (repo) {
10442 const struct got_error *close_err = got_repo_close(repo);
10443 if (error == NULL)
10444 error = close_err;
10446 if (pack_fds) {
10447 const struct got_error *pack_err =
10448 got_repo_pack_fds_close(pack_fds);
10449 if (error == NULL)
10450 error = pack_err;
10453 return error;
10456 __dead static void
10457 usage_backout(void)
10459 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10460 exit(1);
10463 static const struct got_error *
10464 cmd_backout(int argc, char *argv[])
10466 const struct got_error *error = NULL;
10467 struct got_worktree *worktree = NULL;
10468 struct got_repository *repo = NULL;
10469 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10470 struct got_object_id *commit_id = NULL;
10471 struct got_commit_object *commit = NULL;
10472 struct got_object_qid *pid;
10473 int ch, list_refs = 0, remove_refs = 0;
10474 struct got_update_progress_arg upa;
10475 int *pack_fds = NULL;
10477 #ifndef PROFILE
10478 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10479 "unveil", NULL) == -1)
10480 err(1, "pledge");
10481 #endif
10483 while ((ch = getopt(argc, argv, "lX")) != -1) {
10484 switch (ch) {
10485 case 'l':
10486 list_refs = 1;
10487 break;
10488 case 'X':
10489 remove_refs = 1;
10490 break;
10491 default:
10492 usage_backout();
10493 /* NOTREACHED */
10497 argc -= optind;
10498 argv += optind;
10500 if (list_refs || remove_refs) {
10501 if (argc != 0 && argc != 1)
10502 usage_backout();
10503 } else if (argc != 1)
10504 usage_backout();
10505 if (list_refs && remove_refs)
10506 option_conflict('l', 'X');
10508 cwd = getcwd(NULL, 0);
10509 if (cwd == NULL) {
10510 error = got_error_from_errno("getcwd");
10511 goto done;
10514 error = got_repo_pack_fds_open(&pack_fds);
10515 if (error != NULL)
10516 goto done;
10518 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10519 if (error) {
10520 if (list_refs || remove_refs) {
10521 if (error->code != GOT_ERR_NOT_WORKTREE)
10522 goto done;
10523 } else {
10524 if (error->code == GOT_ERR_NOT_WORKTREE)
10525 error = wrap_not_worktree_error(error,
10526 "backout", cwd);
10527 goto done;
10531 error = got_repo_open(&repo,
10532 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10533 NULL, pack_fds);
10534 if (error != NULL)
10535 goto done;
10537 error = apply_unveil(got_repo_get_path(repo), 0,
10538 worktree ? got_worktree_get_root_path(worktree) : NULL);
10539 if (error)
10540 goto done;
10542 if (list_refs || remove_refs) {
10543 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10544 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10545 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10546 goto done;
10549 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10550 if (error != NULL)
10551 goto done;
10553 error = got_repo_match_object_id(&commit_id, NULL,
10554 keyword_idstr != NULL ? keyword_idstr : argv[0],
10555 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10556 if (error)
10557 goto done;
10558 error = got_object_id_str(&commit_id_str, commit_id);
10559 if (error)
10560 goto done;
10562 error = got_object_open_as_commit(&commit, repo, commit_id);
10563 if (error)
10564 goto done;
10565 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10566 if (pid == NULL) {
10567 error = got_error(GOT_ERR_ROOT_COMMIT);
10568 goto done;
10571 memset(&upa, 0, sizeof(upa));
10572 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10573 repo, update_progress, &upa, check_cancelled, NULL);
10574 if (error != NULL)
10575 goto done;
10577 if (upa.did_something) {
10578 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10579 worktree, repo);
10580 if (error)
10581 goto done;
10582 printf("Backed out commit %s\n", commit_id_str);
10584 print_merge_progress_stats(&upa);
10585 done:
10586 free(cwd);
10587 free(keyword_idstr);
10588 if (commit)
10589 got_object_commit_close(commit);
10590 free(commit_id_str);
10591 if (worktree)
10592 got_worktree_close(worktree);
10593 if (repo) {
10594 const struct got_error *close_err = got_repo_close(repo);
10595 if (error == NULL)
10596 error = close_err;
10598 if (pack_fds) {
10599 const struct got_error *pack_err =
10600 got_repo_pack_fds_close(pack_fds);
10601 if (error == NULL)
10602 error = pack_err;
10604 return error;
10607 __dead static void
10608 usage_rebase(void)
10610 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10611 exit(1);
10614 static void
10615 trim_logmsg(char *logmsg, int limit)
10617 char *nl;
10618 size_t len;
10620 len = strlen(logmsg);
10621 if (len > limit)
10622 len = limit;
10623 logmsg[len] = '\0';
10624 nl = strchr(logmsg, '\n');
10625 if (nl)
10626 *nl = '\0';
10629 static const struct got_error *
10630 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10632 const struct got_error *err;
10633 char *logmsg0 = NULL;
10634 const char *s;
10636 err = got_object_commit_get_logmsg(&logmsg0, commit);
10637 if (err)
10638 return err;
10640 s = logmsg0;
10641 while (isspace((unsigned char)s[0]))
10642 s++;
10644 *logmsg = strdup(s);
10645 if (*logmsg == NULL) {
10646 err = got_error_from_errno("strdup");
10647 goto done;
10650 trim_logmsg(*logmsg, limit);
10651 done:
10652 free(logmsg0);
10653 return err;
10656 static const struct got_error *
10657 show_rebase_merge_conflict(struct got_object_id *id,
10658 struct got_repository *repo)
10660 const struct got_error *err;
10661 struct got_commit_object *commit = NULL;
10662 char *id_str = NULL, *logmsg = NULL;
10664 err = got_object_open_as_commit(&commit, repo, id);
10665 if (err)
10666 return err;
10668 err = got_object_id_str(&id_str, id);
10669 if (err)
10670 goto done;
10672 id_str[12] = '\0';
10674 err = get_short_logmsg(&logmsg, 42, commit);
10675 if (err)
10676 goto done;
10678 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10679 done:
10680 free(id_str);
10681 got_object_commit_close(commit);
10682 free(logmsg);
10683 return err;
10686 static const struct got_error *
10687 show_rebase_progress(struct got_commit_object *commit,
10688 struct got_object_id *old_id, struct got_object_id *new_id)
10690 const struct got_error *err;
10691 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10693 err = got_object_id_str(&old_id_str, old_id);
10694 if (err)
10695 goto done;
10697 if (new_id) {
10698 err = got_object_id_str(&new_id_str, new_id);
10699 if (err)
10700 goto done;
10703 old_id_str[12] = '\0';
10704 if (new_id_str)
10705 new_id_str[12] = '\0';
10707 err = get_short_logmsg(&logmsg, 42, commit);
10708 if (err)
10709 goto done;
10711 printf("%s -> %s: %s\n", old_id_str,
10712 new_id_str ? new_id_str : "no-op change", logmsg);
10713 done:
10714 free(old_id_str);
10715 free(new_id_str);
10716 free(logmsg);
10717 return err;
10720 static const struct got_error *
10721 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10722 struct got_reference *branch, struct got_reference *tmp_branch,
10723 struct got_repository *repo, int create_backup)
10725 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10726 return got_worktree_rebase_complete(worktree, fileindex,
10727 tmp_branch, branch, repo, create_backup);
10730 static const struct got_error *
10731 rebase_commit(struct got_pathlist_head *merged_paths,
10732 struct got_worktree *worktree, struct got_fileindex *fileindex,
10733 struct got_reference *tmp_branch, const char *committer,
10734 struct got_object_id *commit_id, int allow_conflict,
10735 struct got_repository *repo)
10737 const struct got_error *error;
10738 struct got_commit_object *commit;
10739 struct got_object_id *new_commit_id;
10741 error = got_object_open_as_commit(&commit, repo, commit_id);
10742 if (error)
10743 return error;
10745 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10746 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10747 allow_conflict, repo);
10748 if (error) {
10749 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10750 goto done;
10751 error = show_rebase_progress(commit, commit_id, NULL);
10752 } else {
10753 error = show_rebase_progress(commit, commit_id, new_commit_id);
10754 free(new_commit_id);
10756 done:
10757 got_object_commit_close(commit);
10758 return error;
10761 struct check_path_prefix_arg {
10762 const char *path_prefix;
10763 size_t len;
10764 int errcode;
10767 static const struct got_error *
10768 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10769 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10770 struct got_object_id *id1, struct got_object_id *id2,
10771 const char *path1, const char *path2,
10772 mode_t mode1, mode_t mode2, struct got_repository *repo)
10774 struct check_path_prefix_arg *a = arg;
10776 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10777 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10778 return got_error(a->errcode);
10780 return NULL;
10783 static const struct got_error *
10784 check_path_prefix(struct got_object_id *parent_id,
10785 struct got_object_id *commit_id, const char *path_prefix,
10786 int errcode, struct got_repository *repo)
10788 const struct got_error *err;
10789 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10790 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10791 struct check_path_prefix_arg cpp_arg;
10793 if (got_path_is_root_dir(path_prefix))
10794 return NULL;
10796 err = got_object_open_as_commit(&commit, repo, commit_id);
10797 if (err)
10798 goto done;
10800 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10801 if (err)
10802 goto done;
10804 err = got_object_open_as_tree(&tree1, repo,
10805 got_object_commit_get_tree_id(parent_commit));
10806 if (err)
10807 goto done;
10809 err = got_object_open_as_tree(&tree2, repo,
10810 got_object_commit_get_tree_id(commit));
10811 if (err)
10812 goto done;
10814 cpp_arg.path_prefix = path_prefix;
10815 while (cpp_arg.path_prefix[0] == '/')
10816 cpp_arg.path_prefix++;
10817 cpp_arg.len = strlen(cpp_arg.path_prefix);
10818 cpp_arg.errcode = errcode;
10819 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10820 check_path_prefix_in_diff, &cpp_arg, 0);
10821 done:
10822 if (tree1)
10823 got_object_tree_close(tree1);
10824 if (tree2)
10825 got_object_tree_close(tree2);
10826 if (commit)
10827 got_object_commit_close(commit);
10828 if (parent_commit)
10829 got_object_commit_close(parent_commit);
10830 return err;
10833 static const struct got_error *
10834 collect_commits(struct got_object_id_queue *commits,
10835 struct got_object_id *initial_commit_id,
10836 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10837 const char *path_prefix, int path_prefix_errcode,
10838 struct got_repository *repo)
10840 const struct got_error *err = NULL;
10841 struct got_commit_graph *graph = NULL;
10842 struct got_object_id parent_id, commit_id;
10843 struct got_object_qid *qid;
10845 err = got_commit_graph_open(&graph, "/", 1);
10846 if (err)
10847 return err;
10849 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10850 check_cancelled, NULL);
10851 if (err)
10852 goto done;
10854 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10855 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10856 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10857 check_cancelled, NULL);
10858 if (err) {
10859 if (err->code == GOT_ERR_ITER_COMPLETED) {
10860 err = got_error_msg(GOT_ERR_ANCESTRY,
10861 "ran out of commits to rebase before "
10862 "youngest common ancestor commit has "
10863 "been reached?!?");
10865 goto done;
10866 } else {
10867 err = check_path_prefix(&parent_id, &commit_id,
10868 path_prefix, path_prefix_errcode, repo);
10869 if (err)
10870 goto done;
10872 err = got_object_qid_alloc(&qid, &commit_id);
10873 if (err)
10874 goto done;
10875 STAILQ_INSERT_HEAD(commits, qid, entry);
10877 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10880 done:
10881 got_commit_graph_close(graph);
10882 return err;
10885 static const struct got_error *
10886 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10888 const struct got_error *err = NULL;
10889 time_t committer_time;
10890 struct tm tm;
10891 char datebuf[11]; /* YYYY-MM-DD + NUL */
10892 char *author0 = NULL, *author, *smallerthan;
10893 char *logmsg0 = NULL, *logmsg, *newline;
10895 committer_time = got_object_commit_get_committer_time(commit);
10896 if (gmtime_r(&committer_time, &tm) == NULL)
10897 return got_error_from_errno("gmtime_r");
10898 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10899 return got_error(GOT_ERR_NO_SPACE);
10901 author0 = strdup(got_object_commit_get_author(commit));
10902 if (author0 == NULL)
10903 return got_error_from_errno("strdup");
10904 author = author0;
10905 smallerthan = strchr(author, '<');
10906 if (smallerthan && smallerthan[1] != '\0')
10907 author = smallerthan + 1;
10908 author[strcspn(author, "@>")] = '\0';
10910 err = got_object_commit_get_logmsg(&logmsg0, commit);
10911 if (err)
10912 goto done;
10913 logmsg = logmsg0;
10914 while (*logmsg == '\n')
10915 logmsg++;
10916 newline = strchr(logmsg, '\n');
10917 if (newline)
10918 *newline = '\0';
10920 if (asprintf(brief_str, "%s %s %s",
10921 datebuf, author, logmsg) == -1)
10922 err = got_error_from_errno("asprintf");
10923 done:
10924 free(author0);
10925 free(logmsg0);
10926 return err;
10929 static const struct got_error *
10930 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10931 struct got_repository *repo)
10933 const struct got_error *err;
10934 char *id_str;
10936 err = got_object_id_str(&id_str, id);
10937 if (err)
10938 return err;
10940 err = got_ref_delete(ref, repo);
10941 if (err)
10942 goto done;
10944 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10945 done:
10946 free(id_str);
10947 return err;
10950 static const struct got_error *
10951 print_backup_ref(const char *branch_name, const char *new_id_str,
10952 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10953 struct got_reflist_object_id_map *refs_idmap,
10954 struct got_repository *repo)
10956 const struct got_error *err = NULL;
10957 struct got_reflist_head *refs;
10958 char *refs_str = NULL;
10959 struct got_object_id *new_commit_id = NULL;
10960 struct got_commit_object *new_commit = NULL;
10961 char *new_commit_brief_str = NULL;
10962 struct got_object_id *yca_id = NULL;
10963 struct got_commit_object *yca_commit = NULL;
10964 char *yca_id_str = NULL, *yca_brief_str = NULL;
10965 char *custom_refs_str;
10967 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10968 return got_error_from_errno("asprintf");
10970 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10971 0, 0, refs_idmap, custom_refs_str, NULL);
10972 if (err)
10973 goto done;
10975 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10976 if (err)
10977 goto done;
10979 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10980 if (refs) {
10981 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10982 if (err)
10983 goto done;
10986 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10987 if (err)
10988 goto done;
10990 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10991 if (err)
10992 goto done;
10994 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10995 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10996 if (err)
10997 goto done;
10999 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11000 refs_str ? " (" : "", refs_str ? refs_str : "",
11001 refs_str ? ")" : "", new_commit_brief_str);
11002 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11003 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11004 free(refs_str);
11005 refs_str = NULL;
11007 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11008 if (err)
11009 goto done;
11011 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11012 if (err)
11013 goto done;
11015 err = got_object_id_str(&yca_id_str, yca_id);
11016 if (err)
11017 goto done;
11019 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11020 if (refs) {
11021 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11022 if (err)
11023 goto done;
11025 printf("history forked at %s%s%s%s\n %s\n",
11026 yca_id_str,
11027 refs_str ? " (" : "", refs_str ? refs_str : "",
11028 refs_str ? ")" : "", yca_brief_str);
11030 done:
11031 free(custom_refs_str);
11032 free(new_commit_id);
11033 free(refs_str);
11034 free(yca_id);
11035 free(yca_id_str);
11036 free(yca_brief_str);
11037 if (new_commit)
11038 got_object_commit_close(new_commit);
11039 if (yca_commit)
11040 got_object_commit_close(yca_commit);
11042 return err;
11045 static const struct got_error *
11046 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11047 struct got_repository *repo)
11049 const struct got_error *err;
11050 struct got_reflist_head refs;
11051 struct got_reflist_entry *re;
11052 char *uuidstr = NULL;
11053 static char msg[160];
11055 TAILQ_INIT(&refs);
11057 err = got_worktree_get_uuid(&uuidstr, worktree);
11058 if (err)
11059 goto done;
11061 err = got_ref_list(&refs, repo, "refs/got/worktree",
11062 got_ref_cmp_by_name, repo);
11063 if (err)
11064 goto done;
11066 TAILQ_FOREACH(re, &refs, entry) {
11067 const char *cmd, *refname, *type;
11069 refname = got_ref_get_name(re->ref);
11071 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11072 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11073 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11074 cmd = "cherrypick";
11075 type = "cherrypicked";
11076 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11077 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11078 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11079 cmd = "backout";
11080 type = "backed-out";
11081 } else
11082 continue;
11084 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11085 continue;
11087 snprintf(msg, sizeof(msg),
11088 "work tree has references created by %s commits which "
11089 "must be removed with 'got %s -X' before running the %s "
11090 "command", type, cmd, caller);
11091 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11092 goto done;
11095 done:
11096 free(uuidstr);
11097 got_ref_list_free(&refs);
11098 return err;
11101 static const struct got_error *
11102 process_backup_refs(const char *backup_ref_prefix,
11103 const char *wanted_branch_name,
11104 int delete, struct got_repository *repo)
11106 const struct got_error *err;
11107 struct got_reflist_head refs, backup_refs;
11108 struct got_reflist_entry *re;
11109 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11110 struct got_object_id *old_commit_id = NULL;
11111 char *branch_name = NULL;
11112 struct got_commit_object *old_commit = NULL;
11113 struct got_reflist_object_id_map *refs_idmap = NULL;
11114 int wanted_branch_found = 0;
11116 TAILQ_INIT(&refs);
11117 TAILQ_INIT(&backup_refs);
11119 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11120 if (err)
11121 return err;
11123 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11124 if (err)
11125 goto done;
11127 if (wanted_branch_name) {
11128 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11129 wanted_branch_name += 11;
11132 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11133 got_ref_cmp_by_commit_timestamp_descending, repo);
11134 if (err)
11135 goto done;
11137 TAILQ_FOREACH(re, &backup_refs, entry) {
11138 const char *refname = got_ref_get_name(re->ref);
11139 char *slash;
11141 err = check_cancelled(NULL);
11142 if (err)
11143 break;
11145 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11146 if (err)
11147 break;
11149 err = got_object_open_as_commit(&old_commit, repo,
11150 old_commit_id);
11151 if (err)
11152 break;
11154 if (strncmp(backup_ref_prefix, refname,
11155 backup_ref_prefix_len) == 0)
11156 refname += backup_ref_prefix_len;
11158 while (refname[0] == '/')
11159 refname++;
11161 branch_name = strdup(refname);
11162 if (branch_name == NULL) {
11163 err = got_error_from_errno("strdup");
11164 break;
11166 slash = strrchr(branch_name, '/');
11167 if (slash) {
11168 *slash = '\0';
11169 refname += strlen(branch_name) + 1;
11172 if (wanted_branch_name == NULL ||
11173 strcmp(wanted_branch_name, branch_name) == 0) {
11174 wanted_branch_found = 1;
11175 if (delete) {
11176 err = delete_backup_ref(re->ref,
11177 old_commit_id, repo);
11178 } else {
11179 err = print_backup_ref(branch_name, refname,
11180 old_commit_id, old_commit, refs_idmap,
11181 repo);
11183 if (err)
11184 break;
11187 free(old_commit_id);
11188 old_commit_id = NULL;
11189 free(branch_name);
11190 branch_name = NULL;
11191 got_object_commit_close(old_commit);
11192 old_commit = NULL;
11195 if (wanted_branch_name && !wanted_branch_found) {
11196 err = got_error_fmt(GOT_ERR_NOT_REF,
11197 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11199 done:
11200 if (refs_idmap)
11201 got_reflist_object_id_map_free(refs_idmap);
11202 got_ref_list_free(&refs);
11203 got_ref_list_free(&backup_refs);
11204 free(old_commit_id);
11205 free(branch_name);
11206 if (old_commit)
11207 got_object_commit_close(old_commit);
11208 return err;
11211 static const struct got_error *
11212 abort_progress(void *arg, unsigned char status, const char *path)
11215 * Unversioned files should not clutter progress output when
11216 * an operation is aborted.
11218 if (status == GOT_STATUS_UNVERSIONED)
11219 return NULL;
11221 return update_progress(arg, status, path);
11224 static const struct got_error *
11225 cmd_rebase(int argc, char *argv[])
11227 const struct got_error *error = NULL;
11228 struct got_worktree *worktree = NULL;
11229 struct got_repository *repo = NULL;
11230 struct got_fileindex *fileindex = NULL;
11231 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11232 struct got_reference *branch = NULL;
11233 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11234 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11235 struct got_object_id *resume_commit_id = NULL;
11236 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11237 struct got_object_id *head_commit_id = NULL;
11238 struct got_reference *head_ref = NULL;
11239 struct got_commit_object *commit = NULL;
11240 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11241 int histedit_in_progress = 0, merge_in_progress = 0;
11242 int create_backup = 1, list_backups = 0, delete_backups = 0;
11243 int allow_conflict = 0;
11244 struct got_object_id_queue commits;
11245 struct got_pathlist_head merged_paths;
11246 const struct got_object_id_queue *parent_ids;
11247 struct got_object_qid *qid, *pid;
11248 struct got_update_progress_arg upa;
11249 int *pack_fds = NULL;
11251 STAILQ_INIT(&commits);
11252 TAILQ_INIT(&merged_paths);
11253 memset(&upa, 0, sizeof(upa));
11255 #ifndef PROFILE
11256 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11257 "unveil", NULL) == -1)
11258 err(1, "pledge");
11259 #endif
11261 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11262 switch (ch) {
11263 case 'a':
11264 abort_rebase = 1;
11265 break;
11266 case 'C':
11267 allow_conflict = 1;
11268 break;
11269 case 'c':
11270 continue_rebase = 1;
11271 break;
11272 case 'l':
11273 list_backups = 1;
11274 break;
11275 case 'X':
11276 delete_backups = 1;
11277 break;
11278 default:
11279 usage_rebase();
11280 /* NOTREACHED */
11284 argc -= optind;
11285 argv += optind;
11287 if (list_backups) {
11288 if (abort_rebase)
11289 option_conflict('l', 'a');
11290 if (allow_conflict)
11291 option_conflict('l', 'C');
11292 if (continue_rebase)
11293 option_conflict('l', 'c');
11294 if (delete_backups)
11295 option_conflict('l', 'X');
11296 if (argc != 0 && argc != 1)
11297 usage_rebase();
11298 } else if (delete_backups) {
11299 if (abort_rebase)
11300 option_conflict('X', 'a');
11301 if (allow_conflict)
11302 option_conflict('X', 'C');
11303 if (continue_rebase)
11304 option_conflict('X', 'c');
11305 if (list_backups)
11306 option_conflict('l', 'X');
11307 if (argc != 0 && argc != 1)
11308 usage_rebase();
11309 } else if (allow_conflict) {
11310 if (abort_rebase)
11311 option_conflict('C', 'a');
11312 if (!continue_rebase)
11313 errx(1, "-C option requires -c");
11314 } else {
11315 if (abort_rebase && continue_rebase)
11316 usage_rebase();
11317 else if (abort_rebase || continue_rebase) {
11318 if (argc != 0)
11319 usage_rebase();
11320 } else if (argc != 1)
11321 usage_rebase();
11324 cwd = getcwd(NULL, 0);
11325 if (cwd == NULL) {
11326 error = got_error_from_errno("getcwd");
11327 goto done;
11330 error = got_repo_pack_fds_open(&pack_fds);
11331 if (error != NULL)
11332 goto done;
11334 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11335 if (error) {
11336 if (list_backups || delete_backups) {
11337 if (error->code != GOT_ERR_NOT_WORKTREE)
11338 goto done;
11339 } else {
11340 if (error->code == GOT_ERR_NOT_WORKTREE)
11341 error = wrap_not_worktree_error(error,
11342 "rebase", cwd);
11343 goto done;
11347 error = get_gitconfig_path(&gitconfig_path);
11348 if (error)
11349 goto done;
11350 error = got_repo_open(&repo,
11351 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11352 gitconfig_path, pack_fds);
11353 if (error != NULL)
11354 goto done;
11356 if (worktree != NULL && !list_backups && !delete_backups) {
11357 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11358 if (error)
11359 goto done;
11362 error = get_author(&committer, repo, worktree);
11363 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11364 goto done;
11366 error = apply_unveil(got_repo_get_path(repo), 0,
11367 worktree ? got_worktree_get_root_path(worktree) : NULL);
11368 if (error)
11369 goto done;
11371 if (list_backups || delete_backups) {
11372 error = process_backup_refs(
11373 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11374 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11375 goto done; /* nothing else to do */
11378 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11379 worktree);
11380 if (error)
11381 goto done;
11382 if (histedit_in_progress) {
11383 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11384 goto done;
11387 error = got_worktree_merge_in_progress(&merge_in_progress,
11388 worktree, repo);
11389 if (error)
11390 goto done;
11391 if (merge_in_progress) {
11392 error = got_error(GOT_ERR_MERGE_BUSY);
11393 goto done;
11396 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11397 if (error)
11398 goto done;
11400 if (abort_rebase) {
11401 if (!rebase_in_progress) {
11402 error = got_error(GOT_ERR_NOT_REBASING);
11403 goto done;
11405 error = got_worktree_rebase_continue(&resume_commit_id,
11406 &new_base_branch, &tmp_branch, &branch, &fileindex,
11407 worktree, repo);
11408 if (error)
11409 goto done;
11410 printf("Switching work tree to %s\n",
11411 got_ref_get_symref_target(new_base_branch));
11412 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11413 new_base_branch, abort_progress, &upa);
11414 if (error)
11415 goto done;
11416 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11417 print_merge_progress_stats(&upa);
11418 goto done; /* nothing else to do */
11421 if (continue_rebase) {
11422 if (!rebase_in_progress) {
11423 error = got_error(GOT_ERR_NOT_REBASING);
11424 goto done;
11426 error = got_worktree_rebase_continue(&resume_commit_id,
11427 &new_base_branch, &tmp_branch, &branch, &fileindex,
11428 worktree, repo);
11429 if (error)
11430 goto done;
11432 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11433 committer, resume_commit_id, allow_conflict, repo);
11434 if (error)
11435 goto done;
11437 yca_id = got_object_id_dup(resume_commit_id);
11438 if (yca_id == NULL) {
11439 error = got_error_from_errno("got_object_id_dup");
11440 goto done;
11442 } else {
11443 error = got_ref_open(&branch, repo, argv[0], 0);
11444 if (error != NULL)
11445 goto done;
11446 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11447 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11448 "will not rebase a branch which lives outside "
11449 "the \"refs/heads/\" reference namespace");
11450 goto done;
11454 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11455 if (error)
11456 goto done;
11458 if (!continue_rebase) {
11459 struct got_object_id *base_commit_id;
11461 error = got_ref_open(&head_ref, repo,
11462 got_worktree_get_head_ref_name(worktree), 0);
11463 if (error)
11464 goto done;
11465 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11466 if (error)
11467 goto done;
11468 base_commit_id = got_worktree_get_base_commit_id(worktree);
11469 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11470 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11471 goto done;
11474 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11475 base_commit_id, branch_head_commit_id, 1, repo,
11476 check_cancelled, NULL);
11477 if (error) {
11478 if (error->code == GOT_ERR_ANCESTRY) {
11479 error = got_error_msg(GOT_ERR_ANCESTRY,
11480 "specified branch shares no common "
11481 "ancestry with work tree's branch");
11483 goto done;
11486 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11487 struct got_pathlist_head paths;
11488 printf("%s is already based on %s\n",
11489 got_ref_get_name(branch),
11490 got_worktree_get_head_ref_name(worktree));
11491 error = switch_head_ref(branch, branch_head_commit_id,
11492 worktree, repo);
11493 if (error)
11494 goto done;
11495 error = got_worktree_set_base_commit_id(worktree, repo,
11496 branch_head_commit_id);
11497 if (error)
11498 goto done;
11499 TAILQ_INIT(&paths);
11500 error = got_pathlist_append(&paths, "", NULL);
11501 if (error)
11502 goto done;
11503 error = got_worktree_checkout_files(worktree,
11504 &paths, repo, update_progress, &upa,
11505 check_cancelled, NULL);
11506 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11507 if (error)
11508 goto done;
11509 if (upa.did_something) {
11510 char *id_str;
11511 error = got_object_id_str(&id_str,
11512 branch_head_commit_id);
11513 if (error)
11514 goto done;
11515 printf("Updated to %s: %s\n",
11516 got_worktree_get_head_ref_name(worktree),
11517 id_str);
11518 free(id_str);
11519 } else
11520 printf("Already up-to-date\n");
11521 print_update_progress_stats(&upa);
11522 goto done;
11526 commit_id = branch_head_commit_id;
11527 error = got_object_open_as_commit(&commit, repo, commit_id);
11528 if (error)
11529 goto done;
11531 parent_ids = got_object_commit_get_parent_ids(commit);
11532 pid = STAILQ_FIRST(parent_ids);
11533 if (pid) {
11534 error = collect_commits(&commits, commit_id, &pid->id,
11535 yca_id, got_worktree_get_path_prefix(worktree),
11536 GOT_ERR_REBASE_PATH, repo);
11537 if (error)
11538 goto done;
11541 got_object_commit_close(commit);
11542 commit = NULL;
11544 if (!continue_rebase) {
11545 error = got_worktree_rebase_prepare(&new_base_branch,
11546 &tmp_branch, &fileindex, worktree, branch, repo);
11547 if (error)
11548 goto done;
11551 if (STAILQ_EMPTY(&commits)) {
11552 if (continue_rebase) {
11553 error = rebase_complete(worktree, fileindex,
11554 branch, tmp_branch, repo, create_backup);
11555 goto done;
11556 } else {
11557 /* Fast-forward the reference of the branch. */
11558 struct got_object_id *new_head_commit_id;
11559 char *id_str;
11560 error = got_ref_resolve(&new_head_commit_id, repo,
11561 new_base_branch);
11562 if (error)
11563 goto done;
11564 error = got_object_id_str(&id_str, new_head_commit_id);
11565 if (error)
11566 goto done;
11567 printf("Forwarding %s to commit %s\n",
11568 got_ref_get_name(branch), id_str);
11569 free(id_str);
11570 error = got_ref_change_ref(branch,
11571 new_head_commit_id);
11572 if (error)
11573 goto done;
11574 /* No backup needed since objects did not change. */
11575 create_backup = 0;
11579 pid = NULL;
11580 STAILQ_FOREACH(qid, &commits, entry) {
11582 commit_id = &qid->id;
11583 parent_id = pid ? &pid->id : yca_id;
11584 pid = qid;
11586 memset(&upa, 0, sizeof(upa));
11587 error = got_worktree_rebase_merge_files(&merged_paths,
11588 worktree, fileindex, parent_id, commit_id, repo,
11589 update_progress, &upa, check_cancelled, NULL);
11590 if (error)
11591 goto done;
11593 print_merge_progress_stats(&upa);
11594 if (upa.conflicts > 0 || upa.missing > 0 ||
11595 upa.not_deleted > 0 || upa.unversioned > 0) {
11596 if (upa.conflicts > 0) {
11597 error = show_rebase_merge_conflict(&qid->id,
11598 repo);
11599 if (error)
11600 goto done;
11602 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11603 break;
11606 error = rebase_commit(&merged_paths, worktree, fileindex,
11607 tmp_branch, committer, commit_id, 0, repo);
11608 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11609 if (error)
11610 goto done;
11613 if (upa.conflicts > 0 || upa.missing > 0 ||
11614 upa.not_deleted > 0 || upa.unversioned > 0) {
11615 error = got_worktree_rebase_postpone(worktree, fileindex);
11616 if (error)
11617 goto done;
11618 if (upa.conflicts > 0 && upa.missing == 0 &&
11619 upa.not_deleted == 0 && upa.unversioned == 0) {
11620 error = got_error_msg(GOT_ERR_CONFLICTS,
11621 "conflicts must be resolved before rebasing "
11622 "can continue");
11623 } else if (upa.conflicts > 0) {
11624 error = got_error_msg(GOT_ERR_CONFLICTS,
11625 "conflicts must be resolved before rebasing "
11626 "can continue; changes destined for some "
11627 "files were not yet merged and should be "
11628 "merged manually if required before the "
11629 "rebase operation is continued");
11630 } else {
11631 error = got_error_msg(GOT_ERR_CONFLICTS,
11632 "changes destined for some files were not "
11633 "yet merged and should be merged manually "
11634 "if required before the rebase operation "
11635 "is continued");
11637 } else
11638 error = rebase_complete(worktree, fileindex, branch,
11639 tmp_branch, repo, create_backup);
11640 done:
11641 free(cwd);
11642 free(committer);
11643 free(gitconfig_path);
11644 got_object_id_queue_free(&commits);
11645 free(branch_head_commit_id);
11646 free(resume_commit_id);
11647 free(head_commit_id);
11648 free(yca_id);
11649 if (commit)
11650 got_object_commit_close(commit);
11651 if (branch)
11652 got_ref_close(branch);
11653 if (new_base_branch)
11654 got_ref_close(new_base_branch);
11655 if (tmp_branch)
11656 got_ref_close(tmp_branch);
11657 if (head_ref)
11658 got_ref_close(head_ref);
11659 if (worktree)
11660 got_worktree_close(worktree);
11661 if (repo) {
11662 const struct got_error *close_err = got_repo_close(repo);
11663 if (error == NULL)
11664 error = close_err;
11666 if (pack_fds) {
11667 const struct got_error *pack_err =
11668 got_repo_pack_fds_close(pack_fds);
11669 if (error == NULL)
11670 error = pack_err;
11672 return error;
11675 __dead static void
11676 usage_histedit(void)
11678 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11679 "[branch]\n", getprogname());
11680 exit(1);
11683 #define GOT_HISTEDIT_PICK 'p'
11684 #define GOT_HISTEDIT_EDIT 'e'
11685 #define GOT_HISTEDIT_FOLD 'f'
11686 #define GOT_HISTEDIT_DROP 'd'
11687 #define GOT_HISTEDIT_MESG 'm'
11689 static const struct got_histedit_cmd {
11690 unsigned char code;
11691 const char *name;
11692 const char *desc;
11693 } got_histedit_cmds[] = {
11694 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11695 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11696 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11697 "be used" },
11698 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11699 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11702 struct got_histedit_list_entry {
11703 TAILQ_ENTRY(got_histedit_list_entry) entry;
11704 struct got_object_id *commit_id;
11705 const struct got_histedit_cmd *cmd;
11706 char *logmsg;
11708 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11710 static const struct got_error *
11711 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11712 FILE *f, struct got_repository *repo)
11714 const struct got_error *err = NULL;
11715 char *logmsg = NULL, *id_str = NULL;
11716 struct got_commit_object *commit = NULL;
11717 int n;
11719 err = got_object_open_as_commit(&commit, repo, commit_id);
11720 if (err)
11721 goto done;
11723 err = get_short_logmsg(&logmsg, 34, commit);
11724 if (err)
11725 goto done;
11727 err = got_object_id_str(&id_str, commit_id);
11728 if (err)
11729 goto done;
11731 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11732 if (n < 0)
11733 err = got_ferror(f, GOT_ERR_IO);
11734 done:
11735 if (commit)
11736 got_object_commit_close(commit);
11737 free(id_str);
11738 free(logmsg);
11739 return err;
11742 static const struct got_error *
11743 histedit_write_commit_list(struct got_object_id_queue *commits,
11744 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11745 int edit_only, struct got_repository *repo)
11747 const struct got_error *err = NULL;
11748 struct got_object_qid *qid;
11749 const char *histedit_cmd = NULL;
11751 if (STAILQ_EMPTY(commits))
11752 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11754 STAILQ_FOREACH(qid, commits, entry) {
11755 histedit_cmd = got_histedit_cmds[0].name;
11756 if (drop_only)
11757 histedit_cmd = "drop";
11758 else if (edit_only)
11759 histedit_cmd = "edit";
11760 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11761 histedit_cmd = "fold";
11762 else if (edit_logmsg_only)
11763 histedit_cmd = "mesg";
11764 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11765 if (err)
11766 break;
11769 return err;
11772 static const struct got_error *
11773 write_cmd_list(FILE *f, const char *branch_name,
11774 struct got_object_id_queue *commits)
11776 const struct got_error *err = NULL;
11777 size_t i;
11778 int n;
11779 char *id_str;
11780 struct got_object_qid *qid;
11782 qid = STAILQ_FIRST(commits);
11783 err = got_object_id_str(&id_str, &qid->id);
11784 if (err)
11785 return err;
11787 n = fprintf(f,
11788 "# Editing the history of branch '%s' starting at\n"
11789 "# commit %s\n"
11790 "# Commits will be processed in order from top to "
11791 "bottom of this file.\n", branch_name, id_str);
11792 if (n < 0) {
11793 err = got_ferror(f, GOT_ERR_IO);
11794 goto done;
11797 n = fprintf(f, "# Available histedit commands:\n");
11798 if (n < 0) {
11799 err = got_ferror(f, GOT_ERR_IO);
11800 goto done;
11803 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11804 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11805 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11806 cmd->desc);
11807 if (n < 0) {
11808 err = got_ferror(f, GOT_ERR_IO);
11809 break;
11812 done:
11813 free(id_str);
11814 return err;
11817 static const struct got_error *
11818 histedit_syntax_error(int lineno)
11820 static char msg[42];
11821 int ret;
11823 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11824 lineno);
11825 if (ret < 0 || (size_t)ret >= sizeof(msg))
11826 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11828 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11831 static const struct got_error *
11832 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11833 char *logmsg, struct got_repository *repo)
11835 const struct got_error *err;
11836 struct got_commit_object *folded_commit = NULL;
11837 char *id_str, *folded_logmsg = NULL;
11839 err = got_object_id_str(&id_str, hle->commit_id);
11840 if (err)
11841 return err;
11843 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11844 if (err)
11845 goto done;
11847 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11848 if (err)
11849 goto done;
11850 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11851 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11852 folded_logmsg) == -1) {
11853 err = got_error_from_errno("asprintf");
11855 done:
11856 if (folded_commit)
11857 got_object_commit_close(folded_commit);
11858 free(id_str);
11859 free(folded_logmsg);
11860 return err;
11863 static struct got_histedit_list_entry *
11864 get_folded_commits(struct got_histedit_list_entry *hle)
11866 struct got_histedit_list_entry *prev, *folded = NULL;
11868 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11869 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11870 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11871 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11872 folded = prev;
11873 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11876 return folded;
11879 static const struct got_error *
11880 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11881 struct got_repository *repo)
11883 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11884 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11885 const struct got_error *err = NULL;
11886 struct got_commit_object *commit = NULL;
11887 int logmsg_len;
11888 int fd = -1;
11889 struct got_histedit_list_entry *folded = NULL;
11891 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11892 if (err)
11893 return err;
11895 folded = get_folded_commits(hle);
11896 if (folded) {
11897 while (folded != hle) {
11898 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11899 folded = TAILQ_NEXT(folded, entry);
11900 continue;
11902 err = append_folded_commit_msg(&new_msg, folded,
11903 logmsg, repo);
11904 if (err)
11905 goto done;
11906 free(logmsg);
11907 logmsg = new_msg;
11908 folded = TAILQ_NEXT(folded, entry);
11912 err = got_object_id_str(&id_str, hle->commit_id);
11913 if (err)
11914 goto done;
11915 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11916 if (err)
11917 goto done;
11918 logmsg_len = asprintf(&new_msg,
11919 "%s\n# original log message of commit %s: %s",
11920 logmsg ? logmsg : "", id_str, orig_logmsg);
11921 if (logmsg_len == -1) {
11922 err = got_error_from_errno("asprintf");
11923 goto done;
11925 free(logmsg);
11926 logmsg = new_msg;
11928 err = got_object_id_str(&id_str, hle->commit_id);
11929 if (err)
11930 goto done;
11932 err = got_opentemp_named_fd(&logmsg_path, &fd,
11933 GOT_TMPDIR_STR "/got-logmsg", "");
11934 if (err)
11935 goto done;
11937 if (write(fd, logmsg, logmsg_len) == -1) {
11938 err = got_error_from_errno2("write", logmsg_path);
11939 goto done;
11941 if (close(fd) == -1) {
11942 err = got_error_from_errno2("close", logmsg_path);
11943 goto done;
11945 fd = -1;
11947 err = get_editor(&editor);
11948 if (err)
11949 goto done;
11951 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11952 logmsg_len, 0);
11953 if (err) {
11954 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11955 goto done;
11956 err = NULL;
11957 hle->logmsg = strdup(new_msg);
11958 if (hle->logmsg == NULL)
11959 err = got_error_from_errno("strdup");
11961 done:
11962 if (fd != -1 && close(fd) == -1 && err == NULL)
11963 err = got_error_from_errno2("close", logmsg_path);
11964 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11965 err = got_error_from_errno2("unlink", logmsg_path);
11966 free(logmsg_path);
11967 free(logmsg);
11968 free(orig_logmsg);
11969 free(editor);
11970 if (commit)
11971 got_object_commit_close(commit);
11972 return err;
11975 static const struct got_error *
11976 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11977 FILE *f, struct got_repository *repo)
11979 const struct got_error *err = NULL;
11980 char *line = NULL, *p, *end;
11981 size_t i, linesize = 0;
11982 ssize_t linelen;
11983 int lineno = 0;
11984 const struct got_histedit_cmd *cmd;
11985 struct got_object_id *commit_id = NULL;
11986 struct got_histedit_list_entry *hle = NULL;
11988 for (;;) {
11989 linelen = getline(&line, &linesize, f);
11990 if (linelen == -1) {
11991 const struct got_error *getline_err;
11992 if (feof(f))
11993 break;
11994 getline_err = got_error_from_errno("getline");
11995 err = got_ferror(f, getline_err->code);
11996 break;
11998 lineno++;
11999 p = line;
12000 while (isspace((unsigned char)p[0]))
12001 p++;
12002 if (p[0] == '#' || p[0] == '\0')
12003 continue;
12004 cmd = NULL;
12005 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12006 cmd = &got_histedit_cmds[i];
12007 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12008 isspace((unsigned char)p[strlen(cmd->name)])) {
12009 p += strlen(cmd->name);
12010 break;
12012 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12013 p++;
12014 break;
12017 if (i == nitems(got_histedit_cmds)) {
12018 err = histedit_syntax_error(lineno);
12019 break;
12021 while (isspace((unsigned char)p[0]))
12022 p++;
12023 end = p;
12024 while (end[0] && !isspace((unsigned char)end[0]))
12025 end++;
12026 *end = '\0';
12027 err = got_object_resolve_id_str(&commit_id, repo, p);
12028 if (err) {
12029 /* override error code */
12030 err = histedit_syntax_error(lineno);
12031 break;
12033 hle = malloc(sizeof(*hle));
12034 if (hle == NULL) {
12035 err = got_error_from_errno("malloc");
12036 break;
12038 hle->cmd = cmd;
12039 hle->commit_id = commit_id;
12040 hle->logmsg = NULL;
12041 commit_id = NULL;
12042 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12045 free(line);
12046 free(commit_id);
12047 return err;
12050 static const struct got_error *
12051 histedit_check_script(struct got_histedit_list *histedit_cmds,
12052 struct got_object_id_queue *commits, struct got_repository *repo)
12054 const struct got_error *err = NULL;
12055 struct got_object_qid *qid;
12056 struct got_histedit_list_entry *hle;
12057 static char msg[92];
12058 char *id_str;
12060 if (TAILQ_EMPTY(histedit_cmds))
12061 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12062 "histedit script contains no commands");
12063 if (STAILQ_EMPTY(commits))
12064 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12066 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12067 struct got_histedit_list_entry *hle2;
12068 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12069 if (hle == hle2)
12070 continue;
12071 if (got_object_id_cmp(hle->commit_id,
12072 hle2->commit_id) != 0)
12073 continue;
12074 err = got_object_id_str(&id_str, hle->commit_id);
12075 if (err)
12076 return err;
12077 snprintf(msg, sizeof(msg), "commit %s is listed "
12078 "more than once in histedit script", id_str);
12079 free(id_str);
12080 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12084 STAILQ_FOREACH(qid, commits, entry) {
12085 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12086 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12087 break;
12089 if (hle == NULL) {
12090 err = got_object_id_str(&id_str, &qid->id);
12091 if (err)
12092 return err;
12093 snprintf(msg, sizeof(msg),
12094 "commit %s missing from histedit script", id_str);
12095 free(id_str);
12096 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12100 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12101 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12102 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12103 "last commit in histedit script cannot be folded");
12105 return NULL;
12108 static const struct got_error *
12109 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12110 const char *path, struct got_object_id_queue *commits,
12111 struct got_repository *repo)
12113 const struct got_error *err = NULL;
12114 struct stat st, st2;
12115 struct timespec timeout;
12116 char *editor;
12117 FILE *f = NULL;
12119 err = get_editor(&editor);
12120 if (err)
12121 return err;
12123 if (stat(path, &st) == -1) {
12124 err = got_error_from_errno2("stat", path);
12125 goto done;
12128 if (spawn_editor(editor, path) == -1) {
12129 err = got_error_from_errno("failed spawning editor");
12130 goto done;
12133 timeout.tv_sec = 0;
12134 timeout.tv_nsec = 1;
12135 nanosleep(&timeout, NULL);
12137 if (stat(path, &st2) == -1) {
12138 err = got_error_from_errno2("stat", path);
12139 goto done;
12142 if (st.st_size == st2.st_size &&
12143 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12144 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12145 "no changes made to histedit script, aborting");
12146 goto done;
12149 f = fopen(path, "re");
12150 if (f == NULL) {
12151 err = got_error_from_errno("fopen");
12152 goto done;
12154 err = histedit_parse_list(histedit_cmds, f, repo);
12155 if (err)
12156 goto done;
12158 err = histedit_check_script(histedit_cmds, commits, repo);
12159 done:
12160 if (f && fclose(f) == EOF && err == NULL)
12161 err = got_error_from_errno("fclose");
12162 free(editor);
12163 return err;
12166 static const struct got_error *
12167 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12168 struct got_object_id_queue *, const char *, const char *,
12169 struct got_repository *);
12171 static const struct got_error *
12172 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12173 struct got_object_id_queue *commits, const char *branch_name,
12174 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12175 struct got_repository *repo)
12177 const struct got_error *err;
12178 FILE *f = NULL;
12179 char *path = NULL;
12181 err = got_opentemp_named(&path, &f, "got-histedit", "");
12182 if (err)
12183 return err;
12185 err = write_cmd_list(f, branch_name, commits);
12186 if (err)
12187 goto done;
12189 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12190 fold_only, drop_only, edit_only, repo);
12191 if (err)
12192 goto done;
12194 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12195 rewind(f);
12196 err = histedit_parse_list(histedit_cmds, f, repo);
12197 } else {
12198 if (fclose(f) == EOF) {
12199 err = got_error_from_errno("fclose");
12200 goto done;
12202 f = NULL;
12203 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12204 if (err) {
12205 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12206 err->code != GOT_ERR_HISTEDIT_CMD)
12207 goto done;
12208 err = histedit_edit_list_retry(histedit_cmds, err,
12209 commits, path, branch_name, repo);
12212 done:
12213 if (f && fclose(f) == EOF && err == NULL)
12214 err = got_error_from_errno("fclose");
12215 if (path && unlink(path) != 0 && err == NULL)
12216 err = got_error_from_errno2("unlink", path);
12217 free(path);
12218 return err;
12221 static const struct got_error *
12222 histedit_save_list(struct got_histedit_list *histedit_cmds,
12223 struct got_worktree *worktree, struct got_repository *repo)
12225 const struct got_error *err = NULL;
12226 char *path = NULL;
12227 FILE *f = NULL;
12228 struct got_histedit_list_entry *hle;
12230 err = got_worktree_get_histedit_script_path(&path, worktree);
12231 if (err)
12232 return err;
12234 f = fopen(path, "we");
12235 if (f == NULL) {
12236 err = got_error_from_errno2("fopen", path);
12237 goto done;
12239 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12240 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12241 repo);
12242 if (err)
12243 break;
12245 done:
12246 if (f && fclose(f) == EOF && err == NULL)
12247 err = got_error_from_errno("fclose");
12248 free(path);
12249 return err;
12252 static void
12253 histedit_free_list(struct got_histedit_list *histedit_cmds)
12255 struct got_histedit_list_entry *hle;
12257 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12258 TAILQ_REMOVE(histedit_cmds, hle, entry);
12259 free(hle);
12263 static const struct got_error *
12264 histedit_load_list(struct got_histedit_list *histedit_cmds,
12265 const char *path, struct got_repository *repo)
12267 const struct got_error *err = NULL;
12268 FILE *f = NULL;
12270 f = fopen(path, "re");
12271 if (f == NULL) {
12272 err = got_error_from_errno2("fopen", path);
12273 goto done;
12276 err = histedit_parse_list(histedit_cmds, f, repo);
12277 done:
12278 if (f && fclose(f) == EOF && err == NULL)
12279 err = got_error_from_errno("fclose");
12280 return err;
12283 static const struct got_error *
12284 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12285 const struct got_error *edit_err, struct got_object_id_queue *commits,
12286 const char *path, const char *branch_name, struct got_repository *repo)
12288 const struct got_error *err = NULL, *prev_err = edit_err;
12289 int resp = ' ';
12291 while (resp != 'c' && resp != 'r' && resp != 'a') {
12292 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12293 "or (a)bort: ", getprogname(), prev_err->msg);
12294 resp = getchar();
12295 if (resp == '\n')
12296 resp = getchar();
12297 if (resp == 'c') {
12298 histedit_free_list(histedit_cmds);
12299 err = histedit_run_editor(histedit_cmds, path, commits,
12300 repo);
12301 if (err) {
12302 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12303 err->code != GOT_ERR_HISTEDIT_CMD)
12304 break;
12305 prev_err = err;
12306 resp = ' ';
12307 continue;
12309 break;
12310 } else if (resp == 'r') {
12311 histedit_free_list(histedit_cmds);
12312 err = histedit_edit_script(histedit_cmds,
12313 commits, branch_name, 0, 0, 0, 0, repo);
12314 if (err) {
12315 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12316 err->code != GOT_ERR_HISTEDIT_CMD)
12317 break;
12318 prev_err = err;
12319 resp = ' ';
12320 continue;
12322 break;
12323 } else if (resp == 'a') {
12324 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12325 break;
12326 } else
12327 printf("invalid response '%c'\n", resp);
12330 return err;
12333 static const struct got_error *
12334 histedit_complete(struct got_worktree *worktree,
12335 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12336 struct got_reference *branch, struct got_repository *repo)
12338 printf("Switching work tree to %s\n",
12339 got_ref_get_symref_target(branch));
12340 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12341 branch, repo);
12344 static const struct got_error *
12345 show_histedit_progress(struct got_commit_object *commit,
12346 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12348 const struct got_error *err;
12349 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12351 err = got_object_id_str(&old_id_str, hle->commit_id);
12352 if (err)
12353 goto done;
12355 if (new_id) {
12356 err = got_object_id_str(&new_id_str, new_id);
12357 if (err)
12358 goto done;
12361 old_id_str[12] = '\0';
12362 if (new_id_str)
12363 new_id_str[12] = '\0';
12365 if (hle->logmsg) {
12366 logmsg = strdup(hle->logmsg);
12367 if (logmsg == NULL) {
12368 err = got_error_from_errno("strdup");
12369 goto done;
12371 trim_logmsg(logmsg, 42);
12372 } else {
12373 err = get_short_logmsg(&logmsg, 42, commit);
12374 if (err)
12375 goto done;
12378 switch (hle->cmd->code) {
12379 case GOT_HISTEDIT_PICK:
12380 case GOT_HISTEDIT_EDIT:
12381 case GOT_HISTEDIT_MESG:
12382 printf("%s -> %s: %s\n", old_id_str,
12383 new_id_str ? new_id_str : "no-op change", logmsg);
12384 break;
12385 case GOT_HISTEDIT_DROP:
12386 case GOT_HISTEDIT_FOLD:
12387 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12388 logmsg);
12389 break;
12390 default:
12391 break;
12393 done:
12394 free(old_id_str);
12395 free(new_id_str);
12396 return err;
12399 static const struct got_error *
12400 histedit_commit(struct got_pathlist_head *merged_paths,
12401 struct got_worktree *worktree, struct got_fileindex *fileindex,
12402 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12403 const char *committer, int allow_conflict, struct got_repository *repo)
12405 const struct got_error *err;
12406 struct got_commit_object *commit;
12407 struct got_object_id *new_commit_id;
12409 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12410 && hle->logmsg == NULL) {
12411 err = histedit_edit_logmsg(hle, repo);
12412 if (err)
12413 return err;
12416 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12417 if (err)
12418 return err;
12420 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12421 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12422 hle->logmsg, allow_conflict, repo);
12423 if (err) {
12424 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12425 goto done;
12426 err = show_histedit_progress(commit, hle, NULL);
12427 } else {
12428 err = show_histedit_progress(commit, hle, new_commit_id);
12429 free(new_commit_id);
12431 done:
12432 got_object_commit_close(commit);
12433 return err;
12436 static const struct got_error *
12437 histedit_skip_commit(struct got_histedit_list_entry *hle,
12438 struct got_worktree *worktree, struct got_repository *repo)
12440 const struct got_error *error;
12441 struct got_commit_object *commit;
12443 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12444 repo);
12445 if (error)
12446 return error;
12448 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12449 if (error)
12450 return error;
12452 error = show_histedit_progress(commit, hle, NULL);
12453 got_object_commit_close(commit);
12454 return error;
12457 static const struct got_error *
12458 check_local_changes(void *arg, unsigned char status,
12459 unsigned char staged_status, const char *path,
12460 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12461 struct got_object_id *commit_id, int dirfd, const char *de_name)
12463 int *have_local_changes = arg;
12465 switch (status) {
12466 case GOT_STATUS_ADD:
12467 case GOT_STATUS_DELETE:
12468 case GOT_STATUS_MODIFY:
12469 case GOT_STATUS_CONFLICT:
12470 *have_local_changes = 1;
12471 return got_error(GOT_ERR_CANCELLED);
12472 default:
12473 break;
12476 switch (staged_status) {
12477 case GOT_STATUS_ADD:
12478 case GOT_STATUS_DELETE:
12479 case GOT_STATUS_MODIFY:
12480 *have_local_changes = 1;
12481 return got_error(GOT_ERR_CANCELLED);
12482 default:
12483 break;
12486 return NULL;
12489 static const struct got_error *
12490 cmd_histedit(int argc, char *argv[])
12492 const struct got_error *error = NULL;
12493 struct got_worktree *worktree = NULL;
12494 struct got_fileindex *fileindex = NULL;
12495 struct got_repository *repo = NULL;
12496 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12497 struct got_reference *branch = NULL;
12498 struct got_reference *tmp_branch = NULL;
12499 struct got_object_id *resume_commit_id = NULL;
12500 struct got_object_id *base_commit_id = NULL;
12501 struct got_object_id *head_commit_id = NULL;
12502 struct got_commit_object *commit = NULL;
12503 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12504 struct got_update_progress_arg upa;
12505 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12506 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12507 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12508 const char *edit_script_path = NULL;
12509 struct got_object_id_queue commits;
12510 struct got_pathlist_head merged_paths;
12511 const struct got_object_id_queue *parent_ids;
12512 struct got_object_qid *pid;
12513 struct got_histedit_list histedit_cmds;
12514 struct got_histedit_list_entry *hle;
12515 int *pack_fds = NULL;
12517 STAILQ_INIT(&commits);
12518 TAILQ_INIT(&histedit_cmds);
12519 TAILQ_INIT(&merged_paths);
12520 memset(&upa, 0, sizeof(upa));
12522 #ifndef PROFILE
12523 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12524 "unveil", NULL) == -1)
12525 err(1, "pledge");
12526 #endif
12528 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12529 switch (ch) {
12530 case 'a':
12531 abort_edit = 1;
12532 break;
12533 case 'C':
12534 allow_conflict = 1;
12535 break;
12536 case 'c':
12537 continue_edit = 1;
12538 break;
12539 case 'd':
12540 drop_only = 1;
12541 break;
12542 case 'e':
12543 edit_only = 1;
12544 break;
12545 case 'F':
12546 edit_script_path = optarg;
12547 break;
12548 case 'f':
12549 fold_only = 1;
12550 break;
12551 case 'l':
12552 list_backups = 1;
12553 break;
12554 case 'm':
12555 edit_logmsg_only = 1;
12556 break;
12557 case 'X':
12558 delete_backups = 1;
12559 break;
12560 default:
12561 usage_histedit();
12562 /* NOTREACHED */
12566 argc -= optind;
12567 argv += optind;
12569 if (abort_edit && allow_conflict)
12570 option_conflict('a', 'C');
12571 if (abort_edit && continue_edit)
12572 option_conflict('a', 'c');
12573 if (edit_script_path && allow_conflict)
12574 option_conflict('F', 'C');
12575 if (edit_script_path && edit_logmsg_only)
12576 option_conflict('F', 'm');
12577 if (abort_edit && edit_logmsg_only)
12578 option_conflict('a', 'm');
12579 if (edit_logmsg_only && allow_conflict)
12580 option_conflict('m', 'C');
12581 if (continue_edit && edit_logmsg_only)
12582 option_conflict('c', 'm');
12583 if (abort_edit && fold_only)
12584 option_conflict('a', 'f');
12585 if (fold_only && allow_conflict)
12586 option_conflict('f', 'C');
12587 if (continue_edit && fold_only)
12588 option_conflict('c', 'f');
12589 if (fold_only && edit_logmsg_only)
12590 option_conflict('f', 'm');
12591 if (edit_script_path && fold_only)
12592 option_conflict('F', 'f');
12593 if (abort_edit && edit_only)
12594 option_conflict('a', 'e');
12595 if (continue_edit && edit_only)
12596 option_conflict('c', 'e');
12597 if (edit_only && edit_logmsg_only)
12598 option_conflict('e', 'm');
12599 if (edit_script_path && edit_only)
12600 option_conflict('F', 'e');
12601 if (fold_only && edit_only)
12602 option_conflict('f', 'e');
12603 if (drop_only && abort_edit)
12604 option_conflict('d', 'a');
12605 if (drop_only && allow_conflict)
12606 option_conflict('d', 'C');
12607 if (drop_only && continue_edit)
12608 option_conflict('d', 'c');
12609 if (drop_only && edit_logmsg_only)
12610 option_conflict('d', 'm');
12611 if (drop_only && edit_only)
12612 option_conflict('d', 'e');
12613 if (drop_only && edit_script_path)
12614 option_conflict('d', 'F');
12615 if (drop_only && fold_only)
12616 option_conflict('d', 'f');
12617 if (list_backups) {
12618 if (abort_edit)
12619 option_conflict('l', 'a');
12620 if (allow_conflict)
12621 option_conflict('l', 'C');
12622 if (continue_edit)
12623 option_conflict('l', 'c');
12624 if (edit_script_path)
12625 option_conflict('l', 'F');
12626 if (edit_logmsg_only)
12627 option_conflict('l', 'm');
12628 if (drop_only)
12629 option_conflict('l', 'd');
12630 if (fold_only)
12631 option_conflict('l', 'f');
12632 if (edit_only)
12633 option_conflict('l', 'e');
12634 if (delete_backups)
12635 option_conflict('l', 'X');
12636 if (argc != 0 && argc != 1)
12637 usage_histedit();
12638 } else if (delete_backups) {
12639 if (abort_edit)
12640 option_conflict('X', 'a');
12641 if (allow_conflict)
12642 option_conflict('X', 'C');
12643 if (continue_edit)
12644 option_conflict('X', 'c');
12645 if (drop_only)
12646 option_conflict('X', 'd');
12647 if (edit_script_path)
12648 option_conflict('X', 'F');
12649 if (edit_logmsg_only)
12650 option_conflict('X', 'm');
12651 if (fold_only)
12652 option_conflict('X', 'f');
12653 if (edit_only)
12654 option_conflict('X', 'e');
12655 if (list_backups)
12656 option_conflict('X', 'l');
12657 if (argc != 0 && argc != 1)
12658 usage_histedit();
12659 } else if (allow_conflict && !continue_edit)
12660 errx(1, "-C option requires -c");
12661 else if (argc != 0)
12662 usage_histedit();
12665 * This command cannot apply unveil(2) in all cases because the
12666 * user may choose to run an editor to edit the histedit script
12667 * and to edit individual commit log messages.
12668 * unveil(2) traverses exec(2); if an editor is used we have to
12669 * apply unveil after edit script and log messages have been written.
12670 * XXX TODO: Make use of unveil(2) where possible.
12673 cwd = getcwd(NULL, 0);
12674 if (cwd == NULL) {
12675 error = got_error_from_errno("getcwd");
12676 goto done;
12679 error = got_repo_pack_fds_open(&pack_fds);
12680 if (error != NULL)
12681 goto done;
12683 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12684 if (error) {
12685 if (list_backups || delete_backups) {
12686 if (error->code != GOT_ERR_NOT_WORKTREE)
12687 goto done;
12688 } else {
12689 if (error->code == GOT_ERR_NOT_WORKTREE)
12690 error = wrap_not_worktree_error(error,
12691 "histedit", cwd);
12692 goto done;
12696 if (list_backups || delete_backups) {
12697 error = got_repo_open(&repo,
12698 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12699 NULL, pack_fds);
12700 if (error != NULL)
12701 goto done;
12702 error = apply_unveil(got_repo_get_path(repo), 0,
12703 worktree ? got_worktree_get_root_path(worktree) : NULL);
12704 if (error)
12705 goto done;
12706 error = process_backup_refs(
12707 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12708 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12709 goto done; /* nothing else to do */
12712 error = get_gitconfig_path(&gitconfig_path);
12713 if (error)
12714 goto done;
12715 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12716 gitconfig_path, pack_fds);
12717 if (error != NULL)
12718 goto done;
12720 if (worktree != NULL && !list_backups && !delete_backups) {
12721 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12722 if (error)
12723 goto done;
12726 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12727 if (error)
12728 goto done;
12729 if (rebase_in_progress) {
12730 error = got_error(GOT_ERR_REBASING);
12731 goto done;
12734 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12735 repo);
12736 if (error)
12737 goto done;
12738 if (merge_in_progress) {
12739 error = got_error(GOT_ERR_MERGE_BUSY);
12740 goto done;
12743 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12744 if (error)
12745 goto done;
12747 if (edit_in_progress && edit_logmsg_only) {
12748 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12749 "histedit operation is in progress in this "
12750 "work tree and must be continued or aborted "
12751 "before the -m option can be used");
12752 goto done;
12754 if (edit_in_progress && drop_only) {
12755 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12756 "histedit operation is in progress in this "
12757 "work tree and must be continued or aborted "
12758 "before the -d option can be used");
12759 goto done;
12761 if (edit_in_progress && fold_only) {
12762 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12763 "histedit operation is in progress in this "
12764 "work tree and must be continued or aborted "
12765 "before the -f option can be used");
12766 goto done;
12768 if (edit_in_progress && edit_only) {
12769 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12770 "histedit operation is in progress in this "
12771 "work tree and must be continued or aborted "
12772 "before the -e option can be used");
12773 goto done;
12776 if (edit_in_progress && abort_edit) {
12777 error = got_worktree_histedit_continue(&resume_commit_id,
12778 &tmp_branch, &branch, &base_commit_id, &fileindex,
12779 worktree, repo);
12780 if (error)
12781 goto done;
12782 printf("Switching work tree to %s\n",
12783 got_ref_get_symref_target(branch));
12784 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12785 branch, base_commit_id, abort_progress, &upa);
12786 if (error)
12787 goto done;
12788 printf("Histedit of %s aborted\n",
12789 got_ref_get_symref_target(branch));
12790 print_merge_progress_stats(&upa);
12791 goto done; /* nothing else to do */
12792 } else if (abort_edit) {
12793 error = got_error(GOT_ERR_NOT_HISTEDIT);
12794 goto done;
12797 error = get_author(&committer, repo, worktree);
12798 if (error)
12799 goto done;
12801 if (continue_edit) {
12802 char *path;
12804 if (!edit_in_progress) {
12805 error = got_error(GOT_ERR_NOT_HISTEDIT);
12806 goto done;
12809 error = got_worktree_get_histedit_script_path(&path, worktree);
12810 if (error)
12811 goto done;
12813 error = histedit_load_list(&histedit_cmds, path, repo);
12814 free(path);
12815 if (error)
12816 goto done;
12818 error = got_worktree_histedit_continue(&resume_commit_id,
12819 &tmp_branch, &branch, &base_commit_id, &fileindex,
12820 worktree, repo);
12821 if (error)
12822 goto done;
12824 error = got_ref_resolve(&head_commit_id, repo, branch);
12825 if (error)
12826 goto done;
12828 error = got_object_open_as_commit(&commit, repo,
12829 head_commit_id);
12830 if (error)
12831 goto done;
12832 parent_ids = got_object_commit_get_parent_ids(commit);
12833 pid = STAILQ_FIRST(parent_ids);
12834 if (pid == NULL) {
12835 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12836 goto done;
12838 error = collect_commits(&commits, head_commit_id, &pid->id,
12839 base_commit_id, got_worktree_get_path_prefix(worktree),
12840 GOT_ERR_HISTEDIT_PATH, repo);
12841 got_object_commit_close(commit);
12842 commit = NULL;
12843 if (error)
12844 goto done;
12845 } else {
12846 if (edit_in_progress) {
12847 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12848 goto done;
12851 error = got_ref_open(&branch, repo,
12852 got_worktree_get_head_ref_name(worktree), 0);
12853 if (error != NULL)
12854 goto done;
12856 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12857 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12858 "will not edit commit history of a branch outside "
12859 "the \"refs/heads/\" reference namespace");
12860 goto done;
12863 error = got_ref_resolve(&head_commit_id, repo, branch);
12864 got_ref_close(branch);
12865 branch = NULL;
12866 if (error)
12867 goto done;
12869 error = got_object_open_as_commit(&commit, repo,
12870 head_commit_id);
12871 if (error)
12872 goto done;
12873 parent_ids = got_object_commit_get_parent_ids(commit);
12874 pid = STAILQ_FIRST(parent_ids);
12875 if (pid == NULL) {
12876 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12877 goto done;
12879 error = collect_commits(&commits, head_commit_id, &pid->id,
12880 got_worktree_get_base_commit_id(worktree),
12881 got_worktree_get_path_prefix(worktree),
12882 GOT_ERR_HISTEDIT_PATH, repo);
12883 got_object_commit_close(commit);
12884 commit = NULL;
12885 if (error)
12886 goto done;
12888 if (STAILQ_EMPTY(&commits)) {
12889 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12890 goto done;
12893 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12894 &base_commit_id, &fileindex, worktree, repo);
12895 if (error)
12896 goto done;
12898 if (edit_script_path) {
12899 error = histedit_load_list(&histedit_cmds,
12900 edit_script_path, repo);
12901 if (error) {
12902 got_worktree_histedit_abort(worktree, fileindex,
12903 repo, branch, base_commit_id,
12904 abort_progress, &upa);
12905 print_merge_progress_stats(&upa);
12906 goto done;
12908 } else {
12909 const char *branch_name;
12910 branch_name = got_ref_get_symref_target(branch);
12911 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12912 branch_name += 11;
12913 error = histedit_edit_script(&histedit_cmds, &commits,
12914 branch_name, edit_logmsg_only, fold_only,
12915 drop_only, edit_only, repo);
12916 if (error) {
12917 got_worktree_histedit_abort(worktree, fileindex,
12918 repo, branch, base_commit_id,
12919 abort_progress, &upa);
12920 print_merge_progress_stats(&upa);
12921 goto done;
12926 error = histedit_save_list(&histedit_cmds, worktree,
12927 repo);
12928 if (error) {
12929 got_worktree_histedit_abort(worktree, fileindex,
12930 repo, branch, base_commit_id,
12931 abort_progress, &upa);
12932 print_merge_progress_stats(&upa);
12933 goto done;
12938 error = histedit_check_script(&histedit_cmds, &commits, repo);
12939 if (error)
12940 goto done;
12942 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12943 if (resume_commit_id) {
12944 if (got_object_id_cmp(hle->commit_id,
12945 resume_commit_id) != 0)
12946 continue;
12948 resume_commit_id = NULL;
12949 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12950 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12951 error = histedit_skip_commit(hle, worktree,
12952 repo);
12953 if (error)
12954 goto done;
12955 } else {
12956 struct got_pathlist_head paths;
12957 int have_changes = 0;
12959 TAILQ_INIT(&paths);
12960 error = got_pathlist_append(&paths, "", NULL);
12961 if (error)
12962 goto done;
12963 error = got_worktree_status(worktree, &paths,
12964 repo, 0, check_local_changes, &have_changes,
12965 check_cancelled, NULL);
12966 got_pathlist_free(&paths,
12967 GOT_PATHLIST_FREE_NONE);
12968 if (error) {
12969 if (error->code != GOT_ERR_CANCELLED)
12970 goto done;
12971 if (sigint_received || sigpipe_received)
12972 goto done;
12974 if (have_changes) {
12975 error = histedit_commit(NULL, worktree,
12976 fileindex, tmp_branch, hle,
12977 committer, allow_conflict, repo);
12978 if (error)
12979 goto done;
12980 } else {
12981 error = got_object_open_as_commit(
12982 &commit, repo, hle->commit_id);
12983 if (error)
12984 goto done;
12985 error = show_histedit_progress(commit,
12986 hle, NULL);
12987 got_object_commit_close(commit);
12988 commit = NULL;
12989 if (error)
12990 goto done;
12993 continue;
12996 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12997 error = histedit_skip_commit(hle, worktree, repo);
12998 if (error)
12999 goto done;
13000 continue;
13002 error = got_object_open_as_commit(&commit, repo,
13003 hle->commit_id);
13004 if (error)
13005 goto done;
13006 parent_ids = got_object_commit_get_parent_ids(commit);
13007 pid = STAILQ_FIRST(parent_ids);
13009 error = got_worktree_histedit_merge_files(&merged_paths,
13010 worktree, fileindex, &pid->id, hle->commit_id, repo,
13011 update_progress, &upa, check_cancelled, NULL);
13012 if (error)
13013 goto done;
13014 got_object_commit_close(commit);
13015 commit = NULL;
13017 print_merge_progress_stats(&upa);
13018 if (upa.conflicts > 0 || upa.missing > 0 ||
13019 upa.not_deleted > 0 || upa.unversioned > 0) {
13020 if (upa.conflicts > 0) {
13021 error = show_rebase_merge_conflict(
13022 hle->commit_id, repo);
13023 if (error)
13024 goto done;
13026 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13027 break;
13030 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13031 char *id_str;
13032 error = got_object_id_str(&id_str, hle->commit_id);
13033 if (error)
13034 goto done;
13035 printf("Stopping histedit for amending commit %s\n",
13036 id_str);
13037 free(id_str);
13038 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13039 error = got_worktree_histedit_postpone(worktree,
13040 fileindex);
13041 goto done;
13042 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13043 error = histedit_skip_commit(hle, worktree, repo);
13044 if (error)
13045 goto done;
13046 continue;
13047 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13048 error = histedit_edit_logmsg(hle, repo);
13049 if (error)
13050 goto done;
13053 error = histedit_commit(&merged_paths, worktree, fileindex,
13054 tmp_branch, hle, committer, allow_conflict, repo);
13055 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13056 if (error)
13057 goto done;
13060 if (upa.conflicts > 0 || upa.missing > 0 ||
13061 upa.not_deleted > 0 || upa.unversioned > 0) {
13062 error = got_worktree_histedit_postpone(worktree, fileindex);
13063 if (error)
13064 goto done;
13065 if (upa.conflicts > 0 && upa.missing == 0 &&
13066 upa.not_deleted == 0 && upa.unversioned == 0) {
13067 error = got_error_msg(GOT_ERR_CONFLICTS,
13068 "conflicts must be resolved before histedit "
13069 "can continue");
13070 } else if (upa.conflicts > 0) {
13071 error = got_error_msg(GOT_ERR_CONFLICTS,
13072 "conflicts must be resolved before histedit "
13073 "can continue; changes destined for some "
13074 "files were not yet merged and should be "
13075 "merged manually if required before the "
13076 "histedit operation is continued");
13077 } else {
13078 error = got_error_msg(GOT_ERR_CONFLICTS,
13079 "changes destined for some files were not "
13080 "yet merged and should be merged manually "
13081 "if required before the histedit operation "
13082 "is continued");
13084 } else
13085 error = histedit_complete(worktree, fileindex, tmp_branch,
13086 branch, repo);
13087 done:
13088 free(cwd);
13089 free(committer);
13090 free(gitconfig_path);
13091 got_object_id_queue_free(&commits);
13092 histedit_free_list(&histedit_cmds);
13093 free(head_commit_id);
13094 free(base_commit_id);
13095 free(resume_commit_id);
13096 if (commit)
13097 got_object_commit_close(commit);
13098 if (branch)
13099 got_ref_close(branch);
13100 if (tmp_branch)
13101 got_ref_close(tmp_branch);
13102 if (worktree)
13103 got_worktree_close(worktree);
13104 if (repo) {
13105 const struct got_error *close_err = got_repo_close(repo);
13106 if (error == NULL)
13107 error = close_err;
13109 if (pack_fds) {
13110 const struct got_error *pack_err =
13111 got_repo_pack_fds_close(pack_fds);
13112 if (error == NULL)
13113 error = pack_err;
13115 return error;
13118 __dead static void
13119 usage_integrate(void)
13121 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13122 exit(1);
13125 static const struct got_error *
13126 cmd_integrate(int argc, char *argv[])
13128 const struct got_error *error = NULL;
13129 struct got_repository *repo = NULL;
13130 struct got_worktree *worktree = NULL;
13131 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13132 const char *branch_arg = NULL;
13133 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13134 struct got_fileindex *fileindex = NULL;
13135 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13136 int ch;
13137 struct got_update_progress_arg upa;
13138 int *pack_fds = NULL;
13140 #ifndef PROFILE
13141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13142 "unveil", NULL) == -1)
13143 err(1, "pledge");
13144 #endif
13146 while ((ch = getopt(argc, argv, "")) != -1) {
13147 switch (ch) {
13148 default:
13149 usage_integrate();
13150 /* NOTREACHED */
13154 argc -= optind;
13155 argv += optind;
13157 if (argc != 1)
13158 usage_integrate();
13159 branch_arg = argv[0];
13161 cwd = getcwd(NULL, 0);
13162 if (cwd == NULL) {
13163 error = got_error_from_errno("getcwd");
13164 goto done;
13167 error = got_repo_pack_fds_open(&pack_fds);
13168 if (error != NULL)
13169 goto done;
13171 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13172 if (error) {
13173 if (error->code == GOT_ERR_NOT_WORKTREE)
13174 error = wrap_not_worktree_error(error, "integrate",
13175 cwd);
13176 goto done;
13179 error = check_rebase_or_histedit_in_progress(worktree);
13180 if (error)
13181 goto done;
13183 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13184 NULL, pack_fds);
13185 if (error != NULL)
13186 goto done;
13188 error = apply_unveil(got_repo_get_path(repo), 0,
13189 got_worktree_get_root_path(worktree));
13190 if (error)
13191 goto done;
13193 error = check_merge_in_progress(worktree, repo);
13194 if (error)
13195 goto done;
13197 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13198 error = got_error_from_errno("asprintf");
13199 goto done;
13202 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13203 &base_branch_ref, worktree, refname, repo);
13204 if (error)
13205 goto done;
13207 refname = strdup(got_ref_get_name(branch_ref));
13208 if (refname == NULL) {
13209 error = got_error_from_errno("strdup");
13210 got_worktree_integrate_abort(worktree, fileindex, repo,
13211 branch_ref, base_branch_ref);
13212 goto done;
13214 base_refname = strdup(got_ref_get_name(base_branch_ref));
13215 if (base_refname == NULL) {
13216 error = got_error_from_errno("strdup");
13217 got_worktree_integrate_abort(worktree, fileindex, repo,
13218 branch_ref, base_branch_ref);
13219 goto done;
13221 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13222 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13223 got_worktree_integrate_abort(worktree, fileindex, repo,
13224 branch_ref, base_branch_ref);
13225 goto done;
13228 error = got_ref_resolve(&commit_id, repo, branch_ref);
13229 if (error)
13230 goto done;
13232 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13233 if (error)
13234 goto done;
13236 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13237 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13238 "specified branch has already been integrated");
13239 got_worktree_integrate_abort(worktree, fileindex, repo,
13240 branch_ref, base_branch_ref);
13241 goto done;
13244 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13245 if (error) {
13246 if (error->code == GOT_ERR_ANCESTRY)
13247 error = got_error(GOT_ERR_REBASE_REQUIRED);
13248 got_worktree_integrate_abort(worktree, fileindex, repo,
13249 branch_ref, base_branch_ref);
13250 goto done;
13253 memset(&upa, 0, sizeof(upa));
13254 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13255 branch_ref, base_branch_ref, update_progress, &upa,
13256 check_cancelled, NULL);
13257 if (error)
13258 goto done;
13260 printf("Integrated %s into %s\n", refname, base_refname);
13261 print_update_progress_stats(&upa);
13262 done:
13263 if (repo) {
13264 const struct got_error *close_err = got_repo_close(repo);
13265 if (error == NULL)
13266 error = close_err;
13268 if (worktree)
13269 got_worktree_close(worktree);
13270 if (pack_fds) {
13271 const struct got_error *pack_err =
13272 got_repo_pack_fds_close(pack_fds);
13273 if (error == NULL)
13274 error = pack_err;
13276 free(cwd);
13277 free(base_commit_id);
13278 free(commit_id);
13279 free(refname);
13280 free(base_refname);
13281 return error;
13284 __dead static void
13285 usage_merge(void)
13287 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13288 exit(1);
13291 static const struct got_error *
13292 cmd_merge(int argc, char *argv[])
13294 const struct got_error *error = NULL;
13295 struct got_worktree *worktree = NULL;
13296 struct got_repository *repo = NULL;
13297 struct got_fileindex *fileindex = NULL;
13298 char *cwd = NULL, *id_str = NULL, *author = NULL;
13299 char *gitconfig_path = NULL;
13300 struct got_reference *branch = NULL, *wt_branch = NULL;
13301 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13302 struct got_object_id *wt_branch_tip = NULL;
13303 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13304 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13305 struct got_update_progress_arg upa;
13306 struct got_object_id *merge_commit_id = NULL;
13307 char *branch_name = NULL;
13308 int *pack_fds = NULL;
13310 memset(&upa, 0, sizeof(upa));
13312 #ifndef PROFILE
13313 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13314 "unveil", NULL) == -1)
13315 err(1, "pledge");
13316 #endif
13318 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13319 switch (ch) {
13320 case 'a':
13321 abort_merge = 1;
13322 break;
13323 case 'C':
13324 allow_conflict = 1;
13325 break;
13326 case 'c':
13327 continue_merge = 1;
13328 break;
13329 case 'M':
13330 prefer_fast_forward = 0;
13331 break;
13332 case 'n':
13333 interrupt_merge = 1;
13334 break;
13335 default:
13336 usage_merge();
13337 /* NOTREACHED */
13341 argc -= optind;
13342 argv += optind;
13344 if (abort_merge) {
13345 if (continue_merge)
13346 option_conflict('a', 'c');
13347 if (!prefer_fast_forward)
13348 option_conflict('a', 'M');
13349 if (interrupt_merge)
13350 option_conflict('a', 'n');
13351 } else if (continue_merge) {
13352 if (!prefer_fast_forward)
13353 option_conflict('c', 'M');
13354 if (interrupt_merge)
13355 option_conflict('c', 'n');
13357 if (allow_conflict) {
13358 if (!continue_merge)
13359 errx(1, "-C option requires -c");
13361 if (abort_merge || continue_merge) {
13362 if (argc != 0)
13363 usage_merge();
13364 } else if (argc != 1)
13365 usage_merge();
13367 cwd = getcwd(NULL, 0);
13368 if (cwd == NULL) {
13369 error = got_error_from_errno("getcwd");
13370 goto done;
13373 error = got_repo_pack_fds_open(&pack_fds);
13374 if (error != NULL)
13375 goto done;
13377 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13378 if (error) {
13379 if (error->code == GOT_ERR_NOT_WORKTREE)
13380 error = wrap_not_worktree_error(error,
13381 "merge", cwd);
13382 goto done;
13385 error = get_gitconfig_path(&gitconfig_path);
13386 if (error)
13387 goto done;
13388 error = got_repo_open(&repo,
13389 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13390 gitconfig_path, pack_fds);
13391 if (error != NULL)
13392 goto done;
13394 if (worktree != NULL) {
13395 error = worktree_has_logmsg_ref("merge", worktree, repo);
13396 if (error)
13397 goto done;
13400 error = apply_unveil(got_repo_get_path(repo), 0,
13401 worktree ? got_worktree_get_root_path(worktree) : NULL);
13402 if (error)
13403 goto done;
13405 error = check_rebase_or_histedit_in_progress(worktree);
13406 if (error)
13407 goto done;
13409 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13410 repo);
13411 if (error)
13412 goto done;
13414 if (merge_in_progress && !(abort_merge || continue_merge)) {
13415 error = got_error(GOT_ERR_MERGE_BUSY);
13416 goto done;
13419 if (!merge_in_progress && (abort_merge || continue_merge)) {
13420 error = got_error(GOT_ERR_NOT_MERGING);
13421 goto done;
13424 if (abort_merge) {
13425 error = got_worktree_merge_continue(&branch_name,
13426 &branch_tip, &fileindex, worktree, repo);
13427 if (error)
13428 goto done;
13429 error = got_worktree_merge_abort(worktree, fileindex, repo,
13430 abort_progress, &upa);
13431 if (error)
13432 goto done;
13433 printf("Merge of %s aborted\n", branch_name);
13434 goto done; /* nothing else to do */
13437 if (strncmp(got_worktree_get_head_ref_name(worktree),
13438 "refs/heads/", 11) != 0) {
13439 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13440 "work tree's current branch %s is outside the "
13441 "\"refs/heads/\" reference namespace; "
13442 "update -b required",
13443 got_worktree_get_head_ref_name(worktree));
13444 goto done;
13447 error = get_author(&author, repo, worktree);
13448 if (error)
13449 goto done;
13451 error = got_ref_open(&wt_branch, repo,
13452 got_worktree_get_head_ref_name(worktree), 0);
13453 if (error)
13454 goto done;
13455 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13456 if (error)
13457 goto done;
13459 if (continue_merge) {
13460 struct got_object_id *base_commit_id;
13461 base_commit_id = got_worktree_get_base_commit_id(worktree);
13462 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13463 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13464 goto done;
13466 error = got_worktree_merge_continue(&branch_name,
13467 &branch_tip, &fileindex, worktree, repo);
13468 if (error)
13469 goto done;
13470 } else {
13471 error = got_ref_open(&branch, repo, argv[0], 0);
13472 if (error != NULL)
13473 goto done;
13474 branch_name = strdup(got_ref_get_name(branch));
13475 if (branch_name == NULL) {
13476 error = got_error_from_errno("strdup");
13477 goto done;
13479 error = got_ref_resolve(&branch_tip, repo, branch);
13480 if (error)
13481 goto done;
13484 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13485 wt_branch_tip, branch_tip, 0, repo,
13486 check_cancelled, NULL);
13487 if (error && error->code != GOT_ERR_ANCESTRY)
13488 goto done;
13490 if (!continue_merge) {
13491 error = check_path_prefix(wt_branch_tip, branch_tip,
13492 got_worktree_get_path_prefix(worktree),
13493 GOT_ERR_MERGE_PATH, repo);
13494 if (error)
13495 goto done;
13496 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13497 if (error)
13498 goto done;
13499 if (prefer_fast_forward && yca_id &&
13500 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13501 struct got_pathlist_head paths;
13502 if (interrupt_merge) {
13503 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13504 "there are no changes to merge since %s "
13505 "is already based on %s; merge cannot be "
13506 "interrupted for amending; -n",
13507 branch_name, got_ref_get_name(wt_branch));
13508 goto done;
13510 printf("Forwarding %s to %s\n",
13511 got_ref_get_name(wt_branch), branch_name);
13512 error = got_ref_change_ref(wt_branch, branch_tip);
13513 if (error)
13514 goto done;
13515 error = got_ref_write(wt_branch, repo);
13516 if (error)
13517 goto done;
13518 error = got_worktree_set_base_commit_id(worktree, repo,
13519 branch_tip);
13520 if (error)
13521 goto done;
13522 TAILQ_INIT(&paths);
13523 error = got_pathlist_append(&paths, "", NULL);
13524 if (error)
13525 goto done;
13526 error = got_worktree_checkout_files(worktree,
13527 &paths, repo, update_progress, &upa,
13528 check_cancelled, NULL);
13529 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13530 if (error)
13531 goto done;
13532 if (upa.did_something) {
13533 char *id_str;
13534 error = got_object_id_str(&id_str, branch_tip);
13535 if (error)
13536 goto done;
13537 printf("Updated to commit %s\n", id_str);
13538 free(id_str);
13539 } else
13540 printf("Already up-to-date\n");
13541 print_update_progress_stats(&upa);
13542 goto done;
13544 error = got_worktree_merge_write_refs(worktree, branch, repo);
13545 if (error)
13546 goto done;
13548 error = got_worktree_merge_branch(worktree, fileindex,
13549 yca_id, branch_tip, repo, update_progress, &upa,
13550 check_cancelled, NULL);
13551 if (error)
13552 goto done;
13553 print_merge_progress_stats(&upa);
13554 if (!upa.did_something) {
13555 error = got_worktree_merge_abort(worktree, fileindex,
13556 repo, abort_progress, &upa);
13557 if (error)
13558 goto done;
13559 printf("Already up-to-date\n");
13560 goto done;
13564 if (interrupt_merge) {
13565 error = got_worktree_merge_postpone(worktree, fileindex);
13566 if (error)
13567 goto done;
13568 printf("Merge of %s interrupted on request\n", branch_name);
13569 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13570 upa.not_deleted > 0 || upa.unversioned > 0) {
13571 error = got_worktree_merge_postpone(worktree, fileindex);
13572 if (error)
13573 goto done;
13574 if (upa.conflicts > 0 && upa.missing == 0 &&
13575 upa.not_deleted == 0 && upa.unversioned == 0) {
13576 error = got_error_msg(GOT_ERR_CONFLICTS,
13577 "conflicts must be resolved before merging "
13578 "can continue");
13579 } else if (upa.conflicts > 0) {
13580 error = got_error_msg(GOT_ERR_CONFLICTS,
13581 "conflicts must be resolved before merging "
13582 "can continue; changes destined for some "
13583 "files were not yet merged and "
13584 "should be merged manually if required before the "
13585 "merge operation is continued");
13586 } else {
13587 error = got_error_msg(GOT_ERR_CONFLICTS,
13588 "changes destined for some "
13589 "files were not yet merged and should be "
13590 "merged manually if required before the "
13591 "merge operation is continued");
13593 goto done;
13594 } else {
13595 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13596 fileindex, author, NULL, 1, branch_tip, branch_name,
13597 allow_conflict, repo, continue_merge ? print_status : NULL,
13598 NULL);
13599 if (error)
13600 goto done;
13601 error = got_worktree_merge_complete(worktree, fileindex, repo);
13602 if (error)
13603 goto done;
13604 error = got_object_id_str(&id_str, merge_commit_id);
13605 if (error)
13606 goto done;
13607 printf("Merged %s into %s: %s\n", branch_name,
13608 got_worktree_get_head_ref_name(worktree),
13609 id_str);
13612 done:
13613 free(gitconfig_path);
13614 free(id_str);
13615 free(merge_commit_id);
13616 free(author);
13617 free(branch_tip);
13618 free(branch_name);
13619 free(yca_id);
13620 if (branch)
13621 got_ref_close(branch);
13622 if (wt_branch)
13623 got_ref_close(wt_branch);
13624 if (worktree)
13625 got_worktree_close(worktree);
13626 if (repo) {
13627 const struct got_error *close_err = got_repo_close(repo);
13628 if (error == NULL)
13629 error = close_err;
13631 if (pack_fds) {
13632 const struct got_error *pack_err =
13633 got_repo_pack_fds_close(pack_fds);
13634 if (error == NULL)
13635 error = pack_err;
13637 return error;
13640 __dead static void
13641 usage_stage(void)
13643 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13644 "[path ...]\n", getprogname());
13645 exit(1);
13648 static const struct got_error *
13649 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13650 const char *path, struct got_object_id *blob_id,
13651 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13652 int dirfd, const char *de_name)
13654 const struct got_error *err = NULL;
13655 char *id_str = NULL;
13657 if (staged_status != GOT_STATUS_ADD &&
13658 staged_status != GOT_STATUS_MODIFY &&
13659 staged_status != GOT_STATUS_DELETE)
13660 return NULL;
13662 if (staged_status == GOT_STATUS_ADD ||
13663 staged_status == GOT_STATUS_MODIFY)
13664 err = got_object_id_str(&id_str, staged_blob_id);
13665 else
13666 err = got_object_id_str(&id_str, blob_id);
13667 if (err)
13668 return err;
13670 printf("%s %c %s\n", id_str, staged_status, path);
13671 free(id_str);
13672 return NULL;
13675 static const struct got_error *
13676 cmd_stage(int argc, char *argv[])
13678 const struct got_error *error = NULL;
13679 struct got_repository *repo = NULL;
13680 struct got_worktree *worktree = NULL;
13681 char *cwd = NULL;
13682 struct got_pathlist_head paths;
13683 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13684 FILE *patch_script_file = NULL;
13685 const char *patch_script_path = NULL;
13686 struct choose_patch_arg cpa;
13687 int *pack_fds = NULL;
13689 TAILQ_INIT(&paths);
13691 #ifndef PROFILE
13692 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13693 "unveil", NULL) == -1)
13694 err(1, "pledge");
13695 #endif
13697 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13698 switch (ch) {
13699 case 'F':
13700 patch_script_path = optarg;
13701 break;
13702 case 'l':
13703 list_stage = 1;
13704 break;
13705 case 'p':
13706 pflag = 1;
13707 break;
13708 case 'S':
13709 allow_bad_symlinks = 1;
13710 break;
13711 default:
13712 usage_stage();
13713 /* NOTREACHED */
13717 argc -= optind;
13718 argv += optind;
13720 if (list_stage && (pflag || patch_script_path))
13721 errx(1, "-l option cannot be used with other options");
13722 if (patch_script_path && !pflag)
13723 errx(1, "-F option can only be used together with -p option");
13725 cwd = getcwd(NULL, 0);
13726 if (cwd == NULL) {
13727 error = got_error_from_errno("getcwd");
13728 goto done;
13731 error = got_repo_pack_fds_open(&pack_fds);
13732 if (error != NULL)
13733 goto done;
13735 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13736 if (error) {
13737 if (error->code == GOT_ERR_NOT_WORKTREE)
13738 error = wrap_not_worktree_error(error, "stage", cwd);
13739 goto done;
13742 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13743 NULL, pack_fds);
13744 if (error != NULL)
13745 goto done;
13747 if (patch_script_path) {
13748 patch_script_file = fopen(patch_script_path, "re");
13749 if (patch_script_file == NULL) {
13750 error = got_error_from_errno2("fopen",
13751 patch_script_path);
13752 goto done;
13755 error = apply_unveil(got_repo_get_path(repo), 0,
13756 got_worktree_get_root_path(worktree));
13757 if (error)
13758 goto done;
13760 error = check_merge_in_progress(worktree, repo);
13761 if (error)
13762 goto done;
13764 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13765 if (error)
13766 goto done;
13768 if (list_stage)
13769 error = got_worktree_status(worktree, &paths, repo, 0,
13770 print_stage, NULL, check_cancelled, NULL);
13771 else {
13772 cpa.patch_script_file = patch_script_file;
13773 cpa.action = "stage";
13774 error = got_worktree_stage(worktree, &paths,
13775 pflag ? NULL : print_status, NULL,
13776 pflag ? choose_patch : NULL, &cpa,
13777 allow_bad_symlinks, repo);
13779 done:
13780 if (patch_script_file && fclose(patch_script_file) == EOF &&
13781 error == NULL)
13782 error = got_error_from_errno2("fclose", patch_script_path);
13783 if (repo) {
13784 const struct got_error *close_err = got_repo_close(repo);
13785 if (error == NULL)
13786 error = close_err;
13788 if (worktree)
13789 got_worktree_close(worktree);
13790 if (pack_fds) {
13791 const struct got_error *pack_err =
13792 got_repo_pack_fds_close(pack_fds);
13793 if (error == NULL)
13794 error = pack_err;
13796 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13797 free(cwd);
13798 return error;
13801 __dead static void
13802 usage_unstage(void)
13804 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13805 "[path ...]\n", getprogname());
13806 exit(1);
13810 static const struct got_error *
13811 cmd_unstage(int argc, char *argv[])
13813 const struct got_error *error = NULL;
13814 struct got_repository *repo = NULL;
13815 struct got_worktree *worktree = NULL;
13816 char *cwd = NULL;
13817 struct got_pathlist_head paths;
13818 int ch, pflag = 0;
13819 struct got_update_progress_arg upa;
13820 FILE *patch_script_file = NULL;
13821 const char *patch_script_path = NULL;
13822 struct choose_patch_arg cpa;
13823 int *pack_fds = NULL;
13825 TAILQ_INIT(&paths);
13827 #ifndef PROFILE
13828 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13829 "unveil", NULL) == -1)
13830 err(1, "pledge");
13831 #endif
13833 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13834 switch (ch) {
13835 case 'F':
13836 patch_script_path = optarg;
13837 break;
13838 case 'p':
13839 pflag = 1;
13840 break;
13841 default:
13842 usage_unstage();
13843 /* NOTREACHED */
13847 argc -= optind;
13848 argv += optind;
13850 if (patch_script_path && !pflag)
13851 errx(1, "-F option can only be used together with -p option");
13853 cwd = getcwd(NULL, 0);
13854 if (cwd == NULL) {
13855 error = got_error_from_errno("getcwd");
13856 goto done;
13859 error = got_repo_pack_fds_open(&pack_fds);
13860 if (error != NULL)
13861 goto done;
13863 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13864 if (error) {
13865 if (error->code == GOT_ERR_NOT_WORKTREE)
13866 error = wrap_not_worktree_error(error, "unstage", cwd);
13867 goto done;
13870 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13871 NULL, pack_fds);
13872 if (error != NULL)
13873 goto done;
13875 if (patch_script_path) {
13876 patch_script_file = fopen(patch_script_path, "re");
13877 if (patch_script_file == NULL) {
13878 error = got_error_from_errno2("fopen",
13879 patch_script_path);
13880 goto done;
13884 error = apply_unveil(got_repo_get_path(repo), 0,
13885 got_worktree_get_root_path(worktree));
13886 if (error)
13887 goto done;
13889 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13890 if (error)
13891 goto done;
13893 cpa.patch_script_file = patch_script_file;
13894 cpa.action = "unstage";
13895 memset(&upa, 0, sizeof(upa));
13896 error = got_worktree_unstage(worktree, &paths, update_progress,
13897 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13898 if (!error)
13899 print_merge_progress_stats(&upa);
13900 done:
13901 if (patch_script_file && fclose(patch_script_file) == EOF &&
13902 error == NULL)
13903 error = got_error_from_errno2("fclose", patch_script_path);
13904 if (repo) {
13905 const struct got_error *close_err = got_repo_close(repo);
13906 if (error == NULL)
13907 error = close_err;
13909 if (worktree)
13910 got_worktree_close(worktree);
13911 if (pack_fds) {
13912 const struct got_error *pack_err =
13913 got_repo_pack_fds_close(pack_fds);
13914 if (error == NULL)
13915 error = pack_err;
13917 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13918 free(cwd);
13919 return error;
13922 __dead static void
13923 usage_cat(void)
13925 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13926 "arg ...\n", getprogname());
13927 exit(1);
13930 static const struct got_error *
13931 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13933 const struct got_error *err;
13934 struct got_blob_object *blob;
13935 int fd = -1;
13937 fd = got_opentempfd();
13938 if (fd == -1)
13939 return got_error_from_errno("got_opentempfd");
13941 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13942 if (err)
13943 goto done;
13945 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13946 done:
13947 if (fd != -1 && close(fd) == -1 && err == NULL)
13948 err = got_error_from_errno("close");
13949 if (blob)
13950 got_object_blob_close(blob);
13951 return err;
13954 static const struct got_error *
13955 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13957 const struct got_error *err;
13958 struct got_tree_object *tree;
13959 int nentries, i;
13961 err = got_object_open_as_tree(&tree, repo, id);
13962 if (err)
13963 return err;
13965 nentries = got_object_tree_get_nentries(tree);
13966 for (i = 0; i < nentries; i++) {
13967 struct got_tree_entry *te;
13968 char *id_str;
13969 if (sigint_received || sigpipe_received)
13970 break;
13971 te = got_object_tree_get_entry(tree, i);
13972 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13973 if (err)
13974 break;
13975 fprintf(outfile, "%s %.7o %s\n", id_str,
13976 got_tree_entry_get_mode(te),
13977 got_tree_entry_get_name(te));
13978 free(id_str);
13981 got_object_tree_close(tree);
13982 return err;
13985 static const struct got_error *
13986 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13988 const struct got_error *err;
13989 struct got_commit_object *commit;
13990 const struct got_object_id_queue *parent_ids;
13991 struct got_object_qid *pid;
13992 char *id_str = NULL;
13993 const char *logmsg = NULL;
13994 char gmtoff[6];
13996 err = got_object_open_as_commit(&commit, repo, id);
13997 if (err)
13998 return err;
14000 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14001 if (err)
14002 goto done;
14004 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14005 parent_ids = got_object_commit_get_parent_ids(commit);
14006 fprintf(outfile, "numparents %d\n",
14007 got_object_commit_get_nparents(commit));
14008 STAILQ_FOREACH(pid, parent_ids, entry) {
14009 char *pid_str;
14010 err = got_object_id_str(&pid_str, &pid->id);
14011 if (err)
14012 goto done;
14013 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14014 free(pid_str);
14016 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14017 got_object_commit_get_author_gmtoff(commit));
14018 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14019 got_object_commit_get_author(commit),
14020 (long long)got_object_commit_get_author_time(commit),
14021 gmtoff);
14023 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14024 got_object_commit_get_committer_gmtoff(commit));
14025 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14026 got_object_commit_get_committer(commit),
14027 (long long)got_object_commit_get_committer_time(commit),
14028 gmtoff);
14030 logmsg = got_object_commit_get_logmsg_raw(commit);
14031 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14032 fprintf(outfile, "%s", logmsg);
14033 done:
14034 free(id_str);
14035 got_object_commit_close(commit);
14036 return err;
14039 static const struct got_error *
14040 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14042 const struct got_error *err;
14043 struct got_tag_object *tag;
14044 char *id_str = NULL;
14045 const char *tagmsg = NULL;
14046 char gmtoff[6];
14048 err = got_object_open_as_tag(&tag, repo, id);
14049 if (err)
14050 return err;
14052 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14053 if (err)
14054 goto done;
14056 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14058 switch (got_object_tag_get_object_type(tag)) {
14059 case GOT_OBJ_TYPE_BLOB:
14060 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14061 GOT_OBJ_LABEL_BLOB);
14062 break;
14063 case GOT_OBJ_TYPE_TREE:
14064 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14065 GOT_OBJ_LABEL_TREE);
14066 break;
14067 case GOT_OBJ_TYPE_COMMIT:
14068 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14069 GOT_OBJ_LABEL_COMMIT);
14070 break;
14071 case GOT_OBJ_TYPE_TAG:
14072 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14073 GOT_OBJ_LABEL_TAG);
14074 break;
14075 default:
14076 break;
14079 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14080 got_object_tag_get_name(tag));
14082 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14083 got_object_tag_get_tagger_gmtoff(tag));
14084 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14085 got_object_tag_get_tagger(tag),
14086 (long long)got_object_tag_get_tagger_time(tag),
14087 gmtoff);
14089 tagmsg = got_object_tag_get_message(tag);
14090 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14091 fprintf(outfile, "%s", tagmsg);
14092 done:
14093 free(id_str);
14094 got_object_tag_close(tag);
14095 return err;
14098 static const struct got_error *
14099 cmd_cat(int argc, char *argv[])
14101 const struct got_error *error;
14102 struct got_repository *repo = NULL;
14103 struct got_worktree *worktree = NULL;
14104 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14105 char *keyword_idstr = NULL;
14106 const char *commit_id_str = NULL;
14107 struct got_object_id *id = NULL, *commit_id = NULL;
14108 struct got_commit_object *commit = NULL;
14109 int ch, obj_type, i, force_path = 0;
14110 struct got_reflist_head refs;
14111 int *pack_fds = NULL;
14113 TAILQ_INIT(&refs);
14115 #ifndef PROFILE
14116 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14117 NULL) == -1)
14118 err(1, "pledge");
14119 #endif
14121 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14122 switch (ch) {
14123 case 'c':
14124 commit_id_str = optarg;
14125 break;
14126 case 'P':
14127 force_path = 1;
14128 break;
14129 case 'r':
14130 repo_path = realpath(optarg, NULL);
14131 if (repo_path == NULL)
14132 return got_error_from_errno2("realpath",
14133 optarg);
14134 got_path_strip_trailing_slashes(repo_path);
14135 break;
14136 default:
14137 usage_cat();
14138 /* NOTREACHED */
14142 argc -= optind;
14143 argv += optind;
14145 cwd = getcwd(NULL, 0);
14146 if (cwd == NULL) {
14147 error = got_error_from_errno("getcwd");
14148 goto done;
14151 error = got_repo_pack_fds_open(&pack_fds);
14152 if (error != NULL)
14153 goto done;
14155 if (repo_path == NULL) {
14156 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14157 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14158 goto done;
14159 if (worktree) {
14160 repo_path = strdup(
14161 got_worktree_get_repo_path(worktree));
14162 if (repo_path == NULL) {
14163 error = got_error_from_errno("strdup");
14164 goto done;
14167 if (commit_id_str == NULL) {
14168 /* Release work tree lock. */
14169 got_worktree_close(worktree);
14170 worktree = NULL;
14175 if (repo_path == NULL) {
14176 repo_path = strdup(cwd);
14177 if (repo_path == NULL)
14178 return got_error_from_errno("strdup");
14181 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14182 free(repo_path);
14183 if (error != NULL)
14184 goto done;
14186 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14187 if (error)
14188 goto done;
14190 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14191 if (error)
14192 goto done;
14194 if (commit_id_str != NULL) {
14195 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14196 repo, worktree);
14197 if (error != NULL)
14198 goto done;
14199 if (keyword_idstr != NULL)
14200 commit_id_str = keyword_idstr;
14201 if (worktree != NULL) {
14202 got_worktree_close(worktree);
14203 worktree = NULL;
14205 } else
14206 commit_id_str = GOT_REF_HEAD;
14207 error = got_repo_match_object_id(&commit_id, NULL,
14208 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14209 if (error)
14210 goto done;
14212 error = got_object_open_as_commit(&commit, repo, commit_id);
14213 if (error)
14214 goto done;
14216 for (i = 0; i < argc; i++) {
14217 if (force_path) {
14218 error = got_object_id_by_path(&id, repo, commit,
14219 argv[i]);
14220 if (error)
14221 break;
14222 } else {
14223 error = got_repo_match_object_id(&id, &label, argv[i],
14224 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14225 repo);
14226 if (error) {
14227 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14228 error->code != GOT_ERR_NOT_REF)
14229 break;
14230 error = got_object_id_by_path(&id, repo,
14231 commit, argv[i]);
14232 if (error)
14233 break;
14237 error = got_object_get_type(&obj_type, repo, id);
14238 if (error)
14239 break;
14241 switch (obj_type) {
14242 case GOT_OBJ_TYPE_BLOB:
14243 error = cat_blob(id, repo, stdout);
14244 break;
14245 case GOT_OBJ_TYPE_TREE:
14246 error = cat_tree(id, repo, stdout);
14247 break;
14248 case GOT_OBJ_TYPE_COMMIT:
14249 error = cat_commit(id, repo, stdout);
14250 break;
14251 case GOT_OBJ_TYPE_TAG:
14252 error = cat_tag(id, repo, stdout);
14253 break;
14254 default:
14255 error = got_error(GOT_ERR_OBJ_TYPE);
14256 break;
14258 if (error)
14259 break;
14260 free(label);
14261 label = NULL;
14262 free(id);
14263 id = NULL;
14265 done:
14266 free(label);
14267 free(id);
14268 free(commit_id);
14269 free(keyword_idstr);
14270 if (commit)
14271 got_object_commit_close(commit);
14272 if (worktree)
14273 got_worktree_close(worktree);
14274 if (repo) {
14275 const struct got_error *close_err = got_repo_close(repo);
14276 if (error == NULL)
14277 error = close_err;
14279 if (pack_fds) {
14280 const struct got_error *pack_err =
14281 got_repo_pack_fds_close(pack_fds);
14282 if (error == NULL)
14283 error = pack_err;
14286 got_ref_list_free(&refs);
14287 return error;
14290 __dead static void
14291 usage_info(void)
14293 fprintf(stderr, "usage: %s info [path ...]\n",
14294 getprogname());
14295 exit(1);
14298 static const struct got_error *
14299 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14300 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14301 struct got_object_id *commit_id)
14303 const struct got_error *err = NULL;
14304 char *id_str = NULL;
14305 char datebuf[128];
14306 struct tm mytm, *tm;
14307 struct got_pathlist_head *paths = arg;
14308 struct got_pathlist_entry *pe;
14311 * Clear error indication from any of the path arguments which
14312 * would cause this file index entry to be displayed.
14314 TAILQ_FOREACH(pe, paths, entry) {
14315 if (got_path_cmp(path, pe->path, strlen(path),
14316 pe->path_len) == 0 ||
14317 got_path_is_child(path, pe->path, pe->path_len))
14318 pe->data = NULL; /* no error */
14321 printf(GOT_COMMIT_SEP_STR);
14322 if (S_ISLNK(mode))
14323 printf("symlink: %s\n", path);
14324 else if (S_ISREG(mode)) {
14325 printf("file: %s\n", path);
14326 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14327 } else if (S_ISDIR(mode))
14328 printf("directory: %s\n", path);
14329 else
14330 printf("something: %s\n", path);
14332 tm = localtime_r(&mtime, &mytm);
14333 if (tm == NULL)
14334 return NULL;
14335 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14336 return got_error(GOT_ERR_NO_SPACE);
14337 printf("timestamp: %s\n", datebuf);
14339 if (blob_id) {
14340 err = got_object_id_str(&id_str, blob_id);
14341 if (err)
14342 return err;
14343 printf("based on blob: %s\n", id_str);
14344 free(id_str);
14347 if (staged_blob_id) {
14348 err = got_object_id_str(&id_str, staged_blob_id);
14349 if (err)
14350 return err;
14351 printf("based on staged blob: %s\n", id_str);
14352 free(id_str);
14355 if (commit_id) {
14356 err = got_object_id_str(&id_str, commit_id);
14357 if (err)
14358 return err;
14359 printf("based on commit: %s\n", id_str);
14360 free(id_str);
14363 return NULL;
14366 static const struct got_error *
14367 cmd_info(int argc, char *argv[])
14369 const struct got_error *error = NULL;
14370 struct got_worktree *worktree = NULL;
14371 char *cwd = NULL, *id_str = NULL;
14372 struct got_pathlist_head paths;
14373 char *uuidstr = NULL;
14374 int ch, show_files = 0;
14376 TAILQ_INIT(&paths);
14378 #ifndef PROFILE
14379 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14380 NULL) == -1)
14381 err(1, "pledge");
14382 #endif
14384 while ((ch = getopt(argc, argv, "")) != -1) {
14385 switch (ch) {
14386 default:
14387 usage_info();
14388 /* NOTREACHED */
14392 argc -= optind;
14393 argv += optind;
14395 cwd = getcwd(NULL, 0);
14396 if (cwd == NULL) {
14397 error = got_error_from_errno("getcwd");
14398 goto done;
14401 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14402 if (error) {
14403 if (error->code == GOT_ERR_NOT_WORKTREE)
14404 error = wrap_not_worktree_error(error, "info", cwd);
14405 goto done;
14408 #ifndef PROFILE
14409 /* Remove "wpath cpath proc exec sendfd" promises. */
14410 if (pledge("stdio rpath flock unveil", NULL) == -1)
14411 err(1, "pledge");
14412 #endif
14413 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14414 if (error)
14415 goto done;
14417 if (argc >= 1) {
14418 error = get_worktree_paths_from_argv(&paths, argc, argv,
14419 worktree);
14420 if (error)
14421 goto done;
14422 show_files = 1;
14425 error = got_object_id_str(&id_str,
14426 got_worktree_get_base_commit_id(worktree));
14427 if (error)
14428 goto done;
14430 error = got_worktree_get_uuid(&uuidstr, worktree);
14431 if (error)
14432 goto done;
14434 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14435 printf("work tree base commit: %s\n", id_str);
14436 printf("work tree path prefix: %s\n",
14437 got_worktree_get_path_prefix(worktree));
14438 printf("work tree branch reference: %s\n",
14439 got_worktree_get_head_ref_name(worktree));
14440 printf("work tree UUID: %s\n", uuidstr);
14441 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14443 if (show_files) {
14444 struct got_pathlist_entry *pe;
14445 TAILQ_FOREACH(pe, &paths, entry) {
14446 if (pe->path_len == 0)
14447 continue;
14449 * Assume this path will fail. This will be corrected
14450 * in print_path_info() in case the path does suceeed.
14452 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14454 error = got_worktree_path_info(worktree, &paths,
14455 print_path_info, &paths, check_cancelled, NULL);
14456 if (error)
14457 goto done;
14458 TAILQ_FOREACH(pe, &paths, entry) {
14459 if (pe->data != NULL) {
14460 const struct got_error *perr;
14462 perr = pe->data;
14463 error = got_error_fmt(perr->code, "%s",
14464 pe->path);
14465 break;
14469 done:
14470 if (worktree)
14471 got_worktree_close(worktree);
14472 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14473 free(cwd);
14474 free(id_str);
14475 free(uuidstr);
14476 return error;