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 *close_err, *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 close_err = got_repo_close(repo);
3255 if (error == NULL)
3256 error = close_err;
3258 if (worktree != NULL) {
3259 close_err = got_worktree_close(worktree);
3260 if (error == NULL)
3261 error = close_err;
3263 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3264 free(commit_id_str);
3265 free(commit_id);
3266 free(repo_path);
3267 free(worktree_path);
3268 free(cwd);
3269 return error;
3272 struct got_update_progress_arg {
3273 int did_something;
3274 int conflicts;
3275 int obstructed;
3276 int not_updated;
3277 int missing;
3278 int not_deleted;
3279 int unversioned;
3280 int verbosity;
3283 static void
3284 print_update_progress_stats(struct got_update_progress_arg *upa)
3286 if (!upa->did_something)
3287 return;
3289 if (upa->conflicts > 0)
3290 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3291 if (upa->obstructed > 0)
3292 printf("File paths obstructed by a non-regular file: %d\n",
3293 upa->obstructed);
3294 if (upa->not_updated > 0)
3295 printf("Files not updated because of existing merge "
3296 "conflicts: %d\n", upa->not_updated);
3300 * The meaning of some status codes differs between merge-style operations and
3301 * update operations. For example, the ! status code means "file was missing"
3302 * if changes were merged into the work tree, and "missing file was restored"
3303 * if the work tree was updated. This function should be used by any operation
3304 * which merges changes into the work tree without updating the work tree.
3306 static void
3307 print_merge_progress_stats(struct got_update_progress_arg *upa)
3309 if (!upa->did_something)
3310 return;
3312 if (upa->conflicts > 0)
3313 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3314 if (upa->obstructed > 0)
3315 printf("File paths obstructed by a non-regular file: %d\n",
3316 upa->obstructed);
3317 if (upa->missing > 0)
3318 printf("Files which had incoming changes but could not be "
3319 "found in the work tree: %d\n", upa->missing);
3320 if (upa->not_deleted > 0)
3321 printf("Files not deleted due to differences in deleted "
3322 "content: %d\n", upa->not_deleted);
3323 if (upa->unversioned > 0)
3324 printf("Files not merged because an unversioned file was "
3325 "found in the work tree: %d\n", upa->unversioned);
3328 __dead static void
3329 usage_update(void)
3331 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3332 "[path ...]\n", getprogname());
3333 exit(1);
3336 static const struct got_error *
3337 update_progress(void *arg, unsigned char status, const char *path)
3339 struct got_update_progress_arg *upa = arg;
3341 if (status == GOT_STATUS_EXISTS ||
3342 status == GOT_STATUS_BASE_REF_ERR)
3343 return NULL;
3345 upa->did_something = 1;
3347 /* Base commit bump happens silently. */
3348 if (status == GOT_STATUS_BUMP_BASE)
3349 return NULL;
3351 if (status == GOT_STATUS_CONFLICT)
3352 upa->conflicts++;
3353 if (status == GOT_STATUS_OBSTRUCTED)
3354 upa->obstructed++;
3355 if (status == GOT_STATUS_CANNOT_UPDATE)
3356 upa->not_updated++;
3357 if (status == GOT_STATUS_MISSING)
3358 upa->missing++;
3359 if (status == GOT_STATUS_CANNOT_DELETE)
3360 upa->not_deleted++;
3361 if (status == GOT_STATUS_UNVERSIONED)
3362 upa->unversioned++;
3364 while (path[0] == '/')
3365 path++;
3366 if (upa->verbosity >= 0)
3367 printf("%c %s\n", status, path);
3369 return NULL;
3372 static const struct got_error *
3373 switch_head_ref(struct got_reference *head_ref,
3374 struct got_object_id *commit_id, struct got_worktree *worktree,
3375 struct got_repository *repo)
3377 const struct got_error *err = NULL;
3378 char *base_id_str;
3379 int ref_has_moved = 0;
3381 /* Trivial case: switching between two different references. */
3382 if (strcmp(got_ref_get_name(head_ref),
3383 got_worktree_get_head_ref_name(worktree)) != 0) {
3384 printf("Switching work tree from %s to %s\n",
3385 got_worktree_get_head_ref_name(worktree),
3386 got_ref_get_name(head_ref));
3387 return got_worktree_set_head_ref(worktree, head_ref);
3390 err = check_linear_ancestry(commit_id,
3391 got_worktree_get_base_commit_id(worktree), 0, repo);
3392 if (err) {
3393 if (err->code != GOT_ERR_ANCESTRY)
3394 return err;
3395 ref_has_moved = 1;
3397 if (!ref_has_moved)
3398 return NULL;
3400 /* Switching to a rebased branch with the same reference name. */
3401 err = got_object_id_str(&base_id_str,
3402 got_worktree_get_base_commit_id(worktree));
3403 if (err)
3404 return err;
3405 printf("Reference %s now points at a different branch\n",
3406 got_worktree_get_head_ref_name(worktree));
3407 printf("Switching work tree from %s to %s\n", base_id_str,
3408 got_worktree_get_head_ref_name(worktree));
3409 return NULL;
3412 static const struct got_error *
3413 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3415 const struct got_error *err;
3416 int in_progress;
3418 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3419 if (err)
3420 return err;
3421 if (in_progress)
3422 return got_error(GOT_ERR_REBASING);
3424 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3425 if (err)
3426 return err;
3427 if (in_progress)
3428 return got_error(GOT_ERR_HISTEDIT_BUSY);
3430 return NULL;
3433 static const struct got_error *
3434 check_merge_in_progress(struct got_worktree *worktree,
3435 struct got_repository *repo)
3437 const struct got_error *err;
3438 int in_progress;
3440 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3441 if (err)
3442 return err;
3443 if (in_progress)
3444 return got_error(GOT_ERR_MERGE_BUSY);
3446 return NULL;
3449 static const struct got_error *
3450 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3451 char *argv[], struct got_worktree *worktree)
3453 const struct got_error *err = NULL;
3454 char *path;
3455 struct got_pathlist_entry *new;
3456 int i;
3458 if (argc == 0) {
3459 path = strdup("");
3460 if (path == NULL)
3461 return got_error_from_errno("strdup");
3462 return got_pathlist_append(paths, path, NULL);
3465 for (i = 0; i < argc; i++) {
3466 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3467 if (err)
3468 break;
3469 err = got_pathlist_insert(&new, paths, path, NULL);
3470 if (err || new == NULL /* duplicate */) {
3471 free(path);
3472 if (err)
3473 break;
3477 return err;
3480 static const struct got_error *
3481 wrap_not_worktree_error(const struct got_error *orig_err,
3482 const char *cmdname, const char *path)
3484 const struct got_error *err;
3485 struct got_repository *repo;
3486 static char msg[512];
3487 int *pack_fds = NULL;
3489 err = got_repo_pack_fds_open(&pack_fds);
3490 if (err)
3491 return err;
3493 err = got_repo_open(&repo, path, NULL, pack_fds);
3494 if (err)
3495 return orig_err;
3497 snprintf(msg, sizeof(msg),
3498 "'got %s' needs a work tree in addition to a git repository\n"
3499 "Work trees can be checked out from this Git repository with "
3500 "'got checkout'.\n"
3501 "The got(1) manual page contains more information.", cmdname);
3502 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3503 if (repo) {
3504 const struct got_error *close_err = got_repo_close(repo);
3505 if (err == NULL)
3506 err = close_err;
3508 if (pack_fds) {
3509 const struct got_error *pack_err =
3510 got_repo_pack_fds_close(pack_fds);
3511 if (err == NULL)
3512 err = pack_err;
3514 return err;
3517 static const struct got_error *
3518 cmd_update(int argc, char *argv[])
3520 const struct got_error *close_err, *error = NULL;
3521 struct got_repository *repo = NULL;
3522 struct got_worktree *worktree = NULL;
3523 char *worktree_path = NULL;
3524 struct got_object_id *commit_id = NULL;
3525 char *commit_id_str = NULL;
3526 const char *branch_name = NULL;
3527 struct got_reference *head_ref = NULL;
3528 struct got_pathlist_head paths;
3529 struct got_pathlist_entry *pe;
3530 int ch, verbosity = 0;
3531 struct got_update_progress_arg upa;
3532 int *pack_fds = NULL;
3534 TAILQ_INIT(&paths);
3536 #ifndef PROFILE
3537 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3538 "unveil", NULL) == -1)
3539 err(1, "pledge");
3540 #endif
3542 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3543 switch (ch) {
3544 case 'b':
3545 branch_name = optarg;
3546 break;
3547 case 'c':
3548 commit_id_str = strdup(optarg);
3549 if (commit_id_str == NULL)
3550 return got_error_from_errno("strdup");
3551 break;
3552 case 'q':
3553 verbosity = -1;
3554 break;
3555 default:
3556 usage_update();
3557 /* NOTREACHED */
3561 argc -= optind;
3562 argv += optind;
3564 worktree_path = getcwd(NULL, 0);
3565 if (worktree_path == NULL) {
3566 error = got_error_from_errno("getcwd");
3567 goto done;
3570 error = got_repo_pack_fds_open(&pack_fds);
3571 if (error != NULL)
3572 goto done;
3574 error = got_worktree_open(&worktree, worktree_path,
3575 GOT_WORKTREE_GOT_DIR);
3576 if (error) {
3577 if (error->code == GOT_ERR_NOT_WORKTREE)
3578 error = wrap_not_worktree_error(error, "update",
3579 worktree_path);
3580 goto done;
3583 error = check_rebase_or_histedit_in_progress(worktree);
3584 if (error)
3585 goto done;
3587 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3588 NULL, pack_fds);
3589 if (error != NULL)
3590 goto done;
3592 error = apply_unveil(got_repo_get_path(repo), 0,
3593 got_worktree_get_root_path(worktree));
3594 if (error)
3595 goto done;
3597 error = check_merge_in_progress(worktree, repo);
3598 if (error)
3599 goto done;
3601 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3602 if (error)
3603 goto done;
3605 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3606 got_worktree_get_head_ref_name(worktree), 0);
3607 if (error != NULL)
3608 goto done;
3609 if (commit_id_str == NULL) {
3610 error = got_ref_resolve(&commit_id, repo, head_ref);
3611 if (error != NULL)
3612 goto done;
3613 error = got_object_id_str(&commit_id_str, commit_id);
3614 if (error != NULL)
3615 goto done;
3616 } else {
3617 struct got_reflist_head refs;
3618 char *keyword_idstr = NULL;
3620 TAILQ_INIT(&refs);
3622 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3623 NULL);
3624 if (error)
3625 goto done;
3627 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3628 repo, worktree);
3629 if (error != NULL)
3630 goto done;
3631 if (keyword_idstr != NULL) {
3632 free(commit_id_str);
3633 commit_id_str = keyword_idstr;
3636 error = got_repo_match_object_id(&commit_id, NULL,
3637 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3638 got_ref_list_free(&refs);
3639 free(commit_id_str);
3640 commit_id_str = NULL;
3641 if (error)
3642 goto done;
3643 error = got_object_id_str(&commit_id_str, commit_id);
3644 if (error)
3645 goto done;
3648 if (branch_name) {
3649 struct got_object_id *head_commit_id;
3650 TAILQ_FOREACH(pe, &paths, entry) {
3651 if (pe->path_len == 0)
3652 continue;
3653 error = got_error_msg(GOT_ERR_BAD_PATH,
3654 "switching between branches requires that "
3655 "the entire work tree gets updated");
3656 goto done;
3658 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3659 if (error)
3660 goto done;
3661 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3662 repo);
3663 free(head_commit_id);
3664 if (error != NULL)
3665 goto done;
3666 error = check_same_branch(commit_id, head_ref, repo);
3667 if (error)
3668 goto done;
3669 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3670 if (error)
3671 goto done;
3672 } else {
3673 error = check_linear_ancestry(commit_id,
3674 got_worktree_get_base_commit_id(worktree), 0, repo);
3675 if (error != NULL) {
3676 if (error->code == GOT_ERR_ANCESTRY)
3677 error = got_error(GOT_ERR_BRANCH_MOVED);
3678 goto done;
3680 error = check_same_branch(commit_id, head_ref, repo);
3681 if (error)
3682 goto done;
3685 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3686 commit_id) != 0) {
3687 error = got_worktree_set_base_commit_id(worktree, repo,
3688 commit_id);
3689 if (error)
3690 goto done;
3693 memset(&upa, 0, sizeof(upa));
3694 upa.verbosity = verbosity;
3695 error = got_worktree_checkout_files(worktree, &paths, repo,
3696 update_progress, &upa, check_cancelled, NULL);
3697 if (error != NULL)
3698 goto done;
3700 if (upa.did_something) {
3701 printf("Updated to %s: %s\n",
3702 got_worktree_get_head_ref_name(worktree), commit_id_str);
3703 } else
3704 printf("Already up-to-date\n");
3706 print_update_progress_stats(&upa);
3707 done:
3708 if (pack_fds) {
3709 const struct got_error *pack_err =
3710 got_repo_pack_fds_close(pack_fds);
3711 if (error == NULL)
3712 error = pack_err;
3714 if (repo) {
3715 close_err = got_repo_close(repo);
3716 if (error == NULL)
3717 error = close_err;
3719 if (worktree != NULL) {
3720 close_err = got_worktree_close(worktree);
3721 if (error == NULL)
3722 error = close_err;
3724 if (head_ref != NULL)
3725 got_ref_close(head_ref);
3726 free(worktree_path);
3727 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3728 free(commit_id);
3729 free(commit_id_str);
3730 return error;
3733 static const struct got_error *
3734 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3735 const char *path, int diff_context, int ignore_whitespace,
3736 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3737 struct got_repository *repo, FILE *outfile)
3739 const struct got_error *err = NULL;
3740 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3741 FILE *f1 = NULL, *f2 = NULL;
3742 int fd1 = -1, fd2 = -1;
3744 fd1 = got_opentempfd();
3745 if (fd1 == -1)
3746 return got_error_from_errno("got_opentempfd");
3747 fd2 = got_opentempfd();
3748 if (fd2 == -1) {
3749 err = got_error_from_errno("got_opentempfd");
3750 goto done;
3753 if (blob_id1) {
3754 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3755 fd1);
3756 if (err)
3757 goto done;
3760 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3761 if (err)
3762 goto done;
3764 f1 = got_opentemp();
3765 if (f1 == NULL) {
3766 err = got_error_from_errno("got_opentemp");
3767 goto done;
3769 f2 = got_opentemp();
3770 if (f2 == NULL) {
3771 err = got_error_from_errno("got_opentemp");
3772 goto done;
3775 while (path[0] == '/')
3776 path++;
3777 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3778 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3779 force_text_diff, dsa, outfile);
3780 done:
3781 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3782 err = got_error_from_errno("close");
3783 if (blob1)
3784 got_object_blob_close(blob1);
3785 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3786 err = got_error_from_errno("close");
3787 if (blob2)
3788 got_object_blob_close(blob2);
3789 if (f1 && fclose(f1) == EOF && err == NULL)
3790 err = got_error_from_errno("fclose");
3791 if (f2 && fclose(f2) == EOF && err == NULL)
3792 err = got_error_from_errno("fclose");
3793 return err;
3796 static const struct got_error *
3797 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3798 const char *path, int diff_context, int ignore_whitespace,
3799 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3800 struct got_repository *repo, FILE *outfile)
3802 const struct got_error *err = NULL;
3803 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3804 struct got_diff_blob_output_unidiff_arg arg;
3805 FILE *f1 = NULL, *f2 = NULL;
3806 int fd1 = -1, fd2 = -1;
3808 if (tree_id1) {
3809 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3810 if (err)
3811 goto done;
3812 fd1 = got_opentempfd();
3813 if (fd1 == -1) {
3814 err = got_error_from_errno("got_opentempfd");
3815 goto done;
3819 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3820 if (err)
3821 goto done;
3823 f1 = got_opentemp();
3824 if (f1 == NULL) {
3825 err = got_error_from_errno("got_opentemp");
3826 goto done;
3829 f2 = got_opentemp();
3830 if (f2 == NULL) {
3831 err = got_error_from_errno("got_opentemp");
3832 goto done;
3834 fd2 = got_opentempfd();
3835 if (fd2 == -1) {
3836 err = got_error_from_errno("got_opentempfd");
3837 goto done;
3839 arg.diff_context = diff_context;
3840 arg.ignore_whitespace = ignore_whitespace;
3841 arg.force_text_diff = force_text_diff;
3842 arg.diffstat = dsa;
3843 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3844 arg.outfile = outfile;
3845 arg.lines = NULL;
3846 arg.nlines = 0;
3847 while (path[0] == '/')
3848 path++;
3849 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3850 got_diff_blob_output_unidiff, &arg, 1);
3851 done:
3852 if (tree1)
3853 got_object_tree_close(tree1);
3854 if (tree2)
3855 got_object_tree_close(tree2);
3856 if (f1 && fclose(f1) == EOF && err == NULL)
3857 err = got_error_from_errno("fclose");
3858 if (f2 && fclose(f2) == EOF && err == NULL)
3859 err = got_error_from_errno("fclose");
3860 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3861 err = got_error_from_errno("close");
3862 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3863 err = got_error_from_errno("close");
3864 return err;
3867 static const struct got_error *
3868 get_changed_paths(struct got_pathlist_head *paths,
3869 struct got_commit_object *commit, struct got_repository *repo,
3870 struct got_diffstat_cb_arg *dsa)
3872 const struct got_error *err = NULL;
3873 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3874 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3875 struct got_object_qid *qid;
3876 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3877 FILE *f1 = NULL, *f2 = NULL;
3878 int fd1 = -1, fd2 = -1;
3880 if (dsa) {
3881 cb = got_diff_tree_compute_diffstat;
3883 f1 = got_opentemp();
3884 if (f1 == NULL) {
3885 err = got_error_from_errno("got_opentemp");
3886 goto done;
3888 f2 = got_opentemp();
3889 if (f2 == NULL) {
3890 err = got_error_from_errno("got_opentemp");
3891 goto done;
3893 fd1 = got_opentempfd();
3894 if (fd1 == -1) {
3895 err = got_error_from_errno("got_opentempfd");
3896 goto done;
3898 fd2 = got_opentempfd();
3899 if (fd2 == -1) {
3900 err = got_error_from_errno("got_opentempfd");
3901 goto done;
3905 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3906 if (qid != NULL) {
3907 struct got_commit_object *pcommit;
3908 err = got_object_open_as_commit(&pcommit, repo,
3909 &qid->id);
3910 if (err)
3911 return err;
3913 tree_id1 = got_object_id_dup(
3914 got_object_commit_get_tree_id(pcommit));
3915 if (tree_id1 == NULL) {
3916 got_object_commit_close(pcommit);
3917 return got_error_from_errno("got_object_id_dup");
3919 got_object_commit_close(pcommit);
3923 if (tree_id1) {
3924 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3925 if (err)
3926 goto done;
3929 tree_id2 = got_object_commit_get_tree_id(commit);
3930 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3931 if (err)
3932 goto done;
3934 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3935 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3936 done:
3937 if (tree1)
3938 got_object_tree_close(tree1);
3939 if (tree2)
3940 got_object_tree_close(tree2);
3941 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3942 err = got_error_from_errno("close");
3943 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3944 err = got_error_from_errno("close");
3945 if (f1 && fclose(f1) == EOF && err == NULL)
3946 err = got_error_from_errno("fclose");
3947 if (f2 && fclose(f2) == EOF && err == NULL)
3948 err = got_error_from_errno("fclose");
3949 free(tree_id1);
3950 return err;
3953 static const struct got_error *
3954 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3955 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3956 struct got_repository *repo, FILE *outfile)
3958 const struct got_error *err = NULL;
3959 struct got_commit_object *pcommit = NULL;
3960 char *id_str1 = NULL, *id_str2 = NULL;
3961 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3962 struct got_object_qid *qid;
3964 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3965 if (qid != NULL) {
3966 err = got_object_open_as_commit(&pcommit, repo,
3967 &qid->id);
3968 if (err)
3969 return err;
3970 err = got_object_id_str(&id_str1, &qid->id);
3971 if (err)
3972 goto done;
3975 err = got_object_id_str(&id_str2, id);
3976 if (err)
3977 goto done;
3979 if (path && path[0] != '\0') {
3980 int obj_type;
3981 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3982 if (err)
3983 goto done;
3984 if (pcommit) {
3985 err = got_object_id_by_path(&obj_id1, repo,
3986 pcommit, path);
3987 if (err) {
3988 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3989 free(obj_id2);
3990 goto done;
3994 err = got_object_get_type(&obj_type, repo, obj_id2);
3995 if (err) {
3996 free(obj_id2);
3997 goto done;
3999 fprintf(outfile,
4000 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4001 fprintf(outfile, "commit - %s\n",
4002 id_str1 ? id_str1 : "/dev/null");
4003 fprintf(outfile, "commit + %s\n", id_str2);
4004 switch (obj_type) {
4005 case GOT_OBJ_TYPE_BLOB:
4006 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4007 0, 0, dsa, repo, outfile);
4008 break;
4009 case GOT_OBJ_TYPE_TREE:
4010 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4011 0, 0, dsa, repo, outfile);
4012 break;
4013 default:
4014 err = got_error(GOT_ERR_OBJ_TYPE);
4015 break;
4017 free(obj_id1);
4018 free(obj_id2);
4019 } else {
4020 obj_id2 = got_object_commit_get_tree_id(commit);
4021 if (pcommit)
4022 obj_id1 = got_object_commit_get_tree_id(pcommit);
4023 fprintf(outfile,
4024 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4025 fprintf(outfile, "commit - %s\n",
4026 id_str1 ? id_str1 : "/dev/null");
4027 fprintf(outfile, "commit + %s\n", id_str2);
4028 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4029 dsa, repo, outfile);
4031 done:
4032 free(id_str1);
4033 free(id_str2);
4034 if (pcommit)
4035 got_object_commit_close(pcommit);
4036 return err;
4039 static char *
4040 get_datestr(time_t *time, char *datebuf)
4042 struct tm mytm, *tm;
4043 char *p, *s;
4045 tm = gmtime_r(time, &mytm);
4046 if (tm == NULL)
4047 return NULL;
4048 s = asctime_r(tm, datebuf);
4049 if (s == NULL)
4050 return NULL;
4051 p = strchr(s, '\n');
4052 if (p)
4053 *p = '\0';
4054 return s;
4057 static const struct got_error *
4058 match_commit(int *have_match, struct got_object_id *id,
4059 struct got_commit_object *commit, regex_t *regex)
4061 const struct got_error *err = NULL;
4062 regmatch_t regmatch;
4063 char *id_str = NULL, *logmsg = NULL;
4065 *have_match = 0;
4067 err = got_object_id_str(&id_str, id);
4068 if (err)
4069 return err;
4071 err = got_object_commit_get_logmsg(&logmsg, commit);
4072 if (err)
4073 goto done;
4075 if (regexec(regex, got_object_commit_get_author(commit), 1,
4076 &regmatch, 0) == 0 ||
4077 regexec(regex, got_object_commit_get_committer(commit), 1,
4078 &regmatch, 0) == 0 ||
4079 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4080 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4081 *have_match = 1;
4082 done:
4083 free(id_str);
4084 free(logmsg);
4085 return err;
4088 static void
4089 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4090 regex_t *regex)
4092 regmatch_t regmatch;
4093 struct got_pathlist_entry *pe;
4095 *have_match = 0;
4097 TAILQ_FOREACH(pe, changed_paths, entry) {
4098 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4099 *have_match = 1;
4100 break;
4105 static const struct got_error *
4106 match_patch(int *have_match, struct got_commit_object *commit,
4107 struct got_object_id *id, const char *path, int diff_context,
4108 struct got_repository *repo, regex_t *regex, FILE *f)
4110 const struct got_error *err = NULL;
4111 char *line = NULL;
4112 size_t linesize = 0;
4113 regmatch_t regmatch;
4115 *have_match = 0;
4117 err = got_opentemp_truncate(f);
4118 if (err)
4119 return err;
4121 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4122 if (err)
4123 goto done;
4125 if (fseeko(f, 0L, SEEK_SET) == -1) {
4126 err = got_error_from_errno("fseeko");
4127 goto done;
4130 while (getline(&line, &linesize, f) != -1) {
4131 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4132 *have_match = 1;
4133 break;
4136 done:
4137 free(line);
4138 return err;
4141 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4143 static const struct got_error*
4144 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4145 struct got_object_id *id, struct got_repository *repo,
4146 int local_only)
4148 static const struct got_error *err = NULL;
4149 struct got_reflist_entry *re;
4150 char *s;
4151 const char *name;
4153 *refs_str = NULL;
4155 TAILQ_FOREACH(re, refs, entry) {
4156 struct got_tag_object *tag = NULL;
4157 struct got_object_id *ref_id;
4158 int cmp;
4160 name = got_ref_get_name(re->ref);
4161 if (strcmp(name, GOT_REF_HEAD) == 0)
4162 continue;
4163 if (strncmp(name, "refs/", 5) == 0)
4164 name += 5;
4165 if (strncmp(name, "got/", 4) == 0)
4166 continue;
4167 if (strncmp(name, "heads/", 6) == 0)
4168 name += 6;
4169 if (strncmp(name, "remotes/", 8) == 0) {
4170 if (local_only)
4171 continue;
4172 name += 8;
4173 s = strstr(name, "/" GOT_REF_HEAD);
4174 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4175 continue;
4177 err = got_ref_resolve(&ref_id, repo, re->ref);
4178 if (err)
4179 break;
4180 if (strncmp(name, "tags/", 5) == 0) {
4181 err = got_object_open_as_tag(&tag, repo, ref_id);
4182 if (err) {
4183 if (err->code != GOT_ERR_OBJ_TYPE) {
4184 free(ref_id);
4185 break;
4187 /* Ref points at something other than a tag. */
4188 err = NULL;
4189 tag = NULL;
4192 cmp = got_object_id_cmp(tag ?
4193 got_object_tag_get_object_id(tag) : ref_id, id);
4194 free(ref_id);
4195 if (tag)
4196 got_object_tag_close(tag);
4197 if (cmp != 0)
4198 continue;
4199 s = *refs_str;
4200 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4201 s ? ", " : "", name) == -1) {
4202 err = got_error_from_errno("asprintf");
4203 free(s);
4204 *refs_str = NULL;
4205 break;
4207 free(s);
4210 return err;
4213 static const struct got_error *
4214 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4215 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4217 const struct got_error *err = NULL;
4218 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4219 char *comma, *s, *nl;
4220 struct got_reflist_head *refs;
4221 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4222 struct tm tm;
4223 time_t committer_time;
4225 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4226 if (refs) {
4227 err = build_refs_str(&ref_str, refs, id, repo, 1);
4228 if (err)
4229 return err;
4231 /* Display the first matching ref only. */
4232 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4233 *comma = '\0';
4236 if (ref_str == NULL) {
4237 err = got_object_id_str(&id_str, id);
4238 if (err)
4239 return err;
4242 committer_time = got_object_commit_get_committer_time(commit);
4243 if (gmtime_r(&committer_time, &tm) == NULL) {
4244 err = got_error_from_errno("gmtime_r");
4245 goto done;
4247 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4248 err = got_error(GOT_ERR_NO_SPACE);
4249 goto done;
4252 err = got_object_commit_get_logmsg(&logmsg0, commit);
4253 if (err)
4254 goto done;
4256 s = logmsg0;
4257 while (isspace((unsigned char)s[0]))
4258 s++;
4260 nl = strchr(s, '\n');
4261 if (nl) {
4262 *nl = '\0';
4265 if (ref_str)
4266 printf("%s%-7s %s\n", datebuf, ref_str, s);
4267 else
4268 printf("%s%.7s %s\n", datebuf, id_str, s);
4270 if (fflush(stdout) != 0 && err == NULL)
4271 err = got_error_from_errno("fflush");
4272 done:
4273 free(id_str);
4274 free(ref_str);
4275 free(logmsg0);
4276 return err;
4279 static const struct got_error *
4280 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4282 struct got_pathlist_entry *pe;
4284 if (header != NULL)
4285 printf("%s\n", header);
4287 TAILQ_FOREACH(pe, dsa->paths, entry) {
4288 struct got_diff_changed_path *cp = pe->data;
4289 int pad = dsa->max_path_len - pe->path_len + 1;
4291 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4292 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4294 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4295 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4296 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4298 if (fflush(stdout) != 0)
4299 return got_error_from_errno("fflush");
4301 return NULL;
4304 static const struct got_error *
4305 printfile(FILE *f)
4307 char buf[8192];
4308 size_t r;
4310 if (fseeko(f, 0L, SEEK_SET) == -1)
4311 return got_error_from_errno("fseek");
4313 for (;;) {
4314 r = fread(buf, 1, sizeof(buf), f);
4315 if (r == 0) {
4316 if (ferror(f))
4317 return got_error_from_errno("fread");
4318 if (feof(f))
4319 break;
4321 if (fwrite(buf, 1, r, stdout) != r)
4322 return got_ferror(stdout, GOT_ERR_IO);
4325 return NULL;
4328 static const struct got_error *
4329 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4330 struct got_repository *repo, const char *path,
4331 struct got_pathlist_head *changed_paths,
4332 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4333 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4334 const char *prefix)
4336 const struct got_error *err = NULL;
4337 FILE *f = NULL;
4338 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4339 char datebuf[26];
4340 time_t committer_time;
4341 const char *author, *committer;
4342 char *refs_str = NULL;
4344 err = got_object_id_str(&id_str, id);
4345 if (err)
4346 return err;
4348 if (custom_refs_str == NULL) {
4349 struct got_reflist_head *refs;
4350 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4351 if (refs) {
4352 err = build_refs_str(&refs_str, refs, id, repo, 0);
4353 if (err)
4354 goto done;
4358 printf(GOT_COMMIT_SEP_STR);
4359 if (custom_refs_str)
4360 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4361 custom_refs_str);
4362 else
4363 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4364 refs_str ? " (" : "", refs_str ? refs_str : "",
4365 refs_str ? ")" : "");
4366 free(id_str);
4367 id_str = NULL;
4368 free(refs_str);
4369 refs_str = NULL;
4370 printf("from: %s\n", got_object_commit_get_author(commit));
4371 author = got_object_commit_get_author(commit);
4372 committer = got_object_commit_get_committer(commit);
4373 if (strcmp(author, committer) != 0)
4374 printf("via: %s\n", committer);
4375 committer_time = got_object_commit_get_committer_time(commit);
4376 datestr = get_datestr(&committer_time, datebuf);
4377 if (datestr)
4378 printf("date: %s UTC\n", datestr);
4379 if (got_object_commit_get_nparents(commit) > 1) {
4380 const struct got_object_id_queue *parent_ids;
4381 struct got_object_qid *qid;
4382 int n = 1;
4383 parent_ids = got_object_commit_get_parent_ids(commit);
4384 STAILQ_FOREACH(qid, parent_ids, entry) {
4385 err = got_object_id_str(&id_str, &qid->id);
4386 if (err)
4387 goto done;
4388 printf("parent %d: %s\n", n++, id_str);
4389 free(id_str);
4390 id_str = NULL;
4394 err = got_object_commit_get_logmsg(&logmsg0, commit);
4395 if (err)
4396 goto done;
4398 logmsg = logmsg0;
4399 do {
4400 line = strsep(&logmsg, "\n");
4401 if (line)
4402 printf(" %s\n", line);
4403 } while (line);
4404 free(logmsg0);
4406 if (changed_paths && diffstat == NULL) {
4407 struct got_pathlist_entry *pe;
4409 TAILQ_FOREACH(pe, changed_paths, entry) {
4410 struct got_diff_changed_path *cp = pe->data;
4412 printf(" %c %s\n", cp->status, pe->path);
4414 printf("\n");
4416 if (show_patch) {
4417 if (diffstat) {
4418 f = got_opentemp();
4419 if (f == NULL) {
4420 err = got_error_from_errno("got_opentemp");
4421 goto done;
4425 err = print_patch(commit, id, path, diff_context, diffstat,
4426 repo, diffstat == NULL ? stdout : f);
4427 if (err)
4428 goto done;
4430 if (diffstat) {
4431 err = print_diffstat(diffstat, NULL);
4432 if (err)
4433 goto done;
4434 if (show_patch) {
4435 err = printfile(f);
4436 if (err)
4437 goto done;
4440 if (show_patch)
4441 printf("\n");
4443 if (fflush(stdout) != 0 && err == NULL)
4444 err = got_error_from_errno("fflush");
4445 done:
4446 if (f && fclose(f) == EOF && err == NULL)
4447 err = got_error_from_errno("fclose");
4448 free(id_str);
4449 free(refs_str);
4450 return err;
4453 static const struct got_error *
4454 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4455 struct got_repository *repo, const char *path, int show_changed_paths,
4456 int show_diffstat, int show_patch, const char *search_pattern,
4457 int diff_context, int limit, int log_branches, int reverse_display_order,
4458 struct got_reflist_object_id_map *refs_idmap, int one_line,
4459 FILE *tmpfile)
4461 const struct got_error *err;
4462 struct got_commit_graph *graph;
4463 regex_t regex;
4464 int have_match;
4465 struct got_object_id_queue reversed_commits;
4466 struct got_object_qid *qid;
4467 struct got_commit_object *commit;
4468 struct got_pathlist_head changed_paths;
4470 STAILQ_INIT(&reversed_commits);
4471 TAILQ_INIT(&changed_paths);
4473 if (search_pattern && regcomp(&regex, search_pattern,
4474 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4475 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4477 err = got_commit_graph_open(&graph, path, !log_branches);
4478 if (err)
4479 return err;
4480 err = got_commit_graph_iter_start(graph, root_id, repo,
4481 check_cancelled, NULL);
4482 if (err)
4483 goto done;
4484 for (;;) {
4485 struct got_object_id id;
4486 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4487 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4489 if (sigint_received || sigpipe_received)
4490 break;
4492 err = got_commit_graph_iter_next(&id, graph, repo,
4493 check_cancelled, NULL);
4494 if (err) {
4495 if (err->code == GOT_ERR_ITER_COMPLETED)
4496 err = NULL;
4497 break;
4500 err = got_object_open_as_commit(&commit, repo, &id);
4501 if (err)
4502 break;
4504 if (((show_changed_paths && !show_diffstat) ||
4505 (show_diffstat && !show_patch))
4506 && !reverse_display_order) {
4507 err = get_changed_paths(&changed_paths, commit, repo,
4508 show_diffstat ? &dsa : NULL);
4509 if (err)
4510 break;
4513 if (search_pattern) {
4514 err = match_commit(&have_match, &id, commit, &regex);
4515 if (err) {
4516 got_object_commit_close(commit);
4517 break;
4519 if (have_match == 0 && show_changed_paths)
4520 match_changed_paths(&have_match,
4521 &changed_paths, &regex);
4522 if (have_match == 0 && show_patch) {
4523 err = match_patch(&have_match, commit, &id,
4524 path, diff_context, repo, &regex, tmpfile);
4525 if (err)
4526 break;
4528 if (have_match == 0) {
4529 got_object_commit_close(commit);
4530 got_pathlist_free(&changed_paths,
4531 GOT_PATHLIST_FREE_ALL);
4532 continue;
4536 if (reverse_display_order) {
4537 err = got_object_qid_alloc(&qid, &id);
4538 if (err)
4539 break;
4540 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4541 got_object_commit_close(commit);
4542 } else {
4543 if (one_line)
4544 err = print_commit_oneline(commit, &id,
4545 repo, refs_idmap);
4546 else
4547 err = print_commit(commit, &id, repo, path,
4548 (show_changed_paths || show_diffstat) ?
4549 &changed_paths : NULL,
4550 show_diffstat ? &dsa : NULL, show_patch,
4551 diff_context, refs_idmap, NULL, NULL);
4552 got_object_commit_close(commit);
4553 if (err)
4554 break;
4556 if ((limit && --limit == 0) ||
4557 (end_id && got_object_id_cmp(&id, end_id) == 0))
4558 break;
4560 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4562 if (reverse_display_order) {
4563 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4564 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4565 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4567 err = got_object_open_as_commit(&commit, repo,
4568 &qid->id);
4569 if (err)
4570 break;
4571 if ((show_changed_paths && !show_diffstat) ||
4572 (show_diffstat && !show_patch)) {
4573 err = get_changed_paths(&changed_paths, commit,
4574 repo, show_diffstat ? &dsa : NULL);
4575 if (err)
4576 break;
4578 if (one_line)
4579 err = print_commit_oneline(commit, &qid->id,
4580 repo, refs_idmap);
4581 else
4582 err = print_commit(commit, &qid->id, repo, path,
4583 (show_changed_paths || show_diffstat) ?
4584 &changed_paths : NULL,
4585 show_diffstat ? &dsa : NULL, show_patch,
4586 diff_context, refs_idmap, NULL, NULL);
4587 got_object_commit_close(commit);
4588 if (err)
4589 break;
4590 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4593 done:
4594 while (!STAILQ_EMPTY(&reversed_commits)) {
4595 qid = STAILQ_FIRST(&reversed_commits);
4596 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4597 got_object_qid_free(qid);
4599 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4600 if (search_pattern)
4601 regfree(&regex);
4602 got_commit_graph_close(graph);
4603 return err;
4606 __dead static void
4607 usage_log(void)
4609 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4610 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4611 "[path]\n", getprogname());
4612 exit(1);
4615 static int
4616 get_default_log_limit(void)
4618 const char *got_default_log_limit;
4619 long long n;
4620 const char *errstr;
4622 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4623 if (got_default_log_limit == NULL)
4624 return 0;
4625 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4626 if (errstr != NULL)
4627 return 0;
4628 return n;
4631 static const struct got_error *
4632 cmd_log(int argc, char *argv[])
4634 const struct got_error *error;
4635 struct got_repository *repo = NULL;
4636 struct got_worktree *worktree = NULL;
4637 struct got_object_id *start_id = NULL, *end_id = NULL;
4638 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4639 char *keyword_idstr = NULL;
4640 const char *start_commit = NULL, *end_commit = NULL;
4641 const char *search_pattern = NULL;
4642 int diff_context = -1, ch;
4643 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4644 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4645 const char *errstr;
4646 struct got_reflist_head refs;
4647 struct got_reflist_object_id_map *refs_idmap = NULL;
4648 FILE *tmpfile = NULL;
4649 int *pack_fds = NULL;
4651 TAILQ_INIT(&refs);
4653 #ifndef PROFILE
4654 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4655 NULL)
4656 == -1)
4657 err(1, "pledge");
4658 #endif
4660 limit = get_default_log_limit();
4662 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4663 switch (ch) {
4664 case 'b':
4665 log_branches = 1;
4666 break;
4667 case 'C':
4668 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4669 &errstr);
4670 if (errstr != NULL)
4671 errx(1, "number of context lines is %s: %s",
4672 errstr, optarg);
4673 break;
4674 case 'c':
4675 start_commit = optarg;
4676 break;
4677 case 'd':
4678 show_diffstat = 1;
4679 break;
4680 case 'l':
4681 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4682 if (errstr != NULL)
4683 errx(1, "number of commits is %s: %s",
4684 errstr, optarg);
4685 break;
4686 case 'P':
4687 show_changed_paths = 1;
4688 break;
4689 case 'p':
4690 show_patch = 1;
4691 break;
4692 case 'R':
4693 reverse_display_order = 1;
4694 break;
4695 case 'r':
4696 repo_path = realpath(optarg, NULL);
4697 if (repo_path == NULL)
4698 return got_error_from_errno2("realpath",
4699 optarg);
4700 got_path_strip_trailing_slashes(repo_path);
4701 break;
4702 case 'S':
4703 search_pattern = optarg;
4704 break;
4705 case 's':
4706 one_line = 1;
4707 break;
4708 case 'x':
4709 end_commit = optarg;
4710 break;
4711 default:
4712 usage_log();
4713 /* NOTREACHED */
4717 argc -= optind;
4718 argv += optind;
4720 if (diff_context == -1)
4721 diff_context = 3;
4722 else if (!show_patch)
4723 errx(1, "-C requires -p");
4725 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4726 errx(1, "cannot use -s with -d, -p or -P");
4728 cwd = getcwd(NULL, 0);
4729 if (cwd == NULL) {
4730 error = got_error_from_errno("getcwd");
4731 goto done;
4734 error = got_repo_pack_fds_open(&pack_fds);
4735 if (error != NULL)
4736 goto done;
4738 if (repo_path == NULL) {
4739 error = got_worktree_open(&worktree, cwd,
4740 GOT_WORKTREE_GOT_DIR);
4741 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4742 goto done;
4743 error = NULL;
4746 if (argc == 1) {
4747 if (worktree) {
4748 error = got_worktree_resolve_path(&path, worktree,
4749 argv[0]);
4750 if (error)
4751 goto done;
4752 } else {
4753 path = strdup(argv[0]);
4754 if (path == NULL) {
4755 error = got_error_from_errno("strdup");
4756 goto done;
4759 } else if (argc != 0)
4760 usage_log();
4762 if (repo_path == NULL) {
4763 repo_path = worktree ?
4764 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4766 if (repo_path == NULL) {
4767 error = got_error_from_errno("strdup");
4768 goto done;
4771 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4772 if (error != NULL)
4773 goto done;
4775 error = apply_unveil(got_repo_get_path(repo), 1,
4776 worktree ? got_worktree_get_root_path(worktree) : NULL);
4777 if (error)
4778 goto done;
4780 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4781 if (error)
4782 goto done;
4784 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4785 if (error)
4786 goto done;
4788 if (start_commit == NULL) {
4789 struct got_reference *head_ref;
4790 struct got_commit_object *commit = NULL;
4791 error = got_ref_open(&head_ref, repo,
4792 worktree ? got_worktree_get_head_ref_name(worktree)
4793 : GOT_REF_HEAD, 0);
4794 if (error != NULL)
4795 goto done;
4796 error = got_ref_resolve(&start_id, repo, head_ref);
4797 got_ref_close(head_ref);
4798 if (error != NULL)
4799 goto done;
4800 error = got_object_open_as_commit(&commit, repo,
4801 start_id);
4802 if (error != NULL)
4803 goto done;
4804 got_object_commit_close(commit);
4805 } else {
4806 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4807 repo, worktree);
4808 if (error != NULL)
4809 goto done;
4810 if (keyword_idstr != NULL)
4811 start_commit = keyword_idstr;
4813 error = got_repo_match_object_id(&start_id, NULL,
4814 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4815 if (error != NULL)
4816 goto done;
4818 if (end_commit != NULL) {
4819 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4820 repo, worktree);
4821 if (error != NULL)
4822 goto done;
4823 if (keyword_idstr != NULL)
4824 end_commit = keyword_idstr;
4826 error = got_repo_match_object_id(&end_id, NULL,
4827 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4828 if (error != NULL)
4829 goto done;
4832 if (worktree) {
4834 * If a path was specified on the command line it was resolved
4835 * to a path in the work tree above. Prepend the work tree's
4836 * path prefix to obtain the corresponding in-repository path.
4838 if (path) {
4839 const char *prefix;
4840 prefix = got_worktree_get_path_prefix(worktree);
4841 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4842 (path[0] != '\0') ? "/" : "", path) == -1) {
4843 error = got_error_from_errno("asprintf");
4844 goto done;
4847 } else
4848 error = got_repo_map_path(&in_repo_path, repo,
4849 path ? path : "");
4850 if (error != NULL)
4851 goto done;
4852 if (in_repo_path) {
4853 free(path);
4854 path = in_repo_path;
4857 if (worktree) {
4858 /* Release work tree lock. */
4859 got_worktree_close(worktree);
4860 worktree = NULL;
4863 if (search_pattern && show_patch) {
4864 tmpfile = got_opentemp();
4865 if (tmpfile == NULL) {
4866 error = got_error_from_errno("got_opentemp");
4867 goto done;
4871 error = print_commits(start_id, end_id, repo, path ? path : "",
4872 show_changed_paths, show_diffstat, show_patch, search_pattern,
4873 diff_context, limit, log_branches, reverse_display_order,
4874 refs_idmap, one_line, tmpfile);
4875 done:
4876 free(path);
4877 free(repo_path);
4878 free(cwd);
4879 free(start_id);
4880 free(end_id);
4881 free(keyword_idstr);
4882 if (worktree)
4883 got_worktree_close(worktree);
4884 if (repo) {
4885 const struct got_error *close_err = got_repo_close(repo);
4886 if (error == NULL)
4887 error = close_err;
4889 if (pack_fds) {
4890 const struct got_error *pack_err =
4891 got_repo_pack_fds_close(pack_fds);
4892 if (error == NULL)
4893 error = pack_err;
4895 if (refs_idmap)
4896 got_reflist_object_id_map_free(refs_idmap);
4897 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4898 error = got_error_from_errno("fclose");
4899 got_ref_list_free(&refs);
4900 return error;
4903 __dead static void
4904 usage_diff(void)
4906 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4907 "[-r repository-path] [object1 object2 | path ...]\n",
4908 getprogname());
4909 exit(1);
4912 struct print_diff_arg {
4913 struct got_repository *repo;
4914 struct got_worktree *worktree;
4915 struct got_diffstat_cb_arg *diffstat;
4916 int diff_context;
4917 const char *id_str;
4918 int header_shown;
4919 int diff_staged;
4920 enum got_diff_algorithm diff_algo;
4921 int ignore_whitespace;
4922 int force_text_diff;
4923 FILE *f1;
4924 FILE *f2;
4925 FILE *outfile;
4929 * Create a file which contains the target path of a symlink so we can feed
4930 * it as content to the diff engine.
4932 static const struct got_error *
4933 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4934 const char *abspath)
4936 const struct got_error *err = NULL;
4937 char target_path[PATH_MAX];
4938 ssize_t target_len, outlen;
4940 *fd = -1;
4942 if (dirfd != -1) {
4943 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4944 if (target_len == -1)
4945 return got_error_from_errno2("readlinkat", abspath);
4946 } else {
4947 target_len = readlink(abspath, target_path, PATH_MAX);
4948 if (target_len == -1)
4949 return got_error_from_errno2("readlink", abspath);
4952 *fd = got_opentempfd();
4953 if (*fd == -1)
4954 return got_error_from_errno("got_opentempfd");
4956 outlen = write(*fd, target_path, target_len);
4957 if (outlen == -1) {
4958 err = got_error_from_errno("got_opentempfd");
4959 goto done;
4962 if (lseek(*fd, 0, SEEK_SET) == -1) {
4963 err = got_error_from_errno2("lseek", abspath);
4964 goto done;
4966 done:
4967 if (err) {
4968 close(*fd);
4969 *fd = -1;
4971 return err;
4974 static const struct got_error *
4975 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4976 const char *path, struct got_object_id *blob_id,
4977 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4978 int dirfd, const char *de_name)
4980 struct print_diff_arg *a = arg;
4981 const struct got_error *err = NULL;
4982 struct got_blob_object *blob1 = NULL;
4983 int fd = -1, fd1 = -1, fd2 = -1;
4984 FILE *f2 = NULL;
4985 char *abspath = NULL, *label1 = NULL;
4986 struct stat sb;
4987 off_t size1 = 0;
4988 int f2_exists = 0;
4990 memset(&sb, 0, sizeof(sb));
4992 if (a->diff_staged) {
4993 if (staged_status != GOT_STATUS_MODIFY &&
4994 staged_status != GOT_STATUS_ADD &&
4995 staged_status != GOT_STATUS_DELETE)
4996 return NULL;
4997 } else {
4998 if (staged_status == GOT_STATUS_DELETE)
4999 return NULL;
5000 if (status == GOT_STATUS_NONEXISTENT)
5001 return got_error_set_errno(ENOENT, path);
5002 if (status != GOT_STATUS_MODIFY &&
5003 status != GOT_STATUS_ADD &&
5004 status != GOT_STATUS_DELETE &&
5005 status != GOT_STATUS_CONFLICT)
5006 return NULL;
5009 err = got_opentemp_truncate(a->f1);
5010 if (err)
5011 return got_error_from_errno("got_opentemp_truncate");
5012 err = got_opentemp_truncate(a->f2);
5013 if (err)
5014 return got_error_from_errno("got_opentemp_truncate");
5016 if (!a->header_shown) {
5017 if (fprintf(a->outfile, "diff %s%s\n",
5018 a->diff_staged ? "-s " : "",
5019 got_worktree_get_root_path(a->worktree)) < 0) {
5020 err = got_error_from_errno("fprintf");
5021 goto done;
5023 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5024 err = got_error_from_errno("fprintf");
5025 goto done;
5027 if (fprintf(a->outfile, "path + %s%s\n",
5028 got_worktree_get_root_path(a->worktree),
5029 a->diff_staged ? " (staged changes)" : "") < 0) {
5030 err = got_error_from_errno("fprintf");
5031 goto done;
5033 a->header_shown = 1;
5036 if (a->diff_staged) {
5037 const char *label1 = NULL, *label2 = NULL;
5038 switch (staged_status) {
5039 case GOT_STATUS_MODIFY:
5040 label1 = path;
5041 label2 = path;
5042 break;
5043 case GOT_STATUS_ADD:
5044 label2 = path;
5045 break;
5046 case GOT_STATUS_DELETE:
5047 label1 = path;
5048 break;
5049 default:
5050 return got_error(GOT_ERR_FILE_STATUS);
5052 fd1 = got_opentempfd();
5053 if (fd1 == -1) {
5054 err = got_error_from_errno("got_opentempfd");
5055 goto done;
5057 fd2 = got_opentempfd();
5058 if (fd2 == -1) {
5059 err = got_error_from_errno("got_opentempfd");
5060 goto done;
5062 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5063 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5064 a->diff_algo, a->diff_context, a->ignore_whitespace,
5065 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5066 goto done;
5069 fd1 = got_opentempfd();
5070 if (fd1 == -1) {
5071 err = got_error_from_errno("got_opentempfd");
5072 goto done;
5075 if (staged_status == GOT_STATUS_ADD ||
5076 staged_status == GOT_STATUS_MODIFY) {
5077 char *id_str;
5078 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5079 8192, fd1);
5080 if (err)
5081 goto done;
5082 err = got_object_id_str(&id_str, staged_blob_id);
5083 if (err)
5084 goto done;
5085 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5086 err = got_error_from_errno("asprintf");
5087 free(id_str);
5088 goto done;
5090 free(id_str);
5091 } else if (status != GOT_STATUS_ADD) {
5092 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5093 fd1);
5094 if (err)
5095 goto done;
5098 if (status != GOT_STATUS_DELETE) {
5099 if (asprintf(&abspath, "%s/%s",
5100 got_worktree_get_root_path(a->worktree), path) == -1) {
5101 err = got_error_from_errno("asprintf");
5102 goto done;
5105 if (dirfd != -1) {
5106 fd = openat(dirfd, de_name,
5107 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5108 if (fd == -1) {
5109 if (!got_err_open_nofollow_on_symlink()) {
5110 err = got_error_from_errno2("openat",
5111 abspath);
5112 goto done;
5114 err = get_symlink_target_file(&fd, dirfd,
5115 de_name, abspath);
5116 if (err)
5117 goto done;
5119 } else {
5120 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5121 if (fd == -1) {
5122 if (!got_err_open_nofollow_on_symlink()) {
5123 err = got_error_from_errno2("open",
5124 abspath);
5125 goto done;
5127 err = get_symlink_target_file(&fd, dirfd,
5128 de_name, abspath);
5129 if (err)
5130 goto done;
5133 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5134 err = got_error_from_errno2("fstatat", abspath);
5135 goto done;
5137 f2 = fdopen(fd, "r");
5138 if (f2 == NULL) {
5139 err = got_error_from_errno2("fdopen", abspath);
5140 goto done;
5142 fd = -1;
5143 f2_exists = 1;
5146 if (blob1) {
5147 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5148 a->f1, blob1);
5149 if (err)
5150 goto done;
5153 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5154 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5155 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5156 done:
5157 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5158 err = got_error_from_errno("close");
5159 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5160 err = got_error_from_errno("close");
5161 if (blob1)
5162 got_object_blob_close(blob1);
5163 if (fd != -1 && close(fd) == -1 && err == NULL)
5164 err = got_error_from_errno("close");
5165 if (f2 && fclose(f2) == EOF && err == NULL)
5166 err = got_error_from_errno("fclose");
5167 free(abspath);
5168 return err;
5171 static const struct got_error *
5172 cmd_diff(int argc, char *argv[])
5174 const struct got_error *error;
5175 struct got_repository *repo = NULL;
5176 struct got_worktree *worktree = NULL;
5177 char *cwd = NULL, *repo_path = NULL;
5178 const char *commit_args[2] = { NULL, NULL };
5179 int ncommit_args = 0;
5180 struct got_object_id *ids[2] = { NULL, NULL };
5181 char *labels[2] = { NULL, NULL };
5182 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5183 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5184 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5185 const char *errstr;
5186 struct got_reflist_head refs;
5187 struct got_pathlist_head diffstat_paths, paths;
5188 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5189 int fd1 = -1, fd2 = -1;
5190 int *pack_fds = NULL;
5191 struct got_diffstat_cb_arg dsa;
5193 memset(&dsa, 0, sizeof(dsa));
5195 TAILQ_INIT(&refs);
5196 TAILQ_INIT(&paths);
5197 TAILQ_INIT(&diffstat_paths);
5199 #ifndef PROFILE
5200 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5201 NULL) == -1)
5202 err(1, "pledge");
5203 #endif
5205 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5206 switch (ch) {
5207 case 'a':
5208 force_text_diff = 1;
5209 break;
5210 case 'C':
5211 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5212 &errstr);
5213 if (errstr != NULL)
5214 errx(1, "number of context lines is %s: %s",
5215 errstr, optarg);
5216 break;
5217 case 'c':
5218 if (ncommit_args >= 2)
5219 errx(1, "too many -c options used");
5220 commit_args[ncommit_args++] = optarg;
5221 break;
5222 case 'd':
5223 show_diffstat = 1;
5224 break;
5225 case 'P':
5226 force_path = 1;
5227 break;
5228 case 'r':
5229 repo_path = realpath(optarg, NULL);
5230 if (repo_path == NULL)
5231 return got_error_from_errno2("realpath",
5232 optarg);
5233 got_path_strip_trailing_slashes(repo_path);
5234 rflag = 1;
5235 break;
5236 case 's':
5237 diff_staged = 1;
5238 break;
5239 case 'w':
5240 ignore_whitespace = 1;
5241 break;
5242 default:
5243 usage_diff();
5244 /* NOTREACHED */
5248 argc -= optind;
5249 argv += optind;
5251 cwd = getcwd(NULL, 0);
5252 if (cwd == NULL) {
5253 error = got_error_from_errno("getcwd");
5254 goto done;
5257 error = got_repo_pack_fds_open(&pack_fds);
5258 if (error != NULL)
5259 goto done;
5261 if (repo_path == NULL) {
5262 error = got_worktree_open(&worktree, cwd,
5263 GOT_WORKTREE_GOT_DIR);
5264 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5265 goto done;
5266 else
5267 error = NULL;
5268 if (worktree) {
5269 repo_path =
5270 strdup(got_worktree_get_repo_path(worktree));
5271 if (repo_path == NULL) {
5272 error = got_error_from_errno("strdup");
5273 goto done;
5275 } else {
5276 repo_path = strdup(cwd);
5277 if (repo_path == NULL) {
5278 error = got_error_from_errno("strdup");
5279 goto done;
5284 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5285 free(repo_path);
5286 if (error != NULL)
5287 goto done;
5289 if (show_diffstat) {
5290 dsa.paths = &diffstat_paths;
5291 dsa.force_text = force_text_diff;
5292 dsa.ignore_ws = ignore_whitespace;
5293 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5296 if (rflag || worktree == NULL || ncommit_args > 0) {
5297 if (force_path) {
5298 error = got_error_msg(GOT_ERR_NOT_IMPL,
5299 "-P option can only be used when diffing "
5300 "a work tree");
5301 goto done;
5303 if (diff_staged) {
5304 error = got_error_msg(GOT_ERR_NOT_IMPL,
5305 "-s option can only be used when diffing "
5306 "a work tree");
5307 goto done;
5311 error = apply_unveil(got_repo_get_path(repo), 1,
5312 worktree ? got_worktree_get_root_path(worktree) : NULL);
5313 if (error)
5314 goto done;
5316 if ((!force_path && argc == 2) || ncommit_args > 0) {
5317 int obj_type = (ncommit_args > 0 ?
5318 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5319 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5320 NULL);
5321 if (error)
5322 goto done;
5323 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5324 const char *arg;
5325 char *keyword_idstr = NULL;
5327 if (ncommit_args > 0)
5328 arg = commit_args[i];
5329 else
5330 arg = argv[i];
5332 error = got_keyword_to_idstr(&keyword_idstr, arg,
5333 repo, worktree);
5334 if (error != NULL)
5335 goto done;
5336 if (keyword_idstr != NULL)
5337 arg = keyword_idstr;
5339 error = got_repo_match_object_id(&ids[i], &labels[i],
5340 arg, obj_type, &refs, repo);
5341 free(keyword_idstr);
5342 if (error) {
5343 if (error->code != GOT_ERR_NOT_REF &&
5344 error->code != GOT_ERR_NO_OBJ)
5345 goto done;
5346 if (ncommit_args > 0)
5347 goto done;
5348 error = NULL;
5349 break;
5354 f1 = got_opentemp();
5355 if (f1 == NULL) {
5356 error = got_error_from_errno("got_opentemp");
5357 goto done;
5360 f2 = got_opentemp();
5361 if (f2 == NULL) {
5362 error = got_error_from_errno("got_opentemp");
5363 goto done;
5366 outfile = got_opentemp();
5367 if (outfile == NULL) {
5368 error = got_error_from_errno("got_opentemp");
5369 goto done;
5372 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5373 struct print_diff_arg arg;
5374 char *id_str;
5376 if (worktree == NULL) {
5377 if (argc == 2 && ids[0] == NULL) {
5378 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5379 goto done;
5380 } else if (argc == 2 && ids[1] == NULL) {
5381 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5382 goto done;
5383 } else if (argc > 0) {
5384 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5385 "%s", "specified paths cannot be resolved");
5386 goto done;
5387 } else {
5388 error = got_error(GOT_ERR_NOT_WORKTREE);
5389 goto done;
5393 error = get_worktree_paths_from_argv(&paths, argc, argv,
5394 worktree);
5395 if (error)
5396 goto done;
5398 error = got_object_id_str(&id_str,
5399 got_worktree_get_base_commit_id(worktree));
5400 if (error)
5401 goto done;
5402 arg.repo = repo;
5403 arg.worktree = worktree;
5404 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5405 arg.diff_context = diff_context;
5406 arg.id_str = id_str;
5407 arg.header_shown = 0;
5408 arg.diff_staged = diff_staged;
5409 arg.ignore_whitespace = ignore_whitespace;
5410 arg.force_text_diff = force_text_diff;
5411 arg.diffstat = show_diffstat ? &dsa : NULL;
5412 arg.f1 = f1;
5413 arg.f2 = f2;
5414 arg.outfile = outfile;
5416 error = got_worktree_status(worktree, &paths, repo, 0,
5417 print_diff, &arg, check_cancelled, NULL);
5418 free(id_str);
5419 if (error)
5420 goto done;
5422 if (show_diffstat && dsa.nfiles > 0) {
5423 char *header;
5425 if (asprintf(&header, "diffstat %s%s",
5426 diff_staged ? "-s " : "",
5427 got_worktree_get_root_path(worktree)) == -1) {
5428 error = got_error_from_errno("asprintf");
5429 goto done;
5432 error = print_diffstat(&dsa, header);
5433 free(header);
5434 if (error)
5435 goto done;
5438 error = printfile(outfile);
5439 goto done;
5442 if (ncommit_args == 1) {
5443 struct got_commit_object *commit;
5444 error = got_object_open_as_commit(&commit, repo, ids[0]);
5445 if (error)
5446 goto done;
5448 labels[1] = labels[0];
5449 ids[1] = ids[0];
5450 if (got_object_commit_get_nparents(commit) > 0) {
5451 const struct got_object_id_queue *pids;
5452 struct got_object_qid *pid;
5453 pids = got_object_commit_get_parent_ids(commit);
5454 pid = STAILQ_FIRST(pids);
5455 ids[0] = got_object_id_dup(&pid->id);
5456 if (ids[0] == NULL) {
5457 error = got_error_from_errno(
5458 "got_object_id_dup");
5459 got_object_commit_close(commit);
5460 goto done;
5462 error = got_object_id_str(&labels[0], ids[0]);
5463 if (error) {
5464 got_object_commit_close(commit);
5465 goto done;
5467 } else {
5468 ids[0] = NULL;
5469 labels[0] = strdup("/dev/null");
5470 if (labels[0] == NULL) {
5471 error = got_error_from_errno("strdup");
5472 got_object_commit_close(commit);
5473 goto done;
5477 got_object_commit_close(commit);
5480 if (ncommit_args == 0 && argc > 2) {
5481 error = got_error_msg(GOT_ERR_BAD_PATH,
5482 "path arguments cannot be used when diffing two objects");
5483 goto done;
5486 if (ids[0]) {
5487 error = got_object_get_type(&type1, repo, ids[0]);
5488 if (error)
5489 goto done;
5492 error = got_object_get_type(&type2, repo, ids[1]);
5493 if (error)
5494 goto done;
5495 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5496 error = got_error(GOT_ERR_OBJ_TYPE);
5497 goto done;
5499 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5500 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5501 "path arguments cannot be used when diffing blobs");
5502 goto done;
5505 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5506 char *in_repo_path;
5507 struct got_pathlist_entry *new;
5508 if (worktree) {
5509 const char *prefix;
5510 char *p;
5511 error = got_worktree_resolve_path(&p, worktree,
5512 argv[i]);
5513 if (error)
5514 goto done;
5515 prefix = got_worktree_get_path_prefix(worktree);
5516 while (prefix[0] == '/')
5517 prefix++;
5518 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5519 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5520 p) == -1) {
5521 error = got_error_from_errno("asprintf");
5522 free(p);
5523 goto done;
5525 free(p);
5526 } else {
5527 char *mapped_path, *s;
5528 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5529 if (error)
5530 goto done;
5531 s = mapped_path;
5532 while (s[0] == '/')
5533 s++;
5534 in_repo_path = strdup(s);
5535 if (in_repo_path == NULL) {
5536 error = got_error_from_errno("asprintf");
5537 free(mapped_path);
5538 goto done;
5540 free(mapped_path);
5543 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5544 if (error || new == NULL /* duplicate */)
5545 free(in_repo_path);
5546 if (error)
5547 goto done;
5550 if (worktree) {
5551 /* Release work tree lock. */
5552 got_worktree_close(worktree);
5553 worktree = NULL;
5556 fd1 = got_opentempfd();
5557 if (fd1 == -1) {
5558 error = got_error_from_errno("got_opentempfd");
5559 goto done;
5562 fd2 = got_opentempfd();
5563 if (fd2 == -1) {
5564 error = got_error_from_errno("got_opentempfd");
5565 goto done;
5568 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5569 case GOT_OBJ_TYPE_BLOB:
5570 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5571 fd1, fd2, ids[0], ids[1], NULL, NULL,
5572 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5573 ignore_whitespace, force_text_diff,
5574 show_diffstat ? &dsa : NULL, repo, outfile);
5575 break;
5576 case GOT_OBJ_TYPE_TREE:
5577 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5578 ids[0], ids[1], &paths, "", "",
5579 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5580 ignore_whitespace, force_text_diff,
5581 show_diffstat ? &dsa : NULL, repo, outfile);
5582 break;
5583 case GOT_OBJ_TYPE_COMMIT:
5584 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5585 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5586 fd1, fd2, ids[0], ids[1], &paths,
5587 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5588 ignore_whitespace, force_text_diff,
5589 show_diffstat ? &dsa : NULL, repo, outfile);
5590 break;
5591 default:
5592 error = got_error(GOT_ERR_OBJ_TYPE);
5594 if (error)
5595 goto done;
5597 if (show_diffstat && dsa.nfiles > 0) {
5598 char *header = NULL;
5600 if (asprintf(&header, "diffstat %s %s",
5601 labels[0], labels[1]) == -1) {
5602 error = got_error_from_errno("asprintf");
5603 goto done;
5606 error = print_diffstat(&dsa, header);
5607 free(header);
5608 if (error)
5609 goto done;
5612 error = printfile(outfile);
5614 done:
5615 free(labels[0]);
5616 free(labels[1]);
5617 free(ids[0]);
5618 free(ids[1]);
5619 if (worktree)
5620 got_worktree_close(worktree);
5621 if (repo) {
5622 const struct got_error *close_err = got_repo_close(repo);
5623 if (error == NULL)
5624 error = close_err;
5626 if (pack_fds) {
5627 const struct got_error *pack_err =
5628 got_repo_pack_fds_close(pack_fds);
5629 if (error == NULL)
5630 error = pack_err;
5632 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5633 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5634 got_ref_list_free(&refs);
5635 if (outfile && fclose(outfile) == EOF && error == NULL)
5636 error = got_error_from_errno("fclose");
5637 if (f1 && fclose(f1) == EOF && error == NULL)
5638 error = got_error_from_errno("fclose");
5639 if (f2 && fclose(f2) == EOF && error == NULL)
5640 error = got_error_from_errno("fclose");
5641 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5642 error = got_error_from_errno("close");
5643 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5644 error = got_error_from_errno("close");
5645 return error;
5648 __dead static void
5649 usage_blame(void)
5651 fprintf(stderr,
5652 "usage: %s blame [-c commit] [-r repository-path] path\n",
5653 getprogname());
5654 exit(1);
5657 struct blame_line {
5658 int annotated;
5659 char *id_str;
5660 char *committer;
5661 char datebuf[11]; /* YYYY-MM-DD + NUL */
5664 struct blame_cb_args {
5665 struct blame_line *lines;
5666 int nlines;
5667 int nlines_prec;
5668 int lineno_cur;
5669 off_t *line_offsets;
5670 FILE *f;
5671 struct got_repository *repo;
5674 static const struct got_error *
5675 blame_cb(void *arg, int nlines, int lineno,
5676 struct got_commit_object *commit, struct got_object_id *id)
5678 const struct got_error *err = NULL;
5679 struct blame_cb_args *a = arg;
5680 struct blame_line *bline;
5681 char *line = NULL;
5682 size_t linesize = 0;
5683 off_t offset;
5684 struct tm tm;
5685 time_t committer_time;
5687 if (nlines != a->nlines ||
5688 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5689 return got_error(GOT_ERR_RANGE);
5691 if (sigint_received)
5692 return got_error(GOT_ERR_ITER_COMPLETED);
5694 if (lineno == -1)
5695 return NULL; /* no change in this commit */
5697 /* Annotate this line. */
5698 bline = &a->lines[lineno - 1];
5699 if (bline->annotated)
5700 return NULL;
5701 err = got_object_id_str(&bline->id_str, id);
5702 if (err)
5703 return err;
5705 bline->committer = strdup(got_object_commit_get_committer(commit));
5706 if (bline->committer == NULL) {
5707 err = got_error_from_errno("strdup");
5708 goto done;
5711 committer_time = got_object_commit_get_committer_time(commit);
5712 if (gmtime_r(&committer_time, &tm) == NULL)
5713 return got_error_from_errno("gmtime_r");
5714 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5715 &tm) == 0) {
5716 err = got_error(GOT_ERR_NO_SPACE);
5717 goto done;
5719 bline->annotated = 1;
5721 /* Print lines annotated so far. */
5722 bline = &a->lines[a->lineno_cur - 1];
5723 if (!bline->annotated)
5724 goto done;
5726 offset = a->line_offsets[a->lineno_cur - 1];
5727 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5728 err = got_error_from_errno("fseeko");
5729 goto done;
5732 while (a->lineno_cur <= a->nlines && bline->annotated) {
5733 char *smallerthan, *at, *nl, *committer;
5734 size_t len;
5736 if (getline(&line, &linesize, a->f) == -1) {
5737 if (ferror(a->f))
5738 err = got_error_from_errno("getline");
5739 break;
5742 committer = bline->committer;
5743 smallerthan = strchr(committer, '<');
5744 if (smallerthan && smallerthan[1] != '\0')
5745 committer = smallerthan + 1;
5746 at = strchr(committer, '@');
5747 if (at)
5748 *at = '\0';
5749 len = strlen(committer);
5750 if (len >= 9)
5751 committer[8] = '\0';
5753 nl = strchr(line, '\n');
5754 if (nl)
5755 *nl = '\0';
5756 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5757 bline->id_str, bline->datebuf, committer, line);
5759 a->lineno_cur++;
5760 bline = &a->lines[a->lineno_cur - 1];
5762 done:
5763 free(line);
5764 return err;
5767 static const struct got_error *
5768 cmd_blame(int argc, char *argv[])
5770 const struct got_error *error;
5771 struct got_repository *repo = NULL;
5772 struct got_worktree *worktree = NULL;
5773 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5774 char *link_target = NULL;
5775 struct got_object_id *obj_id = NULL;
5776 struct got_object_id *commit_id = NULL;
5777 struct got_commit_object *commit = NULL;
5778 struct got_blob_object *blob = NULL;
5779 char *commit_id_str = NULL, *keyword_idstr = NULL;
5780 struct blame_cb_args bca;
5781 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5782 off_t filesize;
5783 int *pack_fds = NULL;
5784 FILE *f1 = NULL, *f2 = NULL;
5786 fd1 = got_opentempfd();
5787 if (fd1 == -1)
5788 return got_error_from_errno("got_opentempfd");
5790 memset(&bca, 0, sizeof(bca));
5792 #ifndef PROFILE
5793 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5794 NULL) == -1)
5795 err(1, "pledge");
5796 #endif
5798 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5799 switch (ch) {
5800 case 'c':
5801 commit_id_str = optarg;
5802 break;
5803 case 'r':
5804 repo_path = realpath(optarg, NULL);
5805 if (repo_path == NULL)
5806 return got_error_from_errno2("realpath",
5807 optarg);
5808 got_path_strip_trailing_slashes(repo_path);
5809 break;
5810 default:
5811 usage_blame();
5812 /* NOTREACHED */
5816 argc -= optind;
5817 argv += optind;
5819 if (argc == 1)
5820 path = argv[0];
5821 else
5822 usage_blame();
5824 cwd = getcwd(NULL, 0);
5825 if (cwd == NULL) {
5826 error = got_error_from_errno("getcwd");
5827 goto done;
5830 error = got_repo_pack_fds_open(&pack_fds);
5831 if (error != NULL)
5832 goto done;
5834 if (repo_path == NULL) {
5835 error = got_worktree_open(&worktree, cwd,
5836 GOT_WORKTREE_GOT_DIR);
5837 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5838 goto done;
5839 else
5840 error = NULL;
5841 if (worktree) {
5842 repo_path =
5843 strdup(got_worktree_get_repo_path(worktree));
5844 if (repo_path == NULL) {
5845 error = got_error_from_errno("strdup");
5846 if (error)
5847 goto done;
5849 } else {
5850 repo_path = strdup(cwd);
5851 if (repo_path == NULL) {
5852 error = got_error_from_errno("strdup");
5853 goto done;
5858 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5859 if (error != NULL)
5860 goto done;
5862 if (worktree) {
5863 const char *prefix = got_worktree_get_path_prefix(worktree);
5864 char *p;
5866 error = got_worktree_resolve_path(&p, worktree, path);
5867 if (error)
5868 goto done;
5869 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5870 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5871 p) == -1) {
5872 error = got_error_from_errno("asprintf");
5873 free(p);
5874 goto done;
5876 free(p);
5877 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5878 } else {
5879 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5880 if (error)
5881 goto done;
5882 error = got_repo_map_path(&in_repo_path, repo, path);
5884 if (error)
5885 goto done;
5887 if (commit_id_str == NULL) {
5888 struct got_reference *head_ref;
5889 error = got_ref_open(&head_ref, repo, worktree ?
5890 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5891 if (error != NULL)
5892 goto done;
5893 error = got_ref_resolve(&commit_id, repo, head_ref);
5894 got_ref_close(head_ref);
5895 if (error != NULL)
5896 goto done;
5897 } else {
5898 struct got_reflist_head refs;
5900 TAILQ_INIT(&refs);
5901 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5902 NULL);
5903 if (error)
5904 goto done;
5906 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5907 repo, worktree);
5908 if (error != NULL)
5909 goto done;
5910 if (keyword_idstr != NULL)
5911 commit_id_str = keyword_idstr;
5913 error = got_repo_match_object_id(&commit_id, NULL,
5914 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5915 got_ref_list_free(&refs);
5916 if (error)
5917 goto done;
5920 if (worktree) {
5921 /* Release work tree lock. */
5922 got_worktree_close(worktree);
5923 worktree = NULL;
5926 error = got_object_open_as_commit(&commit, repo, commit_id);
5927 if (error)
5928 goto done;
5930 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5931 commit, repo);
5932 if (error)
5933 goto done;
5935 error = got_object_id_by_path(&obj_id, repo, commit,
5936 link_target ? link_target : in_repo_path);
5937 if (error)
5938 goto done;
5940 error = got_object_get_type(&obj_type, repo, obj_id);
5941 if (error)
5942 goto done;
5944 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5945 error = got_error_path(link_target ? link_target : in_repo_path,
5946 GOT_ERR_OBJ_TYPE);
5947 goto done;
5950 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5951 if (error)
5952 goto done;
5953 bca.f = got_opentemp();
5954 if (bca.f == NULL) {
5955 error = got_error_from_errno("got_opentemp");
5956 goto done;
5958 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5959 &bca.line_offsets, bca.f, blob);
5960 if (error || bca.nlines == 0)
5961 goto done;
5963 /* Don't include \n at EOF in the blame line count. */
5964 if (bca.line_offsets[bca.nlines - 1] == filesize)
5965 bca.nlines--;
5967 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5968 if (bca.lines == NULL) {
5969 error = got_error_from_errno("calloc");
5970 goto done;
5972 bca.lineno_cur = 1;
5973 bca.nlines_prec = 0;
5974 i = bca.nlines;
5975 while (i > 0) {
5976 i /= 10;
5977 bca.nlines_prec++;
5979 bca.repo = repo;
5981 fd2 = got_opentempfd();
5982 if (fd2 == -1) {
5983 error = got_error_from_errno("got_opentempfd");
5984 goto done;
5986 fd3 = got_opentempfd();
5987 if (fd3 == -1) {
5988 error = got_error_from_errno("got_opentempfd");
5989 goto done;
5991 f1 = got_opentemp();
5992 if (f1 == NULL) {
5993 error = got_error_from_errno("got_opentemp");
5994 goto done;
5996 f2 = got_opentemp();
5997 if (f2 == NULL) {
5998 error = got_error_from_errno("got_opentemp");
5999 goto done;
6001 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6002 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6003 check_cancelled, NULL, fd2, fd3, f1, f2);
6004 done:
6005 free(keyword_idstr);
6006 free(in_repo_path);
6007 free(link_target);
6008 free(repo_path);
6009 free(cwd);
6010 free(commit_id);
6011 free(obj_id);
6012 if (commit)
6013 got_object_commit_close(commit);
6015 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6016 error = got_error_from_errno("close");
6017 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6018 error = got_error_from_errno("close");
6019 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6020 error = got_error_from_errno("close");
6021 if (f1 && fclose(f1) == EOF && error == NULL)
6022 error = got_error_from_errno("fclose");
6023 if (f2 && fclose(f2) == EOF && error == NULL)
6024 error = got_error_from_errno("fclose");
6026 if (blob)
6027 got_object_blob_close(blob);
6028 if (worktree)
6029 got_worktree_close(worktree);
6030 if (repo) {
6031 const struct got_error *close_err = got_repo_close(repo);
6032 if (error == NULL)
6033 error = close_err;
6035 if (pack_fds) {
6036 const struct got_error *pack_err =
6037 got_repo_pack_fds_close(pack_fds);
6038 if (error == NULL)
6039 error = pack_err;
6041 if (bca.lines) {
6042 for (i = 0; i < bca.nlines; i++) {
6043 struct blame_line *bline = &bca.lines[i];
6044 free(bline->id_str);
6045 free(bline->committer);
6047 free(bca.lines);
6049 free(bca.line_offsets);
6050 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6051 error = got_error_from_errno("fclose");
6052 return error;
6055 __dead static void
6056 usage_tree(void)
6058 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6059 "[path]\n", getprogname());
6060 exit(1);
6063 static const struct got_error *
6064 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6065 const char *root_path, struct got_repository *repo)
6067 const struct got_error *err = NULL;
6068 int is_root_path = (strcmp(path, root_path) == 0);
6069 const char *modestr = "";
6070 mode_t mode = got_tree_entry_get_mode(te);
6071 char *link_target = NULL;
6073 path += strlen(root_path);
6074 while (path[0] == '/')
6075 path++;
6077 if (got_object_tree_entry_is_submodule(te))
6078 modestr = "$";
6079 else if (S_ISLNK(mode)) {
6080 int i;
6082 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6083 if (err)
6084 return err;
6085 for (i = 0; link_target[i] != '\0'; i++) {
6086 if (!isprint((unsigned char)link_target[i]))
6087 link_target[i] = '?';
6090 modestr = "@";
6092 else if (S_ISDIR(mode))
6093 modestr = "/";
6094 else if (mode & S_IXUSR)
6095 modestr = "*";
6097 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6098 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6099 link_target ? " -> ": "", link_target ? link_target : "");
6101 free(link_target);
6102 return NULL;
6105 static const struct got_error *
6106 print_tree(const char *path, struct got_commit_object *commit,
6107 int show_ids, int recurse, const char *root_path,
6108 struct got_repository *repo)
6110 const struct got_error *err = NULL;
6111 struct got_object_id *tree_id = NULL;
6112 struct got_tree_object *tree = NULL;
6113 int nentries, i;
6115 err = got_object_id_by_path(&tree_id, repo, commit, path);
6116 if (err)
6117 goto done;
6119 err = got_object_open_as_tree(&tree, repo, tree_id);
6120 if (err)
6121 goto done;
6122 nentries = got_object_tree_get_nentries(tree);
6123 for (i = 0; i < nentries; i++) {
6124 struct got_tree_entry *te;
6125 char *id = NULL;
6127 if (sigint_received || sigpipe_received)
6128 break;
6130 te = got_object_tree_get_entry(tree, i);
6131 if (show_ids) {
6132 char *id_str;
6133 err = got_object_id_str(&id_str,
6134 got_tree_entry_get_id(te));
6135 if (err)
6136 goto done;
6137 if (asprintf(&id, "%s ", id_str) == -1) {
6138 err = got_error_from_errno("asprintf");
6139 free(id_str);
6140 goto done;
6142 free(id_str);
6144 err = print_entry(te, id, path, root_path, repo);
6145 free(id);
6146 if (err)
6147 goto done;
6149 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6150 char *child_path;
6151 if (asprintf(&child_path, "%s%s%s", path,
6152 path[0] == '/' && path[1] == '\0' ? "" : "/",
6153 got_tree_entry_get_name(te)) == -1) {
6154 err = got_error_from_errno("asprintf");
6155 goto done;
6157 err = print_tree(child_path, commit, show_ids, 1,
6158 root_path, repo);
6159 free(child_path);
6160 if (err)
6161 goto done;
6164 done:
6165 if (tree)
6166 got_object_tree_close(tree);
6167 free(tree_id);
6168 return err;
6171 static const struct got_error *
6172 cmd_tree(int argc, char *argv[])
6174 const struct got_error *error;
6175 struct got_repository *repo = NULL;
6176 struct got_worktree *worktree = NULL;
6177 const char *path, *refname = NULL;
6178 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6179 struct got_object_id *commit_id = NULL;
6180 struct got_commit_object *commit = NULL;
6181 char *commit_id_str = NULL, *keyword_idstr = NULL;
6182 int show_ids = 0, recurse = 0;
6183 int ch;
6184 int *pack_fds = NULL;
6186 #ifndef PROFILE
6187 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6188 NULL) == -1)
6189 err(1, "pledge");
6190 #endif
6192 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6193 switch (ch) {
6194 case 'c':
6195 commit_id_str = optarg;
6196 break;
6197 case 'i':
6198 show_ids = 1;
6199 break;
6200 case 'R':
6201 recurse = 1;
6202 break;
6203 case 'r':
6204 repo_path = realpath(optarg, NULL);
6205 if (repo_path == NULL)
6206 return got_error_from_errno2("realpath",
6207 optarg);
6208 got_path_strip_trailing_slashes(repo_path);
6209 break;
6210 default:
6211 usage_tree();
6212 /* NOTREACHED */
6216 argc -= optind;
6217 argv += optind;
6219 if (argc == 1)
6220 path = argv[0];
6221 else if (argc > 1)
6222 usage_tree();
6223 else
6224 path = NULL;
6226 cwd = getcwd(NULL, 0);
6227 if (cwd == NULL) {
6228 error = got_error_from_errno("getcwd");
6229 goto done;
6232 error = got_repo_pack_fds_open(&pack_fds);
6233 if (error != NULL)
6234 goto done;
6236 if (repo_path == NULL) {
6237 error = got_worktree_open(&worktree, cwd,
6238 GOT_WORKTREE_GOT_DIR);
6239 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6240 goto done;
6241 else
6242 error = NULL;
6243 if (worktree) {
6244 repo_path =
6245 strdup(got_worktree_get_repo_path(worktree));
6246 if (repo_path == NULL)
6247 error = got_error_from_errno("strdup");
6248 if (error)
6249 goto done;
6250 } else {
6251 repo_path = strdup(cwd);
6252 if (repo_path == NULL) {
6253 error = got_error_from_errno("strdup");
6254 goto done;
6259 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6260 if (error != NULL)
6261 goto done;
6263 if (worktree) {
6264 const char *prefix = got_worktree_get_path_prefix(worktree);
6265 char *p;
6267 if (path == NULL || got_path_is_root_dir(path))
6268 path = "";
6269 error = got_worktree_resolve_path(&p, worktree, path);
6270 if (error)
6271 goto done;
6272 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6273 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6274 p) == -1) {
6275 error = got_error_from_errno("asprintf");
6276 free(p);
6277 goto done;
6279 free(p);
6280 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6281 if (error)
6282 goto done;
6283 } else {
6284 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6285 if (error)
6286 goto done;
6287 if (path == NULL)
6288 path = "/";
6289 error = got_repo_map_path(&in_repo_path, repo, path);
6290 if (error != NULL)
6291 goto done;
6294 if (commit_id_str == NULL) {
6295 struct got_reference *head_ref;
6296 if (worktree)
6297 refname = got_worktree_get_head_ref_name(worktree);
6298 else
6299 refname = GOT_REF_HEAD;
6300 error = got_ref_open(&head_ref, repo, refname, 0);
6301 if (error != NULL)
6302 goto done;
6303 error = got_ref_resolve(&commit_id, repo, head_ref);
6304 got_ref_close(head_ref);
6305 if (error != NULL)
6306 goto done;
6307 } else {
6308 struct got_reflist_head refs;
6310 TAILQ_INIT(&refs);
6311 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6312 NULL);
6313 if (error)
6314 goto done;
6316 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6317 repo, worktree);
6318 if (error != NULL)
6319 goto done;
6320 if (keyword_idstr != NULL)
6321 commit_id_str = keyword_idstr;
6323 error = got_repo_match_object_id(&commit_id, NULL,
6324 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6325 got_ref_list_free(&refs);
6326 if (error)
6327 goto done;
6330 if (worktree) {
6331 /* Release work tree lock. */
6332 got_worktree_close(worktree);
6333 worktree = NULL;
6336 error = got_object_open_as_commit(&commit, repo, commit_id);
6337 if (error)
6338 goto done;
6340 error = print_tree(in_repo_path, commit, show_ids, recurse,
6341 in_repo_path, repo);
6342 done:
6343 free(keyword_idstr);
6344 free(in_repo_path);
6345 free(repo_path);
6346 free(cwd);
6347 free(commit_id);
6348 if (commit)
6349 got_object_commit_close(commit);
6350 if (worktree)
6351 got_worktree_close(worktree);
6352 if (repo) {
6353 const struct got_error *close_err = got_repo_close(repo);
6354 if (error == NULL)
6355 error = close_err;
6357 if (pack_fds) {
6358 const struct got_error *pack_err =
6359 got_repo_pack_fds_close(pack_fds);
6360 if (error == NULL)
6361 error = pack_err;
6363 return error;
6366 __dead static void
6367 usage_status(void)
6369 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6370 "[-s status-codes] [path ...]\n", getprogname());
6371 exit(1);
6374 struct got_status_arg {
6375 char *status_codes;
6376 int suppress;
6379 static const struct got_error *
6380 print_status(void *arg, unsigned char status, unsigned char staged_status,
6381 const char *path, struct got_object_id *blob_id,
6382 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6383 int dirfd, const char *de_name)
6385 struct got_status_arg *st = arg;
6387 if (status == staged_status && (status == GOT_STATUS_DELETE))
6388 status = GOT_STATUS_NO_CHANGE;
6389 if (st != NULL && st->status_codes) {
6390 size_t ncodes = strlen(st->status_codes);
6391 int i, j = 0;
6393 for (i = 0; i < ncodes ; i++) {
6394 if (st->suppress) {
6395 if (status == st->status_codes[i] ||
6396 staged_status == st->status_codes[i]) {
6397 j++;
6398 continue;
6400 } else {
6401 if (status == st->status_codes[i] ||
6402 staged_status == st->status_codes[i])
6403 break;
6407 if (st->suppress && j == 0)
6408 goto print;
6410 if (i == ncodes)
6411 return NULL;
6413 print:
6414 printf("%c%c %s\n", status, staged_status, path);
6415 return NULL;
6418 static const struct got_error *
6419 cmd_status(int argc, char *argv[])
6421 const struct got_error *close_err, *error = NULL;
6422 struct got_repository *repo = NULL;
6423 struct got_worktree *worktree = NULL;
6424 struct got_status_arg st;
6425 char *cwd = NULL;
6426 struct got_pathlist_head paths;
6427 int ch, i, no_ignores = 0;
6428 int *pack_fds = NULL;
6430 TAILQ_INIT(&paths);
6432 memset(&st, 0, sizeof(st));
6433 st.status_codes = NULL;
6434 st.suppress = 0;
6436 #ifndef PROFILE
6437 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6438 NULL) == -1)
6439 err(1, "pledge");
6440 #endif
6442 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6443 switch (ch) {
6444 case 'I':
6445 no_ignores = 1;
6446 break;
6447 case 'S':
6448 if (st.status_codes != NULL && st.suppress == 0)
6449 option_conflict('S', 's');
6450 st.suppress = 1;
6451 /* fallthrough */
6452 case 's':
6453 for (i = 0; optarg[i] != '\0'; i++) {
6454 switch (optarg[i]) {
6455 case GOT_STATUS_MODIFY:
6456 case GOT_STATUS_ADD:
6457 case GOT_STATUS_DELETE:
6458 case GOT_STATUS_CONFLICT:
6459 case GOT_STATUS_MISSING:
6460 case GOT_STATUS_OBSTRUCTED:
6461 case GOT_STATUS_UNVERSIONED:
6462 case GOT_STATUS_MODE_CHANGE:
6463 case GOT_STATUS_NONEXISTENT:
6464 break;
6465 default:
6466 errx(1, "invalid status code '%c'",
6467 optarg[i]);
6470 if (ch == 's' && st.suppress)
6471 option_conflict('s', 'S');
6472 st.status_codes = optarg;
6473 break;
6474 default:
6475 usage_status();
6476 /* NOTREACHED */
6480 argc -= optind;
6481 argv += optind;
6483 cwd = getcwd(NULL, 0);
6484 if (cwd == NULL) {
6485 error = got_error_from_errno("getcwd");
6486 goto done;
6489 error = got_repo_pack_fds_open(&pack_fds);
6490 if (error != NULL)
6491 goto done;
6493 error = got_worktree_open(&worktree, cwd,
6494 GOT_WORKTREE_GOT_DIR);
6495 if (error) {
6496 if (error->code == GOT_ERR_NOT_WORKTREE)
6497 error = wrap_not_worktree_error(error, "status", cwd);
6498 goto done;
6501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6502 NULL, pack_fds);
6503 if (error != NULL)
6504 goto done;
6506 error = apply_unveil(got_repo_get_path(repo), 1,
6507 got_worktree_get_root_path(worktree));
6508 if (error)
6509 goto done;
6511 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6512 if (error)
6513 goto done;
6515 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6516 print_status, &st, check_cancelled, NULL);
6517 done:
6518 if (pack_fds) {
6519 const struct got_error *pack_err =
6520 got_repo_pack_fds_close(pack_fds);
6521 if (error == NULL)
6522 error = pack_err;
6524 if (repo) {
6525 close_err = got_repo_close(repo);
6526 if (error == NULL)
6527 error = close_err;
6529 if (worktree != NULL) {
6530 close_err = got_worktree_close(worktree);
6531 if (error == NULL)
6532 error = close_err;
6535 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6536 free(cwd);
6537 return error;
6540 __dead static void
6541 usage_ref(void)
6543 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6544 "[-s reference] [name]\n", getprogname());
6545 exit(1);
6548 static const struct got_error *
6549 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6551 static const struct got_error *err = NULL;
6552 struct got_reflist_head refs;
6553 struct got_reflist_entry *re;
6555 TAILQ_INIT(&refs);
6556 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6557 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6558 repo);
6559 if (err)
6560 return err;
6562 TAILQ_FOREACH(re, &refs, entry) {
6563 char *refstr;
6564 refstr = got_ref_to_str(re->ref);
6565 if (refstr == NULL) {
6566 err = got_error_from_errno("got_ref_to_str");
6567 break;
6569 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6570 free(refstr);
6573 got_ref_list_free(&refs);
6574 return err;
6577 static const struct got_error *
6578 delete_ref_by_name(struct got_repository *repo, const char *refname)
6580 const struct got_error *err;
6581 struct got_reference *ref;
6583 err = got_ref_open(&ref, repo, refname, 0);
6584 if (err)
6585 return err;
6587 err = delete_ref(repo, ref);
6588 got_ref_close(ref);
6589 return err;
6592 static const struct got_error *
6593 add_ref(struct got_repository *repo, const char *refname, const char *target)
6595 const struct got_error *err = NULL;
6596 struct got_object_id *id = NULL;
6597 struct got_reference *ref = NULL;
6598 struct got_reflist_head refs;
6601 * Don't let the user create a reference name with a leading '-'.
6602 * While technically a valid reference name, this case is usually
6603 * an unintended typo.
6605 if (refname[0] == '-')
6606 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6608 TAILQ_INIT(&refs);
6609 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6610 if (err)
6611 goto done;
6612 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6613 &refs, repo);
6614 got_ref_list_free(&refs);
6615 if (err)
6616 goto done;
6618 err = got_ref_alloc(&ref, refname, id);
6619 if (err)
6620 goto done;
6622 err = got_ref_write(ref, repo);
6623 done:
6624 if (ref)
6625 got_ref_close(ref);
6626 free(id);
6627 return err;
6630 static const struct got_error *
6631 add_symref(struct got_repository *repo, const char *refname, const char *target)
6633 const struct got_error *err = NULL;
6634 struct got_reference *ref = NULL;
6635 struct got_reference *target_ref = NULL;
6638 * Don't let the user create a reference name with a leading '-'.
6639 * While technically a valid reference name, this case is usually
6640 * an unintended typo.
6642 if (refname[0] == '-')
6643 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6645 err = got_ref_open(&target_ref, repo, target, 0);
6646 if (err)
6647 return err;
6649 err = got_ref_alloc_symref(&ref, refname, target_ref);
6650 if (err)
6651 goto done;
6653 err = got_ref_write(ref, repo);
6654 done:
6655 if (target_ref)
6656 got_ref_close(target_ref);
6657 if (ref)
6658 got_ref_close(ref);
6659 return err;
6662 static const struct got_error *
6663 cmd_ref(int argc, char *argv[])
6665 const struct got_error *error = NULL;
6666 struct got_repository *repo = NULL;
6667 struct got_worktree *worktree = NULL;
6668 char *cwd = NULL, *repo_path = NULL;
6669 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6670 const char *obj_arg = NULL, *symref_target= NULL;
6671 char *refname = NULL, *keyword_idstr = NULL;
6672 int *pack_fds = NULL;
6674 #ifndef PROFILE
6675 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6676 "sendfd unveil", NULL) == -1)
6677 err(1, "pledge");
6678 #endif
6680 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6681 switch (ch) {
6682 case 'c':
6683 obj_arg = optarg;
6684 break;
6685 case 'd':
6686 do_delete = 1;
6687 break;
6688 case 'l':
6689 do_list = 1;
6690 break;
6691 case 'r':
6692 repo_path = realpath(optarg, NULL);
6693 if (repo_path == NULL)
6694 return got_error_from_errno2("realpath",
6695 optarg);
6696 got_path_strip_trailing_slashes(repo_path);
6697 break;
6698 case 's':
6699 symref_target = optarg;
6700 break;
6701 case 't':
6702 sort_by_time = 1;
6703 break;
6704 default:
6705 usage_ref();
6706 /* NOTREACHED */
6710 if (obj_arg && do_list)
6711 option_conflict('c', 'l');
6712 if (obj_arg && do_delete)
6713 option_conflict('c', 'd');
6714 if (obj_arg && symref_target)
6715 option_conflict('c', 's');
6716 if (symref_target && do_delete)
6717 option_conflict('s', 'd');
6718 if (symref_target && do_list)
6719 option_conflict('s', 'l');
6720 if (do_delete && do_list)
6721 option_conflict('d', 'l');
6722 if (sort_by_time && !do_list)
6723 errx(1, "-t option requires -l option");
6725 argc -= optind;
6726 argv += optind;
6728 if (do_list) {
6729 if (argc != 0 && argc != 1)
6730 usage_ref();
6731 if (argc == 1) {
6732 refname = strdup(argv[0]);
6733 if (refname == NULL) {
6734 error = got_error_from_errno("strdup");
6735 goto done;
6738 } else {
6739 if (argc != 1)
6740 usage_ref();
6741 refname = strdup(argv[0]);
6742 if (refname == NULL) {
6743 error = got_error_from_errno("strdup");
6744 goto done;
6748 if (refname)
6749 got_path_strip_trailing_slashes(refname);
6751 cwd = getcwd(NULL, 0);
6752 if (cwd == NULL) {
6753 error = got_error_from_errno("getcwd");
6754 goto done;
6757 error = got_repo_pack_fds_open(&pack_fds);
6758 if (error != NULL)
6759 goto done;
6761 if (repo_path == NULL) {
6762 error = got_worktree_open(&worktree, cwd,
6763 GOT_WORKTREE_GOT_DIR);
6764 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6765 goto done;
6766 else
6767 error = NULL;
6768 if (worktree) {
6769 repo_path =
6770 strdup(got_worktree_get_repo_path(worktree));
6771 if (repo_path == NULL)
6772 error = got_error_from_errno("strdup");
6773 if (error)
6774 goto done;
6775 } else {
6776 repo_path = strdup(cwd);
6777 if (repo_path == NULL) {
6778 error = got_error_from_errno("strdup");
6779 goto done;
6784 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6785 if (error != NULL)
6786 goto done;
6788 #ifndef PROFILE
6789 if (do_list) {
6790 /* Remove "cpath" promise. */
6791 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6792 NULL) == -1)
6793 err(1, "pledge");
6795 #endif
6797 error = apply_unveil(got_repo_get_path(repo), do_list,
6798 worktree ? got_worktree_get_root_path(worktree) : NULL);
6799 if (error)
6800 goto done;
6802 if (do_list)
6803 error = list_refs(repo, refname, sort_by_time);
6804 else if (do_delete)
6805 error = delete_ref_by_name(repo, refname);
6806 else if (symref_target)
6807 error = add_symref(repo, refname, symref_target);
6808 else {
6809 if (obj_arg == NULL)
6810 usage_ref();
6812 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6813 repo, worktree);
6814 if (error != NULL)
6815 goto done;
6816 if (keyword_idstr != NULL)
6817 obj_arg = keyword_idstr;
6819 error = add_ref(repo, refname, obj_arg);
6821 done:
6822 free(refname);
6823 if (repo) {
6824 const struct got_error *close_err = got_repo_close(repo);
6825 if (error == NULL)
6826 error = close_err;
6828 if (worktree)
6829 got_worktree_close(worktree);
6830 if (pack_fds) {
6831 const struct got_error *pack_err =
6832 got_repo_pack_fds_close(pack_fds);
6833 if (error == NULL)
6834 error = pack_err;
6836 free(cwd);
6837 free(repo_path);
6838 free(keyword_idstr);
6839 return error;
6842 __dead static void
6843 usage_branch(void)
6845 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6846 "[-r repository-path] [name]\n", getprogname());
6847 exit(1);
6850 static const struct got_error *
6851 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6852 struct got_reference *ref)
6854 const struct got_error *err = NULL;
6855 const char *refname;
6856 char *refstr;
6857 char marker = ' ';
6859 refname = got_ref_get_name(ref);
6860 if (worktree && strcmp(refname,
6861 got_worktree_get_head_ref_name(worktree)) == 0) {
6862 err = got_worktree_get_state(&marker, repo, worktree,
6863 check_cancelled, NULL);
6864 if (err != NULL)
6865 return err;
6868 if (strncmp(refname, "refs/heads/", 11) == 0)
6869 refname += 11;
6870 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6871 refname += 18;
6872 if (strncmp(refname, "refs/remotes/", 13) == 0)
6873 refname += 13;
6875 refstr = got_ref_to_str(ref);
6876 if (refstr == NULL)
6877 return got_error_from_errno("got_ref_to_str");
6879 printf("%c %s: %s\n", marker, refname, refstr);
6880 free(refstr);
6881 return NULL;
6884 static const struct got_error *
6885 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6887 const char *refname;
6889 if (worktree == NULL)
6890 return got_error(GOT_ERR_NOT_WORKTREE);
6892 refname = got_worktree_get_head_ref_name(worktree);
6894 if (strncmp(refname, "refs/heads/", 11) == 0)
6895 refname += 11;
6896 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6897 refname += 18;
6899 printf("%s\n", refname);
6901 return NULL;
6904 static const struct got_error *
6905 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6906 int sort_by_time)
6908 static const struct got_error *err = NULL;
6909 struct got_reflist_head refs;
6910 struct got_reflist_entry *re;
6911 struct got_reference *temp_ref = NULL;
6912 int rebase_in_progress, histedit_in_progress;
6914 TAILQ_INIT(&refs);
6916 if (worktree) {
6917 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6918 worktree);
6919 if (err)
6920 return err;
6922 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6923 worktree);
6924 if (err)
6925 return err;
6927 if (rebase_in_progress || histedit_in_progress) {
6928 err = got_ref_open(&temp_ref, repo,
6929 got_worktree_get_head_ref_name(worktree), 0);
6930 if (err)
6931 return err;
6932 list_branch(repo, worktree, temp_ref);
6933 got_ref_close(temp_ref);
6937 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6938 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6939 repo);
6940 if (err)
6941 return err;
6943 TAILQ_FOREACH(re, &refs, entry)
6944 list_branch(repo, worktree, re->ref);
6946 got_ref_list_free(&refs);
6948 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6949 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6950 repo);
6951 if (err)
6952 return err;
6954 TAILQ_FOREACH(re, &refs, entry)
6955 list_branch(repo, worktree, re->ref);
6957 got_ref_list_free(&refs);
6959 return NULL;
6962 static const struct got_error *
6963 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6964 const char *branch_name)
6966 const struct got_error *err = NULL;
6967 struct got_reference *ref = NULL;
6968 char *refname, *remote_refname = NULL;
6970 if (strncmp(branch_name, "refs/", 5) == 0)
6971 branch_name += 5;
6972 if (strncmp(branch_name, "heads/", 6) == 0)
6973 branch_name += 6;
6974 else if (strncmp(branch_name, "remotes/", 8) == 0)
6975 branch_name += 8;
6977 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6978 return got_error_from_errno("asprintf");
6980 if (asprintf(&remote_refname, "refs/remotes/%s",
6981 branch_name) == -1) {
6982 err = got_error_from_errno("asprintf");
6983 goto done;
6986 err = got_ref_open(&ref, repo, refname, 0);
6987 if (err) {
6988 const struct got_error *err2;
6989 if (err->code != GOT_ERR_NOT_REF)
6990 goto done;
6992 * Keep 'err' intact such that if neither branch exists
6993 * we report "refs/heads" rather than "refs/remotes" in
6994 * our error message.
6996 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6997 if (err2)
6998 goto done;
6999 err = NULL;
7002 if (worktree &&
7003 strcmp(got_worktree_get_head_ref_name(worktree),
7004 got_ref_get_name(ref)) == 0) {
7005 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7006 "will not delete this work tree's current branch");
7007 goto done;
7010 err = delete_ref(repo, ref);
7011 done:
7012 if (ref)
7013 got_ref_close(ref);
7014 free(refname);
7015 free(remote_refname);
7016 return err;
7019 static const struct got_error *
7020 add_branch(struct got_repository *repo, const char *branch_name,
7021 struct got_object_id *base_commit_id)
7023 const struct got_error *err = NULL;
7024 struct got_reference *ref = NULL;
7025 char *refname = NULL;
7028 * Don't let the user create a branch name with a leading '-'.
7029 * While technically a valid reference name, this case is usually
7030 * an unintended typo.
7032 if (branch_name[0] == '-')
7033 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7035 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7036 branch_name += 11;
7038 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7039 err = got_error_from_errno("asprintf");
7040 goto done;
7043 err = got_ref_open(&ref, repo, refname, 0);
7044 if (err == NULL) {
7045 err = got_error(GOT_ERR_BRANCH_EXISTS);
7046 goto done;
7047 } else if (err->code != GOT_ERR_NOT_REF)
7048 goto done;
7050 err = got_ref_alloc(&ref, refname, base_commit_id);
7051 if (err)
7052 goto done;
7054 err = got_ref_write(ref, repo);
7055 done:
7056 if (ref)
7057 got_ref_close(ref);
7058 free(refname);
7059 return err;
7062 static const struct got_error *
7063 cmd_branch(int argc, char *argv[])
7065 const struct got_error *error = NULL;
7066 struct got_repository *repo = NULL;
7067 struct got_worktree *worktree = NULL;
7068 char *cwd = NULL, *repo_path = NULL;
7069 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7070 const char *delref = NULL, *commit_id_arg = NULL;
7071 struct got_reference *ref = NULL;
7072 struct got_pathlist_head paths;
7073 struct got_object_id *commit_id = NULL;
7074 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7075 int *pack_fds = NULL;
7077 TAILQ_INIT(&paths);
7079 #ifndef PROFILE
7080 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7081 "sendfd unveil", NULL) == -1)
7082 err(1, "pledge");
7083 #endif
7085 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7086 switch (ch) {
7087 case 'c':
7088 commit_id_arg = optarg;
7089 break;
7090 case 'd':
7091 delref = optarg;
7092 break;
7093 case 'l':
7094 do_list = 1;
7095 break;
7096 case 'n':
7097 do_update = 0;
7098 break;
7099 case 'r':
7100 repo_path = realpath(optarg, NULL);
7101 if (repo_path == NULL)
7102 return got_error_from_errno2("realpath",
7103 optarg);
7104 got_path_strip_trailing_slashes(repo_path);
7105 break;
7106 case 't':
7107 sort_by_time = 1;
7108 break;
7109 default:
7110 usage_branch();
7111 /* NOTREACHED */
7115 if (do_list && delref)
7116 option_conflict('l', 'd');
7117 if (sort_by_time && !do_list)
7118 errx(1, "-t option requires -l option");
7120 argc -= optind;
7121 argv += optind;
7123 if (!do_list && !delref && argc == 0)
7124 do_show = 1;
7126 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7127 errx(1, "-c option can only be used when creating a branch");
7129 if (do_list || delref) {
7130 if (argc > 0)
7131 usage_branch();
7132 } else if (!do_show && argc != 1)
7133 usage_branch();
7135 cwd = getcwd(NULL, 0);
7136 if (cwd == NULL) {
7137 error = got_error_from_errno("getcwd");
7138 goto done;
7141 error = got_repo_pack_fds_open(&pack_fds);
7142 if (error != NULL)
7143 goto done;
7145 if (repo_path == NULL) {
7146 error = got_worktree_open(&worktree, cwd,
7147 GOT_WORKTREE_GOT_DIR);
7148 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7149 goto done;
7150 else
7151 error = NULL;
7152 if (worktree) {
7153 repo_path =
7154 strdup(got_worktree_get_repo_path(worktree));
7155 if (repo_path == NULL)
7156 error = got_error_from_errno("strdup");
7157 if (error)
7158 goto done;
7159 } else {
7160 repo_path = strdup(cwd);
7161 if (repo_path == NULL) {
7162 error = got_error_from_errno("strdup");
7163 goto done;
7168 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7169 if (error != NULL)
7170 goto done;
7172 #ifndef PROFILE
7173 if (do_list || do_show) {
7174 /* Remove "cpath" promise. */
7175 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7176 NULL) == -1)
7177 err(1, "pledge");
7179 #endif
7181 error = apply_unveil(got_repo_get_path(repo), do_list,
7182 worktree ? got_worktree_get_root_path(worktree) : NULL);
7183 if (error)
7184 goto done;
7186 if (do_show)
7187 error = show_current_branch(repo, worktree);
7188 else if (do_list)
7189 error = list_branches(repo, worktree, sort_by_time);
7190 else if (delref)
7191 error = delete_branch(repo, worktree, delref);
7192 else {
7193 struct got_reflist_head refs;
7194 TAILQ_INIT(&refs);
7195 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7196 NULL);
7197 if (error)
7198 goto done;
7199 if (commit_id_arg == NULL)
7200 commit_id_arg = worktree ?
7201 got_worktree_get_head_ref_name(worktree) :
7202 GOT_REF_HEAD;
7203 else {
7204 error = got_keyword_to_idstr(&keyword_idstr,
7205 commit_id_arg, repo, worktree);
7206 if (error != NULL)
7207 goto done;
7208 if (keyword_idstr != NULL)
7209 commit_id_arg = keyword_idstr;
7211 error = got_repo_match_object_id(&commit_id, NULL,
7212 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7213 got_ref_list_free(&refs);
7214 if (error)
7215 goto done;
7216 error = add_branch(repo, argv[0], commit_id);
7217 if (error)
7218 goto done;
7219 if (worktree && do_update) {
7220 struct got_update_progress_arg upa;
7221 char *branch_refname = NULL;
7223 error = got_object_id_str(&commit_id_str, commit_id);
7224 if (error)
7225 goto done;
7226 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7227 worktree);
7228 if (error)
7229 goto done;
7230 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7231 == -1) {
7232 error = got_error_from_errno("asprintf");
7233 goto done;
7235 error = got_ref_open(&ref, repo, branch_refname, 0);
7236 free(branch_refname);
7237 if (error)
7238 goto done;
7239 error = switch_head_ref(ref, commit_id, worktree,
7240 repo);
7241 if (error)
7242 goto done;
7243 error = got_worktree_set_base_commit_id(worktree, repo,
7244 commit_id);
7245 if (error)
7246 goto done;
7247 memset(&upa, 0, sizeof(upa));
7248 error = got_worktree_checkout_files(worktree, &paths,
7249 repo, update_progress, &upa, check_cancelled,
7250 NULL);
7251 if (error)
7252 goto done;
7253 if (upa.did_something) {
7254 printf("Updated to %s: %s\n",
7255 got_worktree_get_head_ref_name(worktree),
7256 commit_id_str);
7258 print_update_progress_stats(&upa);
7261 done:
7262 free(keyword_idstr);
7263 if (ref)
7264 got_ref_close(ref);
7265 if (repo) {
7266 const struct got_error *close_err = got_repo_close(repo);
7267 if (error == NULL)
7268 error = close_err;
7270 if (worktree)
7271 got_worktree_close(worktree);
7272 if (pack_fds) {
7273 const struct got_error *pack_err =
7274 got_repo_pack_fds_close(pack_fds);
7275 if (error == NULL)
7276 error = pack_err;
7278 free(cwd);
7279 free(repo_path);
7280 free(commit_id);
7281 free(commit_id_str);
7282 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7283 return error;
7287 __dead static void
7288 usage_tag(void)
7290 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7291 "[-r repository-path] [-s signer-id] name\n", getprogname());
7292 exit(1);
7295 #if 0
7296 static const struct got_error *
7297 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7299 const struct got_error *err = NULL;
7300 struct got_reflist_entry *re, *se, *new;
7301 struct got_object_id *re_id, *se_id;
7302 struct got_tag_object *re_tag, *se_tag;
7303 time_t re_time, se_time;
7305 STAILQ_FOREACH(re, tags, entry) {
7306 se = STAILQ_FIRST(sorted);
7307 if (se == NULL) {
7308 err = got_reflist_entry_dup(&new, re);
7309 if (err)
7310 return err;
7311 STAILQ_INSERT_HEAD(sorted, new, entry);
7312 continue;
7313 } else {
7314 err = got_ref_resolve(&re_id, repo, re->ref);
7315 if (err)
7316 break;
7317 err = got_object_open_as_tag(&re_tag, repo, re_id);
7318 free(re_id);
7319 if (err)
7320 break;
7321 re_time = got_object_tag_get_tagger_time(re_tag);
7322 got_object_tag_close(re_tag);
7325 while (se) {
7326 err = got_ref_resolve(&se_id, repo, re->ref);
7327 if (err)
7328 break;
7329 err = got_object_open_as_tag(&se_tag, repo, se_id);
7330 free(se_id);
7331 if (err)
7332 break;
7333 se_time = got_object_tag_get_tagger_time(se_tag);
7334 got_object_tag_close(se_tag);
7336 if (se_time > re_time) {
7337 err = got_reflist_entry_dup(&new, re);
7338 if (err)
7339 return err;
7340 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7341 break;
7343 se = STAILQ_NEXT(se, entry);
7344 continue;
7347 done:
7348 return err;
7350 #endif
7352 static const struct got_error *
7353 get_tag_refname(char **refname, const char *tag_name)
7355 const struct got_error *err;
7357 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7358 *refname = strdup(tag_name);
7359 if (*refname == NULL)
7360 return got_error_from_errno("strdup");
7361 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7362 err = got_error_from_errno("asprintf");
7363 *refname = NULL;
7364 return err;
7367 return NULL;
7370 static const struct got_error *
7371 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7372 const char *allowed_signers, const char *revoked_signers, int verbosity)
7374 static const struct got_error *err = NULL;
7375 struct got_reflist_head refs;
7376 struct got_reflist_entry *re;
7377 char *wanted_refname = NULL;
7378 int bad_sigs = 0;
7380 TAILQ_INIT(&refs);
7382 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7383 if (err)
7384 return err;
7386 if (tag_name) {
7387 struct got_reference *ref;
7388 err = get_tag_refname(&wanted_refname, tag_name);
7389 if (err)
7390 goto done;
7391 /* Wanted tag reference should exist. */
7392 err = got_ref_open(&ref, repo, wanted_refname, 0);
7393 if (err)
7394 goto done;
7395 got_ref_close(ref);
7398 TAILQ_FOREACH(re, &refs, entry) {
7399 const char *refname;
7400 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7401 char datebuf[26];
7402 const char *tagger, *ssh_sig = NULL;
7403 char *sig_msg = NULL;
7404 time_t tagger_time;
7405 struct got_object_id *id;
7406 struct got_tag_object *tag;
7407 struct got_commit_object *commit = NULL;
7409 refname = got_ref_get_name(re->ref);
7410 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7411 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7412 continue;
7413 refname += 10;
7414 refstr = got_ref_to_str(re->ref);
7415 if (refstr == NULL) {
7416 err = got_error_from_errno("got_ref_to_str");
7417 break;
7420 err = got_ref_resolve(&id, repo, re->ref);
7421 if (err)
7422 break;
7423 err = got_object_open_as_tag(&tag, repo, id);
7424 if (err) {
7425 if (err->code != GOT_ERR_OBJ_TYPE) {
7426 free(id);
7427 break;
7429 /* "lightweight" tag */
7430 err = got_object_open_as_commit(&commit, repo, id);
7431 if (err) {
7432 free(id);
7433 break;
7435 tagger = got_object_commit_get_committer(commit);
7436 tagger_time =
7437 got_object_commit_get_committer_time(commit);
7438 err = got_object_id_str(&id_str, id);
7439 free(id);
7440 if (err)
7441 break;
7442 } else {
7443 free(id);
7444 tagger = got_object_tag_get_tagger(tag);
7445 tagger_time = got_object_tag_get_tagger_time(tag);
7446 err = got_object_id_str(&id_str,
7447 got_object_tag_get_object_id(tag));
7448 if (err)
7449 break;
7452 if (tag && verify_tags) {
7453 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7454 got_object_tag_get_message(tag));
7455 if (ssh_sig && allowed_signers == NULL) {
7456 err = got_error_msg(
7457 GOT_ERR_VERIFY_TAG_SIGNATURE,
7458 "SSH signature verification requires "
7459 "setting allowed_signers in "
7460 "got.conf(5)");
7461 break;
7465 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7466 free(refstr);
7467 printf("from: %s\n", tagger);
7468 datestr = get_datestr(&tagger_time, datebuf);
7469 if (datestr)
7470 printf("date: %s UTC\n", datestr);
7471 if (commit)
7472 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7473 else {
7474 switch (got_object_tag_get_object_type(tag)) {
7475 case GOT_OBJ_TYPE_BLOB:
7476 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7477 id_str);
7478 break;
7479 case GOT_OBJ_TYPE_TREE:
7480 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7481 id_str);
7482 break;
7483 case GOT_OBJ_TYPE_COMMIT:
7484 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7485 id_str);
7486 break;
7487 case GOT_OBJ_TYPE_TAG:
7488 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7489 id_str);
7490 break;
7491 default:
7492 break;
7495 free(id_str);
7497 if (ssh_sig) {
7498 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7499 allowed_signers, revoked_signers, verbosity);
7500 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7501 bad_sigs = 1;
7502 else if (err)
7503 break;
7504 printf("signature: %s", sig_msg);
7505 free(sig_msg);
7506 sig_msg = NULL;
7509 if (commit) {
7510 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7511 if (err)
7512 break;
7513 got_object_commit_close(commit);
7514 } else {
7515 tagmsg0 = strdup(got_object_tag_get_message(tag));
7516 got_object_tag_close(tag);
7517 if (tagmsg0 == NULL) {
7518 err = got_error_from_errno("strdup");
7519 break;
7523 tagmsg = tagmsg0;
7524 do {
7525 line = strsep(&tagmsg, "\n");
7526 if (line)
7527 printf(" %s\n", line);
7528 } while (line);
7529 free(tagmsg0);
7531 done:
7532 got_ref_list_free(&refs);
7533 free(wanted_refname);
7535 if (err == NULL && bad_sigs)
7536 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7537 return err;
7540 static const struct got_error *
7541 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7542 const char *tag_name, const char *repo_path)
7544 const struct got_error *err = NULL;
7545 char *template = NULL, *initial_content = NULL;
7546 char *editor = NULL;
7547 int initial_content_len;
7548 int fd = -1;
7550 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7551 err = got_error_from_errno("asprintf");
7552 goto done;
7555 initial_content_len = asprintf(&initial_content,
7556 "\n# tagging commit %s as %s\n",
7557 commit_id_str, tag_name);
7558 if (initial_content_len == -1) {
7559 err = got_error_from_errno("asprintf");
7560 goto done;
7563 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7564 if (err)
7565 goto done;
7567 if (write(fd, initial_content, initial_content_len) == -1) {
7568 err = got_error_from_errno2("write", *tagmsg_path);
7569 goto done;
7571 if (close(fd) == -1) {
7572 err = got_error_from_errno2("close", *tagmsg_path);
7573 goto done;
7575 fd = -1;
7577 err = get_editor(&editor);
7578 if (err)
7579 goto done;
7580 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7581 initial_content_len, 1);
7582 done:
7583 free(initial_content);
7584 free(template);
7585 free(editor);
7587 if (fd != -1 && close(fd) == -1 && err == NULL)
7588 err = got_error_from_errno2("close", *tagmsg_path);
7590 if (err) {
7591 free(*tagmsg);
7592 *tagmsg = NULL;
7594 return err;
7597 static const struct got_error *
7598 add_tag(struct got_repository *repo, const char *tagger,
7599 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7600 const char *signer_id, int verbosity)
7602 const struct got_error *err = NULL;
7603 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7604 char *label = NULL, *commit_id_str = NULL;
7605 struct got_reference *ref = NULL;
7606 char *refname = NULL, *tagmsg = NULL;
7607 char *tagmsg_path = NULL, *tag_id_str = NULL;
7608 int preserve_tagmsg = 0;
7609 struct got_reflist_head refs;
7611 TAILQ_INIT(&refs);
7614 * Don't let the user create a tag name with a leading '-'.
7615 * While technically a valid reference name, this case is usually
7616 * an unintended typo.
7618 if (tag_name[0] == '-')
7619 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7621 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7622 if (err)
7623 goto done;
7625 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7626 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7627 if (err)
7628 goto done;
7630 err = got_object_id_str(&commit_id_str, commit_id);
7631 if (err)
7632 goto done;
7634 err = get_tag_refname(&refname, tag_name);
7635 if (err)
7636 goto done;
7637 if (strncmp("refs/tags/", tag_name, 10) == 0)
7638 tag_name += 10;
7640 err = got_ref_open(&ref, repo, refname, 0);
7641 if (err == NULL) {
7642 err = got_error(GOT_ERR_TAG_EXISTS);
7643 goto done;
7644 } else if (err->code != GOT_ERR_NOT_REF)
7645 goto done;
7647 if (tagmsg_arg == NULL) {
7648 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7649 tag_name, got_repo_get_path(repo));
7650 if (err) {
7651 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7652 tagmsg_path != NULL)
7653 preserve_tagmsg = 1;
7654 goto done;
7656 /* Editor is done; we can now apply unveil(2) */
7657 err = got_sigs_apply_unveil();
7658 if (err)
7659 goto done;
7660 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7661 if (err)
7662 goto done;
7665 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7666 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7667 verbosity);
7668 if (err) {
7669 if (tagmsg_path)
7670 preserve_tagmsg = 1;
7671 goto done;
7674 err = got_ref_alloc(&ref, refname, tag_id);
7675 if (err) {
7676 if (tagmsg_path)
7677 preserve_tagmsg = 1;
7678 goto done;
7681 err = got_ref_write(ref, repo);
7682 if (err) {
7683 if (tagmsg_path)
7684 preserve_tagmsg = 1;
7685 goto done;
7688 err = got_object_id_str(&tag_id_str, tag_id);
7689 if (err) {
7690 if (tagmsg_path)
7691 preserve_tagmsg = 1;
7692 goto done;
7694 printf("Created tag %s\n", tag_id_str);
7695 done:
7696 if (preserve_tagmsg) {
7697 fprintf(stderr, "%s: tag message preserved in %s\n",
7698 getprogname(), tagmsg_path);
7699 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7700 err = got_error_from_errno2("unlink", tagmsg_path);
7701 free(tag_id_str);
7702 if (ref)
7703 got_ref_close(ref);
7704 free(commit_id);
7705 free(commit_id_str);
7706 free(refname);
7707 free(tagmsg);
7708 free(tagmsg_path);
7709 got_ref_list_free(&refs);
7710 return err;
7713 static const struct got_error *
7714 cmd_tag(int argc, char *argv[])
7716 const struct got_error *error = NULL;
7717 struct got_repository *repo = NULL;
7718 struct got_worktree *worktree = NULL;
7719 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7720 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7721 char *allowed_signers = NULL, *revoked_signers = NULL;
7722 const char *signer_id = NULL;
7723 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7724 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7725 int *pack_fds = NULL;
7727 #ifndef PROFILE
7728 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7729 "sendfd unveil", NULL) == -1)
7730 err(1, "pledge");
7731 #endif
7733 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7734 switch (ch) {
7735 case 'c':
7736 commit_id_arg = optarg;
7737 break;
7738 case 'l':
7739 do_list = 1;
7740 break;
7741 case 'm':
7742 tagmsg = optarg;
7743 break;
7744 case 'r':
7745 repo_path = realpath(optarg, NULL);
7746 if (repo_path == NULL) {
7747 error = got_error_from_errno2("realpath",
7748 optarg);
7749 goto done;
7751 got_path_strip_trailing_slashes(repo_path);
7752 break;
7753 case 's':
7754 signer_id = optarg;
7755 break;
7756 case 'V':
7757 verify_tags = 1;
7758 break;
7759 case 'v':
7760 if (verbosity < 0)
7761 verbosity = 0;
7762 else if (verbosity < 3)
7763 verbosity++;
7764 break;
7765 default:
7766 usage_tag();
7767 /* NOTREACHED */
7771 argc -= optind;
7772 argv += optind;
7774 if (do_list || verify_tags) {
7775 if (commit_id_arg != NULL)
7776 errx(1,
7777 "-c option can only be used when creating a tag");
7778 if (tagmsg) {
7779 if (do_list)
7780 option_conflict('l', 'm');
7781 else
7782 option_conflict('V', 'm');
7784 if (signer_id) {
7785 if (do_list)
7786 option_conflict('l', 's');
7787 else
7788 option_conflict('V', 's');
7790 if (argc > 1)
7791 usage_tag();
7792 } else if (argc != 1)
7793 usage_tag();
7795 if (argc == 1)
7796 tag_name = argv[0];
7798 cwd = getcwd(NULL, 0);
7799 if (cwd == NULL) {
7800 error = got_error_from_errno("getcwd");
7801 goto done;
7804 error = got_repo_pack_fds_open(&pack_fds);
7805 if (error != NULL)
7806 goto done;
7808 if (repo_path == NULL) {
7809 error = got_worktree_open(&worktree, cwd,
7810 GOT_WORKTREE_GOT_DIR);
7811 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7812 goto done;
7813 else
7814 error = NULL;
7815 if (worktree) {
7816 repo_path =
7817 strdup(got_worktree_get_repo_path(worktree));
7818 if (repo_path == NULL)
7819 error = got_error_from_errno("strdup");
7820 if (error)
7821 goto done;
7822 } else {
7823 repo_path = strdup(cwd);
7824 if (repo_path == NULL) {
7825 error = got_error_from_errno("strdup");
7826 goto done;
7831 if (do_list || verify_tags) {
7832 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7833 if (error != NULL)
7834 goto done;
7835 error = get_allowed_signers(&allowed_signers, repo, worktree);
7836 if (error)
7837 goto done;
7838 error = get_revoked_signers(&revoked_signers, repo, worktree);
7839 if (error)
7840 goto done;
7841 if (worktree) {
7842 /* Release work tree lock. */
7843 got_worktree_close(worktree);
7844 worktree = NULL;
7848 * Remove "cpath" promise unless needed for signature tmpfile
7849 * creation.
7851 if (verify_tags)
7852 got_sigs_apply_unveil();
7853 else {
7854 #ifndef PROFILE
7855 if (pledge("stdio rpath wpath flock proc exec sendfd "
7856 "unveil", NULL) == -1)
7857 err(1, "pledge");
7858 #endif
7860 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7861 if (error)
7862 goto done;
7863 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7864 revoked_signers, verbosity);
7865 } else {
7866 error = get_gitconfig_path(&gitconfig_path);
7867 if (error)
7868 goto done;
7869 error = got_repo_open(&repo, repo_path, gitconfig_path,
7870 pack_fds);
7871 if (error != NULL)
7872 goto done;
7874 error = get_author(&tagger, repo, worktree);
7875 if (error)
7876 goto done;
7877 if (signer_id == NULL)
7878 signer_id = get_signer_id(repo, worktree);
7880 if (tagmsg) {
7881 if (signer_id) {
7882 error = got_sigs_apply_unveil();
7883 if (error)
7884 goto done;
7886 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7887 if (error)
7888 goto done;
7891 if (commit_id_arg == NULL) {
7892 struct got_reference *head_ref;
7893 struct got_object_id *commit_id;
7894 error = got_ref_open(&head_ref, repo,
7895 worktree ? got_worktree_get_head_ref_name(worktree)
7896 : GOT_REF_HEAD, 0);
7897 if (error)
7898 goto done;
7899 error = got_ref_resolve(&commit_id, repo, head_ref);
7900 got_ref_close(head_ref);
7901 if (error)
7902 goto done;
7903 error = got_object_id_str(&commit_id_str, commit_id);
7904 free(commit_id);
7905 if (error)
7906 goto done;
7907 } else {
7908 error = got_keyword_to_idstr(&keyword_idstr,
7909 commit_id_arg, repo, worktree);
7910 if (error != NULL)
7911 goto done;
7912 commit_id_str = keyword_idstr;
7915 if (worktree) {
7916 /* Release work tree lock. */
7917 got_worktree_close(worktree);
7918 worktree = NULL;
7921 error = add_tag(repo, tagger, tag_name,
7922 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7923 signer_id, verbosity);
7925 done:
7926 if (repo) {
7927 const struct got_error *close_err = got_repo_close(repo);
7928 if (error == NULL)
7929 error = close_err;
7931 if (worktree)
7932 got_worktree_close(worktree);
7933 if (pack_fds) {
7934 const struct got_error *pack_err =
7935 got_repo_pack_fds_close(pack_fds);
7936 if (error == NULL)
7937 error = pack_err;
7939 free(cwd);
7940 free(repo_path);
7941 free(gitconfig_path);
7942 free(commit_id_str);
7943 free(tagger);
7944 free(allowed_signers);
7945 free(revoked_signers);
7946 return error;
7949 __dead static void
7950 usage_add(void)
7952 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7953 exit(1);
7956 static const struct got_error *
7957 add_progress(void *arg, unsigned char status, const char *path)
7959 while (path[0] == '/')
7960 path++;
7961 printf("%c %s\n", status, path);
7962 return NULL;
7965 static const struct got_error *
7966 cmd_add(int argc, char *argv[])
7968 const struct got_error *error = NULL;
7969 struct got_repository *repo = NULL;
7970 struct got_worktree *worktree = NULL;
7971 char *cwd = NULL;
7972 struct got_pathlist_head paths;
7973 struct got_pathlist_entry *pe;
7974 int ch, can_recurse = 0, no_ignores = 0;
7975 int *pack_fds = NULL;
7977 TAILQ_INIT(&paths);
7979 #ifndef PROFILE
7980 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7981 NULL) == -1)
7982 err(1, "pledge");
7983 #endif
7985 while ((ch = getopt(argc, argv, "IR")) != -1) {
7986 switch (ch) {
7987 case 'I':
7988 no_ignores = 1;
7989 break;
7990 case 'R':
7991 can_recurse = 1;
7992 break;
7993 default:
7994 usage_add();
7995 /* NOTREACHED */
7999 argc -= optind;
8000 argv += optind;
8002 if (argc < 1)
8003 usage_add();
8005 cwd = getcwd(NULL, 0);
8006 if (cwd == NULL) {
8007 error = got_error_from_errno("getcwd");
8008 goto done;
8011 error = got_repo_pack_fds_open(&pack_fds);
8012 if (error != NULL)
8013 goto done;
8015 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8016 if (error) {
8017 if (error->code == GOT_ERR_NOT_WORKTREE)
8018 error = wrap_not_worktree_error(error, "add", cwd);
8019 goto done;
8022 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8023 NULL, pack_fds);
8024 if (error != NULL)
8025 goto done;
8027 error = apply_unveil(got_repo_get_path(repo), 1,
8028 got_worktree_get_root_path(worktree));
8029 if (error)
8030 goto done;
8032 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8033 if (error)
8034 goto done;
8036 if (!can_recurse) {
8037 char *ondisk_path;
8038 struct stat sb;
8039 TAILQ_FOREACH(pe, &paths, entry) {
8040 if (asprintf(&ondisk_path, "%s/%s",
8041 got_worktree_get_root_path(worktree),
8042 pe->path) == -1) {
8043 error = got_error_from_errno("asprintf");
8044 goto done;
8046 if (lstat(ondisk_path, &sb) == -1) {
8047 if (errno == ENOENT) {
8048 free(ondisk_path);
8049 continue;
8051 error = got_error_from_errno2("lstat",
8052 ondisk_path);
8053 free(ondisk_path);
8054 goto done;
8056 free(ondisk_path);
8057 if (S_ISDIR(sb.st_mode)) {
8058 error = got_error_msg(GOT_ERR_BAD_PATH,
8059 "adding directories requires -R option");
8060 goto done;
8065 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8066 NULL, repo, no_ignores);
8067 done:
8068 if (repo) {
8069 const struct got_error *close_err = got_repo_close(repo);
8070 if (error == NULL)
8071 error = close_err;
8073 if (worktree)
8074 got_worktree_close(worktree);
8075 if (pack_fds) {
8076 const struct got_error *pack_err =
8077 got_repo_pack_fds_close(pack_fds);
8078 if (error == NULL)
8079 error = pack_err;
8081 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8082 free(cwd);
8083 return error;
8086 __dead static void
8087 usage_remove(void)
8089 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8090 getprogname());
8091 exit(1);
8094 static const struct got_error *
8095 print_remove_status(void *arg, unsigned char status,
8096 unsigned char staged_status, const char *path)
8098 while (path[0] == '/')
8099 path++;
8100 if (status == GOT_STATUS_NONEXISTENT)
8101 return NULL;
8102 if (status == staged_status && (status == GOT_STATUS_DELETE))
8103 status = GOT_STATUS_NO_CHANGE;
8104 printf("%c%c %s\n", status, staged_status, path);
8105 return NULL;
8108 static const struct got_error *
8109 cmd_remove(int argc, char *argv[])
8111 const struct got_error *error = NULL;
8112 struct got_worktree *worktree = NULL;
8113 struct got_repository *repo = NULL;
8114 const char *status_codes = NULL;
8115 char *cwd = NULL;
8116 struct got_pathlist_head paths;
8117 struct got_pathlist_entry *pe;
8118 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8119 int ignore_missing_paths = 0;
8120 int *pack_fds = NULL;
8122 TAILQ_INIT(&paths);
8124 #ifndef PROFILE
8125 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8126 NULL) == -1)
8127 err(1, "pledge");
8128 #endif
8130 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8131 switch (ch) {
8132 case 'f':
8133 delete_local_mods = 1;
8134 ignore_missing_paths = 1;
8135 break;
8136 case 'k':
8137 keep_on_disk = 1;
8138 break;
8139 case 'R':
8140 can_recurse = 1;
8141 break;
8142 case 's':
8143 for (i = 0; optarg[i] != '\0'; i++) {
8144 switch (optarg[i]) {
8145 case GOT_STATUS_MODIFY:
8146 delete_local_mods = 1;
8147 break;
8148 case GOT_STATUS_MISSING:
8149 ignore_missing_paths = 1;
8150 break;
8151 default:
8152 errx(1, "invalid status code '%c'",
8153 optarg[i]);
8156 status_codes = optarg;
8157 break;
8158 default:
8159 usage_remove();
8160 /* NOTREACHED */
8164 argc -= optind;
8165 argv += optind;
8167 if (argc < 1)
8168 usage_remove();
8170 cwd = getcwd(NULL, 0);
8171 if (cwd == NULL) {
8172 error = got_error_from_errno("getcwd");
8173 goto done;
8176 error = got_repo_pack_fds_open(&pack_fds);
8177 if (error != NULL)
8178 goto done;
8180 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8181 if (error) {
8182 if (error->code == GOT_ERR_NOT_WORKTREE)
8183 error = wrap_not_worktree_error(error, "remove", cwd);
8184 goto done;
8187 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8188 NULL, pack_fds);
8189 if (error)
8190 goto done;
8192 error = apply_unveil(got_repo_get_path(repo), 1,
8193 got_worktree_get_root_path(worktree));
8194 if (error)
8195 goto done;
8197 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8198 if (error)
8199 goto done;
8201 if (!can_recurse) {
8202 char *ondisk_path;
8203 struct stat sb;
8204 TAILQ_FOREACH(pe, &paths, entry) {
8205 if (asprintf(&ondisk_path, "%s/%s",
8206 got_worktree_get_root_path(worktree),
8207 pe->path) == -1) {
8208 error = got_error_from_errno("asprintf");
8209 goto done;
8211 if (lstat(ondisk_path, &sb) == -1) {
8212 if (errno == ENOENT) {
8213 free(ondisk_path);
8214 continue;
8216 error = got_error_from_errno2("lstat",
8217 ondisk_path);
8218 free(ondisk_path);
8219 goto done;
8221 free(ondisk_path);
8222 if (S_ISDIR(sb.st_mode)) {
8223 error = got_error_msg(GOT_ERR_BAD_PATH,
8224 "removing directories requires -R option");
8225 goto done;
8230 error = got_worktree_schedule_delete(worktree, &paths,
8231 delete_local_mods, status_codes, print_remove_status, NULL,
8232 repo, keep_on_disk, ignore_missing_paths);
8233 done:
8234 if (repo) {
8235 const struct got_error *close_err = got_repo_close(repo);
8236 if (error == NULL)
8237 error = close_err;
8239 if (worktree)
8240 got_worktree_close(worktree);
8241 if (pack_fds) {
8242 const struct got_error *pack_err =
8243 got_repo_pack_fds_close(pack_fds);
8244 if (error == NULL)
8245 error = pack_err;
8247 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8248 free(cwd);
8249 return error;
8252 __dead static void
8253 usage_patch(void)
8255 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8256 "[patchfile]\n", getprogname());
8257 exit(1);
8260 static const struct got_error *
8261 patch_from_stdin(int *patchfd)
8263 const struct got_error *err = NULL;
8264 ssize_t r;
8265 char buf[BUFSIZ];
8266 sig_t sighup, sigint, sigquit;
8268 *patchfd = got_opentempfd();
8269 if (*patchfd == -1)
8270 return got_error_from_errno("got_opentempfd");
8272 sighup = signal(SIGHUP, SIG_DFL);
8273 sigint = signal(SIGINT, SIG_DFL);
8274 sigquit = signal(SIGQUIT, SIG_DFL);
8276 for (;;) {
8277 r = read(0, buf, sizeof(buf));
8278 if (r == -1) {
8279 err = got_error_from_errno("read");
8280 break;
8282 if (r == 0)
8283 break;
8284 if (write(*patchfd, buf, r) == -1) {
8285 err = got_error_from_errno("write");
8286 break;
8290 signal(SIGHUP, sighup);
8291 signal(SIGINT, sigint);
8292 signal(SIGQUIT, sigquit);
8294 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8295 err = got_error_from_errno("lseek");
8297 if (err != NULL) {
8298 close(*patchfd);
8299 *patchfd = -1;
8302 return err;
8305 struct got_patch_progress_arg {
8306 int did_something;
8307 int conflicts;
8308 int rejects;
8311 static const struct got_error *
8312 patch_progress(void *arg, const char *old, const char *new,
8313 unsigned char status, const struct got_error *error, int old_from,
8314 int old_lines, int new_from, int new_lines, int offset,
8315 int ws_mangled, const struct got_error *hunk_err)
8317 const char *path = new == NULL ? old : new;
8318 struct got_patch_progress_arg *a = arg;
8320 while (*path == '/')
8321 path++;
8323 if (status != GOT_STATUS_NO_CHANGE &&
8324 status != 0 /* per-hunk progress */) {
8325 printf("%c %s\n", status, path);
8326 a->did_something = 1;
8329 if (hunk_err == NULL) {
8330 if (status == GOT_STATUS_CANNOT_UPDATE)
8331 a->rejects++;
8332 else if (status == GOT_STATUS_CONFLICT)
8333 a->conflicts++;
8336 if (error != NULL)
8337 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8339 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8340 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8341 old_lines, new_from, new_lines);
8342 if (hunk_err != NULL)
8343 printf("%s\n", hunk_err->msg);
8344 else if (offset != 0)
8345 printf("applied with offset %d\n", offset);
8346 else
8347 printf("hunk contains mangled whitespace\n");
8350 return NULL;
8353 static void
8354 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8356 if (!ppa->did_something)
8357 return;
8359 if (ppa->conflicts > 0)
8360 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8362 if (ppa->rejects > 0) {
8363 printf("Files where patch failed to apply: %d\n",
8364 ppa->rejects);
8368 static const struct got_error *
8369 cmd_patch(int argc, char *argv[])
8371 const struct got_error *error = NULL, *close_error = NULL;
8372 struct got_worktree *worktree = NULL;
8373 struct got_repository *repo = NULL;
8374 struct got_reflist_head refs;
8375 struct got_object_id *commit_id = NULL;
8376 const char *commit_id_str = NULL;
8377 struct stat sb;
8378 const char *errstr;
8379 char *cwd = NULL, *keyword_idstr = NULL;
8380 int ch, nop = 0, strip = -1, reverse = 0;
8381 int patchfd;
8382 int *pack_fds = NULL;
8383 struct got_patch_progress_arg ppa;
8385 TAILQ_INIT(&refs);
8387 #ifndef PROFILE
8388 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8389 "unveil", NULL) == -1)
8390 err(1, "pledge");
8391 #endif
8393 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8394 switch (ch) {
8395 case 'c':
8396 commit_id_str = optarg;
8397 break;
8398 case 'n':
8399 nop = 1;
8400 break;
8401 case 'p':
8402 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8403 if (errstr != NULL)
8404 errx(1, "pathname strip count is %s: %s",
8405 errstr, optarg);
8406 break;
8407 case 'R':
8408 reverse = 1;
8409 break;
8410 default:
8411 usage_patch();
8412 /* NOTREACHED */
8416 argc -= optind;
8417 argv += optind;
8419 if (argc == 0) {
8420 error = patch_from_stdin(&patchfd);
8421 if (error)
8422 return error;
8423 } else if (argc == 1) {
8424 patchfd = open(argv[0], O_RDONLY);
8425 if (patchfd == -1) {
8426 error = got_error_from_errno2("open", argv[0]);
8427 return error;
8429 if (fstat(patchfd, &sb) == -1) {
8430 error = got_error_from_errno2("fstat", argv[0]);
8431 goto done;
8433 if (!S_ISREG(sb.st_mode)) {
8434 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8435 goto done;
8437 } else
8438 usage_patch();
8440 if ((cwd = getcwd(NULL, 0)) == NULL) {
8441 error = got_error_from_errno("getcwd");
8442 goto done;
8445 error = got_repo_pack_fds_open(&pack_fds);
8446 if (error != NULL)
8447 goto done;
8449 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8450 if (error != NULL)
8451 goto done;
8453 const char *repo_path = got_worktree_get_repo_path(worktree);
8454 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8455 if (error != NULL)
8456 goto done;
8458 error = apply_unveil(got_repo_get_path(repo), 0,
8459 got_worktree_get_root_path(worktree));
8460 if (error != NULL)
8461 goto done;
8463 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8464 if (error)
8465 goto done;
8467 if (commit_id_str != NULL) {
8468 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8469 repo, worktree);
8470 if (error != NULL)
8471 goto done;
8473 error = got_repo_match_object_id(&commit_id, NULL,
8474 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8475 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8476 if (error)
8477 goto done;
8480 memset(&ppa, 0, sizeof(ppa));
8481 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8482 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8483 print_patch_progress_stats(&ppa);
8484 done:
8485 got_ref_list_free(&refs);
8486 free(keyword_idstr);
8487 free(commit_id);
8488 if (repo) {
8489 close_error = got_repo_close(repo);
8490 if (error == NULL)
8491 error = close_error;
8493 if (worktree != NULL) {
8494 close_error = got_worktree_close(worktree);
8495 if (error == NULL)
8496 error = close_error;
8498 if (pack_fds) {
8499 const struct got_error *pack_err =
8500 got_repo_pack_fds_close(pack_fds);
8501 if (error == NULL)
8502 error = pack_err;
8504 free(cwd);
8505 return error;
8508 __dead static void
8509 usage_revert(void)
8511 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8512 getprogname());
8513 exit(1);
8516 static const struct got_error *
8517 revert_progress(void *arg, unsigned char status, const char *path)
8519 if (status == GOT_STATUS_UNVERSIONED)
8520 return NULL;
8522 while (path[0] == '/')
8523 path++;
8524 printf("%c %s\n", status, path);
8525 return NULL;
8528 struct choose_patch_arg {
8529 FILE *patch_script_file;
8530 const char *action;
8533 static const struct got_error *
8534 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8535 int nchanges, const char *action)
8537 const struct got_error *err;
8538 char *line = NULL;
8539 size_t linesize = 0;
8540 ssize_t linelen;
8542 switch (status) {
8543 case GOT_STATUS_ADD:
8544 printf("A %s\n%s this addition? [y/n] ", path, action);
8545 break;
8546 case GOT_STATUS_DELETE:
8547 printf("D %s\n%s this deletion? [y/n] ", path, action);
8548 break;
8549 case GOT_STATUS_MODIFY:
8550 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8551 return got_error_from_errno("fseek");
8552 printf(GOT_COMMIT_SEP_STR);
8553 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8554 printf("%s", line);
8555 if (linelen == -1 && ferror(patch_file)) {
8556 err = got_error_from_errno("getline");
8557 free(line);
8558 return err;
8560 free(line);
8561 printf(GOT_COMMIT_SEP_STR);
8562 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8563 path, n, nchanges, action);
8564 break;
8565 default:
8566 return got_error_path(path, GOT_ERR_FILE_STATUS);
8569 fflush(stdout);
8570 return NULL;
8573 static const struct got_error *
8574 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8575 FILE *patch_file, int n, int nchanges)
8577 const struct got_error *err = NULL;
8578 char *line = NULL;
8579 size_t linesize = 0;
8580 ssize_t linelen;
8581 int resp = ' ';
8582 struct choose_patch_arg *a = arg;
8584 *choice = GOT_PATCH_CHOICE_NONE;
8586 if (a->patch_script_file) {
8587 char *nl;
8588 err = show_change(status, path, patch_file, n, nchanges,
8589 a->action);
8590 if (err)
8591 return err;
8592 linelen = getline(&line, &linesize, a->patch_script_file);
8593 if (linelen == -1) {
8594 if (ferror(a->patch_script_file))
8595 return got_error_from_errno("getline");
8596 return NULL;
8598 nl = strchr(line, '\n');
8599 if (nl)
8600 *nl = '\0';
8601 if (strcmp(line, "y") == 0) {
8602 *choice = GOT_PATCH_CHOICE_YES;
8603 printf("y\n");
8604 } else if (strcmp(line, "n") == 0) {
8605 *choice = GOT_PATCH_CHOICE_NO;
8606 printf("n\n");
8607 } else if (strcmp(line, "q") == 0 &&
8608 status == GOT_STATUS_MODIFY) {
8609 *choice = GOT_PATCH_CHOICE_QUIT;
8610 printf("q\n");
8611 } else
8612 printf("invalid response '%s'\n", line);
8613 free(line);
8614 return NULL;
8617 while (resp != 'y' && resp != 'n' && resp != 'q') {
8618 err = show_change(status, path, patch_file, n, nchanges,
8619 a->action);
8620 if (err)
8621 return err;
8622 resp = getchar();
8623 if (resp == '\n')
8624 resp = getchar();
8625 if (status == GOT_STATUS_MODIFY) {
8626 if (resp != 'y' && resp != 'n' && resp != 'q') {
8627 printf("invalid response '%c'\n", resp);
8628 resp = ' ';
8630 } else if (resp != 'y' && resp != 'n') {
8631 printf("invalid response '%c'\n", resp);
8632 resp = ' ';
8636 if (resp == 'y')
8637 *choice = GOT_PATCH_CHOICE_YES;
8638 else if (resp == 'n')
8639 *choice = GOT_PATCH_CHOICE_NO;
8640 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8641 *choice = GOT_PATCH_CHOICE_QUIT;
8643 return NULL;
8646 struct wt_commitable_path_arg {
8647 struct got_pathlist_head *commit_paths;
8648 int *has_changes;
8652 * Shortcut work tree status callback to determine if the set of paths scanned
8653 * has at least one versioned path that is being modified and, if not NULL, is
8654 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8655 * soon as a path is passed with a status that satisfies this criteria.
8657 static const struct got_error *
8658 worktree_has_commitable_path(void *arg, unsigned char status,
8659 unsigned char staged_status, const char *path,
8660 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8661 struct got_object_id *commit_id, int dirfd, const char *de_name)
8663 struct wt_commitable_path_arg *a = arg;
8665 if (status == staged_status && (status == GOT_STATUS_DELETE))
8666 status = GOT_STATUS_NO_CHANGE;
8668 if (!(status == GOT_STATUS_NO_CHANGE ||
8669 status == GOT_STATUS_UNVERSIONED) ||
8670 staged_status != GOT_STATUS_NO_CHANGE) {
8671 if (a->commit_paths != NULL) {
8672 struct got_pathlist_entry *pe;
8674 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8675 if (strncmp(path, pe->path,
8676 pe->path_len) == 0) {
8677 *a->has_changes = 1;
8678 break;
8681 } else
8682 *a->has_changes = 1;
8684 if (*a->has_changes)
8685 return got_error(GOT_ERR_FILE_MODIFIED);
8688 return NULL;
8692 * Check that the changeset of the commit identified by id is
8693 * comprised of at least one modified path that is being committed.
8695 static const struct got_error *
8696 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8697 struct got_object_id *id, struct got_worktree *worktree,
8698 struct got_repository *repo)
8700 const struct got_error *err;
8701 struct got_pathlist_head paths;
8702 struct got_commit_object *commit = NULL, *pcommit = NULL;
8703 struct got_tree_object *tree = NULL, *ptree = NULL;
8704 struct got_object_qid *pid;
8706 TAILQ_INIT(&paths);
8708 err = got_object_open_as_commit(&commit, repo, id);
8709 if (err)
8710 goto done;
8712 err = got_object_open_as_tree(&tree, repo,
8713 got_object_commit_get_tree_id(commit));
8714 if (err)
8715 goto done;
8717 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8718 if (pid != NULL) {
8719 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8720 if (err)
8721 goto done;
8723 err = got_object_open_as_tree(&ptree, repo,
8724 got_object_commit_get_tree_id(pcommit));
8725 if (err)
8726 goto done;
8729 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8730 got_diff_tree_collect_changed_paths, &paths, 0);
8731 if (err)
8732 goto done;
8734 err = got_worktree_status(worktree, &paths, repo, 0,
8735 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8736 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8738 * At least one changed path in the referenced commit is
8739 * modified in the work tree, that's all we need to know!
8741 err = NULL;
8744 done:
8745 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8746 if (commit)
8747 got_object_commit_close(commit);
8748 if (pcommit)
8749 got_object_commit_close(pcommit);
8750 if (tree)
8751 got_object_tree_close(tree);
8752 if (ptree)
8753 got_object_tree_close(ptree);
8754 return err;
8758 * Remove any "logmsg" reference comprised entirely of paths that have
8759 * been reverted in this work tree. If any path in the logmsg ref changeset
8760 * remains in a changed state in the worktree, do not remove the reference.
8762 static const struct got_error *
8763 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8765 const struct got_error *err;
8766 struct got_reflist_head refs;
8767 struct got_reflist_entry *re;
8768 struct got_commit_object *commit = NULL;
8769 struct got_object_id *commit_id = NULL;
8770 struct wt_commitable_path_arg wcpa;
8771 char *uuidstr = NULL;
8773 TAILQ_INIT(&refs);
8775 err = got_worktree_get_uuid(&uuidstr, worktree);
8776 if (err)
8777 goto done;
8779 err = got_ref_list(&refs, repo, "refs/got/worktree",
8780 got_ref_cmp_by_name, repo);
8781 if (err)
8782 goto done;
8784 TAILQ_FOREACH(re, &refs, entry) {
8785 const char *refname;
8786 int has_changes = 0;
8788 refname = got_ref_get_name(re->ref);
8790 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8791 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8792 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8793 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8794 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8795 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8796 else
8797 continue;
8799 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8800 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8801 else
8802 continue;
8804 err = got_repo_match_object_id(&commit_id, NULL, refname,
8805 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8806 if (err)
8807 goto done;
8809 err = got_object_open_as_commit(&commit, repo, commit_id);
8810 if (err)
8811 goto done;
8813 wcpa.commit_paths = NULL;
8814 wcpa.has_changes = &has_changes;
8816 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8817 worktree, repo);
8818 if (err)
8819 goto done;
8821 if (!has_changes) {
8822 err = got_ref_delete(re->ref, repo);
8823 if (err)
8824 goto done;
8827 got_object_commit_close(commit);
8828 commit = NULL;
8829 free(commit_id);
8830 commit_id = NULL;
8833 done:
8834 free(uuidstr);
8835 free(commit_id);
8836 got_ref_list_free(&refs);
8837 if (commit)
8838 got_object_commit_close(commit);
8839 return err;
8842 static const struct got_error *
8843 cmd_revert(int argc, char *argv[])
8845 const struct got_error *error = NULL;
8846 struct got_worktree *worktree = NULL;
8847 struct got_repository *repo = NULL;
8848 char *cwd = NULL, *path = NULL;
8849 struct got_pathlist_head paths;
8850 struct got_pathlist_entry *pe;
8851 int ch, can_recurse = 0, pflag = 0;
8852 FILE *patch_script_file = NULL;
8853 const char *patch_script_path = NULL;
8854 struct choose_patch_arg cpa;
8855 int *pack_fds = NULL;
8857 TAILQ_INIT(&paths);
8859 #ifndef PROFILE
8860 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8861 "unveil", NULL) == -1)
8862 err(1, "pledge");
8863 #endif
8865 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8866 switch (ch) {
8867 case 'F':
8868 patch_script_path = optarg;
8869 break;
8870 case 'p':
8871 pflag = 1;
8872 break;
8873 case 'R':
8874 can_recurse = 1;
8875 break;
8876 default:
8877 usage_revert();
8878 /* NOTREACHED */
8882 argc -= optind;
8883 argv += optind;
8885 if (argc < 1)
8886 usage_revert();
8887 if (patch_script_path && !pflag)
8888 errx(1, "-F option can only be used together with -p option");
8890 cwd = getcwd(NULL, 0);
8891 if (cwd == NULL) {
8892 error = got_error_from_errno("getcwd");
8893 goto done;
8896 error = got_repo_pack_fds_open(&pack_fds);
8897 if (error != NULL)
8898 goto done;
8900 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8901 if (error) {
8902 if (error->code == GOT_ERR_NOT_WORKTREE)
8903 error = wrap_not_worktree_error(error, "revert", cwd);
8904 goto done;
8907 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8908 NULL, pack_fds);
8909 if (error != NULL)
8910 goto done;
8912 if (patch_script_path) {
8913 patch_script_file = fopen(patch_script_path, "re");
8914 if (patch_script_file == NULL) {
8915 error = got_error_from_errno2("fopen",
8916 patch_script_path);
8917 goto done;
8922 * XXX "c" perm needed on repo dir to delete merge references.
8924 error = apply_unveil(got_repo_get_path(repo), 0,
8925 got_worktree_get_root_path(worktree));
8926 if (error)
8927 goto done;
8929 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8930 if (error)
8931 goto done;
8933 if (!can_recurse) {
8934 char *ondisk_path;
8935 struct stat sb;
8936 TAILQ_FOREACH(pe, &paths, entry) {
8937 if (asprintf(&ondisk_path, "%s/%s",
8938 got_worktree_get_root_path(worktree),
8939 pe->path) == -1) {
8940 error = got_error_from_errno("asprintf");
8941 goto done;
8943 if (lstat(ondisk_path, &sb) == -1) {
8944 if (errno == ENOENT) {
8945 free(ondisk_path);
8946 continue;
8948 error = got_error_from_errno2("lstat",
8949 ondisk_path);
8950 free(ondisk_path);
8951 goto done;
8953 free(ondisk_path);
8954 if (S_ISDIR(sb.st_mode)) {
8955 error = got_error_msg(GOT_ERR_BAD_PATH,
8956 "reverting directories requires -R option");
8957 goto done;
8962 cpa.patch_script_file = patch_script_file;
8963 cpa.action = "revert";
8964 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8965 pflag ? choose_patch : NULL, &cpa, repo);
8967 error = rm_logmsg_ref(worktree, repo);
8968 done:
8969 if (patch_script_file && fclose(patch_script_file) == EOF &&
8970 error == NULL)
8971 error = got_error_from_errno2("fclose", patch_script_path);
8972 if (repo) {
8973 const struct got_error *close_err = got_repo_close(repo);
8974 if (error == NULL)
8975 error = close_err;
8977 if (worktree)
8978 got_worktree_close(worktree);
8979 if (pack_fds) {
8980 const struct got_error *pack_err =
8981 got_repo_pack_fds_close(pack_fds);
8982 if (error == NULL)
8983 error = pack_err;
8985 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8986 free(path);
8987 free(cwd);
8988 return error;
8991 __dead static void
8992 usage_commit(void)
8994 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8995 "[-m message] [path ...]\n", getprogname());
8996 exit(1);
8999 struct collect_commit_logmsg_arg {
9000 const char *cmdline_log;
9001 const char *prepared_log;
9002 const char *merged_log;
9003 int non_interactive;
9004 const char *editor;
9005 const char *worktree_path;
9006 const char *branch_name;
9007 const char *repo_path;
9008 char *logmsg_path;
9012 static const struct got_error *
9013 read_prepared_logmsg(char **logmsg, const char *path)
9015 const struct got_error *err = NULL;
9016 FILE *f = NULL;
9017 struct stat sb;
9018 size_t r;
9020 *logmsg = NULL;
9021 memset(&sb, 0, sizeof(sb));
9023 f = fopen(path, "re");
9024 if (f == NULL)
9025 return got_error_from_errno2("fopen", path);
9027 if (fstat(fileno(f), &sb) == -1) {
9028 err = got_error_from_errno2("fstat", path);
9029 goto done;
9031 if (sb.st_size == 0) {
9032 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9033 goto done;
9036 *logmsg = malloc(sb.st_size + 1);
9037 if (*logmsg == NULL) {
9038 err = got_error_from_errno("malloc");
9039 goto done;
9042 r = fread(*logmsg, 1, sb.st_size, f);
9043 if (r != sb.st_size) {
9044 if (ferror(f))
9045 err = got_error_from_errno2("fread", path);
9046 else
9047 err = got_error(GOT_ERR_IO);
9048 goto done;
9050 (*logmsg)[sb.st_size] = '\0';
9051 done:
9052 if (fclose(f) == EOF && err == NULL)
9053 err = got_error_from_errno2("fclose", path);
9054 if (err) {
9055 free(*logmsg);
9056 *logmsg = NULL;
9058 return err;
9061 static const struct got_error *
9062 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9063 const char *diff_path, char **logmsg, void *arg)
9065 char *initial_content = NULL;
9066 struct got_pathlist_entry *pe;
9067 const struct got_error *err = NULL;
9068 char *template = NULL;
9069 char *prepared_msg = NULL, *merged_msg = NULL;
9070 struct collect_commit_logmsg_arg *a = arg;
9071 int initial_content_len;
9072 int fd = -1;
9073 size_t len;
9075 /* if a message was specified on the command line, just use it */
9076 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9077 len = strlen(a->cmdline_log) + 1;
9078 *logmsg = malloc(len + 1);
9079 if (*logmsg == NULL)
9080 return got_error_from_errno("malloc");
9081 strlcpy(*logmsg, a->cmdline_log, len);
9082 return NULL;
9083 } else if (a->prepared_log != NULL && a->non_interactive)
9084 return read_prepared_logmsg(logmsg, a->prepared_log);
9086 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9087 return got_error_from_errno("asprintf");
9089 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9090 if (err)
9091 goto done;
9093 if (a->prepared_log) {
9094 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9095 if (err)
9096 goto done;
9097 } else if (a->merged_log) {
9098 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9099 if (err)
9100 goto done;
9103 initial_content_len = asprintf(&initial_content,
9104 "%s%s\n# changes to be committed on branch %s:\n",
9105 prepared_msg ? prepared_msg : "",
9106 merged_msg ? merged_msg : "", a->branch_name);
9107 if (initial_content_len == -1) {
9108 err = got_error_from_errno("asprintf");
9109 goto done;
9112 if (write(fd, initial_content, initial_content_len) == -1) {
9113 err = got_error_from_errno2("write", a->logmsg_path);
9114 goto done;
9117 TAILQ_FOREACH(pe, commitable_paths, entry) {
9118 struct got_commitable *ct = pe->data;
9119 dprintf(fd, "# %c %s\n",
9120 got_commitable_get_status(ct),
9121 got_commitable_get_path(ct));
9124 if (diff_path) {
9125 dprintf(fd, "# detailed changes can be viewed in %s\n",
9126 diff_path);
9129 if (close(fd) == -1) {
9130 err = got_error_from_errno2("close", a->logmsg_path);
9131 goto done;
9133 fd = -1;
9135 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9136 initial_content_len, a->prepared_log ? 0 : 1);
9137 done:
9138 free(initial_content);
9139 free(template);
9140 free(prepared_msg);
9141 free(merged_msg);
9143 if (fd != -1 && close(fd) == -1 && err == NULL)
9144 err = got_error_from_errno2("close", a->logmsg_path);
9146 /* Editor is done; we can now apply unveil(2) */
9147 if (err == NULL)
9148 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9149 if (err) {
9150 free(*logmsg);
9151 *logmsg = NULL;
9153 return err;
9156 static const struct got_error *
9157 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9158 const char *type, int has_content)
9160 const struct got_error *err = NULL;
9161 char *logmsg = NULL;
9163 err = got_object_commit_get_logmsg(&logmsg, commit);
9164 if (err)
9165 return err;
9167 if (fprintf(f, "%s# log message of %s commit %s:%s",
9168 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9169 err = got_ferror(f, GOT_ERR_IO);
9171 free(logmsg);
9172 return err;
9176 * Lookup "logmsg" references of backed-out and cherrypicked commits
9177 * belonging to the current work tree. If found, and the worktree has
9178 * at least one modified file that was changed in the referenced commit,
9179 * add its log message to a new temporary file at *logmsg_path.
9180 * Add all refs found to matched_refs to be scheduled for removal on
9181 * successful commit.
9183 static const struct got_error *
9184 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9185 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9186 struct got_repository *repo)
9188 const struct got_error *err;
9189 struct got_commit_object *commit = NULL;
9190 struct got_object_id *id = NULL;
9191 struct got_reflist_head refs;
9192 struct got_reflist_entry *re, *re_match;
9193 FILE *f = NULL;
9194 char *uuidstr = NULL;
9195 int added_logmsg = 0;
9197 TAILQ_INIT(&refs);
9199 *logmsg_path = NULL;
9201 err = got_worktree_get_uuid(&uuidstr, worktree);
9202 if (err)
9203 goto done;
9205 err = got_ref_list(&refs, repo, "refs/got/worktree",
9206 got_ref_cmp_by_name, repo);
9207 if (err)
9208 goto done;
9210 TAILQ_FOREACH(re, &refs, entry) {
9211 const char *refname, *type;
9212 struct wt_commitable_path_arg wcpa;
9213 int add_logmsg = 0;
9215 refname = got_ref_get_name(re->ref);
9217 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9218 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9219 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9220 type = "cherrypicked";
9221 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9222 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9223 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9224 type = "backed-out";
9225 } else
9226 continue;
9228 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9229 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9230 else
9231 continue;
9233 err = got_repo_match_object_id(&id, NULL, refname,
9234 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9235 if (err)
9236 goto done;
9238 err = got_object_open_as_commit(&commit, repo, id);
9239 if (err)
9240 goto done;
9242 wcpa.commit_paths = paths;
9243 wcpa.has_changes = &add_logmsg;
9245 err = commit_path_changed_in_worktree(&wcpa, id,
9246 worktree, repo);
9247 if (err)
9248 goto done;
9250 if (add_logmsg) {
9251 if (f == NULL) {
9252 err = got_opentemp_named(logmsg_path, &f,
9253 "got-commit-logmsg", "");
9254 if (err)
9255 goto done;
9257 err = cat_logmsg(f, commit, refname, type,
9258 added_logmsg);
9259 if (err)
9260 goto done;
9261 if (!added_logmsg)
9262 ++added_logmsg;
9264 err = got_reflist_entry_dup(&re_match, re);
9265 if (err)
9266 goto done;
9267 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9270 got_object_commit_close(commit);
9271 commit = NULL;
9272 free(id);
9273 id = NULL;
9276 done:
9277 free(id);
9278 free(uuidstr);
9279 got_ref_list_free(&refs);
9280 if (commit)
9281 got_object_commit_close(commit);
9282 if (f && fclose(f) == EOF && err == NULL)
9283 err = got_error_from_errno("fclose");
9284 if (!added_logmsg) {
9285 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9286 err = got_error_from_errno2("unlink", *logmsg_path);
9287 *logmsg_path = NULL;
9289 return err;
9292 static const struct got_error *
9293 cmd_commit(int argc, char *argv[])
9295 const struct got_error *error = NULL;
9296 struct got_worktree *worktree = NULL;
9297 struct got_repository *repo = NULL;
9298 char *cwd = NULL, *id_str = NULL;
9299 struct got_object_id *id = NULL;
9300 const char *logmsg = NULL;
9301 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9302 struct collect_commit_logmsg_arg cl_arg;
9303 const char *author = NULL;
9304 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9305 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9306 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9307 int show_diff = 1, commit_conflicts = 0;
9308 struct got_pathlist_head paths;
9309 struct got_reflist_head refs;
9310 struct got_reflist_entry *re;
9311 int *pack_fds = NULL;
9313 TAILQ_INIT(&refs);
9314 TAILQ_INIT(&paths);
9315 cl_arg.logmsg_path = NULL;
9317 #ifndef PROFILE
9318 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9319 "unveil", NULL) == -1)
9320 err(1, "pledge");
9321 #endif
9323 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9324 switch (ch) {
9325 case 'A':
9326 author = optarg;
9327 error = valid_author(author);
9328 if (error)
9329 return error;
9330 break;
9331 case 'C':
9332 commit_conflicts = 1;
9333 break;
9334 case 'F':
9335 if (logmsg != NULL)
9336 option_conflict('F', 'm');
9337 prepared_logmsg = realpath(optarg, NULL);
9338 if (prepared_logmsg == NULL)
9339 return got_error_from_errno2("realpath",
9340 optarg);
9341 break;
9342 case 'm':
9343 if (prepared_logmsg)
9344 option_conflict('m', 'F');
9345 logmsg = optarg;
9346 break;
9347 case 'N':
9348 non_interactive = 1;
9349 break;
9350 case 'n':
9351 show_diff = 0;
9352 break;
9353 case 'S':
9354 allow_bad_symlinks = 1;
9355 break;
9356 default:
9357 usage_commit();
9358 /* NOTREACHED */
9362 argc -= optind;
9363 argv += optind;
9365 cwd = getcwd(NULL, 0);
9366 if (cwd == NULL) {
9367 error = got_error_from_errno("getcwd");
9368 goto done;
9371 error = got_repo_pack_fds_open(&pack_fds);
9372 if (error != NULL)
9373 goto done;
9375 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9376 if (error) {
9377 if (error->code == GOT_ERR_NOT_WORKTREE)
9378 error = wrap_not_worktree_error(error, "commit", cwd);
9379 goto done;
9382 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9383 if (error)
9384 goto done;
9385 if (rebase_in_progress) {
9386 error = got_error(GOT_ERR_REBASING);
9387 goto done;
9390 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9391 worktree);
9392 if (error)
9393 goto done;
9395 error = get_gitconfig_path(&gitconfig_path);
9396 if (error)
9397 goto done;
9398 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9399 gitconfig_path, pack_fds);
9400 if (error != NULL)
9401 goto done;
9403 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9404 if (error)
9405 goto done;
9406 if (merge_in_progress) {
9407 error = got_error(GOT_ERR_MERGE_BUSY);
9408 goto done;
9411 error = get_author(&committer, repo, worktree);
9412 if (error)
9413 goto done;
9415 if (author == NULL)
9416 author = committer;
9419 * unveil(2) traverses exec(2); if an editor is used we have
9420 * to apply unveil after the log message has been written.
9422 if (logmsg == NULL || strlen(logmsg) == 0)
9423 error = get_editor(&editor);
9424 else
9425 error = apply_unveil(got_repo_get_path(repo), 0,
9426 got_worktree_get_root_path(worktree));
9427 if (error)
9428 goto done;
9430 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9431 if (error)
9432 goto done;
9434 if (prepared_logmsg == NULL) {
9435 error = lookup_logmsg_ref(&merged_logmsg,
9436 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9437 if (error)
9438 goto done;
9441 cl_arg.editor = editor;
9442 cl_arg.cmdline_log = logmsg;
9443 cl_arg.prepared_log = prepared_logmsg;
9444 cl_arg.merged_log = merged_logmsg;
9445 cl_arg.non_interactive = non_interactive;
9446 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9447 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9448 if (!histedit_in_progress) {
9449 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9450 error = got_error(GOT_ERR_COMMIT_BRANCH);
9451 goto done;
9453 cl_arg.branch_name += 11;
9455 cl_arg.repo_path = got_repo_get_path(repo);
9456 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9457 allow_bad_symlinks, show_diff, commit_conflicts,
9458 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9459 if (error) {
9460 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9461 cl_arg.logmsg_path != NULL)
9462 preserve_logmsg = 1;
9463 goto done;
9466 error = got_object_id_str(&id_str, id);
9467 if (error)
9468 goto done;
9469 printf("Created commit %s\n", id_str);
9471 TAILQ_FOREACH(re, &refs, entry) {
9472 error = got_ref_delete(re->ref, repo);
9473 if (error)
9474 goto done;
9477 done:
9478 if (preserve_logmsg) {
9479 fprintf(stderr, "%s: log message preserved in %s\n",
9480 getprogname(), cl_arg.logmsg_path);
9481 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9482 error == NULL)
9483 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9484 free(cl_arg.logmsg_path);
9485 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9486 error = got_error_from_errno2("unlink", merged_logmsg);
9487 free(merged_logmsg);
9488 if (repo) {
9489 const struct got_error *close_err = got_repo_close(repo);
9490 if (error == NULL)
9491 error = close_err;
9493 if (worktree)
9494 got_worktree_close(worktree);
9495 if (pack_fds) {
9496 const struct got_error *pack_err =
9497 got_repo_pack_fds_close(pack_fds);
9498 if (error == NULL)
9499 error = pack_err;
9501 got_ref_list_free(&refs);
9502 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9503 free(cwd);
9504 free(id_str);
9505 free(gitconfig_path);
9506 free(editor);
9507 free(committer);
9508 free(prepared_logmsg);
9509 return error;
9512 __dead static void
9513 usage_send(void)
9515 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9516 "[-r repository-path] [-t tag] [remote-repository]\n",
9517 getprogname());
9518 exit(1);
9521 static void
9522 print_load_info(int print_colored, int print_found, int print_trees,
9523 int ncolored, int nfound, int ntrees)
9525 if (print_colored) {
9526 printf("%d commit%s colored", ncolored,
9527 ncolored == 1 ? "" : "s");
9529 if (print_found) {
9530 printf("%s%d object%s found",
9531 ncolored > 0 ? "; " : "",
9532 nfound, nfound == 1 ? "" : "s");
9534 if (print_trees) {
9535 printf("; %d tree%s scanned", ntrees,
9536 ntrees == 1 ? "" : "s");
9540 struct got_send_progress_arg {
9541 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9542 int verbosity;
9543 int last_ncolored;
9544 int last_nfound;
9545 int last_ntrees;
9546 int loading_done;
9547 int last_ncommits;
9548 int last_nobj_total;
9549 int last_p_deltify;
9550 int last_p_written;
9551 int last_p_sent;
9552 int printed_something;
9553 int sent_something;
9554 struct got_pathlist_head *delete_branches;
9557 static const struct got_error *
9558 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9559 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9560 int nobj_written, off_t bytes_sent, const char *refname,
9561 const char *errmsg, int success)
9563 struct got_send_progress_arg *a = arg;
9564 char scaled_packsize[FMT_SCALED_STRSIZE];
9565 char scaled_sent[FMT_SCALED_STRSIZE];
9566 int p_deltify = 0, p_written = 0, p_sent = 0;
9567 int print_colored = 0, print_found = 0, print_trees = 0;
9568 int print_searching = 0, print_total = 0;
9569 int print_deltify = 0, print_written = 0, print_sent = 0;
9571 if (a->verbosity < 0)
9572 return NULL;
9574 if (refname) {
9575 const char *status = success ? "accepted" : "rejected";
9577 if (success) {
9578 struct got_pathlist_entry *pe;
9579 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9580 const char *branchname = pe->path;
9581 if (got_path_cmp(branchname, refname,
9582 strlen(branchname), strlen(refname)) == 0) {
9583 status = "deleted";
9584 a->sent_something = 1;
9585 break;
9590 if (a->printed_something)
9591 putchar('\n');
9592 printf("Server has %s %s", status, refname);
9593 if (errmsg)
9594 printf(": %s", errmsg);
9595 a->printed_something = 1;
9596 return NULL;
9599 if (a->last_ncolored != ncolored) {
9600 print_colored = 1;
9601 a->last_ncolored = ncolored;
9604 if (a->last_nfound != nfound) {
9605 print_colored = 1;
9606 print_found = 1;
9607 a->last_nfound = nfound;
9610 if (a->last_ntrees != ntrees) {
9611 print_colored = 1;
9612 print_found = 1;
9613 print_trees = 1;
9614 a->last_ntrees = ntrees;
9617 if ((print_colored || print_found || print_trees) &&
9618 !a->loading_done) {
9619 printf("\r");
9620 print_load_info(print_colored, print_found, print_trees,
9621 ncolored, nfound, ntrees);
9622 a->printed_something = 1;
9623 fflush(stdout);
9624 return NULL;
9625 } else if (!a->loading_done) {
9626 printf("\r");
9627 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9628 printf("\n");
9629 a->loading_done = 1;
9632 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9633 return got_error_from_errno("fmt_scaled");
9634 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9635 return got_error_from_errno("fmt_scaled");
9637 if (a->last_ncommits != ncommits) {
9638 print_searching = 1;
9639 a->last_ncommits = ncommits;
9642 if (a->last_nobj_total != nobj_total) {
9643 print_searching = 1;
9644 print_total = 1;
9645 a->last_nobj_total = nobj_total;
9648 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9649 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9650 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9651 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9652 return got_error(GOT_ERR_NO_SPACE);
9655 if (nobj_deltify > 0 || nobj_written > 0) {
9656 if (nobj_deltify > 0) {
9657 p_deltify = (nobj_deltify * 100) / nobj_total;
9658 if (p_deltify != a->last_p_deltify) {
9659 a->last_p_deltify = p_deltify;
9660 print_searching = 1;
9661 print_total = 1;
9662 print_deltify = 1;
9665 if (nobj_written > 0) {
9666 p_written = (nobj_written * 100) / nobj_total;
9667 if (p_written != a->last_p_written) {
9668 a->last_p_written = p_written;
9669 print_searching = 1;
9670 print_total = 1;
9671 print_deltify = 1;
9672 print_written = 1;
9677 if (bytes_sent > 0) {
9678 p_sent = (bytes_sent * 100) / packfile_size;
9679 if (p_sent != a->last_p_sent) {
9680 a->last_p_sent = p_sent;
9681 print_searching = 1;
9682 print_total = 1;
9683 print_deltify = 1;
9684 print_written = 1;
9685 print_sent = 1;
9687 a->sent_something = 1;
9690 if (print_searching || print_total || print_deltify || print_written ||
9691 print_sent)
9692 printf("\r");
9693 if (print_searching)
9694 printf("packing %d reference%s", ncommits,
9695 ncommits == 1 ? "" : "s");
9696 if (print_total)
9697 printf("; %d object%s", nobj_total,
9698 nobj_total == 1 ? "" : "s");
9699 if (print_deltify)
9700 printf("; deltify: %d%%", p_deltify);
9701 if (print_sent)
9702 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9703 scaled_packsize, p_sent);
9704 else if (print_written)
9705 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9706 scaled_packsize, p_written);
9707 if (print_searching || print_total || print_deltify ||
9708 print_written || print_sent) {
9709 a->printed_something = 1;
9710 fflush(stdout);
9712 return NULL;
9715 static const struct got_error *
9716 cmd_send(int argc, char *argv[])
9718 const struct got_error *error = NULL;
9719 char *cwd = NULL, *repo_path = NULL;
9720 const char *remote_name;
9721 char *proto = NULL, *host = NULL, *port = NULL;
9722 char *repo_name = NULL, *server_path = NULL;
9723 const struct got_remote_repo *remotes;
9724 struct got_remote_repo *remote = NULL;
9725 int nremotes, nbranches = 0, ndelete_branches = 0;
9726 struct got_repository *repo = NULL;
9727 struct got_worktree *worktree = NULL;
9728 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9729 struct got_pathlist_head branches;
9730 struct got_pathlist_head tags;
9731 struct got_reflist_head all_branches;
9732 struct got_reflist_head all_tags;
9733 struct got_pathlist_head delete_args;
9734 struct got_pathlist_head delete_branches;
9735 struct got_reflist_entry *re;
9736 struct got_pathlist_entry *pe;
9737 int i, ch, sendfd = -1, sendstatus;
9738 pid_t sendpid = -1;
9739 struct got_send_progress_arg spa;
9740 int verbosity = 0, overwrite_refs = 0;
9741 int send_all_branches = 0, send_all_tags = 0;
9742 struct got_reference *ref = NULL;
9743 int *pack_fds = NULL;
9745 TAILQ_INIT(&branches);
9746 TAILQ_INIT(&tags);
9747 TAILQ_INIT(&all_branches);
9748 TAILQ_INIT(&all_tags);
9749 TAILQ_INIT(&delete_args);
9750 TAILQ_INIT(&delete_branches);
9752 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9753 switch (ch) {
9754 case 'a':
9755 send_all_branches = 1;
9756 break;
9757 case 'b':
9758 error = got_pathlist_append(&branches, optarg, NULL);
9759 if (error)
9760 return error;
9761 nbranches++;
9762 break;
9763 case 'd':
9764 error = got_pathlist_append(&delete_args, optarg, NULL);
9765 if (error)
9766 return error;
9767 break;
9768 case 'f':
9769 overwrite_refs = 1;
9770 break;
9771 case 'q':
9772 verbosity = -1;
9773 break;
9774 case 'r':
9775 repo_path = realpath(optarg, NULL);
9776 if (repo_path == NULL)
9777 return got_error_from_errno2("realpath",
9778 optarg);
9779 got_path_strip_trailing_slashes(repo_path);
9780 break;
9781 case 'T':
9782 send_all_tags = 1;
9783 break;
9784 case 't':
9785 error = got_pathlist_append(&tags, optarg, NULL);
9786 if (error)
9787 return error;
9788 break;
9789 case 'v':
9790 if (verbosity < 0)
9791 verbosity = 0;
9792 else if (verbosity < 3)
9793 verbosity++;
9794 break;
9795 default:
9796 usage_send();
9797 /* NOTREACHED */
9800 argc -= optind;
9801 argv += optind;
9803 if (send_all_branches && !TAILQ_EMPTY(&branches))
9804 option_conflict('a', 'b');
9805 if (send_all_tags && !TAILQ_EMPTY(&tags))
9806 option_conflict('T', 't');
9809 if (argc == 0)
9810 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9811 else if (argc == 1)
9812 remote_name = argv[0];
9813 else
9814 usage_send();
9816 cwd = getcwd(NULL, 0);
9817 if (cwd == NULL) {
9818 error = got_error_from_errno("getcwd");
9819 goto done;
9822 error = got_repo_pack_fds_open(&pack_fds);
9823 if (error != NULL)
9824 goto done;
9826 if (repo_path == NULL) {
9827 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9828 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9829 goto done;
9830 else
9831 error = NULL;
9832 if (worktree) {
9833 repo_path =
9834 strdup(got_worktree_get_repo_path(worktree));
9835 if (repo_path == NULL)
9836 error = got_error_from_errno("strdup");
9837 if (error)
9838 goto done;
9839 } else {
9840 repo_path = strdup(cwd);
9841 if (repo_path == NULL) {
9842 error = got_error_from_errno("strdup");
9843 goto done;
9848 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9849 if (error)
9850 goto done;
9852 if (worktree) {
9853 worktree_conf = got_worktree_get_gotconfig(worktree);
9854 if (worktree_conf) {
9855 got_gotconfig_get_remotes(&nremotes, &remotes,
9856 worktree_conf);
9857 for (i = 0; i < nremotes; i++) {
9858 if (strcmp(remotes[i].name, remote_name) == 0) {
9859 error = got_repo_remote_repo_dup(&remote,
9860 &remotes[i]);
9861 if (error)
9862 goto done;
9863 break;
9868 if (remote == NULL) {
9869 repo_conf = got_repo_get_gotconfig(repo);
9870 if (repo_conf) {
9871 got_gotconfig_get_remotes(&nremotes, &remotes,
9872 repo_conf);
9873 for (i = 0; i < nremotes; i++) {
9874 if (strcmp(remotes[i].name, remote_name) == 0) {
9875 error = got_repo_remote_repo_dup(&remote,
9876 &remotes[i]);
9877 if (error)
9878 goto done;
9879 break;
9884 if (remote == NULL) {
9885 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9886 for (i = 0; i < nremotes; i++) {
9887 if (strcmp(remotes[i].name, remote_name) == 0) {
9888 error = got_repo_remote_repo_dup(&remote,
9889 &remotes[i]);
9890 if (error)
9891 goto done;
9892 break;
9896 if (remote == NULL) {
9897 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9898 goto done;
9901 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9902 &repo_name, remote->send_url);
9903 if (error)
9904 goto done;
9906 if (strcmp(proto, "git") == 0) {
9907 #ifndef PROFILE
9908 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9909 "sendfd dns inet unveil", NULL) == -1)
9910 err(1, "pledge");
9911 #endif
9912 } else if (strcmp(proto, "git+ssh") == 0 ||
9913 strcmp(proto, "ssh") == 0) {
9914 #ifndef PROFILE
9915 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9916 "sendfd unveil", NULL) == -1)
9917 err(1, "pledge");
9918 #endif
9919 } else if (strcmp(proto, "http") == 0 ||
9920 strcmp(proto, "git+http") == 0) {
9921 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9922 goto done;
9923 } else {
9924 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9925 goto done;
9928 error = got_dial_apply_unveil(proto);
9929 if (error)
9930 goto done;
9932 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9933 if (error)
9934 goto done;
9936 if (send_all_branches) {
9937 error = got_ref_list(&all_branches, repo, "refs/heads",
9938 got_ref_cmp_by_name, NULL);
9939 if (error)
9940 goto done;
9941 TAILQ_FOREACH(re, &all_branches, entry) {
9942 const char *branchname = got_ref_get_name(re->ref);
9943 error = got_pathlist_append(&branches,
9944 branchname, NULL);
9945 if (error)
9946 goto done;
9947 nbranches++;
9949 } else if (nbranches == 0) {
9950 for (i = 0; i < remote->nsend_branches; i++) {
9951 error = got_pathlist_append(&branches,
9952 remote->send_branches[i], NULL);
9953 if (error)
9954 goto done;
9958 if (send_all_tags) {
9959 error = got_ref_list(&all_tags, repo, "refs/tags",
9960 got_ref_cmp_by_name, NULL);
9961 if (error)
9962 goto done;
9963 TAILQ_FOREACH(re, &all_tags, entry) {
9964 const char *tagname = got_ref_get_name(re->ref);
9965 error = got_pathlist_append(&tags,
9966 tagname, NULL);
9967 if (error)
9968 goto done;
9973 * To prevent accidents only branches in refs/heads/ can be deleted
9974 * with 'got send -d'.
9975 * Deleting anything else requires local repository access or Git.
9977 TAILQ_FOREACH(pe, &delete_args, entry) {
9978 const char *branchname = pe->path;
9979 char *s;
9980 struct got_pathlist_entry *new;
9981 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9982 s = strdup(branchname);
9983 if (s == NULL) {
9984 error = got_error_from_errno("strdup");
9985 goto done;
9987 } else {
9988 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9989 error = got_error_from_errno("asprintf");
9990 goto done;
9993 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9994 if (error || new == NULL /* duplicate */)
9995 free(s);
9996 if (error)
9997 goto done;
9998 ndelete_branches++;
10001 if (nbranches == 0 && ndelete_branches == 0) {
10002 struct got_reference *head_ref;
10003 if (worktree)
10004 error = got_ref_open(&head_ref, repo,
10005 got_worktree_get_head_ref_name(worktree), 0);
10006 else
10007 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10008 if (error)
10009 goto done;
10010 if (got_ref_is_symbolic(head_ref)) {
10011 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10012 got_ref_close(head_ref);
10013 if (error)
10014 goto done;
10015 } else
10016 ref = head_ref;
10017 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10018 NULL);
10019 if (error)
10020 goto done;
10021 nbranches++;
10024 if (worktree) {
10025 /* Release work tree lock. */
10026 got_worktree_close(worktree);
10027 worktree = NULL;
10030 if (verbosity >= 0) {
10031 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10032 remote->name, proto, host,
10033 port ? ":" : "", port ? port : "",
10034 *server_path == '/' ? "" : "/", server_path);
10037 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10038 server_path, verbosity);
10039 if (error)
10040 goto done;
10042 memset(&spa, 0, sizeof(spa));
10043 spa.last_scaled_packsize[0] = '\0';
10044 spa.last_p_deltify = -1;
10045 spa.last_p_written = -1;
10046 spa.verbosity = verbosity;
10047 spa.delete_branches = &delete_branches;
10048 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10049 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10050 check_cancelled, NULL);
10051 if (spa.printed_something)
10052 putchar('\n');
10053 if (error)
10054 goto done;
10055 if (!spa.sent_something && verbosity >= 0)
10056 printf("Already up-to-date\n");
10057 done:
10058 if (sendpid > 0) {
10059 if (kill(sendpid, SIGTERM) == -1)
10060 error = got_error_from_errno("kill");
10061 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10062 error = got_error_from_errno("waitpid");
10064 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10065 error = got_error_from_errno("close");
10066 if (repo) {
10067 const struct got_error *close_err = got_repo_close(repo);
10068 if (error == NULL)
10069 error = close_err;
10071 if (worktree)
10072 got_worktree_close(worktree);
10073 if (pack_fds) {
10074 const struct got_error *pack_err =
10075 got_repo_pack_fds_close(pack_fds);
10076 if (error == NULL)
10077 error = pack_err;
10079 if (ref)
10080 got_ref_close(ref);
10081 got_repo_free_remote_repo_data(remote);
10082 free(remote);
10083 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10084 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10085 got_ref_list_free(&all_branches);
10086 got_ref_list_free(&all_tags);
10087 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10088 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10089 free(cwd);
10090 free(repo_path);
10091 free(proto);
10092 free(host);
10093 free(port);
10094 free(server_path);
10095 free(repo_name);
10096 return error;
10100 * Print and if delete is set delete all ref_prefix references.
10101 * If wanted_ref is not NULL, only print or delete this reference.
10103 static const struct got_error *
10104 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10105 const char *wanted_ref, int delete, struct got_worktree *worktree,
10106 struct got_repository *repo)
10108 const struct got_error *err;
10109 struct got_pathlist_head paths;
10110 struct got_reflist_head refs;
10111 struct got_reflist_entry *re;
10112 struct got_reflist_object_id_map *refs_idmap = NULL;
10113 struct got_commit_object *commit = NULL;
10114 struct got_object_id *id = NULL;
10115 const char *header_prefix;
10116 char *uuidstr = NULL;
10117 int found = 0;
10119 TAILQ_INIT(&refs);
10120 TAILQ_INIT(&paths);
10122 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10123 if (err)
10124 goto done;
10126 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10127 if (err)
10128 goto done;
10130 if (worktree != NULL) {
10131 err = got_worktree_get_uuid(&uuidstr, worktree);
10132 if (err)
10133 goto done;
10136 if (wanted_ref) {
10137 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10138 wanted_ref += 11;
10141 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10142 header_prefix = "backout";
10143 else
10144 header_prefix = "cherrypick";
10146 TAILQ_FOREACH(re, &refs, entry) {
10147 const char *refname, *wt;
10149 refname = got_ref_get_name(re->ref);
10151 err = check_cancelled(NULL);
10152 if (err)
10153 goto done;
10155 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10156 refname += prefix_len + 1; /* skip '-' delimiter */
10157 else
10158 continue;
10160 wt = refname;
10162 if (worktree == NULL || strncmp(refname, uuidstr,
10163 GOT_WORKTREE_UUID_STRLEN) == 0)
10164 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10165 else
10166 continue;
10168 err = got_repo_match_object_id(&id, NULL, refname,
10169 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10170 if (err)
10171 goto done;
10173 err = got_object_open_as_commit(&commit, repo, id);
10174 if (err)
10175 goto done;
10177 if (wanted_ref)
10178 found = strncmp(wanted_ref, refname,
10179 strlen(wanted_ref)) == 0;
10180 if (wanted_ref && !found) {
10181 struct got_reflist_head *ci_refs;
10183 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10184 id);
10186 if (ci_refs) {
10187 char *refs_str = NULL;
10188 char const *r = NULL;
10190 err = build_refs_str(&refs_str, ci_refs, id,
10191 repo, 1);
10192 if (err)
10193 goto done;
10195 r = refs_str;
10196 while (r) {
10197 if (strncmp(r, wanted_ref,
10198 strlen(wanted_ref)) == 0) {
10199 found = 1;
10200 break;
10202 r = strchr(r, ' ');
10203 if (r)
10204 ++r;
10206 free(refs_str);
10210 if (wanted_ref == NULL || found) {
10211 if (delete) {
10212 err = got_ref_delete(re->ref, repo);
10213 if (err)
10214 goto done;
10215 printf("Deleted: ");
10216 err = print_commit_oneline(commit, id, repo,
10217 refs_idmap);
10218 } else {
10220 * Print paths modified by commit to help
10221 * associate commits with worktree changes.
10223 err = get_changed_paths(&paths, commit,
10224 repo, NULL);
10225 if (err)
10226 goto done;
10228 err = print_commit(commit, id, repo, NULL,
10229 &paths, NULL, 0, 0, refs_idmap, NULL,
10230 header_prefix);
10231 got_pathlist_free(&paths,
10232 GOT_PATHLIST_FREE_ALL);
10234 if (worktree == NULL)
10235 printf("work tree: %.*s\n\n",
10236 GOT_WORKTREE_UUID_STRLEN, wt);
10238 if (err || found)
10239 goto done;
10242 got_object_commit_close(commit);
10243 commit = NULL;
10244 free(id);
10245 id = NULL;
10248 if (wanted_ref != NULL && !found)
10249 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10251 done:
10252 free(id);
10253 free(uuidstr);
10254 got_ref_list_free(&refs);
10255 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10256 if (refs_idmap)
10257 got_reflist_object_id_map_free(refs_idmap);
10258 if (commit)
10259 got_object_commit_close(commit);
10260 return err;
10264 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10265 * identified by id for log messages to prepopulate the editor on commit.
10267 static const struct got_error *
10268 logmsg_ref(struct got_object_id *id, const char *prefix,
10269 struct got_worktree *worktree, struct got_repository *repo)
10271 const struct got_error *err = NULL;
10272 char *idstr, *ref = NULL, *refname = NULL;
10273 int histedit_in_progress;
10274 int rebase_in_progress, merge_in_progress;
10277 * Silenty refuse to create merge reference if any histedit, merge,
10278 * or rebase operation is in progress.
10280 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10281 worktree);
10282 if (err)
10283 return err;
10284 if (histedit_in_progress)
10285 return NULL;
10287 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10288 if (err)
10289 return err;
10290 if (rebase_in_progress)
10291 return NULL;
10293 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10294 repo);
10295 if (err)
10296 return err;
10297 if (merge_in_progress)
10298 return NULL;
10300 err = got_object_id_str(&idstr, id);
10301 if (err)
10302 return err;
10304 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10305 if (err)
10306 goto done;
10308 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10309 err = got_error_from_errno("asprintf");
10310 goto done;
10313 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10314 -1, repo);
10315 done:
10316 free(ref);
10317 free(idstr);
10318 free(refname);
10319 return err;
10322 __dead static void
10323 usage_cherrypick(void)
10325 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10326 getprogname());
10327 exit(1);
10330 static const struct got_error *
10331 cmd_cherrypick(int argc, char *argv[])
10333 const struct got_error *error = NULL;
10334 struct got_worktree *worktree = NULL;
10335 struct got_repository *repo = NULL;
10336 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10337 struct got_object_id *commit_id = NULL;
10338 struct got_commit_object *commit = NULL;
10339 struct got_object_qid *pid;
10340 int ch, list_refs = 0, remove_refs = 0;
10341 struct got_update_progress_arg upa;
10342 int *pack_fds = NULL;
10344 #ifndef PROFILE
10345 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10346 "unveil", NULL) == -1)
10347 err(1, "pledge");
10348 #endif
10350 while ((ch = getopt(argc, argv, "lX")) != -1) {
10351 switch (ch) {
10352 case 'l':
10353 list_refs = 1;
10354 break;
10355 case 'X':
10356 remove_refs = 1;
10357 break;
10358 default:
10359 usage_cherrypick();
10360 /* NOTREACHED */
10364 argc -= optind;
10365 argv += optind;
10367 if (list_refs || remove_refs) {
10368 if (argc != 0 && argc != 1)
10369 usage_cherrypick();
10370 } else if (argc != 1)
10371 usage_cherrypick();
10372 if (list_refs && remove_refs)
10373 option_conflict('l', 'X');
10375 cwd = getcwd(NULL, 0);
10376 if (cwd == NULL) {
10377 error = got_error_from_errno("getcwd");
10378 goto done;
10381 error = got_repo_pack_fds_open(&pack_fds);
10382 if (error != NULL)
10383 goto done;
10385 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10386 if (error) {
10387 if (list_refs || remove_refs) {
10388 if (error->code != GOT_ERR_NOT_WORKTREE)
10389 goto done;
10390 } else {
10391 if (error->code == GOT_ERR_NOT_WORKTREE)
10392 error = wrap_not_worktree_error(error,
10393 "cherrypick", cwd);
10394 goto done;
10398 error = got_repo_open(&repo,
10399 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10400 NULL, pack_fds);
10401 if (error != NULL)
10402 goto done;
10404 error = apply_unveil(got_repo_get_path(repo), 0,
10405 worktree ? got_worktree_get_root_path(worktree) : NULL);
10406 if (error)
10407 goto done;
10409 if (list_refs || remove_refs) {
10410 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10411 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10412 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10413 goto done;
10416 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10417 if (error != NULL)
10418 goto done;
10420 error = got_repo_match_object_id(&commit_id, NULL,
10421 keyword_idstr != NULL ? keyword_idstr : argv[0],
10422 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10423 if (error)
10424 goto done;
10425 error = got_object_id_str(&commit_id_str, commit_id);
10426 if (error)
10427 goto done;
10429 error = got_object_open_as_commit(&commit, repo, commit_id);
10430 if (error)
10431 goto done;
10432 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10433 memset(&upa, 0, sizeof(upa));
10434 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10435 commit_id, repo, update_progress, &upa, check_cancelled,
10436 NULL);
10437 if (error != NULL)
10438 goto done;
10440 if (upa.did_something) {
10441 error = logmsg_ref(commit_id,
10442 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10443 if (error)
10444 goto done;
10445 printf("Merged commit %s\n", commit_id_str);
10447 print_merge_progress_stats(&upa);
10448 done:
10449 free(cwd);
10450 free(keyword_idstr);
10451 if (commit)
10452 got_object_commit_close(commit);
10453 free(commit_id_str);
10454 if (worktree)
10455 got_worktree_close(worktree);
10456 if (repo) {
10457 const struct got_error *close_err = got_repo_close(repo);
10458 if (error == NULL)
10459 error = close_err;
10461 if (pack_fds) {
10462 const struct got_error *pack_err =
10463 got_repo_pack_fds_close(pack_fds);
10464 if (error == NULL)
10465 error = pack_err;
10468 return error;
10471 __dead static void
10472 usage_backout(void)
10474 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10475 exit(1);
10478 static const struct got_error *
10479 cmd_backout(int argc, char *argv[])
10481 const struct got_error *error = NULL;
10482 struct got_worktree *worktree = NULL;
10483 struct got_repository *repo = NULL;
10484 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10485 struct got_object_id *commit_id = NULL;
10486 struct got_commit_object *commit = NULL;
10487 struct got_object_qid *pid;
10488 int ch, list_refs = 0, remove_refs = 0;
10489 struct got_update_progress_arg upa;
10490 int *pack_fds = NULL;
10492 #ifndef PROFILE
10493 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10494 "unveil", NULL) == -1)
10495 err(1, "pledge");
10496 #endif
10498 while ((ch = getopt(argc, argv, "lX")) != -1) {
10499 switch (ch) {
10500 case 'l':
10501 list_refs = 1;
10502 break;
10503 case 'X':
10504 remove_refs = 1;
10505 break;
10506 default:
10507 usage_backout();
10508 /* NOTREACHED */
10512 argc -= optind;
10513 argv += optind;
10515 if (list_refs || remove_refs) {
10516 if (argc != 0 && argc != 1)
10517 usage_backout();
10518 } else if (argc != 1)
10519 usage_backout();
10520 if (list_refs && remove_refs)
10521 option_conflict('l', 'X');
10523 cwd = getcwd(NULL, 0);
10524 if (cwd == NULL) {
10525 error = got_error_from_errno("getcwd");
10526 goto done;
10529 error = got_repo_pack_fds_open(&pack_fds);
10530 if (error != NULL)
10531 goto done;
10533 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10534 if (error) {
10535 if (list_refs || remove_refs) {
10536 if (error->code != GOT_ERR_NOT_WORKTREE)
10537 goto done;
10538 } else {
10539 if (error->code == GOT_ERR_NOT_WORKTREE)
10540 error = wrap_not_worktree_error(error,
10541 "backout", cwd);
10542 goto done;
10546 error = got_repo_open(&repo,
10547 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10548 NULL, pack_fds);
10549 if (error != NULL)
10550 goto done;
10552 error = apply_unveil(got_repo_get_path(repo), 0,
10553 worktree ? got_worktree_get_root_path(worktree) : NULL);
10554 if (error)
10555 goto done;
10557 if (list_refs || remove_refs) {
10558 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10559 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10560 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10561 goto done;
10564 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10565 if (error != NULL)
10566 goto done;
10568 error = got_repo_match_object_id(&commit_id, NULL,
10569 keyword_idstr != NULL ? keyword_idstr : argv[0],
10570 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10571 if (error)
10572 goto done;
10573 error = got_object_id_str(&commit_id_str, commit_id);
10574 if (error)
10575 goto done;
10577 error = got_object_open_as_commit(&commit, repo, commit_id);
10578 if (error)
10579 goto done;
10580 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10581 if (pid == NULL) {
10582 error = got_error(GOT_ERR_ROOT_COMMIT);
10583 goto done;
10586 memset(&upa, 0, sizeof(upa));
10587 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10588 repo, update_progress, &upa, check_cancelled, NULL);
10589 if (error != NULL)
10590 goto done;
10592 if (upa.did_something) {
10593 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10594 worktree, repo);
10595 if (error)
10596 goto done;
10597 printf("Backed out commit %s\n", commit_id_str);
10599 print_merge_progress_stats(&upa);
10600 done:
10601 free(cwd);
10602 free(keyword_idstr);
10603 if (commit)
10604 got_object_commit_close(commit);
10605 free(commit_id_str);
10606 if (worktree)
10607 got_worktree_close(worktree);
10608 if (repo) {
10609 const struct got_error *close_err = got_repo_close(repo);
10610 if (error == NULL)
10611 error = close_err;
10613 if (pack_fds) {
10614 const struct got_error *pack_err =
10615 got_repo_pack_fds_close(pack_fds);
10616 if (error == NULL)
10617 error = pack_err;
10619 return error;
10622 __dead static void
10623 usage_rebase(void)
10625 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10626 exit(1);
10629 static void
10630 trim_logmsg(char *logmsg, int limit)
10632 char *nl;
10633 size_t len;
10635 len = strlen(logmsg);
10636 if (len > limit)
10637 len = limit;
10638 logmsg[len] = '\0';
10639 nl = strchr(logmsg, '\n');
10640 if (nl)
10641 *nl = '\0';
10644 static const struct got_error *
10645 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10647 const struct got_error *err;
10648 char *logmsg0 = NULL;
10649 const char *s;
10651 err = got_object_commit_get_logmsg(&logmsg0, commit);
10652 if (err)
10653 return err;
10655 s = logmsg0;
10656 while (isspace((unsigned char)s[0]))
10657 s++;
10659 *logmsg = strdup(s);
10660 if (*logmsg == NULL) {
10661 err = got_error_from_errno("strdup");
10662 goto done;
10665 trim_logmsg(*logmsg, limit);
10666 done:
10667 free(logmsg0);
10668 return err;
10671 static const struct got_error *
10672 show_rebase_merge_conflict(struct got_object_id *id,
10673 struct got_repository *repo)
10675 const struct got_error *err;
10676 struct got_commit_object *commit = NULL;
10677 char *id_str = NULL, *logmsg = NULL;
10679 err = got_object_open_as_commit(&commit, repo, id);
10680 if (err)
10681 return err;
10683 err = got_object_id_str(&id_str, id);
10684 if (err)
10685 goto done;
10687 id_str[12] = '\0';
10689 err = get_short_logmsg(&logmsg, 42, commit);
10690 if (err)
10691 goto done;
10693 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10694 done:
10695 free(id_str);
10696 got_object_commit_close(commit);
10697 free(logmsg);
10698 return err;
10701 static const struct got_error *
10702 show_rebase_progress(struct got_commit_object *commit,
10703 struct got_object_id *old_id, struct got_object_id *new_id)
10705 const struct got_error *err;
10706 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10708 err = got_object_id_str(&old_id_str, old_id);
10709 if (err)
10710 goto done;
10712 if (new_id) {
10713 err = got_object_id_str(&new_id_str, new_id);
10714 if (err)
10715 goto done;
10718 old_id_str[12] = '\0';
10719 if (new_id_str)
10720 new_id_str[12] = '\0';
10722 err = get_short_logmsg(&logmsg, 42, commit);
10723 if (err)
10724 goto done;
10726 printf("%s -> %s: %s\n", old_id_str,
10727 new_id_str ? new_id_str : "no-op change", logmsg);
10728 done:
10729 free(old_id_str);
10730 free(new_id_str);
10731 free(logmsg);
10732 return err;
10735 static const struct got_error *
10736 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10737 struct got_reference *branch, struct got_reference *tmp_branch,
10738 struct got_repository *repo, int create_backup)
10740 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10741 return got_worktree_rebase_complete(worktree, fileindex,
10742 tmp_branch, branch, repo, create_backup);
10745 static const struct got_error *
10746 rebase_commit(struct got_pathlist_head *merged_paths,
10747 struct got_worktree *worktree, struct got_fileindex *fileindex,
10748 struct got_reference *tmp_branch, const char *committer,
10749 struct got_object_id *commit_id, int allow_conflict,
10750 struct got_repository *repo)
10752 const struct got_error *error;
10753 struct got_commit_object *commit;
10754 struct got_object_id *new_commit_id;
10756 error = got_object_open_as_commit(&commit, repo, commit_id);
10757 if (error)
10758 return error;
10760 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10761 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10762 allow_conflict, repo);
10763 if (error) {
10764 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10765 goto done;
10766 error = show_rebase_progress(commit, commit_id, NULL);
10767 } else {
10768 error = show_rebase_progress(commit, commit_id, new_commit_id);
10769 free(new_commit_id);
10771 done:
10772 got_object_commit_close(commit);
10773 return error;
10776 struct check_path_prefix_arg {
10777 const char *path_prefix;
10778 size_t len;
10779 int errcode;
10782 static const struct got_error *
10783 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10784 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10785 struct got_object_id *id1, struct got_object_id *id2,
10786 const char *path1, const char *path2,
10787 mode_t mode1, mode_t mode2, struct got_repository *repo)
10789 struct check_path_prefix_arg *a = arg;
10791 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10792 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10793 return got_error(a->errcode);
10795 return NULL;
10798 static const struct got_error *
10799 check_path_prefix(struct got_object_id *parent_id,
10800 struct got_object_id *commit_id, const char *path_prefix,
10801 int errcode, struct got_repository *repo)
10803 const struct got_error *err;
10804 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10805 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10806 struct check_path_prefix_arg cpp_arg;
10808 if (got_path_is_root_dir(path_prefix))
10809 return NULL;
10811 err = got_object_open_as_commit(&commit, repo, commit_id);
10812 if (err)
10813 goto done;
10815 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10816 if (err)
10817 goto done;
10819 err = got_object_open_as_tree(&tree1, repo,
10820 got_object_commit_get_tree_id(parent_commit));
10821 if (err)
10822 goto done;
10824 err = got_object_open_as_tree(&tree2, repo,
10825 got_object_commit_get_tree_id(commit));
10826 if (err)
10827 goto done;
10829 cpp_arg.path_prefix = path_prefix;
10830 while (cpp_arg.path_prefix[0] == '/')
10831 cpp_arg.path_prefix++;
10832 cpp_arg.len = strlen(cpp_arg.path_prefix);
10833 cpp_arg.errcode = errcode;
10834 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10835 check_path_prefix_in_diff, &cpp_arg, 0);
10836 done:
10837 if (tree1)
10838 got_object_tree_close(tree1);
10839 if (tree2)
10840 got_object_tree_close(tree2);
10841 if (commit)
10842 got_object_commit_close(commit);
10843 if (parent_commit)
10844 got_object_commit_close(parent_commit);
10845 return err;
10848 static const struct got_error *
10849 collect_commits(struct got_object_id_queue *commits,
10850 struct got_object_id *initial_commit_id,
10851 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10852 const char *path_prefix, int path_prefix_errcode,
10853 struct got_repository *repo)
10855 const struct got_error *err = NULL;
10856 struct got_commit_graph *graph = NULL;
10857 struct got_object_id parent_id, commit_id;
10858 struct got_object_qid *qid;
10860 err = got_commit_graph_open(&graph, "/", 1);
10861 if (err)
10862 return err;
10864 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10865 check_cancelled, NULL);
10866 if (err)
10867 goto done;
10869 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10870 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10871 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10872 check_cancelled, NULL);
10873 if (err) {
10874 if (err->code == GOT_ERR_ITER_COMPLETED) {
10875 err = got_error_msg(GOT_ERR_ANCESTRY,
10876 "ran out of commits to rebase before "
10877 "youngest common ancestor commit has "
10878 "been reached?!?");
10880 goto done;
10881 } else {
10882 err = check_path_prefix(&parent_id, &commit_id,
10883 path_prefix, path_prefix_errcode, repo);
10884 if (err)
10885 goto done;
10887 err = got_object_qid_alloc(&qid, &commit_id);
10888 if (err)
10889 goto done;
10890 STAILQ_INSERT_HEAD(commits, qid, entry);
10892 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10895 done:
10896 got_commit_graph_close(graph);
10897 return err;
10900 static const struct got_error *
10901 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10903 const struct got_error *err = NULL;
10904 time_t committer_time;
10905 struct tm tm;
10906 char datebuf[11]; /* YYYY-MM-DD + NUL */
10907 char *author0 = NULL, *author, *smallerthan;
10908 char *logmsg0 = NULL, *logmsg, *newline;
10910 committer_time = got_object_commit_get_committer_time(commit);
10911 if (gmtime_r(&committer_time, &tm) == NULL)
10912 return got_error_from_errno("gmtime_r");
10913 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10914 return got_error(GOT_ERR_NO_SPACE);
10916 author0 = strdup(got_object_commit_get_author(commit));
10917 if (author0 == NULL)
10918 return got_error_from_errno("strdup");
10919 author = author0;
10920 smallerthan = strchr(author, '<');
10921 if (smallerthan && smallerthan[1] != '\0')
10922 author = smallerthan + 1;
10923 author[strcspn(author, "@>")] = '\0';
10925 err = got_object_commit_get_logmsg(&logmsg0, commit);
10926 if (err)
10927 goto done;
10928 logmsg = logmsg0;
10929 while (*logmsg == '\n')
10930 logmsg++;
10931 newline = strchr(logmsg, '\n');
10932 if (newline)
10933 *newline = '\0';
10935 if (asprintf(brief_str, "%s %s %s",
10936 datebuf, author, logmsg) == -1)
10937 err = got_error_from_errno("asprintf");
10938 done:
10939 free(author0);
10940 free(logmsg0);
10941 return err;
10944 static const struct got_error *
10945 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10946 struct got_repository *repo)
10948 const struct got_error *err;
10949 char *id_str;
10951 err = got_object_id_str(&id_str, id);
10952 if (err)
10953 return err;
10955 err = got_ref_delete(ref, repo);
10956 if (err)
10957 goto done;
10959 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10960 done:
10961 free(id_str);
10962 return err;
10965 static const struct got_error *
10966 print_backup_ref(const char *branch_name, const char *new_id_str,
10967 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10968 struct got_reflist_object_id_map *refs_idmap,
10969 struct got_repository *repo)
10971 const struct got_error *err = NULL;
10972 struct got_reflist_head *refs;
10973 char *refs_str = NULL;
10974 struct got_object_id *new_commit_id = NULL;
10975 struct got_commit_object *new_commit = NULL;
10976 char *new_commit_brief_str = NULL;
10977 struct got_object_id *yca_id = NULL;
10978 struct got_commit_object *yca_commit = NULL;
10979 char *yca_id_str = NULL, *yca_brief_str = NULL;
10980 char *custom_refs_str;
10982 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10983 return got_error_from_errno("asprintf");
10985 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10986 0, 0, refs_idmap, custom_refs_str, NULL);
10987 if (err)
10988 goto done;
10990 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10991 if (err)
10992 goto done;
10994 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10995 if (refs) {
10996 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10997 if (err)
10998 goto done;
11001 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11002 if (err)
11003 goto done;
11005 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11006 if (err)
11007 goto done;
11009 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11010 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
11011 if (err)
11012 goto done;
11014 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11015 refs_str ? " (" : "", refs_str ? refs_str : "",
11016 refs_str ? ")" : "", new_commit_brief_str);
11017 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11018 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11019 free(refs_str);
11020 refs_str = NULL;
11022 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11023 if (err)
11024 goto done;
11026 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11027 if (err)
11028 goto done;
11030 err = got_object_id_str(&yca_id_str, yca_id);
11031 if (err)
11032 goto done;
11034 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11035 if (refs) {
11036 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11037 if (err)
11038 goto done;
11040 printf("history forked at %s%s%s%s\n %s\n",
11041 yca_id_str,
11042 refs_str ? " (" : "", refs_str ? refs_str : "",
11043 refs_str ? ")" : "", yca_brief_str);
11045 done:
11046 free(custom_refs_str);
11047 free(new_commit_id);
11048 free(refs_str);
11049 free(yca_id);
11050 free(yca_id_str);
11051 free(yca_brief_str);
11052 if (new_commit)
11053 got_object_commit_close(new_commit);
11054 if (yca_commit)
11055 got_object_commit_close(yca_commit);
11057 return err;
11060 static const struct got_error *
11061 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11062 struct got_repository *repo)
11064 const struct got_error *err;
11065 struct got_reflist_head refs;
11066 struct got_reflist_entry *re;
11067 char *uuidstr = NULL;
11068 static char msg[160];
11070 TAILQ_INIT(&refs);
11072 err = got_worktree_get_uuid(&uuidstr, worktree);
11073 if (err)
11074 goto done;
11076 err = got_ref_list(&refs, repo, "refs/got/worktree",
11077 got_ref_cmp_by_name, repo);
11078 if (err)
11079 goto done;
11081 TAILQ_FOREACH(re, &refs, entry) {
11082 const char *cmd, *refname, *type;
11084 refname = got_ref_get_name(re->ref);
11086 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11087 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11088 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11089 cmd = "cherrypick";
11090 type = "cherrypicked";
11091 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11092 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11093 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11094 cmd = "backout";
11095 type = "backed-out";
11096 } else
11097 continue;
11099 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11100 continue;
11102 snprintf(msg, sizeof(msg),
11103 "work tree has references created by %s commits which "
11104 "must be removed with 'got %s -X' before running the %s "
11105 "command", type, cmd, caller);
11106 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11107 goto done;
11110 done:
11111 free(uuidstr);
11112 got_ref_list_free(&refs);
11113 return err;
11116 static const struct got_error *
11117 process_backup_refs(const char *backup_ref_prefix,
11118 const char *wanted_branch_name,
11119 int delete, struct got_repository *repo)
11121 const struct got_error *err;
11122 struct got_reflist_head refs, backup_refs;
11123 struct got_reflist_entry *re;
11124 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11125 struct got_object_id *old_commit_id = NULL;
11126 char *branch_name = NULL;
11127 struct got_commit_object *old_commit = NULL;
11128 struct got_reflist_object_id_map *refs_idmap = NULL;
11129 int wanted_branch_found = 0;
11131 TAILQ_INIT(&refs);
11132 TAILQ_INIT(&backup_refs);
11134 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11135 if (err)
11136 return err;
11138 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11139 if (err)
11140 goto done;
11142 if (wanted_branch_name) {
11143 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11144 wanted_branch_name += 11;
11147 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11148 got_ref_cmp_by_commit_timestamp_descending, repo);
11149 if (err)
11150 goto done;
11152 TAILQ_FOREACH(re, &backup_refs, entry) {
11153 const char *refname = got_ref_get_name(re->ref);
11154 char *slash;
11156 err = check_cancelled(NULL);
11157 if (err)
11158 break;
11160 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11161 if (err)
11162 break;
11164 err = got_object_open_as_commit(&old_commit, repo,
11165 old_commit_id);
11166 if (err)
11167 break;
11169 if (strncmp(backup_ref_prefix, refname,
11170 backup_ref_prefix_len) == 0)
11171 refname += backup_ref_prefix_len;
11173 while (refname[0] == '/')
11174 refname++;
11176 branch_name = strdup(refname);
11177 if (branch_name == NULL) {
11178 err = got_error_from_errno("strdup");
11179 break;
11181 slash = strrchr(branch_name, '/');
11182 if (slash) {
11183 *slash = '\0';
11184 refname += strlen(branch_name) + 1;
11187 if (wanted_branch_name == NULL ||
11188 strcmp(wanted_branch_name, branch_name) == 0) {
11189 wanted_branch_found = 1;
11190 if (delete) {
11191 err = delete_backup_ref(re->ref,
11192 old_commit_id, repo);
11193 } else {
11194 err = print_backup_ref(branch_name, refname,
11195 old_commit_id, old_commit, refs_idmap,
11196 repo);
11198 if (err)
11199 break;
11202 free(old_commit_id);
11203 old_commit_id = NULL;
11204 free(branch_name);
11205 branch_name = NULL;
11206 got_object_commit_close(old_commit);
11207 old_commit = NULL;
11210 if (wanted_branch_name && !wanted_branch_found) {
11211 err = got_error_fmt(GOT_ERR_NOT_REF,
11212 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11214 done:
11215 if (refs_idmap)
11216 got_reflist_object_id_map_free(refs_idmap);
11217 got_ref_list_free(&refs);
11218 got_ref_list_free(&backup_refs);
11219 free(old_commit_id);
11220 free(branch_name);
11221 if (old_commit)
11222 got_object_commit_close(old_commit);
11223 return err;
11226 static const struct got_error *
11227 abort_progress(void *arg, unsigned char status, const char *path)
11230 * Unversioned files should not clutter progress output when
11231 * an operation is aborted.
11233 if (status == GOT_STATUS_UNVERSIONED)
11234 return NULL;
11236 return update_progress(arg, status, path);
11239 static const struct got_error *
11240 cmd_rebase(int argc, char *argv[])
11242 const struct got_error *error = NULL;
11243 struct got_worktree *worktree = NULL;
11244 struct got_repository *repo = NULL;
11245 struct got_fileindex *fileindex = NULL;
11246 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11247 struct got_reference *branch = NULL;
11248 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11249 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11250 struct got_object_id *resume_commit_id = NULL;
11251 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11252 struct got_object_id *head_commit_id = NULL;
11253 struct got_reference *head_ref = NULL;
11254 struct got_commit_object *commit = NULL;
11255 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11256 int histedit_in_progress = 0, merge_in_progress = 0;
11257 int create_backup = 1, list_backups = 0, delete_backups = 0;
11258 int allow_conflict = 0;
11259 struct got_object_id_queue commits;
11260 struct got_pathlist_head merged_paths;
11261 const struct got_object_id_queue *parent_ids;
11262 struct got_object_qid *qid, *pid;
11263 struct got_update_progress_arg upa;
11264 int *pack_fds = NULL;
11266 STAILQ_INIT(&commits);
11267 TAILQ_INIT(&merged_paths);
11268 memset(&upa, 0, sizeof(upa));
11270 #ifndef PROFILE
11271 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11272 "unveil", NULL) == -1)
11273 err(1, "pledge");
11274 #endif
11276 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11277 switch (ch) {
11278 case 'a':
11279 abort_rebase = 1;
11280 break;
11281 case 'C':
11282 allow_conflict = 1;
11283 break;
11284 case 'c':
11285 continue_rebase = 1;
11286 break;
11287 case 'l':
11288 list_backups = 1;
11289 break;
11290 case 'X':
11291 delete_backups = 1;
11292 break;
11293 default:
11294 usage_rebase();
11295 /* NOTREACHED */
11299 argc -= optind;
11300 argv += optind;
11302 if (list_backups) {
11303 if (abort_rebase)
11304 option_conflict('l', 'a');
11305 if (allow_conflict)
11306 option_conflict('l', 'C');
11307 if (continue_rebase)
11308 option_conflict('l', 'c');
11309 if (delete_backups)
11310 option_conflict('l', 'X');
11311 if (argc != 0 && argc != 1)
11312 usage_rebase();
11313 } else if (delete_backups) {
11314 if (abort_rebase)
11315 option_conflict('X', 'a');
11316 if (allow_conflict)
11317 option_conflict('X', 'C');
11318 if (continue_rebase)
11319 option_conflict('X', 'c');
11320 if (list_backups)
11321 option_conflict('l', 'X');
11322 if (argc != 0 && argc != 1)
11323 usage_rebase();
11324 } else if (allow_conflict) {
11325 if (abort_rebase)
11326 option_conflict('C', 'a');
11327 if (!continue_rebase)
11328 errx(1, "-C option requires -c");
11329 } else {
11330 if (abort_rebase && continue_rebase)
11331 usage_rebase();
11332 else if (abort_rebase || continue_rebase) {
11333 if (argc != 0)
11334 usage_rebase();
11335 } else if (argc != 1)
11336 usage_rebase();
11339 cwd = getcwd(NULL, 0);
11340 if (cwd == NULL) {
11341 error = got_error_from_errno("getcwd");
11342 goto done;
11345 error = got_repo_pack_fds_open(&pack_fds);
11346 if (error != NULL)
11347 goto done;
11349 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11350 if (error) {
11351 if (list_backups || delete_backups) {
11352 if (error->code != GOT_ERR_NOT_WORKTREE)
11353 goto done;
11354 } else {
11355 if (error->code == GOT_ERR_NOT_WORKTREE)
11356 error = wrap_not_worktree_error(error,
11357 "rebase", cwd);
11358 goto done;
11362 error = get_gitconfig_path(&gitconfig_path);
11363 if (error)
11364 goto done;
11365 error = got_repo_open(&repo,
11366 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11367 gitconfig_path, pack_fds);
11368 if (error != NULL)
11369 goto done;
11371 if (worktree != NULL && !list_backups && !delete_backups) {
11372 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11373 if (error)
11374 goto done;
11377 error = get_author(&committer, repo, worktree);
11378 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11379 goto done;
11381 error = apply_unveil(got_repo_get_path(repo), 0,
11382 worktree ? got_worktree_get_root_path(worktree) : NULL);
11383 if (error)
11384 goto done;
11386 if (list_backups || delete_backups) {
11387 error = process_backup_refs(
11388 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11389 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11390 goto done; /* nothing else to do */
11393 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11394 worktree);
11395 if (error)
11396 goto done;
11397 if (histedit_in_progress) {
11398 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11399 goto done;
11402 error = got_worktree_merge_in_progress(&merge_in_progress,
11403 worktree, repo);
11404 if (error)
11405 goto done;
11406 if (merge_in_progress) {
11407 error = got_error(GOT_ERR_MERGE_BUSY);
11408 goto done;
11411 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11412 if (error)
11413 goto done;
11415 if (abort_rebase) {
11416 if (!rebase_in_progress) {
11417 error = got_error(GOT_ERR_NOT_REBASING);
11418 goto done;
11420 error = got_worktree_rebase_continue(&resume_commit_id,
11421 &new_base_branch, &tmp_branch, &branch, &fileindex,
11422 worktree, repo);
11423 if (error)
11424 goto done;
11425 printf("Switching work tree to %s\n",
11426 got_ref_get_symref_target(new_base_branch));
11427 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11428 new_base_branch, abort_progress, &upa);
11429 if (error)
11430 goto done;
11431 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11432 print_merge_progress_stats(&upa);
11433 goto done; /* nothing else to do */
11436 if (continue_rebase) {
11437 if (!rebase_in_progress) {
11438 error = got_error(GOT_ERR_NOT_REBASING);
11439 goto done;
11441 error = got_worktree_rebase_continue(&resume_commit_id,
11442 &new_base_branch, &tmp_branch, &branch, &fileindex,
11443 worktree, repo);
11444 if (error)
11445 goto done;
11447 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11448 committer, resume_commit_id, allow_conflict, repo);
11449 if (error)
11450 goto done;
11452 yca_id = got_object_id_dup(resume_commit_id);
11453 if (yca_id == NULL) {
11454 error = got_error_from_errno("got_object_id_dup");
11455 goto done;
11457 } else {
11458 error = got_ref_open(&branch, repo, argv[0], 0);
11459 if (error != NULL)
11460 goto done;
11461 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11462 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11463 "will not rebase a branch which lives outside "
11464 "the \"refs/heads/\" reference namespace");
11465 goto done;
11469 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11470 if (error)
11471 goto done;
11473 if (!continue_rebase) {
11474 struct got_object_id *base_commit_id;
11476 error = got_ref_open(&head_ref, repo,
11477 got_worktree_get_head_ref_name(worktree), 0);
11478 if (error)
11479 goto done;
11480 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11481 if (error)
11482 goto done;
11483 base_commit_id = got_worktree_get_base_commit_id(worktree);
11484 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11485 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11486 goto done;
11489 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11490 base_commit_id, branch_head_commit_id, 1, repo,
11491 check_cancelled, NULL);
11492 if (error) {
11493 if (error->code == GOT_ERR_ANCESTRY) {
11494 error = got_error_msg(GOT_ERR_ANCESTRY,
11495 "specified branch shares no common "
11496 "ancestry with work tree's branch");
11498 goto done;
11501 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11502 struct got_pathlist_head paths;
11503 printf("%s is already based on %s\n",
11504 got_ref_get_name(branch),
11505 got_worktree_get_head_ref_name(worktree));
11506 error = switch_head_ref(branch, branch_head_commit_id,
11507 worktree, repo);
11508 if (error)
11509 goto done;
11510 error = got_worktree_set_base_commit_id(worktree, repo,
11511 branch_head_commit_id);
11512 if (error)
11513 goto done;
11514 TAILQ_INIT(&paths);
11515 error = got_pathlist_append(&paths, "", NULL);
11516 if (error)
11517 goto done;
11518 error = got_worktree_checkout_files(worktree,
11519 &paths, repo, update_progress, &upa,
11520 check_cancelled, NULL);
11521 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11522 if (error)
11523 goto done;
11524 if (upa.did_something) {
11525 char *id_str;
11526 error = got_object_id_str(&id_str,
11527 branch_head_commit_id);
11528 if (error)
11529 goto done;
11530 printf("Updated to %s: %s\n",
11531 got_worktree_get_head_ref_name(worktree),
11532 id_str);
11533 free(id_str);
11534 } else
11535 printf("Already up-to-date\n");
11536 print_update_progress_stats(&upa);
11537 goto done;
11541 commit_id = branch_head_commit_id;
11542 error = got_object_open_as_commit(&commit, repo, commit_id);
11543 if (error)
11544 goto done;
11546 parent_ids = got_object_commit_get_parent_ids(commit);
11547 pid = STAILQ_FIRST(parent_ids);
11548 if (pid) {
11549 error = collect_commits(&commits, commit_id, &pid->id,
11550 yca_id, got_worktree_get_path_prefix(worktree),
11551 GOT_ERR_REBASE_PATH, repo);
11552 if (error)
11553 goto done;
11556 got_object_commit_close(commit);
11557 commit = NULL;
11559 if (!continue_rebase) {
11560 error = got_worktree_rebase_prepare(&new_base_branch,
11561 &tmp_branch, &fileindex, worktree, branch, repo);
11562 if (error)
11563 goto done;
11566 if (STAILQ_EMPTY(&commits)) {
11567 if (continue_rebase) {
11568 error = rebase_complete(worktree, fileindex,
11569 branch, tmp_branch, repo, create_backup);
11570 goto done;
11571 } else {
11572 /* Fast-forward the reference of the branch. */
11573 struct got_object_id *new_head_commit_id;
11574 char *id_str;
11575 error = got_ref_resolve(&new_head_commit_id, repo,
11576 new_base_branch);
11577 if (error)
11578 goto done;
11579 error = got_object_id_str(&id_str, new_head_commit_id);
11580 if (error)
11581 goto done;
11582 printf("Forwarding %s to commit %s\n",
11583 got_ref_get_name(branch), id_str);
11584 free(id_str);
11585 error = got_ref_change_ref(branch,
11586 new_head_commit_id);
11587 if (error)
11588 goto done;
11589 /* No backup needed since objects did not change. */
11590 create_backup = 0;
11594 pid = NULL;
11595 STAILQ_FOREACH(qid, &commits, entry) {
11597 commit_id = &qid->id;
11598 parent_id = pid ? &pid->id : yca_id;
11599 pid = qid;
11601 memset(&upa, 0, sizeof(upa));
11602 error = got_worktree_rebase_merge_files(&merged_paths,
11603 worktree, fileindex, parent_id, commit_id, repo,
11604 update_progress, &upa, check_cancelled, NULL);
11605 if (error)
11606 goto done;
11608 print_merge_progress_stats(&upa);
11609 if (upa.conflicts > 0 || upa.missing > 0 ||
11610 upa.not_deleted > 0 || upa.unversioned > 0) {
11611 if (upa.conflicts > 0) {
11612 error = show_rebase_merge_conflict(&qid->id,
11613 repo);
11614 if (error)
11615 goto done;
11617 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11618 break;
11621 error = rebase_commit(&merged_paths, worktree, fileindex,
11622 tmp_branch, committer, commit_id, 0, repo);
11623 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11624 if (error)
11625 goto done;
11628 if (upa.conflicts > 0 || upa.missing > 0 ||
11629 upa.not_deleted > 0 || upa.unversioned > 0) {
11630 error = got_worktree_rebase_postpone(worktree, fileindex);
11631 if (error)
11632 goto done;
11633 if (upa.conflicts > 0 && upa.missing == 0 &&
11634 upa.not_deleted == 0 && upa.unversioned == 0) {
11635 error = got_error_msg(GOT_ERR_CONFLICTS,
11636 "conflicts must be resolved before rebasing "
11637 "can continue");
11638 } else if (upa.conflicts > 0) {
11639 error = got_error_msg(GOT_ERR_CONFLICTS,
11640 "conflicts must be resolved before rebasing "
11641 "can continue; changes destined for some "
11642 "files were not yet merged and should be "
11643 "merged manually if required before the "
11644 "rebase operation is continued");
11645 } else {
11646 error = got_error_msg(GOT_ERR_CONFLICTS,
11647 "changes destined for some files were not "
11648 "yet merged and should be merged manually "
11649 "if required before the rebase operation "
11650 "is continued");
11652 } else
11653 error = rebase_complete(worktree, fileindex, branch,
11654 tmp_branch, repo, create_backup);
11655 done:
11656 free(cwd);
11657 free(committer);
11658 free(gitconfig_path);
11659 got_object_id_queue_free(&commits);
11660 free(branch_head_commit_id);
11661 free(resume_commit_id);
11662 free(head_commit_id);
11663 free(yca_id);
11664 if (commit)
11665 got_object_commit_close(commit);
11666 if (branch)
11667 got_ref_close(branch);
11668 if (new_base_branch)
11669 got_ref_close(new_base_branch);
11670 if (tmp_branch)
11671 got_ref_close(tmp_branch);
11672 if (head_ref)
11673 got_ref_close(head_ref);
11674 if (worktree)
11675 got_worktree_close(worktree);
11676 if (repo) {
11677 const struct got_error *close_err = got_repo_close(repo);
11678 if (error == NULL)
11679 error = close_err;
11681 if (pack_fds) {
11682 const struct got_error *pack_err =
11683 got_repo_pack_fds_close(pack_fds);
11684 if (error == NULL)
11685 error = pack_err;
11687 return error;
11690 __dead static void
11691 usage_histedit(void)
11693 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11694 "[branch]\n", getprogname());
11695 exit(1);
11698 #define GOT_HISTEDIT_PICK 'p'
11699 #define GOT_HISTEDIT_EDIT 'e'
11700 #define GOT_HISTEDIT_FOLD 'f'
11701 #define GOT_HISTEDIT_DROP 'd'
11702 #define GOT_HISTEDIT_MESG 'm'
11704 static const struct got_histedit_cmd {
11705 unsigned char code;
11706 const char *name;
11707 const char *desc;
11708 } got_histedit_cmds[] = {
11709 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11710 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11711 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11712 "be used" },
11713 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11714 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11717 struct got_histedit_list_entry {
11718 TAILQ_ENTRY(got_histedit_list_entry) entry;
11719 struct got_object_id *commit_id;
11720 const struct got_histedit_cmd *cmd;
11721 char *logmsg;
11723 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11725 static const struct got_error *
11726 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11727 FILE *f, struct got_repository *repo)
11729 const struct got_error *err = NULL;
11730 char *logmsg = NULL, *id_str = NULL;
11731 struct got_commit_object *commit = NULL;
11732 int n;
11734 err = got_object_open_as_commit(&commit, repo, commit_id);
11735 if (err)
11736 goto done;
11738 err = get_short_logmsg(&logmsg, 34, commit);
11739 if (err)
11740 goto done;
11742 err = got_object_id_str(&id_str, commit_id);
11743 if (err)
11744 goto done;
11746 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11747 if (n < 0)
11748 err = got_ferror(f, GOT_ERR_IO);
11749 done:
11750 if (commit)
11751 got_object_commit_close(commit);
11752 free(id_str);
11753 free(logmsg);
11754 return err;
11757 static const struct got_error *
11758 histedit_write_commit_list(struct got_object_id_queue *commits,
11759 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11760 int edit_only, struct got_repository *repo)
11762 const struct got_error *err = NULL;
11763 struct got_object_qid *qid;
11764 const char *histedit_cmd = NULL;
11766 if (STAILQ_EMPTY(commits))
11767 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11769 STAILQ_FOREACH(qid, commits, entry) {
11770 histedit_cmd = got_histedit_cmds[0].name;
11771 if (drop_only)
11772 histedit_cmd = "drop";
11773 else if (edit_only)
11774 histedit_cmd = "edit";
11775 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11776 histedit_cmd = "fold";
11777 else if (edit_logmsg_only)
11778 histedit_cmd = "mesg";
11779 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11780 if (err)
11781 break;
11784 return err;
11787 static const struct got_error *
11788 write_cmd_list(FILE *f, const char *branch_name,
11789 struct got_object_id_queue *commits)
11791 const struct got_error *err = NULL;
11792 size_t i;
11793 int n;
11794 char *id_str;
11795 struct got_object_qid *qid;
11797 qid = STAILQ_FIRST(commits);
11798 err = got_object_id_str(&id_str, &qid->id);
11799 if (err)
11800 return err;
11802 n = fprintf(f,
11803 "# Editing the history of branch '%s' starting at\n"
11804 "# commit %s\n"
11805 "# Commits will be processed in order from top to "
11806 "bottom of this file.\n", branch_name, id_str);
11807 if (n < 0) {
11808 err = got_ferror(f, GOT_ERR_IO);
11809 goto done;
11812 n = fprintf(f, "# Available histedit commands:\n");
11813 if (n < 0) {
11814 err = got_ferror(f, GOT_ERR_IO);
11815 goto done;
11818 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11819 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11820 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11821 cmd->desc);
11822 if (n < 0) {
11823 err = got_ferror(f, GOT_ERR_IO);
11824 break;
11827 done:
11828 free(id_str);
11829 return err;
11832 static const struct got_error *
11833 histedit_syntax_error(int lineno)
11835 static char msg[42];
11836 int ret;
11838 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11839 lineno);
11840 if (ret < 0 || (size_t)ret >= sizeof(msg))
11841 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11843 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11846 static const struct got_error *
11847 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11848 char *logmsg, struct got_repository *repo)
11850 const struct got_error *err;
11851 struct got_commit_object *folded_commit = NULL;
11852 char *id_str, *folded_logmsg = NULL;
11854 err = got_object_id_str(&id_str, hle->commit_id);
11855 if (err)
11856 return err;
11858 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11859 if (err)
11860 goto done;
11862 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11863 if (err)
11864 goto done;
11865 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11866 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11867 folded_logmsg) == -1) {
11868 err = got_error_from_errno("asprintf");
11870 done:
11871 if (folded_commit)
11872 got_object_commit_close(folded_commit);
11873 free(id_str);
11874 free(folded_logmsg);
11875 return err;
11878 static struct got_histedit_list_entry *
11879 get_folded_commits(struct got_histedit_list_entry *hle)
11881 struct got_histedit_list_entry *prev, *folded = NULL;
11883 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11884 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11885 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11886 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11887 folded = prev;
11888 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11891 return folded;
11894 static const struct got_error *
11895 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11896 struct got_repository *repo)
11898 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11899 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11900 const struct got_error *err = NULL;
11901 struct got_commit_object *commit = NULL;
11902 int logmsg_len;
11903 int fd = -1;
11904 struct got_histedit_list_entry *folded = NULL;
11906 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11907 if (err)
11908 return err;
11910 folded = get_folded_commits(hle);
11911 if (folded) {
11912 while (folded != hle) {
11913 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11914 folded = TAILQ_NEXT(folded, entry);
11915 continue;
11917 err = append_folded_commit_msg(&new_msg, folded,
11918 logmsg, repo);
11919 if (err)
11920 goto done;
11921 free(logmsg);
11922 logmsg = new_msg;
11923 folded = TAILQ_NEXT(folded, entry);
11927 err = got_object_id_str(&id_str, hle->commit_id);
11928 if (err)
11929 goto done;
11930 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11931 if (err)
11932 goto done;
11933 logmsg_len = asprintf(&new_msg,
11934 "%s\n# original log message of commit %s: %s",
11935 logmsg ? logmsg : "", id_str, orig_logmsg);
11936 if (logmsg_len == -1) {
11937 err = got_error_from_errno("asprintf");
11938 goto done;
11940 free(logmsg);
11941 logmsg = new_msg;
11943 err = got_object_id_str(&id_str, hle->commit_id);
11944 if (err)
11945 goto done;
11947 err = got_opentemp_named_fd(&logmsg_path, &fd,
11948 GOT_TMPDIR_STR "/got-logmsg", "");
11949 if (err)
11950 goto done;
11952 if (write(fd, logmsg, logmsg_len) == -1) {
11953 err = got_error_from_errno2("write", logmsg_path);
11954 goto done;
11956 if (close(fd) == -1) {
11957 err = got_error_from_errno2("close", logmsg_path);
11958 goto done;
11960 fd = -1;
11962 err = get_editor(&editor);
11963 if (err)
11964 goto done;
11966 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11967 logmsg_len, 0);
11968 if (err) {
11969 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11970 goto done;
11971 err = NULL;
11972 hle->logmsg = strdup(new_msg);
11973 if (hle->logmsg == NULL)
11974 err = got_error_from_errno("strdup");
11976 done:
11977 if (fd != -1 && close(fd) == -1 && err == NULL)
11978 err = got_error_from_errno2("close", logmsg_path);
11979 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11980 err = got_error_from_errno2("unlink", logmsg_path);
11981 free(logmsg_path);
11982 free(logmsg);
11983 free(orig_logmsg);
11984 free(editor);
11985 if (commit)
11986 got_object_commit_close(commit);
11987 return err;
11990 static const struct got_error *
11991 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11992 FILE *f, struct got_repository *repo)
11994 const struct got_error *err = NULL;
11995 char *line = NULL, *p, *end;
11996 size_t i, linesize = 0;
11997 ssize_t linelen;
11998 int lineno = 0;
11999 const struct got_histedit_cmd *cmd;
12000 struct got_object_id *commit_id = NULL;
12001 struct got_histedit_list_entry *hle = NULL;
12003 for (;;) {
12004 linelen = getline(&line, &linesize, f);
12005 if (linelen == -1) {
12006 const struct got_error *getline_err;
12007 if (feof(f))
12008 break;
12009 getline_err = got_error_from_errno("getline");
12010 err = got_ferror(f, getline_err->code);
12011 break;
12013 lineno++;
12014 p = line;
12015 while (isspace((unsigned char)p[0]))
12016 p++;
12017 if (p[0] == '#' || p[0] == '\0')
12018 continue;
12019 cmd = NULL;
12020 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12021 cmd = &got_histedit_cmds[i];
12022 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12023 isspace((unsigned char)p[strlen(cmd->name)])) {
12024 p += strlen(cmd->name);
12025 break;
12027 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12028 p++;
12029 break;
12032 if (i == nitems(got_histedit_cmds)) {
12033 err = histedit_syntax_error(lineno);
12034 break;
12036 while (isspace((unsigned char)p[0]))
12037 p++;
12038 end = p;
12039 while (end[0] && !isspace((unsigned char)end[0]))
12040 end++;
12041 *end = '\0';
12042 err = got_object_resolve_id_str(&commit_id, repo, p);
12043 if (err) {
12044 /* override error code */
12045 err = histedit_syntax_error(lineno);
12046 break;
12048 hle = malloc(sizeof(*hle));
12049 if (hle == NULL) {
12050 err = got_error_from_errno("malloc");
12051 break;
12053 hle->cmd = cmd;
12054 hle->commit_id = commit_id;
12055 hle->logmsg = NULL;
12056 commit_id = NULL;
12057 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12060 free(line);
12061 free(commit_id);
12062 return err;
12065 static const struct got_error *
12066 histedit_check_script(struct got_histedit_list *histedit_cmds,
12067 struct got_object_id_queue *commits, struct got_repository *repo)
12069 const struct got_error *err = NULL;
12070 struct got_object_qid *qid;
12071 struct got_histedit_list_entry *hle;
12072 static char msg[92];
12073 char *id_str;
12075 if (TAILQ_EMPTY(histedit_cmds))
12076 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12077 "histedit script contains no commands");
12078 if (STAILQ_EMPTY(commits))
12079 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12081 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12082 struct got_histedit_list_entry *hle2;
12083 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12084 if (hle == hle2)
12085 continue;
12086 if (got_object_id_cmp(hle->commit_id,
12087 hle2->commit_id) != 0)
12088 continue;
12089 err = got_object_id_str(&id_str, hle->commit_id);
12090 if (err)
12091 return err;
12092 snprintf(msg, sizeof(msg), "commit %s is listed "
12093 "more than once in histedit script", id_str);
12094 free(id_str);
12095 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12099 STAILQ_FOREACH(qid, commits, entry) {
12100 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12101 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12102 break;
12104 if (hle == NULL) {
12105 err = got_object_id_str(&id_str, &qid->id);
12106 if (err)
12107 return err;
12108 snprintf(msg, sizeof(msg),
12109 "commit %s missing from histedit script", id_str);
12110 free(id_str);
12111 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12115 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12116 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12117 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12118 "last commit in histedit script cannot be folded");
12120 return NULL;
12123 static const struct got_error *
12124 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12125 const char *path, struct got_object_id_queue *commits,
12126 struct got_repository *repo)
12128 const struct got_error *err = NULL;
12129 struct stat st, st2;
12130 struct timespec timeout;
12131 char *editor;
12132 FILE *f = NULL;
12134 err = get_editor(&editor);
12135 if (err)
12136 return err;
12138 if (stat(path, &st) == -1) {
12139 err = got_error_from_errno2("stat", path);
12140 goto done;
12143 if (spawn_editor(editor, path) == -1) {
12144 err = got_error_from_errno("failed spawning editor");
12145 goto done;
12148 timeout.tv_sec = 0;
12149 timeout.tv_nsec = 1;
12150 nanosleep(&timeout, NULL);
12152 if (stat(path, &st2) == -1) {
12153 err = got_error_from_errno2("stat", path);
12154 goto done;
12157 if (st.st_size == st2.st_size &&
12158 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12159 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12160 "no changes made to histedit script, aborting");
12161 goto done;
12164 f = fopen(path, "re");
12165 if (f == NULL) {
12166 err = got_error_from_errno("fopen");
12167 goto done;
12169 err = histedit_parse_list(histedit_cmds, f, repo);
12170 if (err)
12171 goto done;
12173 err = histedit_check_script(histedit_cmds, commits, repo);
12174 done:
12175 if (f && fclose(f) == EOF && err == NULL)
12176 err = got_error_from_errno("fclose");
12177 free(editor);
12178 return err;
12181 static const struct got_error *
12182 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12183 struct got_object_id_queue *, const char *, const char *,
12184 struct got_repository *);
12186 static const struct got_error *
12187 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12188 struct got_object_id_queue *commits, const char *branch_name,
12189 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12190 struct got_repository *repo)
12192 const struct got_error *err;
12193 FILE *f = NULL;
12194 char *path = NULL;
12196 err = got_opentemp_named(&path, &f, "got-histedit", "");
12197 if (err)
12198 return err;
12200 err = write_cmd_list(f, branch_name, commits);
12201 if (err)
12202 goto done;
12204 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12205 fold_only, drop_only, edit_only, repo);
12206 if (err)
12207 goto done;
12209 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12210 rewind(f);
12211 err = histedit_parse_list(histedit_cmds, f, repo);
12212 } else {
12213 if (fclose(f) == EOF) {
12214 err = got_error_from_errno("fclose");
12215 goto done;
12217 f = NULL;
12218 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12219 if (err) {
12220 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12221 err->code != GOT_ERR_HISTEDIT_CMD)
12222 goto done;
12223 err = histedit_edit_list_retry(histedit_cmds, err,
12224 commits, path, branch_name, repo);
12227 done:
12228 if (f && fclose(f) == EOF && err == NULL)
12229 err = got_error_from_errno("fclose");
12230 if (path && unlink(path) != 0 && err == NULL)
12231 err = got_error_from_errno2("unlink", path);
12232 free(path);
12233 return err;
12236 static const struct got_error *
12237 histedit_save_list(struct got_histedit_list *histedit_cmds,
12238 struct got_worktree *worktree, struct got_repository *repo)
12240 const struct got_error *err = NULL;
12241 char *path = NULL;
12242 FILE *f = NULL;
12243 struct got_histedit_list_entry *hle;
12245 err = got_worktree_get_histedit_script_path(&path, worktree);
12246 if (err)
12247 return err;
12249 f = fopen(path, "we");
12250 if (f == NULL) {
12251 err = got_error_from_errno2("fopen", path);
12252 goto done;
12254 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12255 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12256 repo);
12257 if (err)
12258 break;
12260 done:
12261 if (f && fclose(f) == EOF && err == NULL)
12262 err = got_error_from_errno("fclose");
12263 free(path);
12264 return err;
12267 static void
12268 histedit_free_list(struct got_histedit_list *histedit_cmds)
12270 struct got_histedit_list_entry *hle;
12272 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12273 TAILQ_REMOVE(histedit_cmds, hle, entry);
12274 free(hle);
12278 static const struct got_error *
12279 histedit_load_list(struct got_histedit_list *histedit_cmds,
12280 const char *path, struct got_repository *repo)
12282 const struct got_error *err = NULL;
12283 FILE *f = NULL;
12285 f = fopen(path, "re");
12286 if (f == NULL) {
12287 err = got_error_from_errno2("fopen", path);
12288 goto done;
12291 err = histedit_parse_list(histedit_cmds, f, repo);
12292 done:
12293 if (f && fclose(f) == EOF && err == NULL)
12294 err = got_error_from_errno("fclose");
12295 return err;
12298 static const struct got_error *
12299 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12300 const struct got_error *edit_err, struct got_object_id_queue *commits,
12301 const char *path, const char *branch_name, struct got_repository *repo)
12303 const struct got_error *err = NULL, *prev_err = edit_err;
12304 int resp = ' ';
12306 while (resp != 'c' && resp != 'r' && resp != 'a') {
12307 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12308 "or (a)bort: ", getprogname(), prev_err->msg);
12309 resp = getchar();
12310 if (resp == '\n')
12311 resp = getchar();
12312 if (resp == 'c') {
12313 histedit_free_list(histedit_cmds);
12314 err = histedit_run_editor(histedit_cmds, path, commits,
12315 repo);
12316 if (err) {
12317 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12318 err->code != GOT_ERR_HISTEDIT_CMD)
12319 break;
12320 prev_err = err;
12321 resp = ' ';
12322 continue;
12324 break;
12325 } else if (resp == 'r') {
12326 histedit_free_list(histedit_cmds);
12327 err = histedit_edit_script(histedit_cmds,
12328 commits, branch_name, 0, 0, 0, 0, repo);
12329 if (err) {
12330 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12331 err->code != GOT_ERR_HISTEDIT_CMD)
12332 break;
12333 prev_err = err;
12334 resp = ' ';
12335 continue;
12337 break;
12338 } else if (resp == 'a') {
12339 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12340 break;
12341 } else
12342 printf("invalid response '%c'\n", resp);
12345 return err;
12348 static const struct got_error *
12349 histedit_complete(struct got_worktree *worktree,
12350 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12351 struct got_reference *branch, struct got_repository *repo)
12353 printf("Switching work tree to %s\n",
12354 got_ref_get_symref_target(branch));
12355 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12356 branch, repo);
12359 static const struct got_error *
12360 show_histedit_progress(struct got_commit_object *commit,
12361 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12363 const struct got_error *err;
12364 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12366 err = got_object_id_str(&old_id_str, hle->commit_id);
12367 if (err)
12368 goto done;
12370 if (new_id) {
12371 err = got_object_id_str(&new_id_str, new_id);
12372 if (err)
12373 goto done;
12376 old_id_str[12] = '\0';
12377 if (new_id_str)
12378 new_id_str[12] = '\0';
12380 if (hle->logmsg) {
12381 logmsg = strdup(hle->logmsg);
12382 if (logmsg == NULL) {
12383 err = got_error_from_errno("strdup");
12384 goto done;
12386 trim_logmsg(logmsg, 42);
12387 } else {
12388 err = get_short_logmsg(&logmsg, 42, commit);
12389 if (err)
12390 goto done;
12393 switch (hle->cmd->code) {
12394 case GOT_HISTEDIT_PICK:
12395 case GOT_HISTEDIT_EDIT:
12396 case GOT_HISTEDIT_MESG:
12397 printf("%s -> %s: %s\n", old_id_str,
12398 new_id_str ? new_id_str : "no-op change", logmsg);
12399 break;
12400 case GOT_HISTEDIT_DROP:
12401 case GOT_HISTEDIT_FOLD:
12402 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12403 logmsg);
12404 break;
12405 default:
12406 break;
12408 done:
12409 free(old_id_str);
12410 free(new_id_str);
12411 return err;
12414 static const struct got_error *
12415 histedit_commit(struct got_pathlist_head *merged_paths,
12416 struct got_worktree *worktree, struct got_fileindex *fileindex,
12417 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12418 const char *committer, int allow_conflict, struct got_repository *repo)
12420 const struct got_error *err;
12421 struct got_commit_object *commit;
12422 struct got_object_id *new_commit_id;
12424 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12425 && hle->logmsg == NULL) {
12426 err = histedit_edit_logmsg(hle, repo);
12427 if (err)
12428 return err;
12431 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12432 if (err)
12433 return err;
12435 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12436 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12437 hle->logmsg, allow_conflict, repo);
12438 if (err) {
12439 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12440 goto done;
12441 err = show_histedit_progress(commit, hle, NULL);
12442 } else {
12443 err = show_histedit_progress(commit, hle, new_commit_id);
12444 free(new_commit_id);
12446 done:
12447 got_object_commit_close(commit);
12448 return err;
12451 static const struct got_error *
12452 histedit_skip_commit(struct got_histedit_list_entry *hle,
12453 struct got_worktree *worktree, struct got_repository *repo)
12455 const struct got_error *error;
12456 struct got_commit_object *commit;
12458 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12459 repo);
12460 if (error)
12461 return error;
12463 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12464 if (error)
12465 return error;
12467 error = show_histedit_progress(commit, hle, NULL);
12468 got_object_commit_close(commit);
12469 return error;
12472 static const struct got_error *
12473 check_local_changes(void *arg, unsigned char status,
12474 unsigned char staged_status, const char *path,
12475 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12476 struct got_object_id *commit_id, int dirfd, const char *de_name)
12478 int *have_local_changes = arg;
12480 switch (status) {
12481 case GOT_STATUS_ADD:
12482 case GOT_STATUS_DELETE:
12483 case GOT_STATUS_MODIFY:
12484 case GOT_STATUS_CONFLICT:
12485 *have_local_changes = 1;
12486 return got_error(GOT_ERR_CANCELLED);
12487 default:
12488 break;
12491 switch (staged_status) {
12492 case GOT_STATUS_ADD:
12493 case GOT_STATUS_DELETE:
12494 case GOT_STATUS_MODIFY:
12495 *have_local_changes = 1;
12496 return got_error(GOT_ERR_CANCELLED);
12497 default:
12498 break;
12501 return NULL;
12504 static const struct got_error *
12505 cmd_histedit(int argc, char *argv[])
12507 const struct got_error *error = NULL;
12508 struct got_worktree *worktree = NULL;
12509 struct got_fileindex *fileindex = NULL;
12510 struct got_repository *repo = NULL;
12511 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12512 struct got_reference *branch = NULL;
12513 struct got_reference *tmp_branch = NULL;
12514 struct got_object_id *resume_commit_id = NULL;
12515 struct got_object_id *base_commit_id = NULL;
12516 struct got_object_id *head_commit_id = NULL;
12517 struct got_commit_object *commit = NULL;
12518 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12519 struct got_update_progress_arg upa;
12520 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12521 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12522 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12523 const char *edit_script_path = NULL;
12524 struct got_object_id_queue commits;
12525 struct got_pathlist_head merged_paths;
12526 const struct got_object_id_queue *parent_ids;
12527 struct got_object_qid *pid;
12528 struct got_histedit_list histedit_cmds;
12529 struct got_histedit_list_entry *hle;
12530 int *pack_fds = NULL;
12532 STAILQ_INIT(&commits);
12533 TAILQ_INIT(&histedit_cmds);
12534 TAILQ_INIT(&merged_paths);
12535 memset(&upa, 0, sizeof(upa));
12537 #ifndef PROFILE
12538 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12539 "unveil", NULL) == -1)
12540 err(1, "pledge");
12541 #endif
12543 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12544 switch (ch) {
12545 case 'a':
12546 abort_edit = 1;
12547 break;
12548 case 'C':
12549 allow_conflict = 1;
12550 break;
12551 case 'c':
12552 continue_edit = 1;
12553 break;
12554 case 'd':
12555 drop_only = 1;
12556 break;
12557 case 'e':
12558 edit_only = 1;
12559 break;
12560 case 'F':
12561 edit_script_path = optarg;
12562 break;
12563 case 'f':
12564 fold_only = 1;
12565 break;
12566 case 'l':
12567 list_backups = 1;
12568 break;
12569 case 'm':
12570 edit_logmsg_only = 1;
12571 break;
12572 case 'X':
12573 delete_backups = 1;
12574 break;
12575 default:
12576 usage_histedit();
12577 /* NOTREACHED */
12581 argc -= optind;
12582 argv += optind;
12584 if (abort_edit && allow_conflict)
12585 option_conflict('a', 'C');
12586 if (abort_edit && continue_edit)
12587 option_conflict('a', 'c');
12588 if (edit_script_path && allow_conflict)
12589 option_conflict('F', 'C');
12590 if (edit_script_path && edit_logmsg_only)
12591 option_conflict('F', 'm');
12592 if (abort_edit && edit_logmsg_only)
12593 option_conflict('a', 'm');
12594 if (edit_logmsg_only && allow_conflict)
12595 option_conflict('m', 'C');
12596 if (continue_edit && edit_logmsg_only)
12597 option_conflict('c', 'm');
12598 if (abort_edit && fold_only)
12599 option_conflict('a', 'f');
12600 if (fold_only && allow_conflict)
12601 option_conflict('f', 'C');
12602 if (continue_edit && fold_only)
12603 option_conflict('c', 'f');
12604 if (fold_only && edit_logmsg_only)
12605 option_conflict('f', 'm');
12606 if (edit_script_path && fold_only)
12607 option_conflict('F', 'f');
12608 if (abort_edit && edit_only)
12609 option_conflict('a', 'e');
12610 if (continue_edit && edit_only)
12611 option_conflict('c', 'e');
12612 if (edit_only && edit_logmsg_only)
12613 option_conflict('e', 'm');
12614 if (edit_script_path && edit_only)
12615 option_conflict('F', 'e');
12616 if (fold_only && edit_only)
12617 option_conflict('f', 'e');
12618 if (drop_only && abort_edit)
12619 option_conflict('d', 'a');
12620 if (drop_only && allow_conflict)
12621 option_conflict('d', 'C');
12622 if (drop_only && continue_edit)
12623 option_conflict('d', 'c');
12624 if (drop_only && edit_logmsg_only)
12625 option_conflict('d', 'm');
12626 if (drop_only && edit_only)
12627 option_conflict('d', 'e');
12628 if (drop_only && edit_script_path)
12629 option_conflict('d', 'F');
12630 if (drop_only && fold_only)
12631 option_conflict('d', 'f');
12632 if (list_backups) {
12633 if (abort_edit)
12634 option_conflict('l', 'a');
12635 if (allow_conflict)
12636 option_conflict('l', 'C');
12637 if (continue_edit)
12638 option_conflict('l', 'c');
12639 if (edit_script_path)
12640 option_conflict('l', 'F');
12641 if (edit_logmsg_only)
12642 option_conflict('l', 'm');
12643 if (drop_only)
12644 option_conflict('l', 'd');
12645 if (fold_only)
12646 option_conflict('l', 'f');
12647 if (edit_only)
12648 option_conflict('l', 'e');
12649 if (delete_backups)
12650 option_conflict('l', 'X');
12651 if (argc != 0 && argc != 1)
12652 usage_histedit();
12653 } else if (delete_backups) {
12654 if (abort_edit)
12655 option_conflict('X', 'a');
12656 if (allow_conflict)
12657 option_conflict('X', 'C');
12658 if (continue_edit)
12659 option_conflict('X', 'c');
12660 if (drop_only)
12661 option_conflict('X', 'd');
12662 if (edit_script_path)
12663 option_conflict('X', 'F');
12664 if (edit_logmsg_only)
12665 option_conflict('X', 'm');
12666 if (fold_only)
12667 option_conflict('X', 'f');
12668 if (edit_only)
12669 option_conflict('X', 'e');
12670 if (list_backups)
12671 option_conflict('X', 'l');
12672 if (argc != 0 && argc != 1)
12673 usage_histedit();
12674 } else if (allow_conflict && !continue_edit)
12675 errx(1, "-C option requires -c");
12676 else if (argc != 0)
12677 usage_histedit();
12680 * This command cannot apply unveil(2) in all cases because the
12681 * user may choose to run an editor to edit the histedit script
12682 * and to edit individual commit log messages.
12683 * unveil(2) traverses exec(2); if an editor is used we have to
12684 * apply unveil after edit script and log messages have been written.
12685 * XXX TODO: Make use of unveil(2) where possible.
12688 cwd = getcwd(NULL, 0);
12689 if (cwd == NULL) {
12690 error = got_error_from_errno("getcwd");
12691 goto done;
12694 error = got_repo_pack_fds_open(&pack_fds);
12695 if (error != NULL)
12696 goto done;
12698 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12699 if (error) {
12700 if (list_backups || delete_backups) {
12701 if (error->code != GOT_ERR_NOT_WORKTREE)
12702 goto done;
12703 } else {
12704 if (error->code == GOT_ERR_NOT_WORKTREE)
12705 error = wrap_not_worktree_error(error,
12706 "histedit", cwd);
12707 goto done;
12711 if (list_backups || delete_backups) {
12712 error = got_repo_open(&repo,
12713 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12714 NULL, pack_fds);
12715 if (error != NULL)
12716 goto done;
12717 error = apply_unveil(got_repo_get_path(repo), 0,
12718 worktree ? got_worktree_get_root_path(worktree) : NULL);
12719 if (error)
12720 goto done;
12721 error = process_backup_refs(
12722 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12723 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12724 goto done; /* nothing else to do */
12727 error = get_gitconfig_path(&gitconfig_path);
12728 if (error)
12729 goto done;
12730 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12731 gitconfig_path, pack_fds);
12732 if (error != NULL)
12733 goto done;
12735 if (worktree != NULL && !list_backups && !delete_backups) {
12736 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12737 if (error)
12738 goto done;
12741 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12742 if (error)
12743 goto done;
12744 if (rebase_in_progress) {
12745 error = got_error(GOT_ERR_REBASING);
12746 goto done;
12749 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12750 repo);
12751 if (error)
12752 goto done;
12753 if (merge_in_progress) {
12754 error = got_error(GOT_ERR_MERGE_BUSY);
12755 goto done;
12758 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12759 if (error)
12760 goto done;
12762 if (edit_in_progress && edit_logmsg_only) {
12763 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12764 "histedit operation is in progress in this "
12765 "work tree and must be continued or aborted "
12766 "before the -m option can be used");
12767 goto done;
12769 if (edit_in_progress && drop_only) {
12770 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12771 "histedit operation is in progress in this "
12772 "work tree and must be continued or aborted "
12773 "before the -d option can be used");
12774 goto done;
12776 if (edit_in_progress && fold_only) {
12777 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12778 "histedit operation is in progress in this "
12779 "work tree and must be continued or aborted "
12780 "before the -f option can be used");
12781 goto done;
12783 if (edit_in_progress && edit_only) {
12784 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12785 "histedit operation is in progress in this "
12786 "work tree and must be continued or aborted "
12787 "before the -e option can be used");
12788 goto done;
12791 if (edit_in_progress && abort_edit) {
12792 error = got_worktree_histedit_continue(&resume_commit_id,
12793 &tmp_branch, &branch, &base_commit_id, &fileindex,
12794 worktree, repo);
12795 if (error)
12796 goto done;
12797 printf("Switching work tree to %s\n",
12798 got_ref_get_symref_target(branch));
12799 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12800 branch, base_commit_id, abort_progress, &upa);
12801 if (error)
12802 goto done;
12803 printf("Histedit of %s aborted\n",
12804 got_ref_get_symref_target(branch));
12805 print_merge_progress_stats(&upa);
12806 goto done; /* nothing else to do */
12807 } else if (abort_edit) {
12808 error = got_error(GOT_ERR_NOT_HISTEDIT);
12809 goto done;
12812 error = get_author(&committer, repo, worktree);
12813 if (error)
12814 goto done;
12816 if (continue_edit) {
12817 char *path;
12819 if (!edit_in_progress) {
12820 error = got_error(GOT_ERR_NOT_HISTEDIT);
12821 goto done;
12824 error = got_worktree_get_histedit_script_path(&path, worktree);
12825 if (error)
12826 goto done;
12828 error = histedit_load_list(&histedit_cmds, path, repo);
12829 free(path);
12830 if (error)
12831 goto done;
12833 error = got_worktree_histedit_continue(&resume_commit_id,
12834 &tmp_branch, &branch, &base_commit_id, &fileindex,
12835 worktree, repo);
12836 if (error)
12837 goto done;
12839 error = got_ref_resolve(&head_commit_id, repo, branch);
12840 if (error)
12841 goto done;
12843 error = got_object_open_as_commit(&commit, repo,
12844 head_commit_id);
12845 if (error)
12846 goto done;
12847 parent_ids = got_object_commit_get_parent_ids(commit);
12848 pid = STAILQ_FIRST(parent_ids);
12849 if (pid == NULL) {
12850 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12851 goto done;
12853 error = collect_commits(&commits, head_commit_id, &pid->id,
12854 base_commit_id, got_worktree_get_path_prefix(worktree),
12855 GOT_ERR_HISTEDIT_PATH, repo);
12856 got_object_commit_close(commit);
12857 commit = NULL;
12858 if (error)
12859 goto done;
12860 } else {
12861 if (edit_in_progress) {
12862 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12863 goto done;
12866 error = got_ref_open(&branch, repo,
12867 got_worktree_get_head_ref_name(worktree), 0);
12868 if (error != NULL)
12869 goto done;
12871 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12872 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12873 "will not edit commit history of a branch outside "
12874 "the \"refs/heads/\" reference namespace");
12875 goto done;
12878 error = got_ref_resolve(&head_commit_id, repo, branch);
12879 got_ref_close(branch);
12880 branch = NULL;
12881 if (error)
12882 goto done;
12884 error = got_object_open_as_commit(&commit, repo,
12885 head_commit_id);
12886 if (error)
12887 goto done;
12888 parent_ids = got_object_commit_get_parent_ids(commit);
12889 pid = STAILQ_FIRST(parent_ids);
12890 if (pid == NULL) {
12891 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12892 goto done;
12894 error = collect_commits(&commits, head_commit_id, &pid->id,
12895 got_worktree_get_base_commit_id(worktree),
12896 got_worktree_get_path_prefix(worktree),
12897 GOT_ERR_HISTEDIT_PATH, repo);
12898 got_object_commit_close(commit);
12899 commit = NULL;
12900 if (error)
12901 goto done;
12903 if (STAILQ_EMPTY(&commits)) {
12904 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12905 goto done;
12908 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12909 &base_commit_id, &fileindex, worktree, repo);
12910 if (error)
12911 goto done;
12913 if (edit_script_path) {
12914 error = histedit_load_list(&histedit_cmds,
12915 edit_script_path, 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;
12923 } else {
12924 const char *branch_name;
12925 branch_name = got_ref_get_symref_target(branch);
12926 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12927 branch_name += 11;
12928 error = histedit_edit_script(&histedit_cmds, &commits,
12929 branch_name, edit_logmsg_only, fold_only,
12930 drop_only, edit_only, repo);
12931 if (error) {
12932 got_worktree_histedit_abort(worktree, fileindex,
12933 repo, branch, base_commit_id,
12934 abort_progress, &upa);
12935 print_merge_progress_stats(&upa);
12936 goto done;
12941 error = histedit_save_list(&histedit_cmds, worktree,
12942 repo);
12943 if (error) {
12944 got_worktree_histedit_abort(worktree, fileindex,
12945 repo, branch, base_commit_id,
12946 abort_progress, &upa);
12947 print_merge_progress_stats(&upa);
12948 goto done;
12953 error = histedit_check_script(&histedit_cmds, &commits, repo);
12954 if (error)
12955 goto done;
12957 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12958 if (resume_commit_id) {
12959 if (got_object_id_cmp(hle->commit_id,
12960 resume_commit_id) != 0)
12961 continue;
12963 resume_commit_id = NULL;
12964 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12965 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12966 error = histedit_skip_commit(hle, worktree,
12967 repo);
12968 if (error)
12969 goto done;
12970 } else {
12971 struct got_pathlist_head paths;
12972 int have_changes = 0;
12974 TAILQ_INIT(&paths);
12975 error = got_pathlist_append(&paths, "", NULL);
12976 if (error)
12977 goto done;
12978 error = got_worktree_status(worktree, &paths,
12979 repo, 0, check_local_changes, &have_changes,
12980 check_cancelled, NULL);
12981 got_pathlist_free(&paths,
12982 GOT_PATHLIST_FREE_NONE);
12983 if (error) {
12984 if (error->code != GOT_ERR_CANCELLED)
12985 goto done;
12986 if (sigint_received || sigpipe_received)
12987 goto done;
12989 if (have_changes) {
12990 error = histedit_commit(NULL, worktree,
12991 fileindex, tmp_branch, hle,
12992 committer, allow_conflict, repo);
12993 if (error)
12994 goto done;
12995 } else {
12996 error = got_object_open_as_commit(
12997 &commit, repo, hle->commit_id);
12998 if (error)
12999 goto done;
13000 error = show_histedit_progress(commit,
13001 hle, NULL);
13002 got_object_commit_close(commit);
13003 commit = NULL;
13004 if (error)
13005 goto done;
13008 continue;
13011 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13012 error = histedit_skip_commit(hle, worktree, repo);
13013 if (error)
13014 goto done;
13015 continue;
13017 error = got_object_open_as_commit(&commit, repo,
13018 hle->commit_id);
13019 if (error)
13020 goto done;
13021 parent_ids = got_object_commit_get_parent_ids(commit);
13022 pid = STAILQ_FIRST(parent_ids);
13024 error = got_worktree_histedit_merge_files(&merged_paths,
13025 worktree, fileindex, &pid->id, hle->commit_id, repo,
13026 update_progress, &upa, check_cancelled, NULL);
13027 if (error)
13028 goto done;
13029 got_object_commit_close(commit);
13030 commit = NULL;
13032 print_merge_progress_stats(&upa);
13033 if (upa.conflicts > 0 || upa.missing > 0 ||
13034 upa.not_deleted > 0 || upa.unversioned > 0) {
13035 if (upa.conflicts > 0) {
13036 error = show_rebase_merge_conflict(
13037 hle->commit_id, repo);
13038 if (error)
13039 goto done;
13041 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13042 break;
13045 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13046 char *id_str;
13047 error = got_object_id_str(&id_str, hle->commit_id);
13048 if (error)
13049 goto done;
13050 printf("Stopping histedit for amending commit %s\n",
13051 id_str);
13052 free(id_str);
13053 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13054 error = got_worktree_histedit_postpone(worktree,
13055 fileindex);
13056 goto done;
13057 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13058 error = histedit_skip_commit(hle, worktree, repo);
13059 if (error)
13060 goto done;
13061 continue;
13062 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13063 error = histedit_edit_logmsg(hle, repo);
13064 if (error)
13065 goto done;
13068 error = histedit_commit(&merged_paths, worktree, fileindex,
13069 tmp_branch, hle, committer, allow_conflict, repo);
13070 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13071 if (error)
13072 goto done;
13075 if (upa.conflicts > 0 || upa.missing > 0 ||
13076 upa.not_deleted > 0 || upa.unversioned > 0) {
13077 error = got_worktree_histedit_postpone(worktree, fileindex);
13078 if (error)
13079 goto done;
13080 if (upa.conflicts > 0 && upa.missing == 0 &&
13081 upa.not_deleted == 0 && upa.unversioned == 0) {
13082 error = got_error_msg(GOT_ERR_CONFLICTS,
13083 "conflicts must be resolved before histedit "
13084 "can continue");
13085 } else if (upa.conflicts > 0) {
13086 error = got_error_msg(GOT_ERR_CONFLICTS,
13087 "conflicts must be resolved before histedit "
13088 "can continue; changes destined for some "
13089 "files were not yet merged and should be "
13090 "merged manually if required before the "
13091 "histedit operation is continued");
13092 } else {
13093 error = got_error_msg(GOT_ERR_CONFLICTS,
13094 "changes destined for some files were not "
13095 "yet merged and should be merged manually "
13096 "if required before the histedit operation "
13097 "is continued");
13099 } else
13100 error = histedit_complete(worktree, fileindex, tmp_branch,
13101 branch, repo);
13102 done:
13103 free(cwd);
13104 free(committer);
13105 free(gitconfig_path);
13106 got_object_id_queue_free(&commits);
13107 histedit_free_list(&histedit_cmds);
13108 free(head_commit_id);
13109 free(base_commit_id);
13110 free(resume_commit_id);
13111 if (commit)
13112 got_object_commit_close(commit);
13113 if (branch)
13114 got_ref_close(branch);
13115 if (tmp_branch)
13116 got_ref_close(tmp_branch);
13117 if (worktree)
13118 got_worktree_close(worktree);
13119 if (repo) {
13120 const struct got_error *close_err = got_repo_close(repo);
13121 if (error == NULL)
13122 error = close_err;
13124 if (pack_fds) {
13125 const struct got_error *pack_err =
13126 got_repo_pack_fds_close(pack_fds);
13127 if (error == NULL)
13128 error = pack_err;
13130 return error;
13133 __dead static void
13134 usage_integrate(void)
13136 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13137 exit(1);
13140 static const struct got_error *
13141 cmd_integrate(int argc, char *argv[])
13143 const struct got_error *error = NULL;
13144 struct got_repository *repo = NULL;
13145 struct got_worktree *worktree = NULL;
13146 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13147 const char *branch_arg = NULL;
13148 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13149 struct got_fileindex *fileindex = NULL;
13150 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13151 int ch;
13152 struct got_update_progress_arg upa;
13153 int *pack_fds = NULL;
13155 #ifndef PROFILE
13156 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13157 "unveil", NULL) == -1)
13158 err(1, "pledge");
13159 #endif
13161 while ((ch = getopt(argc, argv, "")) != -1) {
13162 switch (ch) {
13163 default:
13164 usage_integrate();
13165 /* NOTREACHED */
13169 argc -= optind;
13170 argv += optind;
13172 if (argc != 1)
13173 usage_integrate();
13174 branch_arg = argv[0];
13176 cwd = getcwd(NULL, 0);
13177 if (cwd == NULL) {
13178 error = got_error_from_errno("getcwd");
13179 goto done;
13182 error = got_repo_pack_fds_open(&pack_fds);
13183 if (error != NULL)
13184 goto done;
13186 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13187 if (error) {
13188 if (error->code == GOT_ERR_NOT_WORKTREE)
13189 error = wrap_not_worktree_error(error, "integrate",
13190 cwd);
13191 goto done;
13194 error = check_rebase_or_histedit_in_progress(worktree);
13195 if (error)
13196 goto done;
13198 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13199 NULL, pack_fds);
13200 if (error != NULL)
13201 goto done;
13203 error = apply_unveil(got_repo_get_path(repo), 0,
13204 got_worktree_get_root_path(worktree));
13205 if (error)
13206 goto done;
13208 error = check_merge_in_progress(worktree, repo);
13209 if (error)
13210 goto done;
13212 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13213 error = got_error_from_errno("asprintf");
13214 goto done;
13217 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13218 &base_branch_ref, worktree, refname, repo);
13219 if (error)
13220 goto done;
13222 refname = strdup(got_ref_get_name(branch_ref));
13223 if (refname == NULL) {
13224 error = got_error_from_errno("strdup");
13225 got_worktree_integrate_abort(worktree, fileindex, repo,
13226 branch_ref, base_branch_ref);
13227 goto done;
13229 base_refname = strdup(got_ref_get_name(base_branch_ref));
13230 if (base_refname == NULL) {
13231 error = got_error_from_errno("strdup");
13232 got_worktree_integrate_abort(worktree, fileindex, repo,
13233 branch_ref, base_branch_ref);
13234 goto done;
13236 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13237 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13238 got_worktree_integrate_abort(worktree, fileindex, repo,
13239 branch_ref, base_branch_ref);
13240 goto done;
13243 error = got_ref_resolve(&commit_id, repo, branch_ref);
13244 if (error)
13245 goto done;
13247 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13248 if (error)
13249 goto done;
13251 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13252 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13253 "specified branch has already been integrated");
13254 got_worktree_integrate_abort(worktree, fileindex, repo,
13255 branch_ref, base_branch_ref);
13256 goto done;
13259 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13260 if (error) {
13261 if (error->code == GOT_ERR_ANCESTRY)
13262 error = got_error(GOT_ERR_REBASE_REQUIRED);
13263 got_worktree_integrate_abort(worktree, fileindex, repo,
13264 branch_ref, base_branch_ref);
13265 goto done;
13268 memset(&upa, 0, sizeof(upa));
13269 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13270 branch_ref, base_branch_ref, update_progress, &upa,
13271 check_cancelled, NULL);
13272 if (error)
13273 goto done;
13275 printf("Integrated %s into %s\n", refname, base_refname);
13276 print_update_progress_stats(&upa);
13277 done:
13278 if (repo) {
13279 const struct got_error *close_err = got_repo_close(repo);
13280 if (error == NULL)
13281 error = close_err;
13283 if (worktree)
13284 got_worktree_close(worktree);
13285 if (pack_fds) {
13286 const struct got_error *pack_err =
13287 got_repo_pack_fds_close(pack_fds);
13288 if (error == NULL)
13289 error = pack_err;
13291 free(cwd);
13292 free(base_commit_id);
13293 free(commit_id);
13294 free(refname);
13295 free(base_refname);
13296 return error;
13299 __dead static void
13300 usage_merge(void)
13302 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13303 exit(1);
13306 static const struct got_error *
13307 cmd_merge(int argc, char *argv[])
13309 const struct got_error *error = NULL;
13310 struct got_worktree *worktree = NULL;
13311 struct got_repository *repo = NULL;
13312 struct got_fileindex *fileindex = NULL;
13313 char *cwd = NULL, *id_str = NULL, *author = NULL;
13314 char *gitconfig_path = NULL;
13315 struct got_reference *branch = NULL, *wt_branch = NULL;
13316 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13317 struct got_object_id *wt_branch_tip = NULL;
13318 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13319 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13320 struct got_update_progress_arg upa;
13321 struct got_object_id *merge_commit_id = NULL;
13322 char *branch_name = NULL;
13323 int *pack_fds = NULL;
13325 memset(&upa, 0, sizeof(upa));
13327 #ifndef PROFILE
13328 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13329 "unveil", NULL) == -1)
13330 err(1, "pledge");
13331 #endif
13333 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13334 switch (ch) {
13335 case 'a':
13336 abort_merge = 1;
13337 break;
13338 case 'C':
13339 allow_conflict = 1;
13340 break;
13341 case 'c':
13342 continue_merge = 1;
13343 break;
13344 case 'M':
13345 prefer_fast_forward = 0;
13346 break;
13347 case 'n':
13348 interrupt_merge = 1;
13349 break;
13350 default:
13351 usage_merge();
13352 /* NOTREACHED */
13356 argc -= optind;
13357 argv += optind;
13359 if (abort_merge) {
13360 if (continue_merge)
13361 option_conflict('a', 'c');
13362 if (!prefer_fast_forward)
13363 option_conflict('a', 'M');
13364 if (interrupt_merge)
13365 option_conflict('a', 'n');
13366 } else if (continue_merge) {
13367 if (!prefer_fast_forward)
13368 option_conflict('c', 'M');
13369 if (interrupt_merge)
13370 option_conflict('c', 'n');
13372 if (allow_conflict) {
13373 if (!continue_merge)
13374 errx(1, "-C option requires -c");
13376 if (abort_merge || continue_merge) {
13377 if (argc != 0)
13378 usage_merge();
13379 } else if (argc != 1)
13380 usage_merge();
13382 cwd = getcwd(NULL, 0);
13383 if (cwd == NULL) {
13384 error = got_error_from_errno("getcwd");
13385 goto done;
13388 error = got_repo_pack_fds_open(&pack_fds);
13389 if (error != NULL)
13390 goto done;
13392 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13393 if (error) {
13394 if (error->code == GOT_ERR_NOT_WORKTREE)
13395 error = wrap_not_worktree_error(error,
13396 "merge", cwd);
13397 goto done;
13400 error = get_gitconfig_path(&gitconfig_path);
13401 if (error)
13402 goto done;
13403 error = got_repo_open(&repo,
13404 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13405 gitconfig_path, pack_fds);
13406 if (error != NULL)
13407 goto done;
13409 if (worktree != NULL) {
13410 error = worktree_has_logmsg_ref("merge", worktree, repo);
13411 if (error)
13412 goto done;
13415 error = apply_unveil(got_repo_get_path(repo), 0,
13416 worktree ? got_worktree_get_root_path(worktree) : NULL);
13417 if (error)
13418 goto done;
13420 error = check_rebase_or_histedit_in_progress(worktree);
13421 if (error)
13422 goto done;
13424 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13425 repo);
13426 if (error)
13427 goto done;
13429 if (merge_in_progress && !(abort_merge || continue_merge)) {
13430 error = got_error(GOT_ERR_MERGE_BUSY);
13431 goto done;
13434 if (!merge_in_progress && (abort_merge || continue_merge)) {
13435 error = got_error(GOT_ERR_NOT_MERGING);
13436 goto done;
13439 if (abort_merge) {
13440 error = got_worktree_merge_continue(&branch_name,
13441 &branch_tip, &fileindex, worktree, repo);
13442 if (error)
13443 goto done;
13444 error = got_worktree_merge_abort(worktree, fileindex, repo,
13445 abort_progress, &upa);
13446 if (error)
13447 goto done;
13448 printf("Merge of %s aborted\n", branch_name);
13449 goto done; /* nothing else to do */
13452 if (strncmp(got_worktree_get_head_ref_name(worktree),
13453 "refs/heads/", 11) != 0) {
13454 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13455 "work tree's current branch %s is outside the "
13456 "\"refs/heads/\" reference namespace; "
13457 "update -b required",
13458 got_worktree_get_head_ref_name(worktree));
13459 goto done;
13462 error = get_author(&author, repo, worktree);
13463 if (error)
13464 goto done;
13466 error = got_ref_open(&wt_branch, repo,
13467 got_worktree_get_head_ref_name(worktree), 0);
13468 if (error)
13469 goto done;
13470 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13471 if (error)
13472 goto done;
13474 if (continue_merge) {
13475 struct got_object_id *base_commit_id;
13476 base_commit_id = got_worktree_get_base_commit_id(worktree);
13477 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13478 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13479 goto done;
13481 error = got_worktree_merge_continue(&branch_name,
13482 &branch_tip, &fileindex, worktree, repo);
13483 if (error)
13484 goto done;
13485 } else {
13486 error = got_ref_open(&branch, repo, argv[0], 0);
13487 if (error != NULL)
13488 goto done;
13489 branch_name = strdup(got_ref_get_name(branch));
13490 if (branch_name == NULL) {
13491 error = got_error_from_errno("strdup");
13492 goto done;
13494 error = got_ref_resolve(&branch_tip, repo, branch);
13495 if (error)
13496 goto done;
13499 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13500 wt_branch_tip, branch_tip, 0, repo,
13501 check_cancelled, NULL);
13502 if (error && error->code != GOT_ERR_ANCESTRY)
13503 goto done;
13505 if (!continue_merge) {
13506 error = check_path_prefix(wt_branch_tip, branch_tip,
13507 got_worktree_get_path_prefix(worktree),
13508 GOT_ERR_MERGE_PATH, repo);
13509 if (error)
13510 goto done;
13511 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13512 if (error)
13513 goto done;
13514 if (prefer_fast_forward && yca_id &&
13515 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13516 struct got_pathlist_head paths;
13517 if (interrupt_merge) {
13518 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13519 "there are no changes to merge since %s "
13520 "is already based on %s; merge cannot be "
13521 "interrupted for amending; -n",
13522 branch_name, got_ref_get_name(wt_branch));
13523 goto done;
13525 printf("Forwarding %s to %s\n",
13526 got_ref_get_name(wt_branch), branch_name);
13527 error = got_ref_change_ref(wt_branch, branch_tip);
13528 if (error)
13529 goto done;
13530 error = got_ref_write(wt_branch, repo);
13531 if (error)
13532 goto done;
13533 error = got_worktree_set_base_commit_id(worktree, repo,
13534 branch_tip);
13535 if (error)
13536 goto done;
13537 TAILQ_INIT(&paths);
13538 error = got_pathlist_append(&paths, "", NULL);
13539 if (error)
13540 goto done;
13541 error = got_worktree_checkout_files(worktree,
13542 &paths, repo, update_progress, &upa,
13543 check_cancelled, NULL);
13544 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13545 if (error)
13546 goto done;
13547 if (upa.did_something) {
13548 char *id_str;
13549 error = got_object_id_str(&id_str, branch_tip);
13550 if (error)
13551 goto done;
13552 printf("Updated to commit %s\n", id_str);
13553 free(id_str);
13554 } else
13555 printf("Already up-to-date\n");
13556 print_update_progress_stats(&upa);
13557 goto done;
13559 error = got_worktree_merge_write_refs(worktree, branch, repo);
13560 if (error)
13561 goto done;
13563 error = got_worktree_merge_branch(worktree, fileindex,
13564 yca_id, branch_tip, repo, update_progress, &upa,
13565 check_cancelled, NULL);
13566 if (error)
13567 goto done;
13568 print_merge_progress_stats(&upa);
13569 if (!upa.did_something) {
13570 error = got_worktree_merge_abort(worktree, fileindex,
13571 repo, abort_progress, &upa);
13572 if (error)
13573 goto done;
13574 printf("Already up-to-date\n");
13575 goto done;
13579 if (interrupt_merge) {
13580 error = got_worktree_merge_postpone(worktree, fileindex);
13581 if (error)
13582 goto done;
13583 printf("Merge of %s interrupted on request\n", branch_name);
13584 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13585 upa.not_deleted > 0 || upa.unversioned > 0) {
13586 error = got_worktree_merge_postpone(worktree, fileindex);
13587 if (error)
13588 goto done;
13589 if (upa.conflicts > 0 && upa.missing == 0 &&
13590 upa.not_deleted == 0 && upa.unversioned == 0) {
13591 error = got_error_msg(GOT_ERR_CONFLICTS,
13592 "conflicts must be resolved before merging "
13593 "can continue");
13594 } else if (upa.conflicts > 0) {
13595 error = got_error_msg(GOT_ERR_CONFLICTS,
13596 "conflicts must be resolved before merging "
13597 "can continue; changes destined for some "
13598 "files were not yet merged and "
13599 "should be merged manually if required before the "
13600 "merge operation is continued");
13601 } else {
13602 error = got_error_msg(GOT_ERR_CONFLICTS,
13603 "changes destined for some "
13604 "files were not yet merged and should be "
13605 "merged manually if required before the "
13606 "merge operation is continued");
13608 goto done;
13609 } else {
13610 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13611 fileindex, author, NULL, 1, branch_tip, branch_name,
13612 allow_conflict, repo, continue_merge ? print_status : NULL,
13613 NULL);
13614 if (error)
13615 goto done;
13616 error = got_worktree_merge_complete(worktree, fileindex, repo);
13617 if (error)
13618 goto done;
13619 error = got_object_id_str(&id_str, merge_commit_id);
13620 if (error)
13621 goto done;
13622 printf("Merged %s into %s: %s\n", branch_name,
13623 got_worktree_get_head_ref_name(worktree),
13624 id_str);
13627 done:
13628 free(gitconfig_path);
13629 free(id_str);
13630 free(merge_commit_id);
13631 free(author);
13632 free(branch_tip);
13633 free(branch_name);
13634 free(yca_id);
13635 if (branch)
13636 got_ref_close(branch);
13637 if (wt_branch)
13638 got_ref_close(wt_branch);
13639 if (worktree)
13640 got_worktree_close(worktree);
13641 if (repo) {
13642 const struct got_error *close_err = got_repo_close(repo);
13643 if (error == NULL)
13644 error = close_err;
13646 if (pack_fds) {
13647 const struct got_error *pack_err =
13648 got_repo_pack_fds_close(pack_fds);
13649 if (error == NULL)
13650 error = pack_err;
13652 return error;
13655 __dead static void
13656 usage_stage(void)
13658 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13659 "[path ...]\n", getprogname());
13660 exit(1);
13663 static const struct got_error *
13664 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13665 const char *path, struct got_object_id *blob_id,
13666 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13667 int dirfd, const char *de_name)
13669 const struct got_error *err = NULL;
13670 char *id_str = NULL;
13672 if (staged_status != GOT_STATUS_ADD &&
13673 staged_status != GOT_STATUS_MODIFY &&
13674 staged_status != GOT_STATUS_DELETE)
13675 return NULL;
13677 if (staged_status == GOT_STATUS_ADD ||
13678 staged_status == GOT_STATUS_MODIFY)
13679 err = got_object_id_str(&id_str, staged_blob_id);
13680 else
13681 err = got_object_id_str(&id_str, blob_id);
13682 if (err)
13683 return err;
13685 printf("%s %c %s\n", id_str, staged_status, path);
13686 free(id_str);
13687 return NULL;
13690 static const struct got_error *
13691 cmd_stage(int argc, char *argv[])
13693 const struct got_error *error = NULL;
13694 struct got_repository *repo = NULL;
13695 struct got_worktree *worktree = NULL;
13696 char *cwd = NULL;
13697 struct got_pathlist_head paths;
13698 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13699 FILE *patch_script_file = NULL;
13700 const char *patch_script_path = NULL;
13701 struct choose_patch_arg cpa;
13702 int *pack_fds = NULL;
13704 TAILQ_INIT(&paths);
13706 #ifndef PROFILE
13707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13708 "unveil", NULL) == -1)
13709 err(1, "pledge");
13710 #endif
13712 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13713 switch (ch) {
13714 case 'F':
13715 patch_script_path = optarg;
13716 break;
13717 case 'l':
13718 list_stage = 1;
13719 break;
13720 case 'p':
13721 pflag = 1;
13722 break;
13723 case 'S':
13724 allow_bad_symlinks = 1;
13725 break;
13726 default:
13727 usage_stage();
13728 /* NOTREACHED */
13732 argc -= optind;
13733 argv += optind;
13735 if (list_stage && (pflag || patch_script_path))
13736 errx(1, "-l option cannot be used with other options");
13737 if (patch_script_path && !pflag)
13738 errx(1, "-F option can only be used together with -p option");
13740 cwd = getcwd(NULL, 0);
13741 if (cwd == NULL) {
13742 error = got_error_from_errno("getcwd");
13743 goto done;
13746 error = got_repo_pack_fds_open(&pack_fds);
13747 if (error != NULL)
13748 goto done;
13750 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13751 if (error) {
13752 if (error->code == GOT_ERR_NOT_WORKTREE)
13753 error = wrap_not_worktree_error(error, "stage", cwd);
13754 goto done;
13757 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13758 NULL, pack_fds);
13759 if (error != NULL)
13760 goto done;
13762 if (patch_script_path) {
13763 patch_script_file = fopen(patch_script_path, "re");
13764 if (patch_script_file == NULL) {
13765 error = got_error_from_errno2("fopen",
13766 patch_script_path);
13767 goto done;
13770 error = apply_unveil(got_repo_get_path(repo), 0,
13771 got_worktree_get_root_path(worktree));
13772 if (error)
13773 goto done;
13775 error = check_merge_in_progress(worktree, repo);
13776 if (error)
13777 goto done;
13779 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13780 if (error)
13781 goto done;
13783 if (list_stage)
13784 error = got_worktree_status(worktree, &paths, repo, 0,
13785 print_stage, NULL, check_cancelled, NULL);
13786 else {
13787 cpa.patch_script_file = patch_script_file;
13788 cpa.action = "stage";
13789 error = got_worktree_stage(worktree, &paths,
13790 pflag ? NULL : print_status, NULL,
13791 pflag ? choose_patch : NULL, &cpa,
13792 allow_bad_symlinks, repo);
13794 done:
13795 if (patch_script_file && fclose(patch_script_file) == EOF &&
13796 error == NULL)
13797 error = got_error_from_errno2("fclose", patch_script_path);
13798 if (repo) {
13799 const struct got_error *close_err = got_repo_close(repo);
13800 if (error == NULL)
13801 error = close_err;
13803 if (worktree)
13804 got_worktree_close(worktree);
13805 if (pack_fds) {
13806 const struct got_error *pack_err =
13807 got_repo_pack_fds_close(pack_fds);
13808 if (error == NULL)
13809 error = pack_err;
13811 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13812 free(cwd);
13813 return error;
13816 __dead static void
13817 usage_unstage(void)
13819 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13820 "[path ...]\n", getprogname());
13821 exit(1);
13825 static const struct got_error *
13826 cmd_unstage(int argc, char *argv[])
13828 const struct got_error *error = NULL;
13829 struct got_repository *repo = NULL;
13830 struct got_worktree *worktree = NULL;
13831 char *cwd = NULL;
13832 struct got_pathlist_head paths;
13833 int ch, pflag = 0;
13834 struct got_update_progress_arg upa;
13835 FILE *patch_script_file = NULL;
13836 const char *patch_script_path = NULL;
13837 struct choose_patch_arg cpa;
13838 int *pack_fds = NULL;
13840 TAILQ_INIT(&paths);
13842 #ifndef PROFILE
13843 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13844 "unveil", NULL) == -1)
13845 err(1, "pledge");
13846 #endif
13848 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13849 switch (ch) {
13850 case 'F':
13851 patch_script_path = optarg;
13852 break;
13853 case 'p':
13854 pflag = 1;
13855 break;
13856 default:
13857 usage_unstage();
13858 /* NOTREACHED */
13862 argc -= optind;
13863 argv += optind;
13865 if (patch_script_path && !pflag)
13866 errx(1, "-F option can only be used together with -p option");
13868 cwd = getcwd(NULL, 0);
13869 if (cwd == NULL) {
13870 error = got_error_from_errno("getcwd");
13871 goto done;
13874 error = got_repo_pack_fds_open(&pack_fds);
13875 if (error != NULL)
13876 goto done;
13878 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13879 if (error) {
13880 if (error->code == GOT_ERR_NOT_WORKTREE)
13881 error = wrap_not_worktree_error(error, "unstage", cwd);
13882 goto done;
13885 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13886 NULL, pack_fds);
13887 if (error != NULL)
13888 goto done;
13890 if (patch_script_path) {
13891 patch_script_file = fopen(patch_script_path, "re");
13892 if (patch_script_file == NULL) {
13893 error = got_error_from_errno2("fopen",
13894 patch_script_path);
13895 goto done;
13899 error = apply_unveil(got_repo_get_path(repo), 0,
13900 got_worktree_get_root_path(worktree));
13901 if (error)
13902 goto done;
13904 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13905 if (error)
13906 goto done;
13908 cpa.patch_script_file = patch_script_file;
13909 cpa.action = "unstage";
13910 memset(&upa, 0, sizeof(upa));
13911 error = got_worktree_unstage(worktree, &paths, update_progress,
13912 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13913 if (!error)
13914 print_merge_progress_stats(&upa);
13915 done:
13916 if (patch_script_file && fclose(patch_script_file) == EOF &&
13917 error == NULL)
13918 error = got_error_from_errno2("fclose", patch_script_path);
13919 if (repo) {
13920 const struct got_error *close_err = got_repo_close(repo);
13921 if (error == NULL)
13922 error = close_err;
13924 if (worktree)
13925 got_worktree_close(worktree);
13926 if (pack_fds) {
13927 const struct got_error *pack_err =
13928 got_repo_pack_fds_close(pack_fds);
13929 if (error == NULL)
13930 error = pack_err;
13932 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13933 free(cwd);
13934 return error;
13937 __dead static void
13938 usage_cat(void)
13940 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13941 "arg ...\n", getprogname());
13942 exit(1);
13945 static const struct got_error *
13946 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13948 const struct got_error *err;
13949 struct got_blob_object *blob;
13950 int fd = -1;
13952 fd = got_opentempfd();
13953 if (fd == -1)
13954 return got_error_from_errno("got_opentempfd");
13956 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13957 if (err)
13958 goto done;
13960 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13961 done:
13962 if (fd != -1 && close(fd) == -1 && err == NULL)
13963 err = got_error_from_errno("close");
13964 if (blob)
13965 got_object_blob_close(blob);
13966 return err;
13969 static const struct got_error *
13970 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13972 const struct got_error *err;
13973 struct got_tree_object *tree;
13974 int nentries, i;
13976 err = got_object_open_as_tree(&tree, repo, id);
13977 if (err)
13978 return err;
13980 nentries = got_object_tree_get_nentries(tree);
13981 for (i = 0; i < nentries; i++) {
13982 struct got_tree_entry *te;
13983 char *id_str;
13984 if (sigint_received || sigpipe_received)
13985 break;
13986 te = got_object_tree_get_entry(tree, i);
13987 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13988 if (err)
13989 break;
13990 fprintf(outfile, "%s %.7o %s\n", id_str,
13991 got_tree_entry_get_mode(te),
13992 got_tree_entry_get_name(te));
13993 free(id_str);
13996 got_object_tree_close(tree);
13997 return err;
14000 static const struct got_error *
14001 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14003 const struct got_error *err;
14004 struct got_commit_object *commit;
14005 const struct got_object_id_queue *parent_ids;
14006 struct got_object_qid *pid;
14007 char *id_str = NULL;
14008 const char *logmsg = NULL;
14009 char gmtoff[6];
14011 err = got_object_open_as_commit(&commit, repo, id);
14012 if (err)
14013 return err;
14015 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14016 if (err)
14017 goto done;
14019 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14020 parent_ids = got_object_commit_get_parent_ids(commit);
14021 fprintf(outfile, "numparents %d\n",
14022 got_object_commit_get_nparents(commit));
14023 STAILQ_FOREACH(pid, parent_ids, entry) {
14024 char *pid_str;
14025 err = got_object_id_str(&pid_str, &pid->id);
14026 if (err)
14027 goto done;
14028 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14029 free(pid_str);
14031 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14032 got_object_commit_get_author_gmtoff(commit));
14033 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14034 got_object_commit_get_author(commit),
14035 (long long)got_object_commit_get_author_time(commit),
14036 gmtoff);
14038 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14039 got_object_commit_get_committer_gmtoff(commit));
14040 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14041 got_object_commit_get_committer(commit),
14042 (long long)got_object_commit_get_committer_time(commit),
14043 gmtoff);
14045 logmsg = got_object_commit_get_logmsg_raw(commit);
14046 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14047 fprintf(outfile, "%s", logmsg);
14048 done:
14049 free(id_str);
14050 got_object_commit_close(commit);
14051 return err;
14054 static const struct got_error *
14055 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14057 const struct got_error *err;
14058 struct got_tag_object *tag;
14059 char *id_str = NULL;
14060 const char *tagmsg = NULL;
14061 char gmtoff[6];
14063 err = got_object_open_as_tag(&tag, repo, id);
14064 if (err)
14065 return err;
14067 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14068 if (err)
14069 goto done;
14071 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14073 switch (got_object_tag_get_object_type(tag)) {
14074 case GOT_OBJ_TYPE_BLOB:
14075 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14076 GOT_OBJ_LABEL_BLOB);
14077 break;
14078 case GOT_OBJ_TYPE_TREE:
14079 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14080 GOT_OBJ_LABEL_TREE);
14081 break;
14082 case GOT_OBJ_TYPE_COMMIT:
14083 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14084 GOT_OBJ_LABEL_COMMIT);
14085 break;
14086 case GOT_OBJ_TYPE_TAG:
14087 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14088 GOT_OBJ_LABEL_TAG);
14089 break;
14090 default:
14091 break;
14094 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14095 got_object_tag_get_name(tag));
14097 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14098 got_object_tag_get_tagger_gmtoff(tag));
14099 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14100 got_object_tag_get_tagger(tag),
14101 (long long)got_object_tag_get_tagger_time(tag),
14102 gmtoff);
14104 tagmsg = got_object_tag_get_message(tag);
14105 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14106 fprintf(outfile, "%s", tagmsg);
14107 done:
14108 free(id_str);
14109 got_object_tag_close(tag);
14110 return err;
14113 static const struct got_error *
14114 cmd_cat(int argc, char *argv[])
14116 const struct got_error *error;
14117 struct got_repository *repo = NULL;
14118 struct got_worktree *worktree = NULL;
14119 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14120 char *keyword_idstr = NULL;
14121 const char *commit_id_str = NULL;
14122 struct got_object_id *id = NULL, *commit_id = NULL;
14123 struct got_commit_object *commit = NULL;
14124 int ch, obj_type, i, force_path = 0;
14125 struct got_reflist_head refs;
14126 int *pack_fds = NULL;
14128 TAILQ_INIT(&refs);
14130 #ifndef PROFILE
14131 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14132 NULL) == -1)
14133 err(1, "pledge");
14134 #endif
14136 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14137 switch (ch) {
14138 case 'c':
14139 commit_id_str = optarg;
14140 break;
14141 case 'P':
14142 force_path = 1;
14143 break;
14144 case 'r':
14145 repo_path = realpath(optarg, NULL);
14146 if (repo_path == NULL)
14147 return got_error_from_errno2("realpath",
14148 optarg);
14149 got_path_strip_trailing_slashes(repo_path);
14150 break;
14151 default:
14152 usage_cat();
14153 /* NOTREACHED */
14157 argc -= optind;
14158 argv += optind;
14160 cwd = getcwd(NULL, 0);
14161 if (cwd == NULL) {
14162 error = got_error_from_errno("getcwd");
14163 goto done;
14166 error = got_repo_pack_fds_open(&pack_fds);
14167 if (error != NULL)
14168 goto done;
14170 if (repo_path == NULL) {
14171 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14172 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14173 goto done;
14174 if (worktree) {
14175 repo_path = strdup(
14176 got_worktree_get_repo_path(worktree));
14177 if (repo_path == NULL) {
14178 error = got_error_from_errno("strdup");
14179 goto done;
14182 if (commit_id_str == NULL) {
14183 /* Release work tree lock. */
14184 got_worktree_close(worktree);
14185 worktree = NULL;
14190 if (repo_path == NULL) {
14191 repo_path = strdup(cwd);
14192 if (repo_path == NULL)
14193 return got_error_from_errno("strdup");
14196 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14197 free(repo_path);
14198 if (error != NULL)
14199 goto done;
14201 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14202 if (error)
14203 goto done;
14205 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14206 if (error)
14207 goto done;
14209 if (commit_id_str != NULL) {
14210 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14211 repo, worktree);
14212 if (error != NULL)
14213 goto done;
14214 if (keyword_idstr != NULL)
14215 commit_id_str = keyword_idstr;
14216 if (worktree != NULL) {
14217 got_worktree_close(worktree);
14218 worktree = NULL;
14220 } else
14221 commit_id_str = GOT_REF_HEAD;
14222 error = got_repo_match_object_id(&commit_id, NULL,
14223 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14224 if (error)
14225 goto done;
14227 error = got_object_open_as_commit(&commit, repo, commit_id);
14228 if (error)
14229 goto done;
14231 for (i = 0; i < argc; i++) {
14232 if (force_path) {
14233 error = got_object_id_by_path(&id, repo, commit,
14234 argv[i]);
14235 if (error)
14236 break;
14237 } else {
14238 error = got_repo_match_object_id(&id, &label, argv[i],
14239 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14240 repo);
14241 if (error) {
14242 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14243 error->code != GOT_ERR_NOT_REF)
14244 break;
14245 error = got_object_id_by_path(&id, repo,
14246 commit, argv[i]);
14247 if (error)
14248 break;
14252 error = got_object_get_type(&obj_type, repo, id);
14253 if (error)
14254 break;
14256 switch (obj_type) {
14257 case GOT_OBJ_TYPE_BLOB:
14258 error = cat_blob(id, repo, stdout);
14259 break;
14260 case GOT_OBJ_TYPE_TREE:
14261 error = cat_tree(id, repo, stdout);
14262 break;
14263 case GOT_OBJ_TYPE_COMMIT:
14264 error = cat_commit(id, repo, stdout);
14265 break;
14266 case GOT_OBJ_TYPE_TAG:
14267 error = cat_tag(id, repo, stdout);
14268 break;
14269 default:
14270 error = got_error(GOT_ERR_OBJ_TYPE);
14271 break;
14273 if (error)
14274 break;
14275 free(label);
14276 label = NULL;
14277 free(id);
14278 id = NULL;
14280 done:
14281 free(label);
14282 free(id);
14283 free(commit_id);
14284 free(keyword_idstr);
14285 if (commit)
14286 got_object_commit_close(commit);
14287 if (worktree)
14288 got_worktree_close(worktree);
14289 if (repo) {
14290 const struct got_error *close_err = got_repo_close(repo);
14291 if (error == NULL)
14292 error = close_err;
14294 if (pack_fds) {
14295 const struct got_error *pack_err =
14296 got_repo_pack_fds_close(pack_fds);
14297 if (error == NULL)
14298 error = pack_err;
14301 got_ref_list_free(&refs);
14302 return error;
14305 __dead static void
14306 usage_info(void)
14308 fprintf(stderr, "usage: %s info [path ...]\n",
14309 getprogname());
14310 exit(1);
14313 static const struct got_error *
14314 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14315 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14316 struct got_object_id *commit_id)
14318 const struct got_error *err = NULL;
14319 char *id_str = NULL;
14320 char datebuf[128];
14321 struct tm mytm, *tm;
14322 struct got_pathlist_head *paths = arg;
14323 struct got_pathlist_entry *pe;
14326 * Clear error indication from any of the path arguments which
14327 * would cause this file index entry to be displayed.
14329 TAILQ_FOREACH(pe, paths, entry) {
14330 if (got_path_cmp(path, pe->path, strlen(path),
14331 pe->path_len) == 0 ||
14332 got_path_is_child(path, pe->path, pe->path_len))
14333 pe->data = NULL; /* no error */
14336 printf(GOT_COMMIT_SEP_STR);
14337 if (S_ISLNK(mode))
14338 printf("symlink: %s\n", path);
14339 else if (S_ISREG(mode)) {
14340 printf("file: %s\n", path);
14341 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14342 } else if (S_ISDIR(mode))
14343 printf("directory: %s\n", path);
14344 else
14345 printf("something: %s\n", path);
14347 tm = localtime_r(&mtime, &mytm);
14348 if (tm == NULL)
14349 return NULL;
14350 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14351 return got_error(GOT_ERR_NO_SPACE);
14352 printf("timestamp: %s\n", datebuf);
14354 if (blob_id) {
14355 err = got_object_id_str(&id_str, blob_id);
14356 if (err)
14357 return err;
14358 printf("based on blob: %s\n", id_str);
14359 free(id_str);
14362 if (staged_blob_id) {
14363 err = got_object_id_str(&id_str, staged_blob_id);
14364 if (err)
14365 return err;
14366 printf("based on staged blob: %s\n", id_str);
14367 free(id_str);
14370 if (commit_id) {
14371 err = got_object_id_str(&id_str, commit_id);
14372 if (err)
14373 return err;
14374 printf("based on commit: %s\n", id_str);
14375 free(id_str);
14378 return NULL;
14381 static const struct got_error *
14382 cmd_info(int argc, char *argv[])
14384 const struct got_error *error = NULL;
14385 struct got_worktree *worktree = NULL;
14386 char *cwd = NULL, *id_str = NULL;
14387 struct got_pathlist_head paths;
14388 char *uuidstr = NULL;
14389 int ch, show_files = 0;
14391 TAILQ_INIT(&paths);
14393 #ifndef PROFILE
14394 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14395 NULL) == -1)
14396 err(1, "pledge");
14397 #endif
14399 while ((ch = getopt(argc, argv, "")) != -1) {
14400 switch (ch) {
14401 default:
14402 usage_info();
14403 /* NOTREACHED */
14407 argc -= optind;
14408 argv += optind;
14410 cwd = getcwd(NULL, 0);
14411 if (cwd == NULL) {
14412 error = got_error_from_errno("getcwd");
14413 goto done;
14416 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14417 if (error) {
14418 if (error->code == GOT_ERR_NOT_WORKTREE)
14419 error = wrap_not_worktree_error(error, "info", cwd);
14420 goto done;
14423 #ifndef PROFILE
14424 /* Remove "wpath cpath proc exec sendfd" promises. */
14425 if (pledge("stdio rpath flock unveil", NULL) == -1)
14426 err(1, "pledge");
14427 #endif
14428 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14429 if (error)
14430 goto done;
14432 if (argc >= 1) {
14433 error = get_worktree_paths_from_argv(&paths, argc, argv,
14434 worktree);
14435 if (error)
14436 goto done;
14437 show_files = 1;
14440 error = got_object_id_str(&id_str,
14441 got_worktree_get_base_commit_id(worktree));
14442 if (error)
14443 goto done;
14445 error = got_worktree_get_uuid(&uuidstr, worktree);
14446 if (error)
14447 goto done;
14449 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14450 printf("work tree base commit: %s\n", id_str);
14451 printf("work tree path prefix: %s\n",
14452 got_worktree_get_path_prefix(worktree));
14453 printf("work tree branch reference: %s\n",
14454 got_worktree_get_head_ref_name(worktree));
14455 printf("work tree UUID: %s\n", uuidstr);
14456 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14458 if (show_files) {
14459 struct got_pathlist_entry *pe;
14460 TAILQ_FOREACH(pe, &paths, entry) {
14461 if (pe->path_len == 0)
14462 continue;
14464 * Assume this path will fail. This will be corrected
14465 * in print_path_info() in case the path does suceeed.
14467 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14469 error = got_worktree_path_info(worktree, &paths,
14470 print_path_info, &paths, check_cancelled, NULL);
14471 if (error)
14472 goto done;
14473 TAILQ_FOREACH(pe, &paths, entry) {
14474 if (pe->data != NULL) {
14475 const struct got_error *perr;
14477 perr = pe->data;
14478 error = got_error_fmt(perr->code, "%s",
14479 pe->path);
14480 break;
14484 done:
14485 if (worktree)
14486 got_worktree_close(worktree);
14487 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14488 free(cwd);
14489 free(id_str);
14490 free(uuidstr);
14491 return error;