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 "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.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>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_import(void);
99 __dead static void usage_clone(void);
100 __dead static void usage_fetch(void);
101 __dead static void usage_checkout(void);
102 __dead static void usage_update(void);
103 __dead static void usage_log(void);
104 __dead static void usage_diff(void);
105 __dead static void usage_blame(void);
106 __dead static void usage_tree(void);
107 __dead static void usage_status(void);
108 __dead static void usage_ref(void);
109 __dead static void usage_branch(void);
110 __dead static void usage_tag(void);
111 __dead static void usage_add(void);
112 __dead static void usage_remove(void);
113 __dead static void usage_patch(void);
114 __dead static void usage_revert(void);
115 __dead static void usage_commit(void);
116 __dead static void usage_send(void);
117 __dead static void usage_cherrypick(void);
118 __dead static void usage_backout(void);
119 __dead static void usage_rebase(void);
120 __dead static void usage_histedit(void);
121 __dead static void usage_integrate(void);
122 __dead static void usage_merge(void);
123 __dead static void usage_stage(void);
124 __dead static void usage_unstage(void);
125 __dead static void usage_cat(void);
126 __dead static void usage_info(void);
128 static const struct got_error* cmd_import(int, char *[]);
129 static const struct got_error* cmd_clone(int, char *[]);
130 static const struct got_error* cmd_fetch(int, char *[]);
131 static const struct got_error* cmd_checkout(int, char *[]);
132 static const struct got_error* cmd_update(int, char *[]);
133 static const struct got_error* cmd_log(int, char *[]);
134 static const struct got_error* cmd_diff(int, char *[]);
135 static const struct got_error* cmd_blame(int, char *[]);
136 static const struct got_error* cmd_tree(int, char *[]);
137 static const struct got_error* cmd_status(int, char *[]);
138 static const struct got_error* cmd_ref(int, char *[]);
139 static const struct got_error* cmd_branch(int, char *[]);
140 static const struct got_error* cmd_tag(int, char *[]);
141 static const struct got_error* cmd_add(int, char *[]);
142 static const struct got_error* cmd_remove(int, char *[]);
143 static const struct got_error* cmd_patch(int, char *[]);
144 static const struct got_error* cmd_revert(int, char *[]);
145 static const struct got_error* cmd_commit(int, char *[]);
146 static const struct got_error* cmd_send(int, char *[]);
147 static const struct got_error* cmd_cherrypick(int, char *[]);
148 static const struct got_error* cmd_backout(int, char *[]);
149 static const struct got_error* cmd_rebase(int, char *[]);
150 static const struct got_error* cmd_histedit(int, char *[]);
151 static const struct got_error* cmd_integrate(int, char *[]);
152 static const struct got_error* cmd_merge(int, char *[]);
153 static const struct got_error* cmd_stage(int, char *[]);
154 static const struct got_error* cmd_unstage(int, char *[]);
155 static const struct got_error* cmd_cat(int, char *[]);
156 static const struct got_error* cmd_info(int, char *[]);
158 static const struct got_cmd got_commands[] = {
159 { "import", cmd_import, usage_import, "im" },
160 { "clone", cmd_clone, usage_clone, "cl" },
161 { "fetch", cmd_fetch, usage_fetch, "fe" },
162 { "checkout", cmd_checkout, usage_checkout, "co" },
163 { "update", cmd_update, usage_update, "up" },
164 { "log", cmd_log, usage_log, "" },
165 { "diff", cmd_diff, usage_diff, "di" },
166 { "blame", cmd_blame, usage_blame, "bl" },
167 { "tree", cmd_tree, usage_tree, "tr" },
168 { "status", cmd_status, usage_status, "st" },
169 { "ref", cmd_ref, usage_ref, "" },
170 { "branch", cmd_branch, usage_branch, "br" },
171 { "tag", cmd_tag, usage_tag, "" },
172 { "add", cmd_add, usage_add, "" },
173 { "remove", cmd_remove, usage_remove, "rm" },
174 { "patch", cmd_patch, usage_patch, "pa" },
175 { "revert", cmd_revert, usage_revert, "rv" },
176 { "commit", cmd_commit, usage_commit, "ci" },
177 { "send", cmd_send, usage_send, "se" },
178 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
179 { "backout", cmd_backout, usage_backout, "bo" },
180 { "rebase", cmd_rebase, usage_rebase, "rb" },
181 { "histedit", cmd_histedit, usage_histedit, "he" },
182 { "integrate", cmd_integrate, usage_integrate,"ig" },
183 { "merge", cmd_merge, usage_merge, "mg" },
184 { "stage", cmd_stage, usage_stage, "sg" },
185 { "unstage", cmd_unstage, usage_unstage, "ug" },
186 { "cat", cmd_cat, usage_cat, "" },
187 { "info", cmd_info, usage_info, "" },
188 };
190 static void
191 list_commands(FILE *fp)
193 size_t i;
195 fprintf(fp, "commands:");
196 for (i = 0; i < nitems(got_commands); i++) {
197 const struct got_cmd *cmd = &got_commands[i];
198 fprintf(fp, " %s", cmd->cmd_name);
200 fputc('\n', fp);
203 __dead static void
204 option_conflict(char a, char b)
206 errx(1, "-%c and -%c options are mutually exclusive", a, b);
209 int
210 main(int argc, char *argv[])
212 const struct got_cmd *cmd;
213 size_t i;
214 int ch;
215 int hflag = 0, Vflag = 0;
216 static const struct option longopts[] = {
217 { "version", no_argument, NULL, 'V' },
218 { NULL, 0, NULL, 0 }
219 };
221 setlocale(LC_CTYPE, "");
223 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
224 switch (ch) {
225 case 'h':
226 hflag = 1;
227 break;
228 case 'V':
229 Vflag = 1;
230 break;
231 default:
232 usage(hflag, 1);
233 /* NOTREACHED */
237 argc -= optind;
238 argv += optind;
239 optind = 1;
240 optreset = 1;
242 if (Vflag) {
243 got_version_print_str();
244 return 0;
247 if (argc <= 0)
248 usage(hflag, hflag ? 0 : 1);
250 signal(SIGINT, catch_sigint);
251 signal(SIGPIPE, catch_sigpipe);
253 for (i = 0; i < nitems(got_commands); i++) {
254 const struct got_error *error;
256 cmd = &got_commands[i];
258 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
259 strcmp(cmd->cmd_alias, argv[0]) != 0)
260 continue;
262 if (hflag)
263 cmd->cmd_usage();
265 error = cmd->cmd_main(argc, argv);
266 if (error && error->code != GOT_ERR_CANCELLED &&
267 error->code != GOT_ERR_PRIVSEP_EXIT &&
268 !(sigpipe_received &&
269 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
270 !(sigint_received &&
271 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
272 fflush(stdout);
273 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
274 return 1;
277 return 0;
280 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
281 list_commands(stderr);
282 return 1;
285 __dead static void
286 usage(int hflag, int status)
288 FILE *fp = (status == 0) ? stdout : stderr;
290 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
291 getprogname());
292 if (hflag)
293 list_commands(fp);
294 exit(status);
297 static const struct got_error *
298 get_editor(char **abspath)
300 const struct got_error *err = NULL;
301 const char *editor;
303 *abspath = NULL;
305 editor = getenv("VISUAL");
306 if (editor == NULL)
307 editor = getenv("EDITOR");
309 if (editor) {
310 err = got_path_find_prog(abspath, editor);
311 if (err)
312 return err;
315 if (*abspath == NULL) {
316 *abspath = strdup(GOT_DEFAULT_EDITOR);
317 if (*abspath == NULL)
318 return got_error_from_errno("strdup");
321 return NULL;
324 static const struct got_error *
325 apply_unveil(const char *repo_path, int repo_read_only,
326 const char *worktree_path)
328 const struct got_error *err;
330 #ifdef PROFILE
331 if (unveil("gmon.out", "rwc") != 0)
332 return got_error_from_errno2("unveil", "gmon.out");
333 #endif
334 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
335 return got_error_from_errno2("unveil", repo_path);
337 if (worktree_path && unveil(worktree_path, "rwc") != 0)
338 return got_error_from_errno2("unveil", worktree_path);
340 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
341 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
343 err = got_privsep_unveil_exec_helpers();
344 if (err != NULL)
345 return err;
347 if (unveil(NULL, NULL) != 0)
348 return got_error_from_errno("unveil");
350 return NULL;
353 __dead static void
354 usage_import(void)
356 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
357 "[-r repository-path] directory\n", getprogname());
358 exit(1);
361 static int
362 spawn_editor(const char *editor, const char *file)
364 pid_t pid;
365 sig_t sighup, sigint, sigquit;
366 int st = -1;
368 sighup = signal(SIGHUP, SIG_IGN);
369 sigint = signal(SIGINT, SIG_IGN);
370 sigquit = signal(SIGQUIT, SIG_IGN);
372 switch (pid = fork()) {
373 case -1:
374 goto doneediting;
375 case 0:
376 execl(editor, editor, file, (char *)NULL);
377 _exit(127);
380 while (waitpid(pid, &st, 0) == -1)
381 if (errno != EINTR)
382 break;
384 doneediting:
385 (void)signal(SIGHUP, sighup);
386 (void)signal(SIGINT, sigint);
387 (void)signal(SIGQUIT, sigquit);
389 if (!WIFEXITED(st)) {
390 errno = EINTR;
391 return -1;
394 return WEXITSTATUS(st);
397 static const struct got_error *
398 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
400 const struct got_error *err = NULL;
401 char *line = NULL;
402 size_t linesize = 0;
404 *logmsg = NULL;
405 *len = 0;
407 if (fseeko(fp, 0L, SEEK_SET) == -1)
408 return got_error_from_errno("fseeko");
410 *logmsg = malloc(filesize + 1);
411 if (*logmsg == NULL)
412 return got_error_from_errno("malloc");
413 (*logmsg)[0] = '\0';
415 while (getline(&line, &linesize, fp) != -1) {
416 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
417 continue; /* remove comments and leading empty lines */
418 *len = strlcat(*logmsg, line, filesize + 1);
419 if (*len >= filesize + 1) {
420 err = got_error(GOT_ERR_NO_SPACE);
421 goto done;
424 if (ferror(fp)) {
425 err = got_ferror(fp, GOT_ERR_IO);
426 goto done;
429 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
430 (*logmsg)[*len - 1] = '\0';
431 (*len)--;
433 done:
434 free(line);
435 if (err) {
436 free(*logmsg);
437 *logmsg = NULL;
438 *len = 0;
440 return err;
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 struct stat st, st2;
450 FILE *fp = NULL;
451 size_t logmsg_len;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (require_modification) {
462 struct timespec timeout;
464 timeout.tv_sec = 0;
465 timeout.tv_nsec = 1;
466 nanosleep(&timeout, NULL);
469 if (stat(logmsg_path, &st2) == -1)
470 return got_error_from_errno2("stat", logmsg_path);
472 if (require_modification && st.st_size == st2.st_size &&
473 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
474 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
475 "no changes made to commit message, aborting");
477 fp = fopen(logmsg_path, "re");
478 if (fp == NULL) {
479 err = got_error_from_errno("fopen");
480 goto done;
483 /* strip comments and leading/trailing newlines */
484 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
485 if (err)
486 goto done;
487 if (logmsg_len == 0) {
488 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
489 "commit message cannot be empty, aborting");
490 goto done;
492 done:
493 if (fp && fclose(fp) == EOF && err == NULL)
494 err = got_error_from_errno("fclose");
495 if (err) {
496 free(*logmsg);
497 *logmsg = NULL;
499 return err;
502 static const struct got_error *
503 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
504 const char *path_dir, const char *branch_name)
506 char *initial_content = NULL;
507 const struct got_error *err = NULL;
508 int initial_content_len;
509 int fd = -1;
511 initial_content_len = asprintf(&initial_content,
512 "\n# %s to be imported to branch %s\n", path_dir,
513 branch_name);
514 if (initial_content_len == -1)
515 return got_error_from_errno("asprintf");
517 err = got_opentemp_named_fd(logmsg_path, &fd,
518 GOT_TMPDIR_STR "/got-importmsg", "");
519 if (err)
520 goto done;
522 if (write(fd, initial_content, initial_content_len) == -1) {
523 err = got_error_from_errno2("write", *logmsg_path);
524 goto done;
526 if (close(fd) == -1) {
527 err = got_error_from_errno2("close", *logmsg_path);
528 goto done;
530 fd = -1;
532 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
533 initial_content_len, 1);
534 done:
535 if (fd != -1 && close(fd) == -1 && err == NULL)
536 err = got_error_from_errno2("close", *logmsg_path);
537 free(initial_content);
538 if (err) {
539 free(*logmsg_path);
540 *logmsg_path = NULL;
542 return err;
545 static const struct got_error *
546 import_progress(void *arg, const char *path)
548 printf("A %s\n", path);
549 return NULL;
552 static const struct got_error *
553 valid_author(const char *author)
555 const char *email = author;
557 /*
558 * Git' expects the author (or committer) to be in the form
559 * "name <email>", which are mostly free form (see the
560 * "committer" description in git-fast-import(1)). We're only
561 * doing this to avoid git's object parser breaking on commits
562 * we create.
563 */
565 while (*author && *author != '\n' && *author != '<' && *author != '>')
566 author++;
567 if (author != email && *author == '<' && *(author - 1) != ' ')
568 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
569 "between author name and email required", email);
570 if (*author++ != '<')
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 while (*author && *author != '\n' && *author != '<' && *author != '>')
573 author++;
574 if (strcmp(author, ">") != 0)
575 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
576 return NULL;
579 static const struct got_error *
580 get_author(char **author, struct got_repository *repo,
581 struct got_worktree *worktree)
583 const struct got_error *err = NULL;
584 const char *got_author = NULL, *name, *email;
585 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
587 *author = NULL;
589 if (worktree)
590 worktree_conf = got_worktree_get_gotconfig(worktree);
591 repo_conf = got_repo_get_gotconfig(repo);
593 /*
594 * Priority of potential author information sources, from most
595 * significant to least significant:
596 * 1) work tree's .got/got.conf file
597 * 2) repository's got.conf file
598 * 3) repository's git config file
599 * 4) environment variables
600 * 5) global git config files (in user's home directory or /etc)
601 */
603 if (worktree_conf)
604 got_author = got_gotconfig_get_author(worktree_conf);
605 if (got_author == NULL)
606 got_author = got_gotconfig_get_author(repo_conf);
607 if (got_author == NULL) {
608 name = got_repo_get_gitconfig_author_name(repo);
609 email = got_repo_get_gitconfig_author_email(repo);
610 if (name && email) {
611 if (asprintf(author, "%s <%s>", name, email) == -1)
612 return got_error_from_errno("asprintf");
613 return NULL;
616 got_author = getenv("GOT_AUTHOR");
617 if (got_author == NULL) {
618 name = got_repo_get_global_gitconfig_author_name(repo);
619 email = got_repo_get_global_gitconfig_author_email(
620 repo);
621 if (name && email) {
622 if (asprintf(author, "%s <%s>", name, email)
623 == -1)
624 return got_error_from_errno("asprintf");
625 return NULL;
627 /* TODO: Look up user in password database? */
628 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
632 *author = strdup(got_author);
633 if (*author == NULL)
634 return got_error_from_errno("strdup");
636 err = valid_author(*author);
637 if (err) {
638 free(*author);
639 *author = NULL;
641 return err;
644 static const struct got_error *
645 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
646 struct got_worktree *worktree)
648 const char *got_allowed_signers = NULL;
649 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
651 *allowed_signers = NULL;
653 if (worktree)
654 worktree_conf = got_worktree_get_gotconfig(worktree);
655 repo_conf = got_repo_get_gotconfig(repo);
657 /*
658 * Priority of potential author information sources, from most
659 * significant to least significant:
660 * 1) work tree's .got/got.conf file
661 * 2) repository's got.conf file
662 */
664 if (worktree_conf)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 worktree_conf);
667 if (got_allowed_signers == NULL)
668 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
669 repo_conf);
671 if (got_allowed_signers) {
672 *allowed_signers = strdup(got_allowed_signers);
673 if (*allowed_signers == NULL)
674 return got_error_from_errno("strdup");
676 return NULL;
679 static const struct got_error *
680 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
681 struct got_worktree *worktree)
683 const char *got_revoked_signers = NULL;
684 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
686 *revoked_signers = NULL;
688 if (worktree)
689 worktree_conf = got_worktree_get_gotconfig(worktree);
690 repo_conf = got_repo_get_gotconfig(repo);
692 /*
693 * Priority of potential author information sources, from most
694 * significant to least significant:
695 * 1) work tree's .got/got.conf file
696 * 2) repository's got.conf file
697 */
699 if (worktree_conf)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 worktree_conf);
702 if (got_revoked_signers == NULL)
703 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
704 repo_conf);
706 if (got_revoked_signers) {
707 *revoked_signers = strdup(got_revoked_signers);
708 if (*revoked_signers == NULL)
709 return got_error_from_errno("strdup");
711 return NULL;
714 static const char *
715 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
717 const char *got_signer_id = NULL;
718 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
720 if (worktree)
721 worktree_conf = got_worktree_get_gotconfig(worktree);
722 repo_conf = got_repo_get_gotconfig(repo);
724 /*
725 * Priority of potential author information sources, from most
726 * significant to least significant:
727 * 1) work tree's .got/got.conf file
728 * 2) repository's got.conf file
729 */
731 if (worktree_conf)
732 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
733 if (got_signer_id == NULL)
734 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
736 return got_signer_id;
739 static const struct got_error *
740 get_gitconfig_path(char **gitconfig_path)
742 const char *homedir = getenv("HOME");
744 *gitconfig_path = NULL;
745 if (homedir) {
746 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
747 return got_error_from_errno("asprintf");
750 return NULL;
753 static const struct got_error *
754 cmd_import(int argc, char *argv[])
756 const struct got_error *error = NULL;
757 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
758 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
759 const char *branch_name = NULL;
760 char *id_str = NULL, *logmsg_path = NULL;
761 char refname[PATH_MAX] = "refs/heads/";
762 struct got_repository *repo = NULL;
763 struct got_reference *branch_ref = NULL, *head_ref = NULL;
764 struct got_object_id *new_commit_id = NULL;
765 int ch, n = 0;
766 struct got_pathlist_head ignores;
767 struct got_pathlist_entry *pe;
768 int preserve_logmsg = 0;
769 int *pack_fds = NULL;
771 TAILQ_INIT(&ignores);
773 #ifndef PROFILE
774 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
775 "unveil",
776 NULL) == -1)
777 err(1, "pledge");
778 #endif
780 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
781 switch (ch) {
782 case 'b':
783 branch_name = optarg;
784 break;
785 case 'I':
786 if (optarg[0] == '\0')
787 break;
788 error = got_pathlist_insert(&pe, &ignores, optarg,
789 NULL);
790 if (error)
791 goto done;
792 break;
793 case 'm':
794 logmsg = strdup(optarg);
795 if (logmsg == NULL) {
796 error = got_error_from_errno("strdup");
797 goto done;
799 break;
800 case 'r':
801 repo_path = realpath(optarg, NULL);
802 if (repo_path == NULL) {
803 error = got_error_from_errno2("realpath",
804 optarg);
805 goto done;
807 break;
808 default:
809 usage_import();
810 /* NOTREACHED */
814 argc -= optind;
815 argv += optind;
817 if (argc != 1)
818 usage_import();
820 if (repo_path == NULL) {
821 repo_path = getcwd(NULL, 0);
822 if (repo_path == NULL)
823 return got_error_from_errno("getcwd");
825 got_path_strip_trailing_slashes(repo_path);
826 error = get_gitconfig_path(&gitconfig_path);
827 if (error)
828 goto done;
829 error = got_repo_pack_fds_open(&pack_fds);
830 if (error != NULL)
831 goto done;
832 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
833 if (error)
834 goto done;
836 error = get_author(&author, repo, NULL);
837 if (error)
838 return error;
840 /*
841 * Don't let the user create a branch name with a leading '-'.
842 * While technically a valid reference name, this case is usually
843 * an unintended typo.
844 */
845 if (branch_name && branch_name[0] == '-')
846 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
848 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
849 if (error && error->code != GOT_ERR_NOT_REF)
850 goto done;
852 if (branch_name)
853 n = strlcat(refname, branch_name, sizeof(refname));
854 else if (head_ref && got_ref_is_symbolic(head_ref))
855 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
856 sizeof(refname));
857 else
858 n = strlcat(refname, "main", sizeof(refname));
859 if (n >= sizeof(refname)) {
860 error = got_error(GOT_ERR_NO_SPACE);
861 goto done;
864 error = got_ref_open(&branch_ref, repo, refname, 0);
865 if (error) {
866 if (error->code != GOT_ERR_NOT_REF)
867 goto done;
868 } else {
869 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
870 "import target branch already exists");
871 goto done;
874 path_dir = realpath(argv[0], NULL);
875 if (path_dir == NULL) {
876 error = got_error_from_errno2("realpath", argv[0]);
877 goto done;
879 got_path_strip_trailing_slashes(path_dir);
881 /*
882 * unveil(2) traverses exec(2); if an editor is used we have
883 * to apply unveil after the log message has been written.
884 */
885 if (logmsg == NULL || *logmsg == '\0') {
886 error = get_editor(&editor);
887 if (error)
888 goto done;
889 free(logmsg);
890 error = collect_import_msg(&logmsg, &logmsg_path, editor,
891 path_dir, refname);
892 if (error) {
893 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
894 logmsg_path != NULL)
895 preserve_logmsg = 1;
896 goto done;
900 if (unveil(path_dir, "r") != 0) {
901 error = got_error_from_errno2("unveil", path_dir);
902 if (logmsg_path)
903 preserve_logmsg = 1;
904 goto done;
907 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
908 if (error) {
909 if (logmsg_path)
910 preserve_logmsg = 1;
911 goto done;
914 error = got_repo_import(&new_commit_id, path_dir, logmsg,
915 author, &ignores, repo, import_progress, NULL);
916 if (error) {
917 if (logmsg_path)
918 preserve_logmsg = 1;
919 goto done;
922 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
923 if (error) {
924 if (logmsg_path)
925 preserve_logmsg = 1;
926 goto done;
929 error = got_ref_write(branch_ref, repo);
930 if (error) {
931 if (logmsg_path)
932 preserve_logmsg = 1;
933 goto done;
936 error = got_object_id_str(&id_str, new_commit_id);
937 if (error) {
938 if (logmsg_path)
939 preserve_logmsg = 1;
940 goto done;
943 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
944 if (error) {
945 if (error->code != GOT_ERR_NOT_REF) {
946 if (logmsg_path)
947 preserve_logmsg = 1;
948 goto done;
951 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
952 branch_ref);
953 if (error) {
954 if (logmsg_path)
955 preserve_logmsg = 1;
956 goto done;
959 error = got_ref_write(head_ref, repo);
960 if (error) {
961 if (logmsg_path)
962 preserve_logmsg = 1;
963 goto done;
967 printf("Created branch %s with commit %s\n",
968 got_ref_get_name(branch_ref), id_str);
969 done:
970 if (pack_fds) {
971 const struct got_error *pack_err =
972 got_repo_pack_fds_close(pack_fds);
973 if (error == NULL)
974 error = pack_err;
976 if (repo) {
977 const struct got_error *close_err = got_repo_close(repo);
978 if (error == NULL)
979 error = close_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int bflag = 0, list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 bflag = 1;
1582 break;
1583 case 'l':
1584 list_refs_only = 1;
1585 break;
1586 case 'm':
1587 mirror_references = 1;
1588 break;
1589 case 'q':
1590 verbosity = -1;
1591 break;
1592 case 'R':
1593 error = got_pathlist_append(&wanted_refs,
1594 optarg, NULL);
1595 if (error)
1596 return error;
1597 break;
1598 case 'v':
1599 if (verbosity < 0)
1600 verbosity = 0;
1601 else if (verbosity < 3)
1602 verbosity++;
1603 break;
1604 default:
1605 usage_clone();
1606 break;
1609 argc -= optind;
1610 argv += optind;
1612 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1613 option_conflict('a', 'b');
1614 if (list_refs_only) {
1615 if (!TAILQ_EMPTY(&wanted_branches))
1616 option_conflict('l', 'b');
1617 if (fetch_all_branches)
1618 option_conflict('l', 'a');
1619 if (mirror_references)
1620 option_conflict('l', 'm');
1621 if (!TAILQ_EMPTY(&wanted_refs))
1622 option_conflict('l', 'R');
1625 uri = argv[0];
1627 if (argc == 1)
1628 dirname = NULL;
1629 else if (argc == 2)
1630 dirname = argv[1];
1631 else
1632 usage_clone();
1634 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1635 &repo_name, uri);
1636 if (error)
1637 goto done;
1639 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1640 host, port ? ":" : "", port ? port : "",
1641 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1642 error = got_error_from_errno("asprintf");
1643 goto done;
1646 if (strcmp(proto, "git") == 0) {
1647 #ifndef PROFILE
1648 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1649 "sendfd dns inet unveil", NULL) == -1)
1650 err(1, "pledge");
1651 #endif
1652 } else if (strcmp(proto, "git+ssh") == 0 ||
1653 strcmp(proto, "ssh") == 0) {
1654 #ifndef PROFILE
1655 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1656 "sendfd unveil", NULL) == -1)
1657 err(1, "pledge");
1658 #endif
1659 } else if (strcmp(proto, "http") == 0 ||
1660 strcmp(proto, "git+http") == 0) {
1661 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1662 goto done;
1663 } else {
1664 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1665 goto done;
1667 if (dirname == NULL) {
1668 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1669 error = got_error_from_errno("asprintf");
1670 goto done;
1672 repo_path = default_destdir;
1673 } else
1674 repo_path = dirname;
1676 if (!list_refs_only) {
1677 error = got_path_mkdir(repo_path);
1678 if (error &&
1679 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1680 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1681 goto done;
1682 if (!got_path_dir_is_empty(repo_path)) {
1683 error = got_error_path(repo_path,
1684 GOT_ERR_DIR_NOT_EMPTY);
1685 goto done;
1689 error = got_dial_apply_unveil(proto);
1690 if (error)
1691 goto done;
1693 error = apply_unveil(repo_path, 0, NULL);
1694 if (error)
1695 goto done;
1697 if (verbosity >= 0)
1698 printf("Connecting to %s\n", git_url);
1700 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1701 server_path, verbosity);
1702 if (error)
1703 goto done;
1705 if (!list_refs_only) {
1706 error = got_repo_init(repo_path, NULL);
1707 if (error)
1708 goto done;
1709 error = got_repo_pack_fds_open(&pack_fds);
1710 if (error != NULL)
1711 goto done;
1712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1713 if (error)
1714 goto done;
1717 fpa.last_scaled_size[0] = '\0';
1718 fpa.last_p_indexed = -1;
1719 fpa.last_p_resolved = -1;
1720 fpa.verbosity = verbosity;
1721 fpa.create_configs = 1;
1722 fpa.configs_created = 0;
1723 fpa.repo = repo;
1724 fpa.config_info.symrefs = &symrefs;
1725 fpa.config_info.wanted_branches = &wanted_branches;
1726 fpa.config_info.wanted_refs = &wanted_refs;
1727 fpa.config_info.proto = proto;
1728 fpa.config_info.host = host;
1729 fpa.config_info.port = port;
1730 fpa.config_info.remote_repo_path = server_path;
1731 fpa.config_info.git_url = git_url;
1732 fpa.config_info.fetch_all_branches = fetch_all_branches;
1733 fpa.config_info.mirror_references = mirror_references;
1734 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1735 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1736 fetch_all_branches, &wanted_branches, &wanted_refs,
1737 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1738 fetch_progress, &fpa);
1739 if (error)
1740 goto done;
1742 if (list_refs_only) {
1743 error = list_remote_refs(&symrefs, &refs);
1744 goto done;
1747 if (pack_hash == NULL) {
1748 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1749 "server sent an empty pack file");
1750 goto done;
1752 error = got_object_id_str(&id_str, pack_hash);
1753 if (error)
1754 goto done;
1755 if (verbosity >= 0)
1756 printf("\nFetched %s.pack\n", id_str);
1757 free(id_str);
1759 /* Set up references provided with the pack file. */
1760 TAILQ_FOREACH(pe, &refs, entry) {
1761 const char *refname = pe->path;
1762 struct got_object_id *id = pe->data;
1763 char *remote_refname;
1765 if (is_wanted_ref(&wanted_refs, refname) &&
1766 !mirror_references) {
1767 error = create_wanted_ref(refname, id,
1768 GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 verbosity - 1, repo);
1770 if (error)
1771 goto done;
1772 continue;
1775 error = create_ref(refname, id, verbosity - 1, repo);
1776 if (error)
1777 goto done;
1779 if (mirror_references)
1780 continue;
1782 if (strncmp("refs/heads/", refname, 11) != 0)
1783 continue;
1785 if (asprintf(&remote_refname,
1786 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1787 refname + 11) == -1) {
1788 error = got_error_from_errno("asprintf");
1789 goto done;
1791 error = create_ref(remote_refname, id, verbosity - 1, repo);
1792 free(remote_refname);
1793 if (error)
1794 goto done;
1797 /* Set the HEAD reference if the server provided one. */
1798 TAILQ_FOREACH(pe, &symrefs, entry) {
1799 struct got_reference *target_ref;
1800 const char *refname = pe->path;
1801 const char *target = pe->data;
1802 char *remote_refname = NULL, *remote_target = NULL;
1804 if (strcmp(refname, GOT_REF_HEAD) != 0)
1805 continue;
1807 error = got_ref_open(&target_ref, repo, target, 0);
1808 if (error) {
1809 if (error->code == GOT_ERR_NOT_REF) {
1810 error = NULL;
1811 continue;
1813 goto done;
1816 error = create_symref(refname, target_ref, verbosity, repo);
1817 got_ref_close(target_ref);
1818 if (error)
1819 goto done;
1821 if (mirror_references)
1822 continue;
1824 if (strncmp("refs/heads/", target, 11) != 0)
1825 continue;
1827 if (asprintf(&remote_refname,
1828 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1829 refname) == -1) {
1830 error = got_error_from_errno("asprintf");
1831 goto done;
1833 if (asprintf(&remote_target,
1834 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1835 target + 11) == -1) {
1836 error = got_error_from_errno("asprintf");
1837 free(remote_refname);
1838 goto done;
1840 error = got_ref_open(&target_ref, repo, remote_target, 0);
1841 if (error) {
1842 free(remote_refname);
1843 free(remote_target);
1844 if (error->code == GOT_ERR_NOT_REF) {
1845 error = NULL;
1846 continue;
1848 goto done;
1850 error = create_symref(remote_refname, target_ref,
1851 verbosity - 1, repo);
1852 free(remote_refname);
1853 free(remote_target);
1854 got_ref_close(target_ref);
1855 if (error)
1856 goto done;
1858 if (pe == NULL) {
1860 * We failed to set the HEAD reference. If we asked for
1861 * a set of wanted branches use the first of one of those
1862 * which could be fetched instead.
1864 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1865 const char *target = pe->path;
1866 struct got_reference *target_ref;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(GOT_REF_HEAD, target_ref,
1878 verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1882 break;
1885 if (!fpa.configs_created && pe != NULL) {
1886 error = create_config_files(fpa.config_info.proto,
1887 fpa.config_info.host, fpa.config_info.port,
1888 fpa.config_info.remote_repo_path,
1889 fpa.config_info.git_url,
1890 fpa.config_info.fetch_all_branches,
1891 fpa.config_info.mirror_references,
1892 fpa.config_info.symrefs,
1893 fpa.config_info.wanted_branches,
1894 fpa.config_info.wanted_refs, fpa.repo);
1895 if (error)
1896 goto done;
1900 if (verbosity >= 0)
1901 printf("Created %s repository '%s'\n",
1902 mirror_references ? "mirrored" : "cloned", repo_path);
1903 done:
1904 if (pack_fds) {
1905 const struct got_error *pack_err =
1906 got_repo_pack_fds_close(pack_fds);
1907 if (error == NULL)
1908 error = pack_err;
1910 if (fetchpid > 0) {
1911 if (kill(fetchpid, SIGTERM) == -1)
1912 error = got_error_from_errno("kill");
1913 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1914 error = got_error_from_errno("waitpid");
1916 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1917 error = got_error_from_errno("close");
1918 if (repo) {
1919 const struct got_error *close_err = got_repo_close(repo);
1920 if (error == NULL)
1921 error = close_err;
1923 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1924 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1925 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1926 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1927 free(pack_hash);
1928 free(proto);
1929 free(host);
1930 free(port);
1931 free(server_path);
1932 free(repo_name);
1933 free(default_destdir);
1934 free(git_url);
1935 return error;
1938 static const struct got_error *
1939 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1940 int replace_tags, int verbosity, struct got_repository *repo)
1942 const struct got_error *err = NULL;
1943 char *new_id_str = NULL;
1944 struct got_object_id *old_id = NULL;
1946 err = got_object_id_str(&new_id_str, new_id);
1947 if (err)
1948 goto done;
1950 if (!replace_tags &&
1951 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1952 err = got_ref_resolve(&old_id, repo, ref);
1953 if (err)
1954 goto done;
1955 if (got_object_id_cmp(old_id, new_id) == 0)
1956 goto done;
1957 if (verbosity >= 0) {
1958 printf("Rejecting update of existing tag %s: %s\n",
1959 got_ref_get_name(ref), new_id_str);
1961 goto done;
1964 if (got_ref_is_symbolic(ref)) {
1965 if (verbosity >= 0) {
1966 printf("Replacing reference %s: %s\n",
1967 got_ref_get_name(ref),
1968 got_ref_get_symref_target(ref));
1970 err = got_ref_change_symref_to_ref(ref, new_id);
1971 if (err)
1972 goto done;
1973 err = got_ref_write(ref, repo);
1974 if (err)
1975 goto done;
1976 } else {
1977 err = got_ref_resolve(&old_id, repo, ref);
1978 if (err)
1979 goto done;
1980 if (got_object_id_cmp(old_id, new_id) == 0)
1981 goto done;
1983 err = got_ref_change_ref(ref, new_id);
1984 if (err)
1985 goto done;
1986 err = got_ref_write(ref, repo);
1987 if (err)
1988 goto done;
1991 if (verbosity >= 0)
1992 printf("Updated %s: %s\n", got_ref_get_name(ref),
1993 new_id_str);
1994 done:
1995 free(old_id);
1996 free(new_id_str);
1997 return err;
2000 static const struct got_error *
2001 update_symref(const char *refname, struct got_reference *target_ref,
2002 int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL, *unlock_err;
2005 struct got_reference *symref;
2006 int symref_is_locked = 0;
2008 err = got_ref_open(&symref, repo, refname, 1);
2009 if (err) {
2010 if (err->code != GOT_ERR_NOT_REF)
2011 return err;
2012 err = got_ref_alloc_symref(&symref, refname, target_ref);
2013 if (err)
2014 goto done;
2016 err = got_ref_write(symref, repo);
2017 if (err)
2018 goto done;
2020 if (verbosity >= 0)
2021 printf("Created reference %s: %s\n",
2022 got_ref_get_name(symref),
2023 got_ref_get_symref_target(symref));
2024 } else {
2025 symref_is_locked = 1;
2027 if (strcmp(got_ref_get_symref_target(symref),
2028 got_ref_get_name(target_ref)) == 0)
2029 goto done;
2031 err = got_ref_change_symref(symref,
2032 got_ref_get_name(target_ref));
2033 if (err)
2034 goto done;
2036 err = got_ref_write(symref, repo);
2037 if (err)
2038 goto done;
2040 if (verbosity >= 0)
2041 printf("Updated %s: %s\n", got_ref_get_name(symref),
2042 got_ref_get_symref_target(symref));
2045 done:
2046 if (symref_is_locked) {
2047 unlock_err = got_ref_unlock(symref);
2048 if (unlock_err && err == NULL)
2049 err = unlock_err;
2051 got_ref_close(symref);
2052 return err;
2055 __dead static void
2056 usage_fetch(void)
2058 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2059 "[-R reference] [-r repository-path] [remote-repository]\n",
2060 getprogname());
2061 exit(1);
2064 static const struct got_error *
2065 delete_missing_ref(struct got_reference *ref,
2066 int verbosity, struct got_repository *repo)
2068 const struct got_error *err = NULL;
2069 struct got_object_id *id = NULL;
2070 char *id_str = NULL;
2072 if (got_ref_is_symbolic(ref)) {
2073 err = got_ref_delete(ref, repo);
2074 if (err)
2075 return err;
2076 if (verbosity >= 0) {
2077 printf("Deleted %s: %s\n",
2078 got_ref_get_name(ref),
2079 got_ref_get_symref_target(ref));
2081 } else {
2082 err = got_ref_resolve(&id, repo, ref);
2083 if (err)
2084 return err;
2085 err = got_object_id_str(&id_str, id);
2086 if (err)
2087 goto done;
2089 err = got_ref_delete(ref, repo);
2090 if (err)
2091 goto done;
2092 if (verbosity >= 0) {
2093 printf("Deleted %s: %s\n",
2094 got_ref_get_name(ref), id_str);
2097 done:
2098 free(id);
2099 free(id_str);
2100 return err;
2103 static const struct got_error *
2104 delete_missing_refs(struct got_pathlist_head *their_refs,
2105 struct got_pathlist_head *their_symrefs,
2106 const struct got_remote_repo *remote,
2107 int verbosity, struct got_repository *repo)
2109 const struct got_error *err = NULL, *unlock_err;
2110 struct got_reflist_head my_refs;
2111 struct got_reflist_entry *re;
2112 struct got_pathlist_entry *pe;
2113 char *remote_namespace = NULL;
2114 char *local_refname = NULL;
2116 TAILQ_INIT(&my_refs);
2118 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2119 == -1)
2120 return got_error_from_errno("asprintf");
2122 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2123 if (err)
2124 goto done;
2126 TAILQ_FOREACH(re, &my_refs, entry) {
2127 const char *refname = got_ref_get_name(re->ref);
2128 const char *their_refname;
2130 if (remote->mirror_references) {
2131 their_refname = refname;
2132 } else {
2133 if (strncmp(refname, remote_namespace,
2134 strlen(remote_namespace)) == 0) {
2135 if (strcmp(refname + strlen(remote_namespace),
2136 GOT_REF_HEAD) == 0)
2137 continue;
2138 if (asprintf(&local_refname, "refs/heads/%s",
2139 refname + strlen(remote_namespace)) == -1) {
2140 err = got_error_from_errno("asprintf");
2141 goto done;
2143 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2144 continue;
2146 their_refname = local_refname;
2149 TAILQ_FOREACH(pe, their_refs, entry) {
2150 if (strcmp(their_refname, pe->path) == 0)
2151 break;
2153 if (pe != NULL)
2154 continue;
2156 TAILQ_FOREACH(pe, their_symrefs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 err = delete_missing_ref(re->ref, verbosity, repo);
2164 if (err)
2165 break;
2167 if (local_refname) {
2168 struct got_reference *ref;
2169 err = got_ref_open(&ref, repo, local_refname, 1);
2170 if (err) {
2171 if (err->code != GOT_ERR_NOT_REF)
2172 break;
2173 free(local_refname);
2174 local_refname = NULL;
2175 continue;
2177 err = delete_missing_ref(ref, verbosity, repo);
2178 if (err)
2179 break;
2180 unlock_err = got_ref_unlock(ref);
2181 got_ref_close(ref);
2182 if (unlock_err && err == NULL) {
2183 err = unlock_err;
2184 break;
2187 free(local_refname);
2188 local_refname = NULL;
2191 done:
2192 got_ref_list_free(&my_refs);
2193 free(remote_namespace);
2194 free(local_refname);
2195 return err;
2198 static const struct got_error *
2199 update_wanted_ref(const char *refname, struct got_object_id *id,
2200 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2202 const struct got_error *err, *unlock_err;
2203 char *remote_refname;
2204 struct got_reference *ref;
2206 if (strncmp("refs/", refname, 5) == 0)
2207 refname += 5;
2209 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2210 remote_repo_name, refname) == -1)
2211 return got_error_from_errno("asprintf");
2213 err = got_ref_open(&ref, repo, remote_refname, 1);
2214 if (err) {
2215 if (err->code != GOT_ERR_NOT_REF)
2216 goto done;
2217 err = create_ref(remote_refname, id, verbosity, repo);
2218 } else {
2219 err = update_ref(ref, id, 0, verbosity, repo);
2220 unlock_err = got_ref_unlock(ref);
2221 if (unlock_err && err == NULL)
2222 err = unlock_err;
2223 got_ref_close(ref);
2225 done:
2226 free(remote_refname);
2227 return err;
2230 static const struct got_error *
2231 delete_ref(struct got_repository *repo, struct got_reference *ref)
2233 const struct got_error *err = NULL;
2234 struct got_object_id *id = NULL;
2235 char *id_str = NULL;
2236 const char *target;
2238 if (got_ref_is_symbolic(ref)) {
2239 target = got_ref_get_symref_target(ref);
2240 } else {
2241 err = got_ref_resolve(&id, repo, ref);
2242 if (err)
2243 goto done;
2244 err = got_object_id_str(&id_str, id);
2245 if (err)
2246 goto done;
2247 target = id_str;
2250 err = got_ref_delete(ref, repo);
2251 if (err)
2252 goto done;
2254 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2255 done:
2256 free(id);
2257 free(id_str);
2258 return err;
2261 static const struct got_error *
2262 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2264 const struct got_error *err = NULL;
2265 struct got_reflist_head refs;
2266 struct got_reflist_entry *re;
2267 char *prefix;
2269 TAILQ_INIT(&refs);
2271 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2272 err = got_error_from_errno("asprintf");
2273 goto done;
2275 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2276 if (err)
2277 goto done;
2279 TAILQ_FOREACH(re, &refs, entry)
2280 delete_ref(repo, re->ref);
2281 done:
2282 got_ref_list_free(&refs);
2283 return err;
2286 static const struct got_error *
2287 cmd_fetch(int argc, char *argv[])
2289 const struct got_error *error = NULL, *unlock_err;
2290 char *cwd = NULL, *repo_path = NULL;
2291 const char *remote_name;
2292 char *proto = NULL, *host = NULL, *port = NULL;
2293 char *repo_name = NULL, *server_path = NULL;
2294 const struct got_remote_repo *remotes;
2295 struct got_remote_repo *remote = NULL;
2296 int nremotes;
2297 char *id_str = NULL;
2298 struct got_repository *repo = NULL;
2299 struct got_worktree *worktree = NULL;
2300 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2301 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2302 char *head_refname = NULL;
2303 struct got_pathlist_entry *pe;
2304 struct got_reflist_head remote_refs;
2305 struct got_reflist_entry *re;
2306 struct got_object_id *pack_hash = NULL;
2307 int i, ch, fetchfd = -1, fetchstatus;
2308 pid_t fetchpid = -1;
2309 struct got_fetch_progress_arg fpa;
2310 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2311 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2312 int *pack_fds = NULL, have_bflag = 0;
2313 const char *remote_head = NULL, *worktree_branch = NULL;
2315 TAILQ_INIT(&refs);
2316 TAILQ_INIT(&symrefs);
2317 TAILQ_INIT(&remote_refs);
2318 TAILQ_INIT(&wanted_branches);
2319 TAILQ_INIT(&wanted_refs);
2321 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2322 switch (ch) {
2323 case 'a':
2324 fetch_all_branches = 1;
2325 break;
2326 case 'b':
2327 error = got_pathlist_append(&wanted_branches,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 have_bflag = 1;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 error = got_repo_remote_repo_dup(&remote,
2458 &remotes[i]);
2459 if (error)
2460 goto done;
2461 break;
2466 if (remote == NULL) {
2467 repo_conf = got_repo_get_gotconfig(repo);
2468 if (repo_conf) {
2469 got_gotconfig_get_remotes(&nremotes, &remotes,
2470 repo_conf);
2471 for (i = 0; i < nremotes; i++) {
2472 if (strcmp(remotes[i].name, remote_name) == 0) {
2473 error = got_repo_remote_repo_dup(&remote,
2474 &remotes[i]);
2475 if (error)
2476 goto done;
2477 break;
2482 if (remote == NULL) {
2483 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2484 for (i = 0; i < nremotes; i++) {
2485 if (strcmp(remotes[i].name, remote_name) == 0) {
2486 error = got_repo_remote_repo_dup(&remote,
2487 &remotes[i]);
2488 if (error)
2489 goto done;
2490 break;
2494 if (remote == NULL) {
2495 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2496 goto done;
2499 if (TAILQ_EMPTY(&wanted_branches)) {
2500 if (!fetch_all_branches)
2501 fetch_all_branches = remote->fetch_all_branches;
2502 for (i = 0; i < remote->nfetch_branches; i++) {
2503 error = got_pathlist_append(&wanted_branches,
2504 remote->fetch_branches[i], NULL);
2505 if (error)
2506 goto done;
2509 if (TAILQ_EMPTY(&wanted_refs)) {
2510 for (i = 0; i < remote->nfetch_refs; i++) {
2511 error = got_pathlist_append(&wanted_refs,
2512 remote->fetch_refs[i], NULL);
2513 if (error)
2514 goto done;
2518 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2519 &repo_name, remote->fetch_url);
2520 if (error)
2521 goto done;
2523 if (strcmp(proto, "git") == 0) {
2524 #ifndef PROFILE
2525 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2526 "sendfd dns inet unveil", NULL) == -1)
2527 err(1, "pledge");
2528 #endif
2529 } else if (strcmp(proto, "git+ssh") == 0 ||
2530 strcmp(proto, "ssh") == 0) {
2531 #ifndef PROFILE
2532 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2533 "sendfd unveil", NULL) == -1)
2534 err(1, "pledge");
2535 #endif
2536 } else if (strcmp(proto, "http") == 0 ||
2537 strcmp(proto, "git+http") == 0) {
2538 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2539 goto done;
2540 } else {
2541 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2542 goto done;
2545 error = got_dial_apply_unveil(proto);
2546 if (error)
2547 goto done;
2549 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2550 if (error)
2551 goto done;
2553 if (worktree) {
2554 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2555 if (head_refname == NULL) {
2556 error = got_error_from_errno("strdup");
2557 goto done;
2560 /* Release work tree lock. */
2561 got_worktree_close(worktree);
2562 worktree = NULL;
2565 if (verbosity >= 0) {
2566 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2567 remote->name, proto, host,
2568 port ? ":" : "", port ? port : "",
2569 *server_path == '/' ? "" : "/", server_path);
2572 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2573 server_path, verbosity);
2574 if (error)
2575 goto done;
2577 if (!have_bflag) {
2579 * If set, get this remote's HEAD ref target so
2580 * if it has changed on the server we can fetch it.
2582 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2583 got_ref_cmp_by_name, repo);
2584 if (error)
2585 goto done;
2587 TAILQ_FOREACH(re, &remote_refs, entry) {
2588 const char *remote_refname, *remote_target;
2589 size_t remote_name_len;
2591 if (!got_ref_is_symbolic(re->ref))
2592 continue;
2594 remote_name_len = strlen(remote->name);
2595 remote_refname = got_ref_get_name(re->ref);
2597 /* we only want refs/remotes/$remote->name/HEAD */
2598 if (strncmp(remote_refname + 13, remote->name,
2599 remote_name_len) != 0)
2600 continue;
2602 if (strcmp(remote_refname + remote_name_len + 14,
2603 GOT_REF_HEAD) != 0)
2604 continue;
2607 * Take the name itself because we already
2608 * only match with refs/heads/ in fetch_pack().
2610 remote_target = got_ref_get_symref_target(re->ref);
2611 remote_head = remote_target + remote_name_len + 14;
2612 break;
2615 if (head_refname &&
2616 strncmp(head_refname, "refs/heads/", 11) == 0)
2617 worktree_branch = head_refname;
2620 fpa.last_scaled_size[0] = '\0';
2621 fpa.last_p_indexed = -1;
2622 fpa.last_p_resolved = -1;
2623 fpa.verbosity = verbosity;
2624 fpa.repo = repo;
2625 fpa.create_configs = 0;
2626 fpa.configs_created = 0;
2627 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2629 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2630 remote->mirror_references, fetch_all_branches, &wanted_branches,
2631 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2632 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2633 if (error)
2634 goto done;
2636 if (list_refs_only) {
2637 error = list_remote_refs(&symrefs, &refs);
2638 goto done;
2641 if (pack_hash == NULL) {
2642 if (verbosity >= 0)
2643 printf("Already up-to-date\n");
2644 } else if (verbosity >= 0) {
2645 error = got_object_id_str(&id_str, pack_hash);
2646 if (error)
2647 goto done;
2648 printf("\nFetched %s.pack\n", id_str);
2649 free(id_str);
2650 id_str = NULL;
2653 /* Update references provided with the pack file. */
2654 TAILQ_FOREACH(pe, &refs, entry) {
2655 const char *refname = pe->path;
2656 struct got_object_id *id = pe->data;
2657 struct got_reference *ref;
2658 char *remote_refname;
2660 if (is_wanted_ref(&wanted_refs, refname) &&
2661 !remote->mirror_references) {
2662 error = update_wanted_ref(refname, id,
2663 remote->name, verbosity, repo);
2664 if (error)
2665 goto done;
2666 continue;
2669 if (remote->mirror_references ||
2670 strncmp("refs/tags/", refname, 10) == 0) {
2671 error = got_ref_open(&ref, repo, refname, 1);
2672 if (error) {
2673 if (error->code != GOT_ERR_NOT_REF)
2674 goto done;
2675 error = create_ref(refname, id, verbosity,
2676 repo);
2677 if (error)
2678 goto done;
2679 } else {
2680 error = update_ref(ref, id, replace_tags,
2681 verbosity, repo);
2682 unlock_err = got_ref_unlock(ref);
2683 if (unlock_err && error == NULL)
2684 error = unlock_err;
2685 got_ref_close(ref);
2686 if (error)
2687 goto done;
2689 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2690 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2691 remote_name, refname + 11) == -1) {
2692 error = got_error_from_errno("asprintf");
2693 goto done;
2696 error = got_ref_open(&ref, repo, remote_refname, 1);
2697 if (error) {
2698 if (error->code != GOT_ERR_NOT_REF)
2699 goto done;
2700 error = create_ref(remote_refname, id,
2701 verbosity, repo);
2702 if (error)
2703 goto done;
2704 } else {
2705 error = update_ref(ref, id, replace_tags,
2706 verbosity, repo);
2707 unlock_err = got_ref_unlock(ref);
2708 if (unlock_err && error == NULL)
2709 error = unlock_err;
2710 got_ref_close(ref);
2711 if (error)
2712 goto done;
2715 /* Also create a local branch if none exists yet. */
2716 error = got_ref_open(&ref, repo, refname, 1);
2717 if (error) {
2718 if (error->code != GOT_ERR_NOT_REF)
2719 goto done;
2720 error = create_ref(refname, id, verbosity,
2721 repo);
2722 if (error)
2723 goto done;
2724 } else {
2725 unlock_err = got_ref_unlock(ref);
2726 if (unlock_err && error == NULL)
2727 error = unlock_err;
2728 got_ref_close(ref);
2732 if (delete_refs) {
2733 error = delete_missing_refs(&refs, &symrefs, remote,
2734 verbosity, repo);
2735 if (error)
2736 goto done;
2739 if (!remote->mirror_references) {
2740 /* Update remote HEAD reference if the server provided one. */
2741 TAILQ_FOREACH(pe, &symrefs, entry) {
2742 struct got_reference *target_ref;
2743 const char *refname = pe->path;
2744 const char *target = pe->data;
2745 char *remote_refname = NULL, *remote_target = NULL;
2747 if (strcmp(refname, GOT_REF_HEAD) != 0)
2748 continue;
2750 if (strncmp("refs/heads/", target, 11) != 0)
2751 continue;
2753 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2754 remote->name, refname) == -1) {
2755 error = got_error_from_errno("asprintf");
2756 goto done;
2758 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2759 remote->name, target + 11) == -1) {
2760 error = got_error_from_errno("asprintf");
2761 free(remote_refname);
2762 goto done;
2765 error = got_ref_open(&target_ref, repo, remote_target,
2766 0);
2767 if (error) {
2768 free(remote_refname);
2769 free(remote_target);
2770 if (error->code == GOT_ERR_NOT_REF) {
2771 error = NULL;
2772 continue;
2774 goto done;
2776 error = update_symref(remote_refname, target_ref,
2777 verbosity, repo);
2778 free(remote_refname);
2779 free(remote_target);
2780 got_ref_close(target_ref);
2781 if (error)
2782 goto done;
2785 done:
2786 if (fetchpid > 0) {
2787 if (kill(fetchpid, SIGTERM) == -1)
2788 error = got_error_from_errno("kill");
2789 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2790 error = got_error_from_errno("waitpid");
2792 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2793 error = got_error_from_errno("close");
2794 if (repo) {
2795 const struct got_error *close_err = got_repo_close(repo);
2796 if (error == NULL)
2797 error = close_err;
2799 if (worktree)
2800 got_worktree_close(worktree);
2801 if (pack_fds) {
2802 const struct got_error *pack_err =
2803 got_repo_pack_fds_close(pack_fds);
2804 if (error == NULL)
2805 error = pack_err;
2807 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2808 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2809 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2810 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2811 got_ref_list_free(&remote_refs);
2812 got_repo_free_remote_repo_data(remote);
2813 free(remote);
2814 free(head_refname);
2815 free(id_str);
2816 free(cwd);
2817 free(repo_path);
2818 free(pack_hash);
2819 free(proto);
2820 free(host);
2821 free(port);
2822 free(server_path);
2823 free(repo_name);
2824 return error;
2828 __dead static void
2829 usage_checkout(void)
2831 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2832 "[-p path-prefix] repository-path [work-tree-path]\n",
2833 getprogname());
2834 exit(1);
2837 static void
2838 show_worktree_base_ref_warning(void)
2840 fprintf(stderr, "%s: warning: could not create a reference "
2841 "to the work tree's base commit; the commit could be "
2842 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2843 "repository writable and running 'got update' will prevent this\n",
2844 getprogname());
2847 struct got_checkout_progress_arg {
2848 const char *worktree_path;
2849 int had_base_commit_ref_error;
2850 int verbosity;
2853 static const struct got_error *
2854 checkout_progress(void *arg, unsigned char status, const char *path)
2856 struct got_checkout_progress_arg *a = arg;
2858 /* Base commit bump happens silently. */
2859 if (status == GOT_STATUS_BUMP_BASE)
2860 return NULL;
2862 if (status == GOT_STATUS_BASE_REF_ERR) {
2863 a->had_base_commit_ref_error = 1;
2864 return NULL;
2867 while (path[0] == '/')
2868 path++;
2870 if (a->verbosity >= 0)
2871 printf("%c %s/%s\n", status, a->worktree_path, path);
2873 return NULL;
2876 static const struct got_error *
2877 check_cancelled(void *arg)
2879 if (sigint_received || sigpipe_received)
2880 return got_error(GOT_ERR_CANCELLED);
2881 return NULL;
2884 static const struct got_error *
2885 check_linear_ancestry(struct got_object_id *commit_id,
2886 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2887 struct got_repository *repo)
2889 const struct got_error *err = NULL;
2890 struct got_object_id *yca_id;
2892 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2893 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2894 if (err)
2895 return err;
2897 if (yca_id == NULL)
2898 return got_error(GOT_ERR_ANCESTRY);
2901 * Require a straight line of history between the target commit
2902 * and the work tree's base commit.
2904 * Non-linear situations such as this require a rebase:
2906 * (commit) D F (base_commit)
2907 * \ /
2908 * C E
2909 * \ /
2910 * B (yca)
2911 * |
2912 * A
2914 * 'got update' only handles linear cases:
2915 * Update forwards in time: A (base/yca) - B - C - D (commit)
2916 * Update backwards in time: D (base) - C - B - A (commit/yca)
2918 if (allow_forwards_in_time_only) {
2919 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2920 return got_error(GOT_ERR_ANCESTRY);
2921 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2922 got_object_id_cmp(base_commit_id, yca_id) != 0)
2923 return got_error(GOT_ERR_ANCESTRY);
2925 free(yca_id);
2926 return NULL;
2929 static const struct got_error *
2930 check_same_branch(struct got_object_id *commit_id,
2931 struct got_reference *head_ref, struct got_repository *repo)
2933 const struct got_error *err = NULL;
2934 struct got_commit_graph *graph = NULL;
2935 struct got_object_id *head_commit_id = NULL;
2937 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2938 if (err)
2939 goto done;
2941 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2942 goto done;
2944 err = got_commit_graph_open(&graph, "/", 1);
2945 if (err)
2946 goto done;
2948 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2949 check_cancelled, NULL);
2950 if (err)
2951 goto done;
2953 for (;;) {
2954 struct got_object_id id;
2956 err = got_commit_graph_iter_next(&id, graph, repo,
2957 check_cancelled, NULL);
2958 if (err) {
2959 if (err->code == GOT_ERR_ITER_COMPLETED)
2960 err = got_error(GOT_ERR_ANCESTRY);
2961 break;
2964 if (got_object_id_cmp(&id, commit_id) == 0)
2965 break;
2967 done:
2968 if (graph)
2969 got_commit_graph_close(graph);
2970 free(head_commit_id);
2971 return err;
2974 static const struct got_error *
2975 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2977 static char msg[512];
2978 const char *branch_name;
2980 if (got_ref_is_symbolic(ref))
2981 branch_name = got_ref_get_symref_target(ref);
2982 else
2983 branch_name = got_ref_get_name(ref);
2985 if (strncmp("refs/heads/", branch_name, 11) == 0)
2986 branch_name += 11;
2988 snprintf(msg, sizeof(msg),
2989 "target commit is not contained in branch '%s'; "
2990 "the branch to use must be specified with -b; "
2991 "if necessary a new branch can be created for "
2992 "this commit with 'got branch -c %s BRANCH_NAME'",
2993 branch_name, commit_id_str);
2995 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2998 static const struct got_error *
2999 cmd_checkout(int argc, char *argv[])
3001 const struct got_error *close_err, *error = NULL;
3002 struct got_repository *repo = NULL;
3003 struct got_reference *head_ref = NULL, *ref = NULL;
3004 struct got_worktree *worktree = NULL;
3005 char *repo_path = NULL;
3006 char *worktree_path = NULL;
3007 const char *path_prefix = "";
3008 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3009 char *commit_id_str = NULL, *keyword_idstr = NULL;
3010 struct got_object_id *commit_id = NULL;
3011 char *cwd = NULL;
3012 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3013 struct got_pathlist_head paths;
3014 struct got_checkout_progress_arg cpa;
3015 int *pack_fds = NULL;
3017 TAILQ_INIT(&paths);
3019 #ifndef PROFILE
3020 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3021 "unveil", NULL) == -1)
3022 err(1, "pledge");
3023 #endif
3025 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3026 switch (ch) {
3027 case 'b':
3028 branch_name = optarg;
3029 break;
3030 case 'c':
3031 commit_id_str = strdup(optarg);
3032 if (commit_id_str == NULL)
3033 return got_error_from_errno("strdup");
3034 break;
3035 case 'E':
3036 allow_nonempty = 1;
3037 break;
3038 case 'p':
3039 path_prefix = optarg;
3040 break;
3041 case 'q':
3042 verbosity = -1;
3043 break;
3044 default:
3045 usage_checkout();
3046 /* NOTREACHED */
3050 argc -= optind;
3051 argv += optind;
3053 if (argc == 1) {
3054 char *base, *dotgit;
3055 const char *path;
3056 repo_path = realpath(argv[0], NULL);
3057 if (repo_path == NULL)
3058 return got_error_from_errno2("realpath", argv[0]);
3059 cwd = getcwd(NULL, 0);
3060 if (cwd == NULL) {
3061 error = got_error_from_errno("getcwd");
3062 goto done;
3064 if (path_prefix[0])
3065 path = path_prefix;
3066 else
3067 path = repo_path;
3068 error = got_path_basename(&base, path);
3069 if (error)
3070 goto done;
3071 dotgit = strstr(base, ".git");
3072 if (dotgit)
3073 *dotgit = '\0';
3074 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3075 error = got_error_from_errno("asprintf");
3076 free(base);
3077 goto done;
3079 free(base);
3080 } else if (argc == 2) {
3081 repo_path = realpath(argv[0], NULL);
3082 if (repo_path == NULL) {
3083 error = got_error_from_errno2("realpath", argv[0]);
3084 goto done;
3086 worktree_path = realpath(argv[1], NULL);
3087 if (worktree_path == NULL) {
3088 if (errno != ENOENT) {
3089 error = got_error_from_errno2("realpath",
3090 argv[1]);
3091 goto done;
3093 worktree_path = strdup(argv[1]);
3094 if (worktree_path == NULL) {
3095 error = got_error_from_errno("strdup");
3096 goto done;
3099 } else
3100 usage_checkout();
3102 got_path_strip_trailing_slashes(repo_path);
3103 got_path_strip_trailing_slashes(worktree_path);
3105 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3106 got_path_is_child(repo_path, worktree_path,
3107 strlen(worktree_path))) {
3108 error = got_error_fmt(GOT_ERR_BAD_PATH,
3109 "work tree and repository paths may not overlap: %s",
3110 worktree_path);
3111 goto done;
3114 error = got_repo_pack_fds_open(&pack_fds);
3115 if (error != NULL)
3116 goto done;
3118 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3119 if (error != NULL)
3120 goto done;
3122 /* Pre-create work tree path for unveil(2) */
3123 error = got_path_mkdir(worktree_path);
3124 if (error) {
3125 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3126 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3127 goto done;
3128 if (!allow_nonempty &&
3129 !got_path_dir_is_empty(worktree_path)) {
3130 error = got_error_path(worktree_path,
3131 GOT_ERR_DIR_NOT_EMPTY);
3132 goto done;
3136 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3137 if (error)
3138 goto done;
3140 error = got_ref_open(&head_ref, repo, branch_name, 0);
3141 if (error != NULL)
3142 goto done;
3144 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3145 GOT_WORKTREE_GOT_DIR, repo);
3146 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3147 goto done;
3149 error = got_worktree_open(&worktree, worktree_path,
3150 GOT_WORKTREE_GOT_DIR);
3151 if (error != NULL)
3152 goto done;
3154 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3155 path_prefix);
3156 if (error != NULL)
3157 goto done;
3158 if (!same_path_prefix) {
3159 error = got_error(GOT_ERR_PATH_PREFIX);
3160 goto done;
3163 if (commit_id_str) {
3164 struct got_reflist_head refs;
3165 TAILQ_INIT(&refs);
3166 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3167 NULL);
3168 if (error)
3169 goto done;
3171 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3172 repo, worktree);
3173 if (error != NULL)
3174 goto done;
3175 if (keyword_idstr != NULL) {
3176 free(commit_id_str);
3177 commit_id_str = keyword_idstr;
3180 error = got_repo_match_object_id(&commit_id, NULL,
3181 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3182 got_ref_list_free(&refs);
3183 if (error)
3184 goto done;
3185 error = check_linear_ancestry(commit_id,
3186 got_worktree_get_base_commit_id(worktree), 0, repo);
3187 if (error != NULL) {
3188 if (error->code == GOT_ERR_ANCESTRY) {
3189 error = checkout_ancestry_error(
3190 head_ref, commit_id_str);
3192 goto done;
3194 error = check_same_branch(commit_id, head_ref, repo);
3195 if (error) {
3196 if (error->code == GOT_ERR_ANCESTRY) {
3197 error = checkout_ancestry_error(
3198 head_ref, commit_id_str);
3200 goto done;
3202 error = got_worktree_set_base_commit_id(worktree, repo,
3203 commit_id);
3204 if (error)
3205 goto done;
3206 /* Expand potentially abbreviated commit ID string. */
3207 free(commit_id_str);
3208 error = got_object_id_str(&commit_id_str, commit_id);
3209 if (error)
3210 goto done;
3211 } else {
3212 commit_id = got_object_id_dup(
3213 got_worktree_get_base_commit_id(worktree));
3214 if (commit_id == NULL) {
3215 error = got_error_from_errno("got_object_id_dup");
3216 goto done;
3218 error = got_object_id_str(&commit_id_str, commit_id);
3219 if (error)
3220 goto done;
3223 error = got_pathlist_append(&paths, "", NULL);
3224 if (error)
3225 goto done;
3226 cpa.worktree_path = worktree_path;
3227 cpa.had_base_commit_ref_error = 0;
3228 cpa.verbosity = verbosity;
3229 error = got_worktree_checkout_files(worktree, &paths, repo,
3230 checkout_progress, &cpa, check_cancelled, NULL);
3231 if (error != NULL)
3232 goto done;
3234 if (got_ref_is_symbolic(head_ref)) {
3235 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3236 if (error)
3237 goto done;
3238 refname = got_ref_get_name(ref);
3239 } else
3240 refname = got_ref_get_name(head_ref);
3241 printf("Checked out %s: %s\n", refname, commit_id_str);
3242 printf("Now shut up and hack\n");
3243 if (cpa.had_base_commit_ref_error)
3244 show_worktree_base_ref_warning();
3245 done:
3246 if (pack_fds) {
3247 const struct got_error *pack_err =
3248 got_repo_pack_fds_close(pack_fds);
3249 if (error == NULL)
3250 error = pack_err;
3252 if (head_ref)
3253 got_ref_close(head_ref);
3254 if (ref)
3255 got_ref_close(ref);
3256 if (repo) {
3257 close_err = got_repo_close(repo);
3258 if (error == NULL)
3259 error = close_err;
3261 if (worktree != NULL) {
3262 close_err = got_worktree_close(worktree);
3263 if (error == NULL)
3264 error = close_err;
3266 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3267 free(commit_id_str);
3268 free(commit_id);
3269 free(repo_path);
3270 free(worktree_path);
3271 free(cwd);
3272 return error;
3275 struct got_update_progress_arg {
3276 int did_something;
3277 int conflicts;
3278 int obstructed;
3279 int not_updated;
3280 int missing;
3281 int not_deleted;
3282 int unversioned;
3283 int verbosity;
3286 static void
3287 print_update_progress_stats(struct got_update_progress_arg *upa)
3289 if (!upa->did_something)
3290 return;
3292 if (upa->conflicts > 0)
3293 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3294 if (upa->obstructed > 0)
3295 printf("File paths obstructed by a non-regular file: %d\n",
3296 upa->obstructed);
3297 if (upa->not_updated > 0)
3298 printf("Files not updated because of existing merge "
3299 "conflicts: %d\n", upa->not_updated);
3303 * The meaning of some status codes differs between merge-style operations and
3304 * update operations. For example, the ! status code means "file was missing"
3305 * if changes were merged into the work tree, and "missing file was restored"
3306 * if the work tree was updated. This function should be used by any operation
3307 * which merges changes into the work tree without updating the work tree.
3309 static void
3310 print_merge_progress_stats(struct got_update_progress_arg *upa)
3312 if (!upa->did_something)
3313 return;
3315 if (upa->conflicts > 0)
3316 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3317 if (upa->obstructed > 0)
3318 printf("File paths obstructed by a non-regular file: %d\n",
3319 upa->obstructed);
3320 if (upa->missing > 0)
3321 printf("Files which had incoming changes but could not be "
3322 "found in the work tree: %d\n", upa->missing);
3323 if (upa->not_deleted > 0)
3324 printf("Files not deleted due to differences in deleted "
3325 "content: %d\n", upa->not_deleted);
3326 if (upa->unversioned > 0)
3327 printf("Files not merged because an unversioned file was "
3328 "found in the work tree: %d\n", upa->unversioned);
3331 __dead static void
3332 usage_update(void)
3334 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3335 "[path ...]\n", getprogname());
3336 exit(1);
3339 static const struct got_error *
3340 update_progress(void *arg, unsigned char status, const char *path)
3342 struct got_update_progress_arg *upa = arg;
3344 if (status == GOT_STATUS_EXISTS ||
3345 status == GOT_STATUS_BASE_REF_ERR)
3346 return NULL;
3348 upa->did_something = 1;
3350 /* Base commit bump happens silently. */
3351 if (status == GOT_STATUS_BUMP_BASE)
3352 return NULL;
3354 if (status == GOT_STATUS_CONFLICT)
3355 upa->conflicts++;
3356 if (status == GOT_STATUS_OBSTRUCTED)
3357 upa->obstructed++;
3358 if (status == GOT_STATUS_CANNOT_UPDATE)
3359 upa->not_updated++;
3360 if (status == GOT_STATUS_MISSING)
3361 upa->missing++;
3362 if (status == GOT_STATUS_CANNOT_DELETE)
3363 upa->not_deleted++;
3364 if (status == GOT_STATUS_UNVERSIONED)
3365 upa->unversioned++;
3367 while (path[0] == '/')
3368 path++;
3369 if (upa->verbosity >= 0)
3370 printf("%c %s\n", status, path);
3372 return NULL;
3375 static const struct got_error *
3376 switch_head_ref(struct got_reference *head_ref,
3377 struct got_object_id *commit_id, struct got_worktree *worktree,
3378 struct got_repository *repo)
3380 const struct got_error *err = NULL;
3381 char *base_id_str;
3382 int ref_has_moved = 0;
3384 /* Trivial case: switching between two different references. */
3385 if (strcmp(got_ref_get_name(head_ref),
3386 got_worktree_get_head_ref_name(worktree)) != 0) {
3387 printf("Switching work tree from %s to %s\n",
3388 got_worktree_get_head_ref_name(worktree),
3389 got_ref_get_name(head_ref));
3390 return got_worktree_set_head_ref(worktree, head_ref);
3393 err = check_linear_ancestry(commit_id,
3394 got_worktree_get_base_commit_id(worktree), 0, repo);
3395 if (err) {
3396 if (err->code != GOT_ERR_ANCESTRY)
3397 return err;
3398 ref_has_moved = 1;
3400 if (!ref_has_moved)
3401 return NULL;
3403 /* Switching to a rebased branch with the same reference name. */
3404 err = got_object_id_str(&base_id_str,
3405 got_worktree_get_base_commit_id(worktree));
3406 if (err)
3407 return err;
3408 printf("Reference %s now points at a different branch\n",
3409 got_worktree_get_head_ref_name(worktree));
3410 printf("Switching work tree from %s to %s\n", base_id_str,
3411 got_worktree_get_head_ref_name(worktree));
3412 return NULL;
3415 static const struct got_error *
3416 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3418 const struct got_error *err;
3419 int in_progress;
3421 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3422 if (err)
3423 return err;
3424 if (in_progress)
3425 return got_error(GOT_ERR_REBASING);
3427 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3428 if (err)
3429 return err;
3430 if (in_progress)
3431 return got_error(GOT_ERR_HISTEDIT_BUSY);
3433 return NULL;
3436 static const struct got_error *
3437 check_merge_in_progress(struct got_worktree *worktree,
3438 struct got_repository *repo)
3440 const struct got_error *err;
3441 int in_progress;
3443 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3444 if (err)
3445 return err;
3446 if (in_progress)
3447 return got_error(GOT_ERR_MERGE_BUSY);
3449 return NULL;
3452 static const struct got_error *
3453 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3454 char *argv[], struct got_worktree *worktree)
3456 const struct got_error *err = NULL;
3457 char *path;
3458 struct got_pathlist_entry *new;
3459 int i;
3461 if (argc == 0) {
3462 path = strdup("");
3463 if (path == NULL)
3464 return got_error_from_errno("strdup");
3465 return got_pathlist_append(paths, path, NULL);
3468 for (i = 0; i < argc; i++) {
3469 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3470 if (err)
3471 break;
3472 err = got_pathlist_insert(&new, paths, path, NULL);
3473 if (err || new == NULL /* duplicate */) {
3474 free(path);
3475 if (err)
3476 break;
3480 return err;
3483 static const struct got_error *
3484 wrap_not_worktree_error(const struct got_error *orig_err,
3485 const char *cmdname, const char *path)
3487 const struct got_error *err;
3488 struct got_repository *repo;
3489 static char msg[512];
3490 int *pack_fds = NULL;
3492 err = got_repo_pack_fds_open(&pack_fds);
3493 if (err)
3494 return err;
3496 err = got_repo_open(&repo, path, NULL, pack_fds);
3497 if (err)
3498 return orig_err;
3500 snprintf(msg, sizeof(msg),
3501 "'got %s' needs a work tree in addition to a git repository\n"
3502 "Work trees can be checked out from this Git repository with "
3503 "'got checkout'.\n"
3504 "The got(1) manual page contains more information.", cmdname);
3505 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3506 if (repo) {
3507 const struct got_error *close_err = got_repo_close(repo);
3508 if (err == NULL)
3509 err = close_err;
3511 if (pack_fds) {
3512 const struct got_error *pack_err =
3513 got_repo_pack_fds_close(pack_fds);
3514 if (err == NULL)
3515 err = pack_err;
3517 return err;
3520 static const struct got_error *
3521 cmd_update(int argc, char *argv[])
3523 const struct got_error *close_err, *error = NULL;
3524 struct got_repository *repo = NULL;
3525 struct got_worktree *worktree = NULL;
3526 char *worktree_path = NULL;
3527 struct got_object_id *commit_id = NULL;
3528 char *commit_id_str = NULL;
3529 const char *branch_name = NULL;
3530 struct got_reference *head_ref = NULL;
3531 struct got_pathlist_head paths;
3532 struct got_pathlist_entry *pe;
3533 int ch, verbosity = 0;
3534 struct got_update_progress_arg upa;
3535 int *pack_fds = NULL;
3537 TAILQ_INIT(&paths);
3539 #ifndef PROFILE
3540 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3541 "unveil", NULL) == -1)
3542 err(1, "pledge");
3543 #endif
3545 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3546 switch (ch) {
3547 case 'b':
3548 branch_name = optarg;
3549 break;
3550 case 'c':
3551 commit_id_str = strdup(optarg);
3552 if (commit_id_str == NULL)
3553 return got_error_from_errno("strdup");
3554 break;
3555 case 'q':
3556 verbosity = -1;
3557 break;
3558 default:
3559 usage_update();
3560 /* NOTREACHED */
3564 argc -= optind;
3565 argv += optind;
3567 worktree_path = getcwd(NULL, 0);
3568 if (worktree_path == NULL) {
3569 error = got_error_from_errno("getcwd");
3570 goto done;
3573 error = got_repo_pack_fds_open(&pack_fds);
3574 if (error != NULL)
3575 goto done;
3577 error = got_worktree_open(&worktree, worktree_path,
3578 GOT_WORKTREE_GOT_DIR);
3579 if (error) {
3580 if (error->code == GOT_ERR_NOT_WORKTREE)
3581 error = wrap_not_worktree_error(error, "update",
3582 worktree_path);
3583 goto done;
3586 error = check_rebase_or_histedit_in_progress(worktree);
3587 if (error)
3588 goto done;
3590 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3591 NULL, pack_fds);
3592 if (error != NULL)
3593 goto done;
3595 error = apply_unveil(got_repo_get_path(repo), 0,
3596 got_worktree_get_root_path(worktree));
3597 if (error)
3598 goto done;
3600 error = check_merge_in_progress(worktree, repo);
3601 if (error)
3602 goto done;
3604 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3605 if (error)
3606 goto done;
3608 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3609 got_worktree_get_head_ref_name(worktree), 0);
3610 if (error != NULL)
3611 goto done;
3612 if (commit_id_str == NULL) {
3613 error = got_ref_resolve(&commit_id, repo, head_ref);
3614 if (error != NULL)
3615 goto done;
3616 error = got_object_id_str(&commit_id_str, commit_id);
3617 if (error != NULL)
3618 goto done;
3619 } else {
3620 struct got_reflist_head refs;
3621 char *keyword_idstr = NULL;
3623 TAILQ_INIT(&refs);
3625 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3626 NULL);
3627 if (error)
3628 goto done;
3630 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3631 repo, worktree);
3632 if (error != NULL)
3633 goto done;
3634 if (keyword_idstr != NULL) {
3635 free(commit_id_str);
3636 commit_id_str = keyword_idstr;
3639 error = got_repo_match_object_id(&commit_id, NULL,
3640 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3641 got_ref_list_free(&refs);
3642 free(commit_id_str);
3643 commit_id_str = NULL;
3644 if (error)
3645 goto done;
3646 error = got_object_id_str(&commit_id_str, commit_id);
3647 if (error)
3648 goto done;
3651 if (branch_name) {
3652 struct got_object_id *head_commit_id;
3653 TAILQ_FOREACH(pe, &paths, entry) {
3654 if (pe->path_len == 0)
3655 continue;
3656 error = got_error_msg(GOT_ERR_BAD_PATH,
3657 "switching between branches requires that "
3658 "the entire work tree gets updated");
3659 goto done;
3661 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3662 if (error)
3663 goto done;
3664 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3665 repo);
3666 free(head_commit_id);
3667 if (error != NULL)
3668 goto done;
3669 error = check_same_branch(commit_id, head_ref, repo);
3670 if (error)
3671 goto done;
3672 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3673 if (error)
3674 goto done;
3675 } else {
3676 error = check_linear_ancestry(commit_id,
3677 got_worktree_get_base_commit_id(worktree), 0, repo);
3678 if (error != NULL) {
3679 if (error->code == GOT_ERR_ANCESTRY)
3680 error = got_error(GOT_ERR_BRANCH_MOVED);
3681 goto done;
3683 error = check_same_branch(commit_id, head_ref, repo);
3684 if (error)
3685 goto done;
3688 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3689 commit_id) != 0) {
3690 error = got_worktree_set_base_commit_id(worktree, repo,
3691 commit_id);
3692 if (error)
3693 goto done;
3696 memset(&upa, 0, sizeof(upa));
3697 upa.verbosity = verbosity;
3698 error = got_worktree_checkout_files(worktree, &paths, repo,
3699 update_progress, &upa, check_cancelled, NULL);
3700 if (error != NULL)
3701 goto done;
3703 if (upa.did_something) {
3704 printf("Updated to %s: %s\n",
3705 got_worktree_get_head_ref_name(worktree), commit_id_str);
3706 } else
3707 printf("Already up-to-date\n");
3709 print_update_progress_stats(&upa);
3710 done:
3711 if (pack_fds) {
3712 const struct got_error *pack_err =
3713 got_repo_pack_fds_close(pack_fds);
3714 if (error == NULL)
3715 error = pack_err;
3717 if (repo) {
3718 close_err = got_repo_close(repo);
3719 if (error == NULL)
3720 error = close_err;
3722 if (worktree != NULL) {
3723 close_err = got_worktree_close(worktree);
3724 if (error == NULL)
3725 error = close_err;
3727 if (head_ref != NULL)
3728 got_ref_close(head_ref);
3729 free(worktree_path);
3730 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3731 free(commit_id);
3732 free(commit_id_str);
3733 return error;
3736 static const struct got_error *
3737 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3738 const char *path, int diff_context, int ignore_whitespace,
3739 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3740 struct got_repository *repo, FILE *outfile)
3742 const struct got_error *err = NULL;
3743 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3744 FILE *f1 = NULL, *f2 = NULL;
3745 int fd1 = -1, fd2 = -1;
3747 fd1 = got_opentempfd();
3748 if (fd1 == -1)
3749 return got_error_from_errno("got_opentempfd");
3750 fd2 = got_opentempfd();
3751 if (fd2 == -1) {
3752 err = got_error_from_errno("got_opentempfd");
3753 goto done;
3756 if (blob_id1) {
3757 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3758 fd1);
3759 if (err)
3760 goto done;
3763 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3764 if (err)
3765 goto done;
3767 f1 = got_opentemp();
3768 if (f1 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3772 f2 = got_opentemp();
3773 if (f2 == NULL) {
3774 err = got_error_from_errno("got_opentemp");
3775 goto done;
3778 while (path[0] == '/')
3779 path++;
3780 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3781 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3782 force_text_diff, dsa, outfile);
3783 done:
3784 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3785 err = got_error_from_errno("close");
3786 if (blob1)
3787 got_object_blob_close(blob1);
3788 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3789 err = got_error_from_errno("close");
3790 if (blob2)
3791 got_object_blob_close(blob2);
3792 if (f1 && fclose(f1) == EOF && err == NULL)
3793 err = got_error_from_errno("fclose");
3794 if (f2 && fclose(f2) == EOF && err == NULL)
3795 err = got_error_from_errno("fclose");
3796 return err;
3799 static const struct got_error *
3800 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3801 const char *path, int diff_context, int ignore_whitespace,
3802 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3803 struct got_repository *repo, FILE *outfile)
3805 const struct got_error *err = NULL;
3806 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3807 struct got_diff_blob_output_unidiff_arg arg;
3808 FILE *f1 = NULL, *f2 = NULL;
3809 int fd1 = -1, fd2 = -1;
3811 if (tree_id1) {
3812 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3813 if (err)
3814 goto done;
3815 fd1 = got_opentempfd();
3816 if (fd1 == -1) {
3817 err = got_error_from_errno("got_opentempfd");
3818 goto done;
3822 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3823 if (err)
3824 goto done;
3826 f1 = got_opentemp();
3827 if (f1 == NULL) {
3828 err = got_error_from_errno("got_opentemp");
3829 goto done;
3832 f2 = got_opentemp();
3833 if (f2 == NULL) {
3834 err = got_error_from_errno("got_opentemp");
3835 goto done;
3837 fd2 = got_opentempfd();
3838 if (fd2 == -1) {
3839 err = got_error_from_errno("got_opentempfd");
3840 goto done;
3842 arg.diff_context = diff_context;
3843 arg.ignore_whitespace = ignore_whitespace;
3844 arg.force_text_diff = force_text_diff;
3845 arg.diffstat = dsa;
3846 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3847 arg.outfile = outfile;
3848 arg.lines = NULL;
3849 arg.nlines = 0;
3850 while (path[0] == '/')
3851 path++;
3852 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3853 got_diff_blob_output_unidiff, &arg, 1);
3854 done:
3855 if (tree1)
3856 got_object_tree_close(tree1);
3857 if (tree2)
3858 got_object_tree_close(tree2);
3859 if (f1 && fclose(f1) == EOF && err == NULL)
3860 err = got_error_from_errno("fclose");
3861 if (f2 && fclose(f2) == EOF && err == NULL)
3862 err = got_error_from_errno("fclose");
3863 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3864 err = got_error_from_errno("close");
3865 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3866 err = got_error_from_errno("close");
3867 return err;
3870 static const struct got_error *
3871 get_changed_paths(struct got_pathlist_head *paths,
3872 struct got_commit_object *commit, struct got_repository *repo,
3873 struct got_diffstat_cb_arg *dsa)
3875 const struct got_error *err = NULL;
3876 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3877 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3878 struct got_object_qid *qid;
3879 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3880 FILE *f1 = NULL, *f2 = NULL;
3881 int fd1 = -1, fd2 = -1;
3883 if (dsa) {
3884 cb = got_diff_tree_compute_diffstat;
3886 f1 = got_opentemp();
3887 if (f1 == NULL) {
3888 err = got_error_from_errno("got_opentemp");
3889 goto done;
3891 f2 = got_opentemp();
3892 if (f2 == NULL) {
3893 err = got_error_from_errno("got_opentemp");
3894 goto done;
3896 fd1 = got_opentempfd();
3897 if (fd1 == -1) {
3898 err = got_error_from_errno("got_opentempfd");
3899 goto done;
3901 fd2 = got_opentempfd();
3902 if (fd2 == -1) {
3903 err = got_error_from_errno("got_opentempfd");
3904 goto done;
3908 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3909 if (qid != NULL) {
3910 struct got_commit_object *pcommit;
3911 err = got_object_open_as_commit(&pcommit, repo,
3912 &qid->id);
3913 if (err)
3914 return err;
3916 tree_id1 = got_object_id_dup(
3917 got_object_commit_get_tree_id(pcommit));
3918 if (tree_id1 == NULL) {
3919 got_object_commit_close(pcommit);
3920 return got_error_from_errno("got_object_id_dup");
3922 got_object_commit_close(pcommit);
3926 if (tree_id1) {
3927 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3928 if (err)
3929 goto done;
3932 tree_id2 = got_object_commit_get_tree_id(commit);
3933 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3934 if (err)
3935 goto done;
3937 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3938 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3939 done:
3940 if (tree1)
3941 got_object_tree_close(tree1);
3942 if (tree2)
3943 got_object_tree_close(tree2);
3944 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3945 err = got_error_from_errno("close");
3946 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3947 err = got_error_from_errno("close");
3948 if (f1 && fclose(f1) == EOF && err == NULL)
3949 err = got_error_from_errno("fclose");
3950 if (f2 && fclose(f2) == EOF && err == NULL)
3951 err = got_error_from_errno("fclose");
3952 free(tree_id1);
3953 return err;
3956 static const struct got_error *
3957 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3958 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3959 struct got_repository *repo, FILE *outfile)
3961 const struct got_error *err = NULL;
3962 struct got_commit_object *pcommit = NULL;
3963 char *id_str1 = NULL, *id_str2 = NULL;
3964 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3965 struct got_object_qid *qid;
3967 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3968 if (qid != NULL) {
3969 err = got_object_open_as_commit(&pcommit, repo,
3970 &qid->id);
3971 if (err)
3972 return err;
3973 err = got_object_id_str(&id_str1, &qid->id);
3974 if (err)
3975 goto done;
3978 err = got_object_id_str(&id_str2, id);
3979 if (err)
3980 goto done;
3982 if (path && path[0] != '\0') {
3983 int obj_type;
3984 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3985 if (err)
3986 goto done;
3987 if (pcommit) {
3988 err = got_object_id_by_path(&obj_id1, repo,
3989 pcommit, path);
3990 if (err) {
3991 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3992 free(obj_id2);
3993 goto done;
3997 err = got_object_get_type(&obj_type, repo, obj_id2);
3998 if (err) {
3999 free(obj_id2);
4000 goto done;
4002 fprintf(outfile,
4003 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4004 fprintf(outfile, "commit - %s\n",
4005 id_str1 ? id_str1 : "/dev/null");
4006 fprintf(outfile, "commit + %s\n", id_str2);
4007 switch (obj_type) {
4008 case GOT_OBJ_TYPE_BLOB:
4009 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4010 0, 0, dsa, repo, outfile);
4011 break;
4012 case GOT_OBJ_TYPE_TREE:
4013 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4014 0, 0, dsa, repo, outfile);
4015 break;
4016 default:
4017 err = got_error(GOT_ERR_OBJ_TYPE);
4018 break;
4020 free(obj_id1);
4021 free(obj_id2);
4022 } else {
4023 obj_id2 = got_object_commit_get_tree_id(commit);
4024 if (pcommit)
4025 obj_id1 = got_object_commit_get_tree_id(pcommit);
4026 fprintf(outfile,
4027 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4028 fprintf(outfile, "commit - %s\n",
4029 id_str1 ? id_str1 : "/dev/null");
4030 fprintf(outfile, "commit + %s\n", id_str2);
4031 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4032 dsa, repo, outfile);
4034 done:
4035 free(id_str1);
4036 free(id_str2);
4037 if (pcommit)
4038 got_object_commit_close(pcommit);
4039 return err;
4042 static char *
4043 get_datestr(time_t *time, char *datebuf)
4045 struct tm mytm, *tm;
4046 char *p, *s;
4048 tm = gmtime_r(time, &mytm);
4049 if (tm == NULL)
4050 return NULL;
4051 s = asctime_r(tm, datebuf);
4052 if (s == NULL)
4053 return NULL;
4054 p = strchr(s, '\n');
4055 if (p)
4056 *p = '\0';
4057 return s;
4060 static const struct got_error *
4061 match_commit(int *have_match, struct got_object_id *id,
4062 struct got_commit_object *commit, regex_t *regex)
4064 const struct got_error *err = NULL;
4065 regmatch_t regmatch;
4066 char *id_str = NULL, *logmsg = NULL;
4068 *have_match = 0;
4070 err = got_object_id_str(&id_str, id);
4071 if (err)
4072 return err;
4074 err = got_object_commit_get_logmsg(&logmsg, commit);
4075 if (err)
4076 goto done;
4078 if (regexec(regex, got_object_commit_get_author(commit), 1,
4079 &regmatch, 0) == 0 ||
4080 regexec(regex, got_object_commit_get_committer(commit), 1,
4081 &regmatch, 0) == 0 ||
4082 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4083 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4084 *have_match = 1;
4085 done:
4086 free(id_str);
4087 free(logmsg);
4088 return err;
4091 static void
4092 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4093 regex_t *regex)
4095 regmatch_t regmatch;
4096 struct got_pathlist_entry *pe;
4098 *have_match = 0;
4100 TAILQ_FOREACH(pe, changed_paths, entry) {
4101 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4102 *have_match = 1;
4103 break;
4108 static const struct got_error *
4109 match_patch(int *have_match, struct got_commit_object *commit,
4110 struct got_object_id *id, const char *path, int diff_context,
4111 struct got_repository *repo, regex_t *regex, FILE *f)
4113 const struct got_error *err = NULL;
4114 char *line = NULL;
4115 size_t linesize = 0;
4116 regmatch_t regmatch;
4118 *have_match = 0;
4120 err = got_opentemp_truncate(f);
4121 if (err)
4122 return err;
4124 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4125 if (err)
4126 goto done;
4128 if (fseeko(f, 0L, SEEK_SET) == -1) {
4129 err = got_error_from_errno("fseeko");
4130 goto done;
4133 while (getline(&line, &linesize, f) != -1) {
4134 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4135 *have_match = 1;
4136 break;
4139 done:
4140 free(line);
4141 return err;
4144 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4146 static const struct got_error*
4147 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4148 struct got_object_id *id, struct got_repository *repo,
4149 int local_only)
4151 static const struct got_error *err = NULL;
4152 struct got_reflist_entry *re;
4153 char *s;
4154 const char *name;
4156 *refs_str = NULL;
4158 TAILQ_FOREACH(re, refs, entry) {
4159 struct got_tag_object *tag = NULL;
4160 struct got_object_id *ref_id;
4161 int cmp;
4163 name = got_ref_get_name(re->ref);
4164 if (strcmp(name, GOT_REF_HEAD) == 0)
4165 continue;
4166 if (strncmp(name, "refs/", 5) == 0)
4167 name += 5;
4168 if (strncmp(name, "got/", 4) == 0)
4169 continue;
4170 if (strncmp(name, "heads/", 6) == 0)
4171 name += 6;
4172 if (strncmp(name, "remotes/", 8) == 0) {
4173 if (local_only)
4174 continue;
4175 name += 8;
4176 s = strstr(name, "/" GOT_REF_HEAD);
4177 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4178 continue;
4180 err = got_ref_resolve(&ref_id, repo, re->ref);
4181 if (err)
4182 break;
4183 if (strncmp(name, "tags/", 5) == 0) {
4184 err = got_object_open_as_tag(&tag, repo, ref_id);
4185 if (err) {
4186 if (err->code != GOT_ERR_OBJ_TYPE) {
4187 free(ref_id);
4188 break;
4190 /* Ref points at something other than a tag. */
4191 err = NULL;
4192 tag = NULL;
4195 cmp = got_object_id_cmp(tag ?
4196 got_object_tag_get_object_id(tag) : ref_id, id);
4197 free(ref_id);
4198 if (tag)
4199 got_object_tag_close(tag);
4200 if (cmp != 0)
4201 continue;
4202 s = *refs_str;
4203 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4204 s ? ", " : "", name) == -1) {
4205 err = got_error_from_errno("asprintf");
4206 free(s);
4207 *refs_str = NULL;
4208 break;
4210 free(s);
4213 return err;
4216 static const struct got_error *
4217 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4218 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4220 const struct got_error *err = NULL;
4221 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4222 char *comma, *s, *nl;
4223 struct got_reflist_head *refs;
4224 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4225 struct tm tm;
4226 time_t committer_time;
4228 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4229 if (refs) {
4230 err = build_refs_str(&ref_str, refs, id, repo, 1);
4231 if (err)
4232 return err;
4234 /* Display the first matching ref only. */
4235 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4236 *comma = '\0';
4239 if (ref_str == NULL) {
4240 err = got_object_id_str(&id_str, id);
4241 if (err)
4242 return err;
4245 committer_time = got_object_commit_get_committer_time(commit);
4246 if (gmtime_r(&committer_time, &tm) == NULL) {
4247 err = got_error_from_errno("gmtime_r");
4248 goto done;
4250 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4251 err = got_error(GOT_ERR_NO_SPACE);
4252 goto done;
4255 err = got_object_commit_get_logmsg(&logmsg0, commit);
4256 if (err)
4257 goto done;
4259 s = logmsg0;
4260 while (isspace((unsigned char)s[0]))
4261 s++;
4263 nl = strchr(s, '\n');
4264 if (nl) {
4265 *nl = '\0';
4268 if (ref_str)
4269 printf("%s%-7s %s\n", datebuf, ref_str, s);
4270 else
4271 printf("%s%.7s %s\n", datebuf, id_str, s);
4273 if (fflush(stdout) != 0 && err == NULL)
4274 err = got_error_from_errno("fflush");
4275 done:
4276 free(id_str);
4277 free(ref_str);
4278 free(logmsg0);
4279 return err;
4282 static const struct got_error *
4283 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4285 struct got_pathlist_entry *pe;
4287 if (header != NULL)
4288 printf("%s\n", header);
4290 TAILQ_FOREACH(pe, dsa->paths, entry) {
4291 struct got_diff_changed_path *cp = pe->data;
4292 int pad = dsa->max_path_len - pe->path_len + 1;
4294 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4295 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4297 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4298 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4299 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4301 if (fflush(stdout) != 0)
4302 return got_error_from_errno("fflush");
4304 return NULL;
4307 static const struct got_error *
4308 printfile(FILE *f)
4310 char buf[8192];
4311 size_t r;
4313 if (fseeko(f, 0L, SEEK_SET) == -1)
4314 return got_error_from_errno("fseek");
4316 for (;;) {
4317 r = fread(buf, 1, sizeof(buf), f);
4318 if (r == 0) {
4319 if (ferror(f))
4320 return got_error_from_errno("fread");
4321 if (feof(f))
4322 break;
4324 if (fwrite(buf, 1, r, stdout) != r)
4325 return got_ferror(stdout, GOT_ERR_IO);
4328 return NULL;
4331 static const struct got_error *
4332 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4333 struct got_repository *repo, const char *path,
4334 struct got_pathlist_head *changed_paths,
4335 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4336 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4337 const char *prefix)
4339 const struct got_error *err = NULL;
4340 FILE *f = NULL;
4341 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4342 char datebuf[26];
4343 time_t committer_time;
4344 const char *author, *committer;
4345 char *refs_str = NULL;
4347 err = got_object_id_str(&id_str, id);
4348 if (err)
4349 return err;
4351 if (custom_refs_str == NULL) {
4352 struct got_reflist_head *refs;
4353 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4354 if (refs) {
4355 err = build_refs_str(&refs_str, refs, id, repo, 0);
4356 if (err)
4357 goto done;
4361 printf(GOT_COMMIT_SEP_STR);
4362 if (custom_refs_str)
4363 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4364 custom_refs_str);
4365 else
4366 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4367 refs_str ? " (" : "", refs_str ? refs_str : "",
4368 refs_str ? ")" : "");
4369 free(id_str);
4370 id_str = NULL;
4371 free(refs_str);
4372 refs_str = NULL;
4373 printf("from: %s\n", got_object_commit_get_author(commit));
4374 author = got_object_commit_get_author(commit);
4375 committer = got_object_commit_get_committer(commit);
4376 if (strcmp(author, committer) != 0)
4377 printf("via: %s\n", committer);
4378 committer_time = got_object_commit_get_committer_time(commit);
4379 datestr = get_datestr(&committer_time, datebuf);
4380 if (datestr)
4381 printf("date: %s UTC\n", datestr);
4382 if (got_object_commit_get_nparents(commit) > 1) {
4383 const struct got_object_id_queue *parent_ids;
4384 struct got_object_qid *qid;
4385 int n = 1;
4386 parent_ids = got_object_commit_get_parent_ids(commit);
4387 STAILQ_FOREACH(qid, parent_ids, entry) {
4388 err = got_object_id_str(&id_str, &qid->id);
4389 if (err)
4390 goto done;
4391 printf("parent %d: %s\n", n++, id_str);
4392 free(id_str);
4393 id_str = NULL;
4397 err = got_object_commit_get_logmsg(&logmsg0, commit);
4398 if (err)
4399 goto done;
4401 logmsg = logmsg0;
4402 do {
4403 line = strsep(&logmsg, "\n");
4404 if (line)
4405 printf(" %s\n", line);
4406 } while (line);
4407 free(logmsg0);
4409 if (changed_paths && diffstat == NULL) {
4410 struct got_pathlist_entry *pe;
4412 TAILQ_FOREACH(pe, changed_paths, entry) {
4413 struct got_diff_changed_path *cp = pe->data;
4415 printf(" %c %s\n", cp->status, pe->path);
4417 printf("\n");
4419 if (show_patch) {
4420 if (diffstat) {
4421 f = got_opentemp();
4422 if (f == NULL) {
4423 err = got_error_from_errno("got_opentemp");
4424 goto done;
4428 err = print_patch(commit, id, path, diff_context, diffstat,
4429 repo, diffstat == NULL ? stdout : f);
4430 if (err)
4431 goto done;
4433 if (diffstat) {
4434 err = print_diffstat(diffstat, NULL);
4435 if (err)
4436 goto done;
4437 if (show_patch) {
4438 err = printfile(f);
4439 if (err)
4440 goto done;
4443 if (show_patch)
4444 printf("\n");
4446 if (fflush(stdout) != 0 && err == NULL)
4447 err = got_error_from_errno("fflush");
4448 done:
4449 if (f && fclose(f) == EOF && err == NULL)
4450 err = got_error_from_errno("fclose");
4451 free(id_str);
4452 free(refs_str);
4453 return err;
4456 static const struct got_error *
4457 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4458 struct got_repository *repo, const char *path, int show_changed_paths,
4459 int show_diffstat, int show_patch, const char *search_pattern,
4460 int diff_context, int limit, int log_branches, int reverse_display_order,
4461 struct got_reflist_object_id_map *refs_idmap, int one_line,
4462 FILE *tmpfile)
4464 const struct got_error *err;
4465 struct got_commit_graph *graph;
4466 regex_t regex;
4467 int have_match;
4468 struct got_object_id_queue reversed_commits;
4469 struct got_object_qid *qid;
4470 struct got_commit_object *commit;
4471 struct got_pathlist_head changed_paths;
4473 STAILQ_INIT(&reversed_commits);
4474 TAILQ_INIT(&changed_paths);
4476 if (search_pattern && regcomp(&regex, search_pattern,
4477 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4478 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4480 err = got_commit_graph_open(&graph, path, !log_branches);
4481 if (err)
4482 return err;
4483 err = got_commit_graph_iter_start(graph, root_id, repo,
4484 check_cancelled, NULL);
4485 if (err)
4486 goto done;
4487 for (;;) {
4488 struct got_object_id id;
4489 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4490 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4492 if (sigint_received || sigpipe_received)
4493 break;
4495 err = got_commit_graph_iter_next(&id, graph, repo,
4496 check_cancelled, NULL);
4497 if (err) {
4498 if (err->code == GOT_ERR_ITER_COMPLETED)
4499 err = NULL;
4500 break;
4503 err = got_object_open_as_commit(&commit, repo, &id);
4504 if (err)
4505 break;
4507 if (((show_changed_paths && !show_diffstat) ||
4508 (show_diffstat && !show_patch))
4509 && !reverse_display_order) {
4510 err = get_changed_paths(&changed_paths, commit, repo,
4511 show_diffstat ? &dsa : NULL);
4512 if (err)
4513 break;
4516 if (search_pattern) {
4517 err = match_commit(&have_match, &id, commit, &regex);
4518 if (err) {
4519 got_object_commit_close(commit);
4520 break;
4522 if (have_match == 0 && show_changed_paths)
4523 match_changed_paths(&have_match,
4524 &changed_paths, &regex);
4525 if (have_match == 0 && show_patch) {
4526 err = match_patch(&have_match, commit, &id,
4527 path, diff_context, repo, &regex, tmpfile);
4528 if (err)
4529 break;
4531 if (have_match == 0) {
4532 got_object_commit_close(commit);
4533 got_pathlist_free(&changed_paths,
4534 GOT_PATHLIST_FREE_ALL);
4535 continue;
4539 if (reverse_display_order) {
4540 err = got_object_qid_alloc(&qid, &id);
4541 if (err)
4542 break;
4543 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4544 got_object_commit_close(commit);
4545 } else {
4546 if (one_line)
4547 err = print_commit_oneline(commit, &id,
4548 repo, refs_idmap);
4549 else
4550 err = print_commit(commit, &id, repo, path,
4551 (show_changed_paths || show_diffstat) ?
4552 &changed_paths : NULL,
4553 show_diffstat ? &dsa : NULL, show_patch,
4554 diff_context, refs_idmap, NULL, NULL);
4555 got_object_commit_close(commit);
4556 if (err)
4557 break;
4559 if ((limit && --limit == 0) ||
4560 (end_id && got_object_id_cmp(&id, end_id) == 0))
4561 break;
4563 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4565 if (reverse_display_order) {
4566 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4567 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4568 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4570 err = got_object_open_as_commit(&commit, repo,
4571 &qid->id);
4572 if (err)
4573 break;
4574 if ((show_changed_paths && !show_diffstat) ||
4575 (show_diffstat && !show_patch)) {
4576 err = get_changed_paths(&changed_paths, commit,
4577 repo, show_diffstat ? &dsa : NULL);
4578 if (err)
4579 break;
4581 if (one_line)
4582 err = print_commit_oneline(commit, &qid->id,
4583 repo, refs_idmap);
4584 else
4585 err = print_commit(commit, &qid->id, repo, path,
4586 (show_changed_paths || show_diffstat) ?
4587 &changed_paths : NULL,
4588 show_diffstat ? &dsa : NULL, show_patch,
4589 diff_context, refs_idmap, NULL, NULL);
4590 got_object_commit_close(commit);
4591 if (err)
4592 break;
4593 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4596 done:
4597 while (!STAILQ_EMPTY(&reversed_commits)) {
4598 qid = STAILQ_FIRST(&reversed_commits);
4599 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4600 got_object_qid_free(qid);
4602 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4603 if (search_pattern)
4604 regfree(&regex);
4605 got_commit_graph_close(graph);
4606 return err;
4609 __dead static void
4610 usage_log(void)
4612 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4613 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4614 "[path]\n", getprogname());
4615 exit(1);
4618 static int
4619 get_default_log_limit(void)
4621 const char *got_default_log_limit;
4622 long long n;
4623 const char *errstr;
4625 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4626 if (got_default_log_limit == NULL)
4627 return 0;
4628 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4629 if (errstr != NULL)
4630 return 0;
4631 return n;
4634 static const struct got_error *
4635 cmd_log(int argc, char *argv[])
4637 const struct got_error *error;
4638 struct got_repository *repo = NULL;
4639 struct got_worktree *worktree = NULL;
4640 struct got_object_id *start_id = NULL, *end_id = NULL;
4641 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4642 char *keyword_idstr = NULL;
4643 const char *start_commit = NULL, *end_commit = NULL;
4644 const char *search_pattern = NULL;
4645 int diff_context = -1, ch;
4646 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4647 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4648 const char *errstr;
4649 struct got_reflist_head refs;
4650 struct got_reflist_object_id_map *refs_idmap = NULL;
4651 FILE *tmpfile = NULL;
4652 int *pack_fds = NULL;
4654 TAILQ_INIT(&refs);
4656 #ifndef PROFILE
4657 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4658 NULL)
4659 == -1)
4660 err(1, "pledge");
4661 #endif
4663 limit = get_default_log_limit();
4665 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4666 switch (ch) {
4667 case 'b':
4668 log_branches = 1;
4669 break;
4670 case 'C':
4671 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4672 &errstr);
4673 if (errstr != NULL)
4674 errx(1, "number of context lines is %s: %s",
4675 errstr, optarg);
4676 break;
4677 case 'c':
4678 start_commit = optarg;
4679 break;
4680 case 'd':
4681 show_diffstat = 1;
4682 break;
4683 case 'l':
4684 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4685 if (errstr != NULL)
4686 errx(1, "number of commits is %s: %s",
4687 errstr, optarg);
4688 break;
4689 case 'P':
4690 show_changed_paths = 1;
4691 break;
4692 case 'p':
4693 show_patch = 1;
4694 break;
4695 case 'R':
4696 reverse_display_order = 1;
4697 break;
4698 case 'r':
4699 repo_path = realpath(optarg, NULL);
4700 if (repo_path == NULL)
4701 return got_error_from_errno2("realpath",
4702 optarg);
4703 got_path_strip_trailing_slashes(repo_path);
4704 break;
4705 case 'S':
4706 search_pattern = optarg;
4707 break;
4708 case 's':
4709 one_line = 1;
4710 break;
4711 case 'x':
4712 end_commit = optarg;
4713 break;
4714 default:
4715 usage_log();
4716 /* NOTREACHED */
4720 argc -= optind;
4721 argv += optind;
4723 if (diff_context == -1)
4724 diff_context = 3;
4725 else if (!show_patch)
4726 errx(1, "-C requires -p");
4728 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4729 errx(1, "cannot use -s with -d, -p or -P");
4731 cwd = getcwd(NULL, 0);
4732 if (cwd == NULL) {
4733 error = got_error_from_errno("getcwd");
4734 goto done;
4737 error = got_repo_pack_fds_open(&pack_fds);
4738 if (error != NULL)
4739 goto done;
4741 if (repo_path == NULL) {
4742 error = got_worktree_open(&worktree, cwd,
4743 GOT_WORKTREE_GOT_DIR);
4744 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4745 goto done;
4746 error = NULL;
4749 if (argc == 1) {
4750 if (worktree) {
4751 error = got_worktree_resolve_path(&path, worktree,
4752 argv[0]);
4753 if (error)
4754 goto done;
4755 } else {
4756 path = strdup(argv[0]);
4757 if (path == NULL) {
4758 error = got_error_from_errno("strdup");
4759 goto done;
4762 } else if (argc != 0)
4763 usage_log();
4765 if (repo_path == NULL) {
4766 repo_path = worktree ?
4767 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4769 if (repo_path == NULL) {
4770 error = got_error_from_errno("strdup");
4771 goto done;
4774 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4775 if (error != NULL)
4776 goto done;
4778 error = apply_unveil(got_repo_get_path(repo), 1,
4779 worktree ? got_worktree_get_root_path(worktree) : NULL);
4780 if (error)
4781 goto done;
4783 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4784 if (error)
4785 goto done;
4787 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4788 if (error)
4789 goto done;
4791 if (start_commit == NULL) {
4792 struct got_reference *head_ref;
4793 struct got_commit_object *commit = NULL;
4794 error = got_ref_open(&head_ref, repo,
4795 worktree ? got_worktree_get_head_ref_name(worktree)
4796 : GOT_REF_HEAD, 0);
4797 if (error != NULL)
4798 goto done;
4799 error = got_ref_resolve(&start_id, repo, head_ref);
4800 got_ref_close(head_ref);
4801 if (error != NULL)
4802 goto done;
4803 error = got_object_open_as_commit(&commit, repo,
4804 start_id);
4805 if (error != NULL)
4806 goto done;
4807 got_object_commit_close(commit);
4808 } else {
4809 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4810 repo, worktree);
4811 if (error != NULL)
4812 goto done;
4813 if (keyword_idstr != NULL)
4814 start_commit = keyword_idstr;
4816 error = got_repo_match_object_id(&start_id, NULL,
4817 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4818 if (error != NULL)
4819 goto done;
4821 if (end_commit != NULL) {
4822 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4823 repo, worktree);
4824 if (error != NULL)
4825 goto done;
4826 if (keyword_idstr != NULL)
4827 end_commit = keyword_idstr;
4829 error = got_repo_match_object_id(&end_id, NULL,
4830 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4831 if (error != NULL)
4832 goto done;
4835 if (worktree) {
4837 * If a path was specified on the command line it was resolved
4838 * to a path in the work tree above. Prepend the work tree's
4839 * path prefix to obtain the corresponding in-repository path.
4841 if (path) {
4842 const char *prefix;
4843 prefix = got_worktree_get_path_prefix(worktree);
4844 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4845 (path[0] != '\0') ? "/" : "", path) == -1) {
4846 error = got_error_from_errno("asprintf");
4847 goto done;
4850 } else
4851 error = got_repo_map_path(&in_repo_path, repo,
4852 path ? path : "");
4853 if (error != NULL)
4854 goto done;
4855 if (in_repo_path) {
4856 free(path);
4857 path = in_repo_path;
4860 if (worktree) {
4861 /* Release work tree lock. */
4862 got_worktree_close(worktree);
4863 worktree = NULL;
4866 if (search_pattern && show_patch) {
4867 tmpfile = got_opentemp();
4868 if (tmpfile == NULL) {
4869 error = got_error_from_errno("got_opentemp");
4870 goto done;
4874 error = print_commits(start_id, end_id, repo, path ? path : "",
4875 show_changed_paths, show_diffstat, show_patch, search_pattern,
4876 diff_context, limit, log_branches, reverse_display_order,
4877 refs_idmap, one_line, tmpfile);
4878 done:
4879 free(path);
4880 free(repo_path);
4881 free(cwd);
4882 free(start_id);
4883 free(end_id);
4884 free(keyword_idstr);
4885 if (worktree)
4886 got_worktree_close(worktree);
4887 if (repo) {
4888 const struct got_error *close_err = got_repo_close(repo);
4889 if (error == NULL)
4890 error = close_err;
4892 if (pack_fds) {
4893 const struct got_error *pack_err =
4894 got_repo_pack_fds_close(pack_fds);
4895 if (error == NULL)
4896 error = pack_err;
4898 if (refs_idmap)
4899 got_reflist_object_id_map_free(refs_idmap);
4900 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4901 error = got_error_from_errno("fclose");
4902 got_ref_list_free(&refs);
4903 return error;
4906 __dead static void
4907 usage_diff(void)
4909 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4910 "[-r repository-path] [object1 object2 | path ...]\n",
4911 getprogname());
4912 exit(1);
4915 struct print_diff_arg {
4916 struct got_repository *repo;
4917 struct got_worktree *worktree;
4918 struct got_diffstat_cb_arg *diffstat;
4919 int diff_context;
4920 const char *id_str;
4921 int header_shown;
4922 int diff_staged;
4923 enum got_diff_algorithm diff_algo;
4924 int ignore_whitespace;
4925 int force_text_diff;
4926 FILE *f1;
4927 FILE *f2;
4928 FILE *outfile;
4932 * Create a file which contains the target path of a symlink so we can feed
4933 * it as content to the diff engine.
4935 static const struct got_error *
4936 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4937 const char *abspath)
4939 const struct got_error *err = NULL;
4940 char target_path[PATH_MAX];
4941 ssize_t target_len, outlen;
4943 *fd = -1;
4945 if (dirfd != -1) {
4946 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4947 if (target_len == -1)
4948 return got_error_from_errno2("readlinkat", abspath);
4949 } else {
4950 target_len = readlink(abspath, target_path, PATH_MAX);
4951 if (target_len == -1)
4952 return got_error_from_errno2("readlink", abspath);
4955 *fd = got_opentempfd();
4956 if (*fd == -1)
4957 return got_error_from_errno("got_opentempfd");
4959 outlen = write(*fd, target_path, target_len);
4960 if (outlen == -1) {
4961 err = got_error_from_errno("got_opentempfd");
4962 goto done;
4965 if (lseek(*fd, 0, SEEK_SET) == -1) {
4966 err = got_error_from_errno2("lseek", abspath);
4967 goto done;
4969 done:
4970 if (err) {
4971 close(*fd);
4972 *fd = -1;
4974 return err;
4977 static const struct got_error *
4978 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4979 const char *path, struct got_object_id *blob_id,
4980 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4981 int dirfd, const char *de_name)
4983 struct print_diff_arg *a = arg;
4984 const struct got_error *err = NULL;
4985 struct got_blob_object *blob1 = NULL;
4986 int fd = -1, fd1 = -1, fd2 = -1;
4987 FILE *f2 = NULL;
4988 char *abspath = NULL, *label1 = NULL;
4989 struct stat sb;
4990 off_t size1 = 0;
4991 int f2_exists = 0;
4993 memset(&sb, 0, sizeof(sb));
4995 if (a->diff_staged) {
4996 if (staged_status != GOT_STATUS_MODIFY &&
4997 staged_status != GOT_STATUS_ADD &&
4998 staged_status != GOT_STATUS_DELETE)
4999 return NULL;
5000 } else {
5001 if (staged_status == GOT_STATUS_DELETE)
5002 return NULL;
5003 if (status == GOT_STATUS_NONEXISTENT)
5004 return got_error_set_errno(ENOENT, path);
5005 if (status != GOT_STATUS_MODIFY &&
5006 status != GOT_STATUS_ADD &&
5007 status != GOT_STATUS_DELETE &&
5008 status != GOT_STATUS_CONFLICT)
5009 return NULL;
5012 err = got_opentemp_truncate(a->f1);
5013 if (err)
5014 return got_error_from_errno("got_opentemp_truncate");
5015 err = got_opentemp_truncate(a->f2);
5016 if (err)
5017 return got_error_from_errno("got_opentemp_truncate");
5019 if (!a->header_shown) {
5020 if (fprintf(a->outfile, "diff %s%s\n",
5021 a->diff_staged ? "-s " : "",
5022 got_worktree_get_root_path(a->worktree)) < 0) {
5023 err = got_error_from_errno("fprintf");
5024 goto done;
5026 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5027 err = got_error_from_errno("fprintf");
5028 goto done;
5030 if (fprintf(a->outfile, "path + %s%s\n",
5031 got_worktree_get_root_path(a->worktree),
5032 a->diff_staged ? " (staged changes)" : "") < 0) {
5033 err = got_error_from_errno("fprintf");
5034 goto done;
5036 a->header_shown = 1;
5039 if (a->diff_staged) {
5040 const char *label1 = NULL, *label2 = NULL;
5041 switch (staged_status) {
5042 case GOT_STATUS_MODIFY:
5043 label1 = path;
5044 label2 = path;
5045 break;
5046 case GOT_STATUS_ADD:
5047 label2 = path;
5048 break;
5049 case GOT_STATUS_DELETE:
5050 label1 = path;
5051 break;
5052 default:
5053 return got_error(GOT_ERR_FILE_STATUS);
5055 fd1 = got_opentempfd();
5056 if (fd1 == -1) {
5057 err = got_error_from_errno("got_opentempfd");
5058 goto done;
5060 fd2 = got_opentempfd();
5061 if (fd2 == -1) {
5062 err = got_error_from_errno("got_opentempfd");
5063 goto done;
5065 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5066 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5067 a->diff_algo, a->diff_context, a->ignore_whitespace,
5068 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5069 goto done;
5072 fd1 = got_opentempfd();
5073 if (fd1 == -1) {
5074 err = got_error_from_errno("got_opentempfd");
5075 goto done;
5078 if (staged_status == GOT_STATUS_ADD ||
5079 staged_status == GOT_STATUS_MODIFY) {
5080 char *id_str;
5081 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5082 8192, fd1);
5083 if (err)
5084 goto done;
5085 err = got_object_id_str(&id_str, staged_blob_id);
5086 if (err)
5087 goto done;
5088 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5089 err = got_error_from_errno("asprintf");
5090 free(id_str);
5091 goto done;
5093 free(id_str);
5094 } else if (status != GOT_STATUS_ADD) {
5095 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5096 fd1);
5097 if (err)
5098 goto done;
5101 if (status != GOT_STATUS_DELETE) {
5102 if (asprintf(&abspath, "%s/%s",
5103 got_worktree_get_root_path(a->worktree), path) == -1) {
5104 err = got_error_from_errno("asprintf");
5105 goto done;
5108 if (dirfd != -1) {
5109 fd = openat(dirfd, de_name,
5110 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5111 if (fd == -1) {
5112 if (!got_err_open_nofollow_on_symlink()) {
5113 err = got_error_from_errno2("openat",
5114 abspath);
5115 goto done;
5117 err = get_symlink_target_file(&fd, dirfd,
5118 de_name, abspath);
5119 if (err)
5120 goto done;
5122 } else {
5123 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5124 if (fd == -1) {
5125 if (!got_err_open_nofollow_on_symlink()) {
5126 err = got_error_from_errno2("open",
5127 abspath);
5128 goto done;
5130 err = get_symlink_target_file(&fd, dirfd,
5131 de_name, abspath);
5132 if (err)
5133 goto done;
5136 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5137 err = got_error_from_errno2("fstatat", abspath);
5138 goto done;
5140 f2 = fdopen(fd, "r");
5141 if (f2 == NULL) {
5142 err = got_error_from_errno2("fdopen", abspath);
5143 goto done;
5145 fd = -1;
5146 f2_exists = 1;
5149 if (blob1) {
5150 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5151 a->f1, blob1);
5152 if (err)
5153 goto done;
5156 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5157 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5158 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5159 done:
5160 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5161 err = got_error_from_errno("close");
5162 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5163 err = got_error_from_errno("close");
5164 if (blob1)
5165 got_object_blob_close(blob1);
5166 if (fd != -1 && close(fd) == -1 && err == NULL)
5167 err = got_error_from_errno("close");
5168 if (f2 && fclose(f2) == EOF && err == NULL)
5169 err = got_error_from_errno("fclose");
5170 free(abspath);
5171 return err;
5174 static const struct got_error *
5175 cmd_diff(int argc, char *argv[])
5177 const struct got_error *error;
5178 struct got_repository *repo = NULL;
5179 struct got_worktree *worktree = NULL;
5180 char *cwd = NULL, *repo_path = NULL;
5181 const char *commit_args[2] = { NULL, NULL };
5182 int ncommit_args = 0;
5183 struct got_object_id *ids[2] = { NULL, NULL };
5184 char *labels[2] = { NULL, NULL };
5185 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5186 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5187 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5188 const char *errstr;
5189 struct got_reflist_head refs;
5190 struct got_pathlist_head diffstat_paths, paths;
5191 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5192 int fd1 = -1, fd2 = -1;
5193 int *pack_fds = NULL;
5194 struct got_diffstat_cb_arg dsa;
5196 memset(&dsa, 0, sizeof(dsa));
5198 TAILQ_INIT(&refs);
5199 TAILQ_INIT(&paths);
5200 TAILQ_INIT(&diffstat_paths);
5202 #ifndef PROFILE
5203 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5204 NULL) == -1)
5205 err(1, "pledge");
5206 #endif
5208 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5209 switch (ch) {
5210 case 'a':
5211 force_text_diff = 1;
5212 break;
5213 case 'C':
5214 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5215 &errstr);
5216 if (errstr != NULL)
5217 errx(1, "number of context lines is %s: %s",
5218 errstr, optarg);
5219 break;
5220 case 'c':
5221 if (ncommit_args >= 2)
5222 errx(1, "too many -c options used");
5223 commit_args[ncommit_args++] = optarg;
5224 break;
5225 case 'd':
5226 show_diffstat = 1;
5227 break;
5228 case 'P':
5229 force_path = 1;
5230 break;
5231 case 'r':
5232 repo_path = realpath(optarg, NULL);
5233 if (repo_path == NULL)
5234 return got_error_from_errno2("realpath",
5235 optarg);
5236 got_path_strip_trailing_slashes(repo_path);
5237 rflag = 1;
5238 break;
5239 case 's':
5240 diff_staged = 1;
5241 break;
5242 case 'w':
5243 ignore_whitespace = 1;
5244 break;
5245 default:
5246 usage_diff();
5247 /* NOTREACHED */
5251 argc -= optind;
5252 argv += optind;
5254 cwd = getcwd(NULL, 0);
5255 if (cwd == NULL) {
5256 error = got_error_from_errno("getcwd");
5257 goto done;
5260 error = got_repo_pack_fds_open(&pack_fds);
5261 if (error != NULL)
5262 goto done;
5264 if (repo_path == NULL) {
5265 error = got_worktree_open(&worktree, cwd,
5266 GOT_WORKTREE_GOT_DIR);
5267 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5268 goto done;
5269 else
5270 error = NULL;
5271 if (worktree) {
5272 repo_path =
5273 strdup(got_worktree_get_repo_path(worktree));
5274 if (repo_path == NULL) {
5275 error = got_error_from_errno("strdup");
5276 goto done;
5278 } else {
5279 repo_path = strdup(cwd);
5280 if (repo_path == NULL) {
5281 error = got_error_from_errno("strdup");
5282 goto done;
5287 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5288 free(repo_path);
5289 if (error != NULL)
5290 goto done;
5292 if (show_diffstat) {
5293 dsa.paths = &diffstat_paths;
5294 dsa.force_text = force_text_diff;
5295 dsa.ignore_ws = ignore_whitespace;
5296 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5299 if (rflag || worktree == NULL || ncommit_args > 0) {
5300 if (force_path) {
5301 error = got_error_msg(GOT_ERR_NOT_IMPL,
5302 "-P option can only be used when diffing "
5303 "a work tree");
5304 goto done;
5306 if (diff_staged) {
5307 error = got_error_msg(GOT_ERR_NOT_IMPL,
5308 "-s option can only be used when diffing "
5309 "a work tree");
5310 goto done;
5314 error = apply_unveil(got_repo_get_path(repo), 1,
5315 worktree ? got_worktree_get_root_path(worktree) : NULL);
5316 if (error)
5317 goto done;
5319 if ((!force_path && argc == 2) || ncommit_args > 0) {
5320 int obj_type = (ncommit_args > 0 ?
5321 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5322 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5323 NULL);
5324 if (error)
5325 goto done;
5326 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5327 const char *arg;
5328 char *keyword_idstr = NULL;
5330 if (ncommit_args > 0)
5331 arg = commit_args[i];
5332 else
5333 arg = argv[i];
5335 error = got_keyword_to_idstr(&keyword_idstr, arg,
5336 repo, worktree);
5337 if (error != NULL)
5338 goto done;
5339 if (keyword_idstr != NULL)
5340 arg = keyword_idstr;
5342 error = got_repo_match_object_id(&ids[i], &labels[i],
5343 arg, obj_type, &refs, repo);
5344 free(keyword_idstr);
5345 if (error) {
5346 if (error->code != GOT_ERR_NOT_REF &&
5347 error->code != GOT_ERR_NO_OBJ)
5348 goto done;
5349 if (ncommit_args > 0)
5350 goto done;
5351 error = NULL;
5352 break;
5357 f1 = got_opentemp();
5358 if (f1 == NULL) {
5359 error = got_error_from_errno("got_opentemp");
5360 goto done;
5363 f2 = got_opentemp();
5364 if (f2 == NULL) {
5365 error = got_error_from_errno("got_opentemp");
5366 goto done;
5369 outfile = got_opentemp();
5370 if (outfile == NULL) {
5371 error = got_error_from_errno("got_opentemp");
5372 goto done;
5375 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5376 struct print_diff_arg arg;
5377 char *id_str;
5379 if (worktree == NULL) {
5380 if (argc == 2 && ids[0] == NULL) {
5381 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5382 goto done;
5383 } else if (argc == 2 && ids[1] == NULL) {
5384 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5385 goto done;
5386 } else if (argc > 0) {
5387 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5388 "%s", "specified paths cannot be resolved");
5389 goto done;
5390 } else {
5391 error = got_error(GOT_ERR_NOT_WORKTREE);
5392 goto done;
5396 error = get_worktree_paths_from_argv(&paths, argc, argv,
5397 worktree);
5398 if (error)
5399 goto done;
5401 error = got_object_id_str(&id_str,
5402 got_worktree_get_base_commit_id(worktree));
5403 if (error)
5404 goto done;
5405 arg.repo = repo;
5406 arg.worktree = worktree;
5407 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5408 arg.diff_context = diff_context;
5409 arg.id_str = id_str;
5410 arg.header_shown = 0;
5411 arg.diff_staged = diff_staged;
5412 arg.ignore_whitespace = ignore_whitespace;
5413 arg.force_text_diff = force_text_diff;
5414 arg.diffstat = show_diffstat ? &dsa : NULL;
5415 arg.f1 = f1;
5416 arg.f2 = f2;
5417 arg.outfile = outfile;
5419 error = got_worktree_status(worktree, &paths, repo, 0,
5420 print_diff, &arg, check_cancelled, NULL);
5421 free(id_str);
5422 if (error)
5423 goto done;
5425 if (show_diffstat && dsa.nfiles > 0) {
5426 char *header;
5428 if (asprintf(&header, "diffstat %s%s",
5429 diff_staged ? "-s " : "",
5430 got_worktree_get_root_path(worktree)) == -1) {
5431 error = got_error_from_errno("asprintf");
5432 goto done;
5435 error = print_diffstat(&dsa, header);
5436 free(header);
5437 if (error)
5438 goto done;
5441 error = printfile(outfile);
5442 goto done;
5445 if (ncommit_args == 1) {
5446 struct got_commit_object *commit;
5447 error = got_object_open_as_commit(&commit, repo, ids[0]);
5448 if (error)
5449 goto done;
5451 labels[1] = labels[0];
5452 ids[1] = ids[0];
5453 if (got_object_commit_get_nparents(commit) > 0) {
5454 const struct got_object_id_queue *pids;
5455 struct got_object_qid *pid;
5456 pids = got_object_commit_get_parent_ids(commit);
5457 pid = STAILQ_FIRST(pids);
5458 ids[0] = got_object_id_dup(&pid->id);
5459 if (ids[0] == NULL) {
5460 error = got_error_from_errno(
5461 "got_object_id_dup");
5462 got_object_commit_close(commit);
5463 goto done;
5465 error = got_object_id_str(&labels[0], ids[0]);
5466 if (error) {
5467 got_object_commit_close(commit);
5468 goto done;
5470 } else {
5471 ids[0] = NULL;
5472 labels[0] = strdup("/dev/null");
5473 if (labels[0] == NULL) {
5474 error = got_error_from_errno("strdup");
5475 got_object_commit_close(commit);
5476 goto done;
5480 got_object_commit_close(commit);
5483 if (ncommit_args == 0 && argc > 2) {
5484 error = got_error_msg(GOT_ERR_BAD_PATH,
5485 "path arguments cannot be used when diffing two objects");
5486 goto done;
5489 if (ids[0]) {
5490 error = got_object_get_type(&type1, repo, ids[0]);
5491 if (error)
5492 goto done;
5495 error = got_object_get_type(&type2, repo, ids[1]);
5496 if (error)
5497 goto done;
5498 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5499 error = got_error(GOT_ERR_OBJ_TYPE);
5500 goto done;
5502 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5503 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5504 "path arguments cannot be used when diffing blobs");
5505 goto done;
5508 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5509 char *in_repo_path;
5510 struct got_pathlist_entry *new;
5511 if (worktree) {
5512 const char *prefix;
5513 char *p;
5514 error = got_worktree_resolve_path(&p, worktree,
5515 argv[i]);
5516 if (error)
5517 goto done;
5518 prefix = got_worktree_get_path_prefix(worktree);
5519 while (prefix[0] == '/')
5520 prefix++;
5521 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5522 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5523 p) == -1) {
5524 error = got_error_from_errno("asprintf");
5525 free(p);
5526 goto done;
5528 free(p);
5529 } else {
5530 char *mapped_path, *s;
5531 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5532 if (error)
5533 goto done;
5534 s = mapped_path;
5535 while (s[0] == '/')
5536 s++;
5537 in_repo_path = strdup(s);
5538 if (in_repo_path == NULL) {
5539 error = got_error_from_errno("asprintf");
5540 free(mapped_path);
5541 goto done;
5543 free(mapped_path);
5546 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5547 if (error || new == NULL /* duplicate */)
5548 free(in_repo_path);
5549 if (error)
5550 goto done;
5553 if (worktree) {
5554 /* Release work tree lock. */
5555 got_worktree_close(worktree);
5556 worktree = NULL;
5559 fd1 = got_opentempfd();
5560 if (fd1 == -1) {
5561 error = got_error_from_errno("got_opentempfd");
5562 goto done;
5565 fd2 = got_opentempfd();
5566 if (fd2 == -1) {
5567 error = got_error_from_errno("got_opentempfd");
5568 goto done;
5571 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5572 case GOT_OBJ_TYPE_BLOB:
5573 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5574 fd1, fd2, ids[0], ids[1], NULL, NULL,
5575 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5576 ignore_whitespace, force_text_diff,
5577 show_diffstat ? &dsa : NULL, repo, outfile);
5578 break;
5579 case GOT_OBJ_TYPE_TREE:
5580 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5581 ids[0], ids[1], &paths, "", "",
5582 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5583 ignore_whitespace, force_text_diff,
5584 show_diffstat ? &dsa : NULL, repo, outfile);
5585 break;
5586 case GOT_OBJ_TYPE_COMMIT:
5587 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5588 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5589 fd1, fd2, ids[0], ids[1], &paths,
5590 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5591 ignore_whitespace, force_text_diff,
5592 show_diffstat ? &dsa : NULL, repo, outfile);
5593 break;
5594 default:
5595 error = got_error(GOT_ERR_OBJ_TYPE);
5597 if (error)
5598 goto done;
5600 if (show_diffstat && dsa.nfiles > 0) {
5601 char *header = NULL;
5603 if (asprintf(&header, "diffstat %s %s",
5604 labels[0], labels[1]) == -1) {
5605 error = got_error_from_errno("asprintf");
5606 goto done;
5609 error = print_diffstat(&dsa, header);
5610 free(header);
5611 if (error)
5612 goto done;
5615 error = printfile(outfile);
5617 done:
5618 free(labels[0]);
5619 free(labels[1]);
5620 free(ids[0]);
5621 free(ids[1]);
5622 if (worktree)
5623 got_worktree_close(worktree);
5624 if (repo) {
5625 const struct got_error *close_err = got_repo_close(repo);
5626 if (error == NULL)
5627 error = close_err;
5629 if (pack_fds) {
5630 const struct got_error *pack_err =
5631 got_repo_pack_fds_close(pack_fds);
5632 if (error == NULL)
5633 error = pack_err;
5635 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5636 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5637 got_ref_list_free(&refs);
5638 if (outfile && fclose(outfile) == EOF && error == NULL)
5639 error = got_error_from_errno("fclose");
5640 if (f1 && fclose(f1) == EOF && error == NULL)
5641 error = got_error_from_errno("fclose");
5642 if (f2 && fclose(f2) == EOF && error == NULL)
5643 error = got_error_from_errno("fclose");
5644 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5645 error = got_error_from_errno("close");
5646 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5647 error = got_error_from_errno("close");
5648 return error;
5651 __dead static void
5652 usage_blame(void)
5654 fprintf(stderr,
5655 "usage: %s blame [-c commit] [-r repository-path] path\n",
5656 getprogname());
5657 exit(1);
5660 struct blame_line {
5661 int annotated;
5662 char *id_str;
5663 char *committer;
5664 char datebuf[11]; /* YYYY-MM-DD + NUL */
5667 struct blame_cb_args {
5668 struct blame_line *lines;
5669 int nlines;
5670 int nlines_prec;
5671 int lineno_cur;
5672 off_t *line_offsets;
5673 FILE *f;
5674 struct got_repository *repo;
5677 static const struct got_error *
5678 blame_cb(void *arg, int nlines, int lineno,
5679 struct got_commit_object *commit, struct got_object_id *id)
5681 const struct got_error *err = NULL;
5682 struct blame_cb_args *a = arg;
5683 struct blame_line *bline;
5684 char *line = NULL;
5685 size_t linesize = 0;
5686 off_t offset;
5687 struct tm tm;
5688 time_t committer_time;
5690 if (nlines != a->nlines ||
5691 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5692 return got_error(GOT_ERR_RANGE);
5694 if (sigint_received)
5695 return got_error(GOT_ERR_ITER_COMPLETED);
5697 if (lineno == -1)
5698 return NULL; /* no change in this commit */
5700 /* Annotate this line. */
5701 bline = &a->lines[lineno - 1];
5702 if (bline->annotated)
5703 return NULL;
5704 err = got_object_id_str(&bline->id_str, id);
5705 if (err)
5706 return err;
5708 bline->committer = strdup(got_object_commit_get_committer(commit));
5709 if (bline->committer == NULL) {
5710 err = got_error_from_errno("strdup");
5711 goto done;
5714 committer_time = got_object_commit_get_committer_time(commit);
5715 if (gmtime_r(&committer_time, &tm) == NULL)
5716 return got_error_from_errno("gmtime_r");
5717 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5718 &tm) == 0) {
5719 err = got_error(GOT_ERR_NO_SPACE);
5720 goto done;
5722 bline->annotated = 1;
5724 /* Print lines annotated so far. */
5725 bline = &a->lines[a->lineno_cur - 1];
5726 if (!bline->annotated)
5727 goto done;
5729 offset = a->line_offsets[a->lineno_cur - 1];
5730 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5731 err = got_error_from_errno("fseeko");
5732 goto done;
5735 while (a->lineno_cur <= a->nlines && bline->annotated) {
5736 char *smallerthan, *at, *nl, *committer;
5737 size_t len;
5739 if (getline(&line, &linesize, a->f) == -1) {
5740 if (ferror(a->f))
5741 err = got_error_from_errno("getline");
5742 break;
5745 committer = bline->committer;
5746 smallerthan = strchr(committer, '<');
5747 if (smallerthan && smallerthan[1] != '\0')
5748 committer = smallerthan + 1;
5749 at = strchr(committer, '@');
5750 if (at)
5751 *at = '\0';
5752 len = strlen(committer);
5753 if (len >= 9)
5754 committer[8] = '\0';
5756 nl = strchr(line, '\n');
5757 if (nl)
5758 *nl = '\0';
5759 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5760 bline->id_str, bline->datebuf, committer, line);
5762 a->lineno_cur++;
5763 bline = &a->lines[a->lineno_cur - 1];
5765 done:
5766 free(line);
5767 return err;
5770 static const struct got_error *
5771 cmd_blame(int argc, char *argv[])
5773 const struct got_error *error;
5774 struct got_repository *repo = NULL;
5775 struct got_worktree *worktree = NULL;
5776 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5777 char *link_target = NULL;
5778 struct got_object_id *obj_id = NULL;
5779 struct got_object_id *commit_id = NULL;
5780 struct got_commit_object *commit = NULL;
5781 struct got_blob_object *blob = NULL;
5782 char *commit_id_str = NULL, *keyword_idstr = NULL;
5783 struct blame_cb_args bca;
5784 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5785 off_t filesize;
5786 int *pack_fds = NULL;
5787 FILE *f1 = NULL, *f2 = NULL;
5789 fd1 = got_opentempfd();
5790 if (fd1 == -1)
5791 return got_error_from_errno("got_opentempfd");
5793 memset(&bca, 0, sizeof(bca));
5795 #ifndef PROFILE
5796 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5797 NULL) == -1)
5798 err(1, "pledge");
5799 #endif
5801 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5802 switch (ch) {
5803 case 'c':
5804 commit_id_str = optarg;
5805 break;
5806 case 'r':
5807 repo_path = realpath(optarg, NULL);
5808 if (repo_path == NULL)
5809 return got_error_from_errno2("realpath",
5810 optarg);
5811 got_path_strip_trailing_slashes(repo_path);
5812 break;
5813 default:
5814 usage_blame();
5815 /* NOTREACHED */
5819 argc -= optind;
5820 argv += optind;
5822 if (argc == 1)
5823 path = argv[0];
5824 else
5825 usage_blame();
5827 cwd = getcwd(NULL, 0);
5828 if (cwd == NULL) {
5829 error = got_error_from_errno("getcwd");
5830 goto done;
5833 error = got_repo_pack_fds_open(&pack_fds);
5834 if (error != NULL)
5835 goto done;
5837 if (repo_path == NULL) {
5838 error = got_worktree_open(&worktree, cwd,
5839 GOT_WORKTREE_GOT_DIR);
5840 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5841 goto done;
5842 else
5843 error = NULL;
5844 if (worktree) {
5845 repo_path =
5846 strdup(got_worktree_get_repo_path(worktree));
5847 if (repo_path == NULL) {
5848 error = got_error_from_errno("strdup");
5849 if (error)
5850 goto done;
5852 } else {
5853 repo_path = strdup(cwd);
5854 if (repo_path == NULL) {
5855 error = got_error_from_errno("strdup");
5856 goto done;
5861 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5862 if (error != NULL)
5863 goto done;
5865 if (worktree) {
5866 const char *prefix = got_worktree_get_path_prefix(worktree);
5867 char *p;
5869 error = got_worktree_resolve_path(&p, worktree, path);
5870 if (error)
5871 goto done;
5872 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5873 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5874 p) == -1) {
5875 error = got_error_from_errno("asprintf");
5876 free(p);
5877 goto done;
5879 free(p);
5880 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5881 } else {
5882 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5883 if (error)
5884 goto done;
5885 error = got_repo_map_path(&in_repo_path, repo, path);
5887 if (error)
5888 goto done;
5890 if (commit_id_str == NULL) {
5891 struct got_reference *head_ref;
5892 error = got_ref_open(&head_ref, repo, worktree ?
5893 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5894 if (error != NULL)
5895 goto done;
5896 error = got_ref_resolve(&commit_id, repo, head_ref);
5897 got_ref_close(head_ref);
5898 if (error != NULL)
5899 goto done;
5900 } else {
5901 struct got_reflist_head refs;
5903 TAILQ_INIT(&refs);
5904 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5905 NULL);
5906 if (error)
5907 goto done;
5909 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5910 repo, worktree);
5911 if (error != NULL)
5912 goto done;
5913 if (keyword_idstr != NULL)
5914 commit_id_str = keyword_idstr;
5916 error = got_repo_match_object_id(&commit_id, NULL,
5917 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5918 got_ref_list_free(&refs);
5919 if (error)
5920 goto done;
5923 if (worktree) {
5924 /* Release work tree lock. */
5925 got_worktree_close(worktree);
5926 worktree = NULL;
5929 error = got_object_open_as_commit(&commit, repo, commit_id);
5930 if (error)
5931 goto done;
5933 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5934 commit, repo);
5935 if (error)
5936 goto done;
5938 error = got_object_id_by_path(&obj_id, repo, commit,
5939 link_target ? link_target : in_repo_path);
5940 if (error)
5941 goto done;
5943 error = got_object_get_type(&obj_type, repo, obj_id);
5944 if (error)
5945 goto done;
5947 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5948 error = got_error_path(link_target ? link_target : in_repo_path,
5949 GOT_ERR_OBJ_TYPE);
5950 goto done;
5953 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5954 if (error)
5955 goto done;
5956 bca.f = got_opentemp();
5957 if (bca.f == NULL) {
5958 error = got_error_from_errno("got_opentemp");
5959 goto done;
5961 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5962 &bca.line_offsets, bca.f, blob);
5963 if (error || bca.nlines == 0)
5964 goto done;
5966 /* Don't include \n at EOF in the blame line count. */
5967 if (bca.line_offsets[bca.nlines - 1] == filesize)
5968 bca.nlines--;
5970 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5971 if (bca.lines == NULL) {
5972 error = got_error_from_errno("calloc");
5973 goto done;
5975 bca.lineno_cur = 1;
5976 bca.nlines_prec = 0;
5977 i = bca.nlines;
5978 while (i > 0) {
5979 i /= 10;
5980 bca.nlines_prec++;
5982 bca.repo = repo;
5984 fd2 = got_opentempfd();
5985 if (fd2 == -1) {
5986 error = got_error_from_errno("got_opentempfd");
5987 goto done;
5989 fd3 = got_opentempfd();
5990 if (fd3 == -1) {
5991 error = got_error_from_errno("got_opentempfd");
5992 goto done;
5994 f1 = got_opentemp();
5995 if (f1 == NULL) {
5996 error = got_error_from_errno("got_opentemp");
5997 goto done;
5999 f2 = got_opentemp();
6000 if (f2 == NULL) {
6001 error = got_error_from_errno("got_opentemp");
6002 goto done;
6004 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6005 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6006 check_cancelled, NULL, fd2, fd3, f1, f2);
6007 done:
6008 free(keyword_idstr);
6009 free(in_repo_path);
6010 free(link_target);
6011 free(repo_path);
6012 free(cwd);
6013 free(commit_id);
6014 free(obj_id);
6015 if (commit)
6016 got_object_commit_close(commit);
6018 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6019 error = got_error_from_errno("close");
6020 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6021 error = got_error_from_errno("close");
6022 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6023 error = got_error_from_errno("close");
6024 if (f1 && fclose(f1) == EOF && error == NULL)
6025 error = got_error_from_errno("fclose");
6026 if (f2 && fclose(f2) == EOF && error == NULL)
6027 error = got_error_from_errno("fclose");
6029 if (blob)
6030 got_object_blob_close(blob);
6031 if (worktree)
6032 got_worktree_close(worktree);
6033 if (repo) {
6034 const struct got_error *close_err = got_repo_close(repo);
6035 if (error == NULL)
6036 error = close_err;
6038 if (pack_fds) {
6039 const struct got_error *pack_err =
6040 got_repo_pack_fds_close(pack_fds);
6041 if (error == NULL)
6042 error = pack_err;
6044 if (bca.lines) {
6045 for (i = 0; i < bca.nlines; i++) {
6046 struct blame_line *bline = &bca.lines[i];
6047 free(bline->id_str);
6048 free(bline->committer);
6050 free(bca.lines);
6052 free(bca.line_offsets);
6053 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6054 error = got_error_from_errno("fclose");
6055 return error;
6058 __dead static void
6059 usage_tree(void)
6061 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6062 "[path]\n", getprogname());
6063 exit(1);
6066 static const struct got_error *
6067 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6068 const char *root_path, struct got_repository *repo)
6070 const struct got_error *err = NULL;
6071 int is_root_path = (strcmp(path, root_path) == 0);
6072 const char *modestr = "";
6073 mode_t mode = got_tree_entry_get_mode(te);
6074 char *link_target = NULL;
6076 path += strlen(root_path);
6077 while (path[0] == '/')
6078 path++;
6080 if (got_object_tree_entry_is_submodule(te))
6081 modestr = "$";
6082 else if (S_ISLNK(mode)) {
6083 int i;
6085 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6086 if (err)
6087 return err;
6088 for (i = 0; link_target[i] != '\0'; i++) {
6089 if (!isprint((unsigned char)link_target[i]))
6090 link_target[i] = '?';
6093 modestr = "@";
6095 else if (S_ISDIR(mode))
6096 modestr = "/";
6097 else if (mode & S_IXUSR)
6098 modestr = "*";
6100 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6101 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6102 link_target ? " -> ": "", link_target ? link_target : "");
6104 free(link_target);
6105 return NULL;
6108 static const struct got_error *
6109 print_tree(const char *path, struct got_commit_object *commit,
6110 int show_ids, int recurse, const char *root_path,
6111 struct got_repository *repo)
6113 const struct got_error *err = NULL;
6114 struct got_object_id *tree_id = NULL;
6115 struct got_tree_object *tree = NULL;
6116 int nentries, i;
6118 err = got_object_id_by_path(&tree_id, repo, commit, path);
6119 if (err)
6120 goto done;
6122 err = got_object_open_as_tree(&tree, repo, tree_id);
6123 if (err)
6124 goto done;
6125 nentries = got_object_tree_get_nentries(tree);
6126 for (i = 0; i < nentries; i++) {
6127 struct got_tree_entry *te;
6128 char *id = NULL;
6130 if (sigint_received || sigpipe_received)
6131 break;
6133 te = got_object_tree_get_entry(tree, i);
6134 if (show_ids) {
6135 char *id_str;
6136 err = got_object_id_str(&id_str,
6137 got_tree_entry_get_id(te));
6138 if (err)
6139 goto done;
6140 if (asprintf(&id, "%s ", id_str) == -1) {
6141 err = got_error_from_errno("asprintf");
6142 free(id_str);
6143 goto done;
6145 free(id_str);
6147 err = print_entry(te, id, path, root_path, repo);
6148 free(id);
6149 if (err)
6150 goto done;
6152 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6153 char *child_path;
6154 if (asprintf(&child_path, "%s%s%s", path,
6155 path[0] == '/' && path[1] == '\0' ? "" : "/",
6156 got_tree_entry_get_name(te)) == -1) {
6157 err = got_error_from_errno("asprintf");
6158 goto done;
6160 err = print_tree(child_path, commit, show_ids, 1,
6161 root_path, repo);
6162 free(child_path);
6163 if (err)
6164 goto done;
6167 done:
6168 if (tree)
6169 got_object_tree_close(tree);
6170 free(tree_id);
6171 return err;
6174 static const struct got_error *
6175 cmd_tree(int argc, char *argv[])
6177 const struct got_error *error;
6178 struct got_repository *repo = NULL;
6179 struct got_worktree *worktree = NULL;
6180 const char *path, *refname = NULL;
6181 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6182 struct got_object_id *commit_id = NULL;
6183 struct got_commit_object *commit = NULL;
6184 char *commit_id_str = NULL, *keyword_idstr = NULL;
6185 int show_ids = 0, recurse = 0;
6186 int ch;
6187 int *pack_fds = NULL;
6189 #ifndef PROFILE
6190 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6191 NULL) == -1)
6192 err(1, "pledge");
6193 #endif
6195 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6196 switch (ch) {
6197 case 'c':
6198 commit_id_str = optarg;
6199 break;
6200 case 'i':
6201 show_ids = 1;
6202 break;
6203 case 'R':
6204 recurse = 1;
6205 break;
6206 case 'r':
6207 repo_path = realpath(optarg, NULL);
6208 if (repo_path == NULL)
6209 return got_error_from_errno2("realpath",
6210 optarg);
6211 got_path_strip_trailing_slashes(repo_path);
6212 break;
6213 default:
6214 usage_tree();
6215 /* NOTREACHED */
6219 argc -= optind;
6220 argv += optind;
6222 if (argc == 1)
6223 path = argv[0];
6224 else if (argc > 1)
6225 usage_tree();
6226 else
6227 path = NULL;
6229 cwd = getcwd(NULL, 0);
6230 if (cwd == NULL) {
6231 error = got_error_from_errno("getcwd");
6232 goto done;
6235 error = got_repo_pack_fds_open(&pack_fds);
6236 if (error != NULL)
6237 goto done;
6239 if (repo_path == NULL) {
6240 error = got_worktree_open(&worktree, cwd,
6241 GOT_WORKTREE_GOT_DIR);
6242 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6243 goto done;
6244 else
6245 error = NULL;
6246 if (worktree) {
6247 repo_path =
6248 strdup(got_worktree_get_repo_path(worktree));
6249 if (repo_path == NULL)
6250 error = got_error_from_errno("strdup");
6251 if (error)
6252 goto done;
6253 } else {
6254 repo_path = strdup(cwd);
6255 if (repo_path == NULL) {
6256 error = got_error_from_errno("strdup");
6257 goto done;
6262 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6263 if (error != NULL)
6264 goto done;
6266 if (worktree) {
6267 const char *prefix = got_worktree_get_path_prefix(worktree);
6268 char *p;
6270 if (path == NULL || got_path_is_root_dir(path))
6271 path = "";
6272 error = got_worktree_resolve_path(&p, worktree, path);
6273 if (error)
6274 goto done;
6275 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6276 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6277 p) == -1) {
6278 error = got_error_from_errno("asprintf");
6279 free(p);
6280 goto done;
6282 free(p);
6283 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6284 if (error)
6285 goto done;
6286 } else {
6287 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6288 if (error)
6289 goto done;
6290 if (path == NULL)
6291 path = "/";
6292 error = got_repo_map_path(&in_repo_path, repo, path);
6293 if (error != NULL)
6294 goto done;
6297 if (commit_id_str == NULL) {
6298 struct got_reference *head_ref;
6299 if (worktree)
6300 refname = got_worktree_get_head_ref_name(worktree);
6301 else
6302 refname = GOT_REF_HEAD;
6303 error = got_ref_open(&head_ref, repo, refname, 0);
6304 if (error != NULL)
6305 goto done;
6306 error = got_ref_resolve(&commit_id, repo, head_ref);
6307 got_ref_close(head_ref);
6308 if (error != NULL)
6309 goto done;
6310 } else {
6311 struct got_reflist_head refs;
6313 TAILQ_INIT(&refs);
6314 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6315 NULL);
6316 if (error)
6317 goto done;
6319 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6320 repo, worktree);
6321 if (error != NULL)
6322 goto done;
6323 if (keyword_idstr != NULL)
6324 commit_id_str = keyword_idstr;
6326 error = got_repo_match_object_id(&commit_id, NULL,
6327 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6328 got_ref_list_free(&refs);
6329 if (error)
6330 goto done;
6333 if (worktree) {
6334 /* Release work tree lock. */
6335 got_worktree_close(worktree);
6336 worktree = NULL;
6339 error = got_object_open_as_commit(&commit, repo, commit_id);
6340 if (error)
6341 goto done;
6343 error = print_tree(in_repo_path, commit, show_ids, recurse,
6344 in_repo_path, repo);
6345 done:
6346 free(keyword_idstr);
6347 free(in_repo_path);
6348 free(repo_path);
6349 free(cwd);
6350 free(commit_id);
6351 if (commit)
6352 got_object_commit_close(commit);
6353 if (worktree)
6354 got_worktree_close(worktree);
6355 if (repo) {
6356 const struct got_error *close_err = got_repo_close(repo);
6357 if (error == NULL)
6358 error = close_err;
6360 if (pack_fds) {
6361 const struct got_error *pack_err =
6362 got_repo_pack_fds_close(pack_fds);
6363 if (error == NULL)
6364 error = pack_err;
6366 return error;
6369 __dead static void
6370 usage_status(void)
6372 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6373 "[-s status-codes] [path ...]\n", getprogname());
6374 exit(1);
6377 struct got_status_arg {
6378 char *status_codes;
6379 int suppress;
6382 static const struct got_error *
6383 print_status(void *arg, unsigned char status, unsigned char staged_status,
6384 const char *path, struct got_object_id *blob_id,
6385 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6386 int dirfd, const char *de_name)
6388 struct got_status_arg *st = arg;
6390 if (status == staged_status && (status == GOT_STATUS_DELETE))
6391 status = GOT_STATUS_NO_CHANGE;
6392 if (st != NULL && st->status_codes) {
6393 size_t ncodes = strlen(st->status_codes);
6394 int i, j = 0;
6396 for (i = 0; i < ncodes ; i++) {
6397 if (st->suppress) {
6398 if (status == st->status_codes[i] ||
6399 staged_status == st->status_codes[i]) {
6400 j++;
6401 continue;
6403 } else {
6404 if (status == st->status_codes[i] ||
6405 staged_status == st->status_codes[i])
6406 break;
6410 if (st->suppress && j == 0)
6411 goto print;
6413 if (i == ncodes)
6414 return NULL;
6416 print:
6417 printf("%c%c %s\n", status, staged_status, path);
6418 return NULL;
6421 static const struct got_error *
6422 cmd_status(int argc, char *argv[])
6424 const struct got_error *close_err, *error = NULL;
6425 struct got_repository *repo = NULL;
6426 struct got_worktree *worktree = NULL;
6427 struct got_status_arg st;
6428 char *cwd = NULL;
6429 struct got_pathlist_head paths;
6430 int ch, i, no_ignores = 0;
6431 int *pack_fds = NULL;
6433 TAILQ_INIT(&paths);
6435 memset(&st, 0, sizeof(st));
6436 st.status_codes = NULL;
6437 st.suppress = 0;
6439 #ifndef PROFILE
6440 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6441 NULL) == -1)
6442 err(1, "pledge");
6443 #endif
6445 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6446 switch (ch) {
6447 case 'I':
6448 no_ignores = 1;
6449 break;
6450 case 'S':
6451 if (st.status_codes != NULL && st.suppress == 0)
6452 option_conflict('S', 's');
6453 st.suppress = 1;
6454 /* fallthrough */
6455 case 's':
6456 for (i = 0; optarg[i] != '\0'; i++) {
6457 switch (optarg[i]) {
6458 case GOT_STATUS_MODIFY:
6459 case GOT_STATUS_ADD:
6460 case GOT_STATUS_DELETE:
6461 case GOT_STATUS_CONFLICT:
6462 case GOT_STATUS_MISSING:
6463 case GOT_STATUS_OBSTRUCTED:
6464 case GOT_STATUS_UNVERSIONED:
6465 case GOT_STATUS_MODE_CHANGE:
6466 case GOT_STATUS_NONEXISTENT:
6467 break;
6468 default:
6469 errx(1, "invalid status code '%c'",
6470 optarg[i]);
6473 if (ch == 's' && st.suppress)
6474 option_conflict('s', 'S');
6475 st.status_codes = optarg;
6476 break;
6477 default:
6478 usage_status();
6479 /* NOTREACHED */
6483 argc -= optind;
6484 argv += optind;
6486 cwd = getcwd(NULL, 0);
6487 if (cwd == NULL) {
6488 error = got_error_from_errno("getcwd");
6489 goto done;
6492 error = got_repo_pack_fds_open(&pack_fds);
6493 if (error != NULL)
6494 goto done;
6496 error = got_worktree_open(&worktree, cwd,
6497 GOT_WORKTREE_GOT_DIR);
6498 if (error) {
6499 if (error->code == GOT_ERR_NOT_WORKTREE)
6500 error = wrap_not_worktree_error(error, "status", cwd);
6501 goto done;
6504 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6505 NULL, pack_fds);
6506 if (error != NULL)
6507 goto done;
6509 error = apply_unveil(got_repo_get_path(repo), 1,
6510 got_worktree_get_root_path(worktree));
6511 if (error)
6512 goto done;
6514 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6515 if (error)
6516 goto done;
6518 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6519 print_status, &st, check_cancelled, NULL);
6520 done:
6521 if (pack_fds) {
6522 const struct got_error *pack_err =
6523 got_repo_pack_fds_close(pack_fds);
6524 if (error == NULL)
6525 error = pack_err;
6527 if (repo) {
6528 close_err = got_repo_close(repo);
6529 if (error == NULL)
6530 error = close_err;
6532 if (worktree != NULL) {
6533 close_err = got_worktree_close(worktree);
6534 if (error == NULL)
6535 error = close_err;
6538 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6539 free(cwd);
6540 return error;
6543 __dead static void
6544 usage_ref(void)
6546 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6547 "[-s reference] [name]\n", getprogname());
6548 exit(1);
6551 static const struct got_error *
6552 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6554 static const struct got_error *err = NULL;
6555 struct got_reflist_head refs;
6556 struct got_reflist_entry *re;
6558 TAILQ_INIT(&refs);
6559 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6560 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6561 repo);
6562 if (err)
6563 return err;
6565 TAILQ_FOREACH(re, &refs, entry) {
6566 char *refstr;
6567 refstr = got_ref_to_str(re->ref);
6568 if (refstr == NULL) {
6569 err = got_error_from_errno("got_ref_to_str");
6570 break;
6572 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6573 free(refstr);
6576 got_ref_list_free(&refs);
6577 return err;
6580 static const struct got_error *
6581 delete_ref_by_name(struct got_repository *repo, const char *refname)
6583 const struct got_error *err;
6584 struct got_reference *ref;
6586 err = got_ref_open(&ref, repo, refname, 0);
6587 if (err)
6588 return err;
6590 err = delete_ref(repo, ref);
6591 got_ref_close(ref);
6592 return err;
6595 static const struct got_error *
6596 add_ref(struct got_repository *repo, const char *refname, const char *target)
6598 const struct got_error *err = NULL;
6599 struct got_object_id *id = NULL;
6600 struct got_reference *ref = NULL;
6601 struct got_reflist_head refs;
6604 * Don't let the user create a reference name with a leading '-'.
6605 * While technically a valid reference name, this case is usually
6606 * an unintended typo.
6608 if (refname[0] == '-')
6609 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6611 TAILQ_INIT(&refs);
6612 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6613 if (err)
6614 goto done;
6615 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6616 &refs, repo);
6617 got_ref_list_free(&refs);
6618 if (err)
6619 goto done;
6621 err = got_ref_alloc(&ref, refname, id);
6622 if (err)
6623 goto done;
6625 err = got_ref_write(ref, repo);
6626 done:
6627 if (ref)
6628 got_ref_close(ref);
6629 free(id);
6630 return err;
6633 static const struct got_error *
6634 add_symref(struct got_repository *repo, const char *refname, const char *target)
6636 const struct got_error *err = NULL;
6637 struct got_reference *ref = NULL;
6638 struct got_reference *target_ref = NULL;
6641 * Don't let the user create a reference name with a leading '-'.
6642 * While technically a valid reference name, this case is usually
6643 * an unintended typo.
6645 if (refname[0] == '-')
6646 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6648 err = got_ref_open(&target_ref, repo, target, 0);
6649 if (err)
6650 return err;
6652 err = got_ref_alloc_symref(&ref, refname, target_ref);
6653 if (err)
6654 goto done;
6656 err = got_ref_write(ref, repo);
6657 done:
6658 if (target_ref)
6659 got_ref_close(target_ref);
6660 if (ref)
6661 got_ref_close(ref);
6662 return err;
6665 static const struct got_error *
6666 cmd_ref(int argc, char *argv[])
6668 const struct got_error *error = NULL;
6669 struct got_repository *repo = NULL;
6670 struct got_worktree *worktree = NULL;
6671 char *cwd = NULL, *repo_path = NULL;
6672 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6673 const char *obj_arg = NULL, *symref_target= NULL;
6674 char *refname = NULL, *keyword_idstr = NULL;
6675 int *pack_fds = NULL;
6677 #ifndef PROFILE
6678 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6679 "sendfd unveil", NULL) == -1)
6680 err(1, "pledge");
6681 #endif
6683 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6684 switch (ch) {
6685 case 'c':
6686 obj_arg = optarg;
6687 break;
6688 case 'd':
6689 do_delete = 1;
6690 break;
6691 case 'l':
6692 do_list = 1;
6693 break;
6694 case 'r':
6695 repo_path = realpath(optarg, NULL);
6696 if (repo_path == NULL)
6697 return got_error_from_errno2("realpath",
6698 optarg);
6699 got_path_strip_trailing_slashes(repo_path);
6700 break;
6701 case 's':
6702 symref_target = optarg;
6703 break;
6704 case 't':
6705 sort_by_time = 1;
6706 break;
6707 default:
6708 usage_ref();
6709 /* NOTREACHED */
6713 if (obj_arg && do_list)
6714 option_conflict('c', 'l');
6715 if (obj_arg && do_delete)
6716 option_conflict('c', 'd');
6717 if (obj_arg && symref_target)
6718 option_conflict('c', 's');
6719 if (symref_target && do_delete)
6720 option_conflict('s', 'd');
6721 if (symref_target && do_list)
6722 option_conflict('s', 'l');
6723 if (do_delete && do_list)
6724 option_conflict('d', 'l');
6725 if (sort_by_time && !do_list)
6726 errx(1, "-t option requires -l option");
6728 argc -= optind;
6729 argv += optind;
6731 if (do_list) {
6732 if (argc != 0 && argc != 1)
6733 usage_ref();
6734 if (argc == 1) {
6735 refname = strdup(argv[0]);
6736 if (refname == NULL) {
6737 error = got_error_from_errno("strdup");
6738 goto done;
6741 } else {
6742 if (argc != 1)
6743 usage_ref();
6744 refname = strdup(argv[0]);
6745 if (refname == NULL) {
6746 error = got_error_from_errno("strdup");
6747 goto done;
6751 if (refname)
6752 got_path_strip_trailing_slashes(refname);
6754 cwd = getcwd(NULL, 0);
6755 if (cwd == NULL) {
6756 error = got_error_from_errno("getcwd");
6757 goto done;
6760 error = got_repo_pack_fds_open(&pack_fds);
6761 if (error != NULL)
6762 goto done;
6764 if (repo_path == NULL) {
6765 error = got_worktree_open(&worktree, cwd,
6766 GOT_WORKTREE_GOT_DIR);
6767 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6768 goto done;
6769 else
6770 error = NULL;
6771 if (worktree) {
6772 repo_path =
6773 strdup(got_worktree_get_repo_path(worktree));
6774 if (repo_path == NULL)
6775 error = got_error_from_errno("strdup");
6776 if (error)
6777 goto done;
6778 } else {
6779 repo_path = strdup(cwd);
6780 if (repo_path == NULL) {
6781 error = got_error_from_errno("strdup");
6782 goto done;
6787 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6788 if (error != NULL)
6789 goto done;
6791 #ifndef PROFILE
6792 if (do_list) {
6793 /* Remove "cpath" promise. */
6794 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6795 NULL) == -1)
6796 err(1, "pledge");
6798 #endif
6800 error = apply_unveil(got_repo_get_path(repo), do_list,
6801 worktree ? got_worktree_get_root_path(worktree) : NULL);
6802 if (error)
6803 goto done;
6805 if (do_list)
6806 error = list_refs(repo, refname, sort_by_time);
6807 else if (do_delete)
6808 error = delete_ref_by_name(repo, refname);
6809 else if (symref_target)
6810 error = add_symref(repo, refname, symref_target);
6811 else {
6812 if (obj_arg == NULL)
6813 usage_ref();
6815 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6816 repo, worktree);
6817 if (error != NULL)
6818 goto done;
6819 if (keyword_idstr != NULL)
6820 obj_arg = keyword_idstr;
6822 error = add_ref(repo, refname, obj_arg);
6824 done:
6825 free(refname);
6826 if (repo) {
6827 const struct got_error *close_err = got_repo_close(repo);
6828 if (error == NULL)
6829 error = close_err;
6831 if (worktree)
6832 got_worktree_close(worktree);
6833 if (pack_fds) {
6834 const struct got_error *pack_err =
6835 got_repo_pack_fds_close(pack_fds);
6836 if (error == NULL)
6837 error = pack_err;
6839 free(cwd);
6840 free(repo_path);
6841 free(keyword_idstr);
6842 return error;
6845 __dead static void
6846 usage_branch(void)
6848 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6849 "[-r repository-path] [name]\n", getprogname());
6850 exit(1);
6853 static const struct got_error *
6854 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6855 struct got_reference *ref)
6857 const struct got_error *err = NULL;
6858 const char *refname;
6859 char *refstr;
6860 char marker = ' ';
6862 refname = got_ref_get_name(ref);
6863 if (worktree && strcmp(refname,
6864 got_worktree_get_head_ref_name(worktree)) == 0) {
6865 err = got_worktree_get_state(&marker, repo, worktree,
6866 check_cancelled, NULL);
6867 if (err != NULL)
6868 return err;
6871 if (strncmp(refname, "refs/heads/", 11) == 0)
6872 refname += 11;
6873 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6874 refname += 18;
6875 if (strncmp(refname, "refs/remotes/", 13) == 0)
6876 refname += 13;
6878 refstr = got_ref_to_str(ref);
6879 if (refstr == NULL)
6880 return got_error_from_errno("got_ref_to_str");
6882 printf("%c %s: %s\n", marker, refname, refstr);
6883 free(refstr);
6884 return NULL;
6887 static const struct got_error *
6888 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6890 const char *refname;
6892 if (worktree == NULL)
6893 return got_error(GOT_ERR_NOT_WORKTREE);
6895 refname = got_worktree_get_head_ref_name(worktree);
6897 if (strncmp(refname, "refs/heads/", 11) == 0)
6898 refname += 11;
6899 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6900 refname += 18;
6902 printf("%s\n", refname);
6904 return NULL;
6907 static const struct got_error *
6908 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6909 int sort_by_time)
6911 static const struct got_error *err = NULL;
6912 struct got_reflist_head refs;
6913 struct got_reflist_entry *re;
6914 struct got_reference *temp_ref = NULL;
6915 int rebase_in_progress, histedit_in_progress;
6917 TAILQ_INIT(&refs);
6919 if (worktree) {
6920 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6921 worktree);
6922 if (err)
6923 return err;
6925 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6926 worktree);
6927 if (err)
6928 return err;
6930 if (rebase_in_progress || histedit_in_progress) {
6931 err = got_ref_open(&temp_ref, repo,
6932 got_worktree_get_head_ref_name(worktree), 0);
6933 if (err)
6934 return err;
6935 list_branch(repo, worktree, temp_ref);
6936 got_ref_close(temp_ref);
6940 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6941 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6942 repo);
6943 if (err)
6944 return err;
6946 TAILQ_FOREACH(re, &refs, entry)
6947 list_branch(repo, worktree, re->ref);
6949 got_ref_list_free(&refs);
6951 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6952 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6953 repo);
6954 if (err)
6955 return err;
6957 TAILQ_FOREACH(re, &refs, entry)
6958 list_branch(repo, worktree, re->ref);
6960 got_ref_list_free(&refs);
6962 return NULL;
6965 static const struct got_error *
6966 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6967 const char *branch_name)
6969 const struct got_error *err = NULL;
6970 struct got_reference *ref = NULL;
6971 char *refname, *remote_refname = NULL;
6973 if (strncmp(branch_name, "refs/", 5) == 0)
6974 branch_name += 5;
6975 if (strncmp(branch_name, "heads/", 6) == 0)
6976 branch_name += 6;
6977 else if (strncmp(branch_name, "remotes/", 8) == 0)
6978 branch_name += 8;
6980 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6981 return got_error_from_errno("asprintf");
6983 if (asprintf(&remote_refname, "refs/remotes/%s",
6984 branch_name) == -1) {
6985 err = got_error_from_errno("asprintf");
6986 goto done;
6989 err = got_ref_open(&ref, repo, refname, 0);
6990 if (err) {
6991 const struct got_error *err2;
6992 if (err->code != GOT_ERR_NOT_REF)
6993 goto done;
6995 * Keep 'err' intact such that if neither branch exists
6996 * we report "refs/heads" rather than "refs/remotes" in
6997 * our error message.
6999 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7000 if (err2)
7001 goto done;
7002 err = NULL;
7005 if (worktree &&
7006 strcmp(got_worktree_get_head_ref_name(worktree),
7007 got_ref_get_name(ref)) == 0) {
7008 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7009 "will not delete this work tree's current branch");
7010 goto done;
7013 err = delete_ref(repo, ref);
7014 done:
7015 if (ref)
7016 got_ref_close(ref);
7017 free(refname);
7018 free(remote_refname);
7019 return err;
7022 static const struct got_error *
7023 add_branch(struct got_repository *repo, const char *branch_name,
7024 struct got_object_id *base_commit_id)
7026 const struct got_error *err = NULL;
7027 struct got_reference *ref = NULL;
7028 char *refname = NULL;
7031 * Don't let the user create a branch name with a leading '-'.
7032 * While technically a valid reference name, this case is usually
7033 * an unintended typo.
7035 if (branch_name[0] == '-')
7036 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7038 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7039 branch_name += 11;
7041 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7042 err = got_error_from_errno("asprintf");
7043 goto done;
7046 err = got_ref_open(&ref, repo, refname, 0);
7047 if (err == NULL) {
7048 err = got_error(GOT_ERR_BRANCH_EXISTS);
7049 goto done;
7050 } else if (err->code != GOT_ERR_NOT_REF)
7051 goto done;
7053 err = got_ref_alloc(&ref, refname, base_commit_id);
7054 if (err)
7055 goto done;
7057 err = got_ref_write(ref, repo);
7058 done:
7059 if (ref)
7060 got_ref_close(ref);
7061 free(refname);
7062 return err;
7065 static const struct got_error *
7066 cmd_branch(int argc, char *argv[])
7068 const struct got_error *error = NULL;
7069 struct got_repository *repo = NULL;
7070 struct got_worktree *worktree = NULL;
7071 char *cwd = NULL, *repo_path = NULL;
7072 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7073 const char *delref = NULL, *commit_id_arg = NULL;
7074 struct got_reference *ref = NULL;
7075 struct got_pathlist_head paths;
7076 struct got_object_id *commit_id = NULL;
7077 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7078 int *pack_fds = NULL;
7080 TAILQ_INIT(&paths);
7082 #ifndef PROFILE
7083 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7084 "sendfd unveil", NULL) == -1)
7085 err(1, "pledge");
7086 #endif
7088 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7089 switch (ch) {
7090 case 'c':
7091 commit_id_arg = optarg;
7092 break;
7093 case 'd':
7094 delref = optarg;
7095 break;
7096 case 'l':
7097 do_list = 1;
7098 break;
7099 case 'n':
7100 do_update = 0;
7101 break;
7102 case 'r':
7103 repo_path = realpath(optarg, NULL);
7104 if (repo_path == NULL)
7105 return got_error_from_errno2("realpath",
7106 optarg);
7107 got_path_strip_trailing_slashes(repo_path);
7108 break;
7109 case 't':
7110 sort_by_time = 1;
7111 break;
7112 default:
7113 usage_branch();
7114 /* NOTREACHED */
7118 if (do_list && delref)
7119 option_conflict('l', 'd');
7120 if (sort_by_time && !do_list)
7121 errx(1, "-t option requires -l option");
7123 argc -= optind;
7124 argv += optind;
7126 if (!do_list && !delref && argc == 0)
7127 do_show = 1;
7129 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7130 errx(1, "-c option can only be used when creating a branch");
7132 if (do_list || delref) {
7133 if (argc > 0)
7134 usage_branch();
7135 } else if (!do_show && argc != 1)
7136 usage_branch();
7138 cwd = getcwd(NULL, 0);
7139 if (cwd == NULL) {
7140 error = got_error_from_errno("getcwd");
7141 goto done;
7144 error = got_repo_pack_fds_open(&pack_fds);
7145 if (error != NULL)
7146 goto done;
7148 if (repo_path == NULL) {
7149 error = got_worktree_open(&worktree, cwd,
7150 GOT_WORKTREE_GOT_DIR);
7151 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7152 goto done;
7153 else
7154 error = NULL;
7155 if (worktree) {
7156 repo_path =
7157 strdup(got_worktree_get_repo_path(worktree));
7158 if (repo_path == NULL)
7159 error = got_error_from_errno("strdup");
7160 if (error)
7161 goto done;
7162 } else {
7163 repo_path = strdup(cwd);
7164 if (repo_path == NULL) {
7165 error = got_error_from_errno("strdup");
7166 goto done;
7171 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7172 if (error != NULL)
7173 goto done;
7175 #ifndef PROFILE
7176 if (do_list || do_show) {
7177 /* Remove "cpath" promise. */
7178 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7179 NULL) == -1)
7180 err(1, "pledge");
7182 #endif
7184 error = apply_unveil(got_repo_get_path(repo), do_list,
7185 worktree ? got_worktree_get_root_path(worktree) : NULL);
7186 if (error)
7187 goto done;
7189 if (do_show)
7190 error = show_current_branch(repo, worktree);
7191 else if (do_list)
7192 error = list_branches(repo, worktree, sort_by_time);
7193 else if (delref)
7194 error = delete_branch(repo, worktree, delref);
7195 else {
7196 struct got_reflist_head refs;
7197 TAILQ_INIT(&refs);
7198 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7199 NULL);
7200 if (error)
7201 goto done;
7202 if (commit_id_arg == NULL)
7203 commit_id_arg = worktree ?
7204 got_worktree_get_head_ref_name(worktree) :
7205 GOT_REF_HEAD;
7206 else {
7207 error = got_keyword_to_idstr(&keyword_idstr,
7208 commit_id_arg, repo, worktree);
7209 if (error != NULL)
7210 goto done;
7211 if (keyword_idstr != NULL)
7212 commit_id_arg = keyword_idstr;
7214 error = got_repo_match_object_id(&commit_id, NULL,
7215 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7216 got_ref_list_free(&refs);
7217 if (error)
7218 goto done;
7219 error = add_branch(repo, argv[0], commit_id);
7220 if (error)
7221 goto done;
7222 if (worktree && do_update) {
7223 struct got_update_progress_arg upa;
7224 char *branch_refname = NULL;
7226 error = got_object_id_str(&commit_id_str, commit_id);
7227 if (error)
7228 goto done;
7229 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7230 worktree);
7231 if (error)
7232 goto done;
7233 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7234 == -1) {
7235 error = got_error_from_errno("asprintf");
7236 goto done;
7238 error = got_ref_open(&ref, repo, branch_refname, 0);
7239 free(branch_refname);
7240 if (error)
7241 goto done;
7242 error = switch_head_ref(ref, commit_id, worktree,
7243 repo);
7244 if (error)
7245 goto done;
7246 error = got_worktree_set_base_commit_id(worktree, repo,
7247 commit_id);
7248 if (error)
7249 goto done;
7250 memset(&upa, 0, sizeof(upa));
7251 error = got_worktree_checkout_files(worktree, &paths,
7252 repo, update_progress, &upa, check_cancelled,
7253 NULL);
7254 if (error)
7255 goto done;
7256 if (upa.did_something) {
7257 printf("Updated to %s: %s\n",
7258 got_worktree_get_head_ref_name(worktree),
7259 commit_id_str);
7261 print_update_progress_stats(&upa);
7264 done:
7265 free(keyword_idstr);
7266 if (ref)
7267 got_ref_close(ref);
7268 if (repo) {
7269 const struct got_error *close_err = got_repo_close(repo);
7270 if (error == NULL)
7271 error = close_err;
7273 if (worktree)
7274 got_worktree_close(worktree);
7275 if (pack_fds) {
7276 const struct got_error *pack_err =
7277 got_repo_pack_fds_close(pack_fds);
7278 if (error == NULL)
7279 error = pack_err;
7281 free(cwd);
7282 free(repo_path);
7283 free(commit_id);
7284 free(commit_id_str);
7285 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7286 return error;
7290 __dead static void
7291 usage_tag(void)
7293 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7294 "[-r repository-path] [-s signer-id] name\n", getprogname());
7295 exit(1);
7298 #if 0
7299 static const struct got_error *
7300 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7302 const struct got_error *err = NULL;
7303 struct got_reflist_entry *re, *se, *new;
7304 struct got_object_id *re_id, *se_id;
7305 struct got_tag_object *re_tag, *se_tag;
7306 time_t re_time, se_time;
7308 STAILQ_FOREACH(re, tags, entry) {
7309 se = STAILQ_FIRST(sorted);
7310 if (se == NULL) {
7311 err = got_reflist_entry_dup(&new, re);
7312 if (err)
7313 return err;
7314 STAILQ_INSERT_HEAD(sorted, new, entry);
7315 continue;
7316 } else {
7317 err = got_ref_resolve(&re_id, repo, re->ref);
7318 if (err)
7319 break;
7320 err = got_object_open_as_tag(&re_tag, repo, re_id);
7321 free(re_id);
7322 if (err)
7323 break;
7324 re_time = got_object_tag_get_tagger_time(re_tag);
7325 got_object_tag_close(re_tag);
7328 while (se) {
7329 err = got_ref_resolve(&se_id, repo, re->ref);
7330 if (err)
7331 break;
7332 err = got_object_open_as_tag(&se_tag, repo, se_id);
7333 free(se_id);
7334 if (err)
7335 break;
7336 se_time = got_object_tag_get_tagger_time(se_tag);
7337 got_object_tag_close(se_tag);
7339 if (se_time > re_time) {
7340 err = got_reflist_entry_dup(&new, re);
7341 if (err)
7342 return err;
7343 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7344 break;
7346 se = STAILQ_NEXT(se, entry);
7347 continue;
7350 done:
7351 return err;
7353 #endif
7355 static const struct got_error *
7356 get_tag_refname(char **refname, const char *tag_name)
7358 const struct got_error *err;
7360 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7361 *refname = strdup(tag_name);
7362 if (*refname == NULL)
7363 return got_error_from_errno("strdup");
7364 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7365 err = got_error_from_errno("asprintf");
7366 *refname = NULL;
7367 return err;
7370 return NULL;
7373 static const struct got_error *
7374 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7375 const char *allowed_signers, const char *revoked_signers, int verbosity)
7377 static const struct got_error *err = NULL;
7378 struct got_reflist_head refs;
7379 struct got_reflist_entry *re;
7380 char *wanted_refname = NULL;
7381 int bad_sigs = 0;
7383 TAILQ_INIT(&refs);
7385 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7386 if (err)
7387 return err;
7389 if (tag_name) {
7390 struct got_reference *ref;
7391 err = get_tag_refname(&wanted_refname, tag_name);
7392 if (err)
7393 goto done;
7394 /* Wanted tag reference should exist. */
7395 err = got_ref_open(&ref, repo, wanted_refname, 0);
7396 if (err)
7397 goto done;
7398 got_ref_close(ref);
7401 TAILQ_FOREACH(re, &refs, entry) {
7402 const char *refname;
7403 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7404 char datebuf[26];
7405 const char *tagger, *ssh_sig = NULL;
7406 char *sig_msg = NULL;
7407 time_t tagger_time;
7408 struct got_object_id *id;
7409 struct got_tag_object *tag;
7410 struct got_commit_object *commit = NULL;
7412 refname = got_ref_get_name(re->ref);
7413 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7414 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7415 continue;
7416 refname += 10;
7417 refstr = got_ref_to_str(re->ref);
7418 if (refstr == NULL) {
7419 err = got_error_from_errno("got_ref_to_str");
7420 break;
7423 err = got_ref_resolve(&id, repo, re->ref);
7424 if (err)
7425 break;
7426 err = got_object_open_as_tag(&tag, repo, id);
7427 if (err) {
7428 if (err->code != GOT_ERR_OBJ_TYPE) {
7429 free(id);
7430 break;
7432 /* "lightweight" tag */
7433 err = got_object_open_as_commit(&commit, repo, id);
7434 if (err) {
7435 free(id);
7436 break;
7438 tagger = got_object_commit_get_committer(commit);
7439 tagger_time =
7440 got_object_commit_get_committer_time(commit);
7441 err = got_object_id_str(&id_str, id);
7442 free(id);
7443 if (err)
7444 break;
7445 } else {
7446 free(id);
7447 tagger = got_object_tag_get_tagger(tag);
7448 tagger_time = got_object_tag_get_tagger_time(tag);
7449 err = got_object_id_str(&id_str,
7450 got_object_tag_get_object_id(tag));
7451 if (err)
7452 break;
7455 if (tag && verify_tags) {
7456 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7457 got_object_tag_get_message(tag));
7458 if (ssh_sig && allowed_signers == NULL) {
7459 err = got_error_msg(
7460 GOT_ERR_VERIFY_TAG_SIGNATURE,
7461 "SSH signature verification requires "
7462 "setting allowed_signers in "
7463 "got.conf(5)");
7464 break;
7468 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7469 free(refstr);
7470 printf("from: %s\n", tagger);
7471 datestr = get_datestr(&tagger_time, datebuf);
7472 if (datestr)
7473 printf("date: %s UTC\n", datestr);
7474 if (commit)
7475 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7476 else {
7477 switch (got_object_tag_get_object_type(tag)) {
7478 case GOT_OBJ_TYPE_BLOB:
7479 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7480 id_str);
7481 break;
7482 case GOT_OBJ_TYPE_TREE:
7483 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7484 id_str);
7485 break;
7486 case GOT_OBJ_TYPE_COMMIT:
7487 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7488 id_str);
7489 break;
7490 case GOT_OBJ_TYPE_TAG:
7491 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7492 id_str);
7493 break;
7494 default:
7495 break;
7498 free(id_str);
7500 if (ssh_sig) {
7501 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7502 allowed_signers, revoked_signers, verbosity);
7503 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7504 bad_sigs = 1;
7505 else if (err)
7506 break;
7507 printf("signature: %s", sig_msg);
7508 free(sig_msg);
7509 sig_msg = NULL;
7512 if (commit) {
7513 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7514 if (err)
7515 break;
7516 got_object_commit_close(commit);
7517 } else {
7518 tagmsg0 = strdup(got_object_tag_get_message(tag));
7519 got_object_tag_close(tag);
7520 if (tagmsg0 == NULL) {
7521 err = got_error_from_errno("strdup");
7522 break;
7526 tagmsg = tagmsg0;
7527 do {
7528 line = strsep(&tagmsg, "\n");
7529 if (line)
7530 printf(" %s\n", line);
7531 } while (line);
7532 free(tagmsg0);
7534 done:
7535 got_ref_list_free(&refs);
7536 free(wanted_refname);
7538 if (err == NULL && bad_sigs)
7539 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7540 return err;
7543 static const struct got_error *
7544 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7545 const char *tag_name, const char *repo_path)
7547 const struct got_error *err = NULL;
7548 char *template = NULL, *initial_content = NULL;
7549 char *editor = NULL;
7550 int initial_content_len;
7551 int fd = -1;
7553 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7554 err = got_error_from_errno("asprintf");
7555 goto done;
7558 initial_content_len = asprintf(&initial_content,
7559 "\n# tagging commit %s as %s\n",
7560 commit_id_str, tag_name);
7561 if (initial_content_len == -1) {
7562 err = got_error_from_errno("asprintf");
7563 goto done;
7566 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7567 if (err)
7568 goto done;
7570 if (write(fd, initial_content, initial_content_len) == -1) {
7571 err = got_error_from_errno2("write", *tagmsg_path);
7572 goto done;
7574 if (close(fd) == -1) {
7575 err = got_error_from_errno2("close", *tagmsg_path);
7576 goto done;
7578 fd = -1;
7580 err = get_editor(&editor);
7581 if (err)
7582 goto done;
7583 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7584 initial_content_len, 1);
7585 done:
7586 free(initial_content);
7587 free(template);
7588 free(editor);
7590 if (fd != -1 && close(fd) == -1 && err == NULL)
7591 err = got_error_from_errno2("close", *tagmsg_path);
7593 if (err) {
7594 free(*tagmsg);
7595 *tagmsg = NULL;
7597 return err;
7600 static const struct got_error *
7601 add_tag(struct got_repository *repo, const char *tagger,
7602 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7603 const char *signer_id, int verbosity)
7605 const struct got_error *err = NULL;
7606 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7607 char *label = NULL, *commit_id_str = NULL;
7608 struct got_reference *ref = NULL;
7609 char *refname = NULL, *tagmsg = NULL;
7610 char *tagmsg_path = NULL, *tag_id_str = NULL;
7611 int preserve_tagmsg = 0;
7612 struct got_reflist_head refs;
7614 TAILQ_INIT(&refs);
7617 * Don't let the user create a tag name with a leading '-'.
7618 * While technically a valid reference name, this case is usually
7619 * an unintended typo.
7621 if (tag_name[0] == '-')
7622 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7624 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7625 if (err)
7626 goto done;
7628 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7629 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7630 if (err)
7631 goto done;
7633 err = got_object_id_str(&commit_id_str, commit_id);
7634 if (err)
7635 goto done;
7637 err = get_tag_refname(&refname, tag_name);
7638 if (err)
7639 goto done;
7640 if (strncmp("refs/tags/", tag_name, 10) == 0)
7641 tag_name += 10;
7643 err = got_ref_open(&ref, repo, refname, 0);
7644 if (err == NULL) {
7645 err = got_error(GOT_ERR_TAG_EXISTS);
7646 goto done;
7647 } else if (err->code != GOT_ERR_NOT_REF)
7648 goto done;
7650 if (tagmsg_arg == NULL) {
7651 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7652 tag_name, got_repo_get_path(repo));
7653 if (err) {
7654 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7655 tagmsg_path != NULL)
7656 preserve_tagmsg = 1;
7657 goto done;
7659 /* Editor is done; we can now apply unveil(2) */
7660 err = got_sigs_apply_unveil();
7661 if (err)
7662 goto done;
7663 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7664 if (err)
7665 goto done;
7668 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7669 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7670 verbosity);
7671 if (err) {
7672 if (tagmsg_path)
7673 preserve_tagmsg = 1;
7674 goto done;
7677 err = got_ref_alloc(&ref, refname, tag_id);
7678 if (err) {
7679 if (tagmsg_path)
7680 preserve_tagmsg = 1;
7681 goto done;
7684 err = got_ref_write(ref, repo);
7685 if (err) {
7686 if (tagmsg_path)
7687 preserve_tagmsg = 1;
7688 goto done;
7691 err = got_object_id_str(&tag_id_str, tag_id);
7692 if (err) {
7693 if (tagmsg_path)
7694 preserve_tagmsg = 1;
7695 goto done;
7697 printf("Created tag %s\n", tag_id_str);
7698 done:
7699 if (preserve_tagmsg) {
7700 fprintf(stderr, "%s: tag message preserved in %s\n",
7701 getprogname(), tagmsg_path);
7702 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7703 err = got_error_from_errno2("unlink", tagmsg_path);
7704 free(tag_id_str);
7705 if (ref)
7706 got_ref_close(ref);
7707 free(commit_id);
7708 free(commit_id_str);
7709 free(refname);
7710 free(tagmsg);
7711 free(tagmsg_path);
7712 got_ref_list_free(&refs);
7713 return err;
7716 static const struct got_error *
7717 cmd_tag(int argc, char *argv[])
7719 const struct got_error *error = NULL;
7720 struct got_repository *repo = NULL;
7721 struct got_worktree *worktree = NULL;
7722 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7723 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7724 char *allowed_signers = NULL, *revoked_signers = NULL;
7725 const char *signer_id = NULL;
7726 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7727 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7728 int *pack_fds = NULL;
7730 #ifndef PROFILE
7731 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7732 "sendfd unveil", NULL) == -1)
7733 err(1, "pledge");
7734 #endif
7736 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7737 switch (ch) {
7738 case 'c':
7739 commit_id_arg = optarg;
7740 break;
7741 case 'l':
7742 do_list = 1;
7743 break;
7744 case 'm':
7745 tagmsg = optarg;
7746 break;
7747 case 'r':
7748 repo_path = realpath(optarg, NULL);
7749 if (repo_path == NULL) {
7750 error = got_error_from_errno2("realpath",
7751 optarg);
7752 goto done;
7754 got_path_strip_trailing_slashes(repo_path);
7755 break;
7756 case 's':
7757 signer_id = optarg;
7758 break;
7759 case 'V':
7760 verify_tags = 1;
7761 break;
7762 case 'v':
7763 if (verbosity < 0)
7764 verbosity = 0;
7765 else if (verbosity < 3)
7766 verbosity++;
7767 break;
7768 default:
7769 usage_tag();
7770 /* NOTREACHED */
7774 argc -= optind;
7775 argv += optind;
7777 if (do_list || verify_tags) {
7778 if (commit_id_arg != NULL)
7779 errx(1,
7780 "-c option can only be used when creating a tag");
7781 if (tagmsg) {
7782 if (do_list)
7783 option_conflict('l', 'm');
7784 else
7785 option_conflict('V', 'm');
7787 if (signer_id) {
7788 if (do_list)
7789 option_conflict('l', 's');
7790 else
7791 option_conflict('V', 's');
7793 if (argc > 1)
7794 usage_tag();
7795 } else if (argc != 1)
7796 usage_tag();
7798 if (argc == 1)
7799 tag_name = argv[0];
7801 cwd = getcwd(NULL, 0);
7802 if (cwd == NULL) {
7803 error = got_error_from_errno("getcwd");
7804 goto done;
7807 error = got_repo_pack_fds_open(&pack_fds);
7808 if (error != NULL)
7809 goto done;
7811 if (repo_path == NULL) {
7812 error = got_worktree_open(&worktree, cwd,
7813 GOT_WORKTREE_GOT_DIR);
7814 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7815 goto done;
7816 else
7817 error = NULL;
7818 if (worktree) {
7819 repo_path =
7820 strdup(got_worktree_get_repo_path(worktree));
7821 if (repo_path == NULL)
7822 error = got_error_from_errno("strdup");
7823 if (error)
7824 goto done;
7825 } else {
7826 repo_path = strdup(cwd);
7827 if (repo_path == NULL) {
7828 error = got_error_from_errno("strdup");
7829 goto done;
7834 if (do_list || verify_tags) {
7835 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7836 if (error != NULL)
7837 goto done;
7838 error = get_allowed_signers(&allowed_signers, repo, worktree);
7839 if (error)
7840 goto done;
7841 error = get_revoked_signers(&revoked_signers, repo, worktree);
7842 if (error)
7843 goto done;
7844 if (worktree) {
7845 /* Release work tree lock. */
7846 got_worktree_close(worktree);
7847 worktree = NULL;
7851 * Remove "cpath" promise unless needed for signature tmpfile
7852 * creation.
7854 if (verify_tags)
7855 got_sigs_apply_unveil();
7856 else {
7857 #ifndef PROFILE
7858 if (pledge("stdio rpath wpath flock proc exec sendfd "
7859 "unveil", NULL) == -1)
7860 err(1, "pledge");
7861 #endif
7863 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7864 if (error)
7865 goto done;
7866 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7867 revoked_signers, verbosity);
7868 } else {
7869 error = get_gitconfig_path(&gitconfig_path);
7870 if (error)
7871 goto done;
7872 error = got_repo_open(&repo, repo_path, gitconfig_path,
7873 pack_fds);
7874 if (error != NULL)
7875 goto done;
7877 error = get_author(&tagger, repo, worktree);
7878 if (error)
7879 goto done;
7880 if (signer_id == NULL)
7881 signer_id = get_signer_id(repo, worktree);
7883 if (tagmsg) {
7884 if (signer_id) {
7885 error = got_sigs_apply_unveil();
7886 if (error)
7887 goto done;
7889 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7890 if (error)
7891 goto done;
7894 if (commit_id_arg == NULL) {
7895 struct got_reference *head_ref;
7896 struct got_object_id *commit_id;
7897 error = got_ref_open(&head_ref, repo,
7898 worktree ? got_worktree_get_head_ref_name(worktree)
7899 : GOT_REF_HEAD, 0);
7900 if (error)
7901 goto done;
7902 error = got_ref_resolve(&commit_id, repo, head_ref);
7903 got_ref_close(head_ref);
7904 if (error)
7905 goto done;
7906 error = got_object_id_str(&commit_id_str, commit_id);
7907 free(commit_id);
7908 if (error)
7909 goto done;
7910 } else {
7911 error = got_keyword_to_idstr(&keyword_idstr,
7912 commit_id_arg, repo, worktree);
7913 if (error != NULL)
7914 goto done;
7915 commit_id_str = keyword_idstr;
7918 if (worktree) {
7919 /* Release work tree lock. */
7920 got_worktree_close(worktree);
7921 worktree = NULL;
7924 error = add_tag(repo, tagger, tag_name,
7925 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7926 signer_id, verbosity);
7928 done:
7929 if (repo) {
7930 const struct got_error *close_err = got_repo_close(repo);
7931 if (error == NULL)
7932 error = close_err;
7934 if (worktree)
7935 got_worktree_close(worktree);
7936 if (pack_fds) {
7937 const struct got_error *pack_err =
7938 got_repo_pack_fds_close(pack_fds);
7939 if (error == NULL)
7940 error = pack_err;
7942 free(cwd);
7943 free(repo_path);
7944 free(gitconfig_path);
7945 free(commit_id_str);
7946 free(tagger);
7947 free(allowed_signers);
7948 free(revoked_signers);
7949 return error;
7952 __dead static void
7953 usage_add(void)
7955 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7956 exit(1);
7959 static const struct got_error *
7960 add_progress(void *arg, unsigned char status, const char *path)
7962 while (path[0] == '/')
7963 path++;
7964 printf("%c %s\n", status, path);
7965 return NULL;
7968 static const struct got_error *
7969 cmd_add(int argc, char *argv[])
7971 const struct got_error *error = NULL;
7972 struct got_repository *repo = NULL;
7973 struct got_worktree *worktree = NULL;
7974 char *cwd = NULL;
7975 struct got_pathlist_head paths;
7976 struct got_pathlist_entry *pe;
7977 int ch, can_recurse = 0, no_ignores = 0;
7978 int *pack_fds = NULL;
7980 TAILQ_INIT(&paths);
7982 #ifndef PROFILE
7983 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7984 NULL) == -1)
7985 err(1, "pledge");
7986 #endif
7988 while ((ch = getopt(argc, argv, "IR")) != -1) {
7989 switch (ch) {
7990 case 'I':
7991 no_ignores = 1;
7992 break;
7993 case 'R':
7994 can_recurse = 1;
7995 break;
7996 default:
7997 usage_add();
7998 /* NOTREACHED */
8002 argc -= optind;
8003 argv += optind;
8005 if (argc < 1)
8006 usage_add();
8008 cwd = getcwd(NULL, 0);
8009 if (cwd == NULL) {
8010 error = got_error_from_errno("getcwd");
8011 goto done;
8014 error = got_repo_pack_fds_open(&pack_fds);
8015 if (error != NULL)
8016 goto done;
8018 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8019 if (error) {
8020 if (error->code == GOT_ERR_NOT_WORKTREE)
8021 error = wrap_not_worktree_error(error, "add", cwd);
8022 goto done;
8025 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8026 NULL, pack_fds);
8027 if (error != NULL)
8028 goto done;
8030 error = apply_unveil(got_repo_get_path(repo), 1,
8031 got_worktree_get_root_path(worktree));
8032 if (error)
8033 goto done;
8035 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8036 if (error)
8037 goto done;
8039 if (!can_recurse) {
8040 char *ondisk_path;
8041 struct stat sb;
8042 TAILQ_FOREACH(pe, &paths, entry) {
8043 if (asprintf(&ondisk_path, "%s/%s",
8044 got_worktree_get_root_path(worktree),
8045 pe->path) == -1) {
8046 error = got_error_from_errno("asprintf");
8047 goto done;
8049 if (lstat(ondisk_path, &sb) == -1) {
8050 if (errno == ENOENT) {
8051 free(ondisk_path);
8052 continue;
8054 error = got_error_from_errno2("lstat",
8055 ondisk_path);
8056 free(ondisk_path);
8057 goto done;
8059 free(ondisk_path);
8060 if (S_ISDIR(sb.st_mode)) {
8061 error = got_error_msg(GOT_ERR_BAD_PATH,
8062 "adding directories requires -R option");
8063 goto done;
8068 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8069 NULL, repo, no_ignores);
8070 done:
8071 if (repo) {
8072 const struct got_error *close_err = got_repo_close(repo);
8073 if (error == NULL)
8074 error = close_err;
8076 if (worktree)
8077 got_worktree_close(worktree);
8078 if (pack_fds) {
8079 const struct got_error *pack_err =
8080 got_repo_pack_fds_close(pack_fds);
8081 if (error == NULL)
8082 error = pack_err;
8084 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8085 free(cwd);
8086 return error;
8089 __dead static void
8090 usage_remove(void)
8092 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8093 getprogname());
8094 exit(1);
8097 static const struct got_error *
8098 print_remove_status(void *arg, unsigned char status,
8099 unsigned char staged_status, const char *path)
8101 while (path[0] == '/')
8102 path++;
8103 if (status == GOT_STATUS_NONEXISTENT)
8104 return NULL;
8105 if (status == staged_status && (status == GOT_STATUS_DELETE))
8106 status = GOT_STATUS_NO_CHANGE;
8107 printf("%c%c %s\n", status, staged_status, path);
8108 return NULL;
8111 static const struct got_error *
8112 cmd_remove(int argc, char *argv[])
8114 const struct got_error *error = NULL;
8115 struct got_worktree *worktree = NULL;
8116 struct got_repository *repo = NULL;
8117 const char *status_codes = NULL;
8118 char *cwd = NULL;
8119 struct got_pathlist_head paths;
8120 struct got_pathlist_entry *pe;
8121 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8122 int ignore_missing_paths = 0;
8123 int *pack_fds = NULL;
8125 TAILQ_INIT(&paths);
8127 #ifndef PROFILE
8128 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8129 NULL) == -1)
8130 err(1, "pledge");
8131 #endif
8133 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8134 switch (ch) {
8135 case 'f':
8136 delete_local_mods = 1;
8137 ignore_missing_paths = 1;
8138 break;
8139 case 'k':
8140 keep_on_disk = 1;
8141 break;
8142 case 'R':
8143 can_recurse = 1;
8144 break;
8145 case 's':
8146 for (i = 0; optarg[i] != '\0'; i++) {
8147 switch (optarg[i]) {
8148 case GOT_STATUS_MODIFY:
8149 delete_local_mods = 1;
8150 break;
8151 case GOT_STATUS_MISSING:
8152 ignore_missing_paths = 1;
8153 break;
8154 default:
8155 errx(1, "invalid status code '%c'",
8156 optarg[i]);
8159 status_codes = optarg;
8160 break;
8161 default:
8162 usage_remove();
8163 /* NOTREACHED */
8167 argc -= optind;
8168 argv += optind;
8170 if (argc < 1)
8171 usage_remove();
8173 cwd = getcwd(NULL, 0);
8174 if (cwd == NULL) {
8175 error = got_error_from_errno("getcwd");
8176 goto done;
8179 error = got_repo_pack_fds_open(&pack_fds);
8180 if (error != NULL)
8181 goto done;
8183 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8184 if (error) {
8185 if (error->code == GOT_ERR_NOT_WORKTREE)
8186 error = wrap_not_worktree_error(error, "remove", cwd);
8187 goto done;
8190 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8191 NULL, pack_fds);
8192 if (error)
8193 goto done;
8195 error = apply_unveil(got_repo_get_path(repo), 1,
8196 got_worktree_get_root_path(worktree));
8197 if (error)
8198 goto done;
8200 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8201 if (error)
8202 goto done;
8204 if (!can_recurse) {
8205 char *ondisk_path;
8206 struct stat sb;
8207 TAILQ_FOREACH(pe, &paths, entry) {
8208 if (asprintf(&ondisk_path, "%s/%s",
8209 got_worktree_get_root_path(worktree),
8210 pe->path) == -1) {
8211 error = got_error_from_errno("asprintf");
8212 goto done;
8214 if (lstat(ondisk_path, &sb) == -1) {
8215 if (errno == ENOENT) {
8216 free(ondisk_path);
8217 continue;
8219 error = got_error_from_errno2("lstat",
8220 ondisk_path);
8221 free(ondisk_path);
8222 goto done;
8224 free(ondisk_path);
8225 if (S_ISDIR(sb.st_mode)) {
8226 error = got_error_msg(GOT_ERR_BAD_PATH,
8227 "removing directories requires -R option");
8228 goto done;
8233 error = got_worktree_schedule_delete(worktree, &paths,
8234 delete_local_mods, status_codes, print_remove_status, NULL,
8235 repo, keep_on_disk, ignore_missing_paths);
8236 done:
8237 if (repo) {
8238 const struct got_error *close_err = got_repo_close(repo);
8239 if (error == NULL)
8240 error = close_err;
8242 if (worktree)
8243 got_worktree_close(worktree);
8244 if (pack_fds) {
8245 const struct got_error *pack_err =
8246 got_repo_pack_fds_close(pack_fds);
8247 if (error == NULL)
8248 error = pack_err;
8250 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8251 free(cwd);
8252 return error;
8255 __dead static void
8256 usage_patch(void)
8258 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8259 "[patchfile]\n", getprogname());
8260 exit(1);
8263 static const struct got_error *
8264 patch_from_stdin(int *patchfd)
8266 const struct got_error *err = NULL;
8267 ssize_t r;
8268 char buf[BUFSIZ];
8269 sig_t sighup, sigint, sigquit;
8271 *patchfd = got_opentempfd();
8272 if (*patchfd == -1)
8273 return got_error_from_errno("got_opentempfd");
8275 sighup = signal(SIGHUP, SIG_DFL);
8276 sigint = signal(SIGINT, SIG_DFL);
8277 sigquit = signal(SIGQUIT, SIG_DFL);
8279 for (;;) {
8280 r = read(0, buf, sizeof(buf));
8281 if (r == -1) {
8282 err = got_error_from_errno("read");
8283 break;
8285 if (r == 0)
8286 break;
8287 if (write(*patchfd, buf, r) == -1) {
8288 err = got_error_from_errno("write");
8289 break;
8293 signal(SIGHUP, sighup);
8294 signal(SIGINT, sigint);
8295 signal(SIGQUIT, sigquit);
8297 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8298 err = got_error_from_errno("lseek");
8300 if (err != NULL) {
8301 close(*patchfd);
8302 *patchfd = -1;
8305 return err;
8308 struct got_patch_progress_arg {
8309 int did_something;
8310 int conflicts;
8311 int rejects;
8314 static const struct got_error *
8315 patch_progress(void *arg, const char *old, const char *new,
8316 unsigned char status, const struct got_error *error, int old_from,
8317 int old_lines, int new_from, int new_lines, int offset,
8318 int ws_mangled, const struct got_error *hunk_err)
8320 const char *path = new == NULL ? old : new;
8321 struct got_patch_progress_arg *a = arg;
8323 while (*path == '/')
8324 path++;
8326 if (status != GOT_STATUS_NO_CHANGE &&
8327 status != 0 /* per-hunk progress */) {
8328 printf("%c %s\n", status, path);
8329 a->did_something = 1;
8332 if (hunk_err == NULL) {
8333 if (status == GOT_STATUS_CANNOT_UPDATE)
8334 a->rejects++;
8335 else if (status == GOT_STATUS_CONFLICT)
8336 a->conflicts++;
8339 if (error != NULL)
8340 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8342 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8343 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8344 old_lines, new_from, new_lines);
8345 if (hunk_err != NULL)
8346 printf("%s\n", hunk_err->msg);
8347 else if (offset != 0)
8348 printf("applied with offset %d\n", offset);
8349 else
8350 printf("hunk contains mangled whitespace\n");
8353 return NULL;
8356 static void
8357 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8359 if (!ppa->did_something)
8360 return;
8362 if (ppa->conflicts > 0)
8363 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8365 if (ppa->rejects > 0) {
8366 printf("Files where patch failed to apply: %d\n",
8367 ppa->rejects);
8371 static const struct got_error *
8372 cmd_patch(int argc, char *argv[])
8374 const struct got_error *error = NULL, *close_error = NULL;
8375 struct got_worktree *worktree = NULL;
8376 struct got_repository *repo = NULL;
8377 struct got_reflist_head refs;
8378 struct got_object_id *commit_id = NULL;
8379 const char *commit_id_str = NULL;
8380 struct stat sb;
8381 const char *errstr;
8382 char *cwd = NULL, *keyword_idstr = NULL;
8383 int ch, nop = 0, strip = -1, reverse = 0;
8384 int patchfd;
8385 int *pack_fds = NULL;
8386 struct got_patch_progress_arg ppa;
8388 TAILQ_INIT(&refs);
8390 #ifndef PROFILE
8391 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8392 "unveil", NULL) == -1)
8393 err(1, "pledge");
8394 #endif
8396 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8397 switch (ch) {
8398 case 'c':
8399 commit_id_str = optarg;
8400 break;
8401 case 'n':
8402 nop = 1;
8403 break;
8404 case 'p':
8405 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8406 if (errstr != NULL)
8407 errx(1, "pathname strip count is %s: %s",
8408 errstr, optarg);
8409 break;
8410 case 'R':
8411 reverse = 1;
8412 break;
8413 default:
8414 usage_patch();
8415 /* NOTREACHED */
8419 argc -= optind;
8420 argv += optind;
8422 if (argc == 0) {
8423 error = patch_from_stdin(&patchfd);
8424 if (error)
8425 return error;
8426 } else if (argc == 1) {
8427 patchfd = open(argv[0], O_RDONLY);
8428 if (patchfd == -1) {
8429 error = got_error_from_errno2("open", argv[0]);
8430 return error;
8432 if (fstat(patchfd, &sb) == -1) {
8433 error = got_error_from_errno2("fstat", argv[0]);
8434 goto done;
8436 if (!S_ISREG(sb.st_mode)) {
8437 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8438 goto done;
8440 } else
8441 usage_patch();
8443 if ((cwd = getcwd(NULL, 0)) == NULL) {
8444 error = got_error_from_errno("getcwd");
8445 goto done;
8448 error = got_repo_pack_fds_open(&pack_fds);
8449 if (error != NULL)
8450 goto done;
8452 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8453 if (error != NULL)
8454 goto done;
8456 const char *repo_path = got_worktree_get_repo_path(worktree);
8457 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8458 if (error != NULL)
8459 goto done;
8461 error = apply_unveil(got_repo_get_path(repo), 0,
8462 got_worktree_get_root_path(worktree));
8463 if (error != NULL)
8464 goto done;
8466 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8467 if (error)
8468 goto done;
8470 if (commit_id_str != NULL) {
8471 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8472 repo, worktree);
8473 if (error != NULL)
8474 goto done;
8476 error = got_repo_match_object_id(&commit_id, NULL,
8477 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8478 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8479 if (error)
8480 goto done;
8483 memset(&ppa, 0, sizeof(ppa));
8484 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8485 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8486 print_patch_progress_stats(&ppa);
8487 done:
8488 got_ref_list_free(&refs);
8489 free(keyword_idstr);
8490 free(commit_id);
8491 if (repo) {
8492 close_error = got_repo_close(repo);
8493 if (error == NULL)
8494 error = close_error;
8496 if (worktree != NULL) {
8497 close_error = got_worktree_close(worktree);
8498 if (error == NULL)
8499 error = close_error;
8501 if (pack_fds) {
8502 const struct got_error *pack_err =
8503 got_repo_pack_fds_close(pack_fds);
8504 if (error == NULL)
8505 error = pack_err;
8507 free(cwd);
8508 return error;
8511 __dead static void
8512 usage_revert(void)
8514 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8515 getprogname());
8516 exit(1);
8519 static const struct got_error *
8520 revert_progress(void *arg, unsigned char status, const char *path)
8522 if (status == GOT_STATUS_UNVERSIONED)
8523 return NULL;
8525 while (path[0] == '/')
8526 path++;
8527 printf("%c %s\n", status, path);
8528 return NULL;
8531 struct choose_patch_arg {
8532 FILE *patch_script_file;
8533 const char *action;
8536 static const struct got_error *
8537 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8538 int nchanges, const char *action)
8540 const struct got_error *err;
8541 char *line = NULL;
8542 size_t linesize = 0;
8543 ssize_t linelen;
8545 switch (status) {
8546 case GOT_STATUS_ADD:
8547 printf("A %s\n%s this addition? [y/n] ", path, action);
8548 break;
8549 case GOT_STATUS_DELETE:
8550 printf("D %s\n%s this deletion? [y/n] ", path, action);
8551 break;
8552 case GOT_STATUS_MODIFY:
8553 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8554 return got_error_from_errno("fseek");
8555 printf(GOT_COMMIT_SEP_STR);
8556 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8557 printf("%s", line);
8558 if (linelen == -1 && ferror(patch_file)) {
8559 err = got_error_from_errno("getline");
8560 free(line);
8561 return err;
8563 free(line);
8564 printf(GOT_COMMIT_SEP_STR);
8565 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8566 path, n, nchanges, action);
8567 break;
8568 default:
8569 return got_error_path(path, GOT_ERR_FILE_STATUS);
8572 fflush(stdout);
8573 return NULL;
8576 static const struct got_error *
8577 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8578 FILE *patch_file, int n, int nchanges)
8580 const struct got_error *err = NULL;
8581 char *line = NULL;
8582 size_t linesize = 0;
8583 ssize_t linelen;
8584 int resp = ' ';
8585 struct choose_patch_arg *a = arg;
8587 *choice = GOT_PATCH_CHOICE_NONE;
8589 if (a->patch_script_file) {
8590 char *nl;
8591 err = show_change(status, path, patch_file, n, nchanges,
8592 a->action);
8593 if (err)
8594 return err;
8595 linelen = getline(&line, &linesize, a->patch_script_file);
8596 if (linelen == -1) {
8597 if (ferror(a->patch_script_file))
8598 return got_error_from_errno("getline");
8599 return NULL;
8601 nl = strchr(line, '\n');
8602 if (nl)
8603 *nl = '\0';
8604 if (strcmp(line, "y") == 0) {
8605 *choice = GOT_PATCH_CHOICE_YES;
8606 printf("y\n");
8607 } else if (strcmp(line, "n") == 0) {
8608 *choice = GOT_PATCH_CHOICE_NO;
8609 printf("n\n");
8610 } else if (strcmp(line, "q") == 0 &&
8611 status == GOT_STATUS_MODIFY) {
8612 *choice = GOT_PATCH_CHOICE_QUIT;
8613 printf("q\n");
8614 } else
8615 printf("invalid response '%s'\n", line);
8616 free(line);
8617 return NULL;
8620 while (resp != 'y' && resp != 'n' && resp != 'q') {
8621 err = show_change(status, path, patch_file, n, nchanges,
8622 a->action);
8623 if (err)
8624 return err;
8625 resp = getchar();
8626 if (resp == '\n')
8627 resp = getchar();
8628 if (status == GOT_STATUS_MODIFY) {
8629 if (resp != 'y' && resp != 'n' && resp != 'q') {
8630 printf("invalid response '%c'\n", resp);
8631 resp = ' ';
8633 } else if (resp != 'y' && resp != 'n') {
8634 printf("invalid response '%c'\n", resp);
8635 resp = ' ';
8639 if (resp == 'y')
8640 *choice = GOT_PATCH_CHOICE_YES;
8641 else if (resp == 'n')
8642 *choice = GOT_PATCH_CHOICE_NO;
8643 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8644 *choice = GOT_PATCH_CHOICE_QUIT;
8646 return NULL;
8649 struct wt_commitable_path_arg {
8650 struct got_pathlist_head *commit_paths;
8651 int *has_changes;
8655 * Shortcut work tree status callback to determine if the set of paths scanned
8656 * has at least one versioned path that is being modified and, if not NULL, is
8657 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8658 * soon as a path is passed with a status that satisfies this criteria.
8660 static const struct got_error *
8661 worktree_has_commitable_path(void *arg, unsigned char status,
8662 unsigned char staged_status, const char *path,
8663 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8664 struct got_object_id *commit_id, int dirfd, const char *de_name)
8666 struct wt_commitable_path_arg *a = arg;
8668 if (status == staged_status && (status == GOT_STATUS_DELETE))
8669 status = GOT_STATUS_NO_CHANGE;
8671 if (!(status == GOT_STATUS_NO_CHANGE ||
8672 status == GOT_STATUS_UNVERSIONED) ||
8673 staged_status != GOT_STATUS_NO_CHANGE) {
8674 if (a->commit_paths != NULL) {
8675 struct got_pathlist_entry *pe;
8677 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8678 if (strncmp(path, pe->path,
8679 pe->path_len) == 0) {
8680 *a->has_changes = 1;
8681 break;
8684 } else
8685 *a->has_changes = 1;
8687 if (*a->has_changes)
8688 return got_error(GOT_ERR_FILE_MODIFIED);
8691 return NULL;
8695 * Check that the changeset of the commit identified by id is
8696 * comprised of at least one modified path that is being committed.
8698 static const struct got_error *
8699 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8700 struct got_object_id *id, struct got_worktree *worktree,
8701 struct got_repository *repo)
8703 const struct got_error *err;
8704 struct got_pathlist_head paths;
8705 struct got_commit_object *commit = NULL, *pcommit = NULL;
8706 struct got_tree_object *tree = NULL, *ptree = NULL;
8707 struct got_object_qid *pid;
8709 TAILQ_INIT(&paths);
8711 err = got_object_open_as_commit(&commit, repo, id);
8712 if (err)
8713 goto done;
8715 err = got_object_open_as_tree(&tree, repo,
8716 got_object_commit_get_tree_id(commit));
8717 if (err)
8718 goto done;
8720 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8721 if (pid != NULL) {
8722 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8723 if (err)
8724 goto done;
8726 err = got_object_open_as_tree(&ptree, repo,
8727 got_object_commit_get_tree_id(pcommit));
8728 if (err)
8729 goto done;
8732 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8733 got_diff_tree_collect_changed_paths, &paths, 0);
8734 if (err)
8735 goto done;
8737 err = got_worktree_status(worktree, &paths, repo, 0,
8738 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8739 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8741 * At least one changed path in the referenced commit is
8742 * modified in the work tree, that's all we need to know!
8744 err = NULL;
8747 done:
8748 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8749 if (commit)
8750 got_object_commit_close(commit);
8751 if (pcommit)
8752 got_object_commit_close(pcommit);
8753 if (tree)
8754 got_object_tree_close(tree);
8755 if (ptree)
8756 got_object_tree_close(ptree);
8757 return err;
8761 * Remove any "logmsg" reference comprised entirely of paths that have
8762 * been reverted in this work tree. If any path in the logmsg ref changeset
8763 * remains in a changed state in the worktree, do not remove the reference.
8765 static const struct got_error *
8766 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8768 const struct got_error *err;
8769 struct got_reflist_head refs;
8770 struct got_reflist_entry *re;
8771 struct got_commit_object *commit = NULL;
8772 struct got_object_id *commit_id = NULL;
8773 struct wt_commitable_path_arg wcpa;
8774 char *uuidstr = NULL;
8776 TAILQ_INIT(&refs);
8778 err = got_worktree_get_uuid(&uuidstr, worktree);
8779 if (err)
8780 goto done;
8782 err = got_ref_list(&refs, repo, "refs/got/worktree",
8783 got_ref_cmp_by_name, repo);
8784 if (err)
8785 goto done;
8787 TAILQ_FOREACH(re, &refs, entry) {
8788 const char *refname;
8789 int has_changes = 0;
8791 refname = got_ref_get_name(re->ref);
8793 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8794 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8795 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8796 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8797 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8798 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8799 else
8800 continue;
8802 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8803 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8804 else
8805 continue;
8807 err = got_repo_match_object_id(&commit_id, NULL, refname,
8808 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8809 if (err)
8810 goto done;
8812 err = got_object_open_as_commit(&commit, repo, commit_id);
8813 if (err)
8814 goto done;
8816 wcpa.commit_paths = NULL;
8817 wcpa.has_changes = &has_changes;
8819 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8820 worktree, repo);
8821 if (err)
8822 goto done;
8824 if (!has_changes) {
8825 err = got_ref_delete(re->ref, repo);
8826 if (err)
8827 goto done;
8830 got_object_commit_close(commit);
8831 commit = NULL;
8832 free(commit_id);
8833 commit_id = NULL;
8836 done:
8837 free(uuidstr);
8838 free(commit_id);
8839 got_ref_list_free(&refs);
8840 if (commit)
8841 got_object_commit_close(commit);
8842 return err;
8845 static const struct got_error *
8846 cmd_revert(int argc, char *argv[])
8848 const struct got_error *error = NULL;
8849 struct got_worktree *worktree = NULL;
8850 struct got_repository *repo = NULL;
8851 char *cwd = NULL, *path = NULL;
8852 struct got_pathlist_head paths;
8853 struct got_pathlist_entry *pe;
8854 int ch, can_recurse = 0, pflag = 0;
8855 FILE *patch_script_file = NULL;
8856 const char *patch_script_path = NULL;
8857 struct choose_patch_arg cpa;
8858 int *pack_fds = NULL;
8860 TAILQ_INIT(&paths);
8862 #ifndef PROFILE
8863 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8864 "unveil", NULL) == -1)
8865 err(1, "pledge");
8866 #endif
8868 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8869 switch (ch) {
8870 case 'F':
8871 patch_script_path = optarg;
8872 break;
8873 case 'p':
8874 pflag = 1;
8875 break;
8876 case 'R':
8877 can_recurse = 1;
8878 break;
8879 default:
8880 usage_revert();
8881 /* NOTREACHED */
8885 argc -= optind;
8886 argv += optind;
8888 if (argc < 1)
8889 usage_revert();
8890 if (patch_script_path && !pflag)
8891 errx(1, "-F option can only be used together with -p option");
8893 cwd = getcwd(NULL, 0);
8894 if (cwd == NULL) {
8895 error = got_error_from_errno("getcwd");
8896 goto done;
8899 error = got_repo_pack_fds_open(&pack_fds);
8900 if (error != NULL)
8901 goto done;
8903 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8904 if (error) {
8905 if (error->code == GOT_ERR_NOT_WORKTREE)
8906 error = wrap_not_worktree_error(error, "revert", cwd);
8907 goto done;
8910 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8911 NULL, pack_fds);
8912 if (error != NULL)
8913 goto done;
8915 if (patch_script_path) {
8916 patch_script_file = fopen(patch_script_path, "re");
8917 if (patch_script_file == NULL) {
8918 error = got_error_from_errno2("fopen",
8919 patch_script_path);
8920 goto done;
8925 * XXX "c" perm needed on repo dir to delete merge references.
8927 error = apply_unveil(got_repo_get_path(repo), 0,
8928 got_worktree_get_root_path(worktree));
8929 if (error)
8930 goto done;
8932 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8933 if (error)
8934 goto done;
8936 if (!can_recurse) {
8937 char *ondisk_path;
8938 struct stat sb;
8939 TAILQ_FOREACH(pe, &paths, entry) {
8940 if (asprintf(&ondisk_path, "%s/%s",
8941 got_worktree_get_root_path(worktree),
8942 pe->path) == -1) {
8943 error = got_error_from_errno("asprintf");
8944 goto done;
8946 if (lstat(ondisk_path, &sb) == -1) {
8947 if (errno == ENOENT) {
8948 free(ondisk_path);
8949 continue;
8951 error = got_error_from_errno2("lstat",
8952 ondisk_path);
8953 free(ondisk_path);
8954 goto done;
8956 free(ondisk_path);
8957 if (S_ISDIR(sb.st_mode)) {
8958 error = got_error_msg(GOT_ERR_BAD_PATH,
8959 "reverting directories requires -R option");
8960 goto done;
8965 cpa.patch_script_file = patch_script_file;
8966 cpa.action = "revert";
8967 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8968 pflag ? choose_patch : NULL, &cpa, repo);
8970 error = rm_logmsg_ref(worktree, repo);
8971 done:
8972 if (patch_script_file && fclose(patch_script_file) == EOF &&
8973 error == NULL)
8974 error = got_error_from_errno2("fclose", patch_script_path);
8975 if (repo) {
8976 const struct got_error *close_err = got_repo_close(repo);
8977 if (error == NULL)
8978 error = close_err;
8980 if (worktree)
8981 got_worktree_close(worktree);
8982 if (pack_fds) {
8983 const struct got_error *pack_err =
8984 got_repo_pack_fds_close(pack_fds);
8985 if (error == NULL)
8986 error = pack_err;
8988 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8989 free(path);
8990 free(cwd);
8991 return error;
8994 __dead static void
8995 usage_commit(void)
8997 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8998 "[-m message] [path ...]\n", getprogname());
8999 exit(1);
9002 struct collect_commit_logmsg_arg {
9003 const char *cmdline_log;
9004 const char *prepared_log;
9005 const char *merged_log;
9006 int non_interactive;
9007 const char *editor;
9008 const char *worktree_path;
9009 const char *branch_name;
9010 const char *repo_path;
9011 char *logmsg_path;
9015 static const struct got_error *
9016 read_prepared_logmsg(char **logmsg, const char *path)
9018 const struct got_error *err = NULL;
9019 FILE *f = NULL;
9020 struct stat sb;
9021 size_t r;
9023 *logmsg = NULL;
9024 memset(&sb, 0, sizeof(sb));
9026 f = fopen(path, "re");
9027 if (f == NULL)
9028 return got_error_from_errno2("fopen", path);
9030 if (fstat(fileno(f), &sb) == -1) {
9031 err = got_error_from_errno2("fstat", path);
9032 goto done;
9034 if (sb.st_size == 0) {
9035 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9036 goto done;
9039 *logmsg = malloc(sb.st_size + 1);
9040 if (*logmsg == NULL) {
9041 err = got_error_from_errno("malloc");
9042 goto done;
9045 r = fread(*logmsg, 1, sb.st_size, f);
9046 if (r != sb.st_size) {
9047 if (ferror(f))
9048 err = got_error_from_errno2("fread", path);
9049 else
9050 err = got_error(GOT_ERR_IO);
9051 goto done;
9053 (*logmsg)[sb.st_size] = '\0';
9054 done:
9055 if (fclose(f) == EOF && err == NULL)
9056 err = got_error_from_errno2("fclose", path);
9057 if (err) {
9058 free(*logmsg);
9059 *logmsg = NULL;
9061 return err;
9064 static const struct got_error *
9065 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9066 const char *diff_path, char **logmsg, void *arg)
9068 char *initial_content = NULL;
9069 struct got_pathlist_entry *pe;
9070 const struct got_error *err = NULL;
9071 char *template = NULL;
9072 char *prepared_msg = NULL, *merged_msg = NULL;
9073 struct collect_commit_logmsg_arg *a = arg;
9074 int initial_content_len;
9075 int fd = -1;
9076 size_t len;
9078 /* if a message was specified on the command line, just use it */
9079 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9080 len = strlen(a->cmdline_log) + 1;
9081 *logmsg = malloc(len + 1);
9082 if (*logmsg == NULL)
9083 return got_error_from_errno("malloc");
9084 strlcpy(*logmsg, a->cmdline_log, len);
9085 return NULL;
9086 } else if (a->prepared_log != NULL && a->non_interactive)
9087 return read_prepared_logmsg(logmsg, a->prepared_log);
9089 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9090 return got_error_from_errno("asprintf");
9092 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9093 if (err)
9094 goto done;
9096 if (a->prepared_log) {
9097 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9098 if (err)
9099 goto done;
9100 } else if (a->merged_log) {
9101 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9102 if (err)
9103 goto done;
9106 initial_content_len = asprintf(&initial_content,
9107 "%s%s\n# changes to be committed on branch %s:\n",
9108 prepared_msg ? prepared_msg : "",
9109 merged_msg ? merged_msg : "", a->branch_name);
9110 if (initial_content_len == -1) {
9111 err = got_error_from_errno("asprintf");
9112 goto done;
9115 if (write(fd, initial_content, initial_content_len) == -1) {
9116 err = got_error_from_errno2("write", a->logmsg_path);
9117 goto done;
9120 TAILQ_FOREACH(pe, commitable_paths, entry) {
9121 struct got_commitable *ct = pe->data;
9122 dprintf(fd, "# %c %s\n",
9123 got_commitable_get_status(ct),
9124 got_commitable_get_path(ct));
9127 if (diff_path) {
9128 dprintf(fd, "# detailed changes can be viewed in %s\n",
9129 diff_path);
9132 if (close(fd) == -1) {
9133 err = got_error_from_errno2("close", a->logmsg_path);
9134 goto done;
9136 fd = -1;
9138 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9139 initial_content_len, a->prepared_log ? 0 : 1);
9140 done:
9141 free(initial_content);
9142 free(template);
9143 free(prepared_msg);
9144 free(merged_msg);
9146 if (fd != -1 && close(fd) == -1 && err == NULL)
9147 err = got_error_from_errno2("close", a->logmsg_path);
9149 /* Editor is done; we can now apply unveil(2) */
9150 if (err == NULL)
9151 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9152 if (err) {
9153 free(*logmsg);
9154 *logmsg = NULL;
9156 return err;
9159 static const struct got_error *
9160 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9161 const char *type, int has_content)
9163 const struct got_error *err = NULL;
9164 char *logmsg = NULL;
9166 err = got_object_commit_get_logmsg(&logmsg, commit);
9167 if (err)
9168 return err;
9170 if (fprintf(f, "%s# log message of %s commit %s:%s",
9171 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9172 err = got_ferror(f, GOT_ERR_IO);
9174 free(logmsg);
9175 return err;
9179 * Lookup "logmsg" references of backed-out and cherrypicked commits
9180 * belonging to the current work tree. If found, and the worktree has
9181 * at least one modified file that was changed in the referenced commit,
9182 * add its log message to a new temporary file at *logmsg_path.
9183 * Add all refs found to matched_refs to be scheduled for removal on
9184 * successful commit.
9186 static const struct got_error *
9187 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9188 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9189 struct got_repository *repo)
9191 const struct got_error *err;
9192 struct got_commit_object *commit = NULL;
9193 struct got_object_id *id = NULL;
9194 struct got_reflist_head refs;
9195 struct got_reflist_entry *re, *re_match;
9196 FILE *f = NULL;
9197 char *uuidstr = NULL;
9198 int added_logmsg = 0;
9200 TAILQ_INIT(&refs);
9202 *logmsg_path = NULL;
9204 err = got_worktree_get_uuid(&uuidstr, worktree);
9205 if (err)
9206 goto done;
9208 err = got_ref_list(&refs, repo, "refs/got/worktree",
9209 got_ref_cmp_by_name, repo);
9210 if (err)
9211 goto done;
9213 TAILQ_FOREACH(re, &refs, entry) {
9214 const char *refname, *type;
9215 struct wt_commitable_path_arg wcpa;
9216 int add_logmsg = 0;
9218 refname = got_ref_get_name(re->ref);
9220 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9221 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9222 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9223 type = "cherrypicked";
9224 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9225 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9226 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9227 type = "backed-out";
9228 } else
9229 continue;
9231 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9232 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9233 else
9234 continue;
9236 err = got_repo_match_object_id(&id, NULL, refname,
9237 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9238 if (err)
9239 goto done;
9241 err = got_object_open_as_commit(&commit, repo, id);
9242 if (err)
9243 goto done;
9245 wcpa.commit_paths = paths;
9246 wcpa.has_changes = &add_logmsg;
9248 err = commit_path_changed_in_worktree(&wcpa, id,
9249 worktree, repo);
9250 if (err)
9251 goto done;
9253 if (add_logmsg) {
9254 if (f == NULL) {
9255 err = got_opentemp_named(logmsg_path, &f,
9256 "got-commit-logmsg", "");
9257 if (err)
9258 goto done;
9260 err = cat_logmsg(f, commit, refname, type,
9261 added_logmsg);
9262 if (err)
9263 goto done;
9264 if (!added_logmsg)
9265 ++added_logmsg;
9267 err = got_reflist_entry_dup(&re_match, re);
9268 if (err)
9269 goto done;
9270 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9273 got_object_commit_close(commit);
9274 commit = NULL;
9275 free(id);
9276 id = NULL;
9279 done:
9280 free(id);
9281 free(uuidstr);
9282 got_ref_list_free(&refs);
9283 if (commit)
9284 got_object_commit_close(commit);
9285 if (f && fclose(f) == EOF && err == NULL)
9286 err = got_error_from_errno("fclose");
9287 if (!added_logmsg) {
9288 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9289 err = got_error_from_errno2("unlink", *logmsg_path);
9290 *logmsg_path = NULL;
9292 return err;
9295 static const struct got_error *
9296 cmd_commit(int argc, char *argv[])
9298 const struct got_error *error = NULL;
9299 struct got_worktree *worktree = NULL;
9300 struct got_repository *repo = NULL;
9301 char *cwd = NULL, *id_str = NULL;
9302 struct got_object_id *id = NULL;
9303 const char *logmsg = NULL;
9304 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9305 struct collect_commit_logmsg_arg cl_arg;
9306 const char *author = NULL;
9307 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9308 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9309 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9310 int show_diff = 1, commit_conflicts = 0;
9311 struct got_pathlist_head paths;
9312 struct got_reflist_head refs;
9313 struct got_reflist_entry *re;
9314 int *pack_fds = NULL;
9316 TAILQ_INIT(&refs);
9317 TAILQ_INIT(&paths);
9318 cl_arg.logmsg_path = NULL;
9320 #ifndef PROFILE
9321 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9322 "unveil", NULL) == -1)
9323 err(1, "pledge");
9324 #endif
9326 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9327 switch (ch) {
9328 case 'A':
9329 author = optarg;
9330 error = valid_author(author);
9331 if (error)
9332 return error;
9333 break;
9334 case 'C':
9335 commit_conflicts = 1;
9336 break;
9337 case 'F':
9338 if (logmsg != NULL)
9339 option_conflict('F', 'm');
9340 prepared_logmsg = realpath(optarg, NULL);
9341 if (prepared_logmsg == NULL)
9342 return got_error_from_errno2("realpath",
9343 optarg);
9344 break;
9345 case 'm':
9346 if (prepared_logmsg)
9347 option_conflict('m', 'F');
9348 logmsg = optarg;
9349 break;
9350 case 'N':
9351 non_interactive = 1;
9352 break;
9353 case 'n':
9354 show_diff = 0;
9355 break;
9356 case 'S':
9357 allow_bad_symlinks = 1;
9358 break;
9359 default:
9360 usage_commit();
9361 /* NOTREACHED */
9365 argc -= optind;
9366 argv += optind;
9368 cwd = getcwd(NULL, 0);
9369 if (cwd == NULL) {
9370 error = got_error_from_errno("getcwd");
9371 goto done;
9374 error = got_repo_pack_fds_open(&pack_fds);
9375 if (error != NULL)
9376 goto done;
9378 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9379 if (error) {
9380 if (error->code == GOT_ERR_NOT_WORKTREE)
9381 error = wrap_not_worktree_error(error, "commit", cwd);
9382 goto done;
9385 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9386 if (error)
9387 goto done;
9388 if (rebase_in_progress) {
9389 error = got_error(GOT_ERR_REBASING);
9390 goto done;
9393 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9394 worktree);
9395 if (error)
9396 goto done;
9398 error = get_gitconfig_path(&gitconfig_path);
9399 if (error)
9400 goto done;
9401 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9402 gitconfig_path, pack_fds);
9403 if (error != NULL)
9404 goto done;
9406 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9407 if (error)
9408 goto done;
9409 if (merge_in_progress) {
9410 error = got_error(GOT_ERR_MERGE_BUSY);
9411 goto done;
9414 error = get_author(&committer, repo, worktree);
9415 if (error)
9416 goto done;
9418 if (author == NULL)
9419 author = committer;
9422 * unveil(2) traverses exec(2); if an editor is used we have
9423 * to apply unveil after the log message has been written.
9425 if (logmsg == NULL || strlen(logmsg) == 0)
9426 error = get_editor(&editor);
9427 else
9428 error = apply_unveil(got_repo_get_path(repo), 0,
9429 got_worktree_get_root_path(worktree));
9430 if (error)
9431 goto done;
9433 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9434 if (error)
9435 goto done;
9437 if (prepared_logmsg == NULL) {
9438 error = lookup_logmsg_ref(&merged_logmsg,
9439 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9440 if (error)
9441 goto done;
9444 cl_arg.editor = editor;
9445 cl_arg.cmdline_log = logmsg;
9446 cl_arg.prepared_log = prepared_logmsg;
9447 cl_arg.merged_log = merged_logmsg;
9448 cl_arg.non_interactive = non_interactive;
9449 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9450 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9451 if (!histedit_in_progress) {
9452 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9453 error = got_error(GOT_ERR_COMMIT_BRANCH);
9454 goto done;
9456 cl_arg.branch_name += 11;
9458 cl_arg.repo_path = got_repo_get_path(repo);
9459 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9460 allow_bad_symlinks, show_diff, commit_conflicts,
9461 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9462 if (error) {
9463 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9464 cl_arg.logmsg_path != NULL)
9465 preserve_logmsg = 1;
9466 goto done;
9469 error = got_object_id_str(&id_str, id);
9470 if (error)
9471 goto done;
9472 printf("Created commit %s\n", id_str);
9474 TAILQ_FOREACH(re, &refs, entry) {
9475 error = got_ref_delete(re->ref, repo);
9476 if (error)
9477 goto done;
9480 done:
9481 if (preserve_logmsg) {
9482 fprintf(stderr, "%s: log message preserved in %s\n",
9483 getprogname(), cl_arg.logmsg_path);
9484 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9485 error == NULL)
9486 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9487 free(cl_arg.logmsg_path);
9488 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9489 error = got_error_from_errno2("unlink", merged_logmsg);
9490 free(merged_logmsg);
9491 if (repo) {
9492 const struct got_error *close_err = got_repo_close(repo);
9493 if (error == NULL)
9494 error = close_err;
9496 if (worktree)
9497 got_worktree_close(worktree);
9498 if (pack_fds) {
9499 const struct got_error *pack_err =
9500 got_repo_pack_fds_close(pack_fds);
9501 if (error == NULL)
9502 error = pack_err;
9504 got_ref_list_free(&refs);
9505 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9506 free(cwd);
9507 free(id_str);
9508 free(gitconfig_path);
9509 free(editor);
9510 free(committer);
9511 free(prepared_logmsg);
9512 return error;
9515 __dead static void
9516 usage_send(void)
9518 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9519 "[-r repository-path] [-t tag] [remote-repository]\n",
9520 getprogname());
9521 exit(1);
9524 static void
9525 print_load_info(int print_colored, int print_found, int print_trees,
9526 int ncolored, int nfound, int ntrees)
9528 if (print_colored) {
9529 printf("%d commit%s colored", ncolored,
9530 ncolored == 1 ? "" : "s");
9532 if (print_found) {
9533 printf("%s%d object%s found",
9534 ncolored > 0 ? "; " : "",
9535 nfound, nfound == 1 ? "" : "s");
9537 if (print_trees) {
9538 printf("; %d tree%s scanned", ntrees,
9539 ntrees == 1 ? "" : "s");
9543 struct got_send_progress_arg {
9544 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9545 int verbosity;
9546 int last_ncolored;
9547 int last_nfound;
9548 int last_ntrees;
9549 int loading_done;
9550 int last_ncommits;
9551 int last_nobj_total;
9552 int last_p_deltify;
9553 int last_p_written;
9554 int last_p_sent;
9555 int printed_something;
9556 int sent_something;
9557 struct got_pathlist_head *delete_branches;
9560 static const struct got_error *
9561 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9562 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9563 int nobj_written, off_t bytes_sent, const char *refname,
9564 const char *errmsg, int success)
9566 struct got_send_progress_arg *a = arg;
9567 char scaled_packsize[FMT_SCALED_STRSIZE];
9568 char scaled_sent[FMT_SCALED_STRSIZE];
9569 int p_deltify = 0, p_written = 0, p_sent = 0;
9570 int print_colored = 0, print_found = 0, print_trees = 0;
9571 int print_searching = 0, print_total = 0;
9572 int print_deltify = 0, print_written = 0, print_sent = 0;
9574 if (a->verbosity < 0)
9575 return NULL;
9577 if (refname) {
9578 const char *status = success ? "accepted" : "rejected";
9580 if (success) {
9581 struct got_pathlist_entry *pe;
9582 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9583 const char *branchname = pe->path;
9584 if (got_path_cmp(branchname, refname,
9585 strlen(branchname), strlen(refname)) == 0) {
9586 status = "deleted";
9587 a->sent_something = 1;
9588 break;
9593 if (a->printed_something)
9594 putchar('\n');
9595 printf("Server has %s %s", status, refname);
9596 if (errmsg)
9597 printf(": %s", errmsg);
9598 a->printed_something = 1;
9599 return NULL;
9602 if (a->last_ncolored != ncolored) {
9603 print_colored = 1;
9604 a->last_ncolored = ncolored;
9607 if (a->last_nfound != nfound) {
9608 print_colored = 1;
9609 print_found = 1;
9610 a->last_nfound = nfound;
9613 if (a->last_ntrees != ntrees) {
9614 print_colored = 1;
9615 print_found = 1;
9616 print_trees = 1;
9617 a->last_ntrees = ntrees;
9620 if ((print_colored || print_found || print_trees) &&
9621 !a->loading_done) {
9622 printf("\r");
9623 print_load_info(print_colored, print_found, print_trees,
9624 ncolored, nfound, ntrees);
9625 a->printed_something = 1;
9626 fflush(stdout);
9627 return NULL;
9628 } else if (!a->loading_done) {
9629 printf("\r");
9630 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9631 printf("\n");
9632 a->loading_done = 1;
9635 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9636 return got_error_from_errno("fmt_scaled");
9637 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9638 return got_error_from_errno("fmt_scaled");
9640 if (a->last_ncommits != ncommits) {
9641 print_searching = 1;
9642 a->last_ncommits = ncommits;
9645 if (a->last_nobj_total != nobj_total) {
9646 print_searching = 1;
9647 print_total = 1;
9648 a->last_nobj_total = nobj_total;
9651 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9652 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9653 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9654 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9655 return got_error(GOT_ERR_NO_SPACE);
9658 if (nobj_deltify > 0 || nobj_written > 0) {
9659 if (nobj_deltify > 0) {
9660 p_deltify = (nobj_deltify * 100) / nobj_total;
9661 if (p_deltify != a->last_p_deltify) {
9662 a->last_p_deltify = p_deltify;
9663 print_searching = 1;
9664 print_total = 1;
9665 print_deltify = 1;
9668 if (nobj_written > 0) {
9669 p_written = (nobj_written * 100) / nobj_total;
9670 if (p_written != a->last_p_written) {
9671 a->last_p_written = p_written;
9672 print_searching = 1;
9673 print_total = 1;
9674 print_deltify = 1;
9675 print_written = 1;
9680 if (bytes_sent > 0) {
9681 p_sent = (bytes_sent * 100) / packfile_size;
9682 if (p_sent != a->last_p_sent) {
9683 a->last_p_sent = p_sent;
9684 print_searching = 1;
9685 print_total = 1;
9686 print_deltify = 1;
9687 print_written = 1;
9688 print_sent = 1;
9690 a->sent_something = 1;
9693 if (print_searching || print_total || print_deltify || print_written ||
9694 print_sent)
9695 printf("\r");
9696 if (print_searching)
9697 printf("packing %d reference%s", ncommits,
9698 ncommits == 1 ? "" : "s");
9699 if (print_total)
9700 printf("; %d object%s", nobj_total,
9701 nobj_total == 1 ? "" : "s");
9702 if (print_deltify)
9703 printf("; deltify: %d%%", p_deltify);
9704 if (print_sent)
9705 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9706 scaled_packsize, p_sent);
9707 else if (print_written)
9708 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9709 scaled_packsize, p_written);
9710 if (print_searching || print_total || print_deltify ||
9711 print_written || print_sent) {
9712 a->printed_something = 1;
9713 fflush(stdout);
9715 return NULL;
9718 static const struct got_error *
9719 cmd_send(int argc, char *argv[])
9721 const struct got_error *error = NULL;
9722 char *cwd = NULL, *repo_path = NULL;
9723 const char *remote_name;
9724 char *proto = NULL, *host = NULL, *port = NULL;
9725 char *repo_name = NULL, *server_path = NULL;
9726 const struct got_remote_repo *remotes;
9727 struct got_remote_repo *remote = NULL;
9728 int nremotes, nbranches = 0, ndelete_branches = 0;
9729 struct got_repository *repo = NULL;
9730 struct got_worktree *worktree = NULL;
9731 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9732 struct got_pathlist_head branches;
9733 struct got_pathlist_head tags;
9734 struct got_reflist_head all_branches;
9735 struct got_reflist_head all_tags;
9736 struct got_pathlist_head delete_args;
9737 struct got_pathlist_head delete_branches;
9738 struct got_reflist_entry *re;
9739 struct got_pathlist_entry *pe;
9740 int i, ch, sendfd = -1, sendstatus;
9741 pid_t sendpid = -1;
9742 struct got_send_progress_arg spa;
9743 int verbosity = 0, overwrite_refs = 0;
9744 int send_all_branches = 0, send_all_tags = 0;
9745 struct got_reference *ref = NULL;
9746 int *pack_fds = NULL;
9748 TAILQ_INIT(&branches);
9749 TAILQ_INIT(&tags);
9750 TAILQ_INIT(&all_branches);
9751 TAILQ_INIT(&all_tags);
9752 TAILQ_INIT(&delete_args);
9753 TAILQ_INIT(&delete_branches);
9755 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9756 switch (ch) {
9757 case 'a':
9758 send_all_branches = 1;
9759 break;
9760 case 'b':
9761 error = got_pathlist_append(&branches, optarg, NULL);
9762 if (error)
9763 return error;
9764 nbranches++;
9765 break;
9766 case 'd':
9767 error = got_pathlist_append(&delete_args, optarg, NULL);
9768 if (error)
9769 return error;
9770 break;
9771 case 'f':
9772 overwrite_refs = 1;
9773 break;
9774 case 'q':
9775 verbosity = -1;
9776 break;
9777 case 'r':
9778 repo_path = realpath(optarg, NULL);
9779 if (repo_path == NULL)
9780 return got_error_from_errno2("realpath",
9781 optarg);
9782 got_path_strip_trailing_slashes(repo_path);
9783 break;
9784 case 'T':
9785 send_all_tags = 1;
9786 break;
9787 case 't':
9788 error = got_pathlist_append(&tags, optarg, NULL);
9789 if (error)
9790 return error;
9791 break;
9792 case 'v':
9793 if (verbosity < 0)
9794 verbosity = 0;
9795 else if (verbosity < 3)
9796 verbosity++;
9797 break;
9798 default:
9799 usage_send();
9800 /* NOTREACHED */
9803 argc -= optind;
9804 argv += optind;
9806 if (send_all_branches && !TAILQ_EMPTY(&branches))
9807 option_conflict('a', 'b');
9808 if (send_all_tags && !TAILQ_EMPTY(&tags))
9809 option_conflict('T', 't');
9812 if (argc == 0)
9813 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9814 else if (argc == 1)
9815 remote_name = argv[0];
9816 else
9817 usage_send();
9819 cwd = getcwd(NULL, 0);
9820 if (cwd == NULL) {
9821 error = got_error_from_errno("getcwd");
9822 goto done;
9825 error = got_repo_pack_fds_open(&pack_fds);
9826 if (error != NULL)
9827 goto done;
9829 if (repo_path == NULL) {
9830 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9831 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9832 goto done;
9833 else
9834 error = NULL;
9835 if (worktree) {
9836 repo_path =
9837 strdup(got_worktree_get_repo_path(worktree));
9838 if (repo_path == NULL)
9839 error = got_error_from_errno("strdup");
9840 if (error)
9841 goto done;
9842 } else {
9843 repo_path = strdup(cwd);
9844 if (repo_path == NULL) {
9845 error = got_error_from_errno("strdup");
9846 goto done;
9851 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9852 if (error)
9853 goto done;
9855 if (worktree) {
9856 worktree_conf = got_worktree_get_gotconfig(worktree);
9857 if (worktree_conf) {
9858 got_gotconfig_get_remotes(&nremotes, &remotes,
9859 worktree_conf);
9860 for (i = 0; i < nremotes; i++) {
9861 if (strcmp(remotes[i].name, remote_name) == 0) {
9862 error = got_repo_remote_repo_dup(&remote,
9863 &remotes[i]);
9864 if (error)
9865 goto done;
9866 break;
9871 if (remote == NULL) {
9872 repo_conf = got_repo_get_gotconfig(repo);
9873 if (repo_conf) {
9874 got_gotconfig_get_remotes(&nremotes, &remotes,
9875 repo_conf);
9876 for (i = 0; i < nremotes; i++) {
9877 if (strcmp(remotes[i].name, remote_name) == 0) {
9878 error = got_repo_remote_repo_dup(&remote,
9879 &remotes[i]);
9880 if (error)
9881 goto done;
9882 break;
9887 if (remote == NULL) {
9888 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9889 for (i = 0; i < nremotes; i++) {
9890 if (strcmp(remotes[i].name, remote_name) == 0) {
9891 error = got_repo_remote_repo_dup(&remote,
9892 &remotes[i]);
9893 if (error)
9894 goto done;
9895 break;
9899 if (remote == NULL) {
9900 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9901 goto done;
9904 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9905 &repo_name, remote->send_url);
9906 if (error)
9907 goto done;
9909 if (strcmp(proto, "git") == 0) {
9910 #ifndef PROFILE
9911 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9912 "sendfd dns inet unveil", NULL) == -1)
9913 err(1, "pledge");
9914 #endif
9915 } else if (strcmp(proto, "git+ssh") == 0 ||
9916 strcmp(proto, "ssh") == 0) {
9917 #ifndef PROFILE
9918 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9919 "sendfd unveil", NULL) == -1)
9920 err(1, "pledge");
9921 #endif
9922 } else if (strcmp(proto, "http") == 0 ||
9923 strcmp(proto, "git+http") == 0) {
9924 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9925 goto done;
9926 } else {
9927 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9928 goto done;
9931 error = got_dial_apply_unveil(proto);
9932 if (error)
9933 goto done;
9935 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9936 if (error)
9937 goto done;
9939 if (send_all_branches) {
9940 error = got_ref_list(&all_branches, repo, "refs/heads",
9941 got_ref_cmp_by_name, NULL);
9942 if (error)
9943 goto done;
9944 TAILQ_FOREACH(re, &all_branches, entry) {
9945 const char *branchname = got_ref_get_name(re->ref);
9946 error = got_pathlist_append(&branches,
9947 branchname, NULL);
9948 if (error)
9949 goto done;
9950 nbranches++;
9952 } else if (nbranches == 0) {
9953 for (i = 0; i < remote->nsend_branches; i++) {
9954 error = got_pathlist_append(&branches,
9955 remote->send_branches[i], NULL);
9956 if (error)
9957 goto done;
9961 if (send_all_tags) {
9962 error = got_ref_list(&all_tags, repo, "refs/tags",
9963 got_ref_cmp_by_name, NULL);
9964 if (error)
9965 goto done;
9966 TAILQ_FOREACH(re, &all_tags, entry) {
9967 const char *tagname = got_ref_get_name(re->ref);
9968 error = got_pathlist_append(&tags,
9969 tagname, NULL);
9970 if (error)
9971 goto done;
9976 * To prevent accidents only branches in refs/heads/ can be deleted
9977 * with 'got send -d'.
9978 * Deleting anything else requires local repository access or Git.
9980 TAILQ_FOREACH(pe, &delete_args, entry) {
9981 const char *branchname = pe->path;
9982 char *s;
9983 struct got_pathlist_entry *new;
9984 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9985 s = strdup(branchname);
9986 if (s == NULL) {
9987 error = got_error_from_errno("strdup");
9988 goto done;
9990 } else {
9991 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9992 error = got_error_from_errno("asprintf");
9993 goto done;
9996 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9997 if (error || new == NULL /* duplicate */)
9998 free(s);
9999 if (error)
10000 goto done;
10001 ndelete_branches++;
10004 if (nbranches == 0 && ndelete_branches == 0) {
10005 struct got_reference *head_ref;
10006 if (worktree)
10007 error = got_ref_open(&head_ref, repo,
10008 got_worktree_get_head_ref_name(worktree), 0);
10009 else
10010 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10011 if (error)
10012 goto done;
10013 if (got_ref_is_symbolic(head_ref)) {
10014 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10015 got_ref_close(head_ref);
10016 if (error)
10017 goto done;
10018 } else
10019 ref = head_ref;
10020 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10021 NULL);
10022 if (error)
10023 goto done;
10024 nbranches++;
10027 if (worktree) {
10028 /* Release work tree lock. */
10029 got_worktree_close(worktree);
10030 worktree = NULL;
10033 if (verbosity >= 0) {
10034 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10035 remote->name, proto, host,
10036 port ? ":" : "", port ? port : "",
10037 *server_path == '/' ? "" : "/", server_path);
10040 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10041 server_path, verbosity);
10042 if (error)
10043 goto done;
10045 memset(&spa, 0, sizeof(spa));
10046 spa.last_scaled_packsize[0] = '\0';
10047 spa.last_p_deltify = -1;
10048 spa.last_p_written = -1;
10049 spa.verbosity = verbosity;
10050 spa.delete_branches = &delete_branches;
10051 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10052 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10053 check_cancelled, NULL);
10054 if (spa.printed_something)
10055 putchar('\n');
10056 if (error)
10057 goto done;
10058 if (!spa.sent_something && verbosity >= 0)
10059 printf("Already up-to-date\n");
10060 done:
10061 if (sendpid > 0) {
10062 if (kill(sendpid, SIGTERM) == -1)
10063 error = got_error_from_errno("kill");
10064 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10065 error = got_error_from_errno("waitpid");
10067 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10068 error = got_error_from_errno("close");
10069 if (repo) {
10070 const struct got_error *close_err = got_repo_close(repo);
10071 if (error == NULL)
10072 error = close_err;
10074 if (worktree)
10075 got_worktree_close(worktree);
10076 if (pack_fds) {
10077 const struct got_error *pack_err =
10078 got_repo_pack_fds_close(pack_fds);
10079 if (error == NULL)
10080 error = pack_err;
10082 if (ref)
10083 got_ref_close(ref);
10084 got_repo_free_remote_repo_data(remote);
10085 free(remote);
10086 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10087 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10088 got_ref_list_free(&all_branches);
10089 got_ref_list_free(&all_tags);
10090 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10091 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10092 free(cwd);
10093 free(repo_path);
10094 free(proto);
10095 free(host);
10096 free(port);
10097 free(server_path);
10098 free(repo_name);
10099 return error;
10103 * Print and if delete is set delete all ref_prefix references.
10104 * If wanted_ref is not NULL, only print or delete this reference.
10106 static const struct got_error *
10107 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10108 const char *wanted_ref, int delete, struct got_worktree *worktree,
10109 struct got_repository *repo)
10111 const struct got_error *err;
10112 struct got_pathlist_head paths;
10113 struct got_reflist_head refs;
10114 struct got_reflist_entry *re;
10115 struct got_reflist_object_id_map *refs_idmap = NULL;
10116 struct got_commit_object *commit = NULL;
10117 struct got_object_id *id = NULL;
10118 const char *header_prefix;
10119 char *uuidstr = NULL;
10120 int found = 0;
10122 TAILQ_INIT(&refs);
10123 TAILQ_INIT(&paths);
10125 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10126 if (err)
10127 goto done;
10129 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10130 if (err)
10131 goto done;
10133 if (worktree != NULL) {
10134 err = got_worktree_get_uuid(&uuidstr, worktree);
10135 if (err)
10136 goto done;
10139 if (wanted_ref) {
10140 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10141 wanted_ref += 11;
10144 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10145 header_prefix = "backout";
10146 else
10147 header_prefix = "cherrypick";
10149 TAILQ_FOREACH(re, &refs, entry) {
10150 const char *refname, *wt;
10152 refname = got_ref_get_name(re->ref);
10154 err = check_cancelled(NULL);
10155 if (err)
10156 goto done;
10158 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10159 refname += prefix_len + 1; /* skip '-' delimiter */
10160 else
10161 continue;
10163 wt = refname;
10165 if (worktree == NULL || strncmp(refname, uuidstr,
10166 GOT_WORKTREE_UUID_STRLEN) == 0)
10167 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10168 else
10169 continue;
10171 err = got_repo_match_object_id(&id, NULL, refname,
10172 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10173 if (err)
10174 goto done;
10176 err = got_object_open_as_commit(&commit, repo, id);
10177 if (err)
10178 goto done;
10180 if (wanted_ref)
10181 found = strncmp(wanted_ref, refname,
10182 strlen(wanted_ref)) == 0;
10183 if (wanted_ref && !found) {
10184 struct got_reflist_head *ci_refs;
10186 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10187 id);
10189 if (ci_refs) {
10190 char *refs_str = NULL;
10191 char const *r = NULL;
10193 err = build_refs_str(&refs_str, ci_refs, id,
10194 repo, 1);
10195 if (err)
10196 goto done;
10198 r = refs_str;
10199 while (r) {
10200 if (strncmp(r, wanted_ref,
10201 strlen(wanted_ref)) == 0) {
10202 found = 1;
10203 break;
10205 r = strchr(r, ' ');
10206 if (r)
10207 ++r;
10209 free(refs_str);
10213 if (wanted_ref == NULL || found) {
10214 if (delete) {
10215 err = got_ref_delete(re->ref, repo);
10216 if (err)
10217 goto done;
10218 printf("Deleted: ");
10219 err = print_commit_oneline(commit, id, repo,
10220 refs_idmap);
10221 } else {
10223 * Print paths modified by commit to help
10224 * associate commits with worktree changes.
10226 err = get_changed_paths(&paths, commit,
10227 repo, NULL);
10228 if (err)
10229 goto done;
10231 err = print_commit(commit, id, repo, NULL,
10232 &paths, NULL, 0, 0, refs_idmap, NULL,
10233 header_prefix);
10234 got_pathlist_free(&paths,
10235 GOT_PATHLIST_FREE_ALL);
10237 if (worktree == NULL)
10238 printf("work tree: %.*s\n\n",
10239 GOT_WORKTREE_UUID_STRLEN, wt);
10241 if (err || found)
10242 goto done;
10245 got_object_commit_close(commit);
10246 commit = NULL;
10247 free(id);
10248 id = NULL;
10251 if (wanted_ref != NULL && !found)
10252 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10254 done:
10255 free(id);
10256 free(uuidstr);
10257 got_ref_list_free(&refs);
10258 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10259 if (refs_idmap)
10260 got_reflist_object_id_map_free(refs_idmap);
10261 if (commit)
10262 got_object_commit_close(commit);
10263 return err;
10267 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10268 * identified by id for log messages to prepopulate the editor on commit.
10270 static const struct got_error *
10271 logmsg_ref(struct got_object_id *id, const char *prefix,
10272 struct got_worktree *worktree, struct got_repository *repo)
10274 const struct got_error *err = NULL;
10275 char *idstr, *ref = NULL, *refname = NULL;
10276 int histedit_in_progress;
10277 int rebase_in_progress, merge_in_progress;
10280 * Silenty refuse to create merge reference if any histedit, merge,
10281 * or rebase operation is in progress.
10283 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10284 worktree);
10285 if (err)
10286 return err;
10287 if (histedit_in_progress)
10288 return NULL;
10290 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10291 if (err)
10292 return err;
10293 if (rebase_in_progress)
10294 return NULL;
10296 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10297 repo);
10298 if (err)
10299 return err;
10300 if (merge_in_progress)
10301 return NULL;
10303 err = got_object_id_str(&idstr, id);
10304 if (err)
10305 return err;
10307 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10308 if (err)
10309 goto done;
10311 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10312 err = got_error_from_errno("asprintf");
10313 goto done;
10316 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10317 -1, repo);
10318 done:
10319 free(ref);
10320 free(idstr);
10321 free(refname);
10322 return err;
10325 __dead static void
10326 usage_cherrypick(void)
10328 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10329 getprogname());
10330 exit(1);
10333 static const struct got_error *
10334 cmd_cherrypick(int argc, char *argv[])
10336 const struct got_error *error = NULL;
10337 struct got_worktree *worktree = NULL;
10338 struct got_repository *repo = NULL;
10339 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10340 struct got_object_id *commit_id = NULL;
10341 struct got_commit_object *commit = NULL;
10342 struct got_object_qid *pid;
10343 int ch, list_refs = 0, remove_refs = 0;
10344 struct got_update_progress_arg upa;
10345 int *pack_fds = NULL;
10347 #ifndef PROFILE
10348 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10349 "unveil", NULL) == -1)
10350 err(1, "pledge");
10351 #endif
10353 while ((ch = getopt(argc, argv, "lX")) != -1) {
10354 switch (ch) {
10355 case 'l':
10356 list_refs = 1;
10357 break;
10358 case 'X':
10359 remove_refs = 1;
10360 break;
10361 default:
10362 usage_cherrypick();
10363 /* NOTREACHED */
10367 argc -= optind;
10368 argv += optind;
10370 if (list_refs || remove_refs) {
10371 if (argc != 0 && argc != 1)
10372 usage_cherrypick();
10373 } else if (argc != 1)
10374 usage_cherrypick();
10375 if (list_refs && remove_refs)
10376 option_conflict('l', 'X');
10378 cwd = getcwd(NULL, 0);
10379 if (cwd == NULL) {
10380 error = got_error_from_errno("getcwd");
10381 goto done;
10384 error = got_repo_pack_fds_open(&pack_fds);
10385 if (error != NULL)
10386 goto done;
10388 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10389 if (error) {
10390 if (list_refs || remove_refs) {
10391 if (error->code != GOT_ERR_NOT_WORKTREE)
10392 goto done;
10393 } else {
10394 if (error->code == GOT_ERR_NOT_WORKTREE)
10395 error = wrap_not_worktree_error(error,
10396 "cherrypick", cwd);
10397 goto done;
10401 error = got_repo_open(&repo,
10402 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10403 NULL, pack_fds);
10404 if (error != NULL)
10405 goto done;
10407 error = apply_unveil(got_repo_get_path(repo), 0,
10408 worktree ? got_worktree_get_root_path(worktree) : NULL);
10409 if (error)
10410 goto done;
10412 if (list_refs || remove_refs) {
10413 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10414 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10415 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10416 goto done;
10419 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10420 if (error != NULL)
10421 goto done;
10423 error = got_repo_match_object_id(&commit_id, NULL,
10424 keyword_idstr != NULL ? keyword_idstr : argv[0],
10425 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10426 if (error)
10427 goto done;
10428 error = got_object_id_str(&commit_id_str, commit_id);
10429 if (error)
10430 goto done;
10432 error = got_object_open_as_commit(&commit, repo, commit_id);
10433 if (error)
10434 goto done;
10435 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10436 memset(&upa, 0, sizeof(upa));
10437 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10438 commit_id, repo, update_progress, &upa, check_cancelled,
10439 NULL);
10440 if (error != NULL)
10441 goto done;
10443 if (upa.did_something) {
10444 error = logmsg_ref(commit_id,
10445 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10446 if (error)
10447 goto done;
10448 printf("Merged commit %s\n", commit_id_str);
10450 print_merge_progress_stats(&upa);
10451 done:
10452 free(cwd);
10453 free(keyword_idstr);
10454 if (commit)
10455 got_object_commit_close(commit);
10456 free(commit_id_str);
10457 if (worktree)
10458 got_worktree_close(worktree);
10459 if (repo) {
10460 const struct got_error *close_err = got_repo_close(repo);
10461 if (error == NULL)
10462 error = close_err;
10464 if (pack_fds) {
10465 const struct got_error *pack_err =
10466 got_repo_pack_fds_close(pack_fds);
10467 if (error == NULL)
10468 error = pack_err;
10471 return error;
10474 __dead static void
10475 usage_backout(void)
10477 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10478 exit(1);
10481 static const struct got_error *
10482 cmd_backout(int argc, char *argv[])
10484 const struct got_error *error = NULL;
10485 struct got_worktree *worktree = NULL;
10486 struct got_repository *repo = NULL;
10487 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10488 struct got_object_id *commit_id = NULL;
10489 struct got_commit_object *commit = NULL;
10490 struct got_object_qid *pid;
10491 int ch, list_refs = 0, remove_refs = 0;
10492 struct got_update_progress_arg upa;
10493 int *pack_fds = NULL;
10495 #ifndef PROFILE
10496 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10497 "unveil", NULL) == -1)
10498 err(1, "pledge");
10499 #endif
10501 while ((ch = getopt(argc, argv, "lX")) != -1) {
10502 switch (ch) {
10503 case 'l':
10504 list_refs = 1;
10505 break;
10506 case 'X':
10507 remove_refs = 1;
10508 break;
10509 default:
10510 usage_backout();
10511 /* NOTREACHED */
10515 argc -= optind;
10516 argv += optind;
10518 if (list_refs || remove_refs) {
10519 if (argc != 0 && argc != 1)
10520 usage_backout();
10521 } else if (argc != 1)
10522 usage_backout();
10523 if (list_refs && remove_refs)
10524 option_conflict('l', 'X');
10526 cwd = getcwd(NULL, 0);
10527 if (cwd == NULL) {
10528 error = got_error_from_errno("getcwd");
10529 goto done;
10532 error = got_repo_pack_fds_open(&pack_fds);
10533 if (error != NULL)
10534 goto done;
10536 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10537 if (error) {
10538 if (list_refs || remove_refs) {
10539 if (error->code != GOT_ERR_NOT_WORKTREE)
10540 goto done;
10541 } else {
10542 if (error->code == GOT_ERR_NOT_WORKTREE)
10543 error = wrap_not_worktree_error(error,
10544 "backout", cwd);
10545 goto done;
10549 error = got_repo_open(&repo,
10550 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10551 NULL, pack_fds);
10552 if (error != NULL)
10553 goto done;
10555 error = apply_unveil(got_repo_get_path(repo), 0,
10556 worktree ? got_worktree_get_root_path(worktree) : NULL);
10557 if (error)
10558 goto done;
10560 if (list_refs || remove_refs) {
10561 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10562 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10563 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10564 goto done;
10567 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10568 if (error != NULL)
10569 goto done;
10571 error = got_repo_match_object_id(&commit_id, NULL,
10572 keyword_idstr != NULL ? keyword_idstr : argv[0],
10573 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10574 if (error)
10575 goto done;
10576 error = got_object_id_str(&commit_id_str, commit_id);
10577 if (error)
10578 goto done;
10580 error = got_object_open_as_commit(&commit, repo, commit_id);
10581 if (error)
10582 goto done;
10583 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10584 if (pid == NULL) {
10585 error = got_error(GOT_ERR_ROOT_COMMIT);
10586 goto done;
10589 memset(&upa, 0, sizeof(upa));
10590 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10591 repo, update_progress, &upa, check_cancelled, NULL);
10592 if (error != NULL)
10593 goto done;
10595 if (upa.did_something) {
10596 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10597 worktree, repo);
10598 if (error)
10599 goto done;
10600 printf("Backed out commit %s\n", commit_id_str);
10602 print_merge_progress_stats(&upa);
10603 done:
10604 free(cwd);
10605 free(keyword_idstr);
10606 if (commit)
10607 got_object_commit_close(commit);
10608 free(commit_id_str);
10609 if (worktree)
10610 got_worktree_close(worktree);
10611 if (repo) {
10612 const struct got_error *close_err = got_repo_close(repo);
10613 if (error == NULL)
10614 error = close_err;
10616 if (pack_fds) {
10617 const struct got_error *pack_err =
10618 got_repo_pack_fds_close(pack_fds);
10619 if (error == NULL)
10620 error = pack_err;
10622 return error;
10625 __dead static void
10626 usage_rebase(void)
10628 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10629 exit(1);
10632 static void
10633 trim_logmsg(char *logmsg, int limit)
10635 char *nl;
10636 size_t len;
10638 len = strlen(logmsg);
10639 if (len > limit)
10640 len = limit;
10641 logmsg[len] = '\0';
10642 nl = strchr(logmsg, '\n');
10643 if (nl)
10644 *nl = '\0';
10647 static const struct got_error *
10648 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10650 const struct got_error *err;
10651 char *logmsg0 = NULL;
10652 const char *s;
10654 err = got_object_commit_get_logmsg(&logmsg0, commit);
10655 if (err)
10656 return err;
10658 s = logmsg0;
10659 while (isspace((unsigned char)s[0]))
10660 s++;
10662 *logmsg = strdup(s);
10663 if (*logmsg == NULL) {
10664 err = got_error_from_errno("strdup");
10665 goto done;
10668 trim_logmsg(*logmsg, limit);
10669 done:
10670 free(logmsg0);
10671 return err;
10674 static const struct got_error *
10675 show_rebase_merge_conflict(struct got_object_id *id,
10676 struct got_repository *repo)
10678 const struct got_error *err;
10679 struct got_commit_object *commit = NULL;
10680 char *id_str = NULL, *logmsg = NULL;
10682 err = got_object_open_as_commit(&commit, repo, id);
10683 if (err)
10684 return err;
10686 err = got_object_id_str(&id_str, id);
10687 if (err)
10688 goto done;
10690 id_str[12] = '\0';
10692 err = get_short_logmsg(&logmsg, 42, commit);
10693 if (err)
10694 goto done;
10696 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10697 done:
10698 free(id_str);
10699 got_object_commit_close(commit);
10700 free(logmsg);
10701 return err;
10704 static const struct got_error *
10705 show_rebase_progress(struct got_commit_object *commit,
10706 struct got_object_id *old_id, struct got_object_id *new_id)
10708 const struct got_error *err;
10709 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10711 err = got_object_id_str(&old_id_str, old_id);
10712 if (err)
10713 goto done;
10715 if (new_id) {
10716 err = got_object_id_str(&new_id_str, new_id);
10717 if (err)
10718 goto done;
10721 old_id_str[12] = '\0';
10722 if (new_id_str)
10723 new_id_str[12] = '\0';
10725 err = get_short_logmsg(&logmsg, 42, commit);
10726 if (err)
10727 goto done;
10729 printf("%s -> %s: %s\n", old_id_str,
10730 new_id_str ? new_id_str : "no-op change", logmsg);
10731 done:
10732 free(old_id_str);
10733 free(new_id_str);
10734 free(logmsg);
10735 return err;
10738 static const struct got_error *
10739 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10740 struct got_reference *branch, struct got_reference *tmp_branch,
10741 struct got_repository *repo, int create_backup)
10743 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10744 return got_worktree_rebase_complete(worktree, fileindex,
10745 tmp_branch, branch, repo, create_backup);
10748 static const struct got_error *
10749 rebase_commit(struct got_pathlist_head *merged_paths,
10750 struct got_worktree *worktree, struct got_fileindex *fileindex,
10751 struct got_reference *tmp_branch, const char *committer,
10752 struct got_object_id *commit_id, int allow_conflict,
10753 struct got_repository *repo)
10755 const struct got_error *error;
10756 struct got_commit_object *commit;
10757 struct got_object_id *new_commit_id;
10759 error = got_object_open_as_commit(&commit, repo, commit_id);
10760 if (error)
10761 return error;
10763 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10764 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10765 allow_conflict, repo);
10766 if (error) {
10767 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10768 goto done;
10769 error = show_rebase_progress(commit, commit_id, NULL);
10770 } else {
10771 error = show_rebase_progress(commit, commit_id, new_commit_id);
10772 free(new_commit_id);
10774 done:
10775 got_object_commit_close(commit);
10776 return error;
10779 struct check_path_prefix_arg {
10780 const char *path_prefix;
10781 size_t len;
10782 int errcode;
10785 static const struct got_error *
10786 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10787 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10788 struct got_object_id *id1, struct got_object_id *id2,
10789 const char *path1, const char *path2,
10790 mode_t mode1, mode_t mode2, struct got_repository *repo)
10792 struct check_path_prefix_arg *a = arg;
10794 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10795 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10796 return got_error(a->errcode);
10798 return NULL;
10801 static const struct got_error *
10802 check_path_prefix(struct got_object_id *parent_id,
10803 struct got_object_id *commit_id, const char *path_prefix,
10804 int errcode, struct got_repository *repo)
10806 const struct got_error *err;
10807 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10808 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10809 struct check_path_prefix_arg cpp_arg;
10811 if (got_path_is_root_dir(path_prefix))
10812 return NULL;
10814 err = got_object_open_as_commit(&commit, repo, commit_id);
10815 if (err)
10816 goto done;
10818 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10819 if (err)
10820 goto done;
10822 err = got_object_open_as_tree(&tree1, repo,
10823 got_object_commit_get_tree_id(parent_commit));
10824 if (err)
10825 goto done;
10827 err = got_object_open_as_tree(&tree2, repo,
10828 got_object_commit_get_tree_id(commit));
10829 if (err)
10830 goto done;
10832 cpp_arg.path_prefix = path_prefix;
10833 while (cpp_arg.path_prefix[0] == '/')
10834 cpp_arg.path_prefix++;
10835 cpp_arg.len = strlen(cpp_arg.path_prefix);
10836 cpp_arg.errcode = errcode;
10837 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10838 check_path_prefix_in_diff, &cpp_arg, 0);
10839 done:
10840 if (tree1)
10841 got_object_tree_close(tree1);
10842 if (tree2)
10843 got_object_tree_close(tree2);
10844 if (commit)
10845 got_object_commit_close(commit);
10846 if (parent_commit)
10847 got_object_commit_close(parent_commit);
10848 return err;
10851 static const struct got_error *
10852 collect_commits(struct got_object_id_queue *commits,
10853 struct got_object_id *initial_commit_id,
10854 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10855 const char *path_prefix, int path_prefix_errcode,
10856 struct got_repository *repo)
10858 const struct got_error *err = NULL;
10859 struct got_commit_graph *graph = NULL;
10860 struct got_object_id parent_id, commit_id;
10861 struct got_object_qid *qid;
10863 err = got_commit_graph_open(&graph, "/", 1);
10864 if (err)
10865 return err;
10867 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10868 check_cancelled, NULL);
10869 if (err)
10870 goto done;
10872 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10873 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10874 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10875 check_cancelled, NULL);
10876 if (err) {
10877 if (err->code == GOT_ERR_ITER_COMPLETED) {
10878 err = got_error_msg(GOT_ERR_ANCESTRY,
10879 "ran out of commits to rebase before "
10880 "youngest common ancestor commit has "
10881 "been reached?!?");
10883 goto done;
10884 } else {
10885 err = check_path_prefix(&parent_id, &commit_id,
10886 path_prefix, path_prefix_errcode, repo);
10887 if (err)
10888 goto done;
10890 err = got_object_qid_alloc(&qid, &commit_id);
10891 if (err)
10892 goto done;
10893 STAILQ_INSERT_HEAD(commits, qid, entry);
10895 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10898 done:
10899 got_commit_graph_close(graph);
10900 return err;
10903 static const struct got_error *
10904 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10906 const struct got_error *err = NULL;
10907 time_t committer_time;
10908 struct tm tm;
10909 char datebuf[11]; /* YYYY-MM-DD + NUL */
10910 char *author0 = NULL, *author, *smallerthan;
10911 char *logmsg0 = NULL, *logmsg, *newline;
10913 committer_time = got_object_commit_get_committer_time(commit);
10914 if (gmtime_r(&committer_time, &tm) == NULL)
10915 return got_error_from_errno("gmtime_r");
10916 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10917 return got_error(GOT_ERR_NO_SPACE);
10919 author0 = strdup(got_object_commit_get_author(commit));
10920 if (author0 == NULL)
10921 return got_error_from_errno("strdup");
10922 author = author0;
10923 smallerthan = strchr(author, '<');
10924 if (smallerthan && smallerthan[1] != '\0')
10925 author = smallerthan + 1;
10926 author[strcspn(author, "@>")] = '\0';
10928 err = got_object_commit_get_logmsg(&logmsg0, commit);
10929 if (err)
10930 goto done;
10931 logmsg = logmsg0;
10932 while (*logmsg == '\n')
10933 logmsg++;
10934 newline = strchr(logmsg, '\n');
10935 if (newline)
10936 *newline = '\0';
10938 if (asprintf(brief_str, "%s %s %s",
10939 datebuf, author, logmsg) == -1)
10940 err = got_error_from_errno("asprintf");
10941 done:
10942 free(author0);
10943 free(logmsg0);
10944 return err;
10947 static const struct got_error *
10948 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10949 struct got_repository *repo)
10951 const struct got_error *err;
10952 char *id_str;
10954 err = got_object_id_str(&id_str, id);
10955 if (err)
10956 return err;
10958 err = got_ref_delete(ref, repo);
10959 if (err)
10960 goto done;
10962 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10963 done:
10964 free(id_str);
10965 return err;
10968 static const struct got_error *
10969 print_backup_ref(const char *branch_name, const char *new_id_str,
10970 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10971 struct got_reflist_object_id_map *refs_idmap,
10972 struct got_repository *repo)
10974 const struct got_error *err = NULL;
10975 struct got_reflist_head *refs;
10976 char *refs_str = NULL;
10977 struct got_object_id *new_commit_id = NULL;
10978 struct got_commit_object *new_commit = NULL;
10979 char *new_commit_brief_str = NULL;
10980 struct got_object_id *yca_id = NULL;
10981 struct got_commit_object *yca_commit = NULL;
10982 char *yca_id_str = NULL, *yca_brief_str = NULL;
10983 char *custom_refs_str;
10985 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10986 return got_error_from_errno("asprintf");
10988 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10989 0, 0, refs_idmap, custom_refs_str, NULL);
10990 if (err)
10991 goto done;
10993 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10994 if (err)
10995 goto done;
10997 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10998 if (refs) {
10999 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11000 if (err)
11001 goto done;
11004 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11005 if (err)
11006 goto done;
11008 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11009 if (err)
11010 goto done;
11012 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11013 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
11014 if (err)
11015 goto done;
11017 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11018 refs_str ? " (" : "", refs_str ? refs_str : "",
11019 refs_str ? ")" : "", new_commit_brief_str);
11020 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11021 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11022 free(refs_str);
11023 refs_str = NULL;
11025 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11026 if (err)
11027 goto done;
11029 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11030 if (err)
11031 goto done;
11033 err = got_object_id_str(&yca_id_str, yca_id);
11034 if (err)
11035 goto done;
11037 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11038 if (refs) {
11039 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11040 if (err)
11041 goto done;
11043 printf("history forked at %s%s%s%s\n %s\n",
11044 yca_id_str,
11045 refs_str ? " (" : "", refs_str ? refs_str : "",
11046 refs_str ? ")" : "", yca_brief_str);
11048 done:
11049 free(custom_refs_str);
11050 free(new_commit_id);
11051 free(refs_str);
11052 free(yca_id);
11053 free(yca_id_str);
11054 free(yca_brief_str);
11055 if (new_commit)
11056 got_object_commit_close(new_commit);
11057 if (yca_commit)
11058 got_object_commit_close(yca_commit);
11060 return err;
11063 static const struct got_error *
11064 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11065 struct got_repository *repo)
11067 const struct got_error *err;
11068 struct got_reflist_head refs;
11069 struct got_reflist_entry *re;
11070 char *uuidstr = NULL;
11071 static char msg[160];
11073 TAILQ_INIT(&refs);
11075 err = got_worktree_get_uuid(&uuidstr, worktree);
11076 if (err)
11077 goto done;
11079 err = got_ref_list(&refs, repo, "refs/got/worktree",
11080 got_ref_cmp_by_name, repo);
11081 if (err)
11082 goto done;
11084 TAILQ_FOREACH(re, &refs, entry) {
11085 const char *cmd, *refname, *type;
11087 refname = got_ref_get_name(re->ref);
11089 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11090 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11091 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11092 cmd = "cherrypick";
11093 type = "cherrypicked";
11094 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11095 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11096 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11097 cmd = "backout";
11098 type = "backed-out";
11099 } else
11100 continue;
11102 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11103 continue;
11105 snprintf(msg, sizeof(msg),
11106 "work tree has references created by %s commits which "
11107 "must be removed with 'got %s -X' before running the %s "
11108 "command", type, cmd, caller);
11109 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11110 goto done;
11113 done:
11114 free(uuidstr);
11115 got_ref_list_free(&refs);
11116 return err;
11119 static const struct got_error *
11120 process_backup_refs(const char *backup_ref_prefix,
11121 const char *wanted_branch_name,
11122 int delete, struct got_repository *repo)
11124 const struct got_error *err;
11125 struct got_reflist_head refs, backup_refs;
11126 struct got_reflist_entry *re;
11127 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11128 struct got_object_id *old_commit_id = NULL;
11129 char *branch_name = NULL;
11130 struct got_commit_object *old_commit = NULL;
11131 struct got_reflist_object_id_map *refs_idmap = NULL;
11132 int wanted_branch_found = 0;
11134 TAILQ_INIT(&refs);
11135 TAILQ_INIT(&backup_refs);
11137 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11138 if (err)
11139 return err;
11141 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11142 if (err)
11143 goto done;
11145 if (wanted_branch_name) {
11146 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11147 wanted_branch_name += 11;
11150 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11151 got_ref_cmp_by_commit_timestamp_descending, repo);
11152 if (err)
11153 goto done;
11155 TAILQ_FOREACH(re, &backup_refs, entry) {
11156 const char *refname = got_ref_get_name(re->ref);
11157 char *slash;
11159 err = check_cancelled(NULL);
11160 if (err)
11161 break;
11163 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11164 if (err)
11165 break;
11167 err = got_object_open_as_commit(&old_commit, repo,
11168 old_commit_id);
11169 if (err)
11170 break;
11172 if (strncmp(backup_ref_prefix, refname,
11173 backup_ref_prefix_len) == 0)
11174 refname += backup_ref_prefix_len;
11176 while (refname[0] == '/')
11177 refname++;
11179 branch_name = strdup(refname);
11180 if (branch_name == NULL) {
11181 err = got_error_from_errno("strdup");
11182 break;
11184 slash = strrchr(branch_name, '/');
11185 if (slash) {
11186 *slash = '\0';
11187 refname += strlen(branch_name) + 1;
11190 if (wanted_branch_name == NULL ||
11191 strcmp(wanted_branch_name, branch_name) == 0) {
11192 wanted_branch_found = 1;
11193 if (delete) {
11194 err = delete_backup_ref(re->ref,
11195 old_commit_id, repo);
11196 } else {
11197 err = print_backup_ref(branch_name, refname,
11198 old_commit_id, old_commit, refs_idmap,
11199 repo);
11201 if (err)
11202 break;
11205 free(old_commit_id);
11206 old_commit_id = NULL;
11207 free(branch_name);
11208 branch_name = NULL;
11209 got_object_commit_close(old_commit);
11210 old_commit = NULL;
11213 if (wanted_branch_name && !wanted_branch_found) {
11214 err = got_error_fmt(GOT_ERR_NOT_REF,
11215 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11217 done:
11218 if (refs_idmap)
11219 got_reflist_object_id_map_free(refs_idmap);
11220 got_ref_list_free(&refs);
11221 got_ref_list_free(&backup_refs);
11222 free(old_commit_id);
11223 free(branch_name);
11224 if (old_commit)
11225 got_object_commit_close(old_commit);
11226 return err;
11229 static const struct got_error *
11230 abort_progress(void *arg, unsigned char status, const char *path)
11233 * Unversioned files should not clutter progress output when
11234 * an operation is aborted.
11236 if (status == GOT_STATUS_UNVERSIONED)
11237 return NULL;
11239 return update_progress(arg, status, path);
11242 static const struct got_error *
11243 cmd_rebase(int argc, char *argv[])
11245 const struct got_error *error = NULL;
11246 struct got_worktree *worktree = NULL;
11247 struct got_repository *repo = NULL;
11248 struct got_fileindex *fileindex = NULL;
11249 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11250 struct got_reference *branch = NULL;
11251 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11252 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11253 struct got_object_id *resume_commit_id = NULL;
11254 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11255 struct got_object_id *head_commit_id = NULL;
11256 struct got_reference *head_ref = NULL;
11257 struct got_commit_object *commit = NULL;
11258 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11259 int histedit_in_progress = 0, merge_in_progress = 0;
11260 int create_backup = 1, list_backups = 0, delete_backups = 0;
11261 int allow_conflict = 0;
11262 struct got_object_id_queue commits;
11263 struct got_pathlist_head merged_paths;
11264 const struct got_object_id_queue *parent_ids;
11265 struct got_object_qid *qid, *pid;
11266 struct got_update_progress_arg upa;
11267 int *pack_fds = NULL;
11269 STAILQ_INIT(&commits);
11270 TAILQ_INIT(&merged_paths);
11271 memset(&upa, 0, sizeof(upa));
11273 #ifndef PROFILE
11274 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11275 "unveil", NULL) == -1)
11276 err(1, "pledge");
11277 #endif
11279 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11280 switch (ch) {
11281 case 'a':
11282 abort_rebase = 1;
11283 break;
11284 case 'C':
11285 allow_conflict = 1;
11286 break;
11287 case 'c':
11288 continue_rebase = 1;
11289 break;
11290 case 'l':
11291 list_backups = 1;
11292 break;
11293 case 'X':
11294 delete_backups = 1;
11295 break;
11296 default:
11297 usage_rebase();
11298 /* NOTREACHED */
11302 argc -= optind;
11303 argv += optind;
11305 if (list_backups) {
11306 if (abort_rebase)
11307 option_conflict('l', 'a');
11308 if (allow_conflict)
11309 option_conflict('l', 'C');
11310 if (continue_rebase)
11311 option_conflict('l', 'c');
11312 if (delete_backups)
11313 option_conflict('l', 'X');
11314 if (argc != 0 && argc != 1)
11315 usage_rebase();
11316 } else if (delete_backups) {
11317 if (abort_rebase)
11318 option_conflict('X', 'a');
11319 if (allow_conflict)
11320 option_conflict('X', 'C');
11321 if (continue_rebase)
11322 option_conflict('X', 'c');
11323 if (list_backups)
11324 option_conflict('l', 'X');
11325 if (argc != 0 && argc != 1)
11326 usage_rebase();
11327 } else if (allow_conflict) {
11328 if (abort_rebase)
11329 option_conflict('C', 'a');
11330 if (!continue_rebase)
11331 errx(1, "-C option requires -c");
11332 } else {
11333 if (abort_rebase && continue_rebase)
11334 usage_rebase();
11335 else if (abort_rebase || continue_rebase) {
11336 if (argc != 0)
11337 usage_rebase();
11338 } else if (argc != 1)
11339 usage_rebase();
11342 cwd = getcwd(NULL, 0);
11343 if (cwd == NULL) {
11344 error = got_error_from_errno("getcwd");
11345 goto done;
11348 error = got_repo_pack_fds_open(&pack_fds);
11349 if (error != NULL)
11350 goto done;
11352 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11353 if (error) {
11354 if (list_backups || delete_backups) {
11355 if (error->code != GOT_ERR_NOT_WORKTREE)
11356 goto done;
11357 } else {
11358 if (error->code == GOT_ERR_NOT_WORKTREE)
11359 error = wrap_not_worktree_error(error,
11360 "rebase", cwd);
11361 goto done;
11365 error = get_gitconfig_path(&gitconfig_path);
11366 if (error)
11367 goto done;
11368 error = got_repo_open(&repo,
11369 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11370 gitconfig_path, pack_fds);
11371 if (error != NULL)
11372 goto done;
11374 if (worktree != NULL && !list_backups && !delete_backups) {
11375 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11376 if (error)
11377 goto done;
11380 error = get_author(&committer, repo, worktree);
11381 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11382 goto done;
11384 error = apply_unveil(got_repo_get_path(repo), 0,
11385 worktree ? got_worktree_get_root_path(worktree) : NULL);
11386 if (error)
11387 goto done;
11389 if (list_backups || delete_backups) {
11390 error = process_backup_refs(
11391 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11392 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11393 goto done; /* nothing else to do */
11396 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11397 worktree);
11398 if (error)
11399 goto done;
11400 if (histedit_in_progress) {
11401 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11402 goto done;
11405 error = got_worktree_merge_in_progress(&merge_in_progress,
11406 worktree, repo);
11407 if (error)
11408 goto done;
11409 if (merge_in_progress) {
11410 error = got_error(GOT_ERR_MERGE_BUSY);
11411 goto done;
11414 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11415 if (error)
11416 goto done;
11418 if (abort_rebase) {
11419 if (!rebase_in_progress) {
11420 error = got_error(GOT_ERR_NOT_REBASING);
11421 goto done;
11423 error = got_worktree_rebase_continue(&resume_commit_id,
11424 &new_base_branch, &tmp_branch, &branch, &fileindex,
11425 worktree, repo);
11426 if (error)
11427 goto done;
11428 printf("Switching work tree to %s\n",
11429 got_ref_get_symref_target(new_base_branch));
11430 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11431 new_base_branch, abort_progress, &upa);
11432 if (error)
11433 goto done;
11434 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11435 print_merge_progress_stats(&upa);
11436 goto done; /* nothing else to do */
11439 if (continue_rebase) {
11440 if (!rebase_in_progress) {
11441 error = got_error(GOT_ERR_NOT_REBASING);
11442 goto done;
11444 error = got_worktree_rebase_continue(&resume_commit_id,
11445 &new_base_branch, &tmp_branch, &branch, &fileindex,
11446 worktree, repo);
11447 if (error)
11448 goto done;
11450 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11451 committer, resume_commit_id, allow_conflict, repo);
11452 if (error)
11453 goto done;
11455 yca_id = got_object_id_dup(resume_commit_id);
11456 if (yca_id == NULL) {
11457 error = got_error_from_errno("got_object_id_dup");
11458 goto done;
11460 } else {
11461 error = got_ref_open(&branch, repo, argv[0], 0);
11462 if (error != NULL)
11463 goto done;
11464 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11465 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11466 "will not rebase a branch which lives outside "
11467 "the \"refs/heads/\" reference namespace");
11468 goto done;
11472 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11473 if (error)
11474 goto done;
11476 if (!continue_rebase) {
11477 struct got_object_id *base_commit_id;
11479 error = got_ref_open(&head_ref, repo,
11480 got_worktree_get_head_ref_name(worktree), 0);
11481 if (error)
11482 goto done;
11483 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11484 if (error)
11485 goto done;
11486 base_commit_id = got_worktree_get_base_commit_id(worktree);
11487 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11488 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11489 goto done;
11492 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11493 base_commit_id, branch_head_commit_id, 1, repo,
11494 check_cancelled, NULL);
11495 if (error) {
11496 if (error->code == GOT_ERR_ANCESTRY) {
11497 error = got_error_msg(GOT_ERR_ANCESTRY,
11498 "specified branch shares no common "
11499 "ancestry with work tree's branch");
11501 goto done;
11504 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11505 struct got_pathlist_head paths;
11506 printf("%s is already based on %s\n",
11507 got_ref_get_name(branch),
11508 got_worktree_get_head_ref_name(worktree));
11509 error = switch_head_ref(branch, branch_head_commit_id,
11510 worktree, repo);
11511 if (error)
11512 goto done;
11513 error = got_worktree_set_base_commit_id(worktree, repo,
11514 branch_head_commit_id);
11515 if (error)
11516 goto done;
11517 TAILQ_INIT(&paths);
11518 error = got_pathlist_append(&paths, "", NULL);
11519 if (error)
11520 goto done;
11521 error = got_worktree_checkout_files(worktree,
11522 &paths, repo, update_progress, &upa,
11523 check_cancelled, NULL);
11524 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11525 if (error)
11526 goto done;
11527 if (upa.did_something) {
11528 char *id_str;
11529 error = got_object_id_str(&id_str,
11530 branch_head_commit_id);
11531 if (error)
11532 goto done;
11533 printf("Updated to %s: %s\n",
11534 got_worktree_get_head_ref_name(worktree),
11535 id_str);
11536 free(id_str);
11537 } else
11538 printf("Already up-to-date\n");
11539 print_update_progress_stats(&upa);
11540 goto done;
11544 commit_id = branch_head_commit_id;
11545 error = got_object_open_as_commit(&commit, repo, commit_id);
11546 if (error)
11547 goto done;
11549 parent_ids = got_object_commit_get_parent_ids(commit);
11550 pid = STAILQ_FIRST(parent_ids);
11551 if (pid) {
11552 error = collect_commits(&commits, commit_id, &pid->id,
11553 yca_id, got_worktree_get_path_prefix(worktree),
11554 GOT_ERR_REBASE_PATH, repo);
11555 if (error)
11556 goto done;
11559 got_object_commit_close(commit);
11560 commit = NULL;
11562 if (!continue_rebase) {
11563 error = got_worktree_rebase_prepare(&new_base_branch,
11564 &tmp_branch, &fileindex, worktree, branch, repo);
11565 if (error)
11566 goto done;
11569 if (STAILQ_EMPTY(&commits)) {
11570 if (continue_rebase) {
11571 error = rebase_complete(worktree, fileindex,
11572 branch, tmp_branch, repo, create_backup);
11573 goto done;
11574 } else {
11575 /* Fast-forward the reference of the branch. */
11576 struct got_object_id *new_head_commit_id;
11577 char *id_str;
11578 error = got_ref_resolve(&new_head_commit_id, repo,
11579 new_base_branch);
11580 if (error)
11581 goto done;
11582 error = got_object_id_str(&id_str, new_head_commit_id);
11583 if (error)
11584 goto done;
11585 printf("Forwarding %s to commit %s\n",
11586 got_ref_get_name(branch), id_str);
11587 free(id_str);
11588 error = got_ref_change_ref(branch,
11589 new_head_commit_id);
11590 if (error)
11591 goto done;
11592 /* No backup needed since objects did not change. */
11593 create_backup = 0;
11597 pid = NULL;
11598 STAILQ_FOREACH(qid, &commits, entry) {
11600 commit_id = &qid->id;
11601 parent_id = pid ? &pid->id : yca_id;
11602 pid = qid;
11604 memset(&upa, 0, sizeof(upa));
11605 error = got_worktree_rebase_merge_files(&merged_paths,
11606 worktree, fileindex, parent_id, commit_id, repo,
11607 update_progress, &upa, check_cancelled, NULL);
11608 if (error)
11609 goto done;
11611 print_merge_progress_stats(&upa);
11612 if (upa.conflicts > 0 || upa.missing > 0 ||
11613 upa.not_deleted > 0 || upa.unversioned > 0) {
11614 if (upa.conflicts > 0) {
11615 error = show_rebase_merge_conflict(&qid->id,
11616 repo);
11617 if (error)
11618 goto done;
11620 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11621 break;
11624 error = rebase_commit(&merged_paths, worktree, fileindex,
11625 tmp_branch, committer, commit_id, 0, repo);
11626 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11627 if (error)
11628 goto done;
11631 if (upa.conflicts > 0 || upa.missing > 0 ||
11632 upa.not_deleted > 0 || upa.unversioned > 0) {
11633 error = got_worktree_rebase_postpone(worktree, fileindex);
11634 if (error)
11635 goto done;
11636 if (upa.conflicts > 0 && upa.missing == 0 &&
11637 upa.not_deleted == 0 && upa.unversioned == 0) {
11638 error = got_error_msg(GOT_ERR_CONFLICTS,
11639 "conflicts must be resolved before rebasing "
11640 "can continue");
11641 } else if (upa.conflicts > 0) {
11642 error = got_error_msg(GOT_ERR_CONFLICTS,
11643 "conflicts must be resolved before rebasing "
11644 "can continue; changes destined for some "
11645 "files were not yet merged and should be "
11646 "merged manually if required before the "
11647 "rebase operation is continued");
11648 } else {
11649 error = got_error_msg(GOT_ERR_CONFLICTS,
11650 "changes destined for some files were not "
11651 "yet merged and should be merged manually "
11652 "if required before the rebase operation "
11653 "is continued");
11655 } else
11656 error = rebase_complete(worktree, fileindex, branch,
11657 tmp_branch, repo, create_backup);
11658 done:
11659 free(cwd);
11660 free(committer);
11661 free(gitconfig_path);
11662 got_object_id_queue_free(&commits);
11663 free(branch_head_commit_id);
11664 free(resume_commit_id);
11665 free(head_commit_id);
11666 free(yca_id);
11667 if (commit)
11668 got_object_commit_close(commit);
11669 if (branch)
11670 got_ref_close(branch);
11671 if (new_base_branch)
11672 got_ref_close(new_base_branch);
11673 if (tmp_branch)
11674 got_ref_close(tmp_branch);
11675 if (head_ref)
11676 got_ref_close(head_ref);
11677 if (worktree)
11678 got_worktree_close(worktree);
11679 if (repo) {
11680 const struct got_error *close_err = got_repo_close(repo);
11681 if (error == NULL)
11682 error = close_err;
11684 if (pack_fds) {
11685 const struct got_error *pack_err =
11686 got_repo_pack_fds_close(pack_fds);
11687 if (error == NULL)
11688 error = pack_err;
11690 return error;
11693 __dead static void
11694 usage_histedit(void)
11696 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11697 "[branch]\n", getprogname());
11698 exit(1);
11701 #define GOT_HISTEDIT_PICK 'p'
11702 #define GOT_HISTEDIT_EDIT 'e'
11703 #define GOT_HISTEDIT_FOLD 'f'
11704 #define GOT_HISTEDIT_DROP 'd'
11705 #define GOT_HISTEDIT_MESG 'm'
11707 static const struct got_histedit_cmd {
11708 unsigned char code;
11709 const char *name;
11710 const char *desc;
11711 } got_histedit_cmds[] = {
11712 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11713 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11714 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11715 "be used" },
11716 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11717 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11720 struct got_histedit_list_entry {
11721 TAILQ_ENTRY(got_histedit_list_entry) entry;
11722 struct got_object_id *commit_id;
11723 const struct got_histedit_cmd *cmd;
11724 char *logmsg;
11726 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11728 static const struct got_error *
11729 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11730 FILE *f, struct got_repository *repo)
11732 const struct got_error *err = NULL;
11733 char *logmsg = NULL, *id_str = NULL;
11734 struct got_commit_object *commit = NULL;
11735 int n;
11737 err = got_object_open_as_commit(&commit, repo, commit_id);
11738 if (err)
11739 goto done;
11741 err = get_short_logmsg(&logmsg, 34, commit);
11742 if (err)
11743 goto done;
11745 err = got_object_id_str(&id_str, commit_id);
11746 if (err)
11747 goto done;
11749 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11750 if (n < 0)
11751 err = got_ferror(f, GOT_ERR_IO);
11752 done:
11753 if (commit)
11754 got_object_commit_close(commit);
11755 free(id_str);
11756 free(logmsg);
11757 return err;
11760 static const struct got_error *
11761 histedit_write_commit_list(struct got_object_id_queue *commits,
11762 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11763 int edit_only, struct got_repository *repo)
11765 const struct got_error *err = NULL;
11766 struct got_object_qid *qid;
11767 const char *histedit_cmd = NULL;
11769 if (STAILQ_EMPTY(commits))
11770 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11772 STAILQ_FOREACH(qid, commits, entry) {
11773 histedit_cmd = got_histedit_cmds[0].name;
11774 if (drop_only)
11775 histedit_cmd = "drop";
11776 else if (edit_only)
11777 histedit_cmd = "edit";
11778 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11779 histedit_cmd = "fold";
11780 else if (edit_logmsg_only)
11781 histedit_cmd = "mesg";
11782 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11783 if (err)
11784 break;
11787 return err;
11790 static const struct got_error *
11791 write_cmd_list(FILE *f, const char *branch_name,
11792 struct got_object_id_queue *commits)
11794 const struct got_error *err = NULL;
11795 size_t i;
11796 int n;
11797 char *id_str;
11798 struct got_object_qid *qid;
11800 qid = STAILQ_FIRST(commits);
11801 err = got_object_id_str(&id_str, &qid->id);
11802 if (err)
11803 return err;
11805 n = fprintf(f,
11806 "# Editing the history of branch '%s' starting at\n"
11807 "# commit %s\n"
11808 "# Commits will be processed in order from top to "
11809 "bottom of this file.\n", branch_name, id_str);
11810 if (n < 0) {
11811 err = got_ferror(f, GOT_ERR_IO);
11812 goto done;
11815 n = fprintf(f, "# Available histedit commands:\n");
11816 if (n < 0) {
11817 err = got_ferror(f, GOT_ERR_IO);
11818 goto done;
11821 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11822 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11823 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11824 cmd->desc);
11825 if (n < 0) {
11826 err = got_ferror(f, GOT_ERR_IO);
11827 break;
11830 done:
11831 free(id_str);
11832 return err;
11835 static const struct got_error *
11836 histedit_syntax_error(int lineno)
11838 static char msg[42];
11839 int ret;
11841 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11842 lineno);
11843 if (ret < 0 || (size_t)ret >= sizeof(msg))
11844 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11846 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11849 static const struct got_error *
11850 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11851 char *logmsg, struct got_repository *repo)
11853 const struct got_error *err;
11854 struct got_commit_object *folded_commit = NULL;
11855 char *id_str, *folded_logmsg = NULL;
11857 err = got_object_id_str(&id_str, hle->commit_id);
11858 if (err)
11859 return err;
11861 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11862 if (err)
11863 goto done;
11865 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11866 if (err)
11867 goto done;
11868 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11869 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11870 folded_logmsg) == -1) {
11871 err = got_error_from_errno("asprintf");
11873 done:
11874 if (folded_commit)
11875 got_object_commit_close(folded_commit);
11876 free(id_str);
11877 free(folded_logmsg);
11878 return err;
11881 static struct got_histedit_list_entry *
11882 get_folded_commits(struct got_histedit_list_entry *hle)
11884 struct got_histedit_list_entry *prev, *folded = NULL;
11886 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11887 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11888 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11889 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11890 folded = prev;
11891 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11894 return folded;
11897 static const struct got_error *
11898 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11899 struct got_repository *repo)
11901 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11902 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11903 const struct got_error *err = NULL;
11904 struct got_commit_object *commit = NULL;
11905 int logmsg_len;
11906 int fd = -1;
11907 struct got_histedit_list_entry *folded = NULL;
11909 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11910 if (err)
11911 return err;
11913 folded = get_folded_commits(hle);
11914 if (folded) {
11915 while (folded != hle) {
11916 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11917 folded = TAILQ_NEXT(folded, entry);
11918 continue;
11920 err = append_folded_commit_msg(&new_msg, folded,
11921 logmsg, repo);
11922 if (err)
11923 goto done;
11924 free(logmsg);
11925 logmsg = new_msg;
11926 folded = TAILQ_NEXT(folded, entry);
11930 err = got_object_id_str(&id_str, hle->commit_id);
11931 if (err)
11932 goto done;
11933 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11934 if (err)
11935 goto done;
11936 logmsg_len = asprintf(&new_msg,
11937 "%s\n# original log message of commit %s: %s",
11938 logmsg ? logmsg : "", id_str, orig_logmsg);
11939 if (logmsg_len == -1) {
11940 err = got_error_from_errno("asprintf");
11941 goto done;
11943 free(logmsg);
11944 logmsg = new_msg;
11946 err = got_object_id_str(&id_str, hle->commit_id);
11947 if (err)
11948 goto done;
11950 err = got_opentemp_named_fd(&logmsg_path, &fd,
11951 GOT_TMPDIR_STR "/got-logmsg", "");
11952 if (err)
11953 goto done;
11955 if (write(fd, logmsg, logmsg_len) == -1) {
11956 err = got_error_from_errno2("write", logmsg_path);
11957 goto done;
11959 if (close(fd) == -1) {
11960 err = got_error_from_errno2("close", logmsg_path);
11961 goto done;
11963 fd = -1;
11965 err = get_editor(&editor);
11966 if (err)
11967 goto done;
11969 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11970 logmsg_len, 0);
11971 if (err) {
11972 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11973 goto done;
11974 err = NULL;
11975 hle->logmsg = strdup(new_msg);
11976 if (hle->logmsg == NULL)
11977 err = got_error_from_errno("strdup");
11979 done:
11980 if (fd != -1 && close(fd) == -1 && err == NULL)
11981 err = got_error_from_errno2("close", logmsg_path);
11982 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11983 err = got_error_from_errno2("unlink", logmsg_path);
11984 free(logmsg_path);
11985 free(logmsg);
11986 free(orig_logmsg);
11987 free(editor);
11988 if (commit)
11989 got_object_commit_close(commit);
11990 return err;
11993 static const struct got_error *
11994 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11995 FILE *f, struct got_repository *repo)
11997 const struct got_error *err = NULL;
11998 char *line = NULL, *p, *end;
11999 size_t i, linesize = 0;
12000 ssize_t linelen;
12001 int lineno = 0;
12002 const struct got_histedit_cmd *cmd;
12003 struct got_object_id *commit_id = NULL;
12004 struct got_histedit_list_entry *hle = NULL;
12006 for (;;) {
12007 linelen = getline(&line, &linesize, f);
12008 if (linelen == -1) {
12009 const struct got_error *getline_err;
12010 if (feof(f))
12011 break;
12012 getline_err = got_error_from_errno("getline");
12013 err = got_ferror(f, getline_err->code);
12014 break;
12016 lineno++;
12017 p = line;
12018 while (isspace((unsigned char)p[0]))
12019 p++;
12020 if (p[0] == '#' || p[0] == '\0')
12021 continue;
12022 cmd = NULL;
12023 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12024 cmd = &got_histedit_cmds[i];
12025 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12026 isspace((unsigned char)p[strlen(cmd->name)])) {
12027 p += strlen(cmd->name);
12028 break;
12030 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12031 p++;
12032 break;
12035 if (i == nitems(got_histedit_cmds)) {
12036 err = histedit_syntax_error(lineno);
12037 break;
12039 while (isspace((unsigned char)p[0]))
12040 p++;
12041 end = p;
12042 while (end[0] && !isspace((unsigned char)end[0]))
12043 end++;
12044 *end = '\0';
12045 err = got_object_resolve_id_str(&commit_id, repo, p);
12046 if (err) {
12047 /* override error code */
12048 err = histedit_syntax_error(lineno);
12049 break;
12051 hle = malloc(sizeof(*hle));
12052 if (hle == NULL) {
12053 err = got_error_from_errno("malloc");
12054 break;
12056 hle->cmd = cmd;
12057 hle->commit_id = commit_id;
12058 hle->logmsg = NULL;
12059 commit_id = NULL;
12060 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12063 free(line);
12064 free(commit_id);
12065 return err;
12068 static const struct got_error *
12069 histedit_check_script(struct got_histedit_list *histedit_cmds,
12070 struct got_object_id_queue *commits, struct got_repository *repo)
12072 const struct got_error *err = NULL;
12073 struct got_object_qid *qid;
12074 struct got_histedit_list_entry *hle;
12075 static char msg[92];
12076 char *id_str;
12078 if (TAILQ_EMPTY(histedit_cmds))
12079 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12080 "histedit script contains no commands");
12081 if (STAILQ_EMPTY(commits))
12082 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12084 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12085 struct got_histedit_list_entry *hle2;
12086 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12087 if (hle == hle2)
12088 continue;
12089 if (got_object_id_cmp(hle->commit_id,
12090 hle2->commit_id) != 0)
12091 continue;
12092 err = got_object_id_str(&id_str, hle->commit_id);
12093 if (err)
12094 return err;
12095 snprintf(msg, sizeof(msg), "commit %s is listed "
12096 "more than once in histedit script", id_str);
12097 free(id_str);
12098 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12102 STAILQ_FOREACH(qid, commits, entry) {
12103 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12104 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12105 break;
12107 if (hle == NULL) {
12108 err = got_object_id_str(&id_str, &qid->id);
12109 if (err)
12110 return err;
12111 snprintf(msg, sizeof(msg),
12112 "commit %s missing from histedit script", id_str);
12113 free(id_str);
12114 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12118 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12119 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12120 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12121 "last commit in histedit script cannot be folded");
12123 return NULL;
12126 static const struct got_error *
12127 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12128 const char *path, struct got_object_id_queue *commits,
12129 struct got_repository *repo)
12131 const struct got_error *err = NULL;
12132 struct stat st, st2;
12133 struct timespec timeout;
12134 char *editor;
12135 FILE *f = NULL;
12137 err = get_editor(&editor);
12138 if (err)
12139 return err;
12141 if (stat(path, &st) == -1) {
12142 err = got_error_from_errno2("stat", path);
12143 goto done;
12146 if (spawn_editor(editor, path) == -1) {
12147 err = got_error_from_errno("failed spawning editor");
12148 goto done;
12151 timeout.tv_sec = 0;
12152 timeout.tv_nsec = 1;
12153 nanosleep(&timeout, NULL);
12155 if (stat(path, &st2) == -1) {
12156 err = got_error_from_errno2("stat", path);
12157 goto done;
12160 if (st.st_size == st2.st_size &&
12161 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12162 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12163 "no changes made to histedit script, aborting");
12164 goto done;
12167 f = fopen(path, "re");
12168 if (f == NULL) {
12169 err = got_error_from_errno("fopen");
12170 goto done;
12172 err = histedit_parse_list(histedit_cmds, f, repo);
12173 if (err)
12174 goto done;
12176 err = histedit_check_script(histedit_cmds, commits, repo);
12177 done:
12178 if (f && fclose(f) == EOF && err == NULL)
12179 err = got_error_from_errno("fclose");
12180 free(editor);
12181 return err;
12184 static const struct got_error *
12185 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12186 struct got_object_id_queue *, const char *, const char *,
12187 struct got_repository *);
12189 static const struct got_error *
12190 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12191 struct got_object_id_queue *commits, const char *branch_name,
12192 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12193 struct got_repository *repo)
12195 const struct got_error *err;
12196 FILE *f = NULL;
12197 char *path = NULL;
12199 err = got_opentemp_named(&path, &f, "got-histedit", "");
12200 if (err)
12201 return err;
12203 err = write_cmd_list(f, branch_name, commits);
12204 if (err)
12205 goto done;
12207 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12208 fold_only, drop_only, edit_only, repo);
12209 if (err)
12210 goto done;
12212 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12213 rewind(f);
12214 err = histedit_parse_list(histedit_cmds, f, repo);
12215 } else {
12216 if (fclose(f) == EOF) {
12217 err = got_error_from_errno("fclose");
12218 goto done;
12220 f = NULL;
12221 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12222 if (err) {
12223 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12224 err->code != GOT_ERR_HISTEDIT_CMD)
12225 goto done;
12226 err = histedit_edit_list_retry(histedit_cmds, err,
12227 commits, path, branch_name, repo);
12230 done:
12231 if (f && fclose(f) == EOF && err == NULL)
12232 err = got_error_from_errno("fclose");
12233 if (path && unlink(path) != 0 && err == NULL)
12234 err = got_error_from_errno2("unlink", path);
12235 free(path);
12236 return err;
12239 static const struct got_error *
12240 histedit_save_list(struct got_histedit_list *histedit_cmds,
12241 struct got_worktree *worktree, struct got_repository *repo)
12243 const struct got_error *err = NULL;
12244 char *path = NULL;
12245 FILE *f = NULL;
12246 struct got_histedit_list_entry *hle;
12248 err = got_worktree_get_histedit_script_path(&path, worktree);
12249 if (err)
12250 return err;
12252 f = fopen(path, "we");
12253 if (f == NULL) {
12254 err = got_error_from_errno2("fopen", path);
12255 goto done;
12257 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12258 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12259 repo);
12260 if (err)
12261 break;
12263 done:
12264 if (f && fclose(f) == EOF && err == NULL)
12265 err = got_error_from_errno("fclose");
12266 free(path);
12267 return err;
12270 static void
12271 histedit_free_list(struct got_histedit_list *histedit_cmds)
12273 struct got_histedit_list_entry *hle;
12275 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12276 TAILQ_REMOVE(histedit_cmds, hle, entry);
12277 free(hle);
12281 static const struct got_error *
12282 histedit_load_list(struct got_histedit_list *histedit_cmds,
12283 const char *path, struct got_repository *repo)
12285 const struct got_error *err = NULL;
12286 FILE *f = NULL;
12288 f = fopen(path, "re");
12289 if (f == NULL) {
12290 err = got_error_from_errno2("fopen", path);
12291 goto done;
12294 err = histedit_parse_list(histedit_cmds, f, repo);
12295 done:
12296 if (f && fclose(f) == EOF && err == NULL)
12297 err = got_error_from_errno("fclose");
12298 return err;
12301 static const struct got_error *
12302 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12303 const struct got_error *edit_err, struct got_object_id_queue *commits,
12304 const char *path, const char *branch_name, struct got_repository *repo)
12306 const struct got_error *err = NULL, *prev_err = edit_err;
12307 int resp = ' ';
12309 while (resp != 'c' && resp != 'r' && resp != 'a') {
12310 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12311 "or (a)bort: ", getprogname(), prev_err->msg);
12312 resp = getchar();
12313 if (resp == '\n')
12314 resp = getchar();
12315 if (resp == 'c') {
12316 histedit_free_list(histedit_cmds);
12317 err = histedit_run_editor(histedit_cmds, path, commits,
12318 repo);
12319 if (err) {
12320 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12321 err->code != GOT_ERR_HISTEDIT_CMD)
12322 break;
12323 prev_err = err;
12324 resp = ' ';
12325 continue;
12327 break;
12328 } else if (resp == 'r') {
12329 histedit_free_list(histedit_cmds);
12330 err = histedit_edit_script(histedit_cmds,
12331 commits, branch_name, 0, 0, 0, 0, repo);
12332 if (err) {
12333 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12334 err->code != GOT_ERR_HISTEDIT_CMD)
12335 break;
12336 prev_err = err;
12337 resp = ' ';
12338 continue;
12340 break;
12341 } else if (resp == 'a') {
12342 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12343 break;
12344 } else
12345 printf("invalid response '%c'\n", resp);
12348 return err;
12351 static const struct got_error *
12352 histedit_complete(struct got_worktree *worktree,
12353 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12354 struct got_reference *branch, struct got_repository *repo)
12356 printf("Switching work tree to %s\n",
12357 got_ref_get_symref_target(branch));
12358 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12359 branch, repo);
12362 static const struct got_error *
12363 show_histedit_progress(struct got_commit_object *commit,
12364 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12366 const struct got_error *err;
12367 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12369 err = got_object_id_str(&old_id_str, hle->commit_id);
12370 if (err)
12371 goto done;
12373 if (new_id) {
12374 err = got_object_id_str(&new_id_str, new_id);
12375 if (err)
12376 goto done;
12379 old_id_str[12] = '\0';
12380 if (new_id_str)
12381 new_id_str[12] = '\0';
12383 if (hle->logmsg) {
12384 logmsg = strdup(hle->logmsg);
12385 if (logmsg == NULL) {
12386 err = got_error_from_errno("strdup");
12387 goto done;
12389 trim_logmsg(logmsg, 42);
12390 } else {
12391 err = get_short_logmsg(&logmsg, 42, commit);
12392 if (err)
12393 goto done;
12396 switch (hle->cmd->code) {
12397 case GOT_HISTEDIT_PICK:
12398 case GOT_HISTEDIT_EDIT:
12399 case GOT_HISTEDIT_MESG:
12400 printf("%s -> %s: %s\n", old_id_str,
12401 new_id_str ? new_id_str : "no-op change", logmsg);
12402 break;
12403 case GOT_HISTEDIT_DROP:
12404 case GOT_HISTEDIT_FOLD:
12405 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12406 logmsg);
12407 break;
12408 default:
12409 break;
12411 done:
12412 free(old_id_str);
12413 free(new_id_str);
12414 return err;
12417 static const struct got_error *
12418 histedit_commit(struct got_pathlist_head *merged_paths,
12419 struct got_worktree *worktree, struct got_fileindex *fileindex,
12420 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12421 const char *committer, int allow_conflict, struct got_repository *repo)
12423 const struct got_error *err;
12424 struct got_commit_object *commit;
12425 struct got_object_id *new_commit_id;
12427 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12428 && hle->logmsg == NULL) {
12429 err = histedit_edit_logmsg(hle, repo);
12430 if (err)
12431 return err;
12434 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12435 if (err)
12436 return err;
12438 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12439 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12440 hle->logmsg, allow_conflict, repo);
12441 if (err) {
12442 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12443 goto done;
12444 err = show_histedit_progress(commit, hle, NULL);
12445 } else {
12446 err = show_histedit_progress(commit, hle, new_commit_id);
12447 free(new_commit_id);
12449 done:
12450 got_object_commit_close(commit);
12451 return err;
12454 static const struct got_error *
12455 histedit_skip_commit(struct got_histedit_list_entry *hle,
12456 struct got_worktree *worktree, struct got_repository *repo)
12458 const struct got_error *error;
12459 struct got_commit_object *commit;
12461 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12462 repo);
12463 if (error)
12464 return error;
12466 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12467 if (error)
12468 return error;
12470 error = show_histedit_progress(commit, hle, NULL);
12471 got_object_commit_close(commit);
12472 return error;
12475 static const struct got_error *
12476 check_local_changes(void *arg, unsigned char status,
12477 unsigned char staged_status, const char *path,
12478 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12479 struct got_object_id *commit_id, int dirfd, const char *de_name)
12481 int *have_local_changes = arg;
12483 switch (status) {
12484 case GOT_STATUS_ADD:
12485 case GOT_STATUS_DELETE:
12486 case GOT_STATUS_MODIFY:
12487 case GOT_STATUS_CONFLICT:
12488 *have_local_changes = 1;
12489 return got_error(GOT_ERR_CANCELLED);
12490 default:
12491 break;
12494 switch (staged_status) {
12495 case GOT_STATUS_ADD:
12496 case GOT_STATUS_DELETE:
12497 case GOT_STATUS_MODIFY:
12498 *have_local_changes = 1;
12499 return got_error(GOT_ERR_CANCELLED);
12500 default:
12501 break;
12504 return NULL;
12507 static const struct got_error *
12508 cmd_histedit(int argc, char *argv[])
12510 const struct got_error *error = NULL;
12511 struct got_worktree *worktree = NULL;
12512 struct got_fileindex *fileindex = NULL;
12513 struct got_repository *repo = NULL;
12514 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12515 struct got_reference *branch = NULL;
12516 struct got_reference *tmp_branch = NULL;
12517 struct got_object_id *resume_commit_id = NULL;
12518 struct got_object_id *base_commit_id = NULL;
12519 struct got_object_id *head_commit_id = NULL;
12520 struct got_commit_object *commit = NULL;
12521 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12522 struct got_update_progress_arg upa;
12523 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12524 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12525 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12526 const char *edit_script_path = NULL;
12527 struct got_object_id_queue commits;
12528 struct got_pathlist_head merged_paths;
12529 const struct got_object_id_queue *parent_ids;
12530 struct got_object_qid *pid;
12531 struct got_histedit_list histedit_cmds;
12532 struct got_histedit_list_entry *hle;
12533 int *pack_fds = NULL;
12535 STAILQ_INIT(&commits);
12536 TAILQ_INIT(&histedit_cmds);
12537 TAILQ_INIT(&merged_paths);
12538 memset(&upa, 0, sizeof(upa));
12540 #ifndef PROFILE
12541 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12542 "unveil", NULL) == -1)
12543 err(1, "pledge");
12544 #endif
12546 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12547 switch (ch) {
12548 case 'a':
12549 abort_edit = 1;
12550 break;
12551 case 'C':
12552 allow_conflict = 1;
12553 break;
12554 case 'c':
12555 continue_edit = 1;
12556 break;
12557 case 'd':
12558 drop_only = 1;
12559 break;
12560 case 'e':
12561 edit_only = 1;
12562 break;
12563 case 'F':
12564 edit_script_path = optarg;
12565 break;
12566 case 'f':
12567 fold_only = 1;
12568 break;
12569 case 'l':
12570 list_backups = 1;
12571 break;
12572 case 'm':
12573 edit_logmsg_only = 1;
12574 break;
12575 case 'X':
12576 delete_backups = 1;
12577 break;
12578 default:
12579 usage_histedit();
12580 /* NOTREACHED */
12584 argc -= optind;
12585 argv += optind;
12587 if (abort_edit && allow_conflict)
12588 option_conflict('a', 'C');
12589 if (abort_edit && continue_edit)
12590 option_conflict('a', 'c');
12591 if (edit_script_path && allow_conflict)
12592 option_conflict('F', 'C');
12593 if (edit_script_path && edit_logmsg_only)
12594 option_conflict('F', 'm');
12595 if (abort_edit && edit_logmsg_only)
12596 option_conflict('a', 'm');
12597 if (edit_logmsg_only && allow_conflict)
12598 option_conflict('m', 'C');
12599 if (continue_edit && edit_logmsg_only)
12600 option_conflict('c', 'm');
12601 if (abort_edit && fold_only)
12602 option_conflict('a', 'f');
12603 if (fold_only && allow_conflict)
12604 option_conflict('f', 'C');
12605 if (continue_edit && fold_only)
12606 option_conflict('c', 'f');
12607 if (fold_only && edit_logmsg_only)
12608 option_conflict('f', 'm');
12609 if (edit_script_path && fold_only)
12610 option_conflict('F', 'f');
12611 if (abort_edit && edit_only)
12612 option_conflict('a', 'e');
12613 if (continue_edit && edit_only)
12614 option_conflict('c', 'e');
12615 if (edit_only && edit_logmsg_only)
12616 option_conflict('e', 'm');
12617 if (edit_script_path && edit_only)
12618 option_conflict('F', 'e');
12619 if (fold_only && edit_only)
12620 option_conflict('f', 'e');
12621 if (drop_only && abort_edit)
12622 option_conflict('d', 'a');
12623 if (drop_only && allow_conflict)
12624 option_conflict('d', 'C');
12625 if (drop_only && continue_edit)
12626 option_conflict('d', 'c');
12627 if (drop_only && edit_logmsg_only)
12628 option_conflict('d', 'm');
12629 if (drop_only && edit_only)
12630 option_conflict('d', 'e');
12631 if (drop_only && edit_script_path)
12632 option_conflict('d', 'F');
12633 if (drop_only && fold_only)
12634 option_conflict('d', 'f');
12635 if (list_backups) {
12636 if (abort_edit)
12637 option_conflict('l', 'a');
12638 if (allow_conflict)
12639 option_conflict('l', 'C');
12640 if (continue_edit)
12641 option_conflict('l', 'c');
12642 if (edit_script_path)
12643 option_conflict('l', 'F');
12644 if (edit_logmsg_only)
12645 option_conflict('l', 'm');
12646 if (drop_only)
12647 option_conflict('l', 'd');
12648 if (fold_only)
12649 option_conflict('l', 'f');
12650 if (edit_only)
12651 option_conflict('l', 'e');
12652 if (delete_backups)
12653 option_conflict('l', 'X');
12654 if (argc != 0 && argc != 1)
12655 usage_histedit();
12656 } else if (delete_backups) {
12657 if (abort_edit)
12658 option_conflict('X', 'a');
12659 if (allow_conflict)
12660 option_conflict('X', 'C');
12661 if (continue_edit)
12662 option_conflict('X', 'c');
12663 if (drop_only)
12664 option_conflict('X', 'd');
12665 if (edit_script_path)
12666 option_conflict('X', 'F');
12667 if (edit_logmsg_only)
12668 option_conflict('X', 'm');
12669 if (fold_only)
12670 option_conflict('X', 'f');
12671 if (edit_only)
12672 option_conflict('X', 'e');
12673 if (list_backups)
12674 option_conflict('X', 'l');
12675 if (argc != 0 && argc != 1)
12676 usage_histedit();
12677 } else if (allow_conflict && !continue_edit)
12678 errx(1, "-C option requires -c");
12679 else if (argc != 0)
12680 usage_histedit();
12683 * This command cannot apply unveil(2) in all cases because the
12684 * user may choose to run an editor to edit the histedit script
12685 * and to edit individual commit log messages.
12686 * unveil(2) traverses exec(2); if an editor is used we have to
12687 * apply unveil after edit script and log messages have been written.
12688 * XXX TODO: Make use of unveil(2) where possible.
12691 cwd = getcwd(NULL, 0);
12692 if (cwd == NULL) {
12693 error = got_error_from_errno("getcwd");
12694 goto done;
12697 error = got_repo_pack_fds_open(&pack_fds);
12698 if (error != NULL)
12699 goto done;
12701 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12702 if (error) {
12703 if (list_backups || delete_backups) {
12704 if (error->code != GOT_ERR_NOT_WORKTREE)
12705 goto done;
12706 } else {
12707 if (error->code == GOT_ERR_NOT_WORKTREE)
12708 error = wrap_not_worktree_error(error,
12709 "histedit", cwd);
12710 goto done;
12714 if (list_backups || delete_backups) {
12715 error = got_repo_open(&repo,
12716 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12717 NULL, pack_fds);
12718 if (error != NULL)
12719 goto done;
12720 error = apply_unveil(got_repo_get_path(repo), 0,
12721 worktree ? got_worktree_get_root_path(worktree) : NULL);
12722 if (error)
12723 goto done;
12724 error = process_backup_refs(
12725 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12726 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12727 goto done; /* nothing else to do */
12730 error = get_gitconfig_path(&gitconfig_path);
12731 if (error)
12732 goto done;
12733 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12734 gitconfig_path, pack_fds);
12735 if (error != NULL)
12736 goto done;
12738 if (worktree != NULL && !list_backups && !delete_backups) {
12739 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12740 if (error)
12741 goto done;
12744 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12745 if (error)
12746 goto done;
12747 if (rebase_in_progress) {
12748 error = got_error(GOT_ERR_REBASING);
12749 goto done;
12752 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12753 repo);
12754 if (error)
12755 goto done;
12756 if (merge_in_progress) {
12757 error = got_error(GOT_ERR_MERGE_BUSY);
12758 goto done;
12761 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12762 if (error)
12763 goto done;
12765 if (edit_in_progress && edit_logmsg_only) {
12766 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12767 "histedit operation is in progress in this "
12768 "work tree and must be continued or aborted "
12769 "before the -m option can be used");
12770 goto done;
12772 if (edit_in_progress && drop_only) {
12773 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12774 "histedit operation is in progress in this "
12775 "work tree and must be continued or aborted "
12776 "before the -d option can be used");
12777 goto done;
12779 if (edit_in_progress && fold_only) {
12780 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12781 "histedit operation is in progress in this "
12782 "work tree and must be continued or aborted "
12783 "before the -f option can be used");
12784 goto done;
12786 if (edit_in_progress && edit_only) {
12787 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12788 "histedit operation is in progress in this "
12789 "work tree and must be continued or aborted "
12790 "before the -e option can be used");
12791 goto done;
12794 if (edit_in_progress && abort_edit) {
12795 error = got_worktree_histedit_continue(&resume_commit_id,
12796 &tmp_branch, &branch, &base_commit_id, &fileindex,
12797 worktree, repo);
12798 if (error)
12799 goto done;
12800 printf("Switching work tree to %s\n",
12801 got_ref_get_symref_target(branch));
12802 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12803 branch, base_commit_id, abort_progress, &upa);
12804 if (error)
12805 goto done;
12806 printf("Histedit of %s aborted\n",
12807 got_ref_get_symref_target(branch));
12808 print_merge_progress_stats(&upa);
12809 goto done; /* nothing else to do */
12810 } else if (abort_edit) {
12811 error = got_error(GOT_ERR_NOT_HISTEDIT);
12812 goto done;
12815 error = get_author(&committer, repo, worktree);
12816 if (error)
12817 goto done;
12819 if (continue_edit) {
12820 char *path;
12822 if (!edit_in_progress) {
12823 error = got_error(GOT_ERR_NOT_HISTEDIT);
12824 goto done;
12827 error = got_worktree_get_histedit_script_path(&path, worktree);
12828 if (error)
12829 goto done;
12831 error = histedit_load_list(&histedit_cmds, path, repo);
12832 free(path);
12833 if (error)
12834 goto done;
12836 error = got_worktree_histedit_continue(&resume_commit_id,
12837 &tmp_branch, &branch, &base_commit_id, &fileindex,
12838 worktree, repo);
12839 if (error)
12840 goto done;
12842 error = got_ref_resolve(&head_commit_id, repo, branch);
12843 if (error)
12844 goto done;
12846 error = got_object_open_as_commit(&commit, repo,
12847 head_commit_id);
12848 if (error)
12849 goto done;
12850 parent_ids = got_object_commit_get_parent_ids(commit);
12851 pid = STAILQ_FIRST(parent_ids);
12852 if (pid == NULL) {
12853 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12854 goto done;
12856 error = collect_commits(&commits, head_commit_id, &pid->id,
12857 base_commit_id, got_worktree_get_path_prefix(worktree),
12858 GOT_ERR_HISTEDIT_PATH, repo);
12859 got_object_commit_close(commit);
12860 commit = NULL;
12861 if (error)
12862 goto done;
12863 } else {
12864 if (edit_in_progress) {
12865 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12866 goto done;
12869 error = got_ref_open(&branch, repo,
12870 got_worktree_get_head_ref_name(worktree), 0);
12871 if (error != NULL)
12872 goto done;
12874 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12875 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12876 "will not edit commit history of a branch outside "
12877 "the \"refs/heads/\" reference namespace");
12878 goto done;
12881 error = got_ref_resolve(&head_commit_id, repo, branch);
12882 got_ref_close(branch);
12883 branch = NULL;
12884 if (error)
12885 goto done;
12887 error = got_object_open_as_commit(&commit, repo,
12888 head_commit_id);
12889 if (error)
12890 goto done;
12891 parent_ids = got_object_commit_get_parent_ids(commit);
12892 pid = STAILQ_FIRST(parent_ids);
12893 if (pid == NULL) {
12894 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12895 goto done;
12897 error = collect_commits(&commits, head_commit_id, &pid->id,
12898 got_worktree_get_base_commit_id(worktree),
12899 got_worktree_get_path_prefix(worktree),
12900 GOT_ERR_HISTEDIT_PATH, repo);
12901 got_object_commit_close(commit);
12902 commit = NULL;
12903 if (error)
12904 goto done;
12906 if (STAILQ_EMPTY(&commits)) {
12907 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12908 goto done;
12911 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12912 &base_commit_id, &fileindex, worktree, repo);
12913 if (error)
12914 goto done;
12916 if (edit_script_path) {
12917 error = histedit_load_list(&histedit_cmds,
12918 edit_script_path, repo);
12919 if (error) {
12920 got_worktree_histedit_abort(worktree, fileindex,
12921 repo, branch, base_commit_id,
12922 abort_progress, &upa);
12923 print_merge_progress_stats(&upa);
12924 goto done;
12926 } else {
12927 const char *branch_name;
12928 branch_name = got_ref_get_symref_target(branch);
12929 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12930 branch_name += 11;
12931 error = histedit_edit_script(&histedit_cmds, &commits,
12932 branch_name, edit_logmsg_only, fold_only,
12933 drop_only, edit_only, repo);
12934 if (error) {
12935 got_worktree_histedit_abort(worktree, fileindex,
12936 repo, branch, base_commit_id,
12937 abort_progress, &upa);
12938 print_merge_progress_stats(&upa);
12939 goto done;
12944 error = histedit_save_list(&histedit_cmds, worktree,
12945 repo);
12946 if (error) {
12947 got_worktree_histedit_abort(worktree, fileindex,
12948 repo, branch, base_commit_id,
12949 abort_progress, &upa);
12950 print_merge_progress_stats(&upa);
12951 goto done;
12956 error = histedit_check_script(&histedit_cmds, &commits, repo);
12957 if (error)
12958 goto done;
12960 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12961 if (resume_commit_id) {
12962 if (got_object_id_cmp(hle->commit_id,
12963 resume_commit_id) != 0)
12964 continue;
12966 resume_commit_id = NULL;
12967 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12968 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12969 error = histedit_skip_commit(hle, worktree,
12970 repo);
12971 if (error)
12972 goto done;
12973 } else {
12974 struct got_pathlist_head paths;
12975 int have_changes = 0;
12977 TAILQ_INIT(&paths);
12978 error = got_pathlist_append(&paths, "", NULL);
12979 if (error)
12980 goto done;
12981 error = got_worktree_status(worktree, &paths,
12982 repo, 0, check_local_changes, &have_changes,
12983 check_cancelled, NULL);
12984 got_pathlist_free(&paths,
12985 GOT_PATHLIST_FREE_NONE);
12986 if (error) {
12987 if (error->code != GOT_ERR_CANCELLED)
12988 goto done;
12989 if (sigint_received || sigpipe_received)
12990 goto done;
12992 if (have_changes) {
12993 error = histedit_commit(NULL, worktree,
12994 fileindex, tmp_branch, hle,
12995 committer, allow_conflict, repo);
12996 if (error)
12997 goto done;
12998 } else {
12999 error = got_object_open_as_commit(
13000 &commit, repo, hle->commit_id);
13001 if (error)
13002 goto done;
13003 error = show_histedit_progress(commit,
13004 hle, NULL);
13005 got_object_commit_close(commit);
13006 commit = NULL;
13007 if (error)
13008 goto done;
13011 continue;
13014 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13015 error = histedit_skip_commit(hle, worktree, repo);
13016 if (error)
13017 goto done;
13018 continue;
13020 error = got_object_open_as_commit(&commit, repo,
13021 hle->commit_id);
13022 if (error)
13023 goto done;
13024 parent_ids = got_object_commit_get_parent_ids(commit);
13025 pid = STAILQ_FIRST(parent_ids);
13027 error = got_worktree_histedit_merge_files(&merged_paths,
13028 worktree, fileindex, &pid->id, hle->commit_id, repo,
13029 update_progress, &upa, check_cancelled, NULL);
13030 if (error)
13031 goto done;
13032 got_object_commit_close(commit);
13033 commit = NULL;
13035 print_merge_progress_stats(&upa);
13036 if (upa.conflicts > 0 || upa.missing > 0 ||
13037 upa.not_deleted > 0 || upa.unversioned > 0) {
13038 if (upa.conflicts > 0) {
13039 error = show_rebase_merge_conflict(
13040 hle->commit_id, repo);
13041 if (error)
13042 goto done;
13044 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13045 break;
13048 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13049 char *id_str;
13050 error = got_object_id_str(&id_str, hle->commit_id);
13051 if (error)
13052 goto done;
13053 printf("Stopping histedit for amending commit %s\n",
13054 id_str);
13055 free(id_str);
13056 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13057 error = got_worktree_histedit_postpone(worktree,
13058 fileindex);
13059 goto done;
13060 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13061 error = histedit_skip_commit(hle, worktree, repo);
13062 if (error)
13063 goto done;
13064 continue;
13065 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13066 error = histedit_edit_logmsg(hle, repo);
13067 if (error)
13068 goto done;
13071 error = histedit_commit(&merged_paths, worktree, fileindex,
13072 tmp_branch, hle, committer, allow_conflict, repo);
13073 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13074 if (error)
13075 goto done;
13078 if (upa.conflicts > 0 || upa.missing > 0 ||
13079 upa.not_deleted > 0 || upa.unversioned > 0) {
13080 error = got_worktree_histedit_postpone(worktree, fileindex);
13081 if (error)
13082 goto done;
13083 if (upa.conflicts > 0 && upa.missing == 0 &&
13084 upa.not_deleted == 0 && upa.unversioned == 0) {
13085 error = got_error_msg(GOT_ERR_CONFLICTS,
13086 "conflicts must be resolved before histedit "
13087 "can continue");
13088 } else if (upa.conflicts > 0) {
13089 error = got_error_msg(GOT_ERR_CONFLICTS,
13090 "conflicts must be resolved before histedit "
13091 "can continue; changes destined for some "
13092 "files were not yet merged and should be "
13093 "merged manually if required before the "
13094 "histedit operation is continued");
13095 } else {
13096 error = got_error_msg(GOT_ERR_CONFLICTS,
13097 "changes destined for some files were not "
13098 "yet merged and should be merged manually "
13099 "if required before the histedit operation "
13100 "is continued");
13102 } else
13103 error = histedit_complete(worktree, fileindex, tmp_branch,
13104 branch, repo);
13105 done:
13106 free(cwd);
13107 free(committer);
13108 free(gitconfig_path);
13109 got_object_id_queue_free(&commits);
13110 histedit_free_list(&histedit_cmds);
13111 free(head_commit_id);
13112 free(base_commit_id);
13113 free(resume_commit_id);
13114 if (commit)
13115 got_object_commit_close(commit);
13116 if (branch)
13117 got_ref_close(branch);
13118 if (tmp_branch)
13119 got_ref_close(tmp_branch);
13120 if (worktree)
13121 got_worktree_close(worktree);
13122 if (repo) {
13123 const struct got_error *close_err = got_repo_close(repo);
13124 if (error == NULL)
13125 error = close_err;
13127 if (pack_fds) {
13128 const struct got_error *pack_err =
13129 got_repo_pack_fds_close(pack_fds);
13130 if (error == NULL)
13131 error = pack_err;
13133 return error;
13136 __dead static void
13137 usage_integrate(void)
13139 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13140 exit(1);
13143 static const struct got_error *
13144 cmd_integrate(int argc, char *argv[])
13146 const struct got_error *error = NULL;
13147 struct got_repository *repo = NULL;
13148 struct got_worktree *worktree = NULL;
13149 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13150 const char *branch_arg = NULL;
13151 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13152 struct got_fileindex *fileindex = NULL;
13153 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13154 int ch;
13155 struct got_update_progress_arg upa;
13156 int *pack_fds = NULL;
13158 #ifndef PROFILE
13159 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13160 "unveil", NULL) == -1)
13161 err(1, "pledge");
13162 #endif
13164 while ((ch = getopt(argc, argv, "")) != -1) {
13165 switch (ch) {
13166 default:
13167 usage_integrate();
13168 /* NOTREACHED */
13172 argc -= optind;
13173 argv += optind;
13175 if (argc != 1)
13176 usage_integrate();
13177 branch_arg = argv[0];
13179 cwd = getcwd(NULL, 0);
13180 if (cwd == NULL) {
13181 error = got_error_from_errno("getcwd");
13182 goto done;
13185 error = got_repo_pack_fds_open(&pack_fds);
13186 if (error != NULL)
13187 goto done;
13189 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13190 if (error) {
13191 if (error->code == GOT_ERR_NOT_WORKTREE)
13192 error = wrap_not_worktree_error(error, "integrate",
13193 cwd);
13194 goto done;
13197 error = check_rebase_or_histedit_in_progress(worktree);
13198 if (error)
13199 goto done;
13201 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13202 NULL, pack_fds);
13203 if (error != NULL)
13204 goto done;
13206 error = apply_unveil(got_repo_get_path(repo), 0,
13207 got_worktree_get_root_path(worktree));
13208 if (error)
13209 goto done;
13211 error = check_merge_in_progress(worktree, repo);
13212 if (error)
13213 goto done;
13215 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13216 error = got_error_from_errno("asprintf");
13217 goto done;
13220 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13221 &base_branch_ref, worktree, refname, repo);
13222 if (error)
13223 goto done;
13225 refname = strdup(got_ref_get_name(branch_ref));
13226 if (refname == NULL) {
13227 error = got_error_from_errno("strdup");
13228 got_worktree_integrate_abort(worktree, fileindex, repo,
13229 branch_ref, base_branch_ref);
13230 goto done;
13232 base_refname = strdup(got_ref_get_name(base_branch_ref));
13233 if (base_refname == NULL) {
13234 error = got_error_from_errno("strdup");
13235 got_worktree_integrate_abort(worktree, fileindex, repo,
13236 branch_ref, base_branch_ref);
13237 goto done;
13239 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13240 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13241 got_worktree_integrate_abort(worktree, fileindex, repo,
13242 branch_ref, base_branch_ref);
13243 goto done;
13246 error = got_ref_resolve(&commit_id, repo, branch_ref);
13247 if (error)
13248 goto done;
13250 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13251 if (error)
13252 goto done;
13254 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13255 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13256 "specified branch has already been integrated");
13257 got_worktree_integrate_abort(worktree, fileindex, repo,
13258 branch_ref, base_branch_ref);
13259 goto done;
13262 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13263 if (error) {
13264 if (error->code == GOT_ERR_ANCESTRY)
13265 error = got_error(GOT_ERR_REBASE_REQUIRED);
13266 got_worktree_integrate_abort(worktree, fileindex, repo,
13267 branch_ref, base_branch_ref);
13268 goto done;
13271 memset(&upa, 0, sizeof(upa));
13272 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13273 branch_ref, base_branch_ref, update_progress, &upa,
13274 check_cancelled, NULL);
13275 if (error)
13276 goto done;
13278 printf("Integrated %s into %s\n", refname, base_refname);
13279 print_update_progress_stats(&upa);
13280 done:
13281 if (repo) {
13282 const struct got_error *close_err = got_repo_close(repo);
13283 if (error == NULL)
13284 error = close_err;
13286 if (worktree)
13287 got_worktree_close(worktree);
13288 if (pack_fds) {
13289 const struct got_error *pack_err =
13290 got_repo_pack_fds_close(pack_fds);
13291 if (error == NULL)
13292 error = pack_err;
13294 free(cwd);
13295 free(base_commit_id);
13296 free(commit_id);
13297 free(refname);
13298 free(base_refname);
13299 return error;
13302 __dead static void
13303 usage_merge(void)
13305 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13306 exit(1);
13309 static const struct got_error *
13310 cmd_merge(int argc, char *argv[])
13312 const struct got_error *error = NULL;
13313 struct got_worktree *worktree = NULL;
13314 struct got_repository *repo = NULL;
13315 struct got_fileindex *fileindex = NULL;
13316 char *cwd = NULL, *id_str = NULL, *author = NULL;
13317 char *gitconfig_path = NULL;
13318 struct got_reference *branch = NULL, *wt_branch = NULL;
13319 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13320 struct got_object_id *wt_branch_tip = NULL;
13321 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13322 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13323 struct got_update_progress_arg upa;
13324 struct got_object_id *merge_commit_id = NULL;
13325 char *branch_name = NULL;
13326 int *pack_fds = NULL;
13328 memset(&upa, 0, sizeof(upa));
13330 #ifndef PROFILE
13331 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13332 "unveil", NULL) == -1)
13333 err(1, "pledge");
13334 #endif
13336 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13337 switch (ch) {
13338 case 'a':
13339 abort_merge = 1;
13340 break;
13341 case 'C':
13342 allow_conflict = 1;
13343 break;
13344 case 'c':
13345 continue_merge = 1;
13346 break;
13347 case 'M':
13348 prefer_fast_forward = 0;
13349 break;
13350 case 'n':
13351 interrupt_merge = 1;
13352 break;
13353 default:
13354 usage_merge();
13355 /* NOTREACHED */
13359 argc -= optind;
13360 argv += optind;
13362 if (abort_merge) {
13363 if (continue_merge)
13364 option_conflict('a', 'c');
13365 if (!prefer_fast_forward)
13366 option_conflict('a', 'M');
13367 if (interrupt_merge)
13368 option_conflict('a', 'n');
13369 } else if (continue_merge) {
13370 if (!prefer_fast_forward)
13371 option_conflict('c', 'M');
13372 if (interrupt_merge)
13373 option_conflict('c', 'n');
13375 if (allow_conflict) {
13376 if (!continue_merge)
13377 errx(1, "-C option requires -c");
13379 if (abort_merge || continue_merge) {
13380 if (argc != 0)
13381 usage_merge();
13382 } else if (argc != 1)
13383 usage_merge();
13385 cwd = getcwd(NULL, 0);
13386 if (cwd == NULL) {
13387 error = got_error_from_errno("getcwd");
13388 goto done;
13391 error = got_repo_pack_fds_open(&pack_fds);
13392 if (error != NULL)
13393 goto done;
13395 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13396 if (error) {
13397 if (error->code == GOT_ERR_NOT_WORKTREE)
13398 error = wrap_not_worktree_error(error,
13399 "merge", cwd);
13400 goto done;
13403 error = get_gitconfig_path(&gitconfig_path);
13404 if (error)
13405 goto done;
13406 error = got_repo_open(&repo,
13407 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13408 gitconfig_path, pack_fds);
13409 if (error != NULL)
13410 goto done;
13412 if (worktree != NULL) {
13413 error = worktree_has_logmsg_ref("merge", worktree, repo);
13414 if (error)
13415 goto done;
13418 error = apply_unveil(got_repo_get_path(repo), 0,
13419 worktree ? got_worktree_get_root_path(worktree) : NULL);
13420 if (error)
13421 goto done;
13423 error = check_rebase_or_histedit_in_progress(worktree);
13424 if (error)
13425 goto done;
13427 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13428 repo);
13429 if (error)
13430 goto done;
13432 if (merge_in_progress && !(abort_merge || continue_merge)) {
13433 error = got_error(GOT_ERR_MERGE_BUSY);
13434 goto done;
13437 if (!merge_in_progress && (abort_merge || continue_merge)) {
13438 error = got_error(GOT_ERR_NOT_MERGING);
13439 goto done;
13442 if (abort_merge) {
13443 error = got_worktree_merge_continue(&branch_name,
13444 &branch_tip, &fileindex, worktree, repo);
13445 if (error)
13446 goto done;
13447 error = got_worktree_merge_abort(worktree, fileindex, repo,
13448 abort_progress, &upa);
13449 if (error)
13450 goto done;
13451 printf("Merge of %s aborted\n", branch_name);
13452 goto done; /* nothing else to do */
13455 if (strncmp(got_worktree_get_head_ref_name(worktree),
13456 "refs/heads/", 11) != 0) {
13457 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13458 "work tree's current branch %s is outside the "
13459 "\"refs/heads/\" reference namespace; "
13460 "update -b required",
13461 got_worktree_get_head_ref_name(worktree));
13462 goto done;
13465 error = get_author(&author, repo, worktree);
13466 if (error)
13467 goto done;
13469 error = got_ref_open(&wt_branch, repo,
13470 got_worktree_get_head_ref_name(worktree), 0);
13471 if (error)
13472 goto done;
13473 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13474 if (error)
13475 goto done;
13477 if (continue_merge) {
13478 struct got_object_id *base_commit_id;
13479 base_commit_id = got_worktree_get_base_commit_id(worktree);
13480 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13481 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13482 goto done;
13484 error = got_worktree_merge_continue(&branch_name,
13485 &branch_tip, &fileindex, worktree, repo);
13486 if (error)
13487 goto done;
13488 } else {
13489 error = got_ref_open(&branch, repo, argv[0], 0);
13490 if (error != NULL)
13491 goto done;
13492 branch_name = strdup(got_ref_get_name(branch));
13493 if (branch_name == NULL) {
13494 error = got_error_from_errno("strdup");
13495 goto done;
13497 error = got_ref_resolve(&branch_tip, repo, branch);
13498 if (error)
13499 goto done;
13502 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13503 wt_branch_tip, branch_tip, 0, repo,
13504 check_cancelled, NULL);
13505 if (error && error->code != GOT_ERR_ANCESTRY)
13506 goto done;
13508 if (!continue_merge) {
13509 error = check_path_prefix(wt_branch_tip, branch_tip,
13510 got_worktree_get_path_prefix(worktree),
13511 GOT_ERR_MERGE_PATH, repo);
13512 if (error)
13513 goto done;
13514 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13515 if (error)
13516 goto done;
13517 if (prefer_fast_forward && yca_id &&
13518 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13519 struct got_pathlist_head paths;
13520 if (interrupt_merge) {
13521 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13522 "there are no changes to merge since %s "
13523 "is already based on %s; merge cannot be "
13524 "interrupted for amending; -n",
13525 branch_name, got_ref_get_name(wt_branch));
13526 goto done;
13528 printf("Forwarding %s to %s\n",
13529 got_ref_get_name(wt_branch), branch_name);
13530 error = got_ref_change_ref(wt_branch, branch_tip);
13531 if (error)
13532 goto done;
13533 error = got_ref_write(wt_branch, repo);
13534 if (error)
13535 goto done;
13536 error = got_worktree_set_base_commit_id(worktree, repo,
13537 branch_tip);
13538 if (error)
13539 goto done;
13540 TAILQ_INIT(&paths);
13541 error = got_pathlist_append(&paths, "", NULL);
13542 if (error)
13543 goto done;
13544 error = got_worktree_checkout_files(worktree,
13545 &paths, repo, update_progress, &upa,
13546 check_cancelled, NULL);
13547 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13548 if (error)
13549 goto done;
13550 if (upa.did_something) {
13551 char *id_str;
13552 error = got_object_id_str(&id_str, branch_tip);
13553 if (error)
13554 goto done;
13555 printf("Updated to commit %s\n", id_str);
13556 free(id_str);
13557 } else
13558 printf("Already up-to-date\n");
13559 print_update_progress_stats(&upa);
13560 goto done;
13562 error = got_worktree_merge_write_refs(worktree, branch, repo);
13563 if (error)
13564 goto done;
13566 error = got_worktree_merge_branch(worktree, fileindex,
13567 yca_id, branch_tip, repo, update_progress, &upa,
13568 check_cancelled, NULL);
13569 if (error)
13570 goto done;
13571 print_merge_progress_stats(&upa);
13572 if (!upa.did_something) {
13573 error = got_worktree_merge_abort(worktree, fileindex,
13574 repo, abort_progress, &upa);
13575 if (error)
13576 goto done;
13577 printf("Already up-to-date\n");
13578 goto done;
13582 if (interrupt_merge) {
13583 error = got_worktree_merge_postpone(worktree, fileindex);
13584 if (error)
13585 goto done;
13586 printf("Merge of %s interrupted on request\n", branch_name);
13587 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13588 upa.not_deleted > 0 || upa.unversioned > 0) {
13589 error = got_worktree_merge_postpone(worktree, fileindex);
13590 if (error)
13591 goto done;
13592 if (upa.conflicts > 0 && upa.missing == 0 &&
13593 upa.not_deleted == 0 && upa.unversioned == 0) {
13594 error = got_error_msg(GOT_ERR_CONFLICTS,
13595 "conflicts must be resolved before merging "
13596 "can continue");
13597 } else if (upa.conflicts > 0) {
13598 error = got_error_msg(GOT_ERR_CONFLICTS,
13599 "conflicts must be resolved before merging "
13600 "can continue; changes destined for some "
13601 "files were not yet merged and "
13602 "should be merged manually if required before the "
13603 "merge operation is continued");
13604 } else {
13605 error = got_error_msg(GOT_ERR_CONFLICTS,
13606 "changes destined for some "
13607 "files were not yet merged and should be "
13608 "merged manually if required before the "
13609 "merge operation is continued");
13611 goto done;
13612 } else {
13613 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13614 fileindex, author, NULL, 1, branch_tip, branch_name,
13615 allow_conflict, repo, continue_merge ? print_status : NULL,
13616 NULL);
13617 if (error)
13618 goto done;
13619 error = got_worktree_merge_complete(worktree, fileindex, repo);
13620 if (error)
13621 goto done;
13622 error = got_object_id_str(&id_str, merge_commit_id);
13623 if (error)
13624 goto done;
13625 printf("Merged %s into %s: %s\n", branch_name,
13626 got_worktree_get_head_ref_name(worktree),
13627 id_str);
13630 done:
13631 free(gitconfig_path);
13632 free(id_str);
13633 free(merge_commit_id);
13634 free(author);
13635 free(branch_tip);
13636 free(branch_name);
13637 free(yca_id);
13638 if (branch)
13639 got_ref_close(branch);
13640 if (wt_branch)
13641 got_ref_close(wt_branch);
13642 if (worktree)
13643 got_worktree_close(worktree);
13644 if (repo) {
13645 const struct got_error *close_err = got_repo_close(repo);
13646 if (error == NULL)
13647 error = close_err;
13649 if (pack_fds) {
13650 const struct got_error *pack_err =
13651 got_repo_pack_fds_close(pack_fds);
13652 if (error == NULL)
13653 error = pack_err;
13655 return error;
13658 __dead static void
13659 usage_stage(void)
13661 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13662 "[path ...]\n", getprogname());
13663 exit(1);
13666 static const struct got_error *
13667 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13668 const char *path, struct got_object_id *blob_id,
13669 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13670 int dirfd, const char *de_name)
13672 const struct got_error *err = NULL;
13673 char *id_str = NULL;
13675 if (staged_status != GOT_STATUS_ADD &&
13676 staged_status != GOT_STATUS_MODIFY &&
13677 staged_status != GOT_STATUS_DELETE)
13678 return NULL;
13680 if (staged_status == GOT_STATUS_ADD ||
13681 staged_status == GOT_STATUS_MODIFY)
13682 err = got_object_id_str(&id_str, staged_blob_id);
13683 else
13684 err = got_object_id_str(&id_str, blob_id);
13685 if (err)
13686 return err;
13688 printf("%s %c %s\n", id_str, staged_status, path);
13689 free(id_str);
13690 return NULL;
13693 static const struct got_error *
13694 cmd_stage(int argc, char *argv[])
13696 const struct got_error *error = NULL;
13697 struct got_repository *repo = NULL;
13698 struct got_worktree *worktree = NULL;
13699 char *cwd = NULL;
13700 struct got_pathlist_head paths;
13701 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13702 FILE *patch_script_file = NULL;
13703 const char *patch_script_path = NULL;
13704 struct choose_patch_arg cpa;
13705 int *pack_fds = NULL;
13707 TAILQ_INIT(&paths);
13709 #ifndef PROFILE
13710 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13711 "unveil", NULL) == -1)
13712 err(1, "pledge");
13713 #endif
13715 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13716 switch (ch) {
13717 case 'F':
13718 patch_script_path = optarg;
13719 break;
13720 case 'l':
13721 list_stage = 1;
13722 break;
13723 case 'p':
13724 pflag = 1;
13725 break;
13726 case 'S':
13727 allow_bad_symlinks = 1;
13728 break;
13729 default:
13730 usage_stage();
13731 /* NOTREACHED */
13735 argc -= optind;
13736 argv += optind;
13738 if (list_stage && (pflag || patch_script_path))
13739 errx(1, "-l option cannot be used with other options");
13740 if (patch_script_path && !pflag)
13741 errx(1, "-F option can only be used together with -p option");
13743 cwd = getcwd(NULL, 0);
13744 if (cwd == NULL) {
13745 error = got_error_from_errno("getcwd");
13746 goto done;
13749 error = got_repo_pack_fds_open(&pack_fds);
13750 if (error != NULL)
13751 goto done;
13753 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13754 if (error) {
13755 if (error->code == GOT_ERR_NOT_WORKTREE)
13756 error = wrap_not_worktree_error(error, "stage", cwd);
13757 goto done;
13760 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13761 NULL, pack_fds);
13762 if (error != NULL)
13763 goto done;
13765 if (patch_script_path) {
13766 patch_script_file = fopen(patch_script_path, "re");
13767 if (patch_script_file == NULL) {
13768 error = got_error_from_errno2("fopen",
13769 patch_script_path);
13770 goto done;
13773 error = apply_unveil(got_repo_get_path(repo), 0,
13774 got_worktree_get_root_path(worktree));
13775 if (error)
13776 goto done;
13778 error = check_merge_in_progress(worktree, repo);
13779 if (error)
13780 goto done;
13782 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13783 if (error)
13784 goto done;
13786 if (list_stage)
13787 error = got_worktree_status(worktree, &paths, repo, 0,
13788 print_stage, NULL, check_cancelled, NULL);
13789 else {
13790 cpa.patch_script_file = patch_script_file;
13791 cpa.action = "stage";
13792 error = got_worktree_stage(worktree, &paths,
13793 pflag ? NULL : print_status, NULL,
13794 pflag ? choose_patch : NULL, &cpa,
13795 allow_bad_symlinks, repo);
13797 done:
13798 if (patch_script_file && fclose(patch_script_file) == EOF &&
13799 error == NULL)
13800 error = got_error_from_errno2("fclose", patch_script_path);
13801 if (repo) {
13802 const struct got_error *close_err = got_repo_close(repo);
13803 if (error == NULL)
13804 error = close_err;
13806 if (worktree)
13807 got_worktree_close(worktree);
13808 if (pack_fds) {
13809 const struct got_error *pack_err =
13810 got_repo_pack_fds_close(pack_fds);
13811 if (error == NULL)
13812 error = pack_err;
13814 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13815 free(cwd);
13816 return error;
13819 __dead static void
13820 usage_unstage(void)
13822 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13823 "[path ...]\n", getprogname());
13824 exit(1);
13828 static const struct got_error *
13829 cmd_unstage(int argc, char *argv[])
13831 const struct got_error *error = NULL;
13832 struct got_repository *repo = NULL;
13833 struct got_worktree *worktree = NULL;
13834 char *cwd = NULL;
13835 struct got_pathlist_head paths;
13836 int ch, pflag = 0;
13837 struct got_update_progress_arg upa;
13838 FILE *patch_script_file = NULL;
13839 const char *patch_script_path = NULL;
13840 struct choose_patch_arg cpa;
13841 int *pack_fds = NULL;
13843 TAILQ_INIT(&paths);
13845 #ifndef PROFILE
13846 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13847 "unveil", NULL) == -1)
13848 err(1, "pledge");
13849 #endif
13851 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13852 switch (ch) {
13853 case 'F':
13854 patch_script_path = optarg;
13855 break;
13856 case 'p':
13857 pflag = 1;
13858 break;
13859 default:
13860 usage_unstage();
13861 /* NOTREACHED */
13865 argc -= optind;
13866 argv += optind;
13868 if (patch_script_path && !pflag)
13869 errx(1, "-F option can only be used together with -p option");
13871 cwd = getcwd(NULL, 0);
13872 if (cwd == NULL) {
13873 error = got_error_from_errno("getcwd");
13874 goto done;
13877 error = got_repo_pack_fds_open(&pack_fds);
13878 if (error != NULL)
13879 goto done;
13881 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13882 if (error) {
13883 if (error->code == GOT_ERR_NOT_WORKTREE)
13884 error = wrap_not_worktree_error(error, "unstage", cwd);
13885 goto done;
13888 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13889 NULL, pack_fds);
13890 if (error != NULL)
13891 goto done;
13893 if (patch_script_path) {
13894 patch_script_file = fopen(patch_script_path, "re");
13895 if (patch_script_file == NULL) {
13896 error = got_error_from_errno2("fopen",
13897 patch_script_path);
13898 goto done;
13902 error = apply_unveil(got_repo_get_path(repo), 0,
13903 got_worktree_get_root_path(worktree));
13904 if (error)
13905 goto done;
13907 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13908 if (error)
13909 goto done;
13911 cpa.patch_script_file = patch_script_file;
13912 cpa.action = "unstage";
13913 memset(&upa, 0, sizeof(upa));
13914 error = got_worktree_unstage(worktree, &paths, update_progress,
13915 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13916 if (!error)
13917 print_merge_progress_stats(&upa);
13918 done:
13919 if (patch_script_file && fclose(patch_script_file) == EOF &&
13920 error == NULL)
13921 error = got_error_from_errno2("fclose", patch_script_path);
13922 if (repo) {
13923 const struct got_error *close_err = got_repo_close(repo);
13924 if (error == NULL)
13925 error = close_err;
13927 if (worktree)
13928 got_worktree_close(worktree);
13929 if (pack_fds) {
13930 const struct got_error *pack_err =
13931 got_repo_pack_fds_close(pack_fds);
13932 if (error == NULL)
13933 error = pack_err;
13935 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13936 free(cwd);
13937 return error;
13940 __dead static void
13941 usage_cat(void)
13943 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13944 "arg ...\n", getprogname());
13945 exit(1);
13948 static const struct got_error *
13949 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13951 const struct got_error *err;
13952 struct got_blob_object *blob;
13953 int fd = -1;
13955 fd = got_opentempfd();
13956 if (fd == -1)
13957 return got_error_from_errno("got_opentempfd");
13959 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13960 if (err)
13961 goto done;
13963 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13964 done:
13965 if (fd != -1 && close(fd) == -1 && err == NULL)
13966 err = got_error_from_errno("close");
13967 if (blob)
13968 got_object_blob_close(blob);
13969 return err;
13972 static const struct got_error *
13973 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13975 const struct got_error *err;
13976 struct got_tree_object *tree;
13977 int nentries, i;
13979 err = got_object_open_as_tree(&tree, repo, id);
13980 if (err)
13981 return err;
13983 nentries = got_object_tree_get_nentries(tree);
13984 for (i = 0; i < nentries; i++) {
13985 struct got_tree_entry *te;
13986 char *id_str;
13987 if (sigint_received || sigpipe_received)
13988 break;
13989 te = got_object_tree_get_entry(tree, i);
13990 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13991 if (err)
13992 break;
13993 fprintf(outfile, "%s %.7o %s\n", id_str,
13994 got_tree_entry_get_mode(te),
13995 got_tree_entry_get_name(te));
13996 free(id_str);
13999 got_object_tree_close(tree);
14000 return err;
14003 static const struct got_error *
14004 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14006 const struct got_error *err;
14007 struct got_commit_object *commit;
14008 const struct got_object_id_queue *parent_ids;
14009 struct got_object_qid *pid;
14010 char *id_str = NULL;
14011 const char *logmsg = NULL;
14012 char gmtoff[6];
14014 err = got_object_open_as_commit(&commit, repo, id);
14015 if (err)
14016 return err;
14018 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14019 if (err)
14020 goto done;
14022 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14023 parent_ids = got_object_commit_get_parent_ids(commit);
14024 fprintf(outfile, "numparents %d\n",
14025 got_object_commit_get_nparents(commit));
14026 STAILQ_FOREACH(pid, parent_ids, entry) {
14027 char *pid_str;
14028 err = got_object_id_str(&pid_str, &pid->id);
14029 if (err)
14030 goto done;
14031 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14032 free(pid_str);
14034 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14035 got_object_commit_get_author_gmtoff(commit));
14036 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14037 got_object_commit_get_author(commit),
14038 (long long)got_object_commit_get_author_time(commit),
14039 gmtoff);
14041 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14042 got_object_commit_get_committer_gmtoff(commit));
14043 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14044 got_object_commit_get_committer(commit),
14045 (long long)got_object_commit_get_committer_time(commit),
14046 gmtoff);
14048 logmsg = got_object_commit_get_logmsg_raw(commit);
14049 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14050 fprintf(outfile, "%s", logmsg);
14051 done:
14052 free(id_str);
14053 got_object_commit_close(commit);
14054 return err;
14057 static const struct got_error *
14058 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14060 const struct got_error *err;
14061 struct got_tag_object *tag;
14062 char *id_str = NULL;
14063 const char *tagmsg = NULL;
14064 char gmtoff[6];
14066 err = got_object_open_as_tag(&tag, repo, id);
14067 if (err)
14068 return err;
14070 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14071 if (err)
14072 goto done;
14074 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14076 switch (got_object_tag_get_object_type(tag)) {
14077 case GOT_OBJ_TYPE_BLOB:
14078 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14079 GOT_OBJ_LABEL_BLOB);
14080 break;
14081 case GOT_OBJ_TYPE_TREE:
14082 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14083 GOT_OBJ_LABEL_TREE);
14084 break;
14085 case GOT_OBJ_TYPE_COMMIT:
14086 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14087 GOT_OBJ_LABEL_COMMIT);
14088 break;
14089 case GOT_OBJ_TYPE_TAG:
14090 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14091 GOT_OBJ_LABEL_TAG);
14092 break;
14093 default:
14094 break;
14097 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14098 got_object_tag_get_name(tag));
14100 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14101 got_object_tag_get_tagger_gmtoff(tag));
14102 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14103 got_object_tag_get_tagger(tag),
14104 (long long)got_object_tag_get_tagger_time(tag),
14105 gmtoff);
14107 tagmsg = got_object_tag_get_message(tag);
14108 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14109 fprintf(outfile, "%s", tagmsg);
14110 done:
14111 free(id_str);
14112 got_object_tag_close(tag);
14113 return err;
14116 static const struct got_error *
14117 cmd_cat(int argc, char *argv[])
14119 const struct got_error *error;
14120 struct got_repository *repo = NULL;
14121 struct got_worktree *worktree = NULL;
14122 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14123 char *keyword_idstr = NULL;
14124 const char *commit_id_str = NULL;
14125 struct got_object_id *id = NULL, *commit_id = NULL;
14126 struct got_commit_object *commit = NULL;
14127 int ch, obj_type, i, force_path = 0;
14128 struct got_reflist_head refs;
14129 int *pack_fds = NULL;
14131 TAILQ_INIT(&refs);
14133 #ifndef PROFILE
14134 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14135 NULL) == -1)
14136 err(1, "pledge");
14137 #endif
14139 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14140 switch (ch) {
14141 case 'c':
14142 commit_id_str = optarg;
14143 break;
14144 case 'P':
14145 force_path = 1;
14146 break;
14147 case 'r':
14148 repo_path = realpath(optarg, NULL);
14149 if (repo_path == NULL)
14150 return got_error_from_errno2("realpath",
14151 optarg);
14152 got_path_strip_trailing_slashes(repo_path);
14153 break;
14154 default:
14155 usage_cat();
14156 /* NOTREACHED */
14160 argc -= optind;
14161 argv += optind;
14163 cwd = getcwd(NULL, 0);
14164 if (cwd == NULL) {
14165 error = got_error_from_errno("getcwd");
14166 goto done;
14169 error = got_repo_pack_fds_open(&pack_fds);
14170 if (error != NULL)
14171 goto done;
14173 if (repo_path == NULL) {
14174 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14175 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14176 goto done;
14177 if (worktree) {
14178 repo_path = strdup(
14179 got_worktree_get_repo_path(worktree));
14180 if (repo_path == NULL) {
14181 error = got_error_from_errno("strdup");
14182 goto done;
14185 if (commit_id_str == NULL) {
14186 /* Release work tree lock. */
14187 got_worktree_close(worktree);
14188 worktree = NULL;
14193 if (repo_path == NULL) {
14194 repo_path = strdup(cwd);
14195 if (repo_path == NULL)
14196 return got_error_from_errno("strdup");
14199 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14200 free(repo_path);
14201 if (error != NULL)
14202 goto done;
14204 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14205 if (error)
14206 goto done;
14208 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14209 if (error)
14210 goto done;
14212 if (commit_id_str != NULL) {
14213 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14214 repo, worktree);
14215 if (error != NULL)
14216 goto done;
14217 if (keyword_idstr != NULL)
14218 commit_id_str = keyword_idstr;
14219 if (worktree != NULL) {
14220 got_worktree_close(worktree);
14221 worktree = NULL;
14223 } else
14224 commit_id_str = GOT_REF_HEAD;
14225 error = got_repo_match_object_id(&commit_id, NULL,
14226 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14227 if (error)
14228 goto done;
14230 error = got_object_open_as_commit(&commit, repo, commit_id);
14231 if (error)
14232 goto done;
14234 for (i = 0; i < argc; i++) {
14235 if (force_path) {
14236 error = got_object_id_by_path(&id, repo, commit,
14237 argv[i]);
14238 if (error)
14239 break;
14240 } else {
14241 error = got_repo_match_object_id(&id, &label, argv[i],
14242 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14243 repo);
14244 if (error) {
14245 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14246 error->code != GOT_ERR_NOT_REF)
14247 break;
14248 error = got_object_id_by_path(&id, repo,
14249 commit, argv[i]);
14250 if (error)
14251 break;
14255 error = got_object_get_type(&obj_type, repo, id);
14256 if (error)
14257 break;
14259 switch (obj_type) {
14260 case GOT_OBJ_TYPE_BLOB:
14261 error = cat_blob(id, repo, stdout);
14262 break;
14263 case GOT_OBJ_TYPE_TREE:
14264 error = cat_tree(id, repo, stdout);
14265 break;
14266 case GOT_OBJ_TYPE_COMMIT:
14267 error = cat_commit(id, repo, stdout);
14268 break;
14269 case GOT_OBJ_TYPE_TAG:
14270 error = cat_tag(id, repo, stdout);
14271 break;
14272 default:
14273 error = got_error(GOT_ERR_OBJ_TYPE);
14274 break;
14276 if (error)
14277 break;
14278 free(label);
14279 label = NULL;
14280 free(id);
14281 id = NULL;
14283 done:
14284 free(label);
14285 free(id);
14286 free(commit_id);
14287 free(keyword_idstr);
14288 if (commit)
14289 got_object_commit_close(commit);
14290 if (worktree)
14291 got_worktree_close(worktree);
14292 if (repo) {
14293 const struct got_error *close_err = got_repo_close(repo);
14294 if (error == NULL)
14295 error = close_err;
14297 if (pack_fds) {
14298 const struct got_error *pack_err =
14299 got_repo_pack_fds_close(pack_fds);
14300 if (error == NULL)
14301 error = pack_err;
14304 got_ref_list_free(&refs);
14305 return error;
14308 __dead static void
14309 usage_info(void)
14311 fprintf(stderr, "usage: %s info [path ...]\n",
14312 getprogname());
14313 exit(1);
14316 static const struct got_error *
14317 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14318 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14319 struct got_object_id *commit_id)
14321 const struct got_error *err = NULL;
14322 char *id_str = NULL;
14323 char datebuf[128];
14324 struct tm mytm, *tm;
14325 struct got_pathlist_head *paths = arg;
14326 struct got_pathlist_entry *pe;
14329 * Clear error indication from any of the path arguments which
14330 * would cause this file index entry to be displayed.
14332 TAILQ_FOREACH(pe, paths, entry) {
14333 if (got_path_cmp(path, pe->path, strlen(path),
14334 pe->path_len) == 0 ||
14335 got_path_is_child(path, pe->path, pe->path_len))
14336 pe->data = NULL; /* no error */
14339 printf(GOT_COMMIT_SEP_STR);
14340 if (S_ISLNK(mode))
14341 printf("symlink: %s\n", path);
14342 else if (S_ISREG(mode)) {
14343 printf("file: %s\n", path);
14344 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14345 } else if (S_ISDIR(mode))
14346 printf("directory: %s\n", path);
14347 else
14348 printf("something: %s\n", path);
14350 tm = localtime_r(&mtime, &mytm);
14351 if (tm == NULL)
14352 return NULL;
14353 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14354 return got_error(GOT_ERR_NO_SPACE);
14355 printf("timestamp: %s\n", datebuf);
14357 if (blob_id) {
14358 err = got_object_id_str(&id_str, blob_id);
14359 if (err)
14360 return err;
14361 printf("based on blob: %s\n", id_str);
14362 free(id_str);
14365 if (staged_blob_id) {
14366 err = got_object_id_str(&id_str, staged_blob_id);
14367 if (err)
14368 return err;
14369 printf("based on staged blob: %s\n", id_str);
14370 free(id_str);
14373 if (commit_id) {
14374 err = got_object_id_str(&id_str, commit_id);
14375 if (err)
14376 return err;
14377 printf("based on commit: %s\n", id_str);
14378 free(id_str);
14381 return NULL;
14384 static const struct got_error *
14385 cmd_info(int argc, char *argv[])
14387 const struct got_error *error = NULL;
14388 struct got_worktree *worktree = NULL;
14389 char *cwd = NULL, *id_str = NULL;
14390 struct got_pathlist_head paths;
14391 char *uuidstr = NULL;
14392 int ch, show_files = 0;
14394 TAILQ_INIT(&paths);
14396 #ifndef PROFILE
14397 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14398 NULL) == -1)
14399 err(1, "pledge");
14400 #endif
14402 while ((ch = getopt(argc, argv, "")) != -1) {
14403 switch (ch) {
14404 default:
14405 usage_info();
14406 /* NOTREACHED */
14410 argc -= optind;
14411 argv += optind;
14413 cwd = getcwd(NULL, 0);
14414 if (cwd == NULL) {
14415 error = got_error_from_errno("getcwd");
14416 goto done;
14419 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14420 if (error) {
14421 if (error->code == GOT_ERR_NOT_WORKTREE)
14422 error = wrap_not_worktree_error(error, "info", cwd);
14423 goto done;
14426 #ifndef PROFILE
14427 /* Remove "wpath cpath proc exec sendfd" promises. */
14428 if (pledge("stdio rpath flock unveil", NULL) == -1)
14429 err(1, "pledge");
14430 #endif
14431 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14432 if (error)
14433 goto done;
14435 if (argc >= 1) {
14436 error = get_worktree_paths_from_argv(&paths, argc, argv,
14437 worktree);
14438 if (error)
14439 goto done;
14440 show_files = 1;
14443 error = got_object_id_str(&id_str,
14444 got_worktree_get_base_commit_id(worktree));
14445 if (error)
14446 goto done;
14448 error = got_worktree_get_uuid(&uuidstr, worktree);
14449 if (error)
14450 goto done;
14452 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14453 printf("work tree base commit: %s\n", id_str);
14454 printf("work tree path prefix: %s\n",
14455 got_worktree_get_path_prefix(worktree));
14456 printf("work tree branch reference: %s\n",
14457 got_worktree_get_head_ref_name(worktree));
14458 printf("work tree UUID: %s\n", uuidstr);
14459 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14461 if (show_files) {
14462 struct got_pathlist_entry *pe;
14463 TAILQ_FOREACH(pe, &paths, entry) {
14464 if (pe->path_len == 0)
14465 continue;
14467 * Assume this path will fail. This will be corrected
14468 * in print_path_info() in case the path does suceeed.
14470 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14472 error = got_worktree_path_info(worktree, &paths,
14473 print_path_info, &paths, check_cancelled, NULL);
14474 if (error)
14475 goto done;
14476 TAILQ_FOREACH(pe, &paths, entry) {
14477 if (pe->data != NULL) {
14478 const struct got_error *perr;
14480 perr = pe->data;
14481 error = got_error_fmt(perr->code, "%s",
14482 pe->path);
14483 break;
14487 done:
14488 if (worktree)
14489 got_worktree_close(worktree);
14490 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14491 free(cwd);
14492 free(id_str);
14493 free(uuidstr);
14494 return error;